forked from libgdx/libgdx
/
ShaderTester.java
262 lines (234 loc) · 9.35 KB
/
ShaderTester.java
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
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.tools.shadertester;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.tools.FileProcessor;
import com.badlogic.gdx.tools.FileProcessor.Entry;
import com.badlogic.gdx.utils.SharedLibraryLoader;
import com.badlogic.gdx.utils.StreamUtils;
/** A thin wrapper around the Khronos reference shader compiler. It can check whole directories and shaders as strings.
* @author Simon Gerst */
public class ShaderTester {
/** Returns a path to a file that can be written. Tries multiple locations and verifies writing succeeds. */
private static File getWritableFile (String dirName, String fileName) {
// Temp directory with username in path.
File idealFile = new File(System.getProperty("java.io.tmpdir") + "/libgdx" + System.getProperty("user.name") + "/"
+ dirName, fileName);
if (canWrite(idealFile)) return idealFile;
// System provided temp directory.
try {
File file = File.createTempFile(dirName, null);
if (file.delete()) {
file = new File(file, fileName);
if (canWrite(file)) return file;
}
} catch (IOException ignored) {
}
// User home.
File file = new File(System.getProperty("user.home") + "/.libgdx/" + dirName, fileName);
if (canWrite(file)) return file;
// Relative directory.
file = new File(".temp/" + dirName, fileName);
if (canWrite(file)) return file;
return idealFile; // Will likely fail, but we did our best.
}
/** Returns true if the parent directories of the file can be created and the file can be written. */
private static boolean canWrite (File file) {
File parent = file.getParentFile();
File testFile;
if (file.exists()) {
if (!file.canWrite() || !canExecute(file)) return false;
// Don't overwrite existing file just to check if we can write to directory.
testFile = new File(parent, UUID.randomUUID().toString());
} else {
parent.mkdirs();
if (!parent.isDirectory()) return false;
testFile = file;
}
try {
new FileOutputStream(testFile).close();
if (!canExecute(testFile)) return false;
return true;
} catch (Throwable ex) {
return false;
} finally {
testFile.delete();
}
}
private static boolean canExecute (File file) {
try {
Method canExecute = File.class.getMethod("canExecute");
if ((Boolean)canExecute.invoke(file)) return true;
Method setExecutable = File.class.getMethod("setExecutable", boolean.class, boolean.class);
setExecutable.invoke(file, true, false);
return (Boolean)canExecute.invoke(file);
} catch (Exception ignored) {
}
return false;
}
/** Tests a shader.<br>
* Note: This method creates a temp file, due to some limitations
* @param shaderSource the source of the shader
* @param type the type of the shader, see {@link ShaderType} */
static public void processFragmentShader (String shaderSource, ShaderType type) {
ArrayList<File> list = new ArrayList<File>();
File file = getUseableShaderFile(shaderSource, type.getFileExtension());
writeSourceToFile(shaderSource, file);
list.add(file);
process(new Settings() {
{
recursive = false;
}
}, list);
}
static private File getUseableShaderFile (String source, String extension) {
return getWritableFile("shaderTester", new Date().getTime() + MathUtils.random(Integer.MAX_VALUE) + extension);
}
static private void writeSourceToFile (String source, File fileToWrite) {
FileWriter w = null;
try {
w = new FileWriter(fileToWrite);
w.write(source);
} catch (IOException e) {
System.err.println("Failed to write shader to file, internal error!");
e.printStackTrace();
} finally {
StreamUtils.closeQuietly(w);
}
}
/** Tests shaders using defaults settings.<br>
* <b>Fragment shaders must have .frag as extension</b><br>
* <b>Vertex shaders must have .vert as extension</b><br>
* <b>Geometry shaders must have .geom as extension</b><br>
* <b>Tessellation control shaders must have .tesc as extension</b><br>
* <b>Tessellation evaluation shaders must have .tese as extension</b><br>
* Use ShaderTester#process(ArrayList<String>, ArrayList<String>) to circumvent those restrictions
* @param inputDir the directory to process
* @see ShaderTester#process(Settings, String) */
static public void process (String inputDir) {
process(new Settings(), inputDir);
}
/** Tests shaders using the given settings.<br>
* <b>Fragment shaders must have .frag as extension</b><br>
* <b>Vertex shaders must have .vert as extension</b><br>
* <b>Geometry shaders must have .geom as extension</b><br>
* <b>Tessellation control shaders must have .tesc as extension</b><br>
* <b>Tessellation evaluation shaders must have .tese as extension</b><br>
* Use ShaderTester#process(String, ShaderType) to circumvent those restrictions
* @param inputDir the directory to process
* @param settings the {@link Settings} used for processing */
static void process (Settings settings, String inputDir) {
File inputDirectory = new File(inputDir);
FileProcessor fileProcessor = new FileProcessor() {
@Override
protected void processDir (Entry entryDir, ArrayList<Entry> files) throws Exception {
for (Entry entry : files) {
addProcessedFile(entry);
}
}
};
fileProcessor.setRecursive(settings.recursive);
fileProcessor.setInputFilter(new FilenameFilter() {
@Override
public boolean accept (File dir, String name) {
if (name.endsWith(".vert") || name.endsWith(".frag") || name.endsWith(".tese") || name.endsWith(".geom")
|| name.endsWith(".comp") || name.endsWith(".tesc")) return true;
return false;
}
});
ArrayList<Entry> shaderEntries = null;
try {
shaderEntries = fileProcessor.process(inputDirectory, null);
} catch (Exception e1) {
throw new RuntimeException("Faild to process inputDir:" + inputDirectory, e1);
}
ArrayList<File> shaderFiles = new ArrayList<File>();
for (Entry entry : shaderEntries) {
if (entry.inputFile != null) {
shaderFiles.add(entry.inputFile);
}
}
process(settings, shaderFiles);
}
/** Tests shaders using the given settings.<br>
* <b>Fragment shaders must have .frag as extension</b><br>
* <b>Vertex shaders must have .vert as extension</b><br>
* <b>Geometry shaders must have .geom as extension</b><br>
* <b>Tessellation control shaders must have .tesc as extension</b><br>
* <b>Tessellation evaluation shaders must have .tese as extension</b><br>
* Use ShaderTester#process(String, ShaderType) to circumvent those restrictions
* @param filePaths array of files to test
* @param settings the {@link Settings} used for processing */
static public void process (Settings settings, ArrayList<File> filePaths) {
SharedLibraryLoader loader = new SharedLibraryLoader();
File glslangFileExecutable = null;
try {
if (SharedLibraryLoader.isWindows) {
glslangFileExecutable = loader.extractFile("glslangValidator.exe", null);
} else if (SharedLibraryLoader.isLinux) {
glslangFileExecutable = loader.extractFile("glslangValidator", null);
} else if (SharedLibraryLoader.isMac) {
System.err.println("Mac is currently not supported!");
}
} catch (IOException ex) {
throw new RuntimeException("Faild to extract needed natives.", ex);
}
ArrayList<String> command = new ArrayList<String>();
command.add(glslangFileExecutable.getAbsolutePath());
for (File file : filePaths) {
command.add(file.getAbsolutePath());
}
try {
ProcessBuilder b = new ProcessBuilder();
b.command(command);
Process proc = b.start();
// Read input from process, else the process could hang
try {
InputStreamReader isr = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (IOException ioe) {
// Ignore
ioe.printStackTrace();
}
int exitVal = proc.waitFor();
System.out.println("Exit value:" + exitVal);
} catch (IOException ioe) {
// Ignore
ioe.printStackTrace();
} catch (InterruptedException ie) {
// Ignore
ie.printStackTrace();
}
}
static class Settings {
/** Whether to recursively check folders */
public boolean recursive = false;
}
}