This commit is contained in:
Moulberry committed 2024-09-07 02:20:58 +08:00
1 parent d589647c36
commit 7f1d199704
20 files changed
+461 -94

No files matched your search

@@ -13,6 +13,7 @@ public enum VideoContainer implements ComboOption {
MKV("MKV", "mkv"),
AVI("AVI", "avi"),
MOV("MOV", "mov"),
PNG_SEQUENCE("PNG Sequence", "png"),
WEBP("WebP", "webp"),
WEBM("WebM", "webm"),
GIF("GIF", "gif");
@@ -40,7 +41,7 @@ public enum VideoContainer implements ComboOption {
public static VideoContainer[] findSupportedContainers(boolean transparency) {
List<VideoContainer> containers = new ArrayList<>();
for (VideoContainer videoContainer : VideoContainer.values()) {
if (videoContainer.getSupportedVideoCodecs(transparency).length != 0) {
if (videoContainer == VideoContainer.PNG_SEQUENCE || videoContainer.getSupportedVideoCodecs(transparency).length != 0) {
containers.add(videoContainer);
}
}
@@ -52,21 +53,24 @@ public enum VideoContainer implements ComboOption {
if (codecs == null) {
List<VideoCodec> supportedCodecs = new ArrayList<>();
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (VideoCodec codec : VideoCodec.values()) {
if (codec == VideoCodec.AV1 && this != VideoContainer.MP4) {
continue;
}
if (codec.getEncoders().length == 0) {
continue;
}
if (transparency && !codec.supportsTransparency()) {
continue;
}
int ret = avformat.avformat_query_codec(outputFormat, codec.codecId(), avcodec.FF_COMPLIANCE_NORMAL);
if (ret == 1) {
supportedCodecs.add(codec);
if (this != VideoContainer.PNG_SEQUENCE) {
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (VideoCodec codec : VideoCodec.values()) {
if (codec == VideoCodec.AV1 && this != VideoContainer.MP4) {
continue;
}
if (codec.getEncoders().length == 0) {
continue;
}
if (transparency && !codec.supportsTransparency()) {
continue;
}
int ret = avformat.avformat_query_codec(outputFormat, codec.codecId(), avcodec.FF_COMPLIANCE_NORMAL);
if (ret == 1) {
supportedCodecs.add(codec);
}
}
}
}
@@ -84,19 +88,20 @@ public enum VideoContainer implements ComboOption {
public AudioCodec[] getSupportedAudioCodecs() {
if (this.supportedAudioCodecs == null) {
List<AudioCodec> supportedCodecs = new ArrayList<>();
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (AudioCodec codec : AudioCodec.values()) {
if (codec.getEncoders().length == 0) {
continue;
}
if (this != VideoContainer.PNG_SEQUENCE) {
try (AVOutputFormat outputFormat = avformat.av_guess_format(this.extension, "test."+this.extension, null)) {
for (AudioCodec codec : AudioCodec.values()) {
if (codec.getEncoders().length == 0) {
continue;
}
int ret = avformat.avformat_query_codec(outputFormat, codec.codecId(), avcodec.FF_COMPLIANCE_NORMAL);
if (ret == 1) {
supportedCodecs.add(codec);
int ret = avformat.avformat_query_codec(outputFormat, codec.codecId(), avcodec.FF_COMPLIANCE_NORMAL);
if (ret == 1) {
supportedCodecs.add(codec);
}
}
}
}
this.supportedAudioCodecs = supportedCodecs.toArray(new AudioCodec[0]);
}
return this.supportedAudioCodecs;
@@ -692,23 +692,24 @@ public class ReplayUI {
if (Minecraft.getInstance().screen != null) {
ImGui.captureMouseFromApp(false);
}
boolean isMovingCamera = isMovingCamera();
if (isFrameFocused || isMovingCamera) {
LocalPlayer player = Minecraft.getInstance().player;
if (player != null) {
int wheelY = (int) Math.signum(ImGui.getIO().getMouseWheel());
if (wheelY != 0) {
final float defaultFlyingSpeed = 0.05f;
float flyingSpeed = Mth.clamp(player.getAbilities().getFlyingSpeed() + (float)wheelY * defaultFlyingSpeed / 10f,
} else {
boolean isMovingCamera = isMovingCamera();
if (isFrameFocused || isMovingCamera) {
LocalPlayer player = Minecraft.getInstance().player;
if (player != null) {
int wheelY = (int) Math.signum(ImGui.getIO().getMouseWheel());
if (wheelY != 0) {
final float defaultFlyingSpeed = 0.05f;
float flyingSpeed = Mth.clamp(player.getAbilities().getFlyingSpeed() + (float)wheelY * defaultFlyingSpeed / 10f,
defaultFlyingSpeed / 10f, defaultFlyingSpeed * 10.0f);
setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed));
player.getAbilities().setFlyingSpeed(flyingSpeed);
setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed));
player.getAbilities().setFlyingSpeed(flyingSpeed);
}
}
}
}
if (!isMovingCamera && ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) {
fireCancelNavInput |= handleBasicInputs();
if (!isMovingCamera && ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) {
fireCancelNavInput |= handleBasicInputs();
}
}
}
} else {
@@ -29,6 +29,7 @@ import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
public class StartExportWindow {
@@ -284,6 +285,10 @@ public class StartExportWindow {
container = ImGuiHelper.enumCombo("Container", container, containers);
if (container == VideoContainer.PNG_SEQUENCE) {
return;
}
VideoCodec[] codecs = container.getSupportedVideoCodecs(transparentBackground);
if (codecs.length == 0) {
@@ -334,8 +339,6 @@ public class StartExportWindow {
numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
}
String encoder = videoCodec.getEncoders()[selectedVideoEncoder[0]];
if (defaultExportPath == null || !Files.exists(defaultExportPath)) {
defaultExportPath = FabricLoader.getInstance().getGameDir();
}
@@ -355,9 +358,7 @@ public class StartExportWindow {
defaultName = "output." + container.extension();
}
String defaultExportPathString = defaultExportPath.toString();
return AsyncFileDialogs.saveFileDialog(defaultExportPathString, defaultName,
container.extension(), container.extension()).thenApply(pathStr -> {
Function<String, ExportSettings> callback = pathStr -> {
if (pathStr != null) {
int start = Math.max(0, startEndTick[0]);
int end = Math.max(start, startEndTick[1]);
@@ -380,19 +381,43 @@ public class StartExportWindow {
}
boolean transparent = transparentBackground && !editorState.replayVisuals.renderSky;
String encoder = videoCodec.getEncoders()[selectedVideoEncoder[0]];
VideoCodec useVideoCodec = videoCodec;
AudioCodec useAudioCodec = audioCodec;
boolean shouldRecordAudio = recordAudio;
if (container == VideoContainer.PNG_SEQUENCE) {
useVideoCodec = null;
encoder = null;
shouldRecordAudio = false;
}
if (!shouldRecordAudio) {
useAudioCodec = null;
}
Path path = Path.of(pathStr);
defaultExportPath = path.getParent();
return new ExportSettings(name, editorState.copy(),
player.position(), player.getYRot(), player.getXRot(),
resolution[0], resolution[1], start, end,
Math.max(1, framerate[0]), resetRng, container, videoCodec, encoder, numBitrate, transparent, ssaa,
recordAudio, stereoAudio, audioCodec,
Math.max(1, framerate[0]), resetRng, container, useVideoCodec, encoder, numBitrate, transparent, ssaa,
shouldRecordAudio, stereoAudio, useAudioCodec,
path);
}
return null;
});
};
String defaultExportPathString = defaultExportPath.toString();
if (container == VideoContainer.PNG_SEQUENCE) {
return AsyncFileDialogs.openFolderDialog(defaultExportPathString).thenApply(callback);
} else {
return AsyncFileDialogs.saveFileDialog(defaultExportPathString, defaultName,
container.extension(), container.extension()).thenApply(callback);
}
}
private static int stringToBitrate(String string) {
@@ -282,10 +282,9 @@ public class TimelineWindow {
// render markers
{
for (int tick = minTicks; tick <= minTicks + availableTicks; tick++) {
for (int tick = minTicks-10; tick <= minTicks + availableTicks + 10; tick++) {
Map.Entry<Integer, ReplayMarker> markerEntry = metadata.replayMarkers.ceilingEntry(tick);
if (markerEntry == null || markerEntry.getKey() > minTicks + availableTicks) {
if (markerEntry == null || markerEntry.getKey() > minTicks + availableTicks + 10) {
break;
}
@@ -1270,9 +1269,9 @@ public class TimelineWindow {
}
}
for (int tick = minTicks; tick <= minTicks + availableTicks; tick++) {
for (int tick = minTicks - 10; tick <= minTicks + availableTicks + 10; tick++) {
var entry = keyframeTimes.ceilingEntry(tick);
if (entry == null || entry.getKey() > minTicks + availableTicks) {
if (entry == null || entry.getKey() > minTicks + availableTicks + 10) {
break;
}
tick = entry.getKey();
@@ -20,6 +20,7 @@ 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;
@@ -128,6 +129,28 @@ public class VisualsWindow {
}
}
if (ImGui.checkbox("Override Fog Colour", visuals.overrideFogColour)) {
visuals.overrideFogColour = !visuals.overrideFogColour;
if (visuals.overrideFogColour) {
visuals.fogColour[0] = FogRenderer.fogRed;
visuals.fogColour[1] = FogRenderer.fogGreen;
visuals.fogColour[2] = FogRenderer.fogBlue;
}
editorState.markDirty();
}
if (visuals.overrideFogColour) {
if (ImGui.colorButton("Fog Colour", visuals.fogColour)) {
ImGui.openPopup("##EditFogColour");
}
ImGui.sameLine();
ImGui.text("Fog Colour");
if (ImGui.beginPopup("##EditFogColour")) {
ImGui.colorPicker3("Fog Colour", visuals.fogColour);
ImGui.endPopup();
}
}
// FOV
if (ImGui.checkbox("Override FOV", visuals.overrideFov)) {
visuals.overrideFov = !visuals.overrideFov;
@@ -3,25 +3,19 @@ package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.mixin.record.MixinFFmpegFrameRecorder;
import net.fabricmc.loader.api.FabricLoader;
import org.bytedeco.ffmpeg.avutil.AVComponentDescriptor;
import org.bytedeco.ffmpeg.avutil.AVFrame;
import org.bytedeco.ffmpeg.avutil.AVPixFmtDescriptor;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.ffmpeg.global.swscale;
import org.bytedeco.ffmpeg.swscale.SwsContext;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.PointerPointer;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.FFmpegLogCallback;
import org.bytedeco.javacv.Frame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.opengl.GL11;
import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
@@ -34,10 +28,9 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import static org.bytedeco.ffmpeg.global.avutil.*;
import static org.bytedeco.ffmpeg.global.swscale.SWS_BILINEAR;
import static org.bytedeco.ffmpeg.global.swscale.sws_freeContext;
public class AsyncVideoEncoder implements AutoCloseable {
public class AsyncFFmpegVideoWriter implements AutoCloseable, VideoWriter {
@Nullable
private final ArrayBlockingQueue<ImageFrame> rescaleQueue;
@@ -52,8 +45,6 @@ public class AsyncVideoEncoder implements AutoCloseable {
private final AtomicReference<Throwable> threadedError = new AtomicReference<>(null);
public static final int SRC_PIXEL_FORMAT = avutil.AV_PIX_FMT_RGBA;
private record ImageFrame(long pointer, int size, int width, int height, int channels, int imageDepth, int stride, int pixelFormat,
@Nullable FloatBuffer audioBuffer) implements AutoCloseable {
public void close() {
@@ -61,7 +52,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
}
}
public AsyncVideoEncoder(ExportSettings settings, String filename) {
public AsyncFFmpegVideoWriter(ExportSettings settings, String filename) {
int width = settings.resolutionX();
int height = settings.resolutionY();
@@ -96,7 +87,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
int dstPixelFormat = PixelFormatHelper.getBestPixelFormat(settings.encoder(), wantTransparency);
Flashback.LOGGER.info("Encoding video with pixel format {}", PixelFormatHelper.pixelFormatToString(dstPixelFormat));
boolean needsRescale = SRC_PIXEL_FORMAT != dstPixelFormat;
boolean needsRescale = ExportJob.SRC_PIXEL_FORMAT != dstPixelFormat;
int audioChannels = 0;
if (settings.recordAudio()) {
@@ -338,7 +329,7 @@ public class AsyncVideoEncoder implements AutoCloseable {
while (true) {
try {
ImageFrame imageFrame = new ImageFrame(src.pixels, (int) src.size, src.getWidth(), src.getHeight(),
4, Frame.DEPTH_INT, src.getWidth(), SRC_PIXEL_FORMAT, audioBuffer);
4, Frame.DEPTH_INT, src.getWidth(), ExportJob.SRC_PIXEL_FORMAT, audioBuffer);
if (this.rescaleQueue != null) {
this.rescaleQueue.put(imageFrame);
} else {
@@ -8,7 +8,9 @@ import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import com.moulberry.flashback.FixedDeltaTracker;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.Utils;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.keyframe.handler.KeyframeHandler;
import com.moulberry.flashback.keyframe.handler.MinecraftKeyframeHandler;
@@ -28,6 +30,7 @@ import net.minecraft.client.renderer.FogRenderer;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.Vec3;
import org.bytedeco.ffmpeg.global.avutil;
import org.joml.Matrix4f;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.openal.SOFTLoopback;
@@ -74,6 +77,8 @@ public class ExportJob {
private final AtomicBoolean finishedServerTick = new AtomicBoolean(false);
public static final int SRC_PIXEL_FORMAT = avutil.AV_PIX_FMT_RGBA;
public ExportJob(ExportSettings settings) {
this.settings = settings;
this.particleRandom = this.settings.resetRng() ? new Random(2000) : null;
@@ -135,12 +140,14 @@ public class ExportJob {
RenderTarget mainTarget = Minecraft.getInstance().mainRenderTarget;
infoRenderTarget = new TextureTarget(mainTarget.width, mainTarget.height, false, Minecraft.ON_OSX);
try (AsyncVideoEncoder encoder = new AsyncVideoEncoder(this.settings, tempFileName);
SaveableFramebufferQueue downloader = new SaveableFramebufferQueue(this.settings.resolutionX(), this.settings.resolutionY())) {
try (VideoWriter encoder = createVideoWriter(this.settings, tempFileName);
SaveableFramebufferQueue downloader = new SaveableFramebufferQueue(this.settings.resolutionX(), this.settings.resolutionY())) {
doExport(encoder, downloader, infoRenderTarget);
}
Files.move(exportTempFile, this.settings.output(), StandardCopyOption.REPLACE_EXISTING);
if (this.settings.container() != VideoContainer.PNG_SEQUENCE) {
Files.move(exportTempFile, this.settings.output(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
@@ -170,7 +177,15 @@ public class ExportJob {
}
}
private void doExport(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, TextureTarget infoRenderTarget) {
private static VideoWriter createVideoWriter(ExportSettings settings, String tempFileName) {
if (settings.container() == VideoContainer.PNG_SEQUENCE) {
return new PNGSequenceVideoWriter(settings);
} else {
return new AsyncFFmpegVideoWriter(settings, tempFileName);
}
}
private void doExport(VideoWriter videoWriter, SaveableFramebufferQueue downloader, TextureTarget infoRenderTarget) {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
return;
@@ -301,7 +316,7 @@ public class ExportJob {
cancel = finishFrame(renderTarget, infoRenderTarget, tickIndex, ticks.size());
this.shouldChangeFramebufferSize = true;
submitDownloadedFrames(encoder, downloader, false);
submitDownloadedFrames(videoWriter, downloader, false);
saveable.audioBuffer = audioBuffer;
downloader.startDownload(renderTarget, saveable, this.settings.ssaa());
@@ -312,8 +327,8 @@ public class ExportJob {
}
}
submitDownloadedFrames(encoder, downloader, true);
encoder.finish();
submitDownloadedFrames(videoWriter, downloader, true);
videoWriter.finish();
}
private void updateRandoms(Random random, Random mathRandom) {
@@ -432,7 +447,7 @@ public class ExportJob {
}
}
private void submitDownloadedFrames(AsyncVideoEncoder encoder, SaveableFramebufferQueue downloader, boolean drain) {
private void submitDownloadedFrames(VideoWriter videoWriter, SaveableFramebufferQueue downloader, boolean drain) {
SaveableFramebufferQueue.DownloadedFrame frame;
while (true) {
long start = System.nanoTime();
@@ -444,7 +459,7 @@ public class ExportJob {
}
start = System.nanoTime();
encoder.encode(frame.image(), frame.audioBuffer());
videoWriter.encode(frame.image(), frame.audioBuffer());
encodeTimeNanos += System.nanoTime() - start;
}
}
@@ -0,0 +1,158 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
public class PNGSequenceVideoWriter implements VideoWriter {
private final ExportSettings settings;
private int sequenceNumber = 0;
private final AtomicBoolean finishEncodeThread = new AtomicBoolean(false);
private final AtomicBoolean finishedWriting = new AtomicBoolean(false);
private final AtomicReference<Throwable> threadedError = new AtomicReference<>(null);
private final ArrayBlockingQueue<NativeImage> encodeQueue;
public PNGSequenceVideoWriter(ExportSettings settings) {
this.settings = settings;
this.encodeQueue = new ArrayBlockingQueue<>(32);
createEncodeThread().start();
}
private Thread createEncodeThread() {
Thread encodeThread = new Thread(() -> {
while (true) {
NativeImage src;
try {
src = this.encodeQueue.poll(10, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw SneakyThrow.sneakyThrow(e);
}
try {
if (src == null) {
if (this.finishEncodeThread.get()) {
this.finishedWriting.set(true);
return;
} else {
continue;
}
}
// Ensure pixels are fully opaque if transparency is disabled
if (!this.settings.transparent() && src.format().hasAlpha()) {
int alpha = 255 << src.format().alphaOffset();
for (int y = 0; y < src.getHeight(); y++) {
for (int x = 0; x < src.getWidth(); x++) {
src.setPixelRGBA(x, y, src.getPixelRGBA(x, y) | alpha);
}
}
}
this.sequenceNumber += 1;
String filename = String.format("%04d.png", this.sequenceNumber);
src.writeToFile(this.settings.output().resolve(filename));
} catch (Throwable t) {
this.threadedError.set(t);
this.finishEncodeThread.set(true);
this.finishedWriting.set(true);
return;
} finally {
if (src != null) {
src.close();
}
}
}
});
encodeThread.setName("Video Encode Thread");
return encodeThread;
}
private void checkEncodeError(@Nullable AutoCloseable closeable) {
Throwable t = this.threadedError.get();
if (t != null) {
this.finishEncodeThread.set(true);
this.finishedWriting.set(true);
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
Flashback.LOGGER.error("Error while trying to close passed AutoClosable", e);
}
}
SneakyThrow.sneakyThrow(t);
}
}
public void encode(NativeImage src, @Nullable FloatBuffer audioBuffer) {
if (audioBuffer != null) {
throw new RuntimeException("PNG Sequence does not support encoding audio");
}
checkEncodeError(src);
if (this.finishEncodeThread.get() || this.finishedWriting.get()) {
src.close();
throw new IllegalStateException("Cannot encode after finish()");
}
while (true) {
try {
this.encodeQueue.put(src);
break;
} catch (InterruptedException ignored) {}
checkEncodeError(src);
}
}
public void finish() {
checkEncodeError(null);
while (!this.encodeQueue.isEmpty()) {
checkEncodeError(null);
LockSupport.parkNanos("waiting for encode queue to empty", 100000L);
}
this.finishEncodeThread.set(true);
while (!this.finishedWriting.get()) {
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
}
checkEncodeError(null);
}
@Override
public void close() {
for (NativeImage src : this.encodeQueue) {
src.close();
}
this.finishEncodeThread.set(true);
while (!this.finishedWriting.get()) {
LockSupport.parkNanos("waiting for encoder thread to finish", 100000L);
}
}
}
@@ -69,13 +69,13 @@ public class PixelFormatHelper {
supportedFormats.add(avutil.AV_PIX_FMT_NONE);
if (transparent) {
int format = avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), AsyncVideoEncoder.SRC_PIXEL_FORMAT, 1, new int[1]);
int format = avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), ExportJob.SRC_PIXEL_FORMAT, 1, new int[1]);
if (format != avutil.AV_PIX_FMT_NONE) {
return format;
}
}
return avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), AsyncVideoEncoder.SRC_PIXEL_FORMAT, 0, new int[1]);
return avcodec.avcodec_find_best_pix_fmt_of_list(supportedFormats.toIntArray(), ExportJob.SRC_PIXEL_FORMAT, 0, new int[1]);
}
}
@@ -0,0 +1,16 @@
package com.moulberry.flashback.exporting;
import com.mojang.blaze3d.platform.NativeImage;
import org.jetbrains.annotations.Nullable;
import java.nio.FloatBuffer;
public interface VideoWriter extends AutoCloseable {
void encode(NativeImage src, @Nullable FloatBuffer audioBuffer);
void finish();
default void close() {
}
}
@@ -18,6 +18,7 @@ import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateManager;
import com.moulberry.flashback.editor.ui.ReplayUI;
import com.moulberry.flashback.exporting.PerfectFrames;
import com.moulberry.flashback.visuals.ReplayVisuals;
import com.moulberry.flashback.visuals.ShaderManager;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.client.Camera;
@@ -111,12 +112,26 @@ public abstract class MixinLevelRenderer {
@Inject(method = "renderLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/FogRenderer;levelFogColor()V", shift = At.Shift.AFTER))
public void renderLevel_levelFogColor(DeltaTracker deltaTracker, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f matrix4f, Matrix4f matrix4f2, CallbackInfo ci) {
EditorState editorState = EditorStateManager.getCurrent();
if (editorState != null && !editorState.replayVisuals.renderSky) {
if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().transparent()) {
RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0F);
} else {
float[] skyColour = editorState.replayVisuals.skyColour;
RenderSystem.clearColor(skyColour[0], skyColour[1], skyColour[2], 0.0F);
if (editorState != null) {
ReplayVisuals visuals = editorState.replayVisuals;
if (visuals.overrideFogColour) {
float[] fogColour = visuals.fogColour;
FogRenderer.fogRed = fogColour[0];
FogRenderer.fogGreen = fogColour[1];
FogRenderer.fogBlue = fogColour[2];
RenderSystem.setShaderFogColor(fogColour[0], fogColour[1], fogColour[2]);
if (visuals.renderSky) {
RenderSystem.clearColor(fogColour[0], fogColour[1], fogColour[2], 1.0F);
}
}
if (!visuals.renderSky) {
if (Flashback.isExporting() && Flashback.EXPORT_JOB.getSettings().transparent()) {
RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0F);
} else {
float[] skyColour = visuals.skyColour;
RenderSystem.clearColor(skyColour[0], skyColour[1], skyColour[2], 1.0F);
}
}
}
@@ -1,17 +1,20 @@
package com.moulberry.flashback.mixin.record;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.record.Recorder;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
@@ -19,6 +22,7 @@ import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ClientLevel.class)
public class MixinClientLevel {
@@ -27,6 +31,14 @@ public class MixinClientLevel {
@Final
private Minecraft minecraft;
@Inject(method = "setBlock", at = @At("HEAD"))
public void setBlock(BlockPos blockPos, BlockState blockState, int i, int j, CallbackInfoReturnable<Boolean> cir) {
Recorder recorder = Flashback.RECORDER;
if (recorder != null && !recorder.isPaused()) {
recorder.writePacketAsync(new ClientboundBlockUpdatePacket(blockPos.immutable(), blockState), ConnectionProtocol.PLAY);
}
}
@Inject(method = "levelEvent", at = @At("HEAD"))
public void levelEvent(Player player, int type, BlockPos blockPos, int data, CallbackInfo ci) {
if (Flashback.RECORDER != null && !Flashback.RECORDER.isPaused()) {
@@ -1,21 +1,22 @@
package com.moulberry.flashback.mixin.replay_server;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.moulberry.flashback.ext.ServerLevelExt;
import com.moulberry.flashback.playback.ReplayPlayer;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.core.SectionPos;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(ServerLevel.class)
@Mixin(value = ServerLevel.class, priority = 900)
public abstract class MixinServerLevel implements ServerLevelExt {
@Unique
@@ -59,4 +60,16 @@ public abstract class MixinServerLevel implements ServerLevelExt {
}
}
// Fix for worldgen mods injecting on getGeneratorState to add custom worldgen properties
// Lets just nuke the whole line
@WrapOperation(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/level/ServerChunkCache;getGeneratorState()Lnet/minecraft/world/level/chunk/ChunkGeneratorStructureState;"))
public ChunkGeneratorStructureState getGeneratorState(ServerChunkCache instance, Operation<ChunkGeneratorStructureState> original) {
return null;
}
@WrapOperation(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/ChunkGeneratorStructureState;ensureStructuresGenerated()V"))
public void ensureStructuresGenerated(ChunkGeneratorStructureState instance, Operation<Void> original) {
}
}
@@ -46,6 +46,7 @@ import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ExperienceOrb;
import net.minecraft.world.entity.Leashable;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
@@ -342,6 +343,7 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleBlockUpdate(ClientboundBlockUpdatePacket clientboundBlockUpdatePacket) {
System.out.println(clientboundBlockUpdatePacket.getPos());
this.setBlockState(this.level(), clientboundBlockUpdatePacket.getPos(),
clientboundBlockUpdatePacket.getBlockState());
forward(clientboundBlockUpdatePacket);
@@ -443,9 +445,13 @@ public class ReplayGamePacketHandler implements ClientGamePacketListener {
@Override
public void handleEntityLinkPacket(ClientboundSetEntityLinkPacket clientboundSetEntityLinkPacket) {
Entity source = this.level().getEntity(clientboundSetEntityLinkPacket.getSourceId());
if (source instanceof Mob mob) {
Entity dest = this.level().getEntity(clientboundSetEntityLinkPacket.getDestId());
mob.setLeashedTo(dest, true);
if (source instanceof Leashable leashable) {
if (clientboundSetEntityLinkPacket.getDestId() == 0) {
leashable.setLeashedTo(null, true);
} else {
Entity dest = this.level().getEntity(clientboundSetEntityLinkPacket.getDestId());
leashable.setLeashedTo(dest, true);
}
}
}
@@ -30,6 +30,9 @@ import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DecoderException;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.Util;
@@ -48,7 +51,9 @@ import net.minecraft.network.protocol.game.*;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Services;
import net.minecraft.server.WorldStem;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ClientInformation;
import net.minecraft.server.level.ServerEntity;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.TicketType;
@@ -57,7 +62,9 @@ import net.minecraft.server.network.ConfigurationTask;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.players.PlayerList;
import net.minecraft.util.Mth;
import net.minecraft.world.BossEvent;
import net.minecraft.world.entity.Display;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Inventory;
@@ -77,8 +84,11 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
@@ -136,6 +146,7 @@ public class ReplayServer extends IntegratedServer {
private final Map<UUID, BossEvent> bossEvents = new HashMap<>();
private Component tabListHeader = Component.empty();
private Component tabListFooter = Component.empty();
private final Map<ResourceKey<Level>, IntSet> needsPositionUpdate = new HashMap<>();
private Component shutdownReason = null;
private FileSystem playbackFileSystem = null;
@@ -586,6 +597,11 @@ public class ReplayServer extends IntegratedServer {
ResourceKey<Level> dimension = friendlyByteBuf.readResourceKey(Registries.DIMENSION);
ServerLevel level = this.levels.get(dimension);
IntSet positionUpdateSet = null;
if (level != null) {
positionUpdateSet = this.needsPositionUpdate.computeIfAbsent(dimension, k -> new IntOpenHashSet());
}
int count = friendlyByteBuf.readVarInt();
for (int j = 0; j < count; j++) {
int id = friendlyByteBuf.readVarInt();
@@ -605,6 +621,8 @@ public class ReplayServer extends IntegratedServer {
if (entity.onGround() != onGround) {
entity.setOnGround(onGround);
}
positionUpdateSet.add(id);
}
}
}
@@ -921,6 +939,48 @@ public class ReplayServer extends IntegratedServer {
// Tick underlying server
super.tickServer(booleanSupplier);
// Teleport entities
if (!this.needsPositionUpdate.isEmpty()) {
for (Map.Entry<ResourceKey<Level>, IntSet> entry : this.needsPositionUpdate.entrySet()) {
ResourceKey<Level> dimension = entry.getKey();
IntSet entities = entry.getValue();
ServerLevel level = this.getLevel(dimension);
if (level != null) {
Int2ObjectMap<ChunkMap.TrackedEntity> entityMap = level.getChunkSource().chunkMap.entityMap;
IntIterator iterator = entities.intIterator();
while (iterator.hasNext()) {
int entityId = iterator.nextInt();
ChunkMap.TrackedEntity trackedEntity = entityMap.get(entityId);
if (trackedEntity == null) {
continue;
}
ServerEntity serverEntity = trackedEntity.serverEntity;
Vec3 trackingPosition = serverEntity.entity.trackingPosition();
int quantizedYRot = Mth.floor(serverEntity.entity.getYRot() * 256.0F / 360.0F);
int quantizedXRot = Mth.floor(serverEntity.entity.getXRot() * 256.0F / 360.0F);
if (!serverEntity.positionCodec.getBase().equals(trackingPosition)) {
trackedEntity.broadcast(new ClientboundTeleportEntityPacket(serverEntity.entity));
serverEntity.positionCodec.setBase(trackingPosition);
serverEntity.lastSentYRot = quantizedYRot;
serverEntity.lastSentXRot = quantizedXRot;
} else if (quantizedYRot != serverEntity.lastSentYRot || quantizedXRot != serverEntity.lastSentXRot) {
trackedEntity.broadcast(new ClientboundMoveEntityPacket.Rot(entityId, (byte) quantizedYRot, (byte) quantizedXRot, serverEntity.wasOnGround));
serverEntity.lastSentYRot = quantizedYRot;
serverEntity.lastSentXRot = quantizedXRot;
}
}
}
}
this.needsPositionUpdate.clear();
}
if (Flashback.EXPORT_JOB == null) {
if (this.processedSnapshot) {
this.processedSnapshot = false;
@@ -1114,7 +1174,7 @@ public class ReplayServer extends IntegratedServer {
// Stop server
super.stopServer();
this.clearReplayTempFolder();
TempFolderProvider.deleteTemp(TempFolderProvider.TempFolderType.SERVER, this.playbackUUID);
if (this.playbackFileSystem != null) {
try {
@@ -1126,7 +1186,22 @@ public class ReplayServer extends IntegratedServer {
}
public void clearReplayTempFolder() {
TempFolderProvider.deleteTemp(TempFolderProvider.TempFolderType.SERVER, this.playbackUUID);
Path temp = TempFolderProvider.createTemp(TempFolderProvider.TempFolderType.SERVER, this.playbackUUID);
// Delete all files, but not directories
try {
Files.walkFileTree(temp, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!Files.isDirectory(file)) {
Files.deleteIfExists(file);
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
Flashback.LOGGER.error("Unable to delete replay temp folder", e);
}
}
@Override
@@ -55,6 +55,7 @@ import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.Leashable;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
@@ -970,8 +971,8 @@ public class Recorder {
gamePackets.add(new ClientboundSetPassengersPacket(entity.getVehicle()));
}
if (entity instanceof Mob mob && mob.isLeashed()) {
gamePackets.add(new ClientboundSetEntityLinkPacket(mob, mob.getLeashHolder()));
if (entity instanceof Leashable leashable && leashable.isLeashed()) {
gamePackets.add(new ClientboundSetEntityLinkPacket(entity, leashable.getLeashHolder()));
}
}
@@ -24,6 +24,9 @@ public class ReplayVisuals {
public float overrideFogStart = 0.0f;
public float overrideFogEnd = 256.0f;
public boolean overrideFogColour = false;
public float[] fogColour = new float[]{0f, 1f, 0f};
public boolean overrideFov = false;
public float overrideFovAmount = 70f;