diff --git a/build.gradle b/build.gradle index 8979dea..f93095f 100644 --- a/build.gradle +++ b/build.gradle @@ -23,25 +23,31 @@ base { } repositories { - // Add repositories to retrieve artifacts from in here. - // You should only use this when depending on other mods because - // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. - // See https://docs.gradle.org/current/userguide/declaring_repositories.html - // for more information about repositories. - maven { url = "https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1" } + maven { + url = "https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1" + content { + includeGroup("me.djtheredstoner") + } + } + maven { + url 'https://api.modrinth.com/maven' + content { + includeGroup("maven.modrinth") + } + } } loom { - accessWidenerPath.set(new File(rootDir, "src/main/resources/flashback.accesswidener")) - splitEnvironmentSourceSets() - - mods { - "flashback" { - sourceSet sourceSets.main - sourceSet sourceSets.client - } - } + accessWidenerPath = file("src/main/resources/flashback.accesswidener") +// splitEnvironmentSourceSets() +// +// mods { +// "flashback" { +// sourceSet sourceSets.main +// sourceSet sourceSets.client +// } +// } } dependencies { @@ -55,19 +61,89 @@ dependencies { // Fabric API. This is technically optional, but you probably want it anyway. modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + include(implementation("com.moulberry:mixinconstraints:1.0.1")) + + modCompileOnly("maven.modrinth:sodium:RncWhTxD") + modImplementation("maven.modrinth:modmenu:xhN1IvHi") +// modCompileOnly("maven.modrinth:axiom:D3uDJmiB") + + // modRuntimeOnly("maven.modrinth:sodium:mc1.20.6-0.5.11") + // shadow(implementation("org.jcodec:jcodec:0.2.5")) // shadow(implementation("org.jcodec:jcodec-javase:0.2.5")) - shadow(implementation("io.humble:humble-video-all:0.3.0")) +// shadow(implementation("io.humble:humble-video-all:0.3.0")) + + shadow(implementation("org.bytedeco:javacv-platform:1.5.10") { + exclude group: "org.bytedeco", module: "artoolkitplus" + exclude group: "org.bytedeco", module: "artoolkitplus-platform" + exclude group: "org.bytedeco", module: "flycapture" + exclude group: "org.bytedeco", module: "flycapture-platform" + exclude group: "org.bytedeco", module: "leptonica" + exclude group: "org.bytedeco", module: "leptonica-platform" + exclude group: "org.bytedeco", module: "libdc1394" + exclude group: "org.bytedeco", module: "libdc1394-platform" + exclude group: "org.bytedeco", module: "libfreenect" + exclude group: "org.bytedeco", module: "libfreenect-platform" + exclude group: "org.bytedeco", module: "libfreenect2" + exclude group: "org.bytedeco", module: "libfreenect2-platform" + exclude group: "org.bytedeco", module: "librealsense2" + exclude group: "org.bytedeco", module: "librealsense2-platform" + exclude group: "org.bytedeco", module: "librealsense" + exclude group: "org.bytedeco", module: "librealsense-platform" + exclude group: "org.bytedeco", module: "openblas" + exclude group: "org.bytedeco", module: "openblas-platform" + exclude group: "org.bytedeco", module: "opencv" + exclude group: "org.bytedeco", module: "opencv-platform" + exclude group: "org.bytedeco", module: "tesseract" + exclude group: "org.bytedeco", module: "tesseract-platform" + exclude group: "org.bytedeco", module: "videoinput" + exclude group: "org.bytedeco", module: "videoinput-platform" + }) +// implementation 'org.jcodec:jcodec:0.2.5' +// implementation("com.github.zakgof:velvet-video:0.5.2") +// implementation("com.github.zakgof:velvet-video-natives:0.2.8.free") // ImGui - shadow(implementation(rootProject.files('deps/imgui-java-binding-1.86.11-10-g0dbf36c.jar'))) - shadow(implementation("io.github.spair:imgui-java-lwjgl3:1.86.10") { - exclude group: 'org.lwjgl' - exclude group: 'org.lwjgl.lwjgl' - }) - shadow(api(rootProject.files('deps/imgui-java-natives-linux-1.86.11-10-g0dbf36c.jar'))) - shadow(api(rootProject.files('deps/imgui-java-natives-macos-1.86.11-10-g0dbf36c.jar'))) - shadow(api(rootProject.files('deps/imgui-java-natives-windows-1.86.11-10-g0dbf36c.jar'))) + shadow(implementation(rootProject.files('deps/imgui-java-binding-1.86.11-10-g0dbf36c.jar'))) + shadow(implementation("io.github.spair:imgui-java-lwjgl3:1.86.10") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api(rootProject.files('deps/imgui-java-natives-linux-1.86.11-10-g0dbf36c.jar'))) + shadow(api(rootProject.files('deps/imgui-java-natives-macos-1.86.11-10-g0dbf36c.jar'))) + shadow(api(rootProject.files('deps/imgui-java-natives-windows-1.86.11-10-g0dbf36c.jar'))) + + // Native File Dialogs + String nfdVersion = "org.lwjgl:lwjgl-nfd:3.3.3"; + + shadow(implementation(nfdVersion) { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api("org.lwjgl:lwjgl-nfd::natives-macos") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api("org.lwjgl:lwjgl-nfd::natives-linux") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api("org.lwjgl:lwjgl-nfd::natives-windows") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api("org.lwjgl:lwjgl-nfd::natives-macos-arm64") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api("org.lwjgl:lwjgl-nfd::natives-linux-arm64") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) + shadow(api("org.lwjgl:lwjgl-nfd::natives-windows-arm64") { + exclude group: 'org.lwjgl' + exclude group: 'org.lwjgl.lwjgl' + }) } processResources { @@ -108,6 +184,12 @@ shadowJar { exclude("LICENSE.txt") } +remapJar { + dependsOn(shadowJar) + input = shadowJar.getArchiveFile() +} + + // configure the maven publication publishing { publications { diff --git a/gradle.properties b/gradle.properties index acdf74b..306d3c8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,14 +4,14 @@ org.gradle.parallel=true # Fabric Properties # check these on https://fabricmc.net/develop -minecraft_version=1.20.6 -yarn_mappings=1.20.6+build.1 -loader_version=0.15.10 +minecraft_version=1.21 +yarn_mappings=1.21+build.9 +loader_version=0.15.11 # Mod Properties -mod_version=1.0.0 -maven_group=com.example -archives_base_name=modid +mod_version=1.0.2 +maven_group=com.moulberry.flashback +archives_base_name=flashback # Dependencies -fabric_version=0.97.8+1.20.6 \ No newline at end of file +fabric_version=0.100.7+1.21 \ No newline at end of file diff --git a/src/client/java/com/moulberry/flashback/ChunkSectionHash.java b/src/client/java/com/moulberry/flashback/ChunkSectionHash.java deleted file mode 100644 index 6c2d5df..0000000 --- a/src/client/java/com/moulberry/flashback/ChunkSectionHash.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.moulberry.flashback; - -public record ChunkSectionHash(short nonEmptyBlockCount, long blockHash, long biomeHash) { -} diff --git a/src/client/java/com/moulberry/flashback/ReplayVisuals.java b/src/client/java/com/moulberry/flashback/ReplayVisuals.java deleted file mode 100644 index edcbf95..0000000 --- a/src/client/java/com/moulberry/flashback/ReplayVisuals.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.moulberry.flashback; - -public class ReplayVisuals { - - public static boolean showBossBar = true; - public static boolean showTitleText = true; - public static boolean showScoreboard = true; - public static boolean showActionBar = true; - public static boolean showNametags = true; - public static float overrideFogDistance = 0.0f; - public static float overrideFov = 0.0f; - public static long overrideTimeOfDay = -1; - - public static volatile int forceEntityLerpTicks = 0; - - public static void disable() { - showBossBar = true; - showTitleText = true; - showScoreboard = true; - showActionBar = true; - showNametags = true; - overrideFogDistance = 0.0f; - overrideFov = 0.0f; - forceEntityLerpTicks = 0; - overrideTimeOfDay = -1; - } - - public static void setupReplay() { - disable(); - - showBossBar = false; - showTitleText = false; - showActionBar = false; - showScoreboard = false; - } - -} diff --git a/src/client/java/com/moulberry/flashback/exporting/ExportJob.java b/src/client/java/com/moulberry/flashback/exporting/ExportJob.java deleted file mode 100644 index 8bf70ad..0000000 --- a/src/client/java/com/moulberry/flashback/exporting/ExportJob.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.moulberry.flashback.exporting; - -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.platform.Window; -import com.mojang.blaze3d.systems.RenderSystem; -import com.moulberry.flashback.FlashbackClient; -import com.moulberry.flashback.keyframe.Keyframes; -import com.moulberry.flashback.playback.ReplayServer; -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.Screenshot; -import net.minecraft.client.gui.Font; -import net.minecraft.client.renderer.FogRenderer; -import org.joml.Matrix4f; - -import java.util.concurrent.locks.LockSupport; - -public class ExportJob { - - private final int startTick; - private final int endTick; - private final int framesPerTick = 60 / 20; - - private boolean running = false; - private long lastRenderMillis; - private long renderStartTime; - - public ExportJob(int startTick, int endTick) { - this.startTick = startTick; - this.endTick = endTick; - } - - public void run() { - ReplayServer replayServer = FlashbackClient.getReplayServer(); - if (this.running || replayServer == null) { - return; - } - this.running = true; - - AsyncVideoEncoder encoder = new AsyncVideoEncoder(this.framesPerTick * 20); - - int currentFrame = 0; - int totalFrames = (this.endTick - this.startTick + 1) * this.framesPerTick; - int clientTickCount = 0; - - boolean shouldDoTextureDownload = false; - - RenderTarget mainRenderTarget = Minecraft.getInstance().getMainRenderTarget(); - this.renderStartTime = System.currentTimeMillis(); - - while (currentFrame <= totalFrames) { - int targetServerTick = this.startTick + currentFrame / this.framesPerTick; - - // Wait until server is on correct replay tick - while (replayServer.getReplayTick() != targetServerTick) { - replayServer.finishedServerTick.set(false); - replayServer.jumpToTick = targetServerTick; - replayServer.replayPaused = true; - - // Do some work by downloading textures while we're waiting for the server - if (shouldDoTextureDownload) { - shouldDoTextureDownload = false; - finishFrame(encoder, currentFrame-1, totalFrames); - } - - while (!replayServer.finishedServerTick.compareAndExchange(true, false)) { - LockSupport.parkNanos("waiting for server thread", 100000L); - } - } - - if (shouldDoTextureDownload) { - shouldDoTextureDownload = false; - finishFrame(encoder, currentFrame-1, totalFrames); - } - - long targetClientTick = currentFrame / this.framesPerTick; - - // Ensure client isn't frozen so partialTick is correctly used - Minecraft.getInstance().level.tickRateManager().setFrozen(false); - - // Tick client - while (clientTickCount < targetClientTick) { - while (Minecraft.getInstance().pollTask()) {} - Minecraft.getInstance().tick(); - clientTickCount += 1; - } - - float partialTick = (currentFrame / (float) this.framesPerTick) % 1.0f; - Keyframes.applyKeyframes(Minecraft.getInstance(), targetServerTick + partialTick); - - mainRenderTarget.bindWrite(true); - FogRenderer.setupNoFog(); - RenderSystem.enableCull(); - Minecraft.getInstance().timer.partialTick = partialTick; - Minecraft.getInstance().gameRenderer.render(partialTick, Util.getNanos(), true); - mainRenderTarget.unbindWrite(); - - shouldDoTextureDownload = true; - - currentFrame += 1; - } - - if (shouldDoTextureDownload) { - shouldDoTextureDownload = false; - finishFrame(encoder, currentFrame-1, totalFrames); - } - - encoder.finish(); - } - - - private void finishFrame(AsyncVideoEncoder encoder, int currentFrame, int totalFrames) { - RenderTarget mainRenderTarget = Minecraft.getInstance().getMainRenderTarget(); - NativeImage nativeImage = Screenshot.takeScreenshot(mainRenderTarget); - encoder.encode(nativeImage); - Window window = Minecraft.getInstance().getWindow(); - - long currentTime = System.currentTimeMillis(); - if (currentTime - this.lastRenderMillis > 10) { - this.lastRenderMillis = currentTime; - - var bufferSource = Minecraft.getInstance().renderBuffers().bufferSource(); - bufferSource.endBatch(); - mainRenderTarget.bindWrite(true); - - RenderSystem.disableDepthTest(); - Matrix4f matrix = new Matrix4f(); - matrix.translate(0.0f, 0.0f, -11000f); - float x = window.getGuiScaledWidth()/2f; - float y = window.getGuiScaledHeight()/2f; - Font font = Minecraft.getInstance().font; - - String line1 = "Exported Frames: " + currentFrame + "/" + totalFrames; - font.drawInBatch(line1, x - font.width(line1)/2f, y - font.lineHeight, - -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); - - long elapsed = currentTime - this.renderStartTime; - String line2 = "Time elapsed: " + formatTime(elapsed); - font.drawInBatch(line2, x - font.width(line2)/2f, y, - -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); - - if (currentFrame > framesPerTick*20) { - long estimatedRemaining = (currentTime - this.renderStartTime) * (totalFrames - currentFrame) / currentFrame; - String line3 = "Estimated time remaining: " + formatTime(estimatedRemaining); - font.drawInBatch(line3, x - font.width(line3)/2f, y + font.lineHeight, - -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); - } - - bufferSource.endBatch(); - RenderSystem.enableDepthTest(); - - mainRenderTarget.unbindWrite(); - mainRenderTarget.blitToScreen(window.getWidth(), window.getHeight()); - window.updateDisplay(); - } - } - - private String formatTime(long millis) { - long seconds = (millis / 1000) % 60; - long minutes = (millis / 1000 / 60) % 60; - long hours = millis / 1000 / 60 / 60; - - if (hours > 0) { - return hours + "h " + minutes + "m " + seconds + "s"; - } else if (minutes > 0) { - return minutes + "m " + seconds + "s"; - } else { - return seconds + "s"; - } - } - -} diff --git a/src/client/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java b/src/client/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java deleted file mode 100644 index 06413a4..0000000 --- a/src/client/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.moulberry.flashback.ext; - -import com.moulberry.flashback.ChunkSectionHash; - -public interface LevelChunkSectionExt { - - ChunkSectionHash flashback$hashState(); - boolean flashback$doesHashedStateMatch(ChunkSectionHash hashedState); - -} diff --git a/src/client/java/com/moulberry/flashback/ext/PaletteExt.java b/src/client/java/com/moulberry/flashback/ext/PaletteExt.java deleted file mode 100644 index e1345a0..0000000 --- a/src/client/java/com/moulberry/flashback/ext/PaletteExt.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.moulberry.flashback.ext; - -public interface PaletteExt { - - long flashback$hash(); - -} diff --git a/src/client/java/com/moulberry/flashback/keyframe/Keyframe.java b/src/client/java/com/moulberry/flashback/keyframe/Keyframe.java deleted file mode 100644 index 41f40f5..0000000 --- a/src/client/java/com/moulberry/flashback/keyframe/Keyframe.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.moulberry.flashback.keyframe; - -import com.moulberry.flashback.keyframe.interpolation.InterpolationType; - -public abstract class Keyframe { - - public final Class operandClass; - private InterpolationType interpolationType = InterpolationType.SMOOTH; - - public Keyframe(Class operandClass) { - this.operandClass = operandClass; - } - - public InterpolationType interpolationType() { - return interpolationType; - } - - public void interpolationType(InterpolationType interpolationType) { - this.interpolationType = interpolationType; - } - - 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, - float lerpAmount, boolean lerpFromRight); - -} diff --git a/src/client/java/com/moulberry/flashback/keyframe/Keyframes.java b/src/client/java/com/moulberry/flashback/keyframe/Keyframes.java deleted file mode 100644 index 2f32f11..0000000 --- a/src/client/java/com/moulberry/flashback/keyframe/Keyframes.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.moulberry.flashback.keyframe; - -import com.moulberry.flashback.keyframe.interpolation.InterpolationType; -import com.moulberry.flashback.keyframe.interpolation.SidedInterpolationType; -import com.moulberry.flashback.playback.ReplayServer; -import net.minecraft.client.Minecraft; -import org.lwjgl.glfw.GLFW; - -import java.util.EnumMap; -import java.util.Map; -import java.util.Objects; -import java.util.TreeMap; - -public class Keyframes { - - public static final EnumMap>> keyframes = new EnumMap<>(KeyframeType.class); - - @SuppressWarnings("unchecked") - public static void applyKeyframes(T t, float tick) { - for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { - TreeMap> keyframeTimes = entry.getValue(); - if (keyframeTimes.isEmpty()) { - continue; - } - - Map.Entry> lowerEntry = keyframeTimes.floorEntry((int) tick); - if (lowerEntry == null) { - continue; - } - - if (lowerEntry.getValue().operandClass != t.getClass()) { - continue; - } - Keyframe lowerKeyframe = (Keyframe) lowerEntry.getValue(); - - SidedInterpolationType leftInterpolation = lowerEntry.getValue().interpolationType().rightSide; - if (leftInterpolation == SidedInterpolationType.HOLD) { - lowerKeyframe.apply(t); - continue; - } - - Map.Entry> ceilEntry = keyframeTimes.ceilingEntry((int) tick); - if (ceilEntry == null) { - continue; - } - - if (Objects.equals(lowerEntry.getKey(), ceilEntry.getKey())) { - lowerKeyframe.apply(t); - continue; - } - - float amount = (tick - lowerEntry.getKey()) / (ceilEntry.getKey() - lowerEntry.getKey()); - - SidedInterpolationType rightInterpolation = ceilEntry.getValue().interpolationType().leftSide; - if (rightInterpolation == SidedInterpolationType.HOLD) { - rightInterpolation = leftInterpolation; - } - - boolean isUsingSmooth = leftInterpolation == SidedInterpolationType.SMOOTH || - rightInterpolation == SidedInterpolationType.SMOOTH; - - if (isUsingSmooth) { - Map.Entry> beforeEntry = keyframeTimes.floorEntry(lowerEntry.getKey() - 1); - if (beforeEntry == null) { - beforeEntry = lowerEntry; - } - - Map.Entry> afterAfterEntry = keyframeTimes.ceilingEntry(ceilEntry.getKey() + 1); - if (afterAfterEntry == null) { - afterAfterEntry = ceilEntry; - } - - float lerpAmount = -1f; - boolean lerpFromRight = false; - if (leftInterpolation != SidedInterpolationType.SMOOTH) { - lerpAmount = SidedInterpolationType.interpolate(leftInterpolation, leftInterpolation, amount); - lerpFromRight = false; - } else if (rightInterpolation != SidedInterpolationType.SMOOTH) { - lerpAmount = SidedInterpolationType.interpolate(rightInterpolation, rightInterpolation, amount); - lerpFromRight = true; - } - - ((Keyframe)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); - if (amount == 0.0) { - lowerKeyframe.apply(t); - } else { - lowerKeyframe.applyInterpolated(t, ceilEntry.getValue(), amount); - } - } - - } - } - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinLevelRenderer.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinLevelRenderer.java deleted file mode 100644 index 1ef246d..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/MixinLevelRenderer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.moulberry.flashback.mixin.client; - -import com.moulberry.flashback.ui.ReplayUI; -import net.minecraft.client.Camera; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; -import org.joml.Matrix4f; -import org.spongepowered.asm.mixin.Mixin; -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 { - - @Inject(method = "renderLevel", at = @At("HEAD")) - public void renderLevel(float f, long l, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f projection, CallbackInfo ci) { - ReplayUI.lastProjectionMatrix = projection; - ReplayUI.lastViewQuaternion = camera.rotation(); - } - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinRenderTarget.java b/src/client/java/com/moulberry/flashback/mixin/client/MixinRenderTarget.java deleted file mode 100644 index 8904bb3..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/MixinRenderTarget.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.moulberry.flashback.mixin.client; - -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.GlStateManager; -import com.moulberry.flashback.ui.ReplayUI; -import net.minecraft.client.Minecraft; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(RenderTarget.class) -public class MixinRenderTarget { - - @Redirect(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) { - if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive()) { - ReplayUI.setupMainViewport(); - } else { - GlStateManager._viewport(left, bottom, width, height); - } - } - - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLevelChunkSection.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLevelChunkSection.java deleted file mode 100644 index 6900903..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLevelChunkSection.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.moulberry.flashback.mixin.client.playback; - -import com.moulberry.flashback.ChunkSectionHash; -import com.moulberry.flashback.ext.LevelChunkSectionExt; -import com.moulberry.flashback.ext.PaletteExt; -import net.minecraft.core.Holder; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.GlobalPalette; -import net.minecraft.world.level.chunk.HashMapPalette; -import net.minecraft.world.level.chunk.LevelChunkSection; -import net.minecraft.world.level.chunk.LinearPalette; -import net.minecraft.world.level.chunk.PalettedContainer; -import net.minecraft.world.level.chunk.PalettedContainerRO; -import net.minecraft.world.level.chunk.SingleValuePalette; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -@Mixin(LevelChunkSection.class) -public class MixinLevelChunkSection implements LevelChunkSectionExt { - - @Shadow - @Final - private PalettedContainer states; - - @Shadow - private short nonEmptyBlockCount; - - @Shadow - private PalettedContainerRO> biomes; - - @Override - public ChunkSectionHash flashback$hashState() { - long blockHash = hashPalettedContainerData(this.states.data); - long biomeHash = hashPalettedContainerData(((PalettedContainer) this.biomes).data); - return new ChunkSectionHash(this.nonEmptyBlockCount, blockHash, biomeHash); - } - - @Unique - private static long hashPalettedContainerData(PalettedContainer.Data data) { - long hash; - if (data.palette() instanceof PaletteExt paletteExt) { - hash = paletteExt.flashback$hash(); - } else { - throw new RuntimeException("Unknown palette type: " + data.palette().getClass()); - } - for (long l : data.storage().getRaw()) { - hash = l + hash*17; - } - return hash; - } - - @Override - public boolean flashback$doesHashedStateMatch(ChunkSectionHash hashedState) { - if (hashedState.nonEmptyBlockCount() != this.nonEmptyBlockCount) { - return false; - } - - long biomeHash = hashPalettedContainerData(((PalettedContainer) this.biomes).data); - if (hashedState.biomeHash() != biomeHash) { - return false; - } - - long blockHash = hashPalettedContainerData(this.states.data); - return hashedState.blockHash() == blockHash; - } - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLivingEntity.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLivingEntity.java deleted file mode 100644 index 94d6ed2..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinLivingEntity.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.moulberry.flashback.mixin.client.playback; - -import com.moulberry.flashback.FlashbackClient; -import net.minecraft.client.Minecraft; -import net.minecraft.client.player.LocalPlayer; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.level.Level; -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.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(LivingEntity.class) -public abstract class MixinLivingEntity extends Entity { - - @Shadow - public abstract void lerpTo(double d, double e, double f, float g, float h, int i); - - @Shadow - public abstract void lerpHeadTo(float f, int i); - - public MixinLivingEntity(EntityType entityType, Level level) { - super(entityType, level); - } - - @Inject(method = "lerpTo", at = @At("HEAD"), cancellable = true) - public void lerpTo(double d, double e, double f, float g, float h, int i, CallbackInfo ci) { - if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) { - this.lerpTo(d, e, f, g, h, 1); - ci.cancel(); - } - } - - @Inject(method = "lerpHeadTo", at = @At("HEAD"), cancellable = true) - public void lerpHeadTo(float f, int i, CallbackInfo ci) { - if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) { - this.lerpHeadTo(f, 1); - ci.cancel(); - } - } - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinGlobalPalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinGlobalPalette.java deleted file mode 100644 index 526cc91..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinGlobalPalette.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.moulberry.flashback.mixin.client.playback.hashing; - -import com.moulberry.flashback.ext.PaletteExt; -import net.minecraft.world.level.chunk.GlobalPalette; -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(GlobalPalette.class) -public class MixinGlobalPalette implements PaletteExt { - @Override - public long flashback$hash() { - return 0xCF184DF659428CABL; - } -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinHashMapPalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinHashMapPalette.java deleted file mode 100644 index e4a9c84..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinHashMapPalette.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.moulberry.flashback.mixin.client.playback.hashing; - -import com.moulberry.flashback.ext.PaletteExt; -import net.minecraft.core.IdMap; -import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap; -import net.minecraft.world.level.chunk.HashMapPalette; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(HashMapPalette.class) -public abstract class MixinHashMapPalette implements PaletteExt { - @Shadow - @Final - private IdMap registry; - - @Shadow - @Final - private CrudeIncrementalIntIdentityHashBiMap values; - - @Shadow - public abstract int getSize(); - - @Override - public long flashback$hash() { - long hash = 0; - int size = this.getSize(); - for(int j = 0; j < size; ++j) { - hash = this.registry.getId(this.values.byId(j)) + hash*17; - } - return hash; - } -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinLinearPalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinLinearPalette.java deleted file mode 100644 index fb4680b..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinLinearPalette.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.moulberry.flashback.mixin.client.playback.hashing; - -import com.moulberry.flashback.ext.PaletteExt; -import net.minecraft.core.IdMap; -import net.minecraft.world.level.chunk.LinearPalette; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(LinearPalette.class) -public class MixinLinearPalette implements PaletteExt { - @Shadow - private int size; - - @Shadow - @Final - private IdMap registry; - - @Shadow - @Final - public T[] values; - - @Override - public long flashback$hash() { - long hash = 0; - int size = this.size; - for(int i = 0; i < size; ++i) { - hash = this.registry.getId(this.values[i]) + hash*17; - } - return hash; - } -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinSingleValuePalette.java b/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinSingleValuePalette.java deleted file mode 100644 index 2e4ebce..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/hashing/MixinSingleValuePalette.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.moulberry.flashback.mixin.client.playback.hashing; - -import com.moulberry.flashback.ext.PaletteExt; -import net.minecraft.core.IdMap; -import net.minecraft.world.level.chunk.SingleValuePalette; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(SingleValuePalette.class) -public class MixinSingleValuePalette implements PaletteExt { - @Shadow - @Final - public IdMap registry; - - @Shadow - @Nullable - public T value; - - @Override - public long flashback$hash() { - return this.registry.getId(this.value); - } -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkStatusTasks.java b/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkStatusTasks.java deleted file mode 100644 index 7665aff..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkStatusTasks.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.moulberry.flashback.mixin.client.replay_server; - -import com.moulberry.flashback.FlashbackClient; -import net.minecraft.server.level.ThreadedLevelLightEngine; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.status.ChunkStatusTasks; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.concurrent.CompletableFuture; - -@Mixin(ChunkStatusTasks.class) -public class MixinChunkStatusTasks { - - @Inject(method = "initializeLight", at = @At("HEAD"), cancellable = true) - private static void initializeLight(ThreadedLevelLightEngine threadedLevelLightEngine, ChunkAccess chunkAccess, CallbackInfoReturnable> cir) { - if (FlashbackClient.isInReplay()) { - cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess)); - } - } - - @Inject(method = "lightChunk", at = @At("HEAD"), cancellable = true) - private static void lightChunk(ThreadedLevelLightEngine threadedLevelLightEngine, ChunkAccess chunkAccess, CallbackInfoReturnable> cir) { - if (FlashbackClient.isInReplay()) { - cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess)); - } - } - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/ui/MixinTitleScreen.java b/src/client/java/com/moulberry/flashback/mixin/client/ui/MixinTitleScreen.java deleted file mode 100644 index 262ddcb..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/ui/MixinTitleScreen.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.moulberry.flashback.mixin.client.ui; - -import com.moulberry.flashback.FlashbackClient; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.TitleScreen; -import net.minecraft.network.chat.Component; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(TitleScreen.class) -public class MixinTitleScreen extends Screen { - - private MixinTitleScreen() { - super(null); - } - - @Inject(method = "createNormalMenuOptions", at = @At("RETURN")) - public void createNormalMenuOptions(int i, int j, CallbackInfo ci) { - this.addRenderableWidget(Button.builder(Component.literal("Replay"), button -> { - FlashbackClient.testReplayWorld(); - }).bounds(this.width / 2 - 100, i + j * 3, 200, 20).build()); - } - -} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevel.java b/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevel.java deleted file mode 100644 index 3989d46..0000000 --- a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevel.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.moulberry.flashback.mixin.client.visuals; - -public class MixinClientLevel { - - - -} diff --git a/src/client/java/com/moulberry/flashback/record/IgnoredPacketSet.java b/src/client/java/com/moulberry/flashback/record/IgnoredPacketSet.java deleted file mode 100644 index 866a5be..0000000 --- a/src/client/java/com/moulberry/flashback/record/IgnoredPacketSet.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.moulberry.flashback.record; - -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; -import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; -import net.minecraft.network.protocol.common.ClientboundPingPacket; -import net.minecraft.network.protocol.common.ClientboundStoreCookiePacket; -import net.minecraft.network.protocol.common.ClientboundTransferPacket; -import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; -import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; -import net.minecraft.network.protocol.game.ClientboundAwardStatsPacket; -import net.minecraft.network.protocol.game.ClientboundBlockChangedAckPacket; -import net.minecraft.network.protocol.game.ClientboundChunkBatchFinishedPacket; -import net.minecraft.network.protocol.game.ClientboundChunkBatchStartPacket; -import net.minecraft.network.protocol.game.ClientboundCommandSuggestionsPacket; -import net.minecraft.network.protocol.game.ClientboundCommandsPacket; -import net.minecraft.network.protocol.game.ClientboundContainerClosePacket; -import net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket; -import net.minecraft.network.protocol.game.ClientboundContainerSetDataPacket; -import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket; -import net.minecraft.network.protocol.game.ClientboundCooldownPacket; -import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket; -import net.minecraft.network.protocol.game.ClientboundDebugSamplePacket; -import net.minecraft.network.protocol.game.ClientboundDeleteChatPacket; -import net.minecraft.network.protocol.game.ClientboundForgetLevelChunkPacket; -import net.minecraft.network.protocol.game.ClientboundHorseScreenOpenPacket; -import net.minecraft.network.protocol.game.ClientboundMerchantOffersPacket; -import net.minecraft.network.protocol.game.ClientboundMoveEntityPacket; -import net.minecraft.network.protocol.game.ClientboundOpenBookPacket; -import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket; -import net.minecraft.network.protocol.game.ClientboundOpenSignEditorPacket; -import net.minecraft.network.protocol.game.ClientboundPlaceGhostRecipePacket; -import net.minecraft.network.protocol.game.ClientboundPlayerAbilitiesPacket; -import net.minecraft.network.protocol.game.ClientboundPlayerChatPacket; -import net.minecraft.network.protocol.game.ClientboundPlayerCombatEndPacket; -import net.minecraft.network.protocol.game.ClientboundPlayerCombatEnterPacket; -import net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket; -import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket; -import net.minecraft.network.protocol.game.ClientboundRecipePacket; -import net.minecraft.network.protocol.game.ClientboundSelectAdvancementsTabPacket; -import net.minecraft.network.protocol.game.ClientboundSetCameraPacket; -import net.minecraft.network.protocol.game.ClientboundSetCarriedItemPacket; -import net.minecraft.network.protocol.game.ClientboundSetChunkCacheCenterPacket; -import net.minecraft.network.protocol.game.ClientboundSetChunkCacheRadiusPacket; -import net.minecraft.network.protocol.game.ClientboundSetSimulationDistancePacket; -import net.minecraft.network.protocol.game.ClientboundStartConfigurationPacket; -import net.minecraft.network.protocol.game.ClientboundTagQueryPacket; -import net.minecraft.network.protocol.game.ClientboundTickingStatePacket; -import net.minecraft.network.protocol.game.ClientboundTickingStepPacket; -import net.minecraft.network.protocol.game.ClientboundUpdateAdvancementsPacket; -import net.minecraft.network.protocol.game.ClientboundUpdateRecipesPacket; -import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket; - -import java.util.Set; - -public class IgnoredPacketSet { - - public static boolean isIgnored(Packet packet) { - return IGNORED.contains(packet.getClass()); - } - - private static final Set> IGNORED = Set.of( - // Common - ClientboundStoreCookiePacket.class, - ClientboundCookieRequestPacket.class, - ClientboundDisconnectPacket.class, - ClientboundPingPacket.class, - ClientboundKeepAlivePacket.class, - ClientboundTransferPacket.class, - - // Configuration - ClientboundFinishConfigurationPacket.class, - - // Game - ClientboundAwardStatsPacket.class, - ClientboundRecipePacket.class, - ClientboundOpenSignEditorPacket.class, - ClientboundMoveEntityPacket.Pos.class, - ClientboundMoveEntityPacket.Rot.class, - ClientboundMoveEntityPacket.PosRot.class, - ClientboundPlayerPositionPacket.class, - ClientboundPlayerChatPacket.class, - ClientboundDeleteChatPacket.class, - ClientboundContainerClosePacket.class, - ClientboundContainerSetContentPacket.class, - ClientboundHorseScreenOpenPacket.class, - ClientboundContainerSetDataPacket.class, - ClientboundContainerSetSlotPacket.class, - ClientboundForgetLevelChunkPacket.class, - ClientboundPlayerAbilitiesPacket.class, - ClientboundSetCarriedItemPacket.class, - ClientboundTickingStatePacket.class, - ClientboundTickingStepPacket.class, - ClientboundPlayerCombatEndPacket.class, - ClientboundPlayerCombatEnterPacket.class, - ClientboundPlayerCombatKillPacket.class, - ClientboundSetCameraPacket.class, - ClientboundCooldownPacket.class, - ClientboundUpdateAdvancementsPacket.class, - ClientboundSelectAdvancementsTabPacket.class, - ClientboundPlaceGhostRecipePacket.class, - ClientboundCommandsPacket.class, - ClientboundCommandSuggestionsPacket.class, - ClientboundUpdateRecipesPacket.class, - ClientboundTagQueryPacket.class, - ClientboundOpenBookPacket.class, - ClientboundOpenScreenPacket.class, - ClientboundMerchantOffersPacket.class, - ClientboundSetChunkCacheRadiusPacket.class, - ClientboundSetSimulationDistancePacket.class, - ClientboundSetChunkCacheCenterPacket.class, - ClientboundBlockChangedAckPacket.class, - ClientboundCustomChatCompletionsPacket.class, - ClientboundStartConfigurationPacket.class, - ClientboundChunkBatchStartPacket.class, - ClientboundChunkBatchFinishedPacket.class, - ClientboundDebugSamplePacket.class, - ClientboundPongResponsePacket.class - ); - -} diff --git a/src/client/java/com/moulberry/flashback/record/Recorder.java b/src/client/java/com/moulberry/flashback/record/Recorder.java deleted file mode 100644 index 8cb7812..0000000 --- a/src/client/java/com/moulberry/flashback/record/Recorder.java +++ /dev/null @@ -1,562 +0,0 @@ -package com.moulberry.flashback.record; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.mojang.datafixers.util.Pair; -import com.moulberry.flashback.FlashbackClient; -import com.moulberry.flashback.action.ActionConfigurationPacket; -import com.moulberry.flashback.action.ActionCreateLocalPlayer; -import com.moulberry.flashback.action.ActionGamePacket; -import com.moulberry.flashback.action.ActionMoveEntities; -import com.moulberry.flashback.action.ActionNextTick; -import com.moulberry.flashback.io.ReplayWriter; -import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -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.multiplayer.ClientChunkCache; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.client.multiplayer.MultiPlayerGameMode; -import net.minecraft.client.multiplayer.PlayerInfo; -import net.minecraft.client.player.AbstractClientPlayer; -import net.minecraft.client.player.LocalPlayer; -import net.minecraft.client.resources.server.ServerPackManager; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.RegistrySynchronization; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.Tag; -import net.minecraft.network.ConnectionProtocol; -import net.minecraft.network.RegistryFriendlyByteBuf; -import net.minecraft.network.chat.Component; -import net.minecraft.network.codec.ByteBufCodecs; -import net.minecraft.network.codec.StreamCodec; -import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; -import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; -import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; -import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; -import net.minecraft.network.protocol.configuration.ClientboundRegistryDataPacket; -import net.minecraft.network.protocol.configuration.ClientboundUpdateEnabledFeaturesPacket; -import net.minecraft.network.protocol.configuration.ConfigurationProtocols; -import net.minecraft.network.protocol.game.ClientGamePacketListener; -import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; -import net.minecraft.network.protocol.game.ClientboundAnimatePacket; -import net.minecraft.network.protocol.game.ClientboundBlockDestructionPacket; -import net.minecraft.network.protocol.game.ClientboundBossEventPacket; -import net.minecraft.network.protocol.game.ClientboundBundlePacket; -import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; -import net.minecraft.network.protocol.game.ClientboundLoginPacket; -import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; -import net.minecraft.network.protocol.game.ClientboundRotateHeadPacket; -import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; -import net.minecraft.network.protocol.game.ClientboundSetEntityLinkPacket; -import net.minecraft.network.protocol.game.ClientboundSetEquipmentPacket; -import net.minecraft.network.protocol.game.ClientboundSetPassengersPacket; -import net.minecraft.network.protocol.game.ClientboundSetTimePacket; -import net.minecraft.network.protocol.game.ClientboundTabListPacket; -import net.minecraft.network.protocol.game.ClientboundUpdateAttributesPacket; -import net.minecraft.network.protocol.game.CommonPlayerSpawnInfo; -import net.minecraft.network.protocol.game.GameProtocols; -import net.minecraft.network.syncher.SynchedEntityData; -import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.RegistryLayer; -import net.minecraft.tags.TagNetworkSerialization; -import net.minecraft.util.Mth; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.ai.attributes.AttributeInstance; -import net.minecraft.world.flag.FeatureFlags; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.GameRules; -import net.minecraft.world.level.GameType; -import net.minecraft.world.level.chunk.LevelChunk; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Queue; -import java.util.Set; -import java.util.UUID; -import java.util.WeakHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicReferenceArray; -import java.util.concurrent.locks.ReentrantLock; - -public class Recorder { - - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - private static final int CHUNK_LENGTH_SECONDS = 15; - - private final ReplayWriter writer; - private final StreamCodec> configurationPacketCodec; - private StreamCodec> gamePacketCodec; - - private int writtenTicksInChunk = 0; - private FlashbackMeta metadata = new FlashbackMeta(); - private final UUID recordUUID = UUID.randomUUID(); - private ReentrantLock fileDataLock = new ReentrantLock(); - - private record PacketWithPhase(Packet packet, ConnectionProtocol phase){} - private final Queue pendingPackets = new ConcurrentLinkedQueue<>(); - - private record Position(double x, double y, double z, float yaw, float pitch, float headYRot, boolean onGround) {} - private final WeakHashMap lastPositions = new WeakHashMap<>(); - - // Local player data - private final List lastPlayerEntityMeta = new ArrayList<>(); - private final Map lastPlayerEquipment = new EnumMap<>(EquipmentSlot.class); - private BlockPos lastDestroyPos = null; - private int lastDestroyProgress = -1; - private boolean wasSwinging = false; - private int lastSwingTime = -1; - - public Recorder(RegistryAccess registryAccess) { - this.writer = new ReplayWriter(registryAccess); - this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); - this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); - } - - public void setRegistryAccess(RegistryAccess registryAccess) { - this.writer.setRegistryAccess(registryAccess); - this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); - } - - public void writeInitial() { - this.writeSnapshot(); - } - - public void endTick(boolean forceSaveToDisk) { - this.flushPackets(); - - if (Minecraft.getInstance().level != null && Minecraft.getInstance().getOverlay() == null && !Minecraft.getInstance().isPaused()) { - this.writeEntityPositions(); - this.writeLocalData(); - this.writer.startAndFinishAction(ActionNextTick.INSTANCE); - this.writtenTicksInChunk += 1; - } - - if (this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || forceSaveToDisk) { - this.fileDataLock.lock(); - try { - Path replayRecordFolder = FlashbackClient.getReplayRecordTemp(recordUUID); - Files.createDirectories(replayRecordFolder); - - int chunkCount = this.metadata.chunks.size(); - String chunkName = "c" + chunkCount + ".flashback"; - - Path chunkFile = replayRecordFolder.resolve(chunkName); - Files.write(chunkFile, this.writer.popBytes()); - - Path metaFile = replayRecordFolder.resolve("metadata.json"); - if (Files.exists(metaFile)) { - Files.move(metaFile, replayRecordFolder.resolve("metadata.json.old"), StandardCopyOption.ATOMIC_MOVE, - StandardCopyOption.REPLACE_EXISTING); - } - - var chunkMeta = new FlashbackChunkMeta(); - chunkMeta.duration = this.writtenTicksInChunk; - this.metadata.chunks.put(chunkName, chunkMeta); - Files.writeString(metaFile, GSON.toJson(this.metadata.toJson())); - - this.writtenTicksInChunk = 0; - - if (!forceSaveToDisk) { - this.writeSnapshot(); - } - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - this.fileDataLock.unlock(); - } - } - } - - public void export(Path outputFile) { - this.fileDataLock.lock(); - try { - Path replayRecordFolder = FlashbackClient.getReplayRecordTemp(this.recordUUID); - Exporter.export(replayRecordFolder, outputFile); - } finally { - this.fileDataLock.unlock(); - } - } - - public void writeLocalData() { - LocalPlayer player = Minecraft.getInstance().player; - if (player == null) { - this.lastPlayerEntityMeta.clear(); - this.lastPlayerEquipment.clear(); - this.lastDestroyPos = null; - this.lastDestroyProgress = -1; - return; - } - - // Update entity data - SynchedEntityData.DataItem[] items = Minecraft.getInstance().player.getEntityData().itemsById; - List> changedData = new ArrayList<>(); - for (int i = 0; i < items.length; i++) { - SynchedEntityData.DataItem dataItem = items[i]; - Object value = dataItem.value().value(); - - if (i >= this.lastPlayerEntityMeta.size()) { - this.lastPlayerEntityMeta.add(i, value); - } else { - Object old = this.lastPlayerEntityMeta.get(i); - if (!Objects.equals(old, value)) { - this.lastPlayerEntityMeta.set(i, value); - changedData.add(dataItem.value()); - } - } - } - - if (!changedData.isEmpty()) { - this.writeGamePacket(new ClientboundSetEntityDataPacket(player.getId(), changedData)); - } - - // Update equipment - List> changedSlots = new ArrayList<>(); - for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) { - ItemStack itemStack = player.getItemBySlot(equipmentSlot); - - if (!this.lastPlayerEquipment.containsKey(equipmentSlot)) { - this.lastPlayerEquipment.put(equipmentSlot, itemStack.copy()); - } else if (!ItemStack.matches(this.lastPlayerEquipment.get(equipmentSlot), itemStack)) { - ItemStack copied = itemStack.copy(); - this.lastPlayerEquipment.put(equipmentSlot, copied); - changedSlots.add(Pair.of(equipmentSlot, copied)); - } - } - if (!changedSlots.isEmpty()) { - this.writeGamePacket(new ClientboundSetEquipmentPacket(player.getId(), changedSlots)); - } - - // Update breaking - MultiPlayerGameMode multiPlayerGameMode = Minecraft.getInstance().gameMode; - if (multiPlayerGameMode == null) { - this.lastDestroyPos = null; - this.lastDestroyProgress = -1; - } else { - BlockPos destroyPos = multiPlayerGameMode.destroyBlockPos.immutable(); - int destroyProgress = multiPlayerGameMode.getDestroyStage(); - - boolean changed = destroyProgress != this.lastDestroyProgress; - if (destroyProgress >= 0) { - changed |= !destroyPos.equals(this.lastDestroyPos); - } - - if (changed) { - this.writeGamePacket(new ClientboundBlockDestructionPacket(player.getId(), destroyPos, destroyProgress)); - } - - this.lastDestroyPos = destroyPos; - this.lastDestroyProgress = destroyProgress; - } - - // Update swinging - if (player.swinging && (!this.wasSwinging || this.lastSwingTime > player.swingTime)) { - int animation = player.swingingArm == InteractionHand.MAIN_HAND ? ClientboundAnimatePacket.SWING_MAIN_HAND : ClientboundAnimatePacket.SWING_OFF_HAND; - this.writeGamePacket(new ClientboundAnimatePacket(player, animation)); - } - this.lastSwingTime = player.swingTime; - this.wasSwinging = player.swinging; - - } - - public void writeEntityPositions() { - ClientLevel level = Minecraft.getInstance().level; - if (level == null) { - this.lastPositions.clear(); - return; - } - - this.writer.startAction(ActionMoveEntities.INSTANCE); - RegistryFriendlyByteBuf friendlyByteBuf = this.writer.friendlyByteBuf(); - - friendlyByteBuf.writeVarInt(1); - friendlyByteBuf.writeResourceKey(level.dimension()); - - record IdWithPosition(int id, Position position) {} - List changedPositions = new ArrayList<>(); - - for (Entity entity : level.entitiesForRendering()) { - if (entity.isPassenger()) { - 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(), - entity.getYRot(), entity.getXRot(), entity.getYHeadRot(), entity.onGround()); - } - Position lastPosition = this.lastPositions.get(entity); - - if (!Objects.equals(position, lastPosition)) { - this.lastPositions.put(entity, position); - changedPositions.add(new IdWithPosition(entity.getId(), position)); - } - } - - friendlyByteBuf.writeVarInt(changedPositions.size()); - for (IdWithPosition changedPosition : changedPositions) { - friendlyByteBuf.writeVarInt(changedPosition.id); - friendlyByteBuf.writeDouble(changedPosition.position.x); - friendlyByteBuf.writeDouble(changedPosition.position.y); - friendlyByteBuf.writeDouble(changedPosition.position.z); - friendlyByteBuf.writeFloat(changedPosition.position.yaw); - friendlyByteBuf.writeFloat(changedPosition.position.pitch); - friendlyByteBuf.writeFloat(changedPosition.position.headYRot); - friendlyByteBuf.writeBoolean(changedPosition.position.onGround); - } - - this.writer.finishAction(ActionMoveEntities.INSTANCE); - } - - public void flushPackets() { - PacketWithPhase packet; - while ((packet = this.pendingPackets.poll()) != null) { - if (packet.phase == ConnectionProtocol.PLAY) { - this.writeGamePacket((Packet) packet.packet); - if (packet.packet instanceof ClientboundLoginPacket) { - LocalPlayer localPlayer = Minecraft.getInstance().player; - if (localPlayer == null) { - throw new IllegalStateException("Local player doesn't exist?"); - } - - this.writer.startAction(ActionCreateLocalPlayer.INSTANCE); - RegistryFriendlyByteBuf registryFriendlyByteBuf = this.writer.friendlyByteBuf(); - registryFriendlyByteBuf.writeUUID(localPlayer.getUUID()); - registryFriendlyByteBuf.writeDouble(localPlayer.getX()); - registryFriendlyByteBuf.writeDouble(localPlayer.getY()); - registryFriendlyByteBuf.writeDouble(localPlayer.getZ()); - registryFriendlyByteBuf.writeFloat(localPlayer.getXRot()); - registryFriendlyByteBuf.writeFloat(localPlayer.getYRot()); - registryFriendlyByteBuf.writeFloat(localPlayer.getYHeadRot()); - registryFriendlyByteBuf.writeVec3(localPlayer.getDeltaMovement()); - - ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, localPlayer.getGameProfile()); - - registryFriendlyByteBuf.writeVarInt(Minecraft.getInstance().gameMode.getPlayerMode().getId()); - - this.writer.finishAction(ActionCreateLocalPlayer.INSTANCE); - } - } else if (packet.phase == ConnectionProtocol.CONFIGURATION) { - this.writeConfigurationPacket((Packet) packet.packet); - } else { - throw new IllegalArgumentException("Unsupported phase: " + packet.phase); - } - } - } - - public void writePacketAsync(Packet packet, ConnectionProtocol phase) { - if (packet instanceof ClientboundBundlePacket bundlePacket) { - for (Packet subPacket : bundlePacket.subPackets()) { - this.writePacketAsync(subPacket, phase); - } - return; - } - - if (IgnoredPacketSet.isIgnored(packet)) { - return; - } - - LocalPlayer localPlayer = Minecraft.getInstance().player; - if (localPlayer != null) { - int localPlayerId = localPlayer.getId(); - if (packet instanceof ClientboundSetEntityDataPacket entityDataPacket && entityDataPacket.id() == localPlayerId) { - return; - } - if (packet instanceof ClientboundSetEquipmentPacket entityEquipmentPacket && entityEquipmentPacket.getEntity() == localPlayerId) { - return; - } - } - - this.pendingPackets.add(new PacketWithPhase(packet, phase)); - } - - public void writeGamePacket(Packet packet) { - this.writer.startAction(ActionGamePacket.INSTANCE); - this.gamePacketCodec.encode(this.writer.friendlyByteBuf(), packet); - this.writer.finishAction(ActionGamePacket.INSTANCE); - } - - public void writeConfigurationPacket(Packet packet) { - this.writer.startAction(ActionConfigurationPacket.INSTANCE); - this.configurationPacketCodec.encode(this.writer.friendlyByteBuf(), packet); - this.writer.finishAction(ActionConfigurationPacket.INSTANCE); - } - - public void writeSnapshot() { - this.writer.startSnapshot(); - - ClientLevel level = Minecraft.getInstance().level; - LocalPlayer localPlayer = Minecraft.getInstance().player; - ClientPacketListener connection = Minecraft.getInstance().getConnection(); - MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode; - ClientChunkCache clientChunkCache = level.getChunkSource(); - - AtomicReferenceArray chunks = clientChunkCache.storage.chunks; - - // Configuration data - - // Enabled features - this.writeConfigurationPacket(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(level.enabledFeatures()))); - - // Registry data - RegistryOps dynamicOps = localPlayer.registryAccess().createSerializationContext(NbtOps.INSTANCE); - RegistrySynchronization.packRegistries(dynamicOps, localPlayer.registryAccess(), Set.of(), (resourceKey, list) -> { - this.writeConfigurationPacket(new ClientboundRegistryDataPacket(resourceKey, list)); - }); - - // Tags - Map>, TagNetworkSerialization.NetworkPayload> serializedTags = new HashMap<>(); - RegistryLayer.createRegistryAccess().compositeAccess().registries().forEach(entry -> { - if (entry.value().size() > 0) { - var tags = TagNetworkSerialization.serializeToNetwork(entry.value()); - if (tags.size() > 0) { - serializedTags.put(entry.key(), tags); - } - } - }); - localPlayer.registryAccess().registries().forEach(entry -> { - if (serializedTags.containsKey(entry.key())) { - return; - } - if (RegistrySynchronization.NETWORKABLE_REGISTRIES.contains(entry.key()) && entry.value().size() > 0) { - var tags = TagNetworkSerialization.serializeToNetwork(entry.value()); - if (tags.size() > 0) { - serializedTags.put(entry.key(), tags); - } - } - }); - - this.writeConfigurationPacket(new ClientboundUpdateTagsPacket(serializedTags)); - - // Resource packs - this.writeConfigurationPacket(new ClientboundResourcePackPopPacket(Optional.empty())); - for (ServerPackManager.ServerPackData pack : Minecraft.getInstance().getDownloadedPackSource().manager.packs) { - this.writeConfigurationPacket(new ClientboundResourcePackPushPacket(pack.id, pack.url.toString(), pack.hash == null ? "" : pack.hash.toString(), - true, Optional.empty())); - } - - // Login packet - CommonPlayerSpawnInfo commonPlayerSpawnInfo = new CommonPlayerSpawnInfo(level.dimensionTypeRegistration(), level.dimension(), 0, - gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), false, 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); - this.writeGamePacket(loginPacket); - - // Create player info update packet - var infoUpdatePacket = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, - ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LISTED, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), List.of()); - infoUpdatePacket.entries = new ArrayList<>(level.players().size()); - Set addedEntries = new HashSet<>(); - for (AbstractClientPlayer player : level.players()) { - if (addedEntries.add(player.getUUID())) { - PlayerInfo info = connection.getPlayerInfo(player.getUUID()); - if (info != null) { - infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), - player.getGameProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), null)); - } else { - infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), - player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), null)); - } - } - } - for (PlayerInfo info : connection.getListedOnlinePlayers()) { - if (addedEntries.add(info.getProfile().getId())) { - infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(info.getProfile().getId(), - info.getProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), null)); - } - } - this.writeGamePacket(infoUpdatePacket); - - // Tab list - PlayerTabOverlay playerTabOverlay = Minecraft.getInstance().gui.getTabList(); - this.writeGamePacket(new ClientboundTabListPacket( - playerTabOverlay.header != null ? playerTabOverlay.header : Component.empty(), - playerTabOverlay.footer != null ? playerTabOverlay.footer : Component.empty() - )); - - // Boss bar - BossHealthOverlay bossOverlay = Minecraft.getInstance().gui.getBossOverlay(); - for (LerpingBossEvent event : bossOverlay.events.values()) { - this.writeGamePacket(ClientboundBossEventPacket.createAddPacket(event)); - } - - // Time - this.writeGamePacket(new ClientboundSetTimePacket(level.getGameTime(), level.getDayTime(), level.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); - - // Chunk data - for (int i = 0; i < chunks.length(); i++) { - LevelChunk chunk = chunks.get(i); - if (chunk != null) { - this.writeGamePacket(new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), null, null)); - } - } - - // Entity data - for (Entity entity : level.entitiesForRendering()) { - this.writeGamePacket(new ClientboundAddEntityPacket(entity)); - - List> nonDefaultEntityData = entity.getEntityData().getNonDefaultValues(); - if (nonDefaultEntityData != null && !nonDefaultEntityData.isEmpty()) { - this.writeGamePacket(new ClientboundSetEntityDataPacket(entity.getId(), nonDefaultEntityData)); - } - - if (entity instanceof LivingEntity livingEntity) { - Collection syncableAttributes = livingEntity.getAttributes().getSyncableAttributes(); - if (!syncableAttributes.isEmpty()) { - this.writeGamePacket(new ClientboundUpdateAttributesPacket(entity.getId(), syncableAttributes)); - } - - List> changedSlots = new ArrayList<>(); - for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) { - ItemStack itemStack = livingEntity.getItemBySlot(equipmentSlot); - if (!itemStack.isEmpty()) { - changedSlots.add(Pair.of(equipmentSlot, itemStack.copy())); - } - } - if (!changedSlots.isEmpty()) { - this.writeGamePacket(new ClientboundSetEquipmentPacket(entity.getId(), changedSlots)); - } - } - - if (entity.isVehicle()) { - this.writeGamePacket(new ClientboundSetPassengersPacket(entity)); - } - if (entity.isPassenger()) { - this.writeGamePacket(new ClientboundSetPassengersPacket(entity.getVehicle())); - } - - if (entity instanceof Mob mob && mob.isLeashed()) { - this.writeGamePacket(new ClientboundSetEntityLinkPacket(mob, mob.getLeashHolder())); - } - } - - this.writer.endSnapshot(); - } - -} diff --git a/src/client/java/com/moulberry/flashback/ui/Keybinds.java b/src/client/java/com/moulberry/flashback/ui/Keybinds.java deleted file mode 100644 index c452dfa..0000000 --- a/src/client/java/com/moulberry/flashback/ui/Keybinds.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.moulberry.flashback.ui; - -public class Keybinds { - - - -} diff --git a/src/client/java/com/moulberry/flashback/ui/windows/Timeline.java b/src/client/java/com/moulberry/flashback/ui/windows/Timeline.java deleted file mode 100644 index e005b48..0000000 --- a/src/client/java/com/moulberry/flashback/ui/windows/Timeline.java +++ /dev/null @@ -1,774 +0,0 @@ -package com.moulberry.flashback.ui.windows; - -import com.moulberry.flashback.FlashbackClient; -import com.moulberry.flashback.keyframe.Keyframe; -import com.moulberry.flashback.keyframe.KeyframeType; -import com.moulberry.flashback.keyframe.Keyframes; -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.keyframe.interpolation.InterpolationType; -import com.moulberry.flashback.playback.ReplayServer; -import com.moulberry.flashback.ui.ImGuiHelper; -import imgui.ImDrawList; -import imgui.ImGui; -import imgui.flag.ImGuiMouseButton; -import imgui.flag.ImGuiMouseCursor; -import imgui.flag.ImGuiPopupFlags; -import imgui.flag.ImGuiStyleVar; -import net.minecraft.client.Minecraft; -import org.jetbrains.annotations.Nullable; - -import java.util.Map; -import java.util.TreeMap; - -public class Timeline { - - private static float zoomMin = 0.5f; - private static float zoomMax = 1.0f; - private static float zoomMinBeforeDrag = zoomMin; - private static float zoomMaxBeforeDrag = zoomMax; - private static boolean grabbedZoomBar = false; - private static boolean grabbedZoomBarResizeLeft = false; - private static boolean grabbedZoomBarResizeRight = false; - private static boolean grabbedPlayback = false; - private static boolean grabbedKeyframe = false; - - private static float[] speedKeyframeInput = new float[]{1.0f}; - private static int[] timeOfDayKeyframeInput = new int[]{6000}; - private static float[] fogDistanceKeyframeInput = new float[]{256.0f}; - - private record SelectedKeyframe(KeyframeType type, int keyframeTick, float mouseClickOffset) {} - private static SelectedKeyframe selectedKeyframe = null; - - 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 void render() { - ReplayServer replayServer = FlashbackClient.getReplayServer(); - if (replayServer == null) { - return; - } - - ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); - boolean timelineVisible = ImGui.begin("Timeline"); - ImGuiHelper.popStyleVar(); - - if (timelineVisible) { - ImDrawList drawList = ImGui.getWindowDrawList(); - - float maxX = ImGui.getWindowContentRegionMaxX(); - float maxY = ImGui.getWindowContentRegionMaxY(); - float minX = ImGui.getWindowContentRegionMinX(); - float minY = ImGui.getWindowContentRegionMinY(); - - float x = ImGui.getWindowPosX() + minX; - float y = ImGui.getWindowPosY() + minY; - float width = maxX - minX; - float height = maxY - minY; - - if (width < 1 || height < 1) { - ImGui.end(); - return; - } - - if (selectedKeyframe != null) { - TreeMap> keyframeTimes = Keyframes.keyframes.get(selectedKeyframe.type); - if (keyframeTimes == null) { - selectedKeyframe = null; - } else if (keyframeTimes.get(selectedKeyframe.keyframeTick) == null) { - selectedKeyframe = null; - } - } - - float mouseX = ImGui.getMousePosX(); - float mouseY = ImGui.getMousePosY(); - - int currentReplayTick = replayServer.getReplayTick(); - int totalTicks = Math.max(replayServer.getTotalReplayTicks(), currentReplayTick); - - int middleX = 240; - - float availableWidth = width - middleX; - float shownTicks = Math.round((zoomMax - zoomMin) * totalTicks); - int targetMajorSize = 60; - - float targetTicksPerMajor = 1f / (availableWidth / shownTicks / targetMajorSize); - int minorsPerMajor; - int ticksPerMinor; - boolean showSubSeconds; - - if (targetTicksPerMajor < 5) { - minorsPerMajor = 5; - ticksPerMinor = 1; - showSubSeconds = true; - } else if (targetTicksPerMajor < 8) { - minorsPerMajor = 5; - ticksPerMinor = 2; - showSubSeconds = true; - } else { - minorsPerMajor = 4; - ticksPerMinor = (int) Math.ceil(targetTicksPerMajor / 20 ) * 20 / minorsPerMajor; - showSubSeconds = false; - } - - int majorSnap = ticksPerMinor * minorsPerMajor; - int minTicks = Math.round(zoomMin * totalTicks / majorSnap) * majorSnap; - float minorSeparatorWidth = (availableWidth / shownTicks) * ticksPerMinor; - - float error = zoomMin*totalTicks - minTicks; - int errorOffset = (int)(-error/ticksPerMinor*minorSeparatorWidth); - - float availableTicks = availableWidth / minorSeparatorWidth * ticksPerMinor; - - int cursorTicks = currentReplayTick; - if (grabbedPlayback) { - cursorTicks = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); - } else if (replayServer.jumpToTick >= 0) { - cursorTicks = replayServer.jumpToTick; - } - - int cursorX = middleX + (int)((cursorTicks - minTicks)/availableTicks*(width-middleX)) + errorOffset; - int minorSeparatorHeight = 10; - int majorSeparatorHeight = minorSeparatorHeight * 2; - int timestampHeight = 20; - int middleY = timestampHeight+majorSeparatorHeight; - - renderKeyframeElements(replayServer, x, y + middleY, cursorTicks, middleX); - - float zoomBarWidth = width - (middleX+1); - float zoomBarMin = x+middleX+1 + zoomMin*zoomBarWidth; - float zoomBarMax = x+middleX+1 + zoomMax*zoomBarWidth; - - int zoomBarHeight = 6; - boolean zoomBarExpanded = false; - if (mouseY >= y+height-zoomBarHeight*2 && mouseY <= y+height || grabbedZoomBar) { - zoomBarHeight *= 2; - zoomBarExpanded = true; - } - boolean zoomBarHovered = mouseY >= y+height-zoomBarHeight && mouseY <= y+height && - mouseX >= x+zoomBarMin && mouseX <= x+zoomBarMax; - - drawList.pushClipRect(x+middleX, y, x+width, y+height); - - renderKeyframes(x, y + middleY, mouseX, minTicks, availableTicks, middleX, width, errorOffset); - drawSeparators(minorsPerMajor, x, middleX, minorSeparatorWidth, errorOffset, width, drawList, y, timestampHeight, middleY, minTicks, ticksPerMinor, showSubSeconds, majorSeparatorHeight, minorSeparatorHeight); - drawPlaybackHead(cursorX, x, middleX, width, cursorTicks, currentReplayTick, drawList, y, middleY, timestampHeight, height, zoomBarHeight); - - drawList.popClipRect(); - - // Timeline end line - if (zoomMax >= 1.0) { - drawList.addLine(x+width-2, y+timestampHeight, x+width-2, y+height-zoomBarHeight, -1); - } - // Middle divider (x) - drawList.addLine(x+middleX, y+timestampHeight, x+middleX, y+height, -1); - - // Middle divider (y) - drawList.addLine(0, y+middleY, width, y+middleY, -1); - - // Zoom Bar - if (zoomBarExpanded) { - drawList.addRectFilled(x+middleX+1, y+height-zoomBarHeight, x+width, y+height, 0xFF404040, zoomBarHeight); - } - if (zoomBarHovered || grabbedZoomBar) { - drawList.addRectFilled(x+zoomBarMin+zoomBarHeight/2f, y+height-zoomBarHeight, x+zoomBarMax-zoomBarHeight/2f, y+height, -1, zoomBarHeight); - - // Left/right resize - drawList.addCircleFilled(x+zoomBarMin+zoomBarHeight/2f, y+height-zoomBarHeight/2f, zoomBarHeight/2f, 0xffaaaa00); - drawList.addCircleFilled(x+zoomBarMax-zoomBarHeight/2f, y+height-zoomBarHeight/2f, zoomBarHeight/2f, 0xffaaaa00); - } else { - drawList.addRectFilled(x+zoomBarMin, y+height-zoomBarHeight, x+zoomBarMax, y+height, -1, zoomBarHeight); - } - - // Pause/play button - int controlSize = 24; - int controlsY = (int) y + middleY/2 - controlSize /2; - - // Skip backwards - int skipBackwardsX = (int) x + middleX/6 - controlSize/2; - drawList.addTriangleFilled(skipBackwardsX + controlSize/3, controlsY + controlSize/2, - skipBackwardsX + controlSize, controlsY, - skipBackwardsX + controlSize, controlsY + controlSize, -1); - drawList.addRectFilled(skipBackwardsX, controlsY, - skipBackwardsX + controlSize/3, controlsY+controlSize, -1); - - // Slow down - int slowDownX = (int) x + middleX*2/6 - controlSize/2; - drawList.addTriangleFilled(slowDownX, controlsY + controlSize/2, - slowDownX + controlSize/2, controlsY, - slowDownX + controlSize/2, controlsY+controlSize, -1); - drawList.addTriangleFilled(slowDownX + controlSize/2, controlsY + controlSize/2, - slowDownX + controlSize, controlsY, - slowDownX + controlSize, controlsY + controlSize, -1); - - int pauseX = (int) x + middleX/2 - controlSize /2; - if (replayServer.replayPaused) { - // Play button - drawList.addTriangleFilled(pauseX + controlSize/12, controlsY, - pauseX + controlSize, controlsY + controlSize/2, - pauseX + controlSize/12, controlsY + controlSize, - -1); - } else { - // Pause button - drawList.addRectFilled(pauseX, controlsY, - pauseX + controlSize/3, controlsY + controlSize, -1); - drawList.addRectFilled(pauseX + controlSize*2/3, controlsY, - pauseX + controlSize, controlsY + controlSize, -1); - } - - // Fast-forward - int fastForwardsX = (int) x + middleX*4/6 - controlSize/2; - drawList.addTriangleFilled(fastForwardsX, controlsY, - fastForwardsX + controlSize/2, controlsY + controlSize/2, - fastForwardsX, controlsY+controlSize, -1); - drawList.addTriangleFilled(fastForwardsX + controlSize/2, controlsY, - fastForwardsX + controlSize, controlsY + controlSize/2, - fastForwardsX + controlSize/2, controlsY + controlSize, -1); - - // Skip forward - int skipForwardsX = (int) x + middleX*5/6 - controlSize/2; - drawList.addTriangleFilled(skipForwardsX, controlsY, - skipForwardsX + controlSize*2/3, controlsY + controlSize/2, - skipForwardsX, controlsY + controlSize, -1); - drawList.addRectFilled(skipForwardsX + controlSize*2/3, controlsY, - skipForwardsX + controlSize, controlsY+controlSize, -1); - - - boolean hoveredControls = mouseY > controlsY && mouseY < controlsY + controlSize; - boolean hoveredSkipBackwards = hoveredControls && mouseX >= skipBackwardsX && mouseX <= skipBackwardsX+controlSize; - boolean hoveredSlowDown = hoveredControls && mouseX >= slowDownX && mouseX <= slowDownX+controlSize; - boolean hoveredPause = hoveredControls && mouseX >= pauseX && mouseX <= pauseX+controlSize; - boolean hoveredFastForwards = hoveredControls && mouseX >= fastForwardsX && mouseX <= fastForwardsX+controlSize; - boolean 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"); - } - } else if (hoveredFastForwards) { - ImGuiHelper.drawTooltip("Fast-forwards\n(Current speed: " + (replayServer.desiredTickRate/20f) + "x)"); - } else if (hoveredSkipForwards) { - ImGuiHelper.drawTooltip("Skip forwards"); - } - - renderKeyframeOptionsPopup(); - - boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); - boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); - if ((leftClicked || rightClicked) && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { - releaseGrabbed(mouseX, middleX, errorOffset, width, availableTicks, minTicks, replayServer); - selectedKeyframe = null; - - if (hoveredControls) { - // Skip backwards - if (hoveredSkipBackwards) { - replayServer.goToReplayTick(0); - } - - // Slow down - if (hoveredSlowDown) { - float highest = replayTickSpeeds[0]; - float currentTickRate = replayServer.desiredTickRate; - - for (float replayTickSpeed : replayTickSpeeds) { - if (replayTickSpeed >= currentTickRate) { - break; - } - highest = replayTickSpeed; - } - - replayServer.desiredTickRate = highest; - } - - // Pause button - if (hoveredPause) { - replayServer.replayPaused = !replayServer.replayPaused; - } - - // Fast-forward - if (hoveredFastForwards) { - float lowest = replayTickSpeeds[replayTickSpeeds.length - 1]; - float currentTickRate = replayServer.desiredTickRate; - - for (int i = replayTickSpeeds.length - 1; i >= 0; i--) { - float replayTickSpeed = replayTickSpeeds[i]; - if (replayTickSpeed <= currentTickRate) { - break; - } - lowest = replayTickSpeed; - } - - replayServer.desiredTickRate = lowest; - } - - // Skip forward - if (hoveredSkipForwards) { - replayServer.goToReplayTick(totalTicks); - } - } - - if (mouseY > y && mouseY < y+middleY) { - // Timeline - if (mouseX > x+middleX && mouseX < x+width) { - replayServer.replayPaused = true; - grabbedPlayback = leftClicked; - } - } - - // Tracks - if (mouseY > y+middleY && mouseY < y+height && mouseX > x+middleX && mouseX < x+width) { - float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); - - int trackIndex = (int) Math.max(0, Math.floor((mouseY - (y+middleY+2))/lineHeight)); - for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { - if (trackIndex == 0) { - TreeMap> treeMap = entry.getValue(); - int tick = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); - - Map.Entry> floor = treeMap.floorEntry(tick); - Map.Entry> ceil = treeMap.ceilingEntry(tick); - - float floorDistance = Float.MAX_VALUE; - - if (floor != null) { - float keyframeX = x + middleX + (floor.getKey() - minTicks)/availableTicks*(width-middleX) + errorOffset; - floorDistance = Math.abs(mouseX - keyframeX); - if (floorDistance < KEYFRAME_SIZE) { - selectedKeyframe = new SelectedKeyframe(entry.getKey(), floor.getKey(), mouseX - keyframeX); - grabbedKeyframe = leftClicked; - } - } - - if (ceil != null) { - float keyframeX = x + middleX + (ceil.getKey() - minTicks)/availableTicks*(width-middleX) + errorOffset; - float ceilDistance = Math.abs(mouseX - keyframeX); - if (ceilDistance < floorDistance && ceilDistance < KEYFRAME_SIZE) { - selectedKeyframe = new SelectedKeyframe(entry.getKey(), ceil.getKey(), mouseX - keyframeX); - grabbedKeyframe = leftClicked; - } - } - - break; - } else { - trackIndex -= 1; - } - } - - if (rightClicked && selectedKeyframe != null) { - ImGui.openPopup("##KeyframePopup"); - } - } - - if (zoomBarHovered) { - if (mouseX <= x+zoomBarMin+zoomBarHeight) { - grabbedZoomBarResizeLeft = leftClicked; - } else if (mouseX >= x+zoomBarMax-zoomBarHeight) { - grabbedZoomBarResizeRight = leftClicked; - } - grabbedZoomBar = leftClicked; - zoomMinBeforeDrag = zoomMin; - zoomMaxBeforeDrag = zoomMax; - } else if (zoomBarExpanded && mouseX >= x+middleX && mouseX <= x+width) { - float zoomSize = zoomMax - zoomMin; - float targetZoom = (mouseX - (x+middleX))/(x+width - (x+middleX)); - zoomMin = targetZoom - zoomSize/2f; - zoomMax = targetZoom + zoomSize/2f; - if (zoomMax > 1.0f) { - zoomMax = 1.0f; - zoomMin = zoomMax - zoomSize; - } else if (zoomMin < 0.0f) { - zoomMin = 0.0f; - zoomMax = zoomMin + zoomSize; - } - - grabbedZoomBar = leftClicked; - zoomMinBeforeDrag = zoomMin; - zoomMaxBeforeDrag = zoomMax; - } - } else if (ImGui.isMouseDragging(ImGuiMouseButton.Left)) { - if (zoomBarWidth > 1f && grabbedZoomBar) { - float dx = ImGui.getMouseDragDeltaX(); - float factor = dx / zoomBarWidth; - - if (grabbedZoomBarResizeLeft) { - ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); - zoomMin = Math.max(0, Math.min(zoomMax-0.01f, zoomMinBeforeDrag + factor)); - } else if (grabbedZoomBarResizeRight) { - ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); - zoomMax = Math.max(zoomMin+0.01f, Math.min(1, zoomMaxBeforeDrag + factor)); - } else { - ImGui.setMouseCursor(ImGuiMouseCursor.Hand); - - float zoomSize = zoomMaxBeforeDrag - zoomMinBeforeDrag; - if (factor < 0) { - zoomMin = Math.max(0, zoomMinBeforeDrag + factor); - zoomMax = zoomMin + zoomSize; - } else if (factor > 0) { - zoomMax = Math.min(1, zoomMaxBeforeDrag + factor); - zoomMin = zoomMax - zoomSize; - } - } - } - if (grabbedPlayback) { - int desiredTick = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); - - if (desiredTick > currentReplayTick) { - replayServer.goToReplayTick(desiredTick); - } - - replayServer.replayPaused = true; - } - } else if (!ImGui.isAnyMouseDown()) { - releaseGrabbed(mouseX, middleX, errorOffset, width, availableTicks, minTicks, replayServer); - } - } - ImGui.end(); - } - - private static void renderKeyframeOptionsPopup() { - if (ImGui.beginPopup("##KeyframePopup")) { - if (selectedKeyframe == null) { - ImGui.closeCurrentPopup(); - ImGui.endPopup(); - return; - } - - var keyframeTimes = Keyframes.keyframes.get(selectedKeyframe.type); - if (keyframeTimes == null) { - ImGui.closeCurrentPopup(); - ImGui.endPopup(); - return; - } - - Keyframe keyframe = keyframeTimes.get(selectedKeyframe.keyframeTick); - if (keyframe == null) { - ImGui.closeCurrentPopup(); - ImGui.endPopup(); - return; - } - - int[] type = new int[]{keyframe.interpolationType().ordinal()}; - ImGui.setNextItemWidth(160); - if (ImGuiHelper.combo("Type", type, InterpolationType.NAMES)) { - keyframe.interpolationType(InterpolationType.INTERPOLATION_TYPES[type[0]]); - } - - if (ImGui.button("Remove") && selectedKeyframe != null) { - keyframeTimes.remove(selectedKeyframe.keyframeTick); - selectedKeyframe = null; - } - - ImGui.endPopup(); - } - } - - private static void releaseGrabbed(float mouseX, int middleX, int errorOffset, float width, float availableTicks, int minTicks, ReplayServer replayServer) { - grabbedZoomBar = false; - grabbedZoomBarResizeLeft = false; - grabbedZoomBarResizeRight = false; - - if (grabbedPlayback) { - int desiredTick = calculatePlaybackTarget(mouseX, middleX, errorOffset, width, availableTicks, minTicks); - replayServer.goToReplayTick(desiredTick); - replayServer.replayPaused = true; - grabbedPlayback = false; - } - if (grabbedKeyframe) { - if (selectedKeyframe != null) { - int desiredTick = calculatePlaybackTarget(mouseX - selectedKeyframe.mouseClickOffset, middleX, errorOffset, width, availableTicks, minTicks); - if (desiredTick != selectedKeyframe.keyframeTick) { - var keyframeTimes = Keyframes.keyframes.get(selectedKeyframe.type); - if (keyframeTimes == null) { - selectedKeyframe = null; - } else { - Keyframe keyframe = keyframeTimes.remove(selectedKeyframe.keyframeTick); - if (keyframe == null) { - selectedKeyframe = null; - } else { - Keyframes.keyframes.get(selectedKeyframe.type).put(desiredTick, keyframe); - selectedKeyframe = new SelectedKeyframe(selectedKeyframe.type, desiredTick, 0); - } - } - } - } - grabbedKeyframe = false; - } - } - - - private static void renderKeyframes(float x, float y, float mouseX, int minTicks, float availableTicks, int middleX, float width, int errorOffset) { - float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); - - ImDrawList drawList = ImGui.getWindowDrawList(); - - int index = 0; - for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { - TreeMap> keyframeTimes = entry.getValue(); - - for (int i = minTicks; i <= minTicks + availableTicks; i++) { - Keyframe keyframe = keyframeTimes.get(i); - if (keyframe != null) { - int keyframeX = middleX + (int)((i - minTicks)/availableTicks*(width-middleX)) + errorOffset; - - float midX = x + keyframeX; - float midY = y + 2 + (index+0.5f) * lineHeight; - - if (selectedKeyframe != null && selectedKeyframe.type == entry.getKey() && selectedKeyframe.keyframeTick == i) { - continue; - } - - drawKeyframe(drawList, keyframe.interpolationType(), midX, midY, -1); - } - } - - if (selectedKeyframe != null && selectedKeyframe.type == entry.getKey()) { - Keyframe keyframe = keyframeTimes.get(selectedKeyframe.keyframeTick); - if (keyframe != null) { - int showKeyframeAt = selectedKeyframe.keyframeTick; - if (grabbedKeyframe) { - showKeyframeAt = calculatePlaybackTarget(mouseX - selectedKeyframe.mouseClickOffset, middleX, errorOffset, width, availableTicks, minTicks); - } - int keyframeX = middleX + (int)((showKeyframeAt - minTicks)/availableTicks*(width-middleX)) + errorOffset; - - float midX = x + keyframeX; - float midY = y + 2 + (index+0.5f) * lineHeight; - drawKeyframe(drawList, keyframe.interpolationType(), midX, midY, 0xFF0000FF); - } - } - - index += 1; - } - } - - private static void drawKeyframe(ImDrawList drawList, InterpolationType interpolationType, float x, float y, int colour) { - int easeSize = KEYFRAME_SIZE / 5; - switch (interpolationType) { - case SMOOTH -> { - drawList.addCircleFilled(x, y, KEYFRAME_SIZE, colour); - } - case LINEAR -> { - drawList.addTriangleFilled(x - KEYFRAME_SIZE, y, x, y - KEYFRAME_SIZE, x, y + KEYFRAME_SIZE, colour); - drawList.addTriangleFilled(x + KEYFRAME_SIZE, y, x, y + KEYFRAME_SIZE, x, y - KEYFRAME_SIZE, colour); - } - case EASE_IN -> { - // Left inverted triangle - drawList.addTriangleFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y, colour); - drawList.addTriangleFilled(x - KEYFRAME_SIZE, y + KEYFRAME_SIZE, x - easeSize, y, x - easeSize, y + KEYFRAME_SIZE, colour); - // Right triangle - drawList.addTriangleFilled(x + KEYFRAME_SIZE, y, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y - KEYFRAME_SIZE, colour); - // Center - drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); - } - case EASE_OUT -> { - // Left triangle - drawList.addTriangleFilled(x - KEYFRAME_SIZE, y, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y + KEYFRAME_SIZE, colour); - // Right inverted triangle - drawList.addTriangleFilled(x + KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + easeSize, y, x + easeSize, y - KEYFRAME_SIZE, colour); - drawList.addTriangleFilled(x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y, colour); - // Center - drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); - } - case EASE_IN_OUT -> { - // Left inverted triangle - drawList.addTriangleFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y, colour); - drawList.addTriangleFilled(x - KEYFRAME_SIZE, y + KEYFRAME_SIZE, x - easeSize, y, x - easeSize, y + KEYFRAME_SIZE, colour); - // Right inverted triangle - drawList.addTriangleFilled(x + KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + easeSize, y, x + easeSize, y - KEYFRAME_SIZE, colour); - drawList.addTriangleFilled(x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y, colour); - // Center - drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); - } - case HOLD -> { - drawList.addRectFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, colour); - } - } - } - - private static void renderKeyframeElements(ReplayServer replayServer, float x, float y, int cursorTicks, int middleX) { - ImGui.setCursorScreenPos(x + 8, y + 6); - - KeyframeType keyframeTypeToClear = null; - - ImDrawList drawList = ImGui.getWindowDrawList(); - - float buttonSize = ImGui.getTextLineHeight(); - float spacingX = ImGui.getStyle().getItemSpacingX(); - - for (Map.Entry>> entry : Keyframes.keyframes.entrySet()) { - KeyframeType keyframeType = entry.getKey(); - TreeMap> keyframeTimes = entry.getValue(); - - ImGui.pushID(keyframeType.ordinal()); - - ImGui.setCursorPosX(8); - ImGui.text(keyframeType.name); - - ImGui.sameLine(); - - float addX = middleX - buttonSize - spacingX - buttonSize - spacingX; - float buttonY = ImGui.getCursorScreenPosY(); - ImGui.setCursorPosX(addX); - 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()); - case SPEED -> { - speedKeyframeInput[0] = replayServer.desiredTickRate / 20.0f; - ImGui.openPopup("##EnterSpeed"); - yield null; - } - case TIME_OF_DAY -> { - timeOfDayKeyframeInput[0] = (int)(Minecraft.getInstance().level.getDayTime() % 24000); - ImGui.openPopup("##EnterTime"); - yield null; - } - }; - if (keyframe != null) { - keyframeTimes.put(cursorTicks, keyframe); - } - } - drawList.addRectFilled(addX + 2, buttonY + buttonSize/2 - 1, addX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); - drawList.addRectFilled(addX + buttonSize/2 - 1, buttonY + 2, addX + buttonSize/2 + 1, buttonY + buttonSize - 2, -1); - ImGuiHelper.tooltip("Add keyframe"); - - if (ImGui.beginPopup("##EnterSpeed")) { - ImGui.sliderFloat("Speed", speedKeyframeInput, 0.1f, 10f); - if (ImGui.button("Add")) { - keyframeTimes.put(cursorTicks, new TickrateKeyframe(speedKeyframeInput[0] * 20.0f)); - ImGui.closeCurrentPopup(); - } - ImGui.sameLine(); - if (ImGui.button("Cancel")) { - ImGui.closeCurrentPopup(); - } - ImGui.endPopup(); - } - if (ImGui.beginPopup("##EnterTime")) { - ImGui.sliderInt("Time", timeOfDayKeyframeInput, 0, 24000); - if (ImGui.button("Add")) { - keyframeTimes.put(cursorTicks, new TimeOfDayKeyframe(timeOfDayKeyframeInput[0])); - ImGui.closeCurrentPopup(); - } - ImGui.sameLine(); - if (ImGui.button("Cancel")) { - ImGui.closeCurrentPopup(); - } - ImGui.endPopup(); - } - - ImGui.sameLine(); - - float clearX = middleX - buttonSize - spacingX; - if (ImGui.button("##Clear", buttonSize, buttonSize)) { - keyframeTypeToClear = keyframeType; - } - drawList.addRectFilled(clearX + 2, buttonY + buttonSize/2 - 1, clearX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); - ImGuiHelper.tooltip("Remove all keyframes"); - - ImGui.separator(); - - ImGui.popID(); - } - - if (keyframeTypeToClear != null) { - Keyframes.keyframes.remove(keyframeTypeToClear); - } - - ImGui.setCursorPosX(8); - if (Keyframes.keyframes.size() < KeyframeType.KEYFRAME_TYPES.length && ImGui.smallButton("Add Element")) { - ImGui.openPopup("##AddKeyframeElement"); - } - if (ImGui.beginPopup("##AddKeyframeElement")) { - for (KeyframeType keyframeType : KeyframeType.KEYFRAME_TYPES) { - if (!Keyframes.keyframes.containsKey(keyframeType)) { - if (ImGui.selectable(keyframeType.name)) { - Keyframes.keyframes.put(keyframeType, new TreeMap<>()); - ImGui.closeCurrentPopup(); - } - } - } - ImGui.endPopup(); - } - } - - private static void drawSeparators(int minorsPerMajor, float x, int middleX, float minorSeparatorWidth, int errorOffset, float width, ImDrawList drawList, float y, int timestampHeight, int middleY, int minTicks, int ticksPerMinor, boolean showSubSeconds, int majorSeparatorHeight, int minorSeparatorHeight) { - int minor = -minorsPerMajor; - while (true) { - float h = x + middleX + minorSeparatorWidth *minor; - int hi = (int) (h + errorOffset); - - if (hi >= x + width) { - break; - } - - if (minor % minorsPerMajor == 0) { - drawList.addLine(hi, y + timestampHeight, hi, y + middleY, -1); - - int ticks = minTicks + minor* ticksPerMinor; - String timestamp = ticksToTimestamp(ticks); - drawList.addText(hi, y, -1, timestamp); - if (showSubSeconds) { - float timestampWidth = ImGuiHelper.calcTextWidth(timestamp); - drawList.addText(hi+(int)Math.ceil(timestampWidth), y, 0xFF808080, "/"+(ticks % 20)); - } - } else { - drawList.addLine(hi, y + timestampHeight +(majorSeparatorHeight - minorSeparatorHeight), hi, y + middleY, -1); - } - - minor += 1; - } - } - - private static void drawPlaybackHead(int cursorX, float x, int middleX, float width, int cursorTicks, int currentReplayTick, ImDrawList drawList, float y, int middleY, int timestampHeight, float height, int zoomBarHeight) { - if (cursorX > x + middleX -10 && cursorX < x + width +10) { - int colour = -1; - if (cursorTicks < currentReplayTick) { - colour = 0x80FFFFFF; - } - - drawList.addTriangleFilled(x + cursorX, y + middleY, x + cursorX -10, y + timestampHeight +5, - x + cursorX +10, y + timestampHeight +5, colour); - drawList.addRectFilled(x + cursorX -1, y + middleY -2, x + cursorX +1, y + height - zoomBarHeight, colour); - } - } - - private static int calculatePlaybackTarget(float mouseX, int middleX, int errorOffset, float width, float availableTicks, int minTicks) { - float relativeX = mouseX - middleX - errorOffset; - float amount = Math.max(0, Math.min(1, relativeX/(width - middleX))); - int numTicks = Math.round(amount* availableTicks); - int desiredTick = minTicks + numTicks; - return desiredTick; - } - - private static String ticksToTimestamp(int ticks) { - int seconds = ticks/20; - int minutes = seconds/60; - int hours = minutes/60; - - if (hours == 0) { - return String.format("%02d:%02d", minutes, seconds % 60); - } else { - return String.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60); - } - } - -} diff --git a/src/client/java/com/moulberry/flashback/ui/windows/VisualsWindow.java b/src/client/java/com/moulberry/flashback/ui/windows/VisualsWindow.java deleted file mode 100644 index 816dfc2..0000000 --- a/src/client/java/com/moulberry/flashback/ui/windows/VisualsWindow.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.moulberry.flashback.ui.windows; - -import com.moulberry.flashback.ReplayVisuals; -import imgui.ImGui; - -public class VisualsWindow { - - public static void render() { - if (ImGui.begin("Visuals")) { - if (ImGui.checkbox("Show Boss Bar", ReplayVisuals.showBossBar)) { - ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar; - } - if (ImGui.checkbox("Show Title Text", ReplayVisuals.showTitleText)) { - ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText; - } - if (ImGui.checkbox("Show Scoreboard", ReplayVisuals.showScoreboard)) { - ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard; - } - if (ImGui.checkbox("Show Action Bar", ReplayVisuals.showActionBar)) { - ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar; - } - if (ImGui.checkbox("Show Nametags", ReplayVisuals.showNametags)) { - ReplayVisuals.showNametags = !ReplayVisuals.showNametags; - } - - // Fog distance - boolean overridingFog = ReplayVisuals.overrideFogDistance > 0.0; - if (ImGui.checkbox("Override Fog", overridingFog)) { - if (overridingFog) { - ReplayVisuals.overrideFogDistance = 0.0f; - } else { - ReplayVisuals.overrideFogDistance = 256.0f; - } - } - if (overridingFog) { - float[] fogDistance = new float[]{ReplayVisuals.overrideFogDistance}; - if (ImGui.sliderFloat("Override Fog Distance", fogDistance, 0.0f, 512.0f)) { - ReplayVisuals.overrideFogDistance = fogDistance[0]; - } - } - - } - ImGui.end(); - } -} diff --git a/src/client/resources/flashback.client.mixins.json b/src/client/resources/flashback.client.mixins.json deleted file mode 100644 index e619265..0000000 --- a/src/client/resources/flashback.client.mixins.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "required": true, - "package": "com.moulberry.flashback.mixin.client", - "compatibilityLevel": "JAVA_21", - "client": [ - "MixinLevelRenderer", - "MixinMinecraft", - "MixinMouseHandler", - "MixinRenderTarget", - "MixinWindow", - "packet_fix.MixinBossHealthOverlay", - "playback.MixinArmorStandRenderer", - "playback.MixinClientCommonPacketListenerImpl", - "playback.MixinGameRenderer", - "playback.MixinItemInHandRenderer", - "record.MixinClientConfigurationPacketListenerImpl", - "ui.MixinTitleScreen", - "visuals.MixinClientLevelData", - "visuals.MixinFogRenderer" - ], - "injectors": { - "defaultRequire": 1 - }, - "mixins": [ - "MixinThreadedLevelLightEngine", - "playback.MixinEntity", - "playback.MixinLevelChunkSection", - "playback.MixinLivingEntity", - "playback.MixinPlayerChunkSender", - "playback.MixinTickRateManager", - "playback.hashing.MixinGlobalPalette", - "playback.hashing.MixinHashMapPalette", - "playback.hashing.MixinLinearPalette", - "playback.hashing.MixinSingleValuePalette", - "record.MixinConnection", - "replay_server.MixinChunkGenerators", - "replay_server.MixinChunkStatusTasks", - "replay_server.MixinPersistentEntitySectionManager", - "replay_server.MixinPlayerList", - "replay_server.MixinServerChunkCache", - "replay_server.MixinServerConfigurationPacketListenerImpl", - "replay_server.MixinServerEntity", - "replay_server.MixinServerGamePacketListenerImpl", - "replay_server.MixinServerLoginPacketListenerImpl", - "replay_server.MixinTickRateManager" - ] -} diff --git a/src/main/java/com/moulberry/flashback/CachedChunkPacket.java b/src/main/java/com/moulberry/flashback/CachedChunkPacket.java new file mode 100644 index 0000000..37a3260 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/CachedChunkPacket.java @@ -0,0 +1,179 @@ +package com.moulberry.flashback; + +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData; +import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; +import net.minecraft.network.protocol.game.ClientboundLightUpdatePacketData; +import net.minecraft.world.level.block.entity.BlockEntityType; + +import java.util.Arrays; +import java.util.Objects; + +public class CachedChunkPacket { + + private final ClientboundLevelChunkWithLightPacket packet; + private boolean calculatedHashCode = false; + private int hashCode = 0; + public int index; + + public CachedChunkPacket(ClientboundLevelChunkWithLightPacket packet, int index) { + this.packet = packet; + this.index = index; + } + + @Override + public int hashCode() { + if (!this.calculatedHashCode) { + this.hashCode = this.calculateHashCode(); + this.calculatedHashCode = true; + } + return this.hashCode; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof CachedChunkPacket that)) return false; + if (this.hashCode() != that.hashCode()) { + return false; + } + + ClientboundLevelChunkPacketData thisChunkData = this.packet.getChunkData(); + ClientboundLightUpdatePacketData thisLightData = this.packet.getLightData(); + ClientboundLevelChunkPacketData thatChunkData = that.packet.getChunkData(); + ClientboundLightUpdatePacketData thatLightData = that.packet.getLightData(); + + if (this.packet.getX() != that.packet.getX()) { + return false; + } + if (this.packet.getZ() != that.packet.getZ()) { + return false; + } + + if (!thisChunkData.getHeightmaps().equals(thatChunkData.getHeightmaps())) { + return false; + } + if (!thisLightData.getSkyYMask().equals(thatLightData.getSkyYMask())) { + return false; + } + if (!thisLightData.getBlockYMask().equals(thatLightData.getBlockYMask())) { + return false; + } + if (!thisLightData.getEmptySkyYMask().equals(thatLightData.getEmptySkyYMask())) { + return false; + } + if (!thisLightData.getEmptyBlockYMask().equals(thatLightData.getEmptyBlockYMask())) { + return false; + } + + if (thisLightData.getSkyUpdates().size() != thatLightData.getSkyUpdates().size()) { + return false; + } + if (thisLightData.getBlockUpdates().size() != thatLightData.getBlockUpdates().size()) { + return false; + } + + int skySize = thisLightData.getSkyUpdates().size(); + for (int i = 0; i < skySize; i++) { + byte[] thisSkyLight = thisLightData.getSkyUpdates().get(i); + byte[] thatSkyLight = thatLightData.getSkyUpdates().get(i); + if (!Arrays.equals(thisSkyLight, thatSkyLight)) { + return false; + } + } + + int blockSize = thisLightData.getBlockUpdates().size(); + for (int i = 0; i < blockSize; i++) { + byte[] thisBlockLight = thisLightData.getBlockUpdates().get(i); + byte[] thatBlockLight = thatLightData.getBlockUpdates().get(i); + if (!Arrays.equals(thisBlockLight, thatBlockLight)) { + return false; + } + } + + Long2ObjectOpenHashMap thisBlockEntityMap = new Long2ObjectOpenHashMap<>(); + + if (thisChunkData.blockEntitiesData.size() != thatChunkData.blockEntitiesData.size()) { + return false; + } + + for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesDatum : thisChunkData.blockEntitiesData) { + long key = ((long)blockEntitiesDatum.y) << 32 | blockEntitiesDatum.packedXZ; + thisBlockEntityMap.put(key, blockEntitiesDatum.tag); + } + for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesDatum : thatChunkData.blockEntitiesData) { + long key = ((long)blockEntitiesDatum.y) << 32 | blockEntitiesDatum.packedXZ; + + if (!thisBlockEntityMap.containsKey(key)) { + return false; + } + + CompoundTag thisBlockEntity = thisBlockEntityMap.get(key); + if (!Objects.equals(thisBlockEntity, blockEntitiesDatum.tag)) { + return false; + } + } + + return Arrays.equals(thisChunkData.buffer, thatChunkData.buffer); + } + + private int calculateHashCode() { + ClientboundLevelChunkPacketData chunkData = this.packet.getChunkData(); + ClientboundLightUpdatePacketData lightData = this.packet.getLightData(); + + int hashCode = 1; + hashCode = hashCode*31 + this.packet.getX(); + hashCode = hashCode*31 + this.packet.getZ(); + + hashCode = hashCode*31 + chunkData.getHeightmaps().hashCode(); + + hashCode = hashCode*31 + lightData.getSkyYMask().hashCode(); + hashCode = hashCode*31 + lightData.getBlockYMask().hashCode(); + hashCode = hashCode*31 + lightData.getEmptySkyYMask().hashCode(); + hashCode = hashCode*31 + lightData.getEmptyBlockYMask().hashCode(); + + for (byte[] skyUpdate : lightData.getSkyUpdates()) { + hashCode = hashCode*31 + fixedSizeHashForLightArray(skyUpdate); + } + for (byte[] blockUpdate : lightData.getBlockUpdates()) { + hashCode = hashCode*31 + fixedSizeHashForLightArray(blockUpdate); + } + + for (ClientboundLevelChunkPacketData.BlockEntityInfo blockEntitiesDatum : chunkData.blockEntitiesData) { + hashCode = hashCode*31 + blockEntitiesDatum.packedXZ; + hashCode = hashCode*31 + blockEntitiesDatum.y; + hashCode = hashCode*31 + BlockEntityType.getKey(blockEntitiesDatum.type).hashCode(); + hashCode = hashCode*31 + (blockEntitiesDatum.tag == null ? 0 : blockEntitiesDatum.tag.hashCode()); + } + + hashCode = hashCode*31 + chunkData.getReadBuffer().hashCode(); + + return hashCode; + } + + private static final int[] fixedSizeHashCoefficients = new int[2048]; + static { + int coefficient = 1; + for (int i = fixedSizeHashCoefficients.length - 1; i >= 0; i--) { + fixedSizeHashCoefficients[i] = coefficient; + coefficient *= 31; + } + } + + private static int fixedSizeHashForLightArray(byte[] array) { + if (array.length != 2048) { + throw new IllegalArgumentException("Array must be of length 2048"); + } + + int hash = 0; + for (int i = 0; i < array.length; i += 4) { + hash += fixedSizeHashCoefficients[i] * array[i] + + fixedSizeHashCoefficients[i+1] * array[i+1] + + fixedSizeHashCoefficients[i+2] * array[i+2] + + fixedSizeHashCoefficients[i+3] * array[i+3]; + } + return hash; + } + +} diff --git a/src/main/java/com/moulberry/flashback/FixedDeltaTracker.java b/src/main/java/com/moulberry/flashback/FixedDeltaTracker.java new file mode 100644 index 0000000..2086be9 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/FixedDeltaTracker.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback; + +import net.minecraft.client.DeltaTracker; + +public class FixedDeltaTracker implements DeltaTracker { + private final float deltaTick; + private final float partialTick; + + public FixedDeltaTracker(float deltaTick, float partialTick) { + this.deltaTick = deltaTick; + this.partialTick = partialTick; + } + + public float getGameTimeDeltaTicks() { + return this.deltaTick; + } + + public float getGameTimeDeltaPartialTick(boolean bl) { + return this.partialTick; + } + + public float getRealtimeDeltaTicks() { + return this.deltaTick; + } +} \ No newline at end of file diff --git a/src/client/java/com/moulberry/flashback/FlashbackClient.java b/src/main/java/com/moulberry/flashback/Flashback.java similarity index 56% rename from src/client/java/com/moulberry/flashback/FlashbackClient.java rename to src/main/java/com/moulberry/flashback/Flashback.java index 469d3ef..dfb21a0 100644 --- a/src/client/java/com/moulberry/flashback/FlashbackClient.java +++ b/src/main/java/com/moulberry/flashback/Flashback.java @@ -2,28 +2,30 @@ package com.moulberry.flashback; import com.mojang.brigadier.context.CommandContext; import com.mojang.serialization.Lifecycle; -import com.moulberry.flashback.action.ActionConfigurationPacket; -import com.moulberry.flashback.action.ActionCreateLocalPlayer; -import com.moulberry.flashback.action.ActionGamePacket; -import com.moulberry.flashback.action.ActionMoveEntities; -import com.moulberry.flashback.action.ActionNextTick; -import com.moulberry.flashback.action.ActionRegistry; +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.FinishedServerTick; import com.moulberry.flashback.playback.EmptyLevelSource; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.record.Recorder; 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.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.player.AbstractClientPlayer; import net.minecraft.commands.Commands; import net.minecraft.core.*; import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.*; import net.minecraft.server.packs.repository.PackRepository; @@ -45,34 +47,64 @@ import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; +import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.UUID; -public class FlashbackClient implements ClientModInitializer { +public class Flashback implements ModInitializer, ClientModInitializer { public static final Logger LOGGER = LoggerFactory.getLogger("flashback"); public static final int MAGIC = 0xD780E884; public static Recorder RECORDER = null; public static ExportJob EXPORT_JOB = null; + private static Path configDirectory = null; public static ResourceLocation createResourceLocation(String value) { - return new ResourceLocation("flashback", value); + return ResourceLocation.fromNamespaceAndPath("flashback", value); } - @Override + public static Path getConfigDirectory() { + if (configDirectory == null) { + configDirectory = FabricLoader.getInstance().getConfigDir().resolve("flashback"); + try { + Files.createDirectories(configDirectory); + } catch (Exception e) { + LOGGER.error("Unable to create directories for config folder", e); + } + } + return configDirectory; + } + + @Override + public void onInitialize() { + net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry.playS2C().register(FinishedServerTick.TYPE, + StreamCodec.unit(FinishedServerTick.INSTANCE)); + } + + @Override public void onInitializeClient() { + // todo: try recover unfinished recordings + + TempFolderProvider.tryDeleteStaleFolders(); + try { + FileUtils.deleteDirectory(Path.of("replay_export_temp").toFile()); + } catch (Exception ignored) {} + ActionRegistry.register(ActionNextTick.INSTANCE); ActionRegistry.register(ActionGamePacket.INSTANCE); ActionRegistry.register(ActionConfigurationPacket.INSTANCE); ActionRegistry.register(ActionCreateLocalPlayer.INSTANCE); ActionRegistry.register(ActionMoveEntities.INSTANCE); + ActionRegistry.register(ActionLevelChunkCached.INSTANCE); ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { var flashback = ClientCommandManager.literal("flashback"); - flashback.then(ClientCommandManager.literal("start").executes(this::startReplay)); - flashback.then(ClientCommandManager.literal("end").executes(this::endReplay)); + flashback.then(ClientCommandManager.literal("start").executes(this::startRecordingReplay)); + flashback.then(ClientCommandManager.literal("end").executes(this::finishRecordingReplay)); dispatcher.register(flashback); }); } @@ -89,19 +121,86 @@ public class FlashbackClient implements ClientModInitializer { return Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer; } - private int startReplay(CommandContext command) { - Recorder recorder = new Recorder(Minecraft.getInstance().player.registryAccess()); - recorder.writeInitial(); - RECORDER = recorder; + private int startRecordingReplay(CommandContext command) { + startRecordingReplay(); return 0; } - private int endReplay(CommandContext command) { + private int finishRecordingReplay(CommandContext command) { + finishRecordingReplay(); + return 0; + } + + public static void startRecordingReplay() { + if (RECORDER != null) { + SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, + Component.literal("Already Recording"), Component.literal("Cannot start new recording when already recording")); + return; + } + RECORDER = new Recorder(Minecraft.getInstance().player.registryAccess()); + if (FlashbackConfig.showRecordingToasts) { + SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, + Component.literal("Started Recording"), Component.literal("Started recording")); + } + } + + public static void pauseRecordingReplay(boolean pause) { + RECORDER.setPaused(pause); + + if (FlashbackConfig.showRecordingToasts) { + SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, + Component.literal("Paused Recording"), Component.literal("Paused recording")); + } + } + + public static void cancelRecordingReplay() { + Recorder recorder = RECORDER; + RECORDER = null; + recorder.finish(null); + + if (FlashbackConfig.showRecordingToasts) { + SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, + Component.literal("Cancelled Recording"), Component.literal("Cancelled recording")); + } + } + + public static void finishRecordingReplay() { + if (RECORDER == null) { + SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, + Component.literal("Not Recording"), Component.literal("Cannot finish recording when not recording")); + return; + } + Recorder recorder = RECORDER; RECORDER = null; recorder.endTick(true); - recorder.export(FabricLoader.getInstance().getGameDir().resolve("debug_recording.zip")); - return 0; + + Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback"); + Path replayDir = flashbackDir.resolve("replays"); + + try { + Files.createDirectories(replayDir); + } catch (IOException e) { + Flashback.LOGGER.error("Error while trying to create replay directory", e); + } + + 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) { + SystemToast.add(Minecraft.getInstance().getToasts(), FlashbackSystemToasts.RECORDING_TOAST, + Component.literal("Finished Recording"), Component.literal(name)); + } } @Nullable @@ -117,26 +216,10 @@ public class FlashbackClient implements ClientModInitializer { return null; } - // todo: delete on start - public static Path getReplayServerTemp() { - return FabricLoader.getInstance().getGameDir().resolve("replay_server_temp"); - } - - // todo: export any partial recordings + delete on start - public static Path getReplayRecordTemp(UUID uuid) { - return FabricLoader.getInstance().getGameDir().resolve("replay_record_temp") - .resolve(uuid.toString()); - } - - // todo: delete on start - public static Path getReplayPlaybackTemp(UUID uuid) { - return FabricLoader.getInstance().getGameDir().resolve("replay_playback_temp") - .resolve(uuid.toString()); - } - - public static void testReplayWorld() { + public static void openReplayWorld(Path path) { try { - Path replayTemp = getReplayServerTemp(); + UUID replayUuid = UUID.randomUUID(); + Path replayTemp = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.SERVER, replayUuid); FileUtils.deleteDirectory(replayTemp.toFile()); LevelStorageSource source = new LevelStorageSource(replayTemp.resolve("saves"), replayTemp.resolve("backups"), @@ -169,7 +252,7 @@ public class FlashbackClient implements ClientModInitializer { complete.specialWorldProperty(), complete.lifecycle()), complete.dimensionsRegistryAccess()); }, WorldStem::new, Util.backgroundExecutor(), executor)).get(); - ((MinecraftExt)Minecraft.getInstance()).flashback$startReplayServer(access, packRepository, worldStem); + ((MinecraftExt)Minecraft.getInstance()).flashback$startReplayServer(access, packRepository, worldStem, replayUuid, path); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/src/main/java/com/moulberry/flashback/FlashbackGson.java b/src/main/java/com/moulberry/flashback/FlashbackGson.java new file mode 100644 index 0000000..6346ac5 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/FlashbackGson.java @@ -0,0 +1,31 @@ +package com.moulberry.flashback; + +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.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 org.joml.Quaternionf; +import org.joml.Vector3f; + +public class FlashbackGson { + + public static Gson PRETTY = build().setPrettyPrinting().create(); + public static Gson COMPRESSED = build().create(); + + 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()); + } + +} diff --git a/src/main/java/com/moulberry/flashback/FlashbackModMenuApiImpl.java b/src/main/java/com/moulberry/flashback/FlashbackModMenuApiImpl.java new file mode 100644 index 0000000..8a4f51e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/FlashbackModMenuApiImpl.java @@ -0,0 +1,13 @@ +package com.moulberry.flashback; + +import com.moulberry.flashback.screen.ConfigScreen; +import com.terraformersmc.modmenu.api.ConfigScreenFactory; +import com.terraformersmc.modmenu.api.ModMenuApi; + +public class FlashbackModMenuApiImpl implements ModMenuApi { + + @Override + public ConfigScreenFactory getModConfigScreenFactory() { + return ConfigScreen::new; + } +} diff --git a/src/main/java/com/moulberry/flashback/FlashbackSystemToasts.java b/src/main/java/com/moulberry/flashback/FlashbackSystemToasts.java new file mode 100644 index 0000000..29d7147 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/FlashbackSystemToasts.java @@ -0,0 +1,9 @@ +package com.moulberry.flashback; + +import net.minecraft.client.gui.components.toasts.SystemToast; + +public class FlashbackSystemToasts { + + public static final SystemToast.SystemToastId RECORDING_TOAST = new SystemToast.SystemToastId(); + +} diff --git a/src/client/java/com/moulberry/flashback/Interpolation.java b/src/main/java/com/moulberry/flashback/Interpolation.java similarity index 100% rename from src/client/java/com/moulberry/flashback/Interpolation.java rename to src/main/java/com/moulberry/flashback/Interpolation.java diff --git a/src/main/java/com/moulberry/flashback/PacketHelper.java b/src/main/java/com/moulberry/flashback/PacketHelper.java new file mode 100644 index 0000000..bb05451 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/PacketHelper.java @@ -0,0 +1,17 @@ +package com.moulberry.flashback; + +import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; +import net.minecraft.world.entity.Entity; + +public class PacketHelper { + + public static ClientboundAddEntityPacket createAddEntity(Entity entity) { + return createAddEntity(entity, 0); + } + + public static ClientboundAddEntityPacket createAddEntity(Entity entity, int data) { + return new ClientboundAddEntityPacket(entity.getId(), entity.getUUID(), entity.getX(), entity.getY(), entity.getZ(), + entity.getXRot(), entity.getYRot(), entity.getType(), data, entity.getDeltaMovement(), entity.getYHeadRot()); + } + +} diff --git a/src/main/java/com/moulberry/flashback/ReplayVisuals.java b/src/main/java/com/moulberry/flashback/ReplayVisuals.java new file mode 100644 index 0000000..ae514bf --- /dev/null +++ b/src/main/java/com/moulberry/flashback/ReplayVisuals.java @@ -0,0 +1,79 @@ +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/SneakyThrow.java b/src/main/java/com/moulberry/flashback/SneakyThrow.java new file mode 100644 index 0000000..f40cb81 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/SneakyThrow.java @@ -0,0 +1,10 @@ +package com.moulberry.flashback; + +public class SneakyThrow { + + @SuppressWarnings("unchecked") + public static RuntimeException sneakyThrow(Throwable e) throws E { + throw (E) e; + } + +} diff --git a/src/main/java/com/moulberry/flashback/TempFolderProvider.java b/src/main/java/com/moulberry/flashback/TempFolderProvider.java new file mode 100644 index 0000000..bb52875 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/TempFolderProvider.java @@ -0,0 +1,152 @@ +package com.moulberry.flashback; + +import net.fabricmc.loader.api.FabricLoader; +import org.apache.commons.io.FileUtils; + +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +public class TempFolderProvider { + + public enum TempFolderType { + SERVER("server"), + RECORDING("recording"), + PLAYBACK("playback"); + + private final String id; + + TempFolderType(String id) { + this.id = id; + } + } + + private static Path getSharedTempFolder() { + return FabricLoader.getInstance().getGameDir() + .resolve("flashback") + .resolve("temp"); + } + + public static void tryDeleteStaleFolders() { + Path tempFolder = getSharedTempFolder(); + + if (!Files.exists(tempFolder)) { + return; + } + + for (TempFolderType type : TempFolderType.values()) { + // todo: special handling for recordings + + Path typedTempFolder = tempFolder.resolve(type.id); + + if (!Files.exists(typedTempFolder)) { + continue; + } + + Set toDelete = new HashSet<>(); + + try (DirectoryStream directoryStream = Files.newDirectoryStream(typedTempFolder)) { + for (Path path : directoryStream) { + if (!Files.isDirectory(path)) { + continue; + } + + Path lockFile = path.resolve("flashback_pid"); + + String pidStr = "?"; + boolean isStillInUse = false; + try { + pidStr = Files.readString(lockFile); + long pid = Long.parseLong(pidStr); + isStillInUse = ProcessHandle.of(pid).isPresent(); + } catch (Exception ignored) {} + + if (!isStillInUse) { + toDelete.add(path); + } else { + Flashback.LOGGER.error("Cannot delete stale temp folder {}, pid {} is still in use", tempFolder.relativize(path), pidStr); + } + } + } catch (IOException e) { + Flashback.LOGGER.error("Failed to find stale temp folders to delete", e); + } + + for (Path path : toDelete) { + Flashback.LOGGER.info("Deleting stale temp folder {}", tempFolder.relativize(path)); + try { + FileUtils.deleteDirectory(path.toFile()); + } catch (Exception e) { + Flashback.LOGGER.error("Failed to delete stale temp folder", e); + } + } + + deleteDirectoryIfEmpty(typedTempFolder); + } + + deleteDirectoryIfEmpty(tempFolder); + } + + public static Path createTemp(TempFolderType type, UUID uuid) { + Path path = getTempPath(type, uuid); + + if (!Files.exists(path)) { + // Create directories + try { + Files.createDirectories(path); + } catch (IOException e) { + throw new RuntimeException(e); + } + + // Write pid file + long pid = ProcessHandle.current().pid(); + try { + Files.writeString(path.resolve("flashback_pid"), String.valueOf(pid)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + return path; + } + + private static Path getTempPath(TempFolderType type, UUID uuid) { + return getSharedTempFolder() + .resolve(type.id) + .resolve(uuid.toString()); + } + + public static void deleteTemp(TempFolderType type, UUID uuid) { + Path path = getTempPath(type, uuid); + + // Delete directory + try { + FileUtils.deleteDirectory(path.toFile()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + deleteDirectoryIfEmpty(path.getParent()); + deleteDirectoryIfEmpty(path.getParent().getParent()); + } + + public static void deleteDirectoryIfEmpty(Path path) { + if (!Files.exists(path)) { + return; + } + + try { + boolean empty; + try (var stream = Files.newDirectoryStream(path)) { + empty = !stream.iterator().hasNext(); + } + if (empty) { + Files.deleteIfExists(path); + } + } catch (IOException ignored) {} + } + +} diff --git a/src/main/java/com/moulberry/flashback/Utils.java b/src/main/java/com/moulberry/flashback/Utils.java new file mode 100644 index 0000000..814628e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/Utils.java @@ -0,0 +1,60 @@ +package com.moulberry.flashback; + +import it.unimi.dsi.fastutil.objects.Object2FloatFunction; +import org.jetbrains.annotations.Nullable; + +public class Utils { + + /* + * I love Utils.java, very cool, thank you + */ + + public enum ClosestElement { + LEFT, + RIGHT, + NONE + } + + public static T chooseClosest(float position, float leftPosition, T left, float rightPosition, T right, float threshold) { + if (left == null) { + if (Math.abs(rightPosition - position) <= threshold) { + return right; + } else { + return null; + } + } + if (right == null) { + if (Math.abs(leftPosition - position) <= threshold) { + return left; + } else { + return null; + } + } + + return switch (findClosest(position, leftPosition, rightPosition, threshold)) { + case LEFT -> left; + case RIGHT -> right; + case NONE -> null; + }; + } + + public static Utils.ClosestElement findClosest(float position, float leftPosition, float rightPosition, float threshold) { + boolean leftValid = Math.abs(leftPosition - position) <= threshold; + boolean rightValid = Math.abs(rightPosition - position) <= threshold; + + if (leftValid && rightValid) { + if (position <= leftPosition) { + return ClosestElement.LEFT; + } else { + return ClosestElement.RIGHT; + } + } else if (leftValid) { + return ClosestElement.LEFT; + } else if (rightValid) { + return ClosestElement.RIGHT; + } else { + return ClosestElement.NONE; + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/Action.java b/src/main/java/com/moulberry/flashback/action/Action.java similarity index 100% rename from src/client/java/com/moulberry/flashback/action/Action.java rename to src/main/java/com/moulberry/flashback/action/Action.java diff --git a/src/client/java/com/moulberry/flashback/action/ActionConfigurationPacket.java b/src/main/java/com/moulberry/flashback/action/ActionConfigurationPacket.java similarity index 79% rename from src/client/java/com/moulberry/flashback/action/ActionConfigurationPacket.java rename to src/main/java/com/moulberry/flashback/action/ActionConfigurationPacket.java index cdf1ab0..572cdda 100644 --- a/src/client/java/com/moulberry/flashback/action/ActionConfigurationPacket.java +++ b/src/main/java/com/moulberry/flashback/action/ActionConfigurationPacket.java @@ -1,13 +1,13 @@ package com.moulberry.flashback.action; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; public class ActionConfigurationPacket implements Action { - private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/configuration_packet"); + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/configuration_packet"); public static final ActionConfigurationPacket INSTANCE = new ActionConfigurationPacket(); private ActionConfigurationPacket() { } diff --git a/src/client/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java b/src/main/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java similarity index 79% rename from src/client/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java rename to src/main/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java index 01279c1..10e43f1 100644 --- a/src/client/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java +++ b/src/main/java/com/moulberry/flashback/action/ActionCreateLocalPlayer.java @@ -1,13 +1,13 @@ package com.moulberry.flashback.action; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; public class ActionCreateLocalPlayer implements Action { - private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/create_local_player"); + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/create_local_player"); public static final ActionCreateLocalPlayer INSTANCE = new ActionCreateLocalPlayer(); private ActionCreateLocalPlayer() { } diff --git a/src/client/java/com/moulberry/flashback/action/ActionGamePacket.java b/src/main/java/com/moulberry/flashback/action/ActionGamePacket.java similarity index 79% rename from src/client/java/com/moulberry/flashback/action/ActionGamePacket.java rename to src/main/java/com/moulberry/flashback/action/ActionGamePacket.java index 3ec7cdf..a7c36c5 100644 --- a/src/client/java/com/moulberry/flashback/action/ActionGamePacket.java +++ b/src/main/java/com/moulberry/flashback/action/ActionGamePacket.java @@ -1,13 +1,13 @@ package com.moulberry.flashback.action; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; public class ActionGamePacket implements Action { - private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/game_packet"); + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/game_packet"); public static final ActionGamePacket INSTANCE = new ActionGamePacket(); private ActionGamePacket() { } diff --git a/src/main/java/com/moulberry/flashback/action/ActionLevelChunkCached.java b/src/main/java/com/moulberry/flashback/action/ActionLevelChunkCached.java new file mode 100644 index 0000000..31abaac --- /dev/null +++ b/src/main/java/com/moulberry/flashback/action/ActionLevelChunkCached.java @@ -0,0 +1,25 @@ +package com.moulberry.flashback.action; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; + +public class ActionLevelChunkCached implements Action { + + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/level_chunk_cached"); + public static final ActionLevelChunkCached INSTANCE = new ActionLevelChunkCached(); + private ActionLevelChunkCached() { + } + + @Override + public ResourceLocation name() { + return NAME; + } + + @Override + public void handle(ReplayServer replayServer, RegistryFriendlyByteBuf friendlyByteBuf) { + replayServer.handleLevelChunkCached(friendlyByteBuf.readVarInt()); + } + +} diff --git a/src/client/java/com/moulberry/flashback/action/ActionMoveEntities.java b/src/main/java/com/moulberry/flashback/action/ActionMoveEntities.java similarity index 79% rename from src/client/java/com/moulberry/flashback/action/ActionMoveEntities.java rename to src/main/java/com/moulberry/flashback/action/ActionMoveEntities.java index 65e7ef8..5cf834b 100644 --- a/src/client/java/com/moulberry/flashback/action/ActionMoveEntities.java +++ b/src/main/java/com/moulberry/flashback/action/ActionMoveEntities.java @@ -1,13 +1,13 @@ package com.moulberry.flashback.action; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; public class ActionMoveEntities implements Action { - private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/move_entities"); + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/move_entities"); public static final ActionMoveEntities INSTANCE = new ActionMoveEntities(); private ActionMoveEntities() { } diff --git a/src/client/java/com/moulberry/flashback/action/ActionNextTick.java b/src/main/java/com/moulberry/flashback/action/ActionNextTick.java similarity index 79% rename from src/client/java/com/moulberry/flashback/action/ActionNextTick.java rename to src/main/java/com/moulberry/flashback/action/ActionNextTick.java index f269bba..40dc585 100644 --- a/src/client/java/com/moulberry/flashback/action/ActionNextTick.java +++ b/src/main/java/com/moulberry/flashback/action/ActionNextTick.java @@ -1,13 +1,13 @@ package com.moulberry.flashback.action; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.resources.ResourceLocation; public class ActionNextTick implements Action { - private static final ResourceLocation NAME = FlashbackClient.createResourceLocation("action/next_tick"); + private static final ResourceLocation NAME = Flashback.createResourceLocation("action/next_tick"); public static final ActionNextTick INSTANCE = new ActionNextTick(); private ActionNextTick() { } diff --git a/src/client/java/com/moulberry/flashback/action/ActionRegistry.java b/src/main/java/com/moulberry/flashback/action/ActionRegistry.java similarity index 100% rename from src/client/java/com/moulberry/flashback/action/ActionRegistry.java rename to src/main/java/com/moulberry/flashback/action/ActionRegistry.java diff --git a/src/main/java/com/moulberry/flashback/combo_options/AspectRatio.java b/src/main/java/com/moulberry/flashback/combo_options/AspectRatio.java new file mode 100644 index 0000000..617b7ee --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/AspectRatio.java @@ -0,0 +1,28 @@ +package com.moulberry.flashback.combo_options; + +public enum AspectRatio implements ComboOption { + + ASPECT_16_9("16:9 (HDTV)", 16/9f), + ASPECT_9_16("9:16 (Shorts)", 9/16f), + ASPECT_240_1("2.40:1 (Widescreen)", 2.4f), + ASPECT_1_1("1:1 (Square)", 1f), + ASPECT_4_3("4:3 (Fullscreen)", 4/3f), + ASPECT_3_2("3:2 (Photo)", 3/2f); + + private final String text; + private final float aspectRatio; + + AspectRatio(String text, float aspectRatio) { + this.text = text; + this.aspectRatio = aspectRatio; + } + + @Override + public String text() { + return this.text; + } + + public float aspectRatio() { + return aspectRatio; + } +} diff --git a/src/main/java/com/moulberry/flashback/combo_options/ComboOption.java b/src/main/java/com/moulberry/flashback/combo_options/ComboOption.java new file mode 100644 index 0000000..45a09c4 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/ComboOption.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.combo_options; + +public interface ComboOption { + + String text(); + +} \ No newline at end of file diff --git a/src/main/java/com/moulberry/flashback/combo_options/Sizing.java b/src/main/java/com/moulberry/flashback/combo_options/Sizing.java new file mode 100644 index 0000000..0702547 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/Sizing.java @@ -0,0 +1,21 @@ +package com.moulberry.flashback.combo_options; + +public enum Sizing implements ComboOption { + + KEEP_ASPECT_RATIO("Keep Aspect Ratio"), + FILL("Fill"), + UNDERLAY("Underlay"), + CHANGE_ASPECT_RATIO("Change Aspect Ratio"); + + private final String text; + + Sizing(String text) { + this.text = text; + } + + @Override + public String text() { + return this.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 new file mode 100644 index 0000000..d0e7fac --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java @@ -0,0 +1,93 @@ +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 org.bytedeco.ffmpeg.avcodec.AVCodec; +import org.bytedeco.ffmpeg.avcodec.AVCodecHWConfig; +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.*; + +public enum VideoCodec implements ComboOption { + + H264("H264 (AVC)", avcodec.AV_CODEC_ID_H264), + H265("H265 (HEVC)", avcodec.AV_CODEC_ID_H265), + AV1("AV1", avcodec.AV_CODEC_ID_AV1), + VP9("VP9", avcodec.AV_CODEC_ID_VP9), + PRO_RES("Apple ProRes", avcodec.AV_CODEC_ID_PRORES), + QUICK_TIME("QuickTime", avcodec.AV_CODEC_ID_QTRLE); + + private final String text; + private final int codecId; + private String[] encoders; + + VideoCodec(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 || name.equals("libaom-av1")) { + 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/VideoContainer.java b/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java new file mode 100644 index 0000000..d1de03c --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoContainer.java @@ -0,0 +1,59 @@ +package com.moulberry.flashback.combo_options; + +import org.bytedeco.ffmpeg.avformat.AVOutputFormat; +import org.bytedeco.ffmpeg.global.avcodec; +import org.bytedeco.ffmpeg.global.avformat; + +import java.util.ArrayList; +import java.util.List; + +public enum VideoContainer implements ComboOption { + + MP4("MP4", "mp4"), + MKV("MKV", "mkv"), + AVI("AVI", "avi"), + MOV("MOV", "mov"); + + private final String text; + private final String extension; + private VideoCodec[] supportedCodecs = null; + + VideoContainer(String text, String extension) { + this.text = text; + this.extension = extension; + } + + @Override + public String text() { + return this.text; + } + + public String extension() { + return extension; + } + + public VideoCodec[] getSupportedCodecs() { + if (this.supportedCodecs == null) { + List supportedCodecs = new ArrayList<>(); + try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) { + for (VideoCodec codec : VideoCodec.values()) { + if (codec == VideoCodec.AV1 && this != VideoContainer.MP4) { + continue; + } + 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.supportedCodecs = supportedCodecs.toArray(new VideoCodec[0]); + } + return this.supportedCodecs; + } + +} diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoPreset.java b/src/main/java/com/moulberry/flashback/combo_options/VideoPreset.java new file mode 100644 index 0000000..3c15449 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoPreset.java @@ -0,0 +1,31 @@ +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/configuration/FlashbackConfig.java b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java new file mode 100644 index 0000000..a31dc92 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/configuration/FlashbackConfig.java @@ -0,0 +1,73 @@ +package com.moulberry.flashback.configuration; + +import com.moulberry.flashback.Flashback; +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 java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public class FlashbackConfig { + + @OptionCaption("flashback.option.automatically_start") + @OptionDescription("flashback.option.automatically_start.description") + public static boolean automaticallyStart = false; + + @OptionCaption("flashback.option.automatically_finish") + @OptionDescription("flashback.option.automatically_finish.description") + public static boolean automaticallyFinish = true; + + @OptionCaption("flashback.option.show_recording_toasts") + @OptionDescription("flashback.option.show_recording_toasts.description") + public static boolean showRecordingToasts = true; + + @SuppressWarnings("unchecked") + public static OptionInstance[] createOptionInstances() { + List> options = new ArrayList<>(); + + for (Field field : FlashbackConfig.class.getDeclaredFields()) { + try { + // Ignore non-static fields + if ((field.getModifiers() & Modifier.STATIC) == 0) { + continue; + } + + OptionCaption caption = field.getDeclaredAnnotation(OptionCaption.class); + if (caption == null) { + continue; + } + + OptionInstance.TooltipSupplier tooltipSupplier = OptionInstance.noTooltip(); + OptionDescription description = field.getDeclaredAnnotation(OptionDescription.class); + if (description != null) { + MutableComponent root = Component.empty(); + root.append(Component.translatable(caption.value()).withStyle(ChatFormatting.YELLOW)); + root.append(Component.literal("\n")); + root.append(Component.translatable(description.value())); + + tooltipSupplier = OptionInstance.cachedConstantTooltip(root); + } + + if (field.getType() == boolean.class) { + options.add(OptionInstance.createBoolean(caption.value(), tooltipSupplier, field.getBoolean(null), value -> { + try { + field.set(null, value); + } catch (Exception e) { + throw SneakyThrow.sneakyThrow(e); + } + })); + } + } catch (Exception e) { + Flashback.LOGGER.error("Error while trying to convert config field to OptionInstance", e); + } + } + + return options.toArray(new OptionInstance[0]); + } + +} diff --git a/src/main/java/com/moulberry/flashback/configuration/OptionCaption.java b/src/main/java/com/moulberry/flashback/configuration/OptionCaption.java new file mode 100644 index 0000000..1b9dc5b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/configuration/OptionCaption.java @@ -0,0 +1,14 @@ +package com.moulberry.flashback.configuration; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface OptionCaption { + + String value(); + +} diff --git a/src/main/java/com/moulberry/flashback/configuration/OptionDescription.java b/src/main/java/com/moulberry/flashback/configuration/OptionDescription.java new file mode 100644 index 0000000..efad5bd --- /dev/null +++ b/src/main/java/com/moulberry/flashback/configuration/OptionDescription.java @@ -0,0 +1,14 @@ +package com.moulberry.flashback.configuration; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface OptionDescription { + + String value(); + +} diff --git a/src/main/java/com/moulberry/flashback/editor/SavedTrack.java b/src/main/java/com/moulberry/flashback/editor/SavedTrack.java new file mode 100644 index 0000000..7045f9c --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/SavedTrack.java @@ -0,0 +1,55 @@ +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.KeyframeTrack; + +import java.util.Map; +import java.util.TreeMap; + +public record SavedTrack(KeyframeType type, int track, boolean copiedFromDisabled, + 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); + } + } + + // 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); + } + } + + // 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; + } + + public int applyTo(KeyframeTrack keyframeTrack, int cursorTicks, int totalTicks) { + int count = 0; + for (Map.Entry> entry : this.keyframes.entrySet()) { + int newTick = entry.getKey() + cursorTicks; + if (newTick >= 0 && newTick <= totalTicks) { + keyframeTrack.keyframesByTick.put(newTick, entry.getValue()); + count += 1; + } + } + return count; + } +} diff --git a/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java b/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java new file mode 100644 index 0000000..cec7b97 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/SelectedKeyframes.java @@ -0,0 +1,22 @@ +package com.moulberry.flashback.editor; + +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.KeyframeTrack; +import it.unimi.dsi.fastutil.ints.IntSet; + +public record SelectedKeyframes(KeyframeType type, int trackIndex, IntSet keyframeTicks) { + public boolean checkValid(EditorState state) { + if (this.trackIndex < 0 || this.trackIndex >= state.keyframeTracks.size()) { + return false; + } + + KeyframeTrack keyframeTrack = state.keyframeTracks.get(this.trackIndex); + if (keyframeTrack.keyframeType != this.type) { + return false; + } + + this.keyframeTicks.removeIf(tick -> !keyframeTrack.keyframesByTick.containsKey(tick)); + return !this.keyframeTicks.isEmpty(); + } +} diff --git a/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGl3.java b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGl3.java similarity index 99% rename from src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGl3.java rename to src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGl3.java index 0a34b83..712a477 100644 --- a/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGl3.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGl3.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.ui; +package com.moulberry.flashback.editor.ui; import imgui.ImDrawData; import imgui.ImFontAtlas; diff --git a/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGlfw.java b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java similarity index 90% rename from src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGlfw.java rename to src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java index 33f9408..87f4fd5 100644 --- a/src/client/java/com/moulberry/flashback/ui/CustomImGuiImplGlfw.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java @@ -1,5 +1,7 @@ -package com.moulberry.flashback.ui; +package com.moulberry.flashback.editor.ui; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.exporting.AsyncFileDialogs; import imgui.ImGui; import imgui.ImGuiIO; import imgui.ImGuiPlatformIO; @@ -22,10 +24,7 @@ import imgui.flag.ImGuiNavInput; import imgui.flag.ImGuiViewportFlags; import imgui.lwjgl3.glfw.ImGuiImplGlfwNative; import net.minecraft.client.Minecraft; -import net.minecraft.core.Direction; -import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec2; -import net.minecraft.world.phys.Vec3; import org.lwjgl.PointerBuffer; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWCharCallback; @@ -54,6 +53,9 @@ public class CustomImGuiImplGlfw { protected static final boolean IS_WINDOWS = OS.contains("win"); protected static final boolean IS_APPLE = OS.contains("mac") || OS.contains("darwin"); + // ImGui Structs + private ImGuiIO io = null; + // Pointer of the current GLFW window private long mainWindowPtr; @@ -120,6 +122,7 @@ public class CustomImGuiImplGlfw { private MouseHandledBy grabbed = null; private int ignoreMouseMovements = 0; + private boolean releasedAllKeysBecauseOfDialog = false; private boolean releasedAllKeysBecauseOfDisable = false; private final double[] grabbedOriginalMouseX = new double[1]; private final double[] grabbedOriginalMouseY = new double[1]; @@ -148,7 +151,7 @@ public class CustomImGuiImplGlfw { public MouseHandledBy getMouseHandledBy() { if (!ReplayUI.isActive()) return MouseHandledBy.GAME; if (this.grabbed != null) return this.grabbed; - if (ImGui.getIO().getWantCaptureMouse()) return MouseHandledBy.IMGUI; + if (this.io.getWantCaptureMouse()) return MouseHandledBy.IMGUI; return MouseHandledBy.BOTH; } @@ -220,6 +223,8 @@ public class CustomImGuiImplGlfw { * @param mods click modifiers */ public void mouseButtonCallback(final long windowId, final int button, final int action, final int mods) { + if (AsyncFileDialogs.hasDialog()) return; + if (!ReplayUI.isActive()) { if (this.prevUserCallbackMouseButton != null && windowId == this.mainWindowPtr) { this.prevUserCallbackMouseButton.invoke(windowId, button, action, mods); @@ -249,10 +254,11 @@ public class CustomImGuiImplGlfw { * @param yOffset scroll offset by y-axis */ public void scrollCallback(final long windowId, final double xOffset, final double yOffset) { + if (AsyncFileDialogs.hasDialog()) return; + if (ReplayUI.isActive()) { - final ImGuiIO io = ImGui.getIO(); - io.setMouseWheelH(io.getMouseWheelH() + (float) xOffset); - io.setMouseWheel(io.getMouseWheel() + (float) yOffset); + this.io.setMouseWheelH(this.io.getMouseWheelH() + (float) xOffset); + this.io.setMouseWheel(this.io.getMouseWheel() + (float) yOffset); if (Minecraft.getInstance().screen == null || !ReplayUI.isMainFrameHovered()) { return; @@ -274,6 +280,8 @@ public class CustomImGuiImplGlfw { * @param mods press modifiers */ public void keyCallback(final long windowId, int key, final int scancode, final int action, final int mods) { + if (AsyncFileDialogs.hasDialog()) return; + if (key < GLFW_KEY_SPACE || key > GLFW_KEY_LAST) { if (this.prevUserCallbackKey != null && windowId == this.mainWindowPtr) this.prevUserCallbackKey.invoke(windowId, key, scancode, action, mods); return; @@ -286,19 +294,27 @@ public class CustomImGuiImplGlfw { int minecraftKey = key; boolean keyInBoundsForGame = minecraftKey >= 0 && minecraftKey < this.keyPressedGame.length; - final ImGuiIO io = ImGui.getIO(); - if (this.grabbed != null && action == GLFW_RELEASE && this.grabLinkedKey > 0 && key == this.grabLinkedKey) { this.ungrab(); } if (!ReplayUI.isActive() || Minecraft.getInstance().screen != null) { if (action == GLFW_RELEASE && key >= 0 && key < this.keyOwnerWindows.length) { - io.setKeysDown(key, false); + this.io.setKeysDown(key, false); this.keyOwnerWindows[key] = 0; } if (this.prevUserCallbackKey != null && windowId == this.mainWindowPtr) { 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 (action == GLFW_RELEASE && keyInBoundsForGame && this.keyPressedGame[minecraftKey]) { + this.keyPressedGame[minecraftKey] = false; + } else { + return; + } + } + this.prevUserCallbackKey.invoke(windowId, minecraftKey, scancode, action, mods); } return; @@ -318,7 +334,7 @@ public class CustomImGuiImplGlfw { return; } - boolean passToMinecraft = (ReplayUI.isMainFrameHovered() && ImGui.isMouseDown(ImGuiMouseButton.Left) || !io.getWantCaptureKeyboard()) && !io.getWantTextInput(); + boolean passToMinecraft = (ReplayUI.isMainFrameHovered() && this.io.getMouseDown(ImGuiMouseButton.Left) || !this.io.getWantCaptureKeyboard()) && !this.io.getWantTextInput(); if (action == GLFW_RELEASE) { if (keyInBoundsForGame && this.keyPressedGame[minecraftKey]) passToMinecraft = true; @@ -352,6 +368,8 @@ public class CustomImGuiImplGlfw { } public void cursorPosCallback(final long windowId, final double xpos, final double ypos) { + if (AsyncFileDialogs.hasDialog()) return; + if (!ReplayUI.isActive()) { if (this.prevUserCallbackCursorPos != null && windowId == this.mainWindowPtr) this.prevUserCallbackCursorPos.invoke(windowId, xpos, ypos); return; @@ -390,7 +408,7 @@ public class CustomImGuiImplGlfw { this.prevUserCallbackWindowFocus.invoke(windowId, focused); } - ImGui.getIO().addFocusEvent(focused); + this.io.addFocusEvent(focused); } /** @@ -419,19 +437,19 @@ public class CustomImGuiImplGlfw { * @param c pressed char */ public void charCallback(final long windowId, final int c, final int mods) { + if (AsyncFileDialogs.hasDialog()) return; + if (!ReplayUI.isActive()) { if (this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) this.prevUserCallbackChar.invoke(windowId, c, mods); return; } - final ImGuiIO io = ImGui.getIO(); - - if (!io.getWantCaptureKeyboard() && this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) { + if (!this.io.getWantCaptureKeyboard() && this.prevUserCallbackChar != null && windowId == this.mainWindowPtr) { this.prevUserCallbackChar.invoke(windowId, c, mods); } if (!ImGuiHelper.addInputCharacter((char) c)) { - io.addInputCharacter(c); + this.io.addInputCharacter(c); } } @@ -476,12 +494,12 @@ public class CustomImGuiImplGlfw { public void enableTabInput() { this.keyMap[ImGuiKey.Tab] = GLFW_KEY_TAB; - ImGui.getIO().setKeyMap(this.keyMap); + this.io.setKeyMap(this.keyMap); } public void disableTabInput() { this.keyMap[ImGuiKey.Tab] = -1; - ImGui.getIO().setKeyMap(this.keyMap); + this.io.setKeyMap(this.keyMap); } /** @@ -493,13 +511,12 @@ public class CustomImGuiImplGlfw { * @param installCallbacks should window callbacks be installed * @return true if everything initialized */ - public boolean init(final long windowId, final boolean installCallbacks) { + public boolean init(final long windowId, final boolean installCallbacks, ImGuiIO imGuiIo) { this.mainWindowPtr = windowId; + this.io = imGuiIo; this.detectGlfwVersionAndEnabledFeatures(); - final ImGuiIO io = ImGui.getIO(); - io.addBackendFlags(ImGuiBackendFlags.HasMouseCursors | ImGuiBackendFlags.HasSetMousePos | ImGuiBackendFlags.PlatformHasViewports); io.setBackendPlatformName("imgui_java_impl_glfw"); @@ -588,7 +605,7 @@ public class CustomImGuiImplGlfw { * Updates {@link ImGuiIO} and {@link org.lwjgl.glfw.GLFW} state. */ public void newFrame() { - final ImGuiIO io = ImGui.getIO(); + this.io.ptr = ImGui.getIO().ptr; if (this.interframeMousePositions.isEmpty()) { this.capturedInterframeMousePositions.clear(); @@ -596,7 +613,7 @@ public class CustomImGuiImplGlfw { this.capturedInterframeMousePositions = this.interframeMousePositions; this.interframeMousePositions = new ArrayList<>(); - if (io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { + if (this.io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) { // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor) long windowPtr = this.mouseWindowPtr; if (windowPtr == 0) { @@ -615,11 +632,11 @@ public class CustomImGuiImplGlfw { glfwGetWindowSize(this.mainWindowPtr, this.winWidth, this.winHeight); glfwGetFramebufferSize(this.mainWindowPtr, this.fbWidth, this.fbHeight); - io.setDisplaySize((float) this.winWidth[0], (float) this.winHeight[0]); + this.io.setDisplaySize((float) this.winWidth[0], (float) this.winHeight[0]); if (this.winWidth[0] > 0 && this.winHeight[0] > 0) { final float scaleX = (float) this.fbWidth[0] / this.winWidth[0]; final float scaleY = (float) this.fbHeight[0] / this.winHeight[0]; - io.setDisplayFramebufferScale(scaleX, scaleY); + this.io.setDisplayFramebufferScale(scaleX, scaleY); GLFW.glfwGetWindowContentScale(Minecraft.getInstance().getWindow().getWindow(), this.windowScaleX, this.windowScaleY); @@ -630,9 +647,38 @@ public class CustomImGuiImplGlfw { } final double currentTime = glfwGetTime(); - io.setDeltaTime(this.time > 0.0 ? (float) (currentTime - this.time) : 1.0f / 60.0f); + this.io.setDeltaTime(this.time > 0.0 ? (float) (currentTime - this.time) : 1.0f / 60.0f); this.time = currentTime; + if (AsyncFileDialogs.hasDialog()) { + if (!this.releasedAllKeysBecauseOfDialog) { + this.releasedAllKeysBecauseOfDialog = true; + + // Release for game + for (int key = 0; key < this.keyPressedGame.length; key++) { + if (this.keyPressedGame[key]) { + int scancode = GLFW.glfwGetKeyScancode(key); + this.prevUserCallbackKey.invoke(this.mainWindowPtr, key, scancode, GLFW_RELEASE, 0); + } + } + + // Release for imgui + for (int key = 0; key < this.keyOwnerWindows.length; key++) { + this.io.setKeysDown(key, false); + this.keyOwnerWindows[key] = 0; + } + + this.io.setKeyCtrl(false); + this.io.setKeyShift(false); + this.io.setKeyAlt(false); + this.io.setKeySuper(false); + } + + return; + } else { + this.releasedAllKeysBecauseOfDialog = false; + } + boolean shiftDown = false; boolean ctrlDown = false; boolean altDown = false; @@ -667,26 +713,22 @@ public class CustomImGuiImplGlfw { if (!this.releasedAllKeysBecauseOfDisable) { this.releasedAllKeysBecauseOfDisable = true; - final ImGuiIO io = ImGui.getIO(); - for (int key = 0; key < this.keyOwnerWindows.length; key++) { - io.setKeysDown(key, false); + this.io.setKeysDown(key, false); this.keyOwnerWindows[key] = 0; } - io.setKeyCtrl(false); - io.setKeyShift(false); - io.setKeyAlt(false); - io.setKeySuper(false); + this.io.setKeyCtrl(false); + this.io.setKeyShift(false); + this.io.setKeyAlt(false); + this.io.setKeySuper(false); - if (ImGui.getMouseCursor() != ImGuiMouseCursor.Arrow) { - final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); - for (int n = 0; n < platformIO.getViewportsSize(); n++) { - final long windowPtr = platformIO.getViewports(n).getPlatformHandle(); + final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); + for (int n = 0; n < platformIO.getViewportsSize(); n++) { + final long windowPtr = platformIO.getViewports(n).getPlatformHandle(); - // Change cursor back to arrow - glfwSetCursor(windowPtr, this.mouseCursors[ImGuiMouseCursor.Arrow]); - } + // Change cursor back to arrow + glfwSetCursor(windowPtr, this.mouseCursors[ImGuiMouseCursor.Arrow]); } } } else { @@ -711,12 +753,10 @@ public class CustomImGuiImplGlfw { } private void updateMousePosAndButtons() { - final ImGuiIO io = ImGui.getIO(); - var mouseHandledBy = this.getMouseHandledBy(); - if (!mouseHandledBy.allowImgui()) { + if (!mouseHandledBy.allowImgui() || AsyncFileDialogs.hasDialog()) { for (int i = 0; i < ImGuiMouseButton.COUNT; i++) { - io.setMouseDown(i, false); + this.io.setMouseDown(i, false); this.mouseJustPressed[i] = false; } return; @@ -724,13 +764,13 @@ public class CustomImGuiImplGlfw { for (int i = 0; i < ImGuiMouseButton.COUNT; i++) { // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. - io.setMouseDown(i, this.mouseJustPressed[i] || glfwGetMouseButton(this.mainWindowPtr, i) != 0); + this.io.setMouseDown(i, this.mouseJustPressed[i] || glfwGetMouseButton(this.mainWindowPtr, i) != 0); this.mouseJustPressed[i] = false; } - io.getMousePos(this.mousePosBackup); - io.setMousePos(-Float.MAX_VALUE, -Float.MAX_VALUE); - io.setMouseHoveredViewport(0); + this.io.getMousePos(this.mousePosBackup); + this.io.setMousePos(-Float.MAX_VALUE, -Float.MAX_VALUE); + this.io.setMouseHoveredViewport(0); final ImGuiPlatformIO platformIO = ImGui.getPlatformIO(); @@ -772,9 +812,9 @@ public class CustomImGuiImplGlfw { } private void updateMouseCursor() { - final ImGuiIO io = ImGui.getIO(); + if (AsyncFileDialogs.hasDialog()) return; - final boolean noCursorChange = io.hasConfigFlags(ImGuiConfigFlags.NoMouseCursorChange); + final boolean noCursorChange = this.io.hasConfigFlags(ImGuiConfigFlags.NoMouseCursorChange); final boolean cursorDisabled = glfwGetInputMode(this.mainWindowPtr, GLFW_CURSOR) == GLFW_CURSOR_DISABLED; if (noCursorChange || cursorDisabled) { @@ -800,13 +840,13 @@ public class CustomImGuiImplGlfw { } private void updateGamepads() { - final ImGuiIO io = ImGui.getIO(); + if (AsyncFileDialogs.hasDialog()) return; - if (!io.hasConfigFlags(ImGuiConfigFlags.NavEnableGamepad)) { + if (!this.io.hasConfigFlags(ImGuiConfigFlags.NavEnableGamepad)) { return; } - io.setNavInputs(this.emptyNavInputs); + this.io.setNavInputs(this.emptyNavInputs); final ByteBuffer buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1); final int buttonsCount = buttons.limit(); @@ -814,27 +854,27 @@ public class CustomImGuiImplGlfw { final FloatBuffer axis = glfwGetJoystickAxes(GLFW_JOYSTICK_1); final int axisCount = axis.limit(); - this.mapButton(ImGuiNavInput.Activate, 0, buttons, buttonsCount, io); // Cross / A - this.mapButton(ImGuiNavInput.Cancel, 1, buttons, buttonsCount, io); // Circle / B - this.mapButton(ImGuiNavInput.Menu, 2, buttons, buttonsCount, io); // Square / X - this.mapButton(ImGuiNavInput.Input, 3, buttons, buttonsCount, io); // Triangle / Y - this.mapButton(ImGuiNavInput.DpadLeft, 13, buttons, buttonsCount, io); // D-Pad Left - this.mapButton(ImGuiNavInput.DpadRight, 11, buttons, buttonsCount, io); // D-Pad Right - this.mapButton(ImGuiNavInput.DpadUp, 10, buttons, buttonsCount, io); // D-Pad Up - this.mapButton(ImGuiNavInput.DpadDown, 12, buttons, buttonsCount, io); // D-Pad Down - this.mapButton(ImGuiNavInput.FocusPrev, 4, buttons, buttonsCount, io); // L1 / LB - this.mapButton(ImGuiNavInput.FocusNext, 5, buttons, buttonsCount, io); // R1 / RB - this.mapButton(ImGuiNavInput.TweakSlow, 4, buttons, buttonsCount, io); // L1 / LB - this.mapButton(ImGuiNavInput.TweakFast, 5, buttons, buttonsCount, io); // R1 / RB - this.mapAnalog(ImGuiNavInput.LStickLeft, 0, -0.3f, -0.9f, axis, axisCount, io); - this.mapAnalog(ImGuiNavInput.LStickRight, 0, +0.3f, +0.9f, axis, axisCount, io); - this.mapAnalog(ImGuiNavInput.LStickUp, 1, +0.3f, +0.9f, axis, axisCount, io); - this.mapAnalog(ImGuiNavInput.LStickDown, 1, -0.3f, -0.9f, axis, axisCount, io); + this.mapButton(ImGuiNavInput.Activate, 0, buttons, buttonsCount, this.io); // Cross / A + this.mapButton(ImGuiNavInput.Cancel, 1, buttons, buttonsCount, this.io); // Circle / B + this.mapButton(ImGuiNavInput.Menu, 2, buttons, buttonsCount, this.io); // Square / X + this.mapButton(ImGuiNavInput.Input, 3, buttons, buttonsCount, this.io); // Triangle / Y + this.mapButton(ImGuiNavInput.DpadLeft, 13, buttons, buttonsCount, this.io); // D-Pad Left + this.mapButton(ImGuiNavInput.DpadRight, 11, buttons, buttonsCount, this.io); // D-Pad Right + this.mapButton(ImGuiNavInput.DpadUp, 10, buttons, buttonsCount, this.io); // D-Pad Up + this.mapButton(ImGuiNavInput.DpadDown, 12, buttons, buttonsCount, this.io); // D-Pad Down + this.mapButton(ImGuiNavInput.FocusPrev, 4, buttons, buttonsCount, this.io); // L1 / LB + this.mapButton(ImGuiNavInput.FocusNext, 5, buttons, buttonsCount, this.io); // R1 / RB + this.mapButton(ImGuiNavInput.TweakSlow, 4, buttons, buttonsCount, this.io); // L1 / LB + this.mapButton(ImGuiNavInput.TweakFast, 5, buttons, buttonsCount, this.io); // R1 / RB + this.mapAnalog(ImGuiNavInput.LStickLeft, 0, -0.3f, -0.9f, axis, axisCount, this.io); + this.mapAnalog(ImGuiNavInput.LStickRight, 0, +0.3f, +0.9f, axis, axisCount, this.io); + this.mapAnalog(ImGuiNavInput.LStickUp, 1, +0.3f, +0.9f, axis, axisCount, this.io); + this.mapAnalog(ImGuiNavInput.LStickDown, 1, -0.3f, -0.9f, axis, axisCount, this.io); if (axisCount > 0 && buttonsCount > 0) { - io.addBackendFlags(ImGuiBackendFlags.HasGamepad); + this.io.addBackendFlags(ImGuiBackendFlags.HasGamepad); } else { - io.removeBackendFlags(ImGuiBackendFlags.HasGamepad); + this.io.removeBackendFlags(ImGuiBackendFlags.HasGamepad); } } diff --git a/src/client/java/com/moulberry/flashback/ui/EditorMovementControls.java b/src/main/java/com/moulberry/flashback/editor/ui/EditorMovementControls.java similarity index 98% rename from src/client/java/com/moulberry/flashback/ui/EditorMovementControls.java rename to src/main/java/com/moulberry/flashback/editor/ui/EditorMovementControls.java index cd6d8c5..0d8a6d5 100644 --- a/src/client/java/com/moulberry/flashback/ui/EditorMovementControls.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/EditorMovementControls.java @@ -1,11 +1,9 @@ -package com.moulberry.flashback.ui; +package com.moulberry.flashback.editor.ui; import imgui.ImGui; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.util.Mth; -import net.minecraft.world.level.ClipContext; -import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec2; import net.minecraft.world.phys.Vec3; import org.joml.Intersectionf; diff --git a/src/client/java/com/moulberry/flashback/ui/GlyphRanges.java b/src/main/java/com/moulberry/flashback/editor/ui/GlyphRanges.java similarity index 99% rename from src/client/java/com/moulberry/flashback/ui/GlyphRanges.java rename to src/main/java/com/moulberry/flashback/editor/ui/GlyphRanges.java index 1d6fc61..a8f0d55 100644 --- a/src/client/java/com/moulberry/flashback/ui/GlyphRanges.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/GlyphRanges.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.ui; +package com.moulberry.flashback.editor.ui; public class GlyphRanges { diff --git a/src/client/java/com/moulberry/flashback/ui/ImGuiHelper.java b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java similarity index 86% rename from src/client/java/com/moulberry/flashback/ui/ImGuiHelper.java rename to src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java index a9960e7..9076454 100644 --- a/src/client/java/com/moulberry/flashback/ui/ImGuiHelper.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ImGuiHelper.java @@ -1,45 +1,30 @@ -package com.moulberry.flashback.ui; +package com.moulberry.flashback.editor.ui; -import imgui.ImDrawList; +import com.moulberry.flashback.combo_options.ComboOption; import imgui.ImGui; -import imgui.ImGuiListClipper; import imgui.ImVec2; -import imgui.callback.ImListClipperCallback; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiComboFlags; -import imgui.flag.ImGuiDragDropFlags; import imgui.flag.ImGuiHoveredFlags; -import imgui.flag.ImGuiInputTextFlags; -import imgui.flag.ImGuiMouseButton; -import imgui.flag.ImGuiMouseCursor; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import imgui.type.ImString; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.ConfirmLinkScreen; -import net.minecraft.core.HolderSet; -import net.minecraft.world.level.block.Block; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import java.net.URI; +import java.util.HashMap; import java.util.List; -import java.util.concurrent.atomic.AtomicReference; +import java.util.Map; import java.util.function.IntConsumer; import java.util.function.Predicate; public class ImGuiHelper { - public enum LabelPosition { - LABEL_ABOVE, - LABEL_RIGHT - } - - public record Label(@NotNull String key, @NotNull String title, @Nullable String description) { - } - public static String getString(ImString string) { StringBuilder builder = new StringBuilder(); String str = string.get(); @@ -51,6 +36,12 @@ public class ImGuiHelper { return builder.toString(); } + public static ImString createResizableImString(String text) { + ImString imString = new ImString(text); + imString.inputData.isResizable = true; + 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(); @@ -132,6 +123,60 @@ public class ImGuiHelper { 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<>(); + + public static & ComboOption> T enumCombo(String label, T c, T[] values) { + int currentIndex = -1; + for (int i = 0; i < values.length; i++) { + T value = values[i]; + if (value == c) { + currentIndex = i; + break; + } + } + + String[] text = new String[values.length]; + for (int i = 0; i < text.length; i++) { + text[i] = values[i].text(); + } + + enumComboSharedArray[0] = currentIndex; + combo(label, enumComboSharedArray, text); + if (enumComboSharedArray[0] == currentIndex) { + return c; + } else { + return values[enumComboSharedArray[0]]; + } + } + + @SuppressWarnings("unchecked") + public static & ComboOption> T enumCombo(String label, T c) { + Class clazz = c.getClass(); + int currentIndex = c.ordinal(); + + String[] text = enumComboCachedText.get(clazz); + if (text == null) { + T[] options = (T[]) clazz.getEnumConstants(); + enumComboCachedValues.put(clazz, options); + + text = new String[options.length]; + for (int i = 0; i < text.length; i++) { + text[i] = options[i].text(); + } + enumComboCachedText.put(clazz, text); + } + + enumComboSharedArray[0] = currentIndex; + combo(label, enumComboSharedArray, text); + if (enumComboSharedArray[0] == currentIndex) { + return c; + } else { + return (T) enumComboCachedValues.get(clazz)[enumComboSharedArray[0]]; + } + } + public static boolean combo(String label, int[] currentItem, String[] values) { return combo(label, currentItem, values, ImGuiComboFlags.None); } @@ -139,6 +184,10 @@ public class ImGuiHelper { public static boolean combo(String label, int[] currentItem, String[] values, int imguiComboFlags) { boolean changed = false; + if (currentItem[0] >= values.length && values.length > 0) { + currentItem[0] = values.length-1; + } + if (ImGui.beginCombo(label, currentItem[0] < 0 ? "" : values[currentItem[0]], imguiComboFlags)) { for (int i=0; i { - if (open) { - try { - Util.getPlatform().openUri(new URI(page)); - } catch (Exception ignored) {} - } - Minecraft.getInstance().setScreen(null); - }, page, false)); - } - } - public static void tooltip(String message, int imGuiHoveredFlags) { if (ImGui.isItemHovered(imGuiHoveredFlags)) { drawTooltip(message); @@ -363,28 +382,6 @@ public class ImGuiHelper { tooltip(disabledMessage, ImGuiHoveredFlags.AllowWhenDisabled); } - public static boolean drawLabelledWidget(Label label, LabelPosition style, Predicate predicate) { - boolean ret = false; - switch (style) { - case LABEL_ABOVE -> { - ImGui.text(label.title); - if (label.description != null) { - ImGui.sameLine(); - helpMarker(label.description); - } - ret = predicate.test("###" + label.key); - } - case LABEL_RIGHT -> { - ret = predicate.test(label.title + "###" + label.key); - if (label.description != null) { - ImGui.sameLine(); - helpMarker(label.description); - } - } - } - return ret; - } - public static void separatorWithText(String text) { float textStartX = ImGui.getCursorScreenPosX() + ImGui.getStyle().getIndentSpacing(); diff --git a/src/main/java/com/moulberry/flashback/editor/ui/Keybinds.java b/src/main/java/com/moulberry/flashback/editor/ui/Keybinds.java new file mode 100644 index 0000000..e03a818 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/Keybinds.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.editor.ui; + +public class Keybinds { + + + +} diff --git a/src/client/java/com/moulberry/flashback/ui/ReplayUI.java b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java similarity index 63% rename from src/client/java/com/moulberry/flashback/ui/ReplayUI.java rename to src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java index 334fd10..b2aff17 100644 --- a/src/client/java/com/moulberry/flashback/ui/ReplayUI.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java @@ -1,23 +1,38 @@ -package com.moulberry.flashback.ui; +package com.moulberry.flashback.editor.ui; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.TextureUtil; import com.mojang.blaze3d.platform.Window; -import com.moulberry.flashback.FlashbackClient; -import com.moulberry.flashback.exporting.ExportJob; -import com.moulberry.flashback.ui.windows.Timeline; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.combo_options.Sizing; +import com.moulberry.flashback.editor.ui.windows.MainMenuBar; +import com.moulberry.flashback.editor.ui.windows.StartExportWindow; +import com.moulberry.flashback.editor.ui.windows.TimelineWindow; +import com.moulberry.flashback.editor.ui.windows.VisualsWindow; import imgui.*; import imgui.flag.*; +import imgui.internal.ImGuiContext; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.ProgressScreen; import net.minecraft.client.gui.screens.ReceivingLevelScreen; import net.minecraft.client.multiplayer.MultiPlayerGameMode; -import net.minecraft.resources.ResourceLocation; +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; import net.minecraft.world.level.GameType; -import net.minecraft.world.phys.Vec2; -import net.minecraft.world.phys.Vec3; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.CollisionContext; +import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.joml.Quaternionf; import org.joml.Vector4f; @@ -25,25 +40,24 @@ import org.lwjgl.glfw.GLFW; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Predicate; public class ReplayUI { public static final CustomImGuiImplGlfw imguiGlfw = new CustomImGuiImplGlfw(); private static final CustomImGuiImplGl3 imguiGl3 = new CustomImGuiImplGl3(); private static boolean initialized = false; - private static boolean enabled = false; private static boolean isFrameHovered = false; - public static int frameX = 0; - public static int frameY = 0; - public static int frameWidth = 1; - public static int frameHeight = 1; + private static int frameX = 0; + private static int frameY = 0; + private static int frameWidth = 1; + private static int frameHeight = 1; private static boolean activeLastFrame = false; public static Matrix4f lastProjectionMatrix = null; @@ -64,42 +78,58 @@ public class ReplayUI { public static float newGlobalScale = 1.0f; private static float contentScale = 1.0f; + private static ImGuiContext imGuiContext = null; + private static ImGuiIO imGuiIo = null; + + private static boolean popupOpenLastFrame = false; + + private static String infoOverlayText = null; + private static long infoOverlayStartMillis = 0; + + private static int selectedEntity = Integer.MIN_VALUE; + private static boolean openSelectedEntityPopup = false; + public static void init() { if (initialized) { - throw new IllegalStateException("EditorUI initialized twice"); + throw new IllegalStateException("ReplayUI initialized twice"); } initialized = true; - // todo: + // todo: introduce global scale option // newGlobalScale = globalScale = Configuration.internal.globalScale; // Initialize config so that everything starts nicely docked - // todo: -// Path path = Axiom.getInstance().getConfigDirectory().resolve("imgui.ini"); -// if (!Files.exists(path)) { -// try { -// Files.write(path, InternalConfiguration.DEFAULT_LAYOUT.getBytes()); -// } catch(IOException ignored) {} -// } + Path path = Flashback.getConfigDirectory().resolve("imgui.ini"); + if (!Files.exists(path)) { + try { + Files.writeString(path, ReplayUIDefaults.LAYOUT); + } catch(IOException ignored) {} + } - ImGui.createContext(); + long oldImGuiContext = ImGui.getCurrentContext().ptr; + imGuiContext = new ImGuiContext(ImGui.createContext().ptr); + ImGui.setCurrentContext(imGuiContext); - // todo: -// Path relativePath = FabricLoader.getInstance().getGameDir().relativize(path); -// Axiom.dbg("Using DearImGui config: " + relativePath); -// ImGui.getIO().setIniFilename(relativePath.toString()); + Path relativePath = FabricLoader.getInstance().getGameDir().relativize(path); + ImGui.getIO().setIniFilename(relativePath.toString()); ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); ImGui.getIO().addConfigFlags(ImGuiConfigFlags.DockingEnable); // ImGui.getIO().addConfigFlags(ImGuiConfigFlags.ViewportsEnable); ImGui.getIO().setConfigMacOSXBehaviors(Minecraft.ON_OSX); - imguiGlfw.init(Minecraft.getInstance().getWindow().getWindow(), true); + imguiGlfw.init(Minecraft.getInstance().getWindow().getWindow(), true, new ImGuiIO(ImGui.getIO().ptr)); imguiGl3.init("#version 150"); -// contentScale = imguiGlfw.contentScale; + contentScale = imguiGlfw.contentScale; initFonts(languageCode); + + ReplayUIDefaults.applyStyle(ImGui.getStyle()); + + ImGuiContext currentContext = ImGui.getCurrentContext(); + currentContext.ptr = oldImGuiContext; + ImGui.setCurrentContext(currentContext); } public static void initFonts(String languageCode) { @@ -193,7 +223,7 @@ public class ReplayUI { private static byte[] loadFont(String name) { try { - var resource = Minecraft.getInstance().getResourceManager().getResource(new ResourceLocation("flashback", name)); + var resource = Minecraft.getInstance().getResourceManager().getResource(Flashback.createResourceLocation(name)); if (resource.isEmpty()) throw new MissingResourceException("Missing font: " + name, "Font", ""); try (InputStream is = resource.get().open()) { return is.readAllBytes(); @@ -241,13 +271,10 @@ public class ReplayUI { forwards.mul(matrix); // Negate and normalize to match MC coordinate space - //#if MC>=12100 return new Vec3(forwards.x(), -forwards.y(), forwards.z()).normalize(); - //#else - //$$ return new Vec3(-forwards.x(), -forwards.y(), -forwards.z()).normalize(); - //#endif } + @Nullable public static Vec3 getMouseLookVectorFromForwards(Vec3 forwards) { if (forwards == null) return null; @@ -258,22 +285,33 @@ public class ReplayUI { return new Vec3(view.x(), view.y(), view.z()).normalize(); } + @Nullable public static Vec3 getMouseLookVector(float mouseX, float mouseY) { return getMouseLookVectorFromForwards(getMouseForwardsVector(mouseX, mouseY)); } + @Nullable public static Vec3 getMouseLookVector() { return getMouseLookVectorFromForwards(getMouseForwardsVector()); } + public static boolean isEntitySelected(int entityId) { + return isActive() && selectedEntity == entityId; + } + public static boolean isMovingCamera() { return imguiGlfw.isGrabbed() && imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME; } + public static void setInfoOverlay(String text) { + infoOverlayText = text; + infoOverlayStartMillis = System.currentTimeMillis(); + } + public static void setupMainViewport() { var window = Minecraft.getInstance().getWindow(); - int frameBottom = (int) ImGui.getMainViewport().getSizeY() - (frameY + frameHeight); + int frameBottom = window.height - (frameY + frameHeight); GlStateManager._viewport(frameX * window.getWidth() / window.getScreenWidth(), frameBottom * window.getHeight() / window.getScreenHeight(), Math.max(1, frameWidth * window.getWidth() / window.getScreenWidth()), @@ -301,11 +339,15 @@ public class ReplayUI { } private static boolean isActiveInternal() { - if (!FlashbackClient.isInReplay() || !enabled) { + if (!Flashback.isInReplay()) { return false; } - if (FlashbackClient.EXPORT_JOB != null) { + if (Flashback.EXPORT_JOB != null) { + return false; + } + + if (Minecraft.getInstance().options.hideGui) { return false; } @@ -318,18 +360,6 @@ public class ReplayUI { return true; } - public static void enable() { - enabled = true; - } - - public static void disable() { - enabled = false; - } - - public static void toggleEnabled() { - enabled = !enabled; - } - public static void deferredCloseTextureId(int textureId) { deferredCloseLock.lock(); try { @@ -348,10 +378,6 @@ public class ReplayUI { } } - public static boolean isEnabled() { - return enabled; - } - public static boolean isActive() { return activeLastFrame; } @@ -392,6 +418,19 @@ public class ReplayUI { } public static void drawOverlay() { + long oldImGuiContext = ImGui.getCurrentContext().ptr; + ImGui.setCurrentContext(imGuiContext); + + try { + drawOverlayInternal(); + } finally { + ImGuiContext currentContext = ImGui.getCurrentContext(); + currentContext.ptr = oldImGuiContext; + ImGui.setCurrentContext(currentContext); + } + } + + public static void drawOverlayInternal() { int oldFrameX = frameX; int oldFrameY = frameY; int oldFrameWidth = frameWidth; @@ -422,13 +461,8 @@ public class ReplayUI { return; } - enabled = true; - if (!isActiveInternal()) { transitionActiveState(false); - if (!FlashbackClient.isInReplay()) { - enabled = false; - } imguiGlfw.updateReleaseAllKeys(true); return; } else { @@ -449,8 +483,6 @@ public class ReplayUI { globalScale = newGlobalScale; contentScale = newContentScale; if (oldFontSize != (int)(16 * getUiScale())) { - // todo: - // Axiom.dbg("Resizing EditorUI fonts from: " + oldFontSize + " to: " + (int)(16 * getUiScale())); initFonts(languageCode); } } @@ -474,15 +506,7 @@ public class ReplayUI { char controlIcon = Minecraft.ON_OSX ? '\u2318' : '\u2303'; - // todo: - // MainMenuBar.render(); - if (ImGui.beginMainMenuBar()) { - if (ImGui.menuItem("Hello")) { - FlashbackClient.EXPORT_JOB = new ExportJob(20, 100); - } - - ImGui.endMainMenuBar(); - } + MainMenuBar.render(); // Setup docking ImGui.setNextWindowBgAlpha(0); @@ -514,8 +538,13 @@ public class ReplayUI { frameWidth = (int) Math.max(1, maxX - minX); frameHeight = (int) Math.max(1, maxY - minY); - if (true) { - float aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY(); + if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO || ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { + float aspectRatio; + if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO) { + aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY(); + } else { + aspectRatio = ReplayVisuals.changeAspectRatio.aspectRatio(); + } float currentAspectRatio = frameWidth / (float) frameHeight; @@ -530,22 +559,130 @@ public class ReplayUI { } } + if (infoOverlayText != null) { + long currentMillis = System.currentTimeMillis(); + if (currentMillis < infoOverlayStartMillis || currentMillis > infoOverlayStartMillis + 5000) { + infoOverlayText = null; + } 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); + + ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowBorderSize, 2); + ImGuiHelper.pushStyleColor(ImGuiCol.Border, 0xFF00FFFF); + + if (ImGui.begin("##InfoOverlay", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing | + ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse | + ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoSavedSettings)) { + + ImGui.text(infoOverlayText); + } + ImGui.end(); + + ImGuiHelper.popStyleColor(); + ImGuiHelper.popStyleVar(); + } + } + + if (ReplayVisuals.sizing == Sizing.UNDERLAY) { + frameX = 0; + frameY = 0; + frameWidth = Minecraft.getInstance().getWindow().getScreenWidth(); + frameHeight = Minecraft.getInstance().getWindow().getScreenHeight(); + } + if (frameX != oldFrameX || frameY != oldFrameY || frameWidth != oldFrameWidth || frameHeight != oldFrameHeight) { 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 (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 (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) { + selectedEntity = Integer.MIN_VALUE; + } else if (!(entity instanceof Player) && !ReplayVisuals.renderEntities) { + selectedEntity = Integer.MIN_VALUE; + } else { + if (openSelectedEntityPopup) { + ImGui.openPopup("###EntityPopup"); + } + + if (ImGuiHelper.beginPopup("###EntityPopup")) { + ImGui.text("Entity: " + entity.getUUID()); + + ImGui.separator(); + + 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()); +// } +// ImGui.sameLine(); +// ImGui.button("Track Entity"); +// +// ImGui.checkbox("Hide During Export", false); +// +// ImGui.checkbox("Force Glowing", false); +// ImGui.sameLine(); +// ImGui.colorButton("Glow Colour", new float[4]); +// ImGui.sameLine(); +// ImGui.text("Glow Colour"); +// +// if (entity instanceof LivingEntity) { +// ImGui.checkbox("Show Nametag", true); +// ImGui.checkbox("Override Nametag", false); +// } +// if (entity instanceof Player) { +// ImGui.checkbox("Override Skin", false); +// } + + + ImGui.endPopup(); + } + + if (!ImGui.isPopupOpen("###EntityPopup")) { + selectedEntity = Integer.MIN_VALUE; + } + } + } + + openSelectedEntityPopup = false; + if (ImGui.isWindowHovered() && ImGui.getMousePosY() > ImGui.getWindowPosY()) { isFrameHovered = true; if (Minecraft.getInstance().screen != null) { ImGui.captureMouseFromApp(false); - } else { - if (ImGui.getIO().getWantCaptureMouse() && !isMovingCamera()) { -// if (!adjustSpeed) { -// handleScroll(); -// } - fireCancelNavInput |= handleBasicInputs(); + } else if (isMovingCamera()) { + LocalPlayer player = Minecraft.getInstance().player; + if (player != null) { + int wheelY = (int) Math.signum(ImGui.getIO().getMouseWheel()); + if (wheelY != 0) { + final float defaultFlyingSpeed = 0.05f; + float flyingSpeed = Mth.clamp(player.getAbilities().getFlyingSpeed() + (float)wheelY * defaultFlyingSpeed / 10f, + defaultFlyingSpeed / 10f, defaultFlyingSpeed * 5.0f); + setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed)); + player.getAbilities().setFlyingSpeed(flyingSpeed); + } } + } else if (ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) { + fireCancelNavInput |= handleBasicInputs(); } } } else { @@ -553,13 +690,11 @@ public class ReplayUI { } ImGui.end(); - // VisualsWindow.render(); - Timeline.render(); + VisualsWindow.render(); + TimelineWindow.render(); + StartExportWindow.render(); - if (ImGui.begin("There")) { - ImGui.text("Hello!"); - } - ImGui.end(); + popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup); ImGui.render(); ImGuiHelper.endFrame(); @@ -591,7 +726,19 @@ public class ReplayUI { // return true; // } - if (ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_LEFT)) { + if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_RIGHT)) { + HitResult result = getLookTarget(); + if (result instanceof EntityHitResult entityHitResult) { + if (Minecraft.getInstance().player == Minecraft.getInstance().cameraEntity) { + Minecraft.getInstance().player.setDeltaMovement(Vec3.ZERO); + } + selectedEntity = entityHitResult.getEntity().getId(); + openSelectedEntityPopup = true; + } + return true; + } + + if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_LEFT)) { int key = -GLFW.GLFW_MOUSE_BUTTON_LEFT-1; if (key != 0) { imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f); @@ -657,6 +804,63 @@ public class ReplayUI { return false; } + @Nullable + private static HitResult getLookTarget() { + Vec3 look = getMouseLookVector(); + if (look == null) { + return null; + } + + Entity cameraEntity = Minecraft.getInstance().cameraEntity; + if (cameraEntity == null) { + return null; + } + + float distance = 64f; + + Vec3 from = cameraEntity.getEyePosition(); + Vec3 to = from.add(look.scale(distance)); + + BlockHitResult blockResult = null; + EntityHitResult entityResult = null; + + if (ReplayVisuals.renderBlocks) { + ClipContext clipContext = new ClipContext(from, to, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, CollisionContext.empty()); + blockResult = Minecraft.getInstance().level.clip(clipContext); + + if (blockResult.getType() != HitResult.Type.MISS) { + distance = (float) blockResult.getLocation().distanceTo(from); + } + } + + if (ReplayVisuals.renderEntities || 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) { + predicate = entity -> true; + } else if (ReplayVisuals.renderPlayers) { + predicate = entity -> entity instanceof Player; + } else if (ReplayVisuals.renderEntities) { + predicate = entity -> !(entity instanceof Player); + } else { + throw new IllegalStateException(); + } + + entityResult = ProjectileUtil.getEntityHitResult(cameraEntity, from, from.add(look.scale(distance)), + boundingBox, predicate, distance*distance); + } + + if (entityResult != null && entityResult.getLocation().distanceTo(from) < distance) { + return entityResult; + } else if (blockResult != null && blockResult.getType() != HitResult.Type.MISS) { + return blockResult; + } else { + return null; + } + } + public static boolean consumeNavClose() { boolean navClose = ReplayUI.navClose; ReplayUI.navClose = false; diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java new file mode 100644 index 0000000..1792710 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUIDefaults.java @@ -0,0 +1,113 @@ +package com.moulberry.flashback.editor.ui; + +import imgui.ImGui; +import imgui.ImGuiStyle; +import imgui.flag.ImGuiCol; +import net.minecraft.client.Minecraft; +import net.minecraft.util.FastColor; +import org.lwjgl.glfw.GLFW; + +public class ReplayUIDefaults { + + public static final String LAYOUT = """ + [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 + DockNode ID=0x00000003 Parent=0x00000001 SizeRef=1670,830 CentralNode=1 NoTabBar=1 Selected=0x1F1A625A + DockNode ID=0x00000004 Parent=0x00000001 SizeRef=250,830 Selected=0x595032EA + DockNode ID=0x00000002 Parent=0x8B93E3BD SizeRef=1920,250 Selected=0xBF88A430 + """; + + public static void applyStyle(ImGuiStyle style) { + ImGui.styleColorsDark(style); + +// for (int i = 0; i < ImGuiCol.COUNT; i++) { +// style.setColor(i, 0xFF0000FF); +// } + + style.setColor(ImGuiCol.Text, 0xFFFFFFFF); + style.setColor(ImGuiCol.TextDisabled, 0xFFAAAAAA); + style.setColor(ImGuiCol.Separator, 0xFFAAAAAA); + + int windowBg = 0xCC282020; + style.setColor(ImGuiCol.WindowBg, windowBg); + style.setColor(ImGuiCol.Border, brighten(windowBg, 150)); + + int titleBg = 0xFF1b1515; + style.setColor(ImGuiCol.TitleBg, titleBg); + style.setColor(ImGuiCol.TitleBgActive, brighten(titleBg, 140)); + + int popupBg = 0xFF382828; + style.setColor(ImGuiCol.PopupBg, popupBg); + + int frameBg = 0xAA3F3838; + style.setColor(ImGuiCol.FrameBg, frameBg); + style.setColor(ImGuiCol.FrameBgActive, darken(frameBg)); + style.setColor(ImGuiCol.FrameBgHovered, brighten(frameBg)); + + int button = 0xFFCB6800; + style.setColor(ImGuiCol.Button, button); + style.setColor(ImGuiCol.ButtonActive, darken(button)); + style.setColor(ImGuiCol.ButtonHovered, brighten(button)); + + style.setColor(ImGuiCol.CheckMark, 0xFFFB8800); + + int header = 0x80BB5F00; + style.setColor(ImGuiCol.Header, header); + style.setColor(ImGuiCol.HeaderActive, darken(header)); + style.setColor(ImGuiCol.HeaderHovered, brighten(header)); + + style.setColor(ImGuiCol.MenuBarBg, windowBg); + + style.setColor(ImGuiCol.TabUnfocusedActive, 0xCC383030); + style.setColor(ImGuiCol.TabActive, 0xFF484040); + style.setColor(ImGuiCol.ModalWindowDimBg, 0x58CCCCCC); + + if (GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_K) != 0) { + ImGui.styleColorsDark(style); + } + } + + private static int brighten(int abgr) { + return brighten(abgr, 120); + } + + private static int brighten(int abgr, int percentage) { + int alpha = (abgr >> 24) & 0xFF; + int blue = (abgr >> 16) & 0xFF; + int green = (abgr >> 8) & 0xFF; + int red = abgr & 0xFF; + + blue = Math.min(0xFF, blue * percentage/100); + green = Math.min(0xFF, green * percentage/100); + red = Math.min(0xFF, red * percentage/100); + + return FastColor.ABGR32.color(alpha, blue, green, red); + } + + private static int darken(int abgr) { + int alpha = (abgr >> 24) & 0xFF; + int blue = (abgr >> 16) & 0xFF; + int green = (abgr >> 8) & 0xFF; + int red = abgr & 0xFF; + + blue = Math.min(0xFF, blue * 4/5); + green = Math.min(0xFF, green * 4/5); + red = Math.min(0xFF, red * 4/5); + + return FastColor.ABGR32.color(alpha, blue, green, red); + } + +} 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 new file mode 100644 index 0000000..d1d82b0 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/MainMenuBar.java @@ -0,0 +1,17 @@ +package com.moulberry.flashback.editor.ui.windows; + +import imgui.ImGui; + +public class MainMenuBar { + + public static void render() { + if (ImGui.beginMainMenuBar()) { + if (ImGui.menuItem("Export")) { + StartExportWindow.open(); + } + + 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 new file mode 100644 index 0000000..6acdc9c --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java @@ -0,0 +1,232 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.mojang.blaze3d.platform.Window; +import com.moulberry.flashback.Flashback; +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.state.EditorState; +import com.moulberry.flashback.state.EditorStateCache; +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.ImGuiWindowFlags; +import imgui.type.ImFloat; +import imgui.type.ImString; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.client.Minecraft; + +import java.nio.file.Path; +import java.util.List; + +public class StartExportWindow { + + private static boolean open = 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 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 boolean useMaximumBitrate = false; + private static final ImString bitrate = ImGuiHelper.createResizableImString("20m"); + + static { + bitrate.inputData.allowedChars = "0123456789kmb"; + } + + public static void render() { + if (open) { + ImGui.openPopup("###StartExport"); + Window window = Minecraft.getInstance().getWindow(); + + // Only update the resolution if the framebuffer size changes + // This way, when users input custom resolutions it persists between opens + if (window.framebufferWidth != lastFramebufferSize[0] || window.framebufferHeight != lastFramebufferSize[1]) { + resolution[0] = window.framebufferWidth; + resolution[1] = window.framebufferHeight; + lastFramebufferSize[0] = window.framebufferWidth; + lastFramebufferSize[1] = window.framebufferHeight; + } + + open = false; + } + + if (ImGuiHelper.beginPopupModalCloseable("Export to video###StartExport", ImGuiWindowFlags.AlwaysAutoResize)) { + ImGuiHelper.separatorWithText("Capture Options"); + + ImGui.inputInt2("Resolution", resolution); + if (ImGui.inputInt2("Start/end tick", startEndTick)) { + EditorState editorState = EditorStateCache.getCurrent(); + ReplayServer replayServer = Flashback.getReplayServer(); + if (editorState != null && replayServer != null) { + editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks()); + } + } + ImGui.inputFloat("Framerate", framerate); + + ImGuiHelper.separatorWithText("Video Options"); + + VideoContainer newContainer = ImGuiHelper.enumCombo("Container", container); + if (newContainer != container) { + container = newContainer; + + boolean supported = false; + for (VideoCodec supportedCodec : container.getSupportedCodecs()) { + if (codec == supportedCodec) { + supported = true; + break; + } + } + + if (!supported) { + codec = container.getSupportedCodecs()[0]; + } + } + + VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", codec, container.getSupportedCodecs()); + if (newCodec != codec) { + codec = newCodec; + selectedEncoder[0] = 0; + } + + String[] encoders = codec.getEncoders(); + if (encoders.length > 1) { + ImGuiHelper.combo("Encoder", selectedEncoder, 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; + } + if (!useMaximumBitrate) { + ImGui.inputText("Bitrate", bitrate); + if (ImGui.isItemDeactivatedAfterEdit()) { + int numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); + bitrate.set(bitrateToString(numBitrate)); + } + } + + if (ImGui.button("Begin")) { + int numBitrate; + if (useMaximumBitrate) { + numBitrate = 0; + } else { + numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); + } + + String encoder = codec.getEncoders()[selectedEncoder[0]]; + + 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]); + + 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); + Flashback.EXPORT_JOB = new ExportJob(settings); + } + }); + + ImGui.closeCurrentPopup(); + } + + ImGuiHelper.endPopupModalCloseable(); + } + } + + private static int stringToBitrate(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 == 'k') { + modifier *= 1000; + } else if (c == 'm') { + modifier *= 1000000; + } else if (c == 'b') { + modifier *= 1000000000; + } + } + + total += number * modifier; + + return total; + } + + private static String bitrateToString(int bitrate) { + if (bitrate >= 1000000000 && bitrate == (bitrate/1000000000)*1000000000) { + return (bitrate/1000000000) + "b"; + } else if (bitrate >= 1000000 && bitrate == (bitrate/1000000)*1000000) { + return (bitrate/1000000) + "m"; + } else if (bitrate >= 1000 && bitrate == (bitrate/1000)*1000) { + return (bitrate/1000) + "k"; + } else { + return String.valueOf(bitrate); + } + } + + public static void open() { + open = true; + + EditorState editorState = EditorStateCache.getCurrent(); + + if (editorState != null && editorState.exportStartTicks >= 0) { + startEndTick[0] = editorState.exportStartTicks; + } else { + startEndTick[0] = 0; + } + if (editorState != null && editorState.exportEndTicks >= 0) { + startEndTick[1] = editorState.exportEndTicks; + } else { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer == null) { + startEndTick[1] = startEndTick[0] + 100; + } else { + startEndTick[1] = replayServer.getTotalReplayTicks(); + } + } + } + +} 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 new file mode 100644 index 0000000..68d2302 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java @@ -0,0 +1,1087 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.google.gson.reflect.TypeToken; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FlashbackGson; +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.state.EditorState; +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.keyframe.interpolation.InterpolationType; +import com.moulberry.flashback.playback.ReplayServer; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.record.FlashbackMeta; +import com.moulberry.flashback.state.KeyframeTrack; +import imgui.ImDrawList; +import imgui.ImGui; +import imgui.flag.ImGuiMouseButton; +import imgui.flag.ImGuiMouseCursor; +import imgui.flag.ImGuiPopupFlags; +import imgui.flag.ImGuiStyleVar; +import it.unimi.dsi.fastutil.ints.*; +import net.minecraft.client.Minecraft; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector2f; +import org.lwjgl.glfw.GLFW; + +import java.util.*; + +public class TimelineWindow { + + private static float zoomMinBeforeDrag = 0.0f; + private static float zoomMaxBeforeDrag = 1.0f; + private static boolean grabbedZoomBar = false; + private static boolean grabbedZoomBarResizeLeft = false; + private static boolean grabbedZoomBarResizeRight = false; + private static boolean grabbedExportBarResizeLeft = false; + private static boolean grabbedExportBarResizeRight = false; + private static boolean grabbedPlayback = false; + private static boolean grabbedKeyframe = false; + private static float grabbedKeyframeMouseX = 0; + + @Nullable + private static Vector2f dragSelectOrigin = null; + + private static final float[] speedKeyframeInput = new float[]{1.0f}; + private static final int[] timeOfDayKeyframeInput = new int[]{6000}; + + private static float mouseX; + private static float mouseY; + private static int timelineOffset; + private static int minTicks; + private static float availableTicks; + private static float timelineWidth; + private static float x; + private static float y; + private static float width; + private static float height; + + private static boolean hoveredControls; + private static boolean hoveredSkipBackwards; + private static boolean hoveredSlowDown; + private static boolean hoveredPause; + private static boolean hoveredFastForwards; + private static boolean hoveredSkipForwards; + + private static boolean zoomBarHovered; + private static int zoomBarHeight; + private static float zoomBarMin; + private static float zoomBarMax; + private static boolean zoomBarExpanded; + + private static final int minorSeparatorHeight = 10; + private static final int majorSeparatorHeight = minorSeparatorHeight * 2; + private static final int timestampHeight = 20; + private static final int middleY = timestampHeight + majorSeparatorHeight; + private static final int middleX = 240; + + private static final List selectedKeyframesList = new ArrayList<>(); + private static Keyframe editingKeyframe = null; + + 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 void render() { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer == null) { + return; + } + + ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); + boolean timelineVisible = ImGui.begin("Timeline"); + ImGuiHelper.popStyleVar(); + + if (timelineVisible) { + FlashbackMeta metadata = replayServer.getMetadata(); + EditorState editorState = EditorStateCache.get(metadata.replayIdentifier); + + ImDrawList drawList = ImGui.getWindowDrawList(); + + float maxX = ImGui.getWindowContentRegionMaxX(); + float maxY = ImGui.getWindowContentRegionMaxY(); + float minX = ImGui.getWindowContentRegionMinX(); + float minY = ImGui.getWindowContentRegionMinY(); + + x = ImGui.getWindowPosX() + minX; + y = ImGui.getWindowPosY() + minY; + width = maxX - minX; + height = maxY - minY; + + if (width < 1 || height < 1) { + ImGui.end(); + return; + } + + selectedKeyframesList.removeIf(k -> !k.checkValid(editorState)); + + mouseX = ImGui.getMousePosX(); + mouseY = ImGui.getMousePosY(); + + int currentReplayTick = replayServer.getReplayTick(); + int totalTicks = replayServer.getTotalReplayTicks(); + + timelineWidth = width - middleX; + float shownTicks = Math.round((editorState.zoomMax - editorState.zoomMin) * totalTicks); + int targetMajorSize = 60; + + float targetTicksPerMajor = 1f / (timelineWidth / shownTicks / targetMajorSize); + int minorsPerMajor; + int ticksPerMinor; + boolean showSubSeconds; + + if (targetTicksPerMajor < 5) { + minorsPerMajor = 5; + ticksPerMinor = 1; + showSubSeconds = true; + } else if (targetTicksPerMajor < 8) { + minorsPerMajor = 5; + ticksPerMinor = 2; + showSubSeconds = true; + } else { + minorsPerMajor = 4; + ticksPerMinor = (int) Math.ceil(targetTicksPerMajor / 20 ) * 20 / minorsPerMajor; + showSubSeconds = false; + } + + int majorSnap = ticksPerMinor * minorsPerMajor; + minTicks = Math.round(editorState.zoomMin * totalTicks / majorSnap) * majorSnap; + + float minorSeparatorWidth = (timelineWidth / shownTicks) * ticksPerMinor; + availableTicks = timelineWidth / minorSeparatorWidth * ticksPerMinor; + + float errorTicks = editorState.zoomMin*totalTicks - minTicks; + int errorOffset = (int)(-errorTicks/ticksPerMinor*minorSeparatorWidth); + timelineOffset = middleX + errorOffset; + + int cursorTicks = currentReplayTick; + if (grabbedPlayback) { + cursorTicks = timelineXToReplayTick(mouseX); + } else if (replayServer.jumpToTick >= 0) { + cursorTicks = replayServer.jumpToTick; + } + + 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; + + zoomBarExpanded = false; + if (mouseY >= y + height - zoomBarHeight *2 && mouseY <= y + height || grabbedZoomBar) { + zoomBarHeight *= 2; + zoomBarExpanded = true; + } + zoomBarHovered = mouseY >= y + height - zoomBarHeight && mouseY <= y + height && + mouseX >= x + zoomBarMin && mouseX <= x + zoomBarMax; + + renderKeyframeElements(replayServer, editorState, x, y + middleY, cursorTicks, middleX); + + drawList.pushClipRect(x + middleX, y, x + width, y + height); + + renderExportBar(editorState, drawList); + + drawList.pushClipRect(x + middleX, y + middleY, x + width, y + height); + renderKeyframes(editorState, x, y + middleY, mouseX, minTicks, availableTicks, totalTicks); + drawList.popClipRect(); + + renderSeparators(minorsPerMajor, x, middleX, minorSeparatorWidth, errorOffset, width, drawList, y, timestampHeight, middleY, minTicks, ticksPerMinor, showSubSeconds, majorSeparatorHeight, minorSeparatorHeight); + renderPlaybackHead(cursorX, x, middleX, width, cursorTicks, currentReplayTick, drawList, y, middleY, timestampHeight, height, zoomBarHeight); + + if (dragSelectOrigin != null) { + drawList.pushClipRect(x + middleX, y + middleY, x + width, y + height); + drawList.addRectFilled(Math.min(mouseX, dragSelectOrigin.x), + Math.min(mouseY, dragSelectOrigin.y), Math.max(mouseX, dragSelectOrigin.x), + Math.max(mouseY, dragSelectOrigin.y), 0x80DD6000); + drawList.addRect(Math.min(mouseX, dragSelectOrigin.x), + Math.min(mouseY, dragSelectOrigin.y), Math.max(mouseX, dragSelectOrigin.x), + Math.max(mouseY, dragSelectOrigin.y), 0xFFDD6000); + drawList.popClipRect(); + } + + drawList.popClipRect(); + + // Timeline end line + if (editorState.zoomMax >= 1.0) { + drawList.addLine(x + width -2, y + timestampHeight, x + width -2, y + height - zoomBarHeight, -1); + } + // Middle divider (x) + drawList.addLine(x + middleX, y + timestampHeight, x + middleX, y + height, -1); + + // Middle divider (y) + drawList.addLine(0, y + middleY, width, y + middleY, -1); + + // Zoom Bar + if (zoomBarExpanded) { + drawList.addRectFilled(x + middleX +1, y + height - zoomBarHeight, x + width, y + height, 0xFF404040, zoomBarHeight); + } + if (zoomBarHovered || grabbedZoomBar) { + drawList.addRectFilled(x + zoomBarMin + zoomBarHeight /2f, y + height - zoomBarHeight, x + zoomBarMax - zoomBarHeight /2f, y + height, -1, zoomBarHeight); + + // Left/right resize + drawList.addCircleFilled(x + zoomBarMin + zoomBarHeight /2f, y + height - zoomBarHeight /2f, zoomBarHeight /2f, 0xffaaaa00); + drawList.addCircleFilled(x + zoomBarMax - zoomBarHeight /2f, y + height - zoomBarHeight /2f, zoomBarHeight /2f, 0xffaaaa00); + } else { + drawList.addRectFilled(x + zoomBarMin, y + height - zoomBarHeight, x + zoomBarMax, y + height, -1, zoomBarHeight); + } + + // Pause/play button + int controlSize = 24; + int controlsY = (int) y + middleY/2 - controlSize/2; + + // Skip backwards + int skipBackwardsX = (int) x + middleX/6 - controlSize/2; + drawList.addTriangleFilled(skipBackwardsX + controlSize/3f, controlsY + controlSize/2f, + skipBackwardsX + controlSize, controlsY, + skipBackwardsX + controlSize, controlsY + controlSize, -1); + drawList.addRectFilled(skipBackwardsX, controlsY, + skipBackwardsX + controlSize/3f, controlsY+controlSize, -1); + + // Slow down + int slowDownX = (int) x + middleX*2/6 - controlSize/2; + drawList.addTriangleFilled(slowDownX, controlsY + controlSize/2f, + slowDownX + controlSize/2f, controlsY, + slowDownX + controlSize/2f, controlsY+controlSize, -1); + drawList.addTriangleFilled(slowDownX + controlSize/2f, controlsY + controlSize/2f, + slowDownX + controlSize, controlsY, + slowDownX + controlSize, controlsY + controlSize, -1); + + int pauseX = (int) x + middleX/2 - controlSize/2; + if (replayServer.replayPaused) { + // Play button + drawList.addTriangleFilled(pauseX + controlSize/12f, controlsY, + pauseX + controlSize, controlsY + controlSize/2f, + pauseX + controlSize/12f, controlsY + controlSize, + -1); + } else { + // Pause button + drawList.addRectFilled(pauseX, controlsY, + pauseX + controlSize/3f, controlsY + controlSize, -1); + drawList.addRectFilled(pauseX + controlSize*2f/3f, controlsY, + pauseX + controlSize, controlsY + controlSize, -1); + } + + // Fast-forward + int fastForwardsX = (int) x + middleX*4/6 - controlSize/2; + drawList.addTriangleFilled(fastForwardsX, controlsY, + fastForwardsX + controlSize/2f, controlsY + controlSize/2f, + fastForwardsX, controlsY+controlSize, -1); + drawList.addTriangleFilled(fastForwardsX + controlSize/2f, controlsY, + fastForwardsX + controlSize, controlsY + controlSize/2f, + fastForwardsX + controlSize/2f, controlsY + controlSize, -1); + + // Skip forward + int skipForwardsX = (int) x + middleX*5/6 - controlSize/2; + drawList.addTriangleFilled(skipForwardsX, controlsY, + skipForwardsX + controlSize*2f/3f, controlsY + controlSize/2f, + skipForwardsX, controlsY + controlSize, -1); + drawList.addRectFilled(skipForwardsX + controlSize*2f/3f, controlsY, + skipForwardsX + controlSize, controlsY+controlSize, -1); + + + hoveredControls = mouseY > controlsY && mouseY < controlsY + controlSize; + hoveredSkipBackwards = hoveredControls && mouseX >= skipBackwardsX && mouseX <= skipBackwardsX+controlSize; + hoveredSlowDown = hoveredControls && mouseX >= slowDownX && mouseX <= slowDownX+controlSize; + hoveredPause = hoveredControls && mouseX >= pauseX && mouseX <= pauseX+controlSize; + 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"); + } + } 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(); + } + + handleKeyPresses(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); + } else if (ImGui.isMouseDragging(ImGuiMouseButton.Left)) { + if (grabbedExportBarResizeLeft) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + + int target = timelineXToReplayTick(mouseX); + editorState.setExportTicks(target, -1, totalTicks); + } + if (grabbedExportBarResizeRight) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + + int target = timelineXToReplayTick(mouseX); + editorState.setExportTicks(-1, target, totalTicks); + } + if (zoomBarWidth > 1f && grabbedZoomBar) { + float dx = ImGui.getMouseDragDeltaX(); + float factor = dx / zoomBarWidth; + + if (grabbedZoomBarResizeLeft) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + editorState.zoomMin = Math.max(0, Math.min(editorState.zoomMax-0.01f, zoomMinBeforeDrag + factor)); + } else if (grabbedZoomBarResizeRight) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + editorState.zoomMax = Math.max(editorState.zoomMin+0.01f, Math.min(1, zoomMaxBeforeDrag + factor)); + } else { + ImGui.setMouseCursor(ImGuiMouseCursor.Hand); + + float zoomSize = zoomMaxBeforeDrag - zoomMinBeforeDrag; + if (factor < 0) { + editorState.zoomMin = Math.max(0, zoomMinBeforeDrag + factor); + editorState.zoomMax = editorState.zoomMin + zoomSize; + } else if (factor > 0) { + editorState.zoomMax = Math.min(1, zoomMaxBeforeDrag + factor); + editorState.zoomMin = editorState.zoomMax - zoomSize; + } + } + editorState.dirty = true; + } + if (grabbedPlayback) { + int desiredTick = timelineXToReplayTick(mouseX); + + if (desiredTick > currentReplayTick) { + replayServer.goToReplayTick(desiredTick); + } + + replayServer.replayPaused = true; + } + } else if (!ImGui.isAnyMouseDown()) { + releaseGrabbed(editorState, replayServer); + } + } + ImGui.end(); + } + + private static void handleKeyPresses(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 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); + + if (pressedIn || pressedOut) { + int start = -1; + int end = -1; + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_I)) { + start = cursorTicks; + } + if (ImGui.isKeyPressed(GLFW.GLFW_KEY_O)) { + end = cursorTicks; + } + editorState.setExportTicks(start, end, totalTicks); + } + + if (pressedCopy && !selectedKeyframesList.isEmpty()) { + List tracks = new ArrayList<>(); + + int minTick = totalTicks; + int keyframeCount = 0; + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + for (int keyframeTick : selectedKeyframes.keyframeTicks()) { + minTick = Math.min(minTick, keyframeTick); + keyframeCount += 1; + } + } + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + + TreeMap> keyframes = new TreeMap<>(); + for (int tick : selectedKeyframes.keyframeTicks()) { + Keyframe keyframe = keyframeTrack.keyframesByTick.get(tick); + keyframes.put(tick - minTick, keyframe); + } + + tracks.add(new SavedTrack(selectedKeyframes.type(), selectedKeyframes.trackIndex(), !keyframeTrack.enabled, keyframes)); + } + + String serialized = FlashbackGson.COMPRESSED.toJson(tracks); + GLFW.glfwSetClipboardString(Minecraft.getInstance().getWindow().getWindow(), serialized); + + ReplayUI.setInfoOverlay("Copied " + keyframeCount + " keyframe(s) to clipboard"); + } + + if (pressedPaste) { + try { + String clipboard = GLFW.glfwGetClipboardString(Minecraft.getInstance().getWindow().getWindow()); + if (clipboard != null && clipboard.startsWith("[")) { + TypeToken typeToken = TypeToken.getParameterized(List.class, SavedTrack.class); + + // noinspection unchecked + List tracks = (List) FlashbackGson.COMPRESSED.fromJson(clipboard, typeToken); + + int count = 0; + for (SavedTrack savedTrack : tracks) { + count += savedTrack.applyToEditorState(editorState, cursorTicks, totalTicks); + } + + ReplayUI.setInfoOverlay("Pasted " + count + " keyframe(s) from clipboard"); + } + } catch (Exception ignored) {} + } + } + + private static void handleClick(EditorState editorState, ReplayServer replayServer) { + releaseGrabbed(editorState, replayServer); + List oldSelectedKeyframesList = new ArrayList<>(selectedKeyframesList); + selectedKeyframesList.clear(); + + boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); + boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); + + if (hoveredControls) { + // Skip backwards + if (hoveredSkipBackwards) { + replayServer.goToReplayTick(0); + return; + } + + // Slow down + if (hoveredSlowDown) { + float highest = replayTickSpeeds[0]; + float currentTickRate = replayServer.desiredTickRate; + + for (float replayTickSpeed : replayTickSpeeds) { + if (replayTickSpeed >= currentTickRate) { + break; + } + highest = replayTickSpeed; + } + + replayServer.desiredTickRate = highest; + return; + } + + // Pause button + if (hoveredPause) { + replayServer.replayPaused = !replayServer.replayPaused; + return; + } + + // Fast-forward + if (hoveredFastForwards) { + float lowest = replayTickSpeeds[replayTickSpeeds.length - 1]; + float currentTickRate = replayServer.desiredTickRate; + + for (int i = replayTickSpeeds.length - 1; i >= 0; i--) { + float replayTickSpeed = replayTickSpeeds[i]; + if (replayTickSpeed <= currentTickRate) { + break; + } + lowest = replayTickSpeed; + } + + replayServer.desiredTickRate = lowest; + return; + } + + // Skip forward + if (hoveredSkipForwards) { + replayServer.goToReplayTick(replayServer.getTotalReplayTicks()); + return; + } + } + + // Timeline + if (mouseY > y && mouseY < y + middleY && mouseX > x + middleX && mouseX < x + width) { + if (editorState.exportStartTicks >= 0 && editorState.exportEndTicks >= 0 && mouseY > y + timestampHeight) { + int exportStartX = replayTickToTimelineX(editorState.exportStartTicks); + int exportEndX = replayTickToTimelineX(editorState.exportEndTicks); + + Utils.ClosestElement closestElement = Utils.findClosest(mouseX, exportStartX, exportEndX, 5); + + switch (closestElement) { + case LEFT -> grabbedExportBarResizeLeft = leftClicked; + case RIGHT -> grabbedExportBarResizeRight = leftClicked; + case NONE -> { + replayServer.replayPaused = true; + grabbedPlayback = leftClicked; + } + } + } else { + replayServer.replayPaused = true; + grabbedPlayback = leftClicked; + } + return; + } + + if (zoomBarHovered) { + if (mouseX <= x + zoomBarMin + zoomBarHeight) { + grabbedZoomBarResizeLeft = leftClicked; + } else if (mouseX >= x + zoomBarMax - zoomBarHeight) { + grabbedZoomBarResizeRight = leftClicked; + } + grabbedZoomBar = leftClicked; + zoomMinBeforeDrag = editorState.zoomMin; + zoomMaxBeforeDrag = editorState.zoomMax; + return; + } else if (zoomBarExpanded && mouseX >= x + middleX && mouseX <= x + width) { + float zoomSize = editorState.zoomMax - editorState.zoomMin; + float targetZoom = (mouseX - (x + middleX))/(x + width - (x + middleX)); + editorState.zoomMin = targetZoom - zoomSize/2f; + editorState.zoomMax = targetZoom + zoomSize/2f; + if (editorState.zoomMax > 1.0f) { + editorState.zoomMax = 1.0f; + editorState.zoomMin = editorState.zoomMax - zoomSize; + } else if (editorState.zoomMin < 0.0f) { + editorState.zoomMin = 0.0f; + editorState.zoomMax = editorState.zoomMin + zoomSize; + } + editorState.dirty = true; + + grabbedZoomBar = leftClicked; + zoomMinBeforeDrag = editorState.zoomMin; + zoomMaxBeforeDrag = editorState.zoomMax; + return; + } + + // Tracks + if (mouseY > y + middleY && mouseY < y + height && mouseX > x + middleX && mouseX < x + width) { + float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); + + int trackIndex = (int) Math.max(0, Math.floor((mouseY - (y + middleY + 2))/lineHeight)); + + if (trackIndex >= 0 && trackIndex < editorState.keyframeTracks.size()) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + + int tick = timelineXToReplayTick(mouseX); + + 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); + if (closest != null) { + boolean reuseOld = false; + for (SelectedKeyframes selectedKeyframes : oldSelectedKeyframesList) { + if (selectedKeyframes.trackIndex() == trackIndex) { + reuseOld = selectedKeyframes.keyframeTicks().contains((int) closest.getKey()); + break; + } + } + + if (reuseOld) { + selectedKeyframesList.addAll(oldSelectedKeyframesList); + } else { + IntSet intSet = new IntOpenHashSet(); + intSet.add((int) closest.getKey()); + selectedKeyframesList.add(new SelectedKeyframes(keyframeTrack.keyframeType, trackIndex, intSet)); + } + + if (leftClicked) { + grabbedKeyframe = true; + grabbedKeyframeMouseX = mouseX; + } else if (rightClicked) { + ImGui.openPopup("##KeyframePopup"); + editingKeyframe = closest.getValue(); + } + + return; + } + } + + dragSelectOrigin = new Vector2f(mouseX, mouseY); + } + } + + private static void renderExportBar(EditorState editorState, ImDrawList drawList) { + if (editorState.exportStartTicks >= 0 && editorState.exportEndTicks >= 0) { + int exportStartX = replayTickToTimelineX(editorState.exportStartTicks); + int exportEndX = replayTickToTimelineX(editorState.exportEndTicks); + drawList.addRectFilled(x +exportStartX, y + timestampHeight, x +exportEndX, y + middleY, 0x60FFAA00); + drawList.addLine(x +exportStartX, y + timestampHeight, x +exportStartX, y + middleY, 0xFFFFAA00, 4); + drawList.addLine(x +exportEndX, y + timestampHeight, x +exportEndX, y + middleY, 0xFFFFAA00, 4); + + if (mouseY > y + timestampHeight && mouseY < y + middleY) { + if ((mouseX >= exportStartX-5 && mouseX <= exportStartX+5) || (mouseX >= exportEndX-5 && mouseX <= exportEndX+5)) { + ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); + } + } + } + } + + private static void renderKeyframeOptionsPopup(EditorState editorState) { + if (editingKeyframe == null || selectedKeyframesList.isEmpty()) { + editingKeyframe = null; + 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.interpolationType(interpolationType); + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + for (int tick : selectedKeyframes.keyframeTicks()) { + track.keyframesByTick.get(tick).interpolationType(interpolationType); + } + } + + editorState.dirty = true; + } + + boolean multiple = selectedKeyframesList.size() >= 2 || selectedKeyframesList.getFirst().keyframeTicks().size() >= 2; + + if (ImGui.button(multiple ? "Remove All" : "Remove")) { + ImGui.closeCurrentPopup(); + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + KeyframeTrack track = editorState.keyframeTracks.get(selectedKeyframes.trackIndex()); + for (int tick : selectedKeyframes.keyframeTicks()) { + track.keyframesByTick.remove(tick); + } + } + editorState.keyframeTracks.removeIf(track -> track.keyframesByTick.isEmpty()); + + selectedKeyframesList.clear(); + editingKeyframe = null; + editorState.dirty = true; + } + } + + private static void releaseGrabbed(EditorState editorState, ReplayServer replayServer) { + grabbedZoomBar = false; + grabbedZoomBarResizeLeft = false; + grabbedZoomBarResizeRight = false; + grabbedExportBarResizeLeft = false; + grabbedExportBarResizeRight = false; + + if (dragSelectOrigin != null) { + float dragMinX = Math.min(dragSelectOrigin.x, mouseX); + float dragMinY = Math.min(dragSelectOrigin.y, mouseY); + float dragMaxX = Math.max(dragSelectOrigin.x, mouseX); + float dragMaxY = Math.max(dragSelectOrigin.y, mouseY); + + float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); + int minTrackIndex = (int) Math.floor((dragMinY - (y + middleY + 2))/lineHeight); + int maxTrackIndex = (int) Math.floor((dragMaxY - (y + middleY + 2))/lineHeight); + minTrackIndex = Math.max(0, minTrackIndex); + maxTrackIndex = Math.min(editorState.keyframeTracks.size()-1, maxTrackIndex); + + for (int trackIndex = minTrackIndex; trackIndex <= maxTrackIndex; trackIndex++) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + + int minTick = timelineXToReplayTick(dragMinX - KEYFRAME_SIZE); + int maxTick = timelineXToReplayTick(dragMaxX + KEYFRAME_SIZE); + + IntSet intSet = new IntOpenHashSet(); + + for (int tick = minTick; tick <= maxTick; tick++) { + var entry = keyframeTrack.keyframesByTick.ceilingEntry(tick); + if (entry == null || entry.getKey() > maxTick) { + break; + } + tick = entry.getKey(); + intSet.add(tick); + } + + if (!intSet.isEmpty()) { + selectedKeyframesList.add(new SelectedKeyframes(keyframeTrack.keyframeType, trackIndex, intSet)); + } + } + + dragSelectOrigin = null; + } + + if (grabbedPlayback) { + int desiredTick = timelineXToReplayTick(mouseX); + replayServer.goToReplayTick(desiredTick); + replayServer.replayPaused = true; + grabbedPlayback = false; + } + + if (grabbedKeyframe) { + int grabbedDelta = timelineDeltaToReplayTickDelta(mouseX - grabbedKeyframeMouseX); + int totalTicks = replayServer.getTotalReplayTicks(); + + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + int trackIndex = selectedKeyframes.trackIndex(); + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + + IntList selectedTicks = new IntArrayList(selectedKeyframes.keyframeTicks()); + + // Sorting because clamping can result in overlaps + selectedTicks.sort(mouseX < grabbedKeyframeMouseX ? IntComparators.NATURAL_COMPARATOR : IntComparators.OPPOSITE_COMPARATOR); + + selectedKeyframes.keyframeTicks().clear(); + + Int2ObjectMap> newKeyframes = new Int2ObjectOpenHashMap<>(); + + for (int i = 0; i < selectedTicks.size(); i++) { + int tick = selectedTicks.getInt(i); + + Keyframe keyframe = keyframeTrack.keyframesByTick.remove(tick); + Objects.requireNonNull(keyframe); + + int newTick = tick + grabbedDelta; + newTick = Math.max(0, Math.min(totalTicks, newTick)); + + newKeyframes.put(newTick, keyframe); + } + + for (Int2ObjectMap.Entry> entry : newKeyframes.int2ObjectEntrySet()) { + keyframeTrack.keyframesByTick.put(entry.getIntKey(), entry.getValue()); + selectedKeyframes.keyframeTicks().add(entry.getIntKey()); + } + + } + +// 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; + } + } + + + 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(); + + ImDrawList drawList = ImGui.getWindowDrawList(); + ImDrawList foregroundDrawList = ImGui.getForegroundDrawList(); + + foregroundDrawList.pushClipRect(x + middleX, y, x + width, y + height); + + int grabbedDelta = 0; + if (grabbedKeyframe) { + grabbedDelta = timelineDeltaToReplayTickDelta(mouseX - grabbedKeyframeMouseX); + + if (grabbedDelta > 0) { + ImGuiHelper.drawTooltip("+" + grabbedDelta + " ticks"); + } else if (grabbedDelta < 0) { + ImGuiHelper.drawTooltip(grabbedDelta + " ticks"); + } + } + + for (int trackIndex = 0; trackIndex < editorState.keyframeTracks.size(); trackIndex++) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(trackIndex); + + TreeMap> keyframeTimes = keyframeTrack.keyframesByTick; + + SelectedKeyframes selectedKeyframesForTrack = null; + for (SelectedKeyframes selectedKeyframes : selectedKeyframesList) { + if (selectedKeyframes.trackIndex() == trackIndex) { + selectedKeyframesForTrack = selectedKeyframes; + break; + } + } + + for (int tick = minTicks; tick <= minTicks + availableTicks; tick++) { + var entry = keyframeTimes.ceilingEntry(tick); + if (entry == null || entry.getKey() > minTicks + availableTicks) { + break; + } + tick = entry.getKey(); + + Keyframe keyframe = entry.getValue(); + + if (selectedKeyframesForTrack != null && selectedKeyframesForTrack.keyframeTicks().contains(tick)) { + int newTick = tick + grabbedDelta; + newTick = Math.max(0, Math.min(totalTicks, newTick)); + + int keyframeX = replayTickToTimelineX(newTick); + + float midX = x + keyframeX; + float midY = y + 2 + (trackIndex+0.5f) * lineHeight; + + drawKeyframe(foregroundDrawList, keyframe.interpolationType(), midX, midY, keyframeTrack.enabled ? 0xFF0000FF : 0x800000FF); + } else { + int keyframeX = replayTickToTimelineX(tick); + + float midX = x + keyframeX; + float midY = y + 2 + (trackIndex+0.5f) * lineHeight; + + drawKeyframe(drawList, keyframe.interpolationType(), midX, midY, keyframeTrack.enabled ? -1 : 0x80FFFFFF); + } + } + } + + foregroundDrawList.popClipRect(); + } + + private static void drawKeyframe(ImDrawList drawList, InterpolationType interpolationType, float x, float y, int colour) { + int easeSize = KEYFRAME_SIZE / 5; + switch (interpolationType) { + case SMOOTH -> { + drawList.addCircleFilled(x, y, KEYFRAME_SIZE, colour); + } + case LINEAR -> { + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y, x, y - KEYFRAME_SIZE, x, y + KEYFRAME_SIZE, colour); + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y, x, y + KEYFRAME_SIZE, x, y - KEYFRAME_SIZE, colour); + } + case EASE_IN -> { + // Left inverted triangle + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y, colour); + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y + KEYFRAME_SIZE, x - easeSize, y, x - easeSize, y + KEYFRAME_SIZE, colour); + // Right triangle + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y - KEYFRAME_SIZE, colour); + // Center + drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); + } + case EASE_OUT -> { + // Left triangle + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y + KEYFRAME_SIZE, colour); + // Right inverted triangle + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + easeSize, y, x + easeSize, y - KEYFRAME_SIZE, colour); + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y, colour); + // Center + drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); + } + case EASE_IN_OUT -> { + // Left inverted triangle + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x - easeSize, y - KEYFRAME_SIZE, x - easeSize, y, colour); + drawList.addTriangleFilled(x - KEYFRAME_SIZE, y + KEYFRAME_SIZE, x - easeSize, y, x - easeSize, y + KEYFRAME_SIZE, colour); + // Right inverted triangle + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + easeSize, y, x + easeSize, y - KEYFRAME_SIZE, colour); + drawList.addTriangleFilled(x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, x + easeSize, y, colour); + // Center + drawList.addRectFilled(x - easeSize, y - KEYFRAME_SIZE, x + easeSize, y + KEYFRAME_SIZE, colour); + } + case HOLD -> { + drawList.addRectFilled(x - KEYFRAME_SIZE, y - KEYFRAME_SIZE, x + KEYFRAME_SIZE, y + KEYFRAME_SIZE, colour); + } + } + } + + private static void renderKeyframeElements(ReplayServer replayServer, EditorState editorState, float x, float y, int cursorTicks, int middleX) { + ImGui.setCursorScreenPos(x + 8, y + 6); + + int keyframeTrackToClear = -1; + + ImDrawList drawList = ImGui.getWindowDrawList(); + + 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); + + ImGui.setCursorPosX(8); + + if (keyframeTrack.enabled) { + ImGui.text(keyframeType.name); + } else { + ImGui.textDisabled(keyframeType.name); + } + + ImGui.sameLine(); + + float buttonX = middleX - (buttonSize + spacingX) * 3; + 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()); + case SPEED -> { + speedKeyframeInput[0] = replayServer.desiredTickRate / 20.0f; + ImGui.openPopup("##EnterSpeed"); + yield null; + } + case TIME_OF_DAY -> { + timeOfDayKeyframeInput[0] = (int)(Minecraft.getInstance().level.getDayTime() % 24000); + ImGui.openPopup("##EnterTime"); + yield null; + } + }; + if (keyframe != null) { + keyframeTimes.put(cursorTicks, keyframe); + } + } + drawList.addRectFilled(buttonX + 2, buttonY + buttonSize/2 - 1, buttonX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); + drawList.addRectFilled(buttonX + buttonSize/2 - 1, buttonY + 2, buttonX + buttonSize/2 + 1, buttonY + buttonSize - 2, -1); + ImGuiHelper.tooltip("Add keyframe"); + + if (ImGui.beginPopup("##EnterSpeed")) { + ImGui.sliderFloat("Speed", speedKeyframeInput, 0.1f, 10f); + if (ImGui.button("Add")) { + keyframeTimes.put(cursorTicks, new TickrateKeyframe(speedKeyframeInput[0] * 20.0f)); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + if (ImGui.beginPopup("##EnterTime")) { + ImGui.sliderInt("Time", timeOfDayKeyframeInput, 0, 24000); + if (ImGui.button("Add")) { + keyframeTimes.put(cursorTicks, new TimeOfDayKeyframe(timeOfDayKeyframeInput[0])); + ImGui.closeCurrentPopup(); + } + ImGui.sameLine(); + if (ImGui.button("Cancel")) { + ImGui.closeCurrentPopup(); + } + ImGui.endPopup(); + } + + ImGui.sameLine(); + + buttonX += buttonSize + spacingX; + ImGui.setCursorPosX(buttonX); + if (ImGui.button("##Clear", buttonSize, buttonSize)) { + keyframeTrackToClear = trackIndex; + } + drawList.addRectFilled(buttonX + 2, buttonY + buttonSize/2 - 1, buttonX + buttonSize - 2, buttonY + buttonSize/2 + 1, -1); + ImGuiHelper.tooltip("Remove all keyframes"); + + ImGui.sameLine(); + + buttonX += buttonSize + spacingX; + ImGui.setCursorPosX(buttonX); + if (ImGui.button("##ToggleEnabled", buttonSize, buttonSize)) { + keyframeTrack.enabled = !keyframeTrack.enabled; + } + if (keyframeTrack.enabled) { + drawList.addCircleFilled(buttonX + buttonSize/2, buttonY + buttonSize/2, buttonSize/3, -1); + ImGuiHelper.tooltip("Disable keyframe track"); + } else { + drawList.addCircle(buttonX + buttonSize/2, buttonY + buttonSize/2, buttonSize/3, -1, 16, 2); + ImGuiHelper.tooltip("Enable keyframe track"); + } + + ImGui.separator(); + + ImGui.popID(); + } + + if (keyframeTrackToClear >= 0) { + editorState.keyframeTracks.remove(keyframeTrackToClear); + editorState.dirty = true; + selectedKeyframesList.clear(); + } + + ImGui.setCursorPosX(8); + if (editorState.keyframeTracks.size() < KeyframeType.KEYFRAME_TYPES.length && 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; + ImGui.closeCurrentPopup(); + } + } + ImGui.endPopup(); + } + } + + private static void renderSeparators(int minorsPerMajor, float x, int middleX, float minorSeparatorWidth, int errorOffset, float width, ImDrawList drawList, float y, int timestampHeight, int middleY, int minTicks, int ticksPerMinor, boolean showSubSeconds, int majorSeparatorHeight, int minorSeparatorHeight) { + int minor = -minorsPerMajor; + while (true) { + float h = x + middleX + minorSeparatorWidth *minor; + int hi = (int) (h + errorOffset); + + if (hi >= x + width) { + break; + } + + if (minor % minorsPerMajor == 0) { + drawList.addLine(hi, y + timestampHeight, hi, y + middleY, -1); + + int ticks = minTicks + minor* ticksPerMinor; + String timestamp = ticksToTimestamp(ticks); + drawList.addText(hi, y, -1, timestamp); + if (showSubSeconds) { + float timestampWidth = ImGuiHelper.calcTextWidth(timestamp); + drawList.addText(hi+(int)Math.ceil(timestampWidth), y, 0xFF808080, "/"+(ticks % 20)); + } + } else { + drawList.addLine(hi, y + timestampHeight +(majorSeparatorHeight - minorSeparatorHeight), hi, y + middleY, -1); + } + + minor += 1; + } + } + + private static void renderPlaybackHead(int cursorX, float x, int middleX, float width, int cursorTicks, int currentReplayTick, ImDrawList drawList, float y, int middleY, int timestampHeight, float height, int zoomBarHeight) { + if (cursorX > x + middleX -10 && cursorX < x + width +10) { + int colour = -1; + if (cursorTicks < currentReplayTick) { + colour = 0x80FFFFFF; + } + + drawList.addTriangleFilled(x + cursorX, y + middleY, x + cursorX -10, y + timestampHeight +5, + x + cursorX +10, y + timestampHeight +5, colour); + drawList.addRectFilled(x + cursorX -1, y + middleY -2, x + cursorX +1, y + height - zoomBarHeight, colour); + } + } + + private static int replayTickToTimelineX(int tick) { + return timelineOffset + (int) ((tick - minTicks) / availableTicks * timelineWidth); + } + + private static int timelineXToReplayTick(float x) { + float relativeX = x - timelineOffset; + float amount = Math.max(0, Math.min(1, relativeX/timelineWidth)); + int numTicks = Math.round(amount * availableTicks); + return minTicks + numTicks; + } + + private static int timelineDeltaToReplayTickDelta(float x) { + return Math.round(x / timelineWidth * availableTicks); + } + + private static String ticksToTimestamp(int ticks) { + int seconds = ticks/20; + int minutes = seconds/60; + int hours = minutes/60; + + if (hours == 0) { + return String.format("%02d:%02d", minutes, seconds % 60); + } else { + return String.format("%02d:%02d:%02d", hours, minutes % 60, seconds % 60); + } + } + +} 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 new file mode 100644 index 0000000..bb04f3b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java @@ -0,0 +1,121 @@ +package com.moulberry.flashback.editor.ui.windows; + +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.combo_options.Sizing; +import com.moulberry.flashback.editor.ui.ImGuiHelper; +import imgui.ImGui; +import net.minecraft.client.Minecraft; + +public class VisualsWindow { + + private static final float[] floatBuffer = new float[]{0}; + private static final int[] intBuffer = new int[]{0}; + + public static void render() { + if (ImGui.begin("Visuals")) { + ImGuiHelper.separatorWithText("GUI"); + + if (ImGui.checkbox("Chat", ReplayVisuals.showChat)) { + ReplayVisuals.showChat = !ReplayVisuals.showChat; + } + if (ImGui.checkbox("Boss Bar", ReplayVisuals.showBossBar)) { + ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar; + } + if (ImGui.checkbox("Title Text", ReplayVisuals.showTitleText)) { + ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText; + } + if (ImGui.checkbox("Scoreboard", ReplayVisuals.showScoreboard)) { + ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard; + } + if (ImGui.checkbox("Action Bar", ReplayVisuals.showActionBar)) { + ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar; + } + + ImGuiHelper.separatorWithText("World"); + + if (ImGui.checkbox("Render Blocks", ReplayVisuals.renderBlocks)) { + ReplayVisuals.renderBlocks = !ReplayVisuals.renderBlocks; + } + + if (ImGui.checkbox("Render Entities", ReplayVisuals.renderEntities)) { + ReplayVisuals.renderEntities = !ReplayVisuals.renderEntities; + } + + if (ImGui.checkbox("Render Players", ReplayVisuals.renderPlayers)) { + ReplayVisuals.renderPlayers = !ReplayVisuals.renderPlayers; + } + + if (ImGui.checkbox("Render Particles", ReplayVisuals.renderParticles)) { + ReplayVisuals.renderParticles = !ReplayVisuals.renderParticles; + } + + if (ImGui.checkbox("Render Sky", ReplayVisuals.renderSky)) { + ReplayVisuals.renderSky = !ReplayVisuals.renderSky; + } + + if (ImGui.checkbox("Render Nametags", ReplayVisuals.renderNametags)) { + ReplayVisuals.renderNametags = !ReplayVisuals.renderNametags; + } + + ImGuiHelper.separatorWithText("Overrides"); + + // Fog distance + if (ImGui.checkbox("Override Fog", ReplayVisuals.overrideFog)) { + ReplayVisuals.overrideFog = !ReplayVisuals.overrideFog; + } + if (ReplayVisuals.overrideFog) { + floatBuffer[0] = ReplayVisuals.overrideFogStart; + if (ImGui.sliderFloat("Start", floatBuffer, 0.0f, 512.0f)) { + ReplayVisuals.overrideFogStart = floatBuffer[0]; + } + + floatBuffer[0] = ReplayVisuals.overrideFogEnd; + if (ImGui.sliderFloat("End", floatBuffer, 0.0f, 512.0f)) { + ReplayVisuals.overrideFogEnd = floatBuffer[0]; + } + } + + // FOV + if (ImGui.checkbox("Override FOV", ReplayVisuals.overrideFov)) { + ReplayVisuals.overrideFov = !ReplayVisuals.overrideFov; + } + if (ReplayVisuals.overrideFov) { + floatBuffer[0] = ReplayVisuals.overrideFovAmount; + if (ImGui.sliderFloat("FOV", floatBuffer, 0.1f, 110.0f, "%.1f")) { + ReplayVisuals.setFov(floatBuffer[0]); + } + } + + // Time + if (ImGui.checkbox("Override Time", ReplayVisuals.overrideTimeOfDay >= 0)) { + if (ReplayVisuals.overrideTimeOfDay >= 0) { + ReplayVisuals.overrideTimeOfDay = -1; + } else { + ReplayVisuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000); + } + } + if (ReplayVisuals.overrideTimeOfDay >= 0) { + intBuffer[0] = (int) ReplayVisuals.overrideTimeOfDay; + if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) { + ReplayVisuals.overrideTimeOfDay = intBuffer[0]; + } + } + + ImGuiHelper.separatorWithText("Other"); + + if (ImGui.checkbox("Rule of Thirds Guide", ReplayVisuals.ruleOfThirdsGuide)) { + ReplayVisuals.ruleOfThirdsGuide = !ReplayVisuals.ruleOfThirdsGuide; + } + + if (ImGui.checkbox("Center Guide", ReplayVisuals.centerGuide)) { + ReplayVisuals.centerGuide = !ReplayVisuals.centerGuide; + } + + ReplayVisuals.sizing = ImGuiHelper.enumCombo("Sizing", ReplayVisuals.sizing); + if (ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) { + ReplayVisuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", ReplayVisuals.changeAspectRatio); + } + } + ImGui.end(); + } +} diff --git a/src/client/java/com/moulberry/flashback/exception/UnsupportedPacketException.java b/src/main/java/com/moulberry/flashback/exception/UnsupportedPacketException.java similarity index 100% rename from src/client/java/com/moulberry/flashback/exception/UnsupportedPacketException.java rename to src/main/java/com/moulberry/flashback/exception/UnsupportedPacketException.java diff --git a/src/main/java/com/moulberry/flashback/exporting/AsyncFileDialogs.java b/src/main/java/com/moulberry/flashback/exporting/AsyncFileDialogs.java new file mode 100644 index 0000000..ff30fc3 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/AsyncFileDialogs.java @@ -0,0 +1,205 @@ +package com.moulberry.flashback.exporting; + +import net.minecraft.client.Minecraft; +import org.lwjgl.PointerBuffer; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.util.nfd.NFDFilterItem; +import org.lwjgl.util.nfd.NativeFileDialog; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class AsyncFileDialogs { + + private static CompletableFuture currentSaveOrOpenFileDialog = null; + private static final ExecutorService dialogThread = Executors.newSingleThreadExecutor(); + private static boolean initializedNfd = false; + + public static boolean hasDialog() { + return currentSaveOrOpenFileDialog != null; + } + + public static CompletableFuture saveFileDialog(String defaultPath, String defaultName, String filterDescription, String... filters) { + if (hasDialog()) return CompletableFuture.completedFuture(null); + + currentSaveOrOpenFileDialog = new CompletableFuture<>(); + CompletableFuture future = currentSaveOrOpenFileDialog; + + boolean initializedNfd = AsyncFileDialogs.initializedNfd; + AsyncFileDialogs.initializedNfd = true; + + Runnable runnable = () -> { + if (!initializedNfd) { + NativeFileDialog.NFD_Init(); + } + + try (MemoryStack stack = MemoryStack.stackPush()) { + PointerBuffer out = stack.callocPointer(1); + + StringBuilder filterBuilder = new StringBuilder(); + + for (String filter : filters) { + if (!filterBuilder.isEmpty()) filterBuilder.append(","); + filterBuilder.append(filter(filter)); + } + + NFDFilterItem.Buffer filtersBuffer = NFDFilterItem.malloc(1); + filtersBuffer.get(0) + .name(stack.UTF8(filter(filterDescription))) + .spec(stack.UTF8(filterBuilder.toString())); + + int result = NativeFileDialog.NFD_SaveDialog(out, filtersBuffer, filter(defaultPath), filter(defaultName)); + + if (result != NativeFileDialog.NFD_OKAY) { + currentSaveOrOpenFileDialog.complete(null); + currentSaveOrOpenFileDialog = null; + } else { + currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0)); + currentSaveOrOpenFileDialog = null; + NativeFileDialog.NFD_FreePath(out.get(0)); + } + } catch (Throwable t) { + t.printStackTrace(); + } finally { + if (currentSaveOrOpenFileDialog != null) { + currentSaveOrOpenFileDialog.complete(null); + currentSaveOrOpenFileDialog = null; + } + } + }; + + if (Minecraft.ON_OSX) { + // MacOS needs dialogs to be run from the main thread + Minecraft.getInstance().submit(runnable); + } else { + dialogThread.submit(runnable); + } + + return future; + } + + public static CompletableFuture openFileDialog(String defaultPath, String filterDescription, String... filters) { + if (hasDialog()) return CompletableFuture.completedFuture(null); + + currentSaveOrOpenFileDialog = new CompletableFuture<>(); + CompletableFuture future = currentSaveOrOpenFileDialog; + + boolean initializedNfd = AsyncFileDialogs.initializedNfd; + AsyncFileDialogs.initializedNfd = true; + + Runnable runnable = () -> { + if (!initializedNfd) { + NativeFileDialog.NFD_Init(); + } + + try (MemoryStack stack = MemoryStack.stackPush()) { + PointerBuffer out = stack.callocPointer(1); + + StringBuilder filterBuilder = new StringBuilder(); + + for (String filter : filters) { + if (!filterBuilder.isEmpty()) filterBuilder.append(","); + filterBuilder.append(filter(filter)); + } + + NFDFilterItem.Buffer filtersBuffer = NFDFilterItem.malloc(1); + filtersBuffer.get(0) + .name(stack.UTF8(filter(filterDescription))) + .spec(stack.UTF8(filterBuilder.toString())); + + int result = NativeFileDialog.NFD_OpenDialog(out, filtersBuffer, filter(defaultPath)); + + if (result != NativeFileDialog.NFD_OKAY) { + currentSaveOrOpenFileDialog.complete(null); + currentSaveOrOpenFileDialog = null; + } else { + currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0)); + currentSaveOrOpenFileDialog = null; + NativeFileDialog.NFD_FreePath(out.get(0)); + } + } catch (Throwable t) { + t.printStackTrace(); + } finally { + if (currentSaveOrOpenFileDialog != null) { + currentSaveOrOpenFileDialog.complete(null); + currentSaveOrOpenFileDialog = null; + } + } + }; + + if (Minecraft.ON_OSX) { + // MacOS needs dialogs to be run from the main thread + Minecraft.getInstance().submit(runnable); + } else { + dialogThread.submit(runnable); + } + + return future; + } + + public static CompletableFuture openFolderDialog(String defaultPath) { + if (hasDialog()) return CompletableFuture.completedFuture(null); + + currentSaveOrOpenFileDialog = new CompletableFuture<>(); + CompletableFuture future = currentSaveOrOpenFileDialog; + + boolean initializedNfd = AsyncFileDialogs.initializedNfd; + AsyncFileDialogs.initializedNfd = true; + + Runnable runnable = () -> { + if (!initializedNfd) { + NativeFileDialog.NFD_Init(); + } + + try (MemoryStack stack = MemoryStack.stackPush()) { + PointerBuffer out = stack.callocPointer(1); + + int result = NativeFileDialog.NFD_PickFolder(out, filter(defaultPath)); + + if (result != NativeFileDialog.NFD_OKAY) { + currentSaveOrOpenFileDialog.complete(null); + currentSaveOrOpenFileDialog = null; + } else { + currentSaveOrOpenFileDialog.complete(out.getStringUTF8(0)); + currentSaveOrOpenFileDialog = null; + NativeFileDialog.NFD_FreePath(out.get(0)); + } + } catch (Throwable t) { + t.printStackTrace(); + } finally { + if (currentSaveOrOpenFileDialog != null) { + currentSaveOrOpenFileDialog.complete(null); + currentSaveOrOpenFileDialog = null; + } + } + }; + + if (Minecraft.ON_OSX) { + // MacOS needs dialogs to be run from the main thread + Minecraft.getInstance().submit(runnable); + } else { + dialogThread.submit(runnable); + } + + return future; + } + + public static String filter(CharSequence in) { + return filterLT20(in.toString() + .replace("'", "") + .replace("\"", "") + .replace("$", "") + .replace("`", "")); + } + + public static String filterLT20(CharSequence in) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < in.length(); i++) { + char c = in.charAt(i); + if (c >= 32 || c == '\n') builder.append(c); + } + return builder.toString(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java new file mode 100644 index 0000000..749682e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java @@ -0,0 +1,377 @@ +package com.moulberry.flashback.exporting; + +import com.mojang.blaze3d.platform.NativeImage; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.SneakyThrow; +import com.moulberry.flashback.mixin.record.MixinFFmpegFrameRecorder; +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.avutil; +import org.bytedeco.ffmpeg.global.swscale; +import org.bytedeco.ffmpeg.swscale.SwsContext; +import org.bytedeco.javacpp.BytePointer; +import org.bytedeco.javacpp.DoublePointer; +import org.bytedeco.javacpp.Pointer; +import org.bytedeco.javacpp.PointerPointer; +import org.bytedeco.javacv.FFmpegFrameRecorder; +import org.bytedeco.javacv.FFmpegLogCallback; +import org.bytedeco.javacv.Frame; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; + +import static org.bytedeco.ffmpeg.global.avutil.*; +import static org.bytedeco.ffmpeg.global.swscale.SWS_BILINEAR; +import static org.bytedeco.ffmpeg.global.swscale.sws_freeContext; + +public class AsyncVideoEncoder implements AutoCloseable { + + @Nullable + private final ArrayBlockingQueue rescaleQueue; + private final ArrayBlockingQueue encodeQueue; + + @Nullable + private final ArrayBlockingQueue reusePictureData; + + private final AtomicBoolean finishRescaleThread = new AtomicBoolean(false); + private final AtomicBoolean finishEncodeThread = new AtomicBoolean(false); + private final AtomicBoolean finishedWriting = new AtomicBoolean(false); + + private final AtomicReference threadedError = new AtomicReference<>(null); + + 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 { + public void close() { + MemoryUtil.nmemFree(this.pointer); + } + } + + public AsyncVideoEncoder(ExportSettings settings, String filename) { + int width = settings.resolutionX(); + int height = settings.resolutionY(); + + final int maxResolutionArea = 3840 * 2160; + if (width*height > maxResolutionArea) { + double factor = (width*height) / (double) maxResolutionArea; + factor = Math.sqrt(factor); + width = (int) Math.floor(width / factor); + height = (int) Math.floor(height / factor); + } + + int maxBitrate = Math.min(288_000_000, 5000 + (int) Math.ceil(width * height * settings.framerate())); + int bitrate; + if (settings.bitrate() <= 0) { + bitrate = maxBitrate; + } else { + bitrate = Math.min(settings.bitrate(), maxBitrate); + } + double fps = settings.framerate(); + + String extension = settings.container().extension(); + + try { + if (FabricLoader.getInstance().isDevelopmentEnvironment() || true) { + FFmpegLogCallback.set(); + } + + int dstPixelFormat = PixelFormatHelper.getBestPixelFormat(settings.encoder()); + boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat; + + final FFmpegFrameRecorder recorder = new FFmpegFrameRecorder( + filename, width, height, 0); + + recorder.setVideoBitrate(bitrate); + recorder.setVideoCodec(settings.codec().codecId()); + recorder.setVideoCodecName(settings.encoder()); + recorder.setFormat(extension); + recorder.setFrameRate(fps); + recorder.setPixelFormat(dstPixelFormat); + recorder.setGopSize((int) Math.ceil(fps * 2)); + + recorder.start(); + + this.encodeQueue = new ArrayBlockingQueue<>(needsRescale ? 24 : 32); + this.rescaleQueue = needsRescale ? new ArrayBlockingQueue<>(8) : null; + this.reusePictureData = needsRescale ? new ArrayBlockingQueue<>(32) : null; + + Thread encodeThread = createEncodeThread(recorder); + if (needsRescale) { + Thread rescaleThread = createRescaleThread(width, height, dstPixelFormat); + rescaleThread.start(); + } + encodeThread.start(); + } catch (IOException e) { + throw SneakyThrow.sneakyThrow(e); + } + } + + private @NotNull Thread createEncodeThread(FFmpegFrameRecorder recorder) { + Thread encodeThread = new Thread(() -> { + while (true) { + ImageFrame src; + + try { + src = this.encodeQueue.poll(10, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + throw SneakyThrow.sneakyThrow(e); + } + + try { + if (src == null) { + if (this.finishEncodeThread.get()) { + recorder.stop(); + recorder.close(); + this.finishedWriting.set(true); + return; + } else { + continue; + } + } + + int size = src.height * src.stride * Frame.pixelSize(src.imageDepth); + ByteBuffer buffer = MemoryUtil.memByteBuffer(src.pointer, size); + + recorder.recordImage(src.width, src.height, src.imageDepth, src.channels, + src.stride, src.pixelFormat, buffer); + + if (this.reusePictureData != null) { + if (this.reusePictureData.offer(src.pointer)) { // try adding to the reuse queue, ignore if full + src = null; // don't deallocate + } + } + } catch (Throwable t) { + try { + recorder.release(); + } catch (FFmpegFrameRecorder.Exception e) { + e.printStackTrace(); + } + this.threadedError.set(t); + this.finishRescaleThread.set(true); + this.finishEncodeThread.set(true); + this.finishedWriting.set(true); + return; + } finally { + if (src != null) { + src.close(); + } + } + } + }); + encodeThread.setName("Video Encode Thread"); + return encodeThread; + } + + private Thread createRescaleThread(int dstWidth, int dstHeight, int dstPixelFormat) { + int dstSize = av_image_get_buffer_size(dstPixelFormat, dstWidth, dstHeight, 1); + int dstDepth = dstSize * 8 / dstWidth / dstHeight; + int dstChannels; + + try (AVPixFmtDescriptor descriptor = av_pix_fmt_desc_get(dstPixelFormat)) { + dstChannels = descriptor.nb_components(); + } + + AVFrame picture = avutil.av_frame_alloc(); + if (picture == null) { + throw new RuntimeException("av_frame_alloc() error: Could not allocate picture."); + } + + AVFrame tmp_picture = avutil.av_frame_alloc(); + if (tmp_picture == null) { + throw new RuntimeException("av_frame_alloc() error: Could not allocate tmp_picture."); + } + + PointerPointer tmp_picture_ptr = new PointerPointer<>(tmp_picture); + PointerPointer picture_ptr = new PointerPointer<>(picture); + + Thread scaleThread = new Thread(() -> { + SwsContext img_convert_ctx = null; + + while (true) { + try (ImageFrame src = this.rescaleQueue.poll(10, TimeUnit.MILLISECONDS)) { + if (src == null) { + if (this.finishRescaleThread.get()) { + av_frame_free(picture); + av_frame_free(tmp_picture); + sws_freeContext(img_convert_ctx); + this.finishEncodeThread.set(true); + return; + } else { + continue; + } + } + + img_convert_ctx = swscale.sws_getCachedContext(img_convert_ctx, src.width, src.height, src.pixelFormat, + dstWidth, dstHeight, dstPixelFormat, swscale.SWS_BILINEAR, + null, null, (DoublePointer) null); + if (img_convert_ctx == null) { + throw new RuntimeException("sws_getCachedContext() error: Cannot initialize the conversion context."); + } + + BytePointer data = new BytePointer() {{ + this.address = src.pointer; + this.position = 0; + this.limit = src.size; + this.capacity = src.size; + }}; + + Long tempPointerAddressLong = this.reusePictureData.poll(); + if (tempPointerAddressLong == null) { + tempPointerAddressLong = MemoryUtil.nmemAlloc(dstSize); + if (tempPointerAddressLong == 0) { + throw new OutOfMemoryError(); + } + } + + // Bit of a hack to create a BytePointer for this library + long tempPointerAddress = tempPointerAddressLong; + BytePointer tempPointer = new BytePointer() {{ + this.address = tempPointerAddress; + this.position = 0; + this.limit = dstSize; + this.capacity = dstSize; + }}; + + av_image_fill_arrays(tmp_picture_ptr, tmp_picture.linesize(), data, src.pixelFormat, src.width, src.height, 1); + av_image_fill_arrays(picture_ptr, picture.linesize(), tempPointer, dstPixelFormat, dstWidth, dstHeight, 1); + + int step = src.stride * Math.abs(src.imageDepth) / 8; + tmp_picture.linesize(0, step); + tmp_picture.format(src.pixelFormat); + tmp_picture.width(src.width); + tmp_picture.height(src.height); + + picture.format(dstPixelFormat); + picture.width(dstWidth); + picture.height(dstHeight); + + swscale.sws_scale(img_convert_ctx, tmp_picture_ptr, tmp_picture.linesize(), + 0, src.height, picture_ptr, picture.linesize()); + + this.encodeQueue.put(new ImageFrame(tempPointerAddress, dstSize, dstWidth, dstHeight, dstChannels, dstDepth, + dstWidth, dstPixelFormat)); + } catch (Throwable t) { + try { + av_frame_free(picture); + av_frame_free(tmp_picture); + sws_freeContext(img_convert_ctx); + } catch (Exception e) { + e.printStackTrace(); + } + + this.threadedError.set(t); + this.finishRescaleThread.set(true); + this.finishEncodeThread.set(true); + this.finishedWriting.set(true); + return; + } + } + }); + scaleThread.setName("Image Rescale Thread"); + return scaleThread; + } + + private void checkEncodeError(@Nullable AutoCloseable closeable) { + Throwable t = this.threadedError.get(); + if (t != null) { + this.finishRescaleThread.set(true); + this.finishEncodeThread.set(true); + this.finishedWriting.set(true); + + if (closeable != null) { + try { + closeable.close(); + } catch (Exception e) { + Flashback.LOGGER.error("Error while trying to close passed AutoClosable", e); + } + } + SneakyThrow.sneakyThrow(t); + } + } + + public void encode(NativeImage src) { + checkEncodeError(src); + + if (this.finishRescaleThread.get() || this.finishEncodeThread.get() || this.finishedWriting.get()) { + src.close(); + throw new IllegalStateException("Cannot encode after finish()"); + } + + 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); + if (this.rescaleQueue != null) { + this.rescaleQueue.put(imageFrame); + } else { + this.encodeQueue.put(imageFrame); + } + break; + } catch (InterruptedException ignored) {} + checkEncodeError(src); + } + } + + public void finish() { + checkEncodeError(null); + + if (this.rescaleQueue != null) { + while (!this.rescaleQueue.isEmpty()) { + checkEncodeError(null); + LockSupport.parkNanos("waiting for rescale queue to empty", 100000L); + } + } + while (!this.encodeQueue.isEmpty()) { + checkEncodeError(null); + LockSupport.parkNanos("waiting for encode queue to empty", 100000L); + } + + this.finishRescaleThread.set(true); + if (this.rescaleQueue == null) { + this.finishEncodeThread.set(true); + } + + while (!this.finishedWriting.get()) { + LockSupport.parkNanos("waiting for encoder thread to finish", 100000L); + } + + checkEncodeError(null); + } + + @Override + public void close() { + if (this.rescaleQueue != null) { + for (ImageFrame src : this.rescaleQueue) { + src.close(); + } + } + for (ImageFrame src : this.encodeQueue) { + src.close(); + } + + this.finishRescaleThread.set(true); + this.finishEncodeThread.set(true); + + while (!this.finishedWriting.get()) { + LockSupport.parkNanos("waiting for encoder thread to finish", 100000L); + } + + if (this.reusePictureData != null) { + for (Long address : this.reusePictureData) { + if (address != 0) { + MemoryUtil.nmemFree(address); + } + } + } + } +} diff --git a/src/client/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java b/src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java.old similarity index 100% rename from src/client/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java rename to src/main/java/com/moulberry/flashback/exporting/AsyncVideoEncoder.java.old diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java new file mode 100644 index 0000000..9d7cd12 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -0,0 +1,479 @@ +package com.moulberry.flashback.exporting; + +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.pipeline.TextureTarget; +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.blaze3d.platform.Window; +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.state.EditorState; +import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.playback.ReplayServer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.FogRenderer; +import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.client.sounds.SoundEngine; +import org.joml.Matrix4f; +import org.lwjgl.glfw.GLFW; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.LockSupport; + +public class ExportJob { + + private final ExportSettings settings; + + private boolean running = false; + private boolean shouldChangeFramebufferSize = false; + private long lastRenderMillis; + private long escapeCancelStartMillis = -1; + private long renderStartTime; + + private boolean showingDebug = false; + private boolean pressedDebugKey = false; + private long serverTickTimeNanos = 0; + private long clientTickTimeNanos = 0; + private long renderTimeNanos = 0; + private long encodeTimeNanos = 0; + private long downloadTimeNanos = 0; + + private final AtomicBoolean finishedServerTick = new AtomicBoolean(false); + + public ExportJob(ExportSettings settings) { + this.settings = settings; + } + + public boolean isRunning() { + return this.running; + } + + public void onFinishedServerTick() { + this.finishedServerTick.set(true); + } + + public boolean shouldChangeFramebufferSize() { + return this.running && this.shouldChangeFramebufferSize; + } + + public int getWidth() { + return this.settings.resolutionX(); + } + + public int getHeight() { + return this.settings.resolutionY(); + } + + public void run() { + ReplayServer replayServer = Flashback.getReplayServer(); + if (this.running || replayServer == null) { + throw new IllegalStateException("run() called twice"); + } + this.running = true; + + UUID uuid = UUID.randomUUID(); + + String tempFileName = "replay_export_temp/" + uuid + "." + this.settings.container().extension(); + Path exportTempFile = Path.of(tempFileName); + Path exportTempFolder = exportTempFile.getParent(); + + TextureTarget infoRenderTarget = null; + + try { + Files.createDirectories(exportTempFolder); + + RenderTarget mainTarget = Minecraft.getInstance().mainRenderTarget; + infoRenderTarget = new TextureTarget(mainTarget.width, mainTarget.height, false, Minecraft.ON_OSX); + + try (AsyncVideoEncoder encoder = new AsyncVideoEncoder(this.settings, tempFileName); + SaveableFramebufferQueue downloader = new SaveableFramebufferQueue(this.settings.resolutionX(), this.settings.resolutionY())) { + doExport(encoder, downloader, infoRenderTarget); + } + + Files.move(exportTempFile, this.settings.output(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + this.running = false; + this.shouldChangeFramebufferSize = false; + Minecraft.getInstance().resizeDisplay(); + + try { + Files.deleteIfExists(exportTempFile); + } catch (IOException ignored) {} + + try { + boolean empty; + try (var stream = Files.newDirectoryStream(exportTempFolder)) { + empty = !stream.iterator().hasNext(); + } + if (empty) { + Files.deleteIfExists(exportTempFolder); + } + } catch (IOException ignored) {} + + if (infoRenderTarget != null) { + infoRenderTarget.destroyBuffers(); + } + } + } + + private void doExport(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, TextureTarget infoRenderTarget) { + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer == null) { + return; + } + + this.setup(replayServer); + + shouldChangeFramebufferSize = true; + Minecraft.getInstance().resizeDisplay(); + + double framesPerTick = this.settings.framerate() / 20.0; + + 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); + + while (currentFrame <= totalFrames) { + double currentTickDouble = currentFrame / framesPerTick; + int currentTick = (int) currentTickDouble; + double partialTick = currentTickDouble - currentTick; + int targetServerTick = this.settings.startTick() + currentTick; + + // Wait until server is on correct replay tick + long start = System.nanoTime(); + this.setServerTickAndWait(replayServer, targetServerTick, false); + serverTickTimeNanos += System.nanoTime() - start; + + // Tick client + while (clientTickCount < currentTick) { + start = System.nanoTime(); + this.runClientTick(); + clientTickTimeNanos += System.nanoTime() - start; + + clientTickCount += 1; + } + + long pauseScreenStart = System.currentTimeMillis(); + while (Minecraft.getInstance().getOverlay() != null || Minecraft.getInstance().screen != null) { + this.runClientTick(); + + Window window = Minecraft.getInstance().getWindow(); + RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget; + renderTarget.bindWrite(true); + RenderSystem.clear(16640, Minecraft.ON_OSX); + Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(0.0f, 0.0f), true); + renderTarget.unbindWrite(); + + this.shouldChangeFramebufferSize = false; + renderTarget.blitToScreen(window.getWidth(), window.getHeight(), false); + window.updateDisplay(); + this.shouldChangeFramebufferSize = true; + + LockSupport.parkNanos("waiting for pause overlay to disappear", 50_000_000L); + + // Force remove screens/overlays after 5s/15s respectively + long currentTime = System.currentTimeMillis(); + if (pauseScreenStart > currentTime) { + pauseScreenStart = currentTime; + } + if (currentTime - pauseScreenStart > 5000) { + Minecraft.getInstance().setScreen(null); + } + if (currentTime - pauseScreenStart > 15000) { + Minecraft.getInstance().setOverlay(null); + } + } + + this.tryUnfreezeClient(); + + editorState.applyKeyframes(Minecraft.getInstance(), (float)(this.settings.startTick() + currentTickDouble)); + + RenderTarget oldTarget = Minecraft.getInstance().getMainRenderTarget(); + SaveableFramebuffer saveable = downloader.take(); + RenderTarget renderTarget = saveable.getFramebuffer(this.settings.resolutionX(), this.settings.resolutionY()); + + Minecraft.getInstance().mainRenderTarget = renderTarget; + + 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.deltaTickResidual = (float) partialTick; + Minecraft.getInstance().timer.pausedDeltaTickResidual = (float) partialTick; + + start = System.nanoTime(); + Minecraft.getInstance().gameRenderer.render(new FixedDeltaTracker(1 / (float) framesPerTick, (float) partialTick), true); + renderTimeNanos += System.nanoTime() - start; + + renderTarget.unbindWrite(); + + Minecraft.getInstance().mainRenderTarget = oldTarget; + + this.shouldChangeFramebufferSize = false; + boolean cancel = finishFrame(renderTarget, infoRenderTarget, currentFrame, totalFrames); + this.shouldChangeFramebufferSize = true; + + submitDownloadedFrames(encoder, downloader, false); + + downloader.startDownload(saveable); + + if (cancel) { + break; + } + + currentFrame += 1; + } + + submitDownloadedFrames(encoder, downloader, true); + encoder.finish(); + } + + 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 + this.setServerTickAndWait(replayServer, currentTick, true); + this.runClientTick(); + + // Advance until tick is at start + while (currentTick < this.settings.startTick()) { + this.setServerTickAndWait(replayServer, currentTick, true); + this.runClientTick(); + currentTick += 1; + } + + // Ensured replay server is paused at startTick + this.setServerTickAndWait(replayServer, this.settings.startTick(), true); + this.runClientTick(); + + // Remove screen + minecraft.setScreen(null); + } + + private void setServerTickAndWait(ReplayServer replayServer, int targetTick, boolean force) { + if (force || replayServer.getReplayTick() != targetTick) { + this.finishedServerTick.set(false); + + replayServer.jumpToTick = targetTick; + replayServer.replayPaused = true; + replayServer.sendFinishedServerTick.set(true); + + while (!this.finishedServerTick.compareAndExchange(true, false)) { + LockSupport.parkNanos("waiting for server thread", 100000L); + } + } + } + + private void runClientTick() { + this.tryUnfreezeClient(); + + while (Minecraft.getInstance().pollTask()) {} + Minecraft.getInstance().tick(); + this.tryUnfreezeClient(); + } + + private void tryUnfreezeClient() { + ClientLevel level = Minecraft.getInstance().level; + if (level != null) { + level.tickRateManager().setFrozen(false); + } + } + + private void submitDownloadedFrames(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, boolean drain) { + NativeImage image; + while (true) { + long start = System.nanoTime(); + image = downloader.finishDownload(drain); + downloadTimeNanos += System.nanoTime() - start; + + if (image == null) { + break; + } + + start = System.nanoTime(); + encoder.encode(image); + encodeTimeNanos += System.nanoTime() - start; + } + } + + private boolean finishFrame(RenderTarget framebuffer, RenderTarget infoRenderTarget, int currentFrame, int totalFrames) { + boolean cancel = false; + + long currentTime = System.currentTimeMillis(); + if (currentTime - this.lastRenderMillis > 1000/60 || currentFrame == totalFrames) { + Window window = Minecraft.getInstance().getWindow(); + + { + GlStateManager._colorMask(true, true, true, false); + GlStateManager._disableDepthTest(); + GlStateManager._depthMask(false); + GlStateManager._viewport(0, 0, window.getWidth(), window.getHeight()); + GlStateManager._disableBlend(); + + Minecraft minecraft = Minecraft.getInstance(); + ShaderInstance shaderInstance = Objects.requireNonNull(minecraft.gameRenderer.blitShader, "Blit shader not loaded"); + shaderInstance.setSampler("DiffuseSampler", framebuffer.colorTextureId); + shaderInstance.apply(); + BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN); + bufferBuilder.addVertex(0.0F, 0.0F, 0.0F); + bufferBuilder.addVertex(1.0F, 0.0F, 0.0F); + bufferBuilder.addVertex(1.0F, 1.0F, 0.0F); + bufferBuilder.addVertex(0.0F, 1.0F, 0.0F); + BufferUploader.draw(bufferBuilder.buildOrThrow()); + shaderInstance.clear(); + GlStateManager._depthMask(true); + GlStateManager._colorMask(true, true, true, true); + } + + this.lastRenderMillis = currentTime; + + Font font = Minecraft.getInstance().font; + var bufferSource = Minecraft.getInstance().renderBuffers().bufferSource(); + bufferSource.endBatch(); + infoRenderTarget.bindWrite(true); + + RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0f); + + RenderSystem.clear(16640, Minecraft.ON_OSX); + + int guiScale = 4; + int scaledWidth = (int) Math.ceil(infoRenderTarget.width / guiScale); + int scaledHeight = (int) Math.ceil(infoRenderTarget.height / guiScale); + + Matrix4f matrix4f = new Matrix4f().setOrtho(0.0f, scaledWidth, scaledHeight, 0.0f, 1000.0f, 21000.0f); + RenderSystem.setProjectionMatrix(matrix4f, VertexSorting.ORTHOGRAPHIC_Z); + + Matrix4f matrix = new Matrix4f(); + matrix.translate(0.0f, 0.0f, -11000.0f); + + RenderSystem.disableDepthTest(); + + List lines = new ArrayList<>(); + + lines.add("Exported Frames: " + currentFrame + "/" + totalFrames); + + long elapsed = currentTime - this.renderStartTime; + lines.add("Time elapsed: " + formatTime(elapsed)); + + if (currentFrame >= this.settings.framerate()) { + long estimatedRemaining = (currentTime - this.renderStartTime) * (totalFrames - currentFrame) / currentFrame; + lines.add("Estimated time remaining: " + formatTime(estimatedRemaining)); + } + + lines.add(""); + + boolean debugPressed = GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_F3) != GLFW.GLFW_RELEASE; + if (pressedDebugKey != debugPressed) { + pressedDebugKey = debugPressed; + if (pressedDebugKey) { + showingDebug = !showingDebug; + } + } + + if (showingDebug) { + lines.add("ST: " + serverTickTimeNanos/1000000 + ", CT: " + clientTickTimeNanos/1000000); + lines.add("RT: " + renderTimeNanos/1000000 + ", ET: " + encodeTimeNanos/1000000); + lines.add("DT: " + downloadTimeNanos/1000000); + } else { + lines.add("Press [F3] to show debug info"); + } + + lines.add(""); + + if (currentFrame == totalFrames) { + lines.add("Saving..."); + } else if (GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_ESCAPE) != GLFW.GLFW_RELEASE) { + long current = System.currentTimeMillis(); + if (this.escapeCancelStartMillis <= 0 || current < this.escapeCancelStartMillis) { + this.escapeCancelStartMillis = current; + } + if (current - this.escapeCancelStartMillis > 3000) { + cancel = true; + lines.add("Saving..."); + } else { + long remainingSeconds = 3 - (current - this.escapeCancelStartMillis) / 1000; + lines.add("Hold [ESC] to cancel (" + remainingSeconds + "s)"); + } + } else { + lines.add("Hold [ESC] to cancel"); + this.escapeCancelStartMillis = -1; + } + + int x = scaledWidth / 2; + int y = scaledHeight / 2 - font.lineHeight * (lines.size() + 1)/2; + for (String line : lines) { + if (line.isEmpty()) { + y += font.lineHeight / 2 + 1; + } else { + font.drawInBatch(line, x - font.width(line)/2f, y, + -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); + y += font.lineHeight; + } + } + + bufferSource.endBatch(); + RenderSystem.enableDepthTest(); + + infoRenderTarget.unbindWrite(); + + RenderSystem.defaultBlendFunc(); + RenderSystem.enableBlend(); + infoRenderTarget.blitToScreen(window.getWidth(), window.getHeight(), false); + Minecraft.getInstance().getWindow().updateDisplay(); + } + + return cancel; + } + + private String formatTime(long millis) { + long seconds = (millis / 1000) % 60; + long minutes = (millis / 1000 / 60) % 60; + long hours = millis / 1000 / 60 / 60; + + if (hours > 0) { + return hours + "h " + minutes + "m " + seconds + "s"; + } else if (minutes > 0) { + return minutes + "m " + seconds + "s"; + } else { + return seconds + "s"; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java new file mode 100644 index 0000000..34eba49 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java @@ -0,0 +1,11 @@ +package com.moulberry.flashback.exporting; + +import com.moulberry.flashback.combo_options.VideoCodec; +import com.moulberry.flashback.combo_options.VideoContainer; + +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) { + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/FrexFlawlessFramesIntegration.java b/src/main/java/com/moulberry/flashback/exporting/FrexFlawlessFramesIntegration.java new file mode 100644 index 0000000..ee603b0 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/FrexFlawlessFramesIntegration.java @@ -0,0 +1,13 @@ +package com.moulberry.flashback.exporting; + +import java.util.function.Consumer; +import java.util.function.Function; + +public class FrexFlawlessFramesIntegration implements Consumer>> { + + @Override + public void accept(Function> flawlessFrames) { + PerfectFrames.frexFlawlessFrames.add(flawlessFrames.apply("flashback")); + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java b/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java new file mode 100644 index 0000000..a2edd25 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/PerfectFrames.java @@ -0,0 +1,87 @@ +package com.moulberry.flashback.exporting; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.resources.SkinManager; + +import java.util.*; +import java.util.concurrent.locks.LockSupport; +import java.util.function.Consumer; + +public class PerfectFrames { + + private static boolean isEnabled = false; + static List> frexFlawlessFrames = new ArrayList<>(); + + private static final Set ignoreSkinLoading = new HashSet<>(); + + public static void enable() { + isEnabled = true; + ignoreSkinLoading.clear(); + for (Consumer frexFlawlessFramesConsumer : frexFlawlessFrames) { + frexFlawlessFramesConsumer.accept(true); + } + } + + public static void disable() { + isEnabled = false; + ignoreSkinLoading.clear(); + for (Consumer frexFlawlessFramesConsumer : frexFlawlessFrames) { + frexFlawlessFramesConsumer.accept(false); + } + } + + public static boolean isEnabled() { + return isEnabled; + } + + public static void waitUntilFrameReady() { + long start = System.currentTimeMillis(); + while (!isFrameReady(start)) { + LockSupport.parkNanos("waiting for frame to be ready", 100000L); + while (Minecraft.getInstance().pollTask()) {} + } + } + + private static boolean isFrameReady(long start) { + long current = System.currentTimeMillis(); + boolean forceFrameReady = current - start > 15000; + + ClientLevel level = Minecraft.getInstance().level; + SkinManager skinManager = Minecraft.getInstance().getSkinManager(); + + if (level != null) { + if (forceFrameReady) { + System.err.println("Waiting for skin loading took too long, ignoring..."); + for (AbstractClientPlayer player : level.players()) { + if (player == Minecraft.getInstance().player) { + continue; + } + PlayerInfo playerInfo = player.getPlayerInfo(); + if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) { + System.err.println("Took too long to load skin for " + player.getUUID()); + ignoreSkinLoading.add(player.getUUID()); + } + } + } else { + for (AbstractClientPlayer player : level.players()) { + if (player == Minecraft.getInstance().player) { + continue; + } + if (ignoreSkinLoading.contains(player.getUUID())) { + continue; + } + PlayerInfo playerInfo = player.getPlayerInfo(); + if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) { + return false; + } + } + } + } + + return true; + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java b/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java new file mode 100644 index 0000000..31f29bf --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/PixelFormatHelper.java @@ -0,0 +1,71 @@ +package com.moulberry.flashback.exporting; + +import com.moulberry.flashback.Flashback; +import it.unimi.dsi.fastutil.ints.IntArrayList; +import it.unimi.dsi.fastutil.ints.IntList; +import org.bytedeco.ffmpeg.avcodec.AVCodec; +import org.bytedeco.ffmpeg.global.avcodec; +import org.bytedeco.ffmpeg.global.avutil; +import org.bytedeco.javacpp.BytePointer; +import org.bytedeco.javacpp.IntPointer; + +import java.util.HashMap; +import java.util.Map; + +public class PixelFormatHelper { + + private static final Map bestPixelFormats = new HashMap<>(); + + public static int getBestPixelFormat(String codecName) { + if (bestPixelFormats.containsKey(codecName)) { + return bestPixelFormats.get(codecName); + } + + int bestPixelFormat = calculateBestPixelFormat(codecName); + + if (bestPixelFormat == avutil.AV_PIX_FMT_NONE) { + throw new RuntimeException("Unable to determine best alternate pixel format for " + codecName); + } + if (bestPixelFormat != avutil.AV_PIX_FMT_YUV420P) { + Flashback.LOGGER.info("Chose to use alternate pixel format {} for codec {}", pixelFormatToString(bestPixelFormat), codecName); + } + + bestPixelFormats.put(codecName, bestPixelFormat); + return bestPixelFormat; + } + + private static int calculateBestPixelFormat(String codecName) { + try (AVCodec codec = avcodec.avcodec_find_encoder_by_name(codecName)) { + IntList supportedFormats = new IntArrayList(); + + IntPointer pixFmts = codec.pix_fmts(); + + int index = 0; + while (true) { + int pixFmt = pixFmts.get(index); + if (pixFmt == -1) { + break; + } + + if (pixFmt == avutil.AV_PIX_FMT_YUV420P) { + return avutil.AV_PIX_FMT_YUV420P; + } + + supportedFormats.add(pixFmt); + index += 1; + } + + supportedFormats.add(avutil.AV_PIX_FMT_NONE); + + return avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), avutil.AV_PIX_FMT_BGRA, 0, new int[1]); + } + } + + private static String pixelFormatToString(int pixelFormat) { + try (BytePointer name = avutil.av_get_pix_fmt_name(pixelFormat)) { + return name.getString(); + } catch (Throwable ignored) {} + return "UNKNOWN(" + pixelFormat + ")"; + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java new file mode 100644 index 0000000..f1ac4a9 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebuffer.java @@ -0,0 +1,105 @@ +package com.moulberry.flashback.exporting; + +import com.mojang.blaze3d.pipeline.MainTarget; +import com.mojang.blaze3d.platform.NativeImage; +import org.lwjgl.opengl.GL30C; +import org.lwjgl.system.MemoryUtil; + +import java.nio.ByteBuffer; + +public class SaveableFramebuffer implements AutoCloseable { + + private MainTarget framebuffer; + private int pboId; + + private boolean isDownloading = false; + + public SaveableFramebuffer() { + this.framebuffer = null; + this.pboId = -1; + } + + public boolean isDownloading() { + return isDownloading; + } + + public MainTarget getFramebuffer(int width, int height) { + if (this.isDownloading) { + throw new IllegalStateException("Can't get the framebuffer for rendering while still downloading"); + } + + if (this.framebuffer == null) { + this.framebuffer = new MainTarget(width, height); + } + + return this.framebuffer; + } + + public void startDownload(int width, int height) { + if (this.isDownloading) { + throw new IllegalStateException("Can't start downloading while already downloading"); + } + this.isDownloading = true; + + if (this.pboId == -1) { + this.pboId = GL30C.glGenBuffers(); + + GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId); + GL30C.glBufferData(GL30C.GL_PIXEL_PACK_BUFFER, (long) width * height * 4, GL30C.GL_STREAM_READ); + GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0); + } + + this.framebuffer.bindWrite(true); + + GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId); + GL30C.glReadPixels(0, 0, width, height, GL30C.GL_RGBA, GL30C.GL_UNSIGNED_BYTE, 0); + GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0); + + this.framebuffer.unbindWrite(); + } + + public NativeImage finishDownload(int width, int height) { + if (!this.isDownloading) { + throw new IllegalStateException("Can't finish downloading before download has started"); + } + this.isDownloading = false; + + NativeImage nativeImage = new NativeImage(NativeImage.Format.RGBA, width, height, false); + + GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, this.pboId); + ByteBuffer buffer = GL30C.glMapBuffer(GL30C.GL_PIXEL_PACK_BUFFER, GL30C.GL_READ_ONLY); + + if (buffer == null) { + throw new IllegalStateException("OpenGL error occurred while mapping buffer"); + } + + // Copy bytes + MemoryUtil.memCopy(MemoryUtil.memAddress(buffer), nativeImage.pixels, nativeImage.size); + +// for (int y = 0; y < nativeImage.getHeight(); ++y) { +// for (int x = 0; x < nativeImage.getWidth(); ++x) { +// int rgba = nativeImage.getPixelRGBA(x, y); +// nativeImage.setPixelRGBA(x, y, (rgba & 0xFFFFFF) | (80 << NativeImage.Format.RGBA.alphaOffset())); +// } +// } + + nativeImage.flipY(); + + GL30C.glUnmapBuffer(GL30C.GL_PIXEL_PACK_BUFFER); + GL30C.glBindBuffer(GL30C.GL_PIXEL_PACK_BUFFER, 0); + + return nativeImage; + } + + public void close() { + if (this.framebuffer != null) { + this.framebuffer.destroyBuffers(); + this.framebuffer = null; + } + if (this.pboId != -1) { + GL30C.glDeleteBuffers(this.pboId); + this.pboId = -1; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java new file mode 100644 index 0000000..cde7952 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/exporting/SaveableFramebufferQueue.java @@ -0,0 +1,68 @@ +package com.moulberry.flashback.exporting; + +import com.mojang.blaze3d.platform.NativeImage; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; + +public class SaveableFramebufferQueue implements AutoCloseable { + + private final int width; + private final int height; + + private static final int CAPACITY = 3; + + private final List available = new ArrayList<>(); + private final List waiting = new ArrayList<>(); + + public SaveableFramebufferQueue(int width, int height) { + this.width = width; + this.height = height; + + for (int i = 0; i < CAPACITY; i++) { + this.available.add(new SaveableFramebuffer()); + } + } + + public SaveableFramebuffer take() { + if (this.available.isEmpty()) { + throw new IllegalStateException("No textures available!"); + } + return this.available.removeFirst(); + } + + public void startDownload(SaveableFramebuffer texture) { + texture.startDownload(this.width, this.height); + this.waiting.add(texture); + } + + public @Nullable NativeImage finishDownload(boolean drain) { + if (this.waiting.isEmpty()) { + return null; + } + + if (!drain && !this.available.isEmpty()) { + return null; + } + + SaveableFramebuffer texture = this.waiting.removeFirst(); + NativeImage nativeImage = texture.finishDownload(this.width, this.height); + this.available.add(texture); + return nativeImage; + } + + @Override + public void close() { + for (SaveableFramebuffer texture : this.waiting) { + texture.close(); + } + for (SaveableFramebuffer texture : this.available) { + texture.close(); + } + this.waiting.clear(); + this.available.clear(); + } + + +} diff --git a/src/client/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java b/src/main/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java similarity index 100% rename from src/client/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java rename to src/main/java/com/moulberry/flashback/ext/ItemInHandRendererExt.java diff --git a/src/main/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java b/src/main/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java new file mode 100644 index 0000000..01f3ff6 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/ext/LevelChunkSectionExt.java @@ -0,0 +1,8 @@ +package com.moulberry.flashback.ext; + +public interface LevelChunkSectionExt { + + int flashback$getCachedChunkId(); + void flashback$setCachedChunkId(int id); + +} diff --git a/src/client/java/com/moulberry/flashback/ext/MinecraftExt.java b/src/main/java/com/moulberry/flashback/ext/MinecraftExt.java similarity index 82% rename from src/client/java/com/moulberry/flashback/ext/MinecraftExt.java rename to src/main/java/com/moulberry/flashback/ext/MinecraftExt.java index 0f4cc15..a16810d 100644 --- a/src/client/java/com/moulberry/flashback/ext/MinecraftExt.java +++ b/src/main/java/com/moulberry/flashback/ext/MinecraftExt.java @@ -4,10 +4,13 @@ import net.minecraft.server.WorldStem; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.world.level.storage.LevelStorageSource; +import java.nio.file.Path; +import java.util.UUID; + public interface MinecraftExt { void flashback$forceClientTick(); - void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem); + void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem, UUID playbackUUID, Path path); float flashback$getLocalPlayerPartialTick(); } diff --git a/src/client/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java b/src/main/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java similarity index 100% rename from src/client/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java rename to src/main/java/com/moulberry/flashback/ext/ServerConfigurationPacketListenerImplExt.java diff --git a/src/client/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java b/src/main/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java similarity index 100% rename from src/client/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java rename to src/main/java/com/moulberry/flashback/ext/ServerGamePacketListenerImplExt.java diff --git a/src/client/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java b/src/main/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java similarity index 100% rename from src/client/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java rename to src/main/java/com/moulberry/flashback/ext/ThreadedLevelLightEngineExt.java diff --git a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java new file mode 100644 index 0000000..b87389f --- /dev/null +++ b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java @@ -0,0 +1,312 @@ +package com.moulberry.flashback.io; + +import com.mojang.blaze3d.platform.NativeImage; +import com.moulberry.flashback.CachedChunkPacket; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.SneakyThrow; +import com.moulberry.flashback.TempFolderProvider; +import com.moulberry.flashback.action.ActionConfigurationPacket; +import com.moulberry.flashback.action.ActionCreateLocalPlayer; +import com.moulberry.flashback.action.ActionGamePacket; +import com.moulberry.flashback.action.ActionLevelChunkCached; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minecraft.client.Minecraft; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.game.ClientGamePacketListener; +import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; +import net.minecraft.network.protocol.game.ClientboundLoginPacket; + +import java.io.IOException; +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; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; +import java.util.function.Consumer; + +public class AsyncReplaySaver { + + private final ArrayBlockingQueue> tasks = new ArrayBlockingQueue<>(256); + private final AtomicReference error = new AtomicReference<>(null); + private final AtomicBoolean shouldStop = new AtomicBoolean(false); + private final AtomicBoolean hasStopped = new AtomicBoolean(false); + + private final Path recordFolder; + + public AsyncReplaySaver(RegistryAccess registryAccess) { + this.recordFolder = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.RECORDING, UUID.randomUUID()); + + ReplayWriter replayWriter = new ReplayWriter(registryAccess); + new Thread(() -> { + while (true) { + try { + Consumer task = this.tasks.poll(10, TimeUnit.MILLISECONDS); + + if (task == null) { + if (this.shouldStop.get()) { + this.hasStopped.set(true); + return; + } else { + continue; + } + } + + task.accept(replayWriter); + } catch (Throwable t) { + this.error.set(t); + this.hasStopped.set(true); + return; + } + } + }).start(); + } + + public void submit(Consumer consumer) { + this.checkForError(); + + if (this.hasStopped.get()) { + throw new IllegalStateException("Cannot submit task to AsyncReplayWriter that has already stopped"); + } + + while (true) { + try { + this.tasks.put(consumer); + break; + } catch (InterruptedException ignored) {} + } + } + + private final Int2ObjectMap> cachedChunkPackets = new Int2ObjectOpenHashMap<>(); + private int totalWrittenChunkPackets = 0; + + public void writeGamePackets(StreamCodec> gamePacketCodec, + List> packets) { + List> packetCopy = new ArrayList<>(packets); + this.submit(writer -> { + RegistryFriendlyByteBuf chunkCacheOutput = null; + + FriendlyByteBuf customPayloadTempBuffer = null; + + for (Packet packet : packetCopy) { + if (packet instanceof ClientboundLevelChunkWithLightPacket levelChunkPacket) { + int index = -1; + + CachedChunkPacket cachedChunkPacket = new CachedChunkPacket(levelChunkPacket, -1); + int hashCode = cachedChunkPacket.hashCode(); + + boolean add = true; + + List cached = this.cachedChunkPackets.get(hashCode); + if (cached == null) { + cached = new ArrayList<>(); + this.cachedChunkPackets.put(hashCode, cached); + } else { + for (CachedChunkPacket existingChunkPacket : cached) { + if (existingChunkPacket.equals(cachedChunkPacket)) { + add = false; + index = existingChunkPacket.index; + break; + } + } + } + + if (add) { + if (chunkCacheOutput == null) { + chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), writer.registryAccess()); + } + + // Write placeholder value for size + int startWriterIndex = chunkCacheOutput.writerIndex(); + chunkCacheOutput.writeInt(-1); + + // Write chunk packet + gamePacketCodec.encode(chunkCacheOutput, packet); + int endWriterIndex = chunkCacheOutput.writerIndex(); + + // Write real size value + int size = endWriterIndex - startWriterIndex - 4; + chunkCacheOutput.writerIndex(startWriterIndex); + chunkCacheOutput.writeInt(size); + chunkCacheOutput.writerIndex(endWriterIndex); + + index = this.totalWrittenChunkPackets; + this.totalWrittenChunkPackets += 1; + + cachedChunkPacket.index = index; + cached.add(cachedChunkPacket); + } + + writer.startAction(ActionLevelChunkCached.INSTANCE); + writer.friendlyByteBuf().writeVarInt(index); + writer.finishAction(ActionLevelChunkCached.INSTANCE); + + continue; + } + + if (packet instanceof ClientboundCustomPayloadPacket) { + // Some mods might throw errors when encoding packets, so this + // attempts to encode the packet before starting the action + try { + if (customPayloadTempBuffer == null) { + customPayloadTempBuffer = new RegistryFriendlyByteBuf(Unpooled.buffer(), writer.registryAccess()); + } + + customPayloadTempBuffer.clear(); + gamePacketCodec.encode(customPayloadTempBuffer, packet); + + writer.startAction(ActionGamePacket.INSTANCE); + writer.friendlyByteBuf().writeBytes(customPayloadTempBuffer); + writer.finishAction(ActionGamePacket.INSTANCE); + } catch (Exception ignored) {} + } else { + writer.startAction(ActionGamePacket.INSTANCE); + gamePacketCodec.encode(writer.friendlyByteBuf(), packet); + writer.finishAction(ActionGamePacket.INSTANCE); + } + + if (packet instanceof ClientboundLoginPacket) { + LocalPlayer localPlayer = Minecraft.getInstance().player; + if (localPlayer != null) { + writer.startAction(ActionCreateLocalPlayer.INSTANCE); + RegistryFriendlyByteBuf registryFriendlyByteBuf = writer.friendlyByteBuf(); + registryFriendlyByteBuf.writeUUID(localPlayer.getUUID()); + registryFriendlyByteBuf.writeDouble(localPlayer.getX()); + registryFriendlyByteBuf.writeDouble(localPlayer.getY()); + registryFriendlyByteBuf.writeDouble(localPlayer.getZ()); + registryFriendlyByteBuf.writeFloat(localPlayer.getXRot()); + registryFriendlyByteBuf.writeFloat(localPlayer.getYRot()); + registryFriendlyByteBuf.writeFloat(localPlayer.getYHeadRot()); + registryFriendlyByteBuf.writeVec3(localPlayer.getDeltaMovement()); + + ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, localPlayer.getGameProfile()); + + registryFriendlyByteBuf.writeVarInt(Minecraft.getInstance().gameMode.getPlayerMode().getId()); + + writer.finishAction(ActionCreateLocalPlayer.INSTANCE); + } + } + } + + if (chunkCacheOutput != null && chunkCacheOutput.writerIndex() > 0) { + try { + byte[] bytes = new byte[chunkCacheOutput.writerIndex()]; + chunkCacheOutput.getBytes(0, bytes); + + Path levelChunkCachePath = this.recordFolder.resolve("level_chunk_cache"); + Files.write(levelChunkCachePath, bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC); + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + } + }); + } + + + public void writeConfigurationPackets(StreamCodec> configurationPacketCodec, + List> packets) { + List> packetCopy = new ArrayList<>(packets); + this.submit(writer -> { + for (Packet packet : packetCopy) { + writer.startAction(ActionConfigurationPacket.INSTANCE); + configurationPacketCodec.encode(writer.friendlyByteBuf(), packet); + writer.finishAction(ActionConfigurationPacket.INSTANCE); + } + }); + } + + public void writeIcon(NativeImage nativeImage) { + int width = nativeImage.getWidth(); + int height = nativeImage.getHeight(); + int x = 0; + int y = 0; + + if (width > height) { + x = (width - height) / 2; + width = height; + } else { + y = (height - width) / 2; + height = width; + } + + try (NativeImage scaledImage = new NativeImage(64, 64, false);){ + nativeImage.resizeSubRectTo(x, y, width, height, scaledImage); + scaledImage.writeToFile(this.recordFolder.resolve("icon.png")); + } catch (IOException e) { + Flashback.LOGGER.warn("Couldn't save screenshot", e); + } finally { + nativeImage.close(); + } + } + + public void writeReplayChunk(String chunkName, String metadata) { + this.submit(writer -> { + try { + Path chunkFile = this.recordFolder.resolve(chunkName); + Files.write(chunkFile, writer.popBytes()); + + Path metaFile = this.recordFolder.resolve("metadata.json"); + if (Files.exists(metaFile)) { + Files.move(metaFile, this.recordFolder.resolve("metadata.json.old"), StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING); + } + + Files.writeString(metaFile, metadata); + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + }); + } + + private void waitForTasks() { + checkForError(); + + if (this.hasStopped.get()) { + throw new IllegalStateException("Cannot wait for tasks on AsyncReplayWriter that has already stopped"); + } + + while (!this.tasks.isEmpty()) { + checkForError(); + LockSupport.parkNanos("waiting for async replay writer to finish tasks", 100000L); + } + } + + public Path finish() { + this.waitForTasks(); + + this.shouldStop.set(true); + + while (!this.hasStopped.get()) { + checkForError(); + LockSupport.parkNanos("waiting for async replay writer to stop", 100000L); + } + + checkForError(); + + return this.recordFolder; + } + + private void checkForError() { + Throwable t = error.get(); + if (t != null) { + SneakyThrow.sneakyThrow(t); + } + } +} diff --git a/src/client/java/com/moulberry/flashback/io/ReplayReader.java b/src/main/java/com/moulberry/flashback/io/ReplayReader.java similarity index 91% rename from src/client/java/com/moulberry/flashback/io/ReplayReader.java rename to src/main/java/com/moulberry/flashback/io/ReplayReader.java index 138f2eb..287af36 100644 --- a/src/client/java/com/moulberry/flashback/io/ReplayReader.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayReader.java @@ -1,6 +1,6 @@ package com.moulberry.flashback.io; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.action.Action; import com.moulberry.flashback.action.ActionRegistry; @@ -14,9 +14,9 @@ import net.minecraft.resources.ResourceLocation; public class ReplayReader { - private FriendlyByteBuf friendlyByteBuf; - private int replaySnapshotOffset; - private int replayActionsOffset; + private final FriendlyByteBuf friendlyByteBuf; + private final int replaySnapshotOffset; + private final int replayActionsOffset; private RegistryAccess registryAccess; private Action lastAction = null; private final Int2ObjectMap actions = new Int2ObjectOpenHashMap<>(); @@ -26,7 +26,7 @@ public class ReplayReader { this.registryAccess = registryAccess; int magic = this.friendlyByteBuf.readInt(); - if (magic != FlashbackClient.MAGIC) { + if (magic != Flashback.MAGIC) { throw new RuntimeException("Invalid magic"); } @@ -42,7 +42,7 @@ public class ReplayReader { } } - int snapshotSize = this.friendlyByteBuf.readVarInt(); + int snapshotSize = this.friendlyByteBuf.readInt(); this.replaySnapshotOffset = this.friendlyByteBuf.readerIndex(); this.friendlyByteBuf.skipBytes(snapshotSize); this.replayActionsOffset = this.friendlyByteBuf.readerIndex(); @@ -69,7 +69,7 @@ public class ReplayReader { } this.lastAction = action; - int size = this.friendlyByteBuf.readVarInt(); + int size = this.friendlyByteBuf.readInt(); ByteBuf slice = this.friendlyByteBuf.readSlice(size); RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess); action.handle(replayServer, registryFriendlyByteBuf); @@ -97,7 +97,7 @@ public class ReplayReader { } this.lastAction = action; - int size = this.friendlyByteBuf.readVarInt(); + int size = this.friendlyByteBuf.readInt(); ByteBuf slice = this.friendlyByteBuf.readSlice(size); RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess); action.handle(replayServer, registryFriendlyByteBuf); diff --git a/src/client/java/com/moulberry/flashback/io/ReplayWriter.java b/src/main/java/com/moulberry/flashback/io/ReplayWriter.java similarity index 60% rename from src/client/java/com/moulberry/flashback/io/ReplayWriter.java rename to src/main/java/com/moulberry/flashback/io/ReplayWriter.java index 79b74e6..bb643b3 100644 --- a/src/client/java/com/moulberry/flashback/io/ReplayWriter.java +++ b/src/main/java/com/moulberry/flashback/io/ReplayWriter.java @@ -1,6 +1,6 @@ package com.moulberry.flashback.io; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.action.Action; import com.moulberry.flashback.action.ActionRegistry; import io.netty.buffer.ByteBuf; @@ -8,7 +8,6 @@ import io.netty.buffer.Unpooled; import it.unimi.dsi.fastutil.objects.Reference2IntMap; import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; import net.minecraft.core.RegistryAccess; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import java.util.List; @@ -16,22 +15,25 @@ import java.util.Objects; public class ReplayWriter { - private FriendlyByteBuf snapshotBuffer = null; - private final FriendlyByteBuf writeBuffer; private final ByteBuf dataBufferInner; private RegistryFriendlyByteBuf dataBuffer; private Reference2IntMap registeredActions; private Action writingAction = null; + private RegistryAccess registryAccess; + + private int snapshotSizeWriterIndex = -1; + private int actionSizeWriterIndex = -1; + private static final int STATE_EMPTY = 0; private static final int STATE_WRITING_SNAPSHOT = 1; private static final int STATE_WRITING_DATA = 2; private int state = STATE_EMPTY; public ReplayWriter(RegistryAccess registryAccess) { - this.writeBuffer = new FriendlyByteBuf(Unpooled.buffer()); this.dataBufferInner = Unpooled.buffer(); this.dataBuffer = new RegistryFriendlyByteBuf(this.dataBufferInner, registryAccess); + this.registryAccess = registryAccess; this.writeHeader(); } @@ -40,16 +42,16 @@ public class ReplayWriter { this.registeredActions.defaultReturnValue(-1); // Reset to start - this.writeBuffer.writerIndex(0); + this.dataBuffer.writerIndex(0); // Magic - this.writeBuffer.writeInt(FlashbackClient.MAGIC); + this.dataBuffer.writeInt(Flashback.MAGIC); // Actions List actions = ActionRegistry.getActions(); - this.writeBuffer.writeVarInt(actions.size()); + this.dataBuffer.writeVarInt(actions.size()); for (Action action : ActionRegistry.getActions()) { - this.writeBuffer.writeResourceLocation(action.name()); + this.dataBuffer.writeResourceLocation(action.name()); this.registeredActions.put(action, this.registeredActions.size()); } @@ -61,12 +63,14 @@ public class ReplayWriter { newDataBuffer.writerIndex(this.dataBuffer.writerIndex()); newDataBuffer.readerIndex(this.dataBuffer.readerIndex()); this.dataBuffer = newDataBuffer; + this.registryAccess = registryAccess; } public void startSnapshot() { if (this.state == STATE_EMPTY) { this.state = STATE_WRITING_SNAPSHOT; - this.snapshotBuffer = new FriendlyByteBuf(Unpooled.buffer()); + this.snapshotSizeWriterIndex = this.dataBuffer.writerIndex(); + this.dataBuffer.writeInt(0); } else { throw new IllegalStateException("Can only start snapshot in STATE_EMPTY"); } @@ -76,43 +80,38 @@ public class ReplayWriter { if (this.state == STATE_WRITING_SNAPSHOT) { this.state = STATE_WRITING_DATA; - byte[] written = new byte[this.snapshotBuffer.writerIndex()]; - this.snapshotBuffer.getBytes(0, written); - this.snapshotBuffer.writerIndex(0); + if (this.snapshotSizeWriterIndex < 0) { + throw new IllegalStateException("Snapshot size index wasn't set (" + this.snapshotSizeWriterIndex + ")"); + } - this.writeBuffer.writeVarInt(written.length); - this.writeBuffer.writeBytes(written); + int endPosition = this.dataBuffer.writerIndex(); + int written = this.dataBuffer.writerIndex() - this.snapshotSizeWriterIndex - 4; + + this.dataBuffer.writerIndex(this.snapshotSizeWriterIndex); + this.dataBuffer.writeInt(written); + this.dataBuffer.writerIndex(endPosition); + + this.snapshotSizeWriterIndex = -1; } else { throw new IllegalStateException("Can only end snapshot in STATE_WRITING_SNAPSHOT"); } } - private FriendlyByteBuf getWriteBuffer() { - if (this.state == STATE_EMPTY) { - throw new IllegalStateException("No write buffer in STATE_EMPTY"); - } else if (this.state == STATE_WRITING_SNAPSHOT) { - return this.snapshotBuffer; - } else if (this.state == STATE_WRITING_DATA) { - return this.writeBuffer; - } else { - throw new IllegalStateException("Unknown state: " + this.state); - } - } - public void startAndFinishAction(Action action) { Objects.requireNonNull(action); if (this.writingAction != null) { throw new RuntimeException("startAndFinishAction() called while still writing " + action.name()); } - FriendlyByteBuf writeBuffer = this.getWriteBuffer(); int id = this.registeredActions.getInt(action); if (id >= 0) { - writeBuffer.writeVarInt(id); + this.dataBuffer.writeVarInt(id); } else { throw new RuntimeException("Unknown action: " + action.name()); } - writeBuffer.writeVarInt(0); + this.dataBuffer.writeInt(0); + + this.actionSizeWriterIndex = -1; } public void startAction(Action action) { @@ -122,41 +121,55 @@ public class ReplayWriter { } this.writingAction = action; - FriendlyByteBuf writeBuffer = this.getWriteBuffer(); int id = this.registeredActions.getInt(action); if (id >= 0) { - writeBuffer.writeVarInt(id); + this.dataBuffer.writeVarInt(id); } else { throw new RuntimeException("Unknown action: " + action.name()); } + this.actionSizeWriterIndex = this.dataBuffer.writerIndex(); + this.dataBuffer.writeInt(0); } public void finishAction(Action action) { Objects.requireNonNull(action); if (this.writingAction == null) { - throw new RuntimeException("finishAction() called before startAction()"); + throw new IllegalStateException("finishAction() called before startAction()"); } if (this.writingAction != action) { - throw new RuntimeException("finishAction() called with wrong action, expected " + this.writingAction.name() + ", got " + action.name()); + throw new IllegalStateException("finishAction() called with wrong action, expected " + this.writingAction.name() + ", got " + action.name()); } this.writingAction = null; - byte[] written = new byte[this.dataBuffer.writerIndex()]; - this.dataBuffer.getBytes(0, written); - this.dataBuffer.writerIndex(0); + if (this.actionSizeWriterIndex < 0) { + throw new IllegalStateException("Action size index wasn't set (" + this.actionSizeWriterIndex + ")"); + } - FriendlyByteBuf writeBuffer = this.getWriteBuffer(); - writeBuffer.writeVarInt(written.length); - writeBuffer.writeBytes(written); + int endPosition = this.dataBuffer.writerIndex(); + int written = this.dataBuffer.writerIndex() - this.actionSizeWriterIndex - 4; + + this.dataBuffer.writerIndex(this.actionSizeWriterIndex); + this.dataBuffer.writeInt(written); + this.dataBuffer.writerIndex(endPosition); + + this.actionSizeWriterIndex = -1; } public RegistryFriendlyByteBuf friendlyByteBuf() { return this.dataBuffer; } + public RegistryAccess registryAccess() { + return this.registryAccess; + } + public byte[] popBytes() { - byte[] replay = new byte[this.writeBuffer.writerIndex()]; - this.writeBuffer.getBytes(0, replay); + if (this.writingAction != null) { + throw new IllegalStateException("popBytes() called while still writing action " + this.writingAction.name()); + } + + byte[] replay = new byte[this.dataBuffer.writerIndex()]; + this.dataBuffer.getBytes(0, replay); this.writeHeader(); diff --git a/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java new file mode 100644 index 0000000..de20860 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/keyframe/Keyframe.java @@ -0,0 +1,73 @@ +package com.moulberry.flashback.keyframe; + +import com.google.gson.*; +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.keyframe.interpolation.InterpolationType; + +import java.lang.reflect.Type; + +public abstract class Keyframe { + + public final Class operandClass; + private InterpolationType interpolationType = InterpolationType.SMOOTH; + + public Keyframe(Class operandClass) { + this.operandClass = operandClass; + } + + public InterpolationType interpolationType() { + return interpolationType; + } + + public void interpolationType(InterpolationType interpolationType) { + this.interpolationType = interpolationType; + } + + 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, + float lerpAmount, boolean lerpFromRight); + + public static class TypeAdapter implements JsonSerializer>, JsonDeserializer> { + @Override + 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) { + case "camera" -> context.deserialize(json, CameraKeyframe.class); + case "fov" -> context.deserialize(json, FOVKeyframe.class); + case "tickrate" -> context.deserialize(json, TickrateKeyframe.class); + case "time" -> context.deserialize(json, TimeOfDayKeyframe.class); + default -> throw new IllegalStateException("Unknown keyframe type: " + type); + }; + keyframe.interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class); + return keyframe; + } + + @Override + 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()); + } + jsonObject.add("interpolation_type", context.serialize(src.interpolationType)); + return jsonObject; + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/keyframe/KeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java similarity index 100% rename from src/client/java/com/moulberry/flashback/keyframe/KeyframeType.java rename to src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java similarity index 74% rename from src/client/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java rename to src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java index 1da7326..d3f4f2e 100644 --- a/src/client/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/CameraKeyframe.java @@ -1,5 +1,6 @@ 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.spline.CatmullRom; @@ -11,16 +12,18 @@ import net.minecraft.world.phys.Vec3; import org.joml.Quaternionf; import org.joml.Vector3f; +import java.lang.reflect.Type; + public class CameraKeyframe extends Keyframe { - private final Vec3 position; + private final Vector3f position; private final Quaternionf quaternion; public CameraKeyframe(Entity entity) { - this(entity.position(), new Quaternionf().rotationYXZ((float) Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), 0.0f)); + this(entity.position().toVector3f(), new Quaternionf().rotationYXZ((float) Math.toRadians(entity.getYRot()), (float) Math.toRadians(entity.getXRot()), 0.0f)); } - public CameraKeyframe(Vec3 position, Quaternionf quaternion) { + public CameraKeyframe(Vector3f position, Quaternionf quaternion) { super(Minecraft.class); this.position = position; this.quaternion = quaternion; @@ -67,9 +70,9 @@ public class CameraKeyframe extends Keyframe { float time3 = t3 - t0; // Calculate position - Vector3f position = CatmullRom.position(this.position.toVector3f(), - ((CameraKeyframe)p1).position.toVector3f(), ((CameraKeyframe)p2).position.toVector3f(), - ((CameraKeyframe)p3).position.toVector3f(), time1, time2, time3, amount); + Vector3f position = CatmullRom.position(this.position, + ((CameraKeyframe)p1).position, ((CameraKeyframe)p2).position, + ((CameraKeyframe)p3).position, time1, time2, time3, amount); float x = position.x; float y = position.y; @@ -107,4 +110,23 @@ public class CameraKeyframe extends Keyframe { player.moveTo(x, y, z, yaw, pitch); player.setDeltaMovement(Vec3.ZERO); } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + public CameraKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + 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); + } + + @Override + public JsonElement serialize(CameraKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.add("position", context.serialize(src.position)); + jsonObject.add("rotation", context.serialize(src.quaternion)); + return jsonObject; + } + } + } diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java similarity index 67% rename from src/client/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java rename to src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java index 7e41d38..e21e368 100644 --- a/src/client/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/FOVKeyframe.java @@ -1,5 +1,6 @@ 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; @@ -7,6 +8,8 @@ import com.moulberry.flashback.spline.CatmullRom; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; +import java.lang.reflect.Type; + public class FOVKeyframe extends Keyframe { private final int fov; @@ -18,7 +21,7 @@ public class FOVKeyframe extends Keyframe { @Override public void apply(Minecraft minecraft) { - minecraft.options.fov().set(this.fov); + ReplayVisuals.setFov(fov); } @Override @@ -29,8 +32,7 @@ public class FOVKeyframe extends Keyframe { } float fov = Interpolation.linear(this.fov, other.fov, amount); - minecraft.options.fov().set(Math.round(fov)); - ReplayVisuals.overrideFov = fov; + ReplayVisuals.setFov(fov); } @Override @@ -58,8 +60,23 @@ public class FOVKeyframe extends Keyframe { } } - minecraft.options.fov().set(Math.round(fov)); - ReplayVisuals.overrideFov = fov; + ReplayVisuals.setFov(fov); + } + + 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); + } + + @Override + public JsonElement serialize(FOVKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("fov", src.fov); + return jsonObject; + } } } diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java similarity index 71% rename from src/client/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java rename to src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java index 3afd5e4..7f08476 100644 --- a/src/client/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TickrateKeyframe.java @@ -1,11 +1,14 @@ 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.spline.CatmullRom; +import java.lang.reflect.Type; + public class TickrateKeyframe extends Keyframe { private float tickrate; @@ -53,4 +56,20 @@ public class TickrateKeyframe extends Keyframe { replayServer.desiredTickRate = tickrate; } + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + 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); + } + + @Override + public JsonElement serialize(TickrateKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("tickrate", src.tickrate); + return jsonObject; + } + } } diff --git a/src/client/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java similarity index 73% rename from src/client/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java rename to src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java index 63cfc55..1a6227b 100644 --- a/src/client/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java +++ b/src/main/java/com/moulberry/flashback/keyframe/impl/TimeOfDayKeyframe.java @@ -1,5 +1,6 @@ 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; @@ -9,6 +10,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.GameRules; +import java.lang.reflect.Type; + public class TimeOfDayKeyframe extends Keyframe { private final int time; @@ -65,4 +68,22 @@ public class TimeOfDayKeyframe extends Keyframe { this.setTime(minecraft, Math.round(timeOfDay)); } + + + public static class TypeAdapter implements JsonSerializer, JsonDeserializer { + @Override + 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); + } + + @Override + public JsonElement serialize(TimeOfDayKeyframe src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("time", src.time); + return jsonObject; + } + } + } diff --git a/src/client/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java b/src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java similarity index 100% rename from src/client/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java rename to src/main/java/com/moulberry/flashback/keyframe/interpolation/InterpolationType.java diff --git a/src/client/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java b/src/main/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java similarity index 100% rename from src/client/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java rename to src/main/java/com/moulberry/flashback/keyframe/interpolation/SidedInterpolationType.java diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java b/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java new file mode 100644 index 0000000..2de1b5a --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/MixinDebugScreenOverlay.java @@ -0,0 +1,31 @@ +package com.moulberry.flashback.mixin; + +import com.moulberry.flashback.Flashback; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.DebugScreenOverlay; +import org.spongepowered.asm.mixin.Mixin; +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; + +import java.util.List; + +@Mixin(value = DebugScreenOverlay.class, priority = 1100) +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()) { + ci.cancel(); + } + } + + @Inject(method = "getGameInformation", at = @At("RETURN")) + public void getGameInformation(CallbackInfoReturnable> info) { + if (Flashback.RECORDER != null) { + info.getReturnValue().add(Flashback.RECORDER.getDebugString()); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java new file mode 100644 index 0000000..801edfa --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java @@ -0,0 +1,125 @@ +package com.moulberry.flashback.mixin; + +import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; +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.editor.ui.ReplayUI; +import com.moulberry.flashback.exporting.PerfectFrames; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.minecraft.client.Camera; +import net.minecraft.client.CloudStatus; +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.Options; +import net.minecraft.client.particle.ParticleEngine; +import net.minecraft.client.renderer.*; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; +import net.minecraft.client.renderer.chunk.RenderRegionCache; +import net.minecraft.client.renderer.chunk.SectionRenderDispatcher; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.jetbrains.annotations.Nullable; +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(value = LevelRenderer.class, priority = 1100) +public abstract class MixinLevelRenderer { + + @Shadow @Final public ObjectArrayList visibleSections; + + @Shadow private @Nullable SectionRenderDispatcher sectionRenderDispatcher; + + @Shadow @Final public SectionOcclusionGraph sectionOcclusionGraph; + + @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; + ReplayUI.lastViewQuaternion = camera.rotation(); + } + + @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) { + 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) { + 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; + } + + @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) { + if (entity instanceof Player) { + return ReplayVisuals.renderPlayers; + } else { + return 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 { + return CloudStatus.OFF; + } + } + + @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; + } + + @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; + } + + @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")) + public void setupRender(LevelRenderer instance, Camera camera, Frustum frustum, boolean capturedFrustum, boolean isSpectator, Operation original) { + if (PerfectFrames.isEnabled()) { + boolean doCompile = true; + while (doCompile) { + doCompile = false; + + int before = this.visibleSections.size(); + original.call(instance, camera, frustum, capturedFrustum, isSpectator); + if (this.visibleSections.size() != before) { + doCompile = true; + } + + RenderRegionCache renderRegionCache = new RenderRegionCache(); + for (SectionRenderDispatcher.RenderSection renderSection : this.visibleSections) { + if (renderSection.isDirty()) { + this.sectionRenderDispatcher.rebuildSectionSync(renderSection, renderRegionCache); + renderSection.setNotDirty(); + doCompile = true; + } + } + + this.sectionRenderDispatcher.uploadAllPendingUploads(); + } + } else { + original.call(instance, camera, frustum, capturedFrustum, isSpectator); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinMinecraft.java b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java similarity index 78% rename from src/client/java/com/moulberry/flashback/mixin/client/MixinMinecraft.java rename to src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java index 83a1c3d..a2b9e5a 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/MixinMinecraft.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java @@ -1,21 +1,23 @@ -package com.moulberry.flashback.mixin.client; +package com.moulberry.flashback.mixin; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; import com.mojang.blaze3d.systems.RenderSystem; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ReplayVisuals; -import com.moulberry.flashback.keyframe.Keyframes; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.exporting.PerfectFrames; import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.ext.MinecraftExt; -import com.moulberry.flashback.ui.ReplayUI; +import com.moulberry.flashback.editor.ui.ReplayUI; import it.unimi.dsi.fastutil.floats.FloatUnaryOperator; import net.minecraft.CrashReport; import net.minecraft.ReportedException; import net.minecraft.Util; +import net.minecraft.client.DeltaTracker; import net.minecraft.client.Minecraft; -import net.minecraft.client.Timer; import net.minecraft.client.User; import net.minecraft.client.gui.screens.LevelLoadingScreen; import net.minecraft.client.gui.screens.Overlay; @@ -42,6 +44,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.block.entity.SkullBlockEntity; import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -54,9 +57,11 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.io.File; import java.net.SocketAddress; +import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import java.util.Queue; +import java.util.UUID; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; @@ -124,14 +129,27 @@ public abstract class MixinMinecraft implements MinecraftExt { @Final public ParticleEngine particleEngine; - @Shadow - public abstract float getFrameTime(); + @Shadow @Final public DeltaTracker.Timer timer; @Inject(method="", at=@At("RETURN")) public void init(GameConfig gameConfig, CallbackInfo ci) { ReplayUI.init(); } + @Inject(method = "pauseGame", at = @At("HEAD"), cancellable = true) + public void pauseGame(boolean bl, CallbackInfo ci) { + if (Flashback.EXPORT_JOB != null) { + ci.cancel(); + } + } + + @Inject(method = "renderNames", at = @At("HEAD"), cancellable = true) + private static void renderNames(CallbackInfoReturnable cir) { + if (!ReplayVisuals.renderNametags) { + cir.setReturnValue(false); + } + } + @Inject(method = "runTick", at=@At(value = "INVOKE", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;blitToScreen(II)V", shift = At.Shift.AFTER)) public void afterMainBlit(boolean bl, CallbackInfo ci) { if (!RenderSystem.isOnRenderThread()) return; @@ -143,19 +161,23 @@ public abstract class MixinMinecraft implements MinecraftExt { @Inject(method = "tick", at = @At("RETURN")) public void tick(CallbackInfo ci) { - if (FlashbackClient.RECORDER != null) { - FlashbackClient.RECORDER.endTick(false); + if (Flashback.RECORDER != null) { + Flashback.RECORDER.endTick(false); } - ReplayServer replayServer = FlashbackClient.getReplayServer(); + EditorStateCache.saveIfNeeded(); + + ReplayServer replayServer = Flashback.getReplayServer(); boolean inReplay = replayServer != null; if (inReplay != inReplayLast) { inReplayLast = inReplay; if (inReplay) { ReplayVisuals.setupReplay(); + Minecraft.getInstance().options.hideGui = false; } else { ReplayVisuals.disable(); + EditorStateCache.reset(); } } @@ -182,6 +204,10 @@ public abstract class MixinMinecraft implements MinecraftExt { entity.moveTo(entity.lerpTargetX(), entity.lerpTargetY(), entity.lerpTargetZ(), entity.lerpTargetYRot(), entity.lerpTargetXRot()); } + if (entity.isPassenger()) { + entity.setDeltaMovement(Vec3.ZERO); + entity.getVehicle().positionRider(entity); + } } } } @@ -195,9 +221,9 @@ public abstract class MixinMinecraft implements MinecraftExt { this.forceClientTick = true; } - @WrapOperation(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Timer;advanceTime(J)I")) - public int runTick_advanceTime(Timer instance, long l, Operation original) { - int ticks = original.call(instance, l); + @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(); @@ -208,7 +234,7 @@ public abstract class MixinMinecraft implements MinecraftExt { @Inject(method = "getTickTargetMillis", at = @At("HEAD"), cancellable = true) public void getTickTargetMillis(float f, CallbackInfoReturnable cir) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { if (this.level == null) { return; } @@ -221,17 +247,22 @@ public abstract class MixinMinecraft implements MinecraftExt { } @Unique - private final Timer localPlayerTimer = new Timer(20.0f, 0, FloatUnaryOperator.identity()); + private final DeltaTracker.Timer localPlayerTimer = new DeltaTracker.Timer(20.0f, 0, FloatUnaryOperator.identity()); @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runAllTasks()V", shift = At.Shift.AFTER)) - public void runTick_runAllTasks(boolean bl, CallbackInfo ci) { - if (FlashbackClient.EXPORT_JOB != null && !ReplayUI.isActive()) { - FlashbackClient.EXPORT_JOB.run(); - FlashbackClient.EXPORT_JOB = null; + public void runTick_runAllTasks(boolean runTick, CallbackInfo ci) { + if (Flashback.EXPORT_JOB != null && !ReplayUI.isActive()) { + try { + PerfectFrames.enable(); + Flashback.EXPORT_JOB.run(); + } finally { + PerfectFrames.disable(); + Flashback.EXPORT_JOB = null; + } } - if (FlashbackClient.isInReplay()) { - int localPlayerTicks = localPlayerTimer.advanceTime(Util.getMillis()); + if (Flashback.isInReplay()) { + int localPlayerTicks = localPlayerTimer.advanceTime(Util.getMillis(), runTick); 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++) { @@ -243,18 +274,22 @@ public abstract class MixinMinecraft implements MinecraftExt { @Override public float flashback$getLocalPlayerPartialTick() { - return localPlayerTimer.partialTick; + if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) { + return this.timer.getGameTimeDeltaPartialTick(true); + } + return localPlayerTimer.getGameTimeDeltaPartialTick(true); } @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", ordinal = 1), cancellable = true) public void runTick_setErrorSection(boolean bl, CallbackInfo ci) { - ReplayServer replayServer = FlashbackClient.getReplayServer(); + ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer == null) { return; } if (!replayServer.replayPaused) { - Keyframes.applyKeyframes((Minecraft) (Object) this, replayServer.getPartialReplayTick()); + EditorState editorState = EditorStateCache.get(replayServer.getMetadata().replayIdentifier); + editorState.applyKeyframes((Minecraft) (Object) this, replayServer.getPartialReplayTick()); } if (!replayServer.doClientRendering()) { ci.cancel(); @@ -262,27 +297,28 @@ public abstract class MixinMinecraft implements MinecraftExt { } @Override - public void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem) { + public void flashback$startReplayServer(LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem stem, + UUID playbackUUID, Path path) { this.disconnect(); this.progressListener.set(null); Instant instant = Instant.now(); try { // levelStorageAccess.saveDataTag((RegistryAccess)worldStem.registries().compositeAccess(), worldStem.worldData()); - Services services = Services.create((YggdrasilAuthenticationService)this.authenticationService, (File)this.gameDirectory); + Services services = Services.create(this.authenticationService, this.gameDirectory); services.profileCache().setExecutor((Executor)this); SkullBlockEntity.setup(services, (Executor)this); GameProfileCache.setUsesAuthentication(false); - this.singleplayerServer = MinecraftServer.spin(thread -> new ReplayServer((Thread)thread, (Minecraft) (Object) this, + this.singleplayerServer = MinecraftServer.spin(thread -> new ReplayServer(thread, (Minecraft) (Object) this, levelStorageAccess, packRepository, stem, services, i -> { - StoringChunkProgressListener storingChunkProgressListener = StoringChunkProgressListener.createFromGameruleRadius((int)(i + 0)); + StoringChunkProgressListener storingChunkProgressListener = StoringChunkProgressListener.createFromGameruleRadius(i); this.progressListener.set(storingChunkProgressListener); return ProcessorChunkProgressListener.createStarted(storingChunkProgressListener, this.progressTasks::add); - })); + }, playbackUUID, path)); this.isLocalServer = true; this.updateReportEnvironment(ReportEnvironment.local()); // this.quickPlayLog.setWorldData(QuickPlayLog.Type.SINGLEPLAYER, levelStorageAccess.getLevelId(), worldStem.worldData().getLevelName()); } catch (Throwable throwable) { - CrashReport crashReport = CrashReport.forThrowable((Throwable)throwable, (String)"Starting replay server"); + CrashReport crashReport = CrashReport.forThrowable(throwable, "Starting replay server"); // CrashReportCategory crashReportCategory = crashReport.addCategory("Starting integrated server"); // crashReportCategory.setDetail("Level ID", (Object)levelStorageAccess.getLevelId()); // crashReportCategory.setDetail("Level Name", () -> worldStem.worldData().getLevelName()); diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinMouseHandler.java b/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java similarity index 87% rename from src/client/java/com/moulberry/flashback/mixin/client/MixinMouseHandler.java rename to src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java index 68d1ac3..5c1ec7d 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/MixinMouseHandler.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java @@ -1,7 +1,7 @@ -package com.moulberry.flashback.mixin.client; +package com.moulberry.flashback.mixin; -import com.moulberry.flashback.ui.CustomImGuiImplGlfw; -import com.moulberry.flashback.ui.ReplayUI; +import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw; +import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.MouseHandler; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java new file mode 100644 index 0000000..0df649e --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java @@ -0,0 +1,28 @@ +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.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) { + ReplayUI.setupMainViewport(); + } else { + original.call(left, bottom, width, height); + } + } + + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinThreadedLevelLightEngine.java b/src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java similarity index 95% rename from src/client/java/com/moulberry/flashback/mixin/client/MixinThreadedLevelLightEngine.java rename to src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java index b576b12..32b57f6 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/MixinThreadedLevelLightEngine.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinThreadedLevelLightEngine.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client; +package com.moulberry.flashback.mixin; import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; import net.minecraft.server.level.ThreadedLevelLightEngine; diff --git a/src/client/java/com/moulberry/flashback/mixin/client/MixinWindow.java b/src/main/java/com/moulberry/flashback/mixin/MixinWindow.java similarity index 67% rename from src/client/java/com/moulberry/flashback/mixin/client/MixinWindow.java rename to src/main/java/com/moulberry/flashback/mixin/MixinWindow.java index c87949b..d986ce2 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/MixinWindow.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinWindow.java @@ -1,7 +1,10 @@ -package com.moulberry.flashback.mixin.client; +package com.moulberry.flashback.mixin; import com.mojang.blaze3d.platform.Window; -import com.moulberry.flashback.ui.ReplayUI; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.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; @@ -35,28 +38,32 @@ public abstract class MixinWindow { @Inject(method = "getWidth", at=@At("HEAD"), cancellable = true) public void getWidth(CallbackInfoReturnable cir) { - if (ReplayUI.isActive()) { + 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)); } } @Inject(method = "getHeight", at=@At("HEAD"), cancellable = true) public void getHeight(CallbackInfoReturnable cir) { - if (ReplayUI.isActive()) { + 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)); } } @Inject(method = "getScreenWidth", at=@At("HEAD"), cancellable = true) public void getScreenWidth(CallbackInfoReturnable cir) { - if (ReplayUI.isActive()) { + if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { cir.setReturnValue(ReplayUI.getNewGameWidth(1)); } } @Inject(method = "getScreenHeight", at=@At("HEAD"), cancellable = true) public void getScreenHeight(CallbackInfoReturnable cir) { - if (ReplayUI.isActive()) { + if (ReplayUI.isActive() && ReplayVisuals.sizing != Sizing.UNDERLAY) { cir.setReturnValue(ReplayUI.getNewGameHeight(1)); } } @@ -90,7 +97,19 @@ public abstract class MixinWindow { @Inject(method = "calculateScale", at=@At("HEAD"), cancellable = true) public void calculateScale(int scale, boolean forceEven, CallbackInfoReturnable cir) { - if (ReplayUI.isActive()) { + if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) { + int fbw = Flashback.EXPORT_JOB.getWidth(); + int fbh = Flashback.EXPORT_JOB.getHeight(); + + int j = 1; + while (j != scale && j < fbw && j < fbh && fbw / (j + 1) >= 320 && fbh / (j + 1) >= 240) { + j++; + } + if (forceEven && j % 2 != 0) { + 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); @@ -107,7 +126,18 @@ public abstract class MixinWindow { @Inject(method = "setGuiScale", at=@At("HEAD"), cancellable = true) public void setGuiScale(double d, CallbackInfo ci) { - if (ReplayUI.isActive()) { + if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.shouldChangeFramebufferSize()) { + int fbw = Flashback.EXPORT_JOB.getWidth(); + int fbh = Flashback.EXPORT_JOB.getHeight(); + + this.guiScale = d; + int i = (int)((double)fbw / d); + this.guiScaledWidth = (double)fbw / d > (double)i ? i + 1 : i; + int j = (int)((double)fbh / d); + 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); diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/MixinAxiomEditorUI.java b/src/main/java/com/moulberry/flashback/mixin/compat/MixinAxiomEditorUI.java new file mode 100644 index 0000000..a3b80c2 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/MixinAxiomEditorUI.java @@ -0,0 +1,29 @@ +package com.moulberry.flashback.mixin.compat; + +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.editor.ui.ReplayUI; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; +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.CallbackInfoReturnable; + +@IfModLoaded("axiom") +@Pseudo +@Mixin(targets = "com.moulberry.axiom.editor.EditorUI", remap = false) +public class MixinAxiomEditorUI { + + @Shadow + private static boolean enabled; + + @Inject(method = "isActiveInternal", at = @At("HEAD"), cancellable = true) + private static void isActiveInternal(CallbackInfoReturnable cir) { + if (ReplayUI.isActive() || Flashback.isInReplay()) { + enabled = false; + 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 new file mode 100644 index 0000000..24fb32c --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/MixinSodiumWorldRenderer.java @@ -0,0 +1,31 @@ +package com.moulberry.flashback.mixin.compat; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.RenderBuffers; +import net.minecraft.server.level.BlockDestructionProgress; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Pseudo; +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.SortedSet; + +@IfModLoaded(value = "sodium", aliases = "embeddium") +@Pseudo +@Mixin(targets = {"net.caffeinemc.mods.sodium.client.render.SodiumWorldRenderer", "me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer"}) +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) { + ci.cancel(); + } + } + +} \ No newline at end of file diff --git a/src/client/java/com/moulberry/flashback/mixin/client/packet_fix/MixinBossHealthOverlay.java b/src/main/java/com/moulberry/flashback/mixin/packet_fix/MixinBossHealthOverlay.java similarity index 93% rename from src/client/java/com/moulberry/flashback/mixin/client/packet_fix/MixinBossHealthOverlay.java rename to src/main/java/com/moulberry/flashback/mixin/packet_fix/MixinBossHealthOverlay.java index b69b40a..597715f 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/packet_fix/MixinBossHealthOverlay.java +++ b/src/main/java/com/moulberry/flashback/mixin/packet_fix/MixinBossHealthOverlay.java @@ -1,6 +1,6 @@ -package com.moulberry.flashback.mixin.client.packet_fix; +package com.moulberry.flashback.mixin.packet_fix; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import net.minecraft.client.gui.components.BossHealthOverlay; import net.minecraft.client.gui.components.LerpingBossEvent; import net.minecraft.network.chat.Component; @@ -28,7 +28,7 @@ public class MixinBossHealthOverlay { */ @Inject(method = "update", at = @At("HEAD"), cancellable = true) public void update(ClientboundBossEventPacket clientboundBossEventPacket, CallbackInfo ci) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { clientboundBossEventPacket.dispatch(new ClientboundBossEventPacket.Handler() { @Override public void updateProgress(UUID uuid, float f) { diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinArmorStandRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinArmorStandRenderer.java similarity index 87% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinArmorStandRenderer.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinArmorStandRenderer.java index 3af4760..801aacc 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinArmorStandRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinArmorStandRenderer.java @@ -1,8 +1,8 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import net.minecraft.client.renderer.entity.ArmorStandRenderer; import net.minecraft.world.entity.decoration.ArmorStand; import org.spongepowered.asm.mixin.Mixin; @@ -20,7 +20,7 @@ public class MixinArmorStandRenderer { @Inject(method = "setupRotations(Lnet/minecraft/world/entity/decoration/ArmorStand;Lcom/mojang/blaze3d/vertex/PoseStack;FFFF)V", at = @At("HEAD"), cancellable = true) public void setupRotations(ArmorStand armorStand, PoseStack poseStack, float f, float g, float h, float i, CallbackInfo ci) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { poseStack.mulPose(Axis.YP.rotationDegrees(180.0F - g)); ci.cancel(); } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinClientCommonPacketListenerImpl.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinClientCommonPacketListenerImpl.java similarity index 69% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinClientCommonPacketListenerImpl.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinClientCommonPacketListenerImpl.java index 3c3c7d5..30dd962 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinClientCommonPacketListenerImpl.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinClientCommonPacketListenerImpl.java @@ -1,9 +1,11 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.packet.FinishedServerTick; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; import net.minecraft.network.protocol.PacketUtils; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Final; @@ -34,7 +36,7 @@ public abstract class MixinClientCommonPacketListenerImpl { */ @Inject(method = "handleResourcePackPush", at = @At("HEAD"), cancellable = true) public void handleResourcePackPush(ClientboundResourcePackPushPacket clientboundResourcePackPushPacket, CallbackInfo ci) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { PacketUtils.ensureRunningOnSameThread(clientboundResourcePackPushPacket, (ClientCommonPacketListenerImpl)(Object)this, this.minecraft); UUID uuid = clientboundResourcePackPushPacket.id(); @@ -49,4 +51,14 @@ public abstract class MixinClientCommonPacketListenerImpl { } } + @Inject(method = "handleCustomPayload(Lnet/minecraft/network/protocol/common/ClientboundCustomPayloadPacket;)V", at = @At("HEAD"), cancellable = true) + public void handleCustomPayload(ClientboundCustomPayloadPacket clientboundCustomPayloadPacket, CallbackInfo ci) { + if (clientboundCustomPayloadPacket.payload() == FinishedServerTick.INSTANCE) { + if (Flashback.EXPORT_JOB != null) { + Flashback.EXPORT_JOB.onFinishedServerTick(); + } + ci.cancel(); + } + } + } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinEntity.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java similarity index 89% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinEntity.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java index 86efda4..71b17c2 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java @@ -1,6 +1,6 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.client.Minecraft; import net.minecraft.world.entity.Entity; @@ -26,7 +26,7 @@ public abstract class MixinEntity { @Inject(method = "isInvisibleTo", at = @At("HEAD"), cancellable = true) public void isInvisibleTo(Player player, CallbackInfoReturnable cir) { - ReplayServer replayServer = FlashbackClient.getReplayServer(); + ReplayServer replayServer = Flashback.getReplayServer(); if (replayServer != null && player == Minecraft.getInstance().player) { int localId = replayServer.getLocalPlayerId(); if (this.level.getEntity(localId) instanceof Player localPlayer) { diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinGameRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java similarity index 78% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinGameRenderer.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java index e6a9e47..ebc64c6 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinGameRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java @@ -1,14 +1,16 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.blaze3d.vertex.PoseStack; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.ext.ItemInHandRendererExt; import com.moulberry.flashback.ext.MinecraftExt; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; +import net.minecraft.client.Options; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.LocalPlayer; @@ -29,6 +31,15 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(GameRenderer.class) public class MixinGameRenderer { + + @WrapOperation(method = "render", at=@At(value = "FIELD", target = "Lnet/minecraft/client/Options;pauseOnLostFocus:Z")) + public boolean getPauseOnLostFocus(Options instance, Operation original) { + if (ReplayUI.isActive() || Flashback.EXPORT_JOB != null) { + return false; + } + return original.call(instance); + } + /* * Render item in hand for spectators in a replay */ @@ -39,7 +50,7 @@ public class MixinGameRenderer { @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 (FlashbackClient.getSpectatingPlayer() != null) { + if (Flashback.getSpectatingPlayer() != null) { return GameType.SURVIVAL; } return original.call(instance); @@ -47,8 +58,9 @@ public class MixinGameRenderer { @WrapOperation(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderHandsWithItems(FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/player/LocalPlayer;I)V")) public void renderItemInHand_renderHandsWithItems(ItemInHandRenderer instance, float f, PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, LocalPlayer localPlayer, int i, Operation original) { - AbstractClientPlayer spectatingPlayer = FlashbackClient.getSpectatingPlayer(); + AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer(); if (spectatingPlayer != null) { + f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(); ((ItemInHandRendererExt)instance).flashback$renderHandsWithItems(f, poseStack, bufferSource, spectatingPlayer, i); } else { original.call(instance, f, poseStack, bufferSource, localPlayer, i); @@ -57,7 +69,7 @@ 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 (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { f = ((MinecraftExt)this.minecraft).flashback$getLocalPlayerPartialTick(); } original.call(instance, blockGetter, entity, bl, bl2, f); @@ -65,27 +77,23 @@ public class MixinGameRenderer { @Inject(method = "tryTakeScreenshotIfNeeded", at = @At("HEAD"), cancellable = true) public void tryTakeScreenshotIfNeeded(CallbackInfo ci) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { ci.cancel(); } } @Inject(method = "getFov", at = @At("HEAD"), cancellable = true) public void getFov(Camera camera, float f, boolean bl, CallbackInfoReturnable cir) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { if (!bl) { cir.setReturnValue(70.0); return; } int fov = this.minecraft.options.fov().get().intValue(); - if (ReplayVisuals.overrideFov > 0.0) { - if (Math.abs(ReplayVisuals.overrideFov - fov) < 1) { - cir.setReturnValue((double) ReplayVisuals.overrideFov); - return; - } else { - ReplayVisuals.overrideFov = 0.0f; - } + if (ReplayVisuals.overrideFov) { + cir.setReturnValue((double) ReplayVisuals.overrideFovAmount); + return; } cir.setReturnValue((double) fov); } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinItemInHandRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java similarity index 96% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinItemInHandRenderer.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java index 856e9a6..e08d596 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinItemInHandRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinItemInHandRenderer.java @@ -1,8 +1,8 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; import com.google.common.base.MoreObjects; import com.mojang.blaze3d.vertex.PoseStack; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ext.ItemInHandRendererExt; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.renderer.ItemInHandRenderer; @@ -79,7 +79,7 @@ public abstract class MixinItemInHandRenderer implements ItemInHandRendererExt { @Inject(method = "tick", at = @At("HEAD"), cancellable = true) public void tick(CallbackInfo ci) { - AbstractClientPlayer spectatingPlayer = FlashbackClient.getSpectatingPlayer(); + AbstractClientPlayer spectatingPlayer = Flashback.getSpectatingPlayer(); if (spectatingPlayer == null) { this.lastSpectatingPlayer = null; } else { diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunkSection.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunkSection.java new file mode 100644 index 0000000..8acbb6b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunkSection.java @@ -0,0 +1,56 @@ +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/MixinLivingEntity.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLivingEntity.java new file mode 100644 index 0000000..779c118 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLivingEntity.java @@ -0,0 +1,40 @@ +package com.moulberry.flashback.mixin.playback; + +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(LivingEntity.class) +public abstract class MixinLivingEntity extends Entity { + + @Shadow + public abstract void lerpTo(double d, double e, double f, float g, float h, int i); + + @Shadow + public abstract void lerpHeadTo(float f, int i); + + public MixinLivingEntity(EntityType entityType, Level level) { + super(entityType, level); + } + + // todo: maybe reintroduce this lerpTo code? +// @Inject(method = "lerpTo", at = @At("HEAD"), cancellable = true) +// public void lerpTo(double d, double e, double f, float g, float h, int i, CallbackInfo ci) { +// if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) { +// this.lerpTo(d, e, f, g, h, 1); +// ci.cancel(); +// } +// } +// +// @Inject(method = "lerpHeadTo", at = @At("HEAD"), cancellable = true) +// public void lerpHeadTo(float f, int i, CallbackInfo ci) { +// if (FlashbackClient.isInReplay() && i > 1 && FlashbackClient.getReplayServer().getLocalPlayerId() == this.getId() && Minecraft.getInstance().getCameraEntity() == this) { +// this.lerpHeadTo(f, 1); +// ci.cancel(); +// } +// } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinPlayerChunkSender.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinPlayerChunkSender.java similarity index 86% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinPlayerChunkSender.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinPlayerChunkSender.java index fef32bd..4f8cfdb 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinPlayerChunkSender.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinPlayerChunkSender.java @@ -1,6 +1,6 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.network.PlayerChunkSender; import org.spongepowered.asm.mixin.Mixin; @@ -25,7 +25,7 @@ public class MixinPlayerChunkSender { @Inject(method = "sendNextChunks", at = @At("HEAD")) public void sendNextChunks(ServerPlayer serverPlayer, CallbackInfo ci) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { this.unacknowledgedBatches = 0; this.batchQuota = 0.0f; this.desiredChunksPerTick = Math.max(this.desiredChunksPerTick, 256.0f); diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinScoreboard.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinScoreboard.java new file mode 100644 index 0000000..c1ef9b7 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinScoreboard.java @@ -0,0 +1,31 @@ +package com.moulberry.flashback.mixin.playback; + +import com.moulberry.flashback.Flashback; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.numbers.NumberFormat; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; +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.CallbackInfoReturnable; + +@Mixin(Scoreboard.class) +public abstract class MixinScoreboard { + + @Shadow @Final private Object2ObjectMap objectivesByName; + + @Shadow public abstract void removeObjective(Objective objective); + + @Inject(method = "addObjective", at = @At("HEAD")) + public void addObjective(String string, ObjectiveCriteria objectiveCriteria, Component component, ObjectiveCriteria.RenderType renderType, boolean bl, NumberFormat numberFormat, CallbackInfoReturnable cir) { + if (Flashback.isInReplay() && this.objectivesByName.containsKey(string)) { + this.removeObjective(this.objectivesByName.get(string)); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinTickRateManager.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java similarity index 68% rename from src/client/java/com/moulberry/flashback/mixin/client/playback/MixinTickRateManager.java rename to src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java index b2b8d32..e6bda6e 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/playback/MixinTickRateManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinTickRateManager.java @@ -1,6 +1,6 @@ -package com.moulberry.flashback.mixin.client.playback; +package com.moulberry.flashback.mixin.playback; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import net.minecraft.client.Minecraft; import net.minecraft.server.ServerTickRateManager; import net.minecraft.world.TickRateManager; @@ -23,8 +23,12 @@ public abstract class MixinTickRateManager { @Inject(method = "isEntityFrozen", at = @At("HEAD"), cancellable = true) public void isEntityFrozen(Entity entity, CallbackInfoReturnable cir) { - if (this.isClientTickRateManager && FlashbackClient.isInReplay()) { - cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); + if (this.isClientTickRateManager && Flashback.isInReplay()) { + if (Flashback.EXPORT_JOB != null && Flashback.EXPORT_JOB.isRunning()) { + cir.setReturnValue(false); + } else { + cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player); + } } } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/record/MixinClientConfigurationPacketListenerImpl.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientConfigurationPacketListenerImpl.java similarity index 81% rename from src/client/java/com/moulberry/flashback/mixin/client/record/MixinClientConfigurationPacketListenerImpl.java rename to src/main/java/com/moulberry/flashback/mixin/record/MixinClientConfigurationPacketListenerImpl.java index 0d0a689..813443d 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/record/MixinClientConfigurationPacketListenerImpl.java +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinClientConfigurationPacketListenerImpl.java @@ -1,6 +1,6 @@ -package com.moulberry.flashback.mixin.client.record; +package com.moulberry.flashback.mixin.record; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientCommonPacketListenerImpl; import net.minecraft.client.multiplayer.ClientConfigurationPacketListenerImpl; @@ -22,8 +22,8 @@ public abstract class MixinClientConfigurationPacketListenerImpl extends ClientC @Inject(method = "handleConfigurationFinished", at = @At("RETURN")) public void handleConfigurationFinished(ClientboundFinishConfigurationPacket clientboundFinishConfigurationPacket, CallbackInfo ci) { - if (FlashbackClient.RECORDER != null) { - FlashbackClient.RECORDER.setRegistryAccess(((ClientPacketListener)this.connection.getPacketListener()).registryAccess()); + if (Flashback.RECORDER != null) { + Flashback.RECORDER.setRegistryAccess(((ClientPacketListener)this.connection.getPacketListener()).registryAccess()); } } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/record/MixinConnection.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinConnection.java similarity index 71% rename from src/client/java/com/moulberry/flashback/mixin/client/record/MixinConnection.java rename to src/main/java/com/moulberry/flashback/mixin/record/MixinConnection.java index 3dc94d9..f8a0432 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/record/MixinConnection.java +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinConnection.java @@ -1,6 +1,7 @@ -package com.moulberry.flashback.mixin.client.record; +package com.moulberry.flashback.mixin.record; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.record.Recorder; import net.minecraft.network.Connection; import net.minecraft.network.ConnectionProtocol; import net.minecraft.network.PacketListener; @@ -17,11 +18,12 @@ public class MixinConnection { @Inject(method = "genericsFtw", at = @At("HEAD")) private static void genericsFtw(Packet packet, PacketListener packetListener, CallbackInfo ci) { - if (FlashbackClient.RECORDER != null) { + Recorder recorder = Flashback.RECORDER; + if (recorder != null) { if (packetListener instanceof ClientGamePacketListener) { - FlashbackClient.RECORDER.writePacketAsync(packet, ConnectionProtocol.PLAY); + recorder.writePacketAsync(packet, ConnectionProtocol.PLAY); } else if (packetListener instanceof ClientConfigurationPacketListener) { - FlashbackClient.RECORDER.writePacketAsync(packet, ConnectionProtocol.CONFIGURATION); + recorder.writePacketAsync(packet, ConnectionProtocol.CONFIGURATION); } } } diff --git a/src/main/java/com/moulberry/flashback/mixin/record/MixinFFmpegFrameRecorder.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinFFmpegFrameRecorder.java new file mode 100644 index 0000000..262a243 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinFFmpegFrameRecorder.java @@ -0,0 +1,20 @@ +package com.moulberry.flashback.mixin.record; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import org.bytedeco.ffmpeg.avutil.AVFrame; +import org.bytedeco.javacv.FFmpegFrameRecorder; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(value = FFmpegFrameRecorder.class, remap = false) +public class MixinFFmpegFrameRecorder { + + // Don't change linesize, let it be calculated automatically + + @WrapOperation(method = "recordImage", remap = false, at = @At(value = "INVOKE", remap = false, target = "Lorg/bytedeco/ffmpeg/avutil/AVFrame;linesize(II)Lorg/bytedeco/ffmpeg/avutil/AVFrame;")) + private AVFrame changeLinesize(AVFrame instance, int i, int setter, Operation original) { + return instance; + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkGenerators.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinChunkGenerators.java similarity index 93% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkGenerators.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinChunkGenerators.java index f265ae9..0b15410 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinChunkGenerators.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinChunkGenerators.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.mojang.serialization.MapCodec; import com.moulberry.flashback.playback.EmptyLevelSource; diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinChunkStatusTasks.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinChunkStatusTasks.java new file mode 100644 index 0000000..0e6849b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinChunkStatusTasks.java @@ -0,0 +1,34 @@ +package com.moulberry.flashback.mixin.replay_server; + +import com.moulberry.flashback.Flashback; +import net.minecraft.server.level.GenerationChunkHolder; +import net.minecraft.util.StaticCache2D; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.status.ChunkStatusTasks; +import net.minecraft.world.level.chunk.status.ChunkStep; +import net.minecraft.world.level.chunk.status.WorldGenContext; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.concurrent.CompletableFuture; + +@Mixin(ChunkStatusTasks.class) +public class MixinChunkStatusTasks { + + @Inject(method = "initializeLight", at = @At("HEAD"), cancellable = true) + private static void initializeLight(WorldGenContext worldGenContext, ChunkStep chunkStep, StaticCache2D staticCache2D, ChunkAccess chunkAccess, CallbackInfoReturnable> cir) { + if (Flashback.isInReplay()) { + cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess)); + } + } + + @Inject(method = "light", at = @At("HEAD"), cancellable = true) + private static void light(WorldGenContext worldGenContext, ChunkStep chunkStep, StaticCache2D staticCache2D, ChunkAccess chunkAccess, CallbackInfoReturnable> cir) { + if (Flashback.isInReplay()) { + cir.setReturnValue(CompletableFuture.completedFuture(chunkAccess)); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPersistentEntitySectionManager.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPersistentEntitySectionManager.java similarity index 78% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPersistentEntitySectionManager.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPersistentEntitySectionManager.java index a5df6bd..1b12f48 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPersistentEntitySectionManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPersistentEntitySectionManager.java @@ -1,6 +1,6 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import net.minecraft.world.level.entity.PersistentEntitySectionManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -12,7 +12,7 @@ public class MixinPersistentEntitySectionManager { @Inject(method = "saveAll", at = @At("HEAD"), cancellable = true) public void saveAll(CallbackInfo ci) { - if (FlashbackClient.isInReplay()) { + if (Flashback.isInReplay()) { ci.cancel(); } } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPlayerList.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java similarity index 95% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPlayerList.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java index ce9c46f..a09ea80 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinPlayerList.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinPlayerList.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerChunkCache.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerChunkCache.java similarity index 92% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerChunkCache.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerChunkCache.java index 8baf355..7bed623 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerChunkCache.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerChunkCache.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.moulberry.flashback.playback.ReplayServer; import net.minecraft.server.level.ServerChunkCache; diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerConfigurationPacketListenerImpl.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerConfigurationPacketListenerImpl.java similarity index 97% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerConfigurationPacketListenerImpl.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerConfigurationPacketListenerImpl.java index b739ebf..7aa2423 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerConfigurationPacketListenerImpl.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerConfigurationPacketListenerImpl.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.moulberry.flashback.ext.ServerConfigurationPacketListenerImplExt; import net.minecraft.network.Connection; diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerEntity.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java similarity index 93% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerEntity.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java index a5c11aa..0361c21 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.llamalad7.mixinextras.sugar.Local; import com.moulberry.flashback.playback.ReplayServer; diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerGamePacketListenerImpl.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerGamePacketListenerImpl.java similarity index 94% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerGamePacketListenerImpl.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerGamePacketListenerImpl.java index ba63f4b..f1fed4a 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerGamePacketListenerImpl.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerGamePacketListenerImpl.java @@ -1,7 +1,7 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.llamalad7.mixinextras.injector.v2.WrapWithCondition; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ext.ServerConfigurationPacketListenerImplExt; import com.moulberry.flashback.ext.ServerGamePacketListenerImplExt; import net.minecraft.network.Connection; @@ -70,9 +70,9 @@ public abstract class MixinServerGamePacketListenerImpl extends ServerCommonPack } // Remove player disconnect logging in replays - @WrapWithCondition(method = "onDisconnect", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;info(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V")) + @WrapWithCondition(method = "onDisconnect", at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;info(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", remap = false)) public boolean onDisconnect_info(Logger instance, String s, Object o1, Object o2) { - return !FlashbackClient.isInReplay(); + return !Flashback.isInReplay(); } } diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerLoginPacketListenerImpl.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java similarity index 95% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerLoginPacketListenerImpl.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java index 079e94c..d0b7c40 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinServerLoginPacketListenerImpl.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerLoginPacketListenerImpl.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; import com.mojang.authlib.GameProfile; import com.moulberry.flashback.playback.ReplayServer; diff --git a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinTickRateManager.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java similarity index 66% rename from src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinTickRateManager.java rename to src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java index 6292456..7d4def3 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/replay_server/MixinTickRateManager.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java @@ -1,16 +1,13 @@ -package com.moulberry.flashback.mixin.client.replay_server; +package com.moulberry.flashback.mixin.replay_server; -import com.moulberry.flashback.FlashbackClient; -import net.minecraft.client.Minecraft; +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 { @@ -24,7 +21,7 @@ public abstract class MixinTickRateManager { @Inject(method = "tick", at = @At("RETURN")) public void tick(CallbackInfo ci) { - if (FlashbackClient.isInReplay() && (Object)this instanceof ServerTickRateManager) { + if (Flashback.isInReplay() && (Object)this instanceof ServerTickRateManager) { this.runGameElements = false; } } diff --git a/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java b/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java new file mode 100644 index 0000000..c88ff90 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/ui/MixinPauseScreen.java @@ -0,0 +1,62 @@ +package com.moulberry.flashback.mixin.ui; + +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.screens.ConfirmScreen; +import net.minecraft.client.gui.screens.PauseScreen; +import net.minecraft.network.chat.Component; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PauseScreen.class) +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.RECORDER == null) { + rowHelper.addChild(Button.builder(Component.literal("Start Recording"), (button) -> { + Flashback.startRecordingReplay(); + Minecraft.getInstance().setScreen(null); + }).width(204).build(), 2); + } else { + rowHelper.addChild(Button.builder(Component.literal("Finish Recording"), (button) -> { + Flashback.finishRecordingReplay(); + Minecraft.getInstance().setScreen(null); + }).width(204).build(), 2); + + if (Flashback.RECORDER.isPaused()) { + rowHelper.addChild(Button.builder(Component.literal("Unpause Recording"), (button) -> { + Flashback.pauseRecordingReplay(false); + Minecraft.getInstance().setScreen(null); + }).width(98).build()); + } else { + rowHelper.addChild(Button.builder(Component.literal("Pause Recording"), (button) -> { + Flashback.pauseRecordingReplay(true); + Minecraft.getInstance().setScreen(null); + }).width(98).build()); + } + + rowHelper.addChild(Button.builder(Component.literal("Cancel Recording"), (button) -> { + Minecraft.getInstance().setScreen(new ConfirmScreen(value -> { + if (value) { + Flashback.cancelRecordingReplay(); + Minecraft.getInstance().setScreen(null); + } else { + Minecraft.getInstance().setScreen(new PauseScreen(true)); + } + }, Component.literal("Confirm Cancel Recording"), + Component.literal("Are you sure you want to cancel the recording? You won't be able to recover it"))); + }).width(98).build()); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java new file mode 100644 index 0000000..02a76f1 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java @@ -0,0 +1,82 @@ +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.llamalad7.mixinextras.sugar.ref.LocalIntRef; +import com.moulberry.flashback.screen.SelectReplayScreen; +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.Renderable; +import net.minecraft.client.gui.components.events.GuiEventListener; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.gui.screens.TitleScreen; +import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen; +import net.minecraft.network.chat.Component; +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.CallbackInfo; + +import java.util.ArrayList; +import java.util.List; + +@Mixin(value = TitleScreen.class, priority = 1300) +public class MixinTitleScreen extends Screen { + + private MixinTitleScreen() { + super(null); + } + + @Unique + private final List normalMenuWidgets = new ArrayList<>(); + + @Inject(method = "init", at = @At("RETURN")) + public void init(CallbackInfo ci) { + for (int offsetX = 0; offsetX < 5; offsetX++) { + for (int i = this.normalMenuWidgets.size()-1; i >= 0; i--) { + AbstractWidget widget = this.normalMenuWidgets.get(i); + int size = widget.getHeight(); + int x = widget.getRight() + 4 + size * offsetX; + int y = widget.getY(); + + boolean overlapsWithExistingButton = false; + + // Check for overlaps with any existing buttons + 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()) { + overlapsWithExistingButton = true; + break; + } + } + } + + if (!overlapsWithExistingButton) { + this.addRenderableWidget(Button.builder(Component.literal("R"), button -> { + this.minecraft.setScreen(new SelectReplayScreen(this)); + }).bounds(x, y, size, size).build()); + return; + } + } + } + } + + @WrapOperation(method = "createNormalMenuOptions", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/TitleScreen;addRenderableWidget(Lnet/minecraft/client/gui/components/events/GuiEventListener;)Lnet/minecraft/client/gui/components/events/GuiEventListener;")) + public GuiEventListener addNormalMenuOption(TitleScreen instance, GuiEventListener guiEventListener, Operation original) { + GuiEventListener option = original.call(instance, guiEventListener); + if (option instanceof AbstractWidget widget) { + this.normalMenuWidgets.add(widget); + } + return option; + } + + @Inject(method = "createNormalMenuOptions", at = @At("HEAD")) + public void createNormalMenuOptions(int y, int buttonHeight, CallbackInfo ci) { + this.normalMenuWidgets.clear(); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java new file mode 100644 index 0000000..2ed6423 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinBossHealthOverlay.java @@ -0,0 +1,21 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.moulberry.flashback.ReplayVisuals; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.BossHealthOverlay; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(BossHealthOverlay.class) +public class MixinBossHealthOverlay { + + @Inject(method = "render", at = @At("HEAD"), cancellable = true) + public void render(GuiGraphics guiGraphics, CallbackInfo ci) { + if (!ReplayVisuals.showBossBar) { + ci.cancel(); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java new file mode 100644 index 0000000..e7bca62 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java @@ -0,0 +1,7 @@ +package com.moulberry.flashback.mixin.visuals; + +public class MixinClientLevel { + + + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevelData.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java similarity index 92% rename from src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevelData.java rename to src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java index 580ef88..6a64453 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinClientLevelData.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevelData.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.visuals; +package com.moulberry.flashback.mixin.visuals; import com.moulberry.flashback.ReplayVisuals; import net.minecraft.client.multiplayer.ClientLevel; diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java new file mode 100644 index 0000000..48c2476 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinEntityRenderDispatcher.java @@ -0,0 +1,40 @@ +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.editor.ui.ReplayUI; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.entity.EntityRenderDispatcher; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.LevelReader; +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(value = EntityRenderDispatcher.class, priority = 990) +public abstract class MixinEntityRenderDispatcher { + + @Shadow + private static void renderHitbox(PoseStack poseStack, VertexConsumer vertexConsumer, Entity entity, float f, float g, float h, float i) { + } + + // Add a yellow outline to selected entity + @Inject(method = "render", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", shift = At.Shift.BEFORE)) + public void render(Entity entity, double d, double e, double f, float g, float h, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, CallbackInfo ci) { + if (ReplayUI.isEntitySelected(entity.getId())) { + renderHitbox(poseStack, multiBufferSource.getBuffer(RenderType.lines()), entity, h, 1.0f, 1.0f, 0.0f); + } + } + + // 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; + } + +} diff --git a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinFogRenderer.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java similarity index 83% rename from src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinFogRenderer.java rename to src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java index 6c0f776..b196cd8 100644 --- a/src/client/java/com/moulberry/flashback/mixin/client/visuals/MixinFogRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinFogRenderer.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.mixin.client.visuals; +package com.moulberry.flashback.mixin.visuals; import com.mojang.blaze3d.shaders.FogShape; import com.mojang.blaze3d.systems.RenderSystem; @@ -15,9 +15,9 @@ 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.overrideFogDistance > 0.0f) { - RenderSystem.setShaderFogStart(0.0f); - RenderSystem.setShaderFogEnd(ReplayVisuals.overrideFogDistance); + if (ReplayVisuals.overrideFog) { + RenderSystem.setShaderFogStart(ReplayVisuals.overrideFogStart); + RenderSystem.setShaderFogEnd(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 new file mode 100644 index 0000000..19f39ec --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java @@ -0,0 +1,54 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.editor.ui.CustomImGuiImplGlfw; +import com.moulberry.flashback.editor.ui.ReplayUI; +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.world.phys.HitResult; +import org.spongepowered.asm.mixin.Mixin; +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(Gui.class) +public class MixinGui { + + @Inject(method = "renderChat", at = @At("HEAD"), cancellable = true) + public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { + if (!ReplayVisuals.showChat) { + ci.cancel(); + } + } + + @Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true) + public void renderTitle(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { + if (!ReplayVisuals.showTitleText) { + ci.cancel(); + } + } + + @Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true) + public void renderScoreboardSidebar(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { + if (!ReplayVisuals.showScoreboard) { + ci.cancel(); + } + } + + @Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true) + public void renderOverlayMessage(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { + if (!ReplayVisuals.showActionBar) { + ci.cancel(); + } + } + + @Inject(method = "canRenderCrosshairForSpectator", at = @At("HEAD"), cancellable = true) + public void canRenderCrosshairForSpectator(HitResult hitResult, CallbackInfoReturnable cir) { + if (ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) { + cir.setReturnValue(true); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java new file mode 100644 index 0000000..a3f964b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinLoadingOverlay.java @@ -0,0 +1,30 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.moulberry.flashback.Flashback; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.LoadingOverlay; +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(LoadingOverlay.class) +public class MixinLoadingOverlay { + + @Shadow private long fadeOutStart; + + @Shadow @Final private Minecraft minecraft; + + // Make overlay disappear instantly if inside replay + @Inject(method = "render", at = @At("RETURN")) + public void render(GuiGraphics guiGraphics, int i, int j, float f, CallbackInfo ci) { + if (this.fadeOutStart != -1 && Flashback.isInReplay()) { + this.minecraft.setOverlay(null); + } + } + + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java new file mode 100644 index 0000000..37a0b27 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinOptions.java @@ -0,0 +1,34 @@ +package com.moulberry.flashback.mixin.visuals; + +import com.moulberry.flashback.ReplayVisuals; +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +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(Options.class) +public class MixinOptions { + + @Unique + private OptionInstance cachedOptionInstance = 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)) { + 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; + delegate.set(value); + }); + } + + cir.setReturnValue(this.cachedOptionInstance); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/packet/FinishedServerTick.java b/src/main/java/com/moulberry/flashback/packet/FinishedServerTick.java new file mode 100644 index 0000000..6190b55 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/packet/FinishedServerTick.java @@ -0,0 +1,18 @@ +package com.moulberry.flashback.packet; + +import com.moulberry.flashback.Flashback; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +public class FinishedServerTick implements CustomPacketPayload { + public static final Type TYPE = new Type<>(Flashback.createResourceLocation("finished_server_tick")); + public static final FinishedServerTick INSTANCE = new FinishedServerTick(); + + private FinishedServerTick() { + } + + @Override + public Type type() { + return TYPE; + } + +} diff --git a/src/client/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java b/src/main/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java similarity index 100% rename from src/client/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java rename to src/main/java/com/moulberry/flashback/playback/AllowPendingEntityPacketSet.java diff --git a/src/client/java/com/moulberry/flashback/playback/EmptyLevelSource.java b/src/main/java/com/moulberry/flashback/playback/EmptyLevelSource.java similarity index 94% rename from src/client/java/com/moulberry/flashback/playback/EmptyLevelSource.java rename to src/main/java/com/moulberry/flashback/playback/EmptyLevelSource.java index 9dcaaba..70c32ce 100644 --- a/src/client/java/com/moulberry/flashback/playback/EmptyLevelSource.java +++ b/src/main/java/com/moulberry/flashback/playback/EmptyLevelSource.java @@ -45,7 +45,7 @@ public class EmptyLevelSource extends ChunkGenerator { } @Override - public CompletableFuture fillFromNoise(Executor executor, Blender blender, RandomState randomState, StructureManager structureManager, ChunkAccess chunkAccess) { + public CompletableFuture fillFromNoise(Blender blender, RandomState randomState, StructureManager structureManager, ChunkAccess chunkAccess) { return CompletableFuture.completedFuture(chunkAccess); } diff --git a/src/client/java/com/moulberry/flashback/playback/PlayableChunk.java b/src/main/java/com/moulberry/flashback/playback/PlayableChunk.java similarity index 100% rename from src/client/java/com/moulberry/flashback/playback/PlayableChunk.java rename to src/main/java/com/moulberry/flashback/playback/PlayableChunk.java diff --git a/src/client/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java similarity index 95% rename from src/client/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java rename to src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java index e962f4e..3526209 100644 --- a/src/client/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayConfigurationPacketHandler.java @@ -8,17 +8,10 @@ import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistrySynchronization; import net.minecraft.core.registries.Registries; +import net.minecraft.network.DisconnectionDetails; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; -import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; -import net.minecraft.network.protocol.common.ClientboundPingPacket; -import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; -import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; -import net.minecraft.network.protocol.common.ClientboundStoreCookiePacket; -import net.minecraft.network.protocol.common.ClientboundTransferPacket; -import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; +import net.minecraft.network.protocol.common.*; import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; import net.minecraft.network.protocol.configuration.ClientboundRegistryDataPacket; @@ -312,13 +305,23 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack throw new UnsupportedPacketException(clientboundTransferPacket); } + @Override + public void handleCustomReportDetails(ClientboundCustomReportDetailsPacket clientboundCustomReportDetailsPacket) { + throw new UnsupportedPacketException(clientboundCustomReportDetailsPacket); + } + + @Override + public void handleServerLinks(ClientboundServerLinksPacket clientboundServerLinksPacket) { + throw new UnsupportedPacketException(clientboundServerLinksPacket); + } + @Override public void handleRequestCookie(ClientboundCookieRequestPacket clientboundCookieRequestPacket) { throw new UnsupportedPacketException(clientboundCookieRequestPacket); } @Override - public void onDisconnect(Component component) { + public void onDisconnect(DisconnectionDetails disconnectionDetails) { } diff --git a/src/client/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java similarity index 92% rename from src/client/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java rename to src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index 7d829e8..65f27f9 100644 --- a/src/client/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -1,44 +1,26 @@ package com.moulberry.flashback.playback; -import com.google.common.collect.Multimap; import com.mojang.authlib.GameProfile; -import com.moulberry.flashback.ChunkSectionHash; +import com.moulberry.flashback.PacketHelper; import com.moulberry.flashback.exception.UnsupportedPacketException; -import com.moulberry.flashback.ext.LevelChunkSectionExt; import com.moulberry.flashback.ext.ThreadedLevelLightEngineExt; -import com.moulberry.flashback.player.ReplayPlayer; import io.netty.channel.embedded.EmbeddedChannel; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; -import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.multiplayer.PlayerInfo; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Holder; -import net.minecraft.core.HolderLookup; -import net.minecraft.core.Registry; import net.minecraft.core.SectionPos; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; import net.minecraft.network.Connection; -import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.DisconnectionDetails; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.codec.ByteBufCodecs; -import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.PacketFlow; -import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; -import net.minecraft.network.protocol.common.ClientboundDisconnectPacket; -import net.minecraft.network.protocol.common.ClientboundKeepAlivePacket; -import net.minecraft.network.protocol.common.ClientboundPingPacket; -import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; -import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; -import net.minecraft.network.protocol.common.ClientboundStoreCookiePacket; -import net.minecraft.network.protocol.common.ClientboundTransferPacket; -import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; +import net.minecraft.network.protocol.common.*; import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; import net.minecraft.network.protocol.game.*; import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket; @@ -51,7 +33,6 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ThreadedLevelLightEngine; import net.minecraft.server.network.CommonListenerCookie; import net.minecraft.sounds.SoundEvent; -import net.minecraft.util.ExtraCodecs; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.entity.Entity; @@ -62,7 +43,6 @@ 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.ArmorStand; import net.minecraft.world.entity.decoration.Painting; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.ChunkPos; @@ -72,25 +52,19 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; -import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.border.WorldBorder; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.DataLayer; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraft.world.level.chunk.LevelChunkSection; import net.minecraft.world.level.chunk.status.ChunkStatus; import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.Heightmap; import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.storage.DerivedLevelData; import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.phys.Vec3; -import org.apache.commons.io.FileUtils; import org.jetbrains.annotations.Nullable; -import java.io.IOException; -import java.nio.file.Path; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; @@ -98,7 +72,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -134,7 +107,9 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { for (Entity pendingEntity : this.pendingEntities.values()) { Entity existingEntity = level.getEntity(pendingEntity.getId()); if (existingEntity != null) { - if (existingEntity.getType().equals(pendingEntity.getType())) { + if (existingEntity instanceof ServerPlayer existingPlayer) { + existingPlayer.connection.disconnect(Component.empty()); + } else if (existingEntity.getType().equals(pendingEntity.getType())) { existingEntity.restoreFrom(pendingEntity); existingEntity.setPos(pendingEntity.getX(), pendingEntity.getY(), pendingEntity.getZ()); existingEntity.setXRot(pendingEntity.getXRot()); @@ -191,6 +166,8 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } private void spawnPlayer(ClientboundAddEntityPacket addEntityPacket, GameProfile gameProfile, GameType gameType) { + this.flushPendingEntities(); + CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false); ServerPlayer serverPlayer = new ServerPlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()){ @Override @@ -203,6 +180,21 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { return true; } }; + + ServerPlayer existingPlayer = this.replayServer.getPlayerList().getPlayer(serverPlayer.getUUID()); + if (existingPlayer != null) { + existingPlayer.connection.disconnect(Component.empty()); + } + + Entity existingEntity = this.level().getEntity(serverPlayer.getId()); + if (existingEntity != null) { + if (existingEntity instanceof ServerPlayer existingPlayer2) { + existingPlayer2.connection.disconnect(Component.empty()); + } else { + existingEntity.discard(); + } + } + Connection connection = new Connection(PacketFlow.SERVERBOUND); EmbeddedChannel embeddedChannel = new EmbeddedChannel(connection); serverPlayer.recreateFromPacket(addEntityPacket); @@ -312,7 +304,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleBlockUpdate(ClientboundBlockUpdatePacket clientboundBlockUpdatePacket) { this.level().setBlock(clientboundBlockUpdatePacket.getPos(), - clientboundBlockUpdatePacket.getBlockState(), 2); + clientboundBlockUpdatePacket.getBlockState(), 18); } @Override @@ -338,7 +330,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleChunkBlocksUpdate(ClientboundSectionBlocksUpdatePacket clientboundSectionBlocksUpdatePacket) { clientboundSectionBlocksUpdatePacket.runUpdates((blockPos, blockState) -> { - this.level().setBlock(blockPos, blockState, 2); + this.level().setBlock(blockPos, blockState, 18); }); } @@ -414,9 +406,42 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleGameEvent(ClientboundGameEventPacket clientboundGameEventPacket) { - if (clientboundGameEventPacket.getEvent() != ClientboundGameEventPacket.CHANGE_GAME_MODE) { - forward(clientboundGameEventPacket); + ClientboundGameEventPacket.Type type = clientboundGameEventPacket.getEvent(); + ServerLevel level = this.level(); + float floatValue = clientboundGameEventPacket.getParam(); + if (type == ClientboundGameEventPacket.NO_RESPAWN_BLOCK_AVAILABLE) { + return; + } else if (type == ClientboundGameEventPacket.START_RAINING) { + level.getLevelData().setRaining(true); + level.setRainLevel(0.0f); + } else if (type == ClientboundGameEventPacket.STOP_RAINING) { + level.getLevelData().setRaining(false); + level.setRainLevel(1.0f); + } else if (type == ClientboundGameEventPacket.CHANGE_GAME_MODE) { + return; + } else if (type == ClientboundGameEventPacket.WIN_GAME) { + return; + } else if (type == ClientboundGameEventPacket.DEMO_EVENT) { + return; + } else if (type == ClientboundGameEventPacket.ARROW_HIT_PLAYER) { + return; + } else if (type == ClientboundGameEventPacket.RAIN_LEVEL_CHANGE) { + level.setRainLevel(floatValue); + } else if (type == ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE) { + level.setThunderLevel(floatValue); + } else if (type == ClientboundGameEventPacket.PUFFER_FISH_STING) { + return; + } else if (type == ClientboundGameEventPacket.GUARDIAN_ELDER_EFFECT) { + return; + } else if (type == ClientboundGameEventPacket.IMMEDIATE_RESPAWN) { + return; + } else if (type == ClientboundGameEventPacket.LIMITED_CRAFTING) { + return; + } else if (type == ClientboundGameEventPacket.LEVEL_CHUNKS_LOAD_START) { + return; } + + forward(clientboundGameEventPacket); } @Override @@ -428,55 +453,16 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { LevelChunk chunk = this.level().getChunk(x, z); var chunkData = levelChunkWithLightPacket.getChunkData(); - boolean shouldSendChunkData = true; - if (this.replayServer.isProcessingSnapshot) { - boolean blockDataChanged = false; + chunk.replaceWithPacketData(chunkData.getReadBuffer(), chunkData.getHeightmaps(), chunkData.getBlockEntitiesTagsConsumer(x, z)); - FriendlyByteBuf readBuffer = chunkData.getReadBuffer(); - CompoundTag heightmaps = chunkData.getHeightmaps(); - - chunk.clearAllBlockEntities(); - for (LevelChunkSection levelChunkSection : chunk.getSections()) { - if (!blockDataChanged) { - ChunkSectionHash hash = ((LevelChunkSectionExt)levelChunkSection).flashback$hashState(); - levelChunkSection.read(readBuffer); - blockDataChanged = !((LevelChunkSectionExt)levelChunkSection).flashback$doesHashedStateMatch(hash); - } else { - levelChunkSection.read(readBuffer); - } - } - for (Heightmap.Types heightmapType : Heightmap.Types.values()) { - String key = heightmapType.getSerializationKey(); - if (heightmaps.contains(key, CompoundTag.TAG_LONG_ARRAY)) { - chunk.setHeightmap(heightmapType, heightmaps.getLongArray(key)); - } - } - if (blockDataChanged) { - chunk.initializeLightSources(); - } - chunkData.getBlockEntitiesTagsConsumer(x, z).accept((blockPos, blockEntityType, compoundTag) -> { - BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.IMMEDIATE); - if (blockEntity != null && compoundTag != null && blockEntity.getType() == blockEntityType) { - blockEntity.loadWithComponents(compoundTag, this.level().registryAccess()); - } - }); - - shouldSendChunkData = blockDataChanged; - } else { - chunk.replaceWithPacketData(chunkData.getReadBuffer(), chunkData.getHeightmaps(), chunkData.getBlockEntitiesTagsConsumer(x, z)); - } - - // todo: can we avoid updating the light data? var lightData = levelChunkWithLightPacket.getLightData(); this.applyLightData(levelLightEngine, x, z, lightData); - if (shouldSendChunkData) { - ChunkPos chunkPos = chunk.getPos(); - for (ServerPlayer serverPlayer : this.replayServer.getReplayViewers()) { - if (serverPlayer.getChunkTrackingView().contains(chunkPos)) { - serverPlayer.connection.chunkSender.markChunkPendingToSend(chunk); - } + ChunkPos chunkPos = chunk.getPos(); + for (ServerPlayer serverPlayer : this.replayServer.getReplayViewers()) { + if (serverPlayer.getChunkTrackingView().contains(chunkPos)) { + serverPlayer.connection.chunkSender.markChunkPendingToSend(chunk); } } @@ -501,7 +487,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { LevelChunk chunkAccess = this.level().getChunk(x, z); // todo: do we need to do this if replaceWithPacketData already does it? chunkAccess.initializeLightSources(); - boolean isLightCorrect = chunkAccess.getStatus().isOrAfter(ChunkStatus.LIGHT) && chunkAccess.isLightCorrect(); + boolean isLightCorrect = chunkAccess.getPersistedStatus().isOrAfter(ChunkStatus.LIGHT) && chunkAccess.isLightCorrect(); ((ThreadedLevelLightEngine)levelLightEngine).initializeLight(chunkAccess, isLightCorrect).thenRun(() -> { // Send light data LevelChunk chunkAccess2 = this.level().getChunk(x, z); @@ -574,7 +560,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { this.ensureWorldCreated(clientboundLoginPacket.commonPlayerSpawnInfo(), recreatePlayer ? null : localPlayer, true); if (recreatePlayer) { - ClientboundAddEntityPacket addEntityPacket = new ClientboundAddEntityPacket(localPlayer); + ClientboundAddEntityPacket addEntityPacket = PacketHelper.createAddEntity(localPlayer); addEntityPacket.id = clientboundLoginPacket.playerId(); this.spawnPlayer(addEntityPacket, localPlayer.getGameProfile(), localPlayer.gameMode.getGameModeForPlayer()); } @@ -594,8 +580,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { GameProfile gameProfile = ByteBufCodecs.GAME_PROFILE.decode(registryFriendlyByteBuf); GameType gameType = GameType.byId(registryFriendlyByteBuf.readVarInt()); - ServerLevel level = this.level(); - if (level.getEntity(this.localPlayerId) == null) { + if (this.getEntityOrPending(this.localPlayerId) == null) { this.spawnPlayer(addEntityPacket, gameProfile, gameType); } } @@ -627,9 +612,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } if (this.currentDimension == dimension) { - if (!this.replayServer.isProcessingSnapshot) { - this.replayServer.followLocalPlayerNextTick = true; - } + this.replayServer.followLocalPlayerNextTickIfFar = true; return; } @@ -917,7 +900,8 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { serverLevelData.setGameTime(clientboundSetTimePacket.getGameTime()); } } - this.replayServer.forceTimeSynchronization(); + + forward(clientboundSetTimePacket); } @Override @@ -1358,6 +1342,16 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { throw new UnsupportedPacketException(clientboundTransferPacket); } + @Override + public void handleCustomReportDetails(ClientboundCustomReportDetailsPacket clientboundCustomReportDetailsPacket) { + throw new UnsupportedPacketException(clientboundCustomReportDetailsPacket); + } + + @Override + public void handleServerLinks(ClientboundServerLinksPacket clientboundServerLinksPacket) { + throw new UnsupportedPacketException(clientboundServerLinksPacket); + } + @Override public void handleRequestCookie(ClientboundCookieRequestPacket clientboundCookieRequestPacket) { throw new UnsupportedPacketException(clientboundCookieRequestPacket); @@ -1369,7 +1363,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { } @Override - public void onDisconnect(Component component) { + public void onDisconnect(DisconnectionDetails disconnectionDetails) { } @Override diff --git a/src/client/java/com/moulberry/flashback/player/ReplayPlayer.java b/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java similarity index 95% rename from src/client/java/com/moulberry/flashback/player/ReplayPlayer.java rename to src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java index 92e9e1f..ce345b5 100644 --- a/src/client/java/com/moulberry/flashback/player/ReplayPlayer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayPlayer.java @@ -1,4 +1,4 @@ -package com.moulberry.flashback.player; +package com.moulberry.flashback.playback; import com.mojang.authlib.GameProfile; import net.minecraft.server.MinecraftServer; diff --git a/src/client/java/com/moulberry/flashback/playback/ReplayServer.java b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java similarity index 74% rename from src/client/java/com/moulberry/flashback/playback/ReplayServer.java rename to src/main/java/com/moulberry/flashback/playback/ReplayServer.java index eed8aa4..4944bca 100644 --- a/src/client/java/com/moulberry/flashback/playback/ReplayServer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java @@ -3,17 +3,24 @@ package com.moulberry.flashback.playback; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import com.moulberry.flashback.ReplayVisuals; +import com.moulberry.flashback.TempFolderProvider; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateCache; +import com.moulberry.flashback.ext.LevelChunkSectionExt; import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.ext.ServerGamePacketListenerImplExt; import com.moulberry.flashback.io.ReplayReader; -import com.moulberry.flashback.keyframe.Keyframes; -import com.moulberry.flashback.player.ReplayPlayer; +import com.moulberry.flashback.packet.FinishedServerTick; import com.moulberry.flashback.record.FlashbackChunkMeta; import com.moulberry.flashback.record.FlashbackMeta; +import com.moulberry.flashback.record.Recorder; import io.netty.buffer.ByteBuf; -import net.fabricmc.loader.api.FabricLoader; +import io.netty.buffer.Unpooled; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; @@ -22,14 +29,10 @@ import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.Packet; -import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; -import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.common.*; import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; import net.minecraft.network.protocol.configuration.ConfigurationProtocols; -import net.minecraft.network.protocol.game.ClientGamePacketListener; -import net.minecraft.network.protocol.game.ClientboundBossEventPacket; -import net.minecraft.network.protocol.game.ClientboundTabListPacket; -import net.minecraft.network.protocol.game.GameProtocols; +import net.minecraft.network.protocol.game.*; import net.minecraft.resources.ResourceKey; import net.minecraft.server.Services; import net.minecraft.server.WorldStem; @@ -47,8 +50,9 @@ import net.minecraft.world.flag.FeatureFlagSet; 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 org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileOutputStream; @@ -77,8 +81,8 @@ public class ReplayServer extends IntegratedServer { public volatile int jumpToTick = -1; public volatile boolean replayPaused = true; + public AtomicBoolean sendFinishedServerTick = new AtomicBoolean(false); public volatile float desiredTickRate = 20.0f; - public AtomicBoolean finishedServerTick = new AtomicBoolean(false); private int currentTick = 0; private int targetTick = 0; @@ -90,12 +94,14 @@ public class ReplayServer extends IntegratedServer { private final StreamCodec> configurationPacketCodec; private final List replayViewers = new ArrayList<>(); public boolean followLocalPlayerNextTick = false; + public boolean followLocalPlayerNextTickIfFar = false; public boolean isProcessingSnapshot = false; private boolean processedSnapshot = false; - private final UUID playbackUUID = UUID.randomUUID(); + private final UUID playbackUUID; private final FlashbackMeta metadata; private final TreeMap playableChunksByStart = new TreeMap<>(); + private final Int2ObjectMap levelChunkCachedPackets = new Int2ObjectOpenHashMap<>(); private ReplayReader currentReplayReader = null; private record RemotePack(UUID id, String url, String hash){} @@ -105,17 +111,20 @@ public class ReplayServer extends IntegratedServer { private Component tabListHeader = Component.empty(); private Component tabListFooter = Component.empty(); - public ReplayServer(Thread thread, Minecraft minecraft, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Services services, ChunkProgressListenerFactory chunkProgressListenerFactory) { + private Component shutdownReason = null; + + public ReplayServer(Thread thread, Minecraft minecraft, LevelStorageSource.LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Services services, + ChunkProgressListenerFactory chunkProgressListenerFactory, UUID playbackUUID, Path path) { super(thread, minecraft, levelStorageAccess, packRepository, worldStem, services, chunkProgressListenerFactory); + this.playbackUUID = playbackUUID; this.gamePacketHandler = new ReplayGamePacketHandler(this); this.configurationPacketHandler = new ReplayConfigurationPacketHandler(this); - this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(this.registryAccess())).codec(); + this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.registryAccess())).codec(); this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); - Path path = FabricLoader.getInstance().getGameDir().resolve("debug_recording.zip"); try { - Path playbackFolder = FlashbackClient.getReplayPlaybackTemp(playbackUUID); + Path playbackFolder = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.PLAYBACK, playbackUUID); byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(Files.newInputStream(path)); @@ -144,7 +153,6 @@ public class ReplayServer extends IntegratedServer { zipEntry = zis.getNextEntry(); } - String metadataJson = Files.readString(playbackFolder.resolve("metadata.json")); this.metadata = FlashbackMeta.fromJson(GSON.fromJson(metadataJson, JsonObject.class)); if (this.metadata == null) { @@ -159,11 +167,53 @@ public class ReplayServer extends IntegratedServer { } this.totalTicks = ticks; + + Path levelChunkCachePath = playbackFolder.resolve("level_chunk_cache"); + if (Files.exists(levelChunkCachePath)) { + int chunkCacheIndex = 0; + + byte[] bytes = Files.readAllBytes(levelChunkCachePath); + ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes); + while (byteBuf.readerIndex() < byteBuf.writerIndex()) { + int size = byteBuf.readInt(); + + if (size < 0) { + Flashback.LOGGER.error("Expected positive size for chunk packet, got {}", size); + break; + } + + if (byteBuf.readerIndex() > byteBuf.writerIndex() - size) { + Flashback.LOGGER.error("Ran out of bytes while reading level_chunk_cache, needed {}, had {}", + size, byteBuf.writerIndex() - byteBuf.readerIndex()); + break; + } + + RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(byteBuf.readSlice(size), this.registryAccess()); + + try { + Packet packet = this.gamePacketCodec.decode(registryFriendlyByteBuf); + if (packet instanceof ClientboundLevelChunkWithLightPacket levelChunkWithLightPacket) { + this.levelChunkCachedPackets.put(chunkCacheIndex, levelChunkWithLightPacket); + } else { + throw new IllegalStateException("Level chunk cache contains wrong packet: " + packet); + } + } catch (Exception e) { + Flashback.LOGGER.error("Encountered error while reading level_chunk_cache", e); + } + + chunkCacheIndex += 1; + } + Flashback.LOGGER.info("Loaded level_chunk_cache with {} entries", this.levelChunkCachedPackets.size()); + } } catch (IOException e) { throw new RuntimeException(e); } } + public FlashbackMeta getMetadata() { + return this.metadata; + } + public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { File destFile = new File(destinationDir, zipEntry.getName()); @@ -185,7 +235,7 @@ public class ReplayServer extends IntegratedServer { )); this.reloadResources(selectedPacks); - this.gamePacketCodec = GameProtocols.CLIENTBOUND.bind(RegistryFriendlyByteBuf.decorator(this.registryAccess())).codec(); + this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(this.registryAccess())).codec(); if (this.currentReplayReader != null) { this.currentReplayReader.changeRegistryAccess(this.registryAccess()); @@ -251,6 +301,18 @@ public class ReplayServer extends IntegratedServer { @Override public void saveAll() { } + + @Override + public void removeAll() { + if (shutdownReason == null) { + super.removeAll(); + } else { + List players = this.getPlayers(); + for (int i = 0; i < players.size(); ++i) { + players.get(i).connection.disconnect(shutdownReason); + } + } + } }); this.loadLevel(); @@ -456,13 +518,47 @@ public class ReplayServer extends IntegratedServer { if (entity != null) { entity.moveTo(x, y, z, yaw, pitch); entity.setYHeadRot(headYaw); - entity.setOnGround(onGround); + if (entity.onGround() != onGround) { + entity.setOnGround(onGround); + } } } } } } + public void handleLevelChunkCached(int index) { + ClientboundLevelChunkWithLightPacket packet = this.levelChunkCachedPackets.get(index); + if (packet != null) { + this.configurationPacketHandler.flushPendingConfiguration(); + this.gamePacketHandler.flushPendingEntities(); + + int x = packet.getX(); + int z = packet.getZ(); + LevelChunk chunk = this.gamePacketHandler.level().getChunk(x, z); + + if (!doesCachedChunkIdMatch(chunk, index)) { + packet.handle(this.gamePacketHandler); + + for (LevelChunkSection section : chunk.getSections()) { + ((LevelChunkSectionExt)section).flashback$setCachedChunkId(index); + } + } + } else { + Flashback.LOGGER.error("Missing cached level chunk: {}", index); + } + } + + private static boolean doesCachedChunkIdMatch(LevelChunk chunk, int chunkId) { + for (LevelChunkSection section : chunk.getSections()) { + if (chunkId != ((LevelChunkSectionExt) section).flashback$getCachedChunkId()) { + return false; + } + } + + return true; + } + public static final TicketType ENTITY_LOAD_TICKET = TicketType.create("replay_entity_load", Comparator.comparingLong(ChunkPos::toLong), 5); public void closeLevel(ServerLevel serverLevel) { @@ -506,7 +602,10 @@ public class ReplayServer extends IntegratedServer { this.lastReplayTick = this.currentTick; this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick(); - Keyframes.applyKeyframes(this, this.lastReplayTick); + if (!this.replayPaused) { + EditorState editorState = EditorStateCache.get(this.metadata.replayIdentifier); + editorState.applyKeyframes(this, this.lastReplayTick); + } // Update list of replay viewers this.replayViewers.clear(); @@ -516,36 +615,6 @@ public class ReplayServer extends IntegratedServer { } } - // Update resourcepacks - if (this.remotePacks.isEmpty()) { - if (!this.oldRemotePacks.isEmpty()) { - this.oldRemotePacks.clear(); - this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.empty())); - } - } else { - for (Map.Entry entry : this.remotePacks.entrySet()) { - RemotePack remotePack = entry.getValue(); - RemotePack oldRemotePack = this.oldRemotePacks.get(entry.getKey()); - if (oldRemotePack == null) { - this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash, - 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())); - } - this.oldRemotePacks.put(entry.getKey(), remotePack); - } - this.oldRemotePacks.keySet().removeIf(uuid -> { - if (!this.remotePacks.containsKey(uuid)) { - this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.of(uuid))); - return true; - } else { - return false; - } - }); - } - int extraForceEntityLerpTicks = 0; if (this.jumpToTick >= 0) { this.targetTick = this.jumpToTick; @@ -554,6 +623,9 @@ public class ReplayServer extends IntegratedServer { } else if (!this.isPaused() && !this.replayPaused && this.targetTick < this.totalTicks) { // Normal playback this.targetTick += 1; + } else if (this.targetTick == this.totalTicks && this.currentTick == this.totalTicks) { + // Pause when reaching end of replay + this.replayPaused = true; } // Update tick rate & frozen state @@ -569,6 +641,36 @@ public class ReplayServer extends IntegratedServer { this.handleActions(); this.tryFollowLocalPlayer(); + // Update resourcepacks + if (this.remotePacks.isEmpty()) { + if (!this.oldRemotePacks.isEmpty()) { + this.oldRemotePacks.clear(); + this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.empty())); + } + } else { + for (Map.Entry entry : this.remotePacks.entrySet()) { + RemotePack remotePack = entry.getValue(); + RemotePack oldRemotePack = this.oldRemotePacks.get(entry.getKey()); + if (oldRemotePack == null) { + this.getPlayerList().broadcastAll(new ClientboundResourcePackPushPacket(remotePack.id, remotePack.url, remotePack.hash, + 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())); + } + this.oldRemotePacks.put(entry.getKey(), remotePack); + } + this.oldRemotePacks.keySet().removeIf(uuid -> { + if (!this.remotePacks.containsKey(uuid)) { + this.getPlayerList().broadcastAll(new ClientboundResourcePackPopPacket(Optional.of(uuid))); + return true; + } else { + return false; + } + }); + } + if (extraForceEntityLerpTicks > 0) { ReplayVisuals.forceEntityLerpTicks = Math.min(10, ReplayVisuals.forceEntityLerpTicks + extraForceEntityLerpTicks); } @@ -600,13 +702,24 @@ public class ReplayServer extends IntegratedServer { } } - if (FlashbackClient.EXPORT_JOB == null) { + if (Flashback.EXPORT_JOB == null) { ReplayVisuals.forceEntityLerpTicks = 10; ((MinecraftExt)Minecraft.getInstance()).flashback$forceClientTick(); } } - this.finishedServerTick.set(true); + 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(); + } + } + } + + @Override + public void synchronizeTime(ServerLevel level) { } private void handleActions() { @@ -616,11 +729,32 @@ public class ReplayServer extends IntegratedServer { return; } - if (this.targetTick < this.currentTick) { + Map.Entry oldEntry = this.playableChunksByStart.floorEntry(this.currentTick); + + int duration; + if (oldEntry != null) { + duration = oldEntry.getValue().chunkMeta.duration; + } else { + duration = Recorder.CHUNK_LENGTH_SECONDS * 20; + } + duration = Math.max(60 * 20, duration); + + boolean shouldJump = this.targetTick < this.currentTick; + if (this.targetTick > this.currentTick + duration) { + if (oldEntry != null) { + Map.Entry targetEntry = this.playableChunksByStart.floorEntry(this.targetTick); + shouldJump |= oldEntry.getValue() != targetEntry.getValue(); + } else { + shouldJump = true; + } + } + + if (shouldJump) { this.processedSnapshot = true; Map.Entry entry = this.playableChunksByStart.floorEntry(this.targetTick); ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); replayReader.handleSnapshot(this); + entry.getValue().getOrLoadReplayReader(this.registryAccess()).resetToStart(); this.currentTick = entry.getKey(); } @@ -630,29 +764,39 @@ public class ReplayServer extends IntegratedServer { } this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); - // todo: is this problematic if we somehow have a chunk with only 1 tick in it? - if (entry.getKey() == this.currentTick) { + if (this.currentTick == entry.getKey()) { this.currentReplayReader.resetToStart(); } - // todo: what do we do when the number of ticks in the chunk doesn't match the number of ticks we think it has - while (this.currentTick < this.targetTick) { if (!this.currentReplayReader.handleNextAction(this)) { Map.Entry newEntry = this.playableChunksByStart.floorEntry(this.currentTick); if (newEntry.getValue() == entry.getValue()) { this.targetTick = this.currentTick; + this.replayPaused = true; return; } entry = newEntry; if (newEntry.getKey() != this.currentTick) { - throw new RuntimeException("didn't match?"); + Flashback.LOGGER.error("Error processing replay: ran out of entries before expected end of PlayableChunk"); + Flashback.LOGGER.error("Current tick: {}", this.currentTick); + Flashback.LOGGER.error("New entry start: {}", newEntry.getKey()); + this.stopWithReason(Component.literal("Error processing replay: ran out of entries before expected end of PlayableChunk")); + return; } this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); this.currentReplayReader.resetToStart(); } + + if (entry.getKey() + entry.getValue().chunkMeta.duration < this.currentTick) { + Flashback.LOGGER.error("Error processing replay: actual duration of PlayableChunk inconsistent with recorded duration"); + Flashback.LOGGER.error("Current tick: {}", this.currentTick); + Flashback.LOGGER.error("PlayableChunk tick base: {}", entry.getKey()); + Flashback.LOGGER.error("PlayableChunk duration: {}", entry.getValue().chunkMeta.duration); + this.stopWithReason(Component.literal("Error processing replay: actual duration of PlayableChunk inconsistent with recorded duration")); + } } this.currentReplayReader = null; @@ -674,13 +818,24 @@ public class ReplayServer extends IntegratedServer { } for (ReplayPlayer replayViewer : this.getReplayViewers()) { - if (replayViewer.followLocalPlayerNextTick || this.followLocalPlayerNextTick) { + boolean shouldFollow = replayViewer.followLocalPlayerNextTick || this.followLocalPlayerNextTick; + if (this.followLocalPlayerNextTickIfFar) { + shouldFollow |= replayViewer.level() != currentLevel || replayViewer.distanceToSqr(follow) > 256*256; + } + if (shouldFollow) { replayViewer.followLocalPlayerNextTick = false; replayViewer.teleportTo(currentLevel, follow.getX(), follow.getY(), follow.getZ(), follow.getYRot(), follow.getXRot()); } } + this.followLocalPlayerNextTick = false; + this.followLocalPlayerNextTickIfFar = false; + } + + private void stopWithReason(Component reason) { + this.shutdownReason = reason; + this.halt(false); } @Override @@ -712,21 +867,11 @@ public class ReplayServer extends IntegratedServer { super.stopServer(); this.clearReplayTempFolder(); - Path playbackTemp = FlashbackClient.getReplayPlaybackTemp(this.playbackUUID); - try { - FileUtils.deleteDirectory(playbackTemp.toFile()); - } catch (Exception e) { - throw new RuntimeException(e); - } + TempFolderProvider.deleteTemp(TempFolderProvider.TempFolderType.PLAYBACK, this.playbackUUID); } public void clearReplayTempFolder() { - Path replayTemp = FlashbackClient.getReplayServerTemp(); - try { - FileUtils.deleteDirectory(replayTemp.toFile()); - } catch (Exception e) { - throw new RuntimeException(e); - } + TempFolderProvider.deleteTemp(TempFolderProvider.TempFolderType.SERVER, this.playbackUUID); } @Override diff --git a/src/client/java/com/moulberry/flashback/record/FlashbackChunkMeta.java b/src/main/java/com/moulberry/flashback/record/FlashbackChunkMeta.java similarity index 100% rename from src/client/java/com/moulberry/flashback/record/FlashbackChunkMeta.java rename to src/main/java/com/moulberry/flashback/record/FlashbackChunkMeta.java diff --git a/src/client/java/com/moulberry/flashback/record/FlashbackMeta.java b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java similarity index 70% rename from src/client/java/com/moulberry/flashback/record/FlashbackMeta.java rename to src/main/java/com/moulberry/flashback/record/FlashbackMeta.java index b5ec101..72cc453 100644 --- a/src/client/java/com/moulberry/flashback/record/FlashbackMeta.java +++ b/src/main/java/com/moulberry/flashback/record/FlashbackMeta.java @@ -6,16 +6,25 @@ import org.jetbrains.annotations.Nullable; import java.util.LinkedHashMap; import java.util.Map; +import java.util.UUID; public class FlashbackMeta { - public String name = "Whatever"; + public String name = "Unnamed"; public LinkedHashMap chunks = new LinkedHashMap<>(); + public int totalTicks = -1; + public UUID replayIdentifier = UUID.randomUUID(); public JsonObject toJson() { JsonObject meta = new JsonObject(); meta.addProperty("name", this.name); + meta.addProperty("uuid", this.replayIdentifier.toString()); + + if (this.totalTicks > 0) { + meta.addProperty("total_ticks", this.totalTicks); + } + JsonObject chunksJson = new JsonObject(); for (Map.Entry entry : this.chunks.entrySet()) { chunksJson.add(entry.getKey(), entry.getValue().toJson()); @@ -35,6 +44,17 @@ public class FlashbackMeta { } flashbackMeta.name = meta.get("name").getAsString(); + // UUID + if (!meta.has("uuid")) { + return null; + } + flashbackMeta.replayIdentifier = UUID.fromString(meta.get("uuid").getAsString()); + + // Total ticks + if (meta.has("total_ticks")) { + flashbackMeta.totalTicks = meta.get("total_ticks").getAsInt(); + } + // Chunks if (!meta.has("chunks")) { return null; diff --git a/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java new file mode 100644 index 0000000..ef0df92 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/record/IgnoredPacketSet.java @@ -0,0 +1,80 @@ +package com.moulberry.flashback.record; + +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.*; +import net.minecraft.network.protocol.configuration.ClientboundFinishConfigurationPacket; +import net.minecraft.network.protocol.cookie.ClientboundCookieRequestPacket; +import net.minecraft.network.protocol.game.*; +import net.minecraft.network.protocol.ping.ClientboundPongResponsePacket; + +import java.util.Set; + +public class IgnoredPacketSet { + + public static boolean isIgnored(Packet packet) { + return IGNORED.contains(packet.getClass()); + } + + private static final Set> IGNORED = Set.of( + // Common + ClientboundStoreCookiePacket.class, + ClientboundCustomReportDetailsPacket.class, + ClientboundServerLinksPacket.class, + ClientboundCookieRequestPacket.class, + ClientboundDisconnectPacket.class, + ClientboundPingPacket.class, + ClientboundKeepAlivePacket.class, + ClientboundTransferPacket.class, + + // Configuration + ClientboundFinishConfigurationPacket.class, + + // Game + ClientboundAwardStatsPacket.class, + ClientboundRecipePacket.class, + ClientboundOpenSignEditorPacket.class, + ClientboundRotateHeadPacket.class, + ClientboundMoveEntityPacket.Pos.class, + ClientboundMoveEntityPacket.Rot.class, + ClientboundMoveEntityPacket.PosRot.class, + ClientboundPlayerPositionPacket.class, + ClientboundPlayerChatPacket.class, + ClientboundDeleteChatPacket.class, + ClientboundContainerClosePacket.class, + ClientboundContainerSetContentPacket.class, + ClientboundHorseScreenOpenPacket.class, + ClientboundContainerSetDataPacket.class, + ClientboundContainerSetSlotPacket.class, + ClientboundForgetLevelChunkPacket.class, + ClientboundPlayerAbilitiesPacket.class, + ClientboundSetCarriedItemPacket.class, + ClientboundTickingStatePacket.class, + ClientboundTickingStepPacket.class, + ClientboundPlayerCombatEndPacket.class, + ClientboundPlayerCombatEnterPacket.class, + ClientboundPlayerCombatKillPacket.class, + ClientboundSetCameraPacket.class, + ClientboundCooldownPacket.class, + ClientboundUpdateAdvancementsPacket.class, + ClientboundSelectAdvancementsTabPacket.class, + ClientboundPlaceGhostRecipePacket.class, + ClientboundCommandsPacket.class, + ClientboundCommandSuggestionsPacket.class, + ClientboundUpdateRecipesPacket.class, + ClientboundTagQueryPacket.class, + ClientboundOpenBookPacket.class, + ClientboundOpenScreenPacket.class, + ClientboundMerchantOffersPacket.class, + ClientboundSetChunkCacheRadiusPacket.class, + ClientboundSetSimulationDistancePacket.class, + ClientboundSetChunkCacheCenterPacket.class, + ClientboundBlockChangedAckPacket.class, + ClientboundCustomChatCompletionsPacket.class, + ClientboundStartConfigurationPacket.class, + ClientboundChunkBatchStartPacket.class, + ClientboundChunkBatchFinishedPacket.class, + ClientboundDebugSamplePacket.class, + ClientboundPongResponsePacket.class + ); + +} diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java new file mode 100644 index 0000000..9443b1d --- /dev/null +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -0,0 +1,720 @@ +package com.moulberry.flashback.record; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.mojang.blaze3d.platform.NativeImage; +import com.mojang.datafixers.util.Pair; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.PacketHelper; +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.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.multiplayer.ClientChunkCache; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.resources.server.ServerPackManager; +import net.minecraft.core.*; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; +import net.minecraft.network.ConnectionProtocol; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; +import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket; +import net.minecraft.network.protocol.common.ClientboundUpdateTagsPacket; +import net.minecraft.network.protocol.configuration.ClientConfigurationPacketListener; +import net.minecraft.network.protocol.configuration.ClientboundRegistryDataPacket; +import net.minecraft.network.protocol.configuration.ClientboundUpdateEnabledFeaturesPacket; +import net.minecraft.network.protocol.configuration.ConfigurationProtocols; +import net.minecraft.network.protocol.game.*; +import net.minecraft.network.syncher.SynchedEntityData; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.RegistryLayer; +import net.minecraft.tags.TagNetworkSerialization; +import net.minecraft.util.Mth; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.ai.attributes.AttributeInstance; +import net.minecraft.world.flag.FeatureFlags; +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.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.*; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.atomic.AtomicReferenceArray; + +public class Recorder { + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + public static final int CHUNK_LENGTH_SECONDS = 5 * 60; + + private final AsyncReplaySaver asyncReplaySaver; + private final StreamCodec> configurationPacketCodec; + private StreamCodec> gamePacketCodec; + + private int writtenTicksInChunk = 0; + private int writtenTicks = 0; + private final FlashbackMeta metadata = new FlashbackMeta(); + private boolean hasTakenScreenshot = false; + + private record PacketWithPhase(Packet packet, ConnectionProtocol phase){} + private final Queue pendingPackets = new ConcurrentLinkedQueue<>(); + + private record Position(double x, double y, double z, float yaw, float pitch, float headYRot, boolean onGround) { + public Position { + yaw = Mth.wrapDegrees(yaw); + pitch = Mth.wrapDegrees(pitch); + headYRot = Mth.wrapDegrees(headYRot); + } + } + private final WeakHashMap lastPositions = new WeakHashMap<>(); + + // Local player data + private final List lastPlayerEntityMeta = new ArrayList<>(); + private final Map lastPlayerEquipment = new EnumMap<>(EquipmentSlot.class); + private BlockPos lastDestroyPos = null; + private int lastDestroyProgress = -1; + private boolean wasSwinging = false; + private int lastSwingTime = -1; + + private boolean isConfiguring = false; + private boolean finishedConfiguration = false; + private boolean finishedPausing = false; + + private volatile boolean needsInitialSnapshot = true; + private volatile boolean closeForWriting = false; + private volatile boolean isPaused = false; + private volatile boolean wasPaused = false; + + public Recorder(RegistryAccess registryAccess) { + this.asyncReplaySaver = new AsyncReplaySaver(registryAccess); + this.configurationPacketCodec = ConfigurationProtocols.CLIENTBOUND.codec(); + this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); + } + + public void setRegistryAccess(RegistryAccess registryAccess) { + this.asyncReplaySaver.submit(writer -> writer.setRegistryAccess(registryAccess)); + this.gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec(); + } + + public String getDebugString() { + StringBuilder builder = new StringBuilder(); + builder.append("[Flashback] Recording. T: "); + builder.append(this.writtenTicks); + builder.append(". S: "); + builder.append(this.metadata.chunks.size()); + builder.append(" ("); + builder.append(this.writtenTicksInChunk); + builder.append("/"); + builder.append(CHUNK_LENGTH_SECONDS*20); + builder.append(")"); + return builder.toString(); + } + + public void endTick(boolean close) { + if (this.closeForWriting) { + return; + } else if (close) { + this.closeForWriting = true; + } + + if (this.isPaused) { + this.wasPaused = true; + } + + if (this.needsInitialSnapshot) { + this.needsInitialSnapshot = false; + this.writeSnapshot(true); + } + + this.finishedConfiguration |= this.flushPackets(); + + if (Minecraft.getInstance().level != null && Minecraft.getInstance().getOverlay() == null && !Minecraft.getInstance().isPaused() && !this.isPaused) { + 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; + } + } + } + + this.finishedPausing |= this.wasPaused && !this.isPaused; + + boolean writeChunk = close; + if (Minecraft.getInstance().level != null) { + boolean finished = this.finishedConfiguration || this.finishedPausing; + writeChunk |= this.writtenTicksInChunk >= CHUNK_LENGTH_SECONDS*20 || finished; + } + + if (writeChunk) { + // Add an extra tick to avoid edge-cases with 0-length replay chunks + if (this.writtenTicksInChunk == 0) { + this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); + this.writtenTicksInChunk += 1; + this.writtenTicks += 1; + } + + int chunkId = this.metadata.chunks.size(); + String chunkName = "c" + chunkId + ".flashback"; + + var chunkMeta = new FlashbackChunkMeta(); + chunkMeta.duration = this.writtenTicksInChunk; + this.metadata.chunks.put(chunkName, chunkMeta); + this.metadata.totalTicks = this.writtenTicks; + String metadata = GSON.toJson(this.metadata.toJson()); + + this.asyncReplaySaver.writeReplayChunk(chunkName, metadata); + + this.writtenTicksInChunk = 0; + + if (!close) { + // When we finish pausing, we write the snapshot as normal packets directly + if (this.finishedPausing) { + this.asyncReplaySaver.submit(ReplayWriter::startSnapshot); + this.asyncReplaySaver.submit(ReplayWriter::endSnapshot); + this.writeSnapshot(false); + } else { + this.writeSnapshot(true); + } + } + + this.finishedPausing = false; + this.finishedConfiguration = false; + } + + if (!this.isPaused) { + this.wasPaused = false; + } + } + + public boolean isPaused() { + return this.isPaused; + } + + public void setPaused(boolean paused) { + 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); + } + } + } + + private void writeLocalData() { + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) { + this.lastPlayerEntityMeta.clear(); + this.lastPlayerEquipment.clear(); + this.lastDestroyPos = null; + this.lastDestroyProgress = -1; + return; + } + + List> gamePackets = new ArrayList<>(); + + // Update entity data + SynchedEntityData.DataItem[] items = Minecraft.getInstance().player.getEntityData().itemsById; + List> changedData = new ArrayList<>(); + for (int i = 0; i < items.length; i++) { + SynchedEntityData.DataItem dataItem = items[i]; + Object value = dataItem.value().value(); + + if (i >= this.lastPlayerEntityMeta.size()) { + this.lastPlayerEntityMeta.add(i, value); + } else { + Object old = this.lastPlayerEntityMeta.get(i); + if (!Objects.equals(old, value)) { + this.lastPlayerEntityMeta.set(i, value); + changedData.add(dataItem.value()); + } + } + } + + if (!changedData.isEmpty()) { + gamePackets.add(new ClientboundSetEntityDataPacket(player.getId(), changedData)); + } + + // Update equipment + List> changedSlots = new ArrayList<>(); + for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) { + ItemStack itemStack = player.getItemBySlot(equipmentSlot); + + if (!this.lastPlayerEquipment.containsKey(equipmentSlot)) { + this.lastPlayerEquipment.put(equipmentSlot, itemStack.copy()); + } else if (!ItemStack.matches(this.lastPlayerEquipment.get(equipmentSlot), itemStack)) { + ItemStack copied = itemStack.copy(); + this.lastPlayerEquipment.put(equipmentSlot, copied); + changedSlots.add(Pair.of(equipmentSlot, copied)); + } + } + if (!changedSlots.isEmpty()) { + gamePackets.add(new ClientboundSetEquipmentPacket(player.getId(), changedSlots)); + } + + // Update breaking + MultiPlayerGameMode multiPlayerGameMode = Minecraft.getInstance().gameMode; + if (multiPlayerGameMode == null) { + this.lastDestroyPos = null; + this.lastDestroyProgress = -1; + } else { + BlockPos destroyPos = multiPlayerGameMode.destroyBlockPos.immutable(); + int destroyProgress = multiPlayerGameMode.getDestroyStage(); + + boolean changed = destroyProgress != this.lastDestroyProgress; + if (destroyProgress >= 0) { + changed |= !destroyPos.equals(this.lastDestroyPos); + } + + if (changed) { + gamePackets.add(new ClientboundBlockDestructionPacket(player.getId(), destroyPos, destroyProgress)); + } + + this.lastDestroyPos = destroyPos; + this.lastDestroyProgress = destroyProgress; + } + + // Update swinging + if (player.swinging && (!this.wasSwinging || this.lastSwingTime > player.swingTime)) { + int animation = player.swingingArm == InteractionHand.MAIN_HAND ? ClientboundAnimatePacket.SWING_MAIN_HAND : ClientboundAnimatePacket.SWING_OFF_HAND; + gamePackets.add(new ClientboundAnimatePacket(player, animation)); + } + this.lastSwingTime = player.swingTime; + this.wasSwinging = player.swinging; + + this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets); + } + + private void writeEntityPositions() { + ClientLevel level = Minecraft.getInstance().level; + if (level == null) { + this.lastPositions.clear(); + return; + } + + record IdWithPosition(int id, Position position) {} + List changedPositions = new ArrayList<>(); + + for (Entity entity : level.entitiesForRendering()) { + 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(), + entity.getYRot(), entity.getXRot(), entity.getYHeadRot(), entity.onGround()); + } + Position lastPosition = this.lastPositions.get(entity); + + if (!Objects.equals(position, lastPosition)) { + this.lastPositions.put(entity, position); + changedPositions.add(new IdWithPosition(entity.getId(), position)); + } + } + + this.asyncReplaySaver.submit(writer -> { + writer.startAction(ActionMoveEntities.INSTANCE); + RegistryFriendlyByteBuf friendlyByteBuf = writer.friendlyByteBuf(); + + friendlyByteBuf.writeVarInt(1); + friendlyByteBuf.writeResourceKey(level.dimension()); + + friendlyByteBuf.writeVarInt(changedPositions.size()); + for (IdWithPosition changedPosition : changedPositions) { + friendlyByteBuf.writeVarInt(changedPosition.id); + friendlyByteBuf.writeDouble(changedPosition.position.x); + friendlyByteBuf.writeDouble(changedPosition.position.y); + friendlyByteBuf.writeDouble(changedPosition.position.z); + friendlyByteBuf.writeFloat(changedPosition.position.yaw); + friendlyByteBuf.writeFloat(changedPosition.position.pitch); + friendlyByteBuf.writeFloat(changedPosition.position.headYRot); + friendlyByteBuf.writeBoolean(changedPosition.position.onGround); + } + + writer.finishAction(ActionMoveEntities.INSTANCE); + }); + } + + public boolean flushPackets() { + if (this.pendingPackets.isEmpty()) { + return false; + } + + boolean endedConfiguration = false; + + List> gamePackets = new ArrayList<>(); + List> configurationPackets = new ArrayList<>(); + + PacketWithPhase packet; + while ((packet = this.pendingPackets.poll()) != null) { + if (packet.phase == ConnectionProtocol.PLAY) { + if (!configurationPackets.isEmpty()) { + this.asyncReplaySaver.writeConfigurationPackets(this.configurationPacketCodec, configurationPackets); + configurationPackets.clear(); + } + + gamePackets.add(((Packet) packet.packet)); + + if (this.isConfiguring) { + endedConfiguration = true; + this.isConfiguring = false; + } + } else if (packet.phase == ConnectionProtocol.CONFIGURATION) { + if (!gamePackets.isEmpty()) { + this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets); + gamePackets.clear(); + } + + configurationPackets.add(((Packet) packet.packet)); + + this.isConfiguring = true; + } else { + throw new IllegalArgumentException("Unsupported phase: " + packet.phase); + } + } + + if (!configurationPackets.isEmpty()) { + this.asyncReplaySaver.writeConfigurationPackets(this.configurationPacketCodec, configurationPackets); + } + if (!gamePackets.isEmpty()) { + this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets); + + if (this.isConfiguring) { + endedConfiguration = true; + this.isConfiguring = false; + } + } + + return endedConfiguration; + } + + public void writePacketAsync(Packet packet, ConnectionProtocol phase) { + if (this.closeForWriting || this.needsInitialSnapshot || this.wasPaused) { + return; + } + + if (packet instanceof ClientboundBundlePacket bundlePacket) { + for (Packet subPacket : bundlePacket.subPackets()) { + this.writePacketAsync(subPacket, phase); + } + return; + } + + if (IgnoredPacketSet.isIgnored(packet)) { + return; + } + + LocalPlayer localPlayer = Minecraft.getInstance().player; + if (localPlayer != null) { + int localPlayerId = localPlayer.getId(); + if (packet instanceof ClientboundSetEntityDataPacket entityDataPacket && entityDataPacket.id() == localPlayerId) { + return; + } + if (packet instanceof ClientboundSetEquipmentPacket entityEquipmentPacket && entityEquipmentPacket.getEntity() == localPlayerId) { + return; + } + } + + this.pendingPackets.add(new PacketWithPhase(packet, phase)); + } + + public void writeSnapshot(boolean asActualSnapshot) { + if (asActualSnapshot) { + this.asyncReplaySaver.submit(ReplayWriter::startSnapshot); + } + + ClientLevel level = Minecraft.getInstance().level; + LocalPlayer localPlayer = Minecraft.getInstance().player; + ClientPacketListener connection = Minecraft.getInstance().getConnection(); + MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode; + ClientChunkCache clientChunkCache = level.getChunkSource(); + + AtomicReferenceArray chunks = clientChunkCache.storage.chunks; + + // Configuration data + + List> configurationPackets = new ArrayList<>(); + + // Enabled features + configurationPackets.add(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(level.enabledFeatures()))); + + // Registry data + RegistryOps dynamicOps = localPlayer.registryAccess().createSerializationContext(NbtOps.INSTANCE); + RegistrySynchronization.packRegistries(dynamicOps, localPlayer.registryAccess(), Set.of(), (resourceKey, list) -> { + configurationPackets.add(new ClientboundRegistryDataPacket(resourceKey, list)); + }); + + // Tags + Map>, TagNetworkSerialization.NetworkPayload> serializedTags = new HashMap<>(); + RegistryLayer.createRegistryAccess().compositeAccess().registries().forEach(entry -> { + if (entry.value().size() > 0) { + var tags = TagNetworkSerialization.serializeToNetwork(entry.value()); + if (tags.size() > 0) { + serializedTags.put(entry.key(), tags); + } + } + }); + localPlayer.registryAccess().registries().forEach(entry -> { + if (serializedTags.containsKey(entry.key())) { + return; + } + if (RegistrySynchronization.NETWORKABLE_REGISTRIES.contains(entry.key()) && entry.value().size() > 0) { + var tags = TagNetworkSerialization.serializeToNetwork(entry.value()); + if (tags.size() > 0) { + serializedTags.put(entry.key(), tags); + } + } + }); + + configurationPackets.add(new ClientboundUpdateTagsPacket(serializedTags)); + + // Resource packs + configurationPackets.add(new ClientboundResourcePackPopPacket(Optional.empty())); + for (ServerPackManager.ServerPackData pack : Minecraft.getInstance().getDownloadedPackSource().manager.packs) { + configurationPackets.add(new ClientboundResourcePackPushPacket(pack.id, pack.url.toString(), pack.hash == null ? "" : pack.hash.toString(), + true, Optional.empty())); + } + + this.asyncReplaySaver.writeConfigurationPackets(this.configurationPacketCodec, configurationPackets); + List> gamePackets = new ArrayList<>(); + + // Login packet + CommonPlayerSpawnInfo commonPlayerSpawnInfo = new CommonPlayerSpawnInfo(level.dimensionTypeRegistration(), level.dimension(), 0, + gameMode.getPlayerMode(), gameMode.getPreviousPlayerMode(), level.isDebug(), false, 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); + gamePackets.add(loginPacket); + + // Create player info update packet + var infoUpdatePacket = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, + ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LISTED, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), List.of()); + infoUpdatePacket.entries = new ArrayList<>(level.players().size()); + Set addedEntries = new HashSet<>(); + for (AbstractClientPlayer player : level.players()) { + if (addedEntries.add(player.getUUID())) { + PlayerInfo info = connection.getPlayerInfo(player.getUUID()); + if (info != null) { + infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), + player.getGameProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), null)); + } else { + infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(), + player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), null)); + } + } + } + for (PlayerInfo info : connection.getListedOnlinePlayers()) { + if (addedEntries.add(info.getProfile().getId())) { + infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(info.getProfile().getId(), + info.getProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), null)); + } + } + gamePackets.add(infoUpdatePacket); + + // Tab list + PlayerTabOverlay playerTabOverlay = Minecraft.getInstance().gui.getTabList(); + gamePackets.add(new ClientboundTabListPacket( + playerTabOverlay.header != null ? playerTabOverlay.header : Component.empty(), + playerTabOverlay.footer != null ? playerTabOverlay.footer : Component.empty() + )); + + // Boss bar + BossHealthOverlay bossOverlay = Minecraft.getInstance().gui.getBossOverlay(); + for (LerpingBossEvent event : bossOverlay.events.values()) { + gamePackets.add(ClientboundBossEventPacket.createAddPacket(event)); + } + + // Scoreboard + Scoreboard scoreboard = localPlayer.getScoreboard(); + for (PlayerTeam playerTeam : scoreboard.getPlayerTeams()) { + gamePackets.add(ClientboundSetPlayerTeamPacket.createAddOrModifyPacket(playerTeam, true)); + } + HashSet handledObjectives = new HashSet<>(); + for (DisplaySlot displaySlot : DisplaySlot.values()) { + Objective objective = scoreboard.getDisplayObjective(displaySlot); + if (objective != null && handledObjectives.add(objective)) { + gamePackets.add(new ClientboundSetObjectivePacket(objective, 0)); + + for (DisplaySlot displaySlot2 : DisplaySlot.values()) { + if (scoreboard.getDisplayObjective(displaySlot2) == objective) { + gamePackets.add(new ClientboundSetDisplayObjectivePacket(displaySlot2, objective)); + } + } + + for (PlayerScoreEntry playerScoreEntry : scoreboard.listPlayerScores(objective)) { + gamePackets.add(new ClientboundSetScorePacket(playerScoreEntry.owner(), objective.getName(), playerScoreEntry.value(), + Optional.ofNullable(playerScoreEntry.display()), Optional.ofNullable(playerScoreEntry.numberFormatOverride()))); + } + } + } + + // Level info + WorldBorder worldBorder = level.getWorldBorder(); + gamePackets.add(new ClientboundInitializeBorderPacket(worldBorder)); + gamePackets.add(new ClientboundSetTimePacket(level.getGameTime(), level.getDayTime(), level.getGameRules().getBoolean(GameRules.RULE_DAYLIGHT))); + gamePackets.add(new ClientboundSetDefaultSpawnPositionPacket(level.getSharedSpawnPos(), level.getSharedSpawnAngle())); + if (level.isRaining()) { + gamePackets.add(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0f)); + } else { + gamePackets.add(new ClientboundGameEventPacket(ClientboundGameEventPacket.STOP_RAINING, 0.0f)); + } + gamePackets.add(new ClientboundGameEventPacket(ClientboundGameEventPacket.RAIN_LEVEL_CHANGE, level.getRainLevel(1.0f))); + gamePackets.add(new ClientboundGameEventPacket(ClientboundGameEventPacket.THUNDER_LEVEL_CHANGE, level.getThunderLevel(1.0f))); + + // Chunk data + if (Runtime.getRuntime().availableProcessors() <= 1) { + List levelChunkPackets = new ArrayList<>(); + + for (int i = 0; i < chunks.length(); i++) { + LevelChunk chunk = chunks.get(i); + if (chunk != null) { + levelChunkPackets.add(new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), null, null)); + } + } + + int centerX = localPlayer.getBlockX() >> 4; + int centerZ = localPlayer.getBlockZ() >> 4; + levelChunkPackets.sort(Comparator.comparingInt(task -> { + int dx = task.getX() - centerX; + int dz = task.getZ() - centerZ; + return dx*dx + dz*dz; + })); + + gamePackets.addAll(levelChunkPackets); + } else { + try (ForkJoinPool pool = new ForkJoinPool()) { + final class PositionedTask { + private final ChunkPos pos; + private final ForkJoinTask task; + private ClientboundLightUpdatePacketData lightData = null; + + PositionedTask(ChunkPos pos, ForkJoinTask task) { + this.pos = pos; + this.task = task; + } + } + List levelChunkPacketTasks = new ArrayList<>(); + + for (int i = 0; i < chunks.length(); i++) { + LevelChunk chunk = chunks.get(i); + if (chunk != null) { + var task = pool.submit(() -> new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), new BitSet(), new BitSet())); + levelChunkPacketTasks.add(new PositionedTask(chunk.getPos(), task)); + } + } + + int centerX = localPlayer.getBlockX() >> 4; + int centerZ = localPlayer.getBlockZ() >> 4; + levelChunkPacketTasks.sort(Comparator.comparingInt(task -> { + int dx = task.pos.x - centerX; + int dz = task.pos.z - centerZ; + return dx*dx + dz*dz; + })); + + // We get the light data on this thread to avoid + // slowdown due to synchronization + + for (PositionedTask positionedTask : levelChunkPacketTasks) { + positionedTask.lightData = new ClientboundLightUpdatePacketData(positionedTask.pos, + level.getLightEngine(), null, null); + } + + for (PositionedTask positionedTask : levelChunkPacketTasks) { + ClientboundLevelChunkWithLightPacket levelChunkWithLightPacket = positionedTask.task.join(); + levelChunkWithLightPacket.lightData = positionedTask.lightData; + gamePackets.add(levelChunkWithLightPacket); + } + } + } + + // Entity data + for (Entity entity : level.entitiesForRendering()) { + if (!(entity instanceof LocalPlayer)) { + gamePackets.add(PacketHelper.createAddEntity(entity)); + } + + List> nonDefaultEntityData = entity.getEntityData().getNonDefaultValues(); + if (nonDefaultEntityData != null && !nonDefaultEntityData.isEmpty()) { + gamePackets.add(new ClientboundSetEntityDataPacket(entity.getId(), nonDefaultEntityData)); + } + + if (entity instanceof LivingEntity livingEntity) { + Collection syncableAttributes = livingEntity.getAttributes().getSyncableAttributes(); + if (!syncableAttributes.isEmpty()) { + gamePackets.add(new ClientboundUpdateAttributesPacket(entity.getId(), syncableAttributes)); + } + + List> changedSlots = new ArrayList<>(); + for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) { + ItemStack itemStack = livingEntity.getItemBySlot(equipmentSlot); + if (!itemStack.isEmpty()) { + changedSlots.add(Pair.of(equipmentSlot, itemStack.copy())); + } + } + if (!changedSlots.isEmpty()) { + gamePackets.add(new ClientboundSetEquipmentPacket(entity.getId(), changedSlots)); + } + } + + if (entity.isVehicle()) { + gamePackets.add(new ClientboundSetPassengersPacket(entity)); + } + if (entity.isPassenger()) { + gamePackets.add(new ClientboundSetPassengersPacket(entity.getVehicle())); + } + + if (entity instanceof Mob mob && mob.isLeashed()) { + gamePackets.add(new ClientboundSetEntityLinkPacket(mob, mob.getLeashHolder())); + } + } + + this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets); + + if (asActualSnapshot) { + this.asyncReplaySaver.submit(ReplayWriter::endSnapshot); + } + } + +} diff --git a/src/client/java/com/moulberry/flashback/record/Exporter.java b/src/main/java/com/moulberry/flashback/record/ReplayExporter.java similarity index 56% rename from src/client/java/com/moulberry/flashback/record/Exporter.java rename to src/main/java/com/moulberry/flashback/record/ReplayExporter.java index 978b741..76d7d7b 100644 --- a/src/client/java/com/moulberry/flashback/record/Exporter.java +++ b/src/main/java/com/moulberry/flashback/record/ReplayExporter.java @@ -3,31 +3,32 @@ package com.moulberry.flashback.record; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; -import com.moulberry.flashback.FlashbackClient; +import com.moulberry.flashback.Flashback; import org.apache.commons.io.FileUtils; 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; +import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -public class Exporter { +public class ReplayExporter { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); public static void export(Path recordFolder, Path outputFile) { - FlashbackClient.LOGGER.info("Exporting {} to {}", recordFolder, outputFile); + Flashback.LOGGER.info("Exporting {} to {}", recordFolder, outputFile); FlashbackMeta meta = tryReadMeta(recordFolder.resolve("metadata.json")); if (meta == null) { meta = tryReadMeta(recordFolder.resolve("metadata.json.old")); } if (meta == null) { - FlashbackClient.LOGGER.error("Cannot export, both metadata files are invalid"); + Flashback.LOGGER.error("Cannot export, both metadata files are invalid"); return; } @@ -35,7 +36,7 @@ public class Exporter { meta.chunks.keySet().removeIf(chunkName -> { Path chunkPath = recordFolder.resolve(chunkName); if (!Files.exists(chunkPath)) { - FlashbackClient.LOGGER.warn("Cannot find chunk path: {}, skipping", chunkPath); + Flashback.LOGGER.warn("Cannot find chunk path: {}, skipping", chunkPath); return true; } else { return false; @@ -43,72 +44,90 @@ public class Exporter { }); if (meta.chunks.isEmpty()) { - FlashbackClient.LOGGER.error("Cannot export, no chunk files exist"); + Flashback.LOGGER.error("Cannot export, no chunk files exist"); return; } try { FileOutputStream fos = new FileOutputStream(outputFile.toFile()); - ZipOutputStream zipOut = new ZipOutputStream(fos); + BufferedOutputStream bos = new BufferedOutputStream(fos); + ZipOutputStream zipOut = new ZipOutputStream(bos); + zipOut.setLevel(Deflater.BEST_SPEED); // Write metadata ZipEntry zipEntry = new ZipEntry("metadata.json"); zipOut.putNextEntry(zipEntry); zipOut.write(GSON.toJson(meta.toJson()).getBytes(StandardCharsets.UTF_8)); + zipOut.closeEntry(); + + // Write level chunk cache + Path levelChunkCachePath = recordFolder.resolve("level_chunk_cache"); + if (Files.exists(levelChunkCachePath)) { + zipEntry = new ZipEntry("level_chunk_cache"); + zipOut.putNextEntry(zipEntry); + Files.copy(levelChunkCachePath, zipOut); + zipOut.closeEntry(); + } + + // Write icon + Path iconPath = recordFolder.resolve("icon.png"); + if (Files.exists(iconPath)) { + zipEntry = new ZipEntry("icon.png"); + zipOut.putNextEntry(zipEntry); + Files.copy(iconPath, zipOut); + zipOut.closeEntry(); + } // Write chunks for (String chunkName : meta.chunks.keySet()) { Path chunkPath = recordFolder.resolve(chunkName); - byte[] chunkData = Files.readAllBytes(chunkPath); - - if (chunkData.length == 0) { - FlashbackClient.LOGGER.warn("Length of chunk data {} is zero, might be corrupted...", chunkName); - } zipEntry = new ZipEntry(chunkName); zipOut.putNextEntry(zipEntry); - zipOut.write(chunkData); + Files.copy(chunkPath, zipOut); + zipOut.closeEntry(); } zipOut.close(); + bos.close(); fos.close(); // Delete record folder try { FileUtils.deleteDirectory(recordFolder.toFile()); } catch (Exception e) { - FlashbackClient.LOGGER.error("Exception deleting record folder", e); + Flashback.LOGGER.error("Exception deleting record folder", e); } } catch (Exception e) { - FlashbackClient.LOGGER.error("Exception exporting replay", e); + Flashback.LOGGER.error("Exception exporting replay", e); } } @Nullable private static FlashbackMeta tryReadMeta(Path file) { - FlashbackClient.LOGGER.info("Trying to read metadata json {}", file); + Flashback.LOGGER.info("Trying to read metadata json {}", file); if (!Files.exists(file)) { - FlashbackClient.LOGGER.error("Metadata JSON doesn't exist!"); + Flashback.LOGGER.error("Metadata JSON doesn't exist!"); return null; } try { String metaString = Files.readString(file); if (metaString.isBlank()) { - FlashbackClient.LOGGER.error("Metadata JSON is blank"); + Flashback.LOGGER.error("Metadata JSON is blank"); return null; } JsonObject metaObject = GSON.fromJson(metaString, JsonObject.class); if (metaObject.isEmpty()) { - FlashbackClient.LOGGER.error("Metadata JSON is empty"); + Flashback.LOGGER.error("Metadata JSON is empty"); return null; } return FlashbackMeta.fromJson(metaObject); } catch (Exception e) { - FlashbackClient.LOGGER.error("Exception while reading metadata", e); + Flashback.LOGGER.error("Exception while reading metadata", e); return null; } } diff --git a/src/client/java/com/moulberry/flashback/registry/RegistryHelper.java b/src/main/java/com/moulberry/flashback/registry/RegistryHelper.java similarity index 100% rename from src/client/java/com/moulberry/flashback/registry/RegistryHelper.java rename to src/main/java/com/moulberry/flashback/registry/RegistryHelper.java diff --git a/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java b/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java new file mode 100644 index 0000000..2d77322 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/BottomTextWidget.java @@ -0,0 +1,28 @@ +package com.moulberry.flashback.screen; + +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.AbstractStringWidget; +import net.minecraft.network.chat.Component; + +public class BottomTextWidget extends AbstractStringWidget { + + public BottomTextWidget(int width, int height, Component component, Font font) { + super(0, 0, width, height, component, font); + this.active = false; + } + + public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { + Component component = this.getMessage(); + + Font font = this.getFont(); + + int width = this.getWidth(); + int textWidth = font.width(component); + int x = this.getX() + Math.round((width - textWidth)/2.0f); + 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 new file mode 100644 index 0000000..55e64ae --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/ConfigScreen.java @@ -0,0 +1,24 @@ +package com.moulberry.flashback.screen; + +import com.moulberry.flashback.configuration.FlashbackConfig; +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; + +public class ConfigScreen extends OptionsSubScreen { + + public ConfigScreen(Screen previous) { + super(previous, Minecraft.getInstance().options, Component.literal("Flashback Options")); + } + + protected void addOptions() { + if (this.list != null) { + this.list.addSmall(FlashbackConfig.createOptionInstances()); + } + } + + public void removed() { + } + +} diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java new file mode 100644 index 0000000..215cd35 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java @@ -0,0 +1,462 @@ +/* + * Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4). + */ +package com.moulberry.flashback.screen; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +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.SneakyThrow; +import com.moulberry.flashback.record.FlashbackMeta; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.ObjectSelectionList; +import net.minecraft.client.gui.components.toasts.SystemToast; +import net.minecraft.client.gui.narration.NarrationElementOutput; +import net.minecraft.client.gui.navigation.CommonInputs; +import net.minecraft.client.gui.screens.*; +import net.minecraft.client.resources.language.I18n; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundEvents; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; + +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.*; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +public class ReplaySelectionList extends ObjectSelectionList { + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault()); + private static final ResourceLocation ERROR_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error_highlighted"); + private static final ResourceLocation ERROR_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error"); + private static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join_highlighted"); + private static final ResourceLocation JOIN_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join"); + private static final Logger LOGGER = LogUtils.getLogger(); + private final SelectReplayScreen screen; + private CompletableFuture> pendingReplays; + @Nullable + private List currentlyDisplayedReplays; + private String filter; + private final LoadingHeader loadingHeader; + + 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; + this.loadingHeader = new LoadingHeader(minecraft); + this.filter = string; + this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays(); + this.handleNewReplays(this.pollReplaysIgnoreErrors()); + } + + @Override + protected void clearEntries() { + this.children().forEach(Entry::close); + super.clearEntries(); + } + + @Nullable + private List pollReplaysIgnoreErrors() { + try { + return this.pendingReplays.getNow(null); + } catch (CancellationException | CompletionException runtimeException) { + return null; + } + } + + private void reloadWorldList() { + this.pendingReplays = this.loadReplays(); + } + + @Override + public boolean keyPressed(int i, int j, int k) { + if (CommonInputs.selected(i)) { + ReplayListEntry replayListEntry = this.getReplayListEntry(); + if (replayListEntry != null && replayListEntry.canOpen()) { + this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); + replayListEntry.openReplay(); + return true; + } + } + + return super.keyPressed(i, j, k); + } + + @Override + public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) { + List list = this.pollReplaysIgnoreErrors(); + if (list != this.currentlyDisplayedReplays) { + this.handleNewReplays(list); + } + super.renderWidget(guiGraphics, i, j, f); + } + + private void handleNewReplays(@Nullable List list) { + if (list == null) { + this.fillLoadingReplays(); + } else { + this.fillReplays(this.filter, list); + } + this.currentlyDisplayedReplays = list; + } + + public void updateFilter(String string) { + if (this.currentlyDisplayedReplays != null && !string.equals(this.filter)) { + this.fillReplays(string, this.currentlyDisplayedReplays); + } + this.filter = string; + } + + private CompletableFuture> loadReplays() { + Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback"); + Path replayDir = flashbackDir.resolve("replays"); + + if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) { + return CompletableFuture.completedFuture(List.of()); + } + + ArrayList> futures = new ArrayList<>(); + + try (DirectoryStream directoryStream = Files.newDirectoryStream(replayDir)) { + for (Path path : directoryStream) { + if (!path.toString().endsWith(".zip")) { + continue; + } + + futures.add(CompletableFuture.supplyAsync(() -> { + try { + String fileName = path.getFileName().toString(); + + BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class); + BasicFileAttributes basicFileAttributes = attributeView.readAttributes(); + + long lastOpened = Math.max(basicFileAttributes.creationTime().toMillis(), + Math.max(basicFileAttributes.lastAccessTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis())); + + byte[] iconBytes = null; + String metadataString = null; + + try (FileSystem fs = FileSystems.newFileSystem(path)) { + + Path iconPath = fs.getPath("/icon.png"); + if (Files.exists(iconPath)) { + iconBytes = Files.readAllBytes(iconPath); + } + + Path metadataPath = fs.getPath("/metadata.json"); + if (Files.exists(metadataPath)) { + metadataString = Files.readString(metadataPath); + } + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + + if (metadataString == null) { + return null; + } + + JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class); + FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson); + if (metadata != null) { + return new ReplaySummary(path, metadata, fileName, lastOpened, iconBytes); + } + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + return null; + }, Util.backgroundExecutor())); + } + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + + return Util.sequenceFailFastAndCancel(futures).thenApply(list -> list.stream().filter(Objects::nonNull).sorted().toList()); + } + + private void fillReplays(String string, List list) { + this.clearEntries(); + string = string.toLowerCase(Locale.ROOT); + for (ReplaySummary ReplaySummary : list) { + if (!this.filterAccepts(string, ReplaySummary)) continue; + this.addEntry(new ReplayListEntry(this, ReplaySummary)); + } + this.notifyListUpdated(); + } + + private boolean filterAccepts(String string, ReplaySummary ReplaySummary) { + return ReplaySummary.getReplayName().toLowerCase(Locale.ROOT).contains(string) || ReplaySummary.getReplayId().toLowerCase(Locale.ROOT).contains(string); + } + + private void fillLoadingReplays() { + this.clearEntries(); + this.addEntry(this.loadingHeader); + this.notifyListUpdated(); + } + + private void notifyListUpdated() { + this.setScrollAmount(this.getScrollAmount()); + this.screen.triggerImmediateNarration(true); + this.screen.updateButtonStatus(null); + } + + @Override + public int getRowWidth() { + return 270; + } + + @Override + public void setSelected(@Nullable Entry entry) { + super.setSelected(entry); + + if (entry instanceof ReplayListEntry replayListEntry) { + this.screen.updateButtonStatus(replayListEntry.summary); + } else { + this.screen.updateButtonStatus(null); + } + } + + @Nullable + public ReplayListEntry getReplayListEntry() { + if (this.getSelected() instanceof ReplayListEntry replayListEntry) { + return replayListEntry; + } else { + return null; + } + } + + public SelectReplayScreen getScreen() { + return this.screen; + } + + @Override + public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) { + if (this.children().contains(this.loadingHeader)) { + this.loadingHeader.updateNarration(narrationElementOutput); + return; + } + super.updateWidgetNarration(narrationElementOutput); + } + + public static class LoadingHeader extends Entry { + private static final Component LOADING_LABEL = Component.translatable("flashback.select_replay.loading_replays"); + private final Minecraft minecraft; + + public LoadingHeader(Minecraft minecraft) { + this.minecraft = minecraft; + } + + @Override + public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) { + int p = (this.minecraft.screen.width - this.minecraft.font.width(LOADING_LABEL)) / 2; + int q = j + (m - this.minecraft.font.lineHeight) / 2; + guiGraphics.drawString(this.minecraft.font, LOADING_LABEL, p, q, 0xFFFFFF, false); + String string = LoadingDotsText.get(Util.getMillis()); + int r = (this.minecraft.screen.width - this.minecraft.font.width(string)) / 2; + int s = q + this.minecraft.font.lineHeight; + guiGraphics.drawString(this.minecraft.font, string, r, s, -8355712, false); + } + + @Override + public Component getNarration() { + return LOADING_LABEL; + } + } + + public final class ReplayListEntry extends Entry implements AutoCloseable { + private static final int ICON_WIDTH = 32; + private static final int ICON_HEIGHT = 32; + private final Minecraft minecraft; + private final SelectReplayScreen screen; + final ReplaySummary summary; + private final FaviconTexture icon; + private long lastClickTime; + + public ReplayListEntry(ReplaySelectionList replaySelectionList2, ReplaySummary ReplaySummary) { + this.minecraft = replaySelectionList2.minecraft; + this.screen = replaySelectionList2.getScreen(); + this.summary = ReplaySummary; + this.icon = FaviconTexture.forWorld(this.minecraft.getTextureManager(), ReplaySummary.getReplayId()); + this.loadIcon(); + } + + @Override + public Component getNarration() { + MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(), + Component.translationArg(new Date(this.summary.getLastPlayed())), + this.summary.getInfo()); + return Component.translatable("narrator.select", component); + } + + @Override + public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) { + String title = this.summary.getReplayName(); + String fileAndTime = this.summary.getReplayId(); + long p = this.summary.getLastPlayed(); + if (p != -1L) { + fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")"; + } + if (StringUtils.isEmpty(title)) { + title = I18n.get("flashback.select_replay.replay") + " " + (i + 1); + } + Component info = this.summary.getInfo(); + + guiGraphics.drawString(this.minecraft.font, title, k + ICON_WIDTH + 3, j + 1, 0xFFFFFF, false); + guiGraphics.drawString(this.minecraft.font, fileAndTime, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + 3, 0xFF808080, false); + guiGraphics.drawString(this.minecraft.font, info, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false); + + RenderSystem.enableBlend(); + guiGraphics.blit(this.icon.textureLocation(), k, j, 0.0f, 0.0f, 32, 32, 32, 32); + RenderSystem.disableBlend(); + + if (this.minecraft.options.touchscreen().get() || bl) { + guiGraphics.fill(k, j, k + ICON_WIDTH, j + ICON_HEIGHT, -1601138544); + int q = n - k; + boolean bl2 = q < 32; + + if (!this.summary.canOpen()) { + ResourceLocation resourceLocation3 = bl2 ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE; + guiGraphics.blitSprite(resourceLocation3, k, j, ICON_WIDTH, ICON_HEIGHT); + } else { + ResourceLocation resourceLocation = bl2 ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE; + guiGraphics.blitSprite(resourceLocation, k, j, ICON_WIDTH, ICON_HEIGHT); + } + } + } + + @Override + public boolean mouseClicked(double d, double e, int i) { + if (!this.summary.canOpen()) { + return true; + } + ReplaySelectionList.this.setSelected(this); + if (d - (double) ReplaySelectionList.this.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) { + if (this.canOpen()) { + this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f)); + this.openReplay(); + } + return true; + } + this.lastClickTime = Util.getMillis(); + return super.mouseClicked(d, e, i); + } + + public boolean canOpen() { + return this.summary.canOpen(); + } + + public void openReplay() { + if (this.summary.canOpen()) { + this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("flashback.select_replay.data_read"))); + Flashback.openReplayWorld(this.summary.getPath()); + } + } + + public void deleteReplay() { + this.minecraft.setScreen(new ConfirmScreen(bl -> { + if (bl) { + this.minecraft.setScreen(new ProgressScreen(true)); + this.doDeleteReplay(); + } + this.minecraft.setScreen(this.screen); + }, Component.translatable("flashback.select_replay.delete_question"), + Component.translatable("selectWorld.deleteWarning", this.summary.getReplayName()), + Component.translatable("selectWorld.deleteButton"), + CommonComponents.GUI_CANCEL) + ); + } + + private void doDeleteReplay() { + String id = this.summary.getReplayId(); + try { + Files.delete(this.summary.getPath()); + } catch (IOException e) { + SystemToast.onWorldDeleteFailure(this.minecraft, id); + LOGGER.error("Failed to delete replay {}", id, e); + } + + ReplaySelectionList.this.reloadWorldList(); + } + + public void editReplay() { + SystemToast.add(this.minecraft.getToasts(), new SystemToast.SystemToastId(3000), + Component.literal("Sorry"), Component.literal("Editing replay data hasn't been implemented yet")); + // todo: +// EditWorldScreen editWorldScreen; +// ReplayStorageSource.ReplayStorageAccess levelStorageAccess; +// this.queueLoadScreen(); +// String string = this.summary.getReplayId(); +// try { +// levelStorageAccess = this.minecraft.getReplaySource().validateAndCreateAccess; +// } catch (IOException iOException) { +// SystemToast.onWorldAccessFailure(this.minecraft, string); +// LOGGER.error("Failed to access level {}", (Object)string, (Object)iOException); +// ReplaySelectionList.this.reloadWorldList(); +// return; +// } catch (ContentValidationException contentValidationException) { +// LOGGER.warn("{}", (Object)contentValidationException.getMessage()); +// this.minecraft.setScreen(NoticeWithLinkScreen.createWorldSymlinkWarningScreen(() -> this.minecraft.setScreen(this.screen))); +// return; +// } +// try { +// editWorldScreen = EditWorldScreen.create(this.minecraft, levelStorageAccess, bl -> { +// levelStorageAccess.safeClose(); +// if (bl) { +// ReplaySelectionList.this.reloadWorldList(); +// } +// this.minecraft.setScreen(this.screen); +// }); +// } catch (IOException | NbtException | ReportedNbtException exception) { +// levelStorageAccess.safeClose(); +// SystemToast.onWorldAccessFailure(this.minecraft, string); +// LOGGER.error("Failed to load world data {}", (Object)string, (Object)exception); +// ReplaySelectionList.this.reloadWorldList(); +// return; +// } +// this.minecraft.setScreen(editWorldScreen); + } + + private void loadIcon() { + byte[] iconBytes = this.summary.getIconBytes(); + + if (iconBytes != null) { + try { + this.icon.upload(NativeImage.read(iconBytes)); + return; + } catch (Throwable t) { + LOGGER.error("Invalid icon for replay {}", this.summary.getReplayId(), t); + } + } + + this.icon.clear(); + } + + @Override + public void close() { + this.icon.close(); + } + } + + public static abstract class Entry extends ObjectSelectionList.Entry implements AutoCloseable { + @Override + public void close() {} + } +} + diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java b/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java new file mode 100644 index 0000000..8dafb0c --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/ReplaySummary.java @@ -0,0 +1,100 @@ +/* + * Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4). + */ +package com.moulberry.flashback.screen; + +import com.moulberry.flashback.editor.ui.windows.TimelineWindow; +import com.moulberry.flashback.record.FlashbackMeta; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import org.jetbrains.annotations.Nullable; + +import java.nio.file.Path; + +public class ReplaySummary implements Comparable { + private final Path path; + private final FlashbackMeta metadata; + private final String replayId; + private final long lastOpened; + private final byte[] iconBytes; + private Component info = null; + + public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastOpened, @Nullable byte[] iconBytes) { + this.path = path; + this.metadata = metadata; + this.replayId = replayId; + this.lastOpened = lastOpened; + this.iconBytes = iconBytes; + } + + public Path getPath() { + return this.path; + } + + public String getReplayId() { + return this.replayId; + } + + public String getReplayName() { + return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name; + } + + public long getLastPlayed() { + return this.lastOpened; + } + + public Component getInfo() { + if (this.info == null) { + MutableComponent mutable = Component.empty(); + if (this.metadata.totalTicks > 0) { + int ticks = this.metadata.totalTicks; + int seconds = (ticks / 20) % 60; + int minutes = (ticks / 20 / 60) % 60; + int hours = ticks / 20 / 60 / 60; + + StringBuilder builder = new StringBuilder(); + if (hours > 0) { + builder.append(hours).append('h'); + } + if (minutes > 0) { + if (!builder.isEmpty()) { + builder.append(' '); + } + builder.append(minutes).append('m'); + } + if (seconds > 0) { + if (!builder.isEmpty()) { + builder.append(' '); + } + builder.append(seconds).append('s'); + } + + mutable.append(Component.translatable("flashback.select_replay.duration", builder)); + } + this.info = mutable; + } + + return this.info; + } + + public byte[] getIconBytes() { + return this.iconBytes; + } + + public boolean canOpen() { + return true; + } + + @Override + public int compareTo(ReplaySummary levelSummary) { + if (this.getLastPlayed() < levelSummary.getLastPlayed()) { + return 1; + } + if (this.getLastPlayed() > levelSummary.getLastPlayed()) { + return -1; + } + return this.replayId.compareTo(levelSummary.replayId); + } + +} + diff --git a/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java new file mode 100644 index 0000000..403d253 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/SelectReplayScreen.java @@ -0,0 +1,100 @@ +package com.moulberry.flashback.screen; + +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.Component; +import org.jetbrains.annotations.Nullable; + +public class SelectReplayScreen extends Screen { + + protected final Screen lastScreen; + private Button deleteButton; + private Button selectButton; + private Button editButton; + protected EditBox searchBox; + private ReplaySelectionList list; + + public SelectReplayScreen(Screen screen) { + super(Component.translatable("flashback.select_replay")); + this.lastScreen = screen; + } + + @Override + protected void init() { + 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.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()); + this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay) + .bounds(this.width / 2 - 150, this.height - 28, 146, 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()); + this.updateButtonStatus(null); + } + + @Override + protected void setInitialFocus() { + this.setInitialFocus(this.searchBox); + } + + @Override + public void onClose() { + this.minecraft.setScreen(this.lastScreen); + } + + @Override + public void render(GuiGraphics guiGraphics, int i, int j, float f) { + super.render(guiGraphics, i, j, f); + this.searchBox.render(guiGraphics, i, j, f); + guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, 8, 0xFFFFFF); + } + + public void updateButtonStatus(@Nullable ReplaySummary replaySummary) { + if (this.selectButton == null) { + return; + } + + if (replaySummary == null) { + this.selectButton.active = false; + this.editButton.active = false; + this.deleteButton.active = false; + } else { + this.selectButton.active = replaySummary.canOpen(); + this.editButton.active = true; + this.deleteButton.active = true; + } + } + + @Override + public void removed() { + if (this.list != null) { + this.list.children().forEach(ReplaySelectionList.Entry::close); + } + } + + private void tryOpenReplay(Button button) { + ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry(); + if (entry != null) { + entry.openReplay(); + } + } + + private void tryEditReplay(Button button) { + ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry(); + if (entry != null) { + entry.editReplay(); + } + } + + private void tryDeleteReplay(Button button) { + ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry(); + if (entry != null) { + entry.deleteReplay(); + } + } +} diff --git a/src/main/java/com/moulberry/flashback/serialization/QuaternionTypeAdapater.java b/src/main/java/com/moulberry/flashback/serialization/QuaternionTypeAdapater.java new file mode 100644 index 0000000..77c7811 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/serialization/QuaternionTypeAdapater.java @@ -0,0 +1,33 @@ +package com.moulberry.flashback.serialization; + +import com.google.gson.*; +import net.minecraft.world.phys.Vec3; +import org.joml.Quaternionf; + +import java.lang.reflect.Type; + +public class QuaternionTypeAdapater implements JsonSerializer, JsonDeserializer { + @Override + public Quaternionf deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonArray jsonArray = json.getAsJsonArray(); + if (jsonArray.size() != 4) { + throw new IllegalStateException("Error deserializing Quaternionf, expected array to have length 4, was length " + jsonArray.size() + " instead"); + } + double x = jsonArray.get(0).getAsDouble(); + double y = jsonArray.get(1).getAsDouble(); + double z = jsonArray.get(2).getAsDouble(); + double w = jsonArray.get(3).getAsDouble(); + return new Quaternionf(x, y, z, w); + } + + @Override + public JsonElement serialize(Quaternionf src, Type typeOfSrc, JsonSerializationContext context) { + JsonArray jsonArray = new JsonArray(); + jsonArray.add(src.x); + jsonArray.add(src.y); + jsonArray.add(src.z); + jsonArray.add(src.w); + return jsonArray; + } + +} diff --git a/src/main/java/com/moulberry/flashback/serialization/Vector3fTypeAdapater.java b/src/main/java/com/moulberry/flashback/serialization/Vector3fTypeAdapater.java new file mode 100644 index 0000000..9c25cbd --- /dev/null +++ b/src/main/java/com/moulberry/flashback/serialization/Vector3fTypeAdapater.java @@ -0,0 +1,32 @@ +package com.moulberry.flashback.serialization; + +import com.google.gson.*; +import net.minecraft.world.phys.Vec3; +import org.joml.Vector3f; + +import java.lang.reflect.Type; + +public class Vector3fTypeAdapater implements JsonSerializer, JsonDeserializer { + @Override + public Vector3f deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonArray jsonArray = json.getAsJsonArray(); + if (jsonArray.size() != 3) { + throw new IllegalStateException("Error deserializing Vector3f, expected array to have length 3, was length " + jsonArray.size() + " instead"); + } + float x = jsonArray.get(0).getAsFloat(); + float y = jsonArray.get(1).getAsFloat(); + float z = jsonArray.get(2).getAsFloat(); + + return new Vector3f(x, y, z); + } + + @Override + public JsonElement serialize(Vector3f src, Type typeOfSrc, JsonSerializationContext context) { + JsonArray jsonArray = new JsonArray(); + jsonArray.add(src.x); + jsonArray.add(src.y); + jsonArray.add(src.z); + return jsonArray; + } + +} diff --git a/src/client/java/com/moulberry/flashback/spline/CatmullRom.java b/src/main/java/com/moulberry/flashback/spline/CatmullRom.java similarity index 97% rename from src/client/java/com/moulberry/flashback/spline/CatmullRom.java rename to src/main/java/com/moulberry/flashback/spline/CatmullRom.java index cee394d..640dbae 100644 --- a/src/client/java/com/moulberry/flashback/spline/CatmullRom.java +++ b/src/main/java/com/moulberry/flashback/spline/CatmullRom.java @@ -18,6 +18,11 @@ public class CatmullRom { float tj2 = positionCentripetalTj(p1, p2); float tj3 = positionCentripetalTj(p2, p3); float averageTj = (tj1 + tj2 + tj3) / 3f; + + if (averageTj == 0.0) { + return new Vector3f(p1); + } + float averageTime = time3 / 3f; float relation = averageTime / averageTj; @@ -107,6 +112,11 @@ public class CatmullRom { float tj2 = rotationCentripetalTj(p1, p2); float tj3 = rotationCentripetalTj(p2, p3); float averageTj = (tj1 + tj2 + tj3) / 3f; + + if (averageTj == 0.0) { + return new Quaternionf(p1); + } + float averageTime = time3 / 3f; float relation = averageTime / averageTj; @@ -189,6 +199,11 @@ public class CatmullRom { float tj2 = valueCentripetalTj(p1, p2); float tj3 = valueCentripetalTj(p2, p3); float averageTj = (tj1 + tj2 + tj3) / 3f; + + if (averageTj == 0.0) { + return p1; + } + float averageTime = time3 / 3f; float relation = averageTime / averageTj; diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java new file mode 100644 index 0000000..156ed5b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -0,0 +1,112 @@ +package com.moulberry.flashback.state; + +import com.google.gson.*; +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 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.*; + +public class EditorState { + + public transient boolean dirty = false; + + public final List keyframeTracks = new ArrayList<>(); + + public float zoomMin = 0.0f; + public float zoomMax = 1.0f; + public int exportStartTicks = -1; + public int exportEndTicks = -1; + + public void setExportTicks(int start, int end, int totalTicks) { + if (this.exportEndTicks < 0) { + this.exportEndTicks = totalTicks; + } + this.exportStartTicks = Math.max(0, Math.min(totalTicks, this.exportStartTicks)); + this.exportEndTicks = Math.max(0, Math.min(totalTicks, this.exportEndTicks)); + + if (start >= 0) { + this.exportStartTicks = start; + if (this.exportEndTicks < start) { + this.exportEndTicks = start; + } + } + + if (end >= 0) { + this.exportEndTicks = end; + if (this.exportStartTicks > end) { + this.exportStartTicks = end; + } + } + + if (this.exportStartTicks == 0 && this.exportEndTicks == totalTicks) { + this.exportStartTicks = -1; + this.exportEndTicks = -1; + } + + this.dirty = true; + } + + public void save(Path path) { + this.dirty = false; + + String serialized = FlashbackGson.PRETTY.toJson(this, EditorState.class); + + try { + Files.createDirectories(path.getParent()); + Files.writeString(path, serialized, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE, + StandardOpenOption.SYNC); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Nullable + public static EditorState load(Path path) { + if (!Files.exists(path)) { + return null; + } + + try { + String serialized = Files.readString(path); + return FlashbackGson.PRETTY.fromJson(serialized, EditorState.class); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public void applyKeyframes(T t, float tick) { + EnumSet applied = EnumSet.noneOf(KeyframeType.class); + for (KeyframeTrack keyframeTrack : this.keyframeTracks) { + // Ignore lines that are disabled + if (!keyframeTrack.enabled) { + continue; + } + + // Already applied a keyframe of this type earlier, skip + if (applied.contains(keyframeTrack.keyframeType)) { + continue; + } + + // Try to apply keyframes, mark applied if successful + if (keyframeTrack.tryApplyKeyframes(t, tick)) { + applied.add(keyframeTrack.keyframeType); + } + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/state/EditorStateCache.java b/src/main/java/com/moulberry/flashback/state/EditorStateCache.java new file mode 100644 index 0000000..41f3970 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/EditorStateCache.java @@ -0,0 +1,141 @@ +package com.moulberry.flashback.state; + +import com.moulberry.flashback.Flashback; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantLock; + +public class EditorStateCache { + + private static long AUTOSAVE_INTERVAL_MILLIS = 30 * 1000; // 30 seconds + + private static final ReentrantLock lock = new ReentrantLock(); + private static UUID currentUuid = null; + private static EditorState current = null; + private static long lastSave = 0; + + public static void saveIfNeeded() { + try { + lock.lock(); + + if (current == null || currentUuid == null) { + return; + } + + long currentTime = System.currentTimeMillis(); + + if (!current.dirty) { + lastSave = currentTime; + } else if (currentTime < lastSave || currentTime - lastSave > AUTOSAVE_INTERVAL_MILLIS) { + save(); + } + } finally { + lock.unlock(); + } + + } + + private static void save() { + if (current == null || currentUuid == null) { + return; + } + + Path normalPath = getPath(currentUuid, false); + Path oldPath = getPath(currentUuid, true); + + // Backup + if (Files.exists(normalPath)) { + try { + Files.move(normalPath, oldPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ignored) {} + } + + // Save + current.save(normalPath); + lastSave = System.currentTimeMillis(); + } + + private static void load() { + lastSave = System.currentTimeMillis(); + + Path normalPath = getPath(currentUuid, false); + Path backupPath = getPath(currentUuid, true); + + if (Files.exists(normalPath)) { + current = EditorState.load(normalPath); + if (current == null) { + try { + Files.deleteIfExists(normalPath); + } catch (IOException ignored) {} + } else { + return; + } + } + + if (Files.exists(backupPath)) { + current = EditorState.load(backupPath); + if (current == null) { + try { + Files.deleteIfExists(backupPath); + } catch (IOException ignored) {} + } else { + return; + } + } + + current = new EditorState(); + } + + public static void reset() { + try { + lock.lock(); + + save(); + current = null; + currentUuid = null; + } finally { + lock.unlock(); + } + } + + @Nullable + public static EditorState getCurrent() { + return current; + } + + public static EditorState get(UUID replayUuid) { + Objects.requireNonNull(replayUuid); + try { + lock.lock(); + + if (current == null || !Objects.equals(currentUuid, replayUuid)) { + save(); + currentUuid = replayUuid; + load(); + } + + return current; + } finally { + lock.unlock(); + } + } + + private static Path getPath(UUID replayUuid, boolean old) { + Objects.requireNonNull(replayUuid); + + String filename = replayUuid + ".json"; + if (old) { + filename += ".old"; + } + return Flashback.getConfigDirectory() + .resolve("replay_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 new file mode 100644 index 0000000..a881a4d --- /dev/null +++ b/src/main/java/com/moulberry/flashback/state/KeyframeTrack.java @@ -0,0 +1,102 @@ +package com.moulberry.flashback.state; + +import com.moulberry.flashback.keyframe.Keyframe; +import com.moulberry.flashback.keyframe.KeyframeType; +import com.moulberry.flashback.keyframe.interpolation.SidedInterpolationType; + +import java.util.Map; +import java.util.TreeMap; + +public class KeyframeTrack { + + public final KeyframeType keyframeType; + 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) { + // Skip if empty + TreeMap> keyframeTimes = this.keyframesByTick; + if (keyframeTimes.isEmpty()) { + return false; + } + + Map.Entry> lowerEntry = keyframeTimes.floorEntry((int) tick); + if (lowerEntry == null) { + return false; + } + + if (lowerEntry.getValue().operandClass != t.getClass()) { + return false; + } + + Keyframe lowerKeyframe = (Keyframe) lowerEntry.getValue(); + + SidedInterpolationType leftInterpolation = lowerEntry.getValue().interpolationType().rightSide; + + // Immediately apply hold + if (leftInterpolation == SidedInterpolationType.HOLD) { + lowerKeyframe.apply(t); + return true; + } + + // Get next entry, skip if tick is not between two keyframes + Map.Entry> ceilEntry = keyframeTimes.ceilingEntry(lowerEntry.getKey() + 1); + if (ceilEntry == null) { + return false; + } + + SidedInterpolationType rightInterpolation = ceilEntry.getValue().interpolationType().leftSide; + if (rightInterpolation == SidedInterpolationType.HOLD) { + rightInterpolation = leftInterpolation; + } + + float amount = (tick - lowerEntry.getKey()) / (ceilEntry.getKey() - lowerEntry.getKey()); + + boolean isUsingSmooth = leftInterpolation == SidedInterpolationType.SMOOTH || + rightInterpolation == SidedInterpolationType.SMOOTH; + + if (isUsingSmooth) { + Map.Entry> beforeEntry = keyframeTimes.floorEntry(lowerEntry.getKey() - 1); + if (beforeEntry == null) { + beforeEntry = lowerEntry; + } + + Map.Entry> afterAfterEntry = keyframeTimes.ceilingEntry(ceilEntry.getKey() + 1); + if (afterAfterEntry == null) { + afterAfterEntry = ceilEntry; + } + + float lerpAmount; + boolean lerpFromRight; + if (leftInterpolation != SidedInterpolationType.SMOOTH) { + lerpAmount = SidedInterpolationType.interpolate(leftInterpolation, leftInterpolation, amount); + lerpFromRight = false; + } else if (rightInterpolation != SidedInterpolationType.SMOOTH) { + lerpAmount = SidedInterpolationType.interpolate(rightInterpolation, rightInterpolation, amount); + lerpFromRight = true; + } else { + lerpAmount = -1; + lerpFromRight = false; + } + + ((Keyframe)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); + + if (amount == 0.0) { + lowerKeyframe.apply(t); + } else { + lowerKeyframe.applyInterpolated(t, ceilEntry.getValue(), amount); + } + } + + return true; + } + +} diff --git a/src/client/resources/assets/flashback/heebo-medium.ttf b/src/main/resources/assets/flashback/heebo-medium.ttf similarity index 100% rename from src/client/resources/assets/flashback/heebo-medium.ttf rename to src/main/resources/assets/flashback/heebo-medium.ttf diff --git a/src/client/resources/assets/flashback/inter-medium.ttf b/src/main/resources/assets/flashback/inter-medium.ttf similarity index 100% rename from src/client/resources/assets/flashback/inter-medium.ttf rename to src/main/resources/assets/flashback/inter-medium.ttf diff --git a/src/main/resources/assets/flashback/lang/en_us.json b/src/main/resources/assets/flashback/lang/en_us.json new file mode 100644 index 0000000..f15d95d --- /dev/null +++ b/src/main/resources/assets/flashback/lang/en_us.json @@ -0,0 +1,16 @@ +{ + "flashback.select_replay": "Select Replay", + "flashback.select_replay.open": "Open Replay", + "flashback.select_replay.loading_replays": "Loading Replays", + "flashback.select_replay.replay": "Replay", + "flashback.select_replay.data_read": "Reading replay data...", + "flashback.select_replay.delete_question": "Are you sure you want to delete this replay?", + "flashback.select_replay.duration": "Duration: %s", + + "flashback.option.automatically_start": "Automatically Start", + "flashback.option.automatically_start.description": "Automatically starts a replay recording when joining a world/server", + "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 diff --git a/src/client/resources/assets/flashback/notosansjp-medium.ttf b/src/main/resources/assets/flashback/notosansjp-medium.ttf similarity index 100% rename from src/client/resources/assets/flashback/notosansjp-medium.ttf rename to src/main/resources/assets/flashback/notosansjp-medium.ttf diff --git a/src/client/resources/assets/flashback/notosanssc-medium.otf b/src/main/resources/assets/flashback/notosanssc-medium.otf similarity index 100% rename from src/client/resources/assets/flashback/notosanssc-medium.otf rename to src/main/resources/assets/flashback/notosanssc-medium.otf diff --git a/src/client/resources/assets/flashback/notosanstc-medium.otf b/src/main/resources/assets/flashback/notosanstc-medium.otf similarity index 100% rename from src/client/resources/assets/flashback/notosanstc-medium.otf rename to src/main/resources/assets/flashback/notosanstc-medium.otf diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 63e10ea..9107920 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -3,7 +3,7 @@ "id": "flashback", "version": "${version}", "name": "Flashback", - "description": "Record and replay the game", + "description": "Record your gameplay, view the recordings and export cinematic shots", "authors": [ "Moulberry" ], @@ -13,22 +13,28 @@ }, "license": "ARR", "icon": "assets/flashback/icon.png", - "environment": "*", + "environment": "client", "entrypoints": { + "main": [ + "com.moulberry.flashback.Flashback" + ], "client": [ - "com.moulberry.flashback.FlashbackClient" + "com.moulberry.flashback.Flashback" + ], + "frex_flawless_frames": [ + "com.moulberry.flashback.exporting.FrexFlawlessFramesIntegration" + ], + "modmenu": [ + "com.moulberry.flashback.FlashbackModMenuApiImpl" ] }, + "accessWidener": "flashback.accesswidener", "mixins": [ - "flashback.mixins.json", - { - "config": "flashback.client.mixins.json", - "environment": "client" - } + "flashback.mixins.json" ], "depends": { "fabricloader": ">=0.15.10", - "minecraft": "~1.20.6", + "minecraft": "~1.21", "java": ">=21", "fabric-api": "*" } diff --git a/src/main/resources/flashback.accesswidener b/src/main/resources/flashback.accesswidener index 981b111..209a6fc 100644 --- a/src/main/resources/flashback.accesswidener +++ b/src/main/resources/flashback.accesswidener @@ -28,6 +28,9 @@ accessible field net/minecraft/client/gui/components/PlayerTabOverlay footer Lne accessible field net/minecraft/client/multiplayer/MultiPlayerGameMode destroyBlockPos Lnet/minecraft/core/BlockPos; +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; + # Entity accessible field net/minecraft/network/syncher/SynchedEntityData itemsById [Lnet/minecraft/network/syncher/SynchedEntityData$DataItem; @@ -61,7 +64,11 @@ accessible class net/minecraft/world/level/chunk/PalettedContainer$Data accessible method net/minecraft/server/MinecraftServer haveTime ()Z extendable method net/minecraft/server/MinecraftServer haveTime ()Z +accessible method net/minecraft/server/MinecraftServer synchronizeTime (Lnet/minecraft/server/level/ServerLevel;)V +extendable method net/minecraft/server/MinecraftServer synchronizeTime (Lnet/minecraft/server/level/ServerLevel;)V + accessible class net/minecraft/server/level/ThreadedLevelLightEngine$TaskType +accessible field net/minecraft/server/network/PlayerChunkSender pendingChunks Lit/unimi/dsi/fastutil/longs/LongSet; # Packets accessible field net/minecraft/network/protocol/game/ClientboundPlayerInfoUpdatePacket entries Ljava/util/List; @@ -74,11 +81,39 @@ mutable field net/minecraft/network/protocol/game/ClientboundAddEntityPacket dat accessible field net/minecraft/network/protocol/game/ClientboundAddEntityPacket id I mutable field net/minecraft/network/protocol/game/ClientboundAddEntityPacket id I +accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData blockEntitiesData Ljava/util/List; +accessible class net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData$BlockEntityInfo +accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData$BlockEntityInfo packedXZ I +accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData$BlockEntityInfo y I +accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData$BlockEntityInfo type Lnet/minecraft/world/level/block/entity/BlockEntityType; +accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData$BlockEntityInfo tag Lnet/minecraft/nbt/CompoundTag; +accessible field net/minecraft/network/protocol/game/ClientboundLevelChunkPacketData buffer [B + # 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; accessible method net/minecraft/client/particle/ParticleEngine clearParticles ()V +accessible field com/mojang/blaze3d/platform/Window width I +accessible field com/mojang/blaze3d/platform/Window height I + # Exporting accessible field net/minecraft/client/Minecraft clientTickCount J -accessible field net/minecraft/client/Minecraft timer Lnet/minecraft/client/Timer; +accessible field net/minecraft/client/Minecraft timer Lnet/minecraft/client/DeltaTracker$Timer; +accessible field net/minecraft/client/DeltaTracker$Timer deltaTicks F +accessible field net/minecraft/client/DeltaTracker$Timer realtimeDeltaTicks F +accessible field net/minecraft/client/DeltaTracker$Timer deltaTickResidual F +accessible field net/minecraft/client/DeltaTracker$Timer pausedDeltaTickResidual F +accessible field com/mojang/blaze3d/platform/NativeImage pixels J +accessible field com/mojang/blaze3d/platform/NativeImage size J +accessible method net/minecraft/client/player/AbstractClientPlayer getPlayerInfo ()Lnet/minecraft/client/multiplayer/PlayerInfo; +accessible field net/minecraft/client/renderer/LevelRenderer visibleSections Lit/unimi/dsi/fastutil/objects/ObjectArrayList; +accessible field net/minecraft/client/renderer/LevelRenderer sectionOcclusionGraph Lnet/minecraft/client/renderer/SectionOcclusionGraph; +accessible field net/minecraft/client/renderer/SectionOcclusionGraph fullUpdateTask Ljava/util/concurrent/Future; +accessible field net/minecraft/client/renderer/SectionOcclusionGraph needsFullUpdate Z +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 diff --git a/src/main/resources/flashback.mixins.json b/src/main/resources/flashback.mixins.json index 924dba8..ae85f66 100644 --- a/src/main/resources/flashback.mixins.json +++ b/src/main/resources/flashback.mixins.json @@ -1,10 +1,54 @@ { - "required": true, - "package": "com.moulberry.flashback.mixin", - "compatibilityLevel": "JAVA_21", - "mixins": [ - ], - "injectors": { - "defaultRequire": 1 - } + "required": true, + "package": "com.moulberry.flashback.mixin", + "compatibilityLevel": "JAVA_21", + "client": [ + "MixinDebugScreenOverlay", + "MixinLevelRenderer", + "MixinMinecraft", + "MixinMouseHandler", + "MixinRenderTarget", + "MixinWindow", + "packet_fix.MixinBossHealthOverlay", + "playback.MixinArmorStandRenderer", + "playback.MixinClientCommonPacketListenerImpl", + "playback.MixinGameRenderer", + "playback.MixinItemInHandRenderer", + "record.MixinClientConfigurationPacketListenerImpl", + "ui.MixinPauseScreen", + "ui.MixinTitleScreen", + "visuals.MixinBossHealthOverlay", + "visuals.MixinClientLevelData", + "visuals.MixinEntityRenderDispatcher", + "visuals.MixinFogRenderer", + "visuals.MixinGui", + "visuals.MixinLoadingOverlay", + "visuals.MixinOptions" + ], + "injectors": { + "defaultRequire": 1 + }, + "mixins": [ + "MixinThreadedLevelLightEngine", + "compat.MixinAxiomEditorUI", + "compat.MixinSodiumWorldRenderer", + "playback.MixinEntity", + "playback.MixinLevelChunkSection", + "playback.MixinLivingEntity", + "playback.MixinPlayerChunkSender", + "playback.MixinScoreboard", + "playback.MixinTickRateManager", + "record.MixinConnection", + "record.MixinFFmpegFrameRecorder", + "replay_server.MixinChunkGenerators", + "replay_server.MixinChunkStatusTasks", + "replay_server.MixinPersistentEntitySectionManager", + "replay_server.MixinPlayerList", + "replay_server.MixinServerChunkCache", + "replay_server.MixinServerConfigurationPacketListenerImpl", + "replay_server.MixinServerEntity", + "replay_server.MixinServerGamePacketListenerImpl", + "replay_server.MixinServerLoginPacketListenerImpl", + "replay_server.MixinTickRateManager" + ] }