|
| 1 | +package juuxel.adorn.client.gui; |
| 2 | + |
| 3 | +import com.mojang.blaze3d.systems.RenderSystem; |
| 4 | +import net.minecraft.client.MinecraftClient; |
| 5 | + |
| 6 | +import java.util.ArrayDeque; |
| 7 | +import java.util.Deque; |
| 8 | + |
| 9 | +/** |
| 10 | + * A global GL scissor stack that is applied when pushed and popped. |
| 11 | + */ |
| 12 | +public final class Scissors { |
| 13 | + private static final Deque<Frame> STACK = new ArrayDeque<>(); |
| 14 | + |
| 15 | + /** |
| 16 | + * Pushes a new scissor frame at {@code (x, y)} with dimensions {@code (width, height)} |
| 17 | + * and refreshes the scissor state. |
| 18 | + */ |
| 19 | + public static void push(int x, int y, int width, int height) { |
| 20 | + push(new Frame(x, y, x + width, y + height)); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Pushes a scissor frame and refreshes the scissor state. |
| 25 | + */ |
| 26 | + public static void push(Frame frame) { |
| 27 | + STACK.addLast(frame); |
| 28 | + apply(); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Pops the topmost scissor frame and refreshes the scissor state. |
| 33 | + * If there are no remaining frames, disables scissoring. |
| 34 | + */ |
| 35 | + public static Frame pop() { |
| 36 | + var frame = STACK.removeLast(); |
| 37 | + apply(); |
| 38 | + return frame; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Temporarily disables the topmost scissor frame for executing the runnable. |
| 43 | + */ |
| 44 | + public static void suspendScissors(Runnable fn) { |
| 45 | + var frame = pop(); |
| 46 | + fn.run(); |
| 47 | + push(frame); |
| 48 | + } |
| 49 | + |
| 50 | + private static void apply() { |
| 51 | + if (STACK.isEmpty()) { |
| 52 | + RenderSystem.disableScissor(); |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + var window = MinecraftClient.getInstance().getWindow(); |
| 57 | + var x1 = 0; |
| 58 | + var y1 = 0; |
| 59 | + var x2 = window.getScaledWidth(); |
| 60 | + var y2 = window.getScaledHeight(); |
| 61 | + |
| 62 | + for (var frame : STACK) { |
| 63 | + x1 = Math.max(x1, frame.x1); |
| 64 | + y1 = Math.max(y1, frame.y1); |
| 65 | + x2 = Math.min(x2, frame.x2); |
| 66 | + y2 = Math.min(y2, frame.y2); |
| 67 | + } |
| 68 | + |
| 69 | + var scale = window.getScaleFactor(); |
| 70 | + RenderSystem.enableScissor( |
| 71 | + (int) (x1 * scale), (int) (window.getFramebufferHeight() - scale * y2), |
| 72 | + (int) ((x2 - x1) * scale), (int) ((y2 - y1) * scale) |
| 73 | + ); |
| 74 | + } |
| 75 | + |
| 76 | + public record Frame(int x1, int y1, int x2, int y2) { |
| 77 | + } |
| 78 | +} |
0 commit comments