Skip to content

Commit

Permalink
Make addon load once and stay persistent, fix buggy window and debug …
Browse files Browse the repository at this point in the history
…functionality in editors
  • Loading branch information
LGhassen committed Jun 30, 2024
1 parent fd83432 commit 7d76224
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 69 deletions.
71 changes: 30 additions & 41 deletions DeferredKSP/Deferred.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,22 @@
using UnityEngine.Rendering;
using System.Collections;
using System;
using UnityEngine.SceneManagement;

[assembly: AssemblyVersion("1.1.10")]
[assembly: AssemblyVersion("1.1.11")]
[assembly: KSPAssemblyDependency("0Harmony", 0, 0)]
[assembly: KSPAssemblyDependency("Shabby", 0, 0)]
namespace Deferred
{
[KSPAddon(KSPAddon.Startup.EveryScene, false)]
[KSPAddon(KSPAddon.Startup.MainMenu, true)]
public class Deferred : MonoBehaviour
{
Camera nearCamera, firstLocalCamera, scaledCamera, editorCamera, internalCamera;
private bool gbufferDebugModeEnabled = false;
private Settings settings;

private static bool incompatibleShadersReplacedInExistingMaterials = false;

private void Init()
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
var settings = Settings.LoadSettings();

ReplaceIncompatibleShadersInExistingMaterials();

SetupCustomReflectionsAndAmbient(settings);

HandleCameras();
Expand All @@ -39,7 +35,7 @@ private void Init()

if (settings.useDitheredTransparency)
{
Shader.SetGlobalTexture("_DeferredDitherBlueNoise", ShaderLoader.Instance.LoadedTextures["DeferredDitherBlueNoise"]);
Shader.SetGlobalTexture("_DeferredDitherBlueNoise", ShaderLoader.LoadedTextures["DeferredDitherBlueNoise"]);
Shader.SetGlobalInt("_DeferredUseDitheredTransparency", 1);
}
else
Expand Down Expand Up @@ -152,7 +148,7 @@ private static void SetupCustomReflectionsAndAmbient(Settings settings)
{
GraphicsSettings.SetShaderMode(BuiltinShaderType.DeferredReflections, BuiltinShaderMode.UseCustom);
GraphicsSettings.SetCustomShader(BuiltinShaderType.DeferredReflections,
ShaderLoader.Instance.DeferredShaders["Deferred/Internal-DeferredReflections"]);
ShaderLoader.DeferredShaders["Deferred/Internal-DeferredReflections"]);

Shader.SetGlobalFloat("deferredAmbientBrightness", settings.ambientBrightness);
Shader.SetGlobalFloat("deferredAmbientTint", settings.ambientTint);
Expand All @@ -163,28 +159,23 @@ private static void SetupCustomReflectionsAndAmbient(Settings settings)
// Newer materials get the replaced shaders from shabby which replaces Shader.Find
private void ReplaceIncompatibleShadersInExistingMaterials()
{
if (!incompatibleShadersReplacedInExistingMaterials && HighLogic.LoadedScene == GameScenes.MAINMENU)
{
Debug.Log("[Deferred] Replacing shaders for deferred rendering");
Debug.Log("[Deferred] Replacing shaders for deferred rendering");

foreach (Material mat in Resources.FindObjectsOfTypeAll<Material>())
{
string name = mat.shader.name;
foreach (Material mat in Resources.FindObjectsOfTypeAll<Material>())
{
string name = mat.shader.name;

// Some materials have overridden renderqueues not matching the shader ones
// These get overridden by replacing the shader
// Keep the original ones because they are important for parts with depthMasks
int originalRenderqueue = mat.renderQueue;
// Some materials have overridden renderqueues not matching the shader ones
// These get overridden by replacing the shader
// Keep the original ones because they are important for parts with depthMasks
int originalRenderqueue = mat.renderQueue;

if (ShaderLoader.Instance.ReplacementShaders.TryGetValue(name, out Shader replacementShader))
{
mat.shader = replacementShader;
}

mat.renderQueue = originalRenderqueue;
if (ShaderLoader.ReplacementShaders.TryGetValue(name, out Shader replacementShader))
{
mat.shader = replacementShader;
}

incompatibleShadersReplacedInExistingMaterials = true;
mat.renderQueue = originalRenderqueue;
}
}

Expand Down Expand Up @@ -224,7 +215,6 @@ public void OnCameraChange(CameraManager.CameraMode cameraMode)
}
}


public void ToggleDebugMode()
{
if (!RenderingUtils.IsUnifiedCameraMode() && nearCamera != null)
Expand Down Expand Up @@ -259,19 +249,17 @@ private void ToggleCameraDebugMode(Camera camera, bool enable)

private void Start()
{
DontDestroyOnLoad(this);

windowId = UnityEngine.Random.Range(int.MinValue, int.MaxValue);
StartCoroutine(DelayedInit());
}

IEnumerator DelayedInit()
{
// Wait a few frames for the game to finish setting up
for (int i = 0; i < 6; i++)
{
yield return new WaitForFixedUpdate();
}
settings = Settings.LoadSettings();

Init();
ReplaceIncompatibleShadersInExistingMaterials();

SceneManager.sceneLoaded += OnSceneLoaded;

OnSceneLoaded(new Scene(), LoadSceneMode.Single);
}

public void OnDestroy()
Expand All @@ -285,9 +273,11 @@ public void OnDestroy()
ToggleCameraDebugMode(scaledCamera, false);
ToggleCameraDebugMode(internalCamera, false);
ToggleCameraDebugMode(editorCamera, false);

SceneManager.sceneLoaded -= OnSceneLoaded;
}

bool showUI=false;
bool showUI = false;
int windowId;
Rect windowRect = new Rect(20, 50, 200, 150);

Expand All @@ -300,7 +290,6 @@ void OnGUI()

if (showUI)
{

windowRect = GUILayout.Window(windowId, windowRect, DrawWindow,
$"Deferred {Assembly.GetExecutingAssembly().GetName().Version}");
}
Expand Down
2 changes: 1 addition & 1 deletion DeferredKSP/EditorLighting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private static void FixShadowReceiver()
if (mr != null && mr.material != null)
{
int originalRenderqueue = mr.material.renderQueue;
mr.material.shader = ShaderLoader.Instance.ReplacementShaders["KSP/Scenery/Invisible Shadow Receiver"];
mr.material.shader = ShaderLoader.ReplacementShaders["KSP/Scenery/Invisible Shadow Receiver"];
mr.material.renderQueue = originalRenderqueue;
}
}
Expand Down
2 changes: 1 addition & 1 deletion DeferredKSP/Utils/DeferredPQSFade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ private void Awake()
backgroundCopyCommandBuffer = new CommandBuffer();
applyFadeCommandBuffer = new CommandBuffer();

applyFadeMaterial = new Material(ShaderLoader.Instance.DeferredShaders["Deferred/ApplyPQSFade"]);
applyFadeMaterial = new Material(ShaderLoader.DeferredShaders["Deferred/ApplyPQSFade"]);
}

