From cd238e9ea575b0d6ea83065a8d13f54f431e364f Mon Sep 17 00:00:00 2001 From: Evan Hemsley Date: Fri, 17 Jul 2020 13:52:05 -0700 Subject: [PATCH] scaler script --- ResolutionScaler.cs | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 ResolutionScaler.cs diff --git a/ResolutionScaler.cs b/ResolutionScaler.cs new file mode 100644 index 0000000..f807056 --- /dev/null +++ b/ResolutionScaler.cs @@ -0,0 +1,68 @@ +using Microsoft.Xna.Framework; + +namespace ResolutionScaler +{ + static class ResolutionScaler + { + static private int s_virtual_width; + static private int s_virtual_height; + static private int s_screen_width; + static private int s_screen_height; + + static private Matrix s_transform_matrix; + static private bool s_dirtyMatrix = true; + + static public void Init(int screenWidth, int screenHeight, int virtualWidth, int virtualHeight) + { + s_screen_width = screenWidth; + s_screen_height = screenHeight; + s_virtual_width = virtualWidth; + s_virtual_height = virtualHeight; + s_dirtyMatrix = true; + } + + static public Matrix TransformMatrix + { + get + { + if (s_dirtyMatrix) RecreateScaleMatrix(); + return s_transform_matrix; + } + } + + static public void SetScreenResolution(int width, int height) + { + s_screen_width = width; + s_screen_height = height; + s_dirtyMatrix = true; + } + + static public void SetVirtualResolution(int width, int height) + { + s_virtual_width = width; + s_virtual_height = height; + s_dirtyMatrix = true; + } + + static private void RecreateScaleMatrix() + { + var scaleUniform = System.Math.Min( + (float)s_screen_width / s_virtual_width, + (float)s_screen_height / s_virtual_height + ); + + var scaleMatrix = Matrix.CreateScale( + (float)scaleUniform, + (float)scaleUniform, + 1f + ); + + var offX = (s_screen_width - scaleUniform * s_virtual_width) / 2; + var offY = (s_screen_height - scaleUniform * s_virtual_height) / 2; + var translationMatrix = Matrix.CreateTranslation(offX, offY, 0); + + s_transform_matrix = scaleMatrix * translationMatrix; + s_dirtyMatrix = false; + } + } +}