Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify UI scaler #1157

Merged
merged 21 commits into from
Sep 8, 2021
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions TLM/CSUtil.Commons/Log.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace CSUtil.Commons {
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;

Expand Down Expand Up @@ -40,9 +40,9 @@ namespace CSUtil.Commons {
public static class Log {
private static readonly object LogLock = new object();

// TODO refactor log filename to configuration
private static readonly string LogFilename
= Path.Combine(Application.dataPath, "TMPE.log");
private const string LOG_FILE_NAME = "TMPE.log";

private static readonly string LogFilePath;

private enum LogLevel {
Trace,
Expand All @@ -56,8 +56,21 @@ private enum LogLevel {

static Log() {
try {
if (File.Exists(LogFilename)) {
File.Delete(LogFilename);
string dir = Application.dataPath;
LogFilePath = Path.Combine(dir, LOG_FILE_NAME);
if (File.Exists(LogFilePath)) {
File.Delete(LogFilePath); // delete old file to avoid confusion.
}

var args = Environment.GetCommandLineArgs().ToList();
int index = args.IndexOf("-logFile");
if (index >= 0) {
dir = args[index + 1];
dir = Path.GetDirectoryName(dir); // drop output_log.txt
LogFilePath = Path.Combine(dir, LOG_FILE_NAME);
if (File.Exists(LogFilePath)) {
File.Delete(LogFilePath);
}
}
}
catch (Exception e) {
Expand Down Expand Up @@ -189,7 +202,7 @@ public static void NotImpl(string what) {

private static void LogToFile(string log, LogLevel level) {
lock(LogLock){
using (StreamWriter w = File.AppendText(LogFilename)) {
using (StreamWriter w = File.AppendText(LogFilePath)) {
long secs = _sw.ElapsedTicks / Stopwatch.Frequency;
long fraction = _sw.ElapsedTicks % Stopwatch.Frequency;
w.WriteLine(
Expand Down
4 changes: 2 additions & 2 deletions TLM/TLM/State/ConfigData/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public class Main {
public float GuiScale = 100f;

/// <summary>
/// If checked, will use <see cref="ColossalFramework.UI.UIView"/> resolution instead of
/// what <see cref="UnityEngine.Screen"/> object returns.
/// if checked, size remains constnat but pixel count changes when resolution changes. Quality drops with lower resolutions.
/// if unchecked checked, size changes constnat but pixel count remains the same. Maintains same image quality for all resolution.
/// </summary>
public bool GuiScaleToResolution = true;

Expand Down
81 changes: 34 additions & 47 deletions TLM/TLM/U/UIScaler.cs
Original file line number Diff line number Diff line change
@@ -1,79 +1,59 @@
namespace TrafficManager.U {
using ColossalFramework.UI;
using System;
using TrafficManager.State;
using TrafficManager.Util;
using UnityEngine;

/// <summary>
/// Code of UIScaler from ModTools by Kian Zarrin
/// https://github.com/kianzarrin/Skylines-ModTools/blob/master/Debugger/UI/UIScaler.cs
/// </summary>
public static class UIScaler {
public static bool TryGetScreenResolution(out Vector2 resolution) {
UIView uIView = UIView.GetAView();
if (uIView) {
resolution = uIView.GetScreenResolution();
return true;
}

resolution = default;
return false;
}

private static float BaseResolutionX {
get {
if (TryGetScreenResolution(out Vector2 resolution)) {
// 1920f if aspect ratio is 16:9;
return resolution.x;
}

return 1080f * AspectRatio;
}
}

private static float BaseResolutionY {
get {
if (TryGetScreenResolution(out Vector2 resolution)) {
// always 1080f. But we keep this code for the sake of future proofing
return resolution.y;
}
private static State.ConfigData.Main Config => GlobalConfig.Instance.Main;

return 1080f;
}
}
internal static Vector2 BaseResolution { get; private set; }

public static float AspectRatio => Screen.width / (float)Screen.height;
internal static float AspectRatio => Screen.width / (float)Screen.height;

/// <summary>Shortcut to reach global main config containing GuiScale.</summary>
private static State.ConfigData.Main Config => GlobalConfig.Instance.Main;

public static float MaxWidth {
/// <summary>
/// Maximum projected width of GUI space when GUI.matrix = ScaleMatrix
/// </summary>
internal static float MaxWidth {
get {
float ret = Config.GuiScaleToResolution ? BaseResolutionX : Screen.width;
return ret / Config.GuiScale;
float ret = Config.GuiScaleToResolution ? BaseResolution.x : Screen.width;
return ret / UIScale;
}
}

public static float MaxHeight {
/// <summary>
/// Maximum projected height of GUI space when GUI.matrix = ScaleMatrix
/// </summary>
internal static float MaxHeight {
get {
float ret = Config.GuiScaleToResolution ? BaseResolutionY : Screen.height;
return ret / Config.GuiScale;
float ret = Config.GuiScaleToResolution ? BaseResolution.y : Screen.height;
return ret / UIScale;
}
}

public static float UIAspectScale {
internal static float UIAspectScale {
get {
var horizontalScale = Screen.width / MaxWidth;
var verticalScale = Screen.height / MaxHeight;
return Mathf.Min(horizontalScale, verticalScale);
}
}

public static float UIScale => GlobalConfig.Instance.Main.GuiScale * 0.01f;
internal static float UIScale => Config.GuiScale * 0.01f;

internal static Matrix4x4 ScaleMatrix => Matrix4x4.Scale(Vector3.one * UIAspectScale);

public static Matrix4x4 ScaleMatrix => Matrix4x4.Scale(Vector3.one * UIScaler.UIScale);

public static Vector2 MousePosition {
/// <summary>
/// Mouse position in GUI space when GUI.matrix = ScaleMatrix
/// </summary>
internal static Vector2 MousePosition {
get {
var mouse = Input.mousePosition;
mouse.y = Screen.height - mouse.y;
Expand All @@ -87,10 +67,17 @@ public static Vector2 MousePosition {
/// <param name="screenPos">Pixel position.</param>
/// <returns>GUI space position.</returns>
internal static Vector2 ScreenPointToGuiPoint(Vector2 screenPos) {
// TODO: Optimize, this is frequently called
return new(
x: screenPos.x * BaseResolutionX / Screen.width,
y: screenPos.y * BaseResolutionY / Screen.height);
x: screenPos.x * BaseResolution.x / Screen.width,
y: screenPos.y * BaseResolution.y / Screen.height);
}

internal static void Reset() {
try {
BaseResolution = UIView.GetAView().GetScreenResolution();
} catch (Exception ex) {
ex.LogException();
}
}
}
}
3 changes: 1 addition & 2 deletions TLM/TLM/U/UIUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ public static bool ClampToScreen(UIComponent window, UIComponent alwaysVisible)
size: alwaysVisible.size);

Rect clampedRect = new Rect(origRect);
Vector2 resolution = new Vector2(Screen.width, Screen.height);
UIScaler.TryGetScreenResolution(out resolution);
Vector2 resolution = UIScaler.BaseResolution;

VectorUtil.ClampRectToScreen(
rect: ref clampedRect,
Expand Down
4 changes: 2 additions & 2 deletions TLM/TLM/UI/LegacySubTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,8 @@ public virtual string GetTutorialKey() {

protected void DragWindow(ref Rect window) {
Vector2 resolution = UIView.GetAView().GetScreenResolution();
window.x = Mathf.Clamp(window.x, 0, resolution.x - window.width);
window.y = Mathf.Clamp(window.y, 0, resolution.y - window.height);
window.x = Mathf.Clamp(window.x, 0, UIScaler.MaxWidth - window.width);
window.y = Mathf.Clamp(window.y, 0, UIScaler.MaxHeight - window.height);

bool primaryMouseDown = Input.GetMouseButton(0);
if (primaryMouseDown) {
Expand Down
11 changes: 11 additions & 0 deletions TLM/TLM/UI/MainMenu/MainMenuWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -499,5 +499,16 @@ public void UpdateButtons() {
button.UpdateButtonSkinAndTooltip();
}
}

public override void Awake() {
UIScaler.Reset();
base.Awake();
}

protected override void OnResolutionChanged(Vector2 previousResolution, Vector2 currentResolution) {
UIScaler.Reset();
base.OnResolutionChanged(previousResolution, currentResolution);
}

} // end class
}
6 changes: 4 additions & 2 deletions TLM/TLM/UI/SubTools/SpeedLimits/SpeedLimitsTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace TrafficManager.UI.SubTools.SpeedLimits {
using UnityEngine;
using static TrafficManager.Util.Shortcuts;
using TrafficManager.Util.Extensions;
using TrafficManager.U;

public class SpeedLimitsTool : LegacySubTool {
public const int
Expand Down Expand Up @@ -142,6 +143,8 @@ public override void OnSecondaryClickOverlay() {

public override void OnToolGUI(Event e) {
base.OnToolGUI(e);
var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;

string unitTitle = string.Format(
" ({0})",
Expand Down Expand Up @@ -176,8 +179,7 @@ public override void OnToolGUI(Event e) {
&& defaultsWindowRect.Contains(
Event.current.mousePosition));

// overlayHandleHovered = false;
// ShowSigns(false);
GUI.matrix = oldMatrix;
}

private static NetLane[] laneBuffer => NetManager.instance.m_lanes.m_buffer;
Expand Down
14 changes: 10 additions & 4 deletions TLM/TLM/UI/SubTools/TimedTrafficLights/TimedTrafficLightsTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ namespace TrafficManager.UI.SubTools.TimedTrafficLights {
using TrafficManager.API.TrafficLight;
using TrafficManager.Manager.Impl;
using TrafficManager.State;
using TrafficManager.U;
using TrafficManager.UI.MainMenu.OSD;
using TrafficManager.UI.Textures;
using TrafficManager.Util;
Expand Down Expand Up @@ -1098,13 +1099,16 @@ private string GetStepChangeMetricDescription(StepChangeMetric metric) {
private void GuiTimedTrafficLightsNode() {
_cursorInSecondaryPanel = false;

var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;
_windowRect2 = GUILayout.Window(
id: 252,
screenRect: _windowRect2,
func: _guiTimedTrafficLightsNodeWindowDelegate,
text: T("TTL.Window.Title:Select nodes"),
style: WindowStyle,
options: EmptyOptionsArray);
GUI.matrix = oldMatrix;

_cursorInSecondaryPanel = _windowRect2.Contains(Event.current.mousePosition);
}
Expand All @@ -1115,6 +1119,8 @@ private void GuiTimedTrafficLightsNode() {
private void GuiTimedTrafficLights() {
_cursorInSecondaryPanel = false;

var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;
_windowRect = GUILayout.Window(
id: 253,
screenRect: _windowRect,
Expand All @@ -1124,11 +1130,8 @@ private void GuiTimedTrafficLights() {
options: EmptyOptionsArray);

_cursorInSecondaryPanel = _windowRect.Contains(Event.current.mousePosition);
GUI.matrix = oldMatrix;

GUI.matrix = Matrix4x4.TRS(
new Vector3(0, 0, 0),
Quaternion.identity,
new Vector3(1, 1, 1)); // revert scaling
ShowGUI();
}

Expand All @@ -1138,6 +1141,8 @@ private void GuiTimedTrafficLights() {
private void GuiTimedTrafficLightsCopy() {
_cursorInSecondaryPanel = false;

var oldMatrix = GUI.matrix;
GUI.matrix = UIScaler.ScaleMatrix;
_windowRect2 = GUILayout.Window(
id: 255,
screenRect: _windowRect2,
Expand All @@ -1147,6 +1152,7 @@ private void GuiTimedTrafficLightsCopy() {
options: EmptyOptionsArray);

_cursorInSecondaryPanel = _windowRect2.Contains(Event.current.mousePosition);
GUI.matrix = oldMatrix;
}

private void GuiTimedTrafficLightsPasteWindow(int num) {
Expand Down