void OnPreRender()
Expand Down
2 changes: 1 addition & 1 deletion DeferredKSP/Utils/ForwardRenderingCompatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void Init(int layer)
// This dummy forward-rendered object forces these commandBuffer events to fire
private void AddDummyForwardObject(int layer)
{
material = new Material(ShaderLoader.Instance.DeferredShaders["Deferred/DummyForwardShader"]);
material = new Material(ShaderLoader.DeferredShaders["Deferred/DummyForwardShader"]);

go = GameObject.CreatePrimitive(PrimitiveType.Quad);

Expand Down
4 changes: 2 additions & 2 deletions DeferredKSP/Utils/GBufferDebug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ private void Awake()
gbufferCopyCommandBuffer = new CommandBuffer();
gbufferDisplayCommandBuffer = new CommandBuffer();

copyGBufferMaterial = new Material(ShaderLoader.Instance.DeferredShaders["Deferred/CopyGBuffer"]);
displayGBufferMaterial = new Material(ShaderLoader.Instance.DeferredShaders["Deferred/DisplayGBuffer"]);
copyGBufferMaterial = new Material(ShaderLoader.DeferredShaders["Deferred/CopyGBuffer"]);
displayGBufferMaterial = new Material(ShaderLoader.DeferredShaders["Deferred/DisplayGBuffer"]);
}

void OnPreRender()
Expand Down
28 changes: 8 additions & 20 deletions DeferredKSP/Utils/ShaderLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,17 @@

namespace Deferred
{
public class ShaderLoader
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class ShaderLoader : MonoBehaviour
{
private Dictionary<string, Shader> deferredShaders, replacementShaders;
private Dictionary<string, Texture> loadedTextures = new Dictionary<string, Texture>();
private static Dictionary<string, Shader> deferredShaders, replacementShaders;
private static Dictionary<string, Texture> loadedTextures = new Dictionary<string, Texture>();

private static ShaderLoader instance;
public static Dictionary<string, Shader> ReplacementShaders { get => replacementShaders; }
public static Dictionary<string, Shader> DeferredShaders { get => deferredShaders; }
public static Dictionary<string, Texture> LoadedTextures { get => loadedTextures; }

public static ShaderLoader Instance
{
get
{
if (instance == null)
{
instance = new ShaderLoader();
}
return instance;
}
}
public Dictionary<string, Shader> ReplacementShaders { get => replacementShaders; }
public Dictionary<string, Shader> DeferredShaders { get => deferredShaders; }
public Dictionary<string, Texture> LoadedTextures { get => loadedTextures; }

private ShaderLoader()
void Start()
{
replacementShaders = LoadAssetBundle("replacementshaders.shab");
deferredShaders = LoadAssetBundle("deferredshaders", loadedTextures);
Expand Down
6 changes: 3 additions & 3 deletions DeferredKSP/Utils/SubpixelMorphologicalAntiAliasing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,12 @@ public void Awake()
flip.filterMode = FilterMode.Bilinear;
flop.Create();

SMAAMaterial = new Material(ShaderLoader.Instance.DeferredShaders[("Deferred/SubpixelMorphologicalAntialiasing")]);
SMAAMaterial = new Material(ShaderLoader.DeferredShaders[("Deferred/SubpixelMorphologicalAntialiasing")]);

if (areaTex == null)
areaTex = (Texture2D)ShaderLoader.Instance.LoadedTextures["AreaTex"];
areaTex = (Texture2D)ShaderLoader.LoadedTextures["AreaTex"];
if (searchTex == null)
searchTex = (Texture2D)ShaderLoader.Instance.LoadedTextures["SearchTex"];
searchTex = (Texture2D)ShaderLoader.LoadedTextures["SearchTex"];

SMAAMaterial.SetTexture("_AreaTex", areaTex);
SMAAMaterial.SetTexture("_SearchTex", searchTex);
Expand Down

0 comments on commit 7d76224

Please sign in to comment.