This commit is contained in:
Moulberry committed 2024-07-25 16:40:29 +08:00
1 parent 9c4a30d224
commit 666398e480
174 files changed
+8694 -2942

No files matched your search

@@ -0,0 +1,55 @@
package com.moulberry.flashback.editor;
import com.moulberry.flashback.keyframe.Keyframe;
import com.moulberry.flashback.keyframe.KeyframeType;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.KeyframeTrack;
import java.util.Map;
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) {
if (this.keyframes == null || this.keyframes.isEmpty()) {
return 0;
}
editorState.dirty = true;
// Try to apply directly to copied track
if (this.track >= 0 && this.track < editorState.keyframeTracks.size()) {
KeyframeTrack keyframeTrack = editorState.keyframeTracks.get(this.track);
if ((keyframeTrack.enabled || this.copiedFromDisabled) && keyframeTrack.keyframeType == this.type) {
return this.applyTo(keyframeTrack, cursorTicks, totalTicks);
}
}
// Try to find first eligible enabled track
for (KeyframeTrack keyframeTrack : editorState.keyframeTracks) {
if (keyframeTrack.enabled && keyframeTrack.keyframeType == this.type) {
return this.applyTo(keyframeTrack, cursorTicks, totalTicks);
}
}
// Create new track
KeyframeTrack keyframeTrack = new KeyframeTrack(this.type);
int count = this.applyTo(keyframeTrack, cursorTicks, totalTicks);
if (!keyframeTrack.keyframesByTick.isEmpty()) {
editorState.keyframeTracks.add(keyframeTrack);
}
return count;
}
public int applyTo(KeyframeTrack keyframeTrack, int cursorTicks, int totalTicks) {
int count = 0;
for (Map.Entry<Integer, Keyframe<?>> entry : this.keyframes.entrySet()) {
int newTick = entry.getKey() + cursorTicks;
if (newTick >= 0 && newTick <= totalTicks) {
keyframeTrack.keyframesByTick.put(newTick, entry.getValue());
count += 1;
}
}
return count;
}
}
@@ -0,0 +1,22 @@
package com.moulberry.flashback.editor;
import com.moulberry.flashback.keyframe.KeyframeType;
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()) {
return false;
}
KeyframeTrack keyframeTrack = state.keyframeTracks.get(this.trackIndex);
if (keyframeTrack.keyframeType != this.type) {
return false;
}
this.keyframeTicks.removeIf(tick -> !keyframeTrack.keyframesByTick.containsKey(tick));
return !this.keyframeTicks.isEmpty();
}
}
@@ -0,0 +1,592 @@
package com.moulberry.flashback.editor.ui;
import imgui.ImDrawData;
import imgui.ImFontAtlas;
import imgui.ImGui;
import imgui.ImGuiIO;
import imgui.ImGuiViewport;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.callback.ImPlatformFuncViewport;
import imgui.flag.ImGuiBackendFlags;
import imgui.flag.ImGuiConfigFlags;
import imgui.flag.ImGuiViewportFlags;
import imgui.type.ImInt;
import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.lwjgl.opengl.GL32.*;
/**
* This class is a straightforward port of the
* <a href="https://raw.githubusercontent.com/ocornut/imgui/256594575d95d56dda616c544c509740e74906b4/backends/imgui_impl_opengl3.cpp">imgui_impl_opengl3.cpp</a>.
* <p>
* It do support a backup and restoring of the GL state in the same way the original Dear ImGui code does.
* Some of the very specific OpenGL variables may be ignored here,
* yet you can copy-paste this class in your codebase and modify the rendering routine in the way you'd like.
* <p>
* This implementation has an ability to use a GLSL version provided during the initialization.
* Please read the documentation for the {@link #init(String)}.
*/
@SuppressWarnings("MagicNumber")
public final class CustomImGuiImplGl3 {
// OpenGL Data
private int glVersion = 0;
private String glslVersion = "";
private int gFontTexture = -1;
private int gShaderHandle = 0;
private int gVertHandle = 0;
private int gFragHandle = 0;
private int gAttribLocationTex = 0;
private int gAttribLocationProjMtx = 0;
private int gAttribLocationVtxPos = 0;
private int gAttribLocationVtxUV = 0;
private int gAttribLocationVtxColor = 0;
private int gVboHandle = 0;
private int gElementsHandle = 0;
private int gVertexArrayObjectHandle = 0;
// Used to store tmp renderer data
private final ImVec2 displaySize = new ImVec2();
private final ImVec2 framebufferScale = new ImVec2();
private final ImVec2 displayPos = new ImVec2();
private final ImVec4 clipRect = new ImVec4();
private final float[] orthoProjMatrix = new float[4 * 4];
// Variables used to backup GL state before and after the rendering of Dear ImGui
private final int[] lastActiveTexture = new int[1];
private final int[] lastProgram = new int[1];
private final int[] lastTexture = new int[1];
private final int[] lastArrayBuffer = new int[1];
private final int[] lastVertexArrayObject = new int[1];
private final int[] lastFramebuffer = new int[1];
private final int[] lastViewport = new int[4];
private final int[] lastScissorBox = new int[4];
private final int[] lastBlendSrcRgb = new int[1];
private final int[] lastBlendDstRgb = new int[1];
private final int[] lastBlendSrcAlpha = new int[1];
private final int[] lastBlendDstAlpha = new int[1];
private final int[] lastBlendEquationRgb = new int[1];
private final int[] lastBlendEquationAlpha = new int[1];
private boolean lastEnableBlend = false;
private boolean lastEnableCullFace = false;
private boolean lastEnableDepthTest = false;
private boolean lastEnableStencilTest = false;
private boolean lastEnableScissorTest = false;
/**
* Method to do an initialization of the {@link CustomImGuiImplGl3} state.
* It SHOULD be called before calling of the {@link CustomImGuiImplGl3#renderDrawData(ImDrawData)} method.
* <p>
* Unlike in the {@link #init(String)} method, here the glslVersion argument is omitted.
* Thus a "#version 130" string will be used instead.
*/
public void init() {
this.init(null);
}
/**
* Method to do an initialization of the {@link CustomImGuiImplGl3} state.
* It SHOULD be called before calling of the {@link CustomImGuiImplGl3#renderDrawData(ImDrawData)} method.
* <p>
* Method takes an argument, which should be a valid GLSL string with the version to use.
* <pre>
* ----------------------------------------
* OpenGL GLSL GLSL
* version version string
* ---------------------------------------
* 2.0 110 "#version 110"
* 2.1 120 "#version 120"
* 3.0 130 "#version 130"
* 3.1 140 "#version 140"
* 3.2 150 "#version 150"
* 3.3 330 "#version 330 core"
* 4.0 400 "#version 400 core"
* 4.1 410 "#version 410 core"
* 4.2 420 "#version 410 core"
* 4.3 430 "#version 430 core"
* ES 3.0 300 "#version 300 es" = WebGL 2.0
* ---------------------------------------
* </pre>
* <p>
* If the argument is null, then a "#version 130" string will be used by default.
*
* @param glslVersion string with the version of the GLSL
*/
public void init(final String glslVersion) {
this.readGlVersion();
this.setupBackendCapabilitiesFlags();
if (glslVersion == null) {
this.glslVersion = "#version 130";
} else {
this.glslVersion = glslVersion;
}
this.createDeviceObjects();
if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {
this.initPlatformInterface();
}
}
/**
* Method to render {@link ImDrawData} into current OpenGL context.
*
* @param drawData draw data to render
*/
public void renderDrawData(final ImDrawData drawData) {
if (drawData.getCmdListsCount() <= 0) {
return;
}
// Will project scissor/clipping rectangles into framebuffer space
drawData.getDisplaySize(this.displaySize); // (0,0) unless using multi-viewports
drawData.getDisplayPos(this.displayPos);
drawData.getFramebufferScale(this.framebufferScale); // (1,1) unless using retina display which are often (2,2)
final float clipOffX = this.displayPos.x;
final float clipOffY = this.displayPos.y;
final float clipScaleX = this.framebufferScale.x;
final float clipScaleY = this.framebufferScale.y;
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
final int fbWidth = (int) (this.displaySize.x * this.framebufferScale.x);
final int fbHeight = (int) (this.displaySize.y * this.framebufferScale.y);
if (fbWidth <= 0 || fbHeight <= 0) {
return;
}
this.backupGlState();
this.bind(fbWidth, fbHeight);
// Render command lists
for (int cmdListIdx = 0; cmdListIdx < drawData.getCmdListsCount(); cmdListIdx++) {
// Upload vertex/index buffers
glBufferData(GL_ARRAY_BUFFER, drawData.getCmdListVtxBufferData(cmdListIdx), GL_STREAM_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, drawData.getCmdListIdxBufferData(cmdListIdx), GL_STREAM_DRAW);
for (int cmdBufferIdx = 0; cmdBufferIdx < drawData.getCmdListCmdBufferSize(cmdListIdx); cmdBufferIdx++) {
drawData.getCmdListCmdBufferClipRect(cmdListIdx, cmdBufferIdx, this.clipRect);
final float clipMinX = (this.clipRect.x - clipOffX) * clipScaleX;
final float clipMinY = (this.clipRect.y - clipOffY) * clipScaleY;
final float clipMaxX = (this.clipRect.z - clipOffX) * clipScaleX;
final float clipMaxY = (this.clipRect.w - clipOffY) * clipScaleY;
if (clipMaxX <= clipMinX || clipMaxY <= clipMinY) {
continue;
}
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
glScissor((int) clipMinX, (int) (fbHeight - clipMaxY), (int) (clipMaxX - clipMinX), (int) (clipMaxY - clipMinY));
// Bind texture, Draw
final int textureId = drawData.getCmdListCmdBufferTextureId(cmdListIdx, cmdBufferIdx);
final int elemCount = drawData.getCmdListCmdBufferElemCount(cmdListIdx, cmdBufferIdx);
final int idxBufferOffset = drawData.getCmdListCmdBufferIdxOffset(cmdListIdx, cmdBufferIdx);
final int vtxBufferOffset = drawData.getCmdListCmdBufferVtxOffset(cmdListIdx, cmdBufferIdx);
final int indices = idxBufferOffset * ImDrawData.SIZEOF_IM_DRAW_IDX;
glBindTexture(GL_TEXTURE_2D, textureId);
if (this.glVersion >= 320) {
glDrawElementsBaseVertex(GL_TRIANGLES, elemCount, GL_UNSIGNED_SHORT, indices, vtxBufferOffset);
} else {
glDrawElements(GL_TRIANGLES, elemCount, GL_UNSIGNED_SHORT, indices);
}
}
}
this.unbind();
this.restoreModifiedGlState();
}
/**
* Call this method in the end of your application cycle to dispose resources used by {@link CustomImGuiImplGl3}.
*/
public void dispose() {
glDeleteBuffers(this.gVboHandle);
glDeleteBuffers(this.gElementsHandle);
glDetachShader(this.gShaderHandle, this.gVertHandle);
glDetachShader(this.gShaderHandle, this.gFragHandle);
glDeleteProgram(this.gShaderHandle);
glDeleteTextures(this.gFontTexture);
this.shutdownPlatformInterface();
}
/**
* Method rebuilds the font atlas for Dear ImGui. Could be used to update application fonts in runtime.
*/
public void updateFontsTexture() {
if (this.gFontTexture != -1) glDeleteTextures(this.gFontTexture);
final ImFontAtlas fontAtlas = ImGui.getIO().getFonts();
final ImInt width = new ImInt();
final ImInt height = new ImInt();
final ByteBuffer buffer = fontAtlas.getTexDataAsRGBA32(width, height);
this.gFontTexture = glGenTextures();
glBindTexture(GL_TEXTURE_2D, this.gFontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width.get(), height.get(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
fontAtlas.setTexID(this.gFontTexture);
}
private void readGlVersion() {
final int[] major = new int[1];
final int[] minor = new int[1];
glGetIntegerv(GL_MAJOR_VERSION, major);
glGetIntegerv(GL_MINOR_VERSION, minor);
this.glVersion = major[0] * 100 + minor[0] * 10;
}
private void setupBackendCapabilitiesFlags() {
final ImGuiIO io = ImGui.getIO();
io.setBackendRendererName("imgui_java_impl_opengl3");
// We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
if (this.glVersion >= 320) {
io.addBackendFlags(ImGuiBackendFlags.RendererHasVtxOffset);
}
// We can create multi-viewports on the Renderer side (optional)
io.addBackendFlags(ImGuiBackendFlags.RendererHasViewports);
}
private void createDeviceObjects() {
// Backup GL state
final int[] lastTexture = new int[1];
final int[] lastArrayBuffer = new int[1];
final int[] lastVertexArray = new int[1];
glGetIntegerv(GL_TEXTURE_BINDING_2D, lastTexture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, lastArrayBuffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, lastVertexArray);
this.createShaders();
this.gAttribLocationTex = glGetUniformLocation(this.gShaderHandle, "Texture");
this.gAttribLocationProjMtx = glGetUniformLocation(this.gShaderHandle, "ProjMtx");
this.gAttribLocationVtxPos = glGetAttribLocation(this.gShaderHandle, "Position");
this.gAttribLocationVtxUV = glGetAttribLocation(this.gShaderHandle, "UV");
this.gAttribLocationVtxColor = glGetAttribLocation(this.gShaderHandle, "Color");
// Create buffers
this.gVboHandle = glGenBuffers();
this.gElementsHandle = glGenBuffers();
this.updateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, lastTexture[0]);
glBindBuffer(GL_ARRAY_BUFFER, lastArrayBuffer[0]);
glBindVertexArray(lastVertexArray[0]);
}
private void createShaders() {
final int glslVersionValue = this.parseGlslVersionString();
// Select shaders matching our GLSL versions
final CharSequence vertShaderSource;
final CharSequence fragShaderSource;
if (glslVersionValue < 130) {
vertShaderSource = this.getVertexShaderGlsl120();
fragShaderSource = this.getFragmentShaderGlsl120();
} else if (glslVersionValue == 300) {
vertShaderSource = this.getVertexShaderGlsl300es();
fragShaderSource = this.getFragmentShaderGlsl300es();
} else if (glslVersionValue >= 410) {
vertShaderSource = this.getVertexShaderGlsl410Core();
fragShaderSource = this.getFragmentShaderGlsl410Core();
} else {
vertShaderSource = this.getVertexShaderGlsl130();
fragShaderSource = this.getFragmentShaderGlsl130();
}
this.gVertHandle = this.createAndCompileShader(GL_VERTEX_SHADER, vertShaderSource);
this.gFragHandle = this.createAndCompileShader(GL_FRAGMENT_SHADER, fragShaderSource);
this.gShaderHandle = glCreateProgram();
glAttachShader(this.gShaderHandle, this.gVertHandle);
glAttachShader(this.gShaderHandle, this.gFragHandle);
glLinkProgram(this.gShaderHandle);
if (glGetProgrami(this.gShaderHandle, GL_LINK_STATUS) == GL_FALSE) {
throw new IllegalStateException("Failed to link shader program:\n" + glGetProgramInfoLog(this.gShaderHandle));
}
}
private int parseGlslVersionString() {
final Pattern p = Pattern.compile("\\d+");
final Matcher m = p.matcher(this.glslVersion);
if (m.find()) {
return Integer.parseInt(m.group());
} else {
throw new IllegalArgumentException("Invalid GLSL version string: " + this.glslVersion);
}
}
private void backupGlState() {
glGetIntegerv(GL_ACTIVE_TEXTURE, this.lastActiveTexture);
glActiveTexture(GL_TEXTURE0);
glGetIntegerv(GL_CURRENT_PROGRAM, this.lastProgram);
glGetIntegerv(GL_TEXTURE_BINDING_2D, this.lastTexture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, this.lastArrayBuffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, this.lastVertexArrayObject);
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, this.lastFramebuffer);
glGetIntegerv(GL_VIEWPORT, this.lastViewport);
glGetIntegerv(GL_SCISSOR_BOX, this.lastScissorBox);
glGetIntegerv(GL_BLEND_SRC_RGB, this.lastBlendSrcRgb);
glGetIntegerv(GL_BLEND_DST_RGB, this.lastBlendDstRgb);
glGetIntegerv(GL_BLEND_SRC_ALPHA, this.lastBlendSrcAlpha);
glGetIntegerv(GL_BLEND_DST_ALPHA, this.lastBlendDstAlpha);
glGetIntegerv(GL_BLEND_EQUATION_RGB, this.lastBlendEquationRgb);
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, this.lastBlendEquationAlpha);
this.lastEnableBlend = glIsEnabled(GL_BLEND);
this.lastEnableCullFace = glIsEnabled(GL_CULL_FACE);
this.lastEnableDepthTest = glIsEnabled(GL_DEPTH_TEST);
this.lastEnableStencilTest = glIsEnabled(GL_STENCIL_TEST);
this.lastEnableScissorTest = glIsEnabled(GL_SCISSOR_TEST);
}
private void restoreModifiedGlState() {
glUseProgram(this.lastProgram[0]);
glBindTexture(GL_TEXTURE_2D, this.lastTexture[0]);
glActiveTexture(this.lastActiveTexture[0]);
glBindVertexArray(this.lastVertexArrayObject[0]);
glBindFramebuffer(GL_FRAMEBUFFER, this.lastFramebuffer[0]);
glBindBuffer(GL_ARRAY_BUFFER, this.lastArrayBuffer[0]);
glBlendEquationSeparate(this.lastBlendEquationRgb[0], this.lastBlendEquationAlpha[0]);
glBlendFuncSeparate(this.lastBlendSrcRgb[0], this.lastBlendDstRgb[0], this.lastBlendSrcAlpha[0], this.lastBlendDstAlpha[0]);
// @formatter:off CHECKSTYLE:OFF
if (this.lastEnableBlend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (this.lastEnableCullFace) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (this.lastEnableDepthTest) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (this.lastEnableStencilTest) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
if (this.lastEnableScissorTest) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
// @formatter:on CHECKSTYLE:ON
glViewport(this.lastViewport[0], this.lastViewport[1], this.lastViewport[2], this.lastViewport[3]);
glScissor(this.lastScissorBox[0], this.lastScissorBox[1], this.lastScissorBox[2], this.lastScissorBox[3]);
}
// Setup desired GL state
private void bind(final int fbWidth, final int fbHeight) {
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
this.gVertexArrayObjectHandle = glGenVertexArrays();
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glEnable(GL_SCISSOR_TEST);
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
// DisplayPos is (0,0) for single viewport apps.
glViewport(0, 0, fbWidth, fbHeight);
final float left = this.displayPos.x;
final float right = this.displayPos.x + this.displaySize.x;
final float top = this.displayPos.y;
final float bottom = this.displayPos.y + this.displaySize.y;
// Orthographic matrix projection
this.orthoProjMatrix[0] = 2.0f / (right - left);
this.orthoProjMatrix[5] = 2.0f / (top - bottom);
this.orthoProjMatrix[10] = -1.0f;
this.orthoProjMatrix[12] = (right + left) / (left - right);
this.orthoProjMatrix[13] = (top + bottom) / (bottom - top);
this.orthoProjMatrix[15] = 1.0f;
// Bind shader
glUseProgram(this.gShaderHandle);
glUniform1i(this.gAttribLocationTex, 0);
glUniformMatrix4fv(this.gAttribLocationProjMtx, false, this.orthoProjMatrix);
glBindVertexArray(this.gVertexArrayObjectHandle);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Bind vertex/index buffers and setup attributes for ImDrawVert
glBindBuffer(GL_ARRAY_BUFFER, this.gVboHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this.gElementsHandle);
glEnableVertexAttribArray(this.gAttribLocationVtxPos);
glEnableVertexAttribArray(this.gAttribLocationVtxUV);
glEnableVertexAttribArray(this.gAttribLocationVtxColor);
glVertexAttribPointer(this.gAttribLocationVtxPos, 2, GL_FLOAT, false, ImDrawData.SIZEOF_IM_DRAW_VERT, 0);
glVertexAttribPointer(this.gAttribLocationVtxUV, 2, GL_FLOAT, false, ImDrawData.SIZEOF_IM_DRAW_VERT, 8);
glVertexAttribPointer(this.gAttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, true, ImDrawData.SIZEOF_IM_DRAW_VERT, 16);
}
private void unbind() {
// Destroy the temporary VAO
glDeleteVertexArrays(this.gVertexArrayObjectHandle);
}
//--------------------------------------------------------------------------------------------------------
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
// This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
//--------------------------------------------------------------------------------------------------------
private void initPlatformInterface() {
ImGui.getPlatformIO().setRendererRenderWindow(new ImPlatformFuncViewport() {
@Override
public void accept(final ImGuiViewport vp) {
if (!vp.hasFlags(ImGuiViewportFlags.NoRendererClear)) {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
}
CustomImGuiImplGl3.this.renderDrawData(vp.getDrawData());
}
});
}
private void shutdownPlatformInterface() {
ImGui.destroyPlatformWindows();
}
private int createAndCompileShader(final int type, final CharSequence source) {
final int id = glCreateShader(type);
glShaderSource(id, source);
glCompileShader(id);
if (glGetShaderi(id, GL_COMPILE_STATUS) == GL_FALSE) {
throw new IllegalStateException("Failed to compile shader:\n" + glGetShaderInfoLog(id));
}
return id;
}
private String getVertexShaderGlsl120() {
return this.glslVersion + "\n"
+ "uniform mat4 ProjMtx;\n"
+ "attribute vec2 Position;\n"
+ "attribute vec2 UV;\n"
+ "attribute vec4 Color;\n"
+ "varying vec2 Frag_UV;\n"
+ "varying vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getVertexShaderGlsl130() {
return this.glslVersion + "\n"
+ "uniform mat4 ProjMtx;\n"
+ "in vec2 Position;\n"
+ "in vec2 UV;\n"
+ "in vec4 Color;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getVertexShaderGlsl300es() {
return this.glslVersion + "\n"
+ "precision highp float;\n"
+ "layout (location = 0) in vec2 Position;\n"
+ "layout (location = 1) in vec2 UV;\n"
+ "layout (location = 2) in vec4 Color;\n"
+ "uniform mat4 ProjMtx;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getVertexShaderGlsl410Core() {
return this.glslVersion + "\n"
+ "layout (location = 0) in vec2 Position;\n"
+ "layout (location = 1) in vec2 UV;\n"
+ "layout (location = 2) in vec4 Color;\n"
+ "uniform mat4 ProjMtx;\n"
+ "out vec2 Frag_UV;\n"
+ "out vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Frag_UV = UV;\n"
+ " Frag_Color = Color;\n"
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
+ "}\n";
}
private String getFragmentShaderGlsl120() {
return this.glslVersion + "\n"
+ "#ifdef GL_ES\n"
+ " precision mediump float;\n"
+ "#endif\n"
+ "uniform sampler2D Texture;\n"
+ "varying vec2 Frag_UV;\n"
+ "varying vec4 Frag_Color;\n"
+ "void main()\n"
+ "{\n"
+ " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
+ "}\n";
}
private String getFragmentShaderGlsl130() {
return this.glslVersion + "\n"
+ "uniform sampler2D Texture;\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "out vec4 Out_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
}
private String getFragmentShaderGlsl300es() {
return this.glslVersion + "\n"
+ "precision mediump float;\n"
+ "uniform sampler2D Texture;\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "layout (location = 0) out vec4 Out_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
}
private String getFragmentShaderGlsl410Core() {
return this.glslVersion + "\n"
+ "in vec2 Frag_UV;\n"
+ "in vec4 Frag_Color;\n"
+ "uniform sampler2D Texture;\n"
+ "layout (location = 0) out vec4 Out_Color;\n"
+ "void main()\n"
+ "{\n"
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
+ "}\n";
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,256 @@
package com.moulberry.flashback.editor.ui;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import org.joml.Intersectionf;
import org.joml.Vector3f;
import org.lwjgl.glfw.GLFW;
public abstract sealed class EditorMovementControls permits EditorMovementControls.None, EditorMovementControls.Rotate, EditorMovementControls.Pan, EditorMovementControls.Arcball {
// Interface
public abstract boolean allowGameInputWhileCaptureKeyboard();
public abstract boolean shouldStop(boolean isGrabbed);
public abstract void update(double mouseDeltaX, double mouseDeltaY);
// Static constructors
public static EditorMovementControls none() {
return None.INSTANCE;
}
public static EditorMovementControls rotate() {
LocalPlayer player = Minecraft.getInstance().player;
if (player == null) return None.INSTANCE;
return new Rotate(ReplayUI.getMouseForwardsVector(), new Vec2(
Minecraft.getInstance().player.getXRot(),
Minecraft.getInstance().player.getYRot()
));
}
// public static EditorMovementControls pan() {
// LocalPlayer player = Minecraft.getInstance().player;
// if (player == null) return None.INSTANCE;
//
// RayCaster.RaycastResult result = Tool.raycastBlock();
// if (result == null) return None.INSTANCE;
//
// Vec3 planePoint = result.getLocation();
// return new Pan(player.position(), planePoint.toVector3f(), player.getLookAngle().toVector3f().negate());
// }
// public static EditorMovementControls arcball() {
// LocalPlayer player = Minecraft.getInstance().player;
// if (player == null) return None.INSTANCE;
//
// var look = ReplayUI.getMouseLookVector();
// if (look == null) return None.INSTANCE;
//
// RayCaster.RaycastResult result = RayCaster.raycast(Minecraft.getInstance().level,
// player.getEyePosition().toVector3f(), look.toVector3f(), false, false);
//
// Vec3 point;
// if (result != null) {
// point = result.getLocation();
// } else {
// return None.INSTANCE;
// }
//
// float distance = (float) point.distanceTo(player.getEyePosition());
// return new Arcball(point, distance, true);
// }
// Implementations
protected static final class None extends EditorMovementControls {
private static final None INSTANCE = new None();
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return false;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return false;
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
}
}
protected static final class Rotate extends EditorMovementControls {
private final Vec3 originalForwards;
private final Vec2 originalAngles;
public Rotate(Vec3 originalForwards, Vec2 originalAngles) {
this.originalForwards = originalForwards;
this.originalAngles = originalAngles;
}
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return true;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return !ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_LEFT);
// todo: keybinds
// return !Keybinds.ROTATE_CAMERA.isDownIgnoreMods();
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
Vec3 forwards = ReplayUI.getMouseForwardsVector();
LocalPlayer player = Minecraft.getInstance().player;
if (forwards == null || player == null) return;
float pitch = this.originalAngles.x;
float yaw = this.originalAngles.y;
Vec3 lastVector = this.originalForwards;
for (int i=1; i<=10; i++) {
Vec3 thisVector = this.originalForwards.lerp(forwards, i/10f);
// Calculate pitch
double differenceY = lastVector.y - thisVector.y;
double pitchDelta = Math.toDegrees(Math.asin(differenceY / 2f)) * 2;
pitch = Mth.wrapDegrees(pitch - (float) pitchDelta);
pitch = Mth.clamp(pitch, -90, 90);
// Calculate change in yaw
double yaw1 = Math.toDegrees(Math.atan2(lastVector.x, lastVector.z));
double yaw2 = Math.toDegrees(Math.atan2(thisVector.x, thisVector.z));
double yawDelta = Mth.wrapDegrees(yaw1 - yaw2);
// Calculate scaling factor (radius of circle on unit sphere at current pitch)
Vector3f forwards3f = lastVector.lerp(thisVector, 0.5f).toVector3f();
forwards3f.rotateX((float) Math.toRadians(pitch));
forwards3f.normalize();
float radius = (float) Math.sqrt(1 - forwards3f.y() * forwards3f.y()) * 1.08f;
if (radius < 0.2f) radius = 0.2f;
yaw = Mth.wrapDegrees(yaw - (float) yawDelta / radius);
lastVector = thisVector;
}
// Set values
player.setXRot(pitch);
player.setYRot(yaw);
}
}
protected static final class Pan extends EditorMovementControls {
private final Vec3 originalPos;
private final Vector3f planePoint;
private final Vector3f planeNormal;
public Pan(Vec3 originalPos, Vector3f planePoint, Vector3f planeNormal) {
this.originalPos = originalPos;
this.planePoint = planePoint;
this.planeNormal = planeNormal;
}
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return false;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return !ImGui.isMouseDown(GLFW.GLFW_MOUSE_BUTTON_RIGHT);
// return !Keybinds.PAN_CAMERA.isDownIgnoreMods();
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
Vec3 forwards = ReplayUI.getMouseForwardsVector();
LocalPlayer player = Minecraft.getInstance().player;
if (forwards == null || player == null) return;
var origin = this.originalPos.add(0, player.getEyeHeight(), 0).toVector3f();
var view = ReplayUI.getMouseLookVectorFromForwards(forwards).toVector3f();
var distance = Intersectionf.intersectRayPlane(origin, view, this.planePoint, this.planeNormal, 1E-5f);
if (distance < 0) return;
Vector3f targetPoint = origin.add(new Vector3f(view).mul(distance));
Vector3f targetDelta = new Vector3f(targetPoint).sub(this.planePoint);
var finalPos = this.originalPos.subtract(targetDelta.x, targetDelta.y, targetDelta.z);
player.setPos(finalPos);
player.setOldPosAndRot();
}
}
protected static final class Arcball extends EditorMovementControls {
private final Vec3 point;
private float distance;
private boolean snapLook;
public Arcball(Vec3 point, float distance, boolean snapLook) {
this.point = point;
this.distance = Math.max(1, distance);
this.snapLook = snapLook;
}
@Override
public boolean allowGameInputWhileCaptureKeyboard() {
return false;
}
@Override
public boolean shouldStop(boolean isGrabbed) {
return !isGrabbed;
}
@Override
public void update(double mouseDeltaX, double mouseDeltaY) {
LocalPlayer player = Minecraft.getInstance().player;
if (player == null) return;
if (this.snapLook) {
this.snapLook = false;
var look = ReplayUI.getMouseLookVector();
double horizontal = Math.sqrt(look.x*look.x + look.z*look.z);
float newXRot = Mth.wrapDegrees((float)(Math.toDegrees(-(Mth.atan2(look.y, horizontal)))));
float newYRot = Mth.wrapDegrees((float)(Math.toDegrees(Mth.atan2(look.z, look.x))) - 90.0f);
player.setXRot(newXRot);
player.setYRot(newYRot);
return;
}
double baseSensitivity = Minecraft.getInstance().options.sensitivity().get() * (double)0.6f + (double)0.2f;
double sensitivity = baseSensitivity * baseSensitivity * baseSensitivity * 8.0;
int invert = Minecraft.getInstance().options.invertYMouse().get() ? -1 : 1;
player.turn(mouseDeltaX * sensitivity, mouseDeltaY * sensitivity * invert);
if (ImGui.getIO().getMouseWheel() != 0) {
float wheel = Math.signum(ImGui.getIO().getMouseWheel());
float move = this.distance * 0.05f;
if (move > 4) move = 4 + (float)Math.sqrt(move - 4);
move *= wheel;
if (ReplayUI.isMoveQuickDown()) move *= 2;
this.distance = Math.max(1, this.distance - move);
}
Vec3 position = this.point.subtract(player.getLookAngle().scale(this.distance));
Minecraft.getInstance().player.setPos(position.subtract(0, player.getEyeHeight(), 0));
Minecraft.getInstance().player.setOldPosAndRot();
}
}
}
@@ -0,0 +1,160 @@
package com.moulberry.flashback.editor.ui;
public class GlyphRanges {
private static final short[] SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00 = {
0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2,
1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4,
2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1,
1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2,
3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6,
1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1,
1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3,
2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4,
27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12,
3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1,
1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23,
176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6,
5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6,
1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1,
6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5,
2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15,
2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6,
2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4,
3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5,
3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2,
3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16,
1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31,
140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7,
5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2,
2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13,
4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3,
2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4,
4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1,
3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3,
3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11,
2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9,
5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2,
3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3,
1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12,
4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8,
4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5,
26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1,
3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5,
2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6,
10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6
};
private static final short[] SC_BASE_RANGES = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x2000, 0x206F, // General Punctuation
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
(short)0xFF00, (short)0xFFEF, // Half-width characters
(short)0xFFFD, (short)0xFFFD // Invalid
};
private static short[] SC_FULL_RANGES = null;
public static short[] getSimplifiedChineseRanges() {
if (SC_FULL_RANGES == null) {
SC_FULL_RANGES = new short[SC_BASE_RANGES.length + SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00.length*2 + 1];
System.arraycopy(SC_BASE_RANGES, 0, SC_FULL_RANGES, 0, SC_BASE_RANGES.length);
unpackAccumulativeOffsetsIntoRanges(0x4E00,SC_ACCUMULATIVE_OFFSETS_FROM_0x4E00, SC_BASE_RANGES.length, SC_FULL_RANGES);
}
return SC_FULL_RANGES;
}
private static final short[] JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00 = new short[] {
0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1,
1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3,
2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8,
2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5,
2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1,
1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30,
2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3,
13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4,
5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14,
2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1,
1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1,
7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1,
1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1,
6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2,
10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7,
2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5,
3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1,
6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7,
4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2,
4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5,
1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6,
12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2,
1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16,
22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11,
2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18,
18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9,
14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3,
1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6,
40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1,
12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8,
2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1,
1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10,
1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5,
3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2,
14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5,
12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1,
2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5,
1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4,
3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7,
2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5,
13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13,
18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21,
37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1,
5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38,
32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4,
1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4,
4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
3,2,1,1,1,1,2,1,1
};
private static final short JP_BASE_RANGES[] = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
(short)0xFF00, (short)0xFFEF, // Half-width characters
(short)0xFFFD, (short)0xFFFD // Invalid
};
private static short[] JP_FULL_RANGES = null;
public static short[] getJapaneseRanges() {
if (JP_FULL_RANGES == null) {
JP_FULL_RANGES = new short[JP_BASE_RANGES.length + JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00.length*2 + 1];
System.arraycopy(JP_BASE_RANGES, 0, JP_FULL_RANGES, 0, JP_BASE_RANGES.length);
unpackAccumulativeOffsetsIntoRanges(0x4E00, JP_ACCUMULATIVE_OFFSETS_FROM_0x4E00, JP_BASE_RANGES.length, JP_FULL_RANGES);
}
return JP_FULL_RANGES;
}
private static final short[] TC_FULL_RANGES = {
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x2000, 0x206F, // General Punctuation
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
(short)0xFF00, (short)0xFFEF, // Half-width characters
(short)0xFFFD, (short)0xFFFD, // Invalid
0x4e00, (short)0x9FAF, // CJK Ideograms
0,
};
public static short[] getChineseFullRanges() {
return TC_FULL_RANGES;
}
static void unpackAccumulativeOffsetsIntoRanges(int baseCodepoint, short[] accumulativeOffsets, int index, short[] output) {
for (int n = 0; n < accumulativeOffsets.length; n++, index += 2) {
output[index] = output[index+1] = (short)(baseCodepoint + accumulativeOffsets[n]);
baseCodepoint += accumulativeOffsets[n];
}
output[output.length - 1] = 0;
}
}
@@ -0,0 +1,535 @@
package com.moulberry.flashback.editor.ui;
import com.moulberry.flashback.combo_options.ComboOption;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiComboFlags;
import imgui.flag.ImGuiHoveredFlags;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImBoolean;
import imgui.type.ImString;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ConfirmLinkScreen;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.lwjgl.glfw.GLFW;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntConsumer;
import java.util.function.Predicate;
public class ImGuiHelper {
public static String getString(ImString string) {
StringBuilder builder = new StringBuilder();
String str = string.get();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c == '\0') break;
builder.append(c);
}
return builder.toString();
}
public static ImString createResizableImString(String text) {
ImString imString = new ImString(text);
imString.inputData.isResizable = true;
return imString;
}
public static int elementList(String name, List<String> elements, float width, int minLines, int maxLines, boolean framed, IntConsumer buttonConsumer) {
if (minLines > maxLines) throw new IllegalArgumentException();
if (width <= 0) {
width = Math.max(ImGui.getContentRegionAvailX() + width, 4.0f);
}
float itemSpacingX = ImGui.getStyle().getItemSpacingX();
float framePaddingX = ImGui.getStyle().getFramePaddingX();
float availableSpace = width;
if (framed) availableSpace -= framePaddingX*2f;
int lines = 0;
boolean scrollbar = false;
if (minLines == maxLines) {
lines = minLines;
scrollbar = true; // assume there is a scrollbar
} else {
float consumedWidth = 0;
for (String element : elements) {
float elementWidth = framePaddingX*2f + ImGuiHelper.calcTextWidth(element);
if (consumedWidth+elementWidth < availableSpace && consumedWidth > 0) {
consumedWidth += elementWidth + itemSpacingX;
} else {
consumedWidth = elementWidth + itemSpacingX;
lines += 1;
if (lines > maxLines) {
lines = maxLines;
scrollbar = true;
break;
}
}
}
if (lines < minLines) lines = minLines;
}
float lineHeight = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2 + ImGui.getStyle().getItemSpacingY();
boolean visible;
if (framed) {
visible = ImGui.beginChildFrame(ImGui.getID(name), width, lineHeight*lines + ImGui.getStyle().getFramePaddingY()*2 - ImGui.getStyle().getItemSpacingY());
} else {
visible = ImGui.beginChild(name, width, lineHeight*lines - ImGui.getStyle().getItemSpacingY());
}
int ret = -1;
if (visible) {
if (scrollbar) {
availableSpace -= ImGui.getStyle().getScrollbarSize();
}
float consumedWidth = 0;
for (int i=0; i<elements.size(); i++) {
String element = elements.get(i);
float elementWidth = framePaddingX*2f + ImGuiHelper.calcTextWidth(element);
if (consumedWidth+elementWidth < availableSpace && consumedWidth > 0) {
ImGui.sameLine();
consumedWidth += elementWidth + itemSpacingX;
} else {
consumedWidth = elementWidth + itemSpacingX;
}
ImGui.pushID(i);
if (ImGui.button(element)) {
ret = i;
}
if (buttonConsumer != null) {
buttonConsumer.accept(i);
}
ImGui.popID();
}
}
if (framed) {
ImGui.endChildFrame();
} else {
ImGui.endChild();
}
return ret;
}
private static final int[] enumComboSharedArray = new int[]{0};
private static final Map<Class<?>, Object[]> enumComboCachedValues = new HashMap<>();
private static final Map<Class<?>, String[]> enumComboCachedText = new HashMap<>();
public static <T extends Enum<?> & ComboOption> T enumCombo(String label, T c, T[] values) {
int currentIndex = -1;
for (int i = 0; i < values.length; i++) {
T value = values[i];
if (value == c) {
currentIndex = i;
break;
}
}
String[] text = new String[values.length];
for (int i = 0; i < text.length; i++) {
text[i] = values[i].text();
}
enumComboSharedArray[0] = currentIndex;
combo(label, enumComboSharedArray, text);
if (enumComboSharedArray[0] == currentIndex) {
return c;
} else {
return values[enumComboSharedArray[0]];
}
}
@SuppressWarnings("unchecked")
public static <T extends Enum<?> & ComboOption> T enumCombo(String label, T c) {
Class<?> clazz = c.getClass();
int currentIndex = c.ordinal();
String[] text = enumComboCachedText.get(clazz);
if (text == null) {
T[] options = (T[]) clazz.getEnumConstants();
enumComboCachedValues.put(clazz, options);
text = new String[options.length];
for (int i = 0; i < text.length; i++) {
text[i] = options[i].text();
}
enumComboCachedText.put(clazz, text);
}
enumComboSharedArray[0] = currentIndex;
combo(label, enumComboSharedArray, text);
if (enumComboSharedArray[0] == currentIndex) {
return c;
} else {
return (T) enumComboCachedValues.get(clazz)[enumComboSharedArray[0]];
}
}
public static boolean combo(String label, int[] currentItem, String[] values) {
return combo(label, currentItem, values, ImGuiComboFlags.None);
}
public static boolean combo(String label, int[] currentItem, String[] values, int imguiComboFlags) {
boolean changed = false;
if (currentItem[0] >= values.length && values.length > 0) {
currentItem[0] = values.length-1;
}
if (ImGui.beginCombo(label, currentItem[0] < 0 ? "" : values[currentItem[0]], imguiComboFlags)) {
for (int i=0; i<values.length; i++) {
ImGui.pushID(i);
boolean selected = i == currentItem[0];
if (ImGui.selectable(values[i], selected) && !selected) {
currentItem[0] = i;
changed = true;
}
if (selected) ImGui.setItemDefaultFocus();
ImGui.popID();
}
ImGui.endCombo();
}
return changed;
}
private static boolean closeableModalOnTopLast = false;
private static boolean closeableModalOnTop = false;
private static boolean inputIntScrolledLastFrame = false;
private static boolean inputIntScrolledThisFrame = false;
private static boolean wantSpecialInputLastFrame = false;
private static boolean wantSpecialInputThisFrame = false;
private static StringBuilder specialInput = new StringBuilder();
private static int backspaceCount = 0;
private static boolean handledFocusNext = false;
private static boolean focusNext = false;
public static void endFrame() {
closeableModalOnTopLast = closeableModalOnTop;
inputIntScrolledLastFrame = inputIntScrolledThisFrame;
inputIntScrolledThisFrame = false;
wantSpecialInputLastFrame = wantSpecialInputThisFrame;
wantSpecialInputThisFrame = false;
handledFocusNext = false;
focusNext = false;
if (!wantSpecialInputLastFrame) specialInput.setLength(0);
}
public static String modifyFromInput(String existing) {
wantSpecialInputThisFrame = true;
String newInput = specialInput.toString();
existing = existing.substring(0, Math.max(0, existing.length() - backspaceCount));
existing += newInput;
specialInput.setLength(0);
backspaceCount = 0;
return existing;
}
public static boolean getWantsSpecialInput() {
return wantSpecialInputLastFrame;
}
public static boolean addInputCharacter(char c) {
if (wantSpecialInputLastFrame) {
specialInput.append(c);
return true;
}
return false;
}
public static boolean backspaceInput(int mods) {
if (wantSpecialInputLastFrame) {
if ((mods & GLFW.GLFW_MOD_CONTROL) != 0) {
specialInput.setLength(0);
backspaceCount = 10000;
return true;
}
if (specialInput.length() > 0) {
specialInput.setLength(specialInput.length() - 1);
} else {
backspaceCount += 1;
}
return true;
}
return false;
}
public static boolean beginPopup(String id) {
return beginPopup(id, ImGuiWindowFlags.None);
}
public static boolean beginPopup(String id, int imGuiWindowFlags) {
if (ImGui.beginPopup(id, imGuiWindowFlags | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoSavedSettings)) {
closeableModalOnTop = false;
return true;
} else {
return false;
}
}
public static boolean beginPopupModal(String id) {
return beginPopupModal(id, ImGuiWindowFlags.None);
}
public static boolean beginPopupModal(String id, int imGuiWindowFlags) {
if (ImGui.beginPopupModal(id, imGuiWindowFlags | ImGuiWindowFlags.NoSavedSettings)) {
closeableModalOnTop = false;
return true;
} else {
return false;
}
}
public static boolean beginPopupModalCloseable(String id) {
return beginPopupModalCloseable(id, ImGuiWindowFlags.None);
}
public static boolean beginPopupModalCloseable(String id, int imGuiWindowFlags) {
if (ImGui.beginPopupModal(id, new ImBoolean(true), imGuiWindowFlags | ImGuiWindowFlags.NoSavedSettings)) {
closeableModalOnTop = true;
return true;
} else {
return false;
}
}
public static void endPopupModalCloseable() {
if (closeableModalOnTop && closeableModalOnTopLast && ReplayUI.consumeNavClose()) {
ImGui.closeCurrentPopup();
}
ImGui.endPopup();
}
public static float borderIndentation = 0;
public static void setupBorder() {
ImGui.beginGroup();
float windowPadding = ImGui.getStyle().getWindowPaddingX();
borderIndentation += windowPadding;
ImGui.indent(windowPadding);
ImGui.setCursorPosY(ImGui.getCursorPosY() + ImGui.getStyle().getWindowPaddingY());
}
public static void finishBorder() {
float windowPadding = ImGui.getStyle().getWindowPaddingX();
borderIndentation -= windowPadding;
ImGui.unindent(windowPadding);
ImGui.endGroup();
ImGui.getWindowDrawList().addRect(ImGui.getItemRectMinX(), ImGui.getItemRectMinY(),
ImGui.getItemRectMinX() + ImGui.getContentRegionAvailX(),
ImGui.getItemRectMaxY() + ImGui.getStyle().getWindowPaddingY(), ImGui.getColorU32(ImGuiCol.Separator));
ImGui.setCursorPosY(ImGui.getCursorPosY() + ImGui.getStyle().getWindowPaddingY());
}
public static float calcTextWidth(String text) {
ImVec2 textSizeVec = new ImVec2();
ImGui.calcTextSize(textSizeVec, text);
return textSizeVec.x;
}
public static void helpMarker(String message) {
ImGui.textDisabled("(?)");
tooltip(message);
}
public static void tooltip(String message) {
tooltip(message, ImGuiHoveredFlags.None);
}
public static void tooltip(String message, int imGuiHoveredFlags) {
if (ImGui.isItemHovered(imGuiHoveredFlags)) {
drawTooltip(message);
}
}
public static void drawTooltip(String message) {
ImGui.beginTooltip();
ImGui.pushTextWrapPos(ImGui.getFontSize() * 35.0f);
ImGui.textUnformatted(message);
ImGui.popTextWrapPos();
ImGui.endTooltip();
}
public static void disabledMenuItem(String label, String disabledMessage) {
ImGui.beginDisabled();
ImGui.menuItem(label);
ImGui.endDisabled();
tooltip(disabledMessage, ImGuiHoveredFlags.AllowWhenDisabled);
}
public static void separatorWithText(String text) {
float textStartX = ImGui.getCursorScreenPosX() + ImGui.getStyle().getIndentSpacing();
float size = ImGui.getWindowSizeX() - borderIndentation;
if (ImGui.isRectVisible(size, ImGui.getFontSize())) {
float textEndX = textStartX + ImGuiHelper.calcTextWidth(text);
float lineEndX = ImGui.getWindowPosX() + size;
float lineY = ImGui.getCursorScreenPosY() + ImGui.getFontSize()/2f;
ImGui.getWindowDrawList().addLine(ImGui.getCursorScreenPosX() - 4, lineY,
Math.min(lineEndX, textStartX) - 4, lineY,
ImGui.getColorU32(ImGuiCol.Separator));
if (textEndX + 4 < lineEndX) {
ImGui.getWindowDrawList().addLine(textEndX + 4, lineY,
lineEndX - 4, lineY,
ImGui.getColorU32(ImGuiCol.Separator));
}
}
ImGui.setCursorScreenPos(textStartX, ImGui.getCursorScreenPosY());
ImGui.textColored(ImGui.getColorU32(ImGuiCol.TextDisabled), text);
}
public static boolean radio(String label, int[] currentItem, String[] values) {
int item = currentItem[0];
int newItem = -1;
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (i > 0) ImGui.sameLine();
if (item == i) ImGui.beginDisabled();
if (ImGui.button(value)) newItem = i;
if (item == i) ImGui.endDisabled();
}
if (label != null) {
ImGui.sameLine();
ImGui.text(label);
}
if (newItem != -1) {
currentItem[0] = newItem;
return true;
} else {
return false;
}
}
public static int buttons(String... labels) {
if (labels.length == 0) return -1;
// Calculate widths
float[] widths = new float[labels.length];
float totalRawWidth = 0;
for (int i = 0; i < labels.length; i++) {
String label = labels[i];
float width = ImGuiHelper.calcTextWidth(label);
widths[i] = width;
totalRawWidth += width;
}
// Calculate extraPadding
float availableWidth = ImGui.getContentRegionAvailX();
float freeSpace = availableWidth - totalRawWidth - ImGui.getStyle().getItemSpacingX()*(labels.length - 1);
float extraPadding = Math.max(ImGui.getStyle().getFramePaddingX()*2, freeSpace / labels.length);
// Draw buttons
float height = ImGui.getFontSize() + ImGui.getStyle().getFramePaddingY()*2f;
int pressed = -1;
for (int i = 0; i < labels.length; i++) {
if (ImGui.button(labels[i], widths[i] + extraPadding, height)) {
pressed = i;
}
if (i != labels.length-1) ImGui.sameLine();
}
return pressed;
}
private static int pushedColors = 0;
private static int pushedStyleVars = 0;
public static void popAllStyleColors() {
ImGui.popStyleColor(pushedColors);
pushedColors = 0;
}
public static void popAllStyleVars() {
ImGui.popStyleVar(pushedStyleVars);
pushedStyleVars = 0;
}
public static void pushStyleColor(int imGuiCol, float r, float g, float b, float a) {
ImGui.pushStyleColor(imGuiCol, r, g, b, a);
pushedColors += 1;
}
public static void pushStyleColor(int imGuiCol, int r, int g, int b, int a) {
ImGui.pushStyleColor(imGuiCol, r, g, b, a);
pushedColors += 1;
}
public static void pushStyleColor(int imGuiCol, int col) {
ImGui.pushStyleColor(imGuiCol, col);
pushedColors += 1;
}
public static void popStyleColor() {
if (pushedColors >= 1) {
ImGui.popStyleColor();
pushedColors -= 1;
}
}
public static void popStyleColor(int count) {
count = Math.min(count, pushedColors);
if (count == 0) return;
ImGui.popStyleColor(count);
pushedColors -= count;
}
public static void pushStyleVar(int imGuiStyleVar, float val) {
ImGui.pushStyleVar(imGuiStyleVar, val);
pushedStyleVars += 1;
}
public static void pushStyleVar(int imGuiStyleVar, float valX, float valY) {
ImGui.pushStyleVar(imGuiStyleVar, valX, valY);
pushedStyleVars += 1;
}
public static void popStyleVar() {
if (pushedStyleVars >= 1) {
ImGui.popStyleVar();
pushedStyleVars -= 1;
}
}
public static void popStyleVar(int count) {
count = Math.min(count, pushedStyleVars);
if (count == 0) return;
ImGui.popStyleVar(count);
pushedStyleVars -= count;
}
}
@@ -0,0 +1,7 @@
package com.moulberry.flashback.editor.ui;
public class Keybinds {
}
@@ -0,0 +1,878 @@
package com.moulberry.flashback.editor.ui;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.TextureUtil;
import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.windows.MainMenuBar;
import com.moulberry.flashback.editor.ui.windows.StartExportWindow;
import com.moulberry.flashback.editor.ui.windows.TimelineWindow;
import com.moulberry.flashback.editor.ui.windows.VisualsWindow;
import imgui.*;
import imgui.flag.*;
import imgui.internal.ImGuiContext;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.ProgressScreen;
import net.minecraft.client.gui.screens.ReceivingLevelScreen;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.GameType;
import net.minecraft.world.phys.*;
import net.minecraft.world.phys.shapes.CollisionContext;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector4f;
import org.lwjgl.glfw.GLFW;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
public class ReplayUI {
public static final CustomImGuiImplGlfw imguiGlfw = new CustomImGuiImplGlfw();
private static final CustomImGuiImplGl3 imguiGl3 = new CustomImGuiImplGl3();
private static boolean initialized = false;
private static boolean isFrameHovered = false;
private static int frameX = 0;
private static int frameY = 0;
private static int frameWidth = 1;
private static int frameHeight = 1;
private static boolean activeLastFrame = false;
public static Matrix4f lastProjectionMatrix = null;
public static Quaternionf lastViewQuaternion = null;
private static ImFont font = null;
public static ImFont icons = null;
private static String languageCode = null;
private static boolean wasNavClose = false;
private static boolean navClose = false;
private static final Lock deferredCloseLock = new ReentrantLock();
private static final IntList deferredCloseTextureIds = new IntArrayList();
private static final List<AutoCloseable> deferredClose = new ArrayList<>();
private static float globalScale = 1.0f;
public static float newGlobalScale = 1.0f;
private static float contentScale = 1.0f;
private static ImGuiContext imGuiContext = null;
private static ImGuiIO imGuiIo = null;
private static boolean popupOpenLastFrame = false;
private static String infoOverlayText = null;
private static long infoOverlayStartMillis = 0;
private static int selectedEntity = Integer.MIN_VALUE;
private static boolean openSelectedEntityPopup = false;
public static void init() {
if (initialized) {
throw new IllegalStateException("ReplayUI initialized twice");
}
initialized = true;
// todo: introduce global scale option
// newGlobalScale = globalScale = Configuration.internal.globalScale;
// Initialize config so that everything starts nicely docked
Path path = Flashback.getConfigDirectory().resolve("imgui.ini");
if (!Files.exists(path)) {
try {
Files.writeString(path, ReplayUIDefaults.LAYOUT);
} catch(IOException ignored) {}
}
long oldImGuiContext = ImGui.getCurrentContext().ptr;
imGuiContext = new ImGuiContext(ImGui.createContext().ptr);
ImGui.setCurrentContext(imGuiContext);
Path relativePath = FabricLoader.getInstance().getGameDir().relativize(path);
ImGui.getIO().setIniFilename(relativePath.toString());
ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
ImGui.getIO().addConfigFlags(ImGuiConfigFlags.DockingEnable);
// ImGui.getIO().addConfigFlags(ImGuiConfigFlags.ViewportsEnable);
ImGui.getIO().setConfigMacOSXBehaviors(Minecraft.ON_OSX);
imguiGlfw.init(Minecraft.getInstance().getWindow().getWindow(), true, new ImGuiIO(ImGui.getIO().ptr));
imguiGl3.init("#version 150");
contentScale = imguiGlfw.contentScale;
initFonts(languageCode);
ReplayUIDefaults.applyStyle(ImGui.getStyle());
ImGuiContext currentContext = ImGui.getCurrentContext();
currentContext.ptr = oldImGuiContext;
ImGui.setCurrentContext(currentContext);
}
public static void initFonts(String languageCode) {
if (languageCode != null) {
ReplayUI.languageCode = languageCode;
} else {
languageCode = "en_us";
}
if (!initialized) {
return;
}
ImGuiIO io = ImGui.getIO();
ImFontAtlas fonts = io.getFonts();
fonts.clear();
int size = (int)(16 * getUiScale());
ImFontGlyphRangesBuilder rangesBuilder = new ImFontGlyphRangesBuilder();
rangesBuilder.addRanges(fonts.getGlyphRangesDefault());
if (languageCode.startsWith("uk") || languageCode.startsWith("ru") || languageCode.startsWith("bg")) {
rangesBuilder.addRanges(fonts.getGlyphRangesCyrillic());
} else if (languageCode.startsWith("tr")) {
rangesBuilder.addText("ÇçĞğİıÖöŞşÜü");
} else if (languageCode.startsWith("pl")) {
rangesBuilder.addRanges(new short[]{0x0100, 0x017F, 0});
} else if (languageCode.startsWith("cs")) {
rangesBuilder.addText("ÁáČčĎďÉéĚěÍíŇňÓóŘřŠšŤťÚúŮůÝýŽž");
}
rangesBuilder.addChar('\u2318'); // Mac CMD
rangesBuilder.addChar('\u2303'); // CTRL
rangesBuilder.addChar('\u2387'); // Alt
rangesBuilder.addChar('\u21E7'); // Shift (up arrow)
rangesBuilder.addChar('\u2756'); // Super
rangesBuilder.addChar('\u26A0'); // Warning symbol
rangesBuilder.addChar('\u2190'); // Left Arrow
rangesBuilder.addChar('\u2191'); // Up Arrow
rangesBuilder.addChar('\u2192'); // Right Arrow
rangesBuilder.addChar('\u2193'); // Down Arrow
// Make sure every printable key on the keyboard is present
for (int i = GLFW.GLFW_KEY_SPACE; i <= GLFW.GLFW_KEY_LAST; i++) {
int scancode = GLFW.glfwGetKeyScancode(i);
if (scancode != -1) {
String key = GLFW.glfwGetKeyName(i, -1);
if (key != null) {
rangesBuilder.addText(key);
rangesBuilder.addText(key.toLowerCase());
rangesBuilder.addText(key.toUpperCase());
rangesBuilder.addText(key.toLowerCase(Locale.ROOT));
rangesBuilder.addText(key.toUpperCase(Locale.ROOT));
}
}
}
short[] glyphRanges = rangesBuilder.buildRanges();
// Font config for additional fonts
final ImFontConfig fontConfig = new ImFontConfig();
fontConfig.setOversampleH(2);
fontConfig.setOversampleV(2);
fontConfig.setName("Inter (Medium), 16px");
font = fonts.addFontFromMemoryTTF(loadFont("inter-medium.ttf"), size, fontConfig, glyphRanges);
// Merge in Japanese/Korean/Chinese/etc. characters if needed
fontConfig.setMergeMode(true);
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);
} else if (languageCode.startsWith("ja")) {
io.getFonts().addFontFromMemoryTTF(loadFont("notosansjp-medium.ttf"), size,
fontConfig, GlyphRanges.getJapaneseRanges());
} else if (languageCode.startsWith("zh")) {
io.getFonts().addFontFromMemoryTTF(loadFont("notosanssc-medium.otf"), size,
fontConfig, GlyphRanges.getChineseFullRanges());
io.getFonts().addFontFromMemoryTTF(loadFont("notosanstc-medium.otf"), size,
fontConfig, GlyphRanges.getChineseFullRanges());
}
fontConfig.setMergeMode(false);
fonts.build();
imguiGl3.updateFontsTexture();
fontConfig.destroy();
fonts.clearTexData();
}
private static byte[] loadFont(String name) {
try {
var resource = Minecraft.getInstance().getResourceManager().getResource(Flashback.createResourceLocation(name));
if (resource.isEmpty()) throw new MissingResourceException("Missing font: " + name, "Font", "");
try (InputStream is = resource.get().open()) {
return is.readAllBytes();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Vec3 getMouseForwardsVector() {
return getMouseForwardsVector(ImGui.getMousePosX(), ImGui.getMousePosY());
}
public static Vec3 getMouseForwardsVector(float mouseX, float mouseY) {
if (!isActive() || (!isFrameHovered && !isMovingCamera()) || lastProjectionMatrix == null || lastViewQuaternion == null) return null;
return getForwardsVector(mouseX, mouseY);
}
public static Vec2 getMouseViewportFraction() {
float x = (ImGui.getMousePosX() - ImGui.getMainViewport().getPosX() - frameX) / frameWidth;
float y = (ImGui.getMousePosY() - ImGui.getMainViewport().getPosY() - frameY) / frameHeight;
return new Vec2(x, y);
}
public static Vec2 getMouseViewportFraction(float mouseX, float mouseY) {
float x = (mouseX - ImGui.getMainViewport().getPosX() - frameX) / frameWidth;
float y = (mouseY - ImGui.getMainViewport().getPosY() - frameY) / frameHeight;
return new Vec2(x, y);
}
public static Vec3 getForwardsVector(float mouseX, float mouseY) {
float x = (mouseX - ImGui.getMainViewport().getPosX() - frameX) / frameWidth * 2 - 1;
float y = (mouseY - ImGui.getMainViewport().getPosY() - frameY) / frameHeight * 2 - 1;
return getForwardsVectorRaw(x, y);
}
public static Vec3 getForwardsVectorRaw(float x, float y) {
if (!isMovingCamera() && (x < -1 || x > 1 || y < -1 || y > 1)) return null;
var matrix = new Matrix4f(lastProjectionMatrix);
matrix.invert();
// Apply inverse projection matrix to get forwards vector
var forwards = new Vector4f(x, y, 0f, 1f);
forwards.mul(matrix);
// Negate and normalize to match MC coordinate space
return new Vec3(forwards.x(), -forwards.y(), forwards.z()).normalize();
}
@Nullable
public static Vec3 getMouseLookVectorFromForwards(Vec3 forwards) {
if (forwards == null) return null;
// Apply the view quaternion to forwards vector to get view vector
var view = forwards.toVector3f();
view.rotate(lastViewQuaternion);
return new Vec3(view.x(), view.y(), view.z()).normalize();
}
@Nullable
public static Vec3 getMouseLookVector(float mouseX, float mouseY) {
return getMouseLookVectorFromForwards(getMouseForwardsVector(mouseX, mouseY));
}
@Nullable
public static Vec3 getMouseLookVector() {
return getMouseLookVectorFromForwards(getMouseForwardsVector());
}
public static boolean isEntitySelected(int entityId) {
return isActive() && selectedEntity == entityId;
}
public static boolean isMovingCamera() {
return imguiGlfw.isGrabbed() && imguiGlfw.getMouseHandledBy() == CustomImGuiImplGlfw.MouseHandledBy.GAME;
}
public static void setInfoOverlay(String text) {
infoOverlayText = text;
infoOverlayStartMillis = System.currentTimeMillis();
}
public static void setupMainViewport() {
var window = Minecraft.getInstance().getWindow();
int frameBottom = window.height - (frameY + frameHeight);
GlStateManager._viewport(frameX * window.getWidth() / window.getScreenWidth(),
frameBottom * window.getHeight() / window.getScreenHeight(),
Math.max(1, frameWidth * window.getWidth() / window.getScreenWidth()),
Math.max(1, frameHeight * window.getHeight() / window.getScreenHeight()));
}
public static float getUiScale() {
return globalScale * contentScale;
}
public static double getNewMouseX(double x) {
return x - frameX;
}
public static double getNewMouseY(double y) {
return y - frameY;
}
public static int getNewGameWidth(float scale) {
return Math.max(1, Math.round(frameWidth * scale));
}
public static int getNewGameHeight(float scale) {
return Math.max(1, Math.round(frameHeight * scale));
}
private static boolean isActiveInternal() {
if (!Flashback.isInReplay()) {
return false;
}
if (Flashback.EXPORT_JOB != null) {
return false;
}
if (Minecraft.getInstance().options.hideGui) {
return false;
}
MultiPlayerGameMode gameMode = Minecraft.getInstance().gameMode;
if (gameMode == null) return false;
if (gameMode.getPlayerMode() != GameType.SPECTATOR) return false;
if (Minecraft.getInstance().level == null) return false;
if (Minecraft.getInstance().player == null) return false;
if (Minecraft.getInstance().getOverlay() != null) return false;
return true;
}
public static void deferredCloseTextureId(int textureId) {
deferredCloseLock.lock();
try {
deferredCloseTextureIds.add(textureId);
} finally {
deferredCloseLock.unlock();
}
}
public static void deferredClose(AutoCloseable autoCloseable) {
deferredCloseLock.lock();
try {
deferredClose.add(autoCloseable);
} finally {
deferredCloseLock.unlock();
}
}
public static boolean isActive() {
return activeLastFrame;
}
private static void transitionActiveState(boolean active) {
if (activeLastFrame == active) return;
activeLastFrame = active;
// Recalculate the size of the gameplay window
Window window = Minecraft.getInstance().getWindow();
if (window.getWidth() > 0 && window.getWidth() <= 32768 && window.getHeight() > 0 && window.getHeight() <= 32768) {
Minecraft.getInstance().resizeDisplay();
}
imguiGlfw.ungrab();
if (!activeLastFrame) {
// Make sure the vanilla grab state is correct
if (Minecraft.getInstance().gameMode != null) {
if (Minecraft.getInstance().screen == null) {
Minecraft.getInstance().mouseHandler.releaseMouse();
Minecraft.getInstance().mouseHandler.grabMouse();
} else {
Minecraft.getInstance().mouseHandler.grabMouse();
Minecraft.getInstance().mouseHandler.releaseMouse();
}
Minecraft.getInstance().mouseHandler.setIgnoreFirstMove();
}
} else {
// Forcefully ungrab the cursor
long handle = ImGui.getMainViewport().getPlatformHandle();
if (GLFW.glfwGetInputMode(handle, GLFW.GLFW_CURSOR) != GLFW.GLFW_CURSOR_NORMAL) {
GLFW.glfwSetInputMode(handle, GLFW.GLFW_CURSOR, GLFW.GLFW_CURSOR_NORMAL);
GLFW.glfwSetCursorPos(handle, ImGui.getMainViewport().getSizeX()/2f, ImGui.getMainViewport().getSizeY()/2f);
}
}
imguiGlfw.setViewportWindowsHidden(!activeLastFrame);
}
public static void drawOverlay() {
long oldImGuiContext = ImGui.getCurrentContext().ptr;
ImGui.setCurrentContext(imGuiContext);
try {
drawOverlayInternal();
} finally {
ImGuiContext currentContext = ImGui.getCurrentContext();
currentContext.ptr = oldImGuiContext;
ImGui.setCurrentContext(currentContext);
}
}
public static void drawOverlayInternal() {
int oldFrameX = frameX;
int oldFrameY = frameY;
int oldFrameWidth = frameWidth;
int oldFrameHeight = frameHeight;
if (!initialized) {
throw new IllegalStateException("Tried to use EditorUI while it was not initialized");
}
deferredCloseLock.lock();
try {
for (int id : deferredCloseTextureIds) {
TextureUtil.releaseTextureId(id);
}
deferredCloseTextureIds.clear();
for (AutoCloseable closeable : deferredClose) {
try {
closeable.close();
} catch (Exception e) {}
}
deferredClose.clear();
} finally {
deferredCloseLock.unlock();
}
if (Minecraft.getInstance().screen instanceof ProgressScreen || Minecraft.getInstance().screen instanceof ReceivingLevelScreen) {
return;
}
if (!isActiveInternal()) {
transitionActiveState(false);
imguiGlfw.updateReleaseAllKeys(true);
return;
} else {
imguiGlfw.updateReleaseAllKeys(false);
}
if (!ImGui.isAnyMouseDown()) {
newGlobalScale = ((int)(newGlobalScale * 16))/16f;
if (newGlobalScale < 0.25) newGlobalScale = 0.25f;
if (newGlobalScale > 4) newGlobalScale = 4f;
float newContentScale = ((int)(imguiGlfw.contentScale * 16))/16f;
if (newContentScale < 0.125) newContentScale = 0.125f;
if (newContentScale > 8) newContentScale = 8f;
if (globalScale != newGlobalScale || contentScale != newContentScale) {
int oldFontSize = (int)(16 * getUiScale());
globalScale = newGlobalScale;
contentScale = newContentScale;
if (oldFontSize != (int)(16 * getUiScale())) {
initFonts(languageCode);
}
}
}
imguiGlfw.newFrame();
ImGui.newFrame();
navClose = ImGui.getIO().getNavInputs(ImGuiNavInput.Cancel) != 0;
if (wasNavClose != navClose) {
wasNavClose = navClose;
} else if (wasNavClose) {
navClose = false;
}
if (ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) {
ImGui.getIO().addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
} else {
ImGui.getIO().removeConfigFlags(ImGuiConfigFlags.NavEnableKeyboard);
}
char controlIcon = Minecraft.ON_OSX ? '\u2318' : '\u2303';
MainMenuBar.render();
// Setup docking
ImGui.setNextWindowBgAlpha(0);
int mainDock = ImGui.dockSpaceOverViewport(ImGui.getMainViewport(), ImGuiDockNodeFlags.NoDockingInCentralNode);
imgui.internal.ImGui.dockBuilderGetCentralNode(mainDock).addLocalFlags(imgui.internal.flag.ImGuiDockNodeFlags.NoTabBar);
isFrameHovered = false;
ImGui.setNextWindowDockID(mainDock);
ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowPadding, 0, 0);
boolean fireCancelNavInput = false;
if (ImGui.begin("Main", ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoNavInputs | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoSavedSettings)) {
ImGuiHelper.popStyleVar();
float minX = ImGui.getWindowContentRegionMinX();
float maxX = ImGui.getWindowContentRegionMaxX();
float minY = ImGui.getWindowContentRegionMinY();
float maxY = ImGui.getWindowContentRegionMaxY();
if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {
frameX = (int) (ImGui.getWindowPosX() - ImGui.getWindowViewport().getPosX() + minX);
frameY = (int) (ImGui.getWindowPosY() - ImGui.getWindowViewport().getPosY() + minY);
} else {
frameX = (int) (ImGui.getWindowPosX() + minX);
frameY = (int) (ImGui.getWindowPosY() + minY);
}
frameWidth = (int) Math.max(1, maxX - minX);
frameHeight = (int) Math.max(1, maxY - minY);
if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO || ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) {
float aspectRatio;
if (ReplayVisuals.sizing == Sizing.KEEP_ASPECT_RATIO) {
aspectRatio = ImGui.getMainViewport().getSizeX() / ImGui.getMainViewport().getSizeY();
} else {
aspectRatio = ReplayVisuals.changeAspectRatio.aspectRatio();
}
float currentAspectRatio = frameWidth / (float) frameHeight;
if (currentAspectRatio < aspectRatio) {
int newHeight = (int)(frameWidth / aspectRatio);
frameY += (frameHeight - newHeight)/2;
frameHeight = newHeight;
} else if (currentAspectRatio > aspectRatio) {
int newWidth = (int)(frameHeight * aspectRatio);
frameX += (frameWidth - newWidth)/2;
frameWidth = newWidth;
}
}
if (infoOverlayText != null) {
long currentMillis = System.currentTimeMillis();
if (currentMillis < infoOverlayStartMillis || currentMillis > infoOverlayStartMillis + 5000) {
infoOverlayText = null;
} else {
ImGui.setNextWindowPos(frameX + frameWidth*0.5f, frameY + frameHeight*0.75f, ImGuiCond.Always, 0.5f, 0.5f);
ImGui.setNextWindowSizeConstraints(0, 0, 550, frameHeight*0.45f);
ImGuiHelper.pushStyleVar(ImGuiStyleVar.WindowBorderSize, 2);
ImGuiHelper.pushStyleColor(ImGuiCol.Border, 0xFF00FFFF);
if (ImGui.begin("##InfoOverlay", ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoFocusOnAppearing |
ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoCollapse |
ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoSavedSettings)) {
ImGui.text(infoOverlayText);
}
ImGui.end();
ImGuiHelper.popStyleColor();
ImGuiHelper.popStyleVar();
}
}
if (ReplayVisuals.sizing == Sizing.UNDERLAY) {
frameX = 0;
frameY = 0;
frameWidth = Minecraft.getInstance().getWindow().getScreenWidth();
frameHeight = Minecraft.getInstance().getWindow().getScreenHeight();
}
if (frameX != oldFrameX || frameY != oldFrameY || frameWidth != oldFrameWidth || frameHeight != oldFrameHeight) {
Minecraft.getInstance().resizeDisplay();
}
if (ReplayVisuals.ruleOfThirdsGuide) {
ImDrawList drawList = ImGui.getForegroundDrawList();
drawList.addLine(frameX + frameWidth/3, frameY, frameX + frameWidth/3, frameY+frameHeight, -1, 2);
drawList.addLine(frameX + frameWidth*2/3, frameY, frameX + frameWidth*2/3, frameY+frameHeight, -1, 2);
drawList.addLine(frameX, frameY + frameHeight/3, frameX + frameWidth, frameY + frameHeight/3, -1, 2);
drawList.addLine(frameX, frameY + frameHeight*2/3, frameX + frameWidth, frameY + frameHeight*2/3, -1, 2);
}
if (ReplayVisuals.centerGuide) {
ImDrawList drawList = ImGui.getForegroundDrawList();
drawList.addLine(frameX + frameWidth/2, frameY, frameX + frameWidth/2, frameY+frameHeight, -1, 2);
drawList.addLine(frameX, frameY + frameHeight/2, frameX + frameWidth, frameY + frameHeight/2, -1, 2);
}
if (selectedEntity != Integer.MIN_VALUE) {
Entity entity = Minecraft.getInstance().level.getEntity(selectedEntity);
if (entity == null) {
selectedEntity = Integer.MIN_VALUE;
} else if (entity instanceof Player && !ReplayVisuals.renderPlayers) {
selectedEntity = Integer.MIN_VALUE;
} else if (!(entity instanceof Player) && !ReplayVisuals.renderEntities) {
selectedEntity = Integer.MIN_VALUE;
} else {
if (openSelectedEntityPopup) {
ImGui.openPopup("###EntityPopup");
}
if (ImGuiHelper.beginPopup("###EntityPopup")) {
ImGui.text("Entity: " + entity.getUUID());
ImGui.separator();
if (ImGui.button("Look At")) {
Minecraft.getInstance().cameraEntity.lookAt(EntityAnchorArgument.Anchor.EYES, entity.getEyePosition());
}
// todo: need to remember spectate target when a snapshot is played
// if (ImGui.button("Spectate")) {
// Minecraft.getInstance().player.connection.sendUnsignedCommand("spectate " + entity.getUUID());
// }
// ImGui.sameLine();
// ImGui.button("Track Entity");
//
// ImGui.checkbox("Hide During Export", false);
//
// ImGui.checkbox("Force Glowing", false);
// ImGui.sameLine();
// ImGui.colorButton("Glow Colour", new float[4]);
// ImGui.sameLine();
// ImGui.text("Glow Colour");
//
// if (entity instanceof LivingEntity) {
// ImGui.checkbox("Show Nametag", true);
// ImGui.checkbox("Override Nametag", false);
// }
// if (entity instanceof Player) {
// ImGui.checkbox("Override Skin", false);
// }
ImGui.endPopup();
}
if (!ImGui.isPopupOpen("###EntityPopup")) {
selectedEntity = Integer.MIN_VALUE;
}
}
}
openSelectedEntityPopup = false;
if (ImGui.isWindowHovered() && ImGui.getMousePosY() > ImGui.getWindowPosY()) {
isFrameHovered = true;
if (Minecraft.getInstance().screen != null) {
ImGui.captureMouseFromApp(false);
} else if (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 * 5.0f);
setInfoOverlay(String.format("Flying Speed: %.1f", flyingSpeed / defaultFlyingSpeed));
player.getAbilities().setFlyingSpeed(flyingSpeed);
}
}
} else if (ImGui.getIO().getWantCaptureMouse() && !popupOpenLastFrame && !ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup)) {
fireCancelNavInput |= handleBasicInputs();
}
}
} else {
ImGuiHelper.popStyleVar();
}
ImGui.end();
VisualsWindow.render();
TimelineWindow.render();
StartExportWindow.render();
popupOpenLastFrame = ImGui.isPopupOpen("", ImGuiPopupFlags.AnyPopup);
ImGui.render();
ImGuiHelper.endFrame();
if (fireCancelNavInput) {
ImGui.getIO().setNavInputs(ImGuiNavInput.Input, 1.0f);
ImGui.getIO().setNavInputs(ImGuiNavInput.Cancel, 1.0f);
}
long ctx = GLFW.glfwGetCurrentContext();
ImGui.updatePlatformWindows();
ImGui.renderPlatformWindowsDefault();
GLFW.glfwMakeContextCurrent(ctx);
var drawData = ImGui.getDrawData();
if (drawData != null) {
imguiGl3.renderDrawData(drawData);
}
transitionActiveState(true);
}
public static boolean isMainFrameHovered() {
return isFrameHovered;
}
private static boolean handleBasicInputs() {
// if (ImGui.isMouseClicked(ImGuiMouseButton.Left) && UserAction.LEFT_MOUSE.call(null) == UserAction.ActionResult.USED_STOP) {
// return true;
// }
if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_RIGHT)) {
HitResult result = getLookTarget();
if (result instanceof EntityHitResult entityHitResult) {
if (Minecraft.getInstance().player == Minecraft.getInstance().cameraEntity) {
Minecraft.getInstance().player.setDeltaMovement(Vec3.ZERO);
}
selectedEntity = entityHitResult.getEntity().getId();
openSelectedEntityPopup = true;
}
return true;
}
if (ImGui.isMouseClicked(GLFW.GLFW_MOUSE_BUTTON_LEFT)) {
int key = -GLFW.GLFW_MOUSE_BUTTON_LEFT-1;
if (key != 0) {
imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f);
}
return true;
}
// if (Keybinds.ADJUST_RADIUS.isPressed(false)) {
// if (ToolManager.isToolActive() && ToolManager.getCurrentTool().initiateAdjustment()) {
// int key = Keybinds.ADJUST_RADIUS.getKey();
// if (key != 0) {
// imguiGlfw.setGrabbed(false, key, -1, -1);
// }
//
// adjustingTool = true;
// adjustingToolOffsetX = 0;
// adjustingToolOffsetY = 0;
//
// return true;
// }
// } else if (Keybinds.ROTATE_CAMERA.isPressed(false)) {
// movementControls = EditorMovementControls.rotate();
// return true;
// } else if (Keybinds.PICK_BLOCK.isPressed(false)) {
// RayCaster.RaycastResult result = Tool.raycastBlock();
// if (result != null) {
// BlockState blockState = Minecraft.getInstance().level.getBlockState(result.blockPos());
// CustomBlockState customBlockState = ServerCustomBlocks.getCustomStateFor(blockState);
// activeBlockHistory.setActive(Objects.requireNonNullElse(customBlockState, (CustomBlockState) blockState));
// return true;
// }
// } else if (Keybinds.USE_TOOL.isPressed(false)) {
// if (UserAction.RIGHT_MOUSE.call(null) != UserAction.ActionResult.NOT_HANDLED || ToolManager.isToolActive()) {
// return true;
// }
// } else if (Keybinds.ARCBALL_CAMERA.isPressed(false)) {
// Tool currentTool = ToolManager.isToolActive() ? ToolManager.getCurrentTool() : null;
// if (currentTool instanceof RulerTool || currentTool instanceof ModifyTool || Configuration.keybind.useCenterOfScreenForArcball) {
// movementControls = EditorMovementControls.arcballFromRaycast();
// if (movementControls != EditorMovementControls.none()) {
// int key = Keybinds.ARCBALL_CAMERA.getKey();
// if (key != 0) {
// imguiGlfw.setGrabbed(false, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f);
// }
// return true;
// }
// } else {
// pendingDepthActions.add(PendingDepthAction.ARCBALL);
// return true;
// }
// } else if (Keybinds.PAN_CAMERA.isPressed(false)) {
// movementControls = EditorMovementControls.pan();
// return true;
// }
// if (Keybinds.CROSSHAIR_CAMERA.isPressed(false)) {
// int key = Keybinds.CROSSHAIR_CAMERA.getKey();
// if (key != 0) {
// imguiGlfw.setGrabbed(true, key, frameX + frameWidth / 2f, frameY + frameHeight / 2f);
// }
// return true;
// }
return false;
}
@Nullable
private static HitResult getLookTarget() {
Vec3 look = getMouseLookVector();
if (look == null) {
return null;
}
Entity cameraEntity = Minecraft.getInstance().cameraEntity;
if (cameraEntity == null) {
return null;
}
float distance = 64f;
Vec3 from = cameraEntity.getEyePosition();
Vec3 to = from.add(look.scale(distance));
BlockHitResult blockResult = null;
EntityHitResult entityResult = null;
if (ReplayVisuals.renderBlocks) {
ClipContext clipContext = new ClipContext(from, to, ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, CollisionContext.empty());
blockResult = Minecraft.getInstance().level.clip(clipContext);
if (blockResult.getType() != HitResult.Type.MISS) {
distance = (float) blockResult.getLocation().distanceTo(from);
}
}
if (ReplayVisuals.renderEntities || ReplayVisuals.renderPlayers) {
AABB boundingBox = new AABB(from.subtract(0.5f, 0.5f, 0.5f), from.add(0.5f, 0.5f, 0.5f));
boundingBox = boundingBox.expandTowards(look.scale(distance));
Predicate<Entity> predicate;
if (ReplayVisuals.renderEntities && ReplayVisuals.renderPlayers) {
predicate = entity -> true;
} else if (ReplayVisuals.renderPlayers) {
predicate = entity -> entity instanceof Player;
} else if (ReplayVisuals.renderEntities) {
predicate = entity -> !(entity instanceof Player);
} else {
throw new IllegalStateException();
}
entityResult = ProjectileUtil.getEntityHitResult(cameraEntity, from, from.add(look.scale(distance)),
boundingBox, predicate, distance*distance);
}
if (entityResult != null && entityResult.getLocation().distanceTo(from) < distance) {
return entityResult;
} else if (blockResult != null && blockResult.getType() != HitResult.Type.MISS) {
return blockResult;
} else {
return null;
}
}
public static boolean consumeNavClose() {
boolean navClose = ReplayUI.navClose;
ReplayUI.navClose = false;
return navClose;
}
public static boolean isMoveQuickDown() {
return ImGui.isKeyDown(Minecraft.getInstance().options.keySprint.key.getValue());
}
public static boolean isCtrlOrCmdDown() {
return Minecraft.ON_OSX ? ImGui.getIO().getKeySuper() : ImGui.getIO().getKeyCtrl();
}
}
@@ -0,0 +1,113 @@
package com.moulberry.flashback.editor.ui;
import imgui.ImGui;
import imgui.ImGuiStyle;
import imgui.flag.ImGuiCol;
import net.minecraft.client.Minecraft;
import net.minecraft.util.FastColor;
import org.lwjgl.glfw.GLFW;
public class ReplayUIDefaults {
public static final String LAYOUT = """
[Window][Timeline]
Pos=0,830
Size=1920,250
Collapsed=0
DockId=0x00000002,0
[Window][Visuals]
Pos=1670,0
Size=250,830
Collapsed=0
DockId=0x00000004,0
[Docking][Data]
DockSpace ID=0x8B93E3BD Window=0xA787BDB4 Pos=0,22 Size=1920,1080 Split=Y Selected=0x1F1A625A
DockNode ID=0x00000001 Parent=0x8B93E3BD SizeRef=1920,830 Split=X Selected=0x1F1A625A
DockNode ID=0x00000003 Parent=0x00000001 SizeRef=1670,830 CentralNode=1 NoTabBar=1 Selected=0x1F1A625A
DockNode ID=0x00000004 Parent=0x00000001 SizeRef=250,830 Selected=0x595032EA
DockNode ID=0x00000002 Parent=0x8B93E3BD SizeRef=1920,250 Selected=0xBF88A430
""";
public static void applyStyle(ImGuiStyle style) {
ImGui.styleColorsDark(style);
// for (int i = 0; i < ImGuiCol.COUNT; i++) {
// style.setColor(i, 0xFF0000FF);
// }
style.setColor(ImGuiCol.Text, 0xFFFFFFFF);
style.setColor(ImGuiCol.TextDisabled, 0xFFAAAAAA);
style.setColor(ImGuiCol.Separator, 0xFFAAAAAA);
int windowBg = 0xCC282020;
style.setColor(ImGuiCol.WindowBg, windowBg);
style.setColor(ImGuiCol.Border, brighten(windowBg, 150));
int titleBg = 0xFF1b1515;
style.setColor(ImGuiCol.TitleBg, titleBg);
style.setColor(ImGuiCol.TitleBgActive, brighten(titleBg, 140));
int popupBg = 0xFF382828;
style.setColor(ImGuiCol.PopupBg, popupBg);
int frameBg = 0xAA3F3838;
style.setColor(ImGuiCol.FrameBg, frameBg);
style.setColor(ImGuiCol.FrameBgActive, darken(frameBg));
style.setColor(ImGuiCol.FrameBgHovered, brighten(frameBg));
int button = 0xFFCB6800;
style.setColor(ImGuiCol.Button, button);
style.setColor(ImGuiCol.ButtonActive, darken(button));
style.setColor(ImGuiCol.ButtonHovered, brighten(button));
style.setColor(ImGuiCol.CheckMark, 0xFFFB8800);
int header = 0x80BB5F00;
style.setColor(ImGuiCol.Header, header);
style.setColor(ImGuiCol.HeaderActive, darken(header));
style.setColor(ImGuiCol.HeaderHovered, brighten(header));
style.setColor(ImGuiCol.MenuBarBg, windowBg);
style.setColor(ImGuiCol.TabUnfocusedActive, 0xCC383030);
style.setColor(ImGuiCol.TabActive, 0xFF484040);
style.setColor(ImGuiCol.ModalWindowDimBg, 0x58CCCCCC);
if (GLFW.glfwGetKey(Minecraft.getInstance().getWindow().getWindow(), GLFW.GLFW_KEY_K) != 0) {
ImGui.styleColorsDark(style);
}
}
private static int brighten(int abgr) {
return brighten(abgr, 120);
}
private static int brighten(int abgr, int percentage) {
int alpha = (abgr >> 24) & 0xFF;
int blue = (abgr >> 16) & 0xFF;
int green = (abgr >> 8) & 0xFF;
int red = abgr & 0xFF;
blue = Math.min(0xFF, blue * percentage/100);
green = Math.min(0xFF, green * percentage/100);
red = Math.min(0xFF, red * percentage/100);
return FastColor.ABGR32.color(alpha, blue, green, red);
}
private static int darken(int abgr) {
int alpha = (abgr >> 24) & 0xFF;
int blue = (abgr >> 16) & 0xFF;
int green = (abgr >> 8) & 0xFF;
int red = abgr & 0xFF;
blue = Math.min(0xFF, blue * 4/5);
green = Math.min(0xFF, green * 4/5);
red = Math.min(0xFF, red * 4/5);
return FastColor.ABGR32.color(alpha, blue, green, red);
}
}
@@ -0,0 +1,17 @@
package com.moulberry.flashback.editor.ui.windows;
import imgui.ImGui;
public class MainMenuBar {
public static void render() {
if (ImGui.beginMainMenuBar()) {
if (ImGui.menuItem("Export")) {
StartExportWindow.open();
}
ImGui.endMainMenuBar();
}
}
}
@@ -0,0 +1,232 @@
package com.moulberry.flashback.editor.ui.windows;
import com.mojang.blaze3d.platform.Window;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.combo_options.VideoCodec;
import com.moulberry.flashback.combo_options.VideoContainer;
import com.moulberry.flashback.combo_options.VideoPreset;
import com.moulberry.flashback.state.EditorState;
import com.moulberry.flashback.state.EditorStateCache;
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.playback.ReplayServer;
import imgui.ImGui;
import imgui.flag.ImGuiWindowFlags;
import imgui.type.ImFloat;
import imgui.type.ImString;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import java.nio.file.Path;
import java.util.List;
public class StartExportWindow {
private static boolean open = false;
private static final int[] lastFramebufferSize = new int[]{0, 0};
private static final int[] resolution = new int[]{1920, 1080};
private static final int[] startEndTick = new int[]{0, 100};
private static final ImFloat framerate = new ImFloat(60);
private static VideoContainer container = VideoContainer.MP4;
private static VideoCodec codec = VideoCodec.H264;
private static VideoPreset preset = VideoPreset.MEDIUM;
private static int[] selectedEncoder = new int[]{0};
private static boolean useMaximumBitrate = false;
private static final ImString bitrate = ImGuiHelper.createResizableImString("20m");
static {
bitrate.inputData.allowedChars = "0123456789kmb";
}
public static void render() {
if (open) {
ImGui.openPopup("###StartExport");
Window window = Minecraft.getInstance().getWindow();
// Only update the resolution if the framebuffer size changes
// This way, when users input custom resolutions it persists between opens
if (window.framebufferWidth != lastFramebufferSize[0] || window.framebufferHeight != lastFramebufferSize[1]) {
resolution[0] = window.framebufferWidth;
resolution[1] = window.framebufferHeight;
lastFramebufferSize[0] = window.framebufferWidth;
lastFramebufferSize[1] = window.framebufferHeight;
}
open = false;
}
if (ImGuiHelper.beginPopupModalCloseable("Export to video###StartExport", ImGuiWindowFlags.AlwaysAutoResize)) {
ImGuiHelper.separatorWithText("Capture Options");
ImGui.inputInt2("Resolution", resolution);
if (ImGui.inputInt2("Start/end tick", startEndTick)) {
EditorState editorState = EditorStateCache.getCurrent();
ReplayServer replayServer = Flashback.getReplayServer();
if (editorState != null && replayServer != null) {
editorState.setExportTicks(startEndTick[0], startEndTick[1], replayServer.getTotalReplayTicks());
}
}
ImGui.inputFloat("Framerate", framerate);
ImGuiHelper.separatorWithText("Video Options");
VideoContainer newContainer = ImGuiHelper.enumCombo("Container", container);
if (newContainer != container) {
container = newContainer;
boolean supported = false;
for (VideoCodec supportedCodec : container.getSupportedCodecs()) {
if (codec == supportedCodec) {
supported = true;
break;
}
}
if (!supported) {
codec = container.getSupportedCodecs()[0];
}
}
VideoCodec newCodec = ImGuiHelper.enumCombo("Codec", codec, container.getSupportedCodecs());
if (newCodec != codec) {
codec = newCodec;
selectedEncoder[0] = 0;
}
String[] encoders = codec.getEncoders();
if (encoders.length > 1) {
ImGuiHelper.combo("Encoder", selectedEncoder, encoders);
}
// VideoPreset newPreset = ImGuiHelper.enumCombo("Preset", preset);
// if (newPreset != preset) {
// preset = newPreset;
//
// useMaximumBitrate = false;
// if (preset.ordinal() <= VideoPreset.SUPERFAST.ordinal()) {
// bitrate.set("5m");
// } else if (preset.ordinal() <= VideoPreset.MEDIUM.ordinal()) {
// bitrate.set("10m");
// } else {
// bitrate.set("20m");
// }
// }
if (ImGui.checkbox("Use Maximum Bitrate", useMaximumBitrate)) {
useMaximumBitrate = !useMaximumBitrate;
}
if (!useMaximumBitrate) {
ImGui.inputText("Bitrate", bitrate);
if (ImGui.isItemDeactivatedAfterEdit()) {
int numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
bitrate.set(bitrateToString(numBitrate));
}
}
if (ImGui.button("Begin")) {
int numBitrate;
if (useMaximumBitrate) {
numBitrate = 0;
} else {
numBitrate = stringToBitrate(ImGuiHelper.getString(bitrate));
}
String encoder = codec.getEncoders()[selectedEncoder[0]];
Path defaultExportPath = FabricLoader.getInstance().getGameDir();
String defaultExportPathString = defaultExportPath.toString();
AsyncFileDialogs.saveFileDialog(defaultExportPathString, "output." + container.extension(),
container.extension(), container.extension()).thenAccept(pathStr -> {
if (pathStr != null) {
int start = Math.max(0, startEndTick[0]);
int end = Math.max(start, startEndTick[1]);
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer != null) {
int totalTicks = replayServer.getTotalReplayTicks();
start = Math.min(start, totalTicks);
end = Math.min(end, totalTicks);
}
Path path = Path.of(pathStr);
ExportSettings settings = new ExportSettings(resolution[0], resolution[1], start, end,
Math.max(1, framerate.get()), container, codec, encoder, numBitrate, path);
Flashback.EXPORT_JOB = new ExportJob(settings);
}
});
ImGui.closeCurrentPopup();
}
ImGuiHelper.endPopupModalCloseable();
}
}
private static int stringToBitrate(String string) {
int number = 0;
int modifier = 1;
int total = 0;
for (char c : string.toCharArray()) {
if (c >= '0' && c <= '9') {
if (modifier > 1) {
total += number * modifier;
number = 0;
modifier = 1;
}
number *= 10;
number += c - '0';
} else if (c == 'k') {
modifier *= 1000;
} else if (c == 'm') {
modifier *= 1000000;
} else if (c == 'b') {
modifier *= 1000000000;
}
}
total += number * modifier;
return total;
}
private static String bitrateToString(int bitrate) {
if (bitrate >= 1000000000 && bitrate == (bitrate/1000000000)*1000000000) {
return (bitrate/1000000000) + "b";
} else if (bitrate >= 1000000 && bitrate == (bitrate/1000000)*1000000) {
return (bitrate/1000000) + "m";
} else if (bitrate >= 1000 && bitrate == (bitrate/1000)*1000) {
return (bitrate/1000) + "k";
} else {
return String.valueOf(bitrate);
}
}
public static void open() {
open = true;
EditorState editorState = EditorStateCache.getCurrent();
if (editorState != null && editorState.exportStartTicks >= 0) {
startEndTick[0] = editorState.exportStartTicks;
} else {
startEndTick[0] = 0;
}
if (editorState != null && editorState.exportEndTicks >= 0) {
startEndTick[1] = editorState.exportEndTicks;
} else {
ReplayServer replayServer = Flashback.getReplayServer();
if (replayServer == null) {
startEndTick[1] = startEndTick[0] + 100;
} else {
startEndTick[1] = replayServer.getTotalReplayTicks();
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.ReplayVisuals;
import com.moulberry.flashback.combo_options.Sizing;
import com.moulberry.flashback.editor.ui.ImGuiHelper;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
public class VisualsWindow {
private static final float[] floatBuffer = new float[]{0};
private static final int[] intBuffer = new int[]{0};
public static void render() {
if (ImGui.begin("Visuals")) {
ImGuiHelper.separatorWithText("GUI");
if (ImGui.checkbox("Chat", ReplayVisuals.showChat)) {
ReplayVisuals.showChat = !ReplayVisuals.showChat;
}
if (ImGui.checkbox("Boss Bar", ReplayVisuals.showBossBar)) {
ReplayVisuals.showBossBar = !ReplayVisuals.showBossBar;
}
if (ImGui.checkbox("Title Text", ReplayVisuals.showTitleText)) {
ReplayVisuals.showTitleText = !ReplayVisuals.showTitleText;
}
if (ImGui.checkbox("Scoreboard", ReplayVisuals.showScoreboard)) {
ReplayVisuals.showScoreboard = !ReplayVisuals.showScoreboard;
}
if (ImGui.checkbox("Action Bar", ReplayVisuals.showActionBar)) {
ReplayVisuals.showActionBar = !ReplayVisuals.showActionBar;
}
ImGuiHelper.separatorWithText("World");
if (ImGui.checkbox("Render Blocks", ReplayVisuals.renderBlocks)) {
ReplayVisuals.renderBlocks = !ReplayVisuals.renderBlocks;
}
if (ImGui.checkbox("Render Entities", ReplayVisuals.renderEntities)) {
ReplayVisuals.renderEntities = !ReplayVisuals.renderEntities;
}
if (ImGui.checkbox("Render Players", ReplayVisuals.renderPlayers)) {
ReplayVisuals.renderPlayers = !ReplayVisuals.renderPlayers;
}
if (ImGui.checkbox("Render Particles", ReplayVisuals.renderParticles)) {
ReplayVisuals.renderParticles = !ReplayVisuals.renderParticles;
}
if (ImGui.checkbox("Render Sky", ReplayVisuals.renderSky)) {
ReplayVisuals.renderSky = !ReplayVisuals.renderSky;
}
if (ImGui.checkbox("Render Nametags", ReplayVisuals.renderNametags)) {
ReplayVisuals.renderNametags = !ReplayVisuals.renderNametags;
}
ImGuiHelper.separatorWithText("Overrides");
// Fog distance
if (ImGui.checkbox("Override Fog", ReplayVisuals.overrideFog)) {
ReplayVisuals.overrideFog = !ReplayVisuals.overrideFog;
}
if (ReplayVisuals.overrideFog) {
floatBuffer[0] = ReplayVisuals.overrideFogStart;
if (ImGui.sliderFloat("Start", floatBuffer, 0.0f, 512.0f)) {
ReplayVisuals.overrideFogStart = floatBuffer[0];
}
floatBuffer[0] = ReplayVisuals.overrideFogEnd;
if (ImGui.sliderFloat("End", floatBuffer, 0.0f, 512.0f)) {
ReplayVisuals.overrideFogEnd = floatBuffer[0];
}
}
// FOV
if (ImGui.checkbox("Override FOV", ReplayVisuals.overrideFov)) {
ReplayVisuals.overrideFov = !ReplayVisuals.overrideFov;
}
if (ReplayVisuals.overrideFov) {
floatBuffer[0] = ReplayVisuals.overrideFovAmount;
if (ImGui.sliderFloat("FOV", floatBuffer, 0.1f, 110.0f, "%.1f")) {
ReplayVisuals.setFov(floatBuffer[0]);
}
}
// Time
if (ImGui.checkbox("Override Time", ReplayVisuals.overrideTimeOfDay >= 0)) {
if (ReplayVisuals.overrideTimeOfDay >= 0) {
ReplayVisuals.overrideTimeOfDay = -1;
} else {
ReplayVisuals.overrideTimeOfDay = (int)(Minecraft.getInstance().level.getDayTime() % 24000);
}
}
if (ReplayVisuals.overrideTimeOfDay >= 0) {
intBuffer[0] = (int) ReplayVisuals.overrideTimeOfDay;
if (ImGui.sliderInt("Time", intBuffer, 0, 24000)) {
ReplayVisuals.overrideTimeOfDay = intBuffer[0];
}
}
ImGuiHelper.separatorWithText("Other");
if (ImGui.checkbox("Rule of Thirds Guide", ReplayVisuals.ruleOfThirdsGuide)) {
ReplayVisuals.ruleOfThirdsGuide = !ReplayVisuals.ruleOfThirdsGuide;
}
if (ImGui.checkbox("Center Guide", ReplayVisuals.centerGuide)) {
ReplayVisuals.centerGuide = !ReplayVisuals.centerGuide;
}
ReplayVisuals.sizing = ImGuiHelper.enumCombo("Sizing", ReplayVisuals.sizing);
if (ReplayVisuals.sizing == Sizing.CHANGE_ASPECT_RATIO) {
ReplayVisuals.changeAspectRatio = ImGuiHelper.enumCombo("Aspect", ReplayVisuals.changeAspectRatio);
}
}
ImGui.end();
}
}