1
0

puppeteer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. import chalk from 'chalk';
  2. import puppeteer from 'puppeteer';
  3. import express from 'express';
  4. import path from 'path';
  5. import pixelmatch from 'pixelmatch';
  6. import { Jimp } from 'jimp';
  7. import * as fs from 'fs/promises';
  8. class PromiseQueue {
  9. constructor( func, ...args ) {
  10. this.func = func.bind( this, ...args );
  11. this.promises = [];
  12. }
  13. add( ...args ) {
  14. const promise = this.func( ...args );
  15. this.promises.push( promise );
  16. promise.then( () => this.promises.splice( this.promises.indexOf( promise ), 1 ) );
  17. }
  18. async waitForAll() {
  19. while ( this.promises.length > 0 ) {
  20. await Promise.all( this.promises );
  21. }
  22. }
  23. }
  24. /* CONFIG VARIABLES START */
  25. const idleTime = 12; // 9 seconds - for how long there should be no network requests
  26. const parseTime = 6; // 6 seconds per megabyte
  27. const exceptionList = [
  28. // tiles not loaded in time for screenshot
  29. 'webgl_loader_3dtiles',
  30. // video tag isn't deterministic enough?
  31. 'css3d_youtube',
  32. 'webgl_materials_video',
  33. 'webgl_video_kinect',
  34. 'webgl_video_panorama_equirectangular',
  35. 'webgpu_video_frame',
  36. 'webaudio_visualizer', // audio can't be analyzed without proper audio hook
  37. // WebXR also isn't deterministic enough?
  38. 'webxr_ar_lighting',
  39. 'webxr_vr_sandbox',
  40. 'webxr_vr_video',
  41. 'webxr_xr_ballshooter',
  42. 'webxr_xr_dragging_custom_depth',
  43. 'webgl_worker_offscreencanvas', // in a worker, not robust
  44. // Windows-Linux text rendering differences
  45. // TODO: Fix these by e.g. disabling text rendering altogether -- this can also fix a bunch of 0.1%-0.2% examples
  46. 'css3d_periodictable',
  47. 'misc_controls_pointerlock',
  48. 'misc_uv_tests',
  49. 'webgl_camera_logarithmicdepthbuffer',
  50. 'webgl_effects_ascii',
  51. 'webgl_geometry_extrude_shapes',
  52. 'webgl_interactive_lines',
  53. 'webgl_loader_collada_kinematics',
  54. 'webgl_loader_ldraw',
  55. 'webgl_loader_pdb',
  56. 'webgl_modifier_simplifier',
  57. 'webgl_multiple_canvases_circle',
  58. 'webgl_multiple_elements_text',
  59. // Unknown
  60. // TODO: most of these can be fixed just by increasing idleTime and parseTime
  61. 'physics_rapier_basic',
  62. 'webgl_animation_skinning_blending',
  63. 'webgl_animation_skinning_additive_blending',
  64. 'webgl_buffergeometry_glbufferattribute',
  65. 'webgl_interactive_cubes_gpu',
  66. 'webgl_clipping_advanced',
  67. 'webgl_lensflares',
  68. 'webgl_lights_spotlights',
  69. 'webgl_loader_imagebitmap',
  70. 'webgl_loader_texture_ktx',
  71. 'webgl_loader_texture_lottie',
  72. 'webgl_loader_texture_pvrtc',
  73. 'webgl_materials_alphahash',
  74. 'webgpu_materials_alphahash',
  75. 'webgl_materials_blending',
  76. 'webgl_mirror',
  77. 'webgl_morphtargets_face',
  78. 'webgl_postprocessing_transition',
  79. 'webgl_postprocessing_glitch',
  80. 'webgl_postprocessing_dof2',
  81. 'webgl_renderer_pathtracer',
  82. 'webgl_shadowmap',
  83. 'webgl_shadowmap_progressive',
  84. 'webgpu_shadowmap_progressive',
  85. 'webgl_test_memory2',
  86. 'webgl_points_dynamic',
  87. 'webgpu_multisampled_renderbuffers',
  88. 'webgl_test_wide_gamut',
  89. 'webgl_volume_instancing',
  90. // Intentional z-fighting in this demo makes it non-deterministic
  91. 'webgl_reverse_depth_buffer',
  92. // TODO: implement determinism for setTimeout and setInterval
  93. // could it fix some examples from above?
  94. 'physics_rapier_instancing',
  95. 'physics_jolt_instancing',
  96. // Awaiting for WebGL backend support
  97. 'webgpu_compute_audio',
  98. 'webgpu_compute_texture',
  99. 'webgpu_compute_texture_pingpong',
  100. 'webgpu_compute_water',
  101. 'webgpu_materials',
  102. 'webgpu_sandbox',
  103. 'webgpu_video_panorama',
  104. 'webgpu_postprocessing_bloom_emissive',
  105. 'webgpu_lights_tiled',
  106. 'webgpu_postprocessing_traa',
  107. // Awaiting for WebGPU Backend support in Puppeteer
  108. 'webgpu_storage_buffer',
  109. 'webgpu_compute_sort_bitonic',
  110. 'webgpu_struct_drawindirect',
  111. // WebGPURenderer: Unknown problem
  112. 'webgpu_backdrop_water',
  113. "webgpu_centroid_sampling",
  114. 'webgpu_camera_logarithmicdepthbuffer',
  115. 'webgpu_lightprobe_cubecamera',
  116. 'webgpu_loader_materialx',
  117. 'webgpu_materials_video',
  118. 'webgpu_materialx_noise',
  119. 'webgpu_morphtargets_face',
  120. 'webgpu_occlusion',
  121. 'webgpu_particles',
  122. 'webgpu_shadertoy',
  123. 'webgpu_shadowmap',
  124. 'webgpu_shadowmap_array',
  125. 'webgpu_tsl_editor',
  126. 'webgpu_tsl_transpiler',
  127. 'webgpu_tsl_interoperability',
  128. 'webgpu_portal',
  129. 'webgpu_custom_fog',
  130. 'webgpu_instancing_morph',
  131. 'webgpu_texturegrad',
  132. 'webgpu_performance_renderbundle',
  133. 'webgpu_lights_rectarealight',
  134. 'webgpu_tsl_vfx_flames',
  135. 'webgpu_tsl_halftone',
  136. 'webgpu_tsl_vfx_linkedparticles',
  137. 'webgpu_textures_anisotropy',
  138. 'webgpu_textures_2d-array_compressed',
  139. 'webgpu_rendertarget_2d-array_3d',
  140. 'webgpu_materials_envmaps_bpcem',
  141. 'webgpu_postprocessing_sobel',
  142. 'webgpu_postprocessing_3dlut',
  143. 'webgpu_postprocessing_fxaa',
  144. 'webgpu_postprocessing_afterimage',
  145. 'webgpu_xr_native_layers',
  146. 'webgpu_volume_caustics',
  147. // WebGPU idleTime and parseTime too low
  148. 'webgpu_compute_particles',
  149. 'webgpu_compute_particles_rain',
  150. 'webgpu_compute_particles_snow',
  151. 'webgpu_compute_points'
  152. ];
  153. /* CONFIG VARIABLES END */
  154. const port = 1234;
  155. const pixelThreshold = 0.1; // threshold error in one pixel
  156. const maxDifferentPixels = 0.3; // at most 0.3% different pixels
  157. const networkTimeout = 5; // 5 minutes, set to 0 to disable
  158. const renderTimeout = 5; // 5 seconds, set to 0 to disable
  159. const numAttempts = 2; // perform 2 attempts before failing
  160. const numPages = 8; // use 8 browser pages
  161. const numCIJobs = 4; // GitHub Actions run the script in 4 threads
  162. const width = 400;
  163. const height = 250;
  164. const viewScale = 2;
  165. const jpgQuality = 95;
  166. console.red = msg => console.log( chalk.red( msg ) );
  167. console.yellow = msg => console.log( chalk.yellow( msg ) );
  168. console.green = msg => console.log( chalk.green( msg ) );
  169. let browser;
  170. /* Launch server */
  171. const app = express();
  172. app.use( express.static( path.resolve() ) );
  173. const server = app.listen( port, main );
  174. process.on( 'SIGINT', () => close() );
  175. async function main() {
  176. /* Create output directory */
  177. try { await fs.rm( 'test/e2e/output-screenshots', { recursive: true, force: true } ); } catch {}
  178. try { await fs.mkdir( 'test/e2e/output-screenshots' ); } catch {}
  179. /* Find files */
  180. let isMakeScreenshot = false;
  181. let isWebGPU = false;
  182. let argvIndex = 2;
  183. if ( process.argv[ argvIndex ] === '--webgpu' ) {
  184. isWebGPU = true;
  185. argvIndex ++;
  186. }
  187. if ( process.argv[ argvIndex ] === '--make' ) {
  188. isMakeScreenshot = true;
  189. argvIndex ++;
  190. }
  191. const exactList = process.argv.slice( argvIndex )
  192. .map( f => f.replace( '.html', '' ) );
  193. const isExactList = exactList.length !== 0;
  194. let files = ( await fs.readdir( 'examples' ) )
  195. .filter( s => s.slice( - 5 ) === '.html' && s !== 'index.html' )
  196. .map( s => s.slice( 0, s.length - 5 ) )
  197. .filter( f => isExactList ? exactList.includes( f ) : ! exceptionList.includes( f ) );
  198. if ( isExactList ) {
  199. for ( const file of exactList ) {
  200. if ( ! files.includes( file ) ) {
  201. console.log( `Warning! Unrecognised example name: ${ file }` );
  202. }
  203. }
  204. }
  205. if ( isWebGPU ) files = files.filter( f => f.includes( 'webgpu_' ) );
  206. /* CI parallelism */
  207. if ( 'CI' in process.env ) {
  208. const CI = parseInt( process.env.CI );
  209. files = files.slice(
  210. Math.floor( CI * files.length / numCIJobs ),
  211. Math.floor( ( CI + 1 ) * files.length / numCIJobs )
  212. );
  213. }
  214. /* Launch browser */
  215. const flags = [ '--hide-scrollbars', '--enable-gpu' ];
  216. // flags.push( '--enable-unsafe-webgpu', '--enable-features=Vulkan', '--use-gl=swiftshader', '--use-angle=swiftshader', '--use-vulkan=swiftshader', '--use-webgpu-adapter=swiftshader' );
  217. // 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' );
  218. const viewport = { width: width * viewScale, height: height * viewScale };
  219. browser = await puppeteer.launch( {
  220. headless: process.env.VISIBLE ? false : 'new',
  221. args: flags,
  222. defaultViewport: viewport,
  223. handleSIGINT: false,
  224. protocolTimeout: 0
  225. } );
  226. // this line is intended to stop the script if the browser (in headful mode) is closed by user (while debugging)
  227. // browser.on( 'targetdestroyed', target => ( target.type() === 'other' ) ? close() : null );
  228. // for some reason it randomly stops the script after about ~30 screenshots processed
  229. /* Prepare injections */
  230. const buildInjection = ( code ) => code.replace( /Math\.random\(\) \* 0xffffffff/g, 'Math._random() * 0xffffffff' );
  231. const cleanPage = await fs.readFile( 'test/e2e/clean-page.js', 'utf8' );
  232. const injection = await fs.readFile( 'test/e2e/deterministic-injection.js', 'utf8' );
  233. const builds = {
  234. 'three.core.js': buildInjection( await fs.readFile( 'build/three.core.js', 'utf8' ) ),
  235. 'three.module.js': buildInjection( await fs.readFile( 'build/three.module.js', 'utf8' ) ),
  236. 'three.webgpu.js': buildInjection( await fs.readFile( 'build/three.webgpu.js', 'utf8' ) )
  237. };
  238. /* Prepare pages */
  239. const errorMessagesCache = [];
  240. const pages = await browser.pages();
  241. while ( pages.length < numPages && pages.length < files.length ) pages.push( await browser.newPage() );
  242. for ( const page of pages ) await preparePage( page, injection, builds, errorMessagesCache );
  243. /* Loop for each file */
  244. const failedScreenshots = [];
  245. const queue = new PromiseQueue( makeAttempt, pages, failedScreenshots, cleanPage, isMakeScreenshot );
  246. for ( const file of files ) queue.add( file );
  247. await queue.waitForAll();
  248. /* Finish */
  249. failedScreenshots.sort();
  250. const list = failedScreenshots.join( ' ' );
  251. if ( isMakeScreenshot && failedScreenshots.length ) {
  252. console.red( 'List of failed screenshots: ' + list );
  253. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, try increasing idleTime and parseTime variables in /test/e2e/puppeteer.js file. If this also does not help, add remaining screenshots to the exception list.` );
  254. console.red( `${ failedScreenshots.length } from ${ files.length } screenshots have not generated successfully.` );
  255. } else if ( isMakeScreenshot && ! failedScreenshots.length ) {
  256. console.green( `${ files.length } screenshots successfully generated.` );
  257. } else if ( failedScreenshots.length ) {
  258. console.red( 'List of failed screenshots: ' + list );
  259. console.red( `If you are sure that everything is correct, try to run "npm run make-screenshot ${ list }". If this does not help, try increasing idleTime and parseTime variables in /test/e2e/puppeteer.js file. If this also does not help, add remaining screenshots to the exception list.` );
  260. console.red( `TEST FAILED! ${ failedScreenshots.length } from ${ files.length } screenshots have not rendered correctly.` );
  261. } else {
  262. console.green( `TEST PASSED! ${ files.length } screenshots rendered correctly.` );
  263. }
  264. setTimeout( close, 300, failedScreenshots.length );
  265. }
  266. async function preparePage( page, injection, builds, errorMessages ) {
  267. /* let page.file, page.pageSize, page.error */
  268. await page.evaluateOnNewDocument( injection );
  269. await page.setRequestInterception( true );
  270. page.on( 'console', async msg => {
  271. const type = msg.type();
  272. if ( type !== 'warning' && type !== 'error' ) {
  273. return;
  274. }
  275. const file = page.file;
  276. if ( file === undefined ) {
  277. return;
  278. }
  279. const args = await Promise.all( msg.args().map( async arg => {
  280. try {
  281. return await arg.executionContext().evaluate( arg => arg instanceof Error ? arg.message : arg, arg );
  282. } catch ( e ) { // Execution context might have been already destroyed
  283. return arg;
  284. }
  285. } ) );
  286. let text = args.join( ' ' ); // https://github.com/puppeteer/puppeteer/issues/3397#issuecomment-434970058
  287. text = text.trim();
  288. if ( text === '' ) return;
  289. text = file + ': ' + text.replace( /\[\.WebGL-(.+?)\] /g, '' );
  290. if ( text === `${ file }: JSHandle@error` ) {
  291. text = `${ file }: Unknown error`;
  292. }
  293. if ( text.includes( 'Unable to access the camera/webcam' ) ) {
  294. return;
  295. }
  296. if ( errorMessages.includes( text ) ) {
  297. return;
  298. }
  299. errorMessages.push( text );
  300. if ( type === 'warning' ) {
  301. console.yellow( text );
  302. } else {
  303. page.error = text;
  304. }
  305. } );
  306. page.on( 'response', async ( response ) => {
  307. try {
  308. if ( response.status === 200 ) {
  309. await response.buffer().then( buffer => page.pageSize += buffer.length );
  310. }
  311. } catch {}
  312. } );
  313. page.on( 'request', async ( request ) => {
  314. const url = request.url();
  315. for ( const build in builds ) {
  316. if ( url === `http://localhost:${ port }/build/${ build }` ) {
  317. await request.respond( {
  318. status: 200,
  319. contentType: 'application/javascript; charset=utf-8',
  320. body: builds[ build ]
  321. } );
  322. return;
  323. }
  324. }
  325. await request.continue();
  326. } );
  327. }
  328. async function makeAttempt( pages, failedScreenshots, cleanPage, isMakeScreenshot, file, attemptID = 0 ) {
  329. const page = await new Promise( ( resolve, reject ) => {
  330. const interval = setInterval( () => {
  331. for ( const page of pages ) {
  332. if ( page.file === undefined ) {
  333. page.file = file; // acquire lock
  334. clearInterval( interval );
  335. resolve( page );
  336. break;
  337. }
  338. }
  339. }, 100 );
  340. } );
  341. try {
  342. page.pageSize = 0;
  343. page.error = undefined;
  344. /* Load target page */
  345. try {
  346. await page.goto( `http://localhost:${ port }/examples/${ file }.html`, {
  347. waitUntil: 'networkidle0',
  348. timeout: networkTimeout * 60000
  349. } );
  350. } catch ( e ) {
  351. throw new Error( `Error happened while loading file ${ file }: ${ e }` );
  352. }
  353. try {
  354. /* Render page */
  355. await page.evaluate( cleanPage );
  356. await page.waitForNetworkIdle( {
  357. timeout: networkTimeout * 60000,
  358. idleTime: idleTime * 1000
  359. } );
  360. await page.evaluate( async ( renderTimeout, parseTime ) => {
  361. await new Promise( resolve => setTimeout( resolve, parseTime ) );
  362. /* Resolve render promise */
  363. window._renderStarted = true;
  364. await new Promise( function ( resolve, reject ) {
  365. const renderStart = performance._now();
  366. const waitingLoop = setInterval( function () {
  367. const renderTimeoutExceeded = ( renderTimeout > 0 ) && ( performance._now() - renderStart > 1000 * renderTimeout );
  368. if ( renderTimeoutExceeded ) {
  369. clearInterval( waitingLoop );
  370. reject( 'Render timeout exceeded' );
  371. } else if ( window._renderFinished ) {
  372. clearInterval( waitingLoop );
  373. resolve();
  374. }
  375. }, 10 );
  376. } );
  377. }, renderTimeout, page.pageSize / 1024 / 1024 * parseTime * 1000 );
  378. } catch ( e ) {
  379. if ( e.includes && e.includes( 'Render timeout exceeded' ) === false ) {
  380. throw new Error( `Error happened while rendering file ${ file }: ${ e }` );
  381. } /* else { // This can mean that the example doesn't use requestAnimationFrame loop
  382. console.yellow( `Render timeout exceeded in file ${ file }` );
  383. } */ // TODO: fix this
  384. }
  385. const screenshot = ( await Jimp.read( await page.screenshot(), { quality: jpgQuality } ) ).scale( 1 / viewScale );
  386. if ( page.error !== undefined ) throw new Error( page.error );
  387. if ( isMakeScreenshot ) {
  388. /* Make screenshots */
  389. await screenshot.write( `examples/screenshots/${ file }.jpg` );
  390. console.green( `Screenshot generated for file ${ file }` );
  391. } else {
  392. /* Diff screenshots */
  393. let expected;
  394. try {
  395. expected = ( await Jimp.read( `examples/screenshots/${ file }.jpg`, { quality: jpgQuality } ) );
  396. } catch {
  397. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  398. throw new Error( `Screenshot does not exist: ${ file }` );
  399. }
  400. const actual = screenshot.bitmap;
  401. const diff = screenshot.clone();
  402. let numDifferentPixels;
  403. try {
  404. numDifferentPixels = pixelmatch( expected.bitmap.data, actual.data, diff.bitmap.data, actual.width, actual.height, {
  405. threshold: pixelThreshold,
  406. alpha: 0.2
  407. } );
  408. } catch {
  409. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  410. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  411. throw new Error( `Image sizes does not match in file: ${ file }` );
  412. }
  413. /* Print results */
  414. const differentPixels = numDifferentPixels / ( actual.width * actual.height ) * 100;
  415. if ( differentPixels < maxDifferentPixels ) {
  416. console.green( `Diff ${ differentPixels.toFixed( 1 ) }% in file: ${ file }` );
  417. } else {
  418. await screenshot.write( `test/e2e/output-screenshots/${ file }-actual.jpg` );
  419. await expected.write( `test/e2e/output-screenshots/${ file }-expected.jpg` );
  420. await diff.write( `test/e2e/output-screenshots/${ file }-diff.jpg` );
  421. throw new Error( `Diff wrong in ${ differentPixels.toFixed( 1 ) }% of pixels in file: ${ file }` );
  422. }
  423. }
  424. } catch ( e ) {
  425. if ( attemptID === numAttempts - 1 ) {
  426. console.red( e );
  427. failedScreenshots.push( file );
  428. } else {
  429. console.yellow( `${ e }, another attempt...` );
  430. this.add( file, attemptID + 1 );
  431. }
  432. }
  433. page.file = undefined; // release lock
  434. }
  435. function close( exitCode = 1 ) {
  436. console.log( 'Closing...' );
  437. browser.close();
  438. server.close();
  439. process.exit( exitCode );
  440. }
粤ICP备19079148号