17 Commits

Author SHA1 Message Date
9295899787 Saving tests 2021-01-01 14:10:27 -08:00
e069f85e56 More tweaks 2021-01-01 14:02:46 -08:00
2f2b6fb692 Get multi-projection to work 2020-12-31 21:05:30 -08:00
169f2e9bf1 Add uint parsing function 2020-12-21 03:30:36 -08:00
eb033113b3 Merge branch 'main' into feature-multiProject 2020-12-20 01:46:16 -08:00
227c259e51 Cleanup and migrate to using VS 2020-12-08 16:06:01 -08:00
fc6820d73b make normal map gen less dumb 2020-12-04 17:12:41 -08:00
9dc98a6f9d Fix flag aspect ratio and font instantiation 2020-12-04 17:05:37 -08:00
35fce78616 fix flag decal NRE 2020-12-04 16:16:11 -08:00
84611a26e8 Remove workaround for outdated msbuild 2020-12-02 12:39:17 -08:00
a61a2b81a1 Cleanup refactor 2020-12-02 01:40:46 -08:00
e37cf03f7b Merge branch 'main' into feature-multiProject
# Conflicts:
#	GameData/ConformalDecals/Plugins/ConformalDecals.dll
#	Source/ConformalDecals/ModuleConformalDecal.cs
#	Source/ConformalDecals/ModuleConformalText.cs
2020-11-30 00:46:03 -08:00
e6288942ea Cleanup and fix onVariantApplied 2020-11-09 19:34:34 -08:00
62bdd151e1 Refactor to rearrange initialization code
• Add matrix parsing code
• Add target serialization
• Rearrange initialization to allow loading targets from config soon
2020-10-09 19:30:59 -07:00
f5af8a4d53 Merge branch 'develop' into feature-multiProject 2020-10-09 17:28:00 -07:00
df95601416 Allow toggling multiprojection in editor 2020-10-05 23:30:22 -07:00
596675ad8d Add naive implementation of multi-projection 2020-10-05 22:42:01 -07:00
21 changed files with 816 additions and 430 deletions

2
.gitignore vendored
View File

@ -49,5 +49,7 @@ Source/ConformalDecals/bin
.ds_store
*.sublime*
.idea
.vs
obj
*.swp
Source/.editorconfig

View File

@ -30,8 +30,6 @@ public class TextRenderTest : MonoBehaviour {
Debug.Log("starting...");
StartCoroutine(OnRender());
var thing = new GameObject();
thing.AddComponent<TextMeshPro>();
}
// Update is called once per frame

View File

@ -15,7 +15,7 @@ Localization
#LOC_ConformalDecals_gui-opacity = Opacity
#LOC_ConformalDecals_gui-cutoff = Cutoff
#LOC_ConformalDecals_gui-wear = Edge Wear
#LOC_ConformalDecals_gui-aspectratio = Aspect Ratio
#LOC_ConformalDecals_gui-multiproject = Project onto Multiple
#LOC_ConformalDecals_gui-select-flag = Select Flag
#LOC_ConformalDecals_gui-reset-flag = Reset Flag
#LOC_ConformalDecals_gui-set-text = Set Text

View File

@ -98,7 +98,7 @@ PART
MODULE {
IDENTIFIER { name = ModuleConformalDecal }
DATA {
shader = ConformalDecals/Paint/DiffuseSDF
KEYWORD { name = DECAL_SDF_ALPHA }
tile = 0, 2, 128, 112
}
}

View File

