Skip to content

Commit

Permalink
make use of logging utilities in KSPBuildTools
Browse files Browse the repository at this point in the history
  • Loading branch information
drewcassidy committed Nov 18, 2024
1 parent 23b17cb commit ea3d52b
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 61 deletions.
7 changes: 4 additions & 3 deletions Source/IconMaterialPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ You should have received a copy of the GNU General Public License
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using KSPBuildTools;
using UnityEngine;

namespace Shabby
Expand All @@ -36,7 +37,7 @@ class SetPartIconMaterialsPatch
static Shader FindOverrideIconShader(Material material)
{
if (Shabby.iconShaders.TryGetValue(material.shader.name, out var shader)) {
Shabby.LogDebug($"custom icon shader {material.shader.name} -> {shader.name}");
Log.Debug($"custom icon shader {material.shader.name} -> {shader.name}");
return shader;
}

Expand Down Expand Up @@ -80,12 +81,12 @@ static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> inst
code[i].opcode = OpCodes.Ldloc_S;
code[i].operand = locMaterial;
code[i + 1].operand = mInfo_FindOverrideIconShader;
Shabby.LogDebug("patched part icon shader replacement");
Log.Debug("patched part icon shader replacement");
return code;
}
}

Shabby.LogError("failed to patch part icon shader replacement");
Log.Error("failed to patch part icon shader replacement");
return code;
}
}
Expand Down
26 changes: 10 additions & 16 deletions Source/MaterialDef.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ You should have received a copy of the GNU General Public License
using System.Runtime.CompilerServices;
using HarmonyLib;
using UnityEngine;
using KSPBuildTools;

namespace Shabby
{
Expand All @@ -33,15 +34,15 @@ public static void Load()
foreach (var node in GameDatabase.Instance.GetConfigNodes("SHABBY_MATERIAL_DEF")) {
var def = new MaterialDef(node);
if (string.IsNullOrEmpty(def.name) || !def.isValid) {
Shabby.LogError($"[MaterialDef {def.name}] removing invalid definition");
Log.Error($"[MaterialDef {def.name}] removing invalid definition");
} else {
items[def.name] = def;
}
}
}
}

public class MaterialDef
public class MaterialDef : ILogContextProvider
{
[Persistent] public string name;

Expand Down Expand Up @@ -76,13 +77,13 @@ public MaterialDef(ConfigNode node)
if (shaderName != null) {
shader = Shabby.FindShader(shaderName);
if (shader == null) {
LogError($"failed to find shader {shaderName}");
this.LogError($"failed to find shader {shaderName}");
isValid = false;
}
}

if (!updateExisting && shader == null) {
LogError($"from-scratch material must define a valid shader");
this.LogError($"from-scratch material must define a valid shader");
isValid = false;
}

Expand Down Expand Up @@ -113,12 +114,12 @@ Dictionary<string, T> LoadDictionary<T>(ConfigNode defNode, string propKind, Fun
if (value is T parsed) {
items[item.name] = parsed;
} else {
LogError(
this.LogError(
$"failed to load {propKind} property {item.name} = {item.value}");
}
}

Log($"loaded {items.Count} {propKind} properties");
this.LogMessage($"loaded {items.Count} {propKind} properties");
return items;
}

Expand All @@ -132,7 +133,7 @@ public static bool ParseColor(string value, out Color color)
static bool CheckProperty(Material mat, string propName)
{
var exists = mat.HasProperty(propName);
if (!exists) Shabby.LogWarning($"shader {mat.shader.name} does not have property {propName}");
if (!exists) Log.Warning($"shader {mat.shader.name} does not have property {propName}");
return exists;
}

Expand Down Expand Up @@ -181,16 +182,9 @@ public Material Instantiate(Material referenceMaterial)
return material;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Log(string message)
public string context()
{
Debug.Log(logPrefix + message);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void LogError(string message)
{
Debug.LogError(logPrefix + message);
return name;
}
}
}
7 changes: 4 additions & 3 deletions Source/MaterialReplacement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ You should have received a copy of the GNU General Public License
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using KSPBuildTools;
using UnityEngine;

namespace Shabby
Expand All @@ -32,12 +33,12 @@ public MaterialReplacement(ConfigNode node) : base(node)
{
var defName = node.GetValue("materialDef");
if (string.IsNullOrEmpty(defName)) {
Shabby.LogError("material replacement must reference a material definition");
Log.Error("material replacement must reference a material definition");
return;
}

if (!MaterialDefLibrary.items.TryGetValue(defName, out materialDef)) {
Shabby.LogError($"failed to find valid material definition {defName}");
Log.Error($"failed to find valid material definition {defName}");
}
}

Expand Down Expand Up @@ -93,7 +94,7 @@ static void Postfix(ref GameObject __result, ConfigNode partCfg)
}

var replacementNames = string.Join(", ", replacements.Select(rep => rep.materialDef.name));
Shabby.LogDebug($"applied material replacements {replacementNames}");
Log.Debug($"applied material replacements {replacementNames}");
}
}
}
3 changes: 2 additions & 1 deletion Source/ModelFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ You should have received a copy of the GNU General Public License

using System.Collections.Generic;
using System.Linq;
using KSPBuildTools;
using UnityEngine;

namespace Shabby
Expand All @@ -36,7 +37,7 @@ public ModelFilter(ConfigNode node)
targetTransforms = node.GetValuesList("targetTransform").ToHashSet();

if (targetMaterials.Count > 0 && targetTransforms.Count > 0) {
Shabby.LogError("model filter may not specify both materials and transforms");
Log.Error("model filter may not specify both materials and transforms");
targetTransforms.Clear();
}

