puppeteer.js 16 KB

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