puppeteer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. import puppeteer from 'puppeteer';
  2. import express from 'express';
  3. import path from 'path';
  4. import pixelmatch from 'pixelmatch';
  5. import { Jimp } from 'jimp';
  6. import * as fs from 'fs/promises';
  7. const exceptionList = [
  8. // Take too long
  9. 'webgpu_parallax_uv', // 11 min
  10. 'webgpu_cubemap_adjustments', // 9 min
  11. 'webgl_loader_lwo', // 8 min
  12. 'webgpu_cubemap_mix', // 2 min
  13. 'webgl_loader_texture_ultrahdr', // 1 min
  14. 'webgl_marchingcubes', // 1 min
  15. 'webgl_materials_cubemap_dynamic', // 1 min
  16. 'webgl_materials_displacementmap', // 1 min
  17. 'webgl_materials_envmaps_hdr', // 1 min
  18. 'webgpu_water', // 1 min
  19. // Needs investigation
  20. 'physics_rapier_instancing',
  21. 'webgl_shadowmap',
  22. 'webgl_postprocessing_dof2',
  23. 'webgl_postprocessing_glitch',
  24. 'webgl_video_kinect',
  25. 'webgl_worker_offscreencanvas',
  26. 'webgpu_backdrop_water',
  27. 'webgpu_lightprobe_cubecamera',
  28. 'webgpu_portal',
  29. 'webgpu_postprocessing_ao',
  30. 'webgpu_postprocessing_dof',
  31. 'webgpu_postprocessing_ssgi',
  32. 'webgpu_postprocessing_sss',
  33. 'webgpu_postprocessing_traa',
  34. 'webgpu_reflection',
  35. 'webgpu_test_memory',
  36. 'webgpu_texturegrad',
  37. 'webgpu_tsl_vfx_flames',
  38. // Need more time to render
  39. 'css3d_mixed',
  40. 'webgl_loader_3dtiles',
  41. 'webgl_loader_texture_lottie',
  42. 'webgl_morphtargets_face',
  43. 'webgl_renderer_pathtracer',
  44. 'webgl_shadowmap_progressive',
  45. 'webgpu_materials_matcap',
  46. 'webgpu_morphtargets_face',
  47. 'webgpu_shadowmap_progressive',
  48. // Video hangs the CI?
  49. 'css3d_youtube',
  50. 'webgpu_materials_video',
  51. // Timeout
  52. 'webgl_test_memory2',
  53. // Webcam
  54. 'webgl_materials_video_webcam',
  55. 'webgl_morphtargets_webcam',
  56. // WebGL device lost
  57. 'webgpu_materialx_noise',
  58. 'webgpu_portal',
  59. 'webgpu_shadowmap',
  60. // WebGPU needed
  61. 'webgpu_compute_audio',
  62. 'webgpu_compute_birds',
  63. 'webgpu_compute_cloth',
  64. 'webgpu_compute_particles_fluid',
  65. 'webgpu_compute_reduce',
  66. 'webgpu_compute_sort_bitonic',
  67. 'webgpu_compute_texture',
  68. 'webgpu_compute_texture_3d',
  69. 'webgpu_compute_texture_pingpong',
  70. 'webgpu_compute_water',
  71. 'webgpu_hdr',
  72. 'webgpu_lights_tiled',
  73. 'webgpu_materials',
  74. 'webgpu_multiple_canvas',
  75. 'webgpu_particles',
  76. 'webgpu_struct_drawindirect',
  77. 'webgpu_tsl_editor',
  78. 'webgpu_tsl_interoperability',
  79. 'webgpu_tsl_vfx_linkedparticles',
  80. 'webgpu_tsl_wood'
  81. ];
  82. /* Configuration */
  83. const port = 1234;
  84. const pixelThreshold = 0.1; // threshold error in one pixel
  85. const maxDifferentPixels = 0.3; // at most 0.3% different pixels
  86. const idleTime = 2; // 2 seconds - for how long there should be no network requests
  87. const parseTime = 1; // 1 second per megabyte
  88. const networkTimeout = 5; // 5 minutes, set to 0 to disable
  89. const renderTimeout = 5; // 5 seconds, set to 0 to disable
  90. const numAttempts = 2; // perform 2 attempts before failing
  91. const numCIJobs = 5; // GitHub Actions run the script in 5 threads
  92. const width = 400;
  93. const height = 250;
  94. const viewScale = 2;
  95. const jpgQuality = 95;
  96. console.red = msg => console.log( `\x1b[31m${msg}\x1b[39m` );
  97. console.green = msg => console.log( `\x1b[32m${msg}\x1b[39m` );
  98. console.yellow = msg => console.log( `\x1b[33m${msg}\x1b[39m` );
  99. let browser;
  100. /* Launch server */
  101. const app = express();
  102. app.use( express.static( path.resolve() ) );
  103. const server = app.listen( port, main );
  104. process.on( 'SIGINT', async () => {
  105. console.log( '\nInterrupted, cleaning up...' );
  106. if ( browser ) {
  107. try {
  108. await browser.close();
  109. } catch ( e ) {} // eslint-disable-line no-unused-vars
  110. }
  111. server.close();
  112. process.exit( 1 );
  113. } );
  114. async function main() {
  115. /* Create output directory */
  116. try {
  117. await fs.rm( 'test/e2e/output-screenshots', { recursive: true, force: true } );
  118. } catch ( e ) {} // eslint-disable-line no-unused-vars
  119. try {
  120. await fs.mkdir( 'test/e2e/output-screenshots' );
  121. } catch ( e ) {} // eslint-disable-line no-unused-vars
  122. /* Find files */
  123. let isMakeScreenshot = false;
  124. let isWebGPU = false;
  125. let argvIndex = 2;
  126. if ( process.argv[ argvIndex ] === '--webgpu' ) {
  127. isWebGPU = true;
  128. argvIndex ++;
  129. }
  130. if ( process.argv[ argvIndex ] === '--make' ) {
  131. isMakeScreenshot = true;
  132. argvIndex ++;
  133. }
  134. const exactList = process.argv.slice( argvIndex )
  135. .map( f => f.replace( '.html', '' ) );
  136. const isExactList = exactList.length !== 0;
  137. let files = ( await fs.readdir( 'examples' ) )
  138. .filter( s => s.slice( - 5 ) === '.html' && s !== 'index.html' )
  139. .map( s => s.slice( 0, s.length - 5 ) )
  140. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  141. if ( isExactList ) {
  142. for ( const file of exactList ) {
  143. if ( ! files.includes( file ) ) {
  144. console.log( `Warning! Unrecognised example name: ${ file }` );
  145. }
  146. }
  147. }
  148. if ( isWebGPU ) files = files.filter( f => f.includes( 'webgpu_' ) );
  149. /* CI parallelism */
  150. if ( 'CI' in process.env ) {
  151. const CI = parseInt( process.env.CI );
  152. files = files.slice(
  153. Math.floor( CI * files.length / numCIJobs ),
  154. Math.floor( ( CI + 1 ) * files.length / numCIJobs )
  155. );
  156. }
  157. /* Launch browser */
  158. const flags = [
  159. '--hide-scrollbars',
  160. '--use-angle=swiftshader',
  161. '--enable-unsafe-swiftshader',
  162. '--no-sandbox'
  163. ];
  164. const viewport = { width: width * viewScale, height: height * viewScale };
  165. browser = await puppeteer.launch( {
  166. headless: process.env.VISIBLE ? false : 'new',
  167. args: flags,
  168. defaultViewport: viewport,
  169. handleSIGINT: false,
  170. protocolTimeout: 0,
  171. userDataDir: './.puppeteer_profile'
  172. } );
  173. /* Prepare injections */
  174. const buildInjection = ( code ) => code.replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  175. const cleanPage = await fs.readFile( 'test/e2e/clean-page.js', 'utf8' );
  176. const injection = await fs.readFile( 'test/e2e/deterministic-injection.js', 'utf8' );
  177. const builds = {
  178. 'three.core.js': buildInjection( await fs.readFile( 'build/three.core.js', 'utf8' ) ),
  179. 'three.module.js': buildInjection( await fs.readFile( 'build/three.module.js', 'utf8' ) ),
  180. 'three.webgpu.js': buildInjection( await fs.readFile( 'build/three.webgpu.js', 'utf8' ) )
  181. };
  182. /* Prepare page */
  183. const errorMessagesCache = [];
  184. const page = await browser.newPage();
  185. await preparePage( page, injection, builds, errorMessagesCache );
  186. /* Loop for each file */
  187. const failedScreenshots = [];
  188. for ( const file of files ) {
  189. await makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file );
  190. }
  191. /* Finish */
  192. failedScreenshots.sort();
  193. const list = failedScreenshots.join( ' ' );
  194. if ( isMakeScreenshot && failedScreenshots.length ) {
  195. console.red( 'List of failed screenshots: ' + list );
  196. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, add remaining screenshots to the exception list.` );
  197. console.red( `${ failedScreenshots.length } from ${ files.length } screenshots have not generated successfully.` );
  198. } else if ( isMakeScreenshot && ! failedScreenshots.length ) {
  199. console.green( `${ files.length } screenshots successfully generated.` );
  200. } else if ( failedScreenshots.length ) {
  201. console.red( 'List of failed screenshots: ' + list );
  202. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, add remaining screenshots to the exception list.` );
  203. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ files.length } screenshots have not rendered correctly.` );
  204. } else {
  205. console.green( `TEST PASSED! ${ files.length } screenshots rendered correctly.` );
  206. }
  207. setTimeout( close, 300, failedScreenshots.length );
  208. }
  209. async function preparePage( page, injection, builds, errorMessages ) {
  210. await page.evaluateOnNewDocument( injection );
  211. await page.setRequestInterception( true );
  212. page.on( 'console', async msg => {
  213. const type = msg.type();
  214. const file = page.file;
  215. if ( file === undefined ) {
  216. return;
  217. }
  218. const args = await Promise.all( msg.args().map( async arg => {
  219. try {
  220. return await arg.executionContext().evaluate( arg => arg instanceof Error ? arg.message : arg, arg );
  221. } catch ( e ) { // eslint-disable-line no-unused-vars
  222. // Execution context might have been already destroyed
  223. return arg;
  224. }
  225. } ) );
  226. let text = args.join( ' ' ); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
  227. text = text.trim();
  228. if ( text === '' ) return;
  229. text = file + ': ' + text.replace( /\[\.WebGL-(.+?)\] /g, '' );
  230. if ( text === `${ file }: JSHandle@error` ) {
  231. text = `${ file }: Unknown error`;
  232. }
  233. if ( errorMessages.includes( text ) ) {
  234. return;
  235. }
  236. errorMessages.push( text );
  237. if ( type === 'warning' ) {
  238. console.yellow( text );
  239. } else if ( type === 'error' ) {
  240. page.error = text;
  241. } else {
  242. console.log( `[Browser] ${text}` );
  243. }
  244. } );
  245. page.on( 'response', async ( response ) => {
  246. try {
  247. if ( response.status === 200 ) {
  248. await response.buffer().then( buffer => page.pageSize += buffer.length );
  249. }
  250. } catch ( e ) {} // eslint-disable-line no-unused-vars
  251. } );
  252. page.on( 'request', async ( request ) => {
  253. const url = request.url();
  254. for ( const build in builds ) {
  255. if ( url === `http://localhost:${ port }/build/${ build }` ) {
  256. await request.respond( {
  257. status: 200,
  258. contentType: 'application/javascript; charset=utf-8',
  259. body: builds[ build ]
  260. } );
  261. return;
  262. }
  263. }
  264. await request.continue();
  265. } );
  266. }
  267. async function makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID = 0 ) {
  268. try {
  269. page.file = file;
  270. page.pageSize = 0;
  271. page.error = undefined;
  272. /* Load target page */
  273. try {
  274. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  275. waitUntil: 'networkidle0',
  276. timeout: networkTimeout * 60000
  277. } );
  278. } catch ( e ) {
  279. throw new Error( `Error happened while loading file ${ file }: ${ e }` );
  280. }
  281. try {
  282. /* Render page */
  283. await page.evaluate( cleanPage );
  284. await page.waitForNetworkIdle( {
  285. timeout: networkTimeout * 60000,
  286. idleTime: idleTime * 1000
  287. } );
  288. await page.evaluate( async ( renderTimeout, parseTime ) => {
  289. await new Promise( resolve => setTimeout( resolve, parseTime ) );
  290. /* Resolve render promise */
  291. window._renderStarted = true;
  292. await new Promise( function ( resolve, reject ) {
  293. const renderStart = performance._now();
  294. const waitingLoop = setInterval( function () {
  295. const renderTimeoutExceeded = ( renderTimeout > 0 ) && ( performance._now() - renderStart > 1000 * renderTimeout );
  296. if ( renderTimeoutExceeded ) {
  297. clearInterval( waitingLoop );
  298. reject( 'Render timeout exceeded' );
  299. } else if ( window._renderFinished ) {
  300. clearInterval( waitingLoop );
  301. resolve();
  302. }
  303. }, 100 );
  304. } );
  305. }, renderTimeout, page.pageSize / 1024 / 1024 * parseTime * 1000 );
  306. } catch ( e ) {
  307. if ( e.includes && e.includes( 'Render timeout exceeded' ) === false ) {
  308. throw new Error( `Error happened while rendering file ${ file }: ${ e }` );
  309. } /* else { // This can mean that the example doesn't use requestAnimationFrame loop
  310. console.yellow( `Render timeout exceeded in file ${ file }` );
  311. } */ // TODO: fix this
  312. }
  313. const screenshot = ( await Jimp.read( await page.screenshot(), { quality: jpgQuality } ) ).scale( 1 / viewScale );
  314. if ( page.error !== undefined ) throw new Error( page.error );
  315. if ( isMakeScreenshot ) {
  316. /* Make screenshots */
  317. await screenshot.write( `examples/screenshots/${ file }.jpg` );
  318. console.green( `Screenshot generated for file ${ file }` );
  319. } else {
  320. /* Diff screenshots */
  321. let expected;
  322. try {
  323. expected = ( await Jimp.read( `examples/screenshots/${ file }.jpg`, { quality: jpgQuality } ) );
  324. } catch ( e ) { // eslint-disable-line no-unused-vars
  325. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  326. throw new Error( `Screenshot does not exist: ${ file }` );
  327. }
  328. const actual = screenshot.bitmap;
  329. const diff = screenshot.clone();
  330. let numDifferentPixels;
  331. try {
  332. numDifferentPixels = pixelmatch( expected.bitmap.data, actual.data, diff.bitmap.data, actual.width, actual.height, {
  333. threshold: pixelThreshold,
  334. alpha: 0.2
  335. } );
  336. } catch ( e ) { // eslint-disable-line no-unused-vars
  337. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  338. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  339. throw new Error( `Image sizes does not match in file: ${ file }` );
  340. }
  341. /* Print results */
  342. const differentPixels = numDifferentPixels / ( actual.width * actual.height ) * 100;
  343. if ( differentPixels < maxDifferentPixels ) {
  344. console.green( `Diff ${ differentPixels.toFixed( 1 ) }% in file: ${ file }` );
  345. } else {
  346. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  347. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  348. await diff.write( `test/e2e/output-screenshots/${ file }-diff.jpg` );
  349. throw new Error( `Diff wrong in ${ differentPixels.toFixed( 1 ) }% of pixels in file: ${ file }` );
  350. }
  351. }
  352. } catch ( e ) {
  353. if ( attemptID === numAttempts - 1 ) {
  354. console.red( e );
  355. failedScreenshots.push( file );
  356. } else {
  357. console.yellow( `${ e }, another attempt...` );
  358. await makeAttempt( page, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID + 1 );
  359. }
  360. } finally {
  361. page.file = undefined; // release lock
  362. }
  363. }
  364. function close( exitCode = 1 ) {
  365. console.log( 'Closing...' );
  366. browser.close();
  367. server.close();
  368. process.exit( exitCode );
  369. }
粤ICP备19079148号