Expand Down
7 changes: 4 additions & 3 deletions Source/ShabLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ You should have received a copy of the GNU General Public License
using System.IO;
using System.Collections;
using System.Collections.Generic;
using KSPBuildTools;
using UnityEngine;

namespace Shabby
Expand All @@ -29,14 +30,14 @@ public class DatabaseLoaderTexture_SHAB : DatabaseLoader<GameDatabase.TextureInf
{
public override IEnumerator Load(UrlDir.UrlFile urlFile, FileInfo file)
{
Shabby.Log($"loading '{urlFile.fullPath}'");
Log.Message($"loading '{urlFile.fullPath}'");
var bundle = AssetBundle.LoadFromFile(urlFile.fullPath);
if (!bundle) {
Shabby.LogWarning($"could not load {urlFile.fullPath}");
Log.Warning($"could not load {urlFile.fullPath}");
} else {
Shader[] shaders = bundle.LoadAllAssets<Shader>();
foreach (Shader shader in shaders) {
Shabby.LogDebug($"adding {shader.name}");
Log.Debug($"adding {shader.name}");
Shabby.AddShader(shader);
}
}
Expand Down
44 changes: 10 additions & 34 deletions Source/Shabby.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ You should have received a copy of the GNU General Public License
using System.Runtime.CompilerServices;
using UnityEngine;
using HarmonyLib;
using KSPBuildTools;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
Expand Down Expand Up @@ -64,7 +65,7 @@ static Shader FindLoadedShader(string shaderName)
{
Shader shader;
if (loadedShaders.TryGetValue(shaderName, out shader)) {
Log($"custom shader: {shader.name}");
Log.Message($"custom shader: {shader.name}");
return shader;
}

Expand All @@ -82,7 +83,7 @@ public static Shader FindShader(string shaderName)
shader = FindLoadedShader(replacement.shader);

if (shader == null) {
LogError($"failed to find shader {replacement.shader} to replace {shaderName}");
Log.Error($"failed to find shader {replacement.shader} to replace {shaderName}");
}
}

Expand All @@ -107,7 +108,7 @@ public static void MMPostLoadCallback()
var iconShaderName = iconNode.GetValue("iconShader");
var iconShader = FindShader(iconShaderName ?? "");
if (string.IsNullOrEmpty(shader) || iconShader == null) {
LogError($"invalid icon shader specification {shader} -> {iconShaderName}");
Log.Error($"invalid icon shader specification {shader} -> {iconShaderName}");
} else {
iconShaders[shader] = iconShader;
}
Expand All @@ -119,13 +120,14 @@ public static void MMPostLoadCallback()

void Awake()
{
Debug.Log("Test context (shibboleth)", this);
if (loadedShaders == null) {
loadedShaders = new Dictionary<string, Shader>();

harmony = new Harmony("Shabby");
harmony.PatchAll(Assembly.GetExecutingAssembly());

LogDebug("hooked");
Log.Debug("hooked");

// Register as an explicit MM callback such that it is run before all reflected
// callbacks (as used by most mods), which may wish to access the MaterialDef library.
Expand All @@ -149,7 +151,7 @@ private void Start()

List<MethodBase> callSites = new List<MethodBase>();

LogDebug("Beginning search for callsites");
Log.Debug("Beginning search for callsites");

// Don't use appdomain, we don't want to accidentally patch Unity itself and this avoid
// having to iterate on the BCL and Unity assemblies.
Expand Down Expand Up @@ -190,7 +192,7 @@ private void Start()
if (assemblyDef == null)
throw new FileLoadException($"Couldn't read assembly \"{kspAssembly.assembly.Location}\"");
} catch (Exception e) {
LogWarning($"Replace failed for assembly {kspAssembly.name}\n{e}");
Log.Warning($"Replace failed for assembly {kspAssembly.name}\n{e}");
continue;
}

Expand All @@ -211,7 +213,7 @@ private void Start()
if (callSite == null)
throw new MemberAccessException();
} catch {
LogWarning(
Log.Warning(
$"Failed to patch method {assemblyDef.Name}::{typeDef.Name}.{methodDef.Name}");
break;
}
Expand All @@ -234,7 +236,7 @@ private void Start()
if (callSite == mInfo_ShaderFind_Replacement)
continue;

Log(
Log.Debug(
$"Patching call site : {callSite.DeclaringType.Assembly.GetName().Name}::{callSite.DeclaringType}.{callSite.Name}");
harmony.Patch(callSite, null, null, new HarmonyMethod(callSiteTranspiler));
}
Expand All @@ -250,31 +252,5 @@ static IEnumerable<CodeInstruction> CallSiteTranspiler(IEnumerable<CodeInstructi
yield return instruction;
}
}

internal const string LogPrefix = "[Shabby] ";

[System.Diagnostics.Conditional("DEBUG")]
internal static void LogDebug(string message)
{
Debug.Log(LogPrefix + message);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void Log(string message)
{
Debug.Log(LogPrefix + message);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void LogWarning(string message)
{
Debug.LogWarning(LogPrefix + message);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void LogError(string message)
{
Debug.LogError(LogPrefix + message);
}
}
}
6 changes: 5 additions & 1 deletion Source/Shabby.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@

<!-- MSBuild Dependencies -->
<ItemGroup>
<PackageReference Include="KSPBuildTools" Version="0.0.2" />
<PackageReference Include="KSPBuildTools" Version="0.0.3-*"/>
<PackageReference Include="MinVer" Version="5.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>

<!-- Static Properties -->
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>portable</DebugType>
</PropertyGroup>

<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<LangVersion>7.3</LangVersion>
Expand Down

0 comments on commit ea3d52b

Please sign in to comment.