Debian Codegraph @

libs/matdbg/web/script.js

raw
1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 const kMonacoBaseUrl = 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.17.1/min/';
18 const kUntitledPlaceholder = "untitled";
19
20 const materialList = document.getElementById("material-list");
21 const materialDetail = document.getElementById("material-detail");
22 const header = document.querySelector("header");
23 const footer = document.querySelector("footer");
24 const shaderSource = document.getElementById("shader-source");
25 const matDetailTemplate = document.getElementById("material-detail-template");
26 const matListTemplate = document.getElementById("material-list-template");
27
28 const gMaterialDatabase = {};
29
30 let gSocket = null;
31 let gEditor = null;
32 let gCurrentMaterial = "00000000";
33 let gCurrentShader = { matid: "00000000", glindex: 0 };
34 let gCurrentSocketId = 0;
35 let gEditorIsLoading = false;
36
37 require.config({ paths: { "vs": `${kMonacoBaseUrl}vs` }});
38
39 window.MonacoEnvironment = {
40 getWorkerUrl: function() {
41 return `data:text/javascript;charset=utf-8,${encodeURIComponent(`
42 self.MonacoEnvironment = {
43 baseUrl: '${kMonacoBaseUrl}'
44 };
45 importScripts('${kMonacoBaseUrl}vs/base/worker/workerMain.js');`
46 )}`;
47 }
48 };
49
50 // TODO: this function could be simplified by changing the format of the shader selector.
51 function rebuildMaterial() {
52 let api = 0, index = -1;
53 if ("glindex" in gCurrentShader) { api = 1; index = gCurrentShader.glindex; }
54 if ("vkindex" in gCurrentShader) { api = 2; index = gCurrentShader.vkindex; }
55 if ("metalindex" in gCurrentShader) { api = 3; index = gCurrentShader.metalindex; }
56 const editedText = getShaderRecord(gCurrentShader).text;
57 const byteCount = new Blob([editedText]).size;
58 gSocket.send(`EDIT ${gCurrentShader.matid} ${api} ${index} ${byteCount} ${editedText}`);
59 }
60
61 document.querySelector("body").addEventListener("click", (evt) => {
62 const anchor = evt.target.closest("a");
63 if (!anchor) {
64 return;
65 }
66
67 // Handle selection of a material.
68 if (anchor.classList.contains("material")) {
69 selectMaterial(anchor.dataset.matid, true);
70 return;
71 }
72
73 // Handle selection of a shader.
74 if (anchor.classList.contains("shader")) {
75 selectShader(anchor.dataset);
76 return;
77 }
78
79 // Handle a rebuild.
80 if (anchor.classList.contains("rebuild")) {
81 rebuildMaterial();
82 return;
83 }
84 });
85
86 // Handle Ctrl+Arrow for fast keyboard navigation between shader variants and materials. Either the
87 // materialStep or shaderStep argument can be non-zero (not both) and they must be -1, 0, or +1.
88 // TODO: this function could be vastly simplified by changing the format of the shader selector.
89 function selectNextShader(materialStep, shaderStep) {
90 if (materialStep !== 0) {
91 const matids = getDisplayedMaterials().map(m => m.matid).filter(m => m);
92 const currentIndex = matids.indexOf(gCurrentMaterial);
93 const nextIndex = currentIndex + materialStep;
94 if (nextIndex >= 0 && nextIndex < matids.length) {
95 selectMaterial(matids[nextIndex], true);
96 }
97 return;
98 }
99 const material = gMaterialDatabase[gCurrentMaterial];
100 const variants = [];
101 let currentIndex = 0;
102 for (const [index, shader] of material.opengl.entries()) {
103 if (index === gCurrentShader.glindex) currentIndex = variants.length;
104 variants.push({ matid, glindex: index });
105 }
106 for (const [index, shader] of material.vulkan.entries()) {
107 if (index === gCurrentShader.vkindex) currentIndex = variants.length;
108 variants.push({ matid, vkindex: index });
109 }
110 for (const [index, shader] of material.metal.entries()) {
111 if (index === gCurrentShader.metalindex) currentIndex = variants.length;
112 variants.push({ matid, metalindex: index });
113 }
114 const nextIndex = currentIndex + shaderStep;
115 if (nextIndex >= 0 && nextIndex < variants.length) {
116 selectShader(variants[nextIndex]);
117 }
118 }
119
120 function fetchMaterial(matid) {
121 fetch(`api/material?matid=${matid}`).then(function(response) {
122 return response.json();
123 }).then(function(matInfo) {
124 if (matid in gMaterialDatabase) {
125 return;
126 }
127 matInfo.matid = matid;
128 gMaterialDatabase[matid] = matInfo;
129 renderMaterialList();
130 });
131 }
132
133 function queryActiveShaders() {
134 if (!gSocket) {
135 for (matid in gMaterialDatabase) {
136 const material = gMaterialDatabase[matid];
137 material.active = false;
138 for (const shader of material.opengl) shader.active = false;
139 for (const shader of material.vulkan) shader.active = false;
140 for (const shader of material.metal) shader.active = false;
141 }
142 renderMaterialList();
143 renderMaterialDetail();
144 return;
145 }
146 fetch("api/active").then(function(response) {
147 return response.json();
148 }).then(function(activeMaterials) {
149 for (matid in gMaterialDatabase) {
150 const material = gMaterialDatabase[matid];
151 material.active = matid in activeMaterials;
152 }
153 for (matid in activeMaterials) {
154 const material = gMaterialDatabase[matid];
155 const activeBackend = activeMaterials[matid][0];
156 const activeShaders = activeMaterials[matid].slice(1);
157 for (const shader of material[activeBackend]) {
158 const index = parseInt(shader.index);
159 shader.active = activeShaders.indexOf(index) > -1;
160 }
161 }
162 renderMaterialList();
163 renderMaterialDetail();
164 })
165 .catch((error) => {
166 // This is expected to fail when the server is hosted from matinfo instead of Engine, since
167 // there are no active shaders in that situation.
168 });
169 }
170
171 function startSocket() {
172 const url = new URL(document.URL)
173 const ws = new WebSocket(`ws://${url.host}`);
174
175 // When a new server has come online, ask it what materials it has.
176 ws.addEventListener("open", () => {
177 footer.innerText = `connection ${gCurrentSocketId}`;
178 gCurrentSocketId++;
179
180 fetch("api/matids").then(function(response) {
181 return response.json();
182 }).then(function(matInfo) {
183 for (matid of matInfo) {
184 if (!(matid in gMaterialDatabase)) {
185 fetchMaterial(matid);
186 }
187 }
188 });
189 });
190
191 ws.addEventListener("close", (e) => {
192 footer.innerText = "no connection";
193 gSocket = null;
194 setTimeout(() => startSocket(), 3000);
195 });
196
197 ws.addEventListener("message", event => {
198 const matid = event.data;
199 fetchMaterial(matid);
200 });
201
202 gSocket = ws;
203 }
204
205 function fetchMaterials() {
206 fetch("api/materials").then(function(response) {
207 return response.json();
208 }).then(function(matJson) {
209 for (const matInfo of matJson) {
210 if (matInfo.matid in gMaterialDatabase) {
211 continue;
212 }
213 gMaterialDatabase[matInfo.matid] = matInfo;
214 }
215 selectMaterial(matJson[0].matid, true);
216 });
217 }
218
219 function fetchShader(selection, matinfo, onDone) {
220 let query, target;
221 if (selection.glindex >= 0) {
222 query = `type=glsl&glindex=${selection.glindex}`;
223 target = matinfo.opengl[parseInt(selection.glindex)];
224 }
225 if (selection.vkindex >= 0) {
226 query = `type=spirv&vkindex=${selection.vkindex}`;
227 target = matinfo.vulkan[parseInt(selection.vkindex)];
228 }
229 if (selection.metalindex >= 0) {
230 query = `type=glsl&metalindex=${selection.metalindex}`;
231 target = matinfo.metal[parseInt(selection.metalindex)];
232 }
233 fetch(`api/shader?matid=${matinfo.matid}&${query}`).then(function(response) {
234 return response.text();
235 }).then(function(shaderText) {
236 target.text = shaderText;
237 onDone();
238 });
239 }
240
241 function getDisplayedMaterials() {
242 const items = [];
243
244 // Names need not be unique, so we display a numeric suffix for non-unique names.
245 // To achieve stable ordering of anonymous materials, we first sort by matid.
246 const labels = new Set();
247 const matids = Object.keys(gMaterialDatabase).sort();
248 const duplicatedLabels = {};
249 for (const matid of matids) {
250 const name = gMaterialDatabase[matid].name || kUntitledPlaceholder;
251 if (labels.has(name)) {
252 duplicatedLabels[name] = 0;
253 } else {
254 labels.add(name);
255 }
256 }
257
258 // Build a list of objects to pass into the template string.
259 for (const matid of matids) {
260 const item = Object.assign({}, gMaterialDatabase[matid]);
261 item.classes = matid === gCurrentMaterial ? "current " : "";
262 if (!item.active) {
263 item.classes += "inactive "
264 }
265 item.domain = item.shading.material_domain === "surface" ? "surface" : "postpro";
266 item.is_material = true;
267
268 const name = item.name || kUntitledPlaceholder;
269 if (name in duplicatedLabels) {
270 const index = duplicatedLabels[name];
271 item.name = `${name} (${index})`;
272 duplicatedLabels[name] = index + 1;
273 } else {
274 item.name = name;
275 }
276
277 items.push(item);
278 }
279
280 // The template takes a flat list of items, so here we insert items for section headers using
281 // blank names, which causes them to sort to the top of their respective sections.
282 const sectionLabel = {"is_label": true, "name": ""};
283 items.push(Object.assign({"label": "Surface materials", "domain": "surface"}, sectionLabel));
284 items.push(Object.assign({"label": "PostProcess materials", "domain": "postpro"}, sectionLabel));
285
286 // Next, sort all materials and section headers.
287 items.sort((a, b) => {
288 if (a.domain > b.domain) return -1;
289 if (a.domain < b.domain) return +1;
290 if (a.name < b.name) return -1;
291 if (a.name > b.name) return +1;
292 return 0;
293 });
294 return items;
295 }
296
297 function renderMaterialList() {
298 const items = getDisplayedMaterials();
299 materialList.innerHTML = Mustache.render(matListTemplate.innerHTML, { "item": items } );
300 }
301
302 function updateClassList(array, indexProperty, selectedIndex) {
303 for (let item of array) {
304 const current = parseInt(item[indexProperty]) === selectedIndex;
305 item.classes = current ? "current " : "";
306 if (!item.active) {
307 item.classes += "inactive "
308 }
309 }
310 }
311
312 function renderMaterialDetail() {
313 const mat = gMaterialDatabase[gCurrentMaterial];
314 const ok = mat.matid === gCurrentShader.matid;
315 updateClassList(mat.opengl, "index", ok ? parseInt(gCurrentShader.glindex) : -1);
316 updateClassList(mat.vulkan, "index", ok ? parseInt(gCurrentShader.vkindex) : -1);
317 updateClassList(mat.metal, "index", ok ? parseInt(gCurrentShader.metalindex) : -1);
318 const item = Object.assign({}, mat);
319 if (item.shading.material_domain !== "surface") {
320 delete item.shading;
321 }
322 materialDetail.innerHTML = Mustache.render(matDetailTemplate.innerHTML, item);
323 }
324
325 function getShaderRecord(selection) {
326 const mat = gMaterialDatabase[gCurrentMaterial];
327 if (selection.glindex >= 0) return mat.opengl[parseInt(selection.glindex)];
328 if (selection.vkindex >= 0) return mat.vulkan[parseInt(selection.vkindex)];
329 if (selection.metalindex >= 0) return mat.metal[parseInt(selection.metalindex)];
330 return null;
331 }
332
333 function renderShaderStatus() {
334 const shader = getShaderRecord(gCurrentShader);
335 let statusString = "";
336 if (shader && shader.modified) {
337 statusString += " &nbsp; <a class='rebuild'>[rebuild]</a>";
338 }
339 if (shader && !shader.active) {
340 statusString += " &nbsp; <span class='warning'> selected variant is inactive </span>";
341 }
342 header.innerHTML = "matdbg" + statusString;
343 }
344
345 function selectShader(selection) {
346 const shader = getShaderRecord(selection);
347 if (!shader) {
348 console.error("Shader not yet available.")
349 return;
350 }
351 const showShaderSource = () => {
352 gCurrentShader = selection;
353 gCurrentShader.matid = gCurrentMaterial;
354 renderMaterialDetail();
355 gEditorIsLoading = true;
356 gEditor.setValue(shader.text);
357 gEditorIsLoading = false;
358 shaderSource.style.visibility = "visible";
359 renderShaderStatus();
360 };
361 if (!shader.text) {
362 const matInfo = gMaterialDatabase[gCurrentMaterial];
363 fetchShader(selection, matInfo, showShaderSource);
364 } else {
365 showShaderSource();
366 }
367 }
368
369 function onEdit(changes) {
370 if (gEditorIsLoading) {
371 return;
372 }
373 const shader = getShaderRecord(gCurrentShader);
374 if (!shader) {
375 return;
376 }
377 if (!shader.modified) {
378 shader.modified = true;
379 renderShaderStatus();
380 }
381 shader.text = gEditor.getValue();
382 }
383
384 function selectMaterial(matid, selectFirstShader) {
385 gCurrentMaterial = matid;
386 renderMaterialList();
387 renderMaterialDetail();
388 if (selectFirstShader) {
389 const mat = gMaterialDatabase[gCurrentMaterial];
390 const selection = { matid };
391 if (mat.opengl.length > 0) selection.glindex = 0;
392 else if (mat.vkindex.length > 0) selection.vkindex = 0;
393 else if (mat.metalindex.length > 0) selection.metalindex = 0;
394 selectShader(selection);
395 }
396 }
397
398 function init() {
399 require(["vs/editor/editor.main"], function () {
400 const KeyMod = monaco.KeyMod, KeyCode = monaco.KeyCode;
401 gEditor = monaco.editor.create(shaderSource, {
402 value: "",
403 language: "cpp",
404 scrollBeyondLastLine: false,
405 readOnly: false,
406 minimap: { enabled: false }
407 });
408 gEditor.onDidChangeModelContent((e) => { onEdit(e.changes); });
409
410 gEditor.addCommand(KeyMod.CtrlCmd | KeyCode.KEY_S, () => rebuildMaterial());
411
412 gEditor.addCommand(KeyMod.Shift | KeyMod.WinCtrl | KeyCode.UpArrow, () => selectNextShader(-1, 0));
413 gEditor.addCommand(KeyMod.Shift | KeyMod.WinCtrl | KeyCode.DownArrow, () => selectNextShader(+1, 0));
414 gEditor.addCommand(KeyMod.Shift | KeyMod.WinCtrl | KeyCode.LeftArrow, () => selectNextShader(0, -1));
415 gEditor.addCommand(KeyMod.Shift | KeyMod.WinCtrl | KeyCode.RightArrow, () => selectNextShader(0, +1));
416
417 fetchMaterials();
418 });
419
420 Mustache.parse(matDetailTemplate.innerHTML);
421 Mustache.parse(matListTemplate.innerHTML);
422
423 startSocket();
424 setInterval(queryActiveShaders, 1000);
425 }
426
427 init();