screenshotTools.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import { Nullable } from "../types";
  2. import { Camera } from "../Cameras/camera";
  3. import { Texture } from "../Materials/Textures/texture";
  4. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  5. import { FxaaPostProcess } from "../PostProcesses/fxaaPostProcess";
  6. import { Constants } from "../Engines/constants";
  7. import { Logger } from "./logger";
  8. import { _TypeStore } from "./typeStore";
  9. import { Tools } from "./tools";
  10. import { IScreenshotSize } from './interfaces/screenshotSize';
  11. declare type Engine = import("../Engines/engine").Engine;
  12. /**
  13. * Class containing a set of static utilities functions for screenshots
  14. */
  15. export class ScreenshotTools {
  16. /**
  17. * Captures a screenshot of the current rendering
  18. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  19. * @param engine defines the rendering engine
  20. * @param camera defines the source camera
  21. * @param size This parameter can be set to a single number or to an object with the
  22. * following (optional) properties: precision, width, height. If a single number is passed,
  23. * it will be used for both width and height. If an object is passed, the screenshot size
  24. * will be derived from the parameters. The precision property is a multiplier allowing
  25. * rendering at a higher or lower resolution
  26. * @param successCallback defines the callback receives a single parameter which contains the
  27. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  28. * src parameter of an <img> to display it
  29. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  30. * Check your browser for supported MIME types
  31. */
  32. public static CreateScreenshot(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  33. const { height, width } = ScreenshotTools._getScreenshotSize(engine, camera, size);
  34. // TODO WEBGPU use engine.readPixels to get the back buffer
  35. if (!(height && width)) {
  36. Logger.Error("Invalid 'size' parameter !");
  37. return;
  38. }
  39. if (!Tools._ScreenshotCanvas) {
  40. Tools._ScreenshotCanvas = document.createElement('canvas');
  41. }
  42. Tools._ScreenshotCanvas.width = width;
  43. Tools._ScreenshotCanvas.height = height;
  44. var renderContext = Tools._ScreenshotCanvas.getContext("2d");
  45. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  46. var newWidth = width;
  47. var newHeight = newWidth / ratio;
  48. if (newHeight > height) {
  49. newHeight = height;
  50. newWidth = newHeight * ratio;
  51. }
  52. var offsetX = Math.max(0, width - newWidth) / 2;
  53. var offsetY = Math.max(0, height - newHeight) / 2;
  54. var renderingCanvas = engine.getRenderingCanvas();
  55. if (renderContext && renderingCanvas) {
  56. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  57. }
  58. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  59. }
  60. /**
  61. * Captures a screenshot of the current rendering
  62. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  63. * @param engine defines the rendering engine
  64. * @param camera defines the source camera
  65. * @param size This parameter can be set to a single number or to an object with the
  66. * following (optional) properties: precision, width, height. If a single number is passed,
  67. * it will be used for both width and height. If an object is passed, the screenshot size
  68. * will be derived from the parameters. The precision property is a multiplier allowing
  69. * rendering at a higher or lower resolution
  70. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  71. * Check your browser for supported MIME types
  72. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  73. * to the src parameter of an <img> to display it
  74. */
  75. public static CreateScreenshotAsync(engine: Engine, camera: Camera, size: any, mimeType: string = "image/png"): Promise<string> {
  76. return new Promise((resolve, reject) => {
  77. ScreenshotTools.CreateScreenshot(engine, camera, size, (data) => {
  78. if (typeof(data) !== "undefined") {
  79. resolve(data);
  80. } else {
  81. reject(new Error("Data is undefined"));
  82. }
  83. }, mimeType);
  84. });
  85. }
  86. /**
  87. * Generates an image screenshot from the specified camera.
  88. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  89. * @param engine The engine to use for rendering
  90. * @param camera The camera to use for rendering
  91. * @param size This parameter can be set to a single number or to an object with the
  92. * following (optional) properties: precision, width, height. If a single number is passed,
  93. * it will be used for both width and height. If an object is passed, the screenshot size
  94. * will be derived from the parameters. The precision property is a multiplier allowing
  95. * rendering at a higher or lower resolution
  96. * @param successCallback The callback receives a single parameter which contains the
  97. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  98. * src parameter of an <img> to display it
  99. * @param mimeType The MIME type of the screenshot image (default: image/png).
  100. * Check your browser for supported MIME types
  101. * @param samples Texture samples (default: 1)
  102. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  103. * @param fileName A name for for the downloaded file.
  104. * @param renderSprites Whether the sprites should be rendered or not (default: false)
  105. * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)
  106. */
  107. public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string, renderSprites: boolean = false, enableStencilBuffer: boolean = false): void {
  108. const { height, width } = ScreenshotTools._getScreenshotSize(engine, camera, size);
  109. let targetTextureSize = { width, height };
  110. if (!(height && width)) {
  111. Logger.Error("Invalid 'size' parameter !");
  112. return;
  113. }
  114. var scene = camera.getScene();
  115. var previousCamera: Nullable<Camera> = null;
  116. if (scene.activeCamera !== camera) {
  117. previousCamera = scene.activeCamera;
  118. scene.activeCamera = camera;
  119. }
  120. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  121. var texture = new RenderTargetTexture("screenShot", targetTextureSize, scene, false, false, Constants.TEXTURETYPE_UNSIGNED_INT, false, Texture.NEAREST_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples);
  122. texture.renderList = null;
  123. texture.samples = samples;
  124. texture.renderSprites = renderSprites;
  125. engine.onEndFrameObservable.addOnce(() => {
  126. texture.readPixels()!.then((data) => {
  127. Tools.DumpData(width, height, data, successCallback, mimeType, fileName, true);
  128. texture.dispose();
  129. if (previousCamera) {
  130. scene.activeCamera = previousCamera;
  131. }
  132. camera.getProjectionMatrix(true); // Force cache refresh;
  133. });
  134. });
  135. const renderToTexture = () => {
  136. scene.incrementRenderId();
  137. scene.resetCachedMaterial();
  138. texture.render(true);
  139. };
  140. if (antialiasing) {
  141. const fxaaPostProcess = new FxaaPostProcess('antialiasing', 1.0, scene.activeCamera);
  142. texture.addPostProcess(fxaaPostProcess);
  143. // Async Shader Compilation can lead to none ready effects in synchronous code
  144. if (!fxaaPostProcess.getEffect().isReady()) {
  145. fxaaPostProcess.getEffect().onCompiled = () => {
  146. renderToTexture();
  147. };
  148. }
  149. // The effect is ready we can render
  150. else {
  151. renderToTexture();
  152. }
  153. }
  154. else {
  155. // No need to wait for extra resources to be ready
  156. renderToTexture();
  157. }
  158. }
  159. /**
  160. * Generates an image screenshot from the specified camera.
  161. * @see https://doc.babylonjs.com/how_to/render_scene_on_a_png
  162. * @param engine The engine to use for rendering
  163. * @param camera The camera to use for rendering
  164. * @param size This parameter can be set to a single number or to an object with the
  165. * following (optional) properties: precision, width, height. If a single number is passed,
  166. * it will be used for both width and height. If an object is passed, the screenshot size
  167. * will be derived from the parameters. The precision property is a multiplier allowing
  168. * rendering at a higher or lower resolution
  169. * @param mimeType The MIME type of the screenshot image (default: image/png).
  170. * Check your browser for supported MIME types
  171. * @param samples Texture samples (default: 1)
  172. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  173. * @param fileName A name for for the downloaded file.
  174. * @param renderSprites Whether the sprites should be rendered or not (default: false)
  175. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  176. * to the src parameter of an <img> to display it
  177. */
  178. public static CreateScreenshotUsingRenderTargetAsync(engine: Engine, camera: Camera, size: any, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string, renderSprites: boolean = false): Promise<string> {
  179. return new Promise((resolve, reject) => {
  180. ScreenshotTools.CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {
  181. if (typeof(data) !== "undefined") {
  182. resolve(data);
  183. } else {
  184. reject(new Error("Data is undefined"));
  185. }
  186. }, mimeType, samples, antialiasing, fileName, renderSprites);
  187. });
  188. }
  189. /**
  190. * Gets height and width for screenshot size
  191. * @private
  192. */
  193. private static _getScreenshotSize(engine: Engine, camera: Camera, size: IScreenshotSize | number): {height: number, width: number} {
  194. let height = 0;
  195. let width = 0;
  196. //If a size value defined as object
  197. if (typeof(size) === 'object') {
  198. const precision = size.precision
  199. ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height
  200. : 1;
  201. //If a width and height values is specified
  202. if (size.width && size.height) {
  203. height = size.height * precision;
  204. width = size.width * precision;
  205. }
  206. //If passing only width, computing height to keep display canvas ratio.
  207. else if (size.width && !size.height) {
  208. width = size.width * precision;
  209. height = Math.round(width / engine.getAspectRatio(camera));
  210. }
  211. //If passing only height, computing width to keep display canvas ratio.
  212. else if (size.height && !size.width) {
  213. height = size.height * precision;
  214. width = Math.round(height * engine.getAspectRatio(camera));
  215. }
  216. else {
  217. width = Math.round(engine.getRenderWidth() * precision);
  218. height = Math.round(width / engine.getAspectRatio(camera));
  219. }
  220. }
  221. //Assuming here that "size" parameter is a number
  222. else if (!isNaN(size)) {
  223. height = size;
  224. width = size;
  225. }
  226. // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context
  227. // On certain GPUs, it seems as if the _gl context truncates to an integer automatically. Therefore, if a user tries to pass the width of their canvas element
  228. // and it happens to be a float (1000.5 x 600.5 px), the engine.readPixels will return a different size array than context.createImageData
  229. // to resolve this, we truncate the floats here to ensure the same size
  230. if (width) {
  231. width = Math.floor(width);
  232. }
  233. if (height) {
  234. height = Math.floor(height);
  235. }
  236. return { height: height | 0, width: width | 0 };
  237. }
  238. }
  239. Tools.CreateScreenshot = ScreenshotTools.CreateScreenshot;
  240. Tools.CreateScreenshotAsync = ScreenshotTools.CreateScreenshotAsync;
  241. Tools.CreateScreenshotUsingRenderTarget = ScreenshotTools.CreateScreenshotUsingRenderTarget;
  242. Tools.CreateScreenshotUsingRenderTargetAsync = ScreenshotTools.CreateScreenshotUsingRenderTargetAsync;