Merge branch 'master' into taskbar-progress

This commit is contained in:
Moulberry authored and GitHub committed 2024-11-26 14:29:07 +08:00
commit b6ee80ba47
75 files changed
+2559 -1218

No files matched your search

+1 -3
View File
@@ -71,9 +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")
modCompileOnly("maven.modrinth:modmenu:xhN1IvHi")
// modCompileOnly("maven.modrinth:axiom:D3uDJmiB")
modImplementation("maven.modrinth:modmenu:xhN1IvHi")
shadow(implementation("org.bytedeco:javacv-platform:1.5.10") {
exclude group: "org.bytedeco", module: "artoolkitplus"
+1 -1
View File
@@ -9,7 +9,7 @@ yarn_mappings=1.21.3+build.2
loader_version=0.16.9
# Mod Properties
mod_version=0.12.0
mod_version=0.13.0
maven_group=com.moulberry.flashback
archives_base_name=flashback
@@ -20,10 +20,12 @@ 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;
import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition;
import com.moulberry.flashback.packet.FlashbackClearEntities;
import com.moulberry.flashback.packet.FlashbackClearParticles;
import com.moulberry.flashback.packet.FinishedServerTick;
import com.moulberry.flashback.packet.FlashbackForceClientTick;
@@ -106,6 +108,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 +121,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");
@@ -166,6 +172,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
PayloadTypeRegistry.playS2C().register(FlashbackForceClientTick.TYPE, StreamCodec.unit(FlashbackForceClientTick.INSTANCE));
PayloadTypeRegistry.playS2C().register(FlashbackClearParticles.TYPE, StreamCodec.unit(FlashbackClearParticles.INSTANCE));
PayloadTypeRegistry.playS2C().register(FlashbackClearEntities.TYPE, StreamCodec.unit(FlashbackClearEntities.INSTANCE));
PayloadTypeRegistry.playS2C().register(FlashbackInstantlyLerp.TYPE, StreamCodec.unit(FlashbackInstantlyLerp.INSTANCE));
PayloadTypeRegistry.playS2C().register(FlashbackRemoteSelectHotbarSlot.TYPE, FlashbackRemoteSelectHotbarSlot.STREAM_CODEC);
PayloadTypeRegistry.playS2C().register(FlashbackRemoteExperience.TYPE, FlashbackRemoteExperience.STREAM_CODEC);
@@ -231,6 +238,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()) {
@@ -244,6 +252,16 @@ public class Flashback implements ModInitializer, ClientModInitializer {
}
});
ClientPlayNetworking.registerGlobalReceiver(FlashbackClearEntities.TYPE, (payload, context) -> {
if (Flashback.isInReplay()) {
for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) {
if (entity != null && !(entity instanceof Player)) {
entity.discard();
}
}
}
});
ClientPlayNetworking.registerGlobalReceiver(FlashbackInstantlyLerp.TYPE, (payload, context) -> {
if (Flashback.isInReplay()) {
for (Entity entity : Minecraft.getInstance().level.entitiesForRendering()) {
@@ -356,13 +374,6 @@ public class Flashback implements ModInitializer, ClientModInitializer {
AccurateEntityPositionHandler.tick();
if (Flashback.isInReplay() && !Flashback.isExporting()) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null) {
editorState.recordCameraMovement();
}
}
// Fix for camera entity sometimes being incorrect when respawning
Entity camera = Minecraft.getInstance().cameraEntity;
LocalPlayer player = Minecraft.getInstance().player;
@@ -374,6 +385,8 @@ public class Flashback implements ModInitializer, ClientModInitializer {
}
}
}
Flashback.getConfig().tickDelayedSave();
});
ClientTickEvents.START_CLIENT_TICK.register(minecraft -> {
@@ -532,7 +545,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
private void deleteUnusedReplayStates() {
Path flashbackDir = Flashback.getDataDirectory();
Path replayDir = flashbackDir.resolve("replays");
Path replayDir = Flashback.getReplayFolder();
Path replayStatesDir = flashbackDir.resolve("editor_states");
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
@@ -543,6 +556,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
}
CompletableFuture.runAsync(() -> {
long currentTime = System.currentTimeMillis();
Map<UUID, Path> replayStates = new HashMap<>();
// Find existing replay states
@@ -558,6 +572,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 {
@@ -571,6 +594,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)) {
@@ -773,7 +800,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
if (config.recentReplays.size() > 32) {
config.recentReplays.remove(config.recentReplays.size() - 1);
}
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
// Actually load
try {
@@ -2,7 +2,6 @@ package com.moulberry.flashback;
import com.google.gson.Gson;
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.KeyframeRegistry;
@@ -11,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;
@@ -18,7 +18,7 @@ import com.moulberry.flashback.serialization.QuaterniondTypeAdapater;
import com.moulberry.flashback.serialization.QuaternionfTypeAdapater;
import com.moulberry.flashback.serialization.Vector3dTypeAdapater;
import com.moulberry.flashback.serialization.Vector3fTypeAdapater;
import com.moulberry.flashback.state.EditorStateHistoryAction;
import com.moulberry.flashback.state.EditorSceneHistoryAction;
import org.joml.Quaterniond;
import org.joml.Quaternionf;
import org.joml.Vector3d;
@@ -45,13 +45,14 @@ 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(EditorStateHistoryAction.SetKeyframe.class, new EditorStateHistoryAction.SetKeyframe.TypeAdapter())
.registerTypeAdapter(EditorStateHistoryAction.RemoveKeyframe.class, new EditorStateHistoryAction.RemoveKeyframe.TypeAdapter())
.registerTypeAdapter(EditorStateHistoryAction.AddTrack.class, new EditorStateHistoryAction.AddTrack.TypeAdapter())
.registerTypeAdapter(EditorStateHistoryAction.RemoveTrack.class, new EditorStateHistoryAction.RemoveTrack.TypeAdapter())
.registerTypeAdapter(EditorStateHistoryAction.class, new EditorStateHistoryAction.TypeAdapter());
.registerTypeAdapter(EditorSceneHistoryAction.SetKeyframe.class, new EditorSceneHistoryAction.SetKeyframe.TypeAdapter())
.registerTypeAdapter(EditorSceneHistoryAction.RemoveKeyframe.class, new EditorSceneHistoryAction.RemoveKeyframe.TypeAdapter())
.registerTypeAdapter(EditorSceneHistoryAction.AddTrack.class, new EditorSceneHistoryAction.AddTrack.TypeAdapter())
.registerTypeAdapter(EditorSceneHistoryAction.RemoveTrack.class, new EditorSceneHistoryAction.RemoveTrack.TypeAdapter())
.registerTypeAdapter(EditorSceneHistoryAction.class, new EditorSceneHistoryAction.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);
}
}
@@ -3,6 +3,7 @@ package com.moulberry.flashback;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.network.protocol.game.ClientboundTeleportEntityPacket;
import net.minecraft.network.protocol.game.VecDeltaCodec;
import net.minecraft.server.level.ServerEntity;
import net.minecraft.util.Mth;
@@ -10,12 +11,15 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ExperienceOrb;
import net.minecraft.world.entity.Marker;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.PositionMoveRotation;
import net.minecraft.world.entity.Relative;
import net.minecraft.world.entity.boss.EnderDragonPart;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.decoration.Painting;
import net.minecraft.world.entity.item.FallingBlockEntity;
import net.minecraft.world.entity.monster.warden.Warden;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
@@ -25,6 +29,15 @@ public class PacketHelper {
return entity == null || entity.isRemoved() || entity instanceof EnderDragonPart || entity.getType().clientTrackingRange() <= 0;
}
public static ClientboundTeleportEntityPacket createTeleportForUnknown(int id, double x, double y, double z, byte yRot, byte xRot, boolean onGround) {
return new ClientboundTeleportEntityPacket(
id,
new PositionMoveRotation(new Vec3(x, y, z), Vec3.ZERO, yRot, xRot),
Relative.DELTA,
onGround
);
}
public static Packet<ClientGamePacketListener> createAddEntity(Entity entity) {
ServerEntity serverEntity = null;
@@ -5,6 +5,7 @@ import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.screen.select_replay.ReplaySorting;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.ChatFormatting;
import net.minecraft.client.OptionInstance;
@@ -79,6 +80,11 @@ public class FlashbackConfig {
public String defaultExportFilename = "%date%T%time%";
public InterpolationType defaultInterpolationType = InterpolationType.SMOOTH;
public ReplaySorting replaySorting = ReplaySorting.CREATED_DATE;
public boolean sortDescending = true;
private transient int saveDelay = 0;
@SuppressWarnings("unchecked")
public OptionInstance<?>[] createOptionInstances() {
List<OptionInstance<?>> options = new ArrayList<>();
@@ -213,12 +219,28 @@ public class FlashbackConfig {
return new FlashbackConfig();
}
public void delayedSaveToDefaultFolder() {
if (this.saveDelay <= 0) {
this.saveDelay = 200;
}
}
public void tickDelayedSave() {
if (this.saveDelay > 0) {
this.saveDelay -= 1;
if (this.saveDelay == 0) {
this.saveToDefaultFolder();
}
}
}
public void saveToDefaultFolder() {
Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback");
this.saveToFolder(configFolder);
this.saveDelay = 0;
}
public void saveToFolder(Path configFolder) {
public synchronized void saveToFolder(Path configFolder) {
Path primary = configFolder.resolve("flashback.json");
Path backup = configFolder.resolve(".flashback.json.backup");
@@ -2,9 +2,10 @@ package com.moulberry.flashback.editor;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.state.EditorScene;
import com.moulberry.flashback.state.EditorSceneHistoryAction;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateHistoryAction;
import com.moulberry.flashback.state.EditorStateHistoryEntry;
import com.moulberry.flashback.state.EditorSceneHistoryEntry;
import com.moulberry.flashback.state.KeyframeTrack;
import org.jetbrains.annotations.Nullable;
@@ -15,37 +16,37 @@ import java.util.TreeMap;
public record SavedTrack(KeyframeType<?> type, int track, boolean copiedFromDisabled,
TreeMap<Integer, Keyframe> keyframes) {
public int applyToEditorState(EditorState editorState, int cursorTicks, int totalTicks) {
public int applyToScene(EditorScene editorScene, int cursorTicks, int totalTicks) {
if (this.keyframes == null || this.keyframes.isEmpty()) {
return 0;
}
// Try to apply directly to copied track
if (this.track >= 0 && this.track < editorState.keyframeTracks.size()) {
KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.track);
if (this.track >= 0 && this.track < editorScene.keyframeTracks.size()) {
KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(this.track);
if ((keyframeTrack.enabled || this.copiedFromDisabled) && keyframeTrack.keyframeType == this.type) {
return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks);
return this.applyTo(editorScene, this.type, keyframeTrack, this.track, cursorTicks, totalTicks);
}
}
// Try to find first eligible enabled track
for (KeyframeTrack keyframeTrack : editorState.keyframeTracks) {
for (KeyframeTrack keyframeTrack : editorScene.keyframeTracks) {
if (keyframeTrack.enabled && keyframeTrack.keyframeType == this.type) {
return this.applyTo(editorState, this.type, keyframeTrack, this.track, cursorTicks, totalTicks);
return this.applyTo(editorScene, this.type, keyframeTrack, this.track, cursorTicks, totalTicks);
}
}
// Create new track
return this.applyTo(editorState, this.type, null, this.track, cursorTicks, totalTicks);
return this.applyTo(editorScene, this.type, null, this.track, cursorTicks, totalTicks);
}
private int applyTo(EditorState editorState, KeyframeType type, @Nullable KeyframeTrack existing, int trackIndex, int cursorTicks, int totalTicks) {
List<EditorStateHistoryAction> undo = new ArrayList<>();
List<EditorStateHistoryAction> redo = new ArrayList<>();
private int applyTo(EditorScene editorScene, KeyframeType<?> type, @Nullable KeyframeTrack existing, int trackIndex, int cursorTicks, int totalTicks) {
List<EditorSceneHistoryAction> undo = new ArrayList<>();
List<EditorSceneHistoryAction> redo = new ArrayList<>();
if (existing == null) {
undo.add(new EditorStateHistoryAction.RemoveTrack(type, trackIndex));
redo.add(new EditorStateHistoryAction.AddTrack(type, trackIndex));
undo.add(new EditorSceneHistoryAction.RemoveTrack(type, trackIndex));
redo.add(new EditorSceneHistoryAction.AddTrack(type, trackIndex));
}
int count = 0;
@@ -56,18 +57,18 @@ public record SavedTrack(KeyframeType<?> type, int track, boolean copiedFromDisa
Keyframe old = existing.keyframesByTick.get(newTick);
if (old != null) {
undo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, old.copy()));
undo.add(new EditorSceneHistoryAction.SetKeyframe(type, trackIndex, newTick, old.copy()));
} else {
undo.add(new EditorStateHistoryAction.RemoveKeyframe(type, trackIndex, newTick));
undo.add(new EditorSceneHistoryAction.RemoveKeyframe(type, trackIndex, newTick));
}
}
redo.add(new EditorStateHistoryAction.SetKeyframe(type, trackIndex, newTick, entry.getValue().copy()));
redo.add(new EditorSceneHistoryAction.SetKeyframe(type, trackIndex, newTick, entry.getValue().copy()));
count += 1;
}
}
editorState.push(new EditorStateHistoryEntry(undo, redo, "Pasted " + count + " keyframe(s)"));
editorScene.push(new EditorSceneHistoryEntry(undo, redo, "Pasted " + count + " keyframe(s)"));
return count;
}
@@ -1,17 +1,18 @@
package com.moulberry.flashback.editor;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.state.EditorScene;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.KeyframeTrack;
import it.unimi.dsi.fastutil.ints.IntSet;
public record SelectedKeyframes(KeyframeType<?> type, int trackIndex, IntSet keyframeTicks) {
public boolean checkValid(EditorState state) {
if (this.trackIndex < 0 || this.trackIndex >= state.keyframeTracks.size()) {
public boolean checkValid(EditorScene scene) {
if (this.trackIndex < 0 || this.trackIndex >= scene.keyframeTracks.size()) {
return false;
}
KeyframeTrack keyframeTrack = state.keyframeTracks.get(this.trackIndex);
KeyframeTrack keyframeTrack = scene.keyframeTracks.get(this.trackIndex);
if (keyframeTrack.keyframeType != this.type) {
return false;
}
@@ -8,6 +8,7 @@ import imgui.flag.ImGuiComboFlags;
import imgui.flag.ImGuiHoveredFlags;
import imgui.flag.ImGuiInputTextFlags;
import imgui.flag.ImGuiNavInput;
import imgui.flag.ImGuiStyleVar;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImBoolean;
import imgui.type.ImFloat;
@@ -10,6 +10,7 @@ import com.moulberry.flashback.editor.ui.windows.MovementWindow;
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.WindowType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.combo_options.Sizing;
@@ -96,7 +97,6 @@ public class ReplayUI {
private static String infoOverlayText = null;
private static long infoOverlayEndMillis = 0;
public static boolean recordCameraMovement = false;
private static UUID selectedEntity = null;
private static boolean openSelectedEntityPopup = false;
@@ -216,10 +216,16 @@ public class ReplayUI {
fontConfig.setOversampleV(2);
fontConfig.setName("Inter (Medium), 16px");
fontConfig.setGlyphOffset(0, 0);
font = fonts.addFontFromMemoryTTF(loadFont("inter-medium.ttf"), size, fontConfig, glyphRanges);
// Merge in Japanese/Korean/Chinese/etc. characters if needed
fontConfig.setMergeMode(true);
fontConfig.setGlyphOffset(0, (int)(5 * getUiScale()));
io.getFonts().addFontFromMemoryTTF(loadFont("materialiconsround-regular.otf"), (int)(20 * getUiScale()), fontConfig, buildMaterialIconRanges());
fontConfig.setGlyphOffset(0, 0);
if (languageCode.startsWith("he")) {
short[] hebrewRanges = new short[]{(short)'\u0590', (short)'\u05FF', (short)'\uFB1D', (short)'\uFB4F', 0};
io.getFonts().addFontFromMemoryTTF(loadFont("heebo-medium.ttf"), size, fontConfig, hebrewRanges);
@@ -241,6 +247,27 @@ public class ReplayUI {
fonts.clearTexData();
}
private static short[] buildMaterialIconRanges() {
ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder();
builder.addChar('\ue04b');
builder.addChar('\ue577');
builder.addChar('\uefeb');
builder.addChar('\ue3af');
builder.addChar('\ue9e4');
builder.addChar('\ue422');
builder.addChar('\ue518');
builder.addChar('\ue945');
builder.addChar('\ue8f4');
builder.addChar('\ue8f5');
builder.addChar('\ue148');
builder.addChar('\ue5d2');
builder.addChar('\ue872');
builder.addChar('\ue3c9');
builder.addChar('\ue40a');
builder.addChar('\ue92b');
return builder.buildRanges();
}
private static byte[] loadFont(String name) {
try {
var resource = Minecraft.getInstance().getResourceManager().getResource(Flashback.createResourceLocation(name));
@@ -629,9 +656,6 @@ public class ReplayUI {
showText = infoOverlayText;
showTextBorderColour = 0xFF00FFFF;
}
} else if (recordCameraMovement) {
showText = "Recording Movement as Keyframes...";
showTextBorderColour = 0xFF0000FF;
}
if (showText != null) {
@@ -743,8 +767,8 @@ public class ReplayUI {
ExportScreenshotWindow.render();
PreferencesWindow.render();
ExportQueueWindow.render();
PlayerListWindow.render();
MovementWindow.render();
WindowType.renderAll();
popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup);
@@ -8,6 +8,7 @@ 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.EditorScene;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import imgui.ImGui;
@@ -79,7 +80,9 @@ public class ExportScreenshotWindow {
boolean noGui = StartExportWindow.noGui;
EditorState copiedEditorState = editorState.copy();
copiedEditorState.keyframeTracks.clear();
for (EditorScene scene : copiedEditorState.scenes) {
scene.keyframeTracks.clear();
}
ExportSettings settings = new ExportSettings(null, copiedEditorState,
player.position(), player.getYRot(), player.getXRot(),
@@ -0,0 +1,10 @@
package com.moulberry.flashback.editor.ui.windows;
import imgui.type.ImBoolean;
@FunctionalInterface
public interface ImGuiWindowRenderer {
void render(ImBoolean open, boolean newlyOpened);
}
@@ -2,9 +2,8 @@ package com.moulberry.flashback.editor.ui.windows;
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.screen.SelectReplayScreen;
import com.moulberry.flashback.screen.select_replay.SelectReplayScreen;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.TitleScreen;
@@ -73,7 +72,7 @@ public class MainMenuBar {
minecraft.level.disconnect();
}
minecraft.disconnect();
minecraft.setScreen(new SelectReplayScreen(new TitleScreen()));
minecraft.setScreen(new SelectReplayScreen(new TitleScreen(), Flashback.getReplayFolder()));
}
ImGui.endMenu();
}
@@ -105,7 +104,7 @@ public class MainMenuBar {
} else {
openedWindows.add(windowName);
}
Flashback.getConfig().saveToDefaultFolder();
Flashback.getConfig().delayedSaveToDefaultFolder();
}
}
@@ -12,6 +12,7 @@ import imgui.ImGui;
import imgui.ImGuiViewport;
import imgui.flag.ImGuiCond;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImBoolean;
import imgui.type.ImString;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
@@ -27,30 +28,23 @@ import java.util.Locale;
public class MovementWindow {
private static WindowOpenState wasOpen = WindowOpenState.UNKNOWN;
private static boolean wasDocked = false;
public static void render() {
if (!Flashback.getConfig().openedWindows.contains("movement")) {
wasOpen = WindowOpenState.CLOSED;
return;
}
if (wasOpen == WindowOpenState.CLOSED) {
public static void render(ImBoolean open, boolean newlyOpened) {
if (newlyOpened) {
ImGuiViewport viewport = ImGui.getMainViewport();
ImGui.setNextWindowPos(viewport.getCenterX(), viewport.getCenterY(), ImGuiCond.Appearing, 0.5f, 0.5f);
}
wasOpen = WindowOpenState.OPEN;
FlashbackConfig config = Flashback.getConfig();
ImGui.setNextWindowSizeConstraints(250, 50, 5000, 5000);
int flags = ImGuiWindowFlags.NoFocusOnAppearing;
if (!wasDocked) {
flags |= ImGuiWindowFlags.AlwaysAutoResize;
}
if (ImGui.begin("Movement###Movement", flags)) {
if (ImGui.begin("Movement###Movement", open, flags)) {
wasDocked = ImGui.isWindowDocked();
FlashbackConfig config = Flashback.getConfig();
int[] direction = new int[]{config.flightCameraDirection ? 1 : 0};
ImGuiHelper.combo("Direction", direction, new String[]{
@@ -60,46 +54,40 @@ public class MovementWindow {
boolean flightCameraDirection = direction[0] == 1;
if (config.flightCameraDirection != flightCameraDirection) {
config.flightCameraDirection = flightCameraDirection;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
float[] momentum = new float[]{config.flightMomentum};
ImGui.sliderFloat("Momentum", momentum, 0.0f, 1.0f);
if (config.flightMomentum != momentum[0]) {
config.flightMomentum = momentum[0];
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
if (ImGui.checkbox("Lock X", config.flightLockX)) {
config.flightLockX = !config.flightLockX;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
ImGui.sameLine();
if (ImGui.checkbox("Lock Y", config.flightLockY)) {
config.flightLockY = !config.flightLockY;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
ImGui.sameLine();
if (ImGui.checkbox("Lock Z", config.flightLockZ)) {
config.flightLockZ = !config.flightLockZ;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
if (ImGui.checkbox("Lock Yaw", config.flightLockYaw)) {
config.flightLockYaw = !config.flightLockYaw;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
ImGui.sameLine();
if (ImGui.checkbox("Lock Pitch", config.flightLockPitch)) {
config.flightLockPitch = !config.flightLockPitch;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
// todo: record movement: can we make this smoother?
// if (ImGui.checkbox("Record Movement as Keyframes", ReplayUI.recordCameraMovement)) {
// ReplayUI.recordCameraMovement = !ReplayUI.recordCameraMovement;
// }
}
ImGui.end();
}
@@ -10,6 +10,7 @@ import imgui.ImGui;
import imgui.ImGuiViewport;
import imgui.flag.ImGuiCond;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImBoolean;
import imgui.type.ImString;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
@@ -25,8 +26,6 @@ import java.util.Locale;
public class PlayerListWindow {
private static WindowOpenState wasOpen = WindowOpenState.UNKNOWN;
private static String lastSearch = null;
private static long lastUpdate = 0;
private static ImString search = ImGuiHelper.createResizableImString("");
@@ -90,20 +89,14 @@ public class PlayerListWindow {
}
}
public static void render() {
// todo: refactor this if we want to add a lot more windows
if (!Flashback.getConfig().openedWindows.contains("player_list")) {
wasOpen = WindowOpenState.CLOSED;
return;
}
if (wasOpen == WindowOpenState.CLOSED) {
public static void render(ImBoolean open, boolean newlyOpened) {
if (newlyOpened) {
ImGuiViewport viewport = ImGui.getMainViewport();
ImGui.setNextWindowPos(viewport.getCenterX(), viewport.getCenterY(), ImGuiCond.Appearing, 0.5f, 0.5f);
}
wasOpen = WindowOpenState.OPEN;
ImGui.setNextWindowSizeConstraints(250, 50, 5000, 5000);
if (ImGui.begin("Player List###PlayerList", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing)) {
if (ImGui.begin("Player List###PlayerList", open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing)) {
ImGui.setNextItemWidth(ImGui.getContentRegionAvailX() - ImGuiHelper.calcTextWidth("Search") - 32);
if (ImGui.inputText("Search", search)) {
lastSearch = null;
@@ -9,6 +9,7 @@ import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.combo_options.VideoCodec;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.state.EditorScene;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
@@ -158,7 +159,8 @@ public class StartExportWindow {
if (ImGuiHelper.inputInt("Start/end tick", startEndTick)) {
ReplayServer replayServer = Flashback.getReplayServer();
if (editorState != null && replayServer != null) {
editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks());
editorState.currentScene().setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks());
editorState.markDirty();
}
}
ImGuiHelper.inputFloat("Framerate", framerate);
@@ -487,14 +489,15 @@ public class StartExportWindow {
open = true;
EditorState editorState = EditorStateManager.getCurrent();
EditorScene editorScene = editorState == null ? null : editorState.currentScene();
if (editorState != null && editorState.exportStartTicks >= 0) {
startEndTick[0] = editorState.exportStartTicks;
if (editorScene != null && editorScene.exportStartTicks >= 0) {
startEndTick[0] = editorScene.exportStartTicks;
} else {
startEndTick[0] = 0;
}
if (editorState != null && editorState.exportEndTicks >= 0) {
startEndTick[1] = editorState.exportEndTicks;
if (editorScene != null && editorScene.exportEndTicks >= 0) {
startEndTick[1] = editorScene.exportEndTicks;
} else {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
File diff suppressed because it is too large. Load diff
@@ -6,21 +6,19 @@ import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.impl.CameraShakeKeyframe;
import com.moulberry.flashback.keyframe.impl.FOVKeyframe;
import com.moulberry.flashback.keyframe.impl.TimeOfDayKeyframe;
import com.moulberry.flashback.keyframe.types.FOVKeyframeType;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.state.EditorScene;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateHistoryAction;
import com.moulberry.flashback.state.EditorStateHistoryEntry;
import com.moulberry.flashback.state.EditorSceneHistoryAction;
import com.moulberry.flashback.state.EditorSceneHistoryEntry;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.state.KeyframeTrack;
import com.moulberry.flashback.visuals.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import imgui.ImGui;
import imgui.flag.ImGuiColorEditFlags;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.FogRenderer;
import java.util.List;
@@ -324,34 +322,36 @@ public class VisualsWindow {
private static void addKeyframe(EditorState editorState, ReplayServer replayServer, Keyframe keyframe) {
KeyframeType<?> keyframeType = keyframe.keyframeType();
EditorScene scene = editorState.currentScene();
// Try add to existing enabled keyframe track
for (int i = 0; i < editorState.keyframeTracks.size(); i++) {
KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i);
for (int i = 0; i < scene.keyframeTracks.size(); i++) {
KeyframeTrack keyframeTrack = scene.keyframeTracks.get(i);
if (keyframeTrack.enabled && keyframeTrack.keyframeType == keyframeType) {
editorState.setKeyframe(i, replayServer.getReplayTick(), keyframe);
scene.setKeyframe(i, replayServer.getReplayTick(), keyframe);
return;
}
}
// Try add to any keyframe track
for (int i = 0; i < editorState.keyframeTracks.size(); i++) {
KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(i);
for (int i = 0; i < scene.keyframeTracks.size(); i++) {
KeyframeTrack keyframeTrack = scene.keyframeTracks.get(i);
if (keyframeTrack.keyframeType == keyframeType) {
editorState.setKeyframe(i, replayServer.getReplayTick(), keyframe);
scene.setKeyframe(i, replayServer.getReplayTick(), keyframe);
return;
}
}
String description = "Added " + keyframeType.name() + " keyframe";
int newKeyframeTrackIndex = editorState.keyframeTracks.size();
editorState.push(new EditorStateHistoryEntry(
List.of(new EditorStateHistoryAction.RemoveTrack(keyframeType, newKeyframeTrackIndex)),
int newKeyframeTrackIndex = scene.keyframeTracks.size();
scene.push(new EditorSceneHistoryEntry(
List.of(new EditorSceneHistoryAction.RemoveTrack(keyframeType, newKeyframeTrackIndex)),
List.of(
new EditorStateHistoryAction.AddTrack(keyframeType, newKeyframeTrackIndex),
new EditorStateHistoryAction.SetKeyframe(keyframeType, newKeyframeTrackIndex, replayServer.getReplayTick(), keyframe)
new EditorSceneHistoryAction.AddTrack(keyframeType, newKeyframeTrackIndex),
new EditorSceneHistoryAction.SetKeyframe(keyframeType, newKeyframeTrackIndex, replayServer.getReplayTick(), keyframe)
),
description
));
editorState.markDirty();
}
}
@@ -0,0 +1,48 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.editor.ui.WindowOpenState;
import imgui.type.ImBoolean;
import java.util.Set;
public enum WindowType {
PLAYER_LIST("player_list", PlayerListWindow::render),
MOVEMENT("movement", MovementWindow::render);
private final String windowId;
private final ImGuiWindowRenderer renderMethod;
private final ImBoolean open = new ImBoolean();
private WindowOpenState openState = WindowOpenState.UNKNOWN;
WindowType(String windowId, ImGuiWindowRenderer renderMethod) {
this.windowId = windowId;
this.renderMethod = renderMethod;
}
public static void renderAll() {
FlashbackConfig config = Flashback.getConfig();
Set<String> openWindows = config.openedWindows;
for (WindowType windowType : values()) {
if (openWindows.contains(windowType.windowId)) {
boolean justOpened = windowType.openState == WindowOpenState.CLOSED;
windowType.open.set(true);
windowType.renderMethod.render(windowType.open, justOpened);
if (!windowType.open.get()) {
openWindows.remove(windowType.windowId);
config.delayedSaveToDefaultFolder();
}
windowType.openState = WindowOpenState.OPEN;
} else {
windowType.openState = WindowOpenState.CLOSED;
}
}
}
}
@@ -8,6 +8,7 @@ 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;
@@ -16,12 +17,9 @@ import com.moulberry.flashback.exporting.taskbar.TaskbarHost;
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;
@@ -37,6 +35,7 @@ import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.phys.Vec3;
import org.bytedeco.ffmpeg.global.avutil;
import org.joml.Matrix4f;
@@ -54,7 +53,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;
@@ -228,23 +226,25 @@ 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;
this.taskbar = TaskbarHost.createTaskbar();
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();
@@ -252,10 +252,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;
@@ -263,7 +263,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;
@@ -292,7 +292,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));
@@ -309,12 +309,12 @@ public class ExportJob {
RenderSystem.enableCull();
DeltaTracker.Timer timer = Minecraft.getInstance().deltaTracker;
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);
@@ -400,16 +400,24 @@ 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();
// Reset all walk animations & tick counts
for (Entity entity : minecraft.level.entitiesForRendering()) {
if (entity instanceof LivingEntity livingEntity) {
livingEntity.walkAnimation.stop();
}
entity.tickCount = 0;
}
// Advance until tick is at start
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
@@ -420,11 +428,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);
@@ -444,19 +452,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();
@@ -469,10 +478,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);
}
}
@@ -641,29 +650,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;
@@ -671,8 +663,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;
@@ -685,10 +679,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;
}
}
@@ -14,9 +14,6 @@ import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class ReplayReader {
private final FriendlyByteBuf friendlyByteBuf;
@@ -93,8 +90,8 @@ public class ReplayReader {
RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess);
action.handle(replayServer, registryFriendlyByteBuf);
if (slice.readerIndex() < size) {
throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex());
if (slice.readerIndex() < slice.writerIndex()) {
throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + slice.writerIndex() + " bytes available, only read " + slice.readerIndex());
}
}
@@ -127,8 +124,8 @@ public class ReplayReader {
RegistryFriendlyByteBuf registryFriendlyByteBuf = new RegistryFriendlyByteBuf(slice, this.registryAccess);
action.handle(replayServer, registryFriendlyByteBuf);
if (slice.readerIndex() < size) {
throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + size + " bytes available, only read " + slice.readerIndex());
if (slice.readerIndex() < slice.writerIndex()) {
throw new RuntimeException("Action " + this.lastActionName + " failed to fully read. Had " + slice.writerIndex() + " bytes available, only read " + slice.readerIndex());
}
return true;
@@ -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");
@@ -1,13 +1,12 @@
package com.moulberry.flashback.keyframe;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.state.KeyframeTrack;
import org.jetbrains.annotations.Nullable;
import java.util.function.Consumer;
public interface KeyframeType<T extends Keyframe> {
default @Nullable String icon() {
return null;
}
String name();
String id();
@Nullable T createDirect();
@@ -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) {
@@ -14,6 +14,11 @@ public class CameraKeyframeType implements KeyframeType<CameraKeyframe> {
private CameraKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue04b";
}
@Override
public String name() {
return "Camera";
@@ -22,6 +22,11 @@ public class CameraOrbitKeyframeType implements KeyframeType<CameraOrbitKeyframe
private CameraOrbitKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue577";
}
@Override
public String name() {
return "Camera Orbit";
@@ -17,6 +17,12 @@ public class CameraShakeKeyframeType implements KeyframeType<CameraShakeKeyframe
private CameraShakeKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\uefeb";
}
@Override
public String name() {
return "Camera Shake";
@@ -20,6 +20,11 @@ public class FOVKeyframeType implements KeyframeType<FOVKeyframe> {
private FOVKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue3af";
}
@Override
public String name() {
return "FOV";
@@ -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;
};
}
}
@@ -20,6 +20,11 @@ public class SpeedKeyframeType implements KeyframeType<TickrateKeyframe> {
private SpeedKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue9e4";
}
@Override
public String name() {
return "Speed";
@@ -20,6 +20,11 @@ public class TimeOfDayKeyframeType implements KeyframeType<TimeOfDayKeyframe> {
private TimeOfDayKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue518";
}
@Override
public String name() {
return "Time of day";
@@ -15,6 +15,11 @@ public class TimelapseKeyframeType implements KeyframeType<TimelapseKeyframe> {
private TimelapseKeyframeType() {
}
@Override
public @Nullable String icon() {
return "\ue422";
}
@Override
public String name() {
return "Timelapse";
@@ -169,9 +169,6 @@ public abstract class MixinLevelRenderer {
}
}
@Unique
private Biome.Precipitation forcePrecipitation = null;
@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) {
EditorState editorState = EditorStateManager.getCurrent();
@@ -198,33 +195,33 @@ public abstract class MixinLevelRenderer {
}
}
@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) {
if (PerfectFrames.isEnabled()) {
boolean doCompile = true;
while (doCompile) {
doCompile = false;
int before = this.visibleSections.size();
original.call(instance, camera, frustum, capturedFrustum, isSpectator);
if (this.visibleSections.size() != before) {
doCompile = true;
}
RenderRegionCache renderRegionCache = new RenderRegionCache();
for (SectionRenderDispatcher.RenderSection renderSection : this.visibleSections) {
if (renderSection.isDirty()) {
this.sectionRenderDispatcher.rebuildSectionSync(renderSection, renderRegionCache);
renderSection.setNotDirty();
doCompile = true;
}
}
this.sectionRenderDispatcher.uploadAllPendingUploads();
}
} else {
original.call(instance, camera, frustum, capturedFrustum, isSpectator);
}
}
// @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) {
// if (PerfectFrames.isEnabled()) {
// boolean doCompile = true;
// while (doCompile) {
// doCompile = false;
//
// int before = this.visibleSections.size();
// original.call(instance, camera, frustum, capturedFrustum, isSpectator);
// if (this.visibleSections.size() != before) {
// doCompile = true;
// }
//
// RenderRegionCache renderRegionCache = new RenderRegionCache();
// for (SectionRenderDispatcher.RenderSection renderSection : this.visibleSections) {
// if (renderSection.isDirty()) {
// this.sectionRenderDispatcher.rebuildSectionSync(renderSection, renderRegionCache);
// renderSection.setNotDirty();
// doCompile = true;
// }
// }
//
// this.sectionRenderDispatcher.uploadAllPendingUploads();
// }
// } else {
// original.call(instance, camera, frustum, capturedFrustum, isSpectator);
// }
// }
}
@@ -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;
@@ -131,6 +131,13 @@ public abstract class MixinMinecraft implements MinecraftExt {
@Nullable
public Entity cameraEntity;
@Shadow
@Final
public DeltaTracker.Timer deltaTracker;
@Shadow
public long clientTickCount;
@Inject(method="<init>", at=@At("RETURN"))
public void init(GameConfig gameConfig, CallbackInfo ci) {
ReplayUI.init();
@@ -195,17 +202,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.deltaTracker 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());
}
}
}
}
@@ -275,7 +335,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) {
@@ -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);
}
}
}
@@ -2,26 +2,18 @@ package com.moulberry.flashback.mixin.ui;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local;
import com.llamalad7.mixinextras.sugar.ref.LocalIntRef;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.screen.FlashbackButton;
import com.moulberry.flashback.screen.SelectReplayScreen;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import com.moulberry.flashback.screen.select_replay.SelectReplayScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.AbstractButton;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.ImageButton;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.screens.AlertScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
@@ -96,7 +88,7 @@ public class MixinTitleScreen extends Screen {
List<String> incompatibleMods = Screen.hasShiftDown() ? List.of() : Flashback.getReplayIncompatibleMods();
if (incompatibleMods.isEmpty()) {
this.minecraft.setScreen(new SelectReplayScreen(this));
this.minecraft.setScreen(new SelectReplayScreen(this, Flashback.getReplayFolder()));
} else {
String mods = StringUtils.join(incompatibleMods, ", ");
String description = """
@@ -0,0 +1,15 @@
package com.moulberry.flashback.packet;
import com.moulberry.flashback.Flashback;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
public class FlashbackClearEntities implements CustomPacketPayload {
public static final Type<FlashbackClearEntities> TYPE = new Type<>(Flashback.createResourceLocation("clear_entities"));
public static final FlashbackClearEntities INSTANCE = new FlashbackClearEntities();
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}
@@ -19,6 +19,16 @@ public class FakePlayer extends ServerPlayer {
super(minecraftServer, serverLevel, gameProfile, clientInformation);
}
@Override
public void remove(RemovalReason removalReason) {
if (removalReason == RemovalReason.DISCARDED && !this.hasDisconnected()) {
this.disconnect();
this.server.getPlayerList().remove(this);
} else {
super.remove(removalReason);
}
}
@Override
public void sendChatMessage(OutgoingChatMessage outgoingChatMessage, boolean bl, ChatType.Bound bound) {
}
@@ -192,7 +192,7 @@ public class ReplayConfigurationPacketHandler implements ClientConfigurationPack
// Remove all players
for (ServerPlayer player : new ArrayList<>(this.replayServer.getPlayerList().getPlayers())) {
player.connection.disconnect(Component.empty());
player.discard();
}
// Remove all levels
@@ -14,6 +14,8 @@ import com.moulberry.flashback.packet.FlashbackRemoteSetSlot;
import io.netty.channel.embedded.EmbeddedChannel;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.fabric.impl.screenhandler.Networking;
import net.minecraft.client.multiplayer.PlayerInfo;
@@ -95,11 +97,11 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
private void forward(Entity entity, Packet<?> packet) {
if (entity == null) {
return;
this.forward(packet);
} else {
ServerChunkCache serverChunkCache = this.level().getChunkSource();
serverChunkCache.broadcast(entity, packet);
}
ServerChunkCache serverChunkCache = this.level().getChunkSource();
serverChunkCache.broadcast(entity, packet);
}
private void setBlockState(ServerLevel level, BlockPos blockPos, BlockState blockState) {
@@ -121,7 +123,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
Entity existingEntity = level.getEntity(pendingEntity.getId());
if (existingEntity != null) {
if (existingEntity instanceof ServerPlayer existingPlayer) {
existingPlayer.connection.disconnect(Component.empty());
existingPlayer.discard();
} else if (existingEntity.getType().equals(pendingEntity.getType())) {
existingEntity.restoreFrom(pendingEntity);
existingEntity.setPos(pendingEntity.getX(), pendingEntity.getY(), pendingEntity.getZ());
@@ -209,16 +211,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
ServerPlayer existingPlayer = this.replayServer.getPlayerList().getPlayer(serverPlayer.getUUID());
if (existingPlayer != null) {
existingPlayer.connection.disconnect(Component.empty());
existingPlayer.discard();
}
Entity existingEntity = this.level().getEntity(serverPlayer.getId());
if (existingEntity != null) {
if (existingEntity instanceof ServerPlayer existingPlayer2) {
existingPlayer2.connection.disconnect(Component.empty());
} else {
existingEntity.discard();
}
existingEntity.discard();
}
for (ReplayPlayer replayViewer : this.replayServer.getReplayViewers()) {
@@ -281,8 +279,6 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
if (existingEntity instanceof ExperienceOrb) {
existingEntity.restoreFrom(entity);
return;
} else if (existingEntity instanceof ServerPlayer serverPlayer) {
serverPlayer.connection.disconnect(Component.empty());
} else if (existingEntity != null) {
existingEntity.discard();
}
@@ -483,11 +479,20 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleEntityLinkPacket(ClientboundSetEntityLinkPacket clientboundSetEntityLinkPacket) {
Entity source = this.level().getEntity(clientboundSetEntityLinkPacket.getSourceId());
if (source == null) {
forward(clientboundSetEntityLinkPacket);
return;
}
if (source instanceof Leashable leashable) {
if (clientboundSetEntityLinkPacket.getDestId() == 0) {
leashable.setLeashedTo(null, true);
} else {
Entity dest = this.level().getEntity(clientboundSetEntityLinkPacket.getDestId());
if (dest == null) {
forward(clientboundSetEntityLinkPacket);
return;
}
leashable.setLeashedTo(dest, true);
}
}
@@ -677,7 +682,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
if (level != null && level.getEntity(this.localPlayerId) instanceof ServerPlayer serverPlayer) {
localPlayer = serverPlayer;
if (this.localPlayerId != clientboundLoginPacket.playerId()) {
localPlayer.connection.disconnect(Component.empty());
localPlayer.discard();
recreatePlayer = true;
}
}
@@ -908,22 +913,26 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleRemoveEntities(ClientboundRemoveEntitiesPacket clientboundRemoveEntitiesPacket) {
IntList forwardRemoveUnknown = new IntArrayList();
clientboundRemoveEntitiesPacket.getEntityIds().forEach(i -> {
Entity entity = this.level().getEntity(i);
if (entity != null) {
if (entity instanceof ServerPlayer serverPlayer) {
serverPlayer.connection.disconnect(Component.empty());
} else {
entity.discard();
}
if (entity == null) {
forwardRemoveUnknown.add(i);
} else {
entity.discard();
}
});
if (!forwardRemoveUnknown.isEmpty()) {
forward(new ClientboundRemoveEntitiesPacket(forwardRemoveUnknown));
}
}
@Override
public void handleRemoveMobEffect(ClientboundRemoveMobEffectPacket clientboundRemoveMobEffectPacket) {
Entity entity = clientboundRemoveMobEffectPacket.getEntity(this.level());
if (entity instanceof LivingEntity livingEntity) {
Entity entity = this.getEntityOrPending(clientboundRemoveMobEffectPacket.entityId());
if (entity == null) {
forward(clientboundRemoveMobEffectPacket);
} else if (entity instanceof LivingEntity livingEntity) {
livingEntity.removeEffect(clientboundRemoveMobEffectPacket.effect());
}
}
@@ -969,7 +978,12 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleRotateMob(ClientboundRotateHeadPacket clientboundRotateHeadPacket) {
Entity entity = this.getEntityOrPending(clientboundRotateHeadPacket.entityId);
if (entity == null || entity.getId() == this.localPlayerId) {
if (entity == null) {
forward(clientboundRotateHeadPacket);
return;
}
if (entity.getId() == this.localPlayerId) {
return;
}
@@ -1012,6 +1026,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
public void handleSetEntityData(ClientboundSetEntityDataPacket clientboundSetEntityDataPacket) {
Entity entity = this.getEntityOrPending(clientboundSetEntityDataPacket.id());
if (entity == null) {
forward(clientboundSetEntityDataPacket);
return;
}
@@ -1019,6 +1034,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
SynchedEntityData entityData = entity.getEntityData();
for (SynchedEntityData.DataValue<?> dataValue : clientboundSetEntityDataPacket.packedItems()) {
if (dataValue.id() >= entityData.itemsById.length) {
continue;
}
SynchedEntityData.DataItem<?> dataItem = entityData.itemsById[dataValue.id()];
entityData.set((EntityDataAccessor) dataItem.getAccessor(), dataValue.value(), true);
}
@@ -1028,6 +1047,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
public void handleSetEntityMotion(ClientboundSetEntityMotionPacket clientboundSetEntityMotionPacket) {
Entity entity = this.getEntityOrPending(clientboundSetEntityMotionPacket.getId());
if (entity == null) {
forward(clientboundSetEntityMotionPacket);
return;
}
@@ -1041,6 +1061,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleSetEquipment(ClientboundSetEquipmentPacket clientboundSetEquipmentPacket) {
Entity entity = this.getEntityOrPending(clientboundSetEquipmentPacket.getEntity());
if (entity == null) {
forward(clientboundSetEquipmentPacket);
return;
}
if (entity instanceof LivingEntity livingEntity) {
clientboundSetEquipmentPacket.getSlots().forEach((pair) -> {
livingEntity.setItemSlot(pair.getFirst(), pair.getSecond());
@@ -1168,6 +1192,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
public void handleSoundEntityEvent(ClientboundSoundEntityPacket clientboundSoundEntityPacket) {
Entity entity = this.level().getEntity(clientboundSoundEntityPacket.getId());
if (entity == null) {
forward(clientboundSoundEntityPacket);
return;
}
@@ -1187,11 +1212,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
Entity taken = this.level().getEntity(clientboundTakeItemEntityPacket.getItemId());
if (taken != null) {
if (taken instanceof ServerPlayer serverPlayer) {
serverPlayer.connection.disconnect(Component.empty());
} else {
taken.discard();
}
taken.discard();
}
}
@@ -1199,6 +1220,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
public void handleTeleportEntity(ClientboundTeleportEntityPacket clientboundTeleportEntityPacket) {
Entity entity = this.getEntityOrPending(clientboundTeleportEntityPacket.id());
if (entity == null) {
forward(clientboundTeleportEntityPacket);
return;
}
@@ -1227,6 +1249,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleUpdateAttributes(ClientboundUpdateAttributesPacket clientboundUpdateAttributesPacket) {
Entity entity = this.getEntityOrPending(clientboundUpdateAttributesPacket.getEntityId());
if (entity == null) {
forward(clientboundUpdateAttributesPacket);
return;
}
if (entity instanceof LivingEntity livingEntity) {
AttributeMap attributeMap = livingEntity.getAttributes();
for (ClientboundUpdateAttributesPacket.AttributeSnapshot snapshot : clientboundUpdateAttributesPacket.getValues()) {
@@ -1247,6 +1273,10 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleUpdateMobEffect(ClientboundUpdateMobEffectPacket clientboundUpdateMobEffectPacket) {
Entity entity = this.getEntityOrPending(clientboundUpdateMobEffectPacket.getEntityId());
if (entity == null) {
forward(clientboundUpdateMobEffectPacket);
return;
}
if (entity instanceof LivingEntity livingEntity) {
Holder<MobEffect> holder = clientboundUpdateMobEffectPacket.getEffect();
MobEffectInstance mobEffectInstance = new MobEffectInstance(holder, clientboundUpdateMobEffectPacket.getEffectDurationTicks(), clientboundUpdateMobEffectPacket.getEffectAmplifier(),
@@ -4,11 +4,13 @@ import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mojang.authlib.GameProfile;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.PacketHelper;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.ext.LevelChunkExt;
import com.moulberry.flashback.TempFolderProvider;
import com.moulberry.flashback.keyframe.handler.ReplayServerKeyframeHandler;
import com.moulberry.flashback.packet.FlashbackAccurateEntityPosition;
import com.moulberry.flashback.packet.FlashbackClearEntities;
import com.moulberry.flashback.packet.FlashbackClearParticles;
import com.moulberry.flashback.packet.FlashbackForceClientTick;
import com.moulberry.flashback.packet.FlashbackInstantlyLerp;
@@ -34,8 +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.FileUtil;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.server.IntegratedServer;
@@ -49,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;
@@ -111,6 +112,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;
@@ -367,8 +372,8 @@ public class ReplayServer extends IntegratedServer {
super.removeAll();
} else {
List<ServerPlayer> players = this.getPlayers();
for (int i = 0; i < players.size(); ++i) {
players.get(i).connection.disconnect(shutdownReason);
for (ServerPlayer player : players) {
player.connection.disconnect(shutdownReason);
}
}
}
@@ -426,6 +431,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;
}
@@ -643,6 +653,10 @@ public class ReplayServer extends IntegratedServer {
}
positionUpdateSet.add(id);
} 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));
}
}
}
@@ -702,6 +716,9 @@ public class ReplayServer extends IntegratedServer {
public static final TicketType<ChunkPos> ENTITY_LOAD_TICKET = TicketType.create("replay_entity_load", Comparator.comparingLong(ChunkPos::toLong), 5);
public void closeLevel(ServerLevel serverLevel) {
if (serverLevel == null) {
return;
}
this.clearLevel(serverLevel);
try {
serverLevel.close();
@@ -711,12 +728,15 @@ public class ReplayServer extends IntegratedServer {
}
public void clearLevel(ServerLevel serverLevel) {
if (serverLevel == null) {
return;
}
for (ServerPlayer player : new ArrayList<>(serverLevel.players())) {
if (player instanceof ReplayPlayer replayPlayer) {
replayPlayer.lastFirstPersonDataUUID = null;
continue;
}
player.connection.disconnect(Component.empty());
player.discard();
}
List<Entity> entities = new ArrayList<>();
for (Entity entity : serverLevel.getAllEntities()) {
@@ -731,6 +751,12 @@ public class ReplayServer extends IntegratedServer {
}
}
serverLevel.setDayTime(0);
for (ServerPlayer player : serverLevel.players()) {
if (player instanceof ReplayPlayer replayPlayer) {
ServerPlayNetworking.send(replayPlayer, FlashbackClearEntities.INSTANCE);
}
}
}
@Override
@@ -755,9 +781,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
@@ -803,10 +827,8 @@ public class ReplayServer extends IntegratedServer {
this.replayPaused = true;
}
boolean forceApplyKeyframes = this.forceApplyKeyframes.compareAndSet(true, false) && Flashback.EXPORT_JOB == null;
if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback) {
this.runUpdates(booleanSupplier, forceApplyKeyframes);
if (Flashback.EXPORT_JOB != null || this.targetTick == this.currentTick || normalPlayback || this.isFrozen) {
this.runUpdates(booleanSupplier);
} else {
int realTargetTick = this.targetTick;
@@ -819,12 +841,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;
@@ -836,7 +858,7 @@ public class ReplayServer extends IntegratedServer {
}
}
if (forceApplyKeyframes) {
if (this.forceApplyKeyframes.compareAndSet(true, false)) {
((MinecraftExt)Minecraft.getInstance()).flashback$applyKeyframes();
}
@@ -964,10 +986,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;
@@ -975,14 +1006,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()) {
@@ -996,7 +1047,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();
@@ -1060,18 +1111,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);
}
}
}
@@ -20,6 +20,7 @@ public class FlashbackMeta {
public UUID replayIdentifier = UUID.randomUUID();
public String name = "Unnamed";
public String versionString = null;
public String worldName = null;
public String bobbyWorldName = null;
public int dataVersion = 0;
public int protocolVersion = 0;
@@ -39,6 +40,9 @@ public class FlashbackMeta {
if (this.versionString != null) {
meta.addProperty("version_string", this.versionString);
}
if (this.worldName != null) {
meta.addProperty("world_name", this.worldName);
}
if (this.dataVersion != 0) {
meta.addProperty("data_version", this.dataVersion);
}
@@ -98,6 +102,9 @@ public class FlashbackMeta {
if (meta.has("version_string")) {
flashbackMeta.versionString = meta.get("version_string").getAsString();
}
if (meta.has("world_name")) {
flashbackMeta.worldName = meta.get("world_name").getAsString();
}
if (meta.has("data_version")) {
flashbackMeta.dataVersion = meta.get("data_version").getAsInt();
}
@@ -27,9 +27,12 @@ import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.resources.server.ServerPackManager;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.core.*;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
@@ -159,6 +162,24 @@ public class Recorder {
if (Flashback.supportsDistantHorizons) {
this.metadata.distantHorizonPaths.putAll(DistantHorizonsSupport.getDimensionPaths());
}
String worldName = null;
ServerData serverData = Minecraft.getInstance().getCurrentServer();
if (serverData != null) {
worldName = serverData.name;
if (worldName.equalsIgnoreCase(I18n.get("selectServer.defaultName"))) {
worldName = null;
}
} else {
IntegratedServer integratedServer = Minecraft.getInstance().getSingleplayerServer();
if (integratedServer != null) {
worldName = integratedServer.worldData.getLevelName();
if (worldName.equalsIgnoreCase(I18n.get("selectWorld.newWorld"))) {
worldName = null;
}
}
}
this.metadata.worldName = worldName;
}
public boolean readyToWrite() {
@@ -883,13 +904,13 @@ public class Recorder {
Set<UUID> addedEntries = new HashSet<>();
for (AbstractClientPlayer player : level.players()) {
if (addedEntries.add(player.getUUID())) {
PlayerInfo info = connection.getPlayerInfo(player.getUUID());
PlayerInfo info = player.getPlayerInfo();
if (info != null) {
infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(),
player.getGameProfile(), true, info.getLatency(), info.getGameMode(), info.getTabListDisplayName(), info.getTabListOrder(), null));
} else {
infoUpdatePacket.entries.add(new ClientboundPlayerInfoUpdatePacket.Entry(player.getUUID(),
player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), info.getTabListOrder(), null));
player.getGameProfile(), true, 0, GameType.DEFAULT_MODE, player.getDisplayName(), 0, null));
}
}
}
@@ -36,7 +36,7 @@ public class EditReplayScreen extends Screen {
private Path replayPath;
protected EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) {
public EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) {
super(Component.literal("Edit Replay"));
this.lastScreen = lastScreen;
this.metadata = summary.getReplayMetadata();
@@ -1,526 +0,0 @@
/*
* Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4).
*/
package com.moulberry.flashback.screen;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.logging.LogUtils;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.record.FlashbackMeta;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.SharedConstants;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
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.narration.NarrationElementOutput;
import net.minecraft.client.gui.navigation.CommonInputs;
import net.minecraft.client.gui.screens.*;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList.Entry> {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault());
private static final ResourceLocation ERROR_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error_highlighted");
private static final ResourceLocation ERROR_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error");
private static final ResourceLocation WARNING_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning_highlighted");
static private final ResourceLocation WARNING_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning");
private static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join_highlighted");
private static final ResourceLocation JOIN_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join");
private static final Logger LOGGER = LogUtils.getLogger();
private final SelectReplayScreen screen;
private CompletableFuture<List<ReplaySummary>> pendingReplays;
@Nullable
private List<ReplaySummary> currentlyDisplayedReplays;
private String filter;
private final LoadingHeader loadingHeader;
private final LoadFromDeviceHeader loadFromDeviceHeader;
private Map<UUID, Long> lastOpenTimes = null;
public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l, String string, @Nullable ReplaySelectionList replaySelectionList) {
super(minecraft, i, j, k, l);
this.screen = selectReplayScreen;
this.loadingHeader = new LoadingHeader(minecraft);
this.loadFromDeviceHeader = new LoadFromDeviceHeader(minecraft);
this.filter = string;
this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays();
this.handleNewReplays(this.pollReplaysIgnoreErrors());
}
@Override
protected void clearEntries() {
this.children().forEach(Entry::close);
super.clearEntries();
}
@Nullable
private List<ReplaySummary> pollReplaysIgnoreErrors() {
try {
return this.pendingReplays.getNow(null);
} catch (CancellationException | CompletionException runtimeException) {
return null;
}
}
private void reloadWorldList() {
this.pendingReplays = this.loadReplays();
}
@Override
public boolean keyPressed(int i, int j, int k) {
if (CommonInputs.selected(i)) {
ReplayListEntry replayListEntry = this.getReplayListEntry();
if (replayListEntry != null && replayListEntry.canOpen()) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
replayListEntry.openReplay();
return true;
}
}
return super.keyPressed(i, j, k);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
List<ReplaySummary> list = this.pollReplaysIgnoreErrors();
if (list != this.currentlyDisplayedReplays) {
this.handleNewReplays(list);
}
super.renderWidget(guiGraphics, i, j, f);
}
private void handleNewReplays(@Nullable List<ReplaySummary> list) {
if (list == null) {
this.fillLoadingReplays();
} else {
this.fillReplays(this.filter, list);
}
this.currentlyDisplayedReplays = list;
}
public void updateFilter(String string) {
if (this.currentlyDisplayedReplays != null && !string.equals(this.filter)) {
this.fillReplays(string, this.currentlyDisplayedReplays);
}
this.filter = string;
}
// private Path getOpenTimeCachePath() {
// Path flashbackDir = Flashback.getDataDirectory();
// Path replayDir = flashbackDir.resolve("replays");
// return replayDir.resolve(".lastopened.json");
// }
//
// private synchronized long getOpenTime(UUID uuid) {
// if (this.lastOpenTimes == null) {
// Path path = getOpenTimeCachePath();
//
// if (Files.exists(path)) {
// try {
// String serialized = Files.readString(path);
// TypeToken<Map<UUID, Long>> typeToken = (TypeToken<Map<UUID, Long>>) TypeToken.getParameterized(Map.class, UUID.class, Long.class);
// this.lastOpenTimes = FlashbackGson.PRETTY.fromJson(serialized, typeToken);
// return this.lastOpenTimes.getOrDefault(uuid, 0L);
// } catch (IOException e) {
// Flashback.LOGGER.error("Unable to read last opened cache", e);
// }
// }
//
// this.lastOpenTimes = new HashMap<>();
// }
//
// return this.lastOpenTimes.getOrDefault(uuid, 0L);
// }
//
// private synchronized void setOpenTime(UUID uuid, long time) {
// this.lastOpenTimes.put(uuid, time);
// }
//
// private synchronized void saveOpenTimeCache() {
// String serialized = FlashbackGson.PRETTY.toJson(this.lastOpenTimes);
// try {
// Files.writeString(getOpenTimeCachePath(), serialized, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
// StandardOpenOption.CREATE);
// } catch (IOException e) {
// Flashback.LOGGER.error("Unable to write last opened cache", e);
// }
// }
private CompletableFuture<List<ReplaySummary>> loadReplays() {
Path flashbackDir = Flashback.getDataDirectory();
Path replayDir = flashbackDir.resolve("replays");
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
return CompletableFuture.completedFuture(List.of());
}
ArrayList<CompletableFuture<ReplaySummary>> futures = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayDir)) {
for (Path path : directoryStream) {
if (!path.toString().endsWith(".zip")) {
continue;
}
futures.add(CompletableFuture.supplyAsync(() -> {
try {
String fileName = path.getFileName().toString();
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis());
byte[] iconBytes = null;
String metadataString = null;
try (FileSystem fs = FileSystems.newFileSystem(path)) {
Path iconPath = fs.getPath("/icon.png");
if (Files.exists(iconPath)) {
iconBytes = Files.readAllBytes(iconPath);
}
Path metadataPath = fs.getPath("/metadata.json");
if (Files.exists(metadataPath)) {
metadataString = Files.readString(metadataPath);
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
if (metadataString == null) {
return null;
}
JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class);
FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson);
if (metadata != null) {
return new ReplaySummary(path, metadata, fileName, lastModified, iconBytes);
}
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load replay", e);
}
return null;
}, Util.backgroundExecutor()));
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
return Util.sequenceFailFastAndCancel(futures).thenApply(list -> list.stream().filter(Objects::nonNull).sorted().toList());
}
private void fillReplays(String string, List<ReplaySummary> list) {
this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
string = string.toLowerCase(Locale.ROOT);
for (ReplaySummary ReplaySummary : list) {
if (!this.filterAccepts(string, ReplaySummary)) continue;
this.addEntry(new ReplayListEntry(this, ReplaySummary));
}
this.notifyListUpdated();
}
private boolean filterAccepts(String string, ReplaySummary ReplaySummary) {
return ReplaySummary.getReplayName().toLowerCase(Locale.ROOT).contains(string) || ReplaySummary.getReplayId().toLowerCase(Locale.ROOT).contains(string);
}
private void fillLoadingReplays() {
this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
this.addEntry(this.loadingHeader);
this.notifyListUpdated();
}
private void notifyListUpdated() {
this.setScrollAmount(this.getScrollAmount());
this.screen.triggerImmediateNarration(true);
this.screen.updateButtonStatus(null);
}
@Override
public int getRowWidth() {
return 270;
}
@Override
public void setSelected(@Nullable Entry entry) {
if (entry instanceof LoadFromDeviceHeader) {
Flashback.openReplayFromFileBrowser();
return;
}
super.setSelected(entry);
if (entry instanceof ReplayListEntry replayListEntry) {
this.screen.updateButtonStatus(replayListEntry.summary);
} else {
this.screen.updateButtonStatus(null);
}
}
@Nullable
public ReplayListEntry getReplayListEntry() {
if (this.getSelected() instanceof ReplayListEntry replayListEntry) {
return replayListEntry;
} else {
return null;
}
}
public SelectReplayScreen getScreen() {
return this.screen;
}
@Override
public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) {
if (this.children().contains(this.loadingHeader)) {
this.loadingHeader.updateNarration(narrationElementOutput);
return;
}
super.updateWidgetNarration(narrationElementOutput);
}
public static class LoadingHeader extends Entry {
private static final Component LOADING_LABEL = Component.translatable("flashback.select_replay.loading_replays");
private final Minecraft minecraft;
public LoadingHeader(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) {
int p = (this.minecraft.screen.width - this.minecraft.font.width(LOADING_LABEL)) / 2;
int q = j + (m - this.minecraft.font.lineHeight) / 2;
guiGraphics.drawString(this.minecraft.font, LOADING_LABEL, p, q, 0xFFFFFF, false);
String string = LoadingDotsText.get(Util.getMillis());
int r = (this.minecraft.screen.width - this.minecraft.font.width(string)) / 2;
int s = q + this.minecraft.font.lineHeight;
guiGraphics.drawString(this.minecraft.font, string, r, s, -8355712, false);
}
@Override
public Component getNarration() {
return LOADING_LABEL;
}
}
public 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(RenderType::guiTextured, 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 {
private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32;
private final Minecraft minecraft;
private final SelectReplayScreen screen;
final ReplaySummary summary;
private final FaviconTexture icon;
private long lastClickTime;
public ReplayListEntry(ReplaySelectionList replaySelectionList2, ReplaySummary ReplaySummary) {
this.minecraft = replaySelectionList2.minecraft;
this.screen = replaySelectionList2.getScreen();
this.summary = ReplaySummary;
this.icon = FaviconTexture.forWorld(this.minecraft.getTextureManager(), ReplaySummary.getReplayId());
this.loadIcon();
}
@Override
public Component getNarration() {
MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(),
Component.translationArg(new Date(this.summary.getLastModified())),
this.summary.getInfo());
return Component.translatable("narrator.select", component);
}
@Override
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 fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastModified();
if (p != -1L) {
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
}
if (StringUtils.isEmpty(title)) {
title = I18n.get("flashback.select_replay.replay") + " " + (index + 1);
}
Component info = this.summary.getInfo();
int titleColour = 0xFFFFFF;
if (!this.summary.canOpen()) {
titleColour = 0xFF5555;
} else if (this.summary.hasWarning()) {
titleColour = 0xFFAA55;
}
guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, 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, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blit(RenderType::guiTextured, this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = mouseX - x;
boolean hoveredIcon = q < 32;
if (hovered && this.summary.getHoverInfo() != null) {
guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY);
}
ResourceLocation iconOverlay;
if (!this.summary.canOpen()) {
iconOverlay = hoveredIcon ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE;
} else if (this.summary.hasWarning()) {
iconOverlay = hoveredIcon ? WARNING_HIGHLIGHTED_SPRITE : WARNING_SPRITE;
} else {
iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
}
guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT);
}
}
@Override
public boolean mouseClicked(double d, double e, int i) {
if (!this.summary.canOpen()) {
return true;
}
ReplaySelectionList.this.setSelected(this);
if (d - (double) ReplaySelectionList.this.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) {
if (this.canOpen()) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
this.openReplay();
}
return true;
}
this.lastClickTime = Util.getMillis();
return super.mouseClicked(d, e, i);
}
public boolean canOpen() {
return this.summary.canOpen();
}
public void openReplay() {
if (this.summary.canOpen()) {
this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("flashback.select_replay.data_read")));
Flashback.openReplayWorld(this.summary.getPath());
// setOpenTime(this.summary.getReplayMetadata().replayIdentifier, System.currentTimeMillis());
// saveOpenTimeCache();
}
}
public void deleteReplay() {
this.minecraft.setScreen(new ConfirmScreen(bl -> {
if (bl) {
this.minecraft.setScreen(new ProgressScreen(true));
this.doDeleteReplay();
}
this.minecraft.setScreen(this.screen);
}, Component.translatable("flashback.select_replay.delete_question"),
Component.translatable("selectWorld.deleteWarning", this.summary.getReplayName()),
Component.translatable("selectWorld.deleteButton"),
CommonComponents.GUI_CANCEL)
);
}
private void doDeleteReplay() {
String id = this.summary.getReplayId();
try {
Files.delete(this.summary.getPath());
} catch (IOException e) {
SystemToast.onWorldDeleteFailure(this.minecraft, id);
LOGGER.error("Failed to delete replay {}", id, e);
}
ReplaySelectionList.this.reloadWorldList();
}
public void editReplay() {
Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary));
}
private void loadIcon() {
byte[] iconBytes = this.summary.getIconBytes();
if (iconBytes != null) {
try {
this.icon.upload(NativeImage.read(iconBytes));
return;
} catch (Throwable t) {
LOGGER.error("Invalid icon for replay {}", this.summary.getReplayId(), t);
}
}
this.icon.clear();
}
@Override
public void close() {
this.icon.close();
}
}
public static abstract class Entry extends ObjectSelectionList.Entry<Entry> implements AutoCloseable {
@Override
public void close() {}
}
}
@@ -19,17 +19,19 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
private final FlashbackMeta metadata;
private final String replayId;
private final long lastModified;
private final long filesize;
private final byte[] iconBytes;
private Component info = null;
private Component hoverInfo = null;
private boolean canOpen = true;
private boolean hasWarning = false;
public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, @Nullable byte[] iconBytes) {
public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, long filesize, @Nullable byte[] iconBytes) {
this.path = path;
this.metadata = metadata;
this.replayId = replayId;
this.lastModified = lastModified;
this.filesize = filesize;
this.iconBytes = iconBytes;
if (metadata.protocolVersion != 0 && metadata.protocolVersion != SharedConstants.getProtocolVersion()) {
@@ -71,10 +73,18 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name;
}
public @Nullable String getWorldName() {
return this.metadata.worldName;
}
public long getLastModified() {
return this.lastModified;
}
public long getFilesize() {
return filesize;
}
public Component getInfo() {
if (this.info == null) {
MutableComponent mutable = Component.empty();
@@ -48,7 +48,7 @@ public class UnsupportedLoaderScreen extends Screen {
if (this.countdown == 0) {
var button = Button.builder(Component.literal("I Understand"), b -> {
Flashback.getConfig().nextUnsupportedModLoaderWarning = System.currentTimeMillis() + Duration.ofDays(7).toMillis();
Flashback.getConfig().saveToDefaultFolder();
Flashback.getConfig().delayedSaveToDefaultFolder();
Minecraft.getInstance().setScreen(this.lastScreen);
}).bounds((this.width - 150) / 2, buttonY, 150, 20).build();
this.addRenderableWidget(button);
@@ -0,0 +1,157 @@
package com.moulberry.flashback.screen.select_replay;/*
NaturalOrderComparator.java -- Perform 'natural order' comparisons of strings in Java.
Copyright (C) 2003 by Pierre-Luc Paour <natorder@paour.com>
Based on the C version by Martin Pool, of which this is more or less a straight conversion.
Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
===== Moulberry =====
This is an altered source version.
This message is marking it as such.
=====================
*/
import java.util.*;
public class NaturalOrderComparator implements Comparator<String> {
public static NaturalOrderComparator INSTANCE = new NaturalOrderComparator();
private int compareRight(String a, String b) {
int bias = 0, ia = 0, ib = 0;
// The longest run of digits wins. That aside, the greatest
// value wins, but we can't know that it will until we've scanned
// both numbers to know that they have the same magnitude, so we
// remember it in BIAS.
for (;; ia++, ib++) {
char ca = charAt(a, ia);
char cb = charAt(b, ib);
if (!isDigit(ca) && !isDigit(cb)) {
return bias;
}
if (!isDigit(ca)) {
return -1;
}
if (!isDigit(cb)) {
return +1;
}
if (ca == 0 && cb == 0) {
return bias;
}
if (bias == 0) {
if (ca < cb) {
bias = -1;
} else if (ca > cb) {
bias = +1;
}
}
}
}
public int compare(String a, String b) {
int indexA = 0, indexB = 0;
int numZeroesA, numZeroesB;
char charA, charB;
while (true) {
// Only count the number of zeroes leading the last number compared
numZeroesA = numZeroesB = 0;
charA = charAt(a, indexA);
charB = charAt(b, indexB);
// skip over leading spaces or zeros
while (Character.isSpaceChar(charA) || charA == '0') {
if (charA == '0') {
numZeroesA++;
} else {
// Only count consecutive zeroes
numZeroesA = 0;
}
charA = charAt(a, ++indexA);
}
while (Character.isSpaceChar(charB) || charB == '0') {
if (charB == '0') {
numZeroesB++;
} else {
// Only count consecutive zeroes
numZeroesB = 0;
}
charB = charAt(b, ++indexB);
}
if (charA == 0 && charB == 0) {
// The strings compare the same. Perhaps the caller
// will want to call strcmp to break the tie.
return compareEqual(a, b, numZeroesA, numZeroesB);
}
// Process run of digits
boolean isDigitA = Character.isDigit(charA);
boolean isDigitB = Character.isDigit(charB);
if (isDigitA && isDigitB) {
int bias = compareRight(a.substring(indexA), b.substring(indexB));
if (bias != 0) {
return bias;
}
}
if (isDigitA && !isDigitB) {
return 1;
}
if (isDigitB && !isDigitA) {
return -1;
}
int charCompare = Character.compare(charA, charB);
if (charCompare != 0) {
return charCompare;
}
++indexA;
++indexB;
}
}
private static boolean isDigit(char c) {
return Character.isDigit(c) || c == '.' || c == ',';
}
private static char charAt(String s, int i) {
return i >= s.length() ? 0 : s.charAt(i);
}
private static int compareEqual(String a, String b, int nza, int nzb) {
if (nza - nzb != 0) {
return nza - nzb;
}
if (a.length() == b.length()) {
return a.compareTo(b);
}
return a.length() - b.length();
}
}
@@ -0,0 +1,52 @@
package com.moulberry.flashback.screen.select_replay;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.client.Minecraft;
import java.nio.file.Path;
import java.util.Locale;
public interface PendingSelectionEntry {
ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft);
boolean matchesFilter(String filter);
record Folder(Path path, String filename, long modifiedTime, int replayCount) implements PendingSelectionEntry {
public Folder(Path path, long modifiedTime, int replayCount) {
this(path, path.getFileName().toString().toLowerCase(Locale.ROOT), modifiedTime, replayCount);
}
@Override
public ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft) {
return new ReplaySelectionEntry.ReplayFolder(replaySelectionList, minecraft, this.path, this.modifiedTime, this.replayCount);
}
@Override
public boolean matchesFilter(String filter) {
return this.filename.contains(filter);
}
}
record Replay(ReplaySummary summary) implements PendingSelectionEntry {
@Override
public ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft) {
return new ReplaySelectionEntry.ReplayListEntry(replaySelectionList, minecraft, this.summary);
}
@Override
public boolean matchesFilter(String filter) {
if (this.summary.getReplayName().toLowerCase(Locale.ROOT).contains(filter) ||
this.summary.getReplayId().toLowerCase(Locale.ROOT).contains(filter)) {
return true;
}
String worldName = this.summary.getWorldName();
if (worldName != null) {
return worldName.toLowerCase(Locale.ROOT).contains(filter);
} else {
return false;
}
}
}
}
@@ -0,0 +1,342 @@
package com.moulberry.flashback.screen.select_replay;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.logging.LogUtils;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.screen.EditReplayScreen;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.components.WidgetSprites;
import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.FaviconTexture;
import net.minecraft.client.gui.screens.GenericMessageScreen;
import net.minecraft.client.gui.screens.LoadingDotsText;
import net.minecraft.client.gui.screens.ProgressScreen;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.Locale;
public abstract class ReplaySelectionEntry extends ObjectSelectionList.Entry<ReplaySelectionEntry> implements AutoCloseable {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault());
private static final ResourceLocation FOLDER_SPRITE = Flashback.createResourceLocation("folder");
private static final ResourceLocation ERROR_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error_highlighted");
private static final ResourceLocation ERROR_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error");
private static final ResourceLocation WARNING_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning_highlighted");
static private final ResourceLocation WARNING_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning");
private static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join_highlighted");
private static final ResourceLocation JOIN_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join");
private static final Logger LOGGER = LogUtils.getLogger();
@Override
public void close() {
}
public static class LoadFromDeviceHeader extends ReplaySelectionEntry {
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(RenderType::guiTextured, 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 static class LoadingHeader extends ReplaySelectionEntry {
private static final Component LOADING_LABEL = Component.translatable("flashback.select_replay.loading_replays");
private final Minecraft minecraft;
public LoadingHeader(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) {
int p = (this.minecraft.screen.width - this.minecraft.font.width(LOADING_LABEL)) / 2;
int q = j + (m - this.minecraft.font.lineHeight) / 2;
guiGraphics.drawString(this.minecraft.font, LOADING_LABEL, p, q, 0xFFFFFF, false);
String string = LoadingDotsText.get(Util.getMillis());
int r = (this.minecraft.screen.width - this.minecraft.font.width(string)) / 2;
int s = q + this.minecraft.font.lineHeight;
guiGraphics.drawString(this.minecraft.font, string, r, s, -8355712, false);
}
@Override
public Component getNarration() {
return LOADING_LABEL;
}
}
public static class ReplayFolder extends ReplaySelectionEntry implements AutoCloseable {
private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32;
private final Minecraft minecraft;
private final ReplaySelectionList replaySelectionList;
private final Path path;
private final String nameString;
private final Component nameComponent;
private final long modifiedTime;
private final int replayCount;
private long lastClickTime;
public ReplayFolder(ReplaySelectionList replaySelectionList, Minecraft minecraft, Path path, long modifiedTime, int replayCount) {
this.minecraft = minecraft;
this.replaySelectionList = replaySelectionList;
this.path = path;
this.nameString = path.getFileName().toString();
this.nameComponent = Component.literal(this.nameString).withStyle(ChatFormatting.BOLD);
this.modifiedTime = modifiedTime;
this.replayCount = replayCount;
}
@Override
public Component getNarration() {
return Component.translatable("narrator.select", nameComponent);
}
@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.drawString(this.minecraft.font, this.nameComponent, x + ICON_WIDTH + 3, y + 1, -1, false);
int textY = y + this.minecraft.font.lineHeight + 2;
if (this.modifiedTime > 0) {
String time = "Created: " + DATE_FORMAT.format(Instant.ofEpochMilli(this.modifiedTime));
guiGraphics.drawString(this.minecraft.font, time, x + ICON_WIDTH + 3, textY + 1, 0xFF808080, false);
textY += this.minecraft.font.lineHeight;
}
guiGraphics.drawString(this.minecraft.font, "Replays: " + this.replayCount, x + ICON_WIDTH + 3, textY + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blitSprite(RenderType::guiTextured, FOLDER_SPRITE, x, y, ICON_WIDTH, ICON_HEIGHT);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = mouseX - x;
boolean hoveredIcon = q < 32;
ResourceLocation iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT);
}
}
@Override
public boolean mouseClicked(double d, double e, int i) {
this.replaySelectionList.setSelected(this);
if (d - (double) this.replaySelectionList.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
this.minecraft.setScreen(new SelectReplayScreen(this.replaySelectionList.getScreen(), this.path));
return true;
}
this.lastClickTime = Util.getMillis();
return super.mouseClicked(d, e, i);
}
}
public static class ReplayListEntry extends ReplaySelectionEntry implements AutoCloseable {
private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32;
private final Minecraft minecraft;
private final ReplaySelectionList replaySelectionList;
final ReplaySummary summary;
private FaviconTexture icon;
private long lastClickTime;
public ReplayListEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft, ReplaySummary ReplaySummary) {
this.minecraft = minecraft;
this.replaySelectionList = replaySelectionList;
this.summary = ReplaySummary;
this.icon = FaviconTexture.forWorld(this.minecraft.getTextureManager(), ReplaySummary.getReplayId());
this.loadIcon();
}
@Override
public Component getNarration() {
MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(),
Component.translationArg(new Date(this.summary.getLastModified())),
this.summary.getInfo());
return Component.translatable("narrator.select", component);
}
@Override
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 fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastModified();
if (p != -1L) {
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
}
if (StringUtils.isEmpty(title)) {
title = I18n.get("flashback.select_replay.replay") + " " + (index + 1);
}
Component info = this.summary.getInfo();
int titleColour = 0xFFFFFF;
if (!this.summary.canOpen()) {
titleColour = 0xFF5555;
} else if (this.summary.hasWarning()) {
titleColour = 0xFFAA55;
}
int titleEnd = guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, false);
String worldName = this.summary.getWorldName();
if (worldName != null) {
guiGraphics.drawString(this.minecraft.font, "(" + worldName + ")", titleEnd + 4, y + 1, 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, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blit(RenderType::guiTextured, this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = mouseX - x;
boolean hoveredIcon = q < 32;
if (hovered && this.summary.getHoverInfo() != null) {
guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY);
}
ResourceLocation iconOverlay;
if (!this.summary.canOpen()) {
iconOverlay = hoveredIcon ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE;
} else if (this.summary.hasWarning()) {
iconOverlay = hoveredIcon ? WARNING_HIGHLIGHTED_SPRITE : WARNING_SPRITE;
} else {
iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
}
guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT);
}
}
@Override
public boolean mouseClicked(double d, double e, int i) {
if (!this.summary.canOpen()) {
return true;
}
this.replaySelectionList.setSelected(this);
if (d - (double) this.replaySelectionList.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) {
if (this.canOpen()) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
this.openReplay();
}
return true;
}
this.lastClickTime = Util.getMillis();
return super.mouseClicked(d, e, i);
}
public boolean canOpen() {
return this.summary.canOpen();
}
public void openReplay() {
if (this.summary.canOpen()) {
this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("flashback.select_replay.data_read")));
Flashback.openReplayWorld(this.summary.getPath());
// setOpenTime(this.summary.getReplayMetadata().replayIdentifier, System.currentTimeMillis());
// saveOpenTimeCache();
}
}
public void deleteReplay() {
this.minecraft.setScreen(new ConfirmScreen(bl -> {
if (bl) {
this.minecraft.setScreen(new ProgressScreen(true));
this.doDeleteReplay();
}
this.minecraft.setScreen(this.replaySelectionList.getScreen());
}, Component.translatable("flashback.select_replay.delete_question"),
Component.translatable("selectWorld.deleteWarning", this.summary.getReplayName()),
Component.translatable("selectWorld.deleteButton"),
CommonComponents.GUI_CANCEL)
);
}
private void doDeleteReplay() {
String id = this.summary.getReplayId();
try {
Files.delete(this.summary.getPath());
} catch (IOException e) {
SystemToast.onWorldDeleteFailure(this.minecraft, id);
LOGGER.error("Failed to delete replay {}", id, e);
}
this.replaySelectionList.reloadReplayList();
}
public void editReplay() {
Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary));
}
private void loadIcon() {
byte[] iconBytes = this.summary.getIconBytes();
if (iconBytes != null) {
try {
this.icon.upload(NativeImage.read(iconBytes));
return;
} catch (Throwable t) {
LOGGER.error("Invalid icon for replay {}", this.summary.getReplayId(), t);
}
}
this.icon.clear();
}
@Override
public void close() {
if (this.icon != null) {
this.icon.close();
this.icon = null;
}
}
}
}
@@ -0,0 +1,282 @@
/*
* Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4).
*/
package com.moulberry.flashback.screen.select_replay;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.navigation.CommonInputs;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.sounds.SoundEvents;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionEntry> {
private final SelectReplayScreen screen;
private CompletableFuture<List<PendingSelectionEntry>> pendingReplays;
@Nullable
private List<PendingSelectionEntry> currentlyDisplayedReplays;
private String filter;
private ReplaySorting replaySorting;
private boolean sortDescending;
private final ReplaySelectionEntry.LoadingHeader loadingHeader;
private final ReplaySelectionEntry.LoadFromDeviceHeader loadFromDeviceHeader;
public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l,
String filter, ReplaySorting replaySorting, boolean sortDescending,
@Nullable ReplaySelectionList replaySelectionList) {
super(minecraft, i, j, k, l);
this.screen = selectReplayScreen;
this.loadingHeader = new ReplaySelectionEntry.LoadingHeader(minecraft);
this.loadFromDeviceHeader = new ReplaySelectionEntry.LoadFromDeviceHeader(minecraft);
this.filter = filter;
this.replaySorting = replaySorting;
this.sortDescending = sortDescending;
this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays();
this.fillLoadingReplays();
}
@Override
protected void clearEntries() {
this.children().forEach(ReplaySelectionEntry::close);
super.clearEntries();
}
@Nullable
private List<PendingSelectionEntry> pollReplaysIgnoreErrors() {
try {
return this.pendingReplays.getNow(null);
} catch (CancellationException | CompletionException runtimeException) {
return null;
}
}
public void reloadReplayList() {
this.pendingReplays = this.loadReplays();
}
@Override
public boolean keyPressed(int i, int j, int k) {
if (CommonInputs.selected(i)) {
ReplaySelectionEntry.ReplayListEntry replayListEntry = this.getReplayListEntry();
if (replayListEntry != null && replayListEntry.canOpen()) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
replayListEntry.openReplay();
return true;
}
}
return super.keyPressed(i, j, k);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
List<PendingSelectionEntry> list = this.pollReplaysIgnoreErrors();
if (this.currentlyDisplayedReplays != list) {
if (list == null) {
this.fillLoadingReplays();
} else {
list.sort(this.replaySorting.comparator(this.sortDescending));
this.fillReplays(this.filter, list);
}
this.currentlyDisplayedReplays = list;
}
super.renderWidget(guiGraphics, i, j, f);
}
public void updateFilter(String filter, ReplaySorting replaySorting, boolean sortDescending) {
if (this.currentlyDisplayedReplays != null) {
if (this.replaySorting != replaySorting || this.sortDescending != sortDescending) {
this.currentlyDisplayedReplays.sort(replaySorting.comparator(sortDescending));
this.fillReplays(filter, this.currentlyDisplayedReplays);
} else if (!filter.equals(this.filter)) {
this.fillReplays(filter, this.currentlyDisplayedReplays);
}
}
this.filter = filter;
this.replaySorting = replaySorting;
this.sortDescending = sortDescending;
}
private CompletableFuture<List<PendingSelectionEntry>> loadReplays() {
Path replayDir = this.screen.path;
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
return CompletableFuture.completedFuture(new ArrayList<>());
}
ArrayList<CompletableFuture<PendingSelectionEntry>> futures = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayDir)) {
for (Path path : directoryStream) {
if (Files.isDirectory(path)) {
futures.add(CompletableFuture.supplyAsync(() -> {
try {
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis());
int replaysInFolder = 0;
try (DirectoryStream<Path> filesInFolder = Files.newDirectoryStream(path)) {
for (Path fileInFolder : filesInFolder) {
if (fileInFolder.toString().endsWith(".zip")) {
replaysInFolder += 1;
}
}
}
return new PendingSelectionEntry.Folder(path, lastModified, replaysInFolder);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load replay folder", e);
}
return null;
}, Util.backgroundExecutor()));
continue;
}
if (!path.toString().endsWith(".zip")) {
continue;
}
futures.add(CompletableFuture.supplyAsync(() -> {
try {
String fileName = path.getFileName().toString();
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis());
long filesize = basicFileAttributes.size();
byte[] iconBytes = null;
String metadataString = null;
try (FileSystem fs = FileSystems.newFileSystem(path)) {
Path iconPath = fs.getPath("/icon.png");
if (Files.exists(iconPath)) {
iconBytes = Files.readAllBytes(iconPath);
}
Path metadataPath = fs.getPath("/metadata.json");
if (Files.exists(metadataPath)) {
metadataString = Files.readString(metadataPath);
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
if (metadataString == null) {
return null;
}
JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class);
FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson);
if (metadata != null) {
ReplaySummary summary = new ReplaySummary(path, metadata, fileName, lastModified, filesize, iconBytes);
return new PendingSelectionEntry.Replay(summary);
}
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load replay", e);
}
return null;
}, Util.backgroundExecutor()));
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
return Util.sequenceFailFastAndCancel(futures).thenApply(list -> {
list.removeIf(Objects::isNull);
return list;
});
}
private void fillReplays(String filter, List<PendingSelectionEntry> list) {
this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
filter = filter.toLowerCase(Locale.ROOT);
for (PendingSelectionEntry entry : list) {
if (entry.matchesFilter(filter)) {
this.addEntry(entry.createEntry(this, this.minecraft));
}
}
this.notifyListUpdated();
}
private void fillLoadingReplays() {
this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
this.addEntry(this.loadingHeader);
this.notifyListUpdated();
}
private void notifyListUpdated() {
this.setScrollAmount(this.getScrollAmount());
this.screen.triggerImmediateNarration(true);
this.screen.updateButtonStatus(null);
}
@Override
public int getRowWidth() {
return 270;
}
@Override
public void setSelected(@Nullable ReplaySelectionEntry entry) {
if (entry instanceof ReplaySelectionEntry.LoadFromDeviceHeader) {
Flashback.openReplayFromFileBrowser();
return;
}
super.setSelected(entry);
if (entry instanceof ReplaySelectionEntry.ReplayListEntry replayListEntry) {
this.screen.updateButtonStatus(replayListEntry.summary);
} else {
this.screen.updateButtonStatus(null);
}
}
@Nullable
public ReplaySelectionEntry.ReplayListEntry getReplayListEntry() {
if (this.getSelected() instanceof ReplaySelectionEntry.ReplayListEntry replayListEntry) {
return replayListEntry;
} else {
return null;
}
}
public SelectReplayScreen getScreen() {
return this.screen;
}
@Override
public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) {
if (this.children().contains(this.loadingHeader)) {
this.loadingHeader.updateNarration(narrationElementOutput);
return;
}
super.updateWidgetNarration(narrationElementOutput);
}
}
@@ -0,0 +1,76 @@
package com.moulberry.flashback.screen.select_replay;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.network.chat.Component;
import java.util.Comparator;
public enum ReplaySorting {
CREATED_DATE(
Component.literal("Created Date"),
Comparator.comparingLong(ReplaySummary::getLastModified).reversed(),
Comparator.comparingLong(ReplaySummary::getLastModified)
),
REPLAY_NAME(
Component.literal("Replay Name"),
Comparator.comparing(ReplaySummary::getReplayName, NaturalOrderComparator.INSTANCE),
Comparator.comparing(ReplaySummary::getReplayName, NaturalOrderComparator.INSTANCE.reversed())
),
WORLD_NAME(
Component.literal("World Name"),
Comparator.comparing(ReplaySummary::getWorldName, Comparator.nullsLast(NaturalOrderComparator.INSTANCE)),
Comparator.comparing(ReplaySummary::getWorldName, Comparator.nullsLast(NaturalOrderComparator.INSTANCE.reversed()))
),
DURATION(
Component.literal("Duration"),
Comparator.<ReplaySummary>comparingLong(replay -> replay.getReplayMetadata().totalTicks).reversed(),
Comparator.comparingLong(replay -> replay.getReplayMetadata().totalTicks)
),
FILESIZE(
Component.literal("Filesize"),
Comparator.comparingLong(ReplaySummary::getFilesize).reversed(),
Comparator.comparingLong(ReplaySummary::getFilesize)
);
private final Component component;
private final Comparator<ReplaySummary> descendingComparator;
private final Comparator<ReplaySummary> ascendingComparator;
ReplaySorting(Component component, Comparator<ReplaySummary> descendingComparator, Comparator<ReplaySummary> ascendingComparator) {
this.component = component;
this.descendingComparator = descendingComparator.thenComparing(ReplaySummary::getReplayId, NaturalOrderComparator.INSTANCE);
this.ascendingComparator = ascendingComparator.thenComparing(ReplaySummary::getReplayId, NaturalOrderComparator.INSTANCE);
}
public Component component() {
return this.component;
}
public Comparator<PendingSelectionEntry> comparator(boolean descending) {
Comparator<ReplaySummary> replayComparator;
if (descending) {
replayComparator = this.descendingComparator;
} else {
replayComparator = this.ascendingComparator;
}
return (entry1, entry2) -> {
if (entry1 instanceof PendingSelectionEntry.Replay replay1) {
if (entry2 instanceof PendingSelectionEntry.Replay replay2) {
return replayComparator.compare(replay1.summary(), replay2.summary());
} else {
return 1;
}
} else if (entry1 instanceof PendingSelectionEntry.Folder folder1) {
if (entry2 instanceof PendingSelectionEntry.Folder folder2) {
return NaturalOrderComparator.INSTANCE.compare(folder1.filename(), folder2.filename());
} else {
return -1;
}
} else {
return 0;
}
};
}
}
@@ -1,44 +1,77 @@
package com.moulberry.flashback.screen;
package com.moulberry.flashback.screen.select_replay;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.screen.ConfigScreen;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.CycleButton;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
public class SelectReplayScreen extends Screen {
protected final Screen lastScreen;
public final Path path;
private Button selectButton;
private Button editButton;
private Button deleteButton;
protected EditBox searchBox;
private ReplaySelectionList list;
public SelectReplayScreen(Screen screen) {
public SelectReplayScreen(Screen screen, Path path) {
super(Component.translatable("flashback.select_replay"));
this.lastScreen = screen;
this.path = path;
}
@Override
protected void init() {
this.searchBox = new EditBox(this.font, this.width / 2 - 100, 22, 200, 20, this.searchBox, Component.translatable("selectWorld.search"));
this.searchBox.setResponder(string -> this.list.updateFilter(string));
this.searchBox = new EditBox(this.font, this.width / 2 - 128, 22, 126, 20, this.searchBox, Component.translatable("selectWorld.search"));
this.searchBox.setResponder(string -> {
FlashbackConfig config = Flashback.getConfig();
this.list.updateFilter(string, config.replaySorting, config.sortDescending);
});
this.addWidget(this.searchBox);
FlashbackConfig config = Flashback.getConfig();
this.addRenderableWidget(CycleButton.builder(ReplaySorting::component)
.withValues(ReplaySorting.values())
.withInitialValue(config.replaySorting)
.create(this.width / 2 + 2, 22, 125, 20, Component.literal("Sort"), (button, sorting) -> {
FlashbackConfig configuration = Flashback.getConfig();
configuration.replaySorting = sorting;
configuration.delayedSaveToDefaultFolder();
this.list.updateFilter(this.searchBox.getValue(), configuration.replaySorting, configuration.sortDescending);
})
);
this.addRenderableWidget(new SortDirectionButton(this.width / 2 + 131, 22, 20, 20, Component.literal("Sort Direction"),
sortDescending -> {
FlashbackConfig configuration = Flashback.getConfig();
configuration.sortDescending = sortDescending;
configuration.delayedSaveToDefaultFolder();
this.list.updateFilter(this.searchBox.getValue(), configuration.replaySorting, configuration.sortDescending);
}, config.sortDescending));
this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft,
this.width, this.height - 112, 48, 36, this.searchBox.getValue(), this.list));
this.width, this.height - 112, 48, 36, this.searchBox.getValue(), config.replaySorting, config.sortDescending, this.list));
this.selectButton = this.addRenderableWidget(Button.builder(Component.translatable("flashback.select_replay.open"), this::tryOpenReplay)
.bounds(this.width / 2 - 154, this.height - 52, 308, 20).build());
.bounds(this.width / 2 - 151, this.height - 52, 302, 20).build());
this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay)
.bounds(this.width / 2 - 154, this.height - 28, 97, 20).build());
.bounds(this.width / 2 - 151, this.height - 28, 98, 20).build());
this.deleteButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.delete"), this::tryDeleteReplay)
.bounds(this.width / 2 - 49, this.height - 28, 98, 20).build());
this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, button -> this.minecraft.setScreen(this.lastScreen))
.bounds(this.width / 2 + 57, this.height - 28, 97, 20).build());
.bounds(this.width / 2 + 53, this.height - 28, 98, 20).build());
if (this.width/2 > 154 + 128) {
this.addRenderableWidget(Button.builder(Component.literal("Flashback Settings"), btn -> Minecraft.getInstance().setScreen(new ConfigScreen(this)))
@@ -83,26 +116,26 @@ public class SelectReplayScreen extends Screen {
@Override
public void removed() {
if (this.list != null) {
this.list.children().forEach(ReplaySelectionList.Entry::close);
this.list.clearEntries();
}
}
private void tryOpenReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.openReplay();
}
}
private void tryEditReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.editReplay();
}
}
private void tryDeleteReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.deleteReplay();
}
@@ -0,0 +1,50 @@
package com.moulberry.flashback.screen.select_replay;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import java.util.function.Consumer;
public class SortDirectionButton extends Button {
private static final ResourceLocation DOWN_ARROW = ResourceLocation.parse("flashback:down_arrow.png");
private static final ResourceLocation UP_ARROW = ResourceLocation.parse("flashback:up_arrow.png");
public boolean sortDescending;
public SortDirectionButton(int x, int y, int width, int height, Component component, Consumer<Boolean> changed, boolean initialSortDescending) {
super(x, y, width, height, component, button -> {
SortDirectionButton sortButton = (SortDirectionButton) button;
sortButton.sortDescending = !sortButton.sortDescending;
changed.accept(sortButton.sortDescending);
}, DEFAULT_NARRATION);
this.sortDescending = initialSortDescending;
}
@Override
protected void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
super.renderWidget(guiGraphics, i, j, f);
final int size = 16;
int paddingX = (this.getWidth() - size) / 2;
int paddingY = (this.getHeight() - size) / 2;
int x = this.getX() + paddingX;
int y = this.getY() + paddingY;
if (this.sortDescending) {
guiGraphics.blit(RenderType::guiTextured, DOWN_ARROW, x, y, 0f, 0f, size, size, size, size);
} else {
guiGraphics.blit(RenderType::guiTextured, UP_ARROW, x, y, 0f, 0f, size, size, size, size);
}
}
@Override
public void renderString(GuiGraphics guiGraphics, Font font, int i) {
}
}
@@ -0,0 +1,90 @@
package com.moulberry.flashback.state;
import com.moulberry.flashback.keyframe.Keyframe;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class EditorScene {
public String name;
public final List<KeyframeTrack> keyframeTracks = new ArrayList<>();
public int exportStartTicks = -1;
public int exportEndTicks = -1;
private final EditorSceneHistory history = new EditorSceneHistory();
public EditorScene(String name) {
this.name = name;
}
public void setKeyframe(int trackIndex, int tick, Keyframe keyframe) {
if (trackIndex >= this.keyframeTracks.size()) {
return;
}
List<EditorSceneHistoryAction> undo = new ArrayList<>();
List<EditorSceneHistoryAction> redo = new ArrayList<>();
String description;
KeyframeTrack track = this.keyframeTracks.get(trackIndex);
Keyframe old = track.keyframesByTick.get(tick);
if (old != null) {
undo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy()));
description = "Replaced " + track.keyframeType.name() + " keyframe";
} else {
undo.add(new EditorSceneHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick));
description = "Added " + track.keyframeType.name() + " keyframe";
}
redo.add(new EditorSceneHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, keyframe.copy()));
this.push(new EditorSceneHistoryEntry(undo, redo, description));
}
public void push(EditorSceneHistoryEntry entry) {
if (entry.undo().isEmpty() && entry.redo().isEmpty()) {
return;
}
this.history.push(this, entry);
}
public void undo(Consumer<String> descriptionConsumer) {
this.history.undo(this, descriptionConsumer);
}
public void redo(Consumer<String> descriptionConsumer) {
this.history.redo(this, descriptionConsumer);
}
public void setExportTicks(int start, int end, int totalTicks) {
if (this.exportEndTicks < 0) {
this.exportEndTicks = totalTicks;
}
this.exportStartTicks = Math.max(0, Math.min(totalTicks, this.exportStartTicks));
this.exportEndTicks = Math.max(0, Math.min(totalTicks, this.exportEndTicks));
if (start >= 0) {
this.exportStartTicks = start;
if (this.exportEndTicks < start) {
this.exportEndTicks = start;
}
}
if (end >= 0) {
this.exportEndTicks = end;
if (this.exportStartTicks > end) {
this.exportStartTicks = end;
}
}
if (this.exportStartTicks <= 0 && this.exportEndTicks >= totalTicks) {
this.exportStartTicks = -1;
this.exportEndTicks = -1;
}
}
}
@@ -4,12 +4,12 @@ import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class EditorStateHistory {
public class EditorSceneHistory {
private final List<EditorStateHistoryEntry> entries = new ArrayList<>();
private final List<EditorSceneHistoryEntry> entries = new ArrayList<>();
private int position = 0;
public void push(EditorState editorState, EditorStateHistoryEntry entry) {
public void push(EditorScene editorScene, EditorSceneHistoryEntry entry) {
while (this.entries.size() > this.position) {
this.entries.removeLast();
}
@@ -18,35 +18,35 @@ public class EditorStateHistory {
this.position -= 1;
}
for (EditorStateHistoryAction redo : entry.redo()) {
redo.apply(editorState);
for (EditorSceneHistoryAction redo : entry.redo()) {
redo.apply(editorScene);
}
this.entries.add(entry);
this.position += 1;
}
public void undo(EditorState editorState, Consumer<String> descriptionConsumer) {
public void undo(EditorScene editorScene, Consumer<String> descriptionConsumer) {
if (this.position == 0) {
return;
}
this.position -= 1;
EditorStateHistoryEntry entry = this.entries.get(this.position);
for (EditorStateHistoryAction undo : entry.undo()) {
undo.apply(editorState);
EditorSceneHistoryEntry entry = this.entries.get(this.position);
for (EditorSceneHistoryAction undo : entry.undo()) {
undo.apply(editorScene);
}
descriptionConsumer.accept("Undo '" + entry.description() + "'");
}
public void redo(EditorState editorState, Consumer<String> descriptionConsumer) {
public void redo(EditorScene editorScene, Consumer<String> descriptionConsumer) {
if (this.position >= this.entries.size()) {
return;
}
EditorStateHistoryEntry entry = this.entries.get(this.position);
for (EditorStateHistoryAction redo : entry.redo()) {
redo.apply(editorState);
EditorSceneHistoryEntry entry = this.entries.get(this.position);
for (EditorSceneHistoryAction redo : entry.redo()) {
redo.apply(editorScene);
}
descriptionConsumer.accept("Redo '" + entry.description() + "'");
@@ -12,15 +12,15 @@ import com.moulberry.flashback.keyframe.KeyframeType;
import java.lang.reflect.Type;
public interface EditorStateHistoryAction {
public interface EditorSceneHistoryAction {
void apply(EditorState editorState);
void apply(EditorScene editorScene);
record SetKeyframe(KeyframeType<?> type, int trackIndex, int tick, Keyframe keyframe) implements EditorStateHistoryAction {
record SetKeyframe(KeyframeType<?> type, int trackIndex, int tick, Keyframe keyframe) implements EditorSceneHistoryAction {
@Override
public void apply(EditorState editorState) {
if (this.trackIndex < editorState.keyframeTracks.size()) {
KeyframeTrack track = editorState.keyframeTracks.get(this.trackIndex);
public void apply(EditorScene editorScene) {
if (this.trackIndex < editorScene.keyframeTracks.size()) {
KeyframeTrack track = editorScene.keyframeTracks.get(this.trackIndex);
if (track.keyframeType == this.type) {
track.keyframesByTick.put(this.tick, this.keyframe.copy());
}
@@ -51,11 +51,11 @@ public interface EditorStateHistoryAction {
}
}
record RemoveKeyframe(KeyframeType<?> type, int trackIndex, int tick) implements EditorStateHistoryAction {
record RemoveKeyframe(KeyframeType<?> type, int trackIndex, int tick) implements EditorSceneHistoryAction {
@Override
public void apply(EditorState editorState) {
if (this.trackIndex < editorState.keyframeTracks.size()) {
KeyframeTrack track = editorState.keyframeTracks.get(this.trackIndex);
public void apply(EditorScene editorScene) {
if (this.trackIndex < editorScene.keyframeTracks.size()) {
KeyframeTrack track = editorScene.keyframeTracks.get(this.trackIndex);
if (track.keyframeType == this.type) {
track.keyframesByTick.remove(this.tick);
}
@@ -84,11 +84,11 @@ public interface EditorStateHistoryAction {
}
}
record AddTrack(KeyframeType<?> type, int trackIndex) implements EditorStateHistoryAction {
record AddTrack(KeyframeType<?> type, int trackIndex) implements EditorSceneHistoryAction {
@Override
public void apply(EditorState editorState) {
if (this.trackIndex <= editorState.keyframeTracks.size()) {
editorState.keyframeTracks.add(this.trackIndex, new KeyframeTrack(this.type));
public void apply(EditorScene editorScene) {
if (this.trackIndex <= editorScene.keyframeTracks.size()) {
editorScene.keyframeTracks.add(this.trackIndex, new KeyframeTrack(this.type));
}
}
@@ -112,13 +112,13 @@ public interface EditorStateHistoryAction {
}
}
record RemoveTrack(KeyframeType<?> type, int trackIndex) implements EditorStateHistoryAction {
record RemoveTrack(KeyframeType<?> type, int trackIndex) implements EditorSceneHistoryAction {
@Override
public void apply(EditorState editorState) {
if (this.trackIndex < editorState.keyframeTracks.size()) {
KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.trackIndex);
public void apply(EditorScene editorScene) {
if (this.trackIndex < editorScene.keyframeTracks.size()) {
KeyframeTrack keyframeTrack = editorScene.keyframeTracks.get(this.trackIndex);
if (keyframeTrack.keyframeType == type) {
editorState.keyframeTracks.remove(this.trackIndex);
editorScene.keyframeTracks.remove(this.trackIndex);
}
}
}
@@ -143,9 +143,9 @@ public interface EditorStateHistoryAction {
}
}
class TypeAdapter implements JsonSerializer<EditorStateHistoryAction>, JsonDeserializer<EditorStateHistoryAction> {
class TypeAdapter implements JsonSerializer<EditorSceneHistoryAction>, JsonDeserializer<EditorSceneHistoryAction> {
@Override
public EditorStateHistoryAction deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
public EditorSceneHistoryAction deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("action_type").getAsString();
return switch (type) {
@@ -158,7 +158,7 @@ public interface EditorStateHistoryAction {
}
@Override
public JsonElement serialize(EditorStateHistoryAction src, Type typeOfSrc, JsonSerializationContext context) {
public JsonElement serialize(EditorSceneHistoryAction src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject;
switch (src) {
case SetKeyframe setKeyframe -> {
@@ -0,0 +1,6 @@
package com.moulberry.flashback.state;
import java.util.List;
public record EditorSceneHistoryEntry(List<EditorSceneHistoryAction> undo, List<EditorSceneHistoryAction> redo, String description) {
}
@@ -35,14 +35,13 @@ public class EditorState {
transient boolean dirty = false;
public transient int modCount = ThreadLocalRandom.current().nextInt();
public final List<KeyframeTrack> keyframeTracks = new ArrayList<>();
public final ReplayVisuals replayVisuals = new ReplayVisuals();
private final EditorStateHistory history = new EditorStateHistory();
public final List<EditorScene> scenes;
public int sceneIndex = 0;
public double zoomMin = 0.0;
public double zoomMax = 1.0;
public int exportStartTicks = -1;
public int exportEndTicks = -1;
public UUID audioSourceEntity = null;
public Set<UUID> hideDuringExport = new HashSet<>();
@@ -50,105 +49,16 @@ public class EditorState {
public Map<UUID, GameProfile> skinOverride = new HashMap<>();
public Map<UUID, String> nameOverride = new HashMap<>();
public transient int recordingCameraMovementTrack = -1;
public transient int recordingCameraMovementMinTick = -1;
public transient int recordingCameraMovementMaxTick = -1;
public transient Int2ObjectMap<CameraKeyframe> recordingCameraKeyframes = new Int2ObjectOpenHashMap<>();
public void recordCameraMovement() {
if (recordingCameraMovementTrack < 0) {
return;
}
if (!ReplayUI.recordCameraMovement) {
finishRecordingCameraMovement();
return;
}
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
if (replayServer.replayPaused) {
finishRecordingCameraMovement();
return;
}
Entity cameraEntity = Minecraft.getInstance().getCameraEntity();
if (cameraEntity == null) {
return;
}
int tick = replayServer.getReplayTick();
if (recordingCameraMovementMaxTick >= 0) {
int nextCapture = recordingCameraMovementMaxTick + 4;
if (tick >= nextCapture) {
tick = nextCapture;
} else {
return;
}
}
recordingCameraKeyframes.put(tick, new CameraKeyframe(Minecraft.getInstance().getCameraEntity()));
if (recordingCameraMovementMinTick < 0) {
recordingCameraMovementMinTick = tick;
}
recordingCameraMovementMinTick = Math.min(recordingCameraMovementMinTick, tick);
recordingCameraMovementMaxTick = Math.max(recordingCameraMovementMaxTick, tick);
}
public EditorState() {
this.scenes = new ArrayList<>();
this.scenes.add(new EditorScene("Scene 1"));
}
public void finishRecordingCameraMovement() {
int trackIndex = recordingCameraMovementTrack;
if (trackIndex >= 0 && trackIndex < this.keyframeTracks.size()) {
List<EditorStateHistoryAction> undo = new ArrayList<>();
List<EditorStateHistoryAction> redo = new ArrayList<>();
KeyframeTrack track = this.keyframeTracks.get(trackIndex);
for (Int2ObjectMap.Entry<CameraKeyframe> entry : recordingCameraKeyframes.int2ObjectEntrySet()) {
int tick = entry.getIntKey();
Keyframe old = track.keyframesByTick.get(entry.getIntKey());
if (old != null) {
undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy()));
} else {
undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick));
}
redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, entry.getValue()));
}
this.push(new EditorStateHistoryEntry(undo, redo, "Record movement as keyframes"));
public EditorScene currentScene() {
if (this.scenes.isEmpty()) {
this.scenes.add(new EditorScene("Scene 1"));
}
recordingCameraMovementTrack = -1;
recordingCameraMovementMinTick = -1;
recordingCameraMovementMaxTick = -1;
recordingCameraKeyframes.clear();
}
public void setKeyframe(int trackIndex, int tick, Keyframe keyframe) {
if (trackIndex >= this.keyframeTracks.size()) {
return;
}
List<EditorStateHistoryAction> undo = new ArrayList<>();
List<EditorStateHistoryAction> redo = new ArrayList<>();
String description;
KeyframeTrack track = this.keyframeTracks.get(trackIndex);
Keyframe old = track.keyframesByTick.get(tick);
if (old != null) {
undo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, old.copy()));
description = "Replaced " + track.keyframeType.name() + " keyframe";
} else {
undo.add(new EditorStateHistoryAction.RemoveKeyframe(track.keyframeType, trackIndex, tick));
description = "Added " + track.keyframeType.name() + " keyframe";
}
redo.add(new EditorStateHistoryAction.SetKeyframe(track.keyframeType, trackIndex, tick, keyframe.copy()));
this.push(new EditorStateHistoryEntry(undo, redo, description));
return this.scenes.get(this.sceneIndex);
}
@Nullable
@@ -173,54 +83,6 @@ public class EditorState {
return dummyCamera;
}
public void push(EditorStateHistoryEntry entry) {
if (entry.undo().isEmpty() && entry.redo().isEmpty()) {
return;
}
this.history.push(this, entry);
this.markDirty();
}
public void undo(Consumer<String> descriptionConsumer) {
this.history.undo(this, descriptionConsumer);
this.markDirty();
}
public void redo(Consumer<String> descriptionConsumer) {
this.history.redo(this, descriptionConsumer);
this.markDirty();
}
public void setExportTicks(int start, int end, int totalTicks) {
if (this.exportEndTicks < 0) {
this.exportEndTicks = totalTicks;
}
this.exportStartTicks = Math.max(0, Math.min(totalTicks, this.exportStartTicks));
this.exportEndTicks = Math.max(0, Math.min(totalTicks, this.exportEndTicks));
if (start >= 0) {
this.exportStartTicks = start;
if (this.exportEndTicks < start) {
this.exportEndTicks = start;
}
}
if (end >= 0) {
this.exportEndTicks = end;
if (this.exportStartTicks > end) {
this.exportStartTicks = end;
}
}
if (this.exportStartTicks <= 0 && this.exportEndTicks >= totalTicks) {
this.exportStartTicks = -1;
this.exportEndTicks = -1;
}
this.dirty = true;
}
public void markDirty() {
this.dirty = true;
this.modCount += 1;
@@ -264,7 +126,7 @@ public class EditorState {
public void applyKeyframes(KeyframeHandler keyframeHandler, float tick) {
Set<KeyframeType<?>> applied = new HashSet<>();
for (KeyframeTrack keyframeTrack : this.keyframeTracks) {
for (KeyframeTrack keyframeTrack : this.currentScene().keyframeTracks) {
// Ignore lines that are disabled
if (!keyframeTrack.enabled) {
continue;
@@ -1,6 +0,0 @@
package com.moulberry.flashback.state;
import java.util.List;
public record EditorStateHistoryEntry(List<EditorStateHistoryAction> undo, List<EditorStateHistoryAction> redo, String description) {
}
@@ -10,6 +10,7 @@ import com.moulberry.flashback.keyframe.impl.TimelapseKeyframe;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.keyframe.interpolation.SidedInterpolationType;
import com.moulberry.flashback.keyframe.types.TimelapseKeyframeType;
import imgui.type.ImString;
import java.util.Map;
import java.util.TreeMap;
@@ -19,6 +20,12 @@ public class KeyframeTrack {
public final KeyframeType<?> keyframeType;
public TreeMap<Integer, Keyframe> keyframesByTick = new TreeMap<>();
public boolean enabled = true;
public String customName = null;
public int customColour = 0;
public transient ImString nameEditField = null;
public transient boolean forceFocusTrack = false;
public transient float animatedOffsetInUi = 0.0f;
public KeyframeTrack(KeyframeType<?> keyframeType) {
this.keyframeType = keyframeType;
@@ -20,6 +20,7 @@ import com.moulberry.flashback.keyframe.types.CameraKeyframeType;
import com.moulberry.flashback.keyframe.types.CameraOrbitKeyframeType;
import com.moulberry.flashback.keyframe.types.FOVKeyframeType;
import com.moulberry.flashback.playback.ReplayServer;
import com.moulberry.flashback.state.EditorScene;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.state.KeyframeTrack;
@@ -58,7 +59,7 @@ public class CameraPath {
int replayTick = TimelineWindow.getCursorTick();
if (lastEditorStateModCount != state.modCount || lastCursorTick != replayTick) {
CameraPathArgs cameraPathArgs = createCameraPathArgs(state, replayTick, SUPPORTED_CAMERA_KEYFRAMES);
CameraPathArgs cameraPathArgs = createCameraPathArgs(state.currentScene(), replayTick, SUPPORTED_CAMERA_KEYFRAMES);
if (lastEditorStateModCount != state.modCount || !cameraPathArgs.equals(lastCameraPathArgs)) {
lastCameraPathArgs = cameraPathArgs;
@@ -134,12 +135,12 @@ public class CameraPath {
private record CameraPathArgs(int lastLastCameraTick, int lastCameraTick, int nextCameraTick, int nextNextCameraTick) {}
private static CameraPathArgs createCameraPathArgs(EditorState state, int replayTick, Set<KeyframeType<?>> supportedKeyframes) {
private static CameraPathArgs createCameraPathArgs(EditorScene scene, int replayTick, Set<KeyframeType<?>> supportedKeyframes) {
int lastCameraTick = -1;
int nextCameraTick = -1;
for (int trackIndex = 0; trackIndex < state.keyframeTracks.size(); trackIndex++) {
KeyframeTrack keyframeTrack = state.keyframeTracks.get(trackIndex);
for (int trackIndex = 0; trackIndex < scene.keyframeTracks.size(); trackIndex++) {
KeyframeTrack keyframeTrack = scene.keyframeTracks.get(trackIndex);
if (keyframeTrack.enabled && supportedKeyframes.contains(keyframeTrack.keyframeType) && !keyframeTrack.keyframesByTick.isEmpty()) {
var lastEntry = keyframeTrack.keyframesByTick.floorEntry(replayTick);
var nextEntry = keyframeTrack.keyframesByTick.ceilingEntry(replayTick + 1);
@@ -160,8 +161,8 @@ public class CameraPath {
int lastLastCameraTick = -1;
int nextNextCameraTick = -1;
for (int trackIndex = 0; trackIndex < state.keyframeTracks.size(); trackIndex++) {
KeyframeTrack keyframeTrack = state.keyframeTracks.get(trackIndex);
for (int trackIndex = 0; trackIndex < scene.keyframeTracks.size(); trackIndex++) {
KeyframeTrack keyframeTrack = scene.keyframeTracks.get(trackIndex);
if (keyframeTrack.enabled && supportedKeyframes.contains(keyframeTrack.keyframeType) && !keyframeTrack.keyframesByTick.isEmpty()) {
var lastLastEntry = lastCameraTick == -1 ? null : keyframeTrack.keyframesByTick.floorEntry(lastCameraTick - 1);
var nextNextEntry = nextCameraTick == -1 ? null : keyframeTrack.keyframesByTick.ceilingEntry(nextCameraTick + 1);
@@ -35,6 +35,8 @@ public class CameraRotation {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null && visuals.overrideCameraShake && (Flashback.isExporting() || !replayServer.replayPaused)) {
float tick = Flashback.isExporting() ? (float) Flashback.EXPORT_JOB.getCurrentTickDouble() : replayServer.getPartialReplayTick();
float speedFactor = 20.0f / replayServer.getDesiredTickRate(false);
if (tick < lastShakeReplayTick) {
lastShakeReplayTick = tick;
shakeTimeY = 0.0f;
@@ -43,8 +45,8 @@ public class CameraRotation {
float yFrequency = visuals.cameraShakeYFrequency;
float xFrequency = visuals.cameraShakeXFrequency;
shakeTimeY += (tick - lastShakeReplayTick) * yFrequency * 2.0f;
shakeTimeX += (tick - lastShakeReplayTick) * xFrequency * 2.0f;
shakeTimeY += (tick - lastShakeReplayTick) * speedFactor * yFrequency * 2.0f;
shakeTimeX += (tick - lastShakeReplayTick) * speedFactor * xFrequency * 2.0f;
lastShakeReplayTick = tick;
}
@@ -6,8 +6,6 @@ import net.minecraft.client.renderer.ShaderDefines;
import net.minecraft.client.renderer.ShaderProgram;
import net.minecraft.resources.ResourceLocation;
import java.io.IOException;
public class ShaderManager {
public static final ShaderManager INSTANCE = new ShaderManager();
Binary file not shown.

After

Width:  |  Height:  |  Size: 156 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 B