summaryrefslogtreecommitdiffstats
path: root/Scripts/Editor/ModularSlang.cs
blob: f8ae834144a2a6ec04b650d445629d88995895b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace ModularSlang.Editor
{
    internal sealed class ScriptLocator : ScriptableObject
    {
    }

    internal static class ModularSlangTranslator
    {
        private const string MenuPath = "Assets/Translate to HLSL";

        private static string s_cachedExecutablePath;
        private static bool s_missingExecutableLogged;

        [MenuItem(MenuPath, false, priority: 2000)]
        private static void TranslateSelectedSlang()
        {
            var slangAssets = GetSelectedSlangAssets()
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            TranslateSlangAssets(slangAssets, interactive: true, importOutputs: false);
        }

        [MenuItem(MenuPath, true)]
        private static bool TranslateSelectedSlangValidation()
        {
            return GetSelectedSlangAssets().Any();
        }

        private static IEnumerable<string> GetSelectedSlangAssets()
        {
            foreach (var obj in Selection.objects)
            {
                if (!obj)
                {
                    continue;
                }

                var assetPath = AssetDatabase.GetAssetPath(obj);
                if (string.IsNullOrEmpty(assetPath))
                {
                    continue;
                }

                if (assetPath.EndsWith(".slang", StringComparison.OrdinalIgnoreCase))
                {
                    yield return assetPath;
                }
            }
        }

        internal static void TranslateSlangAssets(IReadOnlyCollection<string> assetPaths, bool interactive, bool importOutputs)
        {
            if (assetPaths == null)
            {
                return;
            }

            var uniqueAssets = assetPaths
                .Where(path => !string.IsNullOrWhiteSpace(path))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            if (uniqueAssets.Count == 0)
            {
                return;
            }

            if (!TryGetExecutablePath(out var exePath, interactive))
            {
                return;
            }

            var projectRoot = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
            var showProgress = interactive && uniqueAssets.Count > 1;

            try
            {
                for (var i = 0; i < uniqueAssets.Count; ++i)
                {
                    var assetPath = uniqueAssets[i];
                    if (showProgress)
                    {
                        var progress = (i + 1f) / uniqueAssets.Count;
                        EditorUtility.DisplayProgressBar("Translating Slang", assetPath, progress);
                    }

                    RunTranslator(exePath, assetPath, projectRoot, importOutputs);
                }
            }
            finally
            {
                if (showProgress)
                {
                    EditorUtility.ClearProgressBar();
                }
            }

            if (interactive)
            {
                AssetDatabase.Refresh();
            }
        }

        private static bool TryGetExecutablePath(out string exePath, bool interactive)
        {
            exePath = GetExecutablePath();
            if (File.Exists(exePath))
            {
                s_missingExecutableLogged = false;
                return true;
            }

            var message =
                $"Could not locate modular_slang.exe next to the Scripts folder.\n\nExpected at:\n{exePath}";

            if (interactive)
            {
                EditorUtility.DisplayDialog("Modular Slang", message, "OK");
            }
            else if (!s_missingExecutableLogged)
            {
                UnityEngine.Debug.LogError(message);
                s_missingExecutableLogged = true;
            }

            return false;
        }

        private static string GetExecutablePath()
        {
            if (!string.IsNullOrEmpty(s_cachedExecutablePath))
            {
                return s_cachedExecutablePath;
            }

            var marker = ScriptableObject.CreateInstance<ScriptLocator>();
            try
            {
                var markerScript = MonoScript.FromScriptableObject(marker);
                var assetPath = AssetDatabase.GetAssetPath(markerScript);
                var projectRoot = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
                var scriptFullPath = Path.GetFullPath(Path.Combine(projectRoot, assetPath));

                var scriptDir = Path.GetDirectoryName(scriptFullPath) ?? string.Empty; // .../Scripts/Editor
                var scriptsDir = Path.GetDirectoryName(scriptDir) ?? string.Empty;      // .../Scripts
                var packageRoot = Path.GetDirectoryName(scriptsDir) ?? string.Empty;   // package root

                s_cachedExecutablePath = Path.Combine(packageRoot, "modular_slang.exe");
                return s_cachedExecutablePath;
            }
            finally
            {
                ScriptableObject.DestroyImmediate(marker);
            }
        }

        private static void RunTranslator(string exePath, string assetPath, string projectRoot, bool importOutput)
        {
            var inputFullPath = Path.GetFullPath(Path.Combine(projectRoot, assetPath));
            var outputFullPath = Path.ChangeExtension(inputFullPath, ".hlsl");
            var outputAssetPath = ToProjectRelativePath(outputFullPath, projectRoot);

            var startInfo = new ProcessStartInfo
            {
                FileName = exePath,
                Arguments = QuoteIfNeeded(inputFullPath),
                WorkingDirectory = Path.GetDirectoryName(exePath) ?? projectRoot,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
            };

            using (var process = Process.Start(startInfo))
            {
                if (process == null)
                {
                    UnityEngine.Debug.LogError("Failed to launch modular_slang.exe");
                    return;
                }

                var stdOut = process.StandardOutput.ReadToEnd();
                var stdErr = process.StandardError.ReadToEnd();
                process.WaitForExit();

                if (!string.IsNullOrWhiteSpace(stdOut))
                {
                    UnityEngine.Debug.Log(stdOut);
                }

                if (process.ExitCode != 0)
                {
                    var message = string.IsNullOrWhiteSpace(stdErr)
                        ? $"modular_slang.exe failed with exit code {process.ExitCode}"
                        : stdErr;
                    UnityEngine.Debug.LogError(message);
                    return;
                }

                if (!File.Exists(outputFullPath))
                {
                    UnityEngine.Debug.LogWarning($"Compilation succeeded but {outputFullPath} was not created.");
                }
                else
                {
                    UnityEngine.Debug.Log($"Generated {outputFullPath}");
                    if (importOutput && !string.IsNullOrEmpty(outputAssetPath))
                    {
                        AssetDatabase.ImportAsset(outputAssetPath, ImportAssetOptions.ForceUpdate);
                    }
                }
            }
        }

        private static string QuoteIfNeeded(string path)
        {
            return path.Contains(' ') ? $"\"{path}\"" : path;
        }

        private static string ToProjectRelativePath(string fullPath, string projectRoot)
        {
            if (string.IsNullOrEmpty(fullPath) || string.IsNullOrEmpty(projectRoot))
            {
                return string.Empty;
            }

            if (!fullPath.StartsWith(projectRoot, StringComparison.OrdinalIgnoreCase))
            {
                return string.Empty;
            }

            var relative = fullPath.Substring(projectRoot.Length)
                .TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
            return relative.Replace(Path.DirectorySeparatorChar, '/');
        }
    }

    internal sealed class SlangAssetPostprocessor : AssetPostprocessor
    {
        private static readonly HashSet<string> s_pendingAssets = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        private static bool s_processingScheduled;

        private static void OnPostprocessAllAssets(
            string[] importedAssets,
            string[] deletedAssets,
            string[] movedAssets,
            string[] movedFromAssetPaths)
        {
            var added = false;

            foreach (var asset in importedAssets)
            {
                if (asset.EndsWith(".slang", StringComparison.OrdinalIgnoreCase))
                {
                    if (s_pendingAssets.Add(asset))
                    {
                        added = true;
                    }
                }
            }

            if (added && !s_processingScheduled)
            {
                s_processingScheduled = true;
                EditorApplication.delayCall += ProcessPending;
            }
        }

        private static void ProcessPending()
        {
            s_processingScheduled = false;

            if (s_pendingAssets.Count == 0)
            {
                return;
            }

            var assets = s_pendingAssets.ToArray();
            s_pendingAssets.Clear();

            ModularSlangTranslator.TranslateSlangAssets(assets, interactive: false, importOutputs: true);
        }
    }
}