puppeteer.js 16 KB

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