@ -1,6 +1,12 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformalDecals", "ConformalDecals/ConformalDecals.csproj", "{1EA983F9-42E5-494E-9683-FDAC9C9121F4}"
# Visual Studio Version 16
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformalDecals", "ConformalDecals\ConformalDecals.csproj", "{1EA983F9-42E5-494E-9683-FDAC9C9121F4}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C2564402-B081-479B-B723-D5C065BC884E}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -13,4 +19,28 @@ Global
{1EA983F9-42E5-494E-9683-FDAC9C9121F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1EA983F9-42E5-494E-9683-FDAC9C9121F4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
$0.DotNetNamingPolicy = $1
$1.DirectoryNamespaceAssociation = PrefixedHierarchical
$0.TextStylePolicy = $2
$2.FileWidth = 80
$2.TabsToSpaces = True
$2.scope = text/x-csharp
$2.NoTabsAfterNonTabs = True
$2.EolMarker = Unix
$0.CSharpFormattingPolicy = $3
$3.NewLinesForBracesInTypes = False
$3.NewLinesForBracesInMethods = False
$3.NewLinesForBracesInProperties = False
$3.NewLinesForBracesInAccessors = False
$3.NewLinesForBracesInAnonymousMethods = False
$3.NewLinesForBracesInControlBlocks = False
$3.NewLinesForBracesInAnonymousTypes = False
$3.NewLinesForBracesInObjectCollectionArrayInitializers = False
$3.NewLinesForBracesInLambdaExpressionBody = False
$3.scope = text/x-csharp
$3.SpaceAfterCast = True
$0.StandardHeader = $4
EndGlobalSection
EndGlobal

View File

@ -47,9 +47,11 @@
<None Remove="dlls\**" />
</ItemGroup>
<ItemGroup>
<None Include="..\.editorconfig" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="/bin/cp -v '$(OutDir)ConformalDecals.dll' '$(SolutionDir)../GameData/ConformalDecals/Plugins'" IgnoreExitCode="true" />
<!--Fuck you MSBuild stop trying to run CMD.exe on macOS-->
<Exec Command="/bin/cp -v '$(OutDir)ConformalDecals.dll' '$(SolutionDir)../GameData/ConformalDecals/Plugins'" />
</Target>
</Project>

View File

@ -3,7 +3,6 @@ using System.Collections.Generic;
using ConformalDecals.Text;
using ConformalDecals.Util;
using TMPro;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -51,8 +50,6 @@ namespace ConformalDecals {
public static IEnumerable<DecalFont> Fonts => _fontList.Values;
public static DecalFont FallbackFont { get; private set; }
public static bool IsBlacklisted(Shader shader) {
return IsBlacklisted(shader.name);
}
@ -97,7 +94,7 @@ namespace ConformalDecals {
foreach (var fontNode in node.GetNodes("FONT")) {
try {
var font = new DecalFont(fontNode, allFonts);
var font = DecalFont.Parse(fontNode, allFonts);
_fontList.Add(font.Name, font);
}
catch (Exception e) {
@ -114,12 +111,8 @@ namespace ConformalDecals {
var colors = new[] {color, color, color, color};
var tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
for (var x = 0; x <= width; x++) {
for (var y = 0; y < height; y++) {
tex.SetPixels32(colors);
}
}
tex.SetPixels32(colors);
tex.Apply();
return tex;
@ -133,7 +126,7 @@ namespace ConformalDecals {
var configs = GameDatabase.Instance.GetConfigs("CONFORMALDECALS");
if (configs.Length > 0) {
Logging.Log("loading config");
Logging.Log("Loading config");
foreach (var config in configs) {
ParseConfig(config.config);
}

View File

@ -0,0 +1,9 @@
using UnityEngine;
namespace ConformalDecals {
public interface IProjectionTarget {
bool Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectionBounds);
void Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera);
ConfigNode Save();
}
}

View File

@ -8,7 +8,7 @@ namespace ConformalDecals.MaterialProperties {
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);
ParseUtil.ParseBoolIndirect(ref value, node, "value");
value = ParseUtil.ParseBool(node, "value", true, true);
}
public override void Modify(Material material) {

View File

@ -105,6 +105,28 @@ namespace ConformalDecals.MaterialProperties {
_materialProperties ??= new Dictionary<string, MaterialProperty>();
}
public void Load(ConfigNode node) {
// add keyword nodes
foreach (var keywordNode in node.GetNodes("KEYWORD")) {
ParseProperty<MaterialKeywordProperty>(keywordNode);
}
// add texture nodes
foreach (var textureNode in node.GetNodes("TEXTURE")) {
ParseProperty<MaterialTextureProperty>(textureNode);
}
// add float nodes
foreach (var floatNode in node.GetNodes("FLOAT")) {
ParseProperty<MaterialTextureProperty>(floatNode);
}
// add color nodes
foreach (var colorNode in node.GetNodes("COLOR")) {
ParseProperty<MaterialColorProperty>(colorNode);
}
}
public void OnDestroy() {
if (_decalMaterial != null) Destroy(_decalMaterial);
if (_previewMaterial != null) Destroy(_previewMaterial);
@ -186,13 +208,14 @@ namespace ConformalDecals.MaterialProperties {
public T ParseProperty<T>(ConfigNode node) where T : MaterialProperty {
string propertyName = "";
if (!ParseUtil.ParseStringIndirect(ref propertyName, node, "name")) throw new ArgumentException("node has no name");
Logging.Log($"Parsing material property {propertyName}");
if (ParseUtil.ParseBool(node, "remove", true)) RemoveProperty(propertyName);
var newProperty = AddOrGetProperty<T>(propertyName);
newProperty.ParseNode(node);
if (newProperty is MaterialTextureProperty textureProperty && textureProperty.isMain) {
if (newProperty is MaterialTextureProperty {isMain: true} textureProperty) {
_mainTexture = textureProperty;
}

View File

@ -44,7 +44,7 @@ namespace ConformalDecals.MaterialProperties {
public float AspectRatio {
get {
if (_texture == null) return 1;
if (_textureUrl?.Contains("Squad/Flags") == true) return 0.625f;
if (_textureUrl?.Contains("Squad/Flags") == true) return 0.625f; // squad flags are slightly stretched, so unstretch them
return MaskedHeight / (float) MaskedWidth;
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ConformalDecals.MaterialProperties;
using ConformalDecals.Util;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -79,7 +80,9 @@ namespace ConformalDecals {
UI_FloatRange()]
public float wear = 100;
[KSPField(isPersistant = true)] public bool projectMultiple; // reserved for future features. do not modify
[KSPField(guiName = "#LOC_ConformalDecals_gui-multiproject", guiActive = false, guiActiveEditor = true, isPersistant = true),
UI_Toggle()]
public bool projectMultiple = true;
[KSPField] public MaterialPropertyCollection materialProperties;
@ -96,7 +99,7 @@ namespace ConformalDecals {
private const int DecalQueueMax = 2400;
private static int _decalQueueCounter = -1;
private List<ProjectionTarget> _targets;
private Dictionary<Part, ProjectionPartTarget> _targets = new Dictionary<Part, ProjectionPartTarget>();
private bool _isAttached;
private Matrix4x4 _orthoMatrix;
@ -116,6 +119,8 @@ namespace ConformalDecals {
}
}
// EVENTS
/// <inheritdoc />
public override void OnAwake() {
base.OnAwake();
@ -130,114 +135,39 @@ namespace ConformalDecals {
/// <inheritdoc />
public override void OnLoad(ConfigNode node) {
// Load
try {
// SETUP TRANSFORMS
decalFrontTransform = part.FindModelTransform(decalFront);
if (decalFrontTransform == null) throw new FormatException($"Could not find decalFront transform: '{decalFront}'.");
decalBackTransform = part.FindModelTransform(decalBack);
if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
decalModelTransform = part.FindModelTransform(decalModel);
if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
decalProjectorTransform = part.FindModelTransform(decalProjector);
if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
decalColliderTransform = part.FindModelTransform(decalCollider);
if (decalColliderTransform == null) throw new FormatException($"Could not find decalCollider transform: '{decalCollider}'.");
// SETUP BACK MATERIAL
if (updateBackScale) {
var backRenderer = decalBackTransform.GetComponent<MeshRenderer>();
if (backRenderer == null) {
this.LogError($"Specified decalBack transform {decalBack} has no renderer attached! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
backMaterial = backRenderer.material;
if (backMaterial == null) {
this.LogError($"Specified decalBack transform {decalBack} has a renderer but no material! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
if (backTextureBaseScale == default) backTextureBaseScale = backMaterial.GetTextureScale(PropertyIDs._MainTex);
}
}
}
// PARSE MATERIAL PROPERTIES
// set shader
materialProperties.SetShader(shader);
materialProperties.AddOrGetProperty<MaterialKeywordProperty>("DECAL_BASE_NORMAL").value = useBaseNormal;
// add keyword nodes
foreach (var keywordNode in node.GetNodes("KEYWORD")) {
materialProperties.ParseProperty<MaterialKeywordProperty>(keywordNode);
}
// add texture nodes
foreach (var textureNode in node.GetNodes("TEXTURE")) {
materialProperties.ParseProperty<MaterialTextureProperty>(textureNode);
}
// add float nodes
foreach (var floatNode in node.GetNodes("FLOAT")) {
materialProperties.ParseProperty<MaterialTextureProperty>(floatNode);
}
// add color nodes
foreach (var colorNode in node.GetNodes("COLOR")) {
materialProperties.ParseProperty<MaterialColorProperty>(colorNode);
}
// handle texture tiling parameters
var tileString = node.GetValue("tile");
if (!string.IsNullOrEmpty(tileString)) {
var tileValid = ParseExtensions.TryParseRect(tileString, out tileRect);
if (!tileValid) throw new FormatException($"Invalid rect value for tile '{tileString}'");
}
if (tileRect.x >= 0) {
materialProperties.UpdateTile(tileRect);
}
else if (tileIndex >= 0) {
materialProperties.UpdateTile(tileIndex, tileSize);
}
LoadDecal(node);
}
catch (Exception e) {
this.LogException("Exception parsing partmodule", e);
this.LogException("Error loading decal", e);
}
UpdateMaterials();
foreach (var keyword in _decalMaterial.shaderKeywords) {
this.Log($"keyword: {keyword}");
// Setup
try {
SetupDecal();
}
if (HighLogic.LoadedSceneIsEditor) {
UpdateTweakables();
}
if (HighLogic.LoadedSceneIsGame) {
UpdateScale();
}
else {
scale = defaultScale;
depth = defaultDepth;
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
catch (Exception e) {
this.LogException("Error setting up decal", e);
}
}
/// <inheritdoc />
public override void OnSave(ConfigNode node) {
// SAVE TARGETS
if (HighLogic.LoadedSceneIsFlight) {
foreach (var partTarget in _targets.Values) {
if (partTarget.enabled) node.AddNode(partTarget.Save());
}
}
base.OnSave(node);
}
/// <inheritdoc />
public override void OnIconCreate() {
UpdateScale();
UpdateTextures();
UpdateProjection();
}
/// <inheritdoc />
@ -255,6 +185,8 @@ namespace ConformalDecals {
}
}
/// Called after OnStart is finished for all parts
/// This is mostly used to make sure all B9 variants are already in place for the rest of the vessel
public override void OnStartFinished(StartState state) {
// handle game events
if (HighLogic.LoadedSceneIsGame) {
@ -283,6 +215,7 @@ namespace ConformalDecals {
}
}
/// Called when the decal is destroyed
public virtual void OnDestroy() {
// remove GameEvents
if (HighLogic.LoadedSceneIsEditor) {
@ -301,17 +234,21 @@ namespace ConformalDecals {
Destroy(materialProperties);
}
protected void OnSizeTweakEvent(BaseField field, object obj) {
/// Called when the decal's projection and scale is modified through a tweakable
protected void OnProjectionTweakEvent(BaseField field, object obj) {
// scale or depth values have been changed, so update scale
// and update projection matrices if attached
UpdateScale();
UpdateProjection();
UpdateTargets();
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalDecal>();
decal.UpdateScale();
decal.UpdateProjection();
decal.UpdateTargets();
}
}
/// Called when the decal's material is modified through a tweakable
protected void OnMaterialTweakEvent(BaseField field, object obj) {
materialProperties.SetOpacity(opacity);
materialProperties.SetCutoff(cutoff);
@ -329,35 +266,85 @@ namespace ConformalDecals {
}
}
/// Called when a new variant is applied in the editor
protected void OnVariantApplied(Part eventPart, PartVariant variant) {
if (_isAttached && eventPart == part.parent) {
if (_isAttached && eventPart != null && (!projectMultiple || eventPart == part.parent)) {
_targets.Remove(eventPart);
UpdateTargets();
}
}
/// Called when an editor event occurs
protected void OnEditorEvent(ConstructionEventType eventType, Part eventPart) {
if (this.part != eventPart && !part.symmetryCounterparts.Contains(eventPart)) return;
switch (eventType) {
case ConstructionEventType.PartAttached:
OnAttach();
OnPartAttached(eventPart);
break;
case ConstructionEventType.PartDetached:
OnDetach();
OnPartDetached(eventPart);
break;
case ConstructionEventType.PartOffsetting:
case ConstructionEventType.PartRotating:
UpdateScale();
OnPartTransformed(eventPart);
break;
}
}
/// Called when a part is transformed in the editor
protected void OnPartTransformed(Part eventPart) {
if (this.part == eventPart) {
UpdateProjection();
UpdateTargets();
}
else if (_isAttached && projectMultiple) {
UpdatePartTarget(eventPart, _boundsRenderer.bounds);
// recursively call for child parts
foreach (var child in eventPart.children) {
OnPartTransformed(child);
}
}
}
/// Called when a part is attached in the editor
protected void OnPartAttached(Part eventPart) {
if (this.part == eventPart) {
OnAttach();
}
else if (projectMultiple) {
UpdatePartTarget(eventPart, _boundsRenderer.bounds);
// recursively call for child parts
foreach (var child in eventPart.children) {
OnPartAttached(child);
}
}
}
/// Called when a part is detached in the editor
protected void OnPartDetached(Part eventPart) {
if (this.part == eventPart) {
OnDetach();
}
else if (projectMultiple) {
_targets.Remove(eventPart);
// recursively call for child parts
foreach (var child in eventPart.children) {
OnPartDetached(child);
}
}
}
/// Called when part `willDie` will be destroyed
protected void OnPartWillDie(Part willDie) {
if (willDie == part.parent) {
this.Log("Parent part about to be destroyed! Killing decal part.");
part.Die();
}
else if (projectMultiple) {
_targets.Remove(willDie);
}
}
/// Called when decal is attached to a new part
protected virtual void OnAttach() {
if (part.parent == null) {
this.LogError("Attach function called but part has no parent!");
@ -377,10 +364,11 @@ namespace ConformalDecals {
Camera.onPreCull += Render;
UpdateMaterials();
UpdateProjection();
UpdateTargets();
UpdateScale();
}
/// Called when decal is detached from its parent part
protected virtual void OnDetach() {
_isAttached = false;
@ -394,10 +382,216 @@ namespace ConformalDecals {
Camera.onPreCull -= Render;
UpdateMaterials();
UpdateScale();
UpdateProjection();
}
protected void UpdateScale() {
// FUNCTIONS
/// Load any settings from the decal config
protected virtual void LoadDecal(ConfigNode node) {
// PARSE TRANSFORMS
decalFrontTransform = part.FindModelTransform(decalFront);
if (decalFrontTransform == null) throw new FormatException($"Could not find decalFront transform: '{decalFront}'.");
decalBackTransform = part.FindModelTransform(decalBack);
if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
decalModelTransform = part.FindModelTransform(decalModel);
if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
decalProjectorTransform = part.FindModelTransform(decalProjector);
if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
decalColliderTransform = part.FindModelTransform(decalCollider);
if (decalColliderTransform == null) throw new FormatException($"Could not find decalCollider transform: '{decalCollider}'.");
// SETUP BACK MATERIAL
if (updateBackScale) {
var backRenderer = decalBackTransform.GetComponent<MeshRenderer>();
if (backRenderer == null) {
this.LogError($"Specified decalBack transform {decalBack} has no renderer attached! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
backMaterial = backRenderer.material;
if (backMaterial == null) {
this.LogError($"Specified decalBack transform {decalBack} has a renderer but no material! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
if (backTextureBaseScale == default) backTextureBaseScale = backMaterial.GetTextureScale(PropertyIDs._MainTex);
}
}
}
// PARSE MATERIAL PROPERTIES
// set shader
materialProperties.SetShader(shader);
materialProperties.AddOrGetProperty<MaterialKeywordProperty>("DECAL_BASE_NORMAL").value = useBaseNormal;
materialProperties.Load(node);
// handle texture tiling parameters
var tileString = node.GetValue("tile");
if (!string.IsNullOrEmpty(tileString)) {
var tileValid = ParseExtensions.TryParseRect(tileString, out tileRect);
if (!tileValid) throw new FormatException($"Invalid rect value for tile '{tileString}'");
}
if (tileRect.x >= 0) {
materialProperties.UpdateTile(tileRect);
}
else if (tileIndex >= 0) {
materialProperties.UpdateTile(tileIndex, tileSize);
}
// PARSE TARGETS
if (HighLogic.LoadedSceneIsFlight) {
foreach (var partTargetNode in node.GetNodes(ProjectionPartTarget.NodeName)) {
try {
var partTarget = new ProjectionPartTarget(partTargetNode, part.vessel, useBaseNormal);
_targets.Add(partTarget.part, partTarget);
}
catch (Exception e) {
this.LogWarning($"Encountered error while parsing part node: {e}");
}
}
}
}
/// Setup decal by calling update functions relevent for the current situation
protected virtual void SetupDecal() {
if (HighLogic.LoadedSceneIsEditor) {
// Update tweakables in editor mode
UpdateTweakables();
}
if (HighLogic.LoadedSceneIsGame) {
UpdateAll();
}
else {
scale = defaultScale;
depth = defaultDepth;
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
UpdateAll();
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
}
}
/// Update decal editor tweakables
protected virtual void UpdateTweakables() {
// setup tweakable fields
var scaleField = Fields[nameof(scale)];
var depthField = Fields[nameof(depth)];
var opacityField = Fields[nameof(opacity)];
var cutoffField = Fields[nameof(cutoff)];
var wearField = Fields[nameof(wear)];
var multiprojectField = Fields[nameof(projectMultiple)];
scaleField.guiActiveEditor = scaleAdjustable;
depthField.guiActiveEditor = depthAdjustable;
opacityField.guiActiveEditor = opacityAdjustable;
cutoffField.guiActiveEditor = cutoffAdjustable;
wearField.guiActiveEditor = useBaseNormal;
var steps = 20;
if (scaleAdjustable) {
var minValue = Mathf.Max(Mathf.Epsilon, scaleRange.x);
var maxValue = Mathf.Max(minValue, scaleRange.y);
var scaleEditor = (UI_FloatRange) scaleField.uiControlEditor;
scaleEditor.minValue = minValue;
scaleEditor.maxValue = maxValue;
scaleEditor.stepIncrement = 0.01f; //1cm
scaleEditor.onFieldChanged = OnProjectionTweakEvent;
}
if (depthAdjustable) {
var minValue = Mathf.Max(Mathf.Epsilon, depthRange.x);
var maxValue = Mathf.Max(minValue, depthRange.y);
var depthEditor = (UI_FloatRange) depthField.uiControlEditor;
depthEditor.minValue = minValue;
depthEditor.maxValue = maxValue;
depthEditor.stepIncrement = 0.01f; //1cm
depthEditor.onFieldChanged = OnProjectionTweakEvent;
}
if (opacityAdjustable) {
var minValue = Mathf.Max(0, opacityRange.x);
var maxValue = Mathf.Max(minValue, opacityRange.y);
maxValue = Mathf.Min(1, maxValue);
var opacityEditor = (UI_FloatRange) opacityField.uiControlEditor;
opacityEditor.minValue = minValue;
opacityEditor.maxValue = maxValue;
opacityEditor.stepIncrement = (maxValue - minValue) / steps;
opacityEditor.onFieldChanged = OnMaterialTweakEvent;
}
if (cutoffAdjustable) {
var minValue = Mathf.Max(0, cutoffRange.x);
var maxValue = Mathf.Max(minValue, cutoffRange.y);
maxValue = Mathf.Min(1, maxValue);
var cutoffEditor = (UI_FloatRange) cutoffField.uiControlEditor;
cutoffEditor.minValue = minValue;
cutoffEditor.maxValue = maxValue;
cutoffEditor.stepIncrement = (maxValue - minValue) / steps;
cutoffEditor.onFieldChanged = OnMaterialTweakEvent;
}
if (useBaseNormal) {
var minValue = Mathf.Max(0, wearRange.x);
var maxValue = Mathf.Max(minValue, wearRange.y);
var wearEditor = (UI_FloatRange) wearField.uiControlEditor;
wearEditor.minValue = minValue;
wearEditor.maxValue = maxValue;
wearEditor.stepIncrement = (maxValue - minValue) / steps;
wearEditor.onFieldChanged = OnMaterialTweakEvent;
}
var multiprojectEditor = (UI_Toggle) multiprojectField.uiControlEditor;
multiprojectEditor.onFieldChanged = OnProjectionTweakEvent;
}
/// Updates textures, materials, scale and targets
protected virtual void UpdateAll() {
UpdateTextures();
UpdateMaterials();
UpdateProjection();
UpdateTargets();
}
/// Update decal textures
protected virtual void UpdateTextures() { }
/// Update decal materials
protected virtual void UpdateMaterials() {
materialProperties.UpdateMaterials();
materialProperties.SetOpacity(opacity);
materialProperties.SetCutoff(cutoff);
if (useBaseNormal) {
materialProperties.SetWear(wear);
}
_decalMaterial = materialProperties.DecalMaterial;
_previewMaterial = materialProperties.PreviewMaterial;
if (!_isAttached) decalFrontTransform.GetComponent<MeshRenderer>().material = _previewMaterial;
}
/// Update decal scale and projection
protected void UpdateProjection() {
// Update scale and depth
scale = Mathf.Max(0.01f, scale);
depth = Mathf.Max(0.01f, depth);
var aspectRatio = Mathf.Max(0.01f, materialProperties.AspectRatio);
@ -437,11 +631,6 @@ namespace ConformalDecals {
_orthoMatrix[1, 3] = 0.5f;
decalProjectorTransform.localScale = new Vector3(size.x, size.y, depth);
// update projection
foreach (var target in _targets) {
target.Project(_orthoMatrix, decalProjectorTransform, _boundsRenderer.bounds, useBaseNormal);
}
}
else {
// rescale preview model
@ -454,129 +643,54 @@ namespace ConformalDecals {
}
}
protected virtual void UpdateMaterials() {
materialProperties.UpdateMaterials();
materialProperties.SetOpacity(opacity);
materialProperties.SetCutoff(cutoff);
if (useBaseNormal) {
materialProperties.SetWear(wear);
}
_decalMaterial = materialProperties.DecalMaterial;
_previewMaterial = materialProperties.PreviewMaterial;
if (!_isAttached) decalFrontTransform.GetComponent<MeshRenderer>().material = _previewMaterial;
}
/// Called when updating decal targets
protected void UpdateTargets() {
if (_targets == null) {
_targets = new List<ProjectionTarget>();
if (!_isAttached) return;
var projectionBounds = _boundsRenderer.bounds;
// collect list of potential targets
IEnumerable<Part> targetParts;
if (projectMultiple) {
targetParts = HighLogic.LoadedSceneIsFlight ? part.vessel.parts : EditorLogic.fetch.ship.parts;
}
else {
_targets.Clear();
targetParts = new[] {part.parent};
}
// find all valid renderers
var renderers = part.parent.FindModelComponents<MeshRenderer>();
foreach (var renderer in renderers) {
// skip disabled renderers
if (renderer.gameObject.activeInHierarchy == false) continue;
// skip blacklisted shaders
if (DecalConfig.IsBlacklisted(renderer.material.shader)) continue;
var meshFilter = renderer.GetComponent<MeshFilter>();
if (meshFilter == null) continue; // object has a meshRenderer with no filter, invalid
var mesh = meshFilter.mesh;
if (mesh == null) continue; // object has a null mesh, invalid
// create new ProjectionTarget to represent the renderer
var target = new ProjectionTarget(renderer, mesh);
// add the target to the list
_targets.Add(target);
foreach (var targetPart in targetParts) {
UpdatePartTarget(targetPart, projectionBounds);
}
}
protected virtual void UpdateTweakables() {
// setup tweakable fields
var scaleField = Fields[nameof(scale)];
var depthField = Fields[nameof(depth)];
var opacityField = Fields[nameof(opacity)];
var cutoffField = Fields[nameof(cutoff)];
var wearField = Fields[nameof(wear)];
protected void UpdatePartTarget(Part targetPart, Bounds projectionBounds) {
if (targetPart.GetComponent<ModuleConformalDecal>() != null) return; // skip other decals
scaleField.guiActiveEditor = scaleAdjustable;
depthField.guiActiveEditor = depthAdjustable;
opacityField.guiActiveEditor = opacityAdjustable;
cutoffField.guiActiveEditor = cutoffAdjustable;
wearField.guiActiveEditor = useBaseNormal;
this.Log($"Updating projection onto part {targetPart.name}");
var steps = 20;
if (!_targets.TryGetValue(targetPart, out var target)) {
var rendererList = targetPart.FindModelComponents<MeshRenderer>();
if (scaleAdjustable) {
var minValue = Mathf.Max(Mathf.Epsilon, scaleRange.x);
var maxValue = Mathf.Max(minValue, scaleRange.y);
var scaleEditor = (UI_FloatRange) scaleField.uiControlEditor;
scaleEditor.minValue = minValue;
scaleEditor.maxValue = maxValue;
scaleEditor.stepIncrement = 0.01f; //1cm
scaleEditor.onFieldChanged = OnSizeTweakEvent;
if (rendererList.Any(o => projectionBounds.Intersects(o.bounds))) {
target = new ProjectionPartTarget(targetPart, useBaseNormal);
_targets.Add(targetPart, target);
}
else {
return;
}
}
if (depthAdjustable) {
var minValue = Mathf.Max(Mathf.Epsilon, depthRange.x);
var maxValue = Mathf.Max(minValue, depthRange.y);
this.Log($"valid target: {targetPart.name}");
var depthEditor = (UI_FloatRange) depthField.uiControlEditor;
depthEditor.minValue = minValue;
depthEditor.maxValue = maxValue;
depthEditor.stepIncrement = 0.01f; //1cm
depthEditor.onFieldChanged = OnSizeTweakEvent;
}
if (opacityAdjustable) {
var minValue = Mathf.Max(0, opacityRange.x);
var maxValue = Mathf.Max(minValue, opacityRange.y);
maxValue = Mathf.Min(1, maxValue);
var opacityEditor = (UI_FloatRange) opacityField.uiControlEditor;
opacityEditor.minValue = minValue;
opacityEditor.maxValue = maxValue;
opacityEditor.stepIncrement = (maxValue - minValue) / steps;
opacityEditor.onFieldChanged = OnMaterialTweakEvent;
}
if (cutoffAdjustable) {
var minValue = Mathf.Max(0, cutoffRange.x);
var maxValue = Mathf.Max(minValue, cutoffRange.y);
maxValue = Mathf.Min(1, maxValue);
var cutoffEditor = (UI_FloatRange) cutoffField.uiControlEditor;
cutoffEditor.minValue = minValue;
cutoffEditor.maxValue = maxValue;
cutoffEditor.stepIncrement = (maxValue - minValue) / steps;
cutoffEditor.onFieldChanged = OnMaterialTweakEvent;
}
if (useBaseNormal) {
var minValue = Mathf.Max(0, wearRange.x);
var maxValue = Mathf.Max(minValue, wearRange.y);
var wearEditor = (UI_FloatRange) wearField.uiControlEditor;
wearEditor.minValue = minValue;
wearEditor.maxValue = maxValue;
wearEditor.stepIncrement = (maxValue - minValue) / steps;
wearEditor.onFieldChanged = OnMaterialTweakEvent;
}
target.Project(_orthoMatrix, decalProjectorTransform, projectionBounds);
}
/// Render the decal
public void Render(Camera camera) {
if (!_isAttached) return;
// render on each target object
foreach (var target in _targets) {
foreach (var target in _targets.Values) {
target.Render(_decalMaterial, part.mpb, camera);
}
}

View File

@ -1,4 +1,6 @@
using ConformalDecals.MaterialProperties;
using ConformalDecals.Util;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -9,6 +11,8 @@ namespace ConformalDecals {
[KSPField(isPersistant = true)] public bool useCustomFlag;
private MaterialTextureProperty _flagTextureProperty;
public string MissionFlagUrl {
get {
if (HighLogic.LoadedSceneIsEditor) {
@ -23,17 +27,6 @@ namespace ConformalDecals {
}
}
public override void OnLoad(ConfigNode node) {
base.OnLoad(node);
if (useCustomFlag) {
SetFlag(flagUrl);
}
else {
SetFlag(MissionFlagUrl);
}
}
public override void OnStart(StartState state) {
base.OnStart(state);
@ -44,17 +37,10 @@ namespace ConformalDecals {
if (HighLogic.LoadedSceneIsEditor) {
Events[nameof(ResetFlag)].guiActiveEditor = useCustomFlag;
}
if (useCustomFlag) {
SetFlag(flagUrl);
}
else {
SetFlag(MissionFlagUrl);
}
}
public override void OnDestroy() {
GameEvents.onMissionFlagSelect.Remove(SetFlag);
GameEvents.onMissionFlagSelect.Remove(OnEditorFlagSelected);
base.OnDestroy();
}
@ -66,44 +52,45 @@ namespace ConformalDecals {
[KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "#LOC_ConformalDecals_gui-reset-flag")]
public void ResetFlag() {
SetFlag(MissionFlagUrl);
SetFlagSymmetryCounterparts(MissionFlagUrl);
useCustomFlag = false;
Events[nameof(ResetFlag)].guiActiveEditor = false;
}
private void OnCustomFlagSelected(FlagBrowser.FlagEntry newFlagEntry) {
SetFlag(newFlagEntry.textureInfo.name);
SetFlagSymmetryCounterparts(newFlagEntry.textureInfo.name);
useCustomFlag = true;
Events[nameof(ResetFlag)].guiActiveEditor = true;
}
private void OnEditorFlagSelected(string newFlagUrl) {
if (!useCustomFlag) {
SetFlag(newFlagUrl);
SetFlagSymmetryCounterparts(newFlagUrl);
flagUrl = MissionFlagUrl;
useCustomFlag = false;
UpdateAll();
foreach (var decal in part.symmetryCounterparts.Select(o => o.GetComponent<ModuleConformalFlag>())) {
decal.Events[nameof(ResetFlag)].guiActiveEditor = false;
decal.flagUrl = flagUrl;
decal.useCustomFlag = false;
decal.UpdateAll();
}
}
private void SetFlag(string newFlagUrl) {
this.Log($"Loading flag texture '{newFlagUrl}'.");
private void OnCustomFlagSelected(FlagBrowser.FlagEntry newFlagEntry) {
Events[nameof(ResetFlag)].guiActiveEditor = true;
flagUrl = newFlagEntry.textureInfo.name;
useCustomFlag = true;
UpdateAll();
flagUrl = newFlagUrl;
materialProperties.AddOrGetTextureProperty("_Decal", true).TextureUrl = newFlagUrl;
UpdateMaterials();
UpdateScale();
foreach (var decal in part.symmetryCounterparts.Select(o => o.GetComponent<ModuleConformalFlag>())) {
decal.Events[nameof(ResetFlag)].guiActiveEditor = true;
decal.flagUrl = flagUrl;
decal.useCustomFlag = true;
decal.UpdateAll();
}
}
private void SetFlagSymmetryCounterparts(string newFlagUrl) {
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalFlag>();
private void OnEditorFlagSelected(string newFlagUrl) {
if (!useCustomFlag) UpdateAll();
}
decal.SetFlag(newFlagUrl);
decal.useCustomFlag = useCustomFlag;
protected override void UpdateTextures() {
_flagTextureProperty ??= materialProperties.AddOrGetTextureProperty("_Decal", true);
base.UpdateTextures();
if (useCustomFlag) {
_flagTextureProperty.TextureUrl = flagUrl;
}
else {
_flagTextureProperty.TextureUrl = MissionFlagUrl;
}
}
}

View File

@ -5,6 +5,7 @@ using ConformalDecals.Text;
using ConformalDecals.UI;
using ConformalDecals.Util;
using TMPro;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -89,41 +90,11 @@ namespace ConformalDecals {
private MaterialColorProperty _outlineColorProperty;
private MaterialFloatProperty _outlineWidthProperty;
private DecalText _currentText;
private DecalText _currentText;
public override void OnLoad(ConfigNode node) {
base.OnLoad(node);
string textRaw = "";
if (ParseUtil.ParseStringIndirect(ref textRaw, node, "text")) {
text = WebUtility.UrlDecode(textRaw);
}
string fontName = "";
if (ParseUtil.ParseStringIndirect(ref fontName, node, "fontName")) {
font = DecalConfig.GetFont(fontName);
}
else if (font == null) font = DecalConfig.GetFont("Calibri SDF");
int styleInt = 0;
if (ParseUtil.ParseIntIndirect(ref styleInt, node, "style")) {
style = (FontStyles) styleInt;
}
ParseUtil.ParseColor32Indirect(ref fillColor, node, "fillColor");
ParseUtil.ParseColor32Indirect(ref outlineColor, node, "outlineColor");
if (HighLogic.LoadedSceneIsGame) {
// For some reason, rendering doesnt work right on the first frame a scene is loaded
// So delay any rendering until the next frame when called in OnLoad
// This is probably a problem with Unity, not KSP
StartCoroutine(UpdateTextLate());
}
else {
UpdateText();
}
}
// EVENTS
/// <inheritdoc />
public override void OnSave(ConfigNode node) {
node.AddValue("text", WebUtility.UrlEncode(text));
node.AddValue("fontName", font.Name);
@ -147,13 +118,23 @@ namespace ConformalDecals {
}
public void OnTextUpdate(string newText, DecalFont newFont, FontStyles newStyle, bool newVertical, float newLineSpacing, float newCharSpacing) {
this.text = newText;
this.font = newFont;
this.style = newStyle;
this.vertical = newVertical;
this.lineSpacing = newLineSpacing;
this.charSpacing = newCharSpacing;
UpdateTextRecursive();
text = newText;
font = newFont;
style = newStyle;
vertical = newVertical;
lineSpacing = newLineSpacing;
charSpacing = newCharSpacing;
UpdateAll();
foreach (var decal in part.symmetryCounterparts.Select(o => o.GetComponent<ModuleConformalText>())) {
decal.text = newText;
decal.font = newFont;
decal.style = newStyle;
decal.vertical = newVertical;
decal.lineSpacing = newLineSpacing;
decal.charSpacing = newCharSpacing;
decal.UpdateAll();
}
}
public void OnFillColorUpdate(Color rgb, Util.ColorHSV hsv) {
@ -240,48 +221,70 @@ namespace ConformalDecals {
base.OnDetach();
}
private void UpdateTextRecursive() {
UpdateText();
// FUNCTIONS
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalText>();
decal.text = text;
decal.font = font;
decal.style = style;
decal.vertical = vertical;
decal.charSpacing = charSpacing;
decal.lineSpacing = lineSpacing;
protected override void LoadDecal(ConfigNode node) {
base.LoadDecal(node);
decal._currentText = _currentText;
decal.UpdateText();
string textRaw = "";
if (ParseUtil.ParseStringIndirect(ref textRaw, node, "text")) {
text = WebUtility.UrlDecode(textRaw);
}
string fontName = "";
if (ParseUtil.ParseStringIndirect(ref fontName, node, "fontName")) {
font = DecalConfig.GetFont(fontName);
}
else if (font == null) font = DecalConfig.GetFont("Calibri SDF");
int styleInt = 0;
if (ParseUtil.ParseIntIndirect(ref styleInt, node, "style")) {
style = (FontStyles) styleInt;
}
ParseUtil.ParseColor32Indirect(ref fillColor, node, "fillColor");
ParseUtil.ParseColor32Indirect(ref outlineColor, node, "outlineColor");
}
protected override void SetupDecal() {
if (HighLogic.LoadedSceneIsEditor) {
// Update tweakables in editor mode
UpdateTweakables();
}
if (HighLogic.LoadedSceneIsGame) {
// For some reason text rendering fails on the first frame of a scene, so this is my workaround
StartCoroutine(UpdateTextLate());
}
else {
scale = defaultScale;
depth = defaultDepth;
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
UpdateTextures();
UpdateMaterials();
UpdateProjection();
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
}
}
private IEnumerator UpdateTextLate() {
yield return null;
UpdateText();
UpdateAll();
}
private void UpdateText() {
protected override void UpdateTextures() {
// Render text
var newText = new DecalText(text, font, style, vertical, lineSpacing, charSpacing);
var output = TextRenderer.UpdateText(_currentText, newText);
_currentText = newText;
UpdateTexture(output);
// TODO: ASYNC RENDERING
// var newText = new DecalText(text, _font, _style);
// _currentJob = TextRenderer.UpdateText(_currentText, newText, UpdateTexture);
// _currentText = newText;
}
public void UpdateTexture(TextRenderOutput output) {
_decalTextureProperty.Texture = output.Texture;
_decalTextureProperty.SetTile(output.Window);
UpdateMaterials();
UpdateScale();
}
protected override void UpdateMaterials() {

View File

@ -0,0 +1,167 @@
using System;
using System.Text;
using ConformalDecals.Util;
using UniLinq;
using UnityEngine;
using UnityEngine.Rendering;
namespace ConformalDecals {
public class ProjectionMeshTarget : IProjectionTarget {
public const string NodeName = "MESH_TARGET";
// enabled flag
public bool enabled;
// Target object data
public readonly Transform target;
public readonly Transform root;
public readonly Mesh mesh;
public readonly MeshRenderer renderer;
// Projection data
private Matrix4x4 _decalMatrix;
private Vector3 _decalNormal;
private Vector3 _decalTangent;
// property block
private readonly MaterialPropertyBlock _decalMPB;
public ProjectionMeshTarget(Transform target, Transform root, MeshRenderer renderer, Mesh mesh, bool useBaseNormal) {
this.root = root;
this.target = target;
this.renderer = renderer;
this.mesh = mesh;
_decalMPB = new MaterialPropertyBlock();
SetNormalMap(renderer.sharedMaterial, useBaseNormal);
}
public ProjectionMeshTarget(ConfigNode node, Transform root, bool useBaseNormal) {
if (node == null) throw new ArgumentNullException(nameof(node));
if (root == null) throw new ArgumentNullException(nameof(root));
enabled = true;
var targetPath = ParseUtil.ParseString(node, "targetPath");
var targetName = ParseUtil.ParseString(node, "targetName");
_decalMatrix = ParseUtil.ParseMatrix4x4(node, "decalMatrix");
_decalNormal = ParseUtil.ParseVector3(node, "decalNormal");
_decalTangent = ParseUtil.ParseVector3(node, "decalTangent");
_decalMPB = new MaterialPropertyBlock();
target = LoadTransformPath(targetPath, root);
if (target.name != targetName) throw new FormatException("Target name does not match");
renderer = target.GetComponent<MeshRenderer>();
var filter = target.GetComponent<MeshFilter>();
if (!ValidateTarget(target, renderer, filter)) throw new FormatException("Invalid target");
mesh = filter.sharedMesh;
SetNormalMap(renderer.sharedMaterial, useBaseNormal);
_decalMPB.SetMatrix(DecalPropertyIDs._ProjectionMatrix, _decalMatrix);
_decalMPB.SetVector(DecalPropertyIDs._DecalNormal, _decalNormal);
_decalMPB.SetVector(DecalPropertyIDs._DecalTangent, _decalTangent);
}
private void SetNormalMap(Material targetMaterial, bool useBaseNormal) {
if (useBaseNormal && targetMaterial.HasProperty(DecalPropertyIDs._BumpMap)) {
_decalMPB.SetTexture(DecalPropertyIDs._BumpMap, targetMaterial.GetTexture(DecalPropertyIDs._BumpMap));
var normalScale = targetMaterial.GetTextureScale(DecalPropertyIDs._BumpMap);
var normalOffset = targetMaterial.GetTextureOffset(DecalPropertyIDs._BumpMap);
_decalMPB.SetVector(DecalPropertyIDs._BumpMap_ST, new Vector4(normalScale.x, normalScale.y, normalOffset.x, normalOffset.y));
}
else {
_decalMPB.SetTexture(DecalPropertyIDs._BumpMap, DecalConfig.BlankNormal);
}
}
public bool Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectionBounds) {
if (projectionBounds.Intersects(renderer.bounds)) {
enabled = true;
var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix;
_decalMatrix = orthoMatrix * projectorToTargetMatrix.inverse;
_decalNormal = projectorToTargetMatrix.MultiplyVector(Vector3.back).normalized;
_decalTangent = projectorToTargetMatrix.MultiplyVector(Vector3.right).normalized;
_decalMPB.SetMatrix(DecalPropertyIDs._ProjectionMatrix, _decalMatrix);
_decalMPB.SetVector(DecalPropertyIDs._DecalNormal, _decalNormal);
_decalMPB.SetVector(DecalPropertyIDs._DecalTangent, _decalTangent);
}
else {
enabled = false;
}
return enabled;
}
public void Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
if (!enabled) return;
_decalMPB.SetFloat(PropertyIDs._RimFalloff, partMPB.GetFloat(PropertyIDs._RimFalloff));
_decalMPB.SetColor(PropertyIDs._RimColor, partMPB.GetColor(PropertyIDs._RimColor));
Graphics.DrawMesh(mesh, target.localToWorldMatrix, decalMaterial, 0, camera, 0, _decalMPB, ShadowCastingMode.Off, true);
}
public ConfigNode Save() {
var node = new ConfigNode(NodeName);
node.AddValue("decalMatrix", _decalMatrix);
node.AddValue("decalNormal", _decalNormal);
node.AddValue("decalTangent", _decalTangent);
node.AddValue("targetPath", SaveTransformPath(target, root)); // used to find the target transform
node.AddValue("targetName", target.name); // used to validate the mesh has not changed since last load
return node;
}
public static bool ValidateTarget(Transform target, MeshRenderer renderer, MeshFilter filter) {
if (renderer == null) return false;
if (filter == null) return false;
if (!target.gameObject.activeInHierarchy) return false;
var material = renderer.material;
if (material == null) return false;
if (DecalConfig.IsBlacklisted(material.shader)) return false;
if (filter.sharedMesh == null) return false;
return true;
}
private static string SaveTransformPath(Transform leaf, Transform root) {
var builder = new StringBuilder($"{leaf.GetSiblingIndex()}");
var current = leaf.parent;
while (current != root) {
builder.Insert(0, "/");
builder.Insert(0, current.GetSiblingIndex());
current = current.parent;
if (current == null) throw new FormatException("Leaf does not exist as a child of root");
}
return builder.ToString();
}
private static Transform LoadTransformPath(string path, Transform root) {
var indices = path.Split('/').Select(int.Parse);
var current = root;
Logging.Log($"root transform: {current.name}");
foreach (var index in indices) {
if (index > current.childCount) throw new FormatException("Child index path is invalid");
current = current.GetChild(index);
Logging.Log($"found child {current.name} at index {index}");
}
return current;
}
}
}

View File

@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals {
public class ProjectionPartTarget : IProjectionTarget {
public const string NodeName = "PART_TARGET";
// enabled flag
public bool enabled;
// locked flag, to prevent re-projection of loaded targets
public readonly bool locked;
public readonly Part part;
public readonly List<ProjectionMeshTarget> meshTargets = new List<ProjectionMeshTarget>();
public ProjectionPartTarget(Part part, bool useBaseNormal) {
this.part = part;
locked = false;
foreach (var renderer in part.FindModelComponents<MeshRenderer>()) {
var target = renderer.transform;
var filter = target.GetComponent<MeshFilter>();
// check if the target has any missing data
if (!ProjectionMeshTarget.ValidateTarget(target, renderer, filter)) continue;
// create new ProjectionTarget to represent the renderer
var projectionTarget = new ProjectionMeshTarget(target, part.transform, renderer, filter.sharedMesh, useBaseNormal);
// add the target to the list
meshTargets.Add(projectionTarget);
}
}
public ProjectionPartTarget(ConfigNode node, Vessel vessel, bool useBaseNormal) {
if (node == null) throw new ArgumentNullException(nameof(node));
locked = true;
enabled = true;
var flightID = ParseUtil.ParseUint(node, "part");
part = vessel[flightID];
if (part == null) throw new IndexOutOfRangeException("Vessel returned null part, part must be destroyed or detached");
var root = part.transform;
foreach (var meshTargetNode in node.GetNodes(ProjectionMeshTarget.NodeName)) {
meshTargets.Add(new ProjectionMeshTarget(meshTargetNode, root, useBaseNormal));
}
Logging.Log($"Loaded target for part {part.name}");
}
public bool Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectionBounds) {
if (locked) return true; // dont overwrite saved targets in flight mode
enabled = false;
foreach (var meshTarget in meshTargets) {
enabled |= meshTarget.Project(orthoMatrix, projector, projectionBounds);
}
return enabled;
}
public void Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
foreach (var target in meshTargets) {
target.Render(decalMaterial, partMPB, camera);
}
}
public ConfigNode Save() {
var node = new ConfigNode(NodeName);
node.AddValue("part", part.flightID);
foreach (var meshTarget in meshTargets) {
if (meshTarget.enabled) node.AddNode(meshTarget.Save());
}
Logging.Log($"Saved target for part {part.name}");
return node;
}
}
}

View File

@ -1,68 +0,0 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace ConformalDecals {
public class ProjectionTarget {
// Target object data
public readonly Transform target;
private readonly Renderer _targetRenderer;
private readonly Mesh _targetMesh;
private bool _projectionEnabled;
// property block
private readonly MaterialPropertyBlock _decalMPB;
public ProjectionTarget(MeshRenderer targetRenderer, Mesh targetMesh) {
target = targetRenderer.transform;
_targetRenderer = targetRenderer;
_targetMesh = targetMesh;
_decalMPB = new MaterialPropertyBlock();
}
public void Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectorBounds, bool useBaseNormal) {
if (projectorBounds.Intersects(_targetRenderer.bounds)) {
_projectionEnabled = true;
var targetMaterial = _targetRenderer.sharedMaterial;
var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix;
var projectionMatrix = orthoMatrix * projectorToTargetMatrix.inverse;
var decalNormal = projectorToTargetMatrix.MultiplyVector(Vector3.back).normalized;
var decalTangent = projectorToTargetMatrix.MultiplyVector(Vector3.right).normalized;
_decalMPB.SetMatrix(DecalPropertyIDs._ProjectionMatrix, projectionMatrix);
_decalMPB.SetVector(DecalPropertyIDs._DecalNormal, decalNormal);
_decalMPB.SetVector(DecalPropertyIDs._DecalTangent, decalTangent);
if (useBaseNormal && targetMaterial.HasProperty(DecalPropertyIDs._BumpMap)) {
_decalMPB.SetTexture(DecalPropertyIDs._BumpMap, targetMaterial.GetTexture(DecalPropertyIDs._BumpMap));
var normalScale = targetMaterial.GetTextureScale(DecalPropertyIDs._BumpMap);
var normalOffset = targetMaterial.GetTextureOffset(DecalPropertyIDs._BumpMap);
_decalMPB.SetVector(DecalPropertyIDs._BumpMap_ST, new Vector4(normalScale.x, normalScale.y, normalOffset.x, normalOffset.y));
}
else {
_decalMPB.SetTexture(DecalPropertyIDs._BumpMap, DecalConfig.BlankNormal);
}
}
else {
_projectionEnabled = false;
}
}
public bool Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
if (_projectionEnabled) {
_decalMPB.SetFloat(PropertyIDs._RimFalloff, partMPB.GetFloat(PropertyIDs._RimFalloff));
_decalMPB.SetColor(PropertyIDs._RimColor, partMPB.GetColor(PropertyIDs._RimColor));
Graphics.DrawMesh(_targetMesh, target.localToWorldMatrix, decalMaterial, 0, camera, 0, _decalMPB, ShadowCastingMode.Off, true);
return true;
}
return false;
}
}
}

View File

@ -46,21 +46,25 @@ namespace ConformalDecals.Text {
public bool SmallCapsMask => (_fontStyleMask & FontStyles.SmallCaps) != 0;
public DecalFont(ConfigNode node, IEnumerable<TMP_FontAsset> fontAssets) {
public static DecalFont Parse(ConfigNode node, IEnumerable<TMP_FontAsset> fontAssets) {
if (node == null) throw new ArgumentNullException(nameof(node));
if (fontAssets == null) throw new ArgumentNullException(nameof(fontAssets));
var font = ScriptableObject.CreateInstance<DecalFont>();
var name = ParseUtil.ParseString(node, "name");
_fontAsset = fontAssets.First(o => o.name == name);
if (FontAsset == null) {
var fontAsset = fontAssets.First(o => o.name == name);
if (fontAsset == null) {
throw new FormatException($"Could not find font asset named {name}");
}
_title = ParseUtil.ParseString(node, "title", true, name);
_fontStyle = (FontStyles) ParseUtil.ParseInt(node, "style", true);
_fontStyleMask = (FontStyles) ParseUtil.ParseInt(node, "styleMask", true);
}
font._fontAsset = fontAsset;
font._title = ParseUtil.ParseString(node, "title", true, name);
font._fontStyle = (FontStyles) ParseUtil.ParseInt(node, "style", true);
font._fontStyleMask = (FontStyles) ParseUtil.ParseInt(node, "styleMask", true);
return font;
}
public void SetupSample(TMP_Text tmp) {
if (tmp == null) throw new ArgumentNullException(nameof(tmp));

View File

@ -1,6 +1,5 @@
using System.IO;
using System.Collections;
using System.Collections.Generic;
using ConformalDecals.Util;
using TMPro;
using UniLinq;

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UniLinq;
using UnityEngine;
namespace ConformalDecals.Util {
@ -74,6 +75,14 @@ namespace ConformalDecals.Util {
return ParseValueIndirect(ref value, node, valueName, int.TryParse);
}
public static uint ParseUint(ConfigNode node, string valueName, bool isOptional = false, uint defaultValue = 0) {
return ParseValue(node, valueName, uint.TryParse, isOptional, defaultValue);
}
public static bool ParseUintIndirect(ref uint value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, uint.TryParse);
}
public static Color32 ParseColor32(ConfigNode node, string valueName, bool isOptional = false, Color32 defaultValue = default) {
return ParseValue(node, valueName, TryParseColor32, isOptional, defaultValue);
}
@ -106,6 +115,15 @@ namespace ConformalDecals.Util {
return ParseValueIndirect(ref value, node, valueName, ParseExtensions.TryParseVector3);
}
public static Matrix4x4 ParseMatrix4x4(ConfigNode node, string valueName, bool isOptional = false, Matrix4x4 defaultValue = default) {
return ParseValue(node, valueName, ParseUtil.TryParseMatrix4x4, isOptional, defaultValue);
}
public static bool ParseMatrix4x4Indirect(ref Matrix4x4 value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, ParseUtil.TryParseMatrix4x4);
}
public static T ParseValue<T>(ConfigNode node, string valueName, TryParseDelegate<T> tryParse, bool isOptional = false, T defaultValue = default) {
string valueString = node.GetValue(valueName);
@ -145,6 +163,26 @@ namespace ConformalDecals.Util {
throw new FormatException($"Improperly formatted {typeof(T)} value for {valueName} : '{valueString}");
}
public static bool TryParseMatrix4x4(string valueString, out Matrix4x4 value) {
value = new Matrix4x4();
var split = valueString.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < split.Length; i++) {
split[i] = split[i].Trim();
}
if (split.Length != 16) return false;
int index = 0;
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
if (!float.TryParse(split[index], out float component)) return false;
value[row, col] = component;
}
}
return true;
}
public static bool TryParseHexColor(string valueString, out Color32 value) {
value = new Color32(0, 0, 0, byte.MaxValue);