spriteManager.ts 36 KB

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