diff --git a/build.gradle b/build.gradle index dd97cef..4ad0cb9 100644 --- a/build.gradle +++ b/build.gradle @@ -69,6 +69,7 @@ dependencies { modCompileOnly("maven.modrinth:bobby:2cuVyTav") modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I") modCompileOnly("maven.modrinth:replaymod:NtlpUQgI") + modCompileOnly("maven.modrinth:distanthorizons:pEvLEY5E") modImplementation("maven.modrinth:modmenu:xhN1IvHi") // modCompileOnly("maven.modrinth:axiom:D3uDJmiB") diff --git a/gradle.properties b/gradle.properties index f7bbd71..7b15a47 100644 --- a/gradle.properties +++ b/gradle.properties @@ -9,7 +9,7 @@ yarn_mappings=1.21+build.9 loader_version=0.15.11 # Mod Properties -mod_version=0.5.0 +mod_version=0.7.0 maven_group=com.moulberry.flashback archives_base_name=flashback diff --git a/src/main/java/com/moulberry/flashback/Flashback.java b/src/main/java/com/moulberry/flashback/Flashback.java index 5f1adae..c15c6f6 100644 --- a/src/main/java/com/moulberry/flashback/Flashback.java +++ b/src/main/java/com/moulberry/flashback/Flashback.java @@ -38,8 +38,11 @@ import com.moulberry.flashback.record.Recorder; import com.moulberry.flashback.record.ReplayExporter; import com.moulberry.flashback.record.ReplayMarker; import com.moulberry.flashback.screen.ConfigScreen; +import com.moulberry.flashback.screen.RecoverRecordingsScreen; import com.moulberry.flashback.screen.SaveReplayScreen; import com.moulberry.flashback.screen.UnsupportedLoaderScreen; +import com.moulberry.flashback.state.EditorState; +import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.ShaderManager; import net.fabricmc.api.ClientModInitializer; @@ -53,6 +56,7 @@ import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.fabric.api.resource.ResourceManagerHelper; import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.ChatFormatting; import net.minecraft.FileUtil; import net.minecraft.Util; import net.minecraft.client.Minecraft; @@ -104,6 +108,7 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -121,8 +126,10 @@ public class Flashback implements ModInitializer, ClientModInitializer { private static int delayedStartRecording = 0; private static boolean delayedOpenConfig = false; + private static volatile boolean isInReplay = false; private static final List pendingReplaySave = new ArrayList<>(); + private static final List pendingReplayRecovery = new ArrayList<>(); public static ResourceLocation createResourceLocation(String value) { return ResourceLocation.fromNamespaceAndPath("flashback", value); @@ -176,8 +183,29 @@ public class Flashback implements ModInitializer, ClientModInitializer { config = FlashbackConfig.tryLoadFromFolder(configFolder); - // todo: try recover unfinished recordings - TempFolderProvider.tryDeleteStaleFolders(); + TempFolderProvider.tryDeleteStaleFolders(TempFolderProvider.TempFolderType.SERVER); + + Path recordingFolder = TempFolderProvider.getTypedTempFolder(TempFolderProvider.TempFolderType.RECORDING); + if (Files.exists(recordingFolder)) { + try (DirectoryStream directoryStream = Files.newDirectoryStream(recordingFolder)) { + Iterator iterator = directoryStream.iterator(); + while (iterator.hasNext()) { + Path folder = iterator.next(); + + if (Files.exists(folder.resolve("metadata.json"))) { + pendingReplayRecovery.add(folder); + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + if (pendingReplayRecovery.isEmpty()) { + TempFolderProvider.tryDeleteStaleFolders(TempFolderProvider.TempFolderType.RECORDING); + } + + // Delete partial exports try { FileUtils.deleteDirectory(Path.of("replay_export_temp").toFile()); } catch (Exception ignored) {} @@ -320,7 +348,16 @@ public class Flashback implements ModInitializer, ClientModInitializer { String unsupportedLoader = findUnsupportedLoaders(); ClientTickEvents.END_CLIENT_TICK.register(minecraft -> { + updateIsInReplay(); + AccurateEntityPositionHandler.tick(); + + if (Flashback.isInReplay() && !Flashback.isExporting()) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null) { + editorState.recordCameraMovement(); + } + } }); ClientTickEvents.START_CLIENT_TICK.register(minecraft -> { @@ -341,6 +378,30 @@ public class Flashback implements ModInitializer, ClientModInitializer { Component.literal("Flashback: Unsupported"), Component.literal(warning))); } + if (!pendingReplayRecovery.isEmpty() && canReplaceScreen(Minecraft.getInstance().screen)) { + Component title = Component.literal("Flashback: Recovery"); + Component description = Component.empty() + .append(Component.literal("Flashback has detected ").append(Component.literal("unfinished recordings\n").withStyle(ChatFormatting.YELLOW))) + .append(Component.literal("This is usually because the game closed unexpectedly while recording\n\n")) + .append(Component.literal("Unfortunately, up to 5 minutes of gameplay from the end of the recording may be lost\n\n").withStyle(ChatFormatting.RED) + .append(Component.literal("Would you like to try to recover the recording?").withStyle(ChatFormatting.GREEN))); + Minecraft.getInstance().setScreen(new RecoverRecordingsScreen(Minecraft.getInstance().screen, title, description, recover -> { + switch (recover) { + case RECOVER -> { + pendingReplaySave.addAll(pendingReplayRecovery); + pendingReplayRecovery.clear(); + } + case SKIP -> { + pendingReplayRecovery.clear(); + } + case DELETE -> { + TempFolderProvider.tryDeleteStaleFolders(TempFolderProvider.TempFolderType.RECORDING); + pendingReplayRecovery.clear(); + } + } + })); + } + if (!pendingReplaySave.isEmpty()) { Screen currentScreen = Minecraft.getInstance().screen; if (canReplaceScreen(currentScreen)) { @@ -373,9 +434,19 @@ public class Flashback implements ModInitializer, ClientModInitializer { } delayedOpenConfig = false; } + + updateIsInReplay(); }); } + public static List getReplayIncompatibleMods() { + List incompatible = new ArrayList<>(); + if (FabricLoader.getInstance().isModLoaded("vmp")) { + incompatible.add("VeryManyPlayers (vmp)"); + } + return incompatible; + } + private static @Nullable String findUnsupportedLoaders() { if (FabricLoader.getInstance().isModLoaded("feather")) { return "Feather Client"; @@ -521,8 +592,12 @@ public class Flashback implements ModInitializer, ClientModInitializer { return EXPORT_JOB != null && EXPORT_JOB.isRunning(); } + public static void updateIsInReplay() { + isInReplay = Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer; + } + public static boolean isInReplay() { - return Minecraft.getInstance().getSingleplayerServer() instanceof ReplayServer; + return isInReplay; } private int startRecordingReplay(CommandContext command) { @@ -637,7 +712,7 @@ public class Flashback implements ModInitializer, ClientModInitializer { LevelStorageSource source = new LevelStorageSource(replayTemp.resolve("saves"), replayTemp.resolve("backups"), Minecraft.getInstance().directoryValidator(), Minecraft.getInstance().getFixerUpper()); LevelStorageSource.LevelStorageAccess access = source.createAccess("replay"); - PackRepository packRepository = ServerPacksSource.createVanillaTrustedRepository(); + PackRepository packRepository = ServerPacksSource.createPackRepository(access); packRepository.reload(); diff --git a/src/main/java/com/moulberry/flashback/TempFolderProvider.java b/src/main/java/com/moulberry/flashback/TempFolderProvider.java index f756aab..d5c26f1 100644 --- a/src/main/java/com/moulberry/flashback/TempFolderProvider.java +++ b/src/main/java/com/moulberry/flashback/TempFolderProvider.java @@ -28,62 +28,60 @@ public class TempFolderProvider { return Flashback.getDataDirectory().resolve("temp"); } - public static void tryDeleteStaleFolders() { + public static Path getTypedTempFolder(TempFolderType type) { + return getSharedTempFolder().resolve(type.id); + } + + public static void tryDeleteStaleFolders(TempFolderType type) { 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); + Path typedTempFolder = tempFolder.resolve(type.id); + if (!Files.exists(typedTempFolder)) { + return; } + 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); } diff --git a/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java b/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java index e0196f4..51d6b6c 100644 --- a/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java +++ b/src/main/java/com/moulberry/flashback/action/PositionAndAngle.java @@ -9,8 +9,8 @@ public record PositionAndAngle(double x, double y, double z, float yaw, float pi this.x + (other.x - this.x) * amount, this.y + (other.y - this.y) * amount, this.z + (other.z - this.z) * amount, - (float) (this.yaw + Mth.wrapDegrees(other.yaw - this.yaw) * amount), - (float) (this.pitch + Mth.wrapDegrees(other.pitch - this.pitch) * amount) + (float) Mth.wrapDegrees(this.yaw + Mth.wrapDegrees(other.yaw - this.yaw) * amount), + (float) Mth.wrapDegrees(this.pitch + Mth.wrapDegrees(other.pitch - this.pitch) * amount) ); } } diff --git a/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java index 601ef6d..41d1672 100644 --- a/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java +++ b/src/main/java/com/moulberry/flashback/combo_options/VideoCodec.java @@ -94,7 +94,7 @@ public enum VideoCodec implements ComboOption { break; } else { if (PixelFormatHelper.doesPixelFormatSupportTransparency(pixFmt)) { - System.out.println(name + " supports transparency because of " + PixelFormatHelper.pixelFormatToString(pixFmt)); + // System.out.println(name + " supports transparency because of " + PixelFormatHelper.pixelFormatToString(pixFmt)); this.supportsTransparency = true; break; } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java index ebc101e..f737528 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/CustomImGuiImplGlfw.java @@ -130,6 +130,9 @@ public class CustomImGuiImplGlfw { private int grabLinkedKey = -1; private boolean releaseGrabOnUp = false; + public double rawMouseX; + public double rawMouseY; + public float contentScale = 1.0f; public enum MouseHandledBy { @@ -391,6 +394,9 @@ public class CustomImGuiImplGlfw { public void cursorPosCallback(final long windowId, final double xpos, final double ypos) { if (AsyncFileDialogs.hasDialog()) return; + this.rawMouseX = xpos; + this.rawMouseY = ypos; + if (!ReplayUI.isActive()) { if (this.prevUserCallbackCursorPos != null && windowId == this.mainWindowPtr) this.prevUserCallbackCursorPos.invoke(windowId, xpos, ypos); return; diff --git a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java index 56fe420..7586ec6 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/ReplayUI.java @@ -94,6 +94,7 @@ public class ReplayUI { private static String infoOverlayText = null; private static long infoOverlayEndMillis = 0; + public static boolean recordCameraMovement = false; private static UUID selectedEntity = null; private static boolean openSelectedEntityPopup = false; @@ -605,29 +606,40 @@ public class ReplayUI { isFrameFocused = true; } + String showText = null; + int showTextBorderColour = -1; + if (infoOverlayText != null) { long currentMillis = System.currentTimeMillis(); if (currentMillis < infoOverlayEndMillis - 30000 || currentMillis > infoOverlayEndMillis) { infoOverlayText = null; infoOverlayEndMillis = 0; } else { - ImGui.setNextWindowPos(frameX + frameWidth*0.5f, frameY + frameHeight*0.75f, ImGuiCond.Always, 0.5f, 0.5f); - ImGui.setNextWindowSizeConstraints(0, 0, 550, frameHeight*0.45f); - - 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(); + showText = infoOverlayText; + showTextBorderColour = 0xFF00FFFF; } + } else if (recordCameraMovement) { + showText = "Recording Movement as Keyframes..."; + showTextBorderColour = 0xFF0000FF; + } + + if (showText != null) { + 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, showTextBorderColour); + + if (ImGui.begin("##InfoOverlay", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing | + ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse | + ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoSavedSettings)) { + + ImGui.text(showText); + } + ImGui.end(); + + ImGuiHelper.popStyleColor(); + ImGuiHelper.popStyleVar(); } if (sizing == Sizing.UNDERLAY) { @@ -637,10 +649,6 @@ public class ReplayUI { frameHeight = Minecraft.getInstance().getWindow().getScreenHeight(); } - if (frameX != oldFrameX || frameY != oldFrameY || frameWidth != oldFrameWidth || frameHeight != oldFrameHeight) { - Minecraft.getInstance().resizeDisplay(); - } - if (Minecraft.getInstance().screen == null && Minecraft.getInstance().getOverlay() == null) { if (editorState != null && editorState.replayVisuals.ruleOfThirdsGuide) { ImDrawList drawList = ImGui.getBackgroundDrawList(); @@ -744,6 +752,10 @@ public class ReplayUI { imguiGl3.renderDrawData(drawData); } + if (frameX != oldFrameX || frameY != oldFrameY || frameWidth != oldFrameWidth || frameHeight != oldFrameHeight) { + Minecraft.getInstance().resizeDisplay(); + } + transitionActiveState(true); } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java index 7612f97..7557412 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/MovementWindow.java @@ -4,6 +4,7 @@ import com.mojang.authlib.GameProfile; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.configuration.FlashbackConfig; import com.moulberry.flashback.editor.ui.ImGuiHelper; +import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.editor.ui.WindowOpenState; import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorStateManager; @@ -87,6 +88,11 @@ public class MovementWindow { config.saveToDefaultFolder(); } + // todo: record movement: can we make this smoother? +// if (ImGui.checkbox("Record Movement as Keyframes", ReplayUI.recordCameraMovement)) { +// ReplayUI.recordCameraMovement = !ReplayUI.recordCameraMovement; +// } + } ImGui.end(); } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java index 40a2b53..412eff5 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/StartExportWindow.java @@ -44,6 +44,7 @@ public class StartExportWindow { private static final float[] framerate = new float[]{60}; private static boolean resetRng = false; private static boolean ssaa = false; + private static boolean noGui = false; private static VideoContainer[] supportedContainers = null; private static VideoContainer[] supportedContainersWithTransparency = null; @@ -173,6 +174,13 @@ public class StartExportWindow { } ImGuiHelper.tooltip("Supersampling Anti-Aliasing: Remove jagged edges by rendering the game at double resolution and downscaling"); + ImGui.sameLine(); + + if (ImGui.checkbox("No GUI", noGui)) { + noGui = !noGui; + } + ImGuiHelper.tooltip("Removes all UI from the screen, rendering only the world"); + ImGuiHelper.separatorWithText("Video Options"); renderVideoOptions(editorState); @@ -257,8 +265,12 @@ public class StartExportWindow { } private static void renderVideoOptions(EditorState editorState) { - if (editorState != null && !editorState.replayVisuals.renderSky && ImGui.checkbox("Transparent Sky", transparentBackground)) { - transparentBackground = !transparentBackground; + if (editorState != null && !editorState.replayVisuals.renderSky) { + if (ImGui.checkbox("Transparent Sky", transparentBackground)) { + transparentBackground = !transparentBackground; + } + } else { + transparentBackground = false; } VideoContainer[] containers; @@ -402,7 +414,7 @@ public class StartExportWindow { return new ExportSettings(name, editorState.copy(), player.position(), player.getYRot(), player.getXRot(), resolution[0], resolution[1], start, end, - Math.max(1, framerate[0]), resetRng, container, useVideoCodec, encoder, numBitrate, transparent, ssaa, + Math.max(1, framerate[0]), resetRng, container, useVideoCodec, encoder, numBitrate, transparent, ssaa, noGui, shouldRecordAudio, stereoAudio, useAudioCodec, path); } diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java index b0b6a08..559d3b5 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/TimelineWindow.java @@ -10,6 +10,7 @@ import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.KeyframeRegistry; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; +import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType; import com.moulberry.flashback.record.ReplayMarker; import com.moulberry.flashback.state.EditorStateHistoryAction; @@ -67,6 +68,7 @@ public class TimelineWindow { private static Vector2f dragSelectOrigin = null; private static KeyframeType.KeyframeCreatePopup createKeyframeWithPopup = null; + private static int createKeyframeWithPopupTick = 0; private static float mouseX; private static float mouseY; @@ -105,6 +107,10 @@ public class TimelineWindow { private static int editingKeyframeTrack = 0; private static int editingKeyframeTick = 0; + private static int createKeyframeAtTick = 0; + private static int openCreateKeyframeAtTickTrack = -1; + + 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; @@ -523,7 +529,7 @@ public class TimelineWindow { boolean pressedDelete = ImGui.isKeyPressed(GLFW.GLFW_KEY_DELETE, false) || ImGui.isKeyPressed(GLFW.GLFW_KEY_BACKSPACE, false); if (ImGui.isKeyPressed(GLFW.GLFW_KEY_SPACE, false)) { - replayServer.replayPaused = !replayServer.replayPaused; + togglePaused(replayServer, editorState); } if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT, false)) { pendingStepBackwardsTicks += 1; @@ -720,13 +726,7 @@ public class TimelineWindow { // Pause button if (hoveredPause) { - replayServer.replayPaused = !replayServer.replayPaused; - if (!replayServer.replayPaused) { - Screen screen = Minecraft.getInstance().screen; - if (screen != null && screen.isPauseScreen()) { - Minecraft.getInstance().setScreen(null); - } - } + togglePaused(replayServer, editorState); return; } @@ -870,6 +870,9 @@ public class TimelineWindow { } return; + } else if (rightClicked) { + createKeyframeAtTick = tick; + openCreateKeyframeAtTickTrack = trackIndex; } } @@ -877,6 +880,31 @@ public class TimelineWindow { } } + private static void togglePaused(ReplayServer replayServer, EditorState editorState) { + if (replayServer.getReplayTick() >= replayServer.getTotalReplayTicks()) { + replayServer.jumpToTick = 0; + } + replayServer.replayPaused = !replayServer.replayPaused; + if (!replayServer.replayPaused) { + Screen screen = Minecraft.getInstance().screen; + if (screen != null && screen.isPauseScreen()) { + Minecraft.getInstance().setScreen(null); + } + + if (ReplayUI.recordCameraMovement) { + editorState.recordingCameraMovementTrack = -1; + + for (int i = 0; i < editorState.keyframeTracks.size(); i++) { + KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i); + if (keyframeTrack.enabled && keyframeTrack.keyframeType == CameraKeyframeType.INSTANCE) { + editorState.recordingCameraMovementTrack = i; + break; + } + } + } + } + } + private static void renderExportBar(EditorState editorState, ImDrawList drawList) { if (editorState.exportStartTicks >= 0 && editorState.exportEndTicks >= 0) { int exportStartX = replayTickToTimelineX(editorState.exportStartTicks); @@ -932,7 +960,7 @@ public class TimelineWindow { } }); - if (!(editingKeyframe instanceof TimelapseKeyframe)) { + if (editingKeyframe.keyframeType().allowChangingInterpolationType()) { int[] type = new int[]{editingKeyframe.interpolationType().ordinal()}; ImGui.setNextItemWidth(160); if (ImGuiHelper.combo("Type", type, InterpolationType.NAMES)) { @@ -958,7 +986,8 @@ public class TimelineWindow { editorState.push(new EditorStateHistoryEntry(undo, redo, "Changed interpolation type to " + interpolationType)); } - + } + if (editingKeyframe.keyframeType().allowChangingTimelineTick()) { int[] intWrapper = new int[]{editingKeyframeTick}; ImGui.setNextItemWidth(160); ImGuiHelper.inputInt("Tick", intWrapper); @@ -1247,9 +1276,6 @@ public class TimelineWindow { float lineHeight = ImGui.getTextLineHeightWithSpacing() + ImGui.getStyle().getItemSpacingY(); ImDrawList drawList = ImGui.getWindowDrawList(); - ImDrawList foregroundDrawList = ImGui.getForegroundDrawList(); - - foregroundDrawList.pushClipRect(x + middleX, y, x + width, y + height); GrabMovementInfo grabMovementInfo = null; if (grabbedKeyframe) { @@ -1269,6 +1295,13 @@ public class TimelineWindow { } } + if (editorState.recordingCameraMovementTrack == trackIndex && editorState.recordingCameraMovementMinTick >= 0 && editorState.recordingCameraMovementMaxTick >= 0) { + float fromX = x + replayTickToTimelineX(editorState.recordingCameraMovementMinTick); + float toX = x + replayTickToTimelineX(editorState.recordingCameraMovementMaxTick); + float topY = y + 2 + trackIndex * lineHeight; + drawList.addRectFilled(fromX, topY, toX, topY + lineHeight, 0xFF4040FF); + } + for (int tick = minTicks - 10; tick <= minTicks + availableTicks + 10; tick++) { var entry = keyframeTimes.ceilingEntry(tick); if (entry == null || entry.getKey() > minTicks + availableTicks + 10) { @@ -1298,7 +1331,7 @@ public class TimelineWindow { float midX = x + keyframeX; - drawKeyframe(foregroundDrawList, keyframe.interpolationType(), midX, midY, keyframeTrack.enabled ? 0xFF0000FF : 0x800000FF); + drawKeyframe(drawList, keyframe.interpolationType(), midX, midY, keyframeTrack.enabled ? 0xFF0000FF : 0x800000FF); } else { int keyframeX = replayTickToTimelineX(tick); @@ -1381,8 +1414,6 @@ public class TimelineWindow { } } } - - foregroundDrawList.popClipRect(); } private static void drawKeyframe(ImDrawList drawList, InterpolationType interpolationType, float x, float y, int colour) { @@ -1447,6 +1478,22 @@ public class TimelineWindow { ImGui.pushID(trackIndex); + if (trackIndex == openCreateKeyframeAtTickTrack) { + ImGui.openPopup("##CreateKeyframeAtTickPopup"); + openCreateKeyframeAtTickTrack = -1; + } + + if (ImGui.beginPopup("##CreateKeyframeAtTickPopup")) { + if (ImGui.menuItem("Create Keyframe at " + createKeyframeAtTick)) { + ImGui.closeCurrentPopup(); + ImGui.endPopup(); + + createNewKeyframe(editorState, trackIndex, createKeyframeAtTick, keyframeType, keyframeTrack); + } else { + ImGui.endPopup(); + } + } + ImGui.setCursorPosX(8); if (keyframeTrack.enabled) { @@ -1461,19 +1508,7 @@ public class TimelineWindow { float buttonY = ImGui.getCursorScreenPosY(); ImGui.setCursorPosX(buttonX - x); if (ImGui.button("##Add", buttonSize, buttonSize)) { - Keyframe keyframe = keyframeType.createDirect(); - if (keyframe != null) { - editorState.setKeyframe(trackIndex, cursorTicks, keyframe); - } else { - if (keyframeType == TimelapseKeyframeType.INSTANCE && keyframeTrack.keyframesByTick.isEmpty()) { - editorState.setKeyframe(trackIndex, cursorTicks, new TimelapseKeyframe(0)); - } else { - createKeyframeWithPopup = keyframeType.createPopup(); - if (createKeyframeWithPopup != null) { - ImGui.openPopup("##CreateKeyframe"); - } - } - } + createNewKeyframe(editorState, trackIndex, cursorTicks, keyframeType, keyframeTrack); } 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); @@ -1484,7 +1519,7 @@ public class TimelineWindow { hasOpenPopup = true; Keyframe keyframe = createKeyframeWithPopup.render(); if (keyframe != null) { - editorState.setKeyframe(trackIndex, cursorTicks, keyframe); + editorState.setKeyframe(trackIndex, createKeyframeWithPopupTick, keyframe); ImGui.closeCurrentPopup(); } } else { @@ -1532,7 +1567,9 @@ public class TimelineWindow { if (!hasOpenPopup) { createKeyframeWithPopup = null; + createKeyframeWithPopupTick = cursorTicks; } + openCreateKeyframeAtTickTrack = -1; if (keyframeTrackToClear >= 0) { List undo = new ArrayList<>(); @@ -1573,6 +1610,23 @@ public class TimelineWindow { } } + private static void createNewKeyframe(EditorState editorState, int trackIndex, int tick, KeyframeType keyframeType, KeyframeTrack keyframeTrack) { + Keyframe keyframe = keyframeType.createDirect(); + if (keyframe != null) { + editorState.setKeyframe(trackIndex, tick, keyframe); + } else { + if (keyframeType == TimelapseKeyframeType.INSTANCE && keyframeTrack.keyframesByTick.isEmpty()) { + editorState.setKeyframe(trackIndex, tick, new TimelapseKeyframe(0)); + } else { + createKeyframeWithPopup = keyframeType.createPopup(); + if (createKeyframeWithPopup != null) { + ImGui.openPopup("##CreateKeyframe"); + createKeyframeWithPopupTick = tick; + } + } + } + } + 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) { diff --git a/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java index 9e9d1f1..61f0f91 100644 --- a/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java +++ b/src/main/java/com/moulberry/flashback/editor/ui/windows/VisualsWindow.java @@ -63,6 +63,13 @@ public class VisualsWindow { editorState.markDirty(); } + if (Minecraft.getInstance().cameraEntity != null && Minecraft.getInstance().cameraEntity != Minecraft.getInstance().player) { + if (ImGui.checkbox("Hotbar", visuals.showHotbar)) { + visuals.showHotbar = !visuals.showHotbar; + editorState.markDirty(); + } + } + ImGuiHelper.separatorWithText("World"); if (ImGui.checkbox("Render Blocks", visuals.renderBlocks)) { diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java index d6452fd..8434b3b 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportJob.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportJob.java @@ -11,6 +11,7 @@ import com.moulberry.flashback.Flashback; import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.Utils; import com.moulberry.flashback.combo_options.VideoContainer; +import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler; @@ -21,6 +22,8 @@ import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; +import net.minecraft.ChatFormatting; +import net.minecraft.Util; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; @@ -28,6 +31,8 @@ import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.FogRenderer; import net.minecraft.client.renderer.ShaderInstance; +import net.minecraft.network.chat.Component; +import net.minecraft.util.FormattedCharSequence; import net.minecraft.world.entity.Entity; import net.minecraft.world.phys.Vec3; import org.bytedeco.ffmpeg.global.avutil; @@ -70,6 +75,7 @@ public class ExportJob { private long renderTimeNanos = 0; private long encodeTimeNanos = 0; private long downloadTimeNanos = 0; + private boolean patreonLinkClicked = false; private double currentTickDouble = 0.0; @@ -272,8 +278,6 @@ public class ExportJob { KeyframeHandler keyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance()); this.settings.editorState().applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble)); - AccurateEntityPositionHandler.apply(Minecraft.getInstance().level, (float) partialTick); - SaveableFramebuffer saveable = downloader.take(); RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget; @@ -531,6 +535,8 @@ public class ExportJob { if (currentFrame >= this.settings.framerate()) { long estimatedRemaining = (currentTime - this.renderStartTime) * (totalFrames - currentFrame) / currentFrame; lines.add("Estimated time remaining: " + formatTime(estimatedRemaining)); + } else { + lines.add("Estimated time remaining: ~"); } lines.add(""); @@ -584,6 +590,31 @@ public class ExportJob { } } + double mouseX = ReplayUI.imguiGlfw.rawMouseX / window.getWidth() * scaledWidth; + double mouseY = ReplayUI.imguiGlfw.rawMouseY / window.getHeight() * scaledHeight; + + y += font.lineHeight / 2 + 1; + + String patreon = "https://www.patreon.com/flashbackmod"; + int patreonWidth = font.width(patreon); + if (mouseX > x - patreonWidth/2f && mouseX < x + patreonWidth/2f && mouseY > y && mouseY < y + font.lineHeight) { + font.drawInBatch(Component.literal(patreon).withStyle(ChatFormatting.UNDERLINE), x - patreonWidth/2f, y, + -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); + + if (GLFW.glfwGetMouseButton(window.getWindow(), GLFW.GLFW_MOUSE_BUTTON_LEFT) != 0) { + if (!this.patreonLinkClicked) { + this.patreonLinkClicked = true; + Util.getPlatform().openUri(patreon); + } + } else { + this.patreonLinkClicked = false; + } + } else { + font.drawInBatch(patreon, x - patreonWidth/2f, y, + -1, true, matrix, bufferSource, Font.DisplayMode.NORMAL, 0, 0xF000F0); + this.patreonLinkClicked = false; + } + bufferSource.endBatch(); RenderSystem.enableDepthTest(); diff --git a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java index c7fe24d..231b2ca 100644 --- a/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java +++ b/src/main/java/com/moulberry/flashback/exporting/ExportSettings.java @@ -17,7 +17,7 @@ public record ExportSettings(@Nullable String name, EditorState editorState, int resolutionX, int resolutionY, int startTick, int endTick, double framerate, boolean resetRng, // Video - VideoContainer container, VideoCodec codec, String encoder, int bitrate, boolean transparent, boolean ssaa, + VideoContainer container, VideoCodec codec, String encoder, int bitrate, boolean transparent, boolean ssaa, boolean noGui, // Audio boolean recordAudio, boolean stereoAudio, AudioCodec audioCodec, // Output diff --git a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java index 668fc4b..ec568eb 100644 --- a/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java +++ b/src/main/java/com/moulberry/flashback/io/AsyncReplaySaver.java @@ -10,6 +10,7 @@ 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 com.moulberry.flashback.playback.ReplayServer; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; @@ -103,6 +104,7 @@ public class AsyncReplaySaver { List> packetCopy = new ArrayList<>(packets); this.submit(writer -> { RegistryFriendlyByteBuf chunkCacheOutput = null; + int lastChunkCacheIndex = -1; FriendlyByteBuf customPayloadTempBuffer = null; @@ -130,6 +132,18 @@ public class AsyncReplaySaver { } if (add) { + index = this.totalWrittenChunkPackets; + this.totalWrittenChunkPackets += 1; + + // Write chunk cache file if necessary + int cacheIndex = index / ReplayServer.CHUNK_CACHE_SIZE; + if (lastChunkCacheIndex >= 0 && cacheIndex != lastChunkCacheIndex) { + this.writeChunkCacheFile(chunkCacheOutput, lastChunkCacheIndex); + chunkCacheOutput = null; + } + lastChunkCacheIndex = cacheIndex; + + // Create new chunk cache output buffer if necessary if (chunkCacheOutput == null) { chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), writer.registryAccess()); } @@ -148,9 +162,7 @@ public class AsyncReplaySaver { chunkCacheOutput.writeInt(size); chunkCacheOutput.writerIndex(endWriterIndex); - index = this.totalWrittenChunkPackets; - this.totalWrittenChunkPackets += 1; - + // Add to list so that this chunk can be reused cachedChunkPacket.index = index; cached.add(cachedChunkPacket); } @@ -211,20 +223,29 @@ public class AsyncReplaySaver { } } - 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); - } + if (lastChunkCacheIndex >= 0) { + writeChunkCacheFile(chunkCacheOutput, lastChunkCacheIndex); } }); } + private void writeChunkCacheFile(RegistryFriendlyByteBuf chunkCacheOutput, int index) { + if (chunkCacheOutput == null || chunkCacheOutput.writerIndex() == 0) { + return; + } + + try { + byte[] bytes = new byte[chunkCacheOutput.writerIndex()]; + chunkCacheOutput.getBytes(0, bytes); + + Path levelChunkCachePath = this.recordFolder.resolve("level_chunk_caches").resolve(""+index); + Files.createDirectories(levelChunkCachePath.getParent()); + Files.write(levelChunkCachePath, bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC); + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + } + public void writeConfigurationPackets(StreamCodec> configurationPacketCodec, List> packets) { diff --git a/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java index 91d6d6f..91a2712 100644 --- a/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java +++ b/src/main/java/com/moulberry/flashback/keyframe/KeyframeType.java @@ -6,19 +6,8 @@ import org.jetbrains.annotations.Nullable; import java.util.function.Consumer; -// todo: WIP DON'T COMMIT public interface KeyframeType { - /* - CAMERA("Camera"), - CAMERA_ORBIT("Camera Orbit"), - FOV("FOV"), - SPEED("Speed"), - TIMELAPSE("Timelapse"), - TIME_OF_DAY("Time of day"), - CAMERA_SHAKE("Camera Shake"); - */ - String name(); String id(); @Nullable T createDirect(); diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java index bd24922..71b4818 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinLevelRenderer.java @@ -9,7 +9,6 @@ import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexFormat; import com.moulberry.flashback.Flashback; @@ -32,6 +31,7 @@ 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.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.entity.BlockEntity; diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java index 4c8fe3c..cfd65e9 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMinecraft.java @@ -224,7 +224,7 @@ public abstract class MixinMinecraft implements MinecraftExt { private final DeltaTracker.Timer localPlayerTimer = new DeltaTracker.Timer(20.0f, 0, FloatUnaryOperator.identity()); @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At("HEAD")) - public void disconnect(Screen screen, boolean isTransferring, CallbackInfo ci) { + public void disconnectHead(Screen screen, boolean isTransferring, CallbackInfo ci) { try { if (Flashback.getConfig().automaticallyFinish && Flashback.RECORDER != null && !isTransferring) { Flashback.finishRecordingReplay(); @@ -234,14 +234,9 @@ public abstract class MixinMinecraft implements MinecraftExt { } } - @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MouseHandler;handleAccumulatedMovement()V", shift = At.Shift.AFTER)) - public void runTick_handleAccumulatedMovement(boolean runTick, CallbackInfo ci) { - if (Flashback.RECORDER != null && this.player != null) { - float partialTick = this.timer.deltaTickResidual; - Flashback.RECORDER.trackPartialPosition(this.player, partialTick); - } - - AccurateEntityPositionHandler.apply(this.level, this.timer.deltaTickResidual); + @Inject(method = "disconnect(Lnet/minecraft/client/gui/screens/Screen;Z)V", at = @At("RETURN")) + public void disconnectReturn(Screen screen, boolean bl, CallbackInfo ci) { + Flashback.updateIsInReplay(); } @Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;runAllTasks()V", shift = At.Shift.AFTER)) @@ -326,6 +321,7 @@ public abstract class MixinMinecraft implements MinecraftExt { this.progressListener.set(storingChunkProgressListener); return ProcessorChunkProgressListener.createStarted(storingChunkProgressListener, this.progressTasks::add); }, playbackUUID, path)); + Flashback.updateIsInReplay(); this.isLocalServer = true; this.updateReportEnvironment(ReportEnvironment.local()); // this.quickPlayLog.setWorldData(QuickPlayLog.Type.SINGLEPLAYER, levelStorageAccess.getLevelId(), worldStem.worldData().getLevelName()); diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java b/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java index f40298d..e68da09 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinMouseHandler.java @@ -22,6 +22,13 @@ public class MixinMouseHandler { } } + @Inject(method = {"onPress", "onScroll", "onMove"}, at = @At("HEAD"), cancellable = true) + public void onUseMouse(CallbackInfo ci) { + if (Flashback.isExporting()) { + ci.cancel(); + } + } + @Inject(method = "grabMouse", at=@At("HEAD"), cancellable = true) public void grabMouse(CallbackInfo ci) { if (ReplayUI.isActive() || Flashback.isExporting()) { diff --git a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java index 741c5a8..ca49025 100644 --- a/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java +++ b/src/main/java/com/moulberry/flashback/mixin/MixinRenderTarget.java @@ -3,8 +3,15 @@ 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.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.BufferUploader; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; import com.moulberry.flashback.editor.ui.ReplayUI; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.ShaderInstance; import org.lwjgl.glfw.GLFW; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; @@ -14,12 +21,17 @@ 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.Objects; + @Mixin(value = RenderTarget.class, priority = 800) public abstract class MixinRenderTarget { @Shadow public int frameBufferId; + @Shadow + public abstract int getColorTextureId(); + @Inject(method = "blitToScreen(IIZ)V", at = @At("HEAD"), cancellable = true) public void blitToScreenSodium(int width, int height, boolean noBlend, CallbackInfo ci) { if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive()) { diff --git a/src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java b/src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java new file mode 100644 index 0000000..975f309 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/compat/distanthorizons/MixinSharedApi.java @@ -0,0 +1,23 @@ +package com.moulberry.flashback.mixin.compat.distanthorizons; + +import com.moulberry.mixinconstraints.annotations.IfModLoaded; +import com.seibel.distanthorizons.core.api.internal.SharedApi; +import org.spongepowered.asm.mixin.Mixin; + +@IfModLoaded("distanthorizons") +@Mixin(value = SharedApi.class, remap = false) +public abstract class MixinSharedApi { + + /* + * Override any changes to the DhWorld, changing it to our proxy world + */ + +// @Inject(method = "setDhWorld", at = @At("HEAD"), cancellable = true) +// private static void setDhWorld(AbstractDhWorld newWorld, CallbackInfo ci) { +// if (Flashback.isInReplay() && newWorld != null && !(newWorld instanceof ProxyDhWorld)) { +// SharedApi.setDhWorld(new ProxyDhWorld()); +// ci.cancel(); +// } +// } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinAbstractMinecart.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinAbstractMinecart.java new file mode 100644 index 0000000..aa3e77a --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinAbstractMinecart.java @@ -0,0 +1,26 @@ +package com.moulberry.flashback.mixin.playback; + +import com.moulberry.flashback.Flashback; +import net.minecraft.world.entity.vehicle.AbstractMinecart; +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.Constant; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyConstant; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(AbstractMinecart.class) +public class MixinAbstractMinecart { + + @Shadow + private int lerpSteps; + + @Inject(method = "lerpTo", at = @At("RETURN")) + public void modifyLerpTime(double d, double e, double f, float g, float h, int i, CallbackInfo ci) { + if (Flashback.isInReplay()) { + this.lerpSteps = 3; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinBoat.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinBoat.java new file mode 100644 index 0000000..5a8d146 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinBoat.java @@ -0,0 +1,24 @@ +package com.moulberry.flashback.mixin.playback; + +import com.moulberry.flashback.Flashback; +import net.minecraft.world.entity.vehicle.Boat; +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(Boat.class) +public class MixinBoat { + + @Shadow + private int lerpSteps; + + @Inject(method = "lerpTo", at = @At("RETURN")) + public void modifyLerpTime(double d, double e, double f, float g, float h, int i, CallbackInfo ci) { + if (Flashback.isInReplay()) { + this.lerpSteps = 3; + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java new file mode 100644 index 0000000..0745d2c --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinCamera.java @@ -0,0 +1,49 @@ +package com.moulberry.flashback.mixin.playback; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.llamalad7.mixinextras.sugar.Local; +import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; +import net.minecraft.client.Camera; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import org.joml.Vector2f; +import org.joml.Vector3d; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(Camera.class) +public class MixinCamera { + + @Shadow + private float eyeHeightOld; + + @Shadow + public float eyeHeight; + + @WrapOperation(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setRotation(FF)V", ordinal = 0)) + public void setRotation(Camera instance, float yaw, float pitch, Operation original, + @Local(argsOnly = true) Entity entity, @Local(argsOnly = true) float partialTick) { + Vector2f rotation = AccurateEntityPositionHandler.getAccurateRotation(entity, partialTick); + if (rotation != null) { + pitch = rotation.x; + yaw = rotation.y; + } + original.call(instance, yaw, pitch); + } + + + @WrapOperation(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setPosition(DDD)V", ordinal = 0)) + public void setPosition(Camera instance, double x, double y, double z, Operation original, + @Local(argsOnly = true) Entity entity, @Local(argsOnly = true) float partialTick) { + Vector3d position = AccurateEntityPositionHandler.getAccuratePosition(entity, partialTick); + if (position != null) { + x = position.x; + y = position.y + Mth.lerp(partialTick, this.eyeHeightOld, this.eyeHeight); + z = position.z; + } + original.call(instance, x, y, z); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java index b2e6e63..1884a3a 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinEntity.java @@ -53,4 +53,5 @@ public abstract class MixinEntity { } } + } diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java index 83d85de..238405b 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinGameRenderer.java @@ -10,6 +10,7 @@ import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.ext.ItemInHandRendererExt; import com.moulberry.flashback.ext.MinecraftExt; +import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.CameraRotation; import com.moulberry.flashback.visuals.ShaderManager; import net.minecraft.client.Camera; @@ -55,19 +56,26 @@ public abstract class MixinGameRenderer { @Shadow @Final - private Minecraft minecraft; + Minecraft minecraft; - @Shadow - public abstract float getDepthFar(); + @Inject(method = "render", at = @At("HEAD")) + public void renderHead(DeltaTracker deltaTracker, boolean bl, CallbackInfo ci) { + LocalPlayer player = Minecraft.getInstance().player; - @Shadow - public abstract void renderLevel(DeltaTracker deltaTracker); + if (Flashback.RECORDER != null && player != null) { + float partialTick = deltaTracker.getGameTimeDeltaPartialTick(true); + Flashback.RECORDER.trackPartialPosition(player, partialTick); + } - @Shadow - private @Nullable PostChain postEffect; + AccurateEntityPositionHandler.apply(Minecraft.getInstance().level, deltaTracker); + } - @Shadow - private boolean effectActive; + @Inject(method = "render", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;clear(IZ)V", remap = false, ordinal = 0), cancellable = true) + public void render_noGui(DeltaTracker deltaTracker, boolean bl, CallbackInfo ci) { + if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().noGui()) { + ci.cancel(); + } + } @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) { diff --git a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java index cd126dc..d89ab95 100644 --- a/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java +++ b/src/main/java/com/moulberry/flashback/mixin/playback/MixinLevelChunk.java @@ -63,7 +63,12 @@ public abstract class MixinLevelChunk extends ChunkAccess implements LevelChunkE @Override public void flashback$setBlockStateWithoutUpdates(BlockPos blockPos, BlockState blockState) { int y = blockPos.getY(); - LevelChunkSection levelChunkSection = this.getSection(this.getSectionIndex(y)); + int sectionY = this.getSectionIndex(y); + if (sectionY < 0 || sectionY >= this.getSectionsCount()) { + return; + } + + LevelChunkSection levelChunkSection = this.getSection(sectionY); boolean oldHasOnlyAir = levelChunkSection.hasOnlyAir(); if (oldHasOnlyAir && blockState.isAir()) { return; diff --git a/src/main/java/com/moulberry/flashback/mixin/record/MixinLocalPlayer.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinLocalPlayer.java new file mode 100644 index 0000000..a44d382 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinLocalPlayer.java @@ -0,0 +1,40 @@ +package com.moulberry.flashback.mixin.record; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.Flashback; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.level.Level; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +@Mixin(LocalPlayer.class) +public class MixinLocalPlayer { + + @WrapOperation(method = "playSound", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;playLocalSound(DDDLnet/minecraft/sounds/SoundEvent;Lnet/minecraft/sounds/SoundSource;FFZ)V")) + public void playSound(Level instance, double x, double y, double z, SoundEvent soundEvent, SoundSource soundSource, + float volume, float pitch, boolean global, Operation original) { + if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { + + Optional> builtinSoundEvent = BuiltInRegistries.SOUND_EVENT.getHolder(soundEvent.getLocation()); + Holder holder; + if (builtinSoundEvent.isEmpty()) { + holder = Holder.direct(soundEvent); + } else { + holder = builtinSoundEvent.get(); + } + + Flashback.RECORDER.writeSound(holder, soundSource, x, y, z, volume, pitch, + ThreadLocalRandom.current().nextLong()); + } + original.call(instance, x, y, z, soundEvent, soundSource, volume, pitch, global); + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/record/MixinMultiPlayerGameMode.java b/src/main/java/com/moulberry/flashback/mixin/record/MixinMultiPlayerGameMode.java new file mode 100644 index 0000000..322d99b --- /dev/null +++ b/src/main/java/com/moulberry/flashback/mixin/record/MixinMultiPlayerGameMode.java @@ -0,0 +1,54 @@ +package com.moulberry.flashback.mixin.record; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.moulberry.flashback.Flashback; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.resources.sounds.Sound; +import net.minecraft.client.resources.sounds.SoundInstance; +import net.minecraft.client.sounds.SoundManager; +import net.minecraft.core.Holder; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +import java.util.Optional; +import java.util.concurrent.ThreadLocalRandom; + +@Mixin(MultiPlayerGameMode.class) +public class MixinMultiPlayerGameMode { + + @WrapOperation(method = "continueDestroyBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/sounds/SoundManager;play(Lnet/minecraft/client/resources/sounds/SoundInstance;)V")) + public void playBreakingSound(SoundManager instance, SoundInstance soundInstance, Operation original) { + original.call(instance, soundInstance); + + if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) { + if (soundInstance.getSound() == null) { + return; + } + + Optional> builtinSoundEvent = BuiltInRegistries.SOUND_EVENT.getHolder(soundInstance.getLocation()); + Holder holder; + if (builtinSoundEvent.isEmpty()) { + holder = Holder.direct(SoundEvent.createVariableRangeEvent(soundInstance.getLocation())); + } else { + holder = builtinSoundEvent.get(); + } + + SoundSource soundSource = soundInstance.getSource(); + float volume = soundInstance.getVolume(); + float pitch = soundInstance.getPitch(); + double x = soundInstance.getX(); + double y = soundInstance.getY(); + double z = soundInstance.getZ(); + + Flashback.RECORDER.writeSound(holder, soundSource, x, y, z, volume, pitch, + ThreadLocalRandom.current().nextLong()); + } + } + +} diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java index 7595134..a35a417 100644 --- a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java +++ b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinServerEntity.java @@ -19,7 +19,7 @@ public class MixinServerEntity { @ModifyVariable(method = "", at = @At("HEAD"), argsOnly = true) private static int init_modifyUpdateInterval(int updateInterval, @Local(argsOnly = true) ServerLevel level) { - if (updateInterval <= 3 && level != null && level.getServer() instanceof ReplayServer) { + if (updateInterval < 20 && level != null && level.getServer() instanceof ReplayServer) { return 1; } return updateInterval; diff --git a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java b/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java deleted file mode 100644 index 95d1c92..0000000 --- a/src/main/java/com/moulberry/flashback/mixin/replay_server/MixinTickRateManager.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.moulberry.flashback.mixin.replay_server; - -import com.moulberry.flashback.Flashback; -import net.minecraft.server.ServerTickRateManager; -import net.minecraft.world.TickRateManager; -import net.minecraft.world.entity.Entity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(TickRateManager.class) -public abstract class MixinTickRateManager { - - - - @Inject(method = "isEntityFrozen", at = @At("RETURN")) - public void isEntityFrozen(Entity entity, CallbackInfoReturnable cir) { - - } - -} diff --git a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java index b5a6ac2..8bf11af 100644 --- a/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java +++ b/src/main/java/com/moulberry/flashback/mixin/ui/MixinTitleScreen.java @@ -4,9 +4,11 @@ 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.Flashback; import com.moulberry.flashback.screen.FlashbackButton; import com.moulberry.flashback.screen.SelectReplayScreen; import net.fabricmc.fabric.api.client.screen.v1.Screens; +import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.AbstractButton; import net.minecraft.client.gui.components.AbstractWidget; @@ -14,10 +16,13 @@ import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.ImageButton; import net.minecraft.client.gui.components.Renderable; import net.minecraft.client.gui.components.events.GuiEventListener; +import net.minecraft.client.gui.screens.AlertScreen; 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 net.minecraft.util.StringUtil; +import org.apache.commons.lang3.StringUtils; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -87,7 +92,21 @@ public class MixinTitleScreen extends Screen { if (!overlapsWithExistingButton) { this.openSelectReplayScreenButton = new FlashbackButton(x, y, size, size, Component.literal("Open Replays"), button -> { - this.minecraft.setScreen(new SelectReplayScreen(this)); + List incompatibleMods = Screen.hasShiftDown() ? List.of() : Flashback.getReplayIncompatibleMods(); + + if (incompatibleMods.isEmpty()) { + this.minecraft.setScreen(new SelectReplayScreen(this)); + } else { + String mods = StringUtils.join(incompatibleMods, ", "); + String description = """ + You have mods which are known to cause crashes when loading replays + Please remove the following mods in order to be able to load replays: + + """; + this.minecraft.setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this), + Component.literal("Incompatible Mods"), Component.literal(description).append(Component.literal(mods).withStyle(ChatFormatting.RED)))); + } + }); this.addRenderableWidget(this.openSelectReplayScreenButton); return; diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java index e7bca62..b9f5f76 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinClientLevel.java @@ -1,7 +1,36 @@ package com.moulberry.flashback.mixin.visuals; +import com.moulberry.flashback.Flashback; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +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(ClientLevel.class) public class MixinClientLevel { + /* + * Some entities have weird behaviour when rotating in a replay + * This code here ensures that the interpolation of yRotO -> yRot will always be the shortest path + */ + @Inject(method = "tickNonPassenger", at = @At("RETURN")) + public void tickNonPassengerEnd(Entity entity, CallbackInfo ci) { + if (Flashback.isInReplay()) { + entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot(); + entity.yRotO = Mth.wrapDegrees(entity.yRotO - entity.getYRot()) + entity.getYRot(); + } + } + + @Inject(method = "tickPassenger", at = @At("RETURN")) + public void tickPassengerEnd(Entity vehicle, Entity entity, CallbackInfo ci) { + if (Flashback.isInReplay()) { + entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot(); + entity.yRotO = Mth.wrapDegrees(entity.yRotO - entity.getYRot()) + entity.getYRot(); + } + } } diff --git a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java index 5b77d67..1e495f0 100644 --- a/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java +++ b/src/main/java/com/moulberry/flashback/mixin/visuals/MixinGui.java @@ -86,6 +86,14 @@ public abstract class MixinGui { } } + @Inject(method = "renderHotbarAndDecorations", at = @At("HEAD"), cancellable = true) + public void renderHotbarAndDecorations(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { + EditorState editorState = EditorStateManager.getCurrent(); + if (editorState != null && !editorState.replayVisuals.showHotbar) { + ci.cancel(); + } + } + @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;")) public GameType renderHotbarAndDecorations_getPlayerMode(MultiPlayerGameMode instance, Operation original) { if (Flashback.isInReplay()) { diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java index 56531c0..ecf7564 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayGamePacketHandler.java @@ -21,6 +21,7 @@ import net.minecraft.core.Direction; import net.minecraft.core.Holder; 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.DisconnectionDetails; import net.minecraft.network.RegistryFriendlyByteBuf; @@ -343,7 +344,6 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener { @Override public void handleBlockUpdate(ClientboundBlockUpdatePacket clientboundBlockUpdatePacket) { - System.out.println(clientboundBlockUpdatePacket.getPos()); this.setBlockState(this.level(), clientboundBlockUpdatePacket.getPos(), clientboundBlockUpdatePacket.getBlockState()); forward(clientboundBlockUpdatePacket); diff --git a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java index 0bd827d..c5a7b7b 100644 --- a/src/main/java/com/moulberry/flashback/playback/ReplayServer.java +++ b/src/main/java/com/moulberry/flashback/playback/ReplayServer.java @@ -4,7 +4,7 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.mojang.authlib.GameProfile; import com.moulberry.flashback.Flashback; -import com.moulberry.flashback.action.PositionAndAngle; +import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.ext.LevelChunkExt; import com.moulberry.flashback.TempFolderProvider; import com.moulberry.flashback.keyframe.handler.ReplayServerKeyframeHandler; @@ -33,13 +33,11 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.longs.LongSet; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; import net.minecraft.core.registries.Registries; -import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; import net.minecraft.network.codec.StreamCodec; @@ -59,14 +57,11 @@ import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.TicketType; import net.minecraft.server.level.progress.ChunkProgressListenerFactory; import net.minecraft.server.network.ConfigurationTask; -import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.players.PlayerList; import net.minecraft.util.Mth; import net.minecraft.world.BossEvent; -import net.minecraft.world.entity.Display; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.flag.FeatureFlagSet; @@ -80,8 +75,8 @@ import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; -import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; @@ -99,7 +94,6 @@ import java.util.Objects; import java.util.Optional; import java.util.TreeMap; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; @@ -110,6 +104,7 @@ public class ReplayServer extends IntegratedServer { private static final Gson GSON = new Gson(); public static int REPLAY_VIEWER_IDS_START = -981723987; public static String REPLAY_VIEWER_NAME = "Replay Viewer"; + public static final int CHUNK_CACHE_SIZE = 10000; public volatile int jumpToTick = -1; public volatile boolean replayPaused = true; @@ -138,6 +133,7 @@ public class ReplayServer extends IntegratedServer { private final FlashbackMeta metadata; private final TreeMap playableChunksByStart = new TreeMap<>(); private final Int2ObjectMap levelChunkCachedPackets = new Int2ObjectOpenHashMap<>(); + private final IntSet loadedChunkCacheFiles = new IntOpenHashSet(); private ReplayReader currentReplayReader = null; private record RemotePack(UUID id, String url, String hash){} @@ -183,46 +179,55 @@ public class ReplayServer extends IntegratedServer { Path levelChunkCachePath = this.playbackFileSystem.getPath("/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()); + loadLevelChunkCache(levelChunkCachePath, 0, "/level_chunk_cache"); } } catch (IOException e) { throw new RuntimeException(e); } } + private void loadLevelChunkCache(Path levelChunkCachePath, int chunkCacheIndex, String name) throws IOException { + int startIndex = chunkCacheIndex; + + try (InputStream is = Files.newInputStream(levelChunkCachePath)) { + while (true) { + byte[] sizeBuffer = is.readNBytes(4); + if (sizeBuffer.length < 4) { + break; + } + + int size = (sizeBuffer[0] & 0xff) << 24 | + (sizeBuffer[1] & 0xff) << 16 | + (sizeBuffer[2] & 0xff) << 8 | + sizeBuffer[3] & 0xff; + + byte[] chunk = is.readNBytes(size); + if (chunk.length < size) { + Flashback.LOGGER.error("Ran out of bytes while reading level_chunk_cache, needed {}, had {}", + size, chunk.length); + break; + } + + RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(Unpooled.wrappedBuffer(chunk), 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 {} with {} entries", name, chunkCacheIndex - startIndex); + } + public FlashbackMeta getMetadata() { return this.metadata; } @@ -583,6 +588,7 @@ public class ReplayServer extends IntegratedServer { public void handleAccuratePlayerPosition(RegistryFriendlyByteBuf friendlyByteBuf) { var packet = FlashbackAccurateEntityPosition.STREAM_CODEC.decode(friendlyByteBuf); + for (ReplayPlayer replayViewer : this.replayViewers) { ServerPlayNetworking.send(replayViewer, packet); } @@ -631,6 +637,22 @@ public class ReplayServer extends IntegratedServer { public void handleLevelChunkCached(int index) { ClientboundLevelChunkWithLightPacket packet = this.levelChunkCachedPackets.get(index); + if (packet == null) { + int cacheIndex = index / ReplayServer.CHUNK_CACHE_SIZE; + if (this.loadedChunkCacheFiles.add(cacheIndex)) { + String pathString = "/level_chunk_caches/" + cacheIndex; + Path levelChunkCachePath = this.playbackFileSystem.getPath(pathString); + if (Files.exists(levelChunkCachePath)) { + try { + loadLevelChunkCache(levelChunkCachePath, cacheIndex * ReplayServer.CHUNK_CACHE_SIZE, pathString); + } catch (IOException e) { + SneakyThrow.sneakyThrow(e); + } + } + packet = this.levelChunkCachedPackets.get(index); + } + } + if (packet != null) { this.configurationPacketHandler.flushPendingConfiguration(); this.gamePacketHandler.flushPendingEntities(); @@ -756,8 +778,10 @@ public class ReplayServer extends IntegratedServer { this.replayPaused = true; } + boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false) && Flashback.EXPORT_JOB == null; + if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback) { - this.runUpdates(booleanSupplier); + this.runUpdates(booleanSupplier, forceApplyKeyframes); } else { int realTargetTick = this.targetTick; @@ -770,12 +794,12 @@ public class ReplayServer extends IntegratedServer { if (this.targetTick >= realTargetTick) { this.targetTick = realTargetTick; - this.runUpdates(booleanSupplier); + this.runUpdates(booleanSupplier, forceApplyKeyframes); } else { while (this.targetTick <= realTargetTick) { this.fastForwarding = this.targetTick < realTargetTick; - this.runUpdates(booleanSupplier); + this.runUpdates(booleanSupplier, forceApplyKeyframes); if (this.targetTick == realTargetTick) { break; @@ -787,6 +811,10 @@ public class ReplayServer extends IntegratedServer { } } + if (forceApplyKeyframes) { + ((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes(); + } + this.tryFollowLocalPlayer(); // Update first person data @@ -903,15 +931,10 @@ public class ReplayServer extends IntegratedServer { } } - private void runUpdates(BooleanSupplier booleanSupplier) { - boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false) && Flashback.EXPORT_JOB == null; + private void runUpdates(BooleanSupplier booleanSupplier, boolean forceApplyKeyframes) { if (!this.replayPaused || forceApplyKeyframes) { this.desiredTickRate = 20.0f; this.getEditorState().applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick); - - if (forceApplyKeyframes) { - ((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes(); - } } float tickRate = this.desiredTickRate; @@ -1183,6 +1206,9 @@ public class ReplayServer extends IntegratedServer { Flashback.LOGGER.error("Failed to close playback zip", e); } } + + this.levelChunkCachedPackets.clear(); + this.playableChunksByStart.clear(); } public void clearReplayTempFolder() { diff --git a/src/main/java/com/moulberry/flashback/record/Recorder.java b/src/main/java/com/moulberry/flashback/record/Recorder.java index 391275f..250ea40 100644 --- a/src/main/java/com/moulberry/flashback/record/Recorder.java +++ b/src/main/java/com/moulberry/flashback/record/Recorder.java @@ -29,6 +29,7 @@ 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.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.Tag; import net.minecraft.network.ConnectionProtocol; @@ -73,6 +74,7 @@ import net.minecraft.world.level.saveddata.maps.MapId; import net.minecraft.world.level.saveddata.maps.MapItemSavedData; import net.minecraft.world.phys.Vec3; import net.minecraft.world.scores.*; +import org.jetbrains.annotations.Nullable; import java.nio.file.Path; import java.util.*; @@ -185,10 +187,10 @@ public class Recorder { return builder.toString(); } - private long lastPositionNanos; private PositionAndAngle lastPlayerPositionAndAngle = null; - private Vec3 nextPlayerPosition = null; - private final TreeMap partialPositions = new TreeMap<>(); + private float lastPlayerPositionAndAnglePartialTick; + private final TreeMap partialPositions = new TreeMap<>(); + private int trackAccuratePositionCounter = 10; public void trackPartialPosition(Entity entity, float partialTick) { int localPlayerUpdatesPerSecond = Flashback.getConfig().localPlayerUpdatesPerSecond; @@ -196,16 +198,12 @@ public class Recorder { return; } - long currentNanos = System.nanoTime(); - double x = Mth.lerp(partialTick, entity.xo, entity.getX()); double y = Mth.lerp(partialTick, entity.yo, entity.getY()); double z = Mth.lerp(partialTick, entity.zo, entity.getZ()); float yaw = entity.getViewYRot(partialTick); float pitch = entity.getViewXRot(partialTick); - - this.nextPlayerPosition = new Vec3(entity.getX(), entity.getY(), entity.getZ()); - this.partialPositions.put(currentNanos, new PositionAndAngle(x, y, z, yaw, pitch)); + this.partialPositions.put(partialTick, new PositionAndAngle(x, y, z, yaw, pitch)); } public void endTick(boolean close) { @@ -240,66 +238,7 @@ public class Recorder { this.writeLocalData(); if (trackAccurateFirstPersonPosition) { - long nanos = System.nanoTime(); - - LocalPlayer player = Minecraft.getInstance().player; - if (player == null || this.nextPlayerPosition == null) { - this.lastPlayerPositionAndAngle = null; - } else if (this.lastPlayerPositionAndAngle == null) { - this.lastPlayerPositionAndAngle = new PositionAndAngle(this.nextPlayerPosition.x, this.nextPlayerPosition.y, this.nextPlayerPosition.z, - player.getYRot(), player.getXRot()); - } else { - int divisions = localPlayerUpdatesPerSecond / 20; - PositionAndAngle newPosition = new PositionAndAngle(this.nextPlayerPosition.x, this.nextPlayerPosition.y, this.nextPlayerPosition.z, - player.getYRot(), player.getXRot()); - - if (!this.lastPlayerPositionAndAngle.equals(newPosition)) { - List interpolatedPositions = new ArrayList<>(); - - for (int i = 0; i <= divisions; i++) { - double amount = (double) i / divisions; - double partialNanos = this.lastPositionNanos + (nanos - this.lastPositionNanos) * amount; - long partialNanosRounded = (long) partialNanos; - - Long floorNanos = this.lastPositionNanos; - PositionAndAngle floorPosition = this.lastPlayerPositionAndAngle; - Long ceilNanos = nanos; - PositionAndAngle ceilPosition = newPosition; - - Map.Entry floorEntry = this.partialPositions.floorEntry(partialNanosRounded); - Map.Entry ceilEntry = this.partialPositions.ceilingEntry(partialNanosRounded + 1); - - if (floorEntry != null) { - floorNanos = floorEntry.getKey(); - floorPosition = floorEntry.getValue(); - } - if (ceilEntry != null) { - ceilNanos = ceilEntry.getKey(); - ceilPosition = ceilEntry.getValue(); - } - - double lerpAmount = 0.5; - if (!Objects.equals(ceilNanos, floorNanos)) { - lerpAmount = (partialNanos - floorNanos) / (ceilNanos - floorNanos); - } - - PositionAndAngle interpolatedPosition = floorPosition.lerp(ceilPosition, lerpAmount); - interpolatedPositions.add(interpolatedPosition); - } - - FlashbackAccurateEntityPosition accurateEntityPosition = new FlashbackAccurateEntityPosition(player.getId(), interpolatedPositions); - this.asyncReplaySaver.submit(writer -> { - writer.startAction(ActionAccuratePlayerPosition.INSTANCE); - FlashbackAccurateEntityPosition.STREAM_CODEC.encode(writer.friendlyByteBuf(), accurateEntityPosition); - writer.finishAction(ActionAccuratePlayerPosition.INSTANCE); - }); - - this.lastPlayerPositionAndAngle = newPosition; - } - } - - this.partialPositions.clear(); - this.lastPositionNanos = nanos; + this.writeAccurateFirstPersonPosition(localPlayerUpdatesPerSecond); } this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); @@ -321,15 +260,8 @@ public class Recorder { changedDimensions = true; } } else if (trackAccurateFirstPersonPosition) { + this.updateLastPlayerPositionAndAngle(Minecraft.getInstance().player); this.partialPositions.clear(); - this.lastPositionNanos = System.nanoTime(); - - LocalPlayer player = Minecraft.getInstance().player; - if (player != null) { - this.lastPlayerPositionAndAngle = new PositionAndAngle(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); - } else { - this.lastPlayerPositionAndAngle = null; - } } this.finishedPausing |= this.wasPaused && !this.isPaused; @@ -388,6 +320,96 @@ public class Recorder { } } + private void writeAccurateFirstPersonPosition(int localPlayerUpdatesPerSecond) { + LocalPlayer player = Minecraft.getInstance().player; + if (player == null) { + this.lastPlayerPositionAndAngle = null; + this.partialPositions.clear(); + return; + } + + if (this.lastPlayerPositionAndAngle != null) { + int divisions = localPlayerUpdatesPerSecond / 20; + Minecraft.getInstance().mouseHandler.handleAccumulatedMovement(); + float nextPartialTick = Minecraft.getInstance().timer.getGameTimeDeltaPartialTick(true); + + double nextX = Mth.lerp(nextPartialTick, player.xo, player.getX()); + double nextY = Mth.lerp(nextPartialTick, player.yo, player.getY()); + double nextZ = Mth.lerp(nextPartialTick, player.zo, player.getZ()); + float nextYaw = player.getViewYRot(nextPartialTick); + float nextPitch = player.getViewXRot(nextPartialTick); + PositionAndAngle nextPosition = new PositionAndAngle(nextX, nextY, nextZ, nextYaw, nextPitch); + + if (!this.lastPlayerPositionAndAngle.equals(nextPosition)) { + this.trackAccuratePositionCounter = 10; + } else if (this.trackAccuratePositionCounter > 0) { + this.trackAccuratePositionCounter -= 1; + } + + if (this.trackAccuratePositionCounter > 0) { + List interpolatedPositions = new ArrayList<>(); + + for (int i = 0; i <= divisions; i++) { + float amount = (float) i / divisions; + + float floorPartial = -1.0f + this.lastPlayerPositionAndAnglePartialTick; + PositionAndAngle floorPosition = this.lastPlayerPositionAndAngle; + float ceilPartial = 1.0f + nextPartialTick; + PositionAndAngle ceilPosition = nextPosition; + + Map.Entry floorEntry = this.partialPositions.floorEntry(amount); + Map.Entry ceilEntry = this.partialPositions.ceilingEntry(Math.nextUp(amount)); + + if (floorEntry != null) { + floorPartial = floorEntry.getKey(); + floorPosition = floorEntry.getValue(); + } + if (ceilEntry != null) { + ceilPartial = ceilEntry.getKey(); + ceilPosition = ceilEntry.getValue(); + } + + double lerpAmount = 0.5; + if (!Objects.equals(floorPartial, ceilPartial)) { + lerpAmount = (amount - floorPartial) / (ceilPartial - floorPartial); + } + + PositionAndAngle interpolatedPosition = floorPosition.lerp(ceilPosition, lerpAmount); + interpolatedPositions.add(interpolatedPosition); + } + + FlashbackAccurateEntityPosition accurateEntityPosition = new FlashbackAccurateEntityPosition(player.getId(), interpolatedPositions); + this.asyncReplaySaver.submit(writer -> { + writer.startAction(ActionAccuratePlayerPosition.INSTANCE); + FlashbackAccurateEntityPosition.STREAM_CODEC.encode(writer.friendlyByteBuf(), accurateEntityPosition); + writer.finishAction(ActionAccuratePlayerPosition.INSTANCE); + }); + } + } + + this.updateLastPlayerPositionAndAngle(player); + this.partialPositions.clear(); + } + + private void updateLastPlayerPositionAndAngle(@Nullable LocalPlayer player) { + Map.Entry floorEntry = this.partialPositions.floorEntry(1.0f); + if (floorEntry != null) { + this.lastPlayerPositionAndAngle = floorEntry.getValue(); + this.lastPlayerPositionAndAnglePartialTick = floorEntry.getKey(); + } else if (player != null) { + double x = player.xo; + double y = player.yo; + double z = player.zo; + float yaw = player.getViewYRot(0.0f); + float pitch = player.getViewXRot(0.0f); + + this.lastPlayerPositionAndAngle = new PositionAndAngle(x, y, z, yaw, pitch); + this.lastPlayerPositionAndAnglePartialTick = 1.0f; + } else { + this.lastPlayerPositionAndAngle = null; + } + } + public boolean isPaused() { return this.isPaused; } @@ -888,6 +910,7 @@ public class Recorder { for (int i = 0; i < chunks.length(); i++) { LevelChunk chunk = chunks.get(i); if (chunk != null) { + System.out.println("chunk " + chunk.getPos() + " is light correct: " + chunk.isLightCorrect()); var task = pool.submit(() -> new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), new BitSet(), new BitSet())); levelChunkPacketTasks.add(new PositionedTask(chunk.getPos(), task)); } @@ -901,9 +924,16 @@ public class Recorder { return dx*dx + dz*dz; })); + // Ensure light is up-to-date + for (int i = 0; i < 1000; i++) { + if (level.isLightUpdateQueueEmpty()) { + break; + } + level.pollLightUpdates(); + } + // 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); diff --git a/src/main/java/com/moulberry/flashback/record/ReplayExporter.java b/src/main/java/com/moulberry/flashback/record/ReplayExporter.java index 586b1db..ec3b970 100644 --- a/src/main/java/com/moulberry/flashback/record/ReplayExporter.java +++ b/src/main/java/com/moulberry/flashback/record/ReplayExporter.java @@ -11,8 +11,10 @@ import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Iterator; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -71,6 +73,19 @@ public class ReplayExporter { zipOut.write(GSON.toJson(meta.toJson()).getBytes(StandardCharsets.UTF_8)); zipOut.closeEntry(); + // Write chunked level chunk caches + Path levelChunkCaches = recordFolder.resolve("level_chunk_caches"); + if (Files.exists(levelChunkCaches) && Files.isDirectory(levelChunkCaches)) { + try (DirectoryStream directoryStream = Files.newDirectoryStream(levelChunkCaches)) { + for (Path path : directoryStream) { + zipEntry = new ZipEntry("level_chunk_caches/" + path.getFileName().toString()); + zipOut.putNextEntry(zipEntry); + Files.copy(path, zipOut); + zipOut.closeEntry(); + } + } + } + // Write level chunk cache Path levelChunkCachePath = recordFolder.resolve("level_chunk_cache"); if (Files.exists(levelChunkCachePath)) { diff --git a/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java b/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java new file mode 100644 index 0000000..14e00c8 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/EditReplayScreen.java @@ -0,0 +1,112 @@ +package com.moulberry.flashback.screen; + +import com.google.gson.JsonObject; +import com.moulberry.flashback.Flashback; +import com.moulberry.flashback.FlashbackGson; +import com.moulberry.flashback.exporting.AsyncFileDialogs; +import com.moulberry.flashback.record.FlashbackMeta; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.EditBox; +import net.minecraft.client.gui.components.StringWidget; +import net.minecraft.client.gui.layouts.FrameLayout; +import net.minecraft.client.gui.layouts.GridLayout; +import net.minecraft.client.gui.screens.AlertScreen; +import net.minecraft.client.gui.screens.ConfirmScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.Nullable; + +import java.io.IOException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; + +public class EditReplayScreen extends Screen { + + @Nullable + private final Screen lastScreen; + + private FlashbackMeta metadata; + private String changedReplayName; + private Button saveChangesButton; + + private Path replayPath; + + protected EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) { + super(Component.literal("Edit Replay")); + this.lastScreen = lastScreen; + this.metadata = summary.getReplayMetadata(); + this.changedReplayName = summary.getReplayName(); + this.replayPath = summary.getPath(); + } + + @Override + protected void init() { + super.init(); + + GridLayout gridLayout = new GridLayout(); + gridLayout.defaultCellSetting().padding(4, 4, 4, 0); + GridLayout.RowHelper rowHelper = gridLayout.createRowHelper(2); + + rowHelper.addChild(new StringWidget(204, 20, Component.literal("Edit Replay"), this.font), 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Replay Name"), this.font).alignLeft(), 2); + + EditBox replayNameEditBox = new EditBox(this.font, 0, 0, 204, 20, Component.literal(this.changedReplayName)); + replayNameEditBox.setValue(this.changedReplayName); + replayNameEditBox.setResponder(this::setReplayName); + rowHelper.addChild(replayNameEditBox, 2); + + rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2); + + this.saveChangesButton = rowHelper.addChild(Button.builder(Component.literal("Save Changes"), button -> { + this.applyChanges(); + }).width(98).build()); + this.saveChangesButton.active = false; + rowHelper.addChild(Button.builder(Component.literal("Back"), button -> { + this.minecraft.setScreen(this.lastScreen); + }).width(98).build()); + gridLayout.arrangeElements(); + FrameLayout.alignInRectangle(gridLayout, 0, 0, this.width, this.height, 0.5f, 0.5f); + gridLayout.visitWidgets(this::addRenderableWidget); + + this.updateSaveChangesActive(); + } + + private void applyChanges() { + this.metadata.name = this.changedReplayName; + + try (FileSystem fileSystem = FileSystems.newFileSystem(this.replayPath)) { + Path metadataPath = fileSystem.getPath("/metadata.json"); + + // Update + String metadataJson = FlashbackGson.PRETTY.toJson(this.metadata.toJson()); + Files.writeString(metadataPath, metadataJson); + } catch (IOException e) { + Flashback.LOGGER.error("Unable to edit replay", e); + Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.lastScreen), + Component.literal("Unable to edit replay"), Component.literal(e.toString()))); + } + + this.updateSaveChangesActive(); + this.clearFocus(); + } + + private void setReplayName(String name) { + this.changedReplayName = name; + this.updateSaveChangesActive(); + } + + private void updateSaveChangesActive() { + this.saveChangesButton.active = !Objects.equals(this.metadata.name, this.changedReplayName); + } + + @Override + public void onClose() { + this.minecraft.setScreen(this.lastScreen); + } +} diff --git a/src/main/java/com/moulberry/flashback/screen/RecoverRecordingsScreen.java b/src/main/java/com/moulberry/flashback/screen/RecoverRecordingsScreen.java new file mode 100644 index 0000000..7749861 --- /dev/null +++ b/src/main/java/com/moulberry/flashback/screen/RecoverRecordingsScreen.java @@ -0,0 +1,79 @@ +package com.moulberry.flashback.screen; + +import com.moulberry.flashback.Flashback; +import net.minecraft.ChatFormatting; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.MultiLineLabel; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.CommonComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; + +import java.time.Duration; +import java.util.function.Consumer; + +public class RecoverRecordingsScreen extends Screen { + + private Screen lastScreen; + private final Component title; + private final Component messageText; + private MultiLineLabel message = MultiLineLabel.EMPTY; + private Consumer handler; + + public enum RecoveryOption { + RECOVER, + SKIP, + DELETE + } + + public RecoverRecordingsScreen(Screen lastScreen, Component title, Component message, Consumer handler) { + super(title); + this.lastScreen = lastScreen; + this.title = title; + this.messageText = message; + this.handler = handler; + } + + @Override + public Component getNarrationMessage() { + return CommonComponents.joinForNarration(super.getNarrationMessage(), this.messageText); + } + + @Override + protected void init() { + super.init(); + + this.message = MultiLineLabel.create(this.font, this.messageText, this.width - 50); + int lines = this.message.getLineCount(); + int height = lines * this.font.lineHeight; + int buttonY = Mth.clamp(90 + height + 12, this.height / 6 + 96, this.height - 24); + + this.addRenderableWidget(Button.builder(Component.literal("Recover").withStyle(ChatFormatting.GREEN), b -> { + Minecraft.getInstance().setScreen(this.lastScreen); + this.handler.accept(RecoveryOption.RECOVER); + }).bounds((this.width - 304) / 2, buttonY, 96, 20).build()); + this.addRenderableWidget(Button.builder(Component.literal("Skip").withStyle(ChatFormatting.YELLOW), b -> { + Minecraft.getInstance().setScreen(this.lastScreen); + this.handler.accept(RecoveryOption.SKIP); + }).bounds((this.width - 304) / 2 + 104, buttonY, 96, 20).build()); + this.addRenderableWidget(Button.builder(Component.literal("Delete").withStyle(ChatFormatting.RED), b -> { + Minecraft.getInstance().setScreen(this.lastScreen); + this.handler.accept(RecoveryOption.DELETE); + }).bounds((this.width - 304)/2 + 208, buttonY, 96, 20).build()); + } + + @Override + public void render(GuiGraphics guiGraphics, int i, int j, float f) { + super.render(guiGraphics, i, j, f); + guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, 70, 0xFFFFFF); + this.message.renderCentered(guiGraphics, this.width / 2, 90); + } + + @Override + public boolean shouldCloseOnEsc() { + return false; + } + +} diff --git a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java index b23e8e0..b864c38 100644 --- a/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java +++ b/src/main/java/com/moulberry/flashback/screen/ReplaySelectionList.java @@ -458,8 +458,9 @@ public class ReplaySelectionList extends ObjectSelectionList this.minecraft.setScreen(this.lastScreen)) - .bounds(this.width / 2 + 82, this.height - 28, 72, 20).build()); + .bounds(this.width / 2 + 57, this.height - 28, 97, 20).build()); if (this.width/2 > 154 + 128) { this.addRenderableWidget(Button.builder(Component.literal("Flashback Settings"), btn -> Minecraft.getInstance().setScreen(new ConfigScreen(this))) diff --git a/src/main/java/com/moulberry/flashback/state/EditorState.java b/src/main/java/com/moulberry/flashback/state/EditorState.java index 1c5be9f..65951c3 100644 --- a/src/main/java/com/moulberry/flashback/state/EditorState.java +++ b/src/main/java/com/moulberry/flashback/state/EditorState.java @@ -2,16 +2,22 @@ package com.moulberry.flashback.state; import com.moulberry.flashback.Flashback; import com.moulberry.flashback.FlashbackGson; +import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.handler.KeyframeHandler; +import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import com.moulberry.flashback.keyframe.types.CameraKeyframeType; import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType; +import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.visuals.ReplayVisuals; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.world.entity.Entity; +import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; import java.io.IOException; @@ -39,6 +45,83 @@ public class EditorState { public UUID audioSourceEntity = null; public Set hideDuringExport = new HashSet<>(); + public transient int recordingCameraMovementTrack = -1; + public transient int recordingCameraMovementMinTick = -1; + public transient int recordingCameraMovementMaxTick = -1; + public transient Int2ObjectMap recordingCameraKeyframes = new Int2ObjectOpenHashMap<>(); + + public void recordCameraMovement() { + if (recordingCameraMovementTrack < 0) { + return; + } + + if (!ReplayUI.recordCameraMovement) { + finishRecordingCameraMovement(); + return; + } + + ReplayServer replayServer = Flashback.getReplayServer(); + if (replayServer != null) { + if (replayServer.replayPaused) { + finishRecordingCameraMovement(); + return; + } + + Entity cameraEntity = Minecraft.getInstance().getCameraEntity(); + if (cameraEntity == null) { + return; + } + + int tick = replayServer.getReplayTick(); + if (recordingCameraMovementMaxTick >= 0) { + int nextCapture = recordingCameraMovementMaxTick + 4; + if (tick >= nextCapture) { + tick = nextCapture; + } else { + return; + } + } + + recordingCameraKeyframes.put(tick, new CameraKeyframe(Minecraft.getInstance().getCameraEntity())); + + if (recordingCameraMovementMinTick < 0) { + recordingCameraMovementMinTick = tick; + } + + recordingCameraMovementMinTick = Math.min(recordingCameraMovementMinTick, tick); + recordingCameraMovementMaxTick = Math.max(recordingCameraMovementMaxTick, tick); + } + } + + public void finishRecordingCameraMovement() { + int trackIndex = recordingCameraMovementTrack; + if (trackIndex >= 0 && trackIndex < this.keyframeTracks.size()) { + List undo = new ArrayList<>(); + List redo = new ArrayList<>(); + + KeyframeTrack track = this.keyframeTracks.get(trackIndex); + + for (Int2ObjectMap.Entry entry : recordingCameraKeyframes.int2ObjectEntrySet()) { + int tick = entry.getIntKey(); + + Keyframe old = track.keyframesByTick.get(entry.getIntKey()); + if (old != null) { + undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy())); + } else { + undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick)); + } + redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, entry.getValue())); + } + + this.push(new EditorStateHistoryEntry(undo, redo, "Record movement as keyframes")); + } + + recordingCameraMovementTrack = -1; + recordingCameraMovementMinTick = -1; + recordingCameraMovementMaxTick = -1; + recordingCameraKeyframes.clear(); + } + public void setKeyframe(int trackIndex, int tick, Keyframe keyframe) { if (trackIndex >= this.keyframeTracks.size()) { return; diff --git a/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java b/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java index 830c685..a526483 100644 --- a/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java +++ b/src/main/java/com/moulberry/flashback/visuals/AccurateEntityPositionHandler.java @@ -6,10 +6,15 @@ import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition; import com.moulberry.flashback.playback.ReplayServer; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.minecraft.client.DeltaTracker; +import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector2f; +import org.joml.Vector3d; import java.util.List; @@ -30,13 +35,72 @@ public class AccurateEntityPositionHandler { pendingData.put(data.entityId(), data.positionAndAngles()); } - public static void apply(ClientLevel level, float partialTick) { - if (currentData == null) { + @Nullable + public static Vector2f getAccurateRotation(Entity entity, float partialTick) { + if (currentData != null && currentData.containsKey(entity.getId())) { + List positionAndAngles = currentData.get(entity.getId()); + float amount = partialTick * (positionAndAngles.size() - 1); + + int floorAmount = (int) amount; + PositionAndAngle floorPosition = positionAndAngles.get(floorAmount); + + int ceilAmount = floorAmount + 1; + + if (ceilAmount >= positionAndAngles.size()) { + return new Vector2f(floorPosition.pitch(), floorPosition.yaw()); + } else { + PositionAndAngle ceilPosition = positionAndAngles.get(ceilAmount); + float partialAmount = amount - floorAmount; + + float yaw = floorPosition.yaw() + Mth.wrapDegrees(ceilPosition.yaw() - floorPosition.yaw()) * partialAmount; + float pitch = floorPosition.pitch() + Mth.wrapDegrees(ceilPosition.pitch() - floorPosition.pitch()) * partialAmount; + + return new Vector2f(Mth.wrapDegrees(pitch), Mth.wrapDegrees(yaw)); + } + } + return null; + } + + @Nullable + public static Vector3d getAccuratePosition(Entity entity, float partialTick) { + if (entity.isPassenger() || !Minecraft.getInstance().options.getCameraType().isFirstPerson()) { + return null; + } + + if (currentData != null && currentData.containsKey(entity.getId())) { + List positionAndAngles = currentData.get(entity.getId()); + float amount = partialTick * (positionAndAngles.size() - 1); + + int floorAmount = (int) amount; + PositionAndAngle floorPosition = positionAndAngles.get(floorAmount); + + int ceilAmount = floorAmount + 1; + + if (ceilAmount >= positionAndAngles.size()) { + return new Vector3d(floorPosition.x(), floorPosition.y(), floorPosition.z()); + } else { + PositionAndAngle ceilPosition = positionAndAngles.get(ceilAmount); + float partialAmount = amount - floorAmount; + + double x = floorPosition.x() + (ceilPosition.x() - floorPosition.x()) * partialAmount; + double y = floorPosition.y() + (ceilPosition.y() - floorPosition.y()) * partialAmount; + double z = floorPosition.z() + (ceilPosition.z() - floorPosition.z()) * partialAmount; + + return new Vector3d(x, y, z); + } + } + return null; + } + + public static void apply(ClientLevel level, DeltaTracker deltaTracker) { + if (currentData == null || level == null) { return; } + float partialTick = deltaTracker.getGameTimeDeltaPartialTick(true); + ReplayServer replayServer = Flashback.getReplayServer(); - if (replayServer != null && level != null) { + if (replayServer != null) { for (Int2ObjectMap.Entry> entry : currentData.int2ObjectEntrySet()) { Entity entity = level.getEntity(entry.getIntKey()); if (entity == null) { @@ -52,13 +116,7 @@ public class AccurateEntityPositionHandler { int ceilAmount = floorAmount + 1; if (ceilAmount >= positionAndAngles.size()) { - entity.setYHeadRot(floorPosition.yaw()); - entity.moveTo(floorPosition.x(), floorPosition.y(), floorPosition.z(), floorPosition.yaw(), floorPosition.pitch()); - if (entity instanceof LivingEntity livingEntity) { - livingEntity.lerpSteps = 0; - livingEntity.lerpHeadSteps = 0; - livingEntity.yHeadRotO = livingEntity.yHeadRot; - } + applyPosition(entity, floorPosition.x(), floorPosition.y(), floorPosition.z(), floorPosition.yaw(), floorPosition.pitch()); } else { PositionAndAngle ceilPosition = positionAndAngles.get(ceilAmount); float partialAmount = amount - floorAmount; @@ -69,17 +127,27 @@ public class AccurateEntityPositionHandler { float yaw = floorPosition.yaw() + Mth.wrapDegrees(ceilPosition.yaw() - floorPosition.yaw()) * partialAmount; float pitch = floorPosition.pitch() + Mth.wrapDegrees(ceilPosition.pitch() - floorPosition.pitch()) * partialAmount; - entity.setYHeadRot(Mth.wrapDegrees(yaw)); - entity.moveTo(x, y, z, Mth.wrapDegrees(yaw), Mth.wrapDegrees(pitch)); - if (entity instanceof LivingEntity livingEntity) { - livingEntity.lerpSteps = 0; - livingEntity.lerpHeadSteps = 0; - livingEntity.yHeadRotO = livingEntity.yHeadRot; - } + applyPosition(entity, x, y, z, Mth.wrapDegrees(yaw), Mth.wrapDegrees(pitch)); } } } } + private static void applyPosition(Entity entity, double x, double y, double z, float yaw, float pitch) { + if (!entity.isPassenger() && Minecraft.getInstance().cameraEntity == entity && Minecraft.getInstance().options.getCameraType().isFirstPerson()) { + entity.moveTo(x, y, z, yaw, pitch); + } + + entity.setYRot(yaw); + entity.setXRot(pitch); + entity.setYHeadRot(yaw); + if (entity instanceof LivingEntity livingEntity) { + livingEntity.lerpHeadSteps = 0; + livingEntity.yHeadRotO = livingEntity.yHeadRot; + livingEntity.yRotO = livingEntity.getYRot(); + livingEntity.xRotO = livingEntity.getXRot(); + } + } + } diff --git a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java index ba7f954..9b9095f 100644 --- a/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java +++ b/src/main/java/com/moulberry/flashback/visuals/ReplayVisuals.java @@ -11,6 +11,7 @@ public class ReplayVisuals { public boolean showTitleText = false; public boolean showScoreboard = false; public boolean showActionBar = false; + public boolean showHotbar = true; public boolean renderBlocks = true; public boolean renderEntities = true; diff --git a/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java b/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java index ba73d4e..bdb8137 100644 --- a/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java +++ b/src/main/java/com/moulberry/flashback/visuals/WorldRenderHook.java @@ -28,12 +28,12 @@ public class WorldRenderHook { public static void renderHook(PoseStack poseStack, float partialTick, boolean renderBlockOutline, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f projection) { ReplayServer replayServer = Flashback.getReplayServer(); - if (replayServer == null) { + if (replayServer == null || Flashback.isExporting()) { return; } EditorState editorState = EditorStateManager.getCurrent(); - if (editorState != null && !Flashback.isExporting() && editorState.replayVisuals.cameraPath) { + if (editorState != null && editorState.replayVisuals.cameraPath) { CameraPath.renderCameraPath(poseStack, camera, replayServer); } diff --git a/src/main/resources/flashback.mixins.json b/src/main/resources/flashback.mixins.json index 1759ba6..21e9d75 100644 --- a/src/main/resources/flashback.mixins.json +++ b/src/main/resources/flashback.mixins.json @@ -16,15 +16,19 @@ "norandom.MixinParticle", "packet_fix.MixinBossHealthOverlay", "playback.MixinArmorStandRenderer", + "playback.MixinCamera", "playback.MixinClientCommonPacketListenerImpl", "playback.MixinGameRenderer", "playback.MixinItemInHandRenderer", "playback.MixinRemotePlayer", "record.MixinClientConfigurationPacketListenerImpl", "record.MixinClientLevel", + "record.MixinLocalPlayer", + "record.MixinMultiPlayerGameMode", "ui.MixinPauseScreen", "ui.MixinTitleScreen", "visuals.MixinBossHealthOverlay", + "visuals.MixinClientLevel", "visuals.MixinClientLevelData", "visuals.MixinEntityRenderDispatcher", "visuals.MixinEntityRenderer", @@ -48,13 +52,16 @@ "compat.bobby.FakeChunkManagerAccessor", "compat.bobby.MixinBobby", "compat.bobby.MixinBobbyFakeChunkManager", + "compat.distanthorizons.MixinSharedApi", "compat.iris.MixinIrisSystemTimeUniforms", "compat.replaymod.MixinReplayModRecording", "compat.voice_chat.MixinVoiceChatALSpeakerBase", "compat.voice_chat.MixinVoiceChatClientVoicechat", "compat.voice_chat.MixinVoiceChatRenderEvents", "compat.voice_chat.MixinVoiceChatSoundManager", + "playback.MixinAbstractMinecart", "playback.MixinAttributeInstance", + "playback.MixinBoat", "playback.MixinChunkHolder", "playback.MixinEntity", "playback.MixinLevelChunk", @@ -73,7 +80,6 @@ "replay_server.MixinServerEntity", "replay_server.MixinServerGamePacketListenerImpl", "replay_server.MixinServerLevel", - "replay_server.MixinServerLoginPacketListenerImpl", - "replay_server.MixinTickRateManager" + "replay_server.MixinServerLoginPacketListenerImpl" ] }