puppeteer.js 16 KB

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