diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..4d8daa4 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,39 @@ +# Copyright 2024 Moulberry + +## Acceptance + +In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses. + +## Do Not Distribute + +You may not reupload or redistribute the software, in whole or in part, modified or unmodified, alongside other software or standalone. This includes redistribution by creating or using software to automatically compile and/or download the software. In order to receive any license under these terms, you must obtain the software from the licensor or from a party authorized by the licensor. + +## Do Not Compete + +You may not provide any product that competes with the software or any product the licensor or any of its affiliates provides using the software. + +Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they’re written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes. + +## Grant of Rights + +The licensor grants you a limited, non-exclusive, revocable, non-sublicensable, non-transferable, royalty free license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose, other than distributing the software, making changes/new works based on the software or competing with the software/the licensor. + +## Violations + +The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately. If the licensor is unable to notify you in writing, all your licenses end immediately. + +## No Liability + +As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim. + +## Definitions + +The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms. + +**You** refers to the individual or entity agreeing to these terms. + +**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the software under these terms. + +**Use** means anything you do with the software requiring one of your licenses. diff --git a/build.gradle b/build.gradle index f93095f..353267b 100644 --- a/build.gradle +++ b/build.gradle @@ -63,7 +63,8 @@ dependencies { include(implementation("com.moulberry:mixinconstraints:1.0.1")) - modCompileOnly("maven.modrinth:sodium:RncWhTxD") + modCompileOnly("maven.modrinth:sodium:RncWhTxD") + modCompileOnly("maven.modrinth:iris:kuOV4Ece") modImplementation("maven.modrinth:modmenu:xhN1IvHi") // modCompileOnly("maven.modrinth:axiom:D3uDJmiB") diff --git a/gradle.properties b/gradle.properties index 306d3c8..25fb06c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,9 +9,9 @@ yarn_mappings=1.21+build.9 loader_version=0.15.11 # Mod Properties -mod_version=1.0.2 +mod_version=0.2.0 maven_group=com.moulberry.flashback archives_base_name=flashback # Dependencies -fabric_version=0.100.7+1.21 \ No newline at end of file +fabric_version=0.100.7+1.21 diff --git a/src/main/java/com/moulberry/flashback/Flashback.java b/src/main/java/com/moulberry/flashback/Flashback.java index dfb21a0..20bdb85 100644 --- a/src/main/java/com/moulberry/flashback/Flashback.java +++ b/src/main/java/com/moulberry/flashback/Flashback.java @@ -1,26 +1,46 @@ package com.moulberry.flashback; +import com.google.gson.Gson; +import com.google.gson.JsonObject; import com.mojang.brigadier.context.CommandContext; +import com.mojang.realmsclient.RealmsMainScreen; import com.mojang.serialization.Lifecycle; import com.moulberry.flashback.action.*; import com.moulberry.flashback.configuration.FlashbackConfig; import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.packet.FlashbackClearParticles; import com.moulberry.flashback.packet.FinishedServerTick; +import com.moulberry.flashback.packet.FlashbackForceClientTick; +import com.moulberry.flashback.packet.FlashbackInstantlyLerp; import com.moulberry.flashback.playback.EmptyLevelSource; import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.record.FlashbackMeta; import com.moulberry.flashback.record.Recorder; +import com.moulberry.flashback.record.ReplayExporter; +import com.moulberry.flashback.screen.ConfigScreen; +import com.moulberry.flashback.screen.SaveReplayScreen; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; +import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.FileUtil; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.toasts.SystemToast; +import net.minecraft.client.gui.screens.PauseScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen; import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.server.IntegratedServer; import net.minecraft.commands.Commands; import net.minecraft.core.*; import net.minecraft.core.registries.Registries; @@ -31,6 +51,9 @@ import net.minecraft.server.*; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.packs.repository.ServerPacksSource; import net.minecraft.world.Difficulty; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.level.*; import net.minecraft.world.level.biome.Biome; @@ -48,12 +71,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; public class Flashback implements ModInitializer, ClientModInitializer { public static final Logger LOGGER = LoggerFactory.getLogger("flashback"); @@ -61,12 +92,26 @@ public class Flashback implements ModInitializer, ClientModInitializer { public static final int MAGIC = 0xD780E884; public static Recorder RECORDER = null; public static ExportJob EXPORT_JOB = null; + private static FlashbackConfig config; private static Path configDirectory = null; + private static int delayedStartRecording = 0; + private static boolean delayedOpenConfig = false; + + private static final List pendingReplaySave = new ArrayList<>(); + public static ResourceLocation createResourceLocation(String value) { return ResourceLocation.fromNamespaceAndPath("flashback", value); } + public static Path getDataDirectory() { + return FabricLoader.getInstance().getGameDir().resolve("flashback"); + } + + public static Path getReplayFolder() { + return Flashback.getDataDirectory().resolve("replays"); + } + public static Path getConfigDirectory() { if (configDirectory == null) { configDirectory = FabricLoader.getInstance().getConfigDir().resolve("flashback"); @@ -81,19 +126,57 @@ public class Flashback implements ModInitializer, ClientModInitializer { @Override public void onInitialize() { - net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry.playS2C().register(FinishedServerTick.TYPE, + PayloadTypeRegistry.playS2C().register(FinishedServerTick.TYPE, StreamCodec.unit(FinishedServerTick.INSTANCE)); + + PayloadTypeRegistry.playS2C().register(FlashbackForceClientTick.TYPE, StreamCodec.unit(FlashbackForceClientTick.INSTANCE)); + ClientPlayNetworking.registerGlobalReceiver(FlashbackForceClientTick.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Minecraft.getInstance().tick(); + } + }); + + PayloadTypeRegistry.playS2C().register(FlashbackClearParticles.TYPE, StreamCodec.unit(FlashbackClearParticles.INSTANCE)); + ClientPlayNetworking.registerGlobalReceiver(FlashbackClearParticles.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + Minecraft.getInstance().particleEngine.clearParticles(); + } + }); + + PayloadTypeRegistry.playS2C().register(FlashbackInstantlyLerp.TYPE, StreamCodec.unit(FlashbackInstantlyLerp.INSTANCE)); + ClientPlayNetworking.registerGlobalReceiver(FlashbackInstantlyLerp.TYPE, (payload, context) -> { + if (Flashback.isInReplay()) { + for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) { + if (entity instanceof LivingEntity && !entity.isRemoved() && !(entity instanceof LocalPlayer)) { + entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), + entity.lerpTargetYRot(), entity.lerpTargetXRot()); + } + entity.setOldPosAndRot(); + } + } + }); } @Override public void onInitializeClient() { - // todo: try recover unfinished recordings + Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback"); + try { + Files.createDirectories(configFolder); + } catch (IOException e) { + Flashback.LOGGER.error("Failed to create config folder", e); + } + + config = FlashbackConfig.tryLoadFromFolder(configFolder); + + // todo: try recover unfinished recordings TempFolderProvider.tryDeleteStaleFolders(); try { FileUtils.deleteDirectory(Path.of("replay_export_temp").toFile()); } catch (Exception ignored) {} + this.deleteUnusedReplayStates(); + ActionRegistry.register(ActionNextTick.INSTANCE); ActionRegistry.register(ActionGamePacket.INSTANCE); ActionRegistry.register(ActionConfigurationPacket.INSTANCE); @@ -104,11 +187,142 @@ public class Flashback implements ModInitializer, ClientModInitializer { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { var flashback = ClientCommandManager.literal("flashback"); flashback.then(ClientCommandManager.literal("start").executes(this::startRecordingReplay)); + flashback.then(ClientCommandManager.literal("finish").executes(this::finishRecordingReplay)); flashback.then(ClientCommandManager.literal("end").executes(this::finishRecordingReplay)); + flashback.then(ClientCommandManager.literal("config").executes(this::openFlashbackConfig)); dispatcher.register(flashback); }); + + ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> { + if (!Flashback.isInReplay() && Flashback.getConfig().automaticallyStart && RECORDER == null) { + delayedStartRecording = 20; + } + }); + + ClientTickEvents.START_CLIENT_TICK.register(tick -> { + if (!pendingReplaySave.isEmpty()) { + Screen currentScreen = Minecraft.getInstance().screen; + if (currentScreen == null || currentScreen instanceof PauseScreen || currentScreen instanceof TitleScreen + || currentScreen instanceof RealmsMainScreen || currentScreen instanceof JoinMultiplayerScreen) { + Path recordFolder = pendingReplaySave.getFirst(); + + LocalDateTime dateTime = LocalDateTime.now(); + dateTime = dateTime.withNano(0); + Minecraft.getInstance().setScreen(new SaveReplayScreen(Minecraft.getInstance().screen, + recordFolder, dateTime.toString())); + } + } + + if (Minecraft.getInstance().level != null && delayedStartRecording > 0) { + IntegratedServer integratedServer = Minecraft.getInstance().getSingleplayerServer(); + if (integratedServer != null && integratedServer.getClass() != IntegratedServer.class) { + delayedStartRecording = 0; // Only allow on actual integrated servers, not replay servers or any other custom server a mod might spin up + } else if (Flashback.getConfig().automaticallyStart && RECORDER == null) { + delayedStartRecording -= 1; + if (delayedStartRecording == 0) { + startRecordingReplay(); + } + } else { + delayedStartRecording = 0; + } + } + + if (delayedOpenConfig) { + if (Minecraft.getInstance().screen == null) { + Minecraft.getInstance().setScreen(new ConfigScreen(null)); + } + delayedOpenConfig = false; + } + }); } + private void deleteUnusedReplayStates() { + Path flashbackDir = Flashback.getDataDirectory(); + Path replayDir = flashbackDir.resolve("replays"); + Path replayStatesDir = flashbackDir.resolve("editor_states"); + + if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) { + return; + } + if (!Files.exists(replayStatesDir) || !Files.isDirectory(replayStatesDir)) { + return; + } + + CompletableFuture.runAsync(() -> { + Map replayStates = new HashMap<>(); + + // Find existing replay states + try (DirectoryStream directoryStream = Files.newDirectoryStream(replayStatesDir)) { + for (Path path : directoryStream) { + String filename = path.getFileName().toString(); + + String withoutExtension = null; + + if (filename.endsWith(".json")) { + withoutExtension = filename.substring(0, filename.length() - 5); + } else if (filename.endsWith(".json.old")) { + withoutExtension = filename.substring(0, filename.length() - 9); + } + + if (withoutExtension != null) { + UUID uuid; + try { + uuid = UUID.fromString(withoutExtension); + } catch (Exception ignored) { + continue; + } + + replayStates.put(uuid, path); + } + } + } catch (IOException ignored) {} + + // Find which uuids are still valid because they have replays + Set replayUuids = new HashSet<>(); + try (DirectoryStream directoryStream = Files.newDirectoryStream(replayDir)) { + for (Path path : directoryStream) { + if (!path.toString().endsWith(".zip")) { + continue; + } + + String metadataString = null; + + try (FileSystem fs = FileSystems.newFileSystem(path)) { + Path metadataPath = fs.getPath("/metadata.json"); + if (Files.exists(metadataPath)) { + metadataString = Files.readString(metadataPath); + } + } catch (IOException ignored) { + continue; + } + + if (metadataString != null) { + JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class); + FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson); + if (metadata != null) { + replayUuids.add(metadata.replayIdentifier); + } + } + } + } catch (IOException e) { + Flashback.LOGGER.error("Unable to iterate replay directory", e); + return; + } + + for (Map.Entry entry : replayStates.entrySet()) { + if (!replayUuids.contains(entry.getKey())) { + try { + Files.deleteIfExists(entry.getValue()); + } catch (IOException ignored) {} + } + } + }, Util.backgroundExecutor()); + } + + public static FlashbackConfig getConfig() { + return config; + } + @Nullable public static ReplayServer getReplayServer() { if (Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer replayServer) { @@ -117,6 +331,14 @@ public class Flashback implements ModInitializer, ClientModInitializer { return null; } + public static void removePendingReplaySave(Path recordFolder) { + pendingReplaySave.remove(recordFolder); + } + + public static boolean isExporting() { + return EXPORT_JOB != null && EXPORT_JOB.isRunning(); + } + public static boolean isInReplay() { return Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer; } @@ -131,6 +353,11 @@ public class Flashback implements ModInitializer, ClientModInitializer { return 0; } + private int openFlashbackConfig(CommandContext command) { + delayedOpenConfig = true; + return 0; + } + public static void startRecordingReplay() { if (RECORDER != null) { SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, @@ -138,29 +365,35 @@ public class Flashback implements ModInitializer, ClientModInitializer { return; } RECORDER = new Recorder(Minecraft.getInstance().player.registryAccess()); - if (FlashbackConfig.showRecordingToasts) { + if (Flashback.getConfig().showRecordingToasts) { SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, - Component.literal("Started Recording"), Component.literal("Started recording")); + Component.literal("Flashback"), Component.literal("Started recording")); } } public static void pauseRecordingReplay(boolean pause) { RECORDER.setPaused(pause); - if (FlashbackConfig.showRecordingToasts) { + if (Flashback.getConfig().showRecordingToasts) { SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, - Component.literal("Paused Recording"), Component.literal("Paused recording")); + Component.literal("Flashback"), Component.literal("Paused recording")); } } public static void cancelRecordingReplay() { Recorder recorder = RECORDER; RECORDER = null; - recorder.finish(null); - if (FlashbackConfig.showRecordingToasts) { + Path recordFolder = recorder.finish(); + try { + FileUtils.deleteDirectory(recordFolder.toFile()); + } catch (Exception e) { + Flashback.LOGGER.error("Exception deleting record folder", e); + } + + if (Flashback.getConfig().showRecordingToasts) { SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, - Component.literal("Cancelled Recording"), Component.literal("Cancelled recording")); + Component.literal("Flashback"), Component.literal("Cancelled recording")); } } @@ -175,31 +408,28 @@ public class Flashback implements ModInitializer, ClientModInitializer { RECORDER = null; recorder.endTick(true); - Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback"); - Path replayDir = flashbackDir.resolve("replays"); + if (Flashback.getConfig().quicksave) { + Path replayDir = getReplayFolder(); - try { - Files.createDirectories(replayDir); - } catch (IOException e) { - Flashback.LOGGER.error("Error while trying to create replay directory", e); + String filename; + try { + LocalDateTime dateTime = LocalDateTime.now(); + dateTime = dateTime.withNano(0); + filename = FileUtil.findAvailableName(replayDir, dateTime.toString(), ".zip"); + } catch (IOException e) { + Flashback.LOGGER.error("Error while trying to determine filename", e); + filename = UUID.randomUUID() + ".zip"; + } + + Path outputFile = replayDir.resolve(filename); + ReplayExporter.export(recorder.finish(), outputFile, null); + } else { + pendingReplaySave.add(recorder.finish()); } - String name; - - try { - LocalDateTime dateTime = LocalDateTime.now(); - dateTime = dateTime.withNano(0); - name = FileUtil.findAvailableName(replayDir, dateTime.toString(), ".zip"); - - Path outputFile = replayDir.resolve(name); - recorder.finish(outputFile); - } catch (IOException e) { - throw SneakyThrow.sneakyThrow(e); - } - - if (FlashbackConfig.showRecordingToasts) { + if (Flashback.getConfig().showRecordingToasts) { SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, - Component.literal("Finished Recording"), Component.literal(name)); + Component.literal("Flashback"), Component.literal("Finished recording")); } } @@ -231,6 +461,14 @@ public class Flashback implements ModInitializer, ClientModInitializer { GameRules gameRules = new GameRules(); gameRules.getRule(GameRules.RULE_DOMOBSPAWNING).set(false, null); + gameRules.getRule(GameRules.RULE_DOENTITYDROPS).set(false, null); + gameRules.getRule(GameRules.RULE_ANNOUNCE_ADVANCEMENTS).set(false, null); + gameRules.getRule(GameRules.RULE_DISABLE_RAIDS).set(true, null); + gameRules.getRule(GameRules.RULE_DO_PATROL_SPAWNING).set(false, null); + gameRules.getRule(GameRules.RULE_DO_WARDEN_SPAWNING).set(false, null); + gameRules.getRule(GameRules.RULE_DO_TRADER_SPAWNING).set(false, null); + gameRules.getRule(GameRules.RULE_DO_VINES_SPREAD).set(false, null); + gameRules.getRule(GameRules.RULE_DOFIRETICK).set(false, null); gameRules.getRule(GameRules.RULE_WEATHER_CYCLE).set(false, null); gameRules.getRule(GameRules.RULE_RANDOMTICKING).set(0, null); diff --git a/src/main/java/com/moulberry/flashback/FlashbackGson.java b/src/main/java/com/moulberry/flashback/FlashbackGson.java index 6346ac5..7a75838 100644 --- a/src/main/java/com/moulberry/flashback/FlashbackGson.java +++ b/src/main/java/com/moulberry/flashback/FlashbackGson.java @@ -4,11 +4,15 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.impl.CameraKeyframe; +import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; +import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; import com.moulberry.flashback.keyframe.impl.FOVKeyframe; import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; +import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; import com.moulberry.flashback.serialization.QuaternionTypeAdapater; import com.moulberry.flashback.serialization.Vector3fTypeAdapater; +import com.moulberry.flashback.state.EditorStateHistoryAction; import org.joml.Quaternionf; import org.joml.Vector3f; @@ -19,13 +23,23 @@ public class FlashbackGson { private static GsonBuilder build() { return new GsonBuilder() - .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapater()) - .registerTypeAdapter(Quaternionf.class, new QuaternionTypeAdapater()) - .registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter()) - .registerTypeAdapter(FOVKeyframe.class, new FOVKeyframe.TypeAdapter()) - .registerTypeAdapter(TickrateKeyframe.class, new TickrateKeyframe.TypeAdapter()) - .registerTypeAdapter(TimeOfDayKeyframe.class, new TimeOfDayKeyframe.TypeAdapter()) - .registerTypeAdapter(Keyframe.class, new Keyframe.TypeAdapter()); + .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapater()) + .registerTypeAdapter(Quaternionf.class, new QuaternionTypeAdapater()) + + .registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter()) + .registerTypeAdapter(CameraOrbitKeyframe.class, new CameraOrbitKeyframe.TypeAdapter()) + .registerTypeAdapter(FOVKeyframe.class, new FOVKeyframe.TypeAdapter()) + .registerTypeAdapter(CameraShakeKeyframe.class, new CameraShakeKeyframe.TypeAdapter()) + .registerTypeAdapter(TickrateKeyframe.class, new TickrateKeyframe.TypeAdapter()) + .registerTypeAdapter(TimelapseKeyframe.class, new TimelapseKeyframe.TypeAdapter()) + .registerTypeAdapter(TimeOfDayKeyframe.class, new TimeOfDayKeyframe.TypeAdapter()) + .registerTypeAdapter(Keyframe.class, new Keyframe.TypeAdapter()) + + .registerTypeAdapter(EditorStateHistoryAction.SetKeyframe.class, new EditorStateHistoryAction.SetKeyframe.TypeAdapter()) + .registerTypeAdapter(EditorStateHistoryAction.RemoveKeyframe.class, new EditorStateHistoryAction.RemoveKeyframe.TypeAdapter()) + .registerTypeAdapter(EditorStateHistoryAction.AddTrack.class, new EditorStateHistoryAction.AddTrack.TypeAdapter()) + .registerTypeAdapter(EditorStateHistoryAction.RemoveTrack.class, new EditorStateHistoryAction.RemoveTrack.TypeAdapter()) + .registerTypeAdapter(EditorStateHistoryAction.class, new EditorStateHistoryAction.TypeAdapter()); } } diff --git a/src/main/java/com/moulberry/flashback/Interpolation.java b/src/main/java/com/moulberry/flashback/Interpolation.java index d656705..448e7b5 100644 --- a/src/main/java/com/moulberry/flashback/Interpolation.java +++ b/src/main/java/com/moulberry/flashback/Interpolation.java @@ -1,5 +1,6 @@ package com.moulberry.flashback; +import net.minecraft.util.Mth; import org.joml.Quaternionf; public class Interpolation { @@ -12,6 +13,11 @@ public class Interpolation { return from + (to - from) * amount; } + + public static float linearAngle(float from, float to, float amount) { + return from + Mth.wrapDegrees(to - from) * amount; + } + public static Quaternionf linear(Quaternionf from, Quaternionf to, float amount) { return from.slerp(to, amount, new Quaternionf()); } diff --git a/src/main/java/com/moulberry/flashback/PacketHelper.java b/src/main/java/com/moulberry/flashback/PacketHelper.java index bb05451..77bc623 100644 --- a/src/main/java/com/moulberry/flashback/PacketHelper.java +++ b/src/main/java/com/moulberry/flashback/PacketHelper.java @@ -1,11 +1,60 @@ package com.moulberry.flashback; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientGamePacketListener; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.network.protocol.game.VecDeltaCodec; +import net.minecraft.server.level.ServerEntity; +import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.ExperienceOrb; +import net.minecraft.world.entity.Marker; +import net.minecraft.world.entity.Pose; +import net.minecraft.world.entity.boss.EnderDragonPart; +import net.minecraft.world.entity.decoration.ItemFrame; +import net.minecraft.world.entity.decoration.Painting; +import net.minecraft.world.entity.item.FallingBlockEntity; +import net.minecraft.world.entity.monster.warden.Warden; +import net.minecraft.world.level.block.Block; + +import java.util.ArrayList; public class PacketHelper { - public static ClientboundAddEntityPacket createAddEntity(Entity entity) { + public static boolean shouldIgnoreEntity(Entity entity) { + return entity == null || entity.isRemoved() || entity instanceof EnderDragonPart || entity.getType().clientTrackingRange() <= 0; + } + + public static Packet createAddEntity(Entity entity) { + ServerEntity serverEntity = null; + + // Try to construct ServerEntity with dummy values + try { + serverEntity = new ServerEntity(null, entity, 1, false, packet -> {}); + } catch (Exception e) {} + + // Error while trying to construct, possibly mod incompatibility? Try bypassing the constructor + if (serverEntity == null) { + try { + serverEntity = (ServerEntity) UnsafeWrapper.UNSAFE.allocateInstance(ServerEntity.class); + serverEntity.positionCodec = new VecDeltaCodec(); + serverEntity.lastPassengers = new ArrayList<>(); + serverEntity.broadcast = packet -> {}; + serverEntity.entity = entity; + serverEntity.positionCodec.setBase(entity.trackingPosition()); + serverEntity.lastSentMovement = entity.getDeltaMovement(); + serverEntity.lastSentYRot = Mth.floor((entity.getYRot() * 256.0f / 360.0f)); + serverEntity.lastSentXRot = Mth.floor((entity.getXRot() * 256.0f / 360.0f)); + serverEntity.lastSentYHeadRot = Mth.floor((entity.getYHeadRot() * 256.0f / 360.0f)); + serverEntity.wasOnGround = entity.onGround(); + serverEntity.trackedDataValues = entity.getEntityData().getNonDefaultValues(); + } catch (Exception e) {} + } + + try { + return entity.getAddEntityPacket(serverEntity); + } catch (Exception e) {} + return createAddEntity(entity, 0); } diff --git a/src/main/java/com/moulberry/flashback/ReplayVisuals.java b/src/main/java/com/moulberry/flashback/ReplayVisuals.java deleted file mode 100644 index ae514bf..0000000 --- a/src/main/java/com/moulberry/flashback/ReplayVisuals.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.moulberry.flashback; - -import com.moulberry.flashback.combo_options.AspectRatio; -import com.moulberry.flashback.combo_options.Sizing; -import net.minecraft.client.Minecraft; - -public class ReplayVisuals { - - // todo: move all of this to replaystate? - - public static boolean showChat = true; - public static boolean showBossBar = true; - public static boolean showTitleText = true; - public static boolean showScoreboard = true; - public static boolean showActionBar = true; - - public static boolean renderBlocks = true; - public static boolean renderEntities = true; - public static boolean renderPlayers = true; - public static boolean renderParticles = true; - public static boolean renderSky = true; - public static boolean renderNametags = true; - - public static boolean overrideFog = false; - public static float overrideFogStart = 0.0f; - public static float overrideFogEnd = 256.0f; - - public static boolean overrideFov = false; - public static float overrideFovAmount = 70f; - - public static long overrideTimeOfDay = -1; - - public static boolean ruleOfThirdsGuide = false; - public static boolean centerGuide = false; - public static Sizing sizing = Sizing.KEEP_ASPECT_RATIO; - public static AspectRatio changeAspectRatio = AspectRatio.ASPECT_16_9; - - public static volatile int forceEntityLerpTicks = 0; - - public static void setFov(float fov) { - if (!overrideFov || Math.abs(overrideFovAmount - fov) >= 0.01) { - Minecraft.getInstance().levelRenderer.needsUpdate(); - } - - overrideFov = true; - overrideFovAmount = fov; - } - - public static void disable() { - showBossBar = true; - showTitleText = true; - showScoreboard = true; - showActionBar = true; - - renderBlocks = true; - renderEntities = true; - renderParticles = true; - renderSky = true; - renderNametags = true; - - overrideFog = false; - ruleOfThirdsGuide = false; - centerGuide = false; - overrideFov = false; - forceEntityLerpTicks = 0; - overrideTimeOfDay = -1; - } - - public static void setupReplay() { - disable(); - - showChat = false; - showBossBar = false; - showTitleText = false; - showActionBar = false; - showScoreboard = false; - } - -} diff --git a/src/main/java/com/moulberry/flashback/TempFolderProvider.java b/src/main/java/com/moulberry/flashback/TempFolderProvider.java index bb52875..f756aab 100644 --- a/src/main/java/com/moulberry/flashback/TempFolderProvider.java +++ b/src/main/java/com/moulberry/flashback/TempFolderProvider.java @@ -15,8 +15,7 @@ public class TempFolderProvider { public enum TempFolderType { SERVER("server"), - RECORDING("recording"), - PLAYBACK("playback"); + RECORDING("recording"); private final String id; @@ -26,9 +25,7 @@ public class TempFolderProvider { } private static Path getSharedTempFolder() { - return FabricLoader.getInstance().getGameDir() - .resolve("flashback") - .resolve("temp"); + return Flashback.getDataDirectory().resolve("temp"); } public static void tryDeleteStaleFolders() { @@ -126,7 +123,7 @@ public class TempFolderProvider { try { FileUtils.deleteDirectory(path.toFile()); } catch (Exception e) { - throw new RuntimeException(e); + Flashback.LOGGER.error("Failed to delete temp directory", e); } deleteDirectoryIfEmpty(path.getParent()); diff --git a/src/main/java/com/moulberry/flashback/UnsafeWrapper.java b/src/main/java/com/moulberry/flashback/UnsafeWrapper.java new file mode 100644 index 0000000..17d0730 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/UnsafeWrapper.java @@ -0,0 +1,52 @@ +package com.moulberry.flashback; + +import org.lwjgl.system.Pointer; +import org.lwjgl.system.jni.JNINativeInterface; +import sun.misc.Unsafe; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.util.Objects; +import java.util.function.LongPredicate; + +public class UnsafeWrapper { + + public static final Unsafe UNSAFE; + + static { + UNSAFE = getUnsafeInstance(); + } + + private static Unsafe getUnsafeInstance() { + // Try getting theUnsafe + try { + final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + return (Unsafe) theUnsafe.get(null); + } catch (Exception ignored) {} + + // Try searching for fields + Field[] fields = Unsafe.class.getDeclaredFields(); + for (Field field : fields) { + if (!field.getType().equals(Unsafe.class)) { + continue; + } + + int modifiers = field.getModifiers(); + if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers)) { + continue; + } + + try { + field.setAccessible(true); + return (Unsafe) field.get(null); + } catch (Exception ignored) {} + break; + } + + // Unavailable! :( + throw new Error("Flashback requires sun.misc.Unsafe to be available."); + } + +} diff --git a/src/main/java/com/moulberry/flashback/Utils.java b/src/main/java/com/moulberry/flashback/Utils.java index 814628e..2e40296 100644 --- a/src/main/java/com/moulberry/flashback/Utils.java +++ b/src/main/java/com/moulberry/flashback/Utils.java @@ -3,6 +3,9 @@ package com.moulberry.flashback; import it.unimi.dsi.fastutil.objects.Object2FloatFunction; import org.jetbrains.annotations.Nullable; +import java.lang.reflect.Field; +import java.util.Random; + public class Utils { /* @@ -57,4 +60,92 @@ public class Utils { } } + public static float fovToFocalLength(float fov) { + return 1.0f / (float) Math.tan(Math.toRadians(fov) * 0.5); + } + + public static float focalLengthToFov(float focalLength) { + return (float) Math.toDegrees(Math.atan(1.0 / focalLength) * 2.0f); + } + + public static Random getInternalMathRandom() { + for (Class declaredClass : Math.class.getDeclaredClasses()) { + try { + if (declaredClass.getSimpleName().endsWith("RandomNumberGeneratorHolder")) { + Field field = declaredClass.getDeclaredField("randomNumberGenerator"); + + if (field.trySetAccessible()) { + return (Random) field.get(null); + } else { + return (Random) UnsafeWrapper.UNSAFE.getObject(UnsafeWrapper.UNSAFE.staticFieldBase(field), + UnsafeWrapper.UNSAFE.staticFieldOffset(field)); + } + } + } catch (Exception e) { + Flashback.LOGGER.error("Failed to get internal Math random", e); + } + } + return null; + } + + private static final int SECOND_TO_TICKS = 20; + private static final int MINUTE_TO_TICKS = SECOND_TO_TICKS * 60; + private static final int HOUR_TO_TICKS = MINUTE_TO_TICKS * 60; + + public static int stringToTime(String string) { + int number = 0; + int modifier = 1; + int total = 0; + + for (char c : string.toCharArray()) { + if (c >= '0' && c <= '9') { + if (modifier > 1) { + total += number * modifier; + number = 0; + modifier = 1; + } + + number *= 10; + number += c - '0'; + } else if (c == 's') { + modifier *= SECOND_TO_TICKS; + } else if (c == 'm') { + modifier *= MINUTE_TO_TICKS; + } else if (c == 'h') { + modifier *= HOUR_TO_TICKS; + } + } + + total += number * modifier; + + return total; + } + + public static String timeToString(int ticks) { + StringBuilder builder = new StringBuilder(); + timeToString(builder, ticks); + if (builder.isEmpty()) { + return "0s"; + } + return builder.toString(); + } + + private static void timeToString(StringBuilder builder, int ticks) { + if (ticks >= HOUR_TO_TICKS) { + int hours = ticks / HOUR_TO_TICKS; + builder.append(hours).append('h'); + timeToString(builder, ticks - hours*HOUR_TO_TICKS); + } else if (ticks >= MINUTE_TO_TICKS) { + int minutes = ticks / MINUTE_TO_TICKS; + builder.append(minutes).append('m'); + timeToString(builder, ticks - minutes*MINUTE_TO_TICKS); + } else if (ticks >= SECOND_TO_TICKS) { + int seconds = ticks / SECOND_TO_TICKS; + builder.append(seconds).append('s'); + timeToString(builder, ticks - seconds*SECOND_TO_TICKS); + } else if (ticks > 0) { + builder.append(ticks).append('t'); + } + } + } diff --git a/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java b/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java new file mode 100644 index 0000000..21fcc25 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/AudioCodec.java @@ -0,0 +1,87 @@ +package com.moulberry.flashback.combo_options; + +import org.bytedeco.ffmpeg.avcodec.AVCodec; +import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig; +import org.bytedeco.ffmpeg.global.avcodec; +import org.bytedeco.javacpp.Pointer; + +import java.util.ArrayList; +import java.util.List; + +public enum AudioCodec implements ComboOption { + + AAC("AAC", avcodec.AV_CODEC_ID_AAC), + FLAC("FLAC", avcodec.AV_CODEC_ID_FLAC), + MP3("MP3", avcodec.AV_CODEC_ID_MP3), + OPUS("Opus", avcodec.AV_CODEC_ID_OPUS), + VORBIS("Vorbis", avcodec.AV_CODEC_ID_VORBIS); + + private final String text; + private final int codecId; + private String[] encoders; + + AudioCodec(String text, int codecId) { + this.text = text; + this.codecId = codecId; + } + + @Override + public String text() { + return this.text; + } + + public int codecId() { + return this.codecId; + } + + public String[] getEncoders() { + if (this.encoders == null) { + List encodersHardware = new ArrayList<>(); + List encodersHybrid = new ArrayList<>(); + List encodersSoftware = new ArrayList<>(); + List encodersAvoid = new ArrayList<>(); + + try (Pointer pointer = new Pointer()) { + while (true) { + try (AVCodec codec = avcodec.av_codec_iterate(pointer)) { + if (codec == null) { + break; + } else if (codec.id() == this.codecId && avcodec.av_codec_is_encoder(codec) != 0) { + int capabilities = codec.capabilities(); + String name = codec.name().getString(); + + if ((capabilities & avcodec.AV_CODEC_CAP_HARDWARE) != 0) { + encodersHardware.add(name); + } else if ((capabilities & avcodec.AV_CODEC_CAP_HYBRID) != 0 || codecHasHwConfig(codec)) { + encodersHybrid.add(name); + } else if ((capabilities & avcodec.AV_CODEC_CAP_EXPERIMENTAL) != 0) { + encodersAvoid.add(name); + } else { + encodersSoftware.add(name); + } + } + } + } + } + + List encoders = new ArrayList<>(); + encoders.addAll(encodersHardware); + encoders.addAll(encodersHybrid); + encoders.addAll(encodersSoftware); + encoders.addAll(encodersAvoid); + + this.encoders = encoders.toArray(new String[0]); + } + + return this.encoders; + } + + private static boolean codecHasHwConfig(AVCodec codec) { + try (AVCodecHWConfig config = avcodec.avcodec_get_hw_config(codec, 0)) { + return config != null; + } catch (Throwable t) { + return false; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/combo_options/Sizing.java b/src/main/java/com/moulberry/flashback/combo_options/Sizing.java index 0702547..870b346 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/Sizing.java +++ b/src/main/java/com/moulberry/flashback/combo_options/Sizing.java @@ -3,9 +3,9 @@ package com.moulberry.flashback.combo_options; public enum Sizing implements ComboOption { KEEP_ASPECT_RATIO("Keep Aspect Ratio"), + CHANGE_ASPECT_RATIO("Change Aspect Ratio"), FILL("Fill"), - UNDERLAY("Underlay"), - CHANGE_ASPECT_RATIO("Change Aspect Ratio"); + UNDERLAY("Underlay"); private final String text; diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java index d0e7fac..09b5862 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java @@ -1,18 +1,21 @@ package com.moulberry.flashback.combo_options; -import com.moulberry.flashback.Flashback; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; +import com.moulberry.flashback.exporting.PixelFormatHelper; import org.bytedeco.ffmpeg.avcodec.AVCodec; +import org.bytedeco.ffmpeg.avcodec.AVCodecContext; import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig; +import org.bytedeco.ffmpeg.avutil.AVDictionary; +import org.bytedeco.ffmpeg.avutil.AVRational; import org.bytedeco.ffmpeg.global.avcodec; import org.bytedeco.ffmpeg.global.avutil; -import org.bytedeco.javacpp.BytePointer; -import org.bytedeco.javacpp.IntPointer; import org.bytedeco.javacpp.Pointer; import java.util.*; +import static org.bytedeco.ffmpeg.global.avcodec.*; +import static org.bytedeco.ffmpeg.global.avutil.*; +import static org.bytedeco.ffmpeg.global.avutil.av_find_nearest_q_idx; + public enum VideoCodec implements ComboOption { H264("H264 (AVC)", avcodec.AV_CODEC_ID_H264), @@ -50,9 +53,20 @@ public enum VideoCodec implements ComboOption { try (Pointer pointer = new Pointer()) { while (true) { try (AVCodec codec = avcodec.av_codec_iterate(pointer)) { - if (codec == null) { - break; - } else if (codec.id() == this.codecId && avcodec.av_codec_is_encoder(codec) != 0) { + try { + if (codec == null) { + break; + } + if (codec.id() != this.codecId) { + continue; + } + if (avcodec.av_codec_is_encoder(codec) == 0) { + continue; + } + if (!doesEncoderWork(codec)) { + continue; + } + int capabilities = codec.capabilities(); String name = codec.name().getString(); @@ -65,6 +79,10 @@ public enum VideoCodec implements ComboOption { } else { encodersSoftware.add(name); } + } finally { + if (codec != null) { + codec.close(); + } } } } @@ -82,12 +100,58 @@ public enum VideoCodec implements ComboOption { return this.encoders; } + private static boolean doesEncoderWork(AVCodec codec) { + AVCodecContext codecContext = null; + AVDictionary options = new AVDictionary(null); + + try { + if ((codecContext = avcodec.avcodec_alloc_context3(codec)) == null) { + return false; + } + + // Setup dummy parameters + codecContext.codec_id(codec.id()); + codecContext.codec_type(AVMEDIA_TYPE_VIDEO); + codecContext.bit_rate(400000); + codecContext.width(1920); + codecContext.height(1080); + + AVRational frameRate = av_d2q(60.0, 1001000); + AVRational supportedFramerates = codec.supported_framerates(); + if (supportedFramerates != null) { + int idx = av_find_nearest_q_idx(frameRate, supportedFramerates); + frameRate = supportedFramerates.position(idx); + } + + AVRational time_base = av_inv_q(frameRate); + codecContext.time_base(time_base); + + int pixelFormat = PixelFormatHelper.getBestPixelFormat(codec.name().getString()); + codecContext.pix_fmt(pixelFormat); + + if ((codec.capabilities() & AV_CODEC_CAP_EXPERIMENTAL) != 0) { + codecContext.strict_std_compliance(FF_COMPLIANCE_EXPERIMENTAL); + } + + return avcodec.avcodec_open2(codecContext, codec, options) >= 0; + } finally { + if (codecContext != null) { + avcodec.avcodec_close(codecContext); + codecContext.close(); + } + avutil.av_dict_free(options); + } + + } + private static boolean codecHasHwConfig(AVCodec codec) { try (AVCodecHWConfig config = avcodec.avcodec_get_hw_config(codec, 0)) { - return config != null; - } catch (Throwable t) { - return false; - } + if (config != null) { + config.close(); + return true; + } + } catch (Exception ignored) {} + return false; } } diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java b/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java index d1de03c..57af412 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java @@ -16,7 +16,8 @@ public enum VideoContainer implements ComboOption { private final String text; private final String extension; - private VideoCodec[] supportedCodecs = null; + private VideoCodec[] supportedVideoCodecs = null; + private AudioCodec[] supportedAudioCodecs = null; VideoContainer(String text, String extension) { this.text = text; @@ -32,8 +33,8 @@ public enum VideoContainer implements ComboOption { return extension; } - public VideoCodec[] getSupportedCodecs() { - if (this.supportedCodecs == null) { + public VideoCodec[] getSupportedVideoCodecs() { + if (this.supportedVideoCodecs == null) { List supportedCodecs = new ArrayList<>(); try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) { for (VideoCodec codec : VideoCodec.values()) { @@ -51,9 +52,30 @@ public enum VideoContainer implements ComboOption { } } - this.supportedCodecs = supportedCodecs.toArray(new VideoCodec[0]); + this.supportedVideoCodecs = supportedCodecs.toArray(new VideoCodec[0]); } - return this.supportedCodecs; + return this.supportedVideoCodecs; + } + + public AudioCodec[] getSupportedAudioCodecs() { + if (this.supportedAudioCodecs == null) { + List supportedCodecs = new ArrayList<>(); + try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) { + for (AudioCodec codec : AudioCodec.values()) { + if (codec.getEncoders().length == 0) { + continue; + } + + int ret = avformat.avformat_query_codec(outputFormat, codec.codecId(), avcodec.FF_COMPLIANCE_NORMAL); + if (ret == 1) { + supportedCodecs.add(codec); + } + } + } + + this.supportedAudioCodecs = supportedCodecs.toArray(new AudioCodec[0]); + } + return this.supportedAudioCodecs; } } diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoPreset.java b/src/main/java/com/moulberry/flashback/combo_options/VideoPreset.java deleted file mode 100644 index 3c15449..0000000 --- a/src/main/java/com/moulberry/flashback/combo_options/VideoPreset.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.moulberry.flashback.combo_options; - -public enum VideoPreset implements ComboOption { - - ULTRAFAST("Ultra Fast", "ultrafast"), - SUPERFAST("Super Fast", "superfast"), - VERYFAST("Very Fast", "veryfast"), - FASTER("Faster", "faster"), - FAST("Fast", "fast"), - MEDIUM("Medium", "medium"), - SLOW("Slow", "slow"), - SLOWER("Slower", "slower"), - VERYSLOW("Very Slow", "veryslow"); - - private final String text; - private final String presetId; - - VideoPreset(String text, String presetId) { - this.text = text; - this.presetId = presetId; - } - - @Override - public String text() { - return this.text; - } - - public String presetId() { - return this.presetId; - } -} diff --git a/src/main/java/com/moulberry/flashback/compat/IrisApiWrapper.java b/src/main/java/com/moulberry/flashback/compat/IrisApiWrapper.java new file mode 100644 index 0000000..17c1b60 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/compat/IrisApiWrapper.java @@ -0,0 +1,18 @@ +package com.moulberry.flashback.compat; + +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.api.v0.IrisApi; +import org.jetbrains.annotations.Nullable; + +public class IrisApiWrapper { + + public static boolean isIrisAvailable() { + return FabricLoader.getInstance().isModLoaded("iris"); + } + + public static boolean isShaderPackInUse() { + return IrisApi.getInstance().isShaderPackInUse(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java index a31dc92..f99a386 100644 --- a/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java +++ b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java @@ -1,14 +1,23 @@ package com.moulberry.flashback.configuration; +import com.google.common.reflect.Reflection; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.SneakyThrow; import net.minecraft.ChatFormatting; import net.minecraft.client.OptionInstance; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; +import org.apache.logging.log4j.core.util.ReflectionUtil; +import org.jetbrains.annotations.Nullable; +import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; @@ -16,24 +25,32 @@ public class FlashbackConfig { @OptionCaption("flashback.option.automatically_start") @OptionDescription("flashback.option.automatically_start.description") - public static boolean automaticallyStart = false; + public boolean automaticallyStart = false; @OptionCaption("flashback.option.automatically_finish") @OptionDescription("flashback.option.automatically_finish.description") - public static boolean automaticallyFinish = true; + public boolean automaticallyFinish = true; @OptionCaption("flashback.option.show_recording_toasts") @OptionDescription("flashback.option.show_recording_toasts.description") - public static boolean showRecordingToasts = true; + public boolean showRecordingToasts = true; + + @OptionCaption("flashback.option.quicksave") + @OptionDescription("flashback.option.quicksave.description") + public boolean quicksave = false; + + @OptionCaption("flashback.option.hide_pause_menu_controls") + @OptionDescription("flashback.option.hide_pause_menu_controls.description") + public boolean hidePauseMenuControls = false; @SuppressWarnings("unchecked") - public static OptionInstance[] createOptionInstances() { + public OptionInstance[] createOptionInstances() { List> options = new ArrayList<>(); for (Field field : FlashbackConfig.class.getDeclaredFields()) { try { - // Ignore non-static fields - if ((field.getModifiers() & Modifier.STATIC) == 0) { + // Ignore static & transient fields + if ((field.getModifiers() & Modifier.STATIC) != 0 || (field.getModifiers() & Modifier.TRANSIENT) != 0) { continue; } @@ -54,9 +71,9 @@ public class FlashbackConfig { } if (field.getType() == boolean.class) { - options.add(OptionInstance.createBoolean(caption.value(), tooltipSupplier, field.getBoolean(null), value -> { + options.add(OptionInstance.createBoolean(caption.value(), tooltipSupplier, field.getBoolean(this), value -> { try { - field.set(null, value); + field.set(this, value); } catch (Exception e) { throw SneakyThrow.sneakyThrow(e); } @@ -70,4 +87,58 @@ public class FlashbackConfig { return options.toArray(new OptionInstance[0]); } + public static FlashbackConfig tryLoadFromFolder(Path configFolder) { + Path primary = configFolder.resolve("flashback.json"); + Path backup = configFolder.resolve(".flashback.json.backup"); + + if (Files.exists(primary)) { + try { + return load(primary); + } catch (Exception e) { + Flashback.LOGGER.error("Failed to load config from {}", primary, e); + } + } + + if (Files.exists(backup)) { + try { + return load(backup); + } catch (Exception e) { + Flashback.LOGGER.error("Failed to load config from {}", backup, e); + } + } + + return new FlashbackConfig(); + } + + public void saveToFolder(Path configFolder) { + Path primary = configFolder.resolve("flashback.json"); + Path backup = configFolder.resolve(".flashback.json.backup"); + + if (Files.exists(primary)) { + try { + Files.move(primary, backup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + Flashback.LOGGER.error("Failed to backup config", e); + } + } + + this.save(primary); + } + + private static FlashbackConfig load(Path path) throws IOException { + String serialized = Files.readString(path); + return FlashbackGson.PRETTY.fromJson(serialized, FlashbackConfig.class); + } + + private void save(Path path) { + String serialized = FlashbackGson.PRETTY.toJson(this, FlashbackConfig.class); + + try { + Files.writeString(path, serialized, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, + StandardOpenOption.CREATE, StandardOpenOption.DSYNC); + } catch (IOException e) { + Flashback.LOGGER.error("Failed to save config", e); + } + } + } diff --git a/src/main/java/com/moulberry/flashback/editor/SavedTrack.java b/src/main/java/com/moulberry/flashback/editor/SavedTrack.java index 7045f9c..71922b3 100644 --- a/src/main/java/com/moulberry/flashback/editor/SavedTrack.java +++ b/src/main/java/com/moulberry/flashback/editor/SavedTrack.java @@ -3,53 +3,72 @@ package com.moulberry.flashback.editor; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateHistoryAction; +import com.moulberry.flashback.state.EditorStateHistoryEntry; import com.moulberry.flashback.state.KeyframeTrack; +import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.TreeMap; public record SavedTrack(KeyframeType type, int track, boolean copiedFromDisabled, - TreeMap> keyframes) { + TreeMap keyframes) { public int applyToEditorState(EditorState editorState, int cursorTicks, int totalTicks) { if (this.keyframes == null || this.keyframes.isEmpty()) { return 0; } - editorState.dirty = true; - // Try to apply directly to copied track if (this.track >= 0 && this.track < editorState.keyframeTracks.size()) { KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.track); if ((keyframeTrack.enabled || this.copiedFromDisabled) && keyframeTrack.keyframeType == this.type) { - return this.applyTo(keyframeTrack, cursorTicks, totalTicks); + return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks); } } // Try to find first eligible enabled track for (KeyframeTrack keyframeTrack : editorState.keyframeTracks) { if (keyframeTrack.enabled && keyframeTrack.keyframeType == this.type) { - return this.applyTo(keyframeTrack, cursorTicks, totalTicks); + return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks); } } // Create new track - KeyframeTrack keyframeTrack = new KeyframeTrack(this.type); - int count = this.applyTo(keyframeTrack, cursorTicks, totalTicks); - if (!keyframeTrack.keyframesByTick.isEmpty()) { - editorState.keyframeTracks.add(keyframeTrack); - } - return count; + return this.applyTo(editorState, this.type, null, this.track, cursorTicks, totalTicks); } - public int applyTo(KeyframeTrack keyframeTrack, int cursorTicks, int totalTicks) { + private int applyTo(EditorState editorState, KeyframeType type, @Nullable KeyframeTrack existing, int trackIndex, int cursorTicks, int totalTicks) { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + if (existing == null) { + undo.add(new EditorStateHistoryAction.RemoveTrack(type, trackIndex)); + redo.add(new EditorStateHistoryAction.AddTrack(type, trackIndex)); + } + int count = 0; - for (Map.Entry> entry : this.keyframes.entrySet()) { + for (Map.Entry entry : this.keyframes.entrySet()) { int newTick = entry.getKey() + cursorTicks; if (newTick >= 0 && newTick <= totalTicks) { - keyframeTrack.keyframesByTick.put(newTick, entry.getValue()); + if (existing != null) { + Keyframe old = existing.keyframesByTick.get(newTick); + + if (old != null) { + undo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, old.copy())); + } else { + undo.add(new EditorStateHistoryAction.RemoveKeyframe(type, trackIndex, newTick)); + } + } + redo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, entry.getValue().copy())); + count += 1; } } + + editorState.push(new EditorStateHistoryEntry(undo, redo, "Pasted " + count + " keyframe(s)")); + return count; } } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java index 87f4fd5..165d6bf 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java @@ -307,7 +307,7 @@ public class CustomImGuiImplGlfw { if (keyInBoundsForGame) this.keyPressedGame[minecraftKey] = action != GLFW_RELEASE; // Don't allow key presses during export - if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) { + if (Flashback.isExporting()) { if (action == GLFW_RELEASE && keyInBoundsForGame && this.keyPressedGame[minecraftKey]) { this.keyPressedGame[minecraftKey] = false; } else { diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java index 9076454..b0415a7 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java @@ -42,87 +42,6 @@ public class ImGuiHelper { return imString; } - public static int elementList(String name, List elements, float width, int minLines, int maxLines, boolean framed, IntConsumer buttonConsumer) { - if (minLines > maxLines) throw new IllegalArgumentException(); - - if (width <= 0) { - width = Math.max(ImGui.getContentRegionAvailX() + width, 4.0f); - } - - float itemSpacingX = ImGui.getStyle().getItemSpacingX(); - float framePaddingX = ImGui.getStyle().getFramePaddingX(); - float availableSpace = width; - if (framed) availableSpace -= framePaddingX*2f; - - int lines = 0; - boolean scrollbar = false; - if (minLines == maxLines) { - lines = minLines; - scrollbar = true; // assume there is a scrollbar - } else { - float consumedWidth = 0; - for (String element : elements) { - float elementWidth = framePaddingX*2f + ImGuiHelper.calcTextWidth(element); - if (consumedWidth+elementWidth < availableSpace && consumedWidth > 0) { - consumedWidth += elementWidth + itemSpacingX; - } else { - consumedWidth = elementWidth + itemSpacingX; - lines += 1; - if (lines > maxLines) { - lines = maxLines; - scrollbar = true; - break; - } - } - } - if (lines < minLines) lines = minLines; - } - - float lineHeight = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2 + ImGui.getStyle().getItemSpacingY(); - boolean visible; - if (framed) { - visible = ImGui.beginChildFrame(ImGui.getID(name), width, lineHeight*lines + ImGui.getStyle().getFramePaddingY()*2 - ImGui.getStyle().getItemSpacingY()); - } else { - visible = ImGui.beginChild(name, width, lineHeight*lines - ImGui.getStyle().getItemSpacingY()); - } - - int ret = -1; - - if (visible) { - if (scrollbar) { - availableSpace -= ImGui.getStyle().getScrollbarSize(); - } - - float consumedWidth = 0; - for (int i=0; i 0) { - ImGui.sameLine(); - consumedWidth += elementWidth + itemSpacingX; - } else { - consumedWidth = elementWidth + itemSpacingX; - } - ImGui.pushID(i); - if (ImGui.button(element)) { - ret = i; - } - if (buttonConsumer != null) { - buttonConsumer.accept(i); - } - ImGui.popID(); - } - } - - if (framed) { - ImGui.endChildFrame(); - } else { - ImGui.endChild(); - } - - return ret; - } - private static final int[] enumComboSharedArray = new int[]{0}; private static final Map, Object[]> enumComboCachedValues = new HashMap<>(); private static final Map, String[]> enumComboCachedText = new HashMap<>(); @@ -207,28 +126,18 @@ public class ImGuiHelper { private static boolean closeableModalOnTopLast = false; private static boolean closeableModalOnTop = false; - private static boolean inputIntScrolledLastFrame = false; - private static boolean inputIntScrolledThisFrame = false; - private static boolean wantSpecialInputLastFrame = false; private static boolean wantSpecialInputThisFrame = false; + private static StringBuilder specialInput = new StringBuilder(); private static int backspaceCount = 0; - private static boolean handledFocusNext = false; - private static boolean focusNext = false; - public static void endFrame() { closeableModalOnTopLast = closeableModalOnTop; - inputIntScrolledLastFrame = inputIntScrolledThisFrame; - inputIntScrolledThisFrame = false; wantSpecialInputLastFrame = wantSpecialInputThisFrame; wantSpecialInputThisFrame = false; - handledFocusNext = false; - focusNext = false; - if (!wantSpecialInputLastFrame) specialInput.setLength(0); } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java index b2aff17..a1dfbd7 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java @@ -4,7 +4,9 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.TextureUtil; import com.mojang.blaze3d.platform.Window; import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.editor.ui.windows.ExportQueueWindow; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.editor.ui.windows.MainMenuBar; import com.moulberry.flashback.editor.ui.windows.StartExportWindow; @@ -21,11 +23,9 @@ import net.minecraft.client.gui.screens.ProgressScreen; import net.minecraft.client.gui.screens.ReceivingLevelScreen; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.ProjectileUtil; import net.minecraft.world.level.ClipContext; @@ -54,10 +54,10 @@ public class ReplayUI { private static boolean initialized = false; private static boolean isFrameHovered = false; - private static int frameX = 0; - private static int frameY = 0; - private static int frameWidth = 1; - private static int frameHeight = 1; + public static int frameX = 0; + public static int frameY = 0; + public static int frameWidth = 1; + public static int frameHeight = 1; private static boolean activeLastFrame = false; public static Matrix4f lastProjectionMatrix = null; @@ -84,7 +84,7 @@ public class ReplayUI { private static boolean popupOpenLastFrame = false; private static String infoOverlayText = null; - private static long infoOverlayStartMillis = 0; + private static long infoOverlayEndMillis = 0; private static int selectedEntity = Integer.MIN_VALUE; private static boolean openSelectedEntityPopup = false; @@ -105,6 +105,14 @@ public class ReplayUI { try { Files.writeString(path, ReplayUIDefaults.LAYOUT); } catch(IOException ignored) {} + } else { + try { + String imguiIni = Files.readString(path); + if (imguiIni.contains("[Window][Timeline]")) { + imguiIni = imguiIni.replace("[Window][Timeline]", "[Window][###Timeline]"); + Files.writeString(path, imguiIni); + } + } catch (IOException ignored) {} } long oldImGuiContext = ImGui.getCurrentContext().ptr; @@ -305,7 +313,12 @@ public class ReplayUI { public static void setInfoOverlay(String text) { infoOverlayText = text; - infoOverlayStartMillis = System.currentTimeMillis(); + infoOverlayEndMillis = System.currentTimeMillis() + 5000; + } + + public synchronized static void setInfoOverlayShort(String text) { + infoOverlayText = text; + infoOverlayEndMillis = System.currentTimeMillis() + 1000; } public static void setupMainViewport() { @@ -382,6 +395,11 @@ public class ReplayUI { return activeLastFrame; } + public static boolean shouldModifyViewport() { + EditorState editorState = EditorStateManager.getCurrent(); + return isActive() && editorState != null && editorState.replayVisuals.sizing != Sizing.UNDERLAY; + } + private static void transitionActiveState(boolean active) { if (activeLastFrame == active) return; activeLastFrame = active; @@ -538,12 +556,15 @@ public class ReplayUI { frameWidth = (int) Math.max(1, maxX - minX); frameHeight = (int) Math.max(1, maxY - minY); - if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO || ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { + EditorState editorState = EditorStateManager.getCurrent(); + Sizing sizing = editorState == null ? Sizing.KEEP_ASPECT_RATIO : editorState.replayVisuals.sizing; + + if (sizing == Sizing.KEEP_ASPECT_RATIO || sizing == Sizing.CHANGE_ASPECT_RATIO) { float aspectRatio; - if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO) { + if (sizing == Sizing.KEEP_ASPECT_RATIO) { aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY(); } else { - aspectRatio = ReplayVisuals.changeAspectRatio.aspectRatio(); + aspectRatio = editorState.replayVisuals.changeAspectRatio.aspectRatio(); } float currentAspectRatio = frameWidth / (float) frameHeight; @@ -561,8 +582,9 @@ public class ReplayUI { if (infoOverlayText != null) { long currentMillis = System.currentTimeMillis(); - if (currentMillis < infoOverlayStartMillis || currentMillis > infoOverlayStartMillis + 5000) { + if (currentMillis < infoOverlayEndMillis - 30000 || currentMillis > infoOverlayEndMillis) { infoOverlayText = null; + infoOverlayEndMillis = 0; } else { ImGui.setNextWindowPos(frameX + frameWidth*0.5f, frameY + frameHeight*0.75f, ImGuiCond.Always, 0.5f, 0.5f); ImGui.setNextWindowSizeConstraints(0, 0, 550, frameHeight*0.45f); @@ -583,7 +605,7 @@ public class ReplayUI { } } - if (ReplayVisuals.sizing == Sizing.UNDERLAY) { + if (sizing == Sizing.UNDERLAY) { frameX = 0; frameY = 0; frameWidth = Minecraft.getInstance().getWindow().getScreenWidth(); @@ -594,27 +616,33 @@ public class ReplayUI { Minecraft.getInstance().resizeDisplay(); } - if (ReplayVisuals.ruleOfThirdsGuide) { - ImDrawList drawList = ImGui.getForegroundDrawList(); - drawList.addLine(frameX + frameWidth/3, frameY, frameX + frameWidth/3, frameY+frameHeight, -1, 2); - drawList.addLine(frameX + frameWidth*2/3, frameY, frameX + frameWidth*2/3, frameY+frameHeight, -1, 2); - drawList.addLine(frameX, frameY + frameHeight/3, frameX + frameWidth, frameY + frameHeight/3, -1, 2); - drawList.addLine(frameX, frameY + frameHeight*2/3, frameX + frameWidth, frameY + frameHeight*2/3, -1, 2); - } + if (Minecraft.getInstance().screen == null && Minecraft.getInstance().getOverlay() == null) { + if (editorState != null && editorState.replayVisuals.ruleOfThirdsGuide) { + ImDrawList drawList = ImGui.getBackgroundDrawList(); + drawList.removeImDrawListFlags(ImDrawListFlags.AntiAliasedLines); + drawList.addLine(frameX + frameWidth/3, frameY, frameX + frameWidth/3, frameY+frameHeight, 0xAAFFFFFF, 2); + drawList.addLine(frameX + frameWidth*2/3, frameY, frameX + frameWidth*2/3, frameY+frameHeight, 0xAAFFFFFF, 2); + drawList.addLine(frameX, frameY + frameHeight/3, frameX + frameWidth, frameY + frameHeight/3, 0xAAFFFFFF, 2); + drawList.addLine(frameX, frameY + frameHeight*2/3, frameX + frameWidth, frameY + frameHeight*2/3, 0xAAFFFFFF, 2); + drawList.addImDrawListFlags(ImDrawListFlags.AntiAliasedLines); + } - if (ReplayVisuals.centerGuide) { - ImDrawList drawList = ImGui.getForegroundDrawList(); - drawList.addLine(frameX + frameWidth/2, frameY, frameX + frameWidth/2, frameY+frameHeight, -1, 2); - drawList.addLine(frameX, frameY + frameHeight/2, frameX + frameWidth, frameY + frameHeight/2, -1, 2); + if (editorState != null && editorState.replayVisuals.centerGuide) { + ImDrawList drawList = ImGui.getBackgroundDrawList(); + drawList.removeImDrawListFlags(ImDrawListFlags.AntiAliasedLines); + drawList.addLine(frameX + frameWidth/2, frameY, frameX + frameWidth/2, frameY+frameHeight, 0xAAFFFFFF, 2); + drawList.addLine(frameX, frameY + frameHeight/2, frameX + frameWidth, frameY + frameHeight/2, 0xAAFFFFFF, 2); + drawList.addImDrawListFlags(ImDrawListFlags.AntiAliasedLines); + } } if (selectedEntity != Integer.MIN_VALUE) { Entity entity = Minecraft.getInstance().level.getEntity(selectedEntity); if (entity == null) { selectedEntity = Integer.MIN_VALUE; - } else if (entity instanceof Player && !ReplayVisuals.renderPlayers) { + } else if (entity instanceof Player && editorState != null && !editorState.replayVisuals.renderPlayers) { selectedEntity = Integer.MIN_VALUE; - } else if (!(entity instanceof Player) && !ReplayVisuals.renderEntities) { + } else if (!(entity instanceof Player) && editorState != null && !editorState.replayVisuals.renderEntities) { selectedEntity = Integer.MIN_VALUE; } else { if (openSelectedEntityPopup) { @@ -629,10 +657,10 @@ public class ReplayUI { if (ImGui.button("Look At")) { Minecraft.getInstance().cameraEntity.lookAt(EntityAnchorArgument.Anchor.EYES, entity.getEyePosition()); } - // todo: need to remember spectate target when a snapshot is played -// if (ImGui.button("Spectate")) { -// Minecraft.getInstance().player.connection.sendUnsignedCommand("spectate " + entity.getUUID()); -// } + if (ImGui.button("Spectate")) { + Minecraft.getInstance().player.connection.sendUnsignedCommand("spectate " + entity.getUUID()); + ImGui.closeCurrentPopup(); + } // ImGui.sameLine(); // ImGui.button("Track Entity"); // @@ -676,7 +704,7 @@ public class ReplayUI { if (wheelY != 0) { final float defaultFlyingSpeed = 0.05f; float flyingSpeed = Mth.clamp(player.getAbilities().getFlyingSpeed() + (float)wheelY * defaultFlyingSpeed / 10f, - defaultFlyingSpeed / 10f, defaultFlyingSpeed * 5.0f); + defaultFlyingSpeed / 10f, defaultFlyingSpeed * 10.0f); setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed)); player.getAbilities().setFlyingSpeed(flyingSpeed); } @@ -693,6 +721,7 @@ public class ReplayUI { VisualsWindow.render(); TimelineWindow.render(); StartExportWindow.render(); + ExportQueueWindow.render(); popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup); @@ -824,7 +853,9 @@ public class ReplayUI { BlockHitResult blockResult = null; EntityHitResult entityResult = null; - if (ReplayVisuals.renderBlocks) { + EditorState editorState = EditorStateManager.getCurrent(); + + if (editorState == null || editorState.replayVisuals.renderBlocks) { ClipContext clipContext = new ClipContext(from, to, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, CollisionContext.empty()); blockResult = Minecraft.getInstance().level.clip(clipContext); @@ -833,16 +864,16 @@ public class ReplayUI { } } - if (ReplayVisuals.renderEntities || ReplayVisuals.renderPlayers) { + if (editorState == null || editorState.replayVisuals.renderEntities || editorState.replayVisuals.renderPlayers) { AABB boundingBox = new AABB(from.subtract(0.5f, 0.5f, 0.5f), from.add(0.5f, 0.5f, 0.5f)); boundingBox = boundingBox.expandTowards(look.scale(distance)); Predicate predicate; - if (ReplayVisuals.renderEntities && ReplayVisuals.renderPlayers) { + if (editorState.replayVisuals.renderEntities && editorState.replayVisuals.renderPlayers) { predicate = entity -> true; - } else if (ReplayVisuals.renderPlayers) { + } else if (editorState.replayVisuals.renderPlayers) { predicate = entity -> entity instanceof Player; - } else if (ReplayVisuals.renderEntities) { + } else if (editorState.replayVisuals.renderEntities) { predicate = entity -> !(entity instanceof Player); } else { throw new IllegalStateException(); diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java index 1792710..5de5d6c 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java @@ -10,18 +10,18 @@ import org.lwjgl.glfw.GLFW; public class ReplayUIDefaults { public static final String LAYOUT = """ - [Window][Timeline] + [Window][###Timeline] Pos=0,830 Size=1920,250 Collapsed=0 DockId=0x00000002,0 - + [Window][Visuals] Pos=1670,0 Size=250,830 Collapsed=0 DockId=0x00000004,0 - + [Docking][Data] DockSpace ID=0x8B93E3BD Window=0xA787BDB4 Pos=0,22 Size=1920,1080 Split=Y Selected=0x1F1A625A DockNode ID=0x00000001 Parent=0x8B93E3BD SizeRef=1920,830 Split=X Selected=0x1F1A625A diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportQueueWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportQueueWindow.java new file mode 100644 index 0000000..af49cfb --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/ExportQueueWindow.java @@ -0,0 +1,91 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.exporting.ExportJob; +import com.moulberry.flashback.exporting.ExportJobQueue; +import com.moulberry.flashback.exporting.ExportSettings; +import imgui.ImGui; +import imgui.flag.ImGuiCol; +import imgui.flag.ImGuiTableColumnFlags; +import imgui.flag.ImGuiTableFlags; +import imgui.flag.ImGuiWindowFlags; + +public class ExportQueueWindow { + + private static boolean open = false; + + public static void open() { + open = true; + } + + public static void render() { + if (open) { + ImGui.openPopup("###ExportQueue"); + open = false; + } + + if (ImGuiHelper.beginPopupModalCloseable("Export Queue###ExportQueue", ImGuiWindowFlags.AlwaysAutoResize)) { + ImGuiHelper.pushStyleColor(ImGuiCol.Border, 0xFF808080); + + boolean canStartJob = !ExportJobQueue.queuedJobs.isEmpty() && Flashback.EXPORT_JOB == null; + boolean canRemoveJob = !ExportJobQueue.queuedJobs.isEmpty(); + + ImGui.text("Jobs"); + if (ImGui.beginChild("##Jobs", 300, 150, true)) { + if (ImGui.beginTable("##JobTable", 3, ImGuiTableFlags.SizingFixedFit)) { + ImGui.tableSetupColumn("Name", ImGuiTableColumnFlags.WidthStretch); + + int startJob = -1; + int removeJob = -1; + + for (int i = 0; i < ExportJobQueue.queuedJobs.size(); i++) { + ExportSettings queuedJob = ExportJobQueue.queuedJobs.get(i); + String name = queuedJob.name() == null ? "Job #" + (i+1) : queuedJob.name(); + + ImGui.tableNextColumn(); + ImGui.text(name); + ImGui.tableNextColumn(); + if (ImGui.smallButton("Start")) { + startJob = i; + } + ImGui.tableNextColumn(); + if (ImGui.smallButton("Remove")) { + removeJob = i; + } + } + + if (startJob >= 0 && canStartJob) { + ExportSettings settings = ExportJobQueue.queuedJobs.remove(startJob); + Flashback.EXPORT_JOB = new ExportJob(settings); + } else if (removeJob >= 0 && canRemoveJob) { + ExportJobQueue.queuedJobs.remove(removeJob); + } + + ImGui.endTable(); + } + ImGui.endChild(); + } + + ImGuiHelper.popStyleColor(); + + + if (!canStartJob) ImGui.beginDisabled(); + if (ImGui.button("Start All") && canStartJob) { + ExportJobQueue.drainingQueue = true; + } + if (!canStartJob) ImGui.endDisabled(); + + ImGui.sameLine(); + + if (!canRemoveJob) ImGui.beginDisabled(); + if (ImGui.button("Remove All") && canRemoveJob) { + ExportJobQueue.queuedJobs.clear(); + } + if (!canRemoveJob) ImGui.endDisabled(); + + ImGuiHelper.endPopupModalCloseable(); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java index d1d82b0..478544f 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java @@ -1,6 +1,8 @@ package com.moulberry.flashback.editor.ui.windows; +import com.moulberry.flashback.exporting.ExportJobQueue; import imgui.ImGui; +import net.minecraft.client.Minecraft; public class MainMenuBar { @@ -10,6 +12,17 @@ public class MainMenuBar { StartExportWindow.open(); } + if (!ExportJobQueue.queuedJobs.isEmpty()) { + String name = "Export Queue (" + ExportJobQueue.count() + ")"; + if (ImGui.menuItem(name + "###QueuedJobs")) { + ExportQueueWindow.open(); + } + } + + if (ImGui.menuItem("Hide (F1)")) { + Minecraft.getInstance().options.hideGui = true; + } + ImGui.endMainMenuBar(); } } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java index 6acdc9c..643a6cb 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java @@ -2,42 +2,56 @@ package com.moulberry.flashback.editor.ui.windows; import com.mojang.blaze3d.platform.Window; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.combo_options.AudioCodec; import com.moulberry.flashback.combo_options.VideoCodec; import com.moulberry.flashback.combo_options.VideoContainer; -import com.moulberry.flashback.combo_options.VideoPreset; +import com.moulberry.flashback.compat.IrisApiWrapper; +import com.moulberry.flashback.exporting.ExportJobQueue; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.exporting.AsyncFileDialogs; import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.exporting.ExportSettings; import com.moulberry.flashback.playback.ReplayServer; import imgui.ImGui; +import imgui.flag.ImGuiPopupFlags; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImFloat; import imgui.type.ImString; import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.api.v0.IrisApi; +import net.minecraft.FileUtil; import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import org.jetbrains.annotations.Nullable; import java.nio.file.Path; -import java.util.List; +import java.util.concurrent.CompletableFuture; public class StartExportWindow { private static boolean open = false; + private static boolean close = false; private static final int[] lastFramebufferSize = new int[]{0, 0}; private static final int[] resolution = new int[]{1920, 1080}; private static final int[] startEndTick = new int[]{0, 100}; private static final ImFloat framerate = new ImFloat(60); + private static boolean resetRng = false; + private static VideoContainer container = VideoContainer.MP4; - private static VideoCodec codec = VideoCodec.H264; - private static VideoPreset preset = VideoPreset.MEDIUM; - private static int[] selectedEncoder = new int[]{0}; + private static VideoCodec videoCodec = VideoCodec.H264; + private static int[] selectedVideoEncoder = new int[]{0}; private static boolean useMaximumBitrate = false; private static final ImString bitrate = ImGuiHelper.createResizableImString("20m"); + private static boolean recordAudio = false; + private static AudioCodec audioCodec = AudioCodec.AAC; + + private static final ImString jobName = ImGuiHelper.createResizableImString(""); + static { bitrate.inputData.allowedChars = "0123456789kmb"; } @@ -60,11 +74,23 @@ public class StartExportWindow { } if (ImGuiHelper.beginPopupModalCloseable("Export to video###StartExport", ImGuiWindowFlags.AlwaysAutoResize)) { + if (close) { + close = false; + ImGui.closeCurrentPopup(); + ImGuiHelper.endPopupModalCloseable(); + return; + } + ImGuiHelper.separatorWithText("Capture Options"); ImGui.inputInt2("Resolution", resolution); + if (resolution[0] < 16) resolution[0] = 16; + if (resolution[1] < 16) resolution[1] = 16; + if (resolution[0] % 2 != 0) resolution[0] += 1; + if (resolution[1] % 2 != 0) resolution[1] += 1; + if (ImGui.inputInt2("Start/end tick", startEndTick)) { - EditorState editorState = EditorStateCache.getCurrent(); + EditorState editorState = EditorStateManager.getCurrent(); ReplayServer replayServer = Flashback.getReplayServer(); if (editorState != null && replayServer != null) { editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks()); @@ -72,6 +98,11 @@ public class StartExportWindow { } ImGui.inputFloat("Framerate", framerate); + if (ImGui.checkbox("Reset RNG", resetRng)) { + resetRng = !resetRng; + } + ImGuiHelper.tooltip("Attempts to remove randomness from the replay in order to produce more consistent outputs when recording the same scene multiple times"); + ImGuiHelper.separatorWithText("Video Options"); VideoContainer newContainer = ImGuiHelper.enumCombo("Container", container); @@ -79,43 +110,29 @@ public class StartExportWindow { container = newContainer; boolean supported = false; - for (VideoCodec supportedCodec : container.getSupportedCodecs()) { - if (codec == supportedCodec) { + for (VideoCodec supportedCodec : container.getSupportedVideoCodecs()) { + if (videoCodec == supportedCodec) { supported = true; break; } } if (!supported) { - codec = container.getSupportedCodecs()[0]; + videoCodec = container.getSupportedVideoCodecs()[0]; } } - VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", codec, container.getSupportedCodecs()); - if (newCodec != codec) { - codec = newCodec; - selectedEncoder[0] = 0; + VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", videoCodec, container.getSupportedVideoCodecs()); + if (newCodec != videoCodec) { + videoCodec = newCodec; + selectedVideoEncoder[0] = 0; } - String[] encoders = codec.getEncoders(); + String[] encoders = videoCodec.getEncoders(); if (encoders.length > 1) { - ImGuiHelper.combo("Encoder", selectedEncoder, encoders); + ImGuiHelper.combo("Encoder", selectedVideoEncoder, encoders); } -// VideoPreset newPreset = ImGuiHelper.enumCombo("Preset", preset); -// if (newPreset != preset) { -// preset = newPreset; -// -// useMaximumBitrate = false; -// if (preset.ordinal() <= VideoPreset.SUPERFAST.ordinal()) { -// bitrate.set("5m"); -// } else if (preset.ordinal() <= VideoPreset.MEDIUM.ordinal()) { -// bitrate.set("10m"); -// } else { -// bitrate.set("20m"); -// } -// } - if (ImGui.checkbox("Use Maximum Bitrate", useMaximumBitrate)) { useMaximumBitrate = !useMaximumBitrate; } @@ -127,43 +144,121 @@ public class StartExportWindow { } } - if (ImGui.button("Begin")) { - int numBitrate; - if (useMaximumBitrate) { - numBitrate = 0; - } else { - numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); + AudioCodec[] supportedAudioCodecs = container.getSupportedAudioCodecs(); + if (supportedAudioCodecs.length > 0) { + ImGuiHelper.separatorWithText("Audio Options"); + + if (ImGui.checkbox("Record Audio", recordAudio)) { + recordAudio = !recordAudio; } - String encoder = codec.getEncoders()[selectedEncoder[0]]; + if (recordAudio) { + AudioCodec newAudioCodec = ImGuiHelper.enumCombo("Audio Codec", audioCodec, supportedAudioCodecs); + if (newAudioCodec != audioCodec) { + audioCodec = newAudioCodec; + } + } + } else { + recordAudio = false; + } - Path defaultExportPath = FabricLoader.getInstance().getGameDir(); - String defaultExportPathString = defaultExportPath.toString(); - AsyncFileDialogs.saveFileDialog(defaultExportPathString, "output." + container.extension(), - container.extension(), container.extension()).thenAccept(pathStr -> { - if (pathStr != null) { - int start = Math.max(0, startEndTick[0]); - int end = Math.max(start, startEndTick[1]); + ImGui.dummy(0, 10); - ReplayServer replayServer = Flashback.getReplayServer(); - if (replayServer != null) { - int totalTicks = replayServer.getTotalReplayTicks(); - start = Math.min(start, totalTicks); - end = Math.min(end, totalTicks); - } - - Path path = Path.of(pathStr); - ExportSettings settings = new ExportSettings(resolution[0], resolution[1], start, end, - Math.max(1, framerate.get()), container, codec, encoder, numBitrate, path); + float buttonSize = (ImGui.getContentRegionAvailX() - ImGui.getStyle().getItemSpacingX()) / 2f; + if (ImGui.button("Start Export", buttonSize, 25)) { + createExportSettings(null).thenAccept(settings -> { + if (settings != null) { + close = true; Flashback.EXPORT_JOB = new ExportJob(settings); } }); + } + ImGui.sameLine(); + if (ImGui.button("Add to Queue", buttonSize, 25)) { + jobName.set("Job #" + (ExportJobQueue.count()+1)); + ImGui.openPopup("QueuedJobName"); + } - ImGui.closeCurrentPopup(); + if (ImGui.beginPopup("QueuedJobName")) { + ImGui.setNextItemWidth(100); + ImGui.inputText("Job Name", jobName); + + if (ImGui.button("Queue Job")) { + createExportSettings(ImGuiHelper.getString(jobName)).thenAccept(settings -> { + if (settings != null) { + close = true; + ExportJobQueue.queuedJobs.add(settings); + } + }); + } + ImGui.sameLine(); + if (ImGui.button("Back")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); } ImGuiHelper.endPopupModalCloseable(); } + + close = false; + } + + private static CompletableFuture createExportSettings(@Nullable String name) { + int numBitrate; + if (useMaximumBitrate) { + numBitrate = 0; + } else { + numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); + } + + String encoder = videoCodec.getEncoders()[selectedVideoEncoder[0]]; + + Path defaultExportPath = FabricLoader.getInstance().getGameDir(); + + String defaultName = null; + if (name != null) { + try { + defaultName = FileUtil.findAvailableName(defaultExportPath, name, "." + container.extension()); + } catch (Exception ignored) {} + } + if (defaultName == null) { + defaultName = "output." + container.extension(); + } + + String defaultExportPathString = defaultExportPath.toString(); + return AsyncFileDialogs.saveFileDialog(defaultExportPathString, defaultName, + container.extension(), container.extension()).thenApply(pathStr -> { + if (pathStr != null) { + int start = Math.max(0, startEndTick[0]); + int end = Math.max(start, startEndTick[1]); + + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null) { + int totalTicks = replayServer.getTotalReplayTicks(); + start = Math.min(start, totalTicks); + end = Math.min(end, totalTicks); + } + + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState == null) { + return null; + } + + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) { + return null; + } + + Path path = Path.of(pathStr); + return new ExportSettings(name, editorState.copy(), + player.position(), player.getYRot(), player.getXRot(), + resolution[0], resolution[1], start, end, + Math.max(1, framerate.get()), resetRng, container, videoCodec, encoder, numBitrate, recordAudio, path); + } + + return null; + }); } private static int stringToBitrate(String string) { @@ -210,7 +305,7 @@ public class StartExportWindow { public static void open() { open = true; - EditorState editorState = EditorStateCache.getCurrent(); + EditorState editorState = EditorStateManager.getCurrent(); if (editorState != null && editorState.exportStartTicks >= 0) { startEndTick[0] = editorState.exportStartTicks; diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java index 68d2302..041dae4 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java @@ -7,7 +7,14 @@ import com.moulberry.flashback.Utils; import com.moulberry.flashback.editor.SavedTrack; import com.moulberry.flashback.editor.SelectedKeyframes; import com.moulberry.flashback.editor.ui.ReplayUI; -import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; +import com.moulberry.flashback.state.EditorStateHistoryAction; +import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; +import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; +import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; +import com.moulberry.flashback.state.EditorStateHistoryEntry; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; @@ -26,18 +33,25 @@ import imgui.flag.ImGuiMouseButton; import imgui.flag.ImGuiMouseCursor; import imgui.flag.ImGuiPopupFlags; import imgui.flag.ImGuiStyleVar; +import imgui.type.ImFloat; +import imgui.type.ImInt; +import imgui.type.ImString; import it.unimi.dsi.fastutil.ints.*; import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import org.joml.Vector2f; +import org.joml.Vector3f; import org.lwjgl.glfw.GLFW; import java.util.*; +import java.util.function.Consumer; public class TimelineWindow { - private static float zoomMinBeforeDrag = 0.0f; - private static float zoomMaxBeforeDrag = 1.0f; + private static double zoomMinBeforeDrag = 0.0f; + private static double zoomMaxBeforeDrag = 1.0f; private static boolean grabbedZoomBar = false; private static boolean grabbedZoomBarResizeLeft = false; private static boolean grabbedZoomBarResizeRight = false; @@ -46,12 +60,30 @@ public class TimelineWindow { private static boolean grabbedPlayback = false; private static boolean grabbedKeyframe = false; private static float grabbedKeyframeMouseX = 0; + private static boolean enableKeyframeMovement = false; + private static int grabbedKeyframeTick = 0; + private static int grabbedKeyframeTrack = 0; @Nullable private static Vector2f dragSelectOrigin = null; + private static final float[] fovKeyframeInput = new float[]{70.0f}; private static final float[] speedKeyframeInput = new float[]{1.0f}; - private static final int[] timeOfDayKeyframeInput = new int[]{6000}; + private static final ImInt timeOfDayKeyframeInput = new ImInt(6000); + private static boolean cameraShakeSplitXYKeyframeInput = false; + private static final float[] cameraShakeFrequencyXKeyframeInput = new float[]{1.0f}; + private static final float[] cameraShakeAmplitudeXKeyframeInput = new float[]{0.0f}; + private static final float[] cameraShakeFrequencyYKeyframeInput = new float[]{1.0f}; + private static final float[] cameraShakeAmplitudeYKeyframeInput = new float[]{0.0f}; + private static final ImString timelapseKeyframeInput = ImGuiHelper.createResizableImString("0s"); + static { + timelapseKeyframeInput.inputData.allowedChars = "0123456789tsmh"; + } + + private static final float[] cameraOrbitCenter = new float[]{0.0f, 0.0f, 0.0f}; + private static final ImFloat cameraOrbitDistance = new ImFloat(8.0f); + private static final ImFloat cameraOrbitYaw = new ImFloat(0.0f); + private static final ImFloat cameraOrbitPitch = new ImFloat(0.0f); private static float mouseX; private static float mouseY; @@ -64,6 +96,9 @@ public class TimelineWindow { private static float width; private static float height; + private static int pendingStepBackwardsTicks = 0; + private static int cursorTicks; + private static boolean hoveredControls; private static boolean hoveredSkipBackwards; private static boolean hoveredSlowDown; @@ -84,25 +119,35 @@ public class TimelineWindow { private static final int middleX = 240; private static final List selectedKeyframesList = new ArrayList<>(); - private static Keyframe editingKeyframe = null; + private static int editingKeyframeTrack = 0; + private static int editingKeyframeTick = 0; private static final float[] replayTickSpeeds = new float[]{1.0f, 2.0f, 4.0f, 10.0f, 20.0f, 40.0f, 100.0f, 200.0f, 400.0f}; private static final int KEYFRAME_SIZE = 10; + public static int getCursorTick() { + return cursorTicks; + } + public static void render() { ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer == null) { return; } + + String timestamp = ticksToTimestamp(cursorTicks); + ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); - boolean timelineVisible = ImGui.begin("Timeline"); + boolean timelineVisible = ImGui.begin("Timeline (" + timestamp + "/" + cursorTicks + ")###Timeline"); ImGuiHelper.popStyleVar(); + cursorTicks = replayServer.getReplayTick(); + if (timelineVisible) { FlashbackMeta metadata = replayServer.getMetadata(); - EditorState editorState = EditorStateCache.get(metadata.replayIdentifier); + EditorState editorState = EditorStateManager.get(metadata.replayIdentifier); ImDrawList drawList = ImGui.getWindowDrawList(); @@ -123,6 +168,18 @@ public class TimelineWindow { selectedKeyframesList.removeIf(k -> !k.checkValid(editorState)); + if (editingKeyframeTrack >= 0 && editingKeyframeTick >= 0) { + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + if (selectedKeyframes.trackIndex() == editingKeyframeTrack) { + if (!selectedKeyframes.keyframeTicks().contains(editingKeyframeTick)) { + editingKeyframeTrack = -1; + editingKeyframeTick = -1; + } + break; + } + } + } + mouseX = ImGui.getMousePosX(); mouseY = ImGui.getMousePosY(); @@ -153,31 +210,68 @@ public class TimelineWindow { } int majorSnap = ticksPerMinor * minorsPerMajor; - minTicks = Math.round(editorState.zoomMin * totalTicks / majorSnap) * majorSnap; + minTicks = (int) Math.round(editorState.zoomMin * totalTicks / majorSnap) * majorSnap; float minorSeparatorWidth = (timelineWidth / shownTicks) * ticksPerMinor; availableTicks = timelineWidth / minorSeparatorWidth * ticksPerMinor; - float errorTicks = editorState.zoomMin*totalTicks - minTicks; + double errorTicks = editorState.zoomMin*totalTicks - minTicks; int errorOffset = (int)(-errorTicks/ticksPerMinor*minorSeparatorWidth); timelineOffset = middleX + errorOffset; - int cursorTicks = currentReplayTick; + cursorTicks = currentReplayTick; if (grabbedPlayback) { cursorTicks = timelineXToReplayTick(mouseX); } else if (replayServer.jumpToTick >= 0) { cursorTicks = replayServer.jumpToTick; + } else if (pendingStepBackwardsTicks > 0) { + cursorTicks = Math.max(0, cursorTicks - pendingStepBackwardsTicks); + } + + if (grabbedPlayback && !editorState.keyframeTracks.isEmpty()) { + boolean isCtrlDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_CONTROL); + boolean isShiftDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT); + + if (isShiftDown) { + int closestTick = -1; + for (KeyframeTrack track : editorState.keyframeTracks) { + Integer floor = track.keyframesByTick.floorKey(cursorTicks); + Integer ceil = track.keyframesByTick.ceilingKey(cursorTicks); + + float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor); + float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil); + + Integer closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE); + if (closest != null) { + if (closestTick == -1) { + closestTick = closest; + } else if (Math.abs(closest - cursorTicks) < Math.abs(closestTick - cursorTicks)) { + closestTick = closest; + } + } + } + if (closestTick != -1) { + cursorTicks = closestTick; + } + } + if (isCtrlDown) { + editorState.applyKeyframes(new MinecraftKeyframeHandler(Minecraft.getInstance()), cursorTicks); + } + if (!isCtrlDown && !isShiftDown) { + ImGuiHelper.drawTooltip("Hold CTRL to apply keyframes"); + ImGuiHelper.drawTooltip("Hold SHIFT to snap to keyframes"); + } } int cursorX = replayTickToTimelineX(cursorTicks); zoomBarHeight = 6; float zoomBarWidth = width - (middleX+1); - zoomBarMin = x + middleX+1 + editorState.zoomMin * zoomBarWidth; - zoomBarMax = x + middleX+1 + editorState.zoomMax * zoomBarWidth; + zoomBarMin = (float)(x + middleX+1 + editorState.zoomMin * zoomBarWidth); + zoomBarMax = (float)(x + middleX+1 + editorState.zoomMax * zoomBarWidth); zoomBarExpanded = false; - if (mouseY >= y + height - zoomBarHeight *2 && mouseY <= y + height || grabbedZoomBar) { + if (mouseY >= y + height - zoomBarHeight*2 && mouseY <= y + height || grabbedZoomBar) { zoomBarHeight *= 2; zoomBarExpanded = true; } @@ -295,33 +389,61 @@ public class TimelineWindow { hoveredFastForwards = hoveredControls && mouseX >= fastForwardsX && mouseX <= fastForwardsX+controlSize; hoveredSkipForwards = hoveredControls && mouseX >= skipForwardsX && mouseX <= skipForwardsX+controlSize; - if (hoveredSkipBackwards) { - ImGuiHelper.drawTooltip("Skip backwards"); - } else if (hoveredSlowDown) { - ImGuiHelper.drawTooltip("Slow down\n(Current speed: " + (replayServer.desiredTickRate/20f) + "x)"); - } else if (hoveredPause) { - if (replayServer.replayPaused) { - ImGuiHelper.drawTooltip("Start replay"); - } else { - ImGuiHelper.drawTooltip("Pause replay"); + float currentTickRate = replayServer.getDesiredTickRate(true); + + if (!grabbedPlayback) { + if (hoveredSkipBackwards) { + ImGuiHelper.drawTooltip("Skip backwards"); + } else if (hoveredSlowDown) { + ImGuiHelper.drawTooltip("Slow down\n(Current speed: " + (currentTickRate/20f) + "x)"); + } else if (hoveredPause) { + if (replayServer.replayPaused) { + ImGuiHelper.drawTooltip("Start replay"); + } else { + ImGuiHelper.drawTooltip("Pause replay"); + } + } else if (hoveredFastForwards) { + ImGuiHelper.drawTooltip("Fast-forwards\n(Current speed: " + (currentTickRate/20f) + "x)"); + } else if (hoveredSkipForwards) { + ImGuiHelper.drawTooltip("Skip forwards"); } - } else if (hoveredFastForwards) { - ImGuiHelper.drawTooltip("Fast-forwards\n(Current speed: " + (replayServer.desiredTickRate/20f) + "x)"); - } else if (hoveredSkipForwards) { - ImGuiHelper.drawTooltip("Skip forwards"); } if (ImGui.beginPopup("##KeyframePopup")) { renderKeyframeOptionsPopup(editorState); ImGui.endPopup(); + } else { + editingKeyframeTrack = -1; + editingKeyframeTick = -1; } - handleKeyPresses(cursorTicks, editorState, totalTicks); + if (mouseX > x + middleX && mouseX < x + width && mouseY > y + middleY && mouseY < y + height) { + int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel()); + + double mousePercentage = (mouseX - (x + middleX)) / (width - middleX); + + if (scroll > 0) { + double zoomDelta = editorState.zoomMax - editorState.zoomMin; + if (zoomDelta > 0.001) { + editorState.zoomMin += zoomDelta * 0.05 * mousePercentage; + editorState.zoomMax -= zoomDelta * 0.05 * (1 - mousePercentage); + editorState.markDirty(); + } + } else if (scroll < 0) { + double zoomDelta = editorState.zoomMax - editorState.zoomMin; + + editorState.zoomMin = Math.max(0, editorState.zoomMin - zoomDelta * 0.05/0.9 * mousePercentage); + editorState.zoomMax = Math.min(1, editorState.zoomMax + zoomDelta * 0.05/0.9 * (1 - mousePercentage)); + editorState.markDirty(); + } + } + + handleKeyPresses(replayServer, cursorTicks, editorState, totalTicks); boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); if ((leftClicked || rightClicked) && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { - handleClick(editorState, replayServer); + handleClick(editorState, replayServer, totalTicks); } else if (ImGui.isMouseDragging(ImGuiMouseButton.Left)) { if (grabbedExportBarResizeLeft) { ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); @@ -348,7 +470,7 @@ public class TimelineWindow { } else { ImGui.setMouseCursor(ImGuiMouseCursor.Hand); - float zoomSize = zoomMaxBeforeDrag - zoomMinBeforeDrag; + double zoomSize = zoomMaxBeforeDrag - zoomMinBeforeDrag; if (factor < 0) { editorState.zoomMin = Math.max(0, zoomMinBeforeDrag + factor); editorState.zoomMax = editorState.zoomMin + zoomSize; @@ -357,7 +479,7 @@ public class TimelineWindow { editorState.zoomMin = editorState.zoomMax - zoomSize; } } - editorState.dirty = true; + editorState.markDirty(); } if (grabbedPlayback) { int desiredTick = timelineXToReplayTick(mouseX); @@ -369,32 +491,92 @@ public class TimelineWindow { replayServer.replayPaused = true; } } else if (!ImGui.isAnyMouseDown()) { - releaseGrabbed(editorState, replayServer); + releaseGrabbed(editorState, replayServer, totalTicks); } } ImGui.end(); } - private static void handleKeyPresses(int cursorTicks, EditorState editorState, int totalTicks) { + private static void handleKeyPresses(ReplayServer replayServer, int cursorTicks, EditorState editorState, int totalTicks) { boolean pressedIn = ImGui.isKeyPressed(GLFW.GLFW_KEY_I, false); - boolean pressedOut = ImGui.isKeyPressed(GLFW.GLFW_KEY_I, false); + boolean pressedOut = ImGui.isKeyPressed(GLFW.GLFW_KEY_O, false); boolean ctrlPressed = Minecraft.ON_OSX ? ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SUPER) : ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL); boolean pressedCopy = ctrlPressed && ImGui.isKeyPressed(GLFW.GLFW_KEY_C, false); boolean pressedPaste = ctrlPressed && ImGui.isKeyPressed(GLFW.GLFW_KEY_V, false); + boolean pressedDelete = ImGui.isKeyPressed(GLFW.GLFW_KEY_DELETE) || ImGui.isKeyPressed(GLFW.GLFW_KEY_BACKSPACE); + + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT)) { + pendingStepBackwardsTicks += 1; + } else if (pendingStepBackwardsTicks > 0 && !ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT)) { + replayServer.goToReplayTick(Math.max(0, replayServer.getReplayTick() - pendingStepBackwardsTicks)); + replayServer.forceApplyKeyframes.set(true); + pendingStepBackwardsTicks = 0; + } + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_RIGHT)) { + replayServer.goToReplayTick(Math.min(totalTicks, cursorTicks + 1)); + replayServer.forceApplyKeyframes.set(true); + } + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_UP)) { + int nextKeyframeTick; + if (editorState.exportStartTicks >= 0 && editorState.exportStartTicks > cursorTicks) { + nextKeyframeTick = editorState.exportStartTicks; + } else if (editorState.exportEndTicks >= 0 && editorState.exportEndTicks > cursorTicks) { + nextKeyframeTick = editorState.exportEndTicks; + } else { + nextKeyframeTick = totalTicks; + } + for (KeyframeTrack track : editorState.keyframeTracks) { + Integer ceilingKey = track.keyframesByTick.ceilingKey(cursorTicks+1); + if (ceilingKey != null && ceilingKey < nextKeyframeTick) { + nextKeyframeTick = ceilingKey; + } + } + replayServer.goToReplayTick(nextKeyframeTick); + replayServer.forceApplyKeyframes.set(true); + } + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_DOWN)) { + int previousKeyframeTick; + if (editorState.exportEndTicks >= 0 && editorState.exportEndTicks < cursorTicks) { + previousKeyframeTick = editorState.exportEndTicks; + } else if (editorState.exportStartTicks >= 0 && editorState.exportStartTicks < cursorTicks) { + previousKeyframeTick = editorState.exportStartTicks; + } else { + previousKeyframeTick = 0; + } + for (KeyframeTrack track : editorState.keyframeTracks) { + Integer floorKey = track.keyframesByTick.floorKey(cursorTicks-1); + if (floorKey != null && floorKey > previousKeyframeTick) { + previousKeyframeTick = floorKey; + } + } + replayServer.goToReplayTick(previousKeyframeTick); + replayServer.forceApplyKeyframes.set(true); + } + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_Z) && (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_CONTROL))) { + editorState.undo(ReplayUI::setInfoOverlayShort); + } + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_Y) && (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_CONTROL) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_CONTROL))) { + editorState.redo(ReplayUI::setInfoOverlayShort); + } + if (pressedIn || pressedOut) { int start = -1; int end = -1; - if (ImGui.isKeyPressed(GLFW.GLFW_KEY_I)) { + if (pressedIn) { start = cursorTicks; } - if (ImGui.isKeyPressed(GLFW.GLFW_KEY_O)) { + if (pressedOut) { end = cursorTicks; } editorState.setExportTicks(start, end, totalTicks); } + if (pressedDelete && !selectedKeyframesList.isEmpty()) { + removeAllSelectedKeyframes(editorState); + } + if (pressedCopy && !selectedKeyframesList.isEmpty()) { List tracks = new ArrayList<>(); @@ -411,9 +593,9 @@ public class TimelineWindow { for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); - TreeMap> keyframes = new TreeMap<>(); + TreeMap keyframes = new TreeMap<>(); for (int tick : selectedKeyframes.keyframeTicks()) { - Keyframe keyframe = keyframeTrack.keyframesByTick.get(tick); + Keyframe keyframe = keyframeTrack.keyframesByTick.get(tick); keyframes.put(tick - minTick, keyframe); } @@ -446,8 +628,28 @@ public class TimelineWindow { } } - private static void handleClick(EditorState editorState, ReplayServer replayServer) { - releaseGrabbed(editorState, replayServer); + private static void removeAllSelectedKeyframes(EditorState editorState) { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + for (int tick : selectedKeyframes.keyframeTicks()) { + Keyframe keyframe = track.keyframesByTick.get(tick); + + undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + redo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick)); + } + } + + selectedKeyframesList.clear(); + editingKeyframeTrack = -1; + editingKeyframeTick = -1; + editorState.push(new EditorStateHistoryEntry(undo, redo, "Deleted " + undo.size() + " keyframe(s)")); + } + + private static void handleClick(EditorState editorState, ReplayServer replayServer, int totalTicks) { + releaseGrabbed(editorState, replayServer, totalTicks); List oldSelectedKeyframesList = new ArrayList<>(selectedKeyframesList); selectedKeyframesList.clear(); @@ -464,7 +666,7 @@ public class TimelineWindow { // Slow down if (hoveredSlowDown) { float highest = replayTickSpeeds[0]; - float currentTickRate = replayServer.desiredTickRate; + float currentTickRate = replayServer.getDesiredTickRate(true); for (float replayTickSpeed : replayTickSpeeds) { if (replayTickSpeed >= currentTickRate) { @@ -473,7 +675,7 @@ public class TimelineWindow { highest = replayTickSpeed; } - replayServer.desiredTickRate = highest; + replayServer.setDesiredTickRate(highest, true); return; } @@ -486,7 +688,7 @@ public class TimelineWindow { // Fast-forward if (hoveredFastForwards) { float lowest = replayTickSpeeds[replayTickSpeeds.length - 1]; - float currentTickRate = replayServer.desiredTickRate; + float currentTickRate = replayServer.getDesiredTickRate(true); for (int i = replayTickSpeeds.length - 1; i >= 0; i--) { float replayTickSpeed = replayTickSpeeds[i]; @@ -496,7 +698,7 @@ public class TimelineWindow { lowest = replayTickSpeed; } - replayServer.desiredTickRate = lowest; + replayServer.setDesiredTickRate(lowest, true); return; } @@ -541,7 +743,7 @@ public class TimelineWindow { zoomMaxBeforeDrag = editorState.zoomMax; return; } else if (zoomBarExpanded && mouseX >= x + middleX && mouseX <= x + width) { - float zoomSize = editorState.zoomMax - editorState.zoomMin; + double zoomSize = editorState.zoomMax - editorState.zoomMin; float targetZoom = (mouseX - (x + middleX))/(x + width - (x + middleX)); editorState.zoomMin = targetZoom - zoomSize/2f; editorState.zoomMax = targetZoom + zoomSize/2f; @@ -552,7 +754,7 @@ public class TimelineWindow { editorState.zoomMin = 0.0f; editorState.zoomMax = editorState.zoomMin + zoomSize; } - editorState.dirty = true; + editorState.markDirty(); grabbedZoomBar = leftClicked; zoomMinBeforeDrag = editorState.zoomMin; @@ -571,13 +773,13 @@ public class TimelineWindow { int tick = timelineXToReplayTick(mouseX); - Map.Entry> floor = keyframeTrack.keyframesByTick.floorEntry(tick); - Map.Entry> ceil = keyframeTrack.keyframesByTick.ceilingEntry(tick); + Map.Entry floor = keyframeTrack.keyframesByTick.floorEntry(tick); + Map.Entry ceil = keyframeTrack.keyframesByTick.ceilingEntry(tick); float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor.getKey()); float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil.getKey()); - Map.Entry> closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE); + Map.Entry closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE); if (closest != null) { boolean reuseOld = false; for (SelectedKeyframes selectedKeyframes : oldSelectedKeyframesList) { @@ -598,9 +800,14 @@ public class TimelineWindow { if (leftClicked) { grabbedKeyframe = true; grabbedKeyframeMouseX = mouseX; + grabbedKeyframeTick = closest.getKey(); + grabbedKeyframeTrack = trackIndex; + enableKeyframeMovement = false; } else if (rightClicked) { ImGui.openPopup("##KeyframePopup"); - editingKeyframe = closest.getValue(); + editingKeyframeTrack = trackIndex; + editingKeyframeTick = closest.getKey(); + grabbedKeyframeTrack = trackIndex; } return; @@ -628,49 +835,117 @@ public class TimelineWindow { } private static void renderKeyframeOptionsPopup(EditorState editorState) { + if (editingKeyframeTrack < 0 || editingKeyframeTick < 0) { + return; + } + + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(editingKeyframeTrack); + Keyframe editingKeyframe = keyframeTrack.keyframesByTick.get(editingKeyframeTick); + if (editingKeyframe == null || selectedKeyframesList.isEmpty()) { - editingKeyframe = null; + editingKeyframeTrack = -1; ImGui.closeCurrentPopup(); return; } - int[] type = new int[]{editingKeyframe.interpolationType().ordinal()}; - ImGui.setNextItemWidth(160); - if (ImGuiHelper.combo("Type", type, InterpolationType.NAMES)) { - InterpolationType interpolationType = InterpolationType.INTERPOLATION_TYPES[type[0]]; + editingKeyframe.renderEditKeyframe(updateFunction -> { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); - editingKeyframe.interpolationType(interpolationType); + int modified = 0; for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); for (int tick : selectedKeyframes.keyframeTicks()) { - track.keyframesByTick.get(tick).interpolationType(interpolationType); + Keyframe keyframe = track.keyframesByTick.get(tick); + if (keyframe.getClass() == editingKeyframe.getClass()) { + modified += 1; + + undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + updateFunction.accept(keyframe); + redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + } } } - editorState.dirty = true; + if (modified > 0) { + editorState.push(new EditorStateHistoryEntry(undo, redo, "Modified " + modified + " keyframe(s)")); + } + }); + + if (!(editingKeyframe instanceof TimelapseKeyframe)) { + int[] type = new int[]{editingKeyframe.interpolationType().ordinal()}; + ImGui.setNextItemWidth(160); + if (ImGuiHelper.combo("Type", type, InterpolationType.NAMES)) { + InterpolationType interpolationType = InterpolationType.INTERPOLATION_TYPES[type[0]]; + + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + for (int tick : selectedKeyframes.keyframeTicks()) { + Keyframe keyframe = track.keyframesByTick.get(tick); + + if (keyframe.interpolationType() != interpolationType) { + Keyframe changed = keyframe.copy(); + changed.interpolationType(interpolationType); + + undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, keyframe.copy())); + redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), tick, changed)); + } + } + } + + editorState.push(new EditorStateHistoryEntry(undo, redo, "Changed interpolation type to " + interpolationType)); + } + } + + ImInt intWrapper = new ImInt(editingKeyframeTick); + ImGui.setNextItemWidth(160); + ImGui.inputInt("Tick", intWrapper, 0); + int newEditingKeyframeTick = intWrapper.get(); + + if (ImGui.isItemDeactivatedAfterEdit() && newEditingKeyframeTick != editingKeyframeTick) { + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + + Keyframe possibleKeyframe = track.keyframesByTick.get(editingKeyframeTick); + if (possibleKeyframe == editingKeyframe) { + List undo = List.of( + new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), newEditingKeyframeTick), + new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), editingKeyframeTick, editingKeyframe.copy()) + ); + List redo = List.of( + new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), editingKeyframeTick), + new EditorStateHistoryAction.SetKeyframe(track.keyframeType, selectedKeyframes.trackIndex(), newEditingKeyframeTick, editingKeyframe.copy()) + ); + + editorState.push(new EditorStateHistoryEntry(undo, redo, "Moved 1 keyframe(s)")); + selectedKeyframes.keyframeTicks().remove(editingKeyframeTick); + selectedKeyframes.keyframeTicks().add(newEditingKeyframeTick); + editingKeyframeTick = newEditingKeyframeTick; + return; + } + } } boolean multiple = selectedKeyframesList.size() >= 2 || selectedKeyframesList.getFirst().keyframeTicks().size() >= 2; if (ImGui.button(multiple ? "Remove All" : "Remove")) { ImGui.closeCurrentPopup(); + removeAllSelectedKeyframes(editorState); + } - for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); - for (int tick : selectedKeyframes.keyframeTicks()) { - track.keyframesByTick.remove(tick); - } + if (!multiple && editingKeyframe instanceof CameraKeyframe cameraKeyframe) { + ImGui.sameLine(); + if (ImGui.button("Apply")) { + cameraKeyframe.apply(new MinecraftKeyframeHandler(Minecraft.getInstance())); } - editorState.keyframeTracks.removeIf(track -> track.keyframesByTick.isEmpty()); - - selectedKeyframesList.clear(); - editingKeyframe = null; - editorState.dirty = true; } } - private static void releaseGrabbed(EditorState editorState, ReplayServer replayServer) { + private static void releaseGrabbed(EditorState editorState, ReplayServer replayServer, int totalTicks) { grabbedZoomBar = false; grabbedZoomBarResizeLeft = false; grabbedZoomBarResizeRight = false; @@ -722,58 +997,183 @@ public class TimelineWindow { } if (grabbedKeyframe) { - int grabbedDelta = timelineDeltaToReplayTickDelta(mouseX - grabbedKeyframeMouseX); - int totalTicks = replayServer.getTotalReplayTicks(); + GrabMovementInfo grabMovementInfo = calculateGrabMovementInfo(editorState, totalTicks); - for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { - int trackIndex = selectedKeyframes.trackIndex(); - KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + if (grabMovementInfo.grabbedScalePivotTick >= 0 || grabMovementInfo.grabbedDelta != 0) { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + int movedKeyframes = 0; - IntList selectedTicks = new IntArrayList(selectedKeyframes.keyframeTicks()); + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + int trackIndex = selectedKeyframes.trackIndex(); + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); - // Sorting because clamping can result in overlaps - selectedTicks.sort(mouseX < grabbedKeyframeMouseX ? IntComparators.NATURAL_COMPARATOR : IntComparators.OPPOSITE_COMPARATOR); + IntList selectedTicks = new IntArrayList(selectedKeyframes.keyframeTicks()); - selectedKeyframes.keyframeTicks().clear(); + // Sorting because clamping can result in overlaps + selectedTicks.sort(mouseX < grabbedKeyframeMouseX ? IntComparators.NATURAL_COMPARATOR : IntComparators.OPPOSITE_COMPARATOR); - Int2ObjectMap> newKeyframes = new Int2ObjectOpenHashMap<>(); + selectedKeyframes.keyframeTicks().clear(); - for (int i = 0; i < selectedTicks.size(); i++) { - int tick = selectedTicks.getInt(i); + Int2ObjectMap removeFromTick = new Int2ObjectOpenHashMap<>(); + Int2ObjectMap addToTick = new Int2ObjectOpenHashMap<>(); - Keyframe keyframe = keyframeTrack.keyframesByTick.remove(tick); - Objects.requireNonNull(keyframe); + for (int i = 0; i < selectedTicks.size(); i++) { + int tick = selectedTicks.getInt(i); - int newTick = tick + grabbedDelta; - newTick = Math.max(0, Math.min(totalTicks, newTick)); + Keyframe keyframe = keyframeTrack.keyframesByTick.get(tick); + if (keyframe == null) { + continue; + } - newKeyframes.put(newTick, keyframe); - } + int newTick = tick + grabMovementInfo.grabbedDelta; - for (Int2ObjectMap.Entry> entry : newKeyframes.int2ObjectEntrySet()) { - keyframeTrack.keyframesByTick.put(entry.getIntKey(), entry.getValue()); - selectedKeyframes.keyframeTicks().add(entry.getIntKey()); + if (grabMovementInfo.grabbedScalePivotTick >= 0) { + int tickDelta = tick - grabMovementInfo.grabbedScalePivotTick; + newTick = grabMovementInfo.grabbedScalePivotTick + Math.round(tickDelta * grabMovementInfo.grabbedScaleFactor); + } + + newTick = Math.max(0, Math.min(totalTicks, newTick)); + + if (tick != newTick) { + Keyframe copied = keyframe.copy(); + + removeFromTick.put(tick, copied); + addToTick.put(newTick, copied); + +// undo.add(new EditorStateHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, newTick)); +// undoAdd.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, tick, copied)); +// +// redo.add(new EditorStateHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, tick)); +// redoAdd.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, newTick, copied)); + + movedKeyframes += 1; + } + + selectedKeyframes.keyframeTicks().add(newTick); + } + + for (int removeTick : removeFromTick.keySet()) { + if (!addToTick.containsKey(removeTick)) { + redo.add(new EditorStateHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, removeTick)); + } + } + for (Int2ObjectMap.Entry entry : addToTick.int2ObjectEntrySet()) { + redo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), entry.getValue())); + + if (!removeFromTick.containsKey(entry.getIntKey())) { + Keyframe existing = keyframeTrack.keyframesByTick.get(entry.getIntKey()); + if (existing != null) { + undo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), existing.copy())); + } else { + undo.add(new EditorStateHistoryAction.RemoveKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey())); + } + } + } + for (Int2ObjectMap.Entry entry : removeFromTick.int2ObjectEntrySet()) { + undo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, trackIndex, entry.getIntKey(), entry.getValue())); + } } + editorState.push(new EditorStateHistoryEntry(undo, redo, "Moved " + movedKeyframes + " keyframe(s)")); } -// if (selectedKeyframe != null) { -// int desiredTick = timelineXToReplayTick(mouseX - selectedKeyframe.mouseClickOffset); -// if (desiredTick != selectedKeyframe.keyframeTick) { -// KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(selectedKeyframe.trackIndex()); -// -// -// -// -// selectedKeyframe = new SelectedKeyframe(selectedKeyframe.type(), selectedKeyframe.trackIndex(), desiredTick, 0); -// -// editorState.dirty = true; -// } -// } grabbedKeyframe = false; } } + record GrabMovementInfo(int grabbedDelta, int grabbedScalePivotTick, float grabbedScaleFactor) {} + + private static GrabMovementInfo calculateGrabMovementInfo(EditorState editorState, int totalTicks) { + int grabbedDelta = 0; + int grabbedScalePivotTick = -1; + float grabbedScaleFactor = 0f; + + if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_ALT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_ALT)) { + int minTick = totalTicks; + int maxTick = 0; + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + IntIterator iterator = selectedKeyframes.keyframeTicks().iterator(); + while (iterator.hasNext()) { + int tick = iterator.nextInt(); + minTick = Math.min(minTick, tick); + maxTick = Math.max(maxTick, tick); + } + } + + if (minTick == maxTick) { + ImGuiHelper.drawTooltip("Scale: 100%"); + } else { + if (minTick == grabbedKeyframeTick || minTick == timelineXToReplayTick(grabbedKeyframeMouseX - x)) { + grabbedScalePivotTick = maxTick; + } else { + grabbedScalePivotTick = minTick; + } + + float pivotMouseX = x + replayTickToTimelineX(grabbedScalePivotTick); + grabbedScaleFactor = (mouseX - pivotMouseX) / (grabbedKeyframeMouseX - pivotMouseX); + + if (!Float.isFinite(grabbedScaleFactor)) { + grabbedScaleFactor = 1f; + } + + ImGuiHelper.drawTooltip("Scale: " + Math.round(grabbedScaleFactor*100) + "%"); + } + + return new GrabMovementInfo(0, grabbedScalePivotTick, grabbedScaleFactor); + } else if (grabbedKeyframeMouseX != mouseX || enableKeyframeMovement) { + enableKeyframeMovement = true; + grabbedDelta = timelineDeltaToReplayTickDelta(mouseX - grabbedKeyframeMouseX); + + boolean isShiftDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT); + + if (isShiftDown) { + int closestTick = -1; + for (int i = 0; i < editorState.keyframeTracks.size(); i++) { + if (i == grabbedKeyframeTrack) { + continue; + } + + KeyframeTrack track = editorState.keyframeTracks.get(i); + + Integer floor = track.keyframesByTick.floorKey(grabbedKeyframeTick); + Integer ceil = track.keyframesByTick.ceilingKey(grabbedKeyframeTick); + + float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor); + float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil); + + Integer closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE); + if (closest != null) { + if (closestTick == -1) { + closestTick = closest; + } else if (Math.abs(closest - grabbedKeyframeTick) < Math.abs(closestTick - grabbedKeyframeTick)) { + closestTick = closest; + } + } + } + if (closestTick != -1) { + grabbedDelta = closestTick - grabbedKeyframeTick; + } + } + + String tooltip = "Tick: " + (grabbedKeyframeTick + grabbedDelta); + + if (grabbedDelta >= 0) { + tooltip += " (+" + grabbedDelta + " ticks)"; + } else { + tooltip += " (" + grabbedDelta + " ticks)"; + } + + if (!isShiftDown && editorState.keyframeTracks.size() > 1) { + tooltip += "\nHold SHIFT to snap"; + } + + ImGuiHelper.drawTooltip(tooltip); + } + + return new GrabMovementInfo(grabbedDelta, grabbedScalePivotTick, grabbedScaleFactor); + } private static void renderKeyframes(EditorState editorState, float x, float y, float mouseX, int minTicks, float availableTicks, int totalTicks) { float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); @@ -783,21 +1183,15 @@ public class TimelineWindow { foregroundDrawList.pushClipRect(x + middleX, y, x + width, y + height); - int grabbedDelta = 0; + GrabMovementInfo grabMovementInfo = null; if (grabbedKeyframe) { - grabbedDelta = timelineDeltaToReplayTickDelta(mouseX - grabbedKeyframeMouseX); - - if (grabbedDelta > 0) { - ImGuiHelper.drawTooltip("+" + grabbedDelta + " ticks"); - } else if (grabbedDelta < 0) { - ImGuiHelper.drawTooltip(grabbedDelta + " ticks"); - } + grabMovementInfo = calculateGrabMovementInfo(editorState, totalTicks); } for (int trackIndex = 0; trackIndex < editorState.keyframeTracks.size(); trackIndex++) { KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); - TreeMap> keyframeTimes = keyframeTrack.keyframesByTick; + TreeMap keyframeTimes = keyframeTrack.keyframesByTick; SelectedKeyframes selectedKeyframesForTrack = null; for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { @@ -814,11 +1208,21 @@ public class TimelineWindow { } tick = entry.getKey(); - Keyframe keyframe = entry.getValue(); + Keyframe keyframe = entry.getValue(); if (selectedKeyframesForTrack != null && selectedKeyframesForTrack.keyframeTicks().contains(tick)) { - int newTick = tick + grabbedDelta; - newTick = Math.max(0, Math.min(totalTicks, newTick)); + int newTick = tick; + + if (grabMovementInfo != null) { + newTick = tick + grabMovementInfo.grabbedDelta; + + if (grabMovementInfo.grabbedScalePivotTick >= 0) { + int tickDelta = tick - grabMovementInfo.grabbedScalePivotTick; + newTick = grabMovementInfo.grabbedScalePivotTick + Math.round(tickDelta * grabMovementInfo.grabbedScaleFactor); + } + + newTick = Math.max(0, Math.min(totalTicks, newTick)); + } int keyframeX = replayTickToTimelineX(newTick); @@ -894,12 +1298,9 @@ public class TimelineWindow { float buttonSize = ImGui.getTextLineHeight(); float spacingX = ImGui.getStyle().getItemSpacingX(); - for (int trackIndex = 0; trackIndex < editorState.keyframeTracks.size(); trackIndex++) { KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); - KeyframeType keyframeType = keyframeTrack.keyframeType; - TreeMap> keyframeTimes = keyframeTrack.keyframesByTick; ImGui.pushID(trackIndex); @@ -917,22 +1318,62 @@ public class TimelineWindow { float buttonY = ImGui.getCursorScreenPosY(); ImGui.setCursorPosX(buttonX); if (ImGui.button("##Add", buttonSize, buttonSize)) { - Keyframe keyframe = switch (keyframeType) { - case CAMERA -> new CameraKeyframe(Minecraft.getInstance().player); - case FOV -> new FOVKeyframe(Minecraft.getInstance().options.fov().get()); + LocalPlayer player = Minecraft.getInstance().player; + Keyframe keyframe = switch (keyframeType) { + case CAMERA -> new CameraKeyframe(player); + case CAMERA_ORBIT -> { + Vec3 eyePosition = player.getEyePosition(); + cameraOrbitCenter[0] = (float) eyePosition.x; + cameraOrbitCenter[1] = (float) eyePosition.y; + cameraOrbitCenter[2] = (float) eyePosition.z; + ImGui.openPopup("##EnterCameraOrbit"); + yield null; + } + case FOV -> { + fovKeyframeInput[0] = editorState.replayVisuals.overrideFov ? editorState.replayVisuals.overrideFovAmount : Minecraft.getInstance().options.fov().get(); + ImGui.openPopup("##EnterFov"); + yield null; + } case SPEED -> { - speedKeyframeInput[0] = replayServer.desiredTickRate / 20.0f; + speedKeyframeInput[0] = replayServer.getDesiredTickRate(false) / 20.0f; ImGui.openPopup("##EnterSpeed"); yield null; } + case TIMELAPSE -> { + ImGui.openPopup("##EnterTimelapse"); + yield null; + } case TIME_OF_DAY -> { - timeOfDayKeyframeInput[0] = (int)(Minecraft.getInstance().level.getDayTime() % 24000); + if (editorState.replayVisuals.overrideTimeOfDay >= 0) { + timeOfDayKeyframeInput.set((int) editorState.replayVisuals.overrideTimeOfDay); + } else { + timeOfDayKeyframeInput.set((int)(Minecraft.getInstance().level.getDayTime() % 24000)); + } ImGui.openPopup("##EnterTime"); yield null; } + case CAMERA_SHAKE -> { + if (editorState.replayVisuals.overrideCameraShake) { + cameraShakeSplitXYKeyframeInput = editorState.replayVisuals.cameraShakeSplitParams; + cameraShakeFrequencyXKeyframeInput[0] = editorState.replayVisuals.cameraShakeXFrequency; + cameraShakeAmplitudeXKeyframeInput[0] = editorState.replayVisuals.cameraShakeXAmplitude; + cameraShakeFrequencyYKeyframeInput[0] = editorState.replayVisuals.cameraShakeYFrequency; + cameraShakeAmplitudeYKeyframeInput[0] = editorState.replayVisuals.cameraShakeYAmplitude; + ImGui.openPopup("##EnterCameraShake"); + yield null; + } else { + cameraShakeSplitXYKeyframeInput = false; + cameraShakeFrequencyXKeyframeInput[0] = 1.0f; + cameraShakeAmplitudeXKeyframeInput[0] = 0.0f; + cameraShakeFrequencyYKeyframeInput[0] = 1.0f; + cameraShakeAmplitudeYKeyframeInput[0] = 0.0f; + ImGui.openPopup("##EnterCameraShake"); + yield null; + } + } }; if (keyframe != null) { - keyframeTimes.put(cursorTicks, keyframe); + editorState.setKeyframe(trackIndex, cursorTicks, keyframe); } } drawList.addRectFilled(buttonX + 2, buttonY + buttonSize/2 - 1, buttonX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); @@ -942,7 +1383,19 @@ public class TimelineWindow { if (ImGui.beginPopup("##EnterSpeed")) { ImGui.sliderFloat("Speed", speedKeyframeInput, 0.1f, 10f); if (ImGui.button("Add")) { - keyframeTimes.put(cursorTicks, new TickrateKeyframe(speedKeyframeInput[0] * 20.0f)); + editorState.setKeyframe(trackIndex, cursorTicks, new TickrateKeyframe(speedKeyframeInput[0] * 20.0f)); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + if (ImGui.beginPopup("##EnterTimelapse")) { + ImGui.inputText("Time", timelapseKeyframeInput); + if (ImGui.button("Add")) { + editorState.setKeyframe(trackIndex, cursorTicks, new TimelapseKeyframe(Utils.stringToTime(ImGuiHelper.getString(timelapseKeyframeInput)))); ImGui.closeCurrentPopup(); } ImGui.sameLine(); @@ -952,9 +1405,76 @@ public class TimelineWindow { ImGui.endPopup(); } if (ImGui.beginPopup("##EnterTime")) { - ImGui.sliderInt("Time", timeOfDayKeyframeInput, 0, 24000); + ImGui.inputInt("Time", timeOfDayKeyframeInput, 0); if (ImGui.button("Add")) { - keyframeTimes.put(cursorTicks, new TimeOfDayKeyframe(timeOfDayKeyframeInput[0])); + editorState.setKeyframe(trackIndex, cursorTicks, new TimeOfDayKeyframe(timeOfDayKeyframeInput.get())); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + if (ImGui.beginPopup("##EnterFov")) { + ImGui.sliderFloat("FOV", fovKeyframeInput, 1f, 110f); + if (ImGui.button("Add")) { + editorState.setKeyframe(trackIndex, cursorTicks, new FOVKeyframe(fovKeyframeInput[0])); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + if (ImGui.beginPopup("##EnterCameraOrbit")) { + ImGui.inputFloat3("Position", cameraOrbitCenter); + ImGui.inputFloat("Distance", cameraOrbitDistance); + ImGui.inputFloat("Yaw", cameraOrbitYaw); + ImGui.inputFloat("Pitch", cameraOrbitPitch); + + if (ImGui.button("Add")) { + Vector3f center = new Vector3f(cameraOrbitCenter[0], cameraOrbitCenter[1], cameraOrbitCenter[2]); + Keyframe keyframe = new CameraOrbitKeyframe(center, cameraOrbitDistance.get(), cameraOrbitYaw.get(), cameraOrbitPitch.get()); + editorState.setKeyframe(trackIndex, cursorTicks, keyframe); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + if (ImGui.beginPopup("##EnterCameraShake")) { + if (ImGui.checkbox("Split Y/X", cameraShakeSplitXYKeyframeInput)) { + cameraShakeSplitXYKeyframeInput = !cameraShakeSplitXYKeyframeInput; + if (!cameraShakeSplitXYKeyframeInput) { + cameraShakeFrequencyYKeyframeInput[0] = cameraShakeFrequencyXKeyframeInput[0]; + cameraShakeAmplitudeYKeyframeInput[0] = cameraShakeAmplitudeXKeyframeInput[0]; + } + } + + if (cameraShakeSplitXYKeyframeInput) { + ImGui.sliderFloat("Frequency X", cameraShakeFrequencyXKeyframeInput, 0.1f, 10.0f, "%.1f"); + ImGui.sliderFloat("Amplitude X", cameraShakeAmplitudeXKeyframeInput, 0.0f, 10.0f, "%.1f"); + ImGui.sliderFloat("Frequency Y", cameraShakeFrequencyYKeyframeInput, 0.1f, 10.0f, "%.1f"); + ImGui.sliderFloat("Amplitude Y", cameraShakeAmplitudeYKeyframeInput, 0.0f, 10.0f, "%.1f"); + } else { + ImGui.sliderFloat("Frequency", cameraShakeFrequencyXKeyframeInput, 0.1f, 10.0f, "%.1f"); + ImGui.sliderFloat("Amplitude", cameraShakeAmplitudeXKeyframeInput, 0.0f, 10.0f, "%.1f"); + } + + if (ImGui.button("Add")) { + Keyframe keyframe; + if (cameraShakeSplitXYKeyframeInput) { + keyframe = new CameraShakeKeyframe(cameraShakeFrequencyXKeyframeInput[0], cameraShakeAmplitudeXKeyframeInput[0], + cameraShakeFrequencyYKeyframeInput[0], cameraShakeAmplitudeYKeyframeInput[0]); + } else { + keyframe = new CameraShakeKeyframe(cameraShakeFrequencyXKeyframeInput[0], cameraShakeAmplitudeXKeyframeInput[0], + cameraShakeFrequencyXKeyframeInput[0], cameraShakeAmplitudeXKeyframeInput[0]); + } + editorState.setKeyframe(trackIndex, cursorTicks, keyframe); ImGui.closeCurrentPopup(); } ImGui.sameLine(); @@ -995,20 +1515,37 @@ public class TimelineWindow { } if (keyframeTrackToClear >= 0) { - editorState.keyframeTracks.remove(keyframeTrackToClear); - editorState.dirty = true; + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(keyframeTrackToClear); + + undo.add(new EditorStateHistoryAction.AddTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); + for (Map.Entry entry : keyframeTrack.keyframesByTick.entrySet()) { + undo.add(new EditorStateHistoryAction.SetKeyframe(keyframeTrack.keyframeType, keyframeTrackToClear, entry.getKey(), entry.getValue().copy())); + } + + redo.add(new EditorStateHistoryAction.RemoveTrack(keyframeTrack.keyframeType, keyframeTrackToClear)); + + editorState.push(new EditorStateHistoryEntry(undo, redo, "Delete " + keyframeTrack.keyframeType + " track")); selectedKeyframesList.clear(); } ImGui.setCursorPosX(8); - if (editorState.keyframeTracks.size() < KeyframeType.KEYFRAME_TYPES.length && ImGui.smallButton("Add Element")) { + if (ImGui.smallButton("Add Element")) { ImGui.openPopup("##AddKeyframeElement"); } if (ImGui.beginPopup("##AddKeyframeElement")) { for (KeyframeType keyframeType : KeyframeType.KEYFRAME_TYPES) { if (ImGui.selectable(keyframeType.name)) { - editorState.keyframeTracks.add(new KeyframeTrack(keyframeType)); - editorState.dirty = true; + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + int index = editorState.keyframeTracks.size(); + undo.add(new EditorStateHistoryAction.RemoveTrack(keyframeType, index)); + redo.add(new EditorStateHistoryAction.AddTrack(keyframeType, index)); + + editorState.push(new EditorStateHistoryEntry(undo, redo, "Create " + keyframeType + " track")); ImGui.closeCurrentPopup(); } } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java index bb04f3b..a824ff9 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java @@ -1,6 +1,11 @@ package com.moulberry.flashback.editor.ui.windows; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.record.FlashbackMeta; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.visuals.ReplayVisuals; import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.editor.ui.ImGuiHelper; import imgui.ImGui; @@ -12,108 +17,217 @@ public class VisualsWindow { private static final int[] intBuffer = new int[]{0}; public static void render() { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer == null) { + return; + } + + FlashbackMeta metadata = replayServer.getMetadata(); + EditorState editorState = EditorStateManager.get(metadata.replayIdentifier); + ReplayVisuals visuals = editorState.replayVisuals; + if (ImGui.begin("Visuals")) { ImGuiHelper.separatorWithText("GUI"); - if (ImGui.checkbox("Chat", ReplayVisuals.showChat)) { - ReplayVisuals.showChat = !ReplayVisuals.showChat; + if (ImGui.checkbox("Chat", visuals.showChat)) { + visuals.showChat = !visuals.showChat; + editorState.markDirty(); } - if (ImGui.checkbox("Boss Bar", ReplayVisuals.showBossBar)) { - ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar; + if (ImGui.checkbox("Boss Bar", visuals.showBossBar)) { + visuals.showBossBar = !visuals.showBossBar; + editorState.markDirty(); } - if (ImGui.checkbox("Title Text", ReplayVisuals.showTitleText)) { - ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText; + if (ImGui.checkbox("Title Text", visuals.showTitleText)) { + visuals.showTitleText = !visuals.showTitleText; + editorState.markDirty(); } - if (ImGui.checkbox("Scoreboard", ReplayVisuals.showScoreboard)) { - ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard; + if (ImGui.checkbox("Scoreboard", visuals.showScoreboard)) { + visuals.showScoreboard = !visuals.showScoreboard; + editorState.markDirty(); } - if (ImGui.checkbox("Action Bar", ReplayVisuals.showActionBar)) { - ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar; + if (ImGui.checkbox("Action Bar", visuals.showActionBar)) { + visuals.showActionBar = !visuals.showActionBar; + editorState.markDirty(); } ImGuiHelper.separatorWithText("World"); - if (ImGui.checkbox("Render Blocks", ReplayVisuals.renderBlocks)) { - ReplayVisuals.renderBlocks = !ReplayVisuals.renderBlocks; + if (ImGui.checkbox("Render Blocks", visuals.renderBlocks)) { + visuals.renderBlocks = !visuals.renderBlocks; + editorState.markDirty(); } - if (ImGui.checkbox("Render Entities", ReplayVisuals.renderEntities)) { - ReplayVisuals.renderEntities = !ReplayVisuals.renderEntities; + if (ImGui.checkbox("Render Entities", visuals.renderEntities)) { + visuals.renderEntities = !visuals.renderEntities; + editorState.markDirty(); } - if (ImGui.checkbox("Render Players", ReplayVisuals.renderPlayers)) { - ReplayVisuals.renderPlayers = !ReplayVisuals.renderPlayers; + if (ImGui.checkbox("Render Players", visuals.renderPlayers)) { + visuals.renderPlayers = !visuals.renderPlayers; + editorState.markDirty(); } - if (ImGui.checkbox("Render Particles", ReplayVisuals.renderParticles)) { - ReplayVisuals.renderParticles = !ReplayVisuals.renderParticles; + if (ImGui.checkbox("Render Particles", visuals.renderParticles)) { + visuals.renderParticles = !visuals.renderParticles; + editorState.markDirty(); } - if (ImGui.checkbox("Render Sky", ReplayVisuals.renderSky)) { - ReplayVisuals.renderSky = !ReplayVisuals.renderSky; + if (ImGui.checkbox("Render Sky", visuals.renderSky)) { + visuals.renderSky = !visuals.renderSky; + editorState.markDirty(); } - if (ImGui.checkbox("Render Nametags", ReplayVisuals.renderNametags)) { - ReplayVisuals.renderNametags = !ReplayVisuals.renderNametags; + if (ImGui.checkbox("Render Nametags", visuals.renderNametags)) { + visuals.renderNametags = !visuals.renderNametags; + editorState.markDirty(); } ImGuiHelper.separatorWithText("Overrides"); // Fog distance - if (ImGui.checkbox("Override Fog", ReplayVisuals.overrideFog)) { - ReplayVisuals.overrideFog = !ReplayVisuals.overrideFog; + if (ImGui.checkbox("Override Fog", visuals.overrideFog)) { + visuals.overrideFog = !visuals.overrideFog; + editorState.markDirty(); } - if (ReplayVisuals.overrideFog) { - floatBuffer[0] = ReplayVisuals.overrideFogStart; + if (visuals.overrideFog) { + floatBuffer[0] = visuals.overrideFogStart; if (ImGui.sliderFloat("Start", floatBuffer, 0.0f, 512.0f)) { - ReplayVisuals.overrideFogStart = floatBuffer[0]; + visuals.overrideFogStart = floatBuffer[0]; + editorState.markDirty(); } - floatBuffer[0] = ReplayVisuals.overrideFogEnd; + floatBuffer[0] = visuals.overrideFogEnd; if (ImGui.sliderFloat("End", floatBuffer, 0.0f, 512.0f)) { - ReplayVisuals.overrideFogEnd = floatBuffer[0]; + visuals.overrideFogEnd = floatBuffer[0]; + editorState.markDirty(); } } // FOV - if (ImGui.checkbox("Override FOV", ReplayVisuals.overrideFov)) { - ReplayVisuals.overrideFov = !ReplayVisuals.overrideFov; + if (ImGui.checkbox("Override FOV", visuals.overrideFov)) { + visuals.overrideFov = !visuals.overrideFov; + Minecraft.getInstance().levelRenderer.needsUpdate(); + editorState.markDirty(); } - if (ReplayVisuals.overrideFov) { - floatBuffer[0] = ReplayVisuals.overrideFovAmount; - if (ImGui.sliderFloat("FOV", floatBuffer, 0.1f, 110.0f, "%.1f")) { - ReplayVisuals.setFov(floatBuffer[0]); + if (visuals.overrideFov) { + floatBuffer[0] = visuals.overrideFovAmount; + if (ImGui.sliderFloat("FOV", floatBuffer, 1.0f, 110.0f, "%.1f")) { + visuals.setFov(floatBuffer[0]); + editorState.markDirty(); } } // Time - if (ImGui.checkbox("Override Time", ReplayVisuals.overrideTimeOfDay >= 0)) { - if (ReplayVisuals.overrideTimeOfDay >= 0) { - ReplayVisuals.overrideTimeOfDay = -1; + if (ImGui.checkbox("Override Time", visuals.overrideTimeOfDay >= 0)) { + if (visuals.overrideTimeOfDay >= 0) { + visuals.overrideTimeOfDay = -1; } else { - ReplayVisuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000); + visuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000); + } + editorState.markDirty(); + } + if (visuals.overrideTimeOfDay >= 0) { + intBuffer[0] = (int) visuals.overrideTimeOfDay; + if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) { + visuals.overrideTimeOfDay = intBuffer[0]; + editorState.markDirty(); } } - if (ReplayVisuals.overrideTimeOfDay >= 0) { - intBuffer[0] = (int) ReplayVisuals.overrideTimeOfDay; - if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) { - ReplayVisuals.overrideTimeOfDay = intBuffer[0]; + + // Camera shake + if (ImGui.checkbox("Camera Shake", visuals.overrideCameraShake)) { + visuals.overrideCameraShake = !visuals.overrideCameraShake; + editorState.markDirty(); + } + if (visuals.overrideCameraShake) { + if (ImGui.checkbox("Split Y/X", visuals.cameraShakeSplitParams)) { + visuals.cameraShakeSplitParams = !visuals.cameraShakeSplitParams; + editorState.markDirty(); + } + + if (visuals.cameraShakeSplitParams) { + ImGui.setNextItemWidth(100); + floatBuffer[0] = visuals.cameraShakeXFrequency; + if (ImGui.sliderFloat("Frequency X", floatBuffer, 0.1f, 10.0f, "%.1f")) { + visuals.cameraShakeXFrequency = floatBuffer[0]; + editorState.markDirty(); + } + + ImGui.setNextItemWidth(100); + floatBuffer[0] = visuals.cameraShakeXAmplitude; + if (ImGui.sliderFloat("Amplitude X", floatBuffer, 0.0f, 10.0f, "%.1f")) { + visuals.cameraShakeXAmplitude = floatBuffer[0]; + editorState.markDirty(); + } + + ImGui.setNextItemWidth(100); + floatBuffer[0] = visuals.cameraShakeYFrequency; + if (ImGui.sliderFloat("Frequency Y", floatBuffer, 0.1f, 10.0f, "%.1f")) { + visuals.cameraShakeYFrequency = floatBuffer[0]; + editorState.markDirty(); + } + + ImGui.setNextItemWidth(100); + floatBuffer[0] = visuals.cameraShakeYAmplitude; + if (ImGui.sliderFloat("Amplitude Y", floatBuffer, 0.0f, 10.0f, "%.1f")) { + visuals.cameraShakeYAmplitude = floatBuffer[0]; + editorState.markDirty(); + } + } else { + ImGui.setNextItemWidth(100); + floatBuffer[0] = (visuals.cameraShakeXFrequency + visuals.cameraShakeYFrequency)/2.0f; + if (ImGui.sliderFloat("Frequency", floatBuffer, 0.1f, 10.0f, "%.1f")) { + visuals.cameraShakeXFrequency = floatBuffer[0]; + visuals.cameraShakeYFrequency = floatBuffer[0]; + editorState.markDirty(); + } + + ImGui.setNextItemWidth(100); + floatBuffer[0] = (visuals.cameraShakeXAmplitude + visuals.cameraShakeYAmplitude)/2.0f; + if (ImGui.sliderFloat("Amplitude", floatBuffer, 0.0f, 10.0f, "%.1f")) { + visuals.cameraShakeXAmplitude = floatBuffer[0]; + visuals.cameraShakeYAmplitude = floatBuffer[0]; + editorState.markDirty(); + } + } + } + + // Camera Roll + if (ImGui.checkbox("Camera Roll", visuals.overrideRoll)) { + visuals.overrideRoll = !visuals.overrideRoll; + Minecraft.getInstance().levelRenderer.needsUpdate(); + editorState.markDirty(); + } + if (visuals.overrideRoll) { + floatBuffer[0] = visuals.overrideRollAmount; + if (ImGui.sliderFloat("Roll", floatBuffer, -180.0f, 180.0f, "%.1f")) { + visuals.overrideRollAmount = floatBuffer[0]; + Minecraft.getInstance().levelRenderer.needsUpdate(); + editorState.markDirty(); } } ImGuiHelper.separatorWithText("Other"); - if (ImGui.checkbox("Rule of Thirds Guide", ReplayVisuals.ruleOfThirdsGuide)) { - ReplayVisuals.ruleOfThirdsGuide = !ReplayVisuals.ruleOfThirdsGuide; + if (ImGui.checkbox("Rule of Thirds Guide", visuals.ruleOfThirdsGuide)) { + visuals.ruleOfThirdsGuide = !visuals.ruleOfThirdsGuide; + editorState.markDirty(); } - if (ImGui.checkbox("Center Guide", ReplayVisuals.centerGuide)) { - ReplayVisuals.centerGuide = !ReplayVisuals.centerGuide; + if (ImGui.checkbox("Center Guide", visuals.centerGuide)) { + visuals.centerGuide = !visuals.centerGuide; + editorState.markDirty(); } - ReplayVisuals.sizing = ImGuiHelper.enumCombo("Sizing", ReplayVisuals.sizing); - if (ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { - ReplayVisuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", ReplayVisuals.changeAspectRatio); + if (ImGui.checkbox("Camera Path", visuals.cameraPath)) { + visuals.cameraPath = !visuals.cameraPath; + editorState.markDirty(); + } + + visuals.sizing = ImGuiHelper.enumCombo("Sizing", visuals.sizing); + if (visuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { + visuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", visuals.changeAspectRatio); + editorState.markDirty(); } } ImGui.end(); diff --git a/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java index 749682e..096a4da 100644 --- a/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java +++ b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java @@ -8,6 +8,7 @@ import net.fabricmc.loader.api.FabricLoader; import org.bytedeco.ffmpeg.avutil.AVComponentDescriptor; import org.bytedeco.ffmpeg.avutil.AVFrame; import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor; +import org.bytedeco.ffmpeg.global.avcodec; import org.bytedeco.ffmpeg.global.avutil; import org.bytedeco.ffmpeg.global.swscale; import org.bytedeco.ffmpeg.swscale.SwsContext; @@ -24,6 +25,7 @@ import org.lwjgl.system.MemoryUtil; import java.io.IOException; import java.nio.ByteBuffer; +import java.nio.FloatBuffer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -51,7 +53,8 @@ public class AsyncVideoEncoder implements AutoCloseable { private static final int SRC_PIXEL_FORMAT = avutil.AV_PIX_FMT_RGBA; - private record ImageFrame(long pointer, int size, int width, int height, int channels, int imageDepth, int stride, int pixelFormat) implements AutoCloseable { + private record ImageFrame(long pointer, int size, int width, int height, int channels, int imageDepth, int stride, int pixelFormat, + @Nullable FloatBuffer audioBuffer) implements AutoCloseable { public void close() { MemoryUtil.nmemFree(this.pointer); } @@ -70,6 +73,11 @@ public class AsyncVideoEncoder implements AutoCloseable { } int maxBitrate = Math.min(288_000_000, 5000 + (int) Math.ceil(width * height * settings.framerate())); + + if (settings.encoder().equals("libsvtav1")) { + maxBitrate = Math.min(100_000_000, maxBitrate); + } + int bitrate; if (settings.bitrate() <= 0) { bitrate = maxBitrate; @@ -89,7 +97,7 @@ public class AsyncVideoEncoder implements AutoCloseable { boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat; final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder( - filename, width, height, 0); + filename, width, height, settings.recordAudio() ? 1 : 0); recorder.setVideoBitrate(bitrate); recorder.setVideoCodec(settings.codec().codecId()); @@ -97,7 +105,14 @@ public class AsyncVideoEncoder implements AutoCloseable { recorder.setFormat(extension); recorder.setFrameRate(fps); recorder.setPixelFormat(dstPixelFormat); - recorder.setGopSize((int) Math.ceil(fps * 2)); + recorder.setGopSize((int) Math.max(20, Math.min(240, Math.ceil(fps * 2)))); + + if (settings.recordAudio()) { + recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC); + recorder.setSampleFormat(avutil.AV_SAMPLE_FMT_FLTP); + recorder.setSampleRate(44100); + recorder.setAudioBitrate(320000); + } recorder.start(); @@ -144,6 +159,9 @@ public class AsyncVideoEncoder implements AutoCloseable { recorder.recordImage(src.width, src.height, src.imageDepth, src.channels, src.stride, src.pixelFormat, buffer); + if (src.audioBuffer != null) { + recorder.recordSamples(src.audioBuffer); + } if (this.reusePictureData != null) { if (this.reusePictureData.offer(src.pointer)) { // try adding to the reuse queue, ignore if full @@ -259,7 +277,7 @@ public class AsyncVideoEncoder implements AutoCloseable { 0, src.height, picture_ptr, picture.linesize()); this.encodeQueue.put(new ImageFrame(tempPointerAddress, dstSize, dstWidth, dstHeight, dstChannels, dstDepth, - dstWidth, dstPixelFormat)); + dstWidth, dstPixelFormat, src.audioBuffer)); } catch (Throwable t) { try { av_frame_free(picture); @@ -299,7 +317,7 @@ public class AsyncVideoEncoder implements AutoCloseable { } } - public void encode(NativeImage src) { + public void encode(NativeImage src, @Nullable FloatBuffer audioBuffer) { checkEncodeError(src); if (this.finishRescaleThread.get() || this.finishEncodeThread.get() || this.finishedWriting.get()) { @@ -310,7 +328,7 @@ public class AsyncVideoEncoder implements AutoCloseable { while (true) { try { ImageFrame imageFrame = new ImageFrame(src.pixels, (int) src.size, src.getWidth(), src.getHeight(), - 4, Frame.DEPTH_INT, src.getWidth(), SRC_PIXEL_FORMAT); + 4, Frame.DEPTH_INT, src.getWidth(), SRC_PIXEL_FORMAT, audioBuffer); if (this.rescaleQueue != null) { this.rescaleQueue.put(imageFrame); } else { @@ -368,7 +386,7 @@ public class AsyncVideoEncoder implements AutoCloseable { if (this.reusePictureData != null) { for (Long address : this.reusePictureData) { - if (address != 0) { + if (address != null && address != 0) { MemoryUtil.nmemFree(address); } } diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java index 9d7cd12..0c3529b 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -9,25 +9,44 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.*; import com.moulberry.flashback.FixedDeltaTracker; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.Utils; +import com.moulberry.flashback.compat.IrisApiWrapper; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.state.KeyframeTrack; +import it.unimi.dsi.fastutil.doubles.DoubleArrayList; +import it.unimi.dsi.fastutil.doubles.DoubleList; +import it.unimi.dsi.fastutil.floats.FloatArrayList; +import it.unimi.dsi.fastutil.floats.FloatList; import net.minecraft.client.Minecraft; +import net.minecraft.client.Screenshot; import net.minecraft.client.gui.Font; import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.FogRenderer; import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.client.sounds.SoundEngine; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; import org.joml.Matrix4f; import org.lwjgl.glfw.GLFW; +import org.lwjgl.openal.SOFTLoopback; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Objects; +import java.util.Random; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; @@ -42,6 +61,8 @@ public class ExportJob { private long escapeCancelStartMillis = -1; private long renderStartTime; + private final Random particleRandom; + private boolean showingDebug = false; private boolean pressedDebugKey = false; private long serverTickTimeNanos = 0; @@ -50,10 +71,13 @@ public class ExportJob { private long encodeTimeNanos = 0; private long downloadTimeNanos = 0; + private double audioSamples = 0.0; + private final AtomicBoolean finishedServerTick = new AtomicBoolean(false); public ExportJob(ExportSettings settings) { this.settings = settings; + this.particleRandom = this.settings.resetRng() ? new Random(2000) : null; } public boolean isRunning() { @@ -76,12 +100,21 @@ public class ExportJob { return this.settings.resolutionY(); } + public Random getParticleRandom() { + return this.particleRandom; + } + + public ExportSettings getSettings() { + return this.settings; + } + public void run() { ReplayServer replayServer = Flashback.getReplayServer(); if (this.running || replayServer == null) { throw new IllegalStateException("run() called twice"); } this.running = true; + Minecraft.getInstance().mouseHandler.releaseMouse(); UUID uuid = UUID.randomUUID(); @@ -108,6 +141,7 @@ public class ExportJob { } finally { this.running = false; this.shouldChangeFramebufferSize = false; + Minecraft.getInstance().resizeDisplay(); try { @@ -136,23 +170,29 @@ public class ExportJob { return; } + Random random = new Random(1000); + Random mathRandom = this.settings.resetRng() ? Utils.getInternalMathRandom() : null; + this.setup(replayServer); + this.updateRandoms(random, mathRandom); shouldChangeFramebufferSize = true; Minecraft.getInstance().resizeDisplay(); - double framesPerTick = this.settings.framerate() / 20.0; + DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate()); - int currentFrame = 0; - int totalFrames = (int) Math.ceil((this.settings.endTick() - this.settings.startTick() + 1) * framesPerTick); int clientTickCount = 0; this.renderStartTime = System.currentTimeMillis(); - EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier); + EditorState editorState = EditorStateManager.get(replayServer.getMetadata().replayIdentifier); - while (currentFrame <= totalFrames) { - double currentTickDouble = currentFrame / framesPerTick; + double lastTickDouble = 0; + + for (int tickIndex = 0; tickIndex < ticks.size(); tickIndex++) { + double currentTickDouble = ticks.getDouble(tickIndex); + float deltaTicksFloat = (float)(currentTickDouble - lastTickDouble); + lastTickDouble = currentTickDouble; int currentTick = (int) currentTickDouble; double partialTick = currentTickDouble - currentTick; int targetServerTick = this.settings.startTick() + currentTick; @@ -165,6 +205,7 @@ public class ExportJob { // Tick client while (clientTickCount < currentTick) { start = System.nanoTime(); + this.updateRandoms(random, mathRandom); this.runClientTick(); clientTickTimeNanos += System.nanoTime() - start; @@ -204,68 +245,132 @@ public class ExportJob { this.tryUnfreezeClient(); - editorState.applyKeyframes(Minecraft.getInstance(), (float)(this.settings.startTick() + currentTickDouble)); + KeyframeHandler keyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance()); + editorState.applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble)); - RenderTarget oldTarget = Minecraft.getInstance().getMainRenderTarget(); - SaveableFramebuffer saveable = downloader.take(); - RenderTarget renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY()); + boolean asyncFrameCapture = !IrisApiWrapper.isIrisAvailable() || !IrisApiWrapper.isShaderPackInUse(); - Minecraft.getInstance().mainRenderTarget = renderTarget; + RenderTarget oldTarget = null; + SaveableFramebuffer saveable = null; + RenderTarget renderTarget; + + if (asyncFrameCapture) { + oldTarget = Minecraft.getInstance().getMainRenderTarget(); + saveable = downloader.take(); + renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY()); + + Minecraft.getInstance().mainRenderTarget = renderTarget; + } else { + renderTarget = Minecraft.getInstance().mainRenderTarget; + } renderTarget.bindWrite(true); - RenderSystem.clear(16640, Minecraft.ON_OSX); // Perform rendering PerfectFrames.waitUntilFrameReady(); FogRenderer.setupNoFog(); RenderSystem.enableCull(); - Minecraft.getInstance().timer.deltaTicks = 1 / (float) framesPerTick; - Minecraft.getInstance().timer.realtimeDeltaTicks = 1 / (float) framesPerTick; + Minecraft.getInstance().timer.deltaTicks = deltaTicksFloat; + Minecraft.getInstance().timer.realtimeDeltaTicks = deltaTicksFloat; Minecraft.getInstance().timer.deltaTickResidual = (float) partialTick; Minecraft.getInstance().timer.pausedDeltaTickResidual = (float) partialTick; start = System.nanoTime(); - Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(1 / (float) framesPerTick, (float) partialTick), true); + Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(deltaTicksFloat, (float) partialTick), true); renderTimeNanos += System.nanoTime() - start; renderTarget.unbindWrite(); - Minecraft.getInstance().mainRenderTarget = oldTarget; + boolean cancel; - this.shouldChangeFramebufferSize = false; - boolean cancel = finishFrame(renderTarget, infoRenderTarget, currentFrame, totalFrames); - this.shouldChangeFramebufferSize = true; + // Capture audio if necessary + FloatBuffer audioBuffer = null; + if (this.settings.recordAudio()) { + long device = Minecraft.getInstance().getSoundManager().soundEngine.library.currentDevice; - submitDownloadedFrames(encoder, downloader, false); + audioSamples += 44100 / this.settings.framerate(); + int renderSamples = (int) audioSamples; + audioSamples -= renderSamples; - downloader.startDownload(saveable); - - if (cancel) { - break; + audioBuffer = ByteBuffer.allocateDirect(renderSamples * 4).order(ByteOrder.nativeOrder()).asFloatBuffer(); + SOFTLoopback.alcRenderSamplesSOFT(device, audioBuffer, renderSamples); } - currentFrame += 1; + if (asyncFrameCapture) { + Minecraft.getInstance().mainRenderTarget = oldTarget; + + this.shouldChangeFramebufferSize = false; + cancel = finishFrame(renderTarget, infoRenderTarget, tickIndex, ticks.size()); + this.shouldChangeFramebufferSize = true; + + submitDownloadedFrames(encoder, downloader, false); + + saveable.audioBuffer = audioBuffer; + downloader.startDownload(saveable); + } else { + this.shouldChangeFramebufferSize = false; + cancel = finishFrame(renderTarget, infoRenderTarget, tickIndex, ticks.size()); + this.shouldChangeFramebufferSize = true; + + start = System.nanoTime(); + NativeImage image = Screenshot.takeScreenshot(renderTarget); + downloadTimeNanos += System.nanoTime() - start; + + start = System.nanoTime(); + encoder.encode(image, audioBuffer); + encodeTimeNanos += System.nanoTime() - start; + } + + if (cancel) { + ExportJobQueue.drainingQueue = false; + break; + } } submitDownloadedFrames(encoder, downloader, true); encoder.finish(); } + private void updateRandoms(Random random, Random mathRandom) { + if (!this.settings.resetRng()) { + return; + } + + Minecraft minecraft = Minecraft.getInstance(); + + long connectionSeed = random.nextLong(); + long levelSeed = random.nextLong(); + long entitySeed = random.nextLong(); + long mathSeed = random.nextLong(); + long particleSeed = random.nextLong(); + + if (minecraft.getConnection() != null) { + minecraft.getConnection().random.setSeed(connectionSeed); + } + if (minecraft.level != null) { + minecraft.level.random.setSeed(levelSeed); + + for (Entity entity : minecraft.level.entitiesForRendering()) { + if (entity == null) { + continue; + } + + entity.getRandom().setSeed(entitySeed ^ entity.getUUID().getMostSignificantBits()); + } + } + if (mathRandom != null) { + mathRandom.setSeed(mathSeed); + } + this.particleRandom.setSeed(particleSeed); + } + private void setup(ReplayServer replayServer) { Minecraft minecraft = Minecraft.getInstance(); // Clear particles minecraft.particleEngine.clearParticles(); - // Apply keyframes at start tick - EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier); - editorState.applyKeyframes(Minecraft.getInstance(), this.settings.startTick()); - - // Ensure position is updated before doing anything else - this.runClientTick(); - this.setServerTickAndWait(replayServer, replayServer.getReplayTick(), true); - int currentTick = Math.max(0, this.settings.startTick() - 20); // Ensure replay server is paused at currentTick @@ -279,6 +384,17 @@ public class ExportJob { currentTick += 1; } + // Apply initial position and keyframes at start tick + LocalPlayer player = minecraft.player; + if (player != null) { + Vec3 position = this.settings.initialCameraPosition(); + player.moveTo(position.x, position.y, position.z, this.settings.initialCameraYaw(), this.settings.initialCameraPitch()); + player.setDeltaMovement(Vec3.ZERO); + } + EditorState editorState = EditorStateManager.get(replayServer.getMetadata().replayIdentifier); + editorState.applyKeyframes(new MinecraftKeyframeHandler(Minecraft.getInstance()), this.settings.startTick()); + this.runClientTick(); + // Ensured replay server is paused at startTick this.setServerTickAndWait(replayServer, this.settings.startTick(), true); this.runClientTick(); @@ -306,6 +422,7 @@ public class ExportJob { while (Minecraft.getInstance().pollTask()) {} Minecraft.getInstance().tick(); + Minecraft.getInstance().getSoundManager().updateSource(Minecraft.getInstance().gameRenderer.getMainCamera()); this.tryUnfreezeClient(); } @@ -317,18 +434,18 @@ public class ExportJob { } private void submitDownloadedFrames(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, boolean drain) { - NativeImage image; + SaveableFramebufferQueue.DownloadedFrame frame; while (true) { long start = System.nanoTime(); - image = downloader.finishDownload(drain); + frame = downloader.finishDownload(drain); downloadTimeNanos += System.nanoTime() - start; - if (image == null) { + if (frame == null) { break; } start = System.nanoTime(); - encoder.encode(image); + encoder.encode(frame.image(), frame.audioBuffer()); encodeTimeNanos += System.nanoTime() - start; } } @@ -373,7 +490,7 @@ public class ExportJob { RenderSystem.clear(16640, Minecraft.ON_OSX); - int guiScale = 4; + float guiScale = 4f; int scaledWidth = (int) Math.ceil(infoRenderTarget.width / guiScale); int scaledHeight = (int) Math.ceil(infoRenderTarget.height / guiScale); @@ -387,6 +504,11 @@ public class ExportJob { List lines = new ArrayList<>(); + if (this.settings.name() != null) { + lines.add(this.settings.name()); + lines.add(""); + } + lines.add("Exported Frames: " + currentFrame + "/" + totalFrames); long elapsed = currentTime - this.renderStartTime; @@ -476,4 +598,54 @@ public class ExportJob { } } + private static class TickrateKeyframeCapture implements KeyframeHandler { + private float tickrate = 20.0f; + + @Override + public EnumSet supportedKeyframes() { + return EnumSet.of(KeyframeType.SPEED, KeyframeType.TIMELAPSE); + } + + @Override + public boolean alwaysApplyLastKeyframe() { + return true; + } + + @Override + public void applyTickrate(float tickrate) { + this.tickrate = tickrate; + } + } + + private static DoubleList calculateTicks(EditorState editorState, int startTick, int endTick, double fps) { + DoubleList ticks = new DoubleArrayList(); + + ticks.add(0); + + double residual = 0; + int currentTick = 0; + + TickrateKeyframeCapture capture = new TickrateKeyframeCapture(); + + int count = endTick - startTick; + while (currentTick <= count) { + capture.tickrate = 20.0f; + editorState.applyKeyframes(capture, startTick + currentTick + (float) residual); + + residual += capture.tickrate / fps; + + int roundedResidual = (int) residual; + residual -= roundedResidual; + currentTick += roundedResidual; + + if (currentTick > count) { + break; + } + + ticks.add(currentTick + residual); + } + + return ticks; + } + } diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJobQueue.java b/src/main/java/com/moulberry/flashback/exporting/ExportJobQueue.java new file mode 100644 index 0000000..95c9c47 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJobQueue.java @@ -0,0 +1,16 @@ +package com.moulberry.flashback.exporting; + +import java.util.ArrayList; +import java.util.List; + +public class ExportJobQueue { + + public static List queuedJobs = new ArrayList<>(); + public static boolean drainingQueue = false; + + public static int count() { + return queuedJobs.size(); + } + + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java index 34eba49..8366952 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java @@ -2,10 +2,24 @@ package com.moulberry.flashback.exporting; import com.moulberry.flashback.combo_options.VideoCodec; import com.moulberry.flashback.combo_options.VideoContainer; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.visuals.ReplayVisuals; +import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; import java.nio.file.Path; -public record ExportSettings(int resolutionX, int resolutionY, int startTick, int endTick, double framerate, VideoContainer container, - VideoCodec codec, String encoder, int bitrate, Path output) { +public record ExportSettings(@Nullable String name, EditorState editorState, + // Initial state + Vec3 initialCameraPosition, float initialCameraYaw, float initialCameraPitch, + // Capture + int resolutionX, int resolutionY, int startTick, int endTick, double framerate, + boolean resetRng, + // Video + VideoContainer container, VideoCodec codec, String encoder, int bitrate, + // Audio + boolean recordAudio, + // Output + Path output) { } diff --git a/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java b/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java index 31f29bf..4dbdaf8 100644 --- a/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java +++ b/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java @@ -40,6 +40,10 @@ public class PixelFormatHelper { IntPointer pixFmts = codec.pix_fmts(); + if (pixFmts == null) { + return avutil.AV_PIX_FMT_YUV420P; + } + int index = 0; while (true) { int pixFmt = pixFmts.get(index); diff --git a/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java index f1ac4a9..8250b09 100644 --- a/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java +++ b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java @@ -2,15 +2,18 @@ package com.moulberry.flashback.exporting; import com.mojang.blaze3d.pipeline.MainTarget; import com.mojang.blaze3d.platform.NativeImage; +import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL30C; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; +import java.nio.FloatBuffer; public class SaveableFramebuffer implements AutoCloseable { private MainTarget framebuffer; private int pboId; + public @Nullable FloatBuffer audioBuffer; private boolean isDownloading = false; diff --git a/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java index cde7952..7e90165 100644 --- a/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java +++ b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java @@ -3,6 +3,8 @@ package com.moulberry.flashback.exporting; import com.mojang.blaze3d.platform.NativeImage; import org.jetbrains.annotations.Nullable; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; @@ -37,7 +39,9 @@ public class SaveableFramebufferQueue implements AutoCloseable { this.waiting.add(texture); } - public @Nullable NativeImage finishDownload(boolean drain) { + record DownloadedFrame(NativeImage image, @Nullable FloatBuffer audioBuffer) {} + + public @Nullable DownloadedFrame finishDownload(boolean drain) { if (this.waiting.isEmpty()) { return null; } @@ -47,9 +51,13 @@ public class SaveableFramebufferQueue implements AutoCloseable { } SaveableFramebuffer texture = this.waiting.removeFirst(); + NativeImage nativeImage = texture.finishDownload(this.width, this.height); + FloatBuffer audioBuffer = texture.audioBuffer; + texture.audioBuffer = null; + this.available.add(texture); - return nativeImage; + return new DownloadedFrame(nativeImage, audioBuffer); } @Override diff --git a/src/main/java/com/moulberry/flashback/ext/LevelChunkExt.java b/src/main/java/com/moulberry/flashback/ext/LevelChunkExt.java new file mode 100644 index 0000000..eb20a2f --- /dev/null +++ b/src/main/java/com/moulberry/flashback/ext/LevelChunkExt.java @@ -0,0 +1,12 @@ +package com.moulberry.flashback.ext; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.block.state.BlockState; + +public interface LevelChunkExt { + + void flashback$setBlockStateWithoutUpdates(BlockPos blockPos, BlockState blockState); + int flashback$getCachedChunkId(); + void flashback$setCachedChunkId(int id); + +} diff --git a/src/main/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java b/src/main/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java deleted file mode 100644 index 01f3ff6..0000000 --- a/src/main/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.moulberry.flashback.ext; - -public interface LevelChunkSectionExt { - - int flashback$getCachedChunkId(); - void flashback$setCachedChunkId(int id); - -} diff --git a/src/main/java/com/moulberry/flashback/ext/MinecraftExt.java b/src/main/java/com/moulberry/flashback/ext/MinecraftExt.java index a16810d..962dea3 100644 --- a/src/main/java/com/moulberry/flashback/ext/MinecraftExt.java +++ b/src/main/java/com/moulberry/flashback/ext/MinecraftExt.java @@ -9,8 +9,8 @@ import java.util.UUID; public interface MinecraftExt { - void flashback$forceClientTick(); + void flashback$applyKeyframes(); void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem, UUID playbackUUID, Path path); - float flashback$getLocalPlayerPartialTick(); + float flashback$getLocalPlayerPartialTick(float originalPartialTick); } diff --git a/src/main/java/com/moulberry/flashback/ext/OptionsExt.java b/src/main/java/com/moulberry/flashback/ext/OptionsExt.java new file mode 100644 index 0000000..3a77456 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/ext/OptionsExt.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.ext; + +public interface OptionsExt { + + int flashback$getOriginalFov(); + +} diff --git a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java index b87389f..820586a 100644 --- a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java +++ b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java @@ -44,7 +44,7 @@ import java.util.function.Consumer; public class AsyncReplaySaver { - private final ArrayBlockingQueue> tasks = new ArrayBlockingQueue<>(256); + private final ArrayBlockingQueue> tasks = new ArrayBlockingQueue<>(1024); private final AtomicReference error = new AtomicReference<>(null); private final AtomicBoolean shouldStop = new AtomicBoolean(false); private final AtomicBoolean hasStopped = new AtomicBoolean(false); diff --git a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java index de20860..01234b8 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java @@ -1,69 +1,105 @@ package com.moulberry.flashback.keyframe; import com.google.gson.*; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.impl.CameraKeyframe; +import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; +import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe; import com.moulberry.flashback.keyframe.impl.FOVKeyframe; import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; +import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import java.lang.reflect.Type; +import java.util.Objects; +import java.util.function.Consumer; -public abstract class Keyframe { +public abstract class Keyframe { - public final Class operandClass; - private InterpolationType interpolationType = InterpolationType.SMOOTH; - - public Keyframe(Class operandClass) { - this.operandClass = operandClass; - } + private InterpolationType interpolationType = InterpolationType.DEFAULT; public InterpolationType interpolationType() { return interpolationType; } public void interpolationType(InterpolationType interpolationType) { - this.interpolationType = interpolationType; + this.interpolationType = Objects.requireNonNullElse(interpolationType, InterpolationType.DEFAULT); } - public abstract void apply(T t); - public abstract void applyInterpolated(T t, Keyframe other, float amount); - public abstract void applyInterpolatedSmooth(T t, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, + public abstract Keyframe copy(); + public abstract void apply(KeyframeHandler t); + public abstract void applyInterpolated(KeyframeHandler t, Keyframe other, float amount); + public abstract void applyInterpolatedSmooth(KeyframeHandler t, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight); - public static class TypeAdapter implements JsonSerializer>, JsonDeserializer> { + public void renderEditKeyframe(Consumer> update) {} + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { @Override - public Keyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + public Keyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); - String type = jsonObject.get("type").getAsString(); - Keyframe keyframe = switch (type) { + String type; + if (jsonObject.has("type")) { + type = jsonObject.get("type").getAsString(); + } else if (jsonObject.has("position") && jsonObject.has("rotation")) { + type = "camera"; + } else if (jsonObject.has("center") && jsonObject.has("distance")) { + type = "camera_orbit"; + } else if (jsonObject.has("frequencyX") && jsonObject.has("amplitudeX")) { + type = "camera_shake"; + } else if (jsonObject.has("fov")) { + type = "fov"; + } else if (jsonObject.has("tickrate")) { + type = "tickrate"; + } else if (jsonObject.has("time")) { + type = "time"; + } else { + throw new RuntimeException("Unable to determine type of keyframe for: " + jsonObject); + } + Keyframe keyframe = switch (type) { case "camera" -> context.deserialize(json, CameraKeyframe.class); + case "camera_orbit" -> context.deserialize(json, CameraOrbitKeyframe.class); case "fov" -> context.deserialize(json, FOVKeyframe.class); case "tickrate" -> context.deserialize(json, TickrateKeyframe.class); + case "timelapse" -> context.deserialize(json, TimelapseKeyframe.class); case "time" -> context.deserialize(json, TimeOfDayKeyframe.class); + case "camera_shake" -> context.deserialize(json, CameraShakeKeyframe.class); default -> throw new IllegalStateException("Unknown keyframe type: " + type); }; - keyframe.interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + keyframe.interpolationType(context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class)); return keyframe; } @Override - public JsonElement serialize(Keyframe src, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(Keyframe src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject; - if (src instanceof CameraKeyframe cameraKeyframe) { - jsonObject = (JsonObject) context.serialize(cameraKeyframe); - jsonObject.addProperty("type", "camera"); - } else if (src instanceof FOVKeyframe fovKeyframe) { - jsonObject = (JsonObject) context.serialize(fovKeyframe); - jsonObject.addProperty("type", "fov"); - } else if (src instanceof TickrateKeyframe tickrateKeyframe) { - jsonObject = (JsonObject) context.serialize(tickrateKeyframe); - jsonObject.addProperty("type", "tickrate"); - } else if (src instanceof TimeOfDayKeyframe timeOfDayKeyframe) { - jsonObject = (JsonObject) context.serialize(timeOfDayKeyframe); - jsonObject.addProperty("type", "time"); - } else { - throw new IllegalStateException("Unknown keyframe type: " + src.getClass()); + switch (src) { + case CameraKeyframe cameraKeyframe -> { + jsonObject = (JsonObject) context.serialize(cameraKeyframe); + jsonObject.addProperty("type", "camera"); + } + case CameraOrbitKeyframe cameraOrbitKeyframe -> { + jsonObject = (JsonObject) context.serialize(cameraOrbitKeyframe); + jsonObject.addProperty("type", "camera_orbit"); + } + case FOVKeyframe fovKeyframe -> { + jsonObject = (JsonObject) context.serialize(fovKeyframe); + jsonObject.addProperty("type", "fov"); + } + case TickrateKeyframe tickrateKeyframe -> { + jsonObject = (JsonObject) context.serialize(tickrateKeyframe); + jsonObject.addProperty("type", "tickrate"); + } + case TimeOfDayKeyframe timeOfDayKeyframe -> { + jsonObject = (JsonObject) context.serialize(timeOfDayKeyframe); + jsonObject.addProperty("type", "time"); + } + case CameraShakeKeyframe cameraShakeKeyframe -> { + jsonObject = (JsonObject) context.serialize(cameraShakeKeyframe); + jsonObject.addProperty("type", "camera_shake"); + } + default -> throw new IllegalStateException("Unknown keyframe type: " + src.getClass()); } jsonObject.add("interpolation_type", context.serialize(src.interpolationType)); return jsonObject; diff --git a/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java index e75b1d7..9a53d2f 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java @@ -3,9 +3,12 @@ package com.moulberry.flashback.keyframe; public enum KeyframeType { CAMERA("Camera"), + CAMERA_ORBIT("Camera Orbit"), FOV("FOV"), SPEED("Speed"), - TIME_OF_DAY("Time of day"); + TIMELAPSE("Timelapse"), + TIME_OF_DAY("Time of day"), + CAMERA_SHAKE("Camera Shake"); public static final KeyframeType[] KEYFRAME_TYPES = values(); diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java b/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java new file mode 100644 index 0000000..5432395 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/KeyframeHandler.java @@ -0,0 +1,42 @@ +package com.moulberry.flashback.keyframe.handler; + +import com.moulberry.flashback.keyframe.KeyframeType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.phys.Vec3; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +import java.util.EnumSet; + +public interface KeyframeHandler { + + EnumSet supportedKeyframes(); + + default boolean alwaysApplyLastKeyframe() { + return false; + } + + default void applyCameraPosition(Vector3f position, float yaw, float pitch, float roll) { + throw new UnsupportedOperationException(); + } + + default void applyFov(float fov) { + throw new UnsupportedOperationException(); + } + + default void applyTickrate(float tickrate) { + throw new UnsupportedOperationException(); + } + + default void applyTimeOfDay(int timeOfDay) { + throw new UnsupportedOperationException(); + } + + default void applyCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) { + throw new UnsupportedOperationException(); + } + + +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java b/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java new file mode 100644 index 0000000..446ac30 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/MinecraftKeyframeHandler.java @@ -0,0 +1,80 @@ +package com.moulberry.flashback.keyframe.handler; + +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.keyframe.KeyframeType; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +import java.util.EnumSet; + +public class MinecraftKeyframeHandler implements KeyframeHandler { + + private final Minecraft minecraft; + + public MinecraftKeyframeHandler(Minecraft minecraft) { + this.minecraft = minecraft; + } + + @Override + public EnumSet supportedKeyframes() { + return EnumSet.of(KeyframeType.CAMERA, KeyframeType.CAMERA_ORBIT, KeyframeType.FOV, KeyframeType.TIME_OF_DAY, KeyframeType.CAMERA_SHAKE); + } + + @Override + public void applyCameraPosition(Vector3f position, float yaw, float pitch, float roll) { + LocalPlayer player = this.minecraft.player; + if (player != null) { + player.moveTo(position.x, position.y, position.z, yaw, pitch); + + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + if (roll > -0.1 && roll < 0.1) { + editorState.replayVisuals.overrideRoll = false; + editorState.replayVisuals.overrideRollAmount = 0.0f; + } else { + editorState.replayVisuals.overrideRoll = true; + editorState.replayVisuals.overrideRollAmount = roll; + } + } + + player.setDeltaMovement(Vec3.ZERO); + } + } + + @Override + public void applyFov(float fov) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + editorState.replayVisuals.setFov(fov); + } + } + + @Override + public void applyTickrate(float tickrate) { + throw new UnsupportedOperationException(); + } + + @Override + public void applyTimeOfDay(int timeOfDay) { + timeOfDay = timeOfDay % 24000; + if (timeOfDay < 0) { + timeOfDay += 24000; + } + + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + editorState.replayVisuals.overrideTimeOfDay = timeOfDay; + } + } + + @Override + public void applyCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + editorState.replayVisuals.setCameraShake(frequencyX, amplitudeX, frequencyY, amplitudeY); + } + } +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java b/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java new file mode 100644 index 0000000..dde335e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/handler/ReplayServerKeyframeHandler.java @@ -0,0 +1,45 @@ +package com.moulberry.flashback.keyframe.handler; + +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.playback.ReplayServer; + +import java.util.EnumSet; + +public class ReplayServerKeyframeHandler implements KeyframeHandler { + + private final ReplayServer replayServer; + + public ReplayServerKeyframeHandler(ReplayServer replayServer) { + this.replayServer = replayServer; + } + + @Override + public boolean alwaysApplyLastKeyframe() { + return true; + } + + @Override + public EnumSet supportedKeyframes() { + return EnumSet.of(KeyframeType.SPEED, KeyframeType.TIMELAPSE); + } + + @Override + public void applyFov(float fov) { + throw new UnsupportedOperationException(); + } + + @Override + public void applyTickrate(float tickrate) { + this.replayServer.setDesiredTickRate(tickrate, false); + } + + @Override + public void applyTimeOfDay(int timeOfDay) { + throw new UnsupportedOperationException(); + } + + @Override + public void applyCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java index d3f4f2e..ffc7ccf 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java @@ -3,68 +3,125 @@ package com.moulberry.flashback.keyframe.impl; import com.google.gson.*; import com.moulberry.flashback.Interpolation; import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import com.moulberry.flashback.spline.CatmullRom; -import net.minecraft.client.Minecraft; -import net.minecraft.client.player.LocalPlayer; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; -import net.minecraft.world.phys.Vec3; import org.joml.Quaternionf; import org.joml.Vector3f; import java.lang.reflect.Type; -public class CameraKeyframe extends Keyframe { +public class CameraKeyframe extends Keyframe { - private final Vector3f position; - private final Quaternionf quaternion; + public final Vector3f position; + public final Quaternionf quaternion; + public final boolean hasRoll; + + private static Quaternionf getQuaternion(Entity entity) { + Quaternionf quaternionf = new Quaternionf(); + float angleZ = 0.0f; + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideRoll) { + angleZ = (float) Math.toRadians(editorState.replayVisuals.overrideRollAmount); + } + quaternionf = quaternionf.rotationYXZ((float) -Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), -angleZ); + return quaternionf; + } public CameraKeyframe(Entity entity) { - this(entity.position().toVector3f(), new Quaternionf().rotationYXZ((float) Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), 0.0f)); + this(entity.position().toVector3f(), getQuaternion(entity), shouldHaveRoll()); } - public CameraKeyframe(Vector3f position, Quaternionf quaternion) { - super(Minecraft.class); + public CameraKeyframe(Vector3f position, Quaternionf quaternion, boolean hasRoll) { + this(position, quaternion, hasRoll, InterpolationType.DEFAULT); + } + + public CameraKeyframe(Vector3f position, Quaternionf quaternion, boolean hasRoll, InterpolationType interpolationType) { this.position = position; this.quaternion = quaternion; + this.hasRoll = hasRoll; + this.interpolationType(interpolationType); } @Override - public void apply(Minecraft minecraft) { - LocalPlayer player = minecraft.player; - if (player != null) { - Vector3f euler = this.quaternion.getEulerAnglesYXZ(new Vector3f()); - player.moveTo(this.position.x, this.position.y, this.position.z, (float) Mth.wrapDegrees(Math.toDegrees(euler.y)), (float) Mth.wrapDegrees(Math.toDegrees(euler.x))); - player.setDeltaMovement(Vec3.ZERO); + public Keyframe copy() { + return new CameraKeyframe(new Vector3f(this.position), new Quaternionf(this.quaternion), this.hasRoll, this.interpolationType()); + } + + private static boolean shouldHaveRoll() { + EditorState editorState = EditorStateManager.getCurrent(); + return editorState != null && editorState.replayVisuals.overrideRoll && editorState.replayVisuals.overrideRollAmount != 0.0f; + } + + private void apply(KeyframeHandler keyframeHandler, Vector3f position, Quaternionf quaternion, float rollScale) { + Vector3f euler = quaternion.getEulerAnglesYXZ(new Vector3f()); + float yaw = (float) Mth.wrapDegrees(Math.toDegrees(euler.y)); + float pitch = (float) Mth.wrapDegrees(Math.toDegrees(euler.x)); + float roll = (float) Mth.wrapDegrees(Math.toDegrees(euler.z)) * rollScale; + + // Handle singularity + double test = (double)quaternion.y * (double)quaternion.z - (double)quaternion.w * (double)quaternion.x; + final double MIN_TEST = 0.49999; + final double MAX_TEST = 0.499999; + if (test > MIN_TEST) { + float fixedYaw = (float) Mth.wrapDegrees(Math.toDegrees(2 * Math.atan2(quaternion.z, quaternion.w))); + if (test >= MAX_TEST) { + yaw = fixedYaw; + } else { + yaw = yaw + (float)(Mth.wrapDegrees(fixedYaw - yaw) * (test - MIN_TEST) / (MAX_TEST - MIN_TEST)); + } + } else if (test < -MIN_TEST) { + float fixedYaw = (float) Mth.wrapDegrees(Math.toDegrees(-2 * Math.atan2(quaternion.z, quaternion.w))); + if (test <= -MAX_TEST) { + yaw = fixedYaw; + } else { + yaw = yaw + (float)(Mth.wrapDegrees(fixedYaw - yaw) * (test - -MIN_TEST) / (-MAX_TEST - -MIN_TEST)); + } + } + + // Apply position + keyframeHandler.applyCameraPosition(position, -yaw, pitch, -roll); + } + + private static float calculateRollScale(CameraKeyframe left, CameraKeyframe right, float alpha) { + if (left.hasRoll && right.hasRoll) { + return 1.0f; + } else if (left.hasRoll) { + return 1.0f - alpha; + } else if (right.hasRoll) { + return alpha; + } else { + return 0.0f; } } @Override - public void applyInterpolated(Minecraft minecraft, Keyframe genericOther, float amount) { + public void apply(KeyframeHandler keyframeHandler) { + apply(keyframeHandler, this.position, this.quaternion, this.hasRoll ? 1.0f : 0.0f); + } + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe genericOther, float amount) { if (!(genericOther instanceof CameraKeyframe other)) { - this.apply(minecraft); + this.apply(keyframeHandler); return; } - LocalPlayer player = minecraft.player; - if (player != null) { - double x = Interpolation.linear(this.position.x, other.position.x, amount); - double y = Interpolation.linear(this.position.y, other.position.y, amount); - double z = Interpolation.linear(this.position.z, other.position.z, amount); - Quaternionf quaternion = Interpolation.linear(this.quaternion, other.quaternion, amount); - Vector3f euler = quaternion.getEulerAnglesYXZ(new Vector3f()); - player.moveTo(x, y, z, (float) Mth.wrapDegrees(Math.toDegrees(euler.y)), (float) Mth.wrapDegrees(Math.toDegrees(euler.x))); - player.setDeltaMovement(Vec3.ZERO); - } + double x = Interpolation.linear(this.position.x, other.position.x, amount); + double y = Interpolation.linear(this.position.y, other.position.y, amount); + double z = Interpolation.linear(this.position.z, other.position.z, amount); + Quaternionf quaternion = Interpolation.linear(this.quaternion, other.quaternion, amount); + + Vector3f position = new Vector3f((float) x, (float) y, (float) z); + apply(keyframeHandler, position, quaternion, calculateRollScale(this, other, amount)); } @Override - public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { - LocalPlayer player = minecraft.player; - if (player == null) { - return; - } - + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { float time1 = t1 - t0; float time2 = t2 - t0; float time3 = t3 - t0; @@ -84,9 +141,9 @@ public class CameraKeyframe extends Keyframe { ((CameraKeyframe)p3).quaternion, time1, time2, time3, amount); if (lerpAmount >= 0) { - float linearX = (float) Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount); - float linearY = (float) Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount); - float linearZ = (float) Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount); + float linearX = Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount); + float linearY = Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount); + float linearZ = Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount); Quaternionf linearQuaternion = Interpolation.linear(((CameraKeyframe)p1).quaternion, ((CameraKeyframe)p2).quaternion, lerpAmount); @@ -103,12 +160,7 @@ public class CameraKeyframe extends Keyframe { } } - Vector3f euler = rotation.getEulerAnglesYXZ(new Vector3f()); - float yaw = (float) Mth.wrapDegrees(Math.toDegrees(euler.y)); - float pitch = (float) Mth.wrapDegrees(Math.toDegrees(euler.x)); - - player.moveTo(x, y, z, yaw, pitch); - player.setDeltaMovement(Vec3.ZERO); + apply(keyframeHandler, new Vector3f(x, y, z), rotation, calculateRollScale((CameraKeyframe) p1, (CameraKeyframe) p2, amount)); } public static class TypeAdapter implements JsonSerializer, JsonDeserializer { @@ -117,7 +169,9 @@ public class CameraKeyframe extends Keyframe { JsonObject jsonObject = json.getAsJsonObject(); Vector3f position = context.deserialize(jsonObject.get("position"), Vector3f.class); Quaternionf rotation = context.deserialize(jsonObject.get("rotation"), Quaternionf.class); - return new CameraKeyframe(position, rotation); + boolean hasRoll = jsonObject.has("has_roll") && jsonObject.get("has_roll").getAsBoolean(); + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new CameraKeyframe(position, rotation, hasRoll, interpolationType); } @Override @@ -125,6 +179,9 @@ public class CameraKeyframe extends Keyframe { JsonObject jsonObject = new JsonObject(); jsonObject.add("position", context.serialize(src.position)); jsonObject.add("rotation", context.serialize(src.quaternion)); + jsonObject.add("has_roll", context.serialize(src.hasRoll)); + jsonObject.addProperty("type", "camera"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); return jsonObject; } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java new file mode 100644 index 0000000..da65df6 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraOrbitKeyframe.java @@ -0,0 +1,202 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.spline.CatmullRom; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import imgui.ImGui; +import imgui.type.ImFloat; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +import java.lang.reflect.Type; +import java.util.function.Consumer; + +public class CameraOrbitKeyframe extends Keyframe { + + public final Vector3f center; + public float distance; + public float yaw; + public float pitch; + + public CameraOrbitKeyframe(Vector3f center, float distance, float yaw, float pitch) { + this(center, distance, yaw, pitch, InterpolationType.DEFAULT); + } + + public CameraOrbitKeyframe(Vector3f center, float distance, float yaw, float pitch, InterpolationType interpolationType) { + this.center = center; + this.distance = distance; + this.yaw = yaw; + this.pitch = pitch; + this.interpolationType(interpolationType); + } + + @Override + public Keyframe copy() { + return new CameraOrbitKeyframe(new Vector3f(this.center), this.distance, this.yaw, this.pitch, this.interpolationType()); + } + + @Override + public void renderEditKeyframe(Consumer> update) { + float[] center = new float[]{this.center.x, this.center.y, this.center.z}; + if (ImGui.inputFloat3("Position", center)) { + if (center[0] != this.center.x) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.x = center[0]); + } + if (center[1] != this.center.y) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.y = center[1]); + } + if (center[2] != this.center.z) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).center.z = center[2]); + } + } + ImFloat input = new ImFloat(this.distance); + if (ImGui.inputFloat("Distance", input)) { + if (input.get() != this.distance) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).distance = input.get()); + } + } + input.set(this.yaw); + if (ImGui.inputFloat("Yaw", input)) { + if (input.get() != this.yaw) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).yaw = input.get()); + } + } + input.set(this.pitch); + if (ImGui.inputFloat("Pitch", input)) { + if (input.get() != this.pitch) { + update.accept(keyframe -> ((CameraOrbitKeyframe)keyframe).pitch = input.get()); + } + } + } + + private void apply(KeyframeHandler keyframeHandler, Vector3f center, float distance, float yaw, float pitch) { + float pitchRadians = (float) Math.toRadians(pitch); + float yawRadians = (float) Math.toRadians(-yaw); + float cosYaw = Mth.cos(yawRadians); + float sinYaw = Mth.sin(yawRadians); + float cosPitch = Mth.cos(pitchRadians); + float sinPitch = Mth.sin(pitchRadians); + + Vector3f look = new Vector3f(sinYaw * cosPitch, -sinPitch, cosYaw * cosPitch); + Vector3f cameraPosition = new Vector3f(center).sub(look.mul(distance)); + LocalPlayer player = Minecraft.getInstance().player; + if (player != null) { + cameraPosition.y -= player.getEyeHeight(); + } + keyframeHandler.applyCameraPosition(cameraPosition, yaw, pitch, 0.0f); + } + + @Override + public void apply(KeyframeHandler keyframeHandler) { + apply(keyframeHandler, this.center, this.distance, this.yaw, this.pitch); + } + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe genericOther, float amount) { + if (!(genericOther instanceof CameraOrbitKeyframe other)) { + this.apply(keyframeHandler); + return; + } + + double x = Interpolation.linear(this.center.x, other.center.x, amount); + double y = Interpolation.linear(this.center.y, other.center.y, amount); + double z = Interpolation.linear(this.center.z, other.center.z, amount); + float distance = Interpolation.linear(this.distance, other.distance, amount); + float yaw = Interpolation.linear(this.yaw, other.yaw, amount); + float pitch = Interpolation.linear(this.pitch, other.pitch, amount); + + Vector3f center = new Vector3f((float) x, (float) y, (float) z); + apply(keyframeHandler, center, distance, yaw, pitch); + } + + @Override + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + float time1 = t1 - t0; + float time2 = t2 - t0; + float time3 = t3 - t0; + + // Calculate position + Vector3f position = CatmullRom.position(this.center, + ((CameraOrbitKeyframe)p1).center, ((CameraOrbitKeyframe)p2).center, + ((CameraOrbitKeyframe)p3).center, time1, time2, time3, amount); + + float x = position.x; + float y = position.y; + float z = position.z; + float distance = CatmullRom.value(this.distance, ((CameraOrbitKeyframe)p1).distance, ((CameraOrbitKeyframe)p2).distance, + ((CameraOrbitKeyframe)p3).distance, time1, time2, time3, amount); + float yaw = CatmullRom.value(this.yaw, ((CameraOrbitKeyframe)p1).yaw, ((CameraOrbitKeyframe)p2).yaw, + ((CameraOrbitKeyframe)p3).yaw, time1, time2, time3, amount); + float pitch = CatmullRom.value(this.pitch, ((CameraOrbitKeyframe)p1).pitch, ((CameraOrbitKeyframe)p2).pitch, + ((CameraOrbitKeyframe)p3).pitch, time1, time2, time3, amount); + + if (lerpAmount >= 0) { + float linearX = Interpolation.linear(((CameraOrbitKeyframe)p1).center.x, ((CameraOrbitKeyframe)p2).center.x, lerpAmount); + float linearY = Interpolation.linear(((CameraOrbitKeyframe)p1).center.y, ((CameraOrbitKeyframe)p2).center.y, lerpAmount); + float linearZ = Interpolation.linear(((CameraOrbitKeyframe)p1).center.z, ((CameraOrbitKeyframe)p2).center.z, lerpAmount); + float linearDistance = Interpolation.linear(((CameraOrbitKeyframe)p1).distance, ((CameraOrbitKeyframe)p2).distance, amount); + float linearYaw = Interpolation.linear(((CameraOrbitKeyframe)p1).yaw, ((CameraOrbitKeyframe)p2).yaw, amount); + float linearPitch = Interpolation.linear(((CameraOrbitKeyframe)p1).pitch, ((CameraOrbitKeyframe)p2).pitch, amount); + + if (lerpFromRight) { + x = Interpolation.linear(x, linearX, amount); + y = Interpolation.linear(y, linearY, amount); + z = Interpolation.linear(z, linearZ, amount); + distance = Interpolation.linear(distance, linearDistance, amount); + yaw = Interpolation.linear(yaw, linearYaw, amount); + pitch = Interpolation.linear(pitch, linearPitch, amount); + } else { + x = Interpolation.linear(linearX, x, amount); + y = Interpolation.linear(linearY, y, amount); + z = Interpolation.linear(linearZ, z, amount); + distance = Interpolation.linear(linearDistance, distance, amount); + yaw = Interpolation.linear(linearYaw, yaw, amount); + pitch = Interpolation.linear(linearPitch, pitch, amount); + } + } + + apply(keyframeHandler, new Vector3f(x, y, z), distance, yaw, pitch); + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public CameraOrbitKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + Vector3f center = context.deserialize(jsonObject.get("center"), Vector3f.class); + float distance = jsonObject.get("distance").getAsFloat(); + float yaw = jsonObject.get("yaw").getAsFloat(); + float pitch = jsonObject.get("pitch").getAsFloat(); + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new CameraOrbitKeyframe(center, distance, yaw, pitch, interpolationType); + } + + @Override + public JsonElement serialize(CameraOrbitKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.add("center", context.serialize(src.center)); + jsonObject.addProperty("distance", src.distance); + jsonObject.addProperty("yaw", src.yaw); + jsonObject.addProperty("pitch", src.pitch); + jsonObject.addProperty("type", "camera_orbit"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); + return jsonObject; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java new file mode 100644 index 0000000..cd5bf23 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraShakeKeyframe.java @@ -0,0 +1,124 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.moulberry.flashback.Interpolation; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.spline.CatmullRom; + +import java.lang.reflect.Type; + +public class CameraShakeKeyframe extends Keyframe { + + private final float frequencyX; + private final float amplitudeX; + private final float frequencyY; + private final float amplitudeY; + + public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) { + this(frequencyX, amplitudeX, frequencyY, amplitudeY, InterpolationType.DEFAULT); + } + + public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, InterpolationType interpolationType) { + this.frequencyX = frequencyX; + this.amplitudeX = amplitudeX; + this.frequencyY = frequencyY; + this.amplitudeY = amplitudeY; + this.interpolationType(interpolationType); + } + + @Override + public Keyframe copy() { + return new CameraShakeKeyframe(this.frequencyX, this.amplitudeX, this.frequencyY, this.amplitudeY, this.interpolationType()); + } + + @Override + public void apply(KeyframeHandler keyframeHandler) { + keyframeHandler.applyCameraShake(this.frequencyX, this.amplitudeX, this.frequencyY, this.amplitudeY); + } + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) { + if (!(otherGeneric instanceof CameraShakeKeyframe other)) { + this.apply(keyframeHandler); + return; + } + + float frequencyX = Interpolation.linear(this.frequencyX, other.frequencyX, amount); + float amplitudeX = Interpolation.linear(this.amplitudeX, other.amplitudeX, amount); + float frequencyY = Interpolation.linear(this.frequencyY, other.frequencyY, amount); + float amplitudeY = Interpolation.linear(this.amplitudeY, other.amplitudeY, amount); + + keyframeHandler.applyCameraShake(frequencyX, amplitudeX, frequencyY, amplitudeY); + } + + @Override + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + float time1 = t1 - t0; + float time2 = t2 - t0; + float time3 = t3 - t0; + + float frequencyX = CatmullRom.value(this.frequencyX, ((CameraShakeKeyframe)p1).frequencyX, + ((CameraShakeKeyframe)p2).frequencyX, ((CameraShakeKeyframe)p3).frequencyX, time1, time2, time3, amount); + float amplitudeX = CatmullRom.value(this.amplitudeX, ((CameraShakeKeyframe)p1).amplitudeX, + ((CameraShakeKeyframe)p2).amplitudeX, ((CameraShakeKeyframe)p3).amplitudeX, time1, time2, time3, amount); + float frequencyY = CatmullRom.value(this.frequencyY, ((CameraShakeKeyframe)p1).frequencyY, + ((CameraShakeKeyframe)p2).frequencyY, ((CameraShakeKeyframe)p3).frequencyY, time1, time2, time3, amount); + float amplitudeY = CatmullRom.value(this.amplitudeY, ((CameraShakeKeyframe)p1).amplitudeY, + ((CameraShakeKeyframe)p2).amplitudeY, ((CameraShakeKeyframe)p3).amplitudeY, time1, time2, time3, amount); + + if (lerpAmount >= 0) { + float linearFrequencyX = Interpolation.linear(((CameraShakeKeyframe)p1).frequencyX, ((CameraShakeKeyframe)p2).frequencyX, lerpAmount); + float linearAmplitudeX = Interpolation.linear(((CameraShakeKeyframe)p1).amplitudeX, ((CameraShakeKeyframe)p2).amplitudeX, lerpAmount); + float linearFrequencyY = Interpolation.linear(((CameraShakeKeyframe)p1).frequencyY, ((CameraShakeKeyframe)p2).frequencyY, lerpAmount); + float linearAmplitudeY = Interpolation.linear(((CameraShakeKeyframe)p1).amplitudeY, ((CameraShakeKeyframe)p2).amplitudeY, lerpAmount); + + if (lerpFromRight) { + frequencyX = Interpolation.linear(frequencyX, linearFrequencyX, amount); + amplitudeX = Interpolation.linear(amplitudeX, linearAmplitudeX, amount); + frequencyY = Interpolation.linear(frequencyY, linearFrequencyY, amount); + amplitudeY = Interpolation.linear(amplitudeY, linearAmplitudeY, amount); + } else { + frequencyX = Interpolation.linear(linearFrequencyX, frequencyX, amount); + amplitudeX = Interpolation.linear(linearAmplitudeX, amplitudeX, amount); + frequencyY = Interpolation.linear(linearFrequencyY, frequencyY, amount); + amplitudeY = Interpolation.linear(linearAmplitudeY, amplitudeY, amount); + } + } + + keyframeHandler.applyCameraShake(frequencyX, amplitudeX, frequencyY, amplitudeY); + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public CameraShakeKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + float frequencyX = jsonObject.get("frequencyX").getAsFloat(); + float amplitudeX = jsonObject.get("amplitudeX").getAsFloat(); + float frequencyY = jsonObject.get("frequencyY").getAsFloat(); + float amplitudeY = jsonObject.get("amplitudeY").getAsFloat(); + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new CameraShakeKeyframe(frequencyX, amplitudeX, frequencyY, amplitudeY, interpolationType); + } + + @Override + public JsonElement serialize(CameraShakeKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("frequencyX", src.frequencyX); + jsonObject.addProperty("amplitudeX", src.amplitudeX); + jsonObject.addProperty("frequencyY", src.frequencyY); + jsonObject.addProperty("amplitudeY", src.amplitudeY); + jsonObject.addProperty("type", "camera_shake"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); + return jsonObject; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java index e21e368..3a19a6a 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java @@ -2,79 +2,105 @@ package com.moulberry.flashback.keyframe.impl; import com.google.gson.*; import com.moulberry.flashback.Interpolation; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.Utils; import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import com.moulberry.flashback.spline.CatmullRom; -import net.minecraft.client.Minecraft; -import net.minecraft.client.player.LocalPlayer; +import imgui.ImGui; import java.lang.reflect.Type; +import java.util.function.Consumer; -public class FOVKeyframe extends Keyframe { +public class FOVKeyframe extends Keyframe { - private final int fov; + public float fov; - public FOVKeyframe(int fov) { - super(Minecraft.class); + public FOVKeyframe(float fov) { + this(fov, InterpolationType.DEFAULT); + } + + public FOVKeyframe(float fov, InterpolationType interpolationType) { this.fov = fov; + this.interpolationType(interpolationType); } @Override - public void apply(Minecraft minecraft) { - ReplayVisuals.setFov(fov); + public Keyframe copy() { + return new FOVKeyframe(this.fov, this.interpolationType()); } @Override - public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) { + public void renderEditKeyframe(Consumer> update) { + ImGui.setNextItemWidth(160); + float[] input = new float[]{this.fov}; + if (ImGui.sliderFloat("FOV", input, 1.0f, 110.0f, "%.1f")) { + if (this.fov != input[0]) { + update.accept(keyframe -> ((FOVKeyframe)keyframe).fov = input[0]); + } + } + } + + @Override + public void apply(KeyframeHandler keyframeHandler) { + keyframeHandler.applyFov(this.fov); + } + + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) { if (!(otherGeneric instanceof FOVKeyframe other)) { - this.apply(minecraft); + this.apply(keyframeHandler); return; } - float fov = Interpolation.linear(this.fov, other.fov, amount); - ReplayVisuals.setFov(fov); + float thisFocalLength = Utils.fovToFocalLength(this.fov); + float otherFocalLength = Utils.fovToFocalLength(other.fov); + float focalLength = Interpolation.linear(thisFocalLength, otherFocalLength, amount); + keyframeHandler.applyFov(Utils.focalLengthToFov(focalLength)); } @Override - public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { - LocalPlayer player = minecraft.player; - if (player == null) { - return; - } - + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { float time1 = t1 - t0; float time2 = t2 - t0; float time3 = t3 - t0; - float fov = CatmullRom.value(this.fov, - ((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov, - ((FOVKeyframe)p3).fov, time1, time2, time3, amount); + float f0 = Utils.fovToFocalLength(this.fov); + float f1 = Utils.fovToFocalLength(((FOVKeyframe)p1).fov); + float f2 = Utils.fovToFocalLength(((FOVKeyframe)p2).fov); + float f3 = Utils.fovToFocalLength(((FOVKeyframe)p3).fov); + + float focalLength = CatmullRom.value(f0, f1, f2, f3, time1, time2, time3, amount); if (lerpAmount >= 0) { - float linearFov = Interpolation.linear(((FOVKeyframe)p1).fov, ((FOVKeyframe)p2).fov, lerpAmount); + float linearFocalLength = Interpolation.linear(f1, f2, lerpAmount); if (lerpFromRight) { - fov = Interpolation.linear(fov, linearFov, amount); + focalLength = Interpolation.linear(focalLength, linearFocalLength, amount); } else { - fov = Interpolation.linear(linearFov, fov, amount); + focalLength = Interpolation.linear(linearFocalLength, focalLength, amount); } } - ReplayVisuals.setFov(fov); + keyframeHandler.applyFov(Utils.focalLengthToFov(focalLength)); } public static class TypeAdapter implements JsonSerializer, JsonDeserializer { @Override public FOVKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); - int fov = jsonObject.get("fov").getAsInt(); - return new FOVKeyframe(fov); + float fov = jsonObject.get("fov").getAsFloat(); + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new FOVKeyframe(fov, interpolationType); } @Override public JsonElement serialize(FOVKeyframe src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("fov", src.fov); + jsonObject.addProperty("type", "fov"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); return jsonObject; } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java index 7f08476..90adb9b 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java @@ -2,40 +2,63 @@ package com.moulberry.flashback.keyframe.impl; import com.google.gson.*; import com.moulberry.flashback.Interpolation; -import com.moulberry.flashback.ReplayVisuals; import com.moulberry.flashback.keyframe.Keyframe; -import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import com.moulberry.flashback.spline.CatmullRom; +import imgui.ImGui; import java.lang.reflect.Type; +import java.util.function.Consumer; -public class TickrateKeyframe extends Keyframe { +public class TickrateKeyframe extends Keyframe { private float tickrate; public TickrateKeyframe(float tickrate) { - super(ReplayServer.class); + this(tickrate, InterpolationType.DEFAULT); + } + + public TickrateKeyframe(float tickrate, InterpolationType interpolationType) { this.tickrate = tickrate; + this.interpolationType(interpolationType); } @Override - public void apply(ReplayServer replayServer) { - replayServer.desiredTickRate = this.tickrate; + public Keyframe copy() { + return new TickrateKeyframe(this.tickrate, this.interpolationType()); } @Override - public void applyInterpolated(ReplayServer replayServer, Keyframe otherGeneric, float amount) { + public void renderEditKeyframe(Consumer> update) { + ImGui.setNextItemWidth(160); + float[] input = new float[]{this.tickrate/20f}; + if (ImGui.sliderFloat("Speed", input, 0.1f, 10.0f)) { + float tickrate = input[0]*20f; + if (this.tickrate != tickrate) { + update.accept(keyframe -> ((TickrateKeyframe)keyframe).tickrate = tickrate); + } + } + } + + @Override + public void apply(KeyframeHandler keyframeHandler) { + keyframeHandler.applyTickrate(this.tickrate); + } + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) { if (!(otherGeneric instanceof TickrateKeyframe other)) { - this.apply(replayServer); + this.apply(keyframeHandler); return; } float tickrate = Interpolation.linear(this.tickrate, other.tickrate, amount); - replayServer.desiredTickRate = tickrate; + keyframeHandler.applyTickrate(tickrate); } @Override - public void applyInterpolatedSmooth(ReplayServer replayServer, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { float time1 = t1 - t0; float time2 = t2 - t0; float time3 = t3 - t0; @@ -54,7 +77,7 @@ public class TickrateKeyframe extends Keyframe { } } - replayServer.desiredTickRate = tickrate; + keyframeHandler.applyTickrate(tickrate); } public static class TypeAdapter implements JsonSerializer, JsonDeserializer { @@ -62,13 +85,16 @@ public class TickrateKeyframe extends Keyframe { public TickrateKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); float tickrate = jsonObject.get("tickrate").getAsFloat(); - return new TickrateKeyframe(tickrate); + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new TickrateKeyframe(tickrate, interpolationType); } @Override public JsonElement serialize(TickrateKeyframe src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("tickrate", src.tickrate); + jsonObject.addProperty("type", "tickrate"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); return jsonObject; } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java index 1a6227b..3e05c64 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java @@ -2,52 +2,63 @@ package com.moulberry.flashback.keyframe.impl; import com.google.gson.*; import com.moulberry.flashback.Interpolation; -import com.moulberry.flashback.ReplayVisuals; import com.moulberry.flashback.keyframe.Keyframe; -import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; import com.moulberry.flashback.spline.CatmullRom; -import net.minecraft.client.Minecraft; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.GameRules; +import imgui.ImGui; +import imgui.type.ImInt; import java.lang.reflect.Type; +import java.util.function.Consumer; -public class TimeOfDayKeyframe extends Keyframe { +public class TimeOfDayKeyframe extends Keyframe { - private final int time; + public int time; public TimeOfDayKeyframe(int time) { - super(Minecraft.class); + this(time, InterpolationType.DEFAULT); + } + + public TimeOfDayKeyframe(int time, InterpolationType interpolationType) { this.time = time; + this.interpolationType(interpolationType); } - private void setTime(Minecraft minecraft, int time) { - time = time % 24000; - if (time < 0) { - time += 24000; + @Override + public Keyframe copy() { + return new TimeOfDayKeyframe(this.time, this.interpolationType()); + } + + @Override + public void renderEditKeyframe(Consumer> update) { + ImGui.setNextItemWidth(160); + ImInt input = new ImInt(this.time); + if (ImGui.inputInt("Time", input, 0)) { + if (this.time != input.get()) { + update.accept(keyframe -> ((TimeOfDayKeyframe)keyframe).time = input.get()); + } } - - ReplayVisuals.overrideTimeOfDay = time; } @Override - public void apply(Minecraft minecraft) { - this.setTime(minecraft, this.time); + public void apply(KeyframeHandler keyframeHandler) { + keyframeHandler.applyTimeOfDay(this.time); } @Override - public void applyInterpolated(Minecraft minecraft, Keyframe otherGeneric, float amount) { + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) { if (!(otherGeneric instanceof TimeOfDayKeyframe other)) { - this.apply(minecraft); + this.apply(keyframeHandler); return; } int time = Math.round(Interpolation.linear(this.time, other.time, amount)); - this.setTime(minecraft, time); + keyframeHandler.applyTimeOfDay(time); } @Override - public void applyInterpolatedSmooth(Minecraft minecraft, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { float time1 = t1 - t0; float time2 = t2 - t0; float time3 = t3 - t0; @@ -66,7 +77,7 @@ public class TimeOfDayKeyframe extends Keyframe { } } - this.setTime(minecraft, Math.round(timeOfDay)); + keyframeHandler.applyTimeOfDay(Math.round(timeOfDay)); } @@ -75,13 +86,16 @@ public class TimeOfDayKeyframe extends Keyframe { public TimeOfDayKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); int timeOfDay = jsonObject.get("time").getAsInt(); - return new TimeOfDayKeyframe(timeOfDay); + InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return new TimeOfDayKeyframe(timeOfDay, interpolationType); } @Override public JsonElement serialize(TimeOfDayKeyframe src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("time", src.time); + jsonObject.addProperty("type", "time"); + jsonObject.add("interpolation_type", context.serialize(src.interpolationType())); return jsonObject; } } diff --git a/src/main/java/com/moulberry/flashback/keyframe/impl/TimelapseKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TimelapseKeyframe.java new file mode 100644 index 0000000..2ea0fac --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TimelapseKeyframe.java @@ -0,0 +1,87 @@ +package com.moulberry.flashback.keyframe.impl; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.moulberry.flashback.Utils; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.interpolation.InterpolationType; +import imgui.ImGui; +import imgui.type.ImString; + +import java.lang.reflect.Type; +import java.util.function.Consumer; + +public class TimelapseKeyframe extends Keyframe { + + public int ticks; + + private final ImString timelapseKeyframeInput; + + public TimelapseKeyframe(int ticks) { + this.ticks = ticks; + this.timelapseKeyframeInput = ImGuiHelper.createResizableImString(Utils.timeToString(this.ticks)); + this.timelapseKeyframeInput.inputData.allowedChars = "0123456789tsmh"; + this.interpolationType(InterpolationType.LINEAR); + } + + @Override + public Keyframe copy() { + return new TimelapseKeyframe(this.ticks); + } + + @Override + public InterpolationType interpolationType() { + return InterpolationType.LINEAR; + } + + @Override + public void renderEditKeyframe(Consumer> update) { + ImGui.setNextItemWidth(160); + ImGui.inputText("Time", timelapseKeyframeInput); + if (ImGui.isItemDeactivatedAfterEdit()) { + int ticks = Utils.stringToTime(timelapseKeyframeInput.get()); + if (this.ticks != ticks) { + update.accept(keyframe -> ((TimelapseKeyframe)keyframe).ticks = ticks); + } + } + } + + @Override + public void apply(KeyframeHandler keyframeHandler) { + throw new UnsupportedOperationException(); + } + + @Override + public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) { + throw new UnsupportedOperationException(); + } + + @Override + public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) { + throw new UnsupportedOperationException(); + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public TimelapseKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + int ticks = jsonObject.get("ticks").getAsInt(); + return new TimelapseKeyframe(ticks); + } + + @Override + public JsonElement serialize(TimelapseKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("ticks", src.ticks); + jsonObject.addProperty("type", "timelapse"); + return jsonObject; + } + } +} diff --git a/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java b/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java index f6676e6..fb54d25 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java @@ -11,6 +11,8 @@ public enum InterpolationType { EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE), HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD); + public static InterpolationType DEFAULT = SMOOTH; + public static final InterpolationType[] INTERPOLATION_TYPES = values(); public static String[] NAMES = new String[] { diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java b/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java index 2de1b5a..7ebf7ad 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java @@ -16,7 +16,7 @@ public class MixinDebugScreenOverlay { @Inject(method = "render", at = @At("HEAD"), cancellable = true) public void render(GuiGraphics guiGraphics, CallbackInfo ci) { - if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) { + if (Flashback.isExporting()) { ci.cancel(); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java index 801edfa..a224696 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java @@ -5,7 +5,10 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.exporting.PerfectFrames; import it.unimi.dsi.fastutil.objects.ObjectArrayList; @@ -40,6 +43,18 @@ public abstract class MixinLevelRenderer { @Shadow @Final public SectionOcclusionGraph sectionOcclusionGraph; + @Shadow + private int ticks; + + @Inject(method = "tick", at = @At("HEAD"), cancellable = true) + public void tick(CallbackInfo ci) { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null) { + this.ticks = replayServer.getReplayTick(); + ci.cancel(); + } + } + @Inject(method = "renderLevel", at = @At("HEAD")) public void renderLevel(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f projection, CallbackInfo ci) { ReplayUI.lastProjectionMatrix = projection; @@ -48,49 +63,56 @@ public abstract class MixinLevelRenderer { @Inject(method = "renderSectionLayer", at = @At("HEAD"), cancellable = true) public void renderSectionLayer(RenderType renderType, double d, double e, double f, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { - if (!ReplayVisuals.renderBlocks) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.renderBlocks) { ci.cancel(); } } @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER)) public void renderLevel_levelFogColor(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { - if (!ReplayVisuals.renderSky) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.renderSky) { RenderSystem.clearColor(0.0f, 1.0f, 0.0f, 0.0F); } } @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;render(Lnet/minecraft/world/level/block/entity/BlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V")) public boolean renderLevel_renderBlockEntity(BlockEntityRenderDispatcher instance, BlockEntity blockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource) { - return ReplayVisuals.renderBlocks; + EditorState editorState = EditorStateManager.getCurrent(); + return editorState == null || editorState.replayVisuals.renderBlocks; } @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V")) public boolean renderLevel_renderEntity(LevelRenderer instance, Entity entity, double d, double e, double f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource) { + EditorState editorState = EditorStateManager.getCurrent(); if (entity instanceof Player) { - return ReplayVisuals.renderPlayers; + return editorState == null || editorState.replayVisuals.renderPlayers; } else { - return ReplayVisuals.renderEntities; + return editorState == null || editorState.replayVisuals.renderEntities; } } @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;")) public CloudStatus renderLevel_getCloudsType(Options instance, Operation original) { - if (ReplayVisuals.renderSky) { - return original.call(instance); - } else { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.renderSky) { return CloudStatus.OFF; + } else { + return original.call(instance); } } @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V")) public boolean renderLevel_renderParticles(ParticleEngine instance, LightTexture lightTexture, Camera camera, float f) { - return ReplayVisuals.renderParticles; + EditorState editorState = EditorStateManager.getCurrent(); + return editorState == null || editorState.replayVisuals.renderParticles; } @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSky(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FLnet/minecraft/client/Camera;ZLjava/lang/Runnable;)V")) public boolean renderLevel_renderSky(LevelRenderer instance, Matrix4f matrix4f, Matrix4f matrix4f2, float f, Camera camera, boolean bl, Runnable runnable) { - return ReplayVisuals.renderSky; + EditorState editorState = EditorStateManager.getCurrent(); + return editorState == null || editorState.replayVisuals.renderSky; } @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V")) diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java index a2b9e5a..39815f4 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java @@ -5,9 +5,12 @@ import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; import com.mojang.blaze3d.systems.RenderSystem; import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.configuration.FlashbackConfig; +import com.moulberry.flashback.exporting.ExportJob; +import com.moulberry.flashback.exporting.ExportJobQueue; +import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.exporting.PerfectFrames; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.ext.MinecraftExt; @@ -63,6 +66,8 @@ import java.time.Instant; import java.util.Queue; import java.util.UUID; import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @Mixin(Minecraft.class) @@ -129,7 +134,9 @@ public abstract class MixinMinecraft implements MinecraftExt { @Final public ParticleEngine particleEngine; - @Shadow @Final public DeltaTracker.Timer timer; + @Shadow + @Nullable + public Entity cameraEntity; @Inject(method="", at=@At("RETURN")) public void init(GameConfig gameConfig, CallbackInfo ci) { @@ -145,7 +152,8 @@ public abstract class MixinMinecraft implements MinecraftExt { @Inject(method = "renderNames", at = @At("HEAD"), cancellable = true) private static void renderNames(CallbackInfoReturnable cir) { - if (!ReplayVisuals.renderNametags) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.renderNametags) { cir.setReturnValue(false); } } @@ -165,7 +173,7 @@ public abstract class MixinMinecraft implements MinecraftExt { Flashback.RECORDER.endTick(false); } - EditorStateCache.saveIfNeeded(); + EditorStateManager.saveIfNeeded(); ReplayServer replayServer = Flashback.getReplayServer(); @@ -173,63 +181,11 @@ public abstract class MixinMinecraft implements MinecraftExt { if (inReplay != inReplayLast) { inReplayLast = inReplay; if (inReplay) { - ReplayVisuals.setupReplay(); Minecraft.getInstance().options.hideGui = false; } else { - ReplayVisuals.disable(); - EditorStateCache.reset(); + EditorStateManager.reset(); } } - - if (inReplay && ReplayVisuals.forceEntityLerpTicks > 0) { - ReplayVisuals.forceEntityLerpTicks -= 1; - if (replayServer.replayPaused && this.level != null && !this.level.tickRateManager().runsNormally()) { - for (Entity entity : this.level.entitiesForRendering()) { - if (entity == this.player) { - continue; - } - if (entity instanceof LivingEntity livingEntity) { - if (livingEntity.lerpSteps > 0) { - livingEntity.lerpPositionAndRotationStep(livingEntity.lerpSteps, livingEntity.lerpTargetX(), - livingEntity.lerpTargetY(), livingEntity.lerpTargetZ(), livingEntity.lerpTargetYRot(), livingEntity.lerpTargetXRot()); - --livingEntity.lerpSteps; - } - if (livingEntity.lerpHeadSteps > 0) { - livingEntity.lerpHeadRotationStep(livingEntity.lerpHeadSteps, livingEntity.lerpYHeadRot); - --livingEntity.lerpHeadSteps; - } - livingEntity.setOldPosAndRot(); - livingEntity.tickHeadTurn(livingEntity.yBodyRot, 0.0f); - } else { - entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), - entity.lerpTargetYRot(), entity.lerpTargetXRot()); - } - if (entity.isPassenger()) { - entity.setDeltaMovement(Vec3.ZERO); - entity.getVehicle().positionRider(entity); - } - } - } - } - } - - @Unique - private volatile boolean forceClientTick = false; - - @Override - public void flashback$forceClientTick() { - this.forceClientTick = true; - } - - @WrapOperation(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/DeltaTracker$Timer;advanceTime(JZ)I")) - public int runTick_advanceTime(DeltaTracker.Timer instance, long l, boolean runTick, Operation original) { - int ticks = original.call(instance, l, runTick); - if (this.forceClientTick) { - this.forceClientTick = false; - this.particleEngine.clearParticles(); - return Math.max(1, ticks); - } - return ticks; } @Inject(method = "getTickTargetMillis", at = @At("HEAD"), cancellable = true) @@ -249,8 +205,27 @@ public abstract class MixinMinecraft implements MinecraftExt { @Unique private final DeltaTracker.Timer localPlayerTimer = new DeltaTracker.Timer(20.0f, 0, FloatUnaryOperator.identity()); + @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At("HEAD")) + public void disconnect(Screen screen, boolean isTransferring, CallbackInfo ci) { + try { + if (Flashback.getConfig().automaticallyFinish && Flashback.RECORDER != null && !isTransferring) { + Flashback.finishRecordingReplay(); + } + } catch (Exception e) { + Flashback.LOGGER.error("Failed to finish replay on disconnect", e); + } + } + @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runAllTasks()V", shift = At.Shift.AFTER)) public void runTick_runAllTasks(boolean runTick, CallbackInfo ci) { + if (ExportJobQueue.drainingQueue) { + if (ExportJobQueue.queuedJobs.isEmpty()) { + ExportJobQueue.drainingQueue = false; + } else if (Flashback.EXPORT_JOB == null) { + Flashback.EXPORT_JOB = new ExportJob(ExportJobQueue.queuedJobs.removeFirst()); + } + } + if (Flashback.EXPORT_JOB != null && !ReplayUI.isActive()) { try { PerfectFrames.enable(); @@ -266,18 +241,26 @@ public abstract class MixinMinecraft implements MinecraftExt { if (this.level != null && this.player != null && !this.player.isPassenger() && !this.player.isRemoved()) { localPlayerTicks = Math.min(10, localPlayerTicks); for (int i = 0; i < localPlayerTicks; i++) { - this.level.tickNonPassenger(this.player); + this.level.guardEntityTick(this.level::tickNonPassenger, this.player); } } } } @Override - public float flashback$getLocalPlayerPartialTick() { - if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) { - return this.timer.getGameTimeDeltaPartialTick(true); + public float flashback$getLocalPlayerPartialTick(float originalPartialTick) { + if (Flashback.isExporting() || this.cameraEntity != this.player) { + return originalPartialTick; } - return localPlayerTimer.getGameTimeDeltaPartialTick(true); + return this.localPlayerTimer.getGameTimeDeltaPartialTick(true); + } + + @Unique + private final AtomicBoolean applyKeyframes = new AtomicBoolean(false); + + @Override + public void flashback$applyKeyframes() { + this.applyKeyframes.set(true); } @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", ordinal = 1), cancellable = true) @@ -287,9 +270,10 @@ public abstract class MixinMinecraft implements MinecraftExt { return; } - if (!replayServer.replayPaused) { - EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier); - editorState.applyKeyframes((Minecraft) (Object) this, replayServer.getPartialReplayTick()); + boolean forceApplyKeyframes = this.applyKeyframes.compareAndSet(true, false); + if (!replayServer.replayPaused || forceApplyKeyframes) { + EditorState editorState = EditorStateManager.get(replayServer.getMetadata().replayIdentifier); + editorState.applyKeyframes(new MinecraftKeyframeHandler((Minecraft) (Object) this), replayServer.getPartialReplayTick()); } if (!replayServer.doClientRendering()) { ci.cancel(); diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java b/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java index 5c1ec7d..f40298d 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java @@ -1,5 +1,6 @@ package com.moulberry.flashback.mixin; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.MouseHandler; @@ -16,17 +17,23 @@ public class MixinMouseHandler { public void isMouseGrabbed(CallbackInfoReturnable cir) { if (ReplayUI.isActive()) { cir.setReturnValue(ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME); + } else if (Flashback.isExporting()) { + cir.setReturnValue(false); } } @Inject(method = "grabMouse", at=@At("HEAD"), cancellable = true) public void grabMouse(CallbackInfo ci) { - if (ReplayUI.isActive()) ci.cancel(); + if (ReplayUI.isActive() || Flashback.isExporting()) { + ci.cancel(); + } } @Inject(method = "releaseMouse", at=@At("HEAD"), cancellable = true) public void releaseMouse(CallbackInfo ci) { - if (ReplayUI.isActive()) ci.cancel(); + if (ReplayUI.isActive()) { + ci.cancel(); + } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java index 0df649e..776de11 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java @@ -3,26 +3,22 @@ package com.moulberry.flashback.mixin; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.GlStateManager; -import com.moulberry.flashback.ReplayVisuals; -import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.Minecraft; +import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(value = RenderTarget.class, priority = 1100) public class MixinRenderTarget { @WrapOperation(method = "_blitToScreen", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_viewport(IIII)V", remap = false)) public void blitToScreenViewport(int left, int bottom, int width, int height, Operation original) { - if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { + if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.shouldModifyViewport()) { ReplayUI.setupMainViewport(); } else { original.call(left, bottom, width, height); } } - } diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java b/src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java index 32b57f6..dc3fa30 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java @@ -1,11 +1,15 @@ package com.moulberry.flashback.mixin; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; import net.minecraft.server.level.ThreadedLevelLightEngine; import net.minecraft.world.level.chunk.LightChunkGetter; import net.minecraft.world.level.lighting.LevelLightEngine; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; @Mixin(ThreadedLevelLightEngine.class) public abstract class MixinThreadedLevelLightEngine extends LevelLightEngine implements ThreadedLevelLightEngineExt { @@ -21,4 +25,19 @@ public abstract class MixinThreadedLevelLightEngine extends LevelLightEngine imp public void flashback$submitPost(int x, int z, Runnable runnable) { this.addTask(x, z, ThreadedLevelLightEngine.TaskType.POST_UPDATE, runnable); } + + @WrapOperation(method = "runUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/lighting/LevelLightEngine;runLightUpdates()I")) + public int runUpdate_runLightUpdates(ThreadedLevelLightEngine instance, Operation original) { + if (Flashback.isInReplay()) { + try { + return original.call(instance); + } catch (Exception e) { + Flashback.LOGGER.error("Exception occurred while processing light updates", e); + return 0; + } + } else { + return original.call(instance); + } + } + } diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinWindow.java b/src/main/java/com/moulberry/flashback/mixin/MixinWindow.java index d986ce2..9ccef50 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinWindow.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinWindow.java @@ -2,13 +2,14 @@ package com.moulberry.flashback.mixin; import com.mojang.blaze3d.platform.Window; import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.visuals.ReplayVisuals; import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.editor.ui.ReplayUI; import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -36,12 +37,22 @@ public abstract class MixinWindow { @Final private long window; + @Unique + private float calculateWidthScaleFactor() { + return Math.max(1/8f, Math.min(8f, (float) this.framebufferWidth / this.width)); + } + + @Unique + private float calculateHeightScaleFactor() { + return Math.max(1/8f, Math.min(8f, (float) this.framebufferHeight / this.height)); + } + @Inject(method = "getWidth", at=@At("HEAD"), cancellable = true) public void getWidth(CallbackInfoReturnable cir) { if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) { cir.setReturnValue(Flashback.EXPORT_JOB.getWidth()); - } else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { - cir.setReturnValue(ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width)); + } else if (ReplayUI.shouldModifyViewport()) { + cir.setReturnValue(ReplayUI.getNewGameWidth(this.calculateWidthScaleFactor())); } } @@ -49,49 +60,29 @@ public abstract class MixinWindow { public void getHeight(CallbackInfoReturnable cir) { if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) { cir.setReturnValue(Flashback.EXPORT_JOB.getHeight()); - } else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { - cir.setReturnValue(ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height)); + } else if (ReplayUI.shouldModifyViewport()) { + cir.setReturnValue(ReplayUI.getNewGameHeight(this.calculateHeightScaleFactor())); } } @Inject(method = "getScreenWidth", at=@At("HEAD"), cancellable = true) public void getScreenWidth(CallbackInfoReturnable cir) { - if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { + if (ReplayUI.shouldModifyViewport()) { cir.setReturnValue(ReplayUI.getNewGameWidth(1)); } } @Inject(method = "getScreenHeight", at=@At("HEAD"), cancellable = true) public void getScreenHeight(CallbackInfoReturnable cir) { - if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { + if (ReplayUI.shouldModifyViewport()) { cir.setReturnValue(ReplayUI.getNewGameHeight(1)); } } - @Inject(method = "onFramebufferResize", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/WindowEventHandler;resizeDisplay()V", shift = At.Shift.BEFORE)) - public void onFramebufferResize(long l, int i, int j, CallbackInfo ci) { - int[] widthB = new int[1]; - int[] heightB = new int[1]; - GLFW.glfwGetWindowSize(this.window, widthB, heightB); - if (widthB[0] > 0 && heightB[0] > 0) { - this.width = widthB[0]; - this.height = heightB[0]; - } - } - @Inject(method = "onResize", at=@At("HEAD"), cancellable = true) public void onResize(long l, int i, int j, CallbackInfo ci) { if (l != this.window) { ci.cancel(); - return; - } - - int[] widthB = new int[1]; - int[] heightB = new int[1]; - GLFW.glfwGetFramebufferSize(this.window, widthB, heightB); - if (widthB[0] > 0 && heightB[0] > 0) { - this.framebufferWidth = widthB[0]; - this.framebufferHeight = heightB[0]; } } @@ -109,9 +100,9 @@ public abstract class MixinWindow { j++; } cir.setReturnValue(j); - } else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { - int fbw = ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width); - int fbh = ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height); + } else if (ReplayUI.shouldModifyViewport()) { + int fbw = ReplayUI.getNewGameWidth(this.calculateWidthScaleFactor()); + int fbh = ReplayUI.getNewGameHeight(this.calculateHeightScaleFactor()); int j = 1; while (j != scale && j < fbw && j < fbh && fbw / (j + 1) >= 320 && fbh / (j + 1) >= 240) { @@ -137,9 +128,9 @@ public abstract class MixinWindow { this.guiScaledHeight = (double)fbh / d > (double)j ? j + 1 : j; ci.cancel(); - } else if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { - int fbw = ReplayUI.getNewGameWidth((float) this.framebufferWidth / this.width); - int fbh = ReplayUI.getNewGameHeight((float) this.framebufferHeight / this.height); + } else if (ReplayUI.shouldModifyViewport()) { + int fbw = ReplayUI.getNewGameWidth(this.calculateWidthScaleFactor()); + int fbh = ReplayUI.getNewGameHeight(this.calculateHeightScaleFactor()); this.guiScale = d; int i = (int)((double)fbw / d); diff --git a/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java b/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java new file mode 100644 index 0000000..281f9ba --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/audio/MixinAudioLibrary.java @@ -0,0 +1,62 @@ +package com.moulberry.flashback.mixin.audio; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.blaze3d.audio.Library; +import com.moulberry.flashback.Flashback; +import org.lwjgl.openal.ALC10; +import org.lwjgl.openal.ALC11; +import org.lwjgl.openal.SOFTLoopback; +import org.lwjgl.system.MemoryStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.nio.IntBuffer; + +@Mixin(Library.class) +public class MixinAudioLibrary { + + @Shadow + public long currentDevice; + + @Unique + private boolean usingLoopbackDevice = false; + + @Inject(method = "init", at = @At("HEAD")) + public void init(String string, boolean bl, CallbackInfo ci) { + this.usingLoopbackDevice = Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().recordAudio(); + if (this.usingLoopbackDevice) { + Flashback.LOGGER.info("Enabling loopback device for recording audio"); + } + } + + @WrapOperation(method = "init", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/audio/Library;openDeviceOrFallback(Ljava/lang/String;)J")) + public long init_openDevice(String string, Operation original) { + if (this.usingLoopbackDevice) { + return SOFTLoopback.alcLoopbackOpenDeviceSOFT((CharSequence) null); + } else { + return original.call(string); + } + } + + @WrapOperation(method = "init", at = @At(value = "INVOKE", target = "Lorg/lwjgl/openal/ALC10;alcCreateContext(JLjava/nio/IntBuffer;)J", remap = false)) + public long init_createContext(long deviceHandle, IntBuffer attrList, Operation original) { + if (this.usingLoopbackDevice) { + try (MemoryStack memoryStack = MemoryStack.stackPush()) { + IntBuffer intBuffer = memoryStack.callocInt(7) + .put(SOFTLoopback.ALC_FORMAT_TYPE_SOFT).put(SOFTLoopback.ALC_FLOAT_SOFT) + .put(SOFTLoopback.ALC_FORMAT_CHANNELS_SOFT).put(SOFTLoopback.ALC_MONO_SOFT) + .put(ALC10.ALC_FREQUENCY).put(44100) + .put(0).flip(); + return ALC10.alcCreateContext(this.currentDevice, intBuffer); + } + } else { + return original.call(deviceHandle, attrList); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java b/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java new file mode 100644 index 0000000..4519ef3 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/audio/MixinSoundEngine.java @@ -0,0 +1,29 @@ +package com.moulberry.flashback.mixin.audio; + +import com.moulberry.flashback.Flashback; +import net.minecraft.client.sounds.SoundEngine; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(SoundEngine.class) +public class MixinSoundEngine { + + @Unique + private boolean wasExportingAudio = false; + + @Inject(method = "shouldChangeDevice", at = @At("HEAD"), cancellable = true) + public void shouldChangeDevice(CallbackInfoReturnable cir) { + boolean isExportingAudio = Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().recordAudio(); + + if (wasExportingAudio != isExportingAudio) { + wasExportingAudio = isExportingAudio; + cir.setReturnValue(true); + } else if (isExportingAudio) { + cir.setReturnValue(false); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java b/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java index 24fb32c..026666f 100644 --- a/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java @@ -1,7 +1,8 @@ package com.moulberry.flashback.mixin.compat; import com.mojang.blaze3d.vertex.PoseStack; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.mixinconstraints.annotations.IfModLoaded; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import net.minecraft.client.Camera; @@ -23,9 +24,10 @@ public class MixinSodiumWorldRenderer { @Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;Lnet/minecraft/client/Camera;F)V", at = @At("HEAD"), cancellable = true) public void renderBlockEntities(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, Camera camera, float tickDelta, CallbackInfo ci) { - if (!ReplayVisuals.renderBlocks) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.renderBlocks) { ci.cancel(); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/moulberry/flashback/mixin/norandom/MixinParticle.java b/src/main/java/com/moulberry/flashback/mixin/norandom/MixinParticle.java new file mode 100644 index 0000000..0e518ab --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/norandom/MixinParticle.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.mixin.norandom; + +import com.moulberry.flashback.Flashback; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.particle.Particle; +import net.minecraft.util.RandomSource; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Random; + +@Mixin(Particle.class) +public class MixinParticle { + + @Shadow + @Final + protected RandomSource random; + + @Inject(method = "(Lnet/minecraft/client/multiplayer/ClientLevel;DDD)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/Particle;setSize(FF)V")) + private void newParticle(ClientLevel clientLevel, double d, double e, double f, CallbackInfo ci) { + if (Flashback.isExporting()) { + Random random = Flashback.EXPORT_JOB.getParticleRandom(); + if (random != null) { + this.random.setSeed(random.nextLong()); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinAttributeInstance.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinAttributeInstance.java new file mode 100644 index 0000000..138897e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinAttributeInstance.java @@ -0,0 +1,30 @@ +package com.moulberry.flashback.mixin.playback; + +import com.moulberry.flashback.Flashback; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.entity.ai.attributes.AttributeModifier; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(AttributeInstance.class) +public abstract class MixinAttributeInstance { + + @Shadow + public abstract boolean removeModifier(ResourceLocation resourceLocation); + + @Inject(method = "addModifier", at = @At(value = "HEAD")) + public void addModifier(AttributeModifier attributeModifier, CallbackInfo ci) { + // Some mods (e.g. HorseBuff) may end up adding a duplicate modifier while inside a replay + // Remove the modifier first in order to ensure no exceptions are thrown + if (Flashback.isInReplay()) { + try { + this.removeModifier(attributeModifier.id()); + } catch (Exception ignored) {} + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinChunkHolder.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinChunkHolder.java new file mode 100644 index 0000000..eed10e9 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinChunkHolder.java @@ -0,0 +1,38 @@ +package com.moulberry.flashback.mixin.playback; + +import com.moulberry.flashback.ext.LevelChunkExt; +import net.minecraft.server.level.ChunkHolder; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.BitSet; + +@Mixin(value = ChunkHolder.class, priority = 1100) +public class MixinChunkHolder { + + @Shadow + private boolean hasChangedSections; + + @Shadow + @Final + private BitSet skyChangedLightSectionFilter; + + @Shadow + @Final + private BitSet blockChangedLightSectionFilter; + + @Inject(method = "broadcastChanges", at = @At("HEAD")) + public void broadcastChanges(LevelChunk levelChunk, CallbackInfo ci) { + if (levelChunk instanceof LevelChunkExt levelChunkExt) { + if (this.hasChangedSections || !this.skyChangedLightSectionFilter.isEmpty() || !this.blockChangedLightSectionFilter.isEmpty()) { + levelChunkExt.flashback$setCachedChunkId(-1); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java index ebc64c6..db27c7c 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java @@ -4,10 +4,12 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.blaze3d.vertex.PoseStack; import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.ext.ItemInHandRendererExt; import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.visuals.CameraRotation; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.Options; @@ -20,6 +22,7 @@ import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.GameType; +import org.joml.Quaternionf; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -29,7 +32,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(GameRenderer.class) -public class MixinGameRenderer { +public abstract class MixinGameRenderer { @WrapOperation(method = "render", at=@At(value = "FIELD", target = "Lnet/minecraft/client/Options;pauseOnLostFocus:Z")) @@ -48,6 +51,9 @@ public class MixinGameRenderer { @Final private Minecraft minecraft; + @Shadow + public abstract float getDepthFar(); + @WrapOperation(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;")) public GameType getPlayerMode(MultiPlayerGameMode instance, Operation original) { if (Flashback.getSpectatingPlayer() != null) { @@ -60,8 +66,9 @@ public class MixinGameRenderer { public void renderItemInHand_renderHandsWithItems(ItemInHandRenderer instance, float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, LocalPlayer localPlayer, int i, Operation original) { AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer(); if (spectatingPlayer != null) { - f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(); - ((ItemInHandRendererExt)instance).flashback$renderHandsWithItems(f, poseStack, bufferSource, spectatingPlayer, i); + Entity entity = this.minecraft.getCameraEntity() == null ? this.minecraft.player : this.minecraft.getCameraEntity(); + float frozenPartialTick = this.minecraft.level.tickRateManager().isEntityFrozen(entity) ? 1.0f : f; + ((ItemInHandRendererExt)instance).flashback$renderHandsWithItems(frozenPartialTick, poseStack, bufferSource, spectatingPlayer, i); } else { original.call(instance, f, poseStack, bufferSource, localPlayer, i); } @@ -70,11 +77,34 @@ public class MixinGameRenderer { @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setup(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/world/entity/Entity;ZZF)V")) public void renderLevel_setupCamera(Camera instance, BlockGetter blockGetter, Entity entity, boolean bl, boolean bl2, float f, Operation original) { if (Flashback.isInReplay()) { - f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(); + f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(f); } original.call(instance, blockGetter, entity, bl, bl2, f); } + @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;rotation()Lorg/joml/Quaternionf;")) + public Quaternionf renderLevel(Camera instance, Operation original) { + return CameraRotation.modifyViewQuaternion(original.call(instance)); + } + +// @Inject(method = "getProjectionMatrix", at = @At(value = "INVOKE", target = "Lorg/joml/Matrix4f;perspective(FFFF)Lorg/joml/Matrix4f;", shift = At.Shift.BEFORE)) +// @Inject(method = "getProjectionMatrix", at = @At(value = "RETURN")) +// public void getProjectionMatrix(double d, CallbackInfoReturnable cir) { +// if (ReplayVisuals.overrideZoom) { +// cir.getReturnValue().scaleLocal(ReplayVisuals.overrideZoomAmount, ReplayVisuals.overrideZoomAmount, 1.0f); +// } +// } + +// @Inject(method = "getProjectionMatrix", at = @At(value = "RETURN"), cancellable = true) +// public void getProjectionMatrix(double d, CallbackInfoReturnable cir) { +// if (ReplayVisuals.overrideZoom) { +// Window window = Minecraft.getInstance().getWindow(); +// Matrix4f matrix4f = new Matrix4f().setOrtho(-10.0f, 10.0f, -10.0f, 10.0f, 0.05f, this.getDepthFar()); +// cir.setReturnValue(matrix4f); +//// cir.setReturnValue(new Matrix4f().ortho()); +// } +// } + @Inject(method = "tryTakeScreenshotIfNeeded", at = @At("HEAD"), cancellable = true) public void tryTakeScreenshotIfNeeded(CallbackInfo ci) { if (Flashback.isInReplay()) { @@ -89,13 +119,13 @@ public class MixinGameRenderer { cir.setReturnValue(70.0); return; } - - int fov = this.minecraft.options.fov().get().intValue(); - if (ReplayVisuals.overrideFov) { - cir.setReturnValue((double) ReplayVisuals.overrideFovAmount); - return; + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideFov) { + cir.setReturnValue((double) editorState.replayVisuals.overrideFovAmount); + } else { + int fov = this.minecraft.options.fov().get().intValue(); + cir.setReturnValue((double) fov); } - cir.setReturnValue((double) fov); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java new file mode 100644 index 0000000..a0b6618 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java @@ -0,0 +1,125 @@ +package com.moulberry.flashback.mixin.playback; + +import com.moulberry.flashback.ext.LevelChunkExt; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Registry; +import net.minecraft.util.profiling.ProfilerFiller; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelHeightAccessor; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.chunk.UpgradeData; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.blending.BlendingData; +import net.minecraft.world.level.lighting.LightEngine; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.Inject; + +@Mixin(LevelChunk.class) +public abstract class MixinLevelChunk extends ChunkAccess implements LevelChunkExt { + + @Shadow + @Final + private Level level; + + @Shadow + public abstract void addAndRegisterBlockEntity(BlockEntity blockEntity); + + @Shadow + protected abstract void updateBlockEntityTicker(T blockEntity); + + @Shadow + public abstract @Nullable BlockEntity getBlockEntity(BlockPos blockPos, LevelChunk.EntityCreationType entityCreationType); + + public MixinLevelChunk(ChunkPos chunkPos, UpgradeData upgradeData, LevelHeightAccessor levelHeightAccessor, Registry registry, long l, @Nullable LevelChunkSection[] levelChunkSections, @Nullable BlendingData blendingData) { + super(chunkPos, upgradeData, levelHeightAccessor, registry, l, levelChunkSections, blendingData); + } + + @Unique + private int cachedChunkId = -1; + + @Override + public int flashback$getCachedChunkId() { + return this.cachedChunkId; + } + + @Override + public void flashback$setCachedChunkId(int id) { + this.cachedChunkId = id; + } + + @Override + public void flashback$setBlockStateWithoutUpdates(BlockPos blockPos, BlockState blockState) { + int y = blockPos.getY(); + LevelChunkSection levelChunkSection = this.getSection(this.getSectionIndex(y)); + boolean oldHasOnlyAir = levelChunkSection.hasOnlyAir(); + if (oldHasOnlyAir && blockState.isAir()) { + return; + } + + // Set block + int localX = blockPos.getX() & 0xF; + int localY = y & 0xF; + int localZ = blockPos.getZ() & 0xF; + BlockState oldBlockState = levelChunkSection.setBlockState(localX, localY, localZ, blockState); + if (oldBlockState == blockState) { + return; + } + + // Update heightmaps + this.heightmaps.get(Heightmap.Types.MOTION_BLOCKING).update(localX, y, localZ, blockState); + this.heightmaps.get(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES).update(localX, y, localZ, blockState); + this.heightmaps.get(Heightmap.Types.OCEAN_FLOOR).update(localX, y, localZ, blockState); + this.heightmaps.get(Heightmap.Types.WORLD_SURFACE).update(localX, y, localZ, blockState); + + // Update air status + boolean newHasOnlyAir = levelChunkSection.hasOnlyAir(); + if (oldHasOnlyAir != newHasOnlyAir) { + this.level.getChunkSource().getLightEngine().updateSectionStatus(blockPos, newHasOnlyAir); + } + + // Update light + if (LightEngine.hasDifferentLightProperties(this, blockPos, oldBlockState, blockState)) { + if (this.skyLightSources != null) { + this.skyLightSources.update(this, localX, y, localZ); + } + this.level.getChunkSource().getLightEngine().checkBlock(blockPos); + } + + // Update block entity + Block block = blockState.getBlock(); + if (!oldBlockState.is(block) && oldBlockState.hasBlockEntity()) { + this.removeBlockEntity(blockPos); + } + if (!levelChunkSection.getBlockState(localX, localY, localZ).is(block)) { + return; + } + if (blockState.hasBlockEntity()) { + BlockEntity blockEntity = this.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK); + if (blockEntity == null) { + blockEntity = ((EntityBlock)block).newBlockEntity(blockPos, blockState); + if (blockEntity != null) { + this.addAndRegisterBlockEntity(blockEntity); + } + } else { + blockEntity.setBlockState(blockState); + this.updateBlockEntityTicker(blockEntity); + } + } + + this.unsaved = true; + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunkSection.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunkSection.java deleted file mode 100644 index 8acbb6b..0000000 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunkSection.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.moulberry.flashback.mixin.playback; - -import com.moulberry.flashback.ext.LevelChunkSectionExt; -import net.minecraft.core.Holder; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.LevelChunkSection; -import net.minecraft.world.level.chunk.PalettedContainer; -import net.minecraft.world.level.chunk.PalettedContainerRO; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(LevelChunkSection.class) -public class MixinLevelChunkSection implements LevelChunkSectionExt { - - @Shadow - @Final - private PalettedContainer states; - - @Shadow - private short nonEmptyBlockCount; - - @Shadow - private PalettedContainerRO> biomes; - - @Unique - private int cachedChunkId = -1; - - @Override - public int flashback$getCachedChunkId() { - return this.cachedChunkId; - } - - @Override - public void flashback$setCachedChunkId(int cachedChunkId) { - this.cachedChunkId = cachedChunkId; - } - - @Inject(method = "read", at = @At("RETURN")) - public void read(FriendlyByteBuf friendlyByteBuf, CallbackInfo ci) { - this.cachedChunkId = -1; - } - - @Inject(method = "setBlockState(IIILnet/minecraft/world/level/block/state/BlockState;Z)Lnet/minecraft/world/level/block/state/BlockState;", at = @At("RETURN")) - public void setBlockState(int i, int j, int k, BlockState blockState, boolean bl, CallbackInfoReturnable cir) { - this.cachedChunkId = -1; - } - -} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java index e6bda6e..42dc11c 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java @@ -1,6 +1,7 @@ package com.moulberry.flashback.mixin.playback; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayPlayer; import net.minecraft.client.Minecraft; import net.minecraft.server.ServerTickRateManager; import net.minecraft.world.TickRateManager; @@ -10,6 +11,7 @@ import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(TickRateManager.class) @@ -18,16 +20,34 @@ public abstract class MixinTickRateManager { @Shadow public abstract boolean runsNormally(); + @Shadow + protected boolean runGameElements; + + /* + * Freeze the replay server, preventing game elements from running normally + */ + + @Inject(method = "tick", at = @At("RETURN")) + public void tick(CallbackInfo ci) { + if (Flashback.isInReplay() && this.isServerTickRateManager) { + this.runGameElements = false; + } + } + @Unique - private final boolean isClientTickRateManager = !((Object)this instanceof ServerTickRateManager); + private final boolean isServerTickRateManager = ((Object)this instanceof ServerTickRateManager); @Inject(method = "isEntityFrozen", at = @At("HEAD"), cancellable = true) public void isEntityFrozen(Entity entity, CallbackInfoReturnable cir) { - if (this.isClientTickRateManager && Flashback.isInReplay()) { - if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) { - cir.setReturnValue(false); + if (Flashback.isInReplay()) { + if (this.isServerTickRateManager) { + cir.setReturnValue(!(entity instanceof ReplayPlayer)); } else { - cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); + if (Flashback.isExporting()) { + cir.setReturnValue(false); + } else { + cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); + } } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java new file mode 100644 index 0000000..f20edcd --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientLevel.java @@ -0,0 +1,58 @@ +package com.moulberry.flashback.mixin.record; + +import com.moulberry.flashback.Flashback; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ClientboundSoundPacket; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(ClientLevel.class) +public class MixinClientLevel { + + @Shadow + @Final + private Minecraft minecraft; + + @Inject(method = "levelEvent", at = @At("HEAD")) + public void levelEvent(Player player, int type, BlockPos blockPos, int data, CallbackInfo ci) { + if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { + Flashback.RECORDER.writeLevelEvent(type, blockPos, data, false); + } + } + + @Inject(method = "globalLevelEvent", at = @At("HEAD")) + public void globalLevelEvent(int type, BlockPos blockPos, int data, CallbackInfo ci) { + if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { + Flashback.RECORDER.writeLevelEvent(type, blockPos, data, true); + } + } + + @Inject(method = "playSeededSound(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/entity/Entity;Lnet/minecraft/core/Holder;Lnet/minecraft/sounds/SoundSource;FFJ)V", at = @At("RETURN")) + public void playSeededSoundEntity(@Nullable Player player, Entity entity, Holder holder, SoundSource soundSource, float volume, float pitch, long seed, CallbackInfo ci) { + if (player != null && player == this.minecraft.player && Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { + Flashback.RECORDER.writePacketAsync(new ClientboundSoundEntityPacket(holder, soundSource, entity, volume, pitch, seed), ConnectionProtocol.PLAY); + } + } + + @Inject(method = "playSeededSound(Lnet/minecraft/world/entity/player/Player;DDDLnet/minecraft/core/Holder;Lnet/minecraft/sounds/SoundSource;FFJ)V", at = @At("RETURN")) + public void playSeededSoundNormal(@Nullable Player player, double x, double y, double z, Holder holder, SoundSource soundSource, float volume, float pitch, long seed, CallbackInfo ci) { + if (player != null && player == this.minecraft.player && Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { + Flashback.RECORDER.writePacketAsync(new ClientboundSoundPacket(holder, soundSource, x, y, z, volume, pitch, seed), ConnectionProtocol.PLAY); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java index a09ea80..4975279 100644 --- a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java @@ -1,14 +1,20 @@ package com.moulberry.flashback.mixin.replay_server; +import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.players.PlayerList; import net.minecraft.world.level.Level; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import java.util.Optional; @@ -21,6 +27,10 @@ public class MixinPlayerList { * Don't change the dimension of replay viewers when spawning them */ + @Shadow + @Final + private MinecraftServer server; + @WrapOperation(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Ljava/util/Optional;flatMap(Ljava/util/function/Function;)Ljava/util/Optional;")) public Optional> placeNewPlayer_flatMap(Optional instance, Function function, Operation>> original, @Local(argsOnly = true) ServerPlayer serverPlayer) { @@ -30,4 +40,9 @@ public class MixinPlayerList { return original.call(instance, function); } + @WrapWithCondition(method = "placeNewPlayer", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;info(Ljava/lang/String;[Ljava/lang/Object;)V", remap = false)) + public boolean placeNewPlayer_logInfo(Logger instance, String s, Object[] objects) { + return !(this.server instanceof ReplayServer); + } + } diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java index 0361c21..7595134 100644 --- a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java @@ -4,6 +4,8 @@ import com.llamalad7.mixinextras.sugar.Local; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.server.level.ServerEntity; import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable; @@ -12,12 +14,12 @@ import org.spongepowered.asm.mixin.injection.ModifyVariable; public class MixinServerEntity { /* - * Force update interval to be 1 on a replay server + * Force update interval to be 1 on a replay server, sending updates as soon as possible */ @ModifyVariable(method = "", at = @At("HEAD"), argsOnly = true) private static int init_modifyUpdateInterval(int updateInterval, @Local(argsOnly = true) ServerLevel level) { - if (level.getServer() instanceof ReplayServer) { + if (updateInterval <= 3 && level != null && level.getServer() instanceof ReplayServer) { return 1; } return updateInterval; diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java index d0b7c40..e01abf6 100644 --- a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java @@ -1,6 +1,7 @@ package com.moulberry.flashback.mixin.replay_server; import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.network.protocol.login.ServerboundHelloPacket; import net.minecraft.server.MinecraftServer; @@ -13,6 +14,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import java.nio.charset.StandardCharsets; import java.util.UUID; @Mixin(ServerLoginPacketListenerImpl.class) @@ -32,8 +34,11 @@ public abstract class MixinServerLoginPacketListenerImpl { @Inject(method = "handleHello", at = @At("HEAD"), cancellable = true) public void handleHello(ServerboundHelloPacket serverboundHelloPacket, CallbackInfo ci) { if (this.server instanceof ReplayServer) { - this.requestedUsername = "ReplayViewer"; - this.startClientVerification(new GameProfile(UUID.randomUUID(), "ReplayViewer")); + this.requestedUsername = ReplayServer.REPLAY_VIEWER_NAME; + UUID replayViewerUUID = UUID.nameUUIDFromBytes(serverboundHelloPacket.name().getBytes(StandardCharsets.UTF_8)); + GameProfile gameProfile = new GameProfile(replayViewerUUID, ReplayServer.REPLAY_VIEWER_NAME); + gameProfile.getProperties().put("IsReplayViewer", new Property("IsReplayViewer", "True")); + this.startClientVerification(gameProfile); ci.cancel(); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java index 7d4def3..95d1c92 100644 --- a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java @@ -3,27 +3,22 @@ package com.moulberry.flashback.mixin.replay_server; import com.moulberry.flashback.Flashback; import net.minecraft.server.ServerTickRateManager; import net.minecraft.world.TickRateManager; +import net.minecraft.world.entity.Entity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(TickRateManager.class) public abstract class MixinTickRateManager { - @Shadow - protected boolean runGameElements; - /* - * Freeze the replay server, preventing game elements from running normally - */ - @Inject(method = "tick", at = @At("RETURN")) - public void tick(CallbackInfo ci) { - if (Flashback.isInReplay() && (Object)this instanceof ServerTickRateManager) { - this.runGameElements = false; - } + @Inject(method = "isEntityFrozen", at = @At("RETURN")) + public void isEntityFrozen(Entity entity, CallbackInfoReturnable cir) { + } } diff --git a/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java b/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java index c88ff90..7a19be5 100644 --- a/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java +++ b/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java @@ -1,11 +1,14 @@ package com.moulberry.flashback.mixin.ui; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.screen.BottomTextWidget; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.layouts.LayoutElement; import net.minecraft.client.gui.screens.ConfirmScreen; import net.minecraft.client.gui.screens.PauseScreen; import net.minecraft.network.chat.Component; @@ -19,8 +22,8 @@ public class MixinPauseScreen { @Inject(method = "createPauseMenu", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/layouts/GridLayout;arrangeElements()V", shift = At.Shift.BEFORE)) public void createPauseMenu(CallbackInfo ci, @Local GridLayout.RowHelper rowHelper) { - if (!Flashback.isInReplay()) { - rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Flashback"), Minecraft.getInstance().font), 2); + if (!Flashback.isInReplay() && !Flashback.getConfig().hidePauseMenuControls) { + rowHelper.addChild(new BottomTextWidget(204, 30, Component.literal("Flashback"), Minecraft.getInstance().font), 2); if (Flashback.RECORDER == null) { rowHelper.addChild(Button.builder(Component.literal("Start Recording"), (button) -> { Flashback.startRecordingReplay(); @@ -59,4 +62,12 @@ public class MixinPauseScreen { } } + @WrapOperation(method = "createPauseMenu", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/layouts/FrameLayout;alignInRectangle(Lnet/minecraft/client/gui/layouts/LayoutElement;IIIIFF)V")) + public void createPauseMenu_alignInRectangle(LayoutElement layoutElement, int i, int j, int k, int l, float f, float g, Operation original) { + if (!Flashback.isInReplay() && !Flashback.getConfig().hidePauseMenuControls) { + g += 0.05f; + } + original.call(layoutElement, i, j, k, l, f, g); + } + } diff --git a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java index 02a76f1..b5a6ac2 100644 --- a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java +++ b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java @@ -4,10 +4,14 @@ import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.ref.LocalIntRef; +import com.moulberry.flashback.screen.FlashbackButton; import com.moulberry.flashback.screen.SelectReplayScreen; +import net.fabricmc.fabric.api.client.screen.v1.Screens; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.ImageButton; import net.minecraft.client.gui.components.Renderable; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; @@ -33,8 +37,34 @@ public class MixinTitleScreen extends Screen { @Unique private final List normalMenuWidgets = new ArrayList<>(); + @Unique + private AbstractWidget openSelectReplayScreenButton = null; + @Inject(method = "init", at = @At("RETURN")) public void init(CallbackInfo ci) { + if (this.openSelectReplayScreenButton != null) { + this.removeWidget(this.openSelectReplayScreenButton); + this.openSelectReplayScreenButton = null; + } + } + + // We do this on tick to ensure that our button is added after ever other mod's + // Our button logic has automatic repositioning, whereas other mods (i.e. ModMenu) + // might not implement repositioning logic, causing our button to render under theirs + @Inject(method = "tick", at = @At("RETURN")) + public void tick(CallbackInfo ci) { + if (this.openSelectReplayScreenButton == null) { + this.createOpenSelectReplayScreenButton(); + } + } + + @Unique + private void createOpenSelectReplayScreenButton() { + if (this.openSelectReplayScreenButton != null) { + this.removeWidget(this.openSelectReplayScreenButton); + this.openSelectReplayScreenButton = null; + } + for (int offsetX = 0; offsetX < 5; offsetX++) { for (int i = this.normalMenuWidgets.size()-1; i >= 0; i--) { AbstractWidget widget = this.normalMenuWidgets.get(i); @@ -48,7 +78,7 @@ public class MixinTitleScreen extends Screen { for (Renderable renderable : this.renderables) { if (renderable instanceof AbstractWidget otherWidget) { if (x < otherWidget.getRight() && x+size > otherWidget.getX() && - y < otherWidget.getBottom() && y+size > otherWidget.getY()) { + y < otherWidget.getBottom() && y+size > otherWidget.getY()) { overlapsWithExistingButton = true; break; } @@ -56,9 +86,10 @@ public class MixinTitleScreen extends Screen { } if (!overlapsWithExistingButton) { - this.addRenderableWidget(Button.builder(Component.literal("R"), button -> { + this.openSelectReplayScreenButton = new FlashbackButton(x, y, size, size, Component.literal("Open Replays"), button -> { this.minecraft.setScreen(new SelectReplayScreen(this)); - }).bounds(x, y, size, size).build()); + }); + this.addRenderableWidget(this.openSelectReplayScreenButton); return; } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java index 2ed6423..3902e9d 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java @@ -1,6 +1,7 @@ package com.moulberry.flashback.mixin.visuals; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.BossHealthOverlay; import org.spongepowered.asm.mixin.Mixin; @@ -13,7 +14,8 @@ public class MixinBossHealthOverlay { @Inject(method = "render", at = @At("HEAD"), cancellable = true) public void render(GuiGraphics guiGraphics, CallbackInfo ci) { - if (!ReplayVisuals.showBossBar) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.showBossBar) { ci.cancel(); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java index 6a64453..b14461e 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java @@ -1,6 +1,8 @@ package com.moulberry.flashback.mixin.visuals; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.visuals.ReplayVisuals; import net.minecraft.client.multiplayer.ClientLevel; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -12,8 +14,9 @@ public class MixinClientLevelData { @Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true) public void getDayTime(CallbackInfoReturnable cir) { - if (ReplayVisuals.overrideTimeOfDay >= 0) { - cir.setReturnValue(ReplayVisuals.overrideTimeOfDay); + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideTimeOfDay >= 0) { + cir.setReturnValue(editorState.replayVisuals.overrideTimeOfDay); } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java index 48c2476..6cc64f0 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java @@ -3,7 +3,8 @@ package com.moulberry.flashback.mixin.visuals; import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; @@ -34,7 +35,8 @@ public abstract class MixinEntityRenderDispatcher { // Prevent rendering shadows when blocks are turned off @WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;renderShadow(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/entity/Entity;FFLnet/minecraft/world/level/LevelReader;F)V")) public boolean renderShadow(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, float f, float g, LevelReader levelReader, float h) { - return ReplayVisuals.renderBlocks; + EditorState editorState = EditorStateManager.getCurrent(); + return editorState == null || editorState.replayVisuals.renderBlocks; } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java index b196cd8..48365b9 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java @@ -2,7 +2,8 @@ package com.moulberry.flashback.mixin.visuals; import com.mojang.blaze3d.shaders.FogShape; import com.mojang.blaze3d.systems.RenderSystem; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import net.minecraft.client.Camera; import net.minecraft.client.renderer.FogRenderer; import org.spongepowered.asm.mixin.Mixin; @@ -15,9 +16,10 @@ public class MixinFogRenderer { @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) private static void setupFog(Camera camera, FogRenderer.FogMode fogMode, float f, boolean bl, float g, CallbackInfo ci) { - if (ReplayVisuals.overrideFog) { - RenderSystem.setShaderFogStart(ReplayVisuals.overrideFogStart); - RenderSystem.setShaderFogEnd(ReplayVisuals.overrideFogEnd); + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideFog) { + RenderSystem.setShaderFogStart(editorState.replayVisuals.overrideFogStart); + RenderSystem.setShaderFogEnd(editorState.replayVisuals.overrideFogEnd); RenderSystem.setShaderFogShape(FogShape.SPHERE); ci.cancel(); } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java index 19f39ec..b61f142 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java @@ -1,6 +1,8 @@ package com.moulberry.flashback.mixin.visuals; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.DeltaTracker; @@ -18,28 +20,32 @@ public class MixinGui { @Inject(method = "renderChat", at = @At("HEAD"), cancellable = true) public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { - if (!ReplayVisuals.showChat) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.showChat) { ci.cancel(); } } @Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true) public void renderTitle(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { - if (!ReplayVisuals.showTitleText) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.showTitleText) { ci.cancel(); } } @Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true) public void renderScoreboardSidebar(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { - if (!ReplayVisuals.showScoreboard) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.showScoreboard) { ci.cancel(); } } @Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true) public void renderOverlayMessage(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { - if (!ReplayVisuals.showActionBar) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.showActionBar) { ci.cancel(); } } @@ -49,6 +55,9 @@ public class MixinGui { if (ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) { cir.setReturnValue(true); } + if (Flashback.getSpectatingPlayer() != null) { + cir.setReturnValue(true); + } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLevelRenderer.java new file mode 100644 index 0000000..0be26eb --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLevelRenderer.java @@ -0,0 +1,60 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.PoseStack; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.visuals.WorldRenderHook; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.RenderBuffers; +import org.joml.Matrix4f; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(LevelRenderer.class) +public class MixinLevelRenderer { + + @Shadow + @Final + private RenderBuffers renderBuffers; + + @Inject(method="renderLevel", at=@At( + value = "INVOKE", + target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;", + shift = At.Shift.BEFORE + )) + public void renderLevelPost(net.minecraft.client.DeltaTracker deltaTracker, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, + Matrix4f matrix4f, Matrix4f projection, CallbackInfo ci) { + + if (!Flashback.isInReplay()) { + return; + } + + this.renderBuffers.bufferSource().endBatch(); + + PoseStack poseStack = new PoseStack(); + poseStack.mulPose(matrix4f); + + // Set model view stack to identity + var modelViewStack = RenderSystem.getModelViewStack(); + modelViewStack.pushMatrix(); + modelViewStack.identity(); + RenderSystem.applyModelViewMatrix(); + + float tickDelta = deltaTracker.getGameTimeDeltaPartialTick(true); + WorldRenderHook.renderHook(poseStack, tickDelta, renderBlockOutline, camera, gameRenderer, lightTexture, projection); + + this.renderBuffers.bufferSource().endBatch(); + + // Pop model view stack + modelViewStack.popMatrix(); + RenderSystem.applyModelViewMatrix(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinMouseHandler.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinMouseHandler.java new file mode 100644 index 0000000..1ffe3c9 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinMouseHandler.java @@ -0,0 +1,54 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.Utils; +import com.moulberry.flashback.ext.OptionsExt; +import net.minecraft.client.MouseHandler; +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +import net.minecraft.network.chat.Component; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(MouseHandler.class) +public class MixinMouseHandler { + + // Reduces sensitivity when overriding fov to a lower value + // This makes the camera much easier to control with low fov values + + @WrapOperation(method = "turnPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;sensitivity()Lnet/minecraft/client/OptionInstance;")) + public OptionInstance turnPlayer_sensitivity(Options instance, Operation> original) { + OptionInstance sensitivity = original.call(instance); + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideFov) { + float newFov = editorState.replayVisuals.overrideFovAmount; + if (newFov > 20.0) { + return original.call(instance); + } + float oldFov = ((OptionsExt)instance).flashback$getOriginalFov(); + + if (newFov < oldFov) { + float newFocalLength = Utils.fovToFocalLength(newFov); + float oldFocalLength = Utils.fovToFocalLength(oldFov); + + float sensitivityMultiplier = oldFocalLength / newFocalLength; + double newSensitivity = sensitivity.get() * sensitivityMultiplier; + + sensitivity = new OptionInstance<>("options.sensitivity", OptionInstance.noTooltip(), (component, double_) -> { + if (double_ == 0.0) { + return Options.genericValueLabel(component, Component.translatable("options.sensitivity.min")); + } + if (double_ == 1.0) { + return Options.genericValueLabel(component, Component.translatable("options.sensitivity.max")); + } + return Component.translatable("options.percent_value", component, (int)(double_ * 200.0)); + }, OptionInstance.UnitDouble.INSTANCE, newSensitivity, double_ -> {}); + } + } + return sensitivity; + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java index 37a0b27..531b96d 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java @@ -1,34 +1,46 @@ package com.moulberry.flashback.mixin.visuals; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.ext.OptionsExt; import net.minecraft.client.OptionInstance; import net.minecraft.client.Options; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(Options.class) -public class MixinOptions { +public class MixinOptions implements OptionsExt { + @Shadow + @Final + private OptionInstance fov; @Unique - private OptionInstance cachedOptionInstance = null; + private OptionInstance cachedFovOptionInstance = null; @Inject(method = "fov", at = @At("RETURN"), cancellable = true) public void fov(CallbackInfoReturnable> cir) { - if (ReplayVisuals.overrideFov) { - if (this.cachedOptionInstance == null || this.cachedOptionInstance.get() != Math.round(ReplayVisuals.overrideFovAmount)) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && editorState.replayVisuals.overrideFov) { + if (this.cachedFovOptionInstance == null || this.cachedFovOptionInstance.get() != Math.round(editorState.replayVisuals.overrideFovAmount)) { OptionInstance delegate = cir.getReturnValue(); - this.cachedOptionInstance = new OptionInstance<>("options.fov", OptionInstance.noTooltip(), Options::genericValueLabel, - delegate.values(), delegate.codec(), Math.round(ReplayVisuals.overrideFovAmount), value -> { - ReplayVisuals.overrideFov = false; + this.cachedFovOptionInstance = new OptionInstance<>("options.fov", OptionInstance.noTooltip(), Options::genericValueLabel, + delegate.values(), delegate.codec(), Math.round(editorState.replayVisuals.overrideFovAmount), value -> { + editorState.replayVisuals.overrideFov = false; delegate.set(value); }); } - cir.setReturnValue(this.cachedOptionInstance); + cir.setReturnValue(this.cachedFovOptionInstance); } } + @Override + public int flashback$getOriginalFov() { + return this.fov.get(); + } } diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackClearParticles.java b/src/main/java/com/moulberry/flashback/packet/FlashbackClearParticles.java new file mode 100644 index 0000000..6188717 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackClearParticles.java @@ -0,0 +1,15 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public class FlashbackClearParticles implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("clear_particles")); + public static final FlashbackClearParticles INSTANCE = new FlashbackClearParticles(); + + @Override + public Type type() { + return TYPE; + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackForceClientTick.java b/src/main/java/com/moulberry/flashback/packet/FlashbackForceClientTick.java new file mode 100644 index 0000000..80750c7 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackForceClientTick.java @@ -0,0 +1,15 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public class FlashbackForceClientTick implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("force_client_tick")); + public static final FlashbackForceClientTick INSTANCE = new FlashbackForceClientTick(); + + @Override + public Type type() { + return TYPE; + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FlashbackInstantlyLerp.java b/src/main/java/com/moulberry/flashback/packet/FlashbackInstantlyLerp.java new file mode 100644 index 0000000..6a71aae --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FlashbackInstantlyLerp.java @@ -0,0 +1,15 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public class FlashbackInstantlyLerp implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("instantly_lerp")); + public static final FlashbackInstantlyLerp INSTANCE = new FlashbackInstantlyLerp(); + + @Override + public Type type() { + return TYPE; + } + +} diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index 65f27f9..f73222e 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -1,8 +1,10 @@ package com.moulberry.flashback.playback; import com.mojang.authlib.GameProfile; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.PacketHelper; import com.moulberry.flashback.exception.UnsupportedPacketException; +import com.moulberry.flashback.ext.LevelChunkExt; import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; import io.netty.channel.embedded.EmbeddedChannel; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; @@ -43,7 +45,11 @@ import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.ai.attributes.AttributeMap; import net.minecraft.world.entity.ai.attributes.AttributeModifier; +import net.minecraft.world.entity.decoration.HangingEntity; +import net.minecraft.world.entity.decoration.ItemFrame; import net.minecraft.world.entity.decoration.Painting; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.npc.Villager; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.GameRules; @@ -61,6 +67,7 @@ import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.storage.DerivedLevelData; +import net.minecraft.world.level.storage.PrimaryLevelData; import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; @@ -102,6 +109,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { serverChunkCache.broadcast(entity, packet); } + private void setBlockState(ServerLevel level, BlockPos blockPos, BlockState blockState) { + LevelChunk levelChunk = level.getChunkAt(blockPos); + ((LevelChunkExt)levelChunk).flashback$setBlockStateWithoutUpdates(blockPos, blockState); + level.getChunkSource().blockChanged(blockPos); + } + public void flushPendingEntities() { ServerLevel level = this.level(); for (Entity pendingEntity : this.pendingEntities.values()) { @@ -115,6 +128,8 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { existingEntity.setXRot(pendingEntity.getXRot()); existingEntity.setYRot(pendingEntity.getYRot()); existingEntity.setYHeadRot(pendingEntity.getYHeadRot()); + existingEntity.setDeltaMovement(pendingEntity.getDeltaMovement()); + existingEntity.hasImpulse = pendingEntity.hasImpulse; if (pendingEntity instanceof LivingEntity pendingLiving) { existingEntity.setYBodyRot(pendingLiving.yBodyRot); } @@ -149,7 +164,11 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleAddEntity(ClientboundAddEntityPacket clientboundAddEntityPacket) { if (Entity.ENTITY_COUNTER.get() <= clientboundAddEntityPacket.getId()) { - Entity.ENTITY_COUNTER.set(clientboundAddEntityPacket.getId() + 1); + Entity.ENTITY_COUNTER.set(clientboundAddEntityPacket.getId() + 1000); + } + + if (clientboundAddEntityPacket.id >= ReplayServer.REPLAY_VIEWER_IDS_START && clientboundAddEntityPacket.id <= ReplayServer.REPLAY_VIEWER_IDS_START+128) { + clientboundAddEntityPacket.id += 128; } Entity entity = this.createEntityFromPacket(clientboundAddEntityPacket); @@ -167,6 +186,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { private void spawnPlayer(ClientboundAddEntityPacket addEntityPacket, GameProfile gameProfile, GameType gameType) { this.flushPendingEntities(); + gameProfile.getProperties().removeAll("IsReplayViewer"); CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false); ServerPlayer serverPlayer = new ServerPlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()){ @@ -228,6 +248,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { entity.setYRot(0.0f); entity.setXRot(0.0f); entity.setId(clientboundAddExperienceOrbPacket.getId()); + entity.setDeltaMovement(Vec3.ZERO); Entity existingEntity = this.level().getEntity(clientboundAddExperienceOrbPacket.getId()); if (existingEntity instanceof ExperienceOrb) { @@ -303,8 +324,8 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleBlockUpdate(ClientboundBlockUpdatePacket clientboundBlockUpdatePacket) { - this.level().setBlock(clientboundBlockUpdatePacket.getPos(), - clientboundBlockUpdatePacket.getBlockState(), 18); + this.setBlockState(this.level(), clientboundBlockUpdatePacket.getPos(), + clientboundBlockUpdatePacket.getBlockState()); } @Override @@ -329,8 +350,9 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleChunkBlocksUpdate(ClientboundSectionBlocksUpdatePacket clientboundSectionBlocksUpdatePacket) { + ServerLevel level = this.level(); clientboundSectionBlocksUpdatePacket.runUpdates((blockPos, blockState) -> { - this.level().setBlock(blockPos, blockState, 18); + this.setBlockState(level, blockPos, blockState); }); } @@ -559,8 +581,22 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { this.localPlayerId = clientboundLoginPacket.playerId(); this.ensureWorldCreated(clientboundLoginPacket.commonPlayerSpawnInfo(), recreatePlayer ? null : localPlayer, true); + // Update special world property + CommonPlayerSpawnInfo spawnInfo = clientboundLoginPacket.commonPlayerSpawnInfo(); + if (this.replayServer.getWorldData() instanceof PrimaryLevelData primaryLevelData) { + PrimaryLevelData.SpecialWorldProperty specialWorldProperty; + if (spawnInfo.isFlat()) { + specialWorldProperty = PrimaryLevelData.SpecialWorldProperty.FLAT; + } else if (spawnInfo.isDebug()) { + specialWorldProperty = PrimaryLevelData.SpecialWorldProperty.DEBUG; + } else { + specialWorldProperty = PrimaryLevelData.SpecialWorldProperty.NONE; + } + primaryLevelData.specialWorldProperty = specialWorldProperty; + } + if (recreatePlayer) { - ClientboundAddEntityPacket addEntityPacket = PacketHelper.createAddEntity(localPlayer); + ClientboundAddEntityPacket addEntityPacket = (ClientboundAddEntityPacket) PacketHelper.createAddEntity(localPlayer); addEntityPacket.id = clientboundLoginPacket.playerId(); this.spawnPlayer(addEntityPacket, localPlayer.getGameProfile(), localPlayer.gameMode.getGameModeForPlayer()); } @@ -595,7 +631,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } } - if (!this.replayServer.levels.containsKey(dimension)) { + ServerLevel oldLevel = this.replayServer.getLevel(dimension); + + // Force recreate level if the DimensionType has changed + boolean forceRecreate = oldLevel != null && !oldLevel.dimensionType().equals(commonPlayerSpawnInfo.dimensionType().value()); + + if (oldLevel == null || forceRecreate) { ServerLevelData serverLevelData = this.replayServer.worldData.overworldData(); if (dimension != Level.OVERWORLD) { serverLevelData = new DerivedLevelData(this.replayServer.worldData, serverLevelData); @@ -609,19 +650,27 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { serverLevel.noSave = true; this.replayServer.levels.put(dimension, serverLevel); this.replayServer.followLocalPlayerNextTick = true; + + if (oldLevel != null) { + this.replayServer.closeLevel(oldLevel); + } } - if (this.currentDimension == dimension) { - this.replayServer.followLocalPlayerNextTickIfFar = true; + ServerLevel newLevel = this.replayServer.getLevel(dimension); + + if (newLevel == oldLevel) { + if (!this.replayServer.isProcessingSnapshot) { + this.replayServer.followLocalPlayerNextTickIfFar = true; + } return; } // Move local player and replay viewer if (localPlayer != null) { - localPlayer.teleportTo(this.replayServer.getLevel(dimension), 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f); + localPlayer.teleportTo(newLevel, 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f); } for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) { - replayViewer.teleportTo(this.replayServer.getLevel(dimension), 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f); + replayViewer.teleportTo(newLevel, 0.0, 0.0, 0.0, Set.of(), 0.0f, 0.0f); } this.replayServer.followLocalPlayerNextTick = true; @@ -822,10 +871,11 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { return; } - double motionX = clientboundSetEntityMotionPacket.getXa() / 8000.0; - double motionY = clientboundSetEntityMotionPacket.getYa() / 8000.0; - double motionZ = clientboundSetEntityMotionPacket.getZa() / 8000.0; + double motionX = clientboundSetEntityMotionPacket.getXa(); + double motionY = clientboundSetEntityMotionPacket.getYa(); + double motionZ = clientboundSetEntityMotionPacket.getZa(); entity.setDeltaMovement(motionX, motionY, motionZ); + entity.hasImpulse = true; } @Override @@ -906,6 +956,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleSoundEvent(ClientboundSoundPacket clientboundSoundPacket) { + if (Flashback.EXPORT_JOB == null && this.replayServer.replayPaused) { + return; + } + Holder sound = clientboundSoundPacket.getSound(); double x = clientboundSoundPacket.getX(); double y = clientboundSoundPacket.getY(); @@ -917,6 +971,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleSoundEntityEvent(ClientboundSoundEntityPacket clientboundSoundEntityPacket) { + if (Flashback.EXPORT_JOB == null && this.replayServer.replayPaused) { + return; + } + Entity entity = this.level().getEntity(clientboundSoundEntityPacket.getId()); if (entity == null) { return; diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java b/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java index ce345b5..d0e1237 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java @@ -9,9 +9,11 @@ import net.minecraft.stats.Stat; import net.minecraft.world.item.crafting.RecipeHolder; import java.util.Collection; +import java.util.UUID; public class ReplayPlayer extends ServerPlayer { public boolean followLocalPlayerNextTick = false; + public UUID spectatingUuid = null; public ReplayPlayer(MinecraftServer minecraftServer, ServerLevel serverLevel, GameProfile gameProfile, ClientInformation clientInformation) { super(minecraftServer, serverLevel, gameProfile, clientInformation); diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java index 4944bca..868279a 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java @@ -4,11 +4,14 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.ext.LevelChunkExt; import com.moulberry.flashback.TempFolderProvider; +import com.moulberry.flashback.keyframe.handler.ReplayServerKeyframeHandler; +import com.moulberry.flashback.packet.FlashbackClearParticles; +import com.moulberry.flashback.packet.FlashbackForceClientTick; +import com.moulberry.flashback.packet.FlashbackInstantlyLerp; import com.moulberry.flashback.state.EditorState; -import com.moulberry.flashback.state.EditorStateCache; -import com.moulberry.flashback.ext.LevelChunkSectionExt; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.ext.ServerGamePacketListenerImplExt; import com.moulberry.flashback.io.ReplayReader; @@ -51,12 +54,12 @@ import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.WorldDataConfiguration; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.storage.LevelStorageSource; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -66,6 +69,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -73,19 +77,22 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; public class ReplayServer extends IntegratedServer { private static final Gson GSON = new Gson(); + public static int REPLAY_VIEWER_IDS_START = -981723987; + public static String REPLAY_VIEWER_NAME = "Replay Viewer"; public volatile int jumpToTick = -1; public volatile boolean replayPaused = true; + public AtomicBoolean forceApplyKeyframes = new AtomicBoolean(false); public AtomicBoolean sendFinishedServerTick = new AtomicBoolean(false); - public volatile float desiredTickRate = 20.0f; + private volatile float desiredTickRate = 20.0f; + private volatile float desiredTickRateManual = 20.0f; private int currentTick = 0; - private int targetTick = 0; + private volatile int targetTick = 0; private final int totalTicks; public ResourceKey spawnLevel = null; private final ReplayGamePacketHandler gamePacketHandler; @@ -97,6 +104,7 @@ public class ReplayServer extends IntegratedServer { public boolean followLocalPlayerNextTickIfFar = false; public boolean isProcessingSnapshot = false; private boolean processedSnapshot = false; + private volatile boolean fastForwarding = false; private final UUID playbackUUID; private final FlashbackMeta metadata; @@ -112,6 +120,7 @@ public class ReplayServer extends IntegratedServer { private Component tabListFooter = Component.empty(); private Component shutdownReason = null; + private FileSystem playbackFileSystem = null; public ReplayServer(Thread thread, Minecraft minecraft, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory, UUID playbackUUID, Path path) { @@ -124,36 +133,10 @@ public class ReplayServer extends IntegratedServer { this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); try { - Path playbackFolder = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.PLAYBACK, playbackUUID); + this.playbackFileSystem = FileSystems.newFileSystem(path); - byte[] buffer = new byte[1024]; - ZipInputStream zis = new ZipInputStream(Files.newInputStream(path)); - ZipEntry zipEntry = zis.getNextEntry(); - while (zipEntry != null) { - File newFile = newFile(playbackFolder.toFile(), zipEntry); - if (zipEntry.isDirectory()) { - if (!newFile.isDirectory() && !newFile.mkdirs()) { - throw new IOException("Failed to create directory " + newFile); - } - } else { - // fix for Windows-created archives - File parent = newFile.getParentFile(); - if (!parent.isDirectory() && !parent.mkdirs()) { - throw new IOException("Failed to create directory " + parent); - } - - // write file content - FileOutputStream fos = new FileOutputStream(newFile); - int len; - while ((len = zis.read(buffer)) > 0) { - fos.write(buffer, 0, len); - } - fos.close(); - } - zipEntry = zis.getNextEntry(); - } - - String metadataJson = Files.readString(playbackFolder.resolve("metadata.json")); + Path metadataPath = this.playbackFileSystem.getPath("/metadata.json"); + String metadataJson = Files.readString(metadataPath); this.metadata = FlashbackMeta.fromJson(GSON.fromJson(metadataJson, JsonObject.class)); if (this.metadata == null) { throw new RuntimeException("Invalid metadata file"); @@ -161,14 +144,14 @@ public class ReplayServer extends IntegratedServer { int ticks = 0; for (Map.Entry entry : this.metadata.chunks.entrySet()) { - var chunkMetaWithPath = new PlayableChunk(entry.getValue(), playbackFolder.resolve(entry.getKey())); + var chunkMetaWithPath = new PlayableChunk(entry.getValue(), this.playbackFileSystem.getPath("/"+entry.getKey())); this.playableChunksByStart.put(ticks, chunkMetaWithPath); ticks += entry.getValue().duration; } this.totalTicks = ticks; - Path levelChunkCachePath = playbackFolder.resolve("level_chunk_cache"); + Path levelChunkCachePath = this.playbackFileSystem.getPath("/level_chunk_cache"); if (Files.exists(levelChunkCachePath)) { int chunkCacheIndex = 0; @@ -214,19 +197,6 @@ public class ReplayServer extends IntegratedServer { return this.metadata; } - public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { - File destFile = new File(destinationDir, zipEntry.getName()); - - String destDirPath = destinationDir.getCanonicalPath(); - String destFilePath = destFile.getCanonicalPath(); - - if (!destFilePath.startsWith(destDirPath + File.separator)) { - throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); - } - - return destFile; - } - public void updateRegistry(FeatureFlagSet featureFlagSet, Collection selectedPacks, List> initialPackets, List configurationTasks) { this.worldData.setDataConfiguration(new WorldDataConfiguration( @@ -252,7 +222,9 @@ public class ReplayServer extends IntegratedServer { @Override public boolean initServer() { - AtomicInteger newPlayerIds = new AtomicInteger(-981723987); + Entity.ENTITY_COUNTER.set(1000000); + + AtomicInteger newPlayerIds = new AtomicInteger(REPLAY_VIEWER_IDS_START); this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, 1) { @Override public ServerPlayer getPlayerForLogin(GameProfile gameProfile, ClientInformation clientInformation) { @@ -347,6 +319,22 @@ public class ReplayServer extends IntegratedServer { this.jumpToTick = tick; } + public float getDesiredTickRate(boolean manual) { + if (manual) { + return this.desiredTickRateManual; + } else { + return this.desiredTickRate; + } + } + + public void setDesiredTickRate(float tickrate, boolean manual) { + if (manual) { + this.desiredTickRateManual = tickrate; + } else { + this.desiredTickRate = tickrate; + } + } + public int getReplayTick() { return this.targetTick; } @@ -355,9 +343,8 @@ public class ReplayServer extends IntegratedServer { private long lastTickTimeNanos; public float getPartialReplayTick() { - int lastReplayTick = this.lastReplayTick; if (this.replayPaused || this.isPaused()) { - return lastReplayTick; + return this.targetTick; } else { long currentNanos = Util.getNanos(); long nanosPerTick = this.tickRateManager().nanosecondsPerTick(); @@ -365,7 +352,7 @@ public class ReplayServer extends IntegratedServer { double partial = (currentNanos - this.lastTickTimeNanos) / (double) nanosPerTick; partial = Math.max(0, Math.min(1, partial)); - return lastReplayTick + (float) partial; + return this.lastReplayTick + (float) partial; } } @@ -374,7 +361,7 @@ public class ReplayServer extends IntegratedServer { } public boolean doClientRendering() { - return !this.isProcessingSnapshot && !this.processedSnapshot; + return !this.isProcessingSnapshot && !this.processedSnapshot && !this.fastForwarding; } public void updateBossBar(ClientboundBossEventPacket packet) { @@ -540,8 +527,8 @@ public class ReplayServer extends IntegratedServer { if (!doesCachedChunkIdMatch(chunk, index)) { packet.handle(this.gamePacketHandler); - for (LevelChunkSection section : chunk.getSections()) { - ((LevelChunkSectionExt)section).flashback$setCachedChunkId(index); + if (chunk instanceof LevelChunkExt ext) { + ext.flashback$setCachedChunkId(index); } } } else { @@ -550,13 +537,10 @@ public class ReplayServer extends IntegratedServer { } private static boolean doesCachedChunkIdMatch(LevelChunk chunk, int chunkId) { - for (LevelChunkSection section : chunk.getSections()) { - if (chunkId != ((LevelChunkSectionExt) section).flashback$getCachedChunkId()) { - return false; - } + if (chunk instanceof LevelChunkExt ext) { + return ext.flashback$getCachedChunkId() == chunkId; } - - return true; + return false; } public static final TicketType ENTITY_LOAD_TICKET = TicketType.create("replay_entity_load", Comparator.comparingLong(ChunkPos::toLong), 5); @@ -597,48 +581,70 @@ public class ReplayServer extends IntegratedServer { return super.haveTime() && this.jumpToTick < 0; } + public EditorState getEditorState() { + return EditorStateManager.get(this.metadata.replayIdentifier); + } + @Override public void tickServer(BooleanSupplier booleanSupplier) { this.lastReplayTick = this.currentTick; this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick(); - if (!this.replayPaused) { - EditorState editorState = EditorStateCache.get(this.metadata.replayIdentifier); - editorState.applyKeyframes(this, this.lastReplayTick); - } - // Update list of replay viewers this.replayViewers.clear(); for (ServerPlayer player : this.getPlayerList().getPlayers()) { if (player instanceof ReplayPlayer replayPlayer) { + Entity cameraEntity = replayPlayer.getCamera(); + replayPlayer.spectatingUuid = cameraEntity == null || cameraEntity == replayPlayer ? null : cameraEntity.getUUID(); this.replayViewers.add(replayPlayer); } } - int extraForceEntityLerpTicks = 0; + // Update current tick + boolean normalPlayback = false; if (this.jumpToTick >= 0) { this.targetTick = this.jumpToTick; this.jumpToTick = -1; - extraForceEntityLerpTicks = Math.max(0, Math.abs(this.targetTick - this.currentTick) - 1); } else if (!this.isPaused() && !this.replayPaused && this.targetTick < this.totalTicks) { // Normal playback this.targetTick += 1; + normalPlayback = true; } else if (this.targetTick == this.totalTicks && this.currentTick == this.totalTicks) { // Pause when reaching end of replay this.replayPaused = true; } - // Update tick rate & frozen state - if (this.tickRateManager().tickrate() != this.desiredTickRate) { - this.tickRateManager().setTickRate(this.desiredTickRate); + if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback) { + this.runUpdates(booleanSupplier); + } else { + int realTargetTick = this.targetTick; + + if (this.targetTick < this.currentTick) { + int minTick = this.playableChunksByStart.floorKey(this.targetTick) + 1; + this.targetTick = Math.max(minTick, realTargetTick - 20); + } else { + this.targetTick = Math.max(this.currentTick+1, realTargetTick - 20); + } + + if (this.targetTick >= realTargetTick) { + this.targetTick = realTargetTick; + this.runUpdates(booleanSupplier); + } else { + while (this.targetTick <= realTargetTick) { + this.fastForwarding = this.targetTick < realTargetTick; + + this.runUpdates(booleanSupplier); + + if (this.targetTick == realTargetTick) { + break; + } else { + this.targetTick += 1; + } + } + this.fastForwarding = false; + } } - boolean wantFrozen = this.replayPaused && this.targetTick == this.currentTick; - if (this.tickRateManager().isFrozen() != wantFrozen) { - this.tickRateManager().setFrozen(wantFrozen); - } - - this.handleActions(); this.tryFollowLocalPlayer(); // Update resourcepacks @@ -653,11 +659,11 @@ public class ReplayServer extends IntegratedServer { RemotePack oldRemotePack = this.oldRemotePacks.get(entry.getKey()); if (oldRemotePack == null) { this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash, - true, Optional.empty())); + true, Optional.empty())); } else if (!oldRemotePack.equals(remotePack)) { this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.of(remotePack.id))); this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash, - true, Optional.empty())); + true, Optional.empty())); } this.oldRemotePacks.put(entry.getKey(), remotePack); } @@ -671,9 +677,41 @@ public class ReplayServer extends IntegratedServer { }); } - if (extraForceEntityLerpTicks > 0) { - ReplayVisuals.forceEntityLerpTicks = Math.min(10, ReplayVisuals.forceEntityLerpTicks + extraForceEntityLerpTicks); + if (this.sendFinishedServerTick.compareAndExchange(true, false)) { + for (ReplayPlayer replayViewer : this.replayViewers) { + ServerPlayNetworking.send(replayViewer, FinishedServerTick.INSTANCE); + } + if (this.replayViewers.isEmpty() && Flashback.EXPORT_JOB != null) { + Flashback.EXPORT_JOB.onFinishedServerTick(); + } } + } + + private void runUpdates(BooleanSupplier booleanSupplier) { + boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false) && Flashback.EXPORT_JOB == null; + if (!this.replayPaused || forceApplyKeyframes) { + this.desiredTickRate = 20.0f; + EditorState editorState = EditorStateManager.get(this.metadata.replayIdentifier); + editorState.applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick); + + if (forceApplyKeyframes) { + ((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes(); + } + } + + float tickRate = this.desiredTickRate; + if (Flashback.EXPORT_JOB == null) { + tickRate *= this.desiredTickRateManual / 20f; + } + + // Update tick rate & frozen state + if (this.tickRateManager().tickrate() != tickRate) { + this.tickRateManager().setTickRate(tickRate); + } + + boolean tickChanged = this.targetTick != this.currentTick; + + this.handleActions(); // Add tickets for keeping entities loaded for (ServerLevel level : this.getAllLevels()) { @@ -686,34 +724,55 @@ public class ReplayServer extends IntegratedServer { // Tick underlying server super.tickServer(booleanSupplier); - if (this.processedSnapshot) { - this.processedSnapshot = false; + if (Flashback.EXPORT_JOB == null) { + if (this.processedSnapshot) { + this.processedSnapshot = false; - for (ReplayPlayer replayViewer : this.replayViewers) { - replayViewer.connection.chunkSender.sendNextChunks(replayViewer); - } - for (ServerLevel level : this.getAllLevels()) { - for (ServerPlayer player : level.players()) { - if (player instanceof ReplayPlayer) { - // Called twice, first one will update the chunk tracking & second one will update the entity tracking - level.getChunkSource().move(player); - level.getChunkSource().move(player); + for (ReplayPlayer replayViewer : this.replayViewers) { + replayViewer.connection.chunkSender.sendNextChunks(replayViewer); + ServerPlayNetworking.send(replayViewer, FlashbackInstantlyLerp.INSTANCE); + ServerPlayNetworking.send(replayViewer, FlashbackClearParticles.INSTANCE); + + // Ensure replay viewers are still spectating + if (replayViewer.spectatingUuid != null) { + Entity camera = replayViewer.getCamera(); + if (camera == null || camera == replayViewer || camera.isRemoved()) { + Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid); + if (targetEntity != null && !targetEntity.isRemoved()) { + replayViewer.setCamera(targetEntity); + } else { + replayViewer.spectatingUuid = null; + } + } else { + replayViewer.spectatingUuid = null; + } + } + } + for (ServerLevel level : this.getAllLevels()) { + for (ServerPlayer player : level.players()) { + if (player instanceof ReplayPlayer) { + // Called twice, first one will update the chunk tracking & second one will update the entity tracking + level.getChunkSource().move(player); + level.getChunkSource().move(player); + } } } } - if (Flashback.EXPORT_JOB == null) { - ReplayVisuals.forceEntityLerpTicks = 10; - ((MinecraftExt)Minecraft.getInstance()).flashback$forceClientTick(); - } - } - - if (this.sendFinishedServerTick.compareAndExchange(true, false)) { - for (ReplayPlayer replayViewer : this.replayViewers) { - ServerPlayNetworking.send(replayViewer, FinishedServerTick.INSTANCE); - } - if (this.replayViewers.isEmpty() && Flashback.EXPORT_JOB != null) { - Flashback.EXPORT_JOB.onFinishedServerTick(); + if (this.replayPaused) { + if (tickChanged) { + if (this.tickRateManager().isFrozen()) { + this.tickRateManager().setFrozen(false); + } + for (ReplayPlayer replayViewer : this.replayViewers) { + ServerPlayNetworking.send(replayViewer, FlashbackForceClientTick.INSTANCE); + } + this.tickRateManager().setFrozen(true); + } else if (!this.tickRateManager().isFrozen()) { + this.tickRateManager().setFrozen(true); + } + } else if (this.tickRateManager().isFrozen()) { + this.tickRateManager().setFrozen(false); } } } @@ -751,6 +810,15 @@ public class ReplayServer extends IntegratedServer { if (shouldJump) { this.processedSnapshot = true; + + // Clear bossbars and particles + for (ReplayPlayer replayViewer : this.replayViewers) { + for (UUID uuid : this.bossEvents.keySet()) { + replayViewer.connection.send(ClientboundBossEventPacket.createRemovePacket(uuid)); + } + } + this.bossEvents.clear(); + Map.Entry entry = this.playableChunksByStart.floorEntry(this.targetTick); ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); replayReader.handleSnapshot(this); @@ -867,7 +935,13 @@ public class ReplayServer extends IntegratedServer { super.stopServer(); this.clearReplayTempFolder(); - TempFolderProvider.deleteTemp(TempFolderProvider.TempFolderType.PLAYBACK, this.playbackUUID); + if (this.playbackFileSystem != null) { + try { + this.playbackFileSystem.close(); + } catch (IOException e) { + Flashback.LOGGER.error("Failed to close playback zip", e); + } + } } public void clearReplayTempFolder() { @@ -876,6 +950,6 @@ public class ReplayServer extends IntegratedServer { @Override public boolean isSingleplayerOwner(GameProfile gameProfile) { - return gameProfile.getName().equals("ReplayViewer"); + return gameProfile.getName().equals(REPLAY_VIEWER_NAME) && gameProfile.getProperties().containsKey("IsReplayViewer"); } } diff --git a/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java index 72cc453..447b8c6 100644 --- a/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java +++ b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java @@ -10,16 +10,29 @@ import java.util.UUID; public class FlashbackMeta { - public String name = "Unnamed"; - public LinkedHashMap chunks = new LinkedHashMap<>(); - public int totalTicks = -1; public UUID replayIdentifier = UUID.randomUUID(); + public String name = "Unnamed"; + public String versionString = null; + public int dataVersion = 0; + public int protocolVersion = 0; + + public int totalTicks = -1; + public LinkedHashMap chunks = new LinkedHashMap<>(); public JsonObject toJson() { JsonObject meta = new JsonObject(); + meta.addProperty("uuid", this.replayIdentifier.toString()); meta.addProperty("name", this.name); - meta.addProperty("uuid", this.replayIdentifier.toString()); + if (this.versionString != null) { + meta.addProperty("version_string", this.versionString); + } + if (this.dataVersion != 0) { + meta.addProperty("data_version", this.dataVersion); + } + if (this.protocolVersion != 0) { + meta.addProperty("protocol_version", this.protocolVersion); + } if (this.totalTicks > 0) { meta.addProperty("total_ticks", this.totalTicks); @@ -38,17 +51,27 @@ public class FlashbackMeta { public static FlashbackMeta fromJson(JsonObject meta) { FlashbackMeta flashbackMeta = new FlashbackMeta(); + // UUID + if (!meta.has("uuid")) { + return null; + } + flashbackMeta.replayIdentifier = UUID.fromString(meta.get("uuid").getAsString()); + // Name if (!meta.has("name")) { return null; } flashbackMeta.name = meta.get("name").getAsString(); - // UUID - if (!meta.has("uuid")) { - return null; + if (meta.has("version_string")) { + flashbackMeta.versionString = meta.get("version_string").getAsString(); + } + if (meta.has("data_version")) { + flashbackMeta.dataVersion = meta.get("data_version").getAsInt(); + } + if (meta.has("protocol_version")) { + flashbackMeta.protocolVersion = meta.get("protocol_version").getAsInt(); } - flashbackMeta.replayIdentifier = UUID.fromString(meta.get("uuid").getAsString()); // Total ticks if (meta.has("total_ticks")) { diff --git a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java index ef0df92..c449321 100644 --- a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java +++ b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java @@ -74,7 +74,8 @@ public class IgnoredPacketSet { ClientboundChunkBatchStartPacket.class, ClientboundChunkBatchFinishedPacket.class, ClientboundDebugSamplePacket.class, - ClientboundPongResponsePacket.class + ClientboundPongResponsePacket.class, + ClientboundLevelEventPacket.class ); } diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java index 9443b1d..51809d7 100644 --- a/src/main/java/com/moulberry/flashback/record/Recorder.java +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -10,11 +10,13 @@ import com.moulberry.flashback.action.*; import com.moulberry.flashback.io.AsyncReplaySaver; import com.moulberry.flashback.io.ReplayWriter; import io.netty.buffer.ByteBuf; +import net.minecraft.SharedConstants; import net.minecraft.client.Minecraft; import net.minecraft.client.Screenshot; import net.minecraft.client.gui.components.BossHealthOverlay; import net.minecraft.client.gui.components.LerpingBossEvent; import net.minecraft.client.gui.components.PlayerTabOverlay; +import net.minecraft.client.gui.screens.ReceivingLevelScreen; import net.minecraft.client.multiplayer.ClientChunkCache; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientPacketListener; @@ -56,11 +58,10 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; import net.minecraft.world.level.border.WorldBorder; import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.scores.*; -import org.apache.commons.io.FileUtils; -import org.jetbrains.annotations.Nullable; import java.nio.file.Path; import java.util.*; @@ -106,6 +107,7 @@ public class Recorder { private boolean isConfiguring = false; private boolean finishedConfiguration = false; private boolean finishedPausing = false; + private ResourceKey lastDimensionType = null; private volatile boolean needsInitialSnapshot = true; private volatile boolean closeForWriting = false; @@ -116,6 +118,10 @@ public class Recorder { this.asyncReplaySaver = new AsyncReplaySaver(registryAccess); this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); + + this.metadata.dataVersion = SharedConstants.getCurrentVersion().getDataVersion().getVersion(); + this.metadata.protocolVersion = SharedConstants.getProtocolVersion(); + this.metadata.versionString = SharedConstants.VERSION_STRING; } public void setRegistryAccess(RegistryAccess registryAccess) { @@ -155,29 +161,42 @@ public class Recorder { this.finishedConfiguration |= this.flushPackets(); - if (Minecraft.getInstance().level != null && Minecraft.getInstance().getOverlay() == null && !Minecraft.getInstance().isPaused() && !this.isPaused) { + Minecraft minecraft = Minecraft.getInstance(); + + boolean isLevelLoaded = !(Minecraft.getInstance().screen instanceof ReceivingLevelScreen); + boolean changedDimensions = false; + + if (minecraft.level != null && (minecraft.getOverlay() == null || !minecraft.getOverlay().isPauseScreen()) && + !minecraft.isPaused() && !this.isPaused && isLevelLoaded) { this.writeEntityPositions(); this.writeLocalData(); + this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); this.writtenTicksInChunk += 1; this.writtenTicks += 1; - if (!this.hasTakenScreenshot) { - Minecraft minecraft = Minecraft.getInstance(); - if (minecraft.levelRenderer.countRenderedSections() > 10 && minecraft.levelRenderer.hasRenderedAllSections()) { - NativeImage nativeImage = Screenshot.takeScreenshot(minecraft.getMainRenderTarget()); - this.asyncReplaySaver.writeIcon(nativeImage); - this.hasTakenScreenshot = true; - } + if (!this.hasTakenScreenshot && ((this.writtenTicks >= 20 && minecraft.screen == null) || close)) { + NativeImage nativeImage = Screenshot.takeScreenshot(minecraft.getMainRenderTarget()); + this.asyncReplaySaver.writeIcon(nativeImage); + this.hasTakenScreenshot = true; + } + + // Write chunk after changing dimensions + ResourceKey dimension = minecraft.level.dimension(); + if (this.lastDimensionType == null) { + this.lastDimensionType = dimension; + } else if (this.lastDimensionType != dimension) { + this.lastDimensionType = dimension; + changedDimensions = true; } } this.finishedPausing |= this.wasPaused && !this.isPaused; boolean writeChunk = close; - if (Minecraft.getInstance().level != null) { + if (minecraft.level != null) { boolean finished = this.finishedConfiguration || this.finishedPausing; - writeChunk |= this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || finished; + writeChunk |= this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || finished || changedDimensions; } if (writeChunk) { @@ -214,6 +233,9 @@ public class Recorder { this.finishedPausing = false; this.finishedConfiguration = false; + if (minecraft.level != null) { + this.lastDimensionType = minecraft.level.dimension(); + } } if (!this.isPaused) { @@ -229,17 +251,8 @@ public class Recorder { this.isPaused = paused; } - public void finish(@Nullable Path outputFile) { - Path recordFolder = this.asyncReplaySaver.finish(); - if (outputFile != null) { - ReplayExporter.export(recordFolder, outputFile); - } else { - try { - FileUtils.deleteDirectory(recordFolder.toFile()); - } catch (Exception e) { - Flashback.LOGGER.error("Exception deleting record folder", e); - } - } + public Path finish() { + return this.asyncReplaySaver.finish(); } private void writeLocalData() { @@ -337,13 +350,18 @@ public class Recorder { List changedPositions = new ArrayList<>(); for (Entity entity : level.entitiesForRendering()) { + if (PacketHelper.shouldIgnoreEntity(entity)) { + continue; + } + Position position; if (entity instanceof LivingEntity livingEntity) { double lerpHeadRot = livingEntity.lerpHeadSteps > 0 ? livingEntity.lerpYHeadRot : livingEntity.getYHeadRot(); position = new Position(livingEntity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), entity.lerpTargetYRot(), entity.lerpTargetXRot(), (float) lerpHeadRot, entity.onGround()); } else { - position = new Position(entity.getX(), entity.getY(), entity.getZ(), + var trackingPosition = entity.trackingPosition(); + position = new Position(trackingPosition.x, trackingPosition.y, trackingPosition.z, entity.getYRot(), entity.getXRot(), entity.getYHeadRot(), entity.onGround()); } Position lastPosition = this.lastPositions.get(entity); @@ -430,6 +448,14 @@ public class Recorder { return endedConfiguration; } + public void writeLevelEvent(int type, BlockPos blockPos, int data, boolean globalEvent) { + if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) { + return; + } + + this.pendingPackets.add(new PacketWithPhase(new ClientboundLevelEventPacket(type, blockPos, data, globalEvent), ConnectionProtocol.PLAY)); + } + public void writePacketAsync(Packet packet, ConnectionProtocol phase) { if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) { return; @@ -522,7 +548,7 @@ public class Recorder { // Login packet CommonPlayerSpawnInfo commonPlayerSpawnInfo = new CommonPlayerSpawnInfo(level.dimensionTypeRegistration(), level.dimension(), 0, - gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), false, Optional.empty(), 0); + gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), level.getLevelData().isFlat, Optional.empty(), 0); var loginPacket = new ClientboundLoginPacket(localPlayer.getId(), level.getLevelData().isHardcore(), connection.levels(), 1, Minecraft.getInstance().options.getEffectiveRenderDistance(), level.getServerSimulationDistance(), localPlayer.isReducedDebugInfo(), localPlayer.shouldShowDeathScreen(), localPlayer.getDoLimitedCrafting(), commonPlayerSpawnInfo, false); @@ -671,6 +697,10 @@ public class Recorder { // Entity data for (Entity entity : level.entitiesForRendering()) { + if (PacketHelper.shouldIgnoreEntity(entity)) { + continue; + } + if (!(entity instanceof LocalPlayer)) { gamePackets.add(PacketHelper.createAddEntity(entity)); } diff --git a/src/main/java/com/moulberry/flashback/record/ReplayExporter.java b/src/main/java/com/moulberry/flashback/record/ReplayExporter.java index 76d7d7b..586b1db 100644 --- a/src/main/java/com/moulberry/flashback/record/ReplayExporter.java +++ b/src/main/java/com/moulberry/flashback/record/ReplayExporter.java @@ -9,6 +9,7 @@ import org.jetbrains.annotations.Nullable; import java.io.BufferedOutputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -20,7 +21,7 @@ public class ReplayExporter { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - public static void export(Path recordFolder, Path outputFile) { + public static void export(Path recordFolder, Path outputFile, @Nullable String name) { Flashback.LOGGER.info("Exporting {} to {}", recordFolder, outputFile); FlashbackMeta meta = tryReadMeta(recordFolder.resolve("metadata.json")); @@ -32,6 +33,10 @@ public class ReplayExporter { return; } + if (name != null) { + meta.name = name; + } + // Validate meta.chunks.keySet().removeIf(chunkName -> { Path chunkPath = recordFolder.resolve(chunkName); @@ -48,6 +53,12 @@ public class ReplayExporter { return; } + try { + Files.createDirectories(outputFile.getParent()); + } catch (IOException e) { + Flashback.LOGGER.error("Unable to create parent directories", e); + } + try { FileOutputStream fos = new FileOutputStream(outputFile.toFile()); BufferedOutputStream bos = new BufferedOutputStream(fos); diff --git a/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java b/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java index 2d77322..c42a9c0 100644 --- a/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java +++ b/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java @@ -7,11 +7,18 @@ import net.minecraft.network.chat.Component; public class BottomTextWidget extends AbstractStringWidget { + public float horizontalAlignment = 0.5f; + public BottomTextWidget(int width, int height, Component component, Font font) { super(0, 0, width, height, component, font); this.active = false; } + public BottomTextWidget alignLeft() { + this.horizontalAlignment = 0.0f; + return this; + } + public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { Component component = this.getMessage(); @@ -19,7 +26,7 @@ public class BottomTextWidget extends AbstractStringWidget { int width = this.getWidth(); int textWidth = font.width(component); - int x = this.getX() + Math.round((width - textWidth)/2.0f); + int x = this.getX() + Math.round((width - textWidth) * this.horizontalAlignment); int y = this.getY() + this.getHeight() - this.getFont().lineHeight + 1; guiGraphics.drawString(font, component.getVisualOrderText(), x, y, this.getColor()); diff --git a/src/main/java/com/moulberry/flashback/screen/ConfigScreen.java b/src/main/java/com/moulberry/flashback/screen/ConfigScreen.java index 55e64ae..33d1d45 100644 --- a/src/main/java/com/moulberry/flashback/screen/ConfigScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/ConfigScreen.java @@ -1,11 +1,15 @@ package com.moulberry.flashback.screen; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.configuration.FlashbackConfig; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.options.OptionsSubScreen; import net.minecraft.network.chat.Component; +import java.nio.file.Path; + public class ConfigScreen extends OptionsSubScreen { public ConfigScreen(Screen previous) { @@ -14,11 +18,13 @@ public class ConfigScreen extends OptionsSubScreen { protected void addOptions() { if (this.list != null) { - this.list.addSmall(FlashbackConfig.createOptionInstances()); + this.list.addSmall(Flashback.getConfig().createOptionInstances()); } } public void removed() { + Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback"); + Flashback.getConfig().saveToFolder(configFolder); } } diff --git a/src/main/java/com/moulberry/flashback/screen/FlashbackButton.java b/src/main/java/com/moulberry/flashback/screen/FlashbackButton.java new file mode 100644 index 0000000..e5876db --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/FlashbackButton.java @@ -0,0 +1,53 @@ +package com.moulberry.flashback.screen; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; + +public class FlashbackButton extends Button { + + public FlashbackButton(int x, int y, int width, int height, Component component, OnPress onPress) { + super(x, y, width, height, component, onPress, DEFAULT_NARRATION); + } + + @Override + protected void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { + super.renderWidget(guiGraphics, i, j, f); + + final int size = 14; + int paddingX = (this.getWidth() - size) / 2; + int paddingY = (this.getHeight() - size) / 2; + + int x = this.getX() + paddingX; + int y = this.getY() + paddingY; + + double guiScale = Minecraft.getInstance().getWindow().getGuiScale(); + int realSize = (int)(size * guiScale); + + ResourceLocation icon; + if (realSize == 14) { + icon = ResourceLocation.parse("flashback:icon_14x.png"); + } else if (realSize == 28) { + icon = ResourceLocation.parse("flashback:icon_28x.png"); + } else if (realSize == 42) { + icon = ResourceLocation.parse("flashback:icon_42x.png"); + } else if (realSize == 56) { + icon = ResourceLocation.parse("flashback:icon_56x.png"); + } else { + icon = ResourceLocation.parse("flashback:icon.png"); + } + + guiGraphics.blit(icon, x, y, 0f, 0f, size, size, size, size); + + } + + @Override + public void renderString(GuiGraphics guiGraphics, Font font, int i) { + } + +} diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java index 215cd35..b23e8e0 100644 --- a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java +++ b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java @@ -5,13 +5,16 @@ package com.moulberry.flashback.screen; import com.google.gson.Gson; import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.logging.LogUtils; import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.record.FlashbackMeta; import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.SharedConstants; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; @@ -48,6 +51,8 @@ public class ReplaySelectionList extends ObjectSelectionList lastOpenTimes = null; + public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l, String string, @Nullable ReplaySelectionList replaySelectionList) { super(minecraft, i, j, k, l); this.screen = selectReplayScreen; @@ -125,8 +132,49 @@ public class ReplaySelectionList extends ObjectSelectionList> typeToken = (TypeToken>) TypeToken.getParameterized(Map.class, UUID.class, Long.class); +// this.lastOpenTimes = FlashbackGson.PRETTY.fromJson(serialized, typeToken); +// return this.lastOpenTimes.getOrDefault(uuid, 0L); +// } catch (IOException e) { +// Flashback.LOGGER.error("Unable to read last opened cache", e); +// } +// } +// +// this.lastOpenTimes = new HashMap<>(); +// } +// +// return this.lastOpenTimes.getOrDefault(uuid, 0L); +// } +// +// private synchronized void setOpenTime(UUID uuid, long time) { +// this.lastOpenTimes.put(uuid, time); +// } +// +// private synchronized void saveOpenTimeCache() { +// String serialized = FlashbackGson.PRETTY.toJson(this.lastOpenTimes); +// try { +// Files.writeString(getOpenTimeCachePath(), serialized, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, +// StandardOpenOption.CREATE); +// } catch (IOException e) { +// Flashback.LOGGER.error("Unable to write last opened cache", e); +// } +// } + private CompletableFuture> loadReplays() { - Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback"); + Path flashbackDir = Flashback.getDataDirectory(); Path replayDir = flashbackDir.resolve("replays"); if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) { @@ -148,14 +196,12 @@ public class ReplaySelectionList extends ObjectSelectionList { private final Path path; private final FlashbackMeta metadata; private final String replayId; - private final long lastOpened; + private final long lastModified; private final byte[] iconBytes; private Component info = null; + private Component hoverInfo = null; + private boolean canOpen = true; + private boolean hasWarning = false; - public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastOpened, @Nullable byte[] iconBytes) { + public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, @Nullable byte[] iconBytes) { this.path = path; this.metadata = metadata; this.replayId = replayId; - this.lastOpened = lastOpened; + this.lastModified = lastModified; this.iconBytes = iconBytes; + + if (metadata.protocolVersion != 0 && metadata.protocolVersion != SharedConstants.getProtocolVersion()) { + this.canOpen = false; + + if (metadata.versionString != null && !metadata.versionString.equals(SharedConstants.VERSION_STRING)) { + this.hoverInfo = Component.literal("Unable to open replay\nReplay was created in " + metadata.versionString + + " and is incompatible with " + SharedConstants.VERSION_STRING); + } else { + this.hoverInfo = Component.literal("Unable to open replay\nReplay was created with protocol version " + metadata.protocolVersion + + " and is incompatible with " + SharedConstants.getProtocolVersion()); + } + } else if (metadata.dataVersion != 0 && metadata.dataVersion != SharedConstants.getCurrentVersion().getDataVersion().getVersion()) { + this.hasWarning = true; + + if (metadata.versionString != null && !metadata.versionString.equals(SharedConstants.VERSION_STRING)) { + this.hoverInfo = Component.literal("Important Warning\nReplay was created in " + metadata.versionString + + " and may fail to load in " + SharedConstants.VERSION_STRING); + } else { + this.hoverInfo = Component.literal("Important Warning\nReplay was created with data version " + metadata.dataVersion + + " and may fail to load with " + SharedConstants.getCurrentVersion().getDataVersion().getVersion()); + } + } } public Path getPath() { @@ -35,12 +63,16 @@ public class ReplaySummary implements Comparable { return this.replayId; } + public FlashbackMeta getReplayMetadata() { + return this.metadata; + } + public String getReplayName() { return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name; } - public long getLastPlayed() { - return this.lastOpened; + public long getLastModified() { + return this.lastModified; } public Component getInfo() { @@ -68,6 +100,9 @@ public class ReplaySummary implements Comparable { } builder.append(seconds).append('s'); } + if (builder.isEmpty()) { + builder.append("0s"); + } mutable.append(Component.translatable("flashback.select_replay.duration", builder)); } @@ -81,16 +116,24 @@ public class ReplaySummary implements Comparable { return this.iconBytes; } + public Component getHoverInfo() { + return this.hoverInfo; + } + + public boolean hasWarning() { + return this.hasWarning; + } + public boolean canOpen() { - return true; + return this.canOpen; } @Override public int compareTo(ReplaySummary levelSummary) { - if (this.getLastPlayed() < levelSummary.getLastPlayed()) { + if (this.getLastModified() < levelSummary.getLastModified()) { return 1; } - if (this.getLastPlayed() > levelSummary.getLastPlayed()) { + if (this.getLastModified() > levelSummary.getLastModified()) { return -1; } return this.replayId.compareTo(levelSummary.replayId); diff --git a/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java new file mode 100644 index 0000000..5d5866e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/SaveReplayScreen.java @@ -0,0 +1,164 @@ +package com.moulberry.flashback.screen; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.exporting.AsyncFileDialogs; +import com.moulberry.flashback.record.ReplayExporter; +import net.minecraft.FileUtil; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.StringWidget; +import net.minecraft.client.gui.layouts.FrameLayout; +import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.screens.AlertScreen; +import net.minecraft.client.gui.screens.ConfirmScreen; +import net.minecraft.client.gui.screens.PauseScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import org.apache.commons.io.FileUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +public class SaveReplayScreen extends Screen { + + private Path recordFolder; + + private String replayName; + private Path savePath = null; + private boolean generateFileFromReplayName = true; + + private Button filePathButton; + private Screen previousScreen; + + public SaveReplayScreen(Screen previousScreen, Path recordFolder, String replayName) { + super(Component.literal("Save Replay")); + this.recordFolder = recordFolder; + this.setReplayName(replayName); + + if (this.savePath == null) { + this.savePath = Flashback.getReplayFolder().resolve(UUID.randomUUID() + ".zip"); + } + + if (!(previousScreen instanceof SaveReplayScreen)) { + this.previousScreen = previousScreen; + } + } + + @Override + protected void init() { + super.init(); + + GridLayout gridLayout = new GridLayout(); + gridLayout.defaultCellSetting().padding(4, 4, 4, 0); + GridLayout.RowHelper rowHelper = gridLayout.createRowHelper(2); + + rowHelper.addChild(new StringWidget(204, 20, Component.literal("Save Replay"), this.font), 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Replay Name"), this.font).alignLeft(), 2); + + EditBox replayNameEditBox = new EditBox(this.font, 0, 0, 204, 20, Component.literal(this.replayName)); + replayNameEditBox.setValue(this.replayName); + replayNameEditBox.setResponder(this::setReplayName); + rowHelper.addChild(replayNameEditBox, 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Filename"), this.font).alignLeft(), 2); + + this.filePathButton = Button.builder(Component.literal(this.savePath.getFileName().toString()), button -> { + CompletableFuture future = AsyncFileDialogs.saveFileDialog(this.savePath.getParent().toString(), this.savePath.getFileName().toString(), + "Replay Archive", "zip"); + future.thenAccept(pathStr -> { + if (pathStr != null) { + this.savePath = Path.of(pathStr); + this.generateFileFromReplayName = false; + } + }); + }).width(204).build(); + rowHelper.addChild(this.filePathButton, 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2); + + rowHelper.addChild(Button.builder(Component.literal("Save Replay"), button -> { + this.saveReplay(); + Minecraft.getInstance().setScreen(this.previousScreen); + }).width(98).build(), 1); + rowHelper.addChild(Button.builder(Component.literal("Delete Replay"), button -> { + Minecraft.getInstance().setScreen(new ConfirmScreen(value -> { + if (value) { + this.deleteReplay(); + Minecraft.getInstance().setScreen(this.previousScreen); + } else { + Minecraft.getInstance().setScreen(SaveReplayScreen.this); + } + }, Component.literal("Confirm Delete Recording"), + Component.literal("Are you sure you want to delete the recording? You won't be able to recover it"))); + }).width(98).build(), 1); + gridLayout.arrangeElements(); + FrameLayout.alignInRectangle(gridLayout, 0, 0, this.width, this.height, 0.5f, 0.5f); + gridLayout.visitWidgets(this::addRenderableWidget); + } + + @Override + public boolean shouldCloseOnEsc() { + return false; + } + + @Override + public void tick() { + super.tick(); + + if (!Files.exists(this.recordFolder)) { + Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.previousScreen), + Component.literal("Error Saving Replay"), Component.literal("Recording folder seems to be missing. Did you delete it?"))); + } + } + + private void saveReplay() { + if (!Files.exists(this.recordFolder)) { + Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.previousScreen), + Component.literal("Error Saving Replay"), Component.literal("Recording folder seems to be missing. Did you delete it?"))); + return; + } + + ReplayExporter.export(this.recordFolder, this.savePath, this.replayName); + Flashback.removePendingReplaySave(this.recordFolder); + } + + private void deleteReplay() { + try { + FileUtils.deleteDirectory(this.recordFolder.toFile()); + } catch (Exception e) { + Flashback.LOGGER.error("Exception deleting record folder", e); + } + + Flashback.removePendingReplaySave(this.recordFolder); + } + + private void setReplayName(String replayName) { + this.replayName = replayName; + + if (!this.replayName.isEmpty() && (this.savePath == null || this.generateFileFromReplayName)) { + Path replayDir = Flashback.getReplayFolder(); + String filename; + + try { + filename = FileUtil.findAvailableName(replayDir, this.replayName.replace(' ', '_'), ".zip"); + } catch (IOException e) { + Flashback.LOGGER.error("Error while trying to determine filename", e); + filename = UUID.randomUUID() + ".zip"; + } + + this.savePath = replayDir.resolve(filename); + if (this.filePathButton != null) { + this.filePathButton.setMessage(Component.literal(this.savePath.getFileName().toString())); + } + } + } + + +} diff --git a/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java index 403d253..1b320e9 100644 --- a/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java +++ b/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java @@ -4,15 +4,16 @@ import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import org.jetbrains.annotations.Nullable; public class SelectReplayScreen extends Screen { protected final Screen lastScreen; - private Button deleteButton; private Button selectButton; private Button editButton; + private Button deleteButton; protected EditBox searchBox; private ReplaySelectionList list; @@ -26,14 +27,16 @@ public class SelectReplayScreen extends Screen { this.searchBox = new EditBox(this.font, this.width / 2 - 100, 22, 200, 20, this.searchBox, Component.translatable("selectWorld.search")); this.searchBox.setResponder(string -> this.list.updateFilter(string)); this.addWidget(this.searchBox); - this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft, + this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft, this.width, this.height - 112, 48, 36, this.searchBox.getValue(), this.list)); this.selectButton = this.addRenderableWidget(Button.builder(Component.translatable("flashback.select_replay.open"), this::tryOpenReplay) - .bounds(this.width / 2 - 150, this.height - 52, 300, 20).build()); + .bounds(this.width / 2 - 154, this.height - 52, 308, 20).build()); this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay) - .bounds(this.width / 2 - 150, this.height - 28, 146, 20).build()); + .bounds(this.width / 2 - 154, this.height - 28, 150, 20).build()); this.deleteButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.delete"), this::tryDeleteReplay) - .bounds(this.width / 2 + 4, this.height - 28, 146, 20).build()); + .bounds(this.width / 2 + 4, this.height - 28, 72, 20).build()); + this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, button -> this.minecraft.setScreen(this.lastScreen)) + .bounds(this.width / 2 + 82, this.height - 28, 72, 20).build()); this.updateButtonStatus(null); } diff --git a/src/main/java/com/moulberry/flashback/spline/CatmullRom.java b/src/main/java/com/moulberry/flashback/spline/CatmullRom.java index 640dbae..9e7ecc9 100644 --- a/src/main/java/com/moulberry/flashback/spline/CatmullRom.java +++ b/src/main/java/com/moulberry/flashback/spline/CatmullRom.java @@ -267,7 +267,7 @@ public class CatmullRom { if (t1 == t3) { b2 = Interpolation.linear(a2, a3, 0.5f); } else { - b2 =Interpolation.linear(a2, a3, (t - t1)/(t3 - t1)); + b2 = Interpolation.linear(a2, a3, (t - t1)/(t3 - t1)); } if (t1 == t2) { diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java index 156ed5b..adeaa6f 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorState.java +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -1,36 +1,78 @@ package com.moulberry.flashback.state; -import com.google.gson.*; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; -import com.moulberry.flashback.keyframe.impl.CameraKeyframe; -import com.moulberry.flashback.keyframe.impl.FOVKeyframe; -import com.moulberry.flashback.keyframe.impl.TickrateKeyframe; -import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe; -import com.moulberry.flashback.serialization.QuaternionTypeAdapater; -import com.moulberry.flashback.serialization.Vector3fTypeAdapater; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.visuals.ReplayVisuals; import org.jetbrains.annotations.Nullable; -import org.joml.Quaternionf; -import org.joml.Vector3f; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Consumer; public class EditorState { - public transient boolean dirty = false; + transient boolean dirty = false; + public transient int modCount = ThreadLocalRandom.current().nextInt(); public final List keyframeTracks = new ArrayList<>(); + public final ReplayVisuals replayVisuals = new ReplayVisuals(); + private final EditorStateHistory history = new EditorStateHistory(); - public float zoomMin = 0.0f; - public float zoomMax = 1.0f; + public double zoomMin = 0.0; + public double zoomMax = 1.0; public int exportStartTicks = -1; public int exportEndTicks = -1; + public void setKeyframe(int trackIndex, int tick, Keyframe keyframe) { + if (trackIndex >= this.keyframeTracks.size()) { + return; + } + + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + String description; + + KeyframeTrack track = this.keyframeTracks.get(trackIndex); + Keyframe old = track.keyframesByTick.get(tick); + if (old != null) { + undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy())); + description = "Replaced " + track.keyframeType + " keyframe"; + } else { + undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick)); + description = "Added " + track.keyframeType + " keyframe"; + } + redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, keyframe.copy())); + + this.push(new EditorStateHistoryEntry(undo, redo, description)); + } + + public void push(EditorStateHistoryEntry entry) { + if (entry.undo().isEmpty() && entry.redo().isEmpty()) { + return; + } + + this.history.push(this, entry); + this.markDirty(); + } + + public void undo(Consumer descriptionConsumer) { + this.history.undo(this, descriptionConsumer); + this.markDirty(); + } + + public void redo(Consumer descriptionConsumer) { + this.history.redo(this, descriptionConsumer); + this.markDirty(); + } + public void setExportTicks(int start, int end, int totalTicks) { if (this.exportEndTicks < 0) { this.exportEndTicks = totalTicks; @@ -52,7 +94,7 @@ public class EditorState { } } - if (this.exportStartTicks == 0 && this.exportEndTicks == totalTicks) { + if (this.exportStartTicks <= 0 && this.exportEndTicks >= totalTicks) { this.exportStartTicks = -1; this.exportEndTicks = -1; } @@ -60,6 +102,11 @@ public class EditorState { this.dirty = true; } + public void markDirty() { + this.dirty = true; + this.modCount += 1; + } + public void save(Path path) { this.dirty = false; @@ -80,16 +127,23 @@ public class EditorState { return null; } + String serialized = null; try { - String serialized = Files.readString(path); + serialized = Files.readString(path); return FlashbackGson.PRETTY.fromJson(serialized, EditorState.class); } catch (Exception e) { - e.printStackTrace(); + Flashback.LOGGER.error("Error loading editor state", e); + Flashback.LOGGER.error("JSON: {}", serialized); return null; } } - public void applyKeyframes(T t, float tick) { + public EditorState copy() { + String serialized = FlashbackGson.COMPRESSED.toJson(this, EditorState.class); + return FlashbackGson.COMPRESSED.fromJson(serialized, EditorState.class); + } + + public void applyKeyframes(KeyframeHandler keyframeHandler, float tick) { EnumSet applied = EnumSet.noneOf(KeyframeType.class); for (KeyframeTrack keyframeTrack : this.keyframeTracks) { // Ignore lines that are disabled @@ -97,14 +151,16 @@ public class EditorState { continue; } + KeyframeType baseType = keyframeTrack.keyframeType == KeyframeType.CAMERA_ORBIT ? KeyframeType.CAMERA : keyframeTrack.keyframeType; + // Already applied a keyframe of this type earlier, skip - if (applied.contains(keyframeTrack.keyframeType)) { + if (applied.contains(baseType)) { continue; } // Try to apply keyframes, mark applied if successful - if (keyframeTrack.tryApplyKeyframes(t, tick)) { - applied.add(keyframeTrack.keyframeType); + if (keyframeTrack.tryApplyKeyframes(keyframeHandler, tick)) { + applied.add(baseType); } } } diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateHistory.java b/src/main/java/com/moulberry/flashback/state/EditorStateHistory.java new file mode 100644 index 0000000..3307fba --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorStateHistory.java @@ -0,0 +1,56 @@ +package com.moulberry.flashback.state; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +public class EditorStateHistory { + + private final List entries = new ArrayList<>(); + private int position = 0; + + public void push(EditorState editorState, EditorStateHistoryEntry entry) { + while (this.entries.size() > this.position) { + this.entries.removeLast(); + } + while (this.entries.size() >= 256) { + this.entries.removeFirst(); + this.position -= 1; + } + + for (EditorStateHistoryAction redo : entry.redo()) { + redo.apply(editorState); + } + + this.entries.add(entry); + this.position += 1; + } + + public void undo(EditorState editorState, Consumer descriptionConsumer) { + if (this.position == 0) { + return; + } + + this.position -= 1; + EditorStateHistoryEntry entry = this.entries.get(this.position); + for (EditorStateHistoryAction undo : entry.undo()) { + undo.apply(editorState); + } + descriptionConsumer.accept("Undo '" + entry.description() + "'"); + } + + public void redo(EditorState editorState, Consumer descriptionConsumer) { + if (this.position >= this.entries.size()) { + return; + } + + EditorStateHistoryEntry entry = this.entries.get(this.position); + for (EditorStateHistoryAction redo : entry.redo()) { + redo.apply(editorState); + } + descriptionConsumer.accept("Redo '" + entry.description() + "'"); + + this.position += 1; + } + +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateHistoryAction.java b/src/main/java/com/moulberry/flashback/state/EditorStateHistoryAction.java new file mode 100644 index 0000000..6a44690 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorStateHistoryAction.java @@ -0,0 +1,186 @@ +package com.moulberry.flashback.state; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.KeyframeType; + +import java.lang.reflect.Type; + +public interface EditorStateHistoryAction { + + void apply(EditorState editorState); + + record SetKeyframe(KeyframeType type, int trackIndex, int tick, Keyframe keyframe) implements EditorStateHistoryAction { + @Override + public void apply(EditorState editorState) { + if (this.trackIndex < editorState.keyframeTracks.size()) { + KeyframeTrack track = editorState.keyframeTracks.get(this.trackIndex); + if (track.keyframeType == this.type) { + track.keyframesByTick.put(this.tick, this.keyframe.copy()); + } + } + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public SetKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + KeyframeType type = context.deserialize(jsonObject.get("keyframe_type"), KeyframeType.class); + int trackIndex = jsonObject.get("trackIndex").getAsInt(); + int tick = jsonObject.get("tick").getAsInt(); + Keyframe keyframe = context.deserialize(jsonObject.get("keyframe"), Keyframe.class); + return new SetKeyframe(type, trackIndex, tick, keyframe); + } + + @Override + public JsonElement serialize(SetKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action_type", "set_keyframe"); + jsonObject.add("keyframe_type", context.serialize(src.type)); + jsonObject.addProperty("trackIndex", src.trackIndex); + jsonObject.addProperty("tick", src.tick); + jsonObject.add("keyframe", context.serialize(src.keyframe)); + return jsonObject; + } + } + } + + record RemoveKeyframe(KeyframeType type, int trackIndex, int tick) implements EditorStateHistoryAction { + @Override + public void apply(EditorState editorState) { + if (this.trackIndex < editorState.keyframeTracks.size()) { + KeyframeTrack track = editorState.keyframeTracks.get(this.trackIndex); + if (track.keyframeType == this.type) { + track.keyframesByTick.remove(this.tick); + } + } + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public RemoveKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + KeyframeType type = context.deserialize(jsonObject.get("keyframe_type"), KeyframeType.class); + int trackIndex = jsonObject.get("trackIndex").getAsInt(); + int tick = jsonObject.get("tick").getAsInt(); + return new RemoveKeyframe(type, trackIndex, tick); + } + + @Override + public JsonElement serialize(RemoveKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action_type", "remove_keyframe"); + jsonObject.add("keyframe_type", context.serialize(src.type)); + jsonObject.addProperty("trackIndex", src.trackIndex); + jsonObject.addProperty("tick", src.tick); + return jsonObject; + } + } + } + + record AddTrack(KeyframeType type, int trackIndex) implements EditorStateHistoryAction { + @Override + public void apply(EditorState editorState) { + if (this.trackIndex <= editorState.keyframeTracks.size()) { + editorState.keyframeTracks.add(this.trackIndex, new KeyframeTrack(this.type)); + } + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public AddTrack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + KeyframeType type = context.deserialize(jsonObject.get("keyframe_type"), KeyframeType.class); + int trackIndex = jsonObject.get("trackIndex").getAsInt(); + return new AddTrack(type, trackIndex); + } + + @Override + public JsonElement serialize(AddTrack src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action_type", "add_track"); + jsonObject.add("keyframe_type", context.serialize(src.type)); + jsonObject.addProperty("trackIndex", src.trackIndex); + return jsonObject; + } + } + } + + record RemoveTrack(KeyframeType type, int trackIndex) implements EditorStateHistoryAction { + @Override + public void apply(EditorState editorState) { + if (this.trackIndex < editorState.keyframeTracks.size()) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.trackIndex); + if (keyframeTrack.keyframeType == type) { + editorState.keyframeTracks.remove(this.trackIndex); + } + } + } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public RemoveTrack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + KeyframeType type = context.deserialize(jsonObject.get("keyframe_type"), KeyframeType.class); + int trackIndex = jsonObject.get("trackIndex").getAsInt(); + return new RemoveTrack(type, trackIndex); + } + + @Override + public JsonElement serialize(RemoveTrack src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action_type", "remove_track"); + jsonObject.add("keyframe_type", context.serialize(src.type)); + jsonObject.addProperty("trackIndex", src.trackIndex); + return jsonObject; + } + } + } + + class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public EditorStateHistoryAction deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject jsonObject = json.getAsJsonObject(); + String type = jsonObject.get("action_type").getAsString(); + return switch (type) { + case "set_keyframe" -> context.deserialize(json, SetKeyframe.class); + case "remove_keyframe" -> context.deserialize(json, RemoveKeyframe.class); + case "add_track" -> context.deserialize(json, AddTrack.class); + case "remove_track" -> context.deserialize(json, RemoveTrack.class); + default -> throw new IllegalStateException("Unknown action type: " + type); + }; + } + + @Override + public JsonElement serialize(EditorStateHistoryAction src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject; + switch (src) { + case SetKeyframe setKeyframe -> { + jsonObject = (JsonObject) context.serialize(setKeyframe); + jsonObject.addProperty("action_type", "set_keyframe"); + } + case RemoveKeyframe removeKeyframe -> { + jsonObject = (JsonObject) context.serialize(removeKeyframe); + jsonObject.addProperty("action_type", "remove_keyframe"); + } + case AddTrack addTrack -> { + jsonObject = (JsonObject) context.serialize(addTrack); + jsonObject.addProperty("action_type", "add_track"); + } + case RemoveTrack removeTrack -> { + jsonObject = (JsonObject) context.serialize(removeTrack); + jsonObject.addProperty("action_type", "remove_track"); + } + default -> throw new IllegalStateException("Unknown action type: " + src.getClass()); + } + return jsonObject; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateHistoryEntry.java b/src/main/java/com/moulberry/flashback/state/EditorStateHistoryEntry.java new file mode 100644 index 0000000..7a4d2e6 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorStateHistoryEntry.java @@ -0,0 +1,6 @@ +package com.moulberry.flashback.state; + +import java.util.List; + +public record EditorStateHistoryEntry(List undo, List redo, String description) { +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateCache.java b/src/main/java/com/moulberry/flashback/state/EditorStateManager.java similarity index 91% rename from src/main/java/com/moulberry/flashback/state/EditorStateCache.java rename to src/main/java/com/moulberry/flashback/state/EditorStateManager.java index 41f3970..0076630 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorStateCache.java +++ b/src/main/java/com/moulberry/flashback/state/EditorStateManager.java @@ -11,7 +11,7 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.locks.ReentrantLock; -public class EditorStateCache { +public class EditorStateManager { private static long AUTOSAVE_INTERVAL_MILLIS = 30 * 1000; // 30 seconds @@ -106,6 +106,12 @@ public class EditorStateCache { @Nullable public static EditorState getCurrent() { + if (Flashback.isExporting()) { + return Flashback.EXPORT_JOB.getSettings().editorState(); + } + if (!Flashback.isInReplay()) { + return null; + } return current; } @@ -133,8 +139,8 @@ public class EditorStateCache { if (old) { filename += ".old"; } - return Flashback.getConfigDirectory() - .resolve("replay_states") + return Flashback.getDataDirectory() + .resolve("editor_states") .resolve(filename); } diff --git a/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java b/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java index a881a4d..f3141c5 100644 --- a/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java +++ b/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java @@ -1,7 +1,11 @@ package com.moulberry.flashback.state; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe; import com.moulberry.flashback.keyframe.interpolation.SidedInterpolationType; import java.util.Map; @@ -10,31 +14,39 @@ import java.util.TreeMap; public class KeyframeTrack { public final KeyframeType keyframeType; - public TreeMap> keyframesByTick = new TreeMap<>(); + public TreeMap keyframesByTick = new TreeMap<>(); public boolean enabled = true; public KeyframeTrack(KeyframeType keyframeType) { this.keyframeType = keyframeType; } - @SuppressWarnings("unchecked") - public boolean tryApplyKeyframes(T t, float tick) { + public boolean tryApplyKeyframes(KeyframeHandler t, float tick) { + if (!t.supportedKeyframes().contains(this.keyframeType)) { + return false; + } + + if (this.keyframeType == KeyframeType.TIMELAPSE) { + return this.tryApplyKeyframesTimelapse(t, tick); + } + // Skip if empty - TreeMap> keyframeTimes = this.keyframesByTick; + TreeMap keyframeTimes = this.keyframesByTick; if (keyframeTimes.isEmpty()) { return false; } - Map.Entry> lowerEntry = keyframeTimes.floorEntry((int) tick); + Map.Entry lowerEntry = keyframeTimes.floorEntry((int) tick); if (lowerEntry == null) { return false; } - if (lowerEntry.getValue().operandClass != t.getClass()) { - return false; - } + Keyframe lowerKeyframe = lowerEntry.getValue(); - Keyframe lowerKeyframe = (Keyframe) lowerEntry.getValue(); + if (tick == lowerEntry.getKey()) { + lowerKeyframe.apply(t); + return true; + } SidedInterpolationType leftInterpolation = lowerEntry.getValue().interpolationType().rightSide; @@ -45,8 +57,14 @@ public class KeyframeTrack { } // Get next entry, skip if tick is not between two keyframes - Map.Entry> ceilEntry = keyframeTimes.ceilingEntry(lowerEntry.getKey() + 1); + Map.Entry ceilEntry = keyframeTimes.ceilingEntry(lowerEntry.getKey() + 1); if (ceilEntry == null) { + if ((int) tick == lowerEntry.getKey()) { + lowerKeyframe.apply(t); + return true; + } else if (t.alwaysApplyLastKeyframe()) { + lowerKeyframe.apply(t); + } return false; } @@ -61,12 +79,12 @@ public class KeyframeTrack { rightInterpolation == SidedInterpolationType.SMOOTH; if (isUsingSmooth) { - Map.Entry> beforeEntry = keyframeTimes.floorEntry(lowerEntry.getKey() - 1); + Map.Entry beforeEntry = keyframeTimes.floorEntry(lowerEntry.getKey() - 1); if (beforeEntry == null) { beforeEntry = lowerEntry; } - Map.Entry> afterAfterEntry = keyframeTimes.ceilingEntry(ceilEntry.getKey() + 1); + Map.Entry afterAfterEntry = keyframeTimes.ceilingEntry(ceilEntry.getKey() + 1); if (afterAfterEntry == null) { afterAfterEntry = ceilEntry; } @@ -84,7 +102,7 @@ public class KeyframeTrack { lerpFromRight = false; } - ((Keyframe)beforeEntry.getValue()).applyInterpolatedSmooth(t, lowerEntry.getValue(), ceilEntry.getValue(), afterAfterEntry.getValue(), + beforeEntry.getValue().applyInterpolatedSmooth(t, lowerEntry.getValue(), ceilEntry.getValue(), afterAfterEntry.getValue(), beforeEntry.getKey(), lowerEntry.getKey(), ceilEntry.getKey(), afterAfterEntry.getKey(), amount, lerpAmount, lerpFromRight); } else { amount = SidedInterpolationType.interpolate(leftInterpolation, rightInterpolation, amount); @@ -99,4 +117,37 @@ public class KeyframeTrack { return true; } + private boolean tryApplyKeyframesTimelapse(KeyframeHandler t, float tick) { + // Skip if empty + TreeMap keyframeTimes = this.keyframesByTick; + if (keyframeTimes.isEmpty()) { + return false; + } + + Map.Entry lowerEntry = keyframeTimes.floorEntry((int) tick); + Map.Entry ceilEntry = keyframeTimes.ceilingEntry(((int) tick) + 1); + + if (ceilEntry == null && lowerEntry != null && lowerEntry.getKey() == (int) tick) { + ceilEntry = lowerEntry; + lowerEntry = keyframeTimes.floorEntry((int) tick - 1); + } + + if (lowerEntry != null && ceilEntry != null) { + int lowerTicks = ((TimelapseKeyframe) lowerEntry.getValue()).ticks; + int ceilTicks = ((TimelapseKeyframe) ceilEntry.getValue()).ticks; + + if (ceilTicks <= lowerTicks) { + ReplayUI.setInfoOverlayShort("Unable to timelapse. Right keyframe's time must be greater than left keyframe's time"); + t.applyTickrate(20); + } else { + double tickrate = (double) (ceilEntry.getKey() - lowerEntry.getKey()) / (ceilTicks - lowerTicks) * 20; + t.applyTickrate((float) tickrate); + } + + return true; + } + + return false; + } + } diff --git a/src/main/java/com/moulberry/flashback/visuals/CameraPath.java b/src/main/java/com/moulberry/flashback/visuals/CameraPath.java new file mode 100644 index 0000000..dd640cb --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/CameraPath.java @@ -0,0 +1,339 @@ +package com.moulberry.flashback.visuals; + +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.MeshData; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexBuffer; +import com.mojang.blaze3d.vertex.VertexFormat; +import com.moulberry.flashback.Utils; +import com.moulberry.flashback.combo_options.Sizing; +import com.moulberry.flashback.editor.ui.windows.TimelineWindow; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import com.moulberry.flashback.state.KeyframeTrack; +import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; +import org.joml.Quaternionf; +import org.joml.Vector3f; + +import java.util.EnumSet; + +public class CameraPath { + + private static VertexBuffer cameraPathVertexBuffer = null; + private static CameraPathArgs lastCameraPathArgs = null; + private static int lastEditorStateModCount = 0; + private static int lastCursorTick = 0; + + public static void renderCameraPath(PoseStack poseStack, Camera camera, ReplayServer replayServer) { + RenderSystem.assertOnRenderThread(); + + EditorState state = replayServer.getEditorState(); + int replayTick = TimelineWindow.getCursorTick(); + + if (lastEditorStateModCount != state.modCount || lastCursorTick != replayTick) { + CameraPathArgs cameraPathArgs = createCameraPathArgs(state, replayTick, SUPPORTED_CAMERA_KEYFRAMES); + + if (lastEditorStateModCount != state.modCount || !cameraPathArgs.equals(lastCameraPathArgs)) { + lastCameraPathArgs = cameraPathArgs; + + BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL); + buildCameraPath(state, cameraPathArgs, bufferBuilder); + + if (cameraPathVertexBuffer != null) { + cameraPathVertexBuffer.close(); + cameraPathVertexBuffer = null; + } + + MeshData meshData = bufferBuilder.build(); + if (meshData != null) { + cameraPathVertexBuffer = new VertexBuffer(VertexBuffer.Usage.STATIC); + cameraPathVertexBuffer.bind(); + cameraPathVertexBuffer.upload(meshData); + VertexBuffer.unbind(); + } + } + + lastEditorStateModCount = state.modCount; + lastCursorTick = replayTick; + } + + if (cameraPathVertexBuffer == null) { + return; + } + + RenderSystem.disableCull(); + RenderSystem.enableBlend(); + RenderSystem.defaultBlendFunc(); + RenderSystem.lineWidth(2f); + RenderSystem.setShader(GameRenderer::getRendertypeLinesShader); + float oldFogStart = RenderSystem.getShaderFogStart(); + RenderSystem.setShaderFogStart(Float.MAX_VALUE); + RenderSystem.setShaderColor(1f, 1f, 1f, 1f); + + poseStack.pushPose(); + poseStack.translate(-camera.getPosition().x, + -camera.getPosition().y + camera.eyeHeight, -camera.getPosition().z); + + cameraPathVertexBuffer.bind(); + cameraPathVertexBuffer.drawWithShader(poseStack.last().pose(), RenderSystem.getProjectionMatrix(), GameRenderer.getRendertypeLinesShader()); + VertexBuffer.unbind(); + + if (replayServer.replayPaused) { + var handler = new CapturingKeyframeHandler(); + var fovHandler = new FovCapturingKeyframeHandler(); + + fovHandler.fov = Minecraft.getInstance().options.fov().get(); + state.applyKeyframes(handler, replayTick); + state.applyKeyframes(fovHandler, replayTick); + if (handler.position != null) { + BufferBuilder bufferBuilder = Tesselator.getInstance().begin(VertexFormat.Mode.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL); + renderCamera(bufferBuilder, handler.position, handler.angle, fovHandler.fov, getCameraColour(false, true), 1.0f); + + var oldModelViewMatrix = new Matrix4f(RenderSystem.getModelViewMatrix()); + RenderSystem.getModelViewMatrix().set(poseStack.last().pose()); + BufferUploader.drawWithShader(bufferBuilder.buildOrThrow()); + RenderSystem.getModelViewMatrix().set(oldModelViewMatrix); + } + } + + poseStack.popPose(); + + RenderSystem.setShaderFogStart(oldFogStart); + RenderSystem.enableCull(); + } + + private record CameraPathArgs(int lastLastCameraTick, int lastCameraTick, int nextCameraTick, int nextNextCameraTick) {} + + private static CameraPathArgs createCameraPathArgs(EditorState state, int replayTick, EnumSet supportedKeyframes) { + int lastCameraTick = -1; + int nextCameraTick = -1; + + for (int trackIndex = 0; trackIndex < state.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = state.keyframeTracks.get(trackIndex); + if (keyframeTrack.enabled && supportedKeyframes.contains(keyframeTrack.keyframeType) && !keyframeTrack.keyframesByTick.isEmpty()) { + var lastEntry = keyframeTrack.keyframesByTick.floorEntry(replayTick); + var nextEntry = keyframeTrack.keyframesByTick.ceilingEntry(replayTick + 1); + + if (lastEntry != null && (lastCameraTick == -1 || lastEntry.getKey() > lastCameraTick)) { + lastCameraTick = lastEntry.getKey(); + } + if (nextEntry != null && (nextCameraTick == -1 || nextEntry.getKey() < nextCameraTick)) { + nextCameraTick = nextEntry.getKey(); + } + + if (lastEntry != null && nextEntry != null) { + break; + } + } + } + + int lastLastCameraTick = -1; + int nextNextCameraTick = -1; + + for (int trackIndex = 0; trackIndex < state.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = state.keyframeTracks.get(trackIndex); + if (keyframeTrack.enabled && supportedKeyframes.contains(keyframeTrack.keyframeType) && !keyframeTrack.keyframesByTick.isEmpty()) { + var lastLastEntry = lastCameraTick == -1 ? null : keyframeTrack.keyframesByTick.floorEntry(lastCameraTick - 1); + var nextNextEntry = nextCameraTick == -1 ? null : keyframeTrack.keyframesByTick.ceilingEntry(nextCameraTick + 1); + + if (lastLastEntry != null && lastLastCameraTick == -1) { + lastLastCameraTick = lastLastEntry.getKey(); + } + if (nextNextEntry != null && nextNextCameraTick == -1) { + nextNextCameraTick = nextNextEntry.getKey(); + } + } + } + + return new CameraPathArgs(lastLastCameraTick, lastCameraTick, nextCameraTick, nextNextCameraTick); + } + + private static void buildCameraPath(EditorState state, CameraPathArgs args, BufferBuilder bufferBuilder) { + var handler = new CapturingKeyframeHandler(); + var fovHandler = new FovCapturingKeyframeHandler(); + float defaultFov = Minecraft.getInstance().options.fov().get(); + + if (args.lastCameraTick != -1) { + fovHandler.fov = defaultFov; + state.applyKeyframes(handler, args.lastCameraTick); + state.applyKeyframes(fovHandler, args.lastCameraTick); + + renderCamera(bufferBuilder, handler.position, handler.angle, fovHandler.fov, + getCameraColour(false, false), 1.0f); + + if (args.lastLastCameraTick != -1) { + fovHandler.fov = defaultFov; + state.applyKeyframes(handler, args.lastLastCameraTick); + state.applyKeyframes(fovHandler, args.lastLastCameraTick); + + renderCamera(bufferBuilder, handler.position, handler.angle, fovHandler.fov, + getCameraColour(false, false), 0.6f); + renderPath(bufferBuilder, args.lastLastCameraTick, args.lastCameraTick, state, handler, 0.6f); + } + } + + if (args.nextCameraTick != -1) { + fovHandler.fov = defaultFov; + state.applyKeyframes(handler, args.nextCameraTick); + state.applyKeyframes(fovHandler, args.nextCameraTick); + + renderCamera(bufferBuilder, handler.position, handler.angle, fovHandler.fov, + getCameraColour(false, false), 1.0f); + + if (args.nextNextCameraTick != -1) { + fovHandler.fov = defaultFov; + state.applyKeyframes(handler, args.nextNextCameraTick); + state.applyKeyframes(fovHandler, args.nextNextCameraTick); + + renderCamera(bufferBuilder, handler.position, handler.angle, fovHandler.fov, + getCameraColour(false, false), 0.6f); + renderPath(bufferBuilder, args.nextCameraTick, args.nextNextCameraTick, state, handler, 0.6f); + } + } + + if (args.lastCameraTick != -1 && args.nextCameraTick != -1) { + renderPath(bufferBuilder, args.lastCameraTick, args.nextCameraTick, state, handler, 1.0f); + } + } + + private static int getCameraColour(boolean selected, boolean current) { + if (current) { + return 0x20FF20; + } else if (selected) { + return 0xFF2020; + } else { + return 0xFFFF20; + } + } + + private static void renderPath(BufferBuilder bufferBuilder, int fromTick, int toTick, + EditorState editorState, CapturingKeyframeHandler handler, float opacity) { + Vector3f lastPosition = null; + + int step = (toTick - fromTick) / 2000 + 1; + + for (int tick = fromTick; tick <= toTick; tick += step) { + editorState.applyKeyframes(handler, tick); + Vector3f rawPosition = new Vector3f(handler.position); + + double x = rawPosition.x; + double y = rawPosition.y; + double z = rawPosition.z; + + Vector3f position = new Vector3f((float) x, (float) y, (float) z); + + if (lastPosition != null) { + float dx = position.x - lastPosition.x; + float dy = position.y - lastPosition.y; + float dz = position.z - lastPosition.z; + float distanceInv = 1f / (float) Math.sqrt(dx*dx + dy*dy + dz*dz); + dx *= distanceInv; + dy *= distanceInv; + dz *= distanceInv; + + bufferBuilder.addVertex(lastPosition.x, lastPosition.y, lastPosition.z).setColor(1.0f, 1.0f, 0.1f, 0.0f).setNormal(dx, dy, dz); + bufferBuilder.addVertex( position.x, position.y, position.z).setColor(1.0f, 1.0f, 0.1f, opacity).setNormal(dx, dy, dz); + } + + lastPosition = position; + } + } + + private static final PoseStack cameraPoseStack = new PoseStack(); + private static void renderCamera(BufferBuilder bufferBuilder, Vector3f position, Quaternionf angle, float fov, int rgb, float opacity) { + cameraPoseStack.pushPose(); + cameraPoseStack.translate(position.x, position.y, position.z); + cameraPoseStack.mulPose(angle); + + PoseStack.Pose pose = cameraPoseStack.last(); + + EditorState editorState = EditorStateManager.getCurrent(); + + float aspectRatio; + if (editorState != null && editorState.replayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { + aspectRatio = editorState.replayVisuals.changeAspectRatio.aspectRatio(); + } else { + Window window = Minecraft.getInstance().getWindow(); + aspectRatio = (float) window.getWidth() / window.getHeight(); + } + + float focalLength = Utils.fovToFocalLength(fov); + + float targetArea = (float) Math.sqrt(aspectRatio) * 0.3f; + float d1 = (float) Math.sqrt(targetArea / aspectRatio * (focalLength*focalLength)); + float d2 = 0.5f; + float d = (d1 + d2)/2.0f; + float h = d / focalLength; + float w = h * aspectRatio; + + float red = ((rgb >> 16) & 0xFF)/255f; + float green = ((rgb >> 8) & 0xFF)/255f; + float blue = (rgb & 0xFF)/255f; + + Shapes.line(bufferBuilder, pose, Vec3.ZERO, new Vec3(w, h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, new Vec3(w, h, d), new Vec3(-w, h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, Vec3.ZERO, new Vec3(-w, h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, new Vec3(-w, h, d), new Vec3(-w, -h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, Vec3.ZERO, new Vec3(-w, -h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, new Vec3(-w, -h, d), new Vec3(w, -h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, Vec3.ZERO, new Vec3(w, -h, d), red, green, blue, opacity); + Shapes.line(bufferBuilder, pose, new Vec3(w, -h, d), new Vec3(w, h, d), red, green, blue, opacity); + + cameraPoseStack.popPose(); + } + + private static final EnumSet SUPPORTED_CAMERA_KEYFRAMES = EnumSet.of(KeyframeType.CAMERA, KeyframeType.CAMERA_ORBIT); + + private static class CapturingKeyframeHandler implements KeyframeHandler { + private Vector3f position; + private Quaternionf angle; + + @Override + public EnumSet supportedKeyframes() { + return SUPPORTED_CAMERA_KEYFRAMES; + } + + @Override + public boolean alwaysApplyLastKeyframe() { + return true; + } + + @Override + public void applyCameraPosition(Vector3f position, float yaw, float pitch, float roll) { + this.position = position; + this.angle = new Quaternionf().rotationYXZ((float) -Math.toRadians(yaw), (float) Math.toRadians(pitch), (float) -Math.toRadians(roll)); + } + } + + private static class FovCapturingKeyframeHandler implements KeyframeHandler { + private float fov; + + @Override + public EnumSet supportedKeyframes() { + return EnumSet.of(KeyframeType.FOV); + } + + @Override + public boolean alwaysApplyLastKeyframe() { + return true; + } + + @Override + public void applyFov(float fov) { + this.fov = fov; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java b/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java new file mode 100644 index 0000000..b352fd8 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/CameraRotation.java @@ -0,0 +1,61 @@ +package com.moulberry.flashback.visuals; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.editor.ui.ReplayUI; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import org.joml.Quaternionf; + +public class CameraRotation { + + private static final FastNoiseLite fastNoiseLite = new FastNoiseLite(); + + private static float shakeTimeY = 0.0f; + private static float shakeTimeX = 0.0f; + private static float lastShakeReplayTick = 0.0f; + + public static Quaternionf modifyViewQuaternion(Quaternionf quaternionf) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState == null) { + return quaternionf; + } + + if (ReplayUI.isMovingCamera()) { + return quaternionf; + } + + ReplayVisuals visuals = editorState.replayVisuals; + quaternionf = new Quaternionf(quaternionf); + + if (visuals.overrideRoll) { + quaternionf = quaternionf.rotateZ((float) Math.toRadians(visuals.overrideRollAmount)); + } + + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null && visuals.overrideCameraShake && (Flashback.isExporting() || !replayServer.replayPaused)) { + float tick = replayServer.getPartialReplayTick(); + if (tick < lastShakeReplayTick) { + lastShakeReplayTick = tick; + shakeTimeY = 0.0f; + shakeTimeX = 0.0f; + } else if (tick > lastShakeReplayTick) { + float yFrequency = visuals.cameraShakeYFrequency; + float xFrequency = visuals.cameraShakeXFrequency; + + shakeTimeY += (tick - lastShakeReplayTick) * yFrequency * 2.0f; + shakeTimeX += (tick - lastShakeReplayTick) * xFrequency * 2.0f; + lastShakeReplayTick = tick; + } + + float yAmplitude = visuals.cameraShakeYAmplitude; + float xAmplitude = visuals.cameraShakeXAmplitude; + + float yRot = fastNoiseLite.GetNoise(shakeTimeX, -10000) * 2*(float)Math.PI; + float xRot = fastNoiseLite.GetNoise(-10000, shakeTimeY) * 2*(float)Math.PI; + quaternionf = quaternionf.rotateYXZ(yRot * xAmplitude/360, xRot * yAmplitude/360, 0); + } + return quaternionf; + } + +} diff --git a/src/main/java/com/moulberry/flashback/visuals/FastNoiseLite.java b/src/main/java/com/moulberry/flashback/visuals/FastNoiseLite.java new file mode 100644 index 0000000..7afe2cf --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/FastNoiseLite.java @@ -0,0 +1,2609 @@ +package com.moulberry.flashback.visuals;// MIT License +// +// Copyright(c) 2023 Jordan Peck (jordan.me2@gmail.com) +// Copyright(c) 2023 Contributors +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +// +// .'',;:cldxkO00KKXXNNWWWNNXKOkxdollcc::::::;:::ccllloooolllllllllooollc:,'... ...........',;cldxkO000Okxdlc::;;;,,;;;::cclllllll +// ..',;:ldxO0KXXNNNNNNNNXXK0kxdolcc::::::;;;,,,,,,;;;;;;;;;;:::cclllllc:;'.... ...........',;:ldxO0KXXXK0Okxdolc::;;;;::cllodddddo +// ...',:loxO0KXNNNNNXXKK0Okxdolc::;::::::::;;;,,'''''.....''',;:clllllc:;,'............''''''''',;:loxO0KXNNNNNXK0Okxdollccccllodxxxxxxd +// ....';:ldkO0KXXXKK00Okxdolcc:;;;;;::cclllcc:;;,''..... ....',;clooddolcc:;;;;,,;;;;;::::;;;;;;:cloxk0KXNWWWWWWNXKK0Okxddoooddxxkkkkkxx +// .....';:ldxkOOOOOkxxdolcc:;;;,,,;;:cllooooolcc:;'... ..,:codxkkkxddooollloooooooollcc:::::clodkO0KXNWWWWWWNNXK00Okxxxxxxxxkkkkxxx +// . ....';:cloddddo___________,,,,;;:clooddddoolc:,... ..,:ldx__00OOOkkk___kkkkkkxxdollc::::cclodkO0KXXNNNNNNXXK0OOkxxxxxxxxxxxxddd +// .......',;:cccc:| |,,,;;:cclooddddoll:;'.. ..';cox| \KKK000| |KK00OOkxdocc___;::clldxxkO0KKKKK00Okkxdddddddddddddddoo +// .......'',,,,,''| ________|',,;;::cclloooooolc:;'......___:ldk| \KK000| |XKKK0Okxolc| |;;::cclodxxkkkkxxdoolllcclllooodddooooo +// ''......''''....| | ....'',,,,;;;::cclloooollc:;,''.'| |oxk| \OOO0| |KKK00Oxdoll|___|;;;;;::ccllllllcc::;;,,;;;:cclloooooooo +// ;;,''.......... | |_____',,;;;____:___cllo________.___| |___| \xkk| |KK_______ool___:::;________;;;_______...'',;;:ccclllloo +// c:;,''......... | |:::/ ' |lo/ | | \dx| |0/ \d| |cc/ |'/ \......',,;;:ccllo +// ol:;,'..........| _____|ll/ __ |o/ ______|____ ___| | \o| |/ ___ \| |o/ ______|/ ___ \ .......'',;:clo +// dlc;,...........| |::clooo| / | |x\___ \KXKKK0| |dol| |\ \| | | | | |d\___ \..| | / / ....',:cl +// xoc;'... .....'| |llodddd| \__| |_____\ \KKK0O| |lc:| |'\ | |___| | |_____\ \.| |_/___/... ...',;:c +// dlc;'... ....',;| |oddddddo\ | |Okkx| |::;| |..\ |\ /| | | \ |... ....',;:c +// ol:,'.......',:c|___|xxxddollc\_____,___|_________/ddoll|___|,,,|___|...\_____|:\ ______/l|___|_________/...\________|'........',;::cc +// c:;'.......';:codxxkkkkxxolc::;::clodxkOO0OOkkxdollc::;;,,''''',,,,''''''''''',,'''''',;:loxkkOOkxol:;,'''',,;:ccllcc:;,'''''',;::ccll +// ;,'.......',:codxkOO0OOkxdlc:;,,;;:cldxxkkxxdolc:;;,,''.....'',;;:::;;,,,'''''........,;cldkO0KK0Okdoc::;;::cloodddoolc:;;;;;::ccllooo +// .........',;:lodxOO0000Okdoc:,,',,;:clloddoolc:;,''.......'',;:clooollc:;;,,''.......',:ldkOKXNNXX0Oxdolllloddxxxxxxdolccccccllooodddd +// . .....';:cldxkO0000Okxol:;,''',,;::cccc:;,,'.......'',;:cldxxkkxxdolc:;;,'.......';coxOKXNWWWNXKOkxddddxxkkkkkkxdoollllooddxxxxkkk +// ....',;:codxkO000OOxdoc:;,''',,,;;;;,''.......',,;:clodkO00000Okxolc::;,,''..',;:ldxOKXNWWWNNK0OkkkkkkkkkkkxxddooooodxxkOOOOO000 +// ....',;;clodxkkOOOkkdolc:;,,,,,,,,'..........,;:clodxkO0KKXKK0Okxdolcc::;;,,,;;:codkO0XXNNNNXKK0OOOOOkkkkxxdoollloodxkO0KKKXXXXX +// +// VERSION: 1.1.1 +// https://github.com/Auburn/FastNoiseLite + +// To switch between using floats or doubles for input position, +// perform a file-wide replace on the following strings (including /*FNLfloat*/) +// /*FNLfloat*/ float +// /*FNLfloat*/ double + +public class FastNoiseLite +{ + public enum NoiseType + { + OpenSimplex2, + OpenSimplex2S, + Cellular, + Perlin, + ValueCubic, + Value + }; + + public enum RotationType3D + { + None, + ImproveXYPlanes, + ImproveXZPlanes + }; + + public enum FractalType + { + None, + FBm, + Ridged, + PingPong, + DomainWarpProgressive, + DomainWarpIndependent + }; + + public enum CellularDistanceFunction + { + Euclidean, + EuclideanSq, + Manhattan, + Hybrid + }; + + public enum CellularReturnType + { + CellValue, + Distance, + Distance2, + Distance2Add, + Distance2Sub, + Distance2Mul, + Distance2Div + }; + + public enum DomainWarpType + { + OpenSimplex2, + OpenSimplex2Reduced, + BasicGrid + }; + + private enum TransformType3D + { + None, + ImproveXYPlanes, + ImproveXZPlanes, + DefaultOpenSimplex2 + }; + + private int mSeed = 1337; + private float mFrequency = 0.01f; + private NoiseType mNoiseType = NoiseType.OpenSimplex2; + private RotationType3D mRotationType3D = RotationType3D.None; + private TransformType3D mTransformType3D = TransformType3D.DefaultOpenSimplex2; + + private FractalType mFractalType = FractalType.None; + private int mOctaves = 3; + private float mLacunarity = 2.0f; + private float mGain = 0.5f; + private float mWeightedStrength = 0.0f; + private float mPingPongStrength = 2.0f; + + private float mFractalBounding = 1 / 1.75f; + + private CellularDistanceFunction mCellularDistanceFunction = CellularDistanceFunction.EuclideanSq; + private CellularReturnType mCellularReturnType = CellularReturnType.Distance; + private float mCellularJitterModifier = 1.0f; + + private DomainWarpType mDomainWarpType = DomainWarpType.OpenSimplex2; + private TransformType3D mWarpTransformType3D = TransformType3D.DefaultOpenSimplex2; + private float mDomainWarpAmp = 1.0f; + + /// + /// Create new FastNoise object with default seed + /// + public FastNoiseLite() { } + + /// + /// Create new FastNoise object with specified seed + /// + public FastNoiseLite(int seed) + { + SetSeed(seed); + } + + /// + /// Sets seed used for all noise types + /// + /// + /// Default: 1337 + /// + public void SetSeed(int seed) { mSeed = seed; } + + /// + /// Sets frequency for all noise types + /// + /// + /// Default: 0.01 + /// + public void SetFrequency(float frequency) { mFrequency = frequency; } + + /// + /// Sets noise algorithm used for GetNoise(...) + /// + /// + /// Default: OpenSimplex2 + /// + public void SetNoiseType(NoiseType noiseType) + { + mNoiseType = noiseType; + UpdateTransformType3D(); + } + + /// + /// Sets domain rotation type for 3D Noise and 3D DomainWarp. + /// Can aid in reducing directional artifacts when sampling a 2D plane in 3D + /// + /// + /// Default: None + /// + public void SetRotationType3D(RotationType3D rotationType3D) + { + mRotationType3D = rotationType3D; + UpdateTransformType3D(); + UpdateWarpTransformType3D(); + } + + /// + /// Sets method for combining octaves in all fractal noise types + /// + /// + /// Default: None + /// Note: FractalType.DomainWarp... only affects DomainWarp(...) + /// + public void SetFractalType(FractalType fractalType) { mFractalType = fractalType; } + + /// + /// Sets octave count for all fractal noise types + /// + /// + /// Default: 3 + /// + public void SetFractalOctaves(int octaves) + { + mOctaves = octaves; + CalculateFractalBounding(); + } + + /// + /// Sets octave lacunarity for all fractal noise types + /// + /// + /// Default: 2.0 + /// + public void SetFractalLacunarity(float lacunarity) { mLacunarity = lacunarity; } + + /// + /// Sets octave gain for all fractal noise types + /// + /// + /// Default: 0.5 + /// + public void SetFractalGain(float gain) + { + mGain = gain; + CalculateFractalBounding(); + } + + /// + /// Sets octave weighting for all none DomainWarp fratal types + /// + /// + /// Default: 0.0 + /// Note: Keep between 0...1 to maintain -1...1 output bounding + /// + public void SetFractalWeightedStrength(float weightedStrength) { mWeightedStrength = weightedStrength; } + + /// + /// Sets strength of the fractal ping pong effect + /// + /// + /// Default: 2.0 + /// + public void SetFractalPingPongStrength(float pingPongStrength) { mPingPongStrength = pingPongStrength; } + + + /// + /// Sets distance function used in cellular noise calculations + /// + /// + /// Default: Distance + /// + public void SetCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) { mCellularDistanceFunction = cellularDistanceFunction; } + + /// + /// Sets return type from cellular noise calculations + /// + /// + /// Default: EuclideanSq + /// + public void SetCellularReturnType(CellularReturnType cellularReturnType) { mCellularReturnType = cellularReturnType; } + + /// + /// Sets the maximum distance a cellular point can move from it's grid position + /// + /// + /// Default: 1.0 + /// Note: Setting this higher than 1 will cause artifacts + /// + public void SetCellularJitter(float cellularJitter) { mCellularJitterModifier = cellularJitter; } + + + /// + /// Sets the warp algorithm when using DomainWarp(...) + /// + /// + /// Default: OpenSimplex2 + /// + public void SetDomainWarpType(DomainWarpType domainWarpType) + { + mDomainWarpType = domainWarpType; + UpdateWarpTransformType3D(); + } + + + /// + /// Sets the maximum warp distance from original position when using DomainWarp(...) + /// + /// + /// Default: 1.0 + /// + public void SetDomainWarpAmp(float domainWarpAmp) { mDomainWarpAmp = domainWarpAmp; } + + + /// + /// 2D noise at given position using current settings + /// + /// + /// Noise output bounded between -1...1 + /// + public float GetNoise(/*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + x *= mFrequency; + y *= mFrequency; + + switch (mNoiseType) + { + case OpenSimplex2: + case OpenSimplex2S: + { + final /*FNLfloat*/ float SQRT3 = (/*FNLfloat*/ float)1.7320508075688772935274463415059; + final /*FNLfloat*/ float F2 = 0.5f * (SQRT3 - 1); + /*FNLfloat*/ float t = (x + y) * F2; + x += t; + y += t; + } + break; + default: + break; + } + + switch (mFractalType) + { + default: + return GenNoiseSingle(mSeed, x, y); + case FBm: + return GenFractalFBm(x, y); + case Ridged: + return GenFractalRidged(x, y); + case PingPong: + return GenFractalPingPong(x, y); + } + } + + /// + /// 3D noise at given position using current settings + /// + /// + /// Noise output bounded between -1...1 + /// + public float GetNoise(/*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + x *= mFrequency; + y *= mFrequency; + z *= mFrequency; + + switch (mTransformType3D) + { + case ImproveXYPlanes: + { + /*FNLfloat*/ float xy = x + y; + /*FNLfloat*/ float s2 = xy * -(/*FNLfloat*/ float)0.211324865405187; + z *= (/*FNLfloat*/ float)0.577350269189626; + x += s2 - z; + y = y + s2 - z; + z += xy * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case ImproveXZPlanes: + { + /*FNLfloat*/ float xz = x + z; + /*FNLfloat*/ float s2 = xz * -(/*FNLfloat*/ float)0.211324865405187; + y *= (/*FNLfloat*/ float)0.577350269189626; + x += s2 - y; + z += s2 - y; + y += xz * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case DefaultOpenSimplex2: + { + final /*FNLfloat*/ float R3 = (/*FNLfloat*/ float)(2.0 / 3.0); + /*FNLfloat*/ float r = (x + y + z) * R3; // Rotation, not skew + x = r - x; + y = r - y; + z = r - z; + } + break; + default: + break; + } + + switch (mFractalType) + { + default: + return GenNoiseSingle(mSeed, x, y, z); + case FBm: + return GenFractalFBm(x, y, z); + case Ridged: + return GenFractalRidged(x, y, z); + case PingPong: + return GenFractalPingPong(x, y, z); + } + } + + + /// + /// 2D warps the input position using current domain warp settings + /// + /// + /// Example usage with GetNoise + /// DomainWarp(coord) + /// noise = GetNoise(x, y) + /// + public void DomainWarp(Vector2 coord) + { + switch (mFractalType) + { + default: + DomainWarpSingle(coord); + break; + case DomainWarpProgressive: + DomainWarpFractalProgressive(coord); + break; + case DomainWarpIndependent: + DomainWarpFractalIndependent(coord); + break; + } + } + + /// + /// 3D warps the input position using current domain warp settings + /// + /// + /// Example usage with GetNoise + /// DomainWarp(coord) + /// noise = GetNoise(x, y, z) + /// + public void DomainWarp(Vector3 coord) + { + switch (mFractalType) + { + default: + DomainWarpSingle(coord); + break; + case DomainWarpProgressive: + DomainWarpFractalProgressive(coord); + break; + case DomainWarpIndependent: + DomainWarpFractalIndependent(coord); + break; + } + } + + + private static final float[] Gradients2D = { + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, + 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, + 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, + -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, + -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, + 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, + 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, + -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, + -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, + 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, + 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, + -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, + -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, + 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, + 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, + -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, + -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.130526192220052f, 0.99144486137381f, 0.38268343236509f, 0.923879532511287f, 0.608761429008721f, 0.793353340291235f, 0.793353340291235f, 0.608761429008721f, + 0.923879532511287f, 0.38268343236509f, 0.99144486137381f, 0.130526192220051f, 0.99144486137381f, -0.130526192220051f, 0.923879532511287f, -0.38268343236509f, + 0.793353340291235f, -0.60876142900872f, 0.608761429008721f, -0.793353340291235f, 0.38268343236509f, -0.923879532511287f, 0.130526192220052f, -0.99144486137381f, + -0.130526192220052f, -0.99144486137381f, -0.38268343236509f, -0.923879532511287f, -0.608761429008721f, -0.793353340291235f, -0.793353340291235f, -0.608761429008721f, + -0.923879532511287f, -0.38268343236509f, -0.99144486137381f, -0.130526192220052f, -0.99144486137381f, 0.130526192220051f, -0.923879532511287f, 0.38268343236509f, + -0.793353340291235f, 0.608761429008721f, -0.608761429008721f, 0.793353340291235f, -0.38268343236509f, 0.923879532511287f, -0.130526192220052f, 0.99144486137381f, + 0.38268343236509f, 0.923879532511287f, 0.923879532511287f, 0.38268343236509f, 0.923879532511287f, -0.38268343236509f, 0.38268343236509f, -0.923879532511287f, + -0.38268343236509f, -0.923879532511287f, -0.923879532511287f, -0.38268343236509f, -0.923879532511287f, 0.38268343236509f, -0.38268343236509f, 0.923879532511287f, + }; + + private static final float[] RandVecs2D = { + -0.2700222198f, -0.9628540911f, 0.3863092627f, -0.9223693152f, 0.04444859006f, -0.999011673f, -0.5992523158f, -0.8005602176f, -0.7819280288f, 0.6233687174f, 0.9464672271f, 0.3227999196f, -0.6514146797f, -0.7587218957f, 0.9378472289f, 0.347048376f, + -0.8497875957f, -0.5271252623f, -0.879042592f, 0.4767432447f, -0.892300288f, -0.4514423508f, -0.379844434f, -0.9250503802f, -0.9951650832f, 0.0982163789f, 0.7724397808f, -0.6350880136f, 0.7573283322f, -0.6530343002f, -0.9928004525f, -0.119780055f, + -0.0532665713f, 0.9985803285f, 0.9754253726f, -0.2203300762f, -0.7665018163f, 0.6422421394f, 0.991636706f, 0.1290606184f, -0.994696838f, 0.1028503788f, -0.5379205513f, -0.84299554f, 0.5022815471f, -0.8647041387f, 0.4559821461f, -0.8899889226f, + -0.8659131224f, -0.5001944266f, 0.0879458407f, -0.9961252577f, -0.5051684983f, 0.8630207346f, 0.7753185226f, -0.6315704146f, -0.6921944612f, 0.7217110418f, -0.5191659449f, -0.8546734591f, 0.8978622882f, -0.4402764035f, -0.1706774107f, 0.9853269617f, + -0.9353430106f, -0.3537420705f, -0.9992404798f, 0.03896746794f, -0.2882064021f, -0.9575683108f, -0.9663811329f, 0.2571137995f, -0.8759714238f, -0.4823630009f, -0.8303123018f, -0.5572983775f, 0.05110133755f, -0.9986934731f, -0.8558373281f, -0.5172450752f, + 0.09887025282f, 0.9951003332f, 0.9189016087f, 0.3944867976f, -0.2439375892f, -0.9697909324f, -0.8121409387f, -0.5834613061f, -0.9910431363f, 0.1335421355f, 0.8492423985f, -0.5280031709f, -0.9717838994f, -0.2358729591f, 0.9949457207f, 0.1004142068f, + 0.6241065508f, -0.7813392434f, 0.662910307f, 0.7486988212f, -0.7197418176f, 0.6942418282f, -0.8143370775f, -0.5803922158f, 0.104521054f, -0.9945226741f, -0.1065926113f, -0.9943027784f, 0.445799684f, -0.8951327509f, 0.105547406f, 0.9944142724f, + -0.992790267f, 0.1198644477f, -0.8334366408f, 0.552615025f, 0.9115561563f, -0.4111755999f, 0.8285544909f, -0.5599084351f, 0.7217097654f, -0.6921957921f, 0.4940492677f, -0.8694339084f, -0.3652321272f, -0.9309164803f, -0.9696606758f, 0.2444548501f, + 0.08925509731f, -0.996008799f, 0.5354071276f, -0.8445941083f, -0.1053576186f, 0.9944343981f, -0.9890284586f, 0.1477251101f, 0.004856104961f, 0.9999882091f, 0.9885598478f, 0.1508291331f, 0.9286129562f, -0.3710498316f, -0.5832393863f, -0.8123003252f, + 0.3015207509f, 0.9534596146f, -0.9575110528f, 0.2883965738f, 0.9715802154f, -0.2367105511f, 0.229981792f, 0.9731949318f, 0.955763816f, -0.2941352207f, 0.740956116f, 0.6715534485f, -0.9971513787f, -0.07542630764f, 0.6905710663f, -0.7232645452f, + -0.290713703f, -0.9568100872f, 0.5912777791f, -0.8064679708f, -0.9454592212f, -0.325740481f, 0.6664455681f, 0.74555369f, 0.6236134912f, 0.7817328275f, 0.9126993851f, -0.4086316587f, -0.8191762011f, 0.5735419353f, -0.8812745759f, -0.4726046147f, + 0.9953313627f, 0.09651672651f, 0.9855650846f, -0.1692969699f, -0.8495980887f, 0.5274306472f, 0.6174853946f, -0.7865823463f, 0.8508156371f, 0.52546432f, 0.9985032451f, -0.05469249926f, 0.1971371563f, -0.9803759185f, 0.6607855748f, -0.7505747292f, + -0.03097494063f, 0.9995201614f, -0.6731660801f, 0.739491331f, -0.7195018362f, -0.6944905383f, 0.9727511689f, 0.2318515979f, 0.9997059088f, -0.0242506907f, 0.4421787429f, -0.8969269532f, 0.9981350961f, -0.061043673f, -0.9173660799f, -0.3980445648f, + -0.8150056635f, -0.5794529907f, -0.8789331304f, 0.4769450202f, 0.0158605829f, 0.999874213f, -0.8095464474f, 0.5870558317f, -0.9165898907f, -0.3998286786f, -0.8023542565f, 0.5968480938f, -0.5176737917f, 0.8555780767f, -0.8154407307f, -0.5788405779f, + 0.4022010347f, -0.9155513791f, -0.9052556868f, -0.4248672045f, 0.7317445619f, 0.6815789728f, -0.5647632201f, -0.8252529947f, -0.8403276335f, -0.5420788397f, -0.9314281527f, 0.363925262f, 0.5238198472f, 0.8518290719f, 0.7432803869f, -0.6689800195f, + -0.985371561f, -0.1704197369f, 0.4601468731f, 0.88784281f, 0.825855404f, 0.5638819483f, 0.6182366099f, 0.7859920446f, 0.8331502863f, -0.553046653f, 0.1500307506f, 0.9886813308f, -0.662330369f, -0.7492119075f, -0.668598664f, 0.743623444f, + 0.7025606278f, 0.7116238924f, -0.5419389763f, -0.8404178401f, -0.3388616456f, 0.9408362159f, 0.8331530315f, 0.5530425174f, -0.2989720662f, -0.9542618632f, 0.2638522993f, 0.9645630949f, 0.124108739f, -0.9922686234f, -0.7282649308f, -0.6852956957f, + 0.6962500149f, 0.7177993569f, -0.9183535368f, 0.3957610156f, -0.6326102274f, -0.7744703352f, -0.9331891859f, -0.359385508f, -0.1153779357f, -0.9933216659f, 0.9514974788f, -0.3076565421f, -0.08987977445f, -0.9959526224f, 0.6678496916f, 0.7442961705f, + 0.7952400393f, -0.6062947138f, -0.6462007402f, -0.7631674805f, -0.2733598753f, 0.9619118351f, 0.9669590226f, -0.254931851f, -0.9792894595f, 0.2024651934f, -0.5369502995f, -0.8436138784f, -0.270036471f, -0.9628500944f, -0.6400277131f, 0.7683518247f, + -0.7854537493f, -0.6189203566f, 0.06005905383f, -0.9981948257f, -0.02455770378f, 0.9996984141f, -0.65983623f, 0.751409442f, -0.6253894466f, -0.7803127835f, -0.6210408851f, -0.7837781695f, 0.8348888491f, 0.5504185768f, -0.1592275245f, 0.9872419133f, + 0.8367622488f, 0.5475663786f, -0.8675753916f, -0.4973056806f, -0.2022662628f, -0.9793305667f, 0.9399189937f, 0.3413975472f, 0.9877404807f, -0.1561049093f, -0.9034455656f, 0.4287028224f, 0.1269804218f, -0.9919052235f, -0.3819600854f, 0.924178821f, + 0.9754625894f, 0.2201652486f, -0.3204015856f, -0.9472818081f, -0.9874760884f, 0.1577687387f, 0.02535348474f, -0.9996785487f, 0.4835130794f, -0.8753371362f, -0.2850799925f, -0.9585037287f, -0.06805516006f, -0.99768156f, -0.7885244045f, -0.6150034663f, + 0.3185392127f, -0.9479096845f, 0.8880043089f, 0.4598351306f, 0.6476921488f, -0.7619021462f, 0.9820241299f, 0.1887554194f, 0.9357275128f, -0.3527237187f, -0.8894895414f, 0.4569555293f, 0.7922791302f, 0.6101588153f, 0.7483818261f, 0.6632681526f, + -0.7288929755f, -0.6846276581f, 0.8729032783f, -0.4878932944f, 0.8288345784f, 0.5594937369f, 0.08074567077f, 0.9967347374f, 0.9799148216f, -0.1994165048f, -0.580730673f, -0.8140957471f, -0.4700049791f, -0.8826637636f, 0.2409492979f, 0.9705377045f, + 0.9437816757f, -0.3305694308f, -0.8927998638f, -0.4504535528f, -0.8069622304f, 0.5906030467f, 0.06258973166f, 0.9980393407f, -0.9312597469f, 0.3643559849f, 0.5777449785f, 0.8162173362f, -0.3360095855f, -0.941858566f, 0.697932075f, -0.7161639607f, + -0.002008157227f, -0.9999979837f, -0.1827294312f, -0.9831632392f, -0.6523911722f, 0.7578824173f, -0.4302626911f, -0.9027037258f, -0.9985126289f, -0.05452091251f, -0.01028102172f, -0.9999471489f, -0.4946071129f, 0.8691166802f, -0.2999350194f, 0.9539596344f, + 0.8165471961f, 0.5772786819f, 0.2697460475f, 0.962931498f, -0.7306287391f, -0.6827749597f, -0.7590952064f, -0.6509796216f, -0.907053853f, 0.4210146171f, -0.5104861064f, -0.8598860013f, 0.8613350597f, 0.5080373165f, 0.5007881595f, -0.8655698812f, + -0.654158152f, 0.7563577938f, -0.8382755311f, -0.545246856f, 0.6940070834f, 0.7199681717f, 0.06950936031f, 0.9975812994f, 0.1702942185f, -0.9853932612f, 0.2695973274f, 0.9629731466f, 0.5519612192f, -0.8338697815f, 0.225657487f, -0.9742067022f, + 0.4215262855f, -0.9068161835f, 0.4881873305f, -0.8727388672f, -0.3683854996f, -0.9296731273f, -0.9825390578f, 0.1860564427f, 0.81256471f, 0.5828709909f, 0.3196460933f, -0.9475370046f, 0.9570913859f, 0.2897862643f, -0.6876655497f, -0.7260276109f, + -0.9988770922f, -0.047376731f, -0.1250179027f, 0.992154486f, -0.8280133617f, 0.560708367f, 0.9324863769f, -0.3612051451f, 0.6394653183f, 0.7688199442f, -0.01623847064f, -0.9998681473f, -0.9955014666f, -0.09474613458f, -0.81453315f, 0.580117012f, + 0.4037327978f, -0.9148769469f, 0.9944263371f, 0.1054336766f, -0.1624711654f, 0.9867132919f, -0.9949487814f, -0.100383875f, -0.6995302564f, 0.7146029809f, 0.5263414922f, -0.85027327f, -0.5395221479f, 0.841971408f, 0.6579370318f, 0.7530729462f, + 0.01426758847f, -0.9998982128f, -0.6734383991f, 0.7392433447f, 0.639412098f, -0.7688642071f, 0.9211571421f, 0.3891908523f, -0.146637214f, -0.9891903394f, -0.782318098f, 0.6228791163f, -0.5039610839f, -0.8637263605f, -0.7743120191f, -0.6328039957f, + }; + + private static final float[] Gradients3D = { + 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, + 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, + 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, + 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, + 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, + 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, + 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, + 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, + 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, + 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, + 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, + 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, + 0, 1, 1, 0, 0,-1, 1, 0, 0, 1,-1, 0, 0,-1,-1, 0, + 1, 0, 1, 0, -1, 0, 1, 0, 1, 0,-1, 0, -1, 0,-1, 0, + 1, 1, 0, 0, -1, 1, 0, 0, 1,-1, 0, 0, -1,-1, 0, 0, + 1, 1, 0, 0, 0,-1, 1, 0, -1, 1, 0, 0, 0,-1,-1, 0 + }; + + private static final float[] RandVecs3D = { + -0.7292736885f, -0.6618439697f, 0.1735581948f, 0, 0.790292081f, -0.5480887466f, -0.2739291014f, 0, 0.7217578935f, 0.6226212466f, -0.3023380997f, 0, 0.565683137f, -0.8208298145f, -0.0790000257f, 0, 0.760049034f, -0.5555979497f, -0.3370999617f, 0, 0.3713945616f, 0.5011264475f, 0.7816254623f, 0, -0.1277062463f, -0.4254438999f, -0.8959289049f, 0, -0.2881560924f, -0.5815838982f, 0.7607405838f, 0, + 0.5849561111f, -0.662820239f, -0.4674352136f, 0, 0.3307171178f, 0.0391653737f, 0.94291689f, 0, 0.8712121778f, -0.4113374369f, -0.2679381538f, 0, 0.580981015f, 0.7021915846f, 0.4115677815f, 0, 0.503756873f, 0.6330056931f, -0.5878203852f, 0, 0.4493712205f, 0.601390195f, 0.6606022552f, 0, -0.6878403724f, 0.09018890807f, -0.7202371714f, 0, -0.5958956522f, -0.6469350577f, 0.475797649f, 0, + -0.5127052122f, 0.1946921978f, -0.8361987284f, 0, -0.9911507142f, -0.05410276466f, -0.1212153153f, 0, -0.2149721042f, 0.9720882117f, -0.09397607749f, 0, -0.7518650936f, -0.5428057603f, 0.3742469607f, 0, 0.5237068895f, 0.8516377189f, -0.02107817834f, 0, 0.6333504779f, 0.1926167129f, -0.7495104896f, 0, -0.06788241606f, 0.3998305789f, 0.9140719259f, 0, -0.5538628599f, -0.4729896695f, -0.6852128902f, 0, + -0.7261455366f, -0.5911990757f, 0.3509933228f, 0, -0.9229274737f, -0.1782808786f, 0.3412049336f, 0, -0.6968815002f, 0.6511274338f, 0.3006480328f, 0, 0.9608044783f, -0.2098363234f, -0.1811724921f, 0, 0.06817146062f, -0.9743405129f, 0.2145069156f, 0, -0.3577285196f, -0.6697087264f, -0.6507845481f, 0, -0.1868621131f, 0.7648617052f, -0.6164974636f, 0, -0.6541697588f, 0.3967914832f, 0.6439087246f, 0, + 0.6993340405f, -0.6164538506f, 0.3618239211f, 0, -0.1546665739f, 0.6291283928f, 0.7617583057f, 0, -0.6841612949f, -0.2580482182f, -0.6821542638f, 0, 0.5383980957f, 0.4258654885f, 0.7271630328f, 0, -0.5026987823f, -0.7939832935f, -0.3418836993f, 0, 0.3202971715f, 0.2834415347f, 0.9039195862f, 0, 0.8683227101f, -0.0003762656404f, -0.4959995258f, 0, 0.791120031f, -0.08511045745f, 0.6057105799f, 0, + -0.04011016052f, -0.4397248749f, 0.8972364289f, 0, 0.9145119872f, 0.3579346169f, -0.1885487608f, 0, -0.9612039066f, -0.2756484276f, 0.01024666929f, 0, 0.6510361721f, -0.2877799159f, -0.7023778346f, 0, -0.2041786351f, 0.7365237271f, 0.644859585f, 0, -0.7718263711f, 0.3790626912f, 0.5104855816f, 0, -0.3060082741f, -0.7692987727f, 0.5608371729f, 0, 0.454007341f, -0.5024843065f, 0.7357899537f, 0, + 0.4816795475f, 0.6021208291f, -0.6367380315f, 0, 0.6961980369f, -0.3222197429f, 0.641469197f, 0, -0.6532160499f, -0.6781148932f, 0.3368515753f, 0, 0.5089301236f, -0.6154662304f, -0.6018234363f, 0, -0.1635919754f, -0.9133604627f, -0.372840892f, 0, 0.52408019f, -0.8437664109f, 0.1157505864f, 0, 0.5902587356f, 0.4983817807f, -0.6349883666f, 0, 0.5863227872f, 0.494764745f, 0.6414307729f, 0, + 0.6779335087f, 0.2341345225f, 0.6968408593f, 0, 0.7177054546f, -0.6858979348f, 0.120178631f, 0, -0.5328819713f, -0.5205125012f, 0.6671608058f, 0, -0.8654874251f, -0.0700727088f, -0.4960053754f, 0, -0.2861810166f, 0.7952089234f, 0.5345495242f, 0, -0.04849529634f, 0.9810836427f, -0.1874115585f, 0, -0.6358521667f, 0.6058348682f, 0.4781800233f, 0, 0.6254794696f, -0.2861619734f, 0.7258696564f, 0, + -0.2585259868f, 0.5061949264f, -0.8227581726f, 0, 0.02136306781f, 0.5064016808f, -0.8620330371f, 0, 0.200111773f, 0.8599263484f, 0.4695550591f, 0, 0.4743561372f, 0.6014985084f, -0.6427953014f, 0, 0.6622993731f, -0.5202474575f, -0.5391679918f, 0, 0.08084972818f, -0.6532720452f, 0.7527940996f, 0, -0.6893687501f, 0.0592860349f, 0.7219805347f, 0, -0.1121887082f, -0.9673185067f, 0.2273952515f, 0, + 0.7344116094f, 0.5979668656f, -0.3210532909f, 0, 0.5789393465f, -0.2488849713f, 0.7764570201f, 0, 0.6988182827f, 0.3557169806f, -0.6205791146f, 0, -0.8636845529f, -0.2748771249f, -0.4224826141f, 0, -0.4247027957f, -0.4640880967f, 0.777335046f, 0, 0.5257722489f, -0.8427017621f, 0.1158329937f, 0, 0.9343830603f, 0.316302472f, -0.1639543925f, 0, -0.1016836419f, -0.8057303073f, -0.5834887393f, 0, + -0.6529238969f, 0.50602126f, -0.5635892736f, 0, -0.2465286165f, -0.9668205684f, -0.06694497494f, 0, -0.9776897119f, -0.2099250524f, -0.007368825344f, 0, 0.7736893337f, 0.5734244712f, 0.2694238123f, 0, -0.6095087895f, 0.4995678998f, 0.6155736747f, 0, 0.5794535482f, 0.7434546771f, 0.3339292269f, 0, -0.8226211154f, 0.08142581855f, 0.5627293636f, 0, -0.510385483f, 0.4703667658f, 0.7199039967f, 0, + -0.5764971849f, -0.07231656274f, -0.8138926898f, 0, 0.7250628871f, 0.3949971505f, -0.5641463116f, 0, -0.1525424005f, 0.4860840828f, -0.8604958341f, 0, -0.5550976208f, -0.4957820792f, 0.667882296f, 0, -0.1883614327f, 0.9145869398f, 0.357841725f, 0, 0.7625556724f, -0.5414408243f, -0.3540489801f, 0, -0.5870231946f, -0.3226498013f, -0.7424963803f, 0, 0.3051124198f, 0.2262544068f, -0.9250488391f, 0, + 0.6379576059f, 0.577242424f, -0.5097070502f, 0, -0.5966775796f, 0.1454852398f, -0.7891830656f, 0, -0.658330573f, 0.6555487542f, -0.3699414651f, 0, 0.7434892426f, 0.2351084581f, 0.6260573129f, 0, 0.5562114096f, 0.8264360377f, -0.0873632843f, 0, -0.3028940016f, -0.8251527185f, 0.4768419182f, 0, 0.1129343818f, -0.985888439f, -0.1235710781f, 0, 0.5937652891f, -0.5896813806f, 0.5474656618f, 0, + 0.6757964092f, -0.5835758614f, -0.4502648413f, 0, 0.7242302609f, -0.1152719764f, 0.6798550586f, 0, -0.9511914166f, 0.0753623979f, -0.2992580792f, 0, 0.2539470961f, -0.1886339355f, 0.9486454084f, 0, 0.571433621f, -0.1679450851f, -0.8032795685f, 0, -0.06778234979f, 0.3978269256f, 0.9149531629f, 0, 0.6074972649f, 0.733060024f, -0.3058922593f, 0, -0.5435478392f, 0.1675822484f, 0.8224791405f, 0, + -0.5876678086f, -0.3380045064f, -0.7351186982f, 0, -0.7967562402f, 0.04097822706f, -0.6029098428f, 0, -0.1996350917f, 0.8706294745f, 0.4496111079f, 0, -0.02787660336f, -0.9106232682f, -0.4122962022f, 0, -0.7797625996f, -0.6257634692f, 0.01975775581f, 0, -0.5211232846f, 0.7401644346f, -0.4249554471f, 0, 0.8575424857f, 0.4053272873f, -0.3167501783f, 0, 0.1045223322f, 0.8390195772f, -0.5339674439f, 0, + 0.3501822831f, 0.9242524096f, -0.1520850155f, 0, 0.1987849858f, 0.07647613266f, 0.9770547224f, 0, 0.7845996363f, 0.6066256811f, -0.1280964233f, 0, 0.09006737436f, -0.9750989929f, -0.2026569073f, 0, -0.8274343547f, -0.542299559f, 0.1458203587f, 0, -0.3485797732f, -0.415802277f, 0.840000362f, 0, -0.2471778936f, -0.7304819962f, -0.6366310879f, 0, -0.3700154943f, 0.8577948156f, 0.3567584454f, 0, + 0.5913394901f, -0.548311967f, -0.5913303597f, 0, 0.1204873514f, -0.7626472379f, -0.6354935001f, 0, 0.616959265f, 0.03079647928f, 0.7863922953f, 0, 0.1258156836f, -0.6640829889f, -0.7369967419f, 0, -0.6477565124f, -0.1740147258f, -0.7417077429f, 0, 0.6217889313f, -0.7804430448f, -0.06547655076f, 0, 0.6589943422f, -0.6096987708f, 0.4404473475f, 0, -0.2689837504f, -0.6732403169f, -0.6887635427f, 0, + -0.3849775103f, 0.5676542638f, 0.7277093879f, 0, 0.5754444408f, 0.8110471154f, -0.1051963504f, 0, 0.9141593684f, 0.3832947817f, 0.131900567f, 0, -0.107925319f, 0.9245493968f, 0.3654593525f, 0, 0.377977089f, 0.3043148782f, 0.8743716458f, 0, -0.2142885215f, -0.8259286236f, 0.5214617324f, 0, 0.5802544474f, 0.4148098596f, -0.7008834116f, 0, -0.1982660881f, 0.8567161266f, -0.4761596756f, 0, + -0.03381553704f, 0.3773180787f, -0.9254661404f, 0, -0.6867922841f, -0.6656597827f, 0.2919133642f, 0, 0.7731742607f, -0.2875793547f, -0.5652430251f, 0, -0.09655941928f, 0.9193708367f, -0.3813575004f, 0, 0.2715702457f, -0.9577909544f, -0.09426605581f, 0, 0.2451015704f, -0.6917998565f, -0.6792188003f, 0, 0.977700782f, -0.1753855374f, 0.1155036542f, 0, -0.5224739938f, 0.8521606816f, 0.02903615945f, 0, + -0.7734880599f, -0.5261292347f, 0.3534179531f, 0, -0.7134492443f, -0.269547243f, 0.6467878011f, 0, 0.1644037271f, 0.5105846203f, -0.8439637196f, 0, 0.6494635788f, 0.05585611296f, 0.7583384168f, 0, -0.4711970882f, 0.5017280509f, -0.7254255765f, 0, -0.6335764307f, -0.2381686273f, -0.7361091029f, 0, -0.9021533097f, -0.270947803f, -0.3357181763f, 0, -0.3793711033f, 0.872258117f, 0.3086152025f, 0, + -0.6855598966f, -0.3250143309f, 0.6514394162f, 0, 0.2900942212f, -0.7799057743f, -0.5546100667f, 0, -0.2098319339f, 0.85037073f, 0.4825351604f, 0, -0.4592603758f, 0.6598504336f, -0.5947077538f, 0, 0.8715945488f, 0.09616365406f, -0.4807031248f, 0, -0.6776666319f, 0.7118504878f, -0.1844907016f, 0, 0.7044377633f, 0.312427597f, 0.637304036f, 0, -0.7052318886f, -0.2401093292f, -0.6670798253f, 0, + 0.081921007f, -0.7207336136f, -0.6883545647f, 0, -0.6993680906f, -0.5875763221f, -0.4069869034f, 0, -0.1281454481f, 0.6419895885f, 0.7559286424f, 0, -0.6337388239f, -0.6785471501f, -0.3714146849f, 0, 0.5565051903f, -0.2168887573f, -0.8020356851f, 0, -0.5791554484f, 0.7244372011f, -0.3738578718f, 0, 0.1175779076f, -0.7096451073f, 0.6946792478f, 0, -0.6134619607f, 0.1323631078f, 0.7785527795f, 0, + 0.6984635305f, -0.02980516237f, -0.715024719f, 0, 0.8318082963f, -0.3930171956f, 0.3919597455f, 0, 0.1469576422f, 0.05541651717f, -0.9875892167f, 0, 0.708868575f, -0.2690503865f, 0.6520101478f, 0, 0.2726053183f, 0.67369766f, -0.68688995f, 0, -0.6591295371f, 0.3035458599f, -0.6880466294f, 0, 0.4815131379f, -0.7528270071f, 0.4487723203f, 0, 0.9430009463f, 0.1675647412f, -0.2875261255f, 0, + 0.434802957f, 0.7695304522f, -0.4677277752f, 0, 0.3931996188f, 0.594473625f, 0.7014236729f, 0, 0.7254336655f, -0.603925654f, 0.3301814672f, 0, 0.7590235227f, -0.6506083235f, 0.02433313207f, 0, -0.8552768592f, -0.3430042733f, 0.3883935666f, 0, -0.6139746835f, 0.6981725247f, 0.3682257648f, 0, -0.7465905486f, -0.5752009504f, 0.3342849376f, 0, 0.5730065677f, 0.810555537f, -0.1210916791f, 0, + -0.9225877367f, -0.3475211012f, -0.167514036f, 0, -0.7105816789f, -0.4719692027f, -0.5218416899f, 0, -0.08564609717f, 0.3583001386f, 0.929669703f, 0, -0.8279697606f, -0.2043157126f, 0.5222271202f, 0, 0.427944023f, 0.278165994f, 0.8599346446f, 0, 0.5399079671f, -0.7857120652f, -0.3019204161f, 0, 0.5678404253f, -0.5495413974f, -0.6128307303f, 0, -0.9896071041f, 0.1365639107f, -0.04503418428f, 0, + -0.6154342638f, -0.6440875597f, 0.4543037336f, 0, 0.1074204368f, -0.7946340692f, 0.5975094525f, 0, -0.3595449969f, -0.8885529948f, 0.28495784f, 0, -0.2180405296f, 0.1529888965f, 0.9638738118f, 0, -0.7277432317f, -0.6164050508f, -0.3007234646f, 0, 0.7249729114f, -0.00669719484f, 0.6887448187f, 0, -0.5553659455f, -0.5336586252f, 0.6377908264f, 0, 0.5137558015f, 0.7976208196f, -0.3160000073f, 0, + -0.3794024848f, 0.9245608561f, -0.03522751494f, 0, 0.8229248658f, 0.2745365933f, -0.4974176556f, 0, -0.5404114394f, 0.6091141441f, 0.5804613989f, 0, 0.8036581901f, -0.2703029469f, 0.5301601931f, 0, 0.6044318879f, 0.6832968393f, 0.4095943388f, 0, 0.06389988817f, 0.9658208605f, -0.2512108074f, 0, 0.1087113286f, 0.7402471173f, -0.6634877936f, 0, -0.713427712f, -0.6926784018f, 0.1059128479f, 0, + 0.6458897819f, -0.5724548511f, -0.5050958653f, 0, -0.6553931414f, 0.7381471625f, 0.159995615f, 0, 0.3910961323f, 0.9188871375f, -0.05186755998f, 0, -0.4879022471f, -0.5904376907f, 0.6429111375f, 0, 0.6014790094f, 0.7707441366f, -0.2101820095f, 0, -0.5677173047f, 0.7511360995f, 0.3368851762f, 0, 0.7858573506f, 0.226674665f, 0.5753666838f, 0, -0.4520345543f, -0.604222686f, -0.6561857263f, 0, + 0.002272116345f, 0.4132844051f, -0.9105991643f, 0, -0.5815751419f, -0.5162925989f, 0.6286591339f, 0, -0.03703704785f, 0.8273785755f, 0.5604221175f, 0, -0.5119692504f, 0.7953543429f, -0.3244980058f, 0, -0.2682417366f, -0.9572290247f, -0.1084387619f, 0, -0.2322482736f, -0.9679131102f, -0.09594243324f, 0, 0.3554328906f, -0.8881505545f, 0.2913006227f, 0, 0.7346520519f, -0.4371373164f, 0.5188422971f, 0, + 0.9985120116f, 0.04659011161f, -0.02833944577f, 0, -0.3727687496f, -0.9082481361f, 0.1900757285f, 0, 0.91737377f, -0.3483642108f, 0.1925298489f, 0, 0.2714911074f, 0.4147529736f, -0.8684886582f, 0, 0.5131763485f, -0.7116334161f, 0.4798207128f, 0, -0.8737353606f, 0.18886992f, -0.4482350644f, 0, 0.8460043821f, -0.3725217914f, 0.3814499973f, 0, 0.8978727456f, -0.1780209141f, -0.4026575304f, 0, + 0.2178065647f, -0.9698322841f, -0.1094789531f, 0, -0.1518031304f, -0.7788918132f, -0.6085091231f, 0, -0.2600384876f, -0.4755398075f, -0.8403819825f, 0, 0.572313509f, -0.7474340931f, -0.3373418503f, 0, -0.7174141009f, 0.1699017182f, -0.6756111411f, 0, -0.684180784f, 0.02145707593f, -0.7289967412f, 0, -0.2007447902f, 0.06555605789f, -0.9774476623f, 0, -0.1148803697f, -0.8044887315f, 0.5827524187f, 0, + -0.7870349638f, 0.03447489231f, 0.6159443543f, 0, -0.2015596421f, 0.6859872284f, 0.6991389226f, 0, -0.08581082512f, -0.10920836f, -0.9903080513f, 0, 0.5532693395f, 0.7325250401f, -0.396610771f, 0, -0.1842489331f, -0.9777375055f, -0.1004076743f, 0, 0.0775473789f, -0.9111505856f, 0.4047110257f, 0, 0.1399838409f, 0.7601631212f, -0.6344734459f, 0, 0.4484419361f, -0.845289248f, 0.2904925424f, 0 + }; + + + private static float FastMin(float a, float b) { return a < b ? a : b; } + + private static float FastMax(float a, float b) { return a > b ? a : b; } + + private static float FastAbs(float f) { return f < 0 ? -f : f; } + + private static float FastSqrt(float f) { return (float)Math.sqrt(f); } + + private static int FastFloor(/*FNLfloat*/ float f) { return f >= 0 ? (int)f : (int)f - 1; } + + private static int FastRound(/*FNLfloat*/ float f) { return f >= 0 ? (int)(f + 0.5f) : (int)(f - 0.5f); } + + private static float Lerp(float a, float b, float t) { return a + t * (b - a); } + + private static float InterpHermite(float t) { return t * t * (3 - 2 * t); } + + private static float InterpQuintic(float t) { return t * t * t * (t * (t * 6 - 15) + 10); } + + private static float CubicLerp(float a, float b, float c, float d, float t) + { + float p = (d - c) - (a - b); + return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; + } + + private static float PingPong(float t) + { + t -= (int)(t * 0.5f) * 2; + return t < 1 ? t : 2 - t; + } + + private void CalculateFractalBounding() + { + float gain = FastAbs(mGain); + float amp = gain; + float ampFractal = 1.0f; + for (int i = 1; i < mOctaves; i++) + { + ampFractal += amp; + amp *= gain; + } + mFractalBounding = 1 / ampFractal; + } + + // Hashing + private static final int PrimeX = 501125321; + private static final int PrimeY = 1136930381; + private static final int PrimeZ = 1720413743; + + private static int Hash(int seed, int xPrimed, int yPrimed) + { + int hash = seed ^ xPrimed ^ yPrimed; + + hash *= 0x27d4eb2d; + return hash; + } + + private static int Hash(int seed, int xPrimed, int yPrimed, int zPrimed) + { + int hash = seed ^ xPrimed ^ yPrimed ^ zPrimed; + + hash *= 0x27d4eb2d; + return hash; + } + + private static float ValCoord(int seed, int xPrimed, int yPrimed) + { + int hash = Hash(seed, xPrimed, yPrimed); + + hash *= hash; + hash ^= hash << 19; + return hash * (1 / 2147483648.0f); + } + + private static float ValCoord(int seed, int xPrimed, int yPrimed, int zPrimed) + { + int hash = Hash(seed, xPrimed, yPrimed, zPrimed); + + hash *= hash; + hash ^= hash << 19; + return hash * (1 / 2147483648.0f); + } + + private static float GradCoord(int seed, int xPrimed, int yPrimed, float xd, float yd) + { + int hash = Hash(seed, xPrimed, yPrimed); + hash ^= hash >> 15; + hash &= 127 << 1; + + float xg = Gradients2D[hash]; + float yg = Gradients2D[hash | 1]; + + return xd * xg + yd * yg; + } + + private static float GradCoord(int seed, int xPrimed, int yPrimed, int zPrimed, float xd, float yd, float zd) + { + int hash = Hash(seed, xPrimed, yPrimed, zPrimed); + hash ^= hash >> 15; + hash &= 63 << 2; + + float xg = Gradients3D[hash]; + float yg = Gradients3D[hash | 1]; + float zg = Gradients3D[hash | 2]; + + return xd * xg + yd * yg + zd * zg; + } + + + // Generic noise gen + + private float GenNoiseSingle(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + switch (mNoiseType) + { + case OpenSimplex2: + return SingleSimplex(seed, x, y); + case OpenSimplex2S: + return SingleOpenSimplex2S(seed, x, y); + case Cellular: + return SingleCellular(seed, x, y); + case Perlin: + return SinglePerlin(seed, x, y); + case ValueCubic: + return SingleValueCubic(seed, x, y); + case Value: + return SingleValue(seed, x, y); + default: + return 0; + } + } + + private float GenNoiseSingle(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + switch (mNoiseType) + { + case OpenSimplex2: + return SingleOpenSimplex2(seed, x, y, z); + case OpenSimplex2S: + return SingleOpenSimplex2S(seed, x, y, z); + case Cellular: + return SingleCellular(seed, x, y, z); + case Perlin: + return SinglePerlin(seed, x, y, z); + case ValueCubic: + return SingleValueCubic(seed, x, y, z); + case Value: + return SingleValue(seed, x, y, z); + default: + return 0; + } + } + + + // Noise Coordinate Transforms (frequency, and possible skew or rotation) + + private void UpdateTransformType3D() + { + switch (mRotationType3D) + { + case ImproveXYPlanes: + mTransformType3D = TransformType3D.ImproveXYPlanes; + break; + case ImproveXZPlanes: + mTransformType3D = TransformType3D.ImproveXZPlanes; + break; + default: + switch (mNoiseType) + { + case OpenSimplex2: + case OpenSimplex2S: + mTransformType3D = TransformType3D.DefaultOpenSimplex2; + break; + default: + mTransformType3D = TransformType3D.None; + break; + } + break; + } + } + + private void UpdateWarpTransformType3D() + { + switch (mRotationType3D) + { + case ImproveXYPlanes: + mWarpTransformType3D = TransformType3D.ImproveXYPlanes; + break; + case ImproveXZPlanes: + mWarpTransformType3D = TransformType3D.ImproveXZPlanes; + break; + default: + switch (mDomainWarpType) + { + case OpenSimplex2: + case OpenSimplex2Reduced: + mWarpTransformType3D = TransformType3D.DefaultOpenSimplex2; + break; + default: + mWarpTransformType3D = TransformType3D.None; + break; + } + break; + } + } + + + // Fractal FBm + + private float GenFractalFBm(/*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int seed = mSeed; + float sum = 0; + float amp = mFractalBounding; + + for (int i = 0; i < mOctaves; i++) + { + float noise = GenNoiseSingle(seed++, x, y); + sum += noise * amp; + amp *= Lerp(1.0f, FastMin(noise + 1, 2) * 0.5f, mWeightedStrength); + + x *= mLacunarity; + y *= mLacunarity; + amp *= mGain; + } + + return sum; + } + + private float GenFractalFBm(/*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int seed = mSeed; + float sum = 0; + float amp = mFractalBounding; + + for (int i = 0; i < mOctaves; i++) + { + float noise = GenNoiseSingle(seed++, x, y, z); + sum += noise * amp; + amp *= Lerp(1.0f, (noise + 1) * 0.5f, mWeightedStrength); + + x *= mLacunarity; + y *= mLacunarity; + z *= mLacunarity; + amp *= mGain; + } + + return sum; + } + + + // Fractal Ridged + + private float GenFractalRidged(/*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int seed = mSeed; + float sum = 0; + float amp = mFractalBounding; + + for (int i = 0; i < mOctaves; i++) + { + float noise = FastAbs(GenNoiseSingle(seed++, x, y)); + sum += (noise * -2 + 1) * amp; + amp *= Lerp(1.0f, 1 - noise, mWeightedStrength); + + x *= mLacunarity; + y *= mLacunarity; + amp *= mGain; + } + + return sum; + } + + private float GenFractalRidged(/*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int seed = mSeed; + float sum = 0; + float amp = mFractalBounding; + + for (int i = 0; i < mOctaves; i++) + { + float noise = FastAbs(GenNoiseSingle(seed++, x, y, z)); + sum += (noise * -2 + 1) * amp; + amp *= Lerp(1.0f, 1 - noise, mWeightedStrength); + + x *= mLacunarity; + y *= mLacunarity; + z *= mLacunarity; + amp *= mGain; + } + + return sum; + } + + + // Fractal PingPong + + private float GenFractalPingPong(/*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int seed = mSeed; + float sum = 0; + float amp = mFractalBounding; + + for (int i = 0; i < mOctaves; i++) + { + float noise = PingPong((GenNoiseSingle(seed++, x, y) + 1) * mPingPongStrength); + sum += (noise - 0.5f) * 2 * amp; + amp *= Lerp(1.0f, noise, mWeightedStrength); + + x *= mLacunarity; + y *= mLacunarity; + amp *= mGain; + } + + return sum; + } + + private float GenFractalPingPong(/*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int seed = mSeed; + float sum = 0; + float amp = mFractalBounding; + + for (int i = 0; i < mOctaves; i++) + { + float noise = PingPong((GenNoiseSingle(seed++, x, y, z) + 1) * mPingPongStrength); + sum += (noise - 0.5f) * 2 * amp; + amp *= Lerp(1.0f, noise, mWeightedStrength); + + x *= mLacunarity; + y *= mLacunarity; + z *= mLacunarity; + amp *= mGain; + } + + return sum; + } + + + // Simplex/OpenSimplex2 Noise + + private float SingleSimplex(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + // 2D OpenSimplex2 case uses the same algorithm as ordinary Simplex. + + final float SQRT3 = 1.7320508075688772935274463415059f; + final float G2 = (3 - SQRT3) / 6; + + /* + * --- Skew moved to switch statements before fractal evaluation --- + * final FNLfloat F2 = 0.5f * (SQRT3 - 1); + * FNLfloat s = (x + y) * F2; + * x += s; y += s; + */ + + int i = FastFloor(x); + int j = FastFloor(y); + float xi = (float)(x - i); + float yi = (float)(y - j); + + float t = (xi + yi) * G2; + float x0 = (float)(xi - t); + float y0 = (float)(yi - t); + + i *= PrimeX; + j *= PrimeY; + + float n0, n1, n2; + + float a = 0.5f - x0 * x0 - y0 * y0; + if (a <= 0) n0 = 0; + else + { + n0 = (a * a) * (a * a) * GradCoord(seed, i, j, x0, y0); + } + + float c = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a); + if (c <= 0) n2 = 0; + else + { + float x2 = x0 + (2 * (float)G2 - 1); + float y2 = y0 + (2 * (float)G2 - 1); + n2 = (c * c) * (c * c) * GradCoord(seed, i + PrimeX, j + PrimeY, x2, y2); + } + + if (y0 > x0) + { + float x1 = x0 + (float)G2; + float y1 = y0 + ((float)G2 - 1); + float b = 0.5f - x1 * x1 - y1 * y1; + if (b <= 0) n1 = 0; + else + { + n1 = (b * b) * (b * b) * GradCoord(seed, i, j + PrimeY, x1, y1); + } + } + else + { + float x1 = x0 + ((float)G2 - 1); + float y1 = y0 + (float)G2; + float b = 0.5f - x1 * x1 - y1 * y1; + if (b <= 0) n1 = 0; + else + { + n1 = (b * b) * (b * b) * GradCoord(seed, i + PrimeX, j, x1, y1); + } + } + + return (n0 + n1 + n2) * 99.83685446303647f; + } + + private float SingleOpenSimplex2(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + // 3D OpenSimplex2 case uses two offset rotated cube grids. + + /* + * --- Rotation moved to switch statements before fractal evaluation --- + * final FNLfloat R3 = (FNLfloat)(2.0 / 3.0); + * FNLfloat r = (x + y + z) * R3; // Rotation, not skew + * x = r - x; y = r - y; z = r - z; + */ + + int i = FastRound(x); + int j = FastRound(y); + int k = FastRound(z); + float x0 = (float)(x - i); + float y0 = (float)(y - j); + float z0 = (float)(z - k); + + int xNSign = (int)(-1.0f - x0) | 1; + int yNSign = (int)(-1.0f - y0) | 1; + int zNSign = (int)(-1.0f - z0) | 1; + + float ax0 = xNSign * -x0; + float ay0 = yNSign * -y0; + float az0 = zNSign * -z0; + + i *= PrimeX; + j *= PrimeY; + k *= PrimeZ; + + float value = 0; + float a = (0.6f - x0 * x0) - (y0 * y0 + z0 * z0); + + for (int l = 0; ; l++) + { + if (a > 0) + { + value += (a * a) * (a * a) * GradCoord(seed, i, j, k, x0, y0, z0); + } + + if (ax0 >= ay0 && ax0 >= az0) + { + float b = a + ax0 + ax0; + if (b > 1) + { + b -= 1; + value += (b * b) * (b * b) * GradCoord(seed, i - xNSign * PrimeX, j, k, x0 + xNSign, y0, z0); + } + } + else if (ay0 > ax0 && ay0 >= az0) + { + float b = a + ay0 + ay0; + if (b > 1) + { + b -= 1; + value += (b * b) * (b * b) * GradCoord(seed, i, j - yNSign * PrimeY, k, x0, y0 + yNSign, z0); + } + } + else + { + float b = a + az0 + az0; + if (b > 1) + { + b -= 1; + value += (b * b) * (b * b) * GradCoord(seed, i, j, k - zNSign * PrimeZ, x0, y0, z0 + zNSign); + } + } + + if (l == 1) break; + + ax0 = 0.5f - ax0; + ay0 = 0.5f - ay0; + az0 = 0.5f - az0; + + x0 = xNSign * ax0; + y0 = yNSign * ay0; + z0 = zNSign * az0; + + a += (0.75f - ax0) - (ay0 + az0); + + i += (xNSign >> 1) & PrimeX; + j += (yNSign >> 1) & PrimeY; + k += (zNSign >> 1) & PrimeZ; + + xNSign = -xNSign; + yNSign = -yNSign; + zNSign = -zNSign; + + seed = ~seed; + } + + return value * 32.69428253173828125f; + } + + + // OpenSimplex2S Noise + + private float SingleOpenSimplex2S(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + // 2D OpenSimplex2S case is a modified 2D simplex noise. + + final /*FNLfloat*/ float SQRT3 = (/*FNLfloat*/ float)1.7320508075688772935274463415059; + final /*FNLfloat*/ float G2 = (3 - SQRT3) / 6; + + /* + * --- Skew moved to TransformNoiseCoordinate method --- + * final FNLfloat F2 = 0.5f * (SQRT3 - 1); + * FNLfloat s = (x + y) * F2; + * x += s; y += s; + */ + + int i = FastFloor(x); + int j = FastFloor(y); + float xi = (float)(x - i); + float yi = (float)(y - j); + + i *= PrimeX; + j *= PrimeY; + int i1 = i + PrimeX; + int j1 = j + PrimeY; + + float t = (xi + yi) * (float)G2; + float x0 = xi - t; + float y0 = yi - t; + + float a0 = (2.0f / 3.0f) - x0 * x0 - y0 * y0; + float value = (a0 * a0) * (a0 * a0) * GradCoord(seed, i, j, x0, y0); + + float a1 = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a0); + float x1 = x0 - (float)(1 - 2 * G2); + float y1 = y0 - (float)(1 - 2 * G2); + value += (a1 * a1) * (a1 * a1) * GradCoord(seed, i1, j1, x1, y1); + + // Nested conditionals were faster than compact bit logic/arithmetic. + float xmyi = xi - yi; + if (t > G2) + { + if (xi + xmyi > 1) + { + float x2 = x0 + (float)(3 * G2 - 2); + float y2 = y0 + (float)(3 * G2 - 1); + float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; + if (a2 > 0) + { + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, i + (PrimeX << 1), j + PrimeY, x2, y2); + } + } + else + { + float x2 = x0 + (float)G2; + float y2 = y0 + (float)(G2 - 1); + float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; + if (a2 > 0) + { + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, i, j + PrimeY, x2, y2); + } + } + + if (yi - xmyi > 1) + { + float x3 = x0 + (float)(3 * G2 - 1); + float y3 = y0 + (float)(3 * G2 - 2); + float a3 = (2.0f / 3.0f) - x3 * x3 - y3 * y3; + if (a3 > 0) + { + value += (a3 * a3) * (a3 * a3) * GradCoord(seed, i + PrimeX, j + (PrimeY << 1), x3, y3); + } + } + else + { + float x3 = x0 + (float)(G2 - 1); + float y3 = y0 + (float)G2; + float a3 = (2.0f / 3.0f) - x3 * x3 - y3 * y3; + if (a3 > 0) + { + value += (a3 * a3) * (a3 * a3) * GradCoord(seed, i + PrimeX, j, x3, y3); + } + } + } + else + { + if (xi + xmyi < 0) + { + float x2 = x0 + (float)(1 - G2); + float y2 = y0 - (float)G2; + float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; + if (a2 > 0) + { + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, i - PrimeX, j, x2, y2); + } + } + else + { + float x2 = x0 + (float)(G2 - 1); + float y2 = y0 + (float)G2; + float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; + if (a2 > 0) + { + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, i + PrimeX, j, x2, y2); + } + } + + if (yi < xmyi) + { + float x2 = x0 - (float)G2; + float y2 = y0 - (float)(G2 - 1); + float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; + if (a2 > 0) + { + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, i, j - PrimeY, x2, y2); + } + } + else + { + float x2 = x0 + (float)G2; + float y2 = y0 + (float)(G2 - 1); + float a2 = (2.0f / 3.0f) - x2 * x2 - y2 * y2; + if (a2 > 0) + { + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, i, j + PrimeY, x2, y2); + } + } + } + + return value * 18.24196194486065f; + } + + private float SingleOpenSimplex2S(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + // 3D OpenSimplex2S case uses two offset rotated cube grids. + + /* + * --- Rotation moved to TransformNoiseCoordinate method --- + * final FNLfloat R3 = (FNLfloat)(2.0 / 3.0); + * FNLfloat r = (x + y + z) * R3; // Rotation, not skew + * x = r - x; y = r - y; z = r - z; + */ + + int i = FastFloor(x); + int j = FastFloor(y); + int k = FastFloor(z); + float xi = (float)(x - i); + float yi = (float)(y - j); + float zi = (float)(z - k); + + i *= PrimeX; + j *= PrimeY; + k *= PrimeZ; + int seed2 = seed + 1293373; + + int xNMask = (int)(-0.5f - xi); + int yNMask = (int)(-0.5f - yi); + int zNMask = (int)(-0.5f - zi); + + float x0 = xi + xNMask; + float y0 = yi + yNMask; + float z0 = zi + zNMask; + float a0 = 0.75f - x0 * x0 - y0 * y0 - z0 * z0; + float value = (a0 * a0) * (a0 * a0) * GradCoord(seed, + i + (xNMask & PrimeX), j + (yNMask & PrimeY), k + (zNMask & PrimeZ), x0, y0, z0); + + float x1 = xi - 0.5f; + float y1 = yi - 0.5f; + float z1 = zi - 0.5f; + float a1 = 0.75f - x1 * x1 - y1 * y1 - z1 * z1; + value += (a1 * a1) * (a1 * a1) * GradCoord(seed2, + i + PrimeX, j + PrimeY, k + PrimeZ, x1, y1, z1); + + float xAFlipMask0 = ((xNMask | 1) << 1) * x1; + float yAFlipMask0 = ((yNMask | 1) << 1) * y1; + float zAFlipMask0 = ((zNMask | 1) << 1) * z1; + float xAFlipMask1 = (-2 - (xNMask << 2)) * x1 - 1.0f; + float yAFlipMask1 = (-2 - (yNMask << 2)) * y1 - 1.0f; + float zAFlipMask1 = (-2 - (zNMask << 2)) * z1 - 1.0f; + + boolean skip5 = false; + float a2 = xAFlipMask0 + a0; + if (a2 > 0) + { + float x2 = x0 - (xNMask | 1); + float y2 = y0; + float z2 = z0; + value += (a2 * a2) * (a2 * a2) * GradCoord(seed, + i + (~xNMask & PrimeX), j + (yNMask & PrimeY), k + (zNMask & PrimeZ), x2, y2, z2); + } + else + { + float a3 = yAFlipMask0 + zAFlipMask0 + a0; + if (a3 > 0) + { + float x3 = x0; + float y3 = y0 - (yNMask | 1); + float z3 = z0 - (zNMask | 1); + value += (a3 * a3) * (a3 * a3) * GradCoord(seed, + i + (xNMask & PrimeX), j + (~yNMask & PrimeY), k + (~zNMask & PrimeZ), x3, y3, z3); + } + + float a4 = xAFlipMask1 + a1; + if (a4 > 0) + { + float x4 = (xNMask | 1) + x1; + float y4 = y1; + float z4 = z1; + value += (a4 * a4) * (a4 * a4) * GradCoord(seed2, + i + (xNMask & (PrimeX * 2)), j + PrimeY, k + PrimeZ, x4, y4, z4); + skip5 = true; + } + } + + boolean skip9 = false; + float a6 = yAFlipMask0 + a0; + if (a6 > 0) + { + float x6 = x0; + float y6 = y0 - (yNMask | 1); + float z6 = z0; + value += (a6 * a6) * (a6 * a6) * GradCoord(seed, + i + (xNMask & PrimeX), j + (~yNMask & PrimeY), k + (zNMask & PrimeZ), x6, y6, z6); + } + else + { + float a7 = xAFlipMask0 + zAFlipMask0 + a0; + if (a7 > 0) + { + float x7 = x0 - (xNMask | 1); + float y7 = y0; + float z7 = z0 - (zNMask | 1); + value += (a7 * a7) * (a7 * a7) * GradCoord(seed, + i + (~xNMask & PrimeX), j + (yNMask & PrimeY), k + (~zNMask & PrimeZ), x7, y7, z7); + } + + float a8 = yAFlipMask1 + a1; + if (a8 > 0) + { + float x8 = x1; + float y8 = (yNMask | 1) + y1; + float z8 = z1; + value += (a8 * a8) * (a8 * a8) * GradCoord(seed2, + i + PrimeX, j + (yNMask & (PrimeY << 1)), k + PrimeZ, x8, y8, z8); + skip9 = true; + } + } + + boolean skipD = false; + float aA = zAFlipMask0 + a0; + if (aA > 0) + { + float xA = x0; + float yA = y0; + float zA = z0 - (zNMask | 1); + value += (aA * aA) * (aA * aA) * GradCoord(seed, + i + (xNMask & PrimeX), j + (yNMask & PrimeY), k + (~zNMask & PrimeZ), xA, yA, zA); + } + else + { + float aB = xAFlipMask0 + yAFlipMask0 + a0; + if (aB > 0) + { + float xB = x0 - (xNMask | 1); + float yB = y0 - (yNMask | 1); + float zB = z0; + value += (aB * aB) * (aB * aB) * GradCoord(seed, + i + (~xNMask & PrimeX), j + (~yNMask & PrimeY), k + (zNMask & PrimeZ), xB, yB, zB); + } + + float aC = zAFlipMask1 + a1; + if (aC > 0) + { + float xC = x1; + float yC = y1; + float zC = (zNMask | 1) + z1; + value += (aC * aC) * (aC * aC) * GradCoord(seed2, + i + PrimeX, j + PrimeY, k + (zNMask & (PrimeZ << 1)), xC, yC, zC); + skipD = true; + } + } + + if (!skip5) + { + float a5 = yAFlipMask1 + zAFlipMask1 + a1; + if (a5 > 0) + { + float x5 = x1; + float y5 = (yNMask | 1) + y1; + float z5 = (zNMask | 1) + z1; + value += (a5 * a5) * (a5 * a5) * GradCoord(seed2, + i + PrimeX, j + (yNMask & (PrimeY << 1)), k + (zNMask & (PrimeZ << 1)), x5, y5, z5); + } + } + + if (!skip9) + { + float a9 = xAFlipMask1 + zAFlipMask1 + a1; + if (a9 > 0) + { + float x9 = (xNMask | 1) + x1; + float y9 = y1; + float z9 = (zNMask | 1) + z1; + value += (a9 * a9) * (a9 * a9) * GradCoord(seed2, + i + (xNMask & (PrimeX * 2)), j + PrimeY, k + (zNMask & (PrimeZ << 1)), x9, y9, z9); + } + } + + if (!skipD) + { + float aD = xAFlipMask1 + yAFlipMask1 + a1; + if (aD > 0) + { + float xD = (xNMask | 1) + x1; + float yD = (yNMask | 1) + y1; + float zD = z1; + value += (aD * aD) * (aD * aD) * GradCoord(seed2, + i + (xNMask & (PrimeX << 1)), j + (yNMask & (PrimeY << 1)), k + PrimeZ, xD, yD, zD); + } + } + + return value * 9.046026385208288f; + } + + + // Cellular Noise + + private float SingleCellular(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int xr = FastRound(x); + int yr = FastRound(y); + + float distance0 = Float.MAX_VALUE; + float distance1 = Float.MAX_VALUE; + int closestHash = 0; + + float cellularJitter = 0.43701595f * mCellularJitterModifier; + + int xPrimed = (xr - 1) * PrimeX; + int yPrimedBase = (yr - 1) * PrimeY; + + switch (mCellularDistanceFunction) + { + default: + case Euclidean: + case EuclideanSq: + for (int xi = xr - 1; xi <= xr + 1; xi++) + { + int yPrimed = yPrimedBase; + + for (int yi = yr - 1; yi <= yr + 1; yi++) + { + int hash = Hash(seed, xPrimed, yPrimed); + int idx = hash & (255 << 1); + + float vecX = (float)(xi - x) + RandVecs2D[idx] * cellularJitter; + float vecY = (float)(yi - y) + RandVecs2D[idx | 1] * cellularJitter; + + float newDistance = vecX * vecX + vecY * vecY; + + distance1 = FastMax(FastMin(distance1, newDistance), distance0); + if (newDistance < distance0) + { + distance0 = newDistance; + closestHash = hash; + } + yPrimed += PrimeY; + } + xPrimed += PrimeX; + } + break; + case Manhattan: + for (int xi = xr - 1; xi <= xr + 1; xi++) + { + int yPrimed = yPrimedBase; + + for (int yi = yr - 1; yi <= yr + 1; yi++) + { + int hash = Hash(seed, xPrimed, yPrimed); + int idx = hash & (255 << 1); + + float vecX = (float)(xi - x) + RandVecs2D[idx] * cellularJitter; + float vecY = (float)(yi - y) + RandVecs2D[idx | 1] * cellularJitter; + + float newDistance = FastAbs(vecX) + FastAbs(vecY); + + distance1 = FastMax(FastMin(distance1, newDistance), distance0); + if (newDistance < distance0) + { + distance0 = newDistance; + closestHash = hash; + } + yPrimed += PrimeY; + } + xPrimed += PrimeX; + } + break; + case Hybrid: + for (int xi = xr - 1; xi <= xr + 1; xi++) + { + int yPrimed = yPrimedBase; + + for (int yi = yr - 1; yi <= yr + 1; yi++) + { + int hash = Hash(seed, xPrimed, yPrimed); + int idx = hash & (255 << 1); + + float vecX = (float)(xi - x) + RandVecs2D[idx] * cellularJitter; + float vecY = (float)(yi - y) + RandVecs2D[idx | 1] * cellularJitter; + + float newDistance = (FastAbs(vecX) + FastAbs(vecY)) + (vecX * vecX + vecY * vecY); + + distance1 = FastMax(FastMin(distance1, newDistance), distance0); + if (newDistance < distance0) + { + distance0 = newDistance; + closestHash = hash; + } + yPrimed += PrimeY; + } + xPrimed += PrimeX; + } + break; + } + + if (mCellularDistanceFunction == CellularDistanceFunction.Euclidean && mCellularReturnType != CellularReturnType.CellValue) + { + distance0 = FastSqrt(distance0); + + if (mCellularReturnType != CellularReturnType.Distance) + { + distance1 = FastSqrt(distance1); + } + } + + switch (mCellularReturnType) + { + case CellValue: + return closestHash * (1 / 2147483648.0f); + case Distance: + return distance0 - 1; + case Distance2: + return distance1 - 1; + case Distance2Add: + return (distance1 + distance0) * 0.5f - 1; + case Distance2Sub: + return distance1 - distance0 - 1; + case Distance2Mul: + return distance1 * distance0 * 0.5f - 1; + case Distance2Div: + return distance0 / distance1 - 1; + default: + return 0; + } + } + + private float SingleCellular(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int xr = FastRound(x); + int yr = FastRound(y); + int zr = FastRound(z); + + float distance0 = Float.MAX_VALUE; + float distance1 = Float.MAX_VALUE; + int closestHash = 0; + + float cellularJitter = 0.39614353f * mCellularJitterModifier; + + int xPrimed = (xr - 1) * PrimeX; + int yPrimedBase = (yr - 1) * PrimeY; + int zPrimedBase = (zr - 1) * PrimeZ; + + switch (mCellularDistanceFunction) + { + case Euclidean: + case EuclideanSq: + for (int xi = xr - 1; xi <= xr + 1; xi++) + { + int yPrimed = yPrimedBase; + + for (int yi = yr - 1; yi <= yr + 1; yi++) + { + int zPrimed = zPrimedBase; + + for (int zi = zr - 1; zi <= zr + 1; zi++) + { + int hash = Hash(seed, xPrimed, yPrimed, zPrimed); + int idx = hash & (255 << 2); + + float vecX = (float)(xi - x) + RandVecs3D[idx] * cellularJitter; + float vecY = (float)(yi - y) + RandVecs3D[idx | 1] * cellularJitter; + float vecZ = (float)(zi - z) + RandVecs3D[idx | 2] * cellularJitter; + + float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; + + distance1 = FastMax(FastMin(distance1, newDistance), distance0); + if (newDistance < distance0) + { + distance0 = newDistance; + closestHash = hash; + } + zPrimed += PrimeZ; + } + yPrimed += PrimeY; + } + xPrimed += PrimeX; + } + break; + case Manhattan: + for (int xi = xr - 1; xi <= xr + 1; xi++) + { + int yPrimed = yPrimedBase; + + for (int yi = yr - 1; yi <= yr + 1; yi++) + { + int zPrimed = zPrimedBase; + + for (int zi = zr - 1; zi <= zr + 1; zi++) + { + int hash = Hash(seed, xPrimed, yPrimed, zPrimed); + int idx = hash & (255 << 2); + + float vecX = (float)(xi - x) + RandVecs3D[idx] * cellularJitter; + float vecY = (float)(yi - y) + RandVecs3D[idx | 1] * cellularJitter; + float vecZ = (float)(zi - z) + RandVecs3D[idx | 2] * cellularJitter; + + float newDistance = FastAbs(vecX) + FastAbs(vecY) + FastAbs(vecZ); + + distance1 = FastMax(FastMin(distance1, newDistance), distance0); + if (newDistance < distance0) + { + distance0 = newDistance; + closestHash = hash; + } + zPrimed += PrimeZ; + } + yPrimed += PrimeY; + } + xPrimed += PrimeX; + } + break; + case Hybrid: + for (int xi = xr - 1; xi <= xr + 1; xi++) + { + int yPrimed = yPrimedBase; + + for (int yi = yr - 1; yi <= yr + 1; yi++) + { + int zPrimed = zPrimedBase; + + for (int zi = zr - 1; zi <= zr + 1; zi++) + { + int hash = Hash(seed, xPrimed, yPrimed, zPrimed); + int idx = hash & (255 << 2); + + float vecX = (float)(xi - x) + RandVecs3D[idx] * cellularJitter; + float vecY = (float)(yi - y) + RandVecs3D[idx | 1] * cellularJitter; + float vecZ = (float)(zi - z) + RandVecs3D[idx | 2] * cellularJitter; + + float newDistance = (FastAbs(vecX) + FastAbs(vecY) + FastAbs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); + + distance1 = FastMax(FastMin(distance1, newDistance), distance0); + if (newDistance < distance0) + { + distance0 = newDistance; + closestHash = hash; + } + zPrimed += PrimeZ; + } + yPrimed += PrimeY; + } + xPrimed += PrimeX; + } + break; + default: + break; + } + + if (mCellularDistanceFunction == CellularDistanceFunction.Euclidean && mCellularReturnType != CellularReturnType.CellValue) + { + distance0 = FastSqrt(distance0); + + if (mCellularReturnType != CellularReturnType.Distance) + { + distance1 = FastSqrt(distance1); + } + } + + switch (mCellularReturnType) + { + case CellValue: + return closestHash * (1 / 2147483648.0f); + case Distance: + return distance0 - 1; + case Distance2: + return distance1 - 1; + case Distance2Add: + return (distance1 + distance0) * 0.5f - 1; + case Distance2Sub: + return distance1 - distance0 - 1; + case Distance2Mul: + return distance1 * distance0 * 0.5f - 1; + case Distance2Div: + return distance0 / distance1 - 1; + default: + return 0; + } + } + + + // Perlin Noise + + private float SinglePerlin(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + + float xd0 = (float)(x - x0); + float yd0 = (float)(y - y0); + float xd1 = xd0 - 1; + float yd1 = yd0 - 1; + + float xs = InterpQuintic(xd0); + float ys = InterpQuintic(yd0); + + x0 *= PrimeX; + y0 *= PrimeY; + int x1 = x0 + PrimeX; + int y1 = y0 + PrimeY; + + float xf0 = Lerp(GradCoord(seed, x0, y0, xd0, yd0), GradCoord(seed, x1, y0, xd1, yd0), xs); + float xf1 = Lerp(GradCoord(seed, x0, y1, xd0, yd1), GradCoord(seed, x1, y1, xd1, yd1), xs); + + return Lerp(xf0, xf1, ys) * 1.4247691104677813f; + } + + private float SinglePerlin(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + int z0 = FastFloor(z); + + float xd0 = (float)(x - x0); + float yd0 = (float)(y - y0); + float zd0 = (float)(z - z0); + float xd1 = xd0 - 1; + float yd1 = yd0 - 1; + float zd1 = zd0 - 1; + + float xs = InterpQuintic(xd0); + float ys = InterpQuintic(yd0); + float zs = InterpQuintic(zd0); + + x0 *= PrimeX; + y0 *= PrimeY; + z0 *= PrimeZ; + int x1 = x0 + PrimeX; + int y1 = y0 + PrimeY; + int z1 = z0 + PrimeZ; + + float xf00 = Lerp(GradCoord(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord(seed, x1, y0, z0, xd1, yd0, zd0), xs); + float xf10 = Lerp(GradCoord(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord(seed, x1, y1, z0, xd1, yd1, zd0), xs); + float xf01 = Lerp(GradCoord(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord(seed, x1, y0, z1, xd1, yd0, zd1), xs); + float xf11 = Lerp(GradCoord(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord(seed, x1, y1, z1, xd1, yd1, zd1), xs); + + float yf0 = Lerp(xf00, xf10, ys); + float yf1 = Lerp(xf01, xf11, ys); + + return Lerp(yf0, yf1, zs) * 0.964921414852142333984375f; + } + + + // Value Cubic Noise + + private float SingleValueCubic(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int x1 = FastFloor(x); + int y1 = FastFloor(y); + + float xs = (float)(x - x1); + float ys = (float)(y - y1); + + x1 *= PrimeX; + y1 *= PrimeY; + int x0 = x1 - PrimeX; + int y0 = y1 - PrimeY; + int x2 = x1 + PrimeX; + int y2 = y1 + PrimeY; + int x3 = x1 + (PrimeX << 1); + int y3 = y1 + (PrimeY << 1); + + return CubicLerp( + CubicLerp(ValCoord(seed, x0, y0), ValCoord(seed, x1, y0), ValCoord(seed, x2, y0), ValCoord(seed, x3, y0), + xs), + CubicLerp(ValCoord(seed, x0, y1), ValCoord(seed, x1, y1), ValCoord(seed, x2, y1), ValCoord(seed, x3, y1), + xs), + CubicLerp(ValCoord(seed, x0, y2), ValCoord(seed, x1, y2), ValCoord(seed, x2, y2), ValCoord(seed, x3, y2), + xs), + CubicLerp(ValCoord(seed, x0, y3), ValCoord(seed, x1, y3), ValCoord(seed, x2, y3), ValCoord(seed, x3, y3), + xs), + ys) * (1 / (1.5f * 1.5f)); + } + + private float SingleValueCubic(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int x1 = FastFloor(x); + int y1 = FastFloor(y); + int z1 = FastFloor(z); + + float xs = (float)(x - x1); + float ys = (float)(y - y1); + float zs = (float)(z - z1); + + x1 *= PrimeX; + y1 *= PrimeY; + z1 *= PrimeZ; + + int x0 = x1 - PrimeX; + int y0 = y1 - PrimeY; + int z0 = z1 - PrimeZ; + int x2 = x1 + PrimeX; + int y2 = y1 + PrimeY; + int z2 = z1 + PrimeZ; + int x3 = x1 + (PrimeX << 1); + int y3 = y1 + (PrimeY << 1); + int z3 = z1 + (PrimeZ << 1); + + + return CubicLerp( + CubicLerp( + CubicLerp(ValCoord(seed, x0, y0, z0), ValCoord(seed, x1, y0, z0), ValCoord(seed, x2, y0, z0), ValCoord(seed, x3, y0, z0), xs), + CubicLerp(ValCoord(seed, x0, y1, z0), ValCoord(seed, x1, y1, z0), ValCoord(seed, x2, y1, z0), ValCoord(seed, x3, y1, z0), xs), + CubicLerp(ValCoord(seed, x0, y2, z0), ValCoord(seed, x1, y2, z0), ValCoord(seed, x2, y2, z0), ValCoord(seed, x3, y2, z0), xs), + CubicLerp(ValCoord(seed, x0, y3, z0), ValCoord(seed, x1, y3, z0), ValCoord(seed, x2, y3, z0), ValCoord(seed, x3, y3, z0), xs), + ys), + CubicLerp( + CubicLerp(ValCoord(seed, x0, y0, z1), ValCoord(seed, x1, y0, z1), ValCoord(seed, x2, y0, z1), ValCoord(seed, x3, y0, z1), xs), + CubicLerp(ValCoord(seed, x0, y1, z1), ValCoord(seed, x1, y1, z1), ValCoord(seed, x2, y1, z1), ValCoord(seed, x3, y1, z1), xs), + CubicLerp(ValCoord(seed, x0, y2, z1), ValCoord(seed, x1, y2, z1), ValCoord(seed, x2, y2, z1), ValCoord(seed, x3, y2, z1), xs), + CubicLerp(ValCoord(seed, x0, y3, z1), ValCoord(seed, x1, y3, z1), ValCoord(seed, x2, y3, z1), ValCoord(seed, x3, y3, z1), xs), + ys), + CubicLerp( + CubicLerp(ValCoord(seed, x0, y0, z2), ValCoord(seed, x1, y0, z2), ValCoord(seed, x2, y0, z2), ValCoord(seed, x3, y0, z2), xs), + CubicLerp(ValCoord(seed, x0, y1, z2), ValCoord(seed, x1, y1, z2), ValCoord(seed, x2, y1, z2), ValCoord(seed, x3, y1, z2), xs), + CubicLerp(ValCoord(seed, x0, y2, z2), ValCoord(seed, x1, y2, z2), ValCoord(seed, x2, y2, z2), ValCoord(seed, x3, y2, z2), xs), + CubicLerp(ValCoord(seed, x0, y3, z2), ValCoord(seed, x1, y3, z2), ValCoord(seed, x2, y3, z2), ValCoord(seed, x3, y3, z2), xs), + ys), + CubicLerp( + CubicLerp(ValCoord(seed, x0, y0, z3), ValCoord(seed, x1, y0, z3), ValCoord(seed, x2, y0, z3), ValCoord(seed, x3, y0, z3), xs), + CubicLerp(ValCoord(seed, x0, y1, z3), ValCoord(seed, x1, y1, z3), ValCoord(seed, x2, y1, z3), ValCoord(seed, x3, y1, z3), xs), + CubicLerp(ValCoord(seed, x0, y2, z3), ValCoord(seed, x1, y2, z3), ValCoord(seed, x2, y2, z3), ValCoord(seed, x3, y2, z3), xs), + CubicLerp(ValCoord(seed, x0, y3, z3), ValCoord(seed, x1, y3, z3), ValCoord(seed, x2, y3, z3), ValCoord(seed, x3, y3, z3), xs), + ys), + zs) * (1 / (1.5f * 1.5f * 1.5f)); + } + + + // Value Noise + + private float SingleValue(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + + float xs = InterpHermite((float)(x - x0)); + float ys = InterpHermite((float)(y - y0)); + + x0 *= PrimeX; + y0 *= PrimeY; + int x1 = x0 + PrimeX; + int y1 = y0 + PrimeY; + + float xf0 = Lerp(ValCoord(seed, x0, y0), ValCoord(seed, x1, y0), xs); + float xf1 = Lerp(ValCoord(seed, x0, y1), ValCoord(seed, x1, y1), xs); + + return Lerp(xf0, xf1, ys); + } + + private float SingleValue(int seed, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + int z0 = FastFloor(z); + + float xs = InterpHermite((float)(x - x0)); + float ys = InterpHermite((float)(y - y0)); + float zs = InterpHermite((float)(z - z0)); + + x0 *= PrimeX; + y0 *= PrimeY; + z0 *= PrimeZ; + int x1 = x0 + PrimeX; + int y1 = y0 + PrimeY; + int z1 = z0 + PrimeZ; + + float xf00 = Lerp(ValCoord(seed, x0, y0, z0), ValCoord(seed, x1, y0, z0), xs); + float xf10 = Lerp(ValCoord(seed, x0, y1, z0), ValCoord(seed, x1, y1, z0), xs); + float xf01 = Lerp(ValCoord(seed, x0, y0, z1), ValCoord(seed, x1, y0, z1), xs); + float xf11 = Lerp(ValCoord(seed, x0, y1, z1), ValCoord(seed, x1, y1, z1), xs); + + float yf0 = Lerp(xf00, xf10, ys); + float yf1 = Lerp(xf01, xf11, ys); + + return Lerp(yf0, yf1, zs); + } + + + // Domain Warp + + private void DoSingleDomainWarp(int seed, float amp, float freq, /*FNLfloat*/ float x, /*FNLfloat*/ float y, Vector2 coord) + { + switch (mDomainWarpType) + { + case OpenSimplex2: + SingleDomainWarpSimplexGradient(seed, amp * 38.283687591552734375f, freq, x, y, coord, false); + break; + case OpenSimplex2Reduced: + SingleDomainWarpSimplexGradient(seed, amp * 16.0f, freq, x, y, coord, true); + break; + case BasicGrid: + SingleDomainWarpBasicGrid(seed, amp, freq, x, y, coord); + break; + } + } + + private void DoSingleDomainWarp(int seed, float amp, float freq, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z, Vector3 coord) + { + switch (mDomainWarpType) + { + case OpenSimplex2: + SingleDomainWarpOpenSimplex2Gradient(seed, amp * 32.69428253173828125f, freq, x, y, z, coord, false); + break; + case OpenSimplex2Reduced: + SingleDomainWarpOpenSimplex2Gradient(seed, amp * 7.71604938271605f, freq, x, y, z, coord, true); + break; + case BasicGrid: + SingleDomainWarpBasicGrid(seed, amp, freq, x, y, z, coord); + break; + } + } + + + // Domain Warp Single Wrapper + + private void DomainWarpSingle(Vector2 coord) + { + int seed = mSeed; + float amp = mDomainWarpAmp * mFractalBounding; + float freq = mFrequency; + + /*FNLfloat*/ float xs = coord.x; + /*FNLfloat*/ float ys = coord.y; + switch (mDomainWarpType) + { + case OpenSimplex2: + case OpenSimplex2Reduced: + { + final /*FNLfloat*/ float SQRT3 = (/*FNLfloat*/ float)1.7320508075688772935274463415059; + final /*FNLfloat*/ float F2 = 0.5f * (SQRT3 - 1); + /*FNLfloat*/ float t = (xs + ys) * F2; + xs += t; ys += t; + } + break; + default: + break; + } + + DoSingleDomainWarp(seed, amp, freq, xs, ys, coord); + } + + private void DomainWarpSingle(Vector3 coord) + { + int seed = mSeed; + float amp = mDomainWarpAmp * mFractalBounding; + float freq = mFrequency; + + /*FNLfloat*/ float xs = coord.x; + /*FNLfloat*/ float ys = coord.y; + /*FNLfloat*/ float zs = coord.z; + switch (mWarpTransformType3D) + { + case ImproveXYPlanes: + { + /*FNLfloat*/ float xy = xs + ys; + /*FNLfloat*/ float s2 = xy * -(/*FNLfloat*/ float)0.211324865405187; + zs *= (/*FNLfloat*/ float)0.577350269189626; + xs += s2 - zs; + ys = ys + s2 - zs; + zs += xy * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case ImproveXZPlanes: + { + /*FNLfloat*/ float xz = xs + zs; + /*FNLfloat*/ float s2 = xz * -(/*FNLfloat*/ float)0.211324865405187; + ys *= (/*FNLfloat*/ float)0.577350269189626; + xs += s2 - ys; zs += s2 - ys; + ys += xz * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case DefaultOpenSimplex2: + { + final /*FNLfloat*/ float R3 = (/*FNLfloat*/ float)(2.0 / 3.0); + /*FNLfloat*/ float r = (xs + ys + zs) * R3; // Rotation, not skew + xs = r - xs; + ys = r - ys; + zs = r - zs; + } + break; + default: + break; + } + + DoSingleDomainWarp(seed, amp, freq, xs, ys, zs, coord); + } + + + // Domain Warp Fractal Progressive + + private void DomainWarpFractalProgressive(Vector2 coord) + { + int seed = mSeed; + float amp = mDomainWarpAmp * mFractalBounding; + float freq = mFrequency; + + for (int i = 0; i < mOctaves; i++) + { + /*FNLfloat*/ float xs = coord.x; + /*FNLfloat*/ float ys = coord.y; + switch (mDomainWarpType) + { + case OpenSimplex2: + case OpenSimplex2Reduced: + { + final /*FNLfloat*/ float SQRT3 = (/*FNLfloat*/ float)1.7320508075688772935274463415059; + final /*FNLfloat*/ float F2 = 0.5f * (SQRT3 - 1); + /*FNLfloat*/ float t = (xs + ys) * F2; + xs += t; ys += t; + } + break; + default: + break; + } + + DoSingleDomainWarp(seed, amp, freq, xs, ys, coord); + + seed++; + amp *= mGain; + freq *= mLacunarity; + } + } + + private void DomainWarpFractalProgressive(Vector3 coord) + { + int seed = mSeed; + float amp = mDomainWarpAmp * mFractalBounding; + float freq = mFrequency; + + for (int i = 0; i < mOctaves; i++) + { + /*FNLfloat*/ float xs = coord.x; + /*FNLfloat*/ float ys = coord.y; + /*FNLfloat*/ float zs = coord.z; + switch (mWarpTransformType3D) + { + case ImproveXYPlanes: + { + /*FNLfloat*/ float xy = xs + ys; + /*FNLfloat*/ float s2 = xy * -(/*FNLfloat*/ float)0.211324865405187; + zs *= (/*FNLfloat*/ float)0.577350269189626; + xs += s2 - zs; + ys = ys + s2 - zs; + zs += xy * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case ImproveXZPlanes: + { + /*FNLfloat*/ float xz = xs + zs; + /*FNLfloat*/ float s2 = xz * -(/*FNLfloat*/ float)0.211324865405187; + ys *= (/*FNLfloat*/ float)0.577350269189626; + xs += s2 - ys; zs += s2 - ys; + ys += xz * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case DefaultOpenSimplex2: + { + final /*FNLfloat*/ float R3 = (/*FNLfloat*/ float)(2.0 / 3.0); + /*FNLfloat*/ float r = (xs + ys + zs) * R3; // Rotation, not skew + xs = r - xs; + ys = r - ys; + zs = r - zs; + } + break; + default: + break; + } + + DoSingleDomainWarp(seed, amp, freq, xs, ys, zs, coord); + + seed++; + amp *= mGain; + freq *= mLacunarity; + } + } + + + // Domain Warp Fractal Independant + private void DomainWarpFractalIndependent(Vector2 coord) + { + /*FNLfloat*/ float xs = coord.x; + /*FNLfloat*/ float ys = coord.y; + switch (mDomainWarpType) + { + case OpenSimplex2: + case OpenSimplex2Reduced: + { + final /*FNLfloat*/ float SQRT3 = (/*FNLfloat*/ float)1.7320508075688772935274463415059; + final /*FNLfloat*/ float F2 = 0.5f * (SQRT3 - 1); + /*FNLfloat*/ float t = (xs + ys) * F2; + xs += t; ys += t; + } + break; + default: + break; + } + + int seed = mSeed; + float amp = mDomainWarpAmp * mFractalBounding; + float freq = mFrequency; + + for (int i = 0; i < mOctaves; i++) + { + DoSingleDomainWarp(seed, amp, freq, xs, ys, coord); + + seed++; + amp *= mGain; + freq *= mLacunarity; + } + } + + private void DomainWarpFractalIndependent(Vector3 coord) + { + /*FNLfloat*/ float xs = coord.x; + /*FNLfloat*/ float ys = coord.y; + /*FNLfloat*/ float zs = coord.z; + switch (mWarpTransformType3D) + { + case ImproveXYPlanes: + { + /*FNLfloat*/ float xy = xs + ys; + /*FNLfloat*/ float s2 = xy * -(/*FNLfloat*/ float)0.211324865405187; + zs *= (/*FNLfloat*/ float)0.577350269189626; + xs += s2 - zs; + ys = ys + s2 - zs; + zs += xy * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case ImproveXZPlanes: + { + /*FNLfloat*/ float xz = xs + zs; + /*FNLfloat*/ float s2 = xz * -(/*FNLfloat*/ float)0.211324865405187; + ys *= (/*FNLfloat*/ float)0.577350269189626; + xs += s2 - ys; zs += s2 - ys; + ys += xz * (/*FNLfloat*/ float)0.577350269189626; + } + break; + case DefaultOpenSimplex2: + { + final /*FNLfloat*/ float R3 = (/*FNLfloat*/ float)(2.0 / 3.0); + /*FNLfloat*/ float r = (xs + ys + zs) * R3; // Rotation, not skew + xs = r - xs; + ys = r - ys; + zs = r - zs; + } + break; + default: + break; + } + + int seed = mSeed; + float amp = mDomainWarpAmp * mFractalBounding; + float freq = mFrequency; + + for (int i = 0; i < mOctaves; i++) + { + DoSingleDomainWarp(seed, amp, freq, xs, ys, zs, coord); + + seed++; + amp *= mGain; + freq *= mLacunarity; + } + } + + + // Domain Warp Basic Grid + + private void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, /*FNLfloat*/ float x, /*FNLfloat*/ float y, Vector2 coord) + { + /*FNLfloat*/ float xf = x * frequency; + /*FNLfloat*/ float yf = y * frequency; + + int x0 = FastFloor(xf); + int y0 = FastFloor(yf); + + float xs = InterpHermite((float)(xf - x0)); + float ys = InterpHermite((float)(yf - y0)); + + x0 *= PrimeX; + y0 *= PrimeY; + int x1 = x0 + PrimeX; + int y1 = y0 + PrimeY; + + int hash0 = Hash(seed, x0, y0) & (255 << 1); + int hash1 = Hash(seed, x1, y0) & (255 << 1); + + float lx0x = Lerp(RandVecs2D[hash0], RandVecs2D[hash1], xs); + float ly0x = Lerp(RandVecs2D[hash0 | 1], RandVecs2D[hash1 | 1], xs); + + hash0 = Hash(seed, x0, y1) & (255 << 1); + hash1 = Hash(seed, x1, y1) & (255 << 1); + + float lx1x = Lerp(RandVecs2D[hash0], RandVecs2D[hash1], xs); + float ly1x = Lerp(RandVecs2D[hash0 | 1], RandVecs2D[hash1 | 1], xs); + + coord.x += Lerp(lx0x, lx1x, ys) * warpAmp; + coord.y += Lerp(ly0x, ly1x, ys) * warpAmp; + } + + private void SingleDomainWarpBasicGrid(int seed, float warpAmp, float frequency, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z, Vector3 coord) + { + /*FNLfloat*/ float xf = x * frequency; + /*FNLfloat*/ float yf = y * frequency; + /*FNLfloat*/ float zf = z * frequency; + + int x0 = FastFloor(xf); + int y0 = FastFloor(yf); + int z0 = FastFloor(zf); + + float xs = InterpHermite((float)(xf - x0)); + float ys = InterpHermite((float)(yf - y0)); + float zs = InterpHermite((float)(zf - z0)); + + x0 *= PrimeX; + y0 *= PrimeY; + z0 *= PrimeZ; + int x1 = x0 + PrimeX; + int y1 = y0 + PrimeY; + int z1 = z0 + PrimeZ; + + int hash0 = Hash(seed, x0, y0, z0) & (255 << 2); + int hash1 = Hash(seed, x1, y0, z0) & (255 << 2); + + float lx0x = Lerp(RandVecs3D[hash0], RandVecs3D[hash1], xs); + float ly0x = Lerp(RandVecs3D[hash0 | 1], RandVecs3D[hash1 | 1], xs); + float lz0x = Lerp(RandVecs3D[hash0 | 2], RandVecs3D[hash1 | 2], xs); + + hash0 = Hash(seed, x0, y1, z0) & (255 << 2); + hash1 = Hash(seed, x1, y1, z0) & (255 << 2); + + float lx1x = Lerp(RandVecs3D[hash0], RandVecs3D[hash1], xs); + float ly1x = Lerp(RandVecs3D[hash0 | 1], RandVecs3D[hash1 | 1], xs); + float lz1x = Lerp(RandVecs3D[hash0 | 2], RandVecs3D[hash1 | 2], xs); + + float lx0y = Lerp(lx0x, lx1x, ys); + float ly0y = Lerp(ly0x, ly1x, ys); + float lz0y = Lerp(lz0x, lz1x, ys); + + hash0 = Hash(seed, x0, y0, z1) & (255 << 2); + hash1 = Hash(seed, x1, y0, z1) & (255 << 2); + + lx0x = Lerp(RandVecs3D[hash0], RandVecs3D[hash1], xs); + ly0x = Lerp(RandVecs3D[hash0 | 1], RandVecs3D[hash1 | 1], xs); + lz0x = Lerp(RandVecs3D[hash0 | 2], RandVecs3D[hash1 | 2], xs); + + hash0 = Hash(seed, x0, y1, z1) & (255 << 2); + hash1 = Hash(seed, x1, y1, z1) & (255 << 2); + + lx1x = Lerp(RandVecs3D[hash0], RandVecs3D[hash1], xs); + ly1x = Lerp(RandVecs3D[hash0 | 1], RandVecs3D[hash1 | 1], xs); + lz1x = Lerp(RandVecs3D[hash0 | 2], RandVecs3D[hash1 | 2], xs); + + coord.x += Lerp(lx0y, Lerp(lx0x, lx1x, ys), zs) * warpAmp; + coord.y += Lerp(ly0y, Lerp(ly0x, ly1x, ys), zs) * warpAmp; + coord.z += Lerp(lz0y, Lerp(lz0x, lz1x, ys), zs) * warpAmp; + } + + + // Domain Warp Simplex/OpenSimplex2 + private void SingleDomainWarpSimplexGradient(int seed, float warpAmp, float frequency, /*FNLfloat*/ float x, /*FNLfloat*/ float y, Vector2 coord, boolean outGradOnly) + { + final float SQRT3 = 1.7320508075688772935274463415059f; + final float G2 = (3 - SQRT3) / 6; + + x *= frequency; + y *= frequency; + + /* + * --- Skew moved to switch statements before fractal evaluation --- + * final FNLfloat F2 = 0.5f * (SQRT3 - 1); + * FNLfloat s = (x + y) * F2; + * x += s; y += s; + */ + + int i = FastFloor(x); + int j = FastFloor(y); + float xi = (float)(x - i); + float yi = (float)(y - j); + + float t = (xi + yi) * G2; + float x0 = (float)(xi - t); + float y0 = (float)(yi - t); + + i *= PrimeX; + j *= PrimeY; + + float vx, vy; + vx = vy = 0; + + float a = 0.5f - x0 * x0 - y0 * y0; + if (a > 0) + { + float aaaa = (a * a) * (a * a); + float xo, yo; + if (outGradOnly) + { + int hash = Hash(seed, i, j) & (255 << 1); + xo = RandVecs2D[hash]; + yo = RandVecs2D[hash | 1]; + } + else + { + int hash = Hash(seed, i, j); + int index1 = hash & (127 << 1); + int index2 = (hash >> 7) & (255 << 1); + float xg = Gradients2D[index1]; + float yg = Gradients2D[index1 | 1]; + float value = x0 * xg + y0 * yg; + float xgo = RandVecs2D[index2]; + float ygo = RandVecs2D[index2 | 1]; + xo = value * xgo; + yo = value * ygo; + } + vx += aaaa * xo; + vy += aaaa * yo; + } + + float c = (float)(2 * (1 - 2 * G2) * (1 / G2 - 2)) * t + ((float)(-2 * (1 - 2 * G2) * (1 - 2 * G2)) + a); + if (c > 0) + { + float x2 = x0 + (2 * (float)G2 - 1); + float y2 = y0 + (2 * (float)G2 - 1); + float cccc = (c * c) * (c * c); + float xo, yo; + if (outGradOnly) + { + int hash = Hash(seed, i + PrimeX, j + PrimeY) & (255 << 1); + xo = RandVecs2D[hash]; + yo = RandVecs2D[hash | 1]; + } + else + { + int hash = Hash(seed, i + PrimeX, j + PrimeY); + int index1 = hash & (127 << 1); + int index2 = (hash >> 7) & (255 << 1); + float xg = Gradients2D[index1]; + float yg = Gradients2D[index1 | 1]; + float value = x2 * xg + y2 * yg; + float xgo = RandVecs2D[index2]; + float ygo = RandVecs2D[index2 | 1]; + xo = value * xgo; + yo = value * ygo; + } + vx += cccc * xo; + vy += cccc * yo; + } + + if (y0 > x0) + { + float x1 = x0 + (float)G2; + float y1 = y0 + ((float)G2 - 1); + float b = 0.5f - x1 * x1 - y1 * y1; + if (b > 0) + { + float bbbb = (b * b) * (b * b); + float xo, yo; + if (outGradOnly) + { + int hash = Hash(seed, i, j + PrimeY) & (255 << 1); + xo = RandVecs2D[hash]; + yo = RandVecs2D[hash | 1]; + } + else + { + int hash = Hash(seed, i, j + PrimeY); + int index1 = hash & (127 << 1); + int index2 = (hash >> 7) & (255 << 1); + float xg = Gradients2D[index1]; + float yg = Gradients2D[index1 | 1]; + float value = x1 * xg + y1 * yg; + float xgo = RandVecs2D[index2]; + float ygo = RandVecs2D[index2 | 1]; + xo = value * xgo; + yo = value * ygo; + } + vx += bbbb * xo; + vy += bbbb * yo; + } + } + else + { + float x1 = x0 + ((float)G2 - 1); + float y1 = y0 + (float)G2; + float b = 0.5f - x1 * x1 - y1 * y1; + if (b > 0) + { + float bbbb = (b * b) * (b * b); + float xo, yo; + if (outGradOnly) + { + int hash = Hash(seed, i + PrimeX, j) & (255 << 1); + xo = RandVecs2D[hash]; + yo = RandVecs2D[hash | 1]; + } + else + { + int hash = Hash(seed, i + PrimeX, j); + int index1 = hash & (127 << 1); + int index2 = (hash >> 7) & (255 << 1); + float xg = Gradients2D[index1]; + float yg = Gradients2D[index1 | 1]; + float value = x1 * xg + y1 * yg; + float xgo = RandVecs2D[index2]; + float ygo = RandVecs2D[index2 | 1]; + xo = value * xgo; + yo = value * ygo; + } + vx += bbbb * xo; + vy += bbbb * yo; + } + } + + coord.x += vx * warpAmp; + coord.y += vy * warpAmp; + } + + private void SingleDomainWarpOpenSimplex2Gradient(int seed, float warpAmp, float frequency, /*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z, Vector3 coord, boolean outGradOnly) + { + x *= frequency; + y *= frequency; + z *= frequency; + + /* + * --- Rotation moved to switch statements before fractal evaluation --- + * final FNLfloat R3 = (FNLfloat)(2.0 / 3.0); + * FNLfloat r = (x + y + z) * R3; // Rotation, not skew + * x = r - x; y = r - y; z = r - z; + */ + + int i = FastRound(x); + int j = FastRound(y); + int k = FastRound(z); + float x0 = (float)x - i; + float y0 = (float)y - j; + float z0 = (float)z - k; + + int xNSign = (int)(-x0 - 1.0f) | 1; + int yNSign = (int)(-y0 - 1.0f) | 1; + int zNSign = (int)(-z0 - 1.0f) | 1; + + float ax0 = xNSign * -x0; + float ay0 = yNSign * -y0; + float az0 = zNSign * -z0; + + i *= PrimeX; + j *= PrimeY; + k *= PrimeZ; + + float vx, vy, vz; + vx = vy = vz = 0; + + float a = (0.6f - x0 * x0) - (y0 * y0 + z0 * z0); + for (int l = 0; ; l++) + { + if (a > 0) + { + float aaaa = (a * a) * (a * a); + float xo, yo, zo; + if (outGradOnly) + { + int hash = Hash(seed, i, j, k) & (255 << 2); + xo = RandVecs3D[hash]; + yo = RandVecs3D[hash | 1]; + zo = RandVecs3D[hash | 2]; + } + else + { + int hash = Hash(seed, i, j, k); + int index1 = hash & (63 << 2); + int index2 = (hash >> 6) & (255 << 2); + float xg = Gradients3D[index1]; + float yg = Gradients3D[index1 | 1]; + float zg = Gradients3D[index1 | 2]; + float value = x0 * xg + y0 * yg + z0 * zg; + float xgo = RandVecs3D[index2]; + float ygo = RandVecs3D[index2 | 1]; + float zgo = RandVecs3D[index2 | 2]; + xo = value * xgo; + yo = value * ygo; + zo = value * zgo; + } + vx += aaaa * xo; + vy += aaaa * yo; + vz += aaaa * zo; + } + + float b = a; + int i1 = i; + int j1 = j; + int k1 = k; + float x1 = x0; + float y1 = y0; + float z1 = z0; + + if (ax0 >= ay0 && ax0 >= az0) + { + x1 += xNSign; + b = b + ax0 + ax0; + i1 -= xNSign * PrimeX; + } + else if (ay0 > ax0 && ay0 >= az0) + { + y1 += yNSign; + b = b + ay0 + ay0; + j1 -= yNSign * PrimeY; + } + else + { + z1 += zNSign; + b = b + az0 + az0; + k1 -= zNSign * PrimeZ; + } + + if (b > 1) + { + b -= 1; + float bbbb = (b * b) * (b * b); + float xo, yo, zo; + if (outGradOnly) + { + int hash = Hash(seed, i1, j1, k1) & (255 << 2); + xo = RandVecs3D[hash]; + yo = RandVecs3D[hash | 1]; + zo = RandVecs3D[hash | 2]; + } + else + { + int hash = Hash(seed, i1, j1, k1); + int index1 = hash & (63 << 2); + int index2 = (hash >> 6) & (255 << 2); + float xg = Gradients3D[index1]; + float yg = Gradients3D[index1 | 1]; + float zg = Gradients3D[index1 | 2]; + float value = x1 * xg + y1 * yg + z1 * zg; + float xgo = RandVecs3D[index2]; + float ygo = RandVecs3D[index2 | 1]; + float zgo = RandVecs3D[index2 | 2]; + xo = value * xgo; + yo = value * ygo; + zo = value * zgo; + } + vx += bbbb * xo; + vy += bbbb * yo; + vz += bbbb * zo; + } + + if (l == 1) break; + + ax0 = 0.5f - ax0; + ay0 = 0.5f - ay0; + az0 = 0.5f - az0; + + x0 = xNSign * ax0; + y0 = yNSign * ay0; + z0 = zNSign * az0; + + a += (0.75f - ax0) - (ay0 + az0); + + i += (xNSign >> 1) & PrimeX; + j += (yNSign >> 1) & PrimeY; + k += (zNSign >> 1) & PrimeZ; + + xNSign = -xNSign; + yNSign = -yNSign; + zNSign = -zNSign; + + seed += 1293373; + } + + coord.x += vx * warpAmp; + coord.y += vy * warpAmp; + coord.z += vz * warpAmp; + } + + public static class Vector2 + { + public /*FNLfloat*/ float x; + public /*FNLfloat*/ float y; + public Vector2(/*FNLfloat*/ float x, /*FNLfloat*/ float y) + { + this.x = x; + this.y = y; + } + } + + public static class Vector3 + { + public /*FNLfloat*/ float x; + public /*FNLfloat*/ float y; + public /*FNLfloat*/ float z; + public Vector3(/*FNLfloat*/ float x, /*FNLfloat*/ float y, /*FNLfloat*/ float z) + { + this.x = x; + this.y = y; + this.z = z; + } + } +} diff --git a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java new file mode 100644 index 0000000..764a8e3 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java @@ -0,0 +1,65 @@ +package com.moulberry.flashback.visuals; + +import com.moulberry.flashback.combo_options.AspectRatio; +import com.moulberry.flashback.combo_options.Sizing; +import net.minecraft.client.Minecraft; + +public class ReplayVisuals { + + public boolean showChat = false; + public boolean showBossBar = false; + public boolean showTitleText = false; + public boolean showScoreboard = false; + public boolean showActionBar = false; + + public boolean renderBlocks = true; + public boolean renderEntities = true; + public boolean renderPlayers = true; + public boolean renderParticles = true; + public boolean renderSky = true; + public boolean renderNametags = true; + + public boolean overrideFog = false; + public float overrideFogStart = 0.0f; + public float overrideFogEnd = 256.0f; + + public boolean overrideFov = false; + public float overrideFovAmount = 70f; + + public boolean overrideCameraShake = false; + public boolean cameraShakeSplitParams = false; + public float cameraShakeYFrequency = 1.0f; + public float cameraShakeYAmplitude = 1.0f; + public float cameraShakeXFrequency = 1.0f; + public float cameraShakeXAmplitude = 1.0f; + + public boolean overrideRoll = false; + public float overrideRollAmount = 0.0f; + + public long overrideTimeOfDay = -1; + + public boolean ruleOfThirdsGuide = false; + public boolean centerGuide = false; + public boolean cameraPath = true; + public Sizing sizing = Sizing.KEEP_ASPECT_RATIO; + public AspectRatio changeAspectRatio = AspectRatio.ASPECT_16_9; + + public void setFov(float fov) { + if (!overrideFov || Math.abs(overrideFovAmount - fov) >= 0.01) { + Minecraft.getInstance().levelRenderer.needsUpdate(); + } + + overrideFov = true; + overrideFovAmount = fov; + } + + public void setCameraShake(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY) { + overrideCameraShake = true; + cameraShakeSplitParams = frequencyX != frequencyY || amplitudeX != amplitudeY; + cameraShakeXFrequency = frequencyX; + cameraShakeXAmplitude = amplitudeX; + cameraShakeYFrequency = frequencyY; + cameraShakeYAmplitude = amplitudeY; + } + +} diff --git a/src/main/java/com/moulberry/flashback/visuals/Shapes.java b/src/main/java/com/moulberry/flashback/visuals/Shapes.java new file mode 100644 index 0000000..715f87d --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/Shapes.java @@ -0,0 +1,36 @@ +package com.moulberry.flashback.visuals; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; + +public class Shapes { + + public static void line(BufferBuilder bufferBuilder, PoseStack.Pose pose, Vec3 from, Vec3 to) { + line(bufferBuilder, pose, 1f, 1f, 1f, 1f, + (float) from.x, (float) from.y, (float) from.z, (float) to.x, (float) to.y, (float) to.z); + } + public static void line(BufferBuilder bufferBuilder, PoseStack.Pose pose, Vec3 from, Vec3 to, float red, float green, float blue, float alpha) { + line(bufferBuilder, pose, red, green, blue, alpha, + (float) from.x, (float) from.y, (float) from.z, (float) to.x, (float) to.y, (float) to.z); + } + + public static void line(BufferBuilder bufferBuilder, PoseStack.Pose pose, + float red, float green, float blue, float alpha, + float fromX, float fromY, float fromZ, + float toX, float toY, float toZ) { + float dx = toX - fromX; + float dy = toY - fromY; + float dz = toZ - fromZ; + float distanceInv = 1f / (float) Math.sqrt(dx*dx + dy*dy + dz*dz); + dx *= distanceInv; + dy *= distanceInv; + dz *= distanceInv; + + Matrix4f transform = pose.pose(); + bufferBuilder.addVertex(transform, fromX, fromY, fromZ).setColor(red, green, blue, alpha).setNormal(pose, dx, dy, dz); + bufferBuilder.addVertex(transform, toX, toY, toZ).setColor(red, green, blue, alpha).setNormal(pose, dx, dy, dz); + } + +} diff --git a/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java b/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java new file mode 100644 index 0000000..ebcdeb0 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java @@ -0,0 +1,23 @@ +package com.moulberry.flashback.visuals; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.LightTexture; +import org.joml.Matrix4f; + +public class WorldRenderHook { + + public static void renderHook(PoseStack poseStack, float partialTick, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, + LightTexture lightTexture, Matrix4f projection) { + ReplayServer replayServer = Flashback.getReplayServer(); + EditorState editorState = EditorStateManager.getCurrent(); + if (replayServer != null && editorState != null && !Flashback.isExporting() && editorState.replayVisuals.cameraPath) { + CameraPath.renderCameraPath(poseStack, camera, replayServer); + } + } +} diff --git a/src/main/resources/assets/flashback/icon.png b/src/main/resources/assets/flashback/icon.png index 047b91f..f0c9b23 100644 Binary files a/src/main/resources/assets/flashback/icon.png and b/src/main/resources/assets/flashback/icon.png differ diff --git a/src/main/resources/assets/flashback/icon_14x.png b/src/main/resources/assets/flashback/icon_14x.png new file mode 100644 index 0000000..48021a4 Binary files /dev/null and b/src/main/resources/assets/flashback/icon_14x.png differ diff --git a/src/main/resources/assets/flashback/icon_28x.png b/src/main/resources/assets/flashback/icon_28x.png new file mode 100644 index 0000000..7e14729 Binary files /dev/null and b/src/main/resources/assets/flashback/icon_28x.png differ diff --git a/src/main/resources/assets/flashback/icon_42x.png b/src/main/resources/assets/flashback/icon_42x.png new file mode 100644 index 0000000..a01e404 Binary files /dev/null and b/src/main/resources/assets/flashback/icon_42x.png differ diff --git a/src/main/resources/assets/flashback/icon_56x.png b/src/main/resources/assets/flashback/icon_56x.png new file mode 100644 index 0000000..3c16546 Binary files /dev/null and b/src/main/resources/assets/flashback/icon_56x.png differ diff --git a/src/main/resources/assets/flashback/lang/en_us.json b/src/main/resources/assets/flashback/lang/en_us.json index f15d95d..b3bcd10 100644 --- a/src/main/resources/assets/flashback/lang/en_us.json +++ b/src/main/resources/assets/flashback/lang/en_us.json @@ -12,5 +12,9 @@ "flashback.option.automatically_finish": "Automatically Finish", "flashback.option.automatically_finish.description": "Automatically finishes a replay recording when exiting the world/server", "flashback.option.show_recording_toasts": "Show Recording Toasts", - "flashback.option.show_recording_toasts.description": "Show toasts in the top right when starting/stopping a replay recording" -} \ No newline at end of file + "flashback.option.show_recording_toasts.description": "Show toasts in the top right when starting/stopping a replay recording", + "flashback.option.quicksave": "Quicksave", + "flashback.option.quicksave.description": "Save the replay with default values instead of opening the Save Replay screen", + "flashback.option.hide_pause_menu_controls": "Hide Pause Controls", + "flashback.option.hide_pause_menu_controls.description": "Hide Pause (ESC) menu controls for starting/finishing a replay. The commands will still work" +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 9107920..a55535b 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -11,7 +11,7 @@ "homepage": "https://flashback.moulberry.com/", "sources": "https://github.com/Moulberry/Flashback" }, - "license": "ARR", + "license": "https://github.com/Moulberry/Flashback/blob/master/LICENSE.md", "icon": "assets/flashback/icon.png", "environment": "client", "entrypoints": { @@ -37,5 +37,9 @@ "minecraft": "~1.21", "java": ">=21", "fabric-api": "*" - } + }, + "breaks": { + "essential": "<=1.3.4", + "feather": "*" + } } diff --git a/src/main/resources/flashback.accesswidener b/src/main/resources/flashback.accesswidener index 209a6fc..8098603 100644 --- a/src/main/resources/flashback.accesswidener +++ b/src/main/resources/flashback.accesswidener @@ -31,10 +31,12 @@ accessible field net/minecraft/client/multiplayer/MultiPlayerGameMode destroyBlo accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkWithLightPacket lightData Lnet/minecraft/network/protocol/game/ClientboundLightUpdatePacketData; mutable field net/minecraft/network/protocol/game/ClientboundLevelChunkWithLightPacket lightData Lnet/minecraft/network/protocol/game/ClientboundLightUpdatePacketData; +accessible field net/minecraft/client/multiplayer/ClientLevel$ClientLevelData isFlat Z + # Entity accessible field net/minecraft/network/syncher/SynchedEntityData itemsById [Lnet/minecraft/network/syncher/SynchedEntityData$DataItem; - accessible field net/minecraft/world/entity/Entity ENTITY_COUNTER Ljava/util/concurrent/atomic/AtomicInteger; +accessible field net/minecraft/world/entity/LivingEntity fallFlyTicks I # Minecraft server accessible field net/minecraft/server/MinecraftServer levels Ljava/util/Map; @@ -44,6 +46,9 @@ accessible field net/minecraft/server/MinecraftServer storageSource Lnet/minecra accessible field net/minecraft/server/MinecraftServer progressListenerFactory Lnet/minecraft/server/level/progress/ChunkProgressListenerFactory; accessible field net/minecraft/server/MinecraftServer nextTickTimeNanos J +accessible field net/minecraft/world/level/storage/PrimaryLevelData specialWorldProperty Lnet/minecraft/world/level/storage/PrimaryLevelData$SpecialWorldProperty; +mutable field net/minecraft/world/level/storage/PrimaryLevelData specialWorldProperty Lnet/minecraft/world/level/storage/PrimaryLevelData$SpecialWorldProperty; + accessible field net/minecraft/server/MinecraftServer registries Lnet/minecraft/core/LayeredRegistryAccess; mutable field net/minecraft/server/MinecraftServer registries Lnet/minecraft/core/LayeredRegistryAccess; accessible class net/minecraft/resources/RegistryDataLoader$Loader @@ -89,6 +94,21 @@ accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacket accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData$BlockEntityInfo tag Lnet/minecraft/nbt/CompoundTag; accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData buffer [B +# Recording +accessible field net/minecraft/server/level/ServerEntity positionCodec Lnet/minecraft/network/protocol/game/VecDeltaCodec; +mutable field net/minecraft/server/level/ServerEntity positionCodec Lnet/minecraft/network/protocol/game/VecDeltaCodec; +accessible field net/minecraft/server/level/ServerEntity lastPassengers Ljava/util/List; +accessible field net/minecraft/server/level/ServerEntity broadcast Ljava/util/function/Consumer; +mutable field net/minecraft/server/level/ServerEntity broadcast Ljava/util/function/Consumer; +accessible field net/minecraft/server/level/ServerEntity entity Lnet/minecraft/world/entity/Entity; +mutable field net/minecraft/server/level/ServerEntity entity Lnet/minecraft/world/entity/Entity; +accessible field net/minecraft/server/level/ServerEntity lastSentMovement Lnet/minecraft/world/phys/Vec3; +accessible field net/minecraft/server/level/ServerEntity lastSentYRot I +accessible field net/minecraft/server/level/ServerEntity lastSentXRot I +accessible field net/minecraft/server/level/ServerEntity lastSentYHeadRot I +accessible field net/minecraft/server/level/ServerEntity wasOnGround Z +accessible field net/minecraft/server/level/ServerEntity trackedDataValues Ljava/util/List; + # Replay UI accessible field net/minecraft/client/gui/screens/Screen renderables Ljava/util/List; accessible field net/minecraft/client/KeyMapping key Lcom/mojang/blaze3d/platform/InputConstants$Key; @@ -98,6 +118,9 @@ accessible method net/minecraft/client/particle/ParticleEngine clearParticles () accessible field com/mojang/blaze3d/platform/Window width I accessible field com/mojang/blaze3d/platform/Window height I +# Visuals +accessible field net/minecraft/client/Camera eyeHeight F + # Exporting accessible field net/minecraft/client/Minecraft clientTickCount J accessible field net/minecraft/client/Minecraft timer Lnet/minecraft/client/DeltaTracker$Timer; @@ -116,4 +139,11 @@ accessible field com/mojang/blaze3d/platform/Window framebufferWidth I accessible field com/mojang/blaze3d/platform/Window framebufferHeight I accessible field com/mojang/blaze3d/pipeline/RenderTarget colorTextureId I accessible field net/minecraft/client/Minecraft mainRenderTarget Lcom/mojang/blaze3d/pipeline/RenderTarget; -mutable field net/minecraft/client/Minecraft mainRenderTarget Lcom/mojang/blaze3d/pipeline/RenderTarget; \ No newline at end of file +mutable field net/minecraft/client/Minecraft mainRenderTarget Lcom/mojang/blaze3d/pipeline/RenderTarget; +accessible field net/minecraft/client/multiplayer/ClientPacketListener random Lnet/minecraft/util/RandomSource; + +accessible field net/minecraft/client/sounds/SoundManager soundEngine Lnet/minecraft/client/sounds/SoundEngine; +accessible field net/minecraft/client/sounds/SoundEngine library Lcom/mojang/blaze3d/audio/Library; +accessible field com/mojang/blaze3d/audio/Library currentDevice J +accessible field net/minecraft/client/sounds/SoundEngine executor Lnet/minecraft/client/sounds/SoundEngineExecutor; +accessible field net/minecraft/client/sounds/SoundEngineExecutor thread Ljava/lang/Thread; diff --git a/src/main/resources/flashback.mixins.json b/src/main/resources/flashback.mixins.json index ae85f66..3bb517c 100644 --- a/src/main/resources/flashback.mixins.json +++ b/src/main/resources/flashback.mixins.json @@ -9,12 +9,16 @@ "MixinMouseHandler", "MixinRenderTarget", "MixinWindow", + "audio.MixinAudioLibrary", + "audio.MixinSoundEngine", + "norandom.MixinParticle", "packet_fix.MixinBossHealthOverlay", "playback.MixinArmorStandRenderer", "playback.MixinClientCommonPacketListenerImpl", "playback.MixinGameRenderer", "playback.MixinItemInHandRenderer", "record.MixinClientConfigurationPacketListenerImpl", + "record.MixinClientLevel", "ui.MixinPauseScreen", "ui.MixinTitleScreen", "visuals.MixinBossHealthOverlay", @@ -22,7 +26,9 @@ "visuals.MixinEntityRenderDispatcher", "visuals.MixinFogRenderer", "visuals.MixinGui", + "visuals.MixinLevelRenderer", "visuals.MixinLoadingOverlay", + "visuals.MixinMouseHandler", "visuals.MixinOptions" ], "injectors": { @@ -32,8 +38,10 @@ "MixinThreadedLevelLightEngine", "compat.MixinAxiomEditorUI", "compat.MixinSodiumWorldRenderer", + "playback.MixinAttributeInstance", + "playback.MixinChunkHolder", "playback.MixinEntity", - "playback.MixinLevelChunkSection", + "playback.MixinLevelChunk", "playback.MixinLivingEntity", "playback.MixinPlayerChunkSender", "playback.MixinScoreboard", diff --git a/src/main/resources/licenses/ImGui-LICENSE b/src/main/resources/licenses/ImGui-LICENSE new file mode 100644 index 0000000..3282f5b --- /dev/null +++ b/src/main/resources/licenses/ImGui-LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2024 Omar Cornut + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/main/resources/licenses/Spair-ImGui-LICENSE b/src/main/resources/licenses/Spair-ImGui-LICENSE new file mode 100644 index 0000000..1ab3aa9 --- /dev/null +++ b/src/main/resources/licenses/Spair-ImGui-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-present, Ilya "SpaiR" Prymshyts + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.