-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
333 lines (267 loc) · 9.63 KB
/
index.mjs
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import chalk from "chalk";
import puppeteer from "puppeteer";
import express from "express";
import sharp from "sharp";
import * as FileType from "file-type";
import * as fs from "fs/promises";
import crypto from "crypto";
import * as Relative from "./relative.mjs";
const USAGE_MESSAGE = `
Usage: node index.js <path/to/in/3d_model> <path/to/out/preview>
<path/to/in/3d_model> The filename of the 3D model to render
<path/to/out/preview> The filename to save the preview image to
`;
const redirectToModelSize = 80 * 1024 * 1024; // 80 megabytes in bytes - for how big models should be redirected to file instead of sending them in response
const idleTime = 9; // 9 seconds - for how long there should be no network requests
const parseTime = 1; // 1 seconds per megabyte
const networkTimeout = 5; // 5 minutes, set to 0 to disable
const renderTimeout = 5; // 5 seconds, set to 0 to disable
const width = 1024;
const height = 1024;
const viewScale = 2;
console.red = (msg) => console.log(chalk.red(msg));
console.yellow = (msg) => console.log(chalk.yellow(msg));
console.green = (msg) => console.log(chalk.green(msg));
const pathToIn3dModel = process.argv[2];
const pathToOutPreview = process.argv[3];
if (!pathToIn3dModel) {
console.log(USAGE_MESSAGE);
process.exit(2);
}
if (!pathToOutPreview) {
console.log(USAGE_MESSAGE);
process.exit(3);
}
let browser;
let tempModelFileName;
/* Launch server */
let port;
const app = express();
app.use(express.static(Relative.fullPath("public")));
const server = app.listen(0, "127.0.0.1", main);
process.on("SIGINT", () => close());
async function main() {
port = server.address().port;
console.log(`Server listening on port ${port}`);
/* Launch browser */
const flags = [
"--hide-scrollbars",
"--enable-gpu",
"--no-sandbox",
"--disable-site-isolation-trials",
"--disable-dev-shm-usage",
];
// flags.push(
// "--enable-unsafe-webgpu",
// "--enable-features=Vulkan",
// "--use-gl=swiftshader",
// "--use-angle=swiftshader",
// "--use-vulkan=swiftshader",
// "--use-webgpu-adapter=swiftshader"
// );
// if (process.platform === "linux")
// flags.push(
// "--enable-features=Vulkan,UseSkiaRenderer",
// "--use-vulkan=native",
// "--disable-vulkan-surface",
// "--disable-features=VaapiVideoDecoder",
// "--ignore-gpu-blocklist",
// "--use-angle=vulkan"
// );
const viewport = { width: width * viewScale, height: height * viewScale };
browser = await puppeteer.launch({
headless: process.env.VISIBLE ? false : "new",
args: flags,
defaultViewport: viewport,
handleSIGINT: false,
protocolTimeout: 0,
});
// this line is intended to stop the script if the browser (in headful mode) is closed by user (while debugging)
// browser.on( 'targetdestroyed', target => ( target.type() === 'other' ) ? close() : null );
// for some reason it randomly stops the script after about ~30 screenshots processed
/* Prepare injections */
let cleanPage, injection, model;
try {
cleanPage = await fs.readFile(Relative.fullPath("clean-page.js"), "utf8");
injection = await fs.readFile(Relative.fullPath("deterministic-injection.js"), "utf8");
model = await fs.readFile(pathToIn3dModel);
} catch (e) {
console.red(e);
close();
}
/* Prepare page */
const errorMessagesCache = [];
const pages = await browser.pages();
if (pages.length === 0) pages.push(await browser.newPage());
const page = pages[0];
await preparePage(page, injection, model, errorMessagesCache);
/* Make attempt */
await makeAttempt(page, cleanPage, pathToOutPreview);
/* Finish */
setTimeout(close, 300, 0);
}
async function preparePage(page, injection, model, errorMessages) {
await page.evaluateOnNewDocument(injection);
await page.setRequestInterception(true);
page.on("console", async (msg) => {
const type = msg.type();
if (type !== "warning" && type !== "error") {
return;
}
const file = page.file;
if (file === undefined) {
return;
}
const args = await Promise.all(
msg.args().map(async (arg) => {
try {
return await arg.executionContext().evaluate((arg) => (arg instanceof Error ? arg.message : arg), arg);
} catch (e) {
// Execution context might have been already destroyed
return arg;
}
})
);
let text = args.join(" "); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
text = text.trim();
if (text === "") return;
text = file + ": " + text.replace(/\[\.WebGL-(.+?)\] /g, "");
if (text === `${file}: JSHandle@error`) {
text = `${file}: Unknown error`;
}
if (text.includes("Unable to access the camera/webcam")) {
return;
}
if (errorMessages.includes(text)) {
return;
}
errorMessages.push(text);
if (type === "warning") {
console.yellow(text);
} else {
page.error = text;
}
});
page.on("response", async (response) => {
try {
if (response.status() === 200) {
console.green(`Response: ${response.url()}, ${response.headers()["content-length"]} bytes`);
await response.buffer().then((buffer) => (page.pageSize += buffer.length));
} else if (response.status() === 302) {
console.green(`Response: ${response.url()} (${response.status()})`);
} else {
console.red(`Response: ${response.url()} (${response.status()})`);
}
} catch {}
});
page.on("request", async (request) => {
if (request.url() === `http://localhost:${port}/models/model.glb`) {
const buffer = await Buffer.from(model);
const fileType = await FileType.fileTypeFromBuffer(buffer);
if (buffer.length > redirectToModelSize) {
// save model as file with random name
tempModelFileName = `model.${crypto.randomUUID()}.${fileType.ext}`;
await fs.writeFile(`public/models/${tempModelFileName}`, buffer);
console.green(`Model redirecting: ${tempModelFileName}`);
// redirect request to the file
await request.respond({
status: 302,
headers: {
location: `/models/${tempModelFileName}`,
},
});
// delete file after it was sent
await page.waitForNetworkIdle({
timeout: networkTimeout * 60000,
idleTime: idleTime * 1000,
});
await fs.unlink(`public/models/${tempModelFileName}`);
tempModelFileName = undefined;
} else {
console.green(`Model sending: ${fileType.ext}: ${fileType.mime} ${buffer.length} bytes`);
await request.respond({
status: 200,
contentType: fileType.mime,
body: buffer,
});
}
} else {
await request.continue();
}
});
}
async function makeAttempt(page, cleanPage, screenshotPath) {
try {
page.pageSize = 0;
page.error = undefined;
/* Load target page */
const file = "index";
try {
await page.goto(`http://localhost:${port}/${file}.html`, {
waitUntil: "networkidle0",
timeout: networkTimeout * 60000,
});
} catch (e) {
throw new Error(`Error happened while loading file ${file}: ${e}`);
}
try {
/* Render page */
console.green(`Rendering file ${file}`);
await page.evaluate(cleanPage);
await page.waitForNetworkIdle({
timeout: networkTimeout * 60000,
idleTime: idleTime * 1000,
});
await page.evaluate(
async (renderTimeout, parseTime) => {
await new Promise((resolve) => setTimeout(resolve, parseTime));
/* Resolve render promise */
window._renderStarted = true;
await new Promise(function (resolve, reject) {
const renderStart = performance._now();
const waitingLoop = setInterval(function () {
const renderTimeoutExceeded =
renderTimeout > 0 && performance._now() - renderStart > 1000 * renderTimeout;
if (renderTimeoutExceeded) {
clearInterval(waitingLoop);
reject("Render timeout exceeded");
} else if (window._renderFinished) {
clearInterval(waitingLoop);
resolve();
}
}, 10);
});
},
renderTimeout,
(page.pageSize / 1024 / 1024) * parseTime * 1000
);
} catch (e) {
if (e.includes && e.includes("Render timeout exceeded") === false) {
throw new Error(`Error happened while rendering file ${file}: ${e}`);
} /* else { // This can mean that the example doesn't use requestAnimationFrame loop
console.yellow( `Render timeout exceeded in file ${ file }` );
} */ // TODO: fix this
}
const screenshot = await page.screenshot({ omitBackground: true });
if (page.error !== undefined) throw new Error(page.error);
// check if image is only transparent
const image = await sharp(screenshot).ensureAlpha().raw().toBuffer();
const transparent = image.every((value, index) => index % 4 === 3 || value === 0);
if (transparent) throw new Error("Image is transparent");
/* Make screenshots */
// downscale png screenshot
const png = await sharp(screenshot).png().toBuffer();
const downscale = await sharp(png).resize(width, height).toBuffer();
await fs.writeFile(screenshotPath, downscale);
console.green(`Screenshot generated for file ${screenshotPath}`);
} catch (e) {
console.red(e);
}
}
function close(exitCode = 1) {
console.log("Closing...");
if (browser) browser.close();
if (server) server.close();
if (tempModelFileName) fs.unlink(`public/models/${tempModelFileName}`);
process.exit(exitCode);
}