Implement Freeze keyframe

This commit is contained in:
Moulberry committed 2024-11-26 14:23:03 +08:00
1 parent 67aa3c1401
commit 7c97b9d43c
20 files changed
+521 -146

No files matched your search

-10
View File
@@ -71,17 +71,7 @@ dependencies {
modCompileOnly("maven.modrinth:bobby:2cuVyTav")
modCompileOnly("maven.modrinth:simple-voice-chat:95BK1U8I")
modCompileOnly("maven.modrinth:replaymod:NtlpUQgI")
// modCompileOnly("maven.modrinth:distanthorizons:pEvLEY5E")
modImplementation("maven.modrinth:modmenu:xhN1IvHi")
// modCompileOnly("maven.modrinth:axiom:D3uDJmiB")
// modRuntimeOnly("maven.modrinth:sodium:mc1.20.6-0.5.11")
// shadow(implementation("org.jcodec:jcodec:0.2.5"))
// shadow(implementation("org.jcodec:jcodec-javase:0.2.5"))
// shadow(implementation("io.humble:humble-video-all:0.3.0"))
include(implementation(annotationProcessor("com.bawnorton.mixinsquared:mixinsquared-fabric:0.2.0-beta.6")))
shadow(implementation("org.bytedeco:javacv-platform:1.5.10") {
exclude group: "org.bytedeco", module: "artoolkitplus"
@@ -20,6 +20,7 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType;
import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType;
import com.moulberry.flashback.keyframe.types.CameraShakeKeyframeType;
import com.moulberry.flashback.keyframe.types.FOVKeyframeType;
import com.moulberry.flashback.keyframe.types.FreezeKeyframeType;
import com.moulberry.flashback.keyframe.types.SpeedKeyframeType;
import com.moulberry.flashback.keyframe.types.TimeOfDayKeyframeType;
import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType;
@@ -106,6 +107,9 @@ import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
@@ -116,6 +120,7 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
public class Flashback implements ModInitializer, ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("flashback");
@@ -232,6 +237,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
KeyframeRegistry.register(SpeedKeyframeType.INSTANCE);
KeyframeRegistry.register(TimelapseKeyframeType.INSTANCE);
KeyframeRegistry.register(TimeOfDayKeyframeType.INSTANCE);
KeyframeRegistry.register(FreezeKeyframeType.INSTANCE);
ClientPlayNetworking.registerGlobalReceiver(FlashbackForceClientTick.TYPE, (payload, context) -> {
if (Flashback.isInReplay()) {
@@ -549,6 +555,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
}
CompletableFuture.runAsync(() -> {
long currentTime = System.currentTimeMillis();
Map<UUID, Path> replayStates = new HashMap<>();
// Find existing replay states
@@ -564,6 +571,15 @@ public class Flashback implements ModInitializer, ClientModInitializer {
withoutExtension = filename.substring(0, filename.length() - 9);
}
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis());
long timeDifference = Math.abs(currentTime - lastModified);
if (timeDifference < Duration.ofDays(30).toMillis()) {
continue;
}
if (withoutExtension != null) {
UUID uuid;
try {
@@ -577,6 +593,10 @@ public class Flashback implements ModInitializer, ClientModInitializer {
}
} catch (IOException ignored) {}
if (replayStates.isEmpty()) {
return;
}
// Find which uuids are still valid because they have replays
Set<UUID> replayUuids = new HashSet<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayDir)) {
@@ -10,6 +10,7 @@ import com.moulberry.flashback.keyframe.impl.CameraKeyframe;
import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe;
import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe;
import com.moulberry.flashback.keyframe.impl.FOVKeyframe;
import com.moulberry.flashback.keyframe.impl.FreezeKeyframe;
import com.moulberry.flashback.keyframe.impl.TickrateKeyframe;
import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe;
import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe;
@@ -44,6 +45,7 @@ public class FlashbackGson {
.registerTypeAdapter(TickrateKeyframe.class, new TickrateKeyframe.TypeAdapter())
.registerTypeAdapter(TimelapseKeyframe.class, new TimelapseKeyframe.TypeAdapter())
.registerTypeAdapter(TimeOfDayKeyframe.class, new TimeOfDayKeyframe.TypeAdapter())
.registerTypeAdapter(FreezeKeyframe.class, new FreezeKeyframe.TypeAdapter())
.registerTypeAdapter(Keyframe.class, new Keyframe.TypeAdapter())
.registerTypeAdapter(EditorSceneHistoryAction.SetKeyframe.class, new EditorSceneHistoryAction.SetKeyframe.TypeAdapter())
@@ -0,0 +1,65 @@
package com.moulberry.flashback;
public class FreezeSlowdownFormula {
public static double calculateFreezeClientTickDerivative(double serverTicks, int frozenDelay, double freezePowerBase) {
double freezePowerSq = freezePowerBase * freezePowerBase;
double freezePower4 = freezePowerSq * freezePowerSq;
return -4 * Math.log(freezePowerBase) * Math.pow(freezePowerBase, 4 * serverTicks / frozenDelay) / (frozenDelay - frozenDelay*freezePower4);
}
public static double calculateFreezeClientTick(double serverTicks, int frozenDelay, double freezePowerBase) {
return (1 - Math.pow(freezePowerBase, 4 * serverTicks/frozenDelay)) / (1 - Math.pow(freezePowerBase, 4));
}
private static final double[] freezePowers = new double[11];
public static double getFreezePowerBase(int freezeTicks, double targetDerivative) {
if (freezeTicks < 0) {
freezeTicks = 0;
}
if (freezeTicks > 10) {
freezeTicks = 10;
}
double freezePowerBase = freezePowers[freezeTicks];
if (freezePowerBase == 0) {
freezePowerBase = calculateFreezePower(freezeTicks, targetDerivative);
freezePowers[freezeTicks] = freezePowerBase;
}
return freezePowerBase;
}
private static double calculateFreezePower(int freezeTicks, double targetDerivative) {
double freezePowerBaseMin = 0.05;
double freezePowerBaseMax = 0.95;
if (computeDerivativeAtZero(freezeTicks, freezePowerBaseMin) < targetDerivative) {
return freezePowerBaseMin;
}
if (computeDerivativeAtZero(freezeTicks, freezePowerBaseMax) > targetDerivative) {
return freezePowerBaseMax;
}
double freezePowerBaseMid = (freezePowerBaseMin + freezePowerBaseMax) / 2.0;
for (int i = 0; i < 100; i++) {
if (computeDerivativeAtZero(freezeTicks, freezePowerBaseMid) > targetDerivative) {
freezePowerBaseMin = freezePowerBaseMid;
} else {
freezePowerBaseMax = freezePowerBaseMid;
}
freezePowerBaseMid = (freezePowerBaseMin + freezePowerBaseMax) / 2.0;
}
return freezePowerBaseMid;
}
private static double computeDerivativeAtZero(int freezeTicks, double freezePower) {
double freezePowerSq = freezePower * freezePower;
double freezePower4 = freezePowerSq * freezePowerSq;
return -4 * Math.log(freezePower) / (freezeTicks - freezeTicks*freezePower4);
}
}
@@ -7,18 +7,15 @@ import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FreezeSlowdownFormula;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.editor.ui.ReplayUI;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler;
import com.moulberry.flashback.keyframe.types.SpeedKeyframeType;
import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType;
import com.moulberry.flashback.keyframe.handler.TickrateKeyframeCapture;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.playback.ReplayServer;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.doubles.DoubleList;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.client.Camera;
@@ -51,7 +48,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
@@ -223,21 +219,23 @@ public class ExportJob {
}
Minecraft.getInstance().resizeDisplay();
DoubleList ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate());
List<TickInfo> ticks = calculateTicks(this.settings.editorState(), this.settings.startTick(), this.settings.endTick(), this.settings.framerate());
int clientTickCount = 0;
this.renderStartTime = System.currentTimeMillis();
double lastTickDouble = 0;
double lastClientTickDouble = 0;
for (int tickIndex = 0; tickIndex < ticks.size(); tickIndex++) {
this.currentTickDouble = ticks.getDouble(tickIndex);
float deltaTicksFloat = (float)(currentTickDouble - lastTickDouble);
lastTickDouble = currentTickDouble;
int currentTick = (int) currentTickDouble;
double partialTick = currentTickDouble - currentTick;
int targetServerTick = this.settings.startTick() + currentTick;
TickInfo tickInfo = ticks.get(tickIndex);
boolean frozen = tickInfo.frozen;
this.currentTickDouble = tickInfo.serverTick;
int targetServerTick = this.settings.startTick() + (int) currentTickDouble;
float deltaTicksFloat = (float)(tickInfo.clientTick - lastClientTickDouble);
lastClientTickDouble = tickInfo.clientTick;
double partialClientTick = tickInfo.clientTick - (int) tickInfo.clientTick;
// Wait until server is on correct replay tick
long start = System.nanoTime();
@@ -245,10 +243,10 @@ public class ExportJob {
serverTickTimeNanos += System.nanoTime() - start;
// Tick client
while (clientTickCount < currentTick) {
while (clientTickCount < (int) tickInfo.clientTick) {
start = System.nanoTime();
this.updateRandoms(random, mathRandom);
this.runClientTick();
this.runClientTick(frozen);
clientTickTimeNanos += System.nanoTime() - start;
clientTickCount += 1;
@@ -256,7 +254,7 @@ public class ExportJob {
long pauseScreenStart = System.currentTimeMillis();
while (Minecraft.getInstance().getOverlay() != null || Minecraft.getInstance().screen != null) {
this.runClientTick();
this.runClientTick(frozen);
Window window = Minecraft.getInstance().getWindow();
RenderTarget renderTarget = Minecraft.getInstance().mainRenderTarget;
@@ -285,7 +283,7 @@ public class ExportJob {
}
}
this.tryUnfreezeClient();
this.updateClientFreeze(frozen);
KeyframeHandler keyframeHandler = new MinecraftKeyframeHandler(Minecraft.getInstance());
this.settings.editorState().applyKeyframes(keyframeHandler, (float)(this.settings.startTick() + currentTickDouble));
@@ -302,12 +300,12 @@ public class ExportJob {
RenderSystem.enableCull();
DeltaTracker.Timer timer = Minecraft.getInstance().timer;
timer.updateFrozenState(false);
timer.updateFrozenState(frozen);
timer.updatePauseState(false);
timer.deltaTicks = deltaTicksFloat;
timer.realtimeDeltaTicks = deltaTicksFloat;
timer.deltaTickResidual = (float) partialTick;
timer.pausedDeltaTickResidual = (float) partialTick;
timer.deltaTickResidual = (float) partialClientTick;
timer.pausedDeltaTickResidual = (float) partialClientTick;
start = System.nanoTime();
Minecraft.getInstance().gameRenderer.render(timer, true);
@@ -391,7 +389,7 @@ public class ExportJob {
// Ensure replay server is paused at currentTick
this.setServerTickAndWait(replayServer, currentTick, true);
this.runClientTick();
this.runClientTick(false);
// Clear particles
minecraft.particleEngine.clearParticles();
@@ -408,7 +406,7 @@ public class ExportJob {
while (currentTick < this.settings.startTick()) {
currentTick += 1;
this.setServerTickAndWait(replayServer, currentTick, true);
this.runClientTick();
this.runClientTick(false);
}
// Apply initial position and keyframes at start tick
@@ -419,11 +417,11 @@ public class ExportJob {
player.setDeltaMovement(Vec3.ZERO);
}
this.settings.editorState().applyKeyframes(new MinecraftKeyframeHandler(Minecraft.getInstance()), this.settings.startTick());
this.runClientTick();
this.runClientTick(false);
// Ensured replay server is paused at startTick
this.setServerTickAndWait(replayServer, this.settings.startTick(), true);
this.runClientTick();
this.runClientTick(false);
// Remove screen
minecraft.setScreen(null);
@@ -443,19 +441,20 @@ public class ExportJob {
}
}
private void runClientTick() {
this.tryUnfreezeClient();
private void runClientTick(boolean frozen) {
this.updateClientFreeze(frozen);
Minecraft minecraft = Minecraft.getInstance();
while (minecraft.pollTask()) {}
this.updateClientFreeze(frozen);
minecraft.tick();
this.updateSoundSound(minecraft);
this.updateSoundSource(minecraft);
this.tryUnfreezeClient();
this.updateClientFreeze(frozen);
}
private void updateSoundSound(Minecraft minecraft) {
private void updateSoundSource(Minecraft minecraft) {
EditorState editorState = this.settings.editorState();
if (editorState != null) {
Camera audioCamera = editorState.getAudioCamera();
@@ -468,10 +467,10 @@ public class ExportJob {
minecraft.getSoundManager().updateSource(Minecraft.getInstance().gameRenderer.getMainCamera());
}
private void tryUnfreezeClient() {
private void updateClientFreeze(boolean frozen) {
ClientLevel level = Minecraft.getInstance().level;
if (level != null) {
level.tickRateManager().setFrozen(false);
level.tickRateManager().setFrozen(frozen);
}
}
@@ -667,29 +666,12 @@ public class ExportJob {
}
}
private static class TickrateKeyframeCapture implements KeyframeHandler {
private float tickrate = 20.0f;
private record TickInfo(double serverTick, double clientTick, boolean frozen) {}
@Override
public Set<KeyframeType<?>> supportedKeyframes() {
return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE);
}
private static List<TickInfo> calculateTicks(EditorState editorState, int startTick, int endTick, double fps) {
List<TickInfo> ticks = new ArrayList<>();
@Override
public boolean alwaysApplyLastKeyframe() {
return true;
}
@Override
public void applyTickrate(float tickrate) {
this.tickrate = tickrate;
}
}
private static DoubleList calculateTicks(EditorState editorState, int startTick, int endTick, double fps) {
DoubleList ticks = new DoubleArrayList();
ticks.add(0);
ticks.add(new TickInfo(0, 0, false));
double residual = 0;
int currentTick = 0;
@@ -697,8 +679,10 @@ public class ExportJob {
TickrateKeyframeCapture capture = new TickrateKeyframeCapture();
int count = endTick - startTick;
int startFrozen = -1;
while (currentTick <= count) {
capture.tickrate = 20.0f;
capture.frozen = false;
editorState.applyKeyframes(capture, startTick + currentTick + (float) residual);
residual += capture.tickrate / fps;
@@ -711,10 +695,37 @@ public class ExportJob {
break;
}
ticks.add(currentTick + residual);
double currentTickDouble = currentTick + residual;
if (!capture.frozen) {
startFrozen = -1;
ticks.add(new TickInfo(currentTickDouble, currentTickDouble, false));
} else {
if (startFrozen < 0) {
startFrozen = currentTick;
}
if (capture.frozenDelay == 0) {
ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen), true));
continue;
}
double deltaFromStart = currentTickDouble - startFrozen;
double freezeClientTicks = capture.frozenDelay <= 5 ? 0.999 : 1.999;
double freezeDerivative = capture.frozenDelay <= 5 ? 1.0 : 0.5;
if (deltaFromStart > capture.frozenDelay) {
ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen + freezeClientTicks), true));
} else if (capture.frozenDelay == 1) {
ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen + freezeClientTicks), false));
} else {
double freezePowerBase = FreezeSlowdownFormula.getFreezePowerBase(capture.frozenDelay, freezeDerivative);
double clientTicks = freezeClientTicks * FreezeSlowdownFormula.calculateFreezeClientTick(deltaFromStart, capture.frozenDelay, freezePowerBase);
ticks.add(new TickInfo(currentTickDouble, Math.min(currentTickDouble, startFrozen + clientTicks), false));
}
}
}
return ticks;
}
}
@@ -7,6 +7,7 @@ import com.moulberry.flashback.keyframe.impl.CameraKeyframe;
import com.moulberry.flashback.keyframe.impl.CameraOrbitKeyframe;
import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe;
import com.moulberry.flashback.keyframe.impl.FOVKeyframe;
import com.moulberry.flashback.keyframe.impl.FreezeKeyframe;
import com.moulberry.flashback.keyframe.impl.TickrateKeyframe;
import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe;
import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe;
@@ -52,6 +53,7 @@ public abstract class Keyframe {
case "camera_orbit" -> context.deserialize(json, CameraOrbitKeyframe.class);
case "fov" -> context.deserialize(json, FOVKeyframe.class);
case "tickrate" -> context.deserialize(json, TickrateKeyframe.class);
case "freeze" -> context.deserialize(json, FreezeKeyframe.class);
case "timelapse" -> context.deserialize(json, TimelapseKeyframe.class);
case "time" -> context.deserialize(json, TimeOfDayKeyframe.class);
case "camera_shake" -> context.deserialize(json, CameraShakeKeyframe.class);
@@ -81,6 +83,10 @@ public abstract class Keyframe {
jsonObject = (JsonObject) context.serialize(tickrateKeyframe);
jsonObject.addProperty("type", "tickrate");
}
case FreezeKeyframe freezeKeyframe -> {
jsonObject = (JsonObject) context.serialize(freezeKeyframe);
jsonObject.addProperty("type", "freeze");
}
case TimeOfDayKeyframe timeOfDayKeyframe -> {
jsonObject = (JsonObject) context.serialize(timeOfDayKeyframe);
jsonObject.addProperty("type", "time");
@@ -27,6 +27,10 @@ public interface KeyframeHandler {
throw new UnsupportedOperationException();
}
default void applyFreeze(boolean frozen, int frozenDelay) {
throw new UnsupportedOperationException();
}
default void applyTimeOfDay(int timeOfDay) {
throw new UnsupportedOperationException();
}
@@ -6,6 +6,7 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType;
import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType;
import com.moulberry.flashback.keyframe.types.CameraShakeKeyframeType;
import com.moulberry.flashback.keyframe.types.FOVKeyframeType;
import com.moulberry.flashback.keyframe.types.FreezeKeyframeType;
import com.moulberry.flashback.keyframe.types.TimeOfDayKeyframeType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
@@ -1,6 +1,7 @@
package com.moulberry.flashback.keyframe.handler;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.types.FreezeKeyframeType;
import com.moulberry.flashback.keyframe.types.SpeedKeyframeType;
import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType;
import com.moulberry.flashback.playback.ReplayServer;
@@ -23,7 +24,7 @@ public class ReplayServerKeyframeHandler implements KeyframeHandler {
@Override
public Set<KeyframeType<?>> supportedKeyframes() {
return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE);
return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE, FreezeKeyframeType.INSTANCE);
}
@Override
@@ -36,6 +37,11 @@ public class ReplayServerKeyframeHandler implements KeyframeHandler {
this.replayServer.setDesiredTickRate(tickrate, false);
}
@Override
public void applyFreeze(boolean frozen, int frozenDelay) {
this.replayServer.setFrozen(frozen, frozenDelay);
}
@Override
public void applyTimeOfDay(int timeOfDay) {
throw new UnsupportedOperationException();
@@ -0,0 +1,35 @@
package com.moulberry.flashback.keyframe.handler;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.types.FreezeKeyframeType;
import com.moulberry.flashback.keyframe.types.SpeedKeyframeType;
import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType;
import java.util.Set;
public class TickrateKeyframeCapture implements KeyframeHandler {
public float tickrate = 20.0f;
public boolean frozen = false;
public int frozenDelay = 0;
@Override
public Set<KeyframeType<?>> supportedKeyframes() {
return Set.of(SpeedKeyframeType.INSTANCE, TimelapseKeyframeType.INSTANCE, FreezeKeyframeType.INSTANCE);
}
@Override
public boolean alwaysApplyLastKeyframe() {
return true;
}
@Override
public void applyTickrate(float tickrate) {
this.tickrate = tickrate;
}
@Override
public void applyFreeze(boolean frozen, int frozenDelay) {
this.frozen = frozen;
this.frozenDelay = frozenDelay;
}
}
@@ -0,0 +1,99 @@
package com.moulberry.flashback.keyframe.impl;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.moulberry.flashback.Interpolation;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.keyframe.types.SpeedKeyframeType;
import com.moulberry.flashback.spline.CatmullRom;
import imgui.ImGui;
import java.lang.reflect.Type;
import java.util.function.Consumer;
public class FreezeKeyframe extends Keyframe {
private boolean frozen;
private int frozenDelay;
public FreezeKeyframe(boolean frozen, int frozenDelay) {
this(frozen, frozenDelay, InterpolationType.HOLD);
}
public FreezeKeyframe(boolean frozen, int frozenDelay, InterpolationType interpolationType) {
this.frozen = frozen;
this.frozenDelay = frozenDelay;
this.interpolationType(interpolationType);
}
@Override
public KeyframeType<?> keyframeType() {
return SpeedKeyframeType.INSTANCE;
}
@Override
public Keyframe copy() {
return new FreezeKeyframe(this.frozen, this.frozenDelay, this.interpolationType());
}
@Override
public void renderEditKeyframe(Consumer<Consumer<Keyframe>> update) {
ImGui.setNextItemWidth(160);
if (ImGui.checkbox("Frozen", this.frozen)) {
boolean newFrozen = !this.frozen;
update.accept(keyframe -> ((FreezeKeyframe)keyframe).frozen = newFrozen);
}
int[] delay = new int[]{this.frozenDelay};
ImGui.setNextItemWidth(160);
if (ImGui.sliderInt("Delay", delay, 0, 10)) {
delay[0] = Math.max(0, Math.min(10, delay[0]));
update.accept(keyframe -> ((FreezeKeyframe)keyframe).frozenDelay = delay[0]);
}
ImGuiHelper.tooltip("Smooth freeze delay (in ticks)\nSetting this will make the game gradually slow down over the specified delay until it comes to a freeze");
}
@Override
public void apply(KeyframeHandler keyframeHandler) {
keyframeHandler.applyFreeze(this.frozen, Math.max(0, Math.min(10, this.frozenDelay)));
}
@Override
public void applyInterpolated(KeyframeHandler keyframeHandler, Keyframe otherGeneric, float amount) {
this.apply(keyframeHandler);
}
@Override
public void applyInterpolatedSmooth(KeyframeHandler keyframeHandler, Keyframe p1, Keyframe p2, Keyframe p3, float t0, float t1, float t2, float t3, float amount, float lerpAmount, boolean lerpFromRight) {
p1.apply(keyframeHandler);
}
public static class TypeAdapter implements JsonSerializer<FreezeKeyframe>, JsonDeserializer<FreezeKeyframe> {
@Override
public FreezeKeyframe deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
boolean freeze = jsonObject.get("freeze").getAsBoolean();
int freezeDelay = jsonObject.has("freezeDelay") ? jsonObject.get("freezeDelay").getAsInt() : 0;
InterpolationType interpolationType = context.deserialize(jsonObject.get("interpolation_type"), InterpolationType.class);
return new FreezeKeyframe(freeze, freezeDelay, interpolationType);
}
@Override
public JsonElement serialize(FreezeKeyframe src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("freeze", src.frozen);
jsonObject.addProperty("freezeDelay", src.frozenDelay);
jsonObject.addProperty("type", "freeze");
jsonObject.add("interpolation_type", context.serialize(src.interpolationType()));
return jsonObject;
}
}
}
@@ -29,7 +29,7 @@ public enum SidedInterpolationType {
} else if (left == SidedInterpolationType.EASE) {
if (right == SidedInterpolationType.LINEAR) {
// https://easings.net/#easeInCubic
return amount * amount * amount;
return (float) Math.pow(amount, 3);
} else if (right == SidedInterpolationType.EASE) {
// https://easings.net/#easeInOutCubic
if (amount < 0.5) {
@@ -0,0 +1,59 @@
package com.moulberry.flashback.keyframe.types;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.impl.FreezeKeyframe;
import imgui.ImGui;
import imgui.type.ImBoolean;
import org.jetbrains.annotations.Nullable;
public class FreezeKeyframeType implements KeyframeType<FreezeKeyframe> {
public static FreezeKeyframeType INSTANCE = new FreezeKeyframeType();
private FreezeKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue9e4";
}
@Override
public String name() {
return "Freeze";
}
@Override
public String id() {
return "FREEZE";
}
@Override
public @Nullable FreezeKeyframe createDirect() {
return null;
}
@Override
public KeyframeCreatePopup<FreezeKeyframe> createPopup() {
ImBoolean frozen = new ImBoolean();
int[] delay = new int[]{0};
return () -> {
ImGui.checkbox("Frozen", frozen);
ImGui.sliderInt("Delay", delay, 0, 10);
ImGuiHelper.tooltip("Smooth freeze delay (in ticks)\nSetting this will make the game gradually slow down over the specified delay until it comes to a freeze");
delay[0] = Math.max(0, Math.min(10, delay[0]));
if (ImGui.button("Add")) {
return new FreezeKeyframe(frozen.get(), delay[0]);
}
ImGui.sameLine();
if (ImGui.button("Cancel")) {
ImGui.closeCurrentPopup();
}
return null;
};
}
}
@@ -5,16 +5,17 @@ import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.blaze3d.systems.RenderSystem;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FreezeSlowdownFormula;
import com.moulberry.flashback.exporting.ExportJob;
import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler;
import com.moulberry.flashback.keyframe.handler.TickrateKeyframeCapture;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.exporting.PerfectFrames;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.ext.MinecraftExt;
import com.moulberry.flashback.editor.ui.ReplayUI;
import com.moulberry.flashback.visuals.AccurateEntityPositionHandler;
import it.unimi.dsi.fastutil.floats.FloatUnaryOperator;
import net.minecraft.CrashReport;
import net.minecraft.ReportedException;
@@ -43,7 +44,6 @@ import net.minecraft.server.level.progress.ProcessorChunkProgressListener;
import net.minecraft.server.level.progress.StoringChunkProgressListener;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.players.GameProfileCache;
import net.minecraft.util.Mth;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.world.TickRateManager;
import net.minecraft.world.entity.Entity;
@@ -142,6 +142,9 @@ public abstract class MixinMinecraft implements MinecraftExt {
@Final
public DeltaTracker.Timer timer;
@Shadow
public long clientTickCount;
@Inject(method="<init>", at=@At("RETURN"))
public void init(GameConfig gameConfig, CallbackInfo ci) {
ReplayUI.init();
@@ -206,17 +209,70 @@ public abstract class MixinMinecraft implements MinecraftExt {
}
}
@Unique
private int serverTickFreezeDelayStart = -1;
@Unique
private double clientTickFreezeDelayStart = -1;
@Inject(method = "getTickTargetMillis", at = @At("HEAD"), cancellable = true)
public void getTickTargetMillis(float f, CallbackInfoReturnable<Float> cir) {
if (Flashback.isInReplay()) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
if (this.level == null) {
clientTickFreezeDelayStart = -1;
serverTickFreezeDelayStart = -1;
return;
}
TickRateManager tickRateManager = this.level.tickRateManager();
if (tickRateManager.runsNormally()) {
cir.setReturnValue(tickRateManager.millisecondsPerTick());
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !replayServer.replayPaused) {
float partialReplayTick = replayServer.getPartialReplayTick();
TickrateKeyframeCapture capture = new TickrateKeyframeCapture();
editorState.applyKeyframes(capture, partialReplayTick);
if (capture.frozen && capture.frozenDelay > 0 && this.timer instanceof DeltaTracker.Timer timer) {
if (clientTickFreezeDelayStart < 0) {
clientTickFreezeDelayStart = this.clientTickCount + 1;
serverTickFreezeDelayStart = (int) partialReplayTick;
TickRateManager tickRateManager = this.level.tickRateManager();
tickRateManager.setFrozenTicksToRun(capture.frozenDelay <= 5 ? 1 : 2);
}
double freezeClientTicks = capture.frozenDelay <= 5 ? 0.999 : 1.999;
double freezeDerivative = capture.frozenDelay <= 5 ? 1.0 : 0.5;
double deltaFromStart = partialReplayTick - serverTickFreezeDelayStart;
if (deltaFromStart >= 0 && deltaFromStart <= capture.frozenDelay) {
double freezePowerBase = FreezeSlowdownFormula.getFreezePowerBase(capture.frozenDelay, freezeDerivative);
double clientTicks = freezeClientTicks * FreezeSlowdownFormula.calculateFreezeClientTick(deltaFromStart,
capture.frozenDelay, freezePowerBase);
double currentClientTicks = this.clientTickCount + timer.deltaTickResidual - clientTickFreezeDelayStart;
double freezeRate = Math.max(0.01f, Math.min(1f, clientTicks - currentClientTicks));
float tickrate = Math.max(1f, capture.tickrate) * (float) freezeRate;
cir.setReturnValue(1000f / tickrate);
return;
}
} else {
clientTickFreezeDelayStart = -1;
serverTickFreezeDelayStart = -1;
}
TickRateManager tickRateManager = this.level.tickRateManager();
if (tickRateManager.runsNormally()) {
cir.setReturnValue(1000f / Math.max(1f, capture.tickrate));
}
} else {
TickRateManager tickRateManager = this.level.tickRateManager();
if (tickRateManager.runsNormally()) {
cir.setReturnValue(tickRateManager.millisecondsPerTick());
}
}
}
}
@@ -286,7 +342,9 @@ public abstract class MixinMinecraft implements MinecraftExt {
this.applyKeyframes.set(true);
}
@Inject(method = "runTick", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V", ordinal = 1), cancellable = true)
@Inject(method = "runTick", at = @At(value = "INVOKE",
target = "Lcom/mojang/blaze3d/platform/Window;setErrorSection(Ljava/lang/String;)V",
ordinal = 1), cancellable = true)
public void runTick_setErrorSection(boolean bl, CallbackInfo ci) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
@@ -0,0 +1,21 @@
package com.moulberry.flashback.mixin.compat.fabric;
import com.moulberry.flashback.Flashback;
import net.fabricmc.fabric.impl.biome.modification.BiomeModificationImpl;
import net.minecraft.core.RegistryAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(BiomeModificationImpl.class)
public class MixinBiomeModificationImpl {
@Inject(method = "finalizeWorldGen", at = @At("HEAD"), cancellable = true)
public void finalizeWorldGen(RegistryAccess impl, CallbackInfo ci) {
if (Flashback.isInReplay()) {
ci.cancel();
}
}
}
@@ -1,31 +0,0 @@
package com.moulberry.flashback.mixin.compat.fabric;
import com.bawnorton.mixinsquared.TargetHandler;
import com.moulberry.flashback.playback.ReplayServer;
import net.minecraft.server.MinecraftServer;
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;
/*
* Prevent Fabric from modifying the world gen
* The registry that our ReplayServer uses typically does not contain server-only registries
* like minecraft:worldgen/placed_feature and so trying to modify the world gen context using
* these server-only registries is bound to error
*/
@Mixin(value = MinecraftServer.class, priority = 1500)
public class MixinFabricMinecraftServer {
@TargetHandler(
mixin = "net.fabricmc.fabric.mixin.biome.modification.MinecraftServerMixin",
name = "finalizeWorldGen"
)
@Inject(method = "@MixinSquared:Handler", at = @At("HEAD"), cancellable = true, require = 0)
private void preventWorldGenChanges(CallbackInfo ci) {
if ((Object) this instanceof ReplayServer) {
ci.cancel();
}
}
}
@@ -5,6 +5,7 @@ import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
@@ -1,5 +1,6 @@
package com.moulberry.flashback.mixin.playback;
import com.llamalad7.mixinextras.injector.ModifyReturnValue;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.playback.ReplayPlayer;
import net.minecraft.client.Minecraft;
@@ -22,32 +23,25 @@ public abstract class MixinTickRateManager {
@Shadow
protected boolean runGameElements;
/*
* Freeze the replay server, preventing game elements from running normally
*/
@Unique
private final boolean isServerTickRateManager = ((Object)this instanceof ServerTickRateManager);
@Inject(method = "tick", at = @At("RETURN"))
public void tick(CallbackInfo ci) {
if (Flashback.isInReplay() && this.isServerTickRateManager) {
this.runGameElements = false;
if (Flashback.isInReplay()) {
if (this.isServerTickRateManager) {
this.runGameElements = false;
}
}
}
@Unique
private final boolean isServerTickRateManager = ((Object)this instanceof ServerTickRateManager);
@Inject(method = "isEntityFrozen", at = @At("HEAD"), cancellable = true)
public void isEntityFrozen(Entity entity, CallbackInfoReturnable<Boolean> cir) {
if (Flashback.isInReplay()) {
if (this.isServerTickRateManager) {
cir.setReturnValue(!(entity instanceof ReplayPlayer));
} else {
if (Flashback.isExporting()) {
cir.setReturnValue(false);
} else {
cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player);
}
cir.setReturnValue(!this.runsNormally() || entity == Minecraft.getInstance().player);
}
}
}
@@ -36,7 +36,6 @@ import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.server.IntegratedServer;
@@ -50,6 +49,7 @@ import net.minecraft.network.protocol.configuration.ClientConfigurationPacketLis
import net.minecraft.network.protocol.configuration.ConfigurationProtocols;
import net.minecraft.network.protocol.game.*;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.ServerTickRateManager;
import net.minecraft.server.Services;
import net.minecraft.server.WorldStem;
import net.minecraft.server.level.ChunkMap;
@@ -115,6 +115,10 @@ public class ReplayServer extends IntegratedServer {
public AtomicBoolean sendFinishedServerTick = new AtomicBoolean(false);
private volatile float desiredTickRate = 20.0f;
private volatile float desiredTickRateManual = 20.0f;
private boolean desiredFrozen = false;
private int desiredFrozenDelay = -1;
private boolean isFrozen = false;
private int frozenDelay = -1;
private int currentTick = 0;
private volatile int targetTick = 0;
@@ -423,6 +427,11 @@ public class ReplayServer extends IntegratedServer {
}
}
public void setFrozen(boolean frozen, int delay) {
this.desiredFrozen = frozen;
this.desiredFrozenDelay = delay;
}
public int getReplayTick() {
return this.targetTick;
}
@@ -636,7 +645,7 @@ public class ReplayServer extends IntegratedServer {
}
positionUpdateSet.add(id);
} else {
} else if (!this.isFrozen) {
byte yRot = (byte) Mth.floor(yaw * 256.0F / 360.0F);
byte xRot = (byte) Mth.floor(pitch * 256.0F / 360.0F);
this.getPlayerList().broadcastAll(PacketHelper.createTeleportForUnknown(id, x, y, z, yRot, xRot, onGround));
@@ -764,9 +773,7 @@ public class ReplayServer extends IntegratedServer {
replayReader.handleSnapshot(this);
}
// this.accurateEntityPositions = this.pendingAccurateEntityPositions;
// this.pendingAccurateEntityPositions = new ConcurrentHashMap<>();
this.lastReplayTick = this.currentTick;
this.lastReplayTick = this.targetTick;
this.lastTickTimeNanos = this.nextTickTimeNanos - this.tickRateManager().nanosecondsPerTick();
// Update list of replay viewers
@@ -812,10 +819,8 @@ public class ReplayServer extends IntegratedServer {
this.replayPaused = true;
}
boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false);
if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback) {
this.runUpdates(booleanSupplier, true);
if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback || this.isFrozen) {
this.runUpdates(booleanSupplier);
} else {
int realTargetTick = this.targetTick;
@@ -828,12 +833,12 @@ public class ReplayServer extends IntegratedServer {
if (this.targetTick >= realTargetTick) {
this.targetTick = realTargetTick;
this.runUpdates(booleanSupplier, forceApplyKeyframes);
this.runUpdates(booleanSupplier);
} else {
while (this.targetTick <= realTargetTick) {
this.fastForwarding = this.targetTick < realTargetTick;
this.runUpdates(booleanSupplier, forceApplyKeyframes);
this.runUpdates(booleanSupplier);
if (this.targetTick == realTargetTick) {
break;
@@ -845,7 +850,7 @@ public class ReplayServer extends IntegratedServer {
}
}
if (forceApplyKeyframes) {
if (this.forceApplyKeyframes.compareAndSet(true, false)) {
((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes();
}
@@ -973,10 +978,19 @@ public class ReplayServer extends IntegratedServer {
}
}
private void runUpdates(BooleanSupplier booleanSupplier, boolean forceApplyKeyframes) {
if (!this.replayPaused || forceApplyKeyframes) {
this.desiredTickRate = 20.0f;
this.getEditorState().applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick);
private void runUpdates(BooleanSupplier booleanSupplier) {
this.desiredTickRate = 20.0f;
this.desiredFrozen = false;
this.getEditorState().applyKeyframes(new ReplayServerKeyframeHandler(this), this.targetTick);
if (this.desiredFrozen && this.frozenDelay < 0) {
if (this.desiredFrozenDelay <= 0) {
this.frozenDelay = 1;
} else if (this.desiredFrozenDelay <= 5) {
this.frozenDelay = 2;
} else {
this.frozenDelay = 3;
}
}
float tickRate = this.desiredTickRate;
@@ -984,14 +998,34 @@ public class ReplayServer extends IntegratedServer {
tickRate *= this.desiredTickRateManual / 20f;
}
if (this.desiredFrozen) {
if (this.frozenDelay > 0) {
this.frozenDelay -= 1;
}
if (this.frozenDelay == 0) {
this.isFrozen = true;
}
} else {
this.frozenDelay = -1;
this.isFrozen = false;
}
// Update tick rate & frozen state
if (this.tickRateManager().tickrate() != tickRate) {
this.tickRateManager().setTickRate(tickRate);
ServerTickRateManager tickRateManager = this.tickRateManager();
if (tickRateManager.tickrate() != tickRate) {
tickRateManager.setTickRate(tickRate);
}
if (tickRateManager.isFrozen() != isFrozen) {
tickRateManager.setFrozen(isFrozen);
}
boolean tickChanged = this.targetTick != this.currentTick;
this.handleActions();
if (this.isFrozen && this.targetTick >= this.currentTick) {
tickChanged = false;
} else {
this.handleActions();
}
// Add tickets for keeping entities loaded
for (ServerLevel level : this.getAllLevels()) {
@@ -1005,7 +1039,7 @@ public class ReplayServer extends IntegratedServer {
super.tickServer(booleanSupplier);
// Teleport entities
if (!this.needsPositionUpdate.isEmpty()) {
if (!this.isFrozen && !this.needsPositionUpdate.isEmpty()) {
for (Map.Entry<ResourceKey<Level>, IntSet> entry : this.needsPositionUpdate.entrySet()) {
ResourceKey<Level> dimension = entry.getKey();
IntSet entities = entry.getValue();
@@ -1068,18 +1102,18 @@ public class ReplayServer extends IntegratedServer {
if (this.replayPaused) {
if (tickChanged) {
if (this.tickRateManager().isFrozen()) {
this.tickRateManager().setFrozen(false);
if (tickRateManager.isFrozen()) {
tickRateManager.setFrozen(false);
}
for (ReplayPlayer replayViewer : this.replayViewers) {
ServerPlayNetworking.send(replayViewer, FlashbackForceClientTick.INSTANCE);
}
this.tickRateManager().setFrozen(true);
} else if (!this.tickRateManager().isFrozen()) {
this.tickRateManager().setFrozen(true);
tickRateManager.setFrozen(true);
} else if (!tickRateManager.isFrozen()) {
tickRateManager.setFrozen(true);
}
} else if (this.tickRateManager().isFrozen()) {
this.tickRateManager().setFrozen(false);
} else if (tickRateManager.isFrozen() != isFrozen) {
tickRateManager.setFrozen(isFrozen);
}
}
}
+1 -1
View File
@@ -54,7 +54,7 @@
"compat.bobby.FakeChunkManagerAccessor",
"compat.bobby.MixinBobby",
"compat.bobby.MixinBobbyFakeChunkManager",
"compat.fabric.MixinFabricMinecraftServer",
"compat.fabric.MixinBiomeModificationImpl",
"compat.fabric.MixinFabricServerPlayNetworking",
"compat.iris.MixinIrisSystemTimeUniforms",
"compat.replaymod.MixinReplayModRecording",