spriteManager.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. import { IDisposable, Scene } from "../scene";
  2. import { Nullable } from "../types";
  3. import { Observable, Observer } from "../Misc/observable";
  4. import { Buffer } from "../Meshes/buffer";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { Vector3, TmpVectors } from "../Maths/math.vector";
  7. import { Sprite } from "./sprite";
  8. import { SpriteSceneComponent } from "./spriteSceneComponent";
  9. import { PickingInfo } from "../Collisions/pickingInfo";
  10. import { Camera } from "../Cameras/camera";
  11. import { Texture } from "../Materials/Textures/texture";
  12. import { Effect } from "../Materials/effect";
  13. import { Material } from "../Materials/material";
  14. import { SceneComponentConstants } from "../sceneComponent";
  15. import { Constants } from "../Engines/constants";
  16. import { Logger } from "../Misc/logger";
  17. import "../Shaders/sprites.fragment";
  18. import "../Shaders/sprites.vertex";
  19. import { DataBuffer } from '../Meshes/dataBuffer';
  20. import { Engine } from '../Engines/engine';
  21. declare type Ray = import("../Culling/ray").Ray;
  22. /**
  23. * Defines the minimum interface to fullfil in order to be a sprite manager.
  24. */
  25. export interface ISpriteManager extends IDisposable {
  26. /**
  27. * Gets manager's name
  28. */
  29. name: string;
  30. /**
  31. * Restricts the camera to viewing objects with the same layerMask.
  32. * A camera with a layerMask of 1 will render spriteManager.layerMask & camera.layerMask!== 0
  33. */
  34. layerMask: number;
  35. /**
  36. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  37. */
  38. isPickable: boolean;
  39. /**
  40. * Gets the hosting scene
  41. */
  42. scene: Scene;
  43. /**
  44. * Specifies the rendering group id for this mesh (0 by default)
  45. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  46. */
  47. renderingGroupId: number;
  48. /**
  49. * Defines the list of sprites managed by the manager.
  50. */
  51. sprites: Array<Sprite>;
  52. /**
  53. * Gets or sets the spritesheet texture
  54. */
  55. texture: Texture;
  56. /** Defines the default width of a cell in the spritesheet */
  57. cellWidth: number;
  58. /** Defines the default height of a cell in the spritesheet */
  59. cellHeight: number;
  60. /**
  61. * Tests the intersection of a sprite with a specific ray.
  62. * @param ray The ray we are sending to test the collision
  63. * @param camera The camera space we are sending rays in
  64. * @param predicate A predicate allowing excluding sprites from the list of object to test
  65. * @param fastCheck defines if the first intersection will be used (and not the closest)
  66. * @returns picking info or null.
  67. */
  68. intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable<PickingInfo>;
  69. /**
  70. * Intersects the sprites with a ray
  71. * @param ray defines the ray to intersect with
  72. * @param camera defines the current active camera
  73. * @param predicate defines a predicate used to select candidate sprites
  74. * @returns null if no hit or a PickingInfo array
  75. */
  76. multiIntersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean): Nullable<PickingInfo[]>;
  77. /**
  78. * Renders the list of sprites on screen.
  79. */
  80. render(): void;
  81. }
  82. /**
  83. * Class used to manage multiple sprites on the same spritesheet
  84. * @see http://doc.babylonjs.com/babylon101/sprites
  85. */
  86. export class SpriteManager implements ISpriteManager {
  87. /** Gets the list of sprites */
  88. public sprites = new Array<Sprite>();
  89. /** Gets or sets the rendering group id (0 by default) */
  90. public renderingGroupId = 0;
  91. /** Gets or sets camera layer mask */
  92. public layerMask: number = 0x0FFFFFFF;
  93. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  94. public fogEnabled = true;
  95. /** Gets or sets a boolean indicating if the sprites are pickable */
  96. public isPickable = false;
  97. /** Defines the default width of a cell in the spritesheet */
  98. public cellWidth: number;
  99. /** Defines the default height of a cell in the spritesheet */
  100. public cellHeight: number;
  101. /** Associative array from JSON sprite data file */
  102. private _cellData: any;
  103. /** Array of sprite names from JSON sprite data file */
  104. private _spriteMap: Array<string>;
  105. /** True when packed cell data from JSON file is ready*/
  106. private _packedAndReady: boolean = false;
  107. private _textureContent: Nullable<Uint8Array>;
  108. /**
  109. * An event triggered when the manager is disposed.
  110. */
  111. public onDisposeObservable = new Observable<SpriteManager>();
  112. private _onDisposeObserver: Nullable<Observer<SpriteManager>>;
  113. /**
  114. * Callback called when the manager is disposed
  115. */
  116. public set onDispose(callback: () => void) {
  117. if (this._onDisposeObserver) {
  118. this.onDisposeObservable.remove(this._onDisposeObserver);
  119. }
  120. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  121. }
  122. private _capacity: number;
  123. private _fromPacked: boolean;
  124. private _spriteTexture: Texture;
  125. private _epsilon: number;
  126. private _scene: Scene;
  127. private _vertexData: Float32Array;
  128. private _buffer: Buffer;
  129. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  130. private _indexBuffer: DataBuffer;
  131. private _effectBase: Effect;
  132. private _effectFog: Effect;
  133. /**
  134. * Gets or sets the unique id of the sprite
  135. */
  136. public uniqueId: number;
  137. /**
  138. * Gets the array of sprites
  139. */
  140. public get children() {
  141. return this.sprites;
  142. }
  143. /**
  144. * Gets the hosting scene
  145. */
  146. public get scene() {
  147. return this._scene;
  148. }
  149. /**
  150. * Gets or sets the capacity of the manager
  151. */
  152. public get capacity() {
  153. return this._capacity;
  154. }
  155. public set capacity(value: number) {
  156. this._capacity = value;
  157. }
  158. /**
  159. * Gets or sets the spritesheet texture
  160. */
  161. public get texture(): Texture {
  162. return this._spriteTexture;
  163. }
  164. public set texture(value: Texture) {
  165. this._spriteTexture = value;
  166. this._textureContent = null;
  167. }
  168. private _blendMode = Constants.ALPHA_COMBINE;
  169. /**
  170. * Blend mode use to render the particle, it can be any of
  171. * the static Constants.ALPHA_x properties provided in this class.
  172. * Default value is Constants.ALPHA_COMBINE
  173. */
  174. public get blendMode() { return this._blendMode; }
  175. public set blendMode(blendMode: number) {
  176. this._blendMode = blendMode;
  177. }
  178. /** Disables writing to the depth buffer when rendering the sprites.
  179. * It can be handy to disable depth writing when using textures without alpha channel
  180. * and setting some specific blend modes.
  181. */
  182. public disableDepthWrite: boolean = false;
  183. /**
  184. * Creates a new sprite manager
  185. * @param name defines the manager's name
  186. * @param imgUrl defines the sprite sheet url
  187. * @param capacity defines the maximum allowed number of sprites
  188. * @param cellSize defines the size of a sprite cell
  189. * @param scene defines the hosting scene
  190. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  191. * @param samplingMode defines the smapling mode to use with spritesheet
  192. * @param fromPacked set to false; do not alter
  193. * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter
  194. */
  195. constructor(
  196. /** defines the manager's name */
  197. public name: string,
  198. imgUrl: string, capacity: number, cellSize: any, scene: Scene, epsilon: number = 0.01, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, fromPacked: boolean = false, spriteJSON: any | null = null) {
  199. if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) {
  200. scene._addComponent(new SpriteSceneComponent(scene));
  201. }
  202. this._capacity = capacity;
  203. this._fromPacked = fromPacked;
  204. this._spriteTexture = new Texture(imgUrl, scene, true, false, samplingMode);
  205. this._spriteTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  206. this._spriteTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  207. if (cellSize.width && cellSize.height) {
  208. this.cellWidth = cellSize.width;
  209. this.cellHeight = cellSize.height;
  210. } else if (cellSize !== undefined) {
  211. this.cellWidth = cellSize;
  212. this.cellHeight = cellSize;
  213. } else {
  214. return;
  215. }
  216. this._epsilon = epsilon;
  217. this._scene = scene || Engine.LastCreatedScene;
  218. this._scene.spriteManagers.push(this);
  219. this.uniqueId = this.scene.getUniqueId();
  220. var indices = [];
  221. var index = 0;
  222. for (var count = 0; count < capacity; count++) {
  223. indices.push(index);
  224. indices.push(index + 1);
  225. indices.push(index + 2);
  226. indices.push(index);
  227. indices.push(index + 2);
  228. indices.push(index + 3);
  229. index += 4;
  230. }
  231. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  232. // VBO
  233. // 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)
  234. this._vertexData = new Float32Array(capacity * 18 * 4);
  235. this._buffer = new Buffer(scene.getEngine(), this._vertexData, true, 18);
  236. var positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4);
  237. var options = this._buffer.createVertexBuffer("options", 4, 4);
  238. var inverts = this._buffer.createVertexBuffer("inverts", 8, 2);
  239. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 10, 4);
  240. var colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, 14, 4);
  241. this._vertexBuffers[VertexBuffer.PositionKind] = positions;
  242. this._vertexBuffers["options"] = options;
  243. this._vertexBuffers["inverts"] = inverts;
  244. this._vertexBuffers["cellInfo"] = cellInfo;
  245. this._vertexBuffers[VertexBuffer.ColorKind] = colors;
  246. // Effects
  247. this._effectBase = this._scene.getEngine().createEffect("sprites",
  248. [VertexBuffer.PositionKind, "options", "inverts", "cellInfo", VertexBuffer.ColorKind],
  249. ["view", "projection", "textureInfos", "alphaTest"],
  250. ["diffuseSampler"], "");
  251. this._effectFog = this._scene.getEngine().createEffect("sprites",
  252. [VertexBuffer.PositionKind, "options", "inverts", "cellInfo", VertexBuffer.ColorKind],
  253. ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"],
  254. ["diffuseSampler"], "#define FOG");
  255. if (this._fromPacked) {
  256. this._makePacked(imgUrl, spriteJSON);
  257. }
  258. }
  259. /**
  260. * Returns the string "SpriteManager"
  261. * @returns "SpriteManager"
  262. */
  263. public getClassName(): string {
  264. return "SpriteManager";
  265. }
  266. private _makePacked(imgUrl: string, spriteJSON: any) {
  267. if (spriteJSON !== null) {
  268. try {
  269. //Get the JSON and Check its stucture. If its an array parse it if its a JSON sring etc...
  270. let celldata: any;
  271. if (typeof spriteJSON === "string") {
  272. celldata = JSON.parse(spriteJSON);
  273. }else {
  274. celldata = spriteJSON;
  275. }
  276. if (celldata.frames.length) {
  277. let frametemp: any = {};
  278. for (let i = 0; i < celldata.frames.length; i++) {
  279. let _f = celldata.frames[i];
  280. if (typeof (Object.keys(_f))[0] !== "string") {
  281. throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");
  282. }
  283. let name: string = _f[(Object.keys(_f))[0]];
  284. frametemp[name] = _f;
  285. }
  286. celldata.frames = frametemp;
  287. }
  288. let spritemap = (<string[]>(<any>Reflect).ownKeys(celldata.frames));
  289. this._spriteMap = spritemap;
  290. this._packedAndReady = true;
  291. this._cellData = celldata.frames;
  292. }
  293. catch (e) {
  294. this._fromPacked = false;
  295. this._packedAndReady = false;
  296. throw new Error("Invalid JSON from string. Spritesheet managed with constant cell size.");
  297. }
  298. }
  299. else {
  300. let re = /\./g;
  301. let li: number;
  302. do {
  303. li = re.lastIndex;
  304. re.test(imgUrl);
  305. } while (re.lastIndex > 0);
  306. let jsonUrl = imgUrl.substring(0, li - 1) + ".json";
  307. let xmlhttp = new XMLHttpRequest();
  308. xmlhttp.open("GET", jsonUrl, true);
  309. xmlhttp.onerror = () => {
  310. Logger.Error("JSON ERROR: Unable to load JSON file.");
  311. this._fromPacked = false;
  312. this._packedAndReady = false;
  313. };
  314. xmlhttp.onload = () => {
  315. try {
  316. let celldata = JSON.parse(xmlhttp.response);
  317. let spritemap = (<string[]>(<any>Reflect).ownKeys(celldata.frames));
  318. this._spriteMap = spritemap;
  319. this._packedAndReady = true;
  320. this._cellData = celldata.frames;
  321. }
  322. catch (e) {
  323. this._fromPacked = false;
  324. this._packedAndReady = false;
  325. throw new Error("Invalid JSON format. Please check documentation for format specifications.");
  326. }
  327. };
  328. xmlhttp.send();
  329. }
  330. }
  331. private _appendSpriteVertex(index: number, sprite: Sprite, offsetX: number, offsetY: number, baseSize: any): void {
  332. var arrayOffset = index * 18;
  333. if (offsetX === 0) {
  334. offsetX = this._epsilon;
  335. }
  336. else if (offsetX === 1) {
  337. offsetX = 1 - this._epsilon;
  338. }
  339. if (offsetY === 0) {
  340. offsetY = this._epsilon;
  341. }
  342. else if (offsetY === 1) {
  343. offsetY = 1 - this._epsilon;
  344. }
  345. // Positions
  346. this._vertexData[arrayOffset] = sprite.position.x;
  347. this._vertexData[arrayOffset + 1] = sprite.position.y;
  348. this._vertexData[arrayOffset + 2] = sprite.position.z;
  349. this._vertexData[arrayOffset + 3] = sprite.angle;
  350. // Options
  351. this._vertexData[arrayOffset + 4] = sprite.width;
  352. this._vertexData[arrayOffset + 5] = sprite.height;
  353. this._vertexData[arrayOffset + 6] = offsetX;
  354. this._vertexData[arrayOffset + 7] = offsetY;
  355. // Inverts according to Right Handed
  356. if (this._scene.useRightHandedSystem) {
  357. this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;
  358. }
  359. else {
  360. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  361. }
  362. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  363. // CellIfo
  364. if (this._packedAndReady) {
  365. if (!sprite.cellRef) {
  366. sprite.cellIndex = 0;
  367. }
  368. let num = sprite.cellIndex;
  369. if (typeof (num) === "number" && isFinite(num) && Math.floor(num) === num) {
  370. sprite.cellRef = this._spriteMap[sprite.cellIndex];
  371. }
  372. sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;
  373. sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;
  374. sprite._xSize = this._cellData[sprite.cellRef].frame.w;
  375. sprite._ySize = this._cellData[sprite.cellRef].frame.h;
  376. this._vertexData[arrayOffset + 10] = sprite._xOffset;
  377. this._vertexData[arrayOffset + 11] = sprite._yOffset;
  378. this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;
  379. this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;
  380. }
  381. else {
  382. if (!sprite.cellIndex) {
  383. sprite.cellIndex = 0;
  384. }
  385. var rowSize = baseSize.width / this.cellWidth;
  386. var offset = (sprite.cellIndex / rowSize) >> 0;
  387. sprite._xOffset = (sprite.cellIndex - offset * rowSize) * this.cellWidth / baseSize.width;
  388. sprite._yOffset = offset * this.cellHeight / baseSize.height;
  389. sprite._xSize = this.cellWidth;
  390. sprite._ySize = this.cellHeight;
  391. this._vertexData[arrayOffset + 10] = sprite._xOffset;
  392. this._vertexData[arrayOffset + 11] = sprite._yOffset;
  393. this._vertexData[arrayOffset + 12] = this.cellWidth / baseSize.width;
  394. this._vertexData[arrayOffset + 13] = this.cellHeight / baseSize.height;
  395. }
  396. // Color
  397. this._vertexData[arrayOffset + 14] = sprite.color.r;
  398. this._vertexData[arrayOffset + 15] = sprite.color.g;
  399. this._vertexData[arrayOffset + 16] = sprite.color.b;
  400. this._vertexData[arrayOffset + 17] = sprite.color.a;
  401. }
  402. private _checkTextureAlpha(sprite: Sprite, ray: Ray, distance: number, min: Vector3, max: Vector3) {
  403. if (!sprite.useAlphaForPicking || !this._spriteTexture) {
  404. return true;
  405. }
  406. let textureSize = this._spriteTexture.getSize();
  407. if (!this._textureContent) {
  408. this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4);
  409. this._spriteTexture.readPixels(0, 0, this._textureContent);
  410. }
  411. let contactPoint = TmpVectors.Vector3[0];
  412. contactPoint.copyFrom(ray.direction);
  413. contactPoint.normalize();
  414. contactPoint.scaleInPlace(distance);
  415. contactPoint.addInPlace(ray.origin);
  416. let contactPointU = ((contactPoint.x - min.x) / (max.x - min.x)) - 0.5;
  417. let contactPointV = (1.0 - (contactPoint.y - min.y) / (max.y - min.y)) - 0.5;
  418. // Rotate
  419. let angle = sprite.angle;
  420. let rotatedU = 0.5 + (contactPointU * Math.cos(angle) - contactPointV * Math.sin(angle));
  421. let rotatedV = 0.5 + (contactPointU * Math.sin(angle) + contactPointV * Math.cos(angle));
  422. let u = (sprite._xOffset * textureSize.width + rotatedU * sprite._xSize) | 0;
  423. let v = (sprite._yOffset * textureSize.height + rotatedV * sprite._ySize) | 0;
  424. let alpha = this._textureContent![(u + v * textureSize.width) * 4 + 3];
  425. return (alpha > 0.5);
  426. }
  427. /**
  428. * Intersects the sprites with a ray
  429. * @param ray defines the ray to intersect with
  430. * @param camera defines the current active camera
  431. * @param predicate defines a predicate used to select candidate sprites
  432. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  433. * @returns null if no hit or a PickingInfo
  434. */
  435. public intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): Nullable<PickingInfo> {
  436. var count = Math.min(this._capacity, this.sprites.length);
  437. var min = Vector3.Zero();
  438. var max = Vector3.Zero();
  439. var distance = Number.MAX_VALUE;
  440. var currentSprite: Nullable<Sprite> = null;
  441. var pickedPoint = TmpVectors.Vector3[0];
  442. var cameraSpacePosition = TmpVectors.Vector3[1];
  443. var cameraView = camera.getViewMatrix();
  444. for (var index = 0; index < count; index++) {
  445. var sprite = this.sprites[index];
  446. if (!sprite) {
  447. continue;
  448. }
  449. if (predicate) {
  450. if (!predicate(sprite)) {
  451. continue;
  452. }
  453. } else if (!sprite.isPickable) {
  454. continue;
  455. }
  456. Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  457. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  458. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  459. if (ray.intersectsBoxMinMax(min, max)) {
  460. var currentDistance = Vector3.Distance(cameraSpacePosition, ray.origin);
  461. if (distance > currentDistance) {
  462. if (!this._checkTextureAlpha(sprite, ray, currentDistance, min, max)) {
  463. continue;
  464. }
  465. distance = currentDistance;
  466. currentSprite = sprite;
  467. if (fastCheck) {
  468. break;
  469. }
  470. }
  471. }
  472. }
  473. if (currentSprite) {
  474. var result = new PickingInfo();
  475. cameraView.invertToRef(TmpVectors.Matrix[0]);
  476. result.hit = true;
  477. result.pickedSprite = currentSprite;
  478. result.distance = distance;
  479. // Get picked point
  480. let direction = TmpVectors.Vector3[2];
  481. direction.copyFrom(ray.direction);
  482. direction.normalize();
  483. direction.scaleInPlace(distance);
  484. ray.origin.addToRef(direction, pickedPoint);
  485. result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);
  486. return result;
  487. }
  488. return null;
  489. }
  490. /**
  491. * Intersects the sprites with a ray
  492. * @param ray defines the ray to intersect with
  493. * @param camera defines the current active camera
  494. * @param predicate defines a predicate used to select candidate sprites
  495. * @returns null if no hit or a PickingInfo array
  496. */
  497. public multiIntersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean): Nullable<PickingInfo[]> {
  498. var count = Math.min(this._capacity, this.sprites.length);
  499. var min = Vector3.Zero();
  500. var max = Vector3.Zero();
  501. var distance: number;
  502. var results: Nullable<PickingInfo[]> = [];
  503. var pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0);
  504. var cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0);
  505. var cameraView = camera.getViewMatrix();
  506. for (var index = 0; index < count; index++) {
  507. var sprite = this.sprites[index];
  508. if (!sprite) {
  509. continue;
  510. }
  511. if (predicate) {
  512. if (!predicate(sprite)) {
  513. continue;
  514. }
  515. } else if (!sprite.isPickable) {
  516. continue;
  517. }
  518. Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  519. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  520. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  521. if (ray.intersectsBoxMinMax(min, max)) {
  522. distance = Vector3.Distance(cameraSpacePosition, ray.origin);
  523. if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) {
  524. continue;
  525. }
  526. var result = new PickingInfo();
  527. results.push(result);
  528. cameraView.invertToRef(TmpVectors.Matrix[0]);
  529. result.hit = true;
  530. result.pickedSprite = sprite;
  531. result.distance = distance;
  532. // Get picked point
  533. let direction = TmpVectors.Vector3[2];
  534. direction.copyFrom(ray.direction);
  535. direction.normalize();
  536. direction.scaleInPlace(distance);
  537. ray.origin.addToRef(direction, pickedPoint);
  538. result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);
  539. }
  540. }
  541. return results;
  542. }
  543. /**
  544. * Render all child sprites
  545. */
  546. public render(): void {
  547. // Check
  548. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture
  549. || !this._spriteTexture.isReady() || !this.sprites.length) {
  550. return;
  551. }
  552. if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) {
  553. return;
  554. }
  555. var engine = this._scene.getEngine();
  556. var baseSize = this._spriteTexture.getBaseSize();
  557. // Sprites
  558. var deltaTime = engine.getDeltaTime();
  559. var max = Math.min(this._capacity, this.sprites.length);
  560. var offset = 0;
  561. let noSprite = true;
  562. for (var index = 0; index < max; index++) {
  563. var sprite = this.sprites[index];
  564. if (!sprite || !sprite.isVisible) {
  565. continue;
  566. }
  567. noSprite = false;
  568. sprite._animate(deltaTime);
  569. this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize);
  570. this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize);
  571. this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize);
  572. this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize);
  573. }
  574. if (noSprite) {
  575. return;
  576. }
  577. this._buffer.update(this._vertexData);
  578. // Render
  579. var effect = this._effectBase;
  580. if (this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  581. effect = this._effectFog;
  582. }
  583. engine.enableEffect(effect);
  584. var viewMatrix = this._scene.getViewMatrix();
  585. effect.setTexture("diffuseSampler", this._spriteTexture);
  586. effect.setMatrix("view", viewMatrix);
  587. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  588. // Fog
  589. if (this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE && this.fogEnabled) {
  590. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  591. effect.setColor3("vFogColor", this._scene.fogColor);
  592. }
  593. // VBOs
  594. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  595. // Handle Right Handed
  596. const culling = engine.depthCullingState.cull || true;
  597. const zOffset = engine.depthCullingState.zOffset;
  598. if (this._scene.useRightHandedSystem) {
  599. engine.setState(culling, zOffset, false, false);
  600. }
  601. // Draw order
  602. engine.setDepthFunctionToLessOrEqual();
  603. if (!this.disableDepthWrite) {
  604. effect.setBool("alphaTest", true);
  605. engine.setColorWrite(false);
  606. engine.drawElementsType(Material.TriangleFillMode, 0, (offset / 4) * 6);
  607. engine.setColorWrite(true);
  608. effect.setBool("alphaTest", false);
  609. }
  610. engine.setAlphaMode(this._blendMode);
  611. engine.drawElementsType(Material.TriangleFillMode, 0, (offset / 4) * 6);
  612. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  613. // Restore Right Handed
  614. if (this._scene.useRightHandedSystem) {
  615. engine.setState(culling, zOffset, false, true);
  616. }
  617. }
  618. /**
  619. * Release associated resources
  620. */
  621. public dispose(): void {
  622. if (this._buffer) {
  623. this._buffer.dispose();
  624. (<any>this._buffer) = null;
  625. }
  626. if (this._indexBuffer) {
  627. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  628. (<any>this._indexBuffer) = null;
  629. }
  630. if (this._spriteTexture) {
  631. this._spriteTexture.dispose();
  632. (<any>this._spriteTexture) = null;
  633. }
  634. this._textureContent = null;
  635. // Remove from scene
  636. var index = this._scene.spriteManagers.indexOf(this);
  637. this._scene.spriteManagers.splice(index, 1);
  638. // Callback
  639. this.onDisposeObservable.notifyObservers(this);
  640. this.onDisposeObservable.clear();
  641. }
  642. }