Compare commits

..

No commits in common. "938babb41ba1933110b9513389f8f9281a8bf636" and "1e7c6d81c9ac1023ca9d1b5c3fce2aec92d9d69a" have entirely different histories.

14 changed files with 227 additions and 128 deletions

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

@ -6,14 +6,14 @@
{
"MAJOR":0,
"MINOR":2,
"PATCH":7,
"BUILD":0
"PATCH":6,
"BUILD":1
},
"KSP_VERSION":
{
"MAJOR":1,
"MINOR":11,
"PATCH":0
"MINOR":10,
"PATCH":1
},
"KSP_VERSION_MIN":{
"MAJOR":1,
@ -22,7 +22,7 @@
},
"KSP_VERSION_MAX":{
"MAJOR":1,
"MINOR":11,
"MINOR":10,
"PATCH":99
}
}

View File

@ -1,5 +1,5 @@
# Conformal Decals v0.2.7
[![Build Status](https://travis-ci.com/drewcassidy/KSP-Conformal-Decals.svg?branch=release)](https://travis-ci.com/drewcassidy/KSP-Conformal-Decals) [![Art: CC BY-SA 4.0](https://img.shields.io/badge/Art%20License-CC%20BY--SA%204.0-orange.svg)](https://creativecommons.org/licenses/by-sa/4.0/) [![Code: GPL v3](https://img.shields.io/badge/Code%20License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
# Conformal Decals v0.2.6
[![Build Status](https://travis-ci.org/drewcassidy/KSP-Conformal-Decals.svg?branch=release)](https://travis-ci.org/drewcassidy/KSP-Conformal-Decals) [![Art: CC BY-SA 4.0](https://img.shields.io/badge/Art%20License-CC%20BY--SA%204.0-orange.svg)](https://creativecommons.org/licenses/by-sa/4.0/) [![Code: GPL v3](https://img.shields.io/badge/Code%20License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
![Screenshot](http://pileof.rocks/KSP/images/ConformalDecalsHeader.png)

View File

@ -5,7 +5,6 @@
<IsPackable>false</IsPackable>
<PlatformTarget>x64</PlatformTarget>
<NoWarn>1701;1702;CS0649;CS1591</NoWarn>
<AssemblyVersion>0.2.7</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
@ -36,19 +35,19 @@
</ItemGroup>
<ItemGroup>
<Compile Remove="dlls\**" />
<Compile Remove="dlls\**"/>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="dlls\**" />
<EmbeddedResource Remove="dlls\**"/>
</ItemGroup>
<ItemGroup>
<None Remove="dlls\**" />
<None Remove="dlls\**"/>
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="/bin/cp -v '$(OutDir)ConformalDecals.dll' '$(SolutionDir)../GameData/ConformalDecals/Plugins'" IgnoreExitCode="true" />
<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-->
</Target>

View File

@ -89,6 +89,7 @@ namespace ConformalDecals {
private MaterialColorProperty _outlineColorProperty;
private MaterialFloatProperty _outlineWidthProperty;
private TextRenderJob _currentJob;
private DecalText _currentText;
public override void OnLoad(ConfigNode node) {
@ -252,6 +253,7 @@ namespace ConformalDecals {
decal.charSpacing = charSpacing;
decal.lineSpacing = lineSpacing;
decal._currentJob = _currentJob;
decal._currentText = _currentText;
decal.UpdateText();
}
@ -265,7 +267,7 @@ namespace ConformalDecals {
private void UpdateText() {
// Render text
var newText = new DecalText(text, font, style, vertical, lineSpacing, charSpacing);
var output = TextRenderer.UpdateText(_currentText, newText);
var output = TextRenderer.UpdateTextNow(_currentText, newText);
_currentText = newText;
UpdateTexture(output);

View File

@ -1 +1 @@
[assembly: KSPAssembly("ConformalDecals", 0, 2)]
[assembly: KSPAssembly("ConformalDecals", 0, 2, 6)]

View File

@ -105,9 +105,5 @@ namespace ConformalDecals.Text {
public void OnBeforeSerialize() { }
public void OnAfterDeserialize() { }
public override string ToString() {
return _title;
}
}
}

View File

@ -86,9 +86,5 @@ namespace ConformalDecals.Text {
public static bool operator !=(DecalText left, DecalText right) {
return !Equals(left, right);
}
public override string ToString() {
return $"{nameof(_text)}: {_text}, {nameof(_font)}: {_font}, {nameof(_style)}: {_style}, {nameof(_vertical)}: {_vertical}, {nameof(_lineSpacing)}: {_lineSpacing}, {nameof(_charSpacing)}: {_charSpacing}";
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using UnityEngine.Events;
namespace ConformalDecals.Text {
public class TextRenderJob {
public DecalText OldText { get; }
public DecalText NewText { get; }
public bool Needed { get; private set; }
public bool IsStarted { get; private set; }
public bool IsDone { get; private set; }
public readonly TextRenderer.TextRenderEvent onRenderFinished = new TextRenderer.TextRenderEvent();
public TextRenderJob(DecalText oldText, DecalText newText, UnityAction<TextRenderOutput> renderFinishedCallback) {
OldText = oldText;
NewText = newText ?? throw new ArgumentNullException(nameof(newText));
Needed = true;
if (renderFinishedCallback != null) onRenderFinished.AddListener(renderFinishedCallback);
}
public void Cancel() {
Needed = false;
}
public void Start() {
IsStarted = true;
}
public void Finish(TextRenderOutput output) {
IsDone = true;
onRenderFinished.Invoke(output);
}
}
}

View File

@ -9,7 +9,7 @@ namespace ConformalDecals.Text {
/// The rectangle that the rendered text takes up within the texture
public Rect Window { get; private set; }
/// The number of users for this render output. If 0, it can be discarded from the cache
/// The number of users for this render output. If 0, it can be discarded from the cache and the texture reused
public int UserCount { get; set; }
public TextRenderOutput(Texture2D texture, Rect window) {

View File

@ -3,12 +3,16 @@ using System.Collections.Generic;
using ConformalDecals.Util;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
namespace ConformalDecals.Text {
// TODO: Testing shows the job system is unnecessary, so remove job system code.
/// Class handing text rendering.
public static class TextRenderer {
/// Is a singleton referencing a single gameobject in the scene which contains the TextMeshPro component
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class TextRenderer : MonoBehaviour {
/// Texture format used for returned textures.
/// Unfortunately due to how Unity textures work, this cannot be R8 or Alpha8,
/// so theres always a superfluous green channel using memory
@ -18,73 +22,163 @@ namespace ConformalDecals.Text {
/// Overriden below to be ARGB32 on DirectX because DirectX is dumb
public static RenderTextureFormat textRenderTextureFormat = RenderTextureFormat.R8;
/// The text renderer object within the scene which contains the TextMeshPro component used for rendering.
public static TextRenderer Instance {
get {
if (!_instance._isSetup) {
_instance.Setup();
}
return _instance;
}
}
/// Text Render unityevent, used with the job system to signal render completion
[Serializable]
public class TextRenderEvent : UnityEvent<TextRenderOutput> { }
private const string ShaderName = "ConformalDecals/Text Blit";
private const int MaxTextureSize = 4096;
private const float FontSize = 100;
private const float PixelDensity = 5;
private static Shader _blitShader;
private static Texture2D _blankTexture;
private static TextRenderer _instance;
private bool _isSetup;
private TextMeshPro _tmp;
private Shader _blitShader;
private static readonly Dictionary<DecalText, TextRenderOutput> RenderCache = new Dictionary<DecalText, TextRenderOutput>();
private static readonly Queue<TextRenderJob> RenderJobs = new Queue<TextRenderJob>();
/// Update text immediately without using job queue
public static TextRenderOutput UpdateText(DecalText oldText, DecalText newText) {
/// Update text using the job queue
public static TextRenderJob UpdateText(DecalText oldText, DecalText newText, UnityAction<TextRenderOutput> renderFinishedCallback) {
if (newText == null) throw new ArgumentNullException(nameof(newText));
if (!(oldText is null)) UnregisterText(oldText);
var job = new TextRenderJob(oldText, newText, renderFinishedCallback);
RenderJobs.Enqueue(job);
return job;
}
// now that all old references are handled, begin rendering the new output
if (!RenderCache.TryGetValue(newText, out var renderOutput)) {
renderOutput = RenderText(newText);
RenderCache.Add(newText, renderOutput);
}
/// Update text immediately without using job queue
public static TextRenderOutput UpdateTextNow(DecalText oldText, DecalText newText) {
if (newText == null) throw new ArgumentNullException(nameof(newText));
renderOutput.UserCount++;
return renderOutput;
return Instance.RunJob(new TextRenderJob(oldText, newText, null), out _);
}
/// Unregister a user of a piece of text
public static void UnregisterText(DecalText text) {
if (text == null) throw new ArgumentNullException(nameof(text));
if (RenderCache.TryGetValue(text, out var renderedText)) {
renderedText.UserCount--;
if (renderedText.UserCount <= 0) {
RenderCache.Remove(text);
var texture = renderedText.Texture;
if (texture != _blankTexture) Object.Destroy(texture);
Destroy(renderedText.Texture);
}
}
}
private void Start() {
if (_instance != null) {
Logging.LogError("Duplicate TextRenderer created???");
}
Logging.Log("Creating TextRenderer Object");
_instance = this;
DontDestroyOnLoad(gameObject);
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) {
textRenderTextureFormat = RenderTextureFormat.ARGB32; // DirectX is dumb
}
if (!SystemInfo.SupportsTextureFormat(textTextureFormat)) {
Logging.LogError($"Text texture format {textTextureFormat} not supported on this platform.");
}
if (!SystemInfo.SupportsRenderTextureFormat(textRenderTextureFormat)) {
Logging.LogError($"Text texture format {textRenderTextureFormat} not supported on this platform.");
}
}
/// Setup this text renderer instance for rendering
private void Setup() {
if (_isSetup) return;
Logging.Log("Setting Up TextRenderer Object");
_tmp = gameObject.AddComponent<TextMeshPro>();
_tmp.renderer.enabled = false; // dont automatically render
_blitShader = Shabby.Shabby.FindShader(ShaderName);
if (_blitShader == null) Logging.LogError($"Could not find text blit shader named '{ShaderName}'");
_isSetup = true;
}
/// Run a text render job
private TextRenderOutput RunJob(TextRenderJob job, out bool renderNeeded) {
if (!job.Needed) {
renderNeeded = false;
return null;
}
job.Start();
Texture2D texture = null;
if (job.OldText != null && RenderCache.TryGetValue(job.OldText, out var oldRender)) {
// old output still exists
oldRender.UserCount--;
if (oldRender.UserCount <= 0) {
// this is the only usage of this output, so we are free to re-render into the texture
texture = oldRender.Texture;
RenderCache.Remove(job.OldText);
}
}
// now that all old references are handled, begin rendering the new output
if (RenderCache.TryGetValue(job.NewText, out var renderOutput)) {
renderNeeded = false;
}
else {
renderNeeded = true;
renderOutput = RenderText(job.NewText, texture);
RenderCache.Add(job.NewText, renderOutput);
}
renderOutput.UserCount++;
job.Finish(renderOutput);
return renderOutput;
}
/// Render a piece of text to a given texture
public static TextRenderOutput RenderText(DecalText text) {
public TextRenderOutput RenderText(DecalText text, Texture2D texture) {
if (text == null) throw new ArgumentNullException(nameof(text));
var tmpObject = new GameObject("Text Mesh Pro renderer");
var tmp = tmpObject.AddComponent<TextMeshPro>();
if (_tmp == null) throw new InvalidOperationException("TextMeshPro object not yet created.");
// SETUP TMP OBJECT FOR RENDERING
tmp.text = text.FormattedText;
tmp.font = text.Font.FontAsset;
tmp.fontStyle = text.Style | text.Font.FontStyle;
tmp.lineSpacing = text.LineSpacing;
tmp.characterSpacing = text.CharSpacing;
_tmp.text = text.FormattedText;
_tmp.font = text.Font.FontAsset;
_tmp.fontStyle = text.Style | text.Font.FontStyle;
_tmp.lineSpacing = text.LineSpacing;
_tmp.characterSpacing = text.CharSpacing;
tmp.extraPadding = true;
tmp.enableKerning = true;
tmp.enableWordWrapping = false;
tmp.overflowMode = TextOverflowModes.Overflow;
tmp.alignment = TextAlignmentOptions.Center;
tmp.fontSize = FontSize;
_tmp.extraPadding = true;
_tmp.enableKerning = true;
_tmp.enableWordWrapping = false;
_tmp.overflowMode = TextOverflowModes.Overflow;
_tmp.alignment = TextAlignmentOptions.Center;
_tmp.fontSize = FontSize;
// GENERATE MESH
tmp.ClearMesh(false);
tmp.ForceMeshUpdate();
_tmp.ClearMesh(false);
_tmp.ForceMeshUpdate();
var meshFilters = tmpObject.GetComponentsInChildren<MeshFilter>();
var meshFilters = gameObject.GetComponentsInChildren<MeshFilter>();
var meshes = new Mesh[meshFilters.Length];
var materials = new Material[meshFilters.Length];
@ -95,9 +189,9 @@ namespace ConformalDecals.Text {
var renderer = meshFilters[i].gameObject.GetComponent<MeshRenderer>();
meshes[i] = meshFilters[i].mesh;
if (i == 0) meshes[i] = tmp.mesh;
if (i == 0) meshes[i] = _tmp.mesh;
materials[i] = Object.Instantiate(renderer.material);
materials[i] = Instantiate(renderer.material);
materials[i].shader = _blitShader;
if (renderer == null) throw new FormatException($"Object {meshFilters[i].gameObject.name} has filter but no renderer");
@ -115,16 +209,15 @@ namespace ConformalDecals.Text {
var size = bounds.size * PixelDensity;
size.x = Mathf.Max(size.x, 0.1f);
size.y = Mathf.Max(size.y, 0.1f);
var textureSize = new Vector2Int {
x = Mathf.NextPowerOfTwo((int) size.x),
y = Mathf.NextPowerOfTwo((int) size.y)
};
if (textureSize.x == 0 || textureSize.y == 0) {
Logging.LogError("No text present or error in texture size calculation. Aborting.");
Object.Destroy(tmpObject);
return new TextRenderOutput(_blankTexture, Rect.zero);
Logging.LogWarning("No text present or error in texture size calculation. Aborting.");
return new TextRenderOutput(Texture2D.blackTexture, Rect.zero);
}
// make sure texture isnt too big, scale it down if it is
@ -149,7 +242,12 @@ namespace ConformalDecals.Text {
};
// SETUP TEXTURE
var texture = new Texture2D(textureSize.x, textureSize.y, textTextureFormat, false);
if (texture == null) {
texture = new Texture2D(textureSize.x, textureSize.y, textTextureFormat, true);
}
else if (texture.width != textureSize.x || texture.height != textureSize.y || texture.format != textTextureFormat) {
texture.Resize(textureSize.x, textureSize.y, textTextureFormat, true);
}
// GENERATE PROJECTION MATRIX
var halfSize = (Vector2) textureSize / PixelDensity / 2 / sizeRatio;
@ -157,7 +255,7 @@ namespace ConformalDecals.Text {
bounds.center.y - halfSize.y, bounds.center.y + halfSize.y, -1, 1);
// GET RENDERTEX
var renderTex = RenderTexture.GetTemporary(textureSize.x, textureSize.y, 0, textRenderTextureFormat, RenderTextureReadWrite.Linear);
var renderTex = new RenderTexture(textureSize.x, textureSize.y, 0, textRenderTextureFormat, RenderTextureReadWrite.Linear) {autoGenerateMips = false};
// RENDER
Graphics.SetRenderTarget(renderTex);
@ -173,42 +271,28 @@ namespace ConformalDecals.Text {
}
}
// COPY RENDERTEX INTO TEXTURE
// COPY TEXTURE BACK INTO RAM
var prevRT = RenderTexture.active;
RenderTexture.active = renderTex;
texture.ReadPixels(new Rect(0, 0, textureSize.x, textureSize.y), 0, 0, false);
texture.Apply(false, true);
texture.ReadPixels(new Rect(0, 0, textureSize.x, textureSize.y), 0, 0, true);
texture.Apply();
RenderTexture.active = prevRT;
GL.PopMatrix();
// RELEASE RENDERTEX
RenderTexture.ReleaseTemporary(renderTex);
renderTex.Release();
RenderTexture.Destroy(renderTex);
// DESTROY THE RENDERER OBJECT
Object.Destroy(tmpObject);
// CLEAR SUBMESHES
_tmp.text = "";
for (int i = 0; i < transform.childCount; i++) {
var child = transform.GetChild(i);
Destroy(child.gameObject);
}
return new TextRenderOutput(texture, window);
}
/// Setup shader and texture
public static void ModuleManagerPostLoad() {
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) {
textRenderTextureFormat = RenderTextureFormat.ARGB32; // DirectX is dumb
}
if (!SystemInfo.SupportsTextureFormat(textTextureFormat)) {
Logging.LogError($"Text texture format {textTextureFormat} not supported on this platform.");
}
if (!SystemInfo.SupportsRenderTextureFormat(textRenderTextureFormat)) {
Logging.LogError($"Text texture format {textRenderTextureFormat} not supported on this platform.");
}
_blankTexture = Texture2D.blackTexture;
_blitShader = Shabby.Shabby.FindShader(ShaderName);
if (_blitShader == null) Logging.LogError($"Could not find text blit shader named '{ShaderName}'");
}
}
}

View File

@ -3,6 +3,7 @@ using ConformalDecals.Text;
using ConformalDecals.Util;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace ConformalDecals.UI {
@ -34,15 +35,14 @@ namespace ConformalDecals.UI {
private Vector2 _lineSpacingRange;
private Vector2 _charSpacingRange;
private TMP_InputField _textBoxTMP;
private FontMenuController _fontMenu;
private TextUpdateDelegate _onValueChanged;
private static int _lockCounter;
private FontMenuController _fontMenu;
private bool _ignoreUpdates;
private bool _isLocked;
private string _lockString;
private bool _ignoreUpdates;
private bool _textUpdated;
private static int _lockCounter;
public static TextEntryController Create(
string text, DecalFont font, FontStyles style, bool vertical, float linespacing, float charspacing,
@ -74,7 +74,7 @@ namespace ConformalDecals.UI {
public void SetControlLock(string value = null) {
if (_isLocked) return;
InputLockManager.SetControlLock(ControlTypes.EDITOR_UI, _lockString);
InputLockManager.SetControlLock(_lockString);
_isLocked = true;
}
@ -86,7 +86,8 @@ namespace ConformalDecals.UI {
public void OnTextUpdate(string newText) {
this._text = newText;
_textUpdated = true;
OnValueChanged();
}
public void OnFontMenu() {
@ -104,7 +105,7 @@ namespace ConformalDecals.UI {
_textBoxTMP.fontAsset = _font.FontAsset;
UpdateStyleButtons();
_textUpdated = true;
OnValueChanged();
}
public void OnLineSpacingUpdate(float value) {
@ -113,7 +114,7 @@ namespace ConformalDecals.UI {
_lineSpacing = Mathf.Lerp(_lineSpacingRange.x, _lineSpacingRange.y, value);
UpdateLineSpacing();
_textUpdated = true;
OnValueChanged();
}
public void OnLineSpacingUpdate(string text) {
@ -127,7 +128,7 @@ namespace ConformalDecals.UI {
}
UpdateLineSpacing();
_textUpdated = true;
OnValueChanged();
}
public void OnCharSpacingUpdate(float value) {
@ -136,7 +137,7 @@ namespace ConformalDecals.UI {
_charSpacing = Mathf.Lerp(_charSpacingRange.x, _charSpacingRange.y, value);
UpdateCharSpacing();
_textUpdated = true;
OnValueChanged();
}
public void OnCharSpacingUpdate(string text) {
@ -150,7 +151,7 @@ namespace ConformalDecals.UI {
}
UpdateCharSpacing();
_textUpdated = true;
OnValueChanged();
}
public void OnBoldUpdate(bool state) {
@ -162,7 +163,7 @@ namespace ConformalDecals.UI {
_style &= ~FontStyles.Bold;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
OnValueChanged();
}
public void OnItalicUpdate(bool state) {
@ -174,7 +175,7 @@ namespace ConformalDecals.UI {
_style &= ~FontStyles.Italic;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
OnValueChanged();
}
public void OnUnderlineUpdate(bool state) {
@ -186,7 +187,7 @@ namespace ConformalDecals.UI {
_style &= ~FontStyles.Underline;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
OnValueChanged();
}
public void OnSmallCapsUpdate(bool state) {
@ -198,19 +199,19 @@ namespace ConformalDecals.UI {
_style &= ~FontStyles.SmallCaps;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
OnValueChanged();
}
public void OnVerticalUpdate(bool state) {
if (_ignoreUpdates) return;
_vertical = state;
_textUpdated = true;
OnValueChanged();
}
private void Start() {
_lockString = $"ConformalDecals_TextEditor_{_lockCounter++}";
_textBoxTMP = ((TMP_InputField) _textBox);
_textBoxTMP.text = _text;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
@ -228,12 +229,9 @@ namespace ConformalDecals.UI {
private void OnDestroy() {
RemoveControlLock();
}
private void LateUpdate() {
if (_textUpdated) {
_onValueChanged(_text, _font, _style, _vertical, _lineSpacing, _charSpacing);
_textUpdated = false;
}
private void OnValueChanged() {
_onValueChanged(_text, _font, _style, _vertical, _lineSpacing, _charSpacing);
}
private void UpdateStyleButtons() {

View File

@ -1,12 +1,3 @@
v0.2.7
------
- Supported KSP versions: 1.8.x to 1.11.x
- Notes:
- Attaching decal parts in flight using engineer kerbals is not supported.
- Fixes:
- Fixed certain non-ascii strings not rendering correctly under certain circumstances.
- Yet another attempted fix for the planet text glitch.
v0.2.6
------
- Fixes: