This commit is contained in:
Moulberry committed 2024-09-30 20:00:24 +08:00
1 parent be99313e81
commit 63535e6b3d
79 files changed
+2007 -529

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
.gradle/ .gradle/
build/ build/
out/ out/
deps/
classes/ classes/
# eclipse # eclipse
+3 -1
View File
@@ -64,12 +64,14 @@ dependencies {
include(implementation("com.moulberry:mixinconstraints:1.0.1")) include(implementation("com.moulberry:mixinconstraints:1.0.1"))
modCompileOnly(rootProject.files('deps/DistantHorizons-2.3.0-a-dev-1.21.1.jar'))
modCompileOnly("maven.modrinth:sodium:RncWhTxD") modCompileOnly("maven.modrinth:sodium:RncWhTxD")
modCompileOnly("maven.modrinth:iris:kuOV4Ece") modCompileOnly("maven.modrinth:iris:kuOV4Ece")
modCompileOnly("maven.modrinth:bobby:2cuVyTav") modCompileOnly("maven.modrinth:bobby:2cuVyTav")
modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I") modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I")
modCompileOnly("maven.modrinth:replaymod:NtlpUQgI") modCompileOnly("maven.modrinth:replaymod:NtlpUQgI")
modCompileOnly("maven.modrinth:distanthorizons:pEvLEY5E") // modCompileOnly("maven.modrinth:distanthorizons:pEvLEY5E")
modImplementation("maven.modrinth:modmenu:xhN1IvHi") modImplementation("maven.modrinth:modmenu:xhN1IvHi")
// modCompileOnly("maven.modrinth:axiom:D3uDJmiB") // modCompileOnly("maven.modrinth:axiom:D3uDJmiB")
+1 -1
View File
@@ -9,7 +9,7 @@ yarn_mappings=1.21+build.9
loader_version=0.15.11 loader_version=0.15.11
# Mod Properties # Mod Properties
mod_version=0.7.0 mod_version=0.10.0
maven_group=com.moulberry.flashback maven_group=com.moulberry.flashback
archives_base_name=flashback archives_base_name=flashback
@@ -9,8 +9,10 @@ import com.mojang.realmsclient.RealmsMainScreen;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import com.moulberry.flashback.action.*; import com.moulberry.flashback.action.*;
import com.moulberry.flashback.command.BetterColorArgument; import com.moulberry.flashback.command.BetterColorArgument;
import com.moulberry.flashback.compat.DistantHorizonsSupport;
import com.moulberry.flashback.compat.simple_voice_chat.SimpleVoiceChatPlayback; import com.moulberry.flashback.compat.simple_voice_chat.SimpleVoiceChatPlayback;
import com.moulberry.flashback.configuration.FlashbackConfig; import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.exporting.ExportJob; import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.keyframe.KeyframeRegistry; import com.moulberry.flashback.keyframe.KeyframeRegistry;
@@ -45,6 +47,7 @@ import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.AccurateEntityPositionHandler;
import com.moulberry.flashback.visuals.ShaderManager; import com.moulberry.flashback.visuals.ShaderManager;
import com.seibel.distanthorizons.api.DhApi;
import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
@@ -54,7 +57,6 @@ import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.resource.ResourceManagerHelper;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.FileUtil; import net.minecraft.FileUtil;
@@ -75,7 +77,6 @@ import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.codec.StreamCodec;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.*; import net.minecraft.server.*;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.PackRepository; import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource; import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.world.Difficulty; import net.minecraft.world.Difficulty;
@@ -128,6 +129,8 @@ public class Flashback implements ModInitializer, ClientModInitializer {
private static boolean delayedOpenConfig = false; private static boolean delayedOpenConfig = false;
private static volatile boolean isInReplay = false; private static volatile boolean isInReplay = false;
public static boolean supportsDistantHorizons = false;
private static final List<Path> pendingReplaySave = new ArrayList<>(); private static final List<Path> pendingReplaySave = new ArrayList<>();
private static final List<Path> pendingReplayRecovery = new ArrayList<>(); private static final List<Path> pendingReplayRecovery = new ArrayList<>();
@@ -305,7 +308,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
} }
}); });
ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(ShaderManager.INSTANCE); ShaderManager.INSTANCE.register();
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
var flashback = ClientCommandManager.literal("flashback"); var flashback = ClientCommandManager.literal("flashback");
@@ -358,6 +361,18 @@ public class Flashback implements ModInitializer, ClientModInitializer {
editorState.recordCameraMovement(); editorState.recordCameraMovement();
} }
} }
// Fix for camera entity sometimes being incorrect when respawning
Entity camera = Minecraft.getInstance().cameraEntity;
LocalPlayer player = Minecraft.getInstance().player;
if (player != null && camera != null && camera != player) {
if (camera.isRemoved()) {
Entity other = player.level().getEntity(camera.getId());
if (other != null && !other.isRemoved()) {
Minecraft.getInstance().setCameraEntity(other);
}
}
}
}); });
ClientTickEvents.START_CLIENT_TICK.register(minecraft -> { ClientTickEvents.START_CLIENT_TICK.register(minecraft -> {
@@ -437,6 +452,16 @@ public class Flashback implements ModInitializer, ClientModInitializer {
updateIsInReplay(); updateIsInReplay();
}); });
if (FabricLoader.getInstance().isModLoaded("distanthorizons")) {
if (DhApi.getApiMajorVersion() >= 4) {
Flashback.LOGGER.info("DistantHorizons detected. Enabling Flashback+DistantHorizons integration");
supportsDistantHorizons = true;
DistantHorizonsSupport.register();
} else {
Flashback.LOGGER.error("DistantHorizons is installed, but API version is too low ({}). Disabling integration.", DhApi.getApiMajorVersion());
}
}
} }
public static List<String> getReplayIncompatibleMods() { public static List<String> getReplayIncompatibleMods() {
@@ -444,6 +469,9 @@ public class Flashback implements ModInitializer, ClientModInitializer {
if (FabricLoader.getInstance().isModLoaded("vmp")) { if (FabricLoader.getInstance().isModLoaded("vmp")) {
incompatible.add("VeryManyPlayers (vmp)"); incompatible.add("VeryManyPlayers (vmp)");
} }
if (FabricLoader.getInstance().isModLoaded("c2me")) {
incompatible.add("Concurrent Chunk Management Engine (c2me)");
}
return incompatible; return incompatible;
} }
@@ -466,10 +494,6 @@ public class Flashback implements ModInitializer, ClientModInitializer {
return; return;
} }
if (colour == null) {
colour = 0xFF5555;
}
ReplayMarker.MarkerPosition position = null; ReplayMarker.MarkerPosition position = null;
if (savePosition == null || savePosition) { if (savePosition == null || savePosition) {
Entity camera = Minecraft.getInstance().getCameraEntity(); Entity camera = Minecraft.getInstance().getCameraEntity();
@@ -479,6 +503,21 @@ public class Flashback implements ModInitializer, ClientModInitializer {
} }
} }
String feedback;
if (colour != null) {
feedback = "Added #" + Integer.toHexString(colour) + " marker";
} else {
feedback = "Added marker";
}
if (position != null) {
feedback += String.format(" at %.2f, %.2f, %.2f", position.position().x, position.position().y, position.position().z);
}
if (colour == null) {
colour = 0xFF5555;
}
if (description != null) { if (description != null) {
description = description.trim(); description = description.trim();
if (description.isEmpty()) { if (description.isEmpty()) {
@@ -486,6 +525,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
} }
} }
command.getSource().sendFeedback(Component.literal(feedback));
RECORDER.addMarker(new ReplayMarker(colour, position, description)); RECORDER.addMarker(new ReplayMarker(colour, position, description));
} }
@@ -703,7 +743,38 @@ public class Flashback implements ModInitializer, ClientModInitializer {
return null; return null;
} }
public static void openReplayFromFileBrowser() {
String defaultFolder = Flashback.getReplayFolder().toString();
AsyncFileDialogs.openFileDialog(defaultFolder, "Zip File", "zip").thenAccept(pathStr -> {
if (pathStr != null) {
Path path = Path.of(pathStr);
Minecraft.getInstance().submit(() -> {
Flashback.openReplayWorld(path);
});
}
});
}
public static void openReplayWorld(Path path) { public static void openReplayWorld(Path path) {
// Disconnect
Minecraft minecraft = Minecraft.getInstance();
if (minecraft.level != null) {
minecraft.level.disconnect();
}
minecraft.disconnect();
minecraft.setScreen(new TitleScreen());
// Add as recent
String pathStr = path.toString();
FlashbackConfig config = Flashback.getConfig();
config.recentReplays.remove(pathStr);
config.recentReplays.add(0, pathStr);
if (config.recentReplays.size() > 32) {
config.recentReplays.remove(config.recentReplays.size() - 1);
}
config.saveToDefaultFolder();
// Actually load
try { try {
UUID replayUuid = UUID.randomUUID(); UUID replayUuid = UUID.randomUUID();
Path replayTemp = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.SERVER, replayUuid); Path replayTemp = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.SERVER, replayUuid);
@@ -2,6 +2,8 @@ package com.moulberry.flashback;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.PropertyMap;
import com.moulberry.flashback.keyframe.Keyframe; import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.KeyframeRegistry; import com.moulberry.flashback.keyframe.KeyframeRegistry;
import com.moulberry.flashback.keyframe.KeyframeType; import com.moulberry.flashback.keyframe.KeyframeType;
@@ -33,6 +35,7 @@ public class FlashbackGson {
.registerTypeAdapter(Quaternionf.class, new QuaternionfTypeAdapater()) .registerTypeAdapter(Quaternionf.class, new QuaternionfTypeAdapater())
.registerTypeAdapter(Vector3d.class, new Vector3dTypeAdapater()) .registerTypeAdapter(Vector3d.class, new Vector3dTypeAdapater())
.registerTypeAdapter(Quaterniond.class, new QuaterniondTypeAdapater()) .registerTypeAdapter(Quaterniond.class, new QuaterniondTypeAdapater())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.registerTypeHierarchyAdapter(KeyframeType.class, new KeyframeRegistry.TypeAdapter()) .registerTypeHierarchyAdapter(KeyframeType.class, new KeyframeRegistry.TypeAdapter())
.registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter()) .registerTypeAdapter(CameraKeyframe.class, new CameraKeyframe.TypeAdapter())
@@ -1,8 +1,9 @@
package com.moulberry.flashback; package com.moulberry.flashback;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import org.joml.Math;
import org.joml.Quaterniond; import org.joml.Quaterniond;
import org.joml.Quaternionf; import org.joml.Vector3d;
public class Interpolation { public class Interpolation {
@@ -16,11 +17,8 @@ public class Interpolation {
public static float linearAngle(float from, float to, float amount) { public static float linearAngle(float from, float to, float amount) {
return from + Mth.wrapDegrees(to - from) * amount; float delta = Mth.wrapDegrees(to - from);
} return from + Math.max(-180, Math.min(180, delta * amount));
public static Quaterniond linear(Quaterniond from, Quaterniond to, float amount) {
return from.slerp(to, amount, new Quaterniond());
} }
} }
@@ -1,9 +1,11 @@
package com.moulberry.flashback; package com.moulberry.flashback;
import com.moulberry.flashback.playback.ReplayServer;
import it.unimi.dsi.fastutil.objects.Object2FloatFunction; import it.unimi.dsi.fastutil.objects.Object2FloatFunction;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Random; import java.util.Random;
public class Utils { public class Utils {
@@ -158,4 +160,24 @@ public class Utils {
} }
} }
public static int exportSequenceCount = 1;
public static String resolveFilenameTemplate(String template) {
LocalDateTime dateTime = LocalDateTime.now();
dateTime = dateTime.withNano(0);
String date = dateTime.toLocalDate().toString();
String time = dateTime.toLocalTime().toString();
String replay = "unknown";
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
replay = replayServer.getMetadata().name;
}
return template
.replace("%date%", date)
.replace("%time%", time)
.replace("%replay%", replay)
.replace("%seq%", ""+exportSequenceCount);
}
} }
@@ -0,0 +1,49 @@
package com.moulberry.flashback;
import com.mojang.blaze3d.platform.Window;
import org.lwjgl.glfw.GLFW;
public class WindowSizeTracker {
/**
* Some mods (e.g. qdaa) like to manipulate the framebuffer width
* This can cause rendering issues since we don't know the real width
* This helper will cache and calculate the real framebuffer width to avoid this issue
*/
private static int lastFramebufferWidth;
private static int lastFramebufferHeight;
private static int realFramebufferWidth;
private static int realFramebufferHeight;
public static int getWidth(Window window) {
if (lastFramebufferWidth != window.framebufferWidth) {
recalculate(window);
}
return realFramebufferWidth;
}
public static int getHeight(Window window) {
if (lastFramebufferHeight != window.framebufferHeight) {
recalculate(window);
}
return realFramebufferHeight;
}
private static void recalculate(Window window) {
// Calculate real framebuffer width/height
int[] width = new int[1];
int[] height = new int[1];
GLFW.glfwGetFramebufferSize(window.getWindow(), width, height);
realFramebufferWidth = width[0] > 0 ? width[0] : 1;
realFramebufferHeight = height[0] > 0 ? height[0] : 1;
// Update cached values
lastFramebufferWidth = window.framebufferWidth;
lastFramebufferHeight = window.framebufferHeight;
}
}
@@ -11,7 +11,7 @@ import java.util.List;
public enum AudioCodec implements ComboOption { public enum AudioCodec implements ComboOption {
AAC("AAC", avcodec.AV_CODEC_ID_AAC), AAC("AAC", avcodec.AV_CODEC_ID_AAC),
FLAC("FLAC", avcodec.AV_CODEC_ID_FLAC), // FLAC("FLAC", avcodec.AV_CODEC_ID_FLAC), // Removed because it doesn't support fltp sample format
MP3("MP3", avcodec.AV_CODEC_ID_MP3), MP3("MP3", avcodec.AV_CODEC_ID_MP3),
OPUS("Opus", avcodec.AV_CODEC_ID_OPUS), OPUS("Opus", avcodec.AV_CODEC_ID_OPUS),
VORBIS("Vorbis", avcodec.AV_CODEC_ID_VORBIS); VORBIS("Vorbis", avcodec.AV_CODEC_ID_VORBIS);
@@ -0,0 +1,87 @@
package com.moulberry.flashback.compat;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayServer;
import com.seibel.distanthorizons.api.DhApi;
import com.seibel.distanthorizons.api.interfaces.override.levelHandling.IDhApiSaveStructure;
import com.seibel.distanthorizons.api.interfaces.world.IDhApiLevelWrapper;
import com.seibel.distanthorizons.api.methods.events.DhApiEventRegister;
import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiLevelLoadEvent;
import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiWorldLoadEvent;
import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiWorldUnloadEvent;
import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiEventParam;
import com.seibel.distanthorizons.core.api.internal.SharedApi;
import com.seibel.distanthorizons.core.level.IDhLevel;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class DistantHorizonsSupport {
private static boolean boundReplaySaveStructure = false;
private static class ReplayDhSaveStructure implements IDhApiSaveStructure {
public final Map<String, File> pathOverrides = new HashMap<>();
@Override
public File overrideFilePath(File file, IDhApiLevelWrapper iDhApiLevelWrapper) {
return this.pathOverrides.get(iDhApiLevelWrapper.getDimensionName());
}
}
private static final ReplayDhSaveStructure REPLAY_SAVE_STRUCTURE = new ReplayDhSaveStructure();
public static void register() {
DhApiEventRegister.on(DhApiWorldLoadEvent.class, new DhApiWorldLoadEvent() {
@Override
public void onLevelLoad(DhApiEventParam<EventParam> dhApiEventParam) {
if (Flashback.isInReplay()) {
Flashback.LOGGER.info("Forcing Distant Horizons to read-only because we're inside a replay");
DhApi.Delayed.worldProxy.setReadOnly(true);
Flashback.LOGGER.info("Binding IDhApiSaveStructure to REPLAY_SAVE_STRUCTURE");
ReplayServer replayServer = Flashback.getReplayServer();
REPLAY_SAVE_STRUCTURE.pathOverrides.clear();
REPLAY_SAVE_STRUCTURE.pathOverrides.putAll(replayServer.getMetadata().distantHorizonPaths);
DhApi.overrides.bind(IDhApiSaveStructure.class, REPLAY_SAVE_STRUCTURE);
boundReplaySaveStructure = true;
}
}
});
DhApiEventRegister.on(DhApiWorldUnloadEvent.class, new DhApiWorldUnloadEvent() {
@Override
public void onLevelUnload(DhApiEventParam<EventParam> dhApiEventParam) {
if (boundReplaySaveStructure) {
Flashback.LOGGER.info("Unbinding IDhApiSaveStructure from REPLAY_SAVE_STRUCTURE");
DhApi.overrides.unbind(IDhApiSaveStructure.class, REPLAY_SAVE_STRUCTURE);
boundReplaySaveStructure = false;
}
}
});
DhApiEventRegister.on(DhApiLevelLoadEvent.class, new DhApiLevelLoadEvent() {
@Override
public void onLevelLoad(DhApiEventParam<EventParam> dhApiEventParam) {
if (Flashback.RECORDER != null) {
Flashback.RECORDER.putDistantHorizonsPaths(getDimensionPaths());
}
}
});
}
public static Map<String, File> getDimensionPaths() {
Map<String, File> paths = new HashMap<>();
for (IDhLevel level : SharedApi.getIDhClientWorld().getAllLoadedLevels()) {
File file = level.getSaveStructure().getSaveFolder(level.getLevelWrapper());
String dimensionName = level.getLevelWrapper().getDimensionName();
paths.put(dimensionName, file);
}
return paths;
}
}
@@ -4,6 +4,7 @@ import com.mojang.serialization.Codec;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.client.OptionInstance; import net.minecraft.client.OptionInstance;
@@ -74,6 +75,10 @@ public class FlashbackConfig {
public boolean flightLockYaw = false; public boolean flightLockYaw = false;
public boolean flightLockPitch = false; public boolean flightLockPitch = false;
public List<String> recentReplays = new ArrayList<>();
public String defaultExportFilename = "%date%T%time%";
public InterpolationType defaultInterpolationType = InterpolationType.SMOOTH;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public OptionInstance<?>[] createOptionInstances() { public OptionInstance<?>[] createOptionInstances() {
List<OptionInstance<?>> options = new ArrayList<>(); List<OptionInstance<?>> options = new ArrayList<>();
@@ -219,10 +224,17 @@ public class FlashbackConfig {
if (Files.exists(primary)) { if (Files.exists(primary)) {
try { try {
Files.move(primary, backup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); // Ensure primary can be loaded before backing it up
} catch (IOException e) { // Don't want to back up a bad config now, do we?
Flashback.LOGGER.error("Failed to backup config", e); load(primary);
}
// Try to back up the config
try {
Files.move(primary, backup, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to backup config", e);
}
} catch (Exception ignored) {}
} }
this.save(primary); this.save(primary);
@@ -367,8 +367,10 @@ public class CustomImGuiImplGlfw {
Minecraft.getInstance().options.keyLeft.matches(key, scancode) || Minecraft.getInstance().options.keyLeft.matches(key, scancode) ||
Minecraft.getInstance().options.keyDown.matches(key, scancode) || Minecraft.getInstance().options.keyDown.matches(key, scancode) ||
Minecraft.getInstance().options.keyRight.matches(key, scancode) || Minecraft.getInstance().options.keyRight.matches(key, scancode) ||
Minecraft.getInstance().options.keyJump.matches(key, scancode) ||
Minecraft.getInstance().options.keyChat.matches(key, scancode) || Minecraft.getInstance().options.keyChat.matches(key, scancode) ||
Minecraft.getInstance().options.keyCommand.matches(key, scancode)) { Minecraft.getInstance().options.keyCommand.matches(key, scancode)) {
ReplayUI.focusMainWindowCounter = 5;
passToMinecraft = true; passToMinecraft = true;
} }
@@ -364,11 +364,20 @@ public class ImGuiHelper {
focusLastIndex = 0; focusLastIndex = 0;
} }
if (ImGui.inputInt("", imInt, 0)) { if (ImGui.inputInt("", imInt, 0)) {
valueChanged = true; valueChanged = true;
value[i] = imInt.get(); value[i] = imInt.get();
} }
if (ImGui.isItemHovered()) {
int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel());
if (scroll != 0) {
valueChanged = true;
value[i] += 1;
}
}
if (!handledFocusNext && ImGui.isItemActive() && ImGui.isKeyPressed(GLFW.GLFW_KEY_TAB, false)) { if (!handledFocusNext && ImGui.isItemActive() && ImGui.isKeyPressed(GLFW.GLFW_KEY_TAB, false)) {
handledFocusNext = true; handledFocusNext = true;
if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) { if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) {
@@ -429,11 +438,19 @@ public class ImGuiHelper {
focusLastIndex = 0; focusLastIndex = 0;
} }
int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel());
if (ImGui.inputFloat("", imFloat, 0)) { if (ImGui.inputFloat("", imFloat, 0)) {
valueChanged = true; valueChanged = true;
value[i] = imFloat.get(); value[i] = imFloat.get();
} }
if (ImGui.isItemHovered()) {
if (scroll != 0) {
valueChanged = true;
value[i] = Math.round(value[i] + scroll);
}
}
if (!handledFocusNext && ImGui.isItemActive() && ImGui.isKeyPressed(GLFW.GLFW_KEY_TAB, false)) { if (!handledFocusNext && ImGui.isItemActive() && ImGui.isKeyPressed(GLFW.GLFW_KEY_TAB, false)) {
handledFocusNext = true; handledFocusNext = true;
if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) { if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) {
@@ -5,8 +5,10 @@ import com.mojang.blaze3d.platform.TextureUtil;
import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.editor.ui.windows.ExportQueueWindow; import com.moulberry.flashback.editor.ui.windows.ExportQueueWindow;
import com.moulberry.flashback.editor.ui.windows.ExportScreenshotWindow;
import com.moulberry.flashback.editor.ui.windows.MovementWindow; import com.moulberry.flashback.editor.ui.windows.MovementWindow;
import com.moulberry.flashback.editor.ui.windows.PlayerListWindow; import com.moulberry.flashback.editor.ui.windows.PlayerListWindow;
import com.moulberry.flashback.editor.ui.windows.PreferencesWindow;
import com.moulberry.flashback.editor.ui.windows.SelectedEntityPopup; import com.moulberry.flashback.editor.ui.windows.SelectedEntityPopup;
import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.EditorStateManager;
@@ -65,7 +67,7 @@ public class ReplayUI {
public static int viewportSizeY = 1; public static int viewportSizeY = 1;
private static boolean activeLastFrame = false; private static boolean activeLastFrame = false;
private static int focusMainWindowCounter = 0; public static int focusMainWindowCounter = 0;
public static boolean hasAnyPopupOpen = false; public static boolean hasAnyPopupOpen = false;
@@ -535,10 +537,19 @@ public class ReplayUI {
ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
} }
char controlIcon = Minecraft.ON_OSX ? '\u2318' : '\u2303';
MainMenuBar.render(); MainMenuBar.render();
// The main menu bar can disconnect us, so make sure to check if the UI should still be active here
if (!isActiveInternal()) {
ImGui.render();
ImGuiHelper.endFrame();
transitionActiveState(false);
imguiGlfw.updateReleaseAllKeys(true);
focusMainWindowCounter = 5;
return;
}
// Setup docking // Setup docking
ImGui.setNextWindowBgAlpha(0); ImGui.setNextWindowBgAlpha(0);
int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode); int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode);
@@ -671,15 +682,16 @@ public class ReplayUI {
if (selectedEntity != null) { if (selectedEntity != null) {
Entity entity = Minecraft.getInstance().level.getEntities().get(selectedEntity); Entity entity = Minecraft.getInstance().level.getEntities().get(selectedEntity);
if (entity == null) { if (entity == null || editorState == null) {
selectedEntity = null; selectedEntity = null;
} else if (entity instanceof Player && editorState != null && !editorState.replayVisuals.renderPlayers) { } else if (entity instanceof Player && !editorState.replayVisuals.renderPlayers) {
selectedEntity = null; selectedEntity = null;
} else if (!(entity instanceof Player) && editorState != null && !editorState.replayVisuals.renderEntities) { } else if (!(entity instanceof Player) && !editorState.replayVisuals.renderEntities) {
selectedEntity = null; selectedEntity = null;
} else { } else {
if (openSelectedEntityPopup) { if (openSelectedEntityPopup) {
ImGui.openPopup("###EntityPopup"); ImGui.openPopup("###EntityPopup");
SelectedEntityPopup.open(entity, editorState);
} }
if (ImGuiHelper.beginPopup("###EntityPopup")) { if (ImGuiHelper.beginPopup("###EntityPopup")) {
@@ -728,6 +740,8 @@ public class ReplayUI {
VisualsWindow.render(); VisualsWindow.render();
TimelineWindow.render(); TimelineWindow.render();
StartExportWindow.render(); StartExportWindow.render();
ExportScreenshotWindow.render();
PreferencesWindow.render();
ExportQueueWindow.render(); ExportQueueWindow.render();
PlayerListWindow.render(); PlayerListWindow.render();
MovementWindow.render(); MovementWindow.render();
@@ -0,0 +1,108 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.combo_options.VideoCodec;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.exporting.ExportSettings;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import imgui.ImGui;
import imgui.flag.ImGuiWindowFlags;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import java.nio.file.Path;
public class ExportScreenshotWindow {
private static boolean open = false;
private static boolean close = false;
private static final int[] resolution = new int[]{1920, 1080};
public static void render() {
if (open) {
open = false;
ImGui.openPopup("###ExportScreenshot");
}
if (ImGuiHelper.beginPopupModalCloseable("Export screenshot###ExportScreenshot", ImGuiWindowFlags.AlwaysAutoResize)) {
if (close) {
close = false;
ImGui.closeCurrentPopup();
ImGuiHelper.endPopupModalCloseable();
return;
}
ImGuiHelper.inputInt("Resolution", resolution);
resolution[0] = Math.max(1, resolution[0]);
resolution[1] = Math.max(1, resolution[1]);
EditorState editorState = EditorStateManager.getCurrent();
if (ImGui.checkbox("SSAA", StartExportWindow.ssaa)) {
StartExportWindow.ssaa = !StartExportWindow.ssaa;
}
ImGuiHelper.tooltip("Supersampling Anti-Aliasing: Remove jagged edges by rendering the game at double resolution and downscaling");
ImGui.sameLine();
if (ImGui.checkbox("No GUI", StartExportWindow.noGui)) {
StartExportWindow.noGui = !StartExportWindow.noGui;
}
ImGuiHelper.tooltip("Removes all UI from the screen, rendering only the world");
if (editorState != null && !editorState.replayVisuals.renderSky) {
if (ImGui.checkbox("Transparent Sky", StartExportWindow.transparentBackground)) {
StartExportWindow.transparentBackground = !StartExportWindow.transparentBackground;
}
}
if (editorState != null && ImGui.button("Take Screenshot")) {
String defaultName = StartExportWindow.getDefaultFilename(null, "png");
String defaultExportPathString = StartExportWindow.defaultExportPath.toString();
AsyncFileDialogs.saveFileDialog(defaultExportPathString, defaultName, "PNG", "png").thenAccept(pathStr -> {
if (pathStr != null) {
Path path = Path.of(pathStr);
StartExportWindow.defaultExportPath = path.getParent();
LocalPlayer player = Minecraft.getInstance().player;
int tick = Flashback.getReplayServer().getReplayTick();
boolean transparent = StartExportWindow.transparentBackground && !editorState.replayVisuals.renderSky;
boolean ssaa = StartExportWindow.ssaa;
boolean noGui = StartExportWindow.noGui;
EditorState copiedEditorState = editorState.copy();
copiedEditorState.keyframeTracks.clear();
ExportSettings settings = new ExportSettings(null, copiedEditorState,
player.position(), player.getYRot(), player.getXRot(),
resolution[0], resolution[1], tick, tick,
1, false, VideoContainer.PNG_SEQUENCE, null, null, 0, transparent, ssaa, noGui,
false, false, null,
path);
close = true;
Utils.exportSequenceCount += 1;
Flashback.EXPORT_JOB = new ExportJob(settings);
}
});
}
ImGuiHelper.endPopupModalCloseable();
}
close = false;
}
public static void open() {
open = true;
}
}
@@ -1,9 +1,16 @@
package com.moulberry.flashback.editor.ui.windows; package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.exporting.ExportJobQueue; import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.screen.SelectReplayScreen;
import imgui.ImGui; import imgui.ImGui;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.TitleScreen;
import java.nio.file.Files;
import java.nio.file.Path;
public class MainMenuBar { public class MainMenuBar {
@@ -15,15 +22,63 @@ public class MainMenuBar {
} }
public static void renderInner() { public static void renderInner() {
if (ImGui.menuItem("Export Video")) { FlashbackConfig config = Flashback.getConfig();
StartExportWindow.open();
}
if (!ExportJobQueue.queuedJobs.isEmpty()) { if (ImGui.beginMenu("File")) {
String name = "Export Queue (" + ExportJobQueue.count() + ")"; if (ImGui.menuItem("Export Video")) {
if (ImGui.menuItem(name + "###QueuedJobs")) { StartExportWindow.open();
ExportQueueWindow.open();
} }
if (!ExportJobQueue.queuedJobs.isEmpty()) {
String name = "Export Queue (" + ExportJobQueue.count() + ")";
if (ImGui.menuItem(name + "###QueuedJobs")) {
ExportQueueWindow.open();
}
}
if (ImGui.menuItem("Export Screenshot")) {
ExportScreenshotWindow.open();
}
ImGui.separator();
if (ImGui.menuItem("Open Replay")) {
Flashback.openReplayFromFileBrowser();
}
if (!config.recentReplays.isEmpty()) {
if (ImGui.beginMenu("Open Recent")) {
Path replayFolder = Flashback.getReplayFolder();
for (String recentReplay : config.recentReplays) {
Path path = Path.of(recentReplay);
if (Files.exists(path)) {
String display = path.toString();
try {
Path relative = replayFolder.relativize(path);
String relativeStr = relative.toString();
if (!relativeStr.contains("..")) {
display = relativeStr;
}
} catch (Exception ignored) {}
if (ImGui.menuItem(display)) {
Flashback.openReplayWorld(path);
break;
}
}
}
ImGui.endMenu();
}
}
if (ImGui.menuItem("Exit Replay")) {
Minecraft minecraft = Minecraft.getInstance();
if (minecraft.level != null) {
minecraft.level.disconnect();
}
minecraft.disconnect();
minecraft.setScreen(new SelectReplayScreen(new TitleScreen()));
}
ImGui.endMenu();
}
if (ImGui.menuItem("Preferences")) {
PreferencesWindow.open();
} }
ImGui.separator(); ImGui.separator();
@@ -0,0 +1,73 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.exporting.ExportSettings;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import imgui.ImGui;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImShort;
import imgui.type.ImString;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import java.nio.file.Path;
public class PreferencesWindow {
private static boolean open = false;
private static boolean close = false;
public static void render() {
if (open) {
open = false;
ImGui.openPopup("###Preferences");
}
boolean wasOpen = ImGui.isPopupOpen("###Preferences");
if (ImGuiHelper.beginPopupModalCloseable("Preferences###Preferences", ImGuiWindowFlags.AlwaysAutoResize)) {
if (close) {
close = false;
ImGui.closeCurrentPopup();
ImGuiHelper.endPopupModalCloseable();
return;
}
FlashbackConfig config = Flashback.getConfig();
// Exporting
ImGuiHelper.separatorWithText("Exporting");
ImString imString = ImGuiHelper.createResizableImString(config.defaultExportFilename);
if (ImGui.inputText("Export Filename", imString)) {
config.defaultExportFilename = ImGuiHelper.getString(imString);
}
ImGuiHelper.tooltip("The default filename when exporting\nVariables:\n\t%date%\tyear-month-day\n\t%time%\thh_mm_ss\n\t%replay%\tReplay name\n\t%seq%\tExport count for this session");
// Keyframes
ImGuiHelper.separatorWithText("Keyframes");
config.defaultInterpolationType = ImGuiHelper.enumCombo("Default Interpolation", config.defaultInterpolationType);
ImGuiHelper.endPopupModalCloseable();
}
if (wasOpen && !ImGui.isPopupOpen("###Preferences")) {
Flashback.getConfig().saveToDefaultFolder();
}
close = false;
}
public static void open() {
open = true;
}
}
@@ -1,17 +1,43 @@
package com.moulberry.flashback.editor.ui.windows; package com.moulberry.flashback.editor.ui.windows;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.yggdrasil.ProfileResult;
import com.moulberry.flashback.editor.ui.ImGuiHelper; import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorState;
import imgui.ImGui; import imgui.ImGui;
import imgui.type.ImString; import imgui.type.ImString;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.commands.arguments.EntityAnchorArgument; import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import java.util.UUID; import java.util.UUID;
public class SelectedEntityPopup { public class SelectedEntityPopup {
private static ImString changeSkinInput = ImGuiHelper.createResizableImString("");
static {
changeSkinInput.inputData.allowedChars = "0123456789abcdef-";
}
private static ImString changeNameInput = ImGuiHelper.createResizableImString("");
public static void open(Entity entity, EditorState editorState) {
String nameOverride = editorState.nameOverride.get(entity.getUUID());
if (nameOverride != null) {
changeNameInput.set(nameOverride);
} else {
changeNameInput.set("");
}
GameProfile skinOverride = editorState.skinOverride.get(entity.getUUID());
if (skinOverride != null) {
changeSkinInput.set(skinOverride.getId().toString());
} else {
changeSkinInput.set("");
}
}
public static void render(Entity entity, EditorState editorState) { public static void render(Entity entity, EditorState editorState) {
UUID uuid = entity.getUUID(); UUID uuid = entity.getUUID();
ImGui.text("Entity: " + uuid); ImGui.text("Entity: " + uuid);
@@ -45,6 +71,57 @@ public class SelectedEntityPopup {
editorState.markDirty(); editorState.markDirty();
} }
if (!isHiddenDuringExport && entity instanceof Player player) {
boolean hideNametag = editorState.hideNametags.contains(entity.getUUID());
if (ImGui.checkbox("Render Nametag", !hideNametag)) {
if (hideNametag) {
editorState.hideNametags.remove(entity.getUUID());
} else {
editorState.hideNametags.add(entity.getUUID());
}
}
if (!hideNametag) {
boolean changedName = ImGui.inputTextWithHint("Name##SetNameInput", player.getScoreboardName(), changeNameInput);
if (changedName) {
String string = ImGuiHelper.getString(changeNameInput);
if (string.isEmpty()) {
editorState.nameOverride.remove(entity.getUUID());
} else {
editorState.nameOverride.put(entity.getUUID(), string);
}
}
}
ImGuiHelper.separatorWithText("Change Skin & Cape (UUID)");
ImGui.setNextItemWidth(320);
ImGui.inputTextWithHint("##SetSkinInput", "e.g. d0e05de7-6067-454d-beae-c6d19d886191", changeSkinInput);
boolean hasApplySkin = false;
if (!changeSkinInput.isEmpty()) {
String string = ImGuiHelper.getString(changeSkinInput);
try {
UUID changeSkinUuid = UUID.fromString(string);
if (ImGui.button("Apply Skin")) {
ProfileResult profile = Minecraft.getInstance().getMinecraftSessionService().fetchProfile(changeSkinUuid, true);
editorState.skinOverride.put(entity.getUUID(), profile.profile());
}
hasApplySkin = true;
} catch (Exception ignored) {}
}
if (editorState.skinOverride.containsKey(entity.getUUID())) {
if (hasApplySkin) {
ImGui.sameLine();
}
if (ImGui.button("Reset Skin")) {
editorState.skinOverride.remove(entity.getUUID());
changeSkinInput.set("");
}
}
}
// ImGui.sameLine(); // ImGui.sameLine();
// ImGui.button("Track Entity"); // ImGui.button("Track Entity");
// //
@@ -2,6 +2,7 @@ package com.moulberry.flashback.editor.ui.windows;
import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.combo_options.AspectRatio; import com.moulberry.flashback.combo_options.AspectRatio;
import com.moulberry.flashback.combo_options.AudioCodec; import com.moulberry.flashback.combo_options.AudioCodec;
import com.moulberry.flashback.combo_options.Sizing; import com.moulberry.flashback.combo_options.Sizing;
@@ -22,6 +23,7 @@ import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.FileUtil; import net.minecraft.FileUtil;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.player.LocalPlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.nio.file.Files; import java.nio.file.Files;
@@ -43,8 +45,8 @@ public class StartExportWindow {
private static final int[] startEndTick = new int[]{0, 100}; private static final int[] startEndTick = new int[]{0, 100};
private static final float[] framerate = new float[]{60}; private static final float[] framerate = new float[]{60};
private static boolean resetRng = false; private static boolean resetRng = false;
private static boolean ssaa = false; public static boolean ssaa = false;
private static boolean noGui = false; public static boolean noGui = false;
private static VideoContainer[] supportedContainers = null; private static VideoContainer[] supportedContainers = null;
private static VideoContainer[] supportedContainersWithTransparency = null; private static VideoContainer[] supportedContainersWithTransparency = null;
@@ -56,11 +58,11 @@ public class StartExportWindow {
private static final ImString bitrate = ImGuiHelper.createResizableImString("20m"); private static final ImString bitrate = ImGuiHelper.createResizableImString("20m");
private static boolean recordAudio = false; private static boolean recordAudio = false;
private static boolean transparentBackground = false; public static boolean transparentBackground = false;
private static AudioCodec audioCodec = AudioCodec.AAC; private static AudioCodec audioCodec = AudioCodec.AAC;
private static boolean stereoAudio = false; private static boolean stereoAudio = false;
private static Path defaultExportPath = null; public static Path defaultExportPath = null;
private static final ImString jobName = ImGuiHelper.createResizableImString(""); private static final ImString jobName = ImGuiHelper.createResizableImString("");
private static String installedIncompatibleModsString = null; private static String installedIncompatibleModsString = null;
@@ -229,6 +231,7 @@ public class StartExportWindow {
createExportSettings(null).thenAccept(settings -> { createExportSettings(null).thenAccept(settings -> {
if (settings != null) { if (settings != null) {
close = true; close = true;
Utils.exportSequenceCount += 1;
Flashback.EXPORT_JOB = new ExportJob(settings); Flashback.EXPORT_JOB = new ExportJob(settings);
} }
}); });
@@ -247,6 +250,7 @@ public class StartExportWindow {
createExportSettings(ImGuiHelper.getString(jobName)).thenAccept(settings -> { createExportSettings(ImGuiHelper.getString(jobName)).thenAccept(settings -> {
if (settings != null) { if (settings != null) {
close = true; close = true;
Utils.exportSequenceCount += 1;
ExportJobQueue.queuedJobs.add(settings); ExportJobQueue.queuedJobs.add(settings);
} }
}); });
@@ -351,24 +355,7 @@ public class StartExportWindow {
numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate)); numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
} }
if (defaultExportPath == null || !Files.exists(defaultExportPath)) { String defaultName = getDefaultFilename(name, container.extension());
defaultExportPath = FabricLoader.getInstance().getGameDir();
}
String defaultName = null;
if (name != null) {
try {
defaultName = FileUtil.findAvailableName(defaultExportPath, name, "." + container.extension());
} catch (Exception ignored) {}
}
if (defaultName == null) {
try {
defaultName = FileUtil.findAvailableName(defaultExportPath, "output", "." + container.extension());
} catch (Exception ignored) {}
}
if (defaultName == null) {
defaultName = "output." + container.extension();
}
Function<String, ExportSettings> callback = pathStr -> { Function<String, ExportSettings> callback = pathStr -> {
if (pathStr != null) { if (pathStr != null) {
@@ -432,6 +419,30 @@ public class StartExportWindow {
} }
public static @NotNull String getDefaultFilename(@Nullable String name, String extension) {
if (defaultExportPath == null || !Files.exists(defaultExportPath)) {
defaultExportPath = FabricLoader.getInstance().getGameDir();
}
String defaultName = null;
if (name != null) {
try {
defaultName = FileUtil.findAvailableName(defaultExportPath, name, "." + extension);
} catch (Exception ignored) {}
}
if (defaultName == null) {
String desiredName = Utils.resolveFilenameTemplate(Flashback.getConfig().defaultExportFilename);
try {
defaultName = FileUtil.findAvailableName(defaultExportPath, desiredName, "." + extension);
} catch (Exception ignored) {}
}
if (defaultName == null) {
String desiredName = Utils.resolveFilenameTemplate(Flashback.getConfig().defaultExportFilename);
defaultName = desiredName + "." + extension;
}
return defaultName;
}
private static int stringToBitrate(String string) { private static int stringToBitrate(String string) {
int number = 0; int number = 0;
int modifier = 1; int modifier = 1;
@@ -27,15 +27,12 @@ import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.state.KeyframeTrack; import com.moulberry.flashback.state.KeyframeTrack;
import imgui.ImDrawList; import imgui.ImDrawList;
import imgui.ImGui; import imgui.ImGui;
import imgui.flag.ImGuiButtonFlags;
import imgui.flag.ImGuiHoveredFlags; import imgui.flag.ImGuiHoveredFlags;
import imgui.flag.ImGuiMouseButton; import imgui.flag.ImGuiMouseButton;
import imgui.flag.ImGuiMouseCursor; import imgui.flag.ImGuiMouseCursor;
import imgui.flag.ImGuiPopupFlags; import imgui.flag.ImGuiPopupFlags;
import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiStyleVar;
import imgui.flag.ImGuiWindowFlags; import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImFloat;
import imgui.type.ImInt;
import it.unimi.dsi.fastutil.ints.*; import it.unimi.dsi.fastutil.ints.*;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
@@ -60,6 +57,9 @@ public class TimelineWindow {
private static boolean enableKeyframeMovement = false; private static boolean enableKeyframeMovement = false;
private static int grabbedKeyframeTick = 0; private static int grabbedKeyframeTick = 0;
private static int grabbedKeyframeTrack = 0; private static int grabbedKeyframeTrack = 0;
private static int draggingMouseButton = ImGuiMouseButton.Left;
private static float dragStartMouseX = 0;
private static float dragStartMouseY = 0;
private static boolean trackDisabledButtonDrag = false; private static boolean trackDisabledButtonDrag = false;
private static boolean trackDisabledButtonDragValue = false; private static boolean trackDisabledButtonDragValue = false;
@@ -130,7 +130,11 @@ public class TimelineWindow {
boolean hoveredBody = mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height; boolean hoveredBody = mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height;
ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0); ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0);
boolean timelineVisible = ImGui.begin("Timeline (" + timestamp + "/" + cursorTicks + ")###Timeline", hoveredBody ? ImGuiWindowFlags.NoMove : ImGuiWindowFlags.None); int flags = ImGuiWindowFlags.NoScrollWithMouse | ImGuiWindowFlags.NoScrollbar;
if (hoveredBody) {
flags |= ImGuiWindowFlags.NoMove;
}
boolean timelineVisible = ImGui.begin("Timeline (" + timestamp + "/" + cursorTicks + ")###Timeline", flags);
ImGuiHelper.popStyleVar(); ImGuiHelper.popStyleVar();
cursorTicks = replayServer.getReplayTick(); cursorTicks = replayServer.getReplayTick();
@@ -223,23 +227,7 @@ public class TimelineWindow {
boolean isShiftDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT); boolean isShiftDown = ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT);
if (isShiftDown) { if (isShiftDown) {
int closestTick = -1; int closestTick = findClosestKeyframeForSnap(editorState, cursorTicks);
for (KeyframeTrack track : editorState.keyframeTracks) {
Integer floor = track.keyframesByTick.floorKey(cursorTicks);
Integer ceil = track.keyframesByTick.ceilingKey(cursorTicks);
float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor);
float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil);
Integer closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE);
if (closest != null) {
if (closestTick == -1) {
closestTick = closest;
} else if (Math.abs(closest - cursorTicks) < Math.abs(closestTick - cursorTicks)) {
closestTick = closest;
}
}
}
if (closestTick != -1) { if (closestTick != -1) {
cursorTicks = closestTick; cursorTicks = closestTick;
} }
@@ -272,7 +260,7 @@ public class TimelineWindow {
drawList.addLine(x + middleX, y + timestampHeight, x + middleX, y + height, -1); drawList.addLine(x + middleX, y + timestampHeight, x + middleX, y + height, -1);
// Middle divider (y) // Middle divider (y)
drawList.addLine(0, y + middleY, width, y + middleY, -1); drawList.addLine(x, y + middleY, x + width, y + middleY, -1);
renderKeyframeElements(replayServer, editorState, x, y + middleY, cursorTicks, middleX); renderKeyframeElements(replayServer, editorState, x, y + middleY, cursorTicks, middleX);
@@ -433,58 +421,81 @@ public class TimelineWindow {
editingKeyframeTick = -1; editingKeyframeTick = -1;
} }
if (mouseX > x + middleX && mouseX < x + width && mouseY > y && mouseY < y + height) {
int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel());
double mousePercentage = (mouseX - (x + middleX)) / (width - middleX);
if (scroll > 0) {
double zoomDelta = editorState.zoomMax - editorState.zoomMin;
if (zoomDelta > 0.001) {
editorState.zoomMin += zoomDelta * 0.05 * mousePercentage;
editorState.zoomMax -= zoomDelta * 0.05 * (1 - mousePercentage);
editorState.markDirty();
}
} else if (scroll < 0) {
double zoomDelta = editorState.zoomMax - editorState.zoomMin;
editorState.zoomMin = Math.max(0, editorState.zoomMin - zoomDelta * 0.05/0.9 * mousePercentage);
editorState.zoomMax = Math.min(1, editorState.zoomMax + zoomDelta * 0.05/0.9 * (1 - mousePercentage));
editorState.markDirty();
}
}
boolean shouldProcessInput = !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup) && !ImGui.getIO().getWantTextInput(); boolean shouldProcessInput = !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup) && !ImGui.getIO().getWantTextInput();
if (shouldProcessInput) { if (shouldProcessInput) {
int scroll = (int) Math.signum(ImGui.getIO().getMouseWheel());
if (scroll != 0 && mouseX > x + middleX && mouseX < x + width && mouseY > y && mouseY < y + height) {
double mousePercentage = (mouseX - (x + middleX)) / (width - middleX);
if (scroll > 0) {
double zoomDelta = editorState.zoomMax - editorState.zoomMin;
if (zoomDelta > 0.001) {
editorState.zoomMin += zoomDelta * 0.05 * mousePercentage;
editorState.zoomMax -= zoomDelta * 0.05 * (1 - mousePercentage);
editorState.markDirty();
}
} else if (scroll < 0) {
double zoomDelta = editorState.zoomMax - editorState.zoomMin;
editorState.zoomMin = Math.max(0, editorState.zoomMin - zoomDelta * 0.05/0.9 * mousePercentage);
editorState.zoomMax = Math.min(1, editorState.zoomMax + zoomDelta * 0.05/0.9 * (1 - mousePercentage));
editorState.markDirty();
}
}
handleKeyPresses(replayServer, cursorTicks, editorState, totalTicks); handleKeyPresses(replayServer, cursorTicks, editorState, totalTicks);
boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left); boolean leftClicked = ImGui.isMouseClicked(ImGuiMouseButton.Left);
boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right); boolean rightClicked = ImGui.isMouseClicked(ImGuiMouseButton.Right);
if (leftClicked || rightClicked) { if (leftClicked || rightClicked) {
handleClick(editorState, replayServer, totalTicks); handleClick(editorState, replayServer, totalTicks);
} else if (ImGui.isMouseDragging(ImGuiMouseButton.Left)) { if (leftClicked) {
draggingMouseButton = ImGuiMouseButton.Left;
} else {
draggingMouseButton = ImGuiMouseButton.Right;
}
dragStartMouseX = mouseX;
dragStartMouseY = mouseY;
} else if (ImGui.isMouseDragging(draggingMouseButton)) {
if (grabbedExportBarResizeLeft) { if (grabbedExportBarResizeLeft) {
ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW);
int target = timelineXToReplayTick(mouseX - x); int target = timelineXToReplayTick(mouseX - x);
if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) {
int closestTick = findClosestKeyframeForSnap(editorState, target);
if (closestTick != -1) {
target = closestTick;
}
}
editorState.setExportTicks(target, -1, totalTicks); editorState.setExportTicks(target, -1, totalTicks);
} }
if (grabbedExportBarResizeRight) { if (grabbedExportBarResizeRight) {
ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW);
int target = timelineXToReplayTick(mouseX - x); int target = timelineXToReplayTick(mouseX - x);
if (ImGui.isKeyDown(GLFW.GLFW_KEY_LEFT_SHIFT) || ImGui.isKeyDown(GLFW.GLFW_KEY_RIGHT_SHIFT)) {
int closestTick = findClosestKeyframeForSnap(editorState, target);
if (closestTick != -1) {
target = closestTick;
}
}
editorState.setExportTicks(-1, target, totalTicks); editorState.setExportTicks(-1, target, totalTicks);
} }
if (zoomBarWidth > 1f && grabbedZoomBar) { if (zoomBarWidth > 1f && grabbedZoomBar) {
float dx = ImGui.getMouseDragDeltaX(); float dx = mouseX - dragStartMouseX;
float factor = dx / zoomBarWidth; float factor = dx / zoomBarWidth;
if (grabbedZoomBarResizeLeft) { if (grabbedZoomBarResizeLeft) {
ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW);
editorState.zoomMin = Math.max(0, Math.min(editorState.zoomMax-0.01f, zoomMinBeforeDrag + factor)); editorState.zoomMin = Math.max(0, Math.min(editorState.zoomMax - 0.01f, zoomMinBeforeDrag + factor));
} else if (grabbedZoomBarResizeRight) { } else if (grabbedZoomBarResizeRight) {
ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW); ImGui.setMouseCursor(ImGuiMouseCursor.ResizeEW);
editorState.zoomMax = Math.max(editorState.zoomMin+0.01f, Math.min(1, zoomMaxBeforeDrag + factor)); editorState.zoomMax = Math.max(editorState.zoomMin + 0.01f, Math.min(1, zoomMaxBeforeDrag + factor));
} else { } else {
ImGui.setMouseCursor(ImGuiMouseCursor.Hand); ImGui.setMouseCursor(ImGuiMouseCursor.Hand);
@@ -508,6 +519,13 @@ public class TimelineWindow {
replayServer.replayPaused = true; replayServer.replayPaused = true;
} }
} else if (zoomBarWidth > 1f && mouseY > y + middleY && mouseY < y + height && mouseX > x + middleX && mouseX < x + width && ImGui.isMouseDown(ImGuiMouseButton.Middle)) {
grabbedZoomBar = true;
draggingMouseButton = ImGuiMouseButton.Middle;
zoomMinBeforeDrag = editorState.zoomMin;
zoomMaxBeforeDrag = editorState.zoomMax;
dragStartMouseX = mouseX;
dragStartMouseY = mouseY;
} else if (!ImGui.isAnyMouseDown()) { } else if (!ImGui.isAnyMouseDown()) {
releaseGrabbed(editorState, replayServer, totalTicks); releaseGrabbed(editorState, replayServer, totalTicks);
} }
@@ -518,6 +536,27 @@ public class TimelineWindow {
ImGui.end(); ImGui.end();
} }
private static int findClosestKeyframeForSnap(EditorState editorState, int tick) {
int closestTick = -1;
for (KeyframeTrack track : editorState.keyframeTracks) {
Integer floor = track.keyframesByTick.floorKey(tick);
Integer ceil = track.keyframesByTick.ceilingKey(tick);
float floorX = floor == null ? Float.NaN : x + replayTickToTimelineX(floor);
float ceilX = ceil == null ? Float.NaN : x + replayTickToTimelineX(ceil);
Integer closest = Utils.chooseClosest(mouseX, floorX, floor, ceilX, ceil, KEYFRAME_SIZE);
if (closest != null) {
if (closestTick == -1) {
closestTick = closest;
} else if (Math.abs(closest - tick) < Math.abs(closestTick - tick)) {
closestTick = closest;
}
}
}
return closestTick;
}
private static void handleKeyPresses(ReplayServer replayServer, int cursorTicks, EditorState editorState, int totalTicks) { private static void handleKeyPresses(ReplayServer replayServer, int cursorTicks, EditorState editorState, int totalTicks) {
boolean pressedIn = ImGui.isKeyPressed(GLFW.GLFW_KEY_I, false); boolean pressedIn = ImGui.isKeyPressed(GLFW.GLFW_KEY_I, false);
boolean pressedOut = ImGui.isKeyPressed(GLFW.GLFW_KEY_O, false); boolean pressedOut = ImGui.isKeyPressed(GLFW.GLFW_KEY_O, false);
@@ -528,7 +567,7 @@ public class TimelineWindow {
boolean pressedDelete = ImGui.isKeyPressed(GLFW.GLFW_KEY_DELETE, false) || ImGui.isKeyPressed(GLFW.GLFW_KEY_BACKSPACE, false); boolean pressedDelete = ImGui.isKeyPressed(GLFW.GLFW_KEY_DELETE, false) || ImGui.isKeyPressed(GLFW.GLFW_KEY_BACKSPACE, false);
if (ImGui.isKeyPressed(GLFW.GLFW_KEY_SPACE, false)) { if (ImGui.isKeyPressed(GLFW.GLFW_KEY_P, false)) {
togglePaused(replayServer, editorState); togglePaused(replayServer, editorState);
} }
if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT, false)) { if (ImGui.isKeyPressed(GLFW.GLFW_KEY_LEFT, false)) {
@@ -1656,7 +1695,7 @@ public class TimelineWindow {
} }
private static void renderPlaybackHead(int cursorX, float x, int middleX, float width, int cursorTicks, int currentReplayTick, ImDrawList drawList, float y, int middleY, int timestampHeight, float height, int zoomBarHeight) { private static void renderPlaybackHead(int cursorX, float x, int middleX, float width, int cursorTicks, int currentReplayTick, ImDrawList drawList, float y, int middleY, int timestampHeight, float height, int zoomBarHeight) {
if (cursorX > x + middleX -10 && cursorX < x + width +10) { if (cursorX > middleX - 10 && cursorX < width +10) {
int colour = -1; int colour = -1;
if (cursorTicks < currentReplayTick) { if (cursorTicks < currentReplayTick) {
colour = 0x80FFFFFF; colour = 0x80FFFFFF;
@@ -201,6 +201,11 @@ public class VisualsWindow {
} }
} }
// Night vision
if (ImGui.checkbox("Night Vision", visuals.overrideNightVision)) {
visuals.overrideNightVision = !visuals.overrideNightVision;
}
// Camera shake // Camera shake
if (ImGui.checkbox("Camera Shake", visuals.overrideCameraShake)) { if (ImGui.checkbox("Camera Shake", visuals.overrideCameraShake)) {
visuals.overrideCameraShake = !visuals.overrideCameraShake; visuals.overrideCameraShake = !visuals.overrideCameraShake;
@@ -3,6 +3,7 @@ package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.platform.NativeImage;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow; import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.combo_options.AudioCodec;
import org.bytedeco.ffmpeg.avutil.AVFrame; import org.bytedeco.ffmpeg.avutil.AVFrame;
import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor; import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor;
import org.bytedeco.ffmpeg.global.avutil; import org.bytedeco.ffmpeg.global.avutil;
@@ -91,7 +92,7 @@ public class AsyncFFmpegVideoWriter implements AutoCloseable, VideoWriter {
int audioChannels = 0; int audioChannels = 0;
if (settings.recordAudio()) { if (settings.recordAudio()) {
if (settings.stereoAudio()) { if (settings.audioCodec() == AudioCodec.VORBIS || settings.stereoAudio()) {
audioChannels = 2; audioChannels = 2;
} else { } else {
audioChannels = 1; audioChannels = 1;
@@ -27,11 +27,16 @@ import net.minecraft.Util;
import net.minecraft.client.Camera; import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.screens.CreditsAndAttributionScreen;
import net.minecraft.client.gui.screens.WinScreen;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.FogRenderer; import net.minecraft.client.renderer.FogRenderer;
import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.util.FormattedCharSequence; import net.minecraft.util.FormattedCharSequence;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
@@ -129,6 +134,7 @@ public class ExportJob {
} }
this.running = true; this.running = true;
Minecraft.getInstance().mouseHandler.releaseMouse(); Minecraft.getInstance().mouseHandler.releaseMouse();
Minecraft.getInstance().getSoundManager().stop();
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
@@ -160,9 +166,21 @@ public class ExportJob {
this.running = false; this.running = false;
this.shouldChangeFramebufferSize = false; this.shouldChangeFramebufferSize = false;
// Reset display size
Minecraft.getInstance().options.guiScale().set(oldGuiScale); Minecraft.getInstance().options.guiScale().set(oldGuiScale);
Minecraft.getInstance().resizeDisplay(); Minecraft.getInstance().resizeDisplay();
// Refreeze server & client
replayServer.replayPaused = true;
ClientLevel level = Minecraft.getInstance().level;
if (level != null) {
level.tickRateManager().setFrozen(true);
}
Minecraft.getInstance().getSoundManager().stop();
Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.NOTE_BLOCK_CHIME, 1.0f));
Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.NOTE_BLOCK_BELL, 1.0f));
try { try {
Files.deleteIfExists(exportTempFile); Files.deleteIfExists(exportTempFile);
} catch (IOException ignored) {} } catch (IOException ignored) {}
@@ -210,7 +228,6 @@ public class ExportJob {
} }
Minecraft.getInstance().resizeDisplay(); Minecraft.getInstance().resizeDisplay();
DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate()); DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate());
int clientTickCount = 0; int clientTickCount = 0;
@@ -12,6 +12,8 @@ import org.lwjgl.system.MemoryUtil;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.FloatBuffer; import java.nio.FloatBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@@ -38,6 +40,9 @@ public class PNGSequenceVideoWriter implements VideoWriter {
} }
private Thread createEncodeThread() { private Thread createEncodeThread() {
boolean outputIsDirectory = Files.isDirectory(this.settings.output());
boolean encodeMultiple = outputIsDirectory || this.settings.startTick() != this.settings.endTick();
Thread encodeThread = new Thread(() -> { Thread encodeThread = new Thread(() -> {
while (true) { while (true) {
NativeImage src; NativeImage src;
@@ -69,8 +74,20 @@ public class PNGSequenceVideoWriter implements VideoWriter {
} }
this.sequenceNumber += 1; this.sequenceNumber += 1;
String filename = String.format("%04d.png", this.sequenceNumber);
src.writeToFile(this.settings.output().resolve(filename)); Path output = this.settings.output();
if (encodeMultiple) {
if (outputIsDirectory) {
String filename = String.format("%04d.png", this.sequenceNumber);
src.writeToFile(output.resolve(filename));
} else {
String filename = output.getFileName().toString();
filename += String.format("-%04d.png", this.sequenceNumber);
src.writeToFile(output.getParent().resolve(filename));
}
} else {
src.writeToFile(this.settings.output());
}
} catch (Throwable t) { } catch (Throwable t) {
this.threadedError.set(t); this.threadedError.set(t);
this.finishEncodeThread.set(true); this.finishEncodeThread.set(true);
@@ -1,5 +1,6 @@
package com.moulberry.flashback.exporting; package com.moulberry.flashback.exporting;
import com.moulberry.flashback.Flashback;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.PlayerInfo; import net.minecraft.client.multiplayer.PlayerInfo;
@@ -54,14 +55,14 @@ public class PerfectFrames {
if (level != null) { if (level != null) {
if (forceFrameReady) { if (forceFrameReady) {
System.err.println("Waiting for skin loading took too long, ignoring..."); Flashback.LOGGER.error("Waiting for skin loading took too long, ignoring...");
for (AbstractClientPlayer player : level.players()) { for (AbstractClientPlayer player : level.players()) {
if (player == Minecraft.getInstance().player) { if (player == Minecraft.getInstance().player) {
continue; continue;
} }
PlayerInfo playerInfo = player.getPlayerInfo(); PlayerInfo playerInfo = player.getPlayerInfo();
if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) { if (playerInfo != null && !skinManager.getOrLoad(playerInfo.getProfile()).isDone()) {
System.err.println("Took too long to load skin for " + player.getUUID()); Flashback.LOGGER.error("Took too long to load skin for {}", player.getUUID());
ignoreSkinLoading.add(player.getUUID()); ignoreSkinLoading.add(player.getUUID());
} }
} }
@@ -194,33 +194,6 @@ public class AsyncReplaySaver {
gamePacketCodec.encode(writer.friendlyByteBuf(), packet); gamePacketCodec.encode(writer.friendlyByteBuf(), packet);
writer.finishAction(ActionGamePacket.INSTANCE); writer.finishAction(ActionGamePacket.INSTANCE);
} }
if (packet instanceof ClientboundLoginPacket) {
LocalPlayer localPlayer = Minecraft.getInstance().player;
if (localPlayer != null) {
writer.startAction(ActionCreateLocalPlayer.INSTANCE);
RegistryFriendlyByteBuf registryFriendlyByteBuf = writer.friendlyByteBuf();
registryFriendlyByteBuf.writeUUID(localPlayer.getUUID());
registryFriendlyByteBuf.writeDouble(localPlayer.getX());
registryFriendlyByteBuf.writeDouble(localPlayer.getY());
registryFriendlyByteBuf.writeDouble(localPlayer.getZ());
registryFriendlyByteBuf.writeFloat(localPlayer.getXRot());
registryFriendlyByteBuf.writeFloat(localPlayer.getYRot());
registryFriendlyByteBuf.writeFloat(localPlayer.getYHeadRot());
registryFriendlyByteBuf.writeVec3(localPlayer.getDeltaMovement());
GameProfile currentProfile = localPlayer.getGameProfile();
GameProfile newProfile = new GameProfile(currentProfile.getId(), currentProfile.getName());
newProfile.getProperties().putAll(Minecraft.getInstance().getGameProfile().getProperties());
newProfile.getProperties().putAll(currentProfile.getProperties());
ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, newProfile);
registryFriendlyByteBuf.writeVarInt(Minecraft.getInstance().gameMode.getPlayerMode().getId());
writer.finishAction(ActionCreateLocalPlayer.INSTANCE);
}
}
} }
if (lastChunkCacheIndex >= 0) { if (lastChunkCacheIndex >= 0) {
@@ -246,7 +219,6 @@ public class AsyncReplaySaver {
} }
} }
public void writeConfigurationPackets(StreamCodec<ByteBuf, Packet<? super ClientConfigurationPacketListener>> configurationPacketCodec, public void writeConfigurationPackets(StreamCodec<ByteBuf, Packet<? super ClientConfigurationPacketListener>> configurationPacketCodec,
List<Packet<? super ClientConfigurationPacketListener>> packets) { List<Packet<? super ClientConfigurationPacketListener>> packets) {
List<Packet<? super ClientConfigurationPacketListener>> packetCopy = new ArrayList<>(packets); List<Packet<? super ClientConfigurationPacketListener>> packetCopy = new ArrayList<>(packets);
@@ -0,0 +1,329 @@
package com.moulberry.flashback.io;
import com.google.gson.JsonObject;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.action.Action;
import com.moulberry.flashback.action.ActionLevelChunkCached;
import com.moulberry.flashback.action.ActionRegistry;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.record.FlashbackChunkMeta;
import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.record.ReplayMarker;
import com.replaymod.replaystudio.lib.viaversion.libs.fastutil.ints.Int2ObjectMap;
import com.replaymod.replaystudio.lib.viaversion.libs.fastutil.ints.Int2ObjectOpenHashMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledDirectByteBuf;
import it.unimi.dsi.fastutil.ints.Int2IntMap;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.network.protocol.game.GameProtocols;
import net.minecraft.resources.ResourceLocation;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ReplayCombiner {
public static void combine(RegistryAccess registryAccess, Path first, Path second, Path output) throws Exception {
StreamCodec<ByteBuf, Packet<? super ClientGamePacketListener>> gamePacketCodec = GameProtocols.CLIENTBOUND_TEMPLATE.bind(RegistryFriendlyByteBuf.decorator(registryAccess)).codec();
try (FileSystem firstFileSystem = FileSystems.newFileSystem(first);
FileSystem secondFileSystem = FileSystems.newFileSystem(second)) {
List<ClientboundLevelChunkWithLightPacket> levelChunkPackets = new ArrayList<>();
Int2IntMap levelChunkMappingsFirst = new Int2IntOpenHashMap();
Int2IntMap levelChunkMappingsSecond = new Int2IntOpenHashMap();
extractChunks(registryAccess, firstFileSystem, gamePacketCodec, levelChunkPackets, levelChunkMappingsFirst);
extractChunks(registryAccess, secondFileSystem, gamePacketCodec, levelChunkPackets, levelChunkMappingsSecond);
// Read metadata
Path metadataPath = firstFileSystem.getPath("/metadata.json");
String metadataJson = Files.readString(metadataPath);
FlashbackMeta firstMetadata = FlashbackMeta.fromJson(FlashbackGson.COMPRESSED.fromJson(metadataJson, JsonObject.class));
if (firstMetadata == null) {
throw new RuntimeException("Unable to load /metadata.json from first replay");
}
Path secondMetadataPath = secondFileSystem.getPath("/metadata.json");
String secondMetadataJson = Files.readString(secondMetadataPath);
FlashbackMeta secondMetadata = FlashbackMeta.fromJson(FlashbackGson.COMPRESSED.fromJson(secondMetadataJson, JsonObject.class));
if (secondMetadata == null) {
throw new RuntimeException("Unable to load /metadata.json from second replay");
}
if (firstMetadata.dataVersion != secondMetadata.dataVersion) {
throw new RuntimeException("Replays were created on different versions of the game, unable to combine");
}
firstMetadata.replayIdentifier = UUID.randomUUID();
for (Map.Entry<Integer, ReplayMarker> entry : secondMetadata.replayMarkers.entrySet()) {
firstMetadata.replayMarkers.put(entry.getKey() + firstMetadata.totalTicks, entry.getValue());
}
firstMetadata.totalTicks = firstMetadata.totalTicks + secondMetadata.totalTicks;
record ReplayChunk(Path path, Int2IntMap levelChunkMappings) {}
Map<String, ReplayChunk> newReplayChunks = new HashMap<>();
for (String name : firstMetadata.chunks.keySet()) {
newReplayChunks.put(name, new ReplayChunk(firstFileSystem.getPath("/" + name), levelChunkMappingsFirst));
}
boolean isFirstChunkOfSecondReplay = true;
for (Map.Entry<String, FlashbackChunkMeta> entry : secondMetadata.chunks.entrySet()) {
String newName = "c" + firstMetadata.chunks.size() + ".flashback";
if (isFirstChunkOfSecondReplay) {
isFirstChunkOfSecondReplay = false;
entry.getValue().forcePlaySnapshot = true;
}
firstMetadata.chunks.put(newName, entry.getValue());
newReplayChunks.put(newName, new ReplayChunk(secondFileSystem.getPath("/" + entry.getKey()), levelChunkMappingsSecond));
}
// Actually write
FileOutputStream fos = new FileOutputStream(output.toFile());
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zipOut = new ZipOutputStream(bos);
zipOut.setLevel(Deflater.BEST_SPEED);
// Write metadata
ZipEntry zipEntry = new ZipEntry("metadata.json");
zipOut.putNextEntry(zipEntry);
zipOut.write(FlashbackGson.COMPRESSED.toJson(firstMetadata.toJson()).getBytes(StandardCharsets.UTF_8));
zipOut.closeEntry();
// Write chunked level chunk caches
int lastCacheIndex = -1;
RegistryFriendlyByteBuf chunkCacheOutput = null;
for (int i = 0; i < levelChunkPackets.size(); i++) {
int cacheIndex = i / ReplayServer.CHUNK_CACHE_SIZE;
if (chunkCacheOutput == null) {
lastCacheIndex = cacheIndex;
chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), registryAccess);
} else if (cacheIndex != lastCacheIndex) {
byte[] bytes = new byte[chunkCacheOutput.writerIndex()];
chunkCacheOutput.getBytes(0, bytes);
zipEntry = new ZipEntry("level_chunk_caches/" + lastCacheIndex);
zipOut.putNextEntry(zipEntry);
zipOut.write(bytes);
zipOut.closeEntry();
chunkCacheOutput = new RegistryFriendlyByteBuf(Unpooled.buffer(), registryAccess);
}
// Write placeholder value for size
int startWriterIndex = chunkCacheOutput.writerIndex();
chunkCacheOutput.writeInt(-1);
// Write chunk packet
gamePacketCodec.encode(chunkCacheOutput, levelChunkPackets.get(i));
int endWriterIndex = chunkCacheOutput.writerIndex();
// Write real size value
int size = endWriterIndex - startWriterIndex - 4;
chunkCacheOutput.writerIndex(startWriterIndex);
chunkCacheOutput.writeInt(size);
chunkCacheOutput.writerIndex(endWriterIndex);
}
if (chunkCacheOutput != null) {
byte[] bytes = new byte[chunkCacheOutput.writerIndex()];
chunkCacheOutput.getBytes(0, bytes);
zipEntry = new ZipEntry("level_chunk_caches/" + lastCacheIndex);
zipOut.putNextEntry(zipEntry);
zipOut.write(bytes);
zipOut.closeEntry();
}
// Write icon
zipEntry = new ZipEntry("icon.png");
zipOut.putNextEntry(zipEntry);
Files.copy(firstFileSystem.getPath("/icon.png"), zipOut);
zipOut.closeEntry();
// Write chunks
for (Map.Entry<String, ReplayChunk> entry : newReplayChunks.entrySet()) {
zipEntry = new ZipEntry(entry.getKey());
zipOut.putNextEntry(zipEntry);
Path path = entry.getValue().path();
byte[] replayChunk = Files.readAllBytes(path);
RegistryFriendlyByteBuf inputBuf = new RegistryFriendlyByteBuf(Unpooled.wrappedBuffer(replayChunk), registryAccess);
FriendlyByteBuf outputBuf = new FriendlyByteBuf(Unpooled.buffer());
int magic = inputBuf.readInt();
if (magic != Flashback.MAGIC) {
throw new RuntimeException("Invalid magic");
}
outputBuf.writeInt(magic);
int levelChunkCachedActionId = -1;
int actions = inputBuf.readVarInt();
outputBuf.writeVarInt(actions);
for (int i = 0; i < actions; i++) {
ResourceLocation actionName = inputBuf.readResourceLocation();
outputBuf.writeResourceLocation(actionName);
Action action = ActionRegistry.getAction(actionName);
if (action instanceof ActionLevelChunkCached) {
levelChunkCachedActionId = i;
}
}
if (levelChunkCachedActionId == -1) {
Files.copy(entry.getValue().path, zipOut);
} else {
int snapshotSize = inputBuf.readInt();
if (snapshotSize < 0) {
throw new RuntimeException("Invalid snapshot size: " + snapshotSize + " (0x" + Integer.toHexString(snapshotSize) + ")");
}
int snapshotInputEnd = inputBuf.readerIndex() + snapshotSize;
int snapshotOutputWriterIndex = outputBuf.writerIndex();
outputBuf.writeInt(0xDEADBEEF);
int snapshotStartWriterIndex = outputBuf.writerIndex();
int snapshotEndWriterIndex = outputBuf.writerIndex();
while (inputBuf.readerIndex() < inputBuf.writerIndex()) {
boolean inSnapshot = inputBuf.readerIndex() < snapshotInputEnd;
int id = inputBuf.readVarInt();
int size = inputBuf.readInt();
if (id == levelChunkCachedActionId) {
int cachedChunkId = inputBuf.readVarInt();
if (!entry.getValue().levelChunkMappings.containsKey(cachedChunkId)) {
throw new RuntimeException("Missing cached chunk id " + cachedChunkId);
}
int newCachedChunkId = entry.getValue().levelChunkMappings.get(cachedChunkId);
outputBuf.writeVarInt(id);
int sizeWriterIndex = outputBuf.writerIndex();
outputBuf.writeInt(0);
int cachedIdWriterIndex = outputBuf.writerIndex();
outputBuf.writeVarInt(newCachedChunkId);
int endWriterIndex = outputBuf.writerIndex();
outputBuf.writerIndex(sizeWriterIndex);
outputBuf.writeInt(endWriterIndex - cachedIdWriterIndex);
outputBuf.writerIndex(endWriterIndex);
} else {
outputBuf.writeVarInt(id);
outputBuf.writeInt(size);
outputBuf.writeBytes(inputBuf, size);
}
if (inSnapshot) {
snapshotEndWriterIndex = outputBuf.writerIndex();
}
}
int endWriterIndex = outputBuf.writerIndex();
outputBuf.writerIndex(snapshotOutputWriterIndex);
outputBuf.writeInt(snapshotEndWriterIndex - snapshotStartWriterIndex);
outputBuf.writerIndex(endWriterIndex);
byte[] bytes = new byte[outputBuf.writerIndex()];
outputBuf.getBytes(0, bytes);
zipOut.write(bytes);
}
zipOut.closeEntry();
}
zipOut.close();
bos.close();
fos.close();
}
}
private static void extractChunks(RegistryAccess registryAccess, FileSystem fileSystem, StreamCodec<ByteBuf, Packet<? super ClientGamePacketListener>> gamePacketCodec,
List<ClientboundLevelChunkWithLightPacket> packets, Int2IntMap levelChunkMappings) throws IOException {
Path levelChunkCachePath = fileSystem.getPath("/level_chunk_cache");
if (Files.exists(levelChunkCachePath)) {
loadLevelChunkCache(gamePacketCodec, registryAccess, levelChunkCachePath, 0, packets, levelChunkMappings);
}
int index = 0;
while (true) {
levelChunkCachePath = fileSystem.getPath("/level_chunk_caches/"+index);
if (Files.exists(levelChunkCachePath)) {
loadLevelChunkCache(gamePacketCodec, registryAccess, levelChunkCachePath, index * ReplayServer.CHUNK_CACHE_SIZE, packets, levelChunkMappings);
index += 1;
} else {
break;
}
}
}
private static void loadLevelChunkCache(StreamCodec<ByteBuf, Packet<? super ClientGamePacketListener>> gamePacketCodec, RegistryAccess registryAccess,
Path levelChunkCachePath, int chunkCacheIndex, List<ClientboundLevelChunkWithLightPacket> packets, Int2IntMap levelChunkMappings) throws IOException {
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), registryAccess);
try {
Packet<?> packet = gamePacketCodec.decode(registryFriendlyByteBuf);
if (packet instanceof ClientboundLevelChunkWithLightPacket levelChunkWithLightPacket) {
levelChunkMappings.put(chunkCacheIndex, packets.size());
packets.add(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;
}
}
}
}
@@ -28,7 +28,7 @@ public class ReplayWriter {
private static final int STATE_EMPTY = 0; private static final int STATE_EMPTY = 0;
private static final int STATE_WRITING_SNAPSHOT = 1; private static final int STATE_WRITING_SNAPSHOT = 1;
private static final int STATE_WRITING_DATA = 2; private static final int STATE_WRITING_DATA = 2;
private int state = STATE_EMPTY; public int state = STATE_EMPTY;
public ReplayWriter(RegistryAccess registryAccess) { public ReplayWriter(RegistryAccess registryAccess) {
this.dataBufferInner = Unpooled.buffer(); this.dataBufferInner = Unpooled.buffer();
@@ -1,6 +1,7 @@
package com.moulberry.flashback.keyframe; package com.moulberry.flashback.keyframe;
import com.google.gson.*; import com.google.gson.*;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler; import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import com.moulberry.flashback.keyframe.impl.CameraKeyframe;
import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe; import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe;
@@ -17,14 +18,14 @@ import java.util.function.Consumer;
public abstract class Keyframe { public abstract class Keyframe {
private InterpolationType interpolationType = InterpolationType.DEFAULT; private InterpolationType interpolationType = InterpolationType.getDefault();
public InterpolationType interpolationType() { public InterpolationType interpolationType() {
return interpolationType; return interpolationType;
} }
public void interpolationType(InterpolationType interpolationType) { public void interpolationType(InterpolationType interpolationType) {
this.interpolationType = Objects.requireNonNullElse(interpolationType, InterpolationType.DEFAULT); this.interpolationType = Objects.requireNonNullElse(interpolationType, InterpolationType.getDefault());
} }
public abstract KeyframeType<?> keyframeType(); public abstract KeyframeType<?> keyframeType();
@@ -11,15 +11,9 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType;
import com.moulberry.flashback.spline.CatmullRom; import com.moulberry.flashback.spline.CatmullRom;
import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.visuals.CameraPath;
import imgui.ImGui;
import imgui.type.ImFloat;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import org.joml.Quaterniond;
import org.joml.Quaterniond;
import org.joml.Vector3d; import org.joml.Vector3d;
import org.joml.Vector3f;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -45,7 +39,7 @@ public class CameraKeyframe extends Keyframe {
} }
public CameraKeyframe(Vector3d position, float yaw, float pitch, float roll) { public CameraKeyframe(Vector3d position, float yaw, float pitch, float roll) {
this(position, yaw, pitch, roll, InterpolationType.DEFAULT); this(position, yaw, pitch, roll, InterpolationType.getDefault());
} }
public CameraKeyframe(Vector3d position, float yaw, float pitch, float roll, InterpolationType interpolationType) { public CameraKeyframe(Vector3d position, float yaw, float pitch, float roll, InterpolationType interpolationType) {
@@ -56,8 +50,16 @@ public class CameraKeyframe extends Keyframe {
this.interpolationType(interpolationType); this.interpolationType(interpolationType);
} }
public Quaterniond getQuaternion() { public Vector3d getNormal() {
return new Quaterniond().rotationYXZ((float) -Math.toRadians(this.yaw), (float) Math.toRadians(this.pitch), 0.0); double yawRad = Math.toRadians(-this.yaw);
double cosYaw = Math.cos((float)yawRad);
double sinYaw = Math.sin((float)yawRad);
double pitchRad = Math.toRadians(this.pitch);
double cosPitch = Math.cos((float)pitchRad);
double sinPitch = Math.sin((float)pitchRad);
return new Vector3d(sinYaw * cosPitch, -sinPitch, cosYaw * cosPitch);
} }
@Override @Override
@@ -104,38 +106,11 @@ public class CameraKeyframe extends Keyframe {
} }
} }
private void apply(KeyframeHandler keyframeHandler, Vector3d position, Quaterniond quaternion, float roll) {
Vector3d euler = quaternion.getEulerAnglesYXZ(new Vector3d());
double yaw = Mth.wrapDegrees(Math.toDegrees(euler.y));
double pitch = Mth.wrapDegrees(Math.toDegrees(euler.x));
// Handle singularity
double test = quaternion.y * quaternion.z - quaternion.w * quaternion.x;
final double MIN_TEST = 0.49999;
final double MAX_TEST = 0.499999;
if (test > MIN_TEST) {
double fixedYaw = Mth.wrapDegrees(Math.toDegrees(2 * Math.atan2(quaternion.z, quaternion.w)));
if (test >= MAX_TEST) {
yaw = fixedYaw;
} else {
yaw = yaw + Mth.wrapDegrees(fixedYaw - yaw) * (test - MIN_TEST) / (MAX_TEST - MIN_TEST);
}
} else if (test < -MIN_TEST) {
double fixedYaw = Mth.wrapDegrees(Math.toDegrees(-2 * Math.atan2(quaternion.z, quaternion.w)));
if (test <= -MAX_TEST) {
yaw = fixedYaw;
} else {
yaw = yaw + Mth.wrapDegrees(fixedYaw - yaw) * (test - -MIN_TEST) / (-MAX_TEST - -MIN_TEST);
}
}
// Apply position
keyframeHandler.applyCameraPosition(position, -yaw, pitch, roll);
}
@Override @Override
public void apply(KeyframeHandler keyframeHandler) { public void apply(KeyframeHandler keyframeHandler) {
apply(keyframeHandler, this.position, this.getQuaternion(), this.roll); keyframeHandler.applyCameraPosition(this.position, this.yaw, this.pitch, this.roll);
} }
@Override @Override
@@ -148,11 +123,13 @@ public class CameraKeyframe extends Keyframe {
double x = Interpolation.linear(this.position.x, other.position.x, amount); double x = Interpolation.linear(this.position.x, other.position.x, amount);
double y = Interpolation.linear(this.position.y, other.position.y, amount); double y = Interpolation.linear(this.position.y, other.position.y, amount);
double z = Interpolation.linear(this.position.z, other.position.z, amount); double z = Interpolation.linear(this.position.z, other.position.z, amount);
float roll = Interpolation.linear(this.roll, other.roll, amount);
Quaterniond quaternion = Interpolation.linear(this.getQuaternion(), other.getQuaternion(), amount);
Vector3d position = new Vector3d(x, y, z); Vector3d position = new Vector3d(x, y, z);
apply(keyframeHandler, position, quaternion, roll);
float yaw = Interpolation.linearAngle(this.yaw, other.yaw, amount);
float pitch = Interpolation.linearAngle(this.pitch, other.pitch, amount);
float roll = Interpolation.linearAngle(this.roll, other.roll, amount);
keyframeHandler.applyCameraPosition(position, yaw, pitch, roll);
} }
@Override @Override
@@ -171,11 +148,13 @@ public class CameraKeyframe extends Keyframe {
double z = position.z; double z = position.z;
// Calculate rotation // Calculate rotation
Quaterniond rotation = CatmullRom.rotation(this.getQuaternion(), float yaw = CatmullRom.degrees(this.yaw,
((CameraKeyframe)p1).getQuaternion(), ((CameraKeyframe)p2).getQuaternion(), ((CameraKeyframe)p1).yaw, ((CameraKeyframe)p2).yaw,
((CameraKeyframe)p3).getQuaternion(), time1, time2, time3, amount); ((CameraKeyframe)p3).yaw, time1, time2, time3, amount);
float pitch = CatmullRom.degrees(this.pitch,
float roll = CatmullRom.value(this.roll, ((CameraKeyframe)p1).pitch, ((CameraKeyframe)p2).pitch,
((CameraKeyframe)p3).pitch, time1, time2, time3, amount);
float roll = CatmullRom.degrees(this.roll,
((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll, ((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll,
((CameraKeyframe)p3).roll, time1, time2, time3, amount); ((CameraKeyframe)p3).roll, time1, time2, time3, amount);
@@ -183,27 +162,31 @@ public class CameraKeyframe extends Keyframe {
double linearX = Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount); double linearX = Interpolation.linear(((CameraKeyframe)p1).position.x, ((CameraKeyframe)p2).position.x, lerpAmount);
double linearY = Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount); double linearY = Interpolation.linear(((CameraKeyframe)p1).position.y, ((CameraKeyframe)p2).position.y, lerpAmount);
double linearZ = Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount); double linearZ = Interpolation.linear(((CameraKeyframe)p1).position.z, ((CameraKeyframe)p2).position.z, lerpAmount);
float linearRoll = Interpolation.linear(((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll, lerpAmount); float linearYaw = Interpolation.linearAngle(((CameraKeyframe)p1).yaw, ((CameraKeyframe)p2).yaw, lerpAmount);
float linearPitch = Interpolation.linearAngle(((CameraKeyframe)p1).pitch, ((CameraKeyframe)p2).pitch, lerpAmount);
Quaterniond linearQuaternion = Interpolation.linear(((CameraKeyframe)p1).getQuaternion(), float linearRoll = Interpolation.linearAngle(((CameraKeyframe)p1).roll, ((CameraKeyframe)p2).roll, lerpAmount);
((CameraKeyframe)p2).getQuaternion(), lerpAmount);
if (lerpFromRight) { if (lerpFromRight) {
x = Interpolation.linear(x, linearX, amount); x = Interpolation.linear(x, linearX, amount);
y = Interpolation.linear(y, linearY, amount); y = Interpolation.linear(y, linearY, amount);
z = Interpolation.linear(z, linearZ, amount); z = Interpolation.linear(z, linearZ, amount);
roll = Interpolation.linear(roll, linearRoll, amount); yaw = Interpolation.linearAngle(yaw, linearYaw, amount);
rotation = Interpolation.linear(rotation, linearQuaternion, amount); pitch = Interpolation.linearAngle(pitch, linearPitch, amount);
roll = Interpolation.linearAngle(roll, linearRoll, amount);
} else { } else {
x = Interpolation.linear(linearX, x, amount); x = Interpolation.linear(linearX, x, amount);
y = Interpolation.linear(linearY, y, amount); y = Interpolation.linear(linearY, y, amount);
z = Interpolation.linear(linearZ, z, amount); z = Interpolation.linear(linearZ, z, amount);
roll = Interpolation.linear(linearRoll, roll, amount); yaw = Interpolation.linearAngle(linearYaw, yaw, amount);
rotation = Interpolation.linear(linearQuaternion, rotation, amount); pitch = Interpolation.linearAngle(linearPitch, pitch, amount);
roll = Interpolation.linearAngle(linearRoll, roll, amount);
} }
} }
apply(keyframeHandler, new Vector3d(x, y, z), rotation, roll); position.x = x;
position.y = y;
position.z = z;
keyframeHandler.applyCameraPosition(position, yaw, pitch, roll);
} }
public static class TypeAdapter implements JsonSerializer<CameraKeyframe>, JsonDeserializer<CameraKeyframe> { public static class TypeAdapter implements JsonSerializer<CameraKeyframe>, JsonDeserializer<CameraKeyframe> {
@@ -38,7 +38,7 @@ public class CameraOrbitKeyframe extends Keyframe {
public float pitch; public float pitch;
public CameraOrbitKeyframe(Vector3d center, float distance, float yaw, float pitch) { public CameraOrbitKeyframe(Vector3d center, float distance, float yaw, float pitch) {
this(center, distance, yaw, pitch, InterpolationType.DEFAULT); this(center, distance, yaw, pitch, InterpolationType.getDefault());
} }
public CameraOrbitKeyframe(Vector3d center, float distance, float yaw, float pitch, InterpolationType interpolationType) { public CameraOrbitKeyframe(Vector3d center, float distance, float yaw, float pitch, InterpolationType interpolationType) {
@@ -30,7 +30,7 @@ public class CameraShakeKeyframe extends Keyframe {
private boolean splitParams; private boolean splitParams;
public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, boolean splitParams) { public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, boolean splitParams) {
this(frequencyX, amplitudeX, frequencyY, amplitudeY, splitParams, InterpolationType.DEFAULT); this(frequencyX, amplitudeX, frequencyY, amplitudeY, splitParams, InterpolationType.getDefault());
} }
public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, boolean splitParams, InterpolationType interpolationType) { public CameraShakeKeyframe(float frequencyX, float amplitudeX, float frequencyY, float amplitudeY, boolean splitParams, InterpolationType interpolationType) {
@@ -19,7 +19,7 @@ public class FOVKeyframe extends Keyframe {
public float fov; public float fov;
public FOVKeyframe(float fov) { public FOVKeyframe(float fov) {
this(fov, InterpolationType.DEFAULT); this(fov, InterpolationType.getDefault());
} }
public FOVKeyframe(float fov, InterpolationType interpolationType) { public FOVKeyframe(float fov, InterpolationType interpolationType) {
@@ -18,7 +18,7 @@ public class TickrateKeyframe extends Keyframe {
private float tickrate; private float tickrate;
public TickrateKeyframe(float tickrate) { public TickrateKeyframe(float tickrate) {
this(tickrate, InterpolationType.DEFAULT); this(tickrate, InterpolationType.getDefault());
} }
public TickrateKeyframe(float tickrate, InterpolationType interpolationType) { public TickrateKeyframe(float tickrate, InterpolationType interpolationType) {
@@ -20,7 +20,7 @@ public class TimeOfDayKeyframe extends Keyframe {
public int time; public int time;
public TimeOfDayKeyframe(int time) { public TimeOfDayKeyframe(int time) {
this(time, InterpolationType.DEFAULT); this(time, InterpolationType.getDefault());
} }
public TimeOfDayKeyframe(int time, InterpolationType interpolationType) { public TimeOfDayKeyframe(int time, InterpolationType interpolationType) {
@@ -1,18 +1,28 @@
package com.moulberry.flashback.keyframe.interpolation; package com.moulberry.flashback.keyframe.interpolation;
public enum InterpolationType { import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.combo_options.ComboOption;
import com.moulberry.flashback.configuration.FlashbackConfig;
SMOOTH(SidedInterpolationType.SMOOTH, SidedInterpolationType.SMOOTH), public enum InterpolationType implements ComboOption {
LINEAR(SidedInterpolationType.LINEAR, SidedInterpolationType.LINEAR),
EASE_IN(SidedInterpolationType.EASE, SidedInterpolationType.LINEAR),
EASE_OUT(SidedInterpolationType.LINEAR, SidedInterpolationType.EASE),
EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE),
HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD);
public static InterpolationType DEFAULT = SMOOTH; SMOOTH(SidedInterpolationType.SMOOTH, SidedInterpolationType.SMOOTH, "Smooth"),
LINEAR(SidedInterpolationType.LINEAR, SidedInterpolationType.LINEAR, "Linear"),
EASE_IN(SidedInterpolationType.EASE, SidedInterpolationType.LINEAR, "Ease In (Linear Out)"),
EASE_OUT(SidedInterpolationType.LINEAR, SidedInterpolationType.EASE, "Ease Out (Linear In)"),
EASE_IN_OUT(SidedInterpolationType.EASE, SidedInterpolationType.EASE, "Ease In/Out"),
HOLD(SidedInterpolationType.HOLD, SidedInterpolationType.HOLD, "Hold");
public static final InterpolationType[] INTERPOLATION_TYPES = values(); public static final InterpolationType[] INTERPOLATION_TYPES = values();
public static InterpolationType getDefault() {
FlashbackConfig config = Flashback.getConfig();
if (config != null && config.defaultInterpolationType != null) {
return config.defaultInterpolationType;
}
return InterpolationType.SMOOTH;
}
public static String[] NAMES = new String[] { public static String[] NAMES = new String[] {
"Smooth", "Smooth",
"Linear", "Linear",
@@ -22,12 +32,18 @@ public enum InterpolationType {
"Hold" "Hold"
}; };
public SidedInterpolationType leftSide; public final SidedInterpolationType leftSide;
public SidedInterpolationType rightSide; public final SidedInterpolationType rightSide;
public final String name;
InterpolationType(SidedInterpolationType leftSide, SidedInterpolationType rightSide) { InterpolationType(SidedInterpolationType leftSide, SidedInterpolationType rightSide, String name) {
this.leftSide = leftSide; this.leftSide = leftSide;
this.rightSide = rightSide; this.rightSide = rightSide;
this.name = name;
} }
@Override
public String text() {
return this.name;
}
} }
@@ -4,6 +4,7 @@ import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.impl.CameraKeyframe; import com.moulberry.flashback.keyframe.impl.CameraKeyframe;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.player.LocalPlayer;
import net.minecraft.world.entity.Entity;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class CameraKeyframeType implements KeyframeType<CameraKeyframe> { public class CameraKeyframeType implements KeyframeType<CameraKeyframe> {
@@ -25,9 +26,13 @@ public class CameraKeyframeType implements KeyframeType<CameraKeyframe> {
@Override @Override
public @Nullable CameraKeyframe createDirect() { public @Nullable CameraKeyframe createDirect() {
LocalPlayer player = Minecraft.getInstance().player; Entity entity = Minecraft.getInstance().cameraEntity;
if (player != null) { if (entity != null) {
return new CameraKeyframe(player); return new CameraKeyframe(entity);
}
entity = Minecraft.getInstance().player;
if (entity != null) {
return new CameraKeyframe(entity);
} }
return null; return null;
} }
@@ -0,0 +1,45 @@
package com.moulberry.flashback.mixin;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.yggdrasil.ProfileResult;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.resources.PlayerSkin;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(AbstractClientPlayer.class)
public abstract class MixinAbstractClientPlayer extends Player {
public MixinAbstractClientPlayer(Level level, BlockPos blockPos, float f, GameProfile gameProfile) {
super(level, blockPos, f, gameProfile);
}
@Unique
private PlayerInfo skinOverridePlayerInfo = null;
@Inject(method = "getSkin", at = @At("HEAD"), cancellable = true, require = 0)
public void getSkin(CallbackInfoReturnable<PlayerSkin> cir) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
GameProfile skinOverride = editorState.skinOverride.get(this.uuid);
if (skinOverride != null) {
if (skinOverridePlayerInfo == null || skinOverridePlayerInfo.getProfile() != skinOverride) {
skinOverridePlayerInfo = new PlayerInfo(skinOverride, false);
}
cir.setReturnValue(skinOverridePlayerInfo.getSkin());
}
}
}
}
@@ -73,7 +73,7 @@ public abstract class MixinLevelRenderer {
ReplayUI.lastViewQuaternion = camera.rotation(); ReplayUI.lastViewQuaternion = camera.rotation();
} }
@Inject(method = "renderSectionLayer", at = @At("HEAD"), cancellable = true) @Inject(method = "renderSectionLayer", at = @At("HEAD"), cancellable = true, require = 0)
public void renderSectionLayer(RenderType renderType, double d, double e, double f, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { public void renderSectionLayer(RenderType renderType, double d, double e, double f, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) { if (editorState != null) {
@@ -83,7 +83,7 @@ public abstract class MixinLevelRenderer {
} }
} }
@Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", ordinal = 2, shift = At.Shift.AFTER)) @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;DDDLorg/joml/Matrix4f;Lorg/joml/Matrix4f;)V", ordinal = 2, shift = At.Shift.AFTER), require = 0)
public void renderLevel_renderCutoutLayer(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { public void renderLevel_renderCutoutLayer(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) {
if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().transparent()) { if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().transparent()) {
RenderTarget main = Minecraft.getInstance().mainRenderTarget; RenderTarget main = Minecraft.getInstance().mainRenderTarget;
@@ -109,7 +109,7 @@ public abstract class MixinLevelRenderer {
} }
} }
@Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER)) @Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER), require = 0)
public void renderLevel_levelFogColor(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) { public void renderLevel_levelFogColor(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) { if (editorState != null) {
@@ -137,13 +137,13 @@ public abstract class MixinLevelRenderer {
} }
} }
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;render(Lnet/minecraft/world/level/block/entity/BlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V")) @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;render(Lnet/minecraft/world/level/block/entity/BlockEntity;FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"), require = 0)
public boolean renderLevel_renderBlockEntity(BlockEntityRenderDispatcher instance, BlockEntity blockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource) { public boolean renderLevel_renderBlockEntity(BlockEntityRenderDispatcher instance, BlockEntity blockEntity, float f, PoseStack poseStack, MultiBufferSource multiBufferSource) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderBlocks; return editorState == null || editorState.replayVisuals.renderBlocks;
} }
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V")) @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"), require = 0)
public boolean renderLevel_renderEntity(LevelRenderer instance, Entity entity, double d, double e, double f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource) { public boolean renderLevel_renderEntity(LevelRenderer instance, Entity entity, double d, double e, double f, float g, PoseStack poseStack, MultiBufferSource multiBufferSource) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (entity instanceof Player) { if (entity instanceof Player) {
@@ -153,7 +153,7 @@ public abstract class MixinLevelRenderer {
} }
} }
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;")) @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Options;getCloudsType()Lnet/minecraft/client/CloudStatus;"), require = 0)
public CloudStatus renderLevel_getCloudsType(Options instance, Operation<CloudStatus> original) { public CloudStatus renderLevel_getCloudsType(Options instance, Operation<CloudStatus> original) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderSky) { if (editorState != null && !editorState.replayVisuals.renderSky) {
@@ -163,19 +163,19 @@ public abstract class MixinLevelRenderer {
} }
} }
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V")) @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/particle/ParticleEngine;render(Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V"), require = 0)
public boolean renderLevel_renderParticles(ParticleEngine instance, LightTexture lightTexture, Camera camera, float f) { public boolean renderLevel_renderParticles(ParticleEngine instance, LightTexture lightTexture, Camera camera, float f) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderParticles; return editorState == null || editorState.replayVisuals.renderParticles;
} }
@WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSky(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FLnet/minecraft/client/Camera;ZLjava/lang/Runnable;)V")) @WrapWithCondition(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;renderSky(Lorg/joml/Matrix4f;Lorg/joml/Matrix4f;FLnet/minecraft/client/Camera;ZLjava/lang/Runnable;)V"), require = 0)
public boolean renderLevel_renderSky(LevelRenderer instance, Matrix4f matrix4f, Matrix4f matrix4f2, float f, Camera camera, boolean bl, Runnable runnable) { public boolean renderLevel_renderSky(LevelRenderer instance, Matrix4f matrix4f, Matrix4f matrix4f2, float f, Camera camera, boolean bl, Runnable runnable) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderSky; return editorState == null || editorState.replayVisuals.renderSky;
} }
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V")) @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/LevelRenderer;setupRender(Lnet/minecraft/client/Camera;Lnet/minecraft/client/renderer/culling/Frustum;ZZ)V"), require = 0)
public void setupRender(LevelRenderer instance, Camera camera, Frustum frustum, boolean capturedFrustum, boolean isSpectator, Operation<Void> original) { public void setupRender(LevelRenderer instance, Camera camera, Frustum frustum, boolean capturedFrustum, boolean isSpectator, Operation<Void> original) {
if (PerfectFrames.isEnabled()) { if (PerfectFrames.isEnabled()) {
boolean doCompile = true; boolean doCompile = true;
@@ -8,7 +8,9 @@ import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.BufferUploader;
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.MeshData;
import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormat;
import com.moulberry.flashback.WindowSizeTracker;
import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.editor.ui.ReplayUI;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.ShaderInstance;
@@ -27,24 +29,42 @@ import java.util.Objects;
public abstract class MixinRenderTarget { public abstract class MixinRenderTarget {
@Shadow @Shadow
public int frameBufferId; public int colorTextureId;
@Shadow
public abstract int getColorTextureId();
@Inject(method = "blitToScreen(IIZ)V", at = @At("HEAD"), cancellable = true) @Inject(method = "blitToScreen(IIZ)V", at = @At("HEAD"), cancellable = true)
public void blitToScreenSodium(int width, int height, boolean noBlend, CallbackInfo ci) { public void blitToScreenSodium(int width, int height, boolean noBlend, CallbackInfo ci) {
if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive()) { if ((Object)this == Minecraft.getInstance().getMainRenderTarget() && ReplayUI.isActive()) {
var window = Minecraft.getInstance().getWindow(); var window = Minecraft.getInstance().getWindow();
int frameBottom = (ReplayUI.viewportSizeY - (ReplayUI.frameY + ReplayUI.frameHeight)) * window.framebufferHeight / ReplayUI.viewportSizeY; float frameLeft = (float) ReplayUI.frameX / ReplayUI.viewportSizeX;
int frameLeft = ReplayUI.frameX * window.framebufferWidth / ReplayUI.viewportSizeX; float frameTop = (float) ReplayUI.frameY / ReplayUI.viewportSizeY;
int frameWidth = Math.max(1, ReplayUI.frameWidth) * window.framebufferWidth / ReplayUI.viewportSizeX; float frameWidth = (float) Math.max(1, ReplayUI.frameWidth) / ReplayUI.viewportSizeX;
int frameHeight = Math.max(1, ReplayUI.frameHeight) * window.framebufferHeight / ReplayUI.viewportSizeY; float frameHeight = (float) Math.max(1, ReplayUI.frameHeight) / ReplayUI.viewportSizeY;
GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, this.frameBufferId); int realWidth = WindowSizeTracker.getWidth(window);
GL30.glBlitFramebuffer(0, 0, width, height, frameLeft, frameBottom, frameLeft+frameWidth, frameBottom+frameHeight, int realHeight = WindowSizeTracker.getHeight(window);
GL11.GL_COLOR_BUFFER_BIT, GL11.GL_LINEAR);
GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, 0); RenderSystem.assertOnRenderThread();
GlStateManager._colorMask(true, true, true, false);
GlStateManager._disableDepthTest();
GlStateManager._depthMask(false);
GlStateManager._viewport((int)(realWidth * frameLeft), (int)(realHeight * (1 - (frameTop+frameHeight))),
Math.max(1, (int)(realWidth * frameWidth)), Math.max(1, (int)(realHeight * frameHeight)));
if (noBlend) {
GlStateManager._disableBlend();
}
Minecraft minecraft = Minecraft.getInstance();
ShaderInstance shaderInstance = Objects.requireNonNull(minecraft.gameRenderer.blitShader, "Blit shader not loaded");
shaderInstance.setSampler("DiffuseSampler", this.colorTextureId);
shaderInstance.apply();
BufferBuilder bufferBuilder = RenderSystem.renderThreadTesselator().begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.BLIT_SCREEN);
bufferBuilder.addVertex(0.0f, 0.0f, 0.0f);
bufferBuilder.addVertex(1.0f, 0.0f, 0.0f);
bufferBuilder.addVertex(1.0f, 1.0f, 0.0f);
bufferBuilder.addVertex(0.0f, 1.0f, 0.0f);
BufferUploader.draw(bufferBuilder.buildOrThrow());
shaderInstance.clear();
GlStateManager._depthMask(true);
GlStateManager._colorMask(true, true, true, true);
ci.cancel(); ci.cancel();
} }
} }
@@ -21,9 +21,8 @@ import java.util.SortedSet;
@Mixin(targets = {"net.caffeinemc.mods.sodium.client.render.SodiumWorldRenderer", "me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer"}) @Mixin(targets = {"net.caffeinemc.mods.sodium.client.render.SodiumWorldRenderer", "me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer"})
public class MixinSodiumWorldRenderer { public class MixinSodiumWorldRenderer {
@Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;Lnet/minecraft/client/Camera;F)V", @Inject(method = "renderBlockEntities", at = @At("HEAD"), cancellable = true, require = 0, remap = false)
at = @At("HEAD"), cancellable = true) public void renderBlockEntities(CallbackInfo ci) {
public void renderBlockEntities(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap<SortedSet<BlockDestructionProgress>> blockBreakingProgressions, Camera camera, float tickDelta, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderBlocks) { if (editorState != null && !editorState.replayVisuals.renderBlocks) {
ci.cancel(); ci.cancel();
@@ -1,4 +1,4 @@
package com.moulberry.flashback.mixin.compat; package com.moulberry.flashback.mixin.compat.axiom;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.editor.ui.ReplayUI;
@@ -0,0 +1,23 @@
package com.moulberry.flashback.mixin.compat.axiom;
import com.moulberry.flashback.Flashback;
import com.moulberry.mixinconstraints.annotations.IfModLoaded;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@IfModLoaded("axiom")
@Pseudo
@Mixin(targets = "com.moulberry.axiom.integration.ServerIntegration", remap = false)
public class MixinAxiomServerIntegration {
@Inject(method = "changeGameMode", at = @At("HEAD"), cancellable = true, require = 0)
private static void changeGameMode(CallbackInfo ci) {
if (Flashback.isInReplay()) {
ci.cancel();
}
}
}
@@ -1,23 +0,0 @@
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();
// }
// }
}
@@ -1,4 +1,4 @@
package com.moulberry.flashback.mixin.compat; package com.moulberry.flashback.mixin.compat.fabric;
import com.bawnorton.mixinsquared.TargetHandler; import com.bawnorton.mixinsquared.TargetHandler;
import com.moulberry.flashback.playback.ReplayServer; import com.moulberry.flashback.playback.ReplayServer;
@@ -21,7 +21,7 @@ public class MixinFabricMinecraftServer {
mixin = "net.fabricmc.fabric.mixin.biome.modification.MinecraftServerMixin", mixin = "net.fabricmc.fabric.mixin.biome.modification.MinecraftServerMixin",
name = "finalizeWorldGen" name = "finalizeWorldGen"
) )
@Inject(method = "@MixinSquared:Handler", at = @At("HEAD"), cancellable = true) @Inject(method = "@MixinSquared:Handler", at = @At("HEAD"), cancellable = true, require = 0)
private void preventWorldGenChanges(CallbackInfo ci) { private void preventWorldGenChanges(CallbackInfo ci) {
if ((Object) this instanceof ReplayServer) { if ((Object) this instanceof ReplayServer) {
ci.cancel(); ci.cancel();
@@ -0,0 +1,39 @@
package com.moulberry.flashback.mixin.compat.fabric;
import com.moulberry.flashback.playback.FakePlayer;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(value = ServerPlayNetworking.class, remap = false)
public class MixinFabricServerPlayNetworking {
@Inject(method = "canSend(Lnet/minecraft/server/network/ServerGamePacketListenerImpl;Lnet/minecraft/network/protocol/common/custom/CustomPacketPayload$Type;)Z", at = @At("HEAD"), cancellable = true, require = 0)
private static void canSend1(ServerGamePacketListenerImpl handler, CustomPacketPayload.Type<?> type, CallbackInfoReturnable<Boolean> cir) {
if (handler.player instanceof FakePlayer) {
cir.setReturnValue(true);
}
}
@Inject(method = "canSend(Lnet/minecraft/server/network/ServerGamePacketListenerImpl;Lnet/minecraft/resources/ResourceLocation;)Z", at = @At("HEAD"), cancellable = true, require = 0)
private static void canSend2(ServerGamePacketListenerImpl handler, ResourceLocation channelName, CallbackInfoReturnable<Boolean> cir) {
if (handler.player instanceof FakePlayer) {
cir.setReturnValue(true);
}
}
@Inject(method = "send", at = @At("HEAD"), cancellable = true, require = 0)
private static void send(ServerPlayer player, CustomPacketPayload payload, CallbackInfo ci) {
if (player instanceof FakePlayer) {
ci.cancel();
}
}
}
@@ -14,7 +14,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(value = SystemTimeUniforms.Timer.class, remap = false) @Mixin(value = SystemTimeUniforms.Timer.class, remap = false)
public class MixinIrisSystemTimeUniforms { public class MixinIrisSystemTimeUniforms {
@Inject(method = "getFrameTimeCounter", at = @At("HEAD"), cancellable = true) @Inject(method = "getFrameTimeCounter", at = @At("HEAD"), require = 0, cancellable = true)
public void getFrameTimeCounter(CallbackInfoReturnable<Float> cir) { public void getFrameTimeCounter(CallbackInfoReturnable<Float> cir) {
if (Flashback.isExporting()) { if (Flashback.isExporting()) {
double currentTick = Flashback.EXPORT_JOB.getCurrentTickDouble(); double currentTick = Flashback.EXPORT_JOB.getCurrentTickDouble();
@@ -22,7 +22,7 @@ public class MixinIrisSystemTimeUniforms {
} }
} }
@Inject(method = "getLastFrameTime", at = @At("HEAD"), cancellable = true) @Inject(method = "getLastFrameTime", at = @At("HEAD"), require = 0, cancellable = true)
public void getLastFrameTime(CallbackInfoReturnable<Float> cir) { public void getLastFrameTime(CallbackInfoReturnable<Float> cir) {
if (Flashback.isExporting()) { if (Flashback.isExporting()) {
cir.setReturnValue((float)(1 / Flashback.EXPORT_JOB.getSettings().framerate())); cir.setReturnValue((float)(1 / Flashback.EXPORT_JOB.getSettings().framerate()));
@@ -15,7 +15,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(value = ReplayModRecording.class, remap = false) @Mixin(value = ReplayModRecording.class, remap = false)
public class MixinReplayModRecording { public class MixinReplayModRecording {
@Inject(method = "initiateRecording", at = @At("HEAD"), cancellable = true) @Inject(method = "initiateRecording", at = @At("HEAD"), require = 0, cancellable = true)
public void initiateRecording(Connection networkManager, CallbackInfo ci) { public void initiateRecording(Connection networkManager, CallbackInfo ci) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
ci.cancel(); ci.cancel();
@@ -5,7 +5,10 @@ import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig; import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.state.EditorState; import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager; import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.player.RemotePlayer;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
@@ -54,4 +57,17 @@ public abstract class MixinPlayerEntity extends LivingEntity {
} }
} }
@Inject(method = "getName", at = @At("HEAD"), cancellable = true)
public void getName(CallbackInfoReturnable<Component> cir) {
if ((Object)this instanceof RemotePlayer) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
String nameOverride = editorState.nameOverride.get(this.uuid);
if (nameOverride != null) {
cir.setReturnValue(Component.literal(nameOverride));
}
}
}
}
} }
@@ -7,14 +7,17 @@ import com.moulberry.flashback.visuals.AccurateEntityPositionHandler;
import net.minecraft.client.Camera; import net.minecraft.client.Camera;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.BlockGetter;
import org.joml.Vector2f; import org.joml.Vector2f;
import org.joml.Vector3d; import org.joml.Vector3d;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Camera.class) @Mixin(Camera.class)
public class MixinCamera { public abstract class MixinCamera {
@Shadow @Shadow
private float eyeHeightOld; private float eyeHeightOld;
@@ -22,28 +25,22 @@ public class MixinCamera {
@Shadow @Shadow
public float eyeHeight; public float eyeHeight;
@WrapOperation(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setRotation(FF)V", ordinal = 0)) @Shadow
public void setRotation(Camera instance, float yaw, float pitch, Operation<Void> original, protected abstract void setRotation(float f, float g);
@Local(argsOnly = true) Entity entity, @Local(argsOnly = true) float partialTick) {
@Shadow
protected abstract void setPosition(double d, double e, double f);
@Inject(method = "setup", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;setPosition(DDD)V", ordinal = 0, shift = At.Shift.AFTER))
public void afterSetPosition(BlockGetter blockGetter, Entity entity, boolean bl, boolean bl2, float partialTick, CallbackInfo ci) {
Vector2f rotation = AccurateEntityPositionHandler.getAccurateRotation(entity, partialTick); Vector2f rotation = AccurateEntityPositionHandler.getAccurateRotation(entity, partialTick);
if (rotation != null) { if (rotation != null) {
pitch = rotation.x; this.setRotation(rotation.y, 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<Void> original,
@Local(argsOnly = true) Entity entity, @Local(argsOnly = true) float partialTick) {
Vector3d position = AccurateEntityPositionHandler.getAccuratePosition(entity, partialTick); Vector3d position = AccurateEntityPositionHandler.getAccuratePosition(entity, partialTick);
if (position != null) { if (position != null) {
x = position.x; this.setPosition(position.x, position.y + Mth.lerp(partialTick, this.eyeHeightOld, this.eyeHeight), position.z);
y = position.y + Mth.lerp(partialTick, this.eyeHeightOld, this.eyeHeight);
z = position.z;
} }
original.call(instance, x, y, z);
} }
} }
@@ -12,6 +12,7 @@ import com.moulberry.flashback.ext.ItemInHandRendererExt;
import com.moulberry.flashback.ext.MinecraftExt; import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.visuals.AccurateEntityPositionHandler; import com.moulberry.flashback.visuals.AccurateEntityPositionHandler;
import com.moulberry.flashback.visuals.CameraRotation; import com.moulberry.flashback.visuals.CameraRotation;
import com.moulberry.flashback.visuals.ReplayVisuals;
import com.moulberry.flashback.visuals.ShaderManager; import com.moulberry.flashback.visuals.ShaderManager;
import net.minecraft.client.Camera; import net.minecraft.client.Camera;
import net.minecraft.client.DeltaTracker; import net.minecraft.client.DeltaTracker;
@@ -26,6 +27,7 @@ import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.PostChain; import net.minecraft.client.renderer.PostChain;
import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.GameType; import net.minecraft.world.level.GameType;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -105,6 +107,14 @@ public abstract class MixinGameRenderer {
original.call(instance, blockGetter, entity, bl, bl2, f); original.call(instance, blockGetter, entity, bl, bl2, f);
} }
@Inject(method = "getNightVisionScale", at = @At("HEAD"), cancellable = true)
private static void getNightVisionScale(LivingEntity livingEntity, float f, CallbackInfoReturnable<Float> cir) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideNightVision) {
cir.setReturnValue(1.0f);
}
}
@WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;rotation()Lorg/joml/Quaternionf;")) @WrapOperation(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/Camera;rotation()Lorg/joml/Quaternionf;"))
public Quaternionf renderLevel(Camera instance, Operation<Quaternionf> original) { public Quaternionf renderLevel(Camera instance, Operation<Quaternionf> original) {
return CameraRotation.modifyViewQuaternion(original.call(instance)); return CameraRotation.modifyViewQuaternion(original.call(instance));
@@ -4,6 +4,7 @@ import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.record.Recorder; import com.moulberry.flashback.record.Recorder;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.prediction.BlockStatePredictionHandler;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.network.ConnectionProtocol; import net.minecraft.network.ConnectionProtocol;
@@ -31,11 +32,17 @@ public class MixinClientLevel {
@Final @Final
private Minecraft minecraft; private Minecraft minecraft;
@Shadow
@Final
private BlockStatePredictionHandler blockStatePredictionHandler;
@Inject(method = "setBlock", at = @At("HEAD")) @Inject(method = "setBlock", at = @At("HEAD"))
public void setBlock(BlockPos blockPos, BlockState blockState, int i, int j, CallbackInfoReturnable<Boolean> cir) { public void setBlock(BlockPos blockPos, BlockState blockState, int i, int j, CallbackInfoReturnable<Boolean> cir) {
Recorder recorder = Flashback.RECORDER; if (this.blockStatePredictionHandler.isPredicting()) {
if (recorder != null && !recorder.isPaused()) { Recorder recorder = Flashback.RECORDER;
recorder.writePacketAsync(new ClientboundBlockUpdatePacket(blockPos.immutable(), blockState), ConnectionProtocol.PLAY); if (recorder != null && !recorder.isPaused()) {
recorder.writePacketAsync(new ClientboundBlockUpdatePacket(blockPos.immutable(), blockState), ConnectionProtocol.PLAY);
}
} }
} }
@@ -12,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BossHealthOverlay.class) @Mixin(BossHealthOverlay.class)
public class MixinBossHealthOverlay { public class MixinBossHealthOverlay {
@Inject(method = "render", at = @At("HEAD"), cancellable = true) @Inject(method = "render", at = @At("HEAD"), cancellable = true, require = 0)
public void render(GuiGraphics guiGraphics, CallbackInfo ci) { public void render(GuiGraphics guiGraphics, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showBossBar) { if (editorState != null && !editorState.replayVisuals.showBossBar) {
@@ -17,7 +17,7 @@ public class MixinClientLevel {
* This code here ensures that the interpolation of yRotO -> yRot will always be the shortest path * This code here ensures that the interpolation of yRotO -> yRot will always be the shortest path
*/ */
@Inject(method = "tickNonPassenger", at = @At("RETURN")) @Inject(method = "tickNonPassenger", at = @At("RETURN"), require = 0)
public void tickNonPassengerEnd(Entity entity, CallbackInfo ci) { public void tickNonPassengerEnd(Entity entity, CallbackInfo ci) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot(); entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot();
@@ -25,7 +25,7 @@ public class MixinClientLevel {
} }
} }
@Inject(method = "tickPassenger", at = @At("RETURN")) @Inject(method = "tickPassenger", at = @At("RETURN"), require = 0)
public void tickPassengerEnd(Entity vehicle, Entity entity, CallbackInfo ci) { public void tickPassengerEnd(Entity vehicle, Entity entity, CallbackInfo ci) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot(); entity.xRotO = Mth.wrapDegrees(entity.xRotO - entity.getXRot()) + entity.getXRot();
@@ -12,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ClientLevel.ClientLevelData.class) @Mixin(ClientLevel.ClientLevelData.class)
public class MixinClientLevelData { public class MixinClientLevelData {
@Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true) @Inject(method = "getDayTime", at = @At("HEAD"), cancellable = true, require = 0)
public void getDayTime(CallbackInfoReturnable<Long> cir) { public void getDayTime(CallbackInfoReturnable<Long> cir) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideTimeOfDay >= 0) { if (editorState != null && editorState.replayVisuals.overrideTimeOfDay >= 0) {
@@ -36,7 +36,7 @@ public abstract class MixinEntityRenderDispatcher {
} }
// Add a yellow outline to selected entity // Add a yellow outline to selected entity
@Inject(method = "render", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", shift = At.Shift.BEFORE)) @Inject(method = "render", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;popPose()V", shift = At.Shift.BEFORE), require = 0)
public void renderAfter(Entity entity, double d, double e, double f, float g, float h, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, CallbackInfo ci) { public void renderAfter(Entity entity, double d, double e, double f, float g, float h, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, CallbackInfo ci) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
if (ReplayUI.isEntitySelected(entity.getUUID())) { if (ReplayUI.isEntitySelected(entity.getUUID())) {
@@ -51,7 +51,7 @@ public abstract class MixinEntityRenderDispatcher {
} }
// Prevent rendering shadows when blocks are turned off // Prevent rendering shadows when blocks are turned off
@WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;renderShadow(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/entity/Entity;FFLnet/minecraft/world/level/LevelReader;F)V")) @WrapWithCondition(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;renderShadow(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/world/entity/Entity;FFLnet/minecraft/world/level/LevelReader;F)V"), require = 0)
public boolean renderShadow(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, float f, float g, LevelReader levelReader, float h) { public boolean renderShadow(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, float f, float g, LevelReader levelReader, float h) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
return editorState == null || editorState.replayVisuals.renderBlocks; return editorState == null || editorState.replayVisuals.renderBlocks;
@@ -15,11 +15,17 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(EntityRenderer.class) @Mixin(EntityRenderer.class)
public class MixinEntityRenderer { public class MixinEntityRenderer {
@Inject(method = "renderNameTag", at = @At("HEAD"), cancellable = true) @Inject(method = "renderNameTag", at = @At("HEAD"), cancellable = true, require = 0)
public void renderNameTag(Entity entity, Component component, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, float f, CallbackInfo ci) { public void renderNameTag(Entity entity, Component component, PoseStack poseStack, MultiBufferSource multiBufferSource, int i, float f, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderNametags) { if (editorState != null) {
ci.cancel(); if (!editorState.replayVisuals.renderNametags) {
ci.cancel();
} else if (editorState.hideNametags.contains(entity.getUUID())) {
ci.cancel();
} else if (editorState.hideDuringExport.contains(entity.getUUID())) {
ci.cancel();
}
} }
} }
@@ -14,7 +14,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(FogRenderer.class) @Mixin(FogRenderer.class)
public class MixinFogRenderer { public class MixinFogRenderer {
@Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true, require = 0)
private static void setupFog(Camera camera, FogRenderer.FogMode fogMode, float f, boolean bl, float g, CallbackInfo ci) { private static void setupFog(Camera camera, FogRenderer.FogMode fogMode, float f, boolean bl, float g, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideFog) { if (editorState != null && editorState.replayVisuals.overrideFog) {
@@ -54,7 +54,7 @@ public abstract class MixinGui {
} }
} }
@Inject(method = "renderChat", at = @At("HEAD"), cancellable = true) @Inject(method = "renderChat", at = @At("HEAD"), cancellable = true, require = 0)
public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { public void renderChat(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showChat) { if (editorState != null && !editorState.replayVisuals.showChat) {
@@ -62,7 +62,7 @@ public abstract class MixinGui {
} }
} }
@Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true) @Inject(method = "renderTitle", at = @At("HEAD"), cancellable = true, require = 0)
public void renderTitle(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { public void renderTitle(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showTitleText) { if (editorState != null && !editorState.replayVisuals.showTitleText) {
@@ -70,7 +70,7 @@ public abstract class MixinGui {
} }
} }
@Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true) @Inject(method = "renderScoreboardSidebar", at = @At("HEAD"), cancellable = true, require = 0)
public void renderScoreboardSidebar(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { public void renderScoreboardSidebar(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showScoreboard) { if (editorState != null && !editorState.replayVisuals.showScoreboard) {
@@ -78,7 +78,7 @@ public abstract class MixinGui {
} }
} }
@Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true) @Inject(method = "renderOverlayMessage", at = @At("HEAD"), cancellable = true, require = 0)
public void renderOverlayMessage(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { public void renderOverlayMessage(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showActionBar) { if (editorState != null && !editorState.replayVisuals.showActionBar) {
@@ -86,7 +86,7 @@ public abstract class MixinGui {
} }
} }
@Inject(method = "renderHotbarAndDecorations", at = @At("HEAD"), cancellable = true) @Inject(method = "renderHotbarAndDecorations", at = @At("HEAD"), cancellable = true, require = 0)
public void renderHotbarAndDecorations(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) { public void renderHotbarAndDecorations(GuiGraphics guiGraphics, DeltaTracker deltaTracker, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.showHotbar) { if (editorState != null && !editorState.replayVisuals.showHotbar) {
@@ -94,7 +94,7 @@ public abstract class MixinGui {
} }
} }
@WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;")) @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;getPlayerMode()Lnet/minecraft/world/level/GameType;"), require = 0)
public GameType renderHotbarAndDecorations_getPlayerMode(MultiPlayerGameMode instance, Operation<GameType> original) { public GameType renderHotbarAndDecorations_getPlayerMode(MultiPlayerGameMode instance, Operation<GameType> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
return this.cameraGameType; return this.cameraGameType;
@@ -102,7 +102,7 @@ public abstract class MixinGui {
return original.call(instance); return original.call(instance);
} }
@WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;canHurtPlayer()Z")) @WrapOperation(method = "renderHotbarAndDecorations", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/MultiPlayerGameMode;canHurtPlayer()Z"), require = 0)
public boolean renderHotbarAndDecorations_canHurtPlayer(MultiPlayerGameMode instance, Operation<Boolean> original) { public boolean renderHotbarAndDecorations_canHurtPlayer(MultiPlayerGameMode instance, Operation<Boolean> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
return this.cameraGameType.isSurvival(); return this.cameraGameType.isSurvival();
@@ -110,14 +110,14 @@ public abstract class MixinGui {
return original.call(instance); return original.call(instance);
} }
@Inject(method = "isExperienceBarVisible", at = @At("HEAD"), cancellable = true) @Inject(method = "isExperienceBarVisible", at = @At("HEAD"), cancellable = true, require = 0)
public void isExperienceBarVisible(CallbackInfoReturnable<Boolean> cir) { public void isExperienceBarVisible(CallbackInfoReturnable<Boolean> cir) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
cir.setReturnValue(this.cameraGameType.isSurvival()); cir.setReturnValue(this.cameraGameType.isSurvival());
} }
} }
@WrapOperation(method = "renderExperienceBar", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getXpNeededForNextLevel()I")) @WrapOperation(method = "renderExperienceBar", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getXpNeededForNextLevel()I"), require = 0)
public int renderExperienceBar_getXpNeededForNextLevel(LocalPlayer instance, Operation<Integer> original) { public int renderExperienceBar_getXpNeededForNextLevel(LocalPlayer instance, Operation<Integer> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
Player player = this.getCameraPlayer(); Player player = this.getCameraPlayer();
@@ -128,7 +128,7 @@ public abstract class MixinGui {
return original.call(instance); return original.call(instance);
} }
@WrapOperation(method = "renderExperienceBar", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceProgress:F")) @WrapOperation(method = "renderExperienceBar", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceProgress:F"), require = 0)
public float renderExperienceBar_experienceProgress(LocalPlayer instance, Operation<Float> original) { public float renderExperienceBar_experienceProgress(LocalPlayer instance, Operation<Float> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
Player player = this.getCameraPlayer(); Player player = this.getCameraPlayer();
@@ -139,7 +139,7 @@ public abstract class MixinGui {
return original.call(instance); return original.call(instance);
} }
@WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getAttackStrengthScale(F)F")) @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getAttackStrengthScale(F)F"), require = 0)
public float renderCrosshair_getAttackStrengthScale(LocalPlayer instance, float partialTick, Operation<Float> original) { public float renderCrosshair_getAttackStrengthScale(LocalPlayer instance, float partialTick, Operation<Float> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
Player player = this.getCameraPlayer(); Player player = this.getCameraPlayer();
@@ -150,7 +150,7 @@ public abstract class MixinGui {
return original.call(instance, partialTick); return original.call(instance, partialTick);
} }
@WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getCurrentItemAttackStrengthDelay()F")) @WrapOperation(method = "renderCrosshair", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;getCurrentItemAttackStrengthDelay()F"), require = 0)
public float renderCrosshair_getCurrentItemAttackStrengthDelay(LocalPlayer instance, Operation<Float> original) { public float renderCrosshair_getCurrentItemAttackStrengthDelay(LocalPlayer instance, Operation<Float> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
Player player = this.getCameraPlayer(); Player player = this.getCameraPlayer();
@@ -161,7 +161,7 @@ public abstract class MixinGui {
return original.call(instance); return original.call(instance);
} }
@WrapOperation(method = "renderExperienceLevel", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceLevel:I")) @WrapOperation(method = "renderExperienceLevel", at = @At(value = "FIELD", target = "Lnet/minecraft/client/player/LocalPlayer;experienceLevel:I"), require = 0)
public int renderExperienceLevel_experienceLevel(LocalPlayer instance, Operation<Integer> original) { public int renderExperienceLevel_experienceLevel(LocalPlayer instance, Operation<Integer> original) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
Player player = this.getCameraPlayer(); Player player = this.getCameraPlayer();
@@ -181,7 +181,7 @@ public abstract class MixinGui {
} }
} }
@Inject(method = "canRenderCrosshairForSpectator", at = @At("HEAD"), cancellable = true) @Inject(method = "canRenderCrosshairForSpectator", at = @At("HEAD"), cancellable = true, require = 0)
public void canRenderCrosshairForSpectator(HitResult hitResult, CallbackInfoReturnable<Boolean> cir) { public void canRenderCrosshairForSpectator(HitResult hitResult, CallbackInfoReturnable<Boolean> cir) {
if (Flashback.isInReplay()) { if (Flashback.isInReplay()) {
if (!Flashback.isExporting() && ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) { if (!Flashback.isExporting() && ReplayUI.isActive() && ReplayUI.imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME) {
@@ -0,0 +1,28 @@
package com.moulberry.flashback.mixin.visuals;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.core.Holder;
import net.minecraft.world.effect.MobEffects;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(LightTexture.class)
public class MixinLightTexture {
@WrapOperation(method = "updateLightTexture", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/player/LocalPlayer;hasEffect(Lnet/minecraft/core/Holder;)Z"), require = 0)
public boolean updateLightTexture_hasEffect(LocalPlayer instance, Holder holder, Operation<Boolean> original) {
if (holder == MobEffects.NIGHT_VISION) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.replayVisuals.overrideNightVision) {
return true;
}
}
return original.call(instance, holder);
}
}
@@ -12,7 +12,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(LivingEntityRenderer.class) @Mixin(LivingEntityRenderer.class)
public class MixinLivingEntityRenderer { public class MixinLivingEntityRenderer {
@Inject(method = "isBodyVisible", at = @At("HEAD"), cancellable = true) @Inject(method = "isBodyVisible", at = @At("HEAD"), cancellable = true, require = 0)
public void isBodyVisible(LivingEntity livingEntity, CallbackInfoReturnable<Boolean> cir) { public void isBodyVisible(LivingEntity livingEntity, CallbackInfoReturnable<Boolean> cir) {
EditorState editorState = EditorStateManager.getCurrent(); EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && editorState.hideDuringExport.contains(livingEntity.getUUID())) { if (editorState != null && editorState.hideDuringExport.contains(livingEntity.getUUID())) {
@@ -19,7 +19,7 @@ public class MixinLoadingOverlay {
@Shadow @Final private Minecraft minecraft; @Shadow @Final private Minecraft minecraft;
// Make overlay disappear instantly if inside replay // Make overlay disappear instantly if inside replay
@Inject(method = "render", at = @At("RETURN")) @Inject(method = "render", at = @At("RETURN"), require = 0)
public void render(GuiGraphics guiGraphics, int i, int j, float f, CallbackInfo ci) { public void render(GuiGraphics guiGraphics, int i, int j, float f, CallbackInfo ci) {
if (this.fadeOutStart != -1 && Flashback.isInReplay()) { if (this.fadeOutStart != -1 && Flashback.isInReplay()) {
this.minecraft.setOverlay(null); this.minecraft.setOverlay(null);
@@ -10,7 +10,7 @@ import org.spongepowered.asm.mixin.injection.At;
@Mixin(RenderStateShard.class) @Mixin(RenderStateShard.class)
public class MixinRenderStateShard { public class MixinRenderStateShard {
@WrapOperation(method = "setupGlintTexturing", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J")) @WrapOperation(method = "setupGlintTexturing", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;getMillis()J"), require = 0)
private static long setupGlintTexturing(Operation<Long> original) { private static long setupGlintTexturing(Operation<Long> original) {
if (Flashback.isExporting()) { if (Flashback.isExporting()) {
double currentTick = Flashback.EXPORT_JOB.getCurrentTickDouble(); double currentTick = Flashback.EXPORT_JOB.getCurrentTickDouble();
@@ -40,4 +40,7 @@ public class FakePlayer extends ServerPlayer {
public void awardStat(Stat<?> stat, int i) { public void awardStat(Stat<?> stat, int i) {
} }
@Override
public void resetStat(Stat<?> stat) {
}
} }
@@ -3,6 +3,7 @@ package com.moulberry.flashback.playback;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.moulberry.flashback.exception.UnsupportedPacketException; import com.moulberry.flashback.exception.UnsupportedPacketException;
import com.moulberry.flashback.registry.RegistryHelper; import com.moulberry.flashback.registry.RegistryHelper;
import net.fabricmc.fabric.api.event.registry.DynamicRegistries;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
@@ -77,14 +78,6 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack
boolean sendTags = false; boolean sendTags = false;
if (this.pendingTags != null && !this.pendingTags.isEmpty()) {
this.pendingTags.forEach((resourceKey, networkPayload) -> {
networkPayload.applyToRegistry(this.replayServer.registryAccess().registryOrThrow(resourceKey));
});
sendTags = true;
this.pendingTags = null;
}
List<ConfigurationTask> configurationTasks = new ArrayList<>(); List<ConfigurationTask> configurationTasks = new ArrayList<>();
FeatureFlagSet currentFeatureFlags = this.replayServer.worldData.enabledFeatures(); FeatureFlagSet currentFeatureFlags = this.replayServer.worldData.enabledFeatures();
List<KnownPack> currentKnownPacks = this.replayServer.getResourceManager().listPacks().flatMap(packResources -> packResources.location().knownPackInfo().stream()).toList(); List<KnownPack> currentKnownPacks = this.replayServer.getResourceManager().listPacks().flatMap(packResources -> packResources.location().knownPackInfo().stream()).toList();
@@ -130,7 +123,7 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack
if (!RegistryHelper.equals(this.replayServer.registryAccess(), synchronizedRegistries, RegistryDataLoader.SYNCHRONIZED_REGISTRIES)) { if (!RegistryHelper.equals(this.replayServer.registryAccess(), synchronizedRegistries, RegistryDataLoader.SYNCHRONIZED_REGISTRIES)) {
Set<ResourceKey<?>> neededRegistries = new HashSet<>(); Set<ResourceKey<?>> neededRegistries = new HashSet<>();
for (RegistryDataLoader.RegistryData<?> worldgenRegistry : RegistryDataLoader.WORLDGEN_REGISTRIES) { for (RegistryDataLoader.RegistryData<?> worldgenRegistry : DynamicRegistries.getDynamicRegistries()) {
neededRegistries.add(worldgenRegistry.key()); neededRegistries.add(worldgenRegistry.key());
} }
@@ -162,12 +155,17 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack
} }
} }
if (synchronizeRegistries) { if (this.pendingTags != null && !this.pendingTags.isEmpty()) {
configurationTasks.add(new SynchronizeRegistriesTask(currentKnownPacks, this.replayServer.registries)); this.pendingTags.forEach((resourceKey, networkPayload) -> {
sendTags = false; networkPayload.applyToRegistry(this.replayServer.registryAccess().registryOrThrow(resourceKey));
});
sendTags = true;
this.pendingTags = null;
} }
if (sendTags) { if (synchronizeRegistries) {
configurationTasks.add(new SynchronizeRegistriesTask(currentKnownPacks, this.replayServer.registries));
} else if (sendTags) {
this.replayServer.getPlayerList().broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.replayServer.registries))); this.replayServer.getPlayerList().broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.replayServer.registries)));
} }
@@ -201,6 +199,7 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack
false, 0, List.of(), false, null); false, 0, List.of(), false, null);
serverLevel.noSave = true; serverLevel.noSave = true;
this.replayServer.levels.put(Level.OVERWORLD, serverLevel); this.replayServer.levels.put(Level.OVERWORLD, serverLevel);
this.replayServer.getPlayerList().addWorldborderListener(serverLevel);
} }
private static Collection<String> knownPacksToIds(PackRepository packRepository, Collection<KnownPack> knownPacks) { private static Collection<String> knownPacksToIds(PackRepository packRepository, Collection<KnownPack> knownPacks) {
@@ -24,6 +24,7 @@ import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.Connection; import net.minecraft.network.Connection;
import net.minecraft.network.DisconnectionDetails; import net.minecraft.network.DisconnectionDetails;
import net.minecraft.network.PacketSendListener;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.ByteBufCodecs; import net.minecraft.network.codec.ByteBufCodecs;
@@ -149,11 +150,14 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
} }
((ServerLevelExt) level).flashback$setCanSpawnEntities(true); ((ServerLevelExt) level).flashback$setCanSpawnEntities(true);
level.addFreshEntity(pendingEntity); try {
level.addFreshEntity(pendingEntity);
ChunkPos chunkPos = new ChunkPos(pendingEntity.blockPosition());
level.getChunkSource().addRegionTicket(ReplayServer.ENTITY_LOAD_TICKET, chunkPos, 3, chunkPos);
} catch (Exception e) {
Flashback.LOGGER.error("Unable to spawn entity", e);
}
((ServerLevelExt) level).flashback$setCanSpawnEntities(false); ((ServerLevelExt) level).flashback$setCanSpawnEntities(false);
ChunkPos chunkPos = new ChunkPos(pendingEntity.blockPosition());
level.getChunkSource().addRegionTicket(ReplayServer.ENTITY_LOAD_TICKET, chunkPos, 3, chunkPos);
} }
this.pendingEntities.clear(); this.pendingEntities.clear();
} }
@@ -198,7 +202,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
gameProfile.getProperties().removeAll("IsReplayViewer"); gameProfile.getProperties().removeAll("IsReplayViewer");
CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false); CommonListenerCookie commonListenerCookie = CommonListenerCookie.createInitial(gameProfile, false);
ServerPlayer serverPlayer = new FakePlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()){ ServerPlayer serverPlayer = new FakePlayer(this.replayServer, this.level(), commonListenerCookie.gameProfile(), commonListenerCookie.clientInformation()) {
@Override @Override
public boolean isSpectator() { public boolean isSpectator() {
return false; return false;
@@ -230,12 +234,25 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
} }
} }
Connection connection = new Connection(PacketFlow.SERVERBOUND); Connection connection = new Connection(PacketFlow.SERVERBOUND) {
@Override
public void send(Packet<?> packet, @Nullable PacketSendListener packetSendListener, boolean bl) {}
};
EmbeddedChannel embeddedChannel = new EmbeddedChannel(connection); EmbeddedChannel embeddedChannel = new EmbeddedChannel(connection);
serverPlayer.recreateFromPacket(addEntityPacket); serverPlayer.recreateFromPacket(addEntityPacket);
this.replayServer.getPlayerList().placeNewPlayer(connection, serverPlayer, commonListenerCookie); try {
this.replayServer.getPlayerList().placeNewPlayer(connection, serverPlayer, commonListenerCookie);
} catch (Exception e) {
Flashback.LOGGER.error("Failed to spawn player", e);
return null;
}
serverPlayer.setGameMode(gameType); serverPlayer.setGameMode(gameType);
if (serverPlayer.isRemoved()) {
Flashback.LOGGER.error("ServerPlayer {} was removed while spawning. Incompatible mod?", serverPlayer.getUUID());
return null;
}
return serverPlayer; return serverPlayer;
} }
@@ -705,6 +722,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
false, commonPlayerSpawnInfo.seed(), List.of(), false, null); false, commonPlayerSpawnInfo.seed(), List.of(), false, null);
serverLevel.noSave = true; serverLevel.noSave = true;
this.replayServer.levels.put(dimension, serverLevel); this.replayServer.levels.put(dimension, serverLevel);
this.replayServer.getPlayerList().addWorldborderListener(serverLevel);
if (oldLevel != null) { if (oldLevel != null) {
this.replayServer.closeLevel(oldLevel); this.replayServer.closeLevel(oldLevel);
@@ -894,6 +912,9 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
0, Vec3.ZERO, oldServerPlayer.getYHeadRot()); 0, Vec3.ZERO, oldServerPlayer.getYHeadRot());
ServerPlayer newServerPlayer = this.spawnPlayer(addEntityPacket, oldServerPlayer.getGameProfile(), oldServerPlayer.gameMode.getGameModeForPlayer()); ServerPlayer newServerPlayer = this.spawnPlayer(addEntityPacket, oldServerPlayer.getGameProfile(), oldServerPlayer.gameMode.getGameModeForPlayer());
if (newServerPlayer == null) {
return;
}
if (clientboundRespawnPacket.shouldKeep((byte)2)) { if (clientboundRespawnPacket.shouldKeep((byte)2)) {
newServerPlayer.setShiftKeyDown(oldServerPlayer.isShiftKeyDown()); newServerPlayer.setShiftKeyDown(oldServerPlayer.isShiftKeyDown());
@@ -34,6 +34,7 @@ import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet; import it.unimi.dsi.fastutil.ints.IntSet;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.server.IntegratedServer; import net.minecraft.client.server.IntegratedServer;
@@ -349,6 +350,9 @@ public class ReplayServer extends IntegratedServer {
// Send tab list customization // Send tab list customization
serverPlayer.connection.send(new ClientboundTabListPacket(tabListHeader, tabListFooter)); serverPlayer.connection.send(new ClientboundTabListPacket(tabListHeader, tabListFooter));
// Send world border
serverPlayer.connection.send(new ClientboundInitializeBorderPacket(serverLevel.getWorldBorder()));
} }
@Override @Override
@@ -372,7 +376,8 @@ public class ReplayServer extends IntegratedServer {
} }
}); });
this.loadLevel(); super.initServer();
this.overworld().noSave = true; this.overworld().noSave = true;
return true; return true;
@@ -764,12 +769,17 @@ public class ReplayServer extends IntegratedServer {
} }
} }
// Pause replay if game is paused (by opening the ESC pause menu for example)
if (!this.replayPaused && this.isPaused()) {
this.replayPaused = true;
}
// Update current tick // Update current tick
boolean normalPlayback = false; boolean normalPlayback = false;
if (this.jumpToTick >= 0) { if (this.jumpToTick >= 0) {
this.targetTick = this.jumpToTick; this.targetTick = this.jumpToTick;
this.jumpToTick = -1; this.jumpToTick = -1;
} else if (!this.isPaused() && !this.replayPaused && this.targetTick < this.totalTicks) { } else if (!this.replayPaused && this.targetTick < this.totalTicks) {
// Normal playback // Normal playback
this.targetTick += 1; this.targetTick += 1;
normalPlayback = true; normalPlayback = true;
@@ -825,6 +835,7 @@ public class ReplayServer extends IntegratedServer {
if (camera == null || camera == replayViewer || camera.isRemoved()) { if (camera == null || camera == replayViewer || camera.isRemoved()) {
Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid); Entity targetEntity = replayViewer.serverLevel().getEntity(replayViewer.spectatingUuid);
if (targetEntity != null && !targetEntity.isRemoved()) { if (targetEntity != null && !targetEntity.isRemoved()) {
replayViewer.setCamera(null);
replayViewer.setCamera(targetEntity); replayViewer.setCamera(targetEntity);
} }
} }
@@ -1076,13 +1087,7 @@ public class ReplayServer extends IntegratedServer {
if (shouldJump) { if (shouldJump) {
this.processedSnapshot = true; this.processedSnapshot = true;
// Clear bossbars and particles this.clearDataForPlayingSnapshot();
for (ReplayPlayer replayViewer : this.replayViewers) {
for (UUID uuid : this.bossEvents.keySet()) {
replayViewer.connection.send(ClientboundBossEventPacket.createRemovePacket(uuid));
}
}
this.bossEvents.clear();
Map.Entry<Integer, PlayableChunk> entry = this.playableChunksByStart.floorEntry(this.targetTick); Map.Entry<Integer, PlayableChunk> entry = this.playableChunksByStart.floorEntry(this.targetTick);
ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); ReplayReader replayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess());
@@ -1099,6 +1104,12 @@ public class ReplayServer extends IntegratedServer {
this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess());
if (this.currentTick == entry.getKey()) { if (this.currentTick == entry.getKey()) {
this.currentReplayReader.resetToStart(); this.currentReplayReader.resetToStart();
if (!this.processedSnapshot && entry.getValue().chunkMeta.forcePlaySnapshot) {
this.processedSnapshot = true;
this.clearDataForPlayingSnapshot();
this.currentReplayReader.handleSnapshot(this);
}
} }
while (this.currentTick < this.targetTick) { while (this.currentTick < this.targetTick) {
@@ -1121,6 +1132,12 @@ public class ReplayServer extends IntegratedServer {
this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess()); this.currentReplayReader = entry.getValue().getOrLoadReplayReader(this.registryAccess());
this.currentReplayReader.resetToStart(); this.currentReplayReader.resetToStart();
if (entry.getValue().chunkMeta.forcePlaySnapshot) {
this.processedSnapshot = true;
this.clearDataForPlayingSnapshot();
this.currentReplayReader.handleSnapshot(this);
}
} }
if (entry.getKey() + entry.getValue().chunkMeta.duration < this.currentTick) { if (entry.getKey() + entry.getValue().chunkMeta.duration < this.currentTick) {
@@ -1135,6 +1152,15 @@ public class ReplayServer extends IntegratedServer {
this.currentReplayReader = null; this.currentReplayReader = null;
} }
private void clearDataForPlayingSnapshot() {
for (ReplayPlayer replayViewer : this.replayViewers) {
for (UUID uuid : this.bossEvents.keySet()) {
replayViewer.connection.send(ClientboundBossEventPacket.createRemovePacket(uuid));
}
}
this.bossEvents.clear();
}
private void tryFollowLocalPlayer() { private void tryFollowLocalPlayer() {
if (this.spawnLevel == null) { if (this.spawnLevel == null) {
return; return;
@@ -1219,10 +1245,10 @@ public class ReplayServer extends IntegratedServer {
Files.walkFileTree(temp, new SimpleFileVisitor<>() { Files.walkFileTree(temp, new SimpleFileVisitor<>() {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) { if (!Files.isDirectory(file)) {
Files.deleteIfExists(file); Files.deleteIfExists(file);
} }
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
}); });
} catch (IOException e) { } catch (IOException e) {
@@ -5,10 +5,12 @@ import org.jetbrains.annotations.Nullable;
public class FlashbackChunkMeta { public class FlashbackChunkMeta {
public int duration = 0; public int duration = 0;
public boolean forcePlaySnapshot = false;
public JsonObject toJson() { public JsonObject toJson() {
JsonObject chunkMeta = new JsonObject(); JsonObject chunkMeta = new JsonObject();
chunkMeta.addProperty("duration", this.duration); chunkMeta.addProperty("duration", this.duration);
chunkMeta.addProperty("forcePlaySnapshot", this.forcePlaySnapshot);
return chunkMeta; return chunkMeta;
} }
@@ -20,6 +22,9 @@ public class FlashbackChunkMeta {
return null; return null;
} }
flashbackChunkMeta.duration = chunkMeta.get("duration").getAsInt(); flashbackChunkMeta.duration = chunkMeta.get("duration").getAsInt();
if (chunkMeta.has("forcePlaySnapshot")) {
flashbackChunkMeta.forcePlaySnapshot = chunkMeta.get("forcePlaySnapshot").getAsBoolean();
}
return flashbackChunkMeta; return flashbackChunkMeta;
} }
@@ -6,7 +6,9 @@ import com.google.gson.JsonObject;
import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.FlashbackGson;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -27,6 +29,8 @@ public class FlashbackMeta {
public int totalTicks = -1; public int totalTicks = -1;
public LinkedHashMap<String, FlashbackChunkMeta> chunks = new LinkedHashMap<>(); public LinkedHashMap<String, FlashbackChunkMeta> chunks = new LinkedHashMap<>();
public Map<String, File> distantHorizonPaths = new HashMap<>();
public JsonObject toJson() { public JsonObject toJson() {
JsonObject meta = new JsonObject(); JsonObject meta = new JsonObject();
meta.addProperty("uuid", this.replayIdentifier.toString()); meta.addProperty("uuid", this.replayIdentifier.toString());
@@ -57,6 +61,15 @@ public class FlashbackMeta {
meta.add("markers", jsonMarkers); meta.add("markers", jsonMarkers);
} }
// Distant horizons
if (!this.distantHorizonPaths.isEmpty()) {
JsonObject distantHorizonPaths = new JsonObject();
for (Map.Entry<String, File> entry : this.distantHorizonPaths.entrySet()) {
distantHorizonPaths.addProperty(entry.getKey(), entry.getValue().getPath());
}
meta.add("distantHorizonPaths", distantHorizonPaths);
}
JsonObject chunksJson = new JsonObject(); JsonObject chunksJson = new JsonObject();
for (Map.Entry<String, FlashbackChunkMeta> entry : this.chunks.entrySet()) { for (Map.Entry<String, FlashbackChunkMeta> entry : this.chunks.entrySet()) {
chunksJson.add(entry.getKey(), entry.getValue().toJson()); chunksJson.add(entry.getKey(), entry.getValue().toJson());
@@ -110,6 +123,14 @@ public class FlashbackMeta {
} }
} }
// Distant horizons
if (meta.has("distantHorizonPaths")) {
JsonObject distantHorizonPaths = meta.getAsJsonObject("distantHorizonPaths");
for (Map.Entry<String, JsonElement> entry : distantHorizonPaths.entrySet()) {
flashbackMeta.distantHorizonPaths.put(entry.getKey(), new File(entry.getValue().getAsString()));
}
}
// Chunks // Chunks
if (!meta.has("chunks")) { if (!meta.has("chunks")) {
return null; return null;
@@ -2,11 +2,13 @@ package com.moulberry.flashback.record;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.datafixers.util.Pair; import com.mojang.datafixers.util.Pair;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.PacketHelper; import com.moulberry.flashback.PacketHelper;
import com.moulberry.flashback.action.*; import com.moulberry.flashback.action.*;
import com.moulberry.flashback.compat.DistantHorizonsSupport;
import com.moulberry.flashback.io.AsyncReplaySaver; import com.moulberry.flashback.io.AsyncReplaySaver;
import com.moulberry.flashback.io.ReplayWriter; import com.moulberry.flashback.io.ReplayWriter;
import com.moulberry.flashback.mixin.compat.bobby.FakeChunkManagerAccessor; import com.moulberry.flashback.mixin.compat.bobby.FakeChunkManagerAccessor;
@@ -29,12 +31,12 @@ import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.resources.server.ServerPackManager; import net.minecraft.client.resources.server.ServerPackManager;
import net.minecraft.core.*; import net.minecraft.core.*;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag; import net.minecraft.nbt.Tag;
import net.minecraft.network.ConnectionProtocol; import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket; import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
@@ -58,7 +60,6 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.Leashable; import net.minecraft.world.entity.Leashable;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.AttributeInstance; import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.flag.FeatureFlags; import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.food.FoodData; import net.minecraft.world.food.FoodData;
@@ -76,6 +77,7 @@ import net.minecraft.world.phys.Vec3;
import net.minecraft.world.scores.*; import net.minecraft.world.scores.*;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
@@ -150,12 +152,20 @@ public class Recorder {
this.metadata.bobbyWorldName = bobbyWorldName; this.metadata.bobbyWorldName = bobbyWorldName;
} catch (Throwable t) {} } catch (Throwable t) {}
} }
if (Flashback.supportsDistantHorizons) {
this.metadata.distantHorizonPaths.putAll(DistantHorizonsSupport.getDimensionPaths());
}
} }
public boolean readyToWrite() { public boolean readyToWrite() {
return !this.closeForWriting && !this.needsInitialSnapshot && !this.wasPaused; return !this.closeForWriting && !this.needsInitialSnapshot && !this.wasPaused;
} }
public void putDistantHorizonsPaths(Map<String, File> paths) {
this.metadata.distantHorizonPaths.putAll(paths);
}
public void addMarker(ReplayMarker marker) { public void addMarker(ReplayMarker marker) {
this.metadata.replayMarkers.put(this.writtenTicks, marker); this.metadata.replayMarkers.put(this.writtenTicks, marker);
} }
@@ -231,6 +241,7 @@ public class Recorder {
int localPlayerUpdatesPerSecond = Flashback.getConfig().localPlayerUpdatesPerSecond; int localPlayerUpdatesPerSecond = Flashback.getConfig().localPlayerUpdatesPerSecond;
boolean trackAccurateFirstPersonPosition = localPlayerUpdatesPerSecond > 20; boolean trackAccurateFirstPersonPosition = localPlayerUpdatesPerSecond > 20;
boolean wroteNewTick = false;
if (minecraft.level != null && (minecraft.getOverlay() == null || !minecraft.getOverlay().isPauseScreen()) && if (minecraft.level != null && (minecraft.getOverlay() == null || !minecraft.getOverlay().isPauseScreen()) &&
!minecraft.isPaused() && !this.isPaused && isLevelLoaded) { !minecraft.isPaused() && !this.isPaused && isLevelLoaded) {
@@ -241,6 +252,7 @@ public class Recorder {
this.writeAccurateFirstPersonPosition(localPlayerUpdatesPerSecond); this.writeAccurateFirstPersonPosition(localPlayerUpdatesPerSecond);
} }
wroteNewTick = true;
this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE));
this.writtenTicksInChunk += 1; this.writtenTicksInChunk += 1;
this.writtenTicks += 1; this.writtenTicks += 1;
@@ -274,7 +286,7 @@ public class Recorder {
if (writeChunk) { if (writeChunk) {
// Add an extra tick to avoid edge-cases with 0-length replay chunks // Add an extra tick to avoid edge-cases with 0-length replay chunks
if (this.writtenTicksInChunk == 0) { if (this.writtenTicksInChunk == 0 || !wroteNewTick) {
this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE)); this.asyncReplaySaver.submit(writer -> writer.startAndFinishAction(ActionNextTick.INSTANCE));
this.writtenTicksInChunk += 1; this.writtenTicksInChunk += 1;
this.writtenTicks += 1; this.writtenTicks += 1;
@@ -631,6 +643,13 @@ public class Recorder {
gamePackets.add(((Packet<? super ClientGamePacketListener>) packet.packet)); gamePackets.add(((Packet<? super ClientGamePacketListener>) packet.packet));
if (packet.packet instanceof ClientboundLoginPacket) {
this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets);
gamePackets.clear();
this.writeCreateLocalPlayer();
}
if (this.isConfiguring) { if (this.isConfiguring) {
endedConfiguration = true; endedConfiguration = true;
this.isConfiguring = false; this.isConfiguring = false;
@@ -664,6 +683,44 @@ public class Recorder {
return endedConfiguration; return endedConfiguration;
} }
private void writeCreateLocalPlayer() {
LocalPlayer localPlayer = Minecraft.getInstance().player;
if (localPlayer != null) {
UUID uuid = localPlayer.getUUID();
double x = localPlayer.getX();
double y = localPlayer.getY();
double z = localPlayer.getZ();
float xRot = localPlayer.getXRot();
float yRot = localPlayer.getYRot();
float yHeadRot = localPlayer.getYHeadRot();
Vec3 deltaMovement = localPlayer.getDeltaMovement();
GameProfile currentProfile = localPlayer.getGameProfile();
GameProfile newProfile = new GameProfile(currentProfile.getId(), currentProfile.getName());
newProfile.getProperties().putAll(Minecraft.getInstance().getGameProfile().getProperties());
newProfile.getProperties().putAll(currentProfile.getProperties());
int gameModeId = Minecraft.getInstance().gameMode.getPlayerMode().getId();
this.asyncReplaySaver.submit(writer -> {
writer.startAction(ActionCreateLocalPlayer.INSTANCE);
RegistryFriendlyByteBuf registryFriendlyByteBuf = writer.friendlyByteBuf();
registryFriendlyByteBuf.writeUUID(uuid);
registryFriendlyByteBuf.writeDouble(x);
registryFriendlyByteBuf.writeDouble(y);
registryFriendlyByteBuf.writeDouble(z);
registryFriendlyByteBuf.writeFloat(xRot);
registryFriendlyByteBuf.writeFloat(yRot);
registryFriendlyByteBuf.writeFloat(yHeadRot);
registryFriendlyByteBuf.writeVec3(deltaMovement);
ByteBufCodecs.GAME_PROFILE.encode(registryFriendlyByteBuf, newProfile);
registryFriendlyByteBuf.writeVarInt(gameModeId);
writer.finishAction(ActionCreateLocalPlayer.INSTANCE);
});
}
}
public void writeLevelEvent(int type, BlockPos blockPos, int data, boolean globalEvent) { public void writeLevelEvent(int type, BlockPos blockPos, int data, boolean globalEvent) {
if (!this.readyToWrite()) { if (!this.readyToWrite()) {
return; return;
@@ -798,6 +855,11 @@ public class Recorder {
localPlayer.isReducedDebugInfo(), localPlayer.shouldShowDeathScreen(), localPlayer.getDoLimitedCrafting(), commonPlayerSpawnInfo, false); localPlayer.isReducedDebugInfo(), localPlayer.shouldShowDeathScreen(), localPlayer.getDoLimitedCrafting(), commonPlayerSpawnInfo, false);
gamePackets.add(loginPacket); gamePackets.add(loginPacket);
// Write local player
this.asyncReplaySaver.writeGamePackets(this.gamePacketCodec, gamePackets);
gamePackets.clear();
this.writeCreateLocalPlayer();
// Create player info update packet // Create player info update packet
var infoUpdatePacket = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER, var infoUpdatePacket = new ClientboundPlayerInfoUpdatePacket(EnumSet.of(ClientboundPlayerInfoUpdatePacket.Action.ADD_PLAYER,
ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LISTED, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), List.of()); ClientboundPlayerInfoUpdatePacket.Action.UPDATE_LISTED, ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME), List.of());
@@ -910,7 +972,6 @@ public class Recorder {
for (int i = 0; i < chunks.length(); i++) { for (int i = 0; i < chunks.length(); i++) {
LevelChunk chunk = chunks.get(i); LevelChunk chunk = chunks.get(i);
if (chunk != null) { 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())); var task = pool.submit(() -> new ClientboundLevelChunkWithLightPacket(chunk, level.getLightEngine(), new BitSet(), new BitSet()));
levelChunkPacketTasks.add(new PositionedTask(chunk.getPos(), task)); levelChunkPacketTasks.add(new PositionedTask(chunk.getPos(), task));
} }
@@ -0,0 +1,195 @@
package com.moulberry.flashback.screen;
import com.mojang.serialization.Lifecycle;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.io.ReplayCombiner;
import com.moulberry.flashback.playback.EmptyLevelSource;
import com.moulberry.flashback.record.FlashbackMeta;
import net.minecraft.Util;
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.client.gui.screens.TitleScreen;
import net.minecraft.commands.Commands;
import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.server.WorldLoader;
import net.minecraft.server.WorldStem;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.level.DataPackConfig;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.WorldDataConfiguration;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.WorldDimensions;
import net.minecraft.world.level.levelgen.WorldOptions;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
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.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
public class CombineReplayScreen extends Screen {
@Nullable
private final Screen lastScreen;
private String newReplayName = "Combined Replay";
private Path firstReplay;
private Path secondReplay;
private Path output;
private Button firstReplayButton;
private Button secondReplayButton;
private Button outputButton;
protected CombineReplayScreen(@Nullable Screen lastScreen, @Nullable Path firstReplay, @Nullable Path secondReplay, @Nullable Path output) {
super(Component.literal("Combine Replay"));
this.lastScreen = lastScreen;
this.firstReplay = firstReplay;
this.secondReplay = secondReplay;
this.output = output;
}
@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("Combine Replay"), this.font), 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("New Replay Name"), this.font).alignLeft(), 2);
EditBox replayNameEditBox = new EditBox(this.font, 0, 0, 204, 20, Component.literal(this.newReplayName));
replayNameEditBox.setValue(this.newReplayName);
replayNameEditBox.setResponder(string -> this.newReplayName = string);
rowHelper.addChild(replayNameEditBox, 2);
Path replayFolder = Flashback.getReplayFolder();
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Source #1"), this.font).alignLeft(), 2);
String firstReplayPath = this.firstReplay == null ? "" : this.firstReplay.toString();
this.firstReplayButton = Button.builder(Component.literal(firstReplayPath), button -> {
CompletableFuture<String> future = AsyncFileDialogs.openFileDialog(replayFolder.toString(),
"Replay Archive", "zip");
future.thenAccept(pathStr -> {
if (pathStr != null) {
this.firstReplay = Path.of(pathStr);
this.firstReplayButton.setMessage(Component.literal(this.firstReplay.toString()));
}
});
}).width(204).build();
rowHelper.addChild(this.firstReplayButton, 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Source #2"), this.font).alignLeft(), 2);
String secondReplayPath = this.secondReplay == null ? "" : this.secondReplay.toString();
this.secondReplayButton = Button.builder(Component.literal(secondReplayPath), button -> {
CompletableFuture<String> future = AsyncFileDialogs.openFileDialog(replayFolder.toString(),
"Replay Archive", "zip");
future.thenAccept(pathStr -> {
if (pathStr != null) {
this.secondReplay = Path.of(pathStr);
this.secondReplayButton.setMessage(Component.literal(this.secondReplay.toString()));
}
});
}).width(204).build();
rowHelper.addChild(this.secondReplayButton, 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal("Output"), this.font).alignLeft(), 2);
String outputPath = this.output == null ? "" : this.output.toString();
this.outputButton = Button.builder(Component.literal(outputPath), button -> {
CompletableFuture<String> future = AsyncFileDialogs.saveFileDialog(replayFolder.toString(), "combined.zip",
"Replay Archive", "zip");
future.thenAccept(pathStr -> {
if (pathStr != null) {
this.output = Path.of(pathStr);
this.outputButton.setMessage(Component.literal(this.output.toString()));
}
});
}).width(204).build();
rowHelper.addChild(this.outputButton, 2);
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2);
rowHelper.addChild(Button.builder(Component.literal("Combine Replays"), button -> {
try {
PackRepository packRepository = ServerPacksSource.createVanillaTrustedRepository();
packRepository.reload();
WorldDataConfiguration worldDataConfiguration = new WorldDataConfiguration(new DataPackConfig(List.of(), List.of()), FeatureFlags.DEFAULT_FLAGS);
LevelSettings levelSettings = new LevelSettings("Replay", GameType.SPECTATOR, false, Difficulty.NORMAL, true, new GameRules(), worldDataConfiguration);
WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packRepository, worldDataConfiguration, false, true);
WorldLoader.InitConfig initConfig = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, 4);
WorldStem worldStem = Util.blockUntilDone(executor -> WorldLoader.load(initConfig, dataLoadContext -> {
Registry<LevelStem> registry = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
Holder.Reference<Biome> plains = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.BIOME).getHolder(Biomes.PLAINS).get();
Holder.Reference<DimensionType> overworld = dataLoadContext.datapackWorldgen().registryOrThrow(Registries.DIMENSION_TYPE).getHolder(BuiltinDimensionTypes.OVERWORLD).get();
WorldDimensions worldDimensions = new WorldDimensions(Map.of(LevelStem.OVERWORLD, new LevelStem(overworld, new EmptyLevelSource(plains))));
WorldDimensions.Complete complete = worldDimensions.bake(registry);
return new WorldLoader.DataLoadOutput<>(new PrimaryLevelData(levelSettings, new WorldOptions(0L, false, false),
complete.specialWorldProperty(), complete.lifecycle()), complete.dimensionsRegistryAccess());
}, WorldStem::new, Util.backgroundExecutor(), executor)).get();
ReplayCombiner.combine(worldStem.registries().compositeAccess(), this.firstReplay, this.secondReplay, this.output);
Minecraft.getInstance().setScreen(new TitleScreen());
worldStem.close();
} catch (Exception e) {
Flashback.LOGGER.error("Error combining replays", e);
Minecraft.getInstance().setScreen(new AlertScreen(() -> Minecraft.getInstance().setScreen(this.lastScreen),
Component.literal("Unable to combine replays"), Component.literal(e.getMessage())));
}
}).width(98).build(), 1);
rowHelper.addChild(Button.builder(Component.literal("Cancel"), button -> {
Minecraft.getInstance().setScreen(this.lastScreen);
}).width(98).build(), 1);
gridLayout.arrangeElements();
FrameLayout.alignInRectangle(gridLayout, 0, 0, this.width, this.height, 0.5f, 0.5f);
gridLayout.visitWidgets(this::addRenderableWidget);
}
@Override
public void onClose() {
this.minecraft.setScreen(this.lastScreen);
}
}
@@ -63,6 +63,10 @@ public class EditReplayScreen extends Screen {
rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2); rowHelper.addChild(new BottomTextWidget(204, 10, Component.literal(""), this.font), 2);
rowHelper.addChild(Button.builder(Component.literal("Combine With Other Replay"), button -> {
this.minecraft.setScreen(new CombineReplayScreen(this, this.replayPath, null, null));
}).width(204).build(), 2);
this.saveChangesButton = rowHelper.addChild(Button.builder(Component.literal("Save Changes"), button -> { this.saveChangesButton = rowHelper.addChild(Button.builder(Component.literal("Save Changes"), button -> {
this.applyChanges(); this.applyChanges();
}).width(98).build()); }).width(98).build());
@@ -19,6 +19,7 @@ import net.minecraft.Util;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.ObjectSelectionList; import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.components.WidgetSprites;
import net.minecraft.client.gui.components.toasts.SystemToast; import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.navigation.CommonInputs; import net.minecraft.client.gui.navigation.CommonInputs;
@@ -62,6 +63,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
private List<ReplaySummary> currentlyDisplayedReplays; private List<ReplaySummary> currentlyDisplayedReplays;
private String filter; private String filter;
private final LoadingHeader loadingHeader; private final LoadingHeader loadingHeader;
private final LoadFromDeviceHeader loadFromDeviceHeader;
private Map<UUID, Long> lastOpenTimes = null; private Map<UUID, Long> lastOpenTimes = null;
@@ -69,6 +71,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
super(minecraft, i, j, k, l); super(minecraft, i, j, k, l);
this.screen = selectReplayScreen; this.screen = selectReplayScreen;
this.loadingHeader = new LoadingHeader(minecraft); this.loadingHeader = new LoadingHeader(minecraft);
this.loadFromDeviceHeader = new LoadFromDeviceHeader(minecraft);
this.filter = string; this.filter = string;
this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays(); this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays();
this.handleNewReplays(this.pollReplaysIgnoreErrors()); this.handleNewReplays(this.pollReplaysIgnoreErrors());
@@ -239,6 +242,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
private void fillReplays(String string, List<ReplaySummary> list) { private void fillReplays(String string, List<ReplaySummary> list) {
this.clearEntries(); this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
string = string.toLowerCase(Locale.ROOT); string = string.toLowerCase(Locale.ROOT);
for (ReplaySummary ReplaySummary : list) { for (ReplaySummary ReplaySummary : list) {
if (!this.filterAccepts(string, ReplaySummary)) continue; if (!this.filterAccepts(string, ReplaySummary)) continue;
@@ -253,6 +257,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
private void fillLoadingReplays() { private void fillLoadingReplays() {
this.clearEntries(); this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
this.addEntry(this.loadingHeader); this.addEntry(this.loadingHeader);
this.notifyListUpdated(); this.notifyListUpdated();
} }
@@ -270,6 +275,11 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
@Override @Override
public void setSelected(@Nullable Entry entry) { public void setSelected(@Nullable Entry entry) {
if (entry instanceof LoadFromDeviceHeader) {
Flashback.openReplayFromFileBrowser();
return;
}
super.setSelected(entry); super.setSelected(entry);
if (entry instanceof ReplayListEntry replayListEntry) { if (entry instanceof ReplayListEntry replayListEntry) {
@@ -326,6 +336,31 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
} }
} }
public static class LoadFromDeviceHeader extends Entry {
private static final Component LOAD_REPLAY_LABEL = Component.translatable("flashback.select_replay.load_replay_from_file");
private static final WidgetSprites SPRITES = new WidgetSprites(ResourceLocation.withDefaultNamespace("widget/button"), ResourceLocation.withDefaultNamespace("widget/button_disabled"),
ResourceLocation.withDefaultNamespace("widget/button_highlighted"));
private final Minecraft minecraft;
public LoadFromDeviceHeader(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
guiGraphics.blitSprite(SPRITES.get(true, hovered), x + 4, y + 2, width - 8, height - 4);
int p = (this.minecraft.screen.width - this.minecraft.font.width(LOAD_REPLAY_LABEL)) / 2;
int q = y + (height - this.minecraft.font.lineHeight) / 2 + 1;
guiGraphics.drawString(this.minecraft.font, LOAD_REPLAY_LABEL, p, q, 0xFFFFFF, true);
}
@Override
public Component getNarration() {
return LOAD_REPLAY_LABEL;
}
}
public final class ReplayListEntry extends Entry implements AutoCloseable { public final class ReplayListEntry extends Entry implements AutoCloseable {
private static final int ICON_WIDTH = 32; private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32; private static final int ICON_HEIGHT = 32;
@@ -352,7 +387,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
} }
@Override @Override
public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) { public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
String title = this.summary.getReplayName(); String title = this.summary.getReplayName();
String fileAndTime = this.summary.getReplayId(); String fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastModified(); long p = this.summary.getLastModified();
@@ -360,7 +395,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")"; fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
} }
if (StringUtils.isEmpty(title)) { if (StringUtils.isEmpty(title)) {
title = I18n.get("flashback.select_replay.replay") + " " + (i + 1); title = I18n.get("flashback.select_replay.replay") + " " + (index + 1);
} }
Component info = this.summary.getInfo(); Component info = this.summary.getInfo();
@@ -371,21 +406,21 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
titleColour = 0xFFAA55; titleColour = 0xFFAA55;
} }
guiGraphics.drawString(this.minecraft.font, title, k + ICON_WIDTH + 3, j + 1, titleColour, false); guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, false);
guiGraphics.drawString(this.minecraft.font, fileAndTime, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + 3, 0xFF808080, false); guiGraphics.drawString(this.minecraft.font, fileAndTime, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
guiGraphics.drawString(this.minecraft.font, info, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false); guiGraphics.drawString(this.minecraft.font, info, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
RenderSystem.enableBlend(); RenderSystem.enableBlend();
guiGraphics.blit(this.icon.textureLocation(), k, j, 0.0f, 0.0f, 32, 32, 32, 32); guiGraphics.blit(this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32);
RenderSystem.disableBlend(); RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || bl) { if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(k, j, k + ICON_WIDTH, j + ICON_HEIGHT, -1601138544); guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = n - k; int q = mouseX - x;
boolean hoveredIcon = q < 32; boolean hoveredIcon = q < 32;
if (bl && this.summary.getHoverInfo() != null) { if (hovered && this.summary.getHoverInfo() != null) {
guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), n, o); guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY);
} }
ResourceLocation iconOverlay; ResourceLocation iconOverlay;
@@ -396,7 +431,7 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
} else { } else {
iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE; iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
} }
guiGraphics.blitSprite(iconOverlay, k, j, ICON_WIDTH, ICON_HEIGHT); guiGraphics.blitSprite(iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT);
} }
} }
@@ -459,41 +494,6 @@ public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList
public void editReplay() { public void editReplay() {
Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary)); Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary));
// SystemToast.add(this.minecraft.getToasts(), new SystemToast.SystemToastId(3000),
// Component.literal("Sorry"), Component.literal("Editing replay data hasn't been implemented yet"));
// todo: implement editing replay data
// EditWorldScreen editWorldScreen;
// ReplayStorageSource.ReplayStorageAccess levelStorageAccess;
// this.queueLoadScreen();
// String string = this.summary.getReplayId();
// try {
// levelStorageAccess = this.minecraft.getReplaySource().validateAndCreateAccess;
// } catch (IOException iOException) {
// SystemToast.onWorldAccessFailure(this.minecraft, string);
// LOGGER.error("Failed to access level {}", (Object)string, (Object)iOException);
// ReplaySelectionList.this.reloadWorldList();
// return;
// } catch (ContentValidationException contentValidationException) {
// LOGGER.warn("{}", (Object)contentValidationException.getMessage());
// this.minecraft.setScreen(NoticeWithLinkScreen.createWorldSymlinkWarningScreen(() -> this.minecraft.setScreen(this.screen)));
// return;
// }
// try {
// editWorldScreen = EditWorldScreen.create(this.minecraft, levelStorageAccess, bl -> {
// levelStorageAccess.safeClose();
// if (bl) {
// ReplaySelectionList.this.reloadWorldList();
// }
// this.minecraft.setScreen(this.screen);
// });
// } catch (IOException | NbtException | ReportedNbtException exception) {
// levelStorageAccess.safeClose();
// SystemToast.onWorldAccessFailure(this.minecraft, string);
// LOGGER.error("Failed to load world data {}", (Object)string, (Object)exception);
// ReplaySelectionList.this.reloadWorldList();
// return;
// }
// this.minecraft.setScreen(editWorldScreen);
} }
private void loadIcon() { private void loadIcon() {
@@ -1,9 +1,8 @@
package com.moulberry.flashback.spline; package com.moulberry.flashback.spline;
import com.moulberry.flashback.Interpolation; import com.moulberry.flashback.Interpolation;
import org.joml.Quaterniond; import net.minecraft.util.Mth;
import org.joml.Vector3d; import org.joml.Vector3d;
import org.joml.Vector3f;
public class CatmullRom { public class CatmullRom {
@@ -97,100 +96,6 @@ public class CatmullRom {
} }
} }
private static double rotationCentripetalTj(Quaterniond p1, Quaterniond p2) {
Quaterniond delta = p1.invert(new Quaterniond()).mul(p2);
double lengthSq = delta.x*delta.x + delta.y*delta.y + delta.z*delta.z;
double length = Math.sqrt(lengthSq);
double angleBetween = Math.abs(2 * Math.atan2(length, delta.w));
angleBetween = Math.max(0, Math.min(Math.PI, angleBetween));
return Math.pow(angleBetween, 0.5f);
}
public static Quaterniond rotation(Quaterniond p0, Quaterniond p1, Quaterniond p2, Quaterniond p3, float time1, float time2, float time3, float amount) {
double tj1 = rotationCentripetalTj(p0, p1);
double tj2 = rotationCentripetalTj(p1, p2);
double tj3 = rotationCentripetalTj(p2, p3);
double averageTj = (tj1 + tj2 + tj3) / 3f;
if (averageTj == 0.0) {
return new Quaterniond(p1);
}
double averageTime = time3 / 3f;
double relation = averageTime / averageTj;
double deltaTime1 = 0.0f;
if (time1 > 0.0f) {
double factor1 = (tj1 * relation) / time1;
factor1 = Math.max(0.4f, Math.min(2.5f, factor1));
deltaTime1 = (tj1 * relation) / factor1;
}
double deltaTime2 = 0.0f;
if (time2 - time1 > 0.0f) {
double factor2 = (tj2 * relation) / (time2 - time1);
factor2 = Math.max(0.4f, Math.min(2.5f, factor2));
deltaTime2 = (tj2 * relation) / factor2;
}
double deltaTime3 = 0.0f;
if (time3 - time2 > 0.0f) {
double factor3 = (tj3 * relation) / (time3 - time2);
factor3 = Math.max(0.4f, Math.min(2.5f, factor3));
deltaTime3 = (tj3 * relation) / factor3;
}
double t0 = 0;
double t1 = t0 + deltaTime1;
double t2 = t1 + deltaTime2;
double t3 = t2 + deltaTime3;
double t = t1 + (t2 - t1) * amount;
Quaterniond a1;
if (t0 == t1) {
a1 = p0.nlerp(p1, 0.5f, new Quaterniond()).normalize();
} else {
a1 = p0.nlerp(p1, (t - t0)/(t1 - t0), new Quaterniond()).normalize();
}
Quaterniond a2;
if (t1 == t2) {
a2 = p1.nlerp(p2, 0.5f, new Quaterniond()).normalize();
} else {
a2 = p1.nlerp(p2, (t - t1)/(t2 - t1), new Quaterniond()).normalize();
}
Quaterniond a3;
if (t2 == t3) {
a3 = p2.nlerp(p3, 0.5f, new Quaterniond()).normalize();
} else {
a3 = p2.nlerp(p3, (t - t2)/(t3 - t2), new Quaterniond()).normalize();
}
Quaterniond b1;
if (t0 == t2) {
b1 = a1.nlerp(a2, 0.5f, new Quaterniond()).normalize();
} else {
b1 = a1.nlerp(a2, (t - t0)/(t2 - t0), new Quaterniond()).normalize();
}
Quaterniond b2;
if (t1 == t3) {
b2 = a2.nlerp(a3, 0.5f, new Quaterniond()).normalize();
} else {
b2 = a2.nlerp(a3, (t - t1)/(t3 - t1), new Quaterniond()).normalize();
}
if (t1 == t2) {
return b1.nlerp(b2, 0.5f, new Quaterniond()).normalize();
} else {
return b1.nlerp(b2, (t - t1)/(t2 - t1), new Quaterniond()).normalize();
}
}
private static float valueCentripetalTj(float p1, float p2) { private static float valueCentripetalTj(float p1, float p2) {
return (float) Math.sqrt(Math.abs(p1 - p2)); return (float) Math.sqrt(Math.abs(p1 - p2));
} }
@@ -278,4 +183,96 @@ public class CatmullRom {
} }
} }
private static float degreesCentripetalTj(float p1, float p2) {
return (float) Math.sqrt(Math.abs(Mth.wrapDegrees(p1 - p2)));
}
public static float degrees(float p0, float p1, float p2, float p3, float time1, float time2, float time3, float amount) {
p0 = Mth.wrapDegrees(p0);
p1 = Mth.wrapDegrees(p1);
p2 = Mth.wrapDegrees(p2);
p3 = Mth.wrapDegrees(p3);
float tj1 = degreesCentripetalTj(p0, p1);
float tj2 = degreesCentripetalTj(p1, p2);
float tj3 = degreesCentripetalTj(p2, p3);
float averageTj = (tj1 + tj2 + tj3) / 3f;
if (averageTj == 0.0) {
return p1;
}
float averageTime = time3 / 3f;
float relation = averageTime / averageTj;
float deltaTime1 = 0.0f;
if (time1 > 0.0f) {
float factor1 = (tj1 * relation) / time1;
factor1 = Math.max(0.4f, Math.min(2.5f, factor1));
deltaTime1 = (tj1 * relation) / factor1;
}
float deltaTime2 = 0.0f;
if (time2 - time1 > 0.0f) {
float factor2 = (tj2 * relation) / (time2 - time1);
factor2 = Math.max(0.4f, Math.min(2.5f, factor2));
deltaTime2 = (tj2 * relation) / factor2;
}
float deltaTime3 = 0.0f;
if (time3 - time2 > 0.0f) {
float factor3 = (tj3 * relation) / (time3 - time2);
factor3 = Math.max(0.4f, Math.min(2.5f, factor3));
deltaTime3 = (tj3 * relation) / factor3;
}
float t0 = 0;
float t1 = t0 + deltaTime1;
float t2 = t1 + deltaTime2;
float t3 = t2 + deltaTime3;
float t = t1 + (t2 - t1) * amount;
float a1;
if (t0 == t1) {
a1 = Interpolation.linearAngle(p0, p1, 0.5f);
} else {
a1 = Interpolation.linearAngle(p0, p1, (t - t0)/(t1 - t0));
}
float a2;
if (t1 == t2) {
a2 = Interpolation.linearAngle(p1, p2, 0.5f);
} else {
a2 = Interpolation.linearAngle(p1, p2, (t - t1)/(t2 - t1));
}
float a3;
if (t2 == t3) {
a3 = Interpolation.linearAngle(p2, p3, 0.5f);
} else {
a3 = Interpolation.linearAngle(p2, p3, (t - t2)/(t3 - t2));
}
float b1;
if (t0 == t2) {
b1 = Interpolation.linearAngle(a1, a2, 0.5f);
} else {
b1 = Interpolation.linearAngle(a1, a2, (t - t0)/(t2 - t0));
}
float b2;
if (t1 == t3) {
b2 = Interpolation.linearAngle(a2, a3, 0.5f);
} else {
b2 = Interpolation.linearAngle(a2, a3, (t - t1)/(t3 - t1));
}
if (t1 == t2) {
return Interpolation.linearAngle(b1, b2, 0.5f);
} else {
return Interpolation.linearAngle(b1, b2, (t - t1)/(t2 - t1));
}
}
} }
@@ -1,5 +1,6 @@
package com.moulberry.flashback.state; package com.moulberry.flashback.state;
import com.mojang.authlib.GameProfile;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson; import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.editor.ui.ReplayUI; import com.moulberry.flashback.editor.ui.ReplayUI;
@@ -16,6 +17,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.client.Camera; import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -44,6 +46,9 @@ public class EditorState {
public UUID audioSourceEntity = null; public UUID audioSourceEntity = null;
public Set<UUID> hideDuringExport = new HashSet<>(); public Set<UUID> hideDuringExport = new HashSet<>();
public Set<UUID> hideNametags = new HashSet<>();
public Map<UUID, GameProfile> skinOverride = new HashMap<>();
public Map<UUID, String> nameOverride = new HashMap<>();
public transient int recordingCameraMovementTrack = -1; public transient int recordingCameraMovementTrack = -1;
public transient int recordingCameraMovementMinTick = -1; public transient int recordingCameraMovementMinTick = -1;
@@ -43,6 +43,8 @@ public class ReplayVisuals {
public long overrideTimeOfDay = -1; public long overrideTimeOfDay = -1;
public boolean overrideNightVision = false;
public boolean ruleOfThirdsGuide = false; public boolean ruleOfThirdsGuide = false;
public boolean centerGuide = false; public boolean centerGuide = false;
public boolean cameraPath = true; public boolean cameraPath = true;
@@ -2,6 +2,7 @@ package com.moulberry.flashback.visuals;
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.moulberry.flashback.Flashback; import com.moulberry.flashback.Flashback;
import net.fabricmc.fabric.api.client.rendering.v1.CoreShaderRegistrationCallback;
import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener; import net.fabricmc.fabric.api.resource.SimpleSynchronousResourceReloadListener;
import net.fabricmc.fabric.impl.client.rendering.FabricShaderProgram; import net.fabricmc.fabric.impl.client.rendering.FabricShaderProgram;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
@@ -11,43 +12,22 @@ import net.minecraft.server.packs.resources.ResourceManager;
import java.io.IOException; import java.io.IOException;
public class ShaderManager implements SimpleSynchronousResourceReloadListener { public class ShaderManager {
public static final ShaderManager INSTANCE = new ShaderManager(); public static final ShaderManager INSTANCE = new ShaderManager();
public static ShaderInstance blitScreenRoundAlpha; public static ShaderInstance blitScreenRoundAlpha;
public static ShaderInstance blitScreenFlip; public static ShaderInstance blitScreenFlip;
@Override public void register() {
public ResourceLocation getFabricId() { CoreShaderRegistrationCallback.EVENT.register(context -> {
return ResourceLocation.parse("flashback:shaders"); context.register(ResourceLocation.parse("flashback:blit_screen_round_alpha"), DefaultVertexFormat.BLIT_SCREEN, shaderInstance -> {
} blitScreenRoundAlpha = shaderInstance;
});
@Override context.register(ResourceLocation.parse("flashback:blit_screen_flip"), DefaultVertexFormat.BLIT_SCREEN, shaderInstance -> {
public void onResourceManagerReload(ResourceManager resourceManager) { blitScreenFlip = shaderInstance;
Flashback.LOGGER.info("Reloading shaders..."); });
});
if (blitScreenRoundAlpha != null) {
blitScreenRoundAlpha.close();
blitScreenRoundAlpha = null;
}
if (blitScreenFlip != null) {
blitScreenFlip.close();
blitScreenFlip = null;
}
try {
blitScreenRoundAlpha = new FabricShaderProgram(Minecraft.getInstance().getResourceManager(),
ResourceLocation.parse("flashback:blit_screen_round_alpha"), DefaultVertexFormat.BLIT_SCREEN);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load flashback:blit_screen_round_alpha shader", e);
}
try {
blitScreenFlip = new FabricShaderProgram(Minecraft.getInstance().getResourceManager(),
ResourceLocation.parse("flashback:blit_screen_flip"), DefaultVertexFormat.BLIT_SCREEN);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load flashback:blit_screen_flip shader", e);
}
} }
} }
@@ -2,6 +2,7 @@
"flashback.select_replay": "Select Replay", "flashback.select_replay": "Select Replay",
"flashback.select_replay.open": "Open Replay", "flashback.select_replay.open": "Open Replay",
"flashback.select_replay.loading_replays": "Loading Replays", "flashback.select_replay.loading_replays": "Loading Replays",
"flashback.select_replay.load_replay_from_file": "Load replay from file...",
"flashback.select_replay.replay": "Replay", "flashback.select_replay.replay": "Replay",
"flashback.select_replay.data_read": "Reading replay data...", "flashback.select_replay.data_read": "Reading replay data...",
"flashback.select_replay.delete_question": "Are you sure you want to delete this replay?", "flashback.select_replay.delete_question": "Are you sure you want to delete this replay?",
+6 -3
View File
@@ -3,6 +3,7 @@
"package": "com.moulberry.flashback.mixin", "package": "com.moulberry.flashback.mixin",
"compatibilityLevel": "JAVA_21", "compatibilityLevel": "JAVA_21",
"client": [ "client": [
"MixinAbstractClientPlayer",
"MixinDebugScreenOverlay", "MixinDebugScreenOverlay",
"MixinLevelRenderer", "MixinLevelRenderer",
"MixinMinecraft", "MixinMinecraft",
@@ -35,6 +36,7 @@
"visuals.MixinFogRenderer", "visuals.MixinFogRenderer",
"visuals.MixinGui", "visuals.MixinGui",
"visuals.MixinLevelRenderer", "visuals.MixinLevelRenderer",
"visuals.MixinLightTexture",
"visuals.MixinLivingEntityRenderer", "visuals.MixinLivingEntityRenderer",
"visuals.MixinLoadingOverlay", "visuals.MixinLoadingOverlay",
"visuals.MixinMouseHandler", "visuals.MixinMouseHandler",
@@ -46,13 +48,14 @@
}, },
"mixins": [ "mixins": [
"MixinThreadedLevelLightEngine", "MixinThreadedLevelLightEngine",
"compat.MixinAxiomEditorUI", "compat.axiom.MixinAxiomEditorUI",
"compat.MixinFabricMinecraftServer",
"compat.MixinSodiumWorldRenderer", "compat.MixinSodiumWorldRenderer",
"compat.axiom.MixinAxiomServerIntegration",
"compat.bobby.FakeChunkManagerAccessor", "compat.bobby.FakeChunkManagerAccessor",
"compat.bobby.MixinBobby", "compat.bobby.MixinBobby",
"compat.bobby.MixinBobbyFakeChunkManager", "compat.bobby.MixinBobbyFakeChunkManager",
"compat.distanthorizons.MixinSharedApi", "compat.fabric.MixinFabricMinecraftServer",
"compat.fabric.MixinFabricServerPlayNetworking",
"compat.iris.MixinIrisSystemTimeUniforms", "compat.iris.MixinIrisSystemTimeUniforms",
"compat.replaymod.MixinReplayModRecording", "compat.replaymod.MixinReplayModRecording",
"compat.voice_chat.MixinVoiceChatALSpeakerBase", "compat.voice_chat.MixinVoiceChatALSpeakerBase",