puppeteer.js 16 KB

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