spriteRenderer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import { Buffer, VertexBuffer } from "../Buffers/buffer.js";
  2. import { DrawWrapper } from "../Materials/drawWrapper.js";
  3. import "../Engines/Extensions/engine.alpha.js";
  4. import "../Engines/Extensions/engine.dynamicBuffer.js";
  5. import "../Shaders/sprites.fragment.js";
  6. import "../Shaders/sprites.vertex.js";
  7. /**
  8. * Class used to render sprites.
  9. *
  10. * It can be used either to render Sprites or ThinSprites with ThinEngine only.
  11. */
  12. export class SpriteRenderer {
  13. /**
  14. * Gets the capacity of the manager
  15. */
  16. get capacity() {
  17. return this._capacity;
  18. }
  19. /**
  20. * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering
  21. * Note that pixel perfect mode is not supported in WebGL 1
  22. */
  23. get pixelPerfect() {
  24. return this._pixelPerfect;
  25. }
  26. set pixelPerfect(value) {
  27. if (this._pixelPerfect === value) {
  28. return;
  29. }
  30. this._pixelPerfect = value;
  31. this._createEffects();
  32. }
  33. /**
  34. * Creates a new sprite Renderer
  35. * @param engine defines the engine the renderer works with
  36. * @param capacity defines the maximum allowed number of sprites
  37. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  38. * @param scene defines the hosting scene
  39. */
  40. constructor(engine, capacity, epsilon = 0.01, scene = null) {
  41. /**
  42. * Blend mode use to render the particle, it can be any of
  43. * the static undefined properties provided in this class.
  44. * Default value is 2
  45. */
  46. this.blendMode = 2;
  47. /**
  48. * Gets or sets a boolean indicating if alpha mode is automatically
  49. * reset.
  50. */
  51. this.autoResetAlpha = true;
  52. /**
  53. * Disables writing to the depth buffer when rendering the sprites.
  54. * It can be handy to disable depth writing when using textures without alpha channel
  55. * and setting some specific blend modes.
  56. */
  57. this.disableDepthWrite = false;
  58. /**
  59. * Gets or sets a boolean indicating if the manager must consider scene fog when rendering
  60. */
  61. this.fogEnabled = true;
  62. this._pixelPerfect = false;
  63. this._useVAO = false;
  64. this._useInstancing = false;
  65. this._vertexBuffers = {};
  66. this._capacity = capacity;
  67. this._epsilon = epsilon;
  68. this._engine = engine;
  69. this._useInstancing = engine.getCaps().instancedArrays && engine._features.supportSpriteInstancing;
  70. this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects;
  71. this._scene = scene;
  72. if (!this._useInstancing) {
  73. this._buildIndexBuffer();
  74. }
  75. // VBO
  76. // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a)
  77. // 16 when using instances
  78. this._vertexBufferSize = this._useInstancing ? 16 : 18;
  79. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  80. this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  81. const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing);
  82. const options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing);
  83. let offset = 6;
  84. let offsets;
  85. if (this._useInstancing) {
  86. const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);
  87. this._spriteBuffer = new Buffer(engine, spriteData, false, 2);
  88. offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2);
  89. }
  90. else {
  91. offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing);
  92. offset += 2;
  93. }
  94. const inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing);
  95. const cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing);
  96. const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing);
  97. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  98. this._vertexBuffers["options"] = options;
  99. this._vertexBuffers["offsets"] = offsets;
  100. this._vertexBuffers["inverts"] = inverts;
  101. this._vertexBuffers["cellInfo"] = cellInfo;
  102. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  103. this._createEffects();
  104. }
  105. _createEffects() {
  106. this._drawWrapperBase?.dispose();
  107. this._drawWrapperFog?.dispose();
  108. this._drawWrapperDepth?.dispose();
  109. this._drawWrapperFogDepth?.dispose();
  110. this._drawWrapperBase = new DrawWrapper(this._engine);
  111. this._drawWrapperFog = new DrawWrapper(this._engine);
  112. this._drawWrapperDepth = new DrawWrapper(this._engine, false);
  113. this._drawWrapperFogDepth = new DrawWrapper(this._engine, false);
  114. if (this._drawWrapperBase.drawContext) {
  115. this._drawWrapperBase.drawContext.useInstancing = this._useInstancing;
  116. }
  117. if (this._drawWrapperFog.drawContext) {
  118. this._drawWrapperFog.drawContext.useInstancing = this._useInstancing;
  119. }
  120. if (this._drawWrapperDepth.drawContext) {
  121. this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing;
  122. }
  123. if (this._drawWrapperFogDepth.drawContext) {
  124. this._drawWrapperFogDepth.drawContext.useInstancing = this._useInstancing;
  125. }
  126. const defines = this._pixelPerfect ? "#define PIXEL_PERFECT\n" : "";
  127. this._drawWrapperBase.effect = this._engine.createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], defines);
  128. this._drawWrapperDepth.effect = this._drawWrapperBase.effect;
  129. this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext;
  130. if (this._scene) {
  131. this._drawWrapperFog.effect = this._scene
  132. .getEngine()
  133. .createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], defines + "#define FOG");
  134. this._drawWrapperFogDepth.effect = this._drawWrapperFog.effect;
  135. this._drawWrapperFogDepth.materialContext = this._drawWrapperFog.materialContext;
  136. }
  137. }
  138. /**
  139. * Render all child sprites
  140. * @param sprites defines the list of sprites to render
  141. * @param deltaTime defines the time since last frame
  142. * @param viewMatrix defines the viewMatrix to use to render the sprites
  143. * @param projectionMatrix defines the projectionMatrix to use to render the sprites
  144. * @param customSpriteUpdate defines a custom function to update the sprites data before they render
  145. */
  146. render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) {
  147. if (!this.texture || !this.texture.isReady() || !sprites.length) {
  148. return;
  149. }
  150. let drawWrapper = this._drawWrapperBase;
  151. let drawWrapperDepth = this._drawWrapperDepth;
  152. let shouldRenderFog = false;
  153. if (this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0) {
  154. drawWrapper = this._drawWrapperFog;
  155. drawWrapperDepth = this._drawWrapperFogDepth;
  156. shouldRenderFog = true;
  157. }
  158. const effect = drawWrapper.effect;
  159. // Check
  160. if (!effect.isReady()) {
  161. return;
  162. }
  163. const engine = this._engine;
  164. const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem);
  165. const baseSize = this.texture.getBaseSize();
  166. // Sprites
  167. const max = Math.min(this._capacity, sprites.length);
  168. let offset = 0;
  169. let noSprite = true;
  170. for (let index = 0; index < max; index++) {
  171. const sprite = sprites[index];
  172. if (!sprite || !sprite.isVisible) {
  173. continue;
  174. }
  175. noSprite = false;
  176. sprite._animate(deltaTime);
  177. this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate);
  178. if (!this._useInstancing) {
  179. this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate);
  180. this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate);
  181. this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate);
  182. }
  183. }
  184. if (noSprite) {
  185. return;
  186. }
  187. this._buffer.update(this._vertexData);
  188. const culling = !!engine.depthCullingState.cull;
  189. const zOffset = engine.depthCullingState.zOffset;
  190. const zOffsetUnits = engine.depthCullingState.zOffsetUnits;
  191. engine.setState(culling, zOffset, false, false, undefined, undefined, zOffsetUnits);
  192. // Render
  193. engine.enableEffect(drawWrapper);
  194. effect.setTexture("diffuseSampler", this.texture);
  195. effect.setMatrix("view", viewMatrix);
  196. effect.setMatrix("projection", projectionMatrix);
  197. // Scene Info
  198. if (shouldRenderFog) {
  199. const scene = this._scene;
  200. // Fog
  201. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  202. effect.setColor3("vFogColor", scene.fogColor);
  203. }
  204. if (this._useVAO) {
  205. if (!this._vertexArrayObject) {
  206. this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);
  207. }
  208. engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);
  209. }
  210. else {
  211. // VBOs
  212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  213. }
  214. // Draw order
  215. engine.depthCullingState.depthFunc = engine.useReverseDepthBuffer ? 518 : 515;
  216. if (!this.disableDepthWrite) {
  217. effect.setBool("alphaTest", true);
  218. engine.setColorWrite(false);
  219. engine.enableEffect(drawWrapperDepth);
  220. if (this._useInstancing) {
  221. engine.drawArraysType(7, 0, 4, offset);
  222. }
  223. else {
  224. engine.drawElementsType(0, 0, (offset / 4) * 6);
  225. }
  226. engine.enableEffect(drawWrapper);
  227. engine.setColorWrite(true);
  228. effect.setBool("alphaTest", false);
  229. }
  230. engine.setAlphaMode(this.blendMode);
  231. if (this._useInstancing) {
  232. engine.drawArraysType(7, 0, 4, offset);
  233. }
  234. else {
  235. engine.drawElementsType(0, 0, (offset / 4) * 6);
  236. }
  237. if (this.autoResetAlpha) {
  238. engine.setAlphaMode(0);
  239. }
  240. // Restore Right Handed
  241. if (useRightHandedSystem) {
  242. this._scene.getEngine().setState(culling, zOffset, false, true, undefined, undefined, zOffsetUnits);
  243. }
  244. engine.unbindInstanceAttributes();
  245. }
  246. _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) {
  247. let arrayOffset = index * this._vertexBufferSize;
  248. if (offsetX === 0) {
  249. offsetX = this._epsilon;
  250. }
  251. else if (offsetX === 1) {
  252. offsetX = 1 - this._epsilon;
  253. }
  254. if (offsetY === 0) {
  255. offsetY = this._epsilon;
  256. }
  257. else if (offsetY === 1) {
  258. offsetY = 1 - this._epsilon;
  259. }
  260. if (customSpriteUpdate) {
  261. customSpriteUpdate(sprite, baseSize);
  262. }
  263. else {
  264. if (!sprite.cellIndex) {
  265. sprite.cellIndex = 0;
  266. }
  267. const rowSize = baseSize.width / this.cellWidth;
  268. const offset = (sprite.cellIndex / rowSize) >> 0;
  269. sprite._xOffset = ((sprite.cellIndex - offset * rowSize) * this.cellWidth) / baseSize.width;
  270. sprite._yOffset = (offset * this.cellHeight) / baseSize.height;
  271. sprite._xSize = this.cellWidth;
  272. sprite._ySize = this.cellHeight;
  273. }
  274. // Positions
  275. this._vertexData[arrayOffset] = sprite.position.x;
  276. this._vertexData[arrayOffset + 1] = sprite.position.y;
  277. this._vertexData[arrayOffset + 2] = sprite.position.z;
  278. this._vertexData[arrayOffset + 3] = sprite.angle;
  279. // Options
  280. this._vertexData[arrayOffset + 4] = sprite.width;
  281. this._vertexData[arrayOffset + 5] = sprite.height;
  282. if (!this._useInstancing) {
  283. this._vertexData[arrayOffset + 6] = offsetX;
  284. this._vertexData[arrayOffset + 7] = offsetY;
  285. }
  286. else {
  287. arrayOffset -= 2;
  288. }
  289. // Inverts according to Right Handed
  290. if (useRightHandedSystem) {
  291. this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;
  292. }
  293. else {
  294. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  295. }
  296. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  297. this._vertexData[arrayOffset + 10] = sprite._xOffset;
  298. this._vertexData[arrayOffset + 11] = sprite._yOffset;
  299. this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;
  300. this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;
  301. // Color
  302. this._vertexData[arrayOffset + 14] = sprite.color.r;
  303. this._vertexData[arrayOffset + 15] = sprite.color.g;
  304. this._vertexData[arrayOffset + 16] = sprite.color.b;
  305. this._vertexData[arrayOffset + 17] = sprite.color.a;
  306. }
  307. _buildIndexBuffer() {
  308. const indices = [];
  309. let index = 0;
  310. for (let count = 0; count < this._capacity; count++) {
  311. indices.push(index);
  312. indices.push(index + 1);
  313. indices.push(index + 2);
  314. indices.push(index);
  315. indices.push(index + 2);
  316. indices.push(index + 3);
  317. index += 4;
  318. }
  319. this._indexBuffer = this._engine.createIndexBuffer(indices);
  320. }
  321. /**
  322. * Rebuilds the renderer (after a context lost, for eg)
  323. */
  324. rebuild() {
  325. if (this._indexBuffer) {
  326. this._buildIndexBuffer();
  327. }
  328. if (this._useVAO) {
  329. this._vertexArrayObject = undefined;
  330. }
  331. this._buffer._rebuild();
  332. for (const key in this._vertexBuffers) {
  333. const vertexBuffer = this._vertexBuffers[key];
  334. vertexBuffer._rebuild();
  335. }
  336. this._spriteBuffer?._rebuild();
  337. }
  338. /**
  339. * Release associated resources
  340. */
  341. dispose() {
  342. if (this._buffer) {
  343. this._buffer.dispose();
  344. this._buffer = null;
  345. }
  346. if (this._spriteBuffer) {
  347. this._spriteBuffer.dispose();
  348. this._spriteBuffer = null;
  349. }
  350. if (this._indexBuffer) {
  351. this._engine._releaseBuffer(this._indexBuffer);
  352. this._indexBuffer = null;
  353. }
  354. if (this._vertexArrayObject) {
  355. this._engine.releaseVertexArrayObject(this._vertexArrayObject);
  356. this._vertexArrayObject = null;
  357. }
  358. if (this.texture) {
  359. this.texture.dispose();
  360. this.texture = null;
  361. }
  362. this._drawWrapperBase.dispose();
  363. this._drawWrapperFog.dispose();
  364. this._drawWrapperDepth.dispose();
  365. this._drawWrapperFogDepth.dispose();
  366. }
  367. }
  368. //# sourceMappingURL=spriteRenderer.js.map