babylon.scene.ts 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. class ClickInfo {
  6. private _singleClick = false;
  7. private _doubleClick = false;
  8. private _hasSwiped = false;
  9. private _ignore = false;
  10. public get singleClick(): boolean {
  11. return this._singleClick;
  12. }
  13. public get doubleClick(): boolean {
  14. return this._doubleClick;
  15. }
  16. public get hasSwiped(): boolean{
  17. return this._hasSwiped;
  18. }
  19. public get ignore(): boolean{
  20. return this._ignore;
  21. }
  22. public set singleClick(b: boolean) {
  23. this._singleClick = b;
  24. }
  25. public set doubleClick(b: boolean) {
  26. this._doubleClick = b;
  27. }
  28. public set hasSwiped(b: boolean) {
  29. this._hasSwiped = b;
  30. }
  31. public set ignore(b: boolean) {
  32. this._ignore = b;
  33. }
  34. }
  35. export class PointerEventTypes {
  36. static _POINTERDOWN = 0x01;
  37. static _POINTERUP = 0x02;
  38. static _POINTERMOVE = 0x04;
  39. static _POINTERWHEEL = 0x08;
  40. static _POINTERPICK = 0x10;
  41. static _POINTERTAP = 0x20;
  42. static _POINTERDOUBLETAP = 0x40;
  43. public static get POINTERDOWN(): number {
  44. return PointerEventTypes._POINTERDOWN;
  45. }
  46. public static get POINTERUP(): number {
  47. return PointerEventTypes._POINTERUP;
  48. }
  49. public static get POINTERMOVE(): number {
  50. return PointerEventTypes._POINTERMOVE;
  51. }
  52. public static get POINTERWHEEL(): number {
  53. return PointerEventTypes._POINTERWHEEL;
  54. }
  55. public static get POINTERPICK(): number {
  56. return PointerEventTypes._POINTERPICK;
  57. }
  58. public static get POINTERTAP(): number {
  59. return PointerEventTypes._POINTERTAP;
  60. }
  61. public static get POINTERDOUBLETAP(): number {
  62. return PointerEventTypes._POINTERDOUBLETAP;
  63. }
  64. }
  65. export class PointerInfoBase {
  66. constructor(public type: number, public event: PointerEvent | MouseWheelEvent) {
  67. }
  68. }
  69. /**
  70. * This class is used to store pointer related info for the onPrePointerObservable event.
  71. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  72. */
  73. export class PointerInfoPre extends PointerInfoBase {
  74. constructor(type: number, event: PointerEvent | MouseWheelEvent, localX, localY) {
  75. super(type, event);
  76. this.skipOnPointerObservable = false;
  77. this.localPosition = new Vector2(localX, localY);
  78. }
  79. public localPosition: Vector2;
  80. public skipOnPointerObservable: boolean;
  81. }
  82. /**
  83. * This type contains all the data related to a pointer event in Babylon.js.
  84. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  85. */
  86. export class PointerInfo extends PointerInfoBase {
  87. constructor(type: number, event: PointerEvent | MouseWheelEvent, public pickInfo: PickingInfo) {
  88. super(type, event);
  89. }
  90. }
  91. /**
  92. * This class is used by the onRenderingGroupObservable
  93. */
  94. export class RenderingGroupInfo {
  95. /**
  96. * The Scene that being rendered
  97. */
  98. scene: Scene;
  99. /**
  100. * The camera currently used for the rendering pass
  101. */
  102. camera: Camera;
  103. /**
  104. * The ID of the renderingGroup being processed
  105. */
  106. renderingGroupId: number;
  107. /**
  108. * The rendering stage, can be either STAGE_PRECLEAR, STAGE_PREOPAQUE, STAGE_PRETRANSPARENT, STAGE_POSTTRANSPARENT
  109. */
  110. renderStage: number;
  111. /**
  112. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  113. * This stage will be fired no matter what
  114. */
  115. static STAGE_PRECLEAR = 1;
  116. /**
  117. * Called before opaque object are rendered.
  118. * This stage will be fired only if there's 3D Opaque content to render
  119. */
  120. static STAGE_PREOPAQUE = 2;
  121. /**
  122. * Called after the opaque objects are rendered and before the transparent ones
  123. * This stage will be fired only if there's 3D transparent content to render
  124. */
  125. static STAGE_PRETRANSPARENT = 3;
  126. /**
  127. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  128. * This stage will be fired no matter what
  129. */
  130. static STAGE_POSTTRANSPARENT = 4;
  131. }
  132. /**
  133. * Represents a scene to be rendered by the engine.
  134. * @see http://doc.babylonjs.com/page.php?p=21911
  135. */
  136. export class Scene implements IAnimatable {
  137. // Statics
  138. private static _FOGMODE_NONE = 0;
  139. private static _FOGMODE_EXP = 1;
  140. private static _FOGMODE_EXP2 = 2;
  141. private static _FOGMODE_LINEAR = 3;
  142. public static MinDeltaTime = 1.0;
  143. public static MaxDeltaTime = 1000.0;
  144. public static get FOGMODE_NONE(): number {
  145. return Scene._FOGMODE_NONE;
  146. }
  147. public static get FOGMODE_EXP(): number {
  148. return Scene._FOGMODE_EXP;
  149. }
  150. public static get FOGMODE_EXP2(): number {
  151. return Scene._FOGMODE_EXP2;
  152. }
  153. public static get FOGMODE_LINEAR(): number {
  154. return Scene._FOGMODE_LINEAR;
  155. }
  156. // Members
  157. public autoClear = true;
  158. public clearColor: Color4 = new Color4(0.2, 0.2, 0.3, 1.0);
  159. public ambientColor = new Color3(0, 0, 0);
  160. public forceWireframe = false;
  161. private _forcePointsCloud = false;
  162. public set forcePointsCloud(value : boolean) {
  163. if (this._forcePointsCloud === value) {
  164. return;
  165. }
  166. this._forcePointsCloud = value;
  167. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  168. }
  169. public get forcePointsCloud(): boolean {
  170. return this._forcePointsCloud;
  171. }
  172. public forceShowBoundingBoxes = false;
  173. public clipPlane: Plane;
  174. public animationsEnabled = true;
  175. public constantlyUpdateMeshUnderPointer = false;
  176. public useRightHandedSystem = false;
  177. public hoverCursor = "pointer";
  178. // Metadata
  179. public metadata: any = null;
  180. // Events
  181. /**
  182. * An event triggered when the scene is disposed.
  183. * @type {BABYLON.Observable}
  184. */
  185. public onDisposeObservable = new Observable<Scene>();
  186. private _onDisposeObserver: Observer<Scene>;
  187. public set onDispose(callback: () => void) {
  188. if (this._onDisposeObserver) {
  189. this.onDisposeObservable.remove(this._onDisposeObserver);
  190. }
  191. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  192. }
  193. /**
  194. * An event triggered before rendering the scene
  195. * @type {BABYLON.Observable}
  196. */
  197. public onBeforeRenderObservable = new Observable<Scene>();
  198. private _onBeforeRenderObserver: Observer<Scene>;
  199. public set beforeRender(callback: () => void) {
  200. if (this._onBeforeRenderObserver) {
  201. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  202. }
  203. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  204. }
  205. /**
  206. * An event triggered after rendering the scene
  207. * @type {BABYLON.Observable}
  208. */
  209. public onAfterRenderObservable = new Observable<Scene>();
  210. private _onAfterRenderObserver: Observer<Scene>;
  211. public set afterRender(callback: () => void) {
  212. if (this._onAfterRenderObserver) {
  213. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  214. }
  215. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  216. }
  217. /**
  218. * An event triggered when the scene is ready
  219. * @type {BABYLON.Observable}
  220. */
  221. public onReadyObservable = new Observable<Scene>();
  222. /**
  223. * An event triggered before rendering a camera
  224. * @type {BABYLON.Observable}
  225. */
  226. public onBeforeCameraRenderObservable = new Observable<Camera>();
  227. private _onBeforeCameraRenderObserver: Observer<Camera>;
  228. public set beforeCameraRender(callback: () => void) {
  229. if (this._onBeforeCameraRenderObserver) {
  230. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  231. }
  232. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  233. }
  234. /**
  235. * An event triggered after rendering a camera
  236. * @type {BABYLON.Observable}
  237. */
  238. public onAfterCameraRenderObservable = new Observable<Camera>();
  239. private _onAfterCameraRenderObserver: Observer<Camera>;
  240. public set afterCameraRender(callback: () => void) {
  241. if (this._onAfterCameraRenderObserver) {
  242. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  243. }
  244. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  245. }
  246. /**
  247. * An event triggered when a camera is created
  248. * @type {BABYLON.Observable}
  249. */
  250. public onNewCameraAddedObservable = new Observable<Camera>();
  251. /**
  252. * An event triggered when a camera is removed
  253. * @type {BABYLON.Observable}
  254. */
  255. public onCameraRemovedObservable = new Observable<Camera>();
  256. /**
  257. * An event triggered when a light is created
  258. * @type {BABYLON.Observable}
  259. */
  260. public onNewLightAddedObservable = new Observable<Light>();
  261. /**
  262. * An event triggered when a light is removed
  263. * @type {BABYLON.Observable}
  264. */
  265. public onLightRemovedObservable = new Observable<Light>();
  266. /**
  267. * An event triggered when a geometry is created
  268. * @type {BABYLON.Observable}
  269. */
  270. public onNewGeometryAddedObservable = new Observable<Geometry>();
  271. /**
  272. * An event triggered when a geometry is removed
  273. * @type {BABYLON.Observable}
  274. */
  275. public onGeometryRemovedObservable = new Observable<Geometry>();
  276. /**
  277. * An event triggered when a mesh is created
  278. * @type {BABYLON.Observable}
  279. */
  280. public onNewMeshAddedObservable = new Observable<AbstractMesh>();
  281. /**
  282. * An event triggered when a mesh is removed
  283. * @type {BABYLON.Observable}
  284. */
  285. public onMeshRemovedObservable = new Observable<AbstractMesh>();
  286. /**
  287. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  288. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  289. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  290. */
  291. public onRenderingGroupObservable = new Observable<RenderingGroupInfo>();
  292. // Animations
  293. public animations: Animation[] = [];
  294. // Pointers
  295. public pointerDownPredicate: (Mesh: AbstractMesh) => boolean;
  296. public pointerUpPredicate: (Mesh: AbstractMesh) => boolean;
  297. public pointerMovePredicate: (Mesh: AbstractMesh) => boolean;
  298. private _onPointerMove: (evt: PointerEvent) => void;
  299. private _onPointerDown: (evt: PointerEvent) => void;
  300. private _onPointerUp: (evt: PointerEvent) => void;
  301. public onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  302. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  303. public onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  304. public onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  305. /**
  306. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  307. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  308. */
  309. public onPrePointerObservable = new Observable<PointerInfoPre>();
  310. /**
  311. * Observable event triggered each time an input event is received from the rendering canvas
  312. */
  313. public onPointerObservable = new Observable<PointerInfo>();
  314. public get unTranslatedPointer(): Vector2 {
  315. return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  316. }
  317. public static DragMovementThreshold = 10; // in pixels
  318. public static LongPressDelay = 500; // in milliseconds
  319. public static DoubleClickDelay = 300; // in milliseconds
  320. public static ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  321. private _initClickEvent: (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void) => void;
  322. private _initActionManager: (act: ActionManager, clickInfo: ClickInfo) => ActionManager;
  323. private _delayedSimpleClick: (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void) => void;
  324. private _delayedSimpleClickTimeout;
  325. private _previousDelayedSimpleClickTimeout;
  326. private _meshPickProceed = false;
  327. private _previousButtonPressed;
  328. private _previousHasSwiped = false;
  329. private _currentPickResult = null;
  330. private _previousPickResult = null;
  331. private _isButtonPressed = false;
  332. private _doubleClickOccured = false;
  333. public cameraToUseForPointers: Camera = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  334. private _pointerX: number;
  335. private _pointerY: number;
  336. private _unTranslatedPointerX: number;
  337. private _unTranslatedPointerY: number;
  338. private _startingPointerPosition = new Vector2(0, 0);
  339. private _previousStartingPointerPosition = new Vector2(0, 0);
  340. private _startingPointerTime = 0;
  341. private _previousStartingPointerTime = 0;
  342. // Mirror
  343. public _mirroredCameraPosition: Vector3;
  344. // Keyboard
  345. private _onKeyDown: (evt: Event) => void;
  346. private _onKeyUp: (evt: Event) => void;
  347. // Fog
  348. /**
  349. * is fog enabled on this scene.
  350. * @type {boolean}
  351. */
  352. private _fogEnabled = true;
  353. public set fogEnabled(value : boolean) {
  354. if (this._fogEnabled === value) {
  355. return;
  356. }
  357. this._fogEnabled = value;
  358. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  359. }
  360. public get fogEnabled(): boolean {
  361. return this._fogEnabled;
  362. }
  363. private _fogMode = Scene.FOGMODE_NONE;
  364. public set fogMode(value : number) {
  365. if (this._fogMode === value) {
  366. return;
  367. }
  368. this._fogMode = value;
  369. this.markAllMaterialsAsDirty(Material.MiscDirtyFlag);
  370. }
  371. public get fogMode(): number {
  372. return this._fogMode;
  373. }
  374. public fogColor = new Color3(0.2, 0.2, 0.3);
  375. public fogDensity = 0.1;
  376. public fogStart = 0;
  377. public fogEnd = 1000.0;
  378. // Lights
  379. /**
  380. * is shadow enabled on this scene.
  381. * @type {boolean}
  382. */
  383. private _shadowsEnabled = true;
  384. public set shadowsEnabled(value : boolean) {
  385. if (this._shadowsEnabled === value) {
  386. return;
  387. }
  388. this._shadowsEnabled = value;
  389. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  390. }
  391. public get shadowsEnabled(): boolean {
  392. return this._shadowsEnabled;
  393. }
  394. /**
  395. * is light enabled on this scene.
  396. * @type {boolean}
  397. */
  398. private _lightsEnabled = true;
  399. public set lightsEnabled(value : boolean) {
  400. if (this._lightsEnabled === value) {
  401. return;
  402. }
  403. this._lightsEnabled = value;
  404. this.markAllMaterialsAsDirty(Material.LightDirtyFlag);
  405. }
  406. public get lightsEnabled(): boolean {
  407. return this._lightsEnabled;
  408. }
  409. /**
  410. * All of the lights added to this scene.
  411. * @see BABYLON.Light
  412. * @type {BABYLON.Light[]}
  413. */
  414. public lights = new Array<Light>();
  415. // Cameras
  416. /**
  417. * All of the cameras added to this scene.
  418. * @see BABYLON.Camera
  419. * @type {BABYLON.Camera[]}
  420. */
  421. public cameras = new Array<Camera>();
  422. public activeCameras = new Array<Camera>();
  423. public activeCamera: Camera;
  424. // Meshes
  425. /**
  426. * All of the (abstract) meshes added to this scene.
  427. * @see BABYLON.AbstractMesh
  428. * @type {BABYLON.AbstractMesh[]}
  429. */
  430. public meshes = new Array<AbstractMesh>();
  431. // Geometries
  432. private _geometries = new Array<Geometry>();
  433. public materials = new Array<Material>();
  434. public multiMaterials = new Array<MultiMaterial>();
  435. private _defaultMaterial: StandardMaterial;
  436. public get defaultMaterial(): StandardMaterial {
  437. if (!this._defaultMaterial) {
  438. this._defaultMaterial = new StandardMaterial("default material", this);
  439. }
  440. return this._defaultMaterial;
  441. }
  442. // Textures
  443. private _texturesEnabled = true;
  444. public set texturesEnabled(value : boolean) {
  445. if (this._texturesEnabled === value) {
  446. return;
  447. }
  448. this._texturesEnabled = value;
  449. this.markAllMaterialsAsDirty(Material.TextureDirtyFlag);
  450. }
  451. public get texturesEnabled(): boolean {
  452. return this._texturesEnabled;
  453. }
  454. public textures = new Array<BaseTexture>();
  455. // Particles
  456. public particlesEnabled = true;
  457. public particleSystems = new Array<ParticleSystem>();
  458. // Sprites
  459. public spritesEnabled = true;
  460. public spriteManagers = new Array<SpriteManager>();
  461. // Layers
  462. public layers = new Array<Layer>();
  463. public highlightLayers = new Array<HighlightLayer>();
  464. // Skeletons
  465. private _skeletonsEnabled = true;
  466. public set skeletonsEnabled(value : boolean) {
  467. if (this._skeletonsEnabled === value) {
  468. return;
  469. }
  470. this._skeletonsEnabled = value;
  471. this.markAllMaterialsAsDirty(Material.AttributesDirtyFlag);
  472. }
  473. public get skeletonsEnabled(): boolean {
  474. return this._skeletonsEnabled;
  475. }
  476. public skeletons = new Array<Skeleton>();
  477. // Lens flares
  478. public lensFlaresEnabled = true;
  479. public lensFlareSystems = new Array<LensFlareSystem>();
  480. // Collisions
  481. public collisionsEnabled = true;
  482. private _workerCollisions;
  483. public collisionCoordinator: ICollisionCoordinator;
  484. public gravity = new Vector3(0, -9.807, 0);
  485. // Postprocesses
  486. public postProcessesEnabled = true;
  487. public postProcessManager: PostProcessManager;
  488. public postProcessRenderPipelineManager: PostProcessRenderPipelineManager;
  489. // Customs render targets
  490. public renderTargetsEnabled = true;
  491. public dumpNextRenderTargets = false;
  492. public customRenderTargets = new Array<RenderTargetTexture>();
  493. // Delay loading
  494. public useDelayedTextureLoading: boolean;
  495. // Imported meshes
  496. public importedMeshesFiles = new Array<String>();
  497. // Probes
  498. public probesEnabled = true;
  499. public reflectionProbes = new Array<ReflectionProbe>();
  500. // Database
  501. public database; //ANY
  502. /**
  503. * This scene's action manager
  504. * @type {BABYLON.ActionManager}
  505. */
  506. public actionManager: ActionManager;
  507. public _actionManagers = new Array<ActionManager>();
  508. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  509. // Procedural textures
  510. public proceduralTexturesEnabled = true;
  511. public _proceduralTextures = new Array<ProceduralTexture>();
  512. // Sound Tracks
  513. public mainSoundTrack: SoundTrack;
  514. public soundTracks = new Array<SoundTrack>();
  515. private _audioEnabled = true;
  516. private _headphone = false;
  517. //Simplification Queue
  518. public simplificationQueue: SimplificationQueue;
  519. // Private
  520. private _engine: Engine;
  521. // Performance counters
  522. private _totalMeshesCounter = new PerfCounter();
  523. private _totalLightsCounter = new PerfCounter();
  524. private _totalMaterialsCounter = new PerfCounter();
  525. private _totalTexturesCounter = new PerfCounter();
  526. private _totalVertices = new PerfCounter();
  527. public _activeIndices = new PerfCounter();
  528. public _activeParticles = new PerfCounter();
  529. private _lastFrameDuration = new PerfCounter();
  530. private _evaluateActiveMeshesDuration = new PerfCounter();
  531. private _renderTargetsDuration = new PerfCounter();
  532. public _particlesDuration = new PerfCounter();
  533. private _renderDuration = new PerfCounter();
  534. public _spritesDuration = new PerfCounter();
  535. public _activeBones = new PerfCounter();
  536. private _animationRatio: number;
  537. private _animationTimeLast: number;
  538. private _animationTime: number = 0;
  539. public animationTimeScale: number = 1;
  540. public _cachedMaterial: Material;
  541. private _renderId = 0;
  542. private _executeWhenReadyTimeoutId = -1;
  543. private _intermediateRendering = false;
  544. public _toBeDisposed = new SmartArray<IDisposable>(256);
  545. private _pendingData = [];//ANY
  546. private _activeMeshes = new SmartArray<Mesh>(256);
  547. private _processedMaterials = new SmartArray<Material>(256);
  548. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  549. public _activeParticleSystems = new SmartArray<ParticleSystem>(256);
  550. private _activeSkeletons = new SmartArray<Skeleton>(32);
  551. private _softwareSkinnedMeshes = new SmartArray<Mesh>(32);
  552. private _renderingManager: RenderingManager;
  553. private _physicsEngine: PhysicsEngine;
  554. public _activeAnimatables = new Array<Animatable>();
  555. private _transformMatrix = Matrix.Zero();
  556. private _pickWithRayInverseMatrix: Matrix;
  557. private _edgesRenderers = new SmartArray<EdgesRenderer>(16);
  558. private _boundingBoxRenderer: BoundingBoxRenderer;
  559. private _outlineRenderer: OutlineRenderer;
  560. private _viewMatrix: Matrix;
  561. private _projectionMatrix: Matrix;
  562. private _frustumPlanes: Plane[];
  563. public get frustumPlanes(): Plane[] {
  564. return this._frustumPlanes;
  565. }
  566. private _selectionOctree: Octree<AbstractMesh>;
  567. private _pointerOverMesh: AbstractMesh;
  568. private _pointerOverSprite: Sprite;
  569. private _debugLayer: DebugLayer;
  570. private _depthRenderer: DepthRenderer;
  571. private _uniqueIdCounter = 0;
  572. private _pickedDownMesh: AbstractMesh;
  573. private _pickedUpMesh: AbstractMesh;
  574. private _pickedDownSprite: Sprite;
  575. private _externalData: StringDictionary<Object>;
  576. private _uid: string;
  577. /**
  578. * @constructor
  579. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  580. */
  581. constructor(engine: Engine) {
  582. this._engine = engine || Engine.LastCreatedEngine;
  583. this._engine.scenes.push(this);
  584. this._externalData = new StringDictionary<Object>();
  585. this._uid = null;
  586. this._renderingManager = new RenderingManager(this);
  587. this.postProcessManager = new PostProcessManager(this);
  588. this.postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  589. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  590. if (OutlineRenderer) {
  591. this._outlineRenderer = new OutlineRenderer(this);
  592. }
  593. this.attachControl();
  594. if (SoundTrack) {
  595. this.mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  596. }
  597. //simplification queue
  598. if (SimplificationQueue) {
  599. this.simplificationQueue = new SimplificationQueue();
  600. }
  601. //collision coordinator initialization. For now legacy per default.
  602. this.workerCollisions = false;//(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  603. }
  604. // Properties
  605. public get debugLayer(): DebugLayer {
  606. if (!this._debugLayer) {
  607. this._debugLayer = new DebugLayer(this);
  608. }
  609. return this._debugLayer;
  610. }
  611. public set workerCollisions(enabled: boolean) {
  612. enabled = (enabled && !!Worker);
  613. this._workerCollisions = enabled;
  614. if (this.collisionCoordinator) {
  615. this.collisionCoordinator.destroy();
  616. }
  617. this.collisionCoordinator = enabled ? new CollisionCoordinatorWorker() : new CollisionCoordinatorLegacy();
  618. this.collisionCoordinator.init(this);
  619. }
  620. public get workerCollisions(): boolean {
  621. return this._workerCollisions;
  622. }
  623. public get SelectionOctree(): Octree<AbstractMesh> {
  624. return this._selectionOctree;
  625. }
  626. /**
  627. * The mesh that is currently under the pointer.
  628. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  629. */
  630. public get meshUnderPointer(): AbstractMesh {
  631. return this._pointerOverMesh;
  632. }
  633. /**
  634. * Current on-screen X position of the pointer
  635. * @return {number} X position of the pointer
  636. */
  637. public get pointerX(): number {
  638. return this._pointerX;
  639. }
  640. /**
  641. * Current on-screen Y position of the pointer
  642. * @return {number} Y position of the pointer
  643. */
  644. public get pointerY(): number {
  645. return this._pointerY;
  646. }
  647. public getCachedMaterial(): Material {
  648. return this._cachedMaterial;
  649. }
  650. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  651. return this._boundingBoxRenderer;
  652. }
  653. public getOutlineRenderer(): OutlineRenderer {
  654. return this._outlineRenderer;
  655. }
  656. public getEngine(): Engine {
  657. return this._engine;
  658. }
  659. public getTotalVertices(): number {
  660. return this._totalVertices.current;
  661. }
  662. public get totalVerticesPerfCounter(): PerfCounter {
  663. return this._totalVertices;
  664. }
  665. public getActiveIndices(): number {
  666. return this._activeIndices.current;
  667. }
  668. public get totalActiveIndicesPerfCounter(): PerfCounter {
  669. return this._activeIndices;
  670. }
  671. public getActiveParticles(): number {
  672. return this._activeParticles.current;
  673. }
  674. public get activeParticlesPerfCounter(): PerfCounter {
  675. return this._activeParticles;
  676. }
  677. public getActiveBones(): number {
  678. return this._activeBones.current;
  679. }
  680. public get activeBonesPerfCounter(): PerfCounter {
  681. return this._activeBones;
  682. }
  683. // Stats
  684. public getLastFrameDuration(): number {
  685. return this._lastFrameDuration.current;
  686. }
  687. public get lastFramePerfCounter(): PerfCounter {
  688. return this._lastFrameDuration;
  689. }
  690. public getEvaluateActiveMeshesDuration(): number {
  691. return this._evaluateActiveMeshesDuration.current;
  692. }
  693. public get evaluateActiveMeshesDurationPerfCounter(): PerfCounter {
  694. return this._evaluateActiveMeshesDuration;
  695. }
  696. public getActiveMeshes(): SmartArray<Mesh> {
  697. return this._activeMeshes;
  698. }
  699. public getRenderTargetsDuration(): number {
  700. return this._renderTargetsDuration.current;
  701. }
  702. public getRenderDuration(): number {
  703. return this._renderDuration.current;
  704. }
  705. public get renderDurationPerfCounter(): PerfCounter {
  706. return this._renderDuration;
  707. }
  708. public getParticlesDuration(): number {
  709. return this._particlesDuration.current;
  710. }
  711. public get particlesDurationPerfCounter(): PerfCounter {
  712. return this._particlesDuration;
  713. }
  714. public getSpritesDuration(): number {
  715. return this._spritesDuration.current;
  716. }
  717. public get spriteDuractionPerfCounter(): PerfCounter {
  718. return this._spritesDuration;
  719. }
  720. public getAnimationRatio(): number {
  721. return this._animationRatio;
  722. }
  723. public getRenderId(): number {
  724. return this._renderId;
  725. }
  726. public incrementRenderId(): void {
  727. this._renderId++;
  728. }
  729. private _updatePointerPosition(evt: PointerEvent): void {
  730. var canvasRect = this._engine.getRenderingCanvasClientRect();
  731. this._pointerX = evt.clientX - canvasRect.left;
  732. this._pointerY = evt.clientY - canvasRect.top;
  733. this._unTranslatedPointerX = this._pointerX;
  734. this._unTranslatedPointerY = this._pointerY;
  735. if (this.cameraToUseForPointers) {
  736. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  737. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  738. }
  739. }
  740. // Pointers handling
  741. /**
  742. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  743. * @param attachUp defines if you want to attach events to pointerup
  744. * @param attachDown defines if you want to attach events to pointerdown
  745. * @param attachMove defines if you want to attach events to pointermove
  746. */
  747. public attachControl(attachUp = true, attachDown = true, attachMove = true) {
  748. this._initActionManager = (act: ActionManager, clickInfo: ClickInfo): ActionManager => {
  749. if (!this._meshPickProceed) {
  750. let pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  751. this._currentPickResult = pickResult;
  752. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  753. this._meshPickProceed = true;
  754. }
  755. return act;
  756. };
  757. this._delayedSimpleClick = (btn: number, clickInfo: ClickInfo, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void) => {
  758. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  759. if ((new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay && !this._doubleClickOccured) ||
  760. btn !== this._previousButtonPressed ) {
  761. this._doubleClickOccured = false;
  762. clickInfo.singleClick = true;
  763. clickInfo.ignore = false;
  764. cb(clickInfo, this._currentPickResult);
  765. }
  766. }
  767. this._initClickEvent = (obs1: Observable<PointerInfoPre>, obs2: Observable<PointerInfo>, evt: PointerEvent, cb: (clickInfo: ClickInfo, pickResult: PointerInfo) => void): void => {
  768. let clickInfo = new ClickInfo();
  769. this._currentPickResult = null;
  770. let act;
  771. let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  772. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  773. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  774. if (!checkPicking && ActionManager.HasPickTriggers) {
  775. act = this._initActionManager(act, clickInfo);
  776. if (act)
  777. checkPicking = act.hasPickTriggers;
  778. }
  779. if (checkPicking) {
  780. let btn = evt.button;
  781. clickInfo.hasSwiped = Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  782. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  783. if (!clickInfo.hasSwiped) {
  784. let checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  785. if (!checkSingleClickImmediately) {
  786. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  787. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  788. if (checkSingleClickImmediately && !ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  789. act = this._initActionManager(act, clickInfo);
  790. if (act)
  791. checkSingleClickImmediately = !act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  792. }
  793. }
  794. if (checkSingleClickImmediately) {
  795. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  796. if (new Date().getTime() - this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  797. btn !== this._previousButtonPressed ) {
  798. clickInfo.singleClick = true;
  799. cb(clickInfo, this._currentPickResult);
  800. }
  801. }
  802. // at least one double click is required to be check and exclusive double click is enabled
  803. else {
  804. // wait that no double click has been raised during the double click delay
  805. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  806. this._delayedSimpleClickTimeout = window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  807. }
  808. let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  809. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  810. if (!checkDoubleClick && ActionManager.HasSpecificTrigger(ActionManager.OnDoublePickTrigger)){
  811. act = this._initActionManager(act, clickInfo);
  812. if (act)
  813. checkDoubleClick = act.hasSpecificTrigger(ActionManager.OnDoublePickTrigger);
  814. }
  815. if (checkDoubleClick) {
  816. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  817. if (btn === this._previousButtonPressed &&
  818. new Date().getTime() - this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  819. !this._doubleClickOccured
  820. ) {
  821. // pointer has not moved for 2 clicks, it's a double click
  822. if (!clickInfo.hasSwiped &&
  823. Math.abs(this._previousStartingPointerPosition.x - this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  824. Math.abs(this._previousStartingPointerPosition.y - this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  825. this._previousStartingPointerTime = 0;
  826. this._doubleClickOccured = true;
  827. clickInfo.doubleClick = true;
  828. clickInfo.ignore = false;
  829. if (Scene.ExclusiveDoubleClickMode && this._previousDelayedSimpleClickTimeout && this._previousDelayedSimpleClickTimeout.clearTimeout)
  830. this._previousDelayedSimpleClickTimeout.clearTimeout();
  831. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  832. cb(clickInfo, this._currentPickResult);
  833. }
  834. // if the two successive clicks are too far, it's just two simple clicks
  835. else {
  836. this._doubleClickOccured = false;
  837. this._previousStartingPointerTime = this._startingPointerTime;
  838. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  839. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  840. this._previousButtonPressed = btn;
  841. this._previousHasSwiped = clickInfo.hasSwiped;
  842. if (Scene.ExclusiveDoubleClickMode){
  843. if (this._previousDelayedSimpleClickTimeout && this._previousDelayedSimpleClickTimeout.clearTimeout) {
  844. this._previousDelayedSimpleClickTimeout.clearTimeout();
  845. }
  846. this._previousDelayedSimpleClickTimeout = this._delayedSimpleClickTimeout;
  847. cb(clickInfo, this._previousPickResult);
  848. }
  849. else {
  850. cb(clickInfo, this._currentPickResult);
  851. }
  852. }
  853. }
  854. // just the first click of the double has been raised
  855. else {
  856. this._doubleClickOccured = false;
  857. this._previousStartingPointerTime = this._startingPointerTime;
  858. this._previousStartingPointerPosition.x = this._startingPointerPosition.x;
  859. this._previousStartingPointerPosition.y = this._startingPointerPosition.y;
  860. this._previousButtonPressed = btn;
  861. this._previousHasSwiped = clickInfo.hasSwiped;
  862. }
  863. }
  864. }
  865. }
  866. clickInfo.ignore = true;
  867. cb(clickInfo, this._currentPickResult);
  868. };
  869. var spritePredicate = (sprite: Sprite): boolean => {
  870. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  871. };
  872. this._onPointerMove = (evt: PointerEvent) => {
  873. this._updatePointerPosition(evt);
  874. // PreObservable support
  875. if (this.onPrePointerObservable.hasObservers()) {
  876. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  877. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  878. this.onPrePointerObservable.notifyObservers(pi, type);
  879. if (pi.skipOnPointerObservable) {
  880. return;
  881. }
  882. }
  883. if (!this.cameraToUseForPointers && !this.activeCamera) {
  884. return;
  885. }
  886. var canvas = this._engine.getRenderingCanvas();
  887. if (!this.pointerMovePredicate) {
  888. this.pointerMovePredicate = (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && (this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined));
  889. }
  890. // Meshes
  891. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerMovePredicate, false, this.cameraToUseForPointers);
  892. if (pickResult.hit && pickResult.pickedMesh) {
  893. this.setPointerOverSprite(null);
  894. this.setPointerOverMesh(pickResult.pickedMesh);
  895. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  896. if (this._pointerOverMesh.actionManager.hoverCursor) {
  897. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  898. } else {
  899. canvas.style.cursor = this.hoverCursor;
  900. }
  901. } else {
  902. canvas.style.cursor = "";
  903. }
  904. } else {
  905. this.setPointerOverMesh(null);
  906. // Sprites
  907. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  908. if (pickResult.hit && pickResult.pickedSprite) {
  909. this.setPointerOverSprite(pickResult.pickedSprite);
  910. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  911. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  912. } else {
  913. canvas.style.cursor = this.hoverCursor;
  914. }
  915. } else {
  916. this.setPointerOverSprite(null);
  917. // Restore pointer
  918. canvas.style.cursor = "";
  919. }
  920. }
  921. if (this.onPointerMove) {
  922. this.onPointerMove(evt, pickResult);
  923. }
  924. if (this.onPointerObservable.hasObservers()) {
  925. let type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  926. let pi = new PointerInfo(type, evt, pickResult);
  927. this.onPointerObservable.notifyObservers(pi, type);
  928. }
  929. };
  930. this._onPointerDown = (evt: PointerEvent) => {
  931. this._isButtonPressed = true;
  932. this._pickedDownMesh = null;
  933. this._meshPickProceed = false;
  934. this._updatePointerPosition(evt);
  935. // PreObservable support
  936. if (this.onPrePointerObservable.hasObservers()) {
  937. let type = PointerEventTypes.POINTERDOWN;
  938. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  939. this.onPrePointerObservable.notifyObservers(pi, type);
  940. if (pi.skipOnPointerObservable) {
  941. return;
  942. }
  943. }
  944. if (!this.cameraToUseForPointers && !this.activeCamera) {
  945. return;
  946. }
  947. this._startingPointerPosition.x = this._pointerX;
  948. this._startingPointerPosition.y = this._pointerY;
  949. this._startingPointerTime = new Date().getTime();
  950. if (!this.pointerDownPredicate) {
  951. this.pointerDownPredicate = (mesh: AbstractMesh): boolean => {
  952. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  953. };
  954. }
  955. // Meshes
  956. this._pickedDownMesh = null;
  957. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, this.pointerDownPredicate, false, this.cameraToUseForPointers);
  958. if (pickResult.hit && pickResult.pickedMesh) {
  959. this._pickedDownMesh = pickResult.pickedMesh;
  960. var actionManager = pickResult.pickedMesh.actionManager;
  961. if (actionManager) {
  962. if (actionManager.hasPickTriggers) {
  963. actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  964. switch (evt.button) {
  965. case 0:
  966. actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  967. break;
  968. case 1:
  969. actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  970. break;
  971. case 2:
  972. actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  973. break;
  974. }
  975. }
  976. if (actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger)) {
  977. window.setTimeout((function () {
  978. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY,
  979. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(ActionManager.OnLongPressTrigger) && mesh == this._pickedDownMesh,
  980. false, this.cameraToUseForPointers);
  981. if (pickResult.hit && pickResult.pickedMesh) {
  982. if (this._isButtonPressed &&
  983. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  984. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  985. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  986. this._startingPointerTime = 0;
  987. actionManager.processTrigger(ActionManager.OnLongPressTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  988. }
  989. }
  990. }).bind(this), Scene.LongPressDelay);
  991. }
  992. }
  993. }
  994. if (this.onPointerDown) {
  995. this.onPointerDown(evt, pickResult);
  996. }
  997. if (this.onPointerObservable.hasObservers()) {
  998. let type = PointerEventTypes.POINTERDOWN;
  999. let pi = new PointerInfo(type, evt, pickResult);
  1000. this.onPointerObservable.notifyObservers(pi, type);
  1001. }
  1002. // Sprites
  1003. this._pickedDownSprite = null;
  1004. if (this.spriteManagers.length > 0) {
  1005. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  1006. if (pickResult.hit && pickResult.pickedSprite) {
  1007. if (pickResult.pickedSprite.actionManager) {
  1008. this._pickedDownSprite = pickResult.pickedSprite;
  1009. switch (evt.button) {
  1010. case 0:
  1011. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1012. break;
  1013. case 1:
  1014. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1015. break;
  1016. case 2:
  1017. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1018. break;
  1019. }
  1020. if (pickResult.pickedSprite.actionManager) {
  1021. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickDownTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1022. }
  1023. }
  1024. }
  1025. }
  1026. };
  1027. this._onPointerUp = (evt: PointerEvent) => {
  1028. this._isButtonPressed = false;
  1029. this._pickedUpMesh = null;
  1030. this._meshPickProceed = false;
  1031. this._updatePointerPosition(evt);
  1032. this._initClickEvent(this.onPrePointerObservable, this.onPointerObservable, evt, (function(clickInfo, pickResult){
  1033. // PreObservable support
  1034. if (this.onPrePointerObservable.hasObservers()) {
  1035. if (!clickInfo.ignore) {
  1036. if (!clickInfo.hasSwiped) {
  1037. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1038. let type = PointerEventTypes.POINTERTAP;
  1039. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1040. this.onPrePointerObservable.notifyObservers(pi, type);
  1041. if (pi.skipOnPointerObservable) {
  1042. return;
  1043. }
  1044. }
  1045. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1046. let type = PointerEventTypes.POINTERDOUBLETAP;
  1047. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1048. this.onPrePointerObservable.notifyObservers(pi, type);
  1049. if (pi.skipOnPointerObservable) {
  1050. return;
  1051. }
  1052. }
  1053. }
  1054. }
  1055. else {
  1056. let type = PointerEventTypes.POINTERUP;
  1057. let pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  1058. this.onPrePointerObservable.notifyObservers(pi, type);
  1059. if (pi.skipOnPointerObservable) {
  1060. return;
  1061. }
  1062. }
  1063. }
  1064. if (!this.cameraToUseForPointers && !this.activeCamera) {
  1065. return;
  1066. }
  1067. if (!this.pointerUpPredicate) {
  1068. this.pointerUpPredicate = (mesh: AbstractMesh): boolean => {
  1069. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  1070. };
  1071. }
  1072. // Meshes
  1073. if (!this._meshPickProceed && (ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  1074. this._initActionManager(null, clickInfo);
  1075. }
  1076. if (!pickResult) {
  1077. pickResult = this._currentPickResult;
  1078. }
  1079. if (pickResult && pickResult.pickedMesh) {
  1080. this._pickedUpMesh = pickResult.pickedMesh;
  1081. if (this._pickedDownMesh === this._pickedUpMesh) {
  1082. if (this.onPointerPick) {
  1083. this.onPointerPick(evt, pickResult);
  1084. }
  1085. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  1086. let type = PointerEventTypes.POINTERPICK;
  1087. let pi = new PointerInfo(type, evt, pickResult);
  1088. this.onPointerObservable.notifyObservers(pi, type);
  1089. }
  1090. }
  1091. if (pickResult.pickedMesh.actionManager) {
  1092. if (clickInfo.ignore) {
  1093. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1094. }
  1095. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  1096. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1097. }
  1098. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(ActionManager.OnDoublePickTrigger)) {
  1099. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnDoublePickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  1100. }
  1101. }
  1102. }
  1103. if (this._pickedDownMesh &&
  1104. this._pickedDownMesh.actionManager &&
  1105. this._pickedDownMesh.actionManager.hasSpecificTrigger(ActionManager.OnPickOutTrigger) &&
  1106. this._pickedDownMesh !== this._pickedUpMesh) {
  1107. this._pickedDownMesh.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNew(this._pickedDownMesh, evt));
  1108. }
  1109. if (this.onPointerUp) {
  1110. this.onPointerUp(evt, pickResult);
  1111. }
  1112. if (this.onPointerObservable.hasObservers()) {
  1113. if (!clickInfo.ignore) {
  1114. if (!clickInfo.hasSwiped) {
  1115. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  1116. let type = PointerEventTypes.POINTERTAP;
  1117. let pi = new PointerInfo(type, evt, pickResult);
  1118. this.onPointerObservable.notifyObservers(pi, type);
  1119. }
  1120. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  1121. let type = PointerEventTypes.POINTERDOUBLETAP;
  1122. let pi = new PointerInfo(type, evt, pickResult);
  1123. this.onPointerObservable.notifyObservers(pi, type);
  1124. }
  1125. }
  1126. }
  1127. else {
  1128. let type = PointerEventTypes.POINTERUP;
  1129. let pi = new PointerInfo(type, evt, pickResult);
  1130. this.onPointerObservable.notifyObservers(pi, type);
  1131. }
  1132. }
  1133. // Sprites
  1134. if (this.spriteManagers.length > 0) {
  1135. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  1136. if (pickResult.hit && pickResult.pickedSprite) {
  1137. if (pickResult.pickedSprite.actionManager) {
  1138. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickUpTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1139. if (pickResult.pickedSprite.actionManager) {
  1140. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  1141. pickResult.pickedSprite.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  1142. }
  1143. }
  1144. }
  1145. }
  1146. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  1147. this._pickedDownSprite.actionManager.processTrigger(ActionManager.OnPickOutTrigger, ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  1148. }
  1149. }
  1150. this._previousPickResult = this._currentPickResult;
  1151. }).bind(this));
  1152. };
  1153. this._onKeyDown = (evt: Event) => {
  1154. if (this.actionManager) {
  1155. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1156. }
  1157. };
  1158. this._onKeyUp = (evt: Event) => {
  1159. if (this.actionManager) {
  1160. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  1161. }
  1162. };
  1163. var eventPrefix = Tools.GetPointerPrefix();
  1164. var canvas = this._engine.getRenderingCanvas();
  1165. if (attachMove) {
  1166. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  1167. // Wheel
  1168. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  1169. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  1170. }
  1171. if (attachDown) {
  1172. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  1173. }
  1174. if (attachUp) {
  1175. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  1176. }
  1177. canvas.tabIndex = 1;
  1178. canvas.addEventListener("keydown", this._onKeyDown, false);
  1179. canvas.addEventListener("keyup", this._onKeyUp, false);
  1180. }
  1181. public detachControl() {
  1182. var eventPrefix = Tools.GetPointerPrefix();
  1183. var canvas = this._engine.getRenderingCanvas();
  1184. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  1185. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  1186. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  1187. // Wheel
  1188. canvas.removeEventListener('mousewheel', this._onPointerMove);
  1189. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  1190. canvas.removeEventListener("keydown", this._onKeyDown);
  1191. canvas.removeEventListener("keyup", this._onKeyUp);
  1192. }
  1193. // Ready
  1194. public isReady(): boolean {
  1195. if (this._pendingData.length > 0) {
  1196. return false;
  1197. }
  1198. var index: number;
  1199. for (index = 0; index < this._geometries.length; index++) {
  1200. var geometry = this._geometries[index];
  1201. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1202. return false;
  1203. }
  1204. }
  1205. for (index = 0; index < this.meshes.length; index++) {
  1206. var mesh = this.meshes[index];
  1207. if (!mesh.isEnabled()) {
  1208. continue;
  1209. }
  1210. if (!mesh.isReady()) {
  1211. return false;
  1212. }
  1213. var mat = mesh.material;
  1214. if (mat) {
  1215. if (!mat.isReady(mesh)) {
  1216. return false;
  1217. }
  1218. }
  1219. }
  1220. return true;
  1221. }
  1222. public resetCachedMaterial(): void {
  1223. this._cachedMaterial = null;
  1224. }
  1225. public registerBeforeRender(func: () => void): void {
  1226. this.onBeforeRenderObservable.add(func);
  1227. }
  1228. public unregisterBeforeRender(func: () => void): void {
  1229. this.onBeforeRenderObservable.removeCallback(func);
  1230. }
  1231. public registerAfterRender(func: () => void): void {
  1232. this.onAfterRenderObservable.add(func);
  1233. }
  1234. public unregisterAfterRender(func: () => void): void {
  1235. this.onAfterRenderObservable.removeCallback(func);
  1236. }
  1237. public _addPendingData(data): void {
  1238. this._pendingData.push(data);
  1239. }
  1240. public _removePendingData(data): void {
  1241. var index = this._pendingData.indexOf(data);
  1242. if (index !== -1) {
  1243. this._pendingData.splice(index, 1);
  1244. }
  1245. }
  1246. public getWaitingItemsCount(): number {
  1247. return this._pendingData.length;
  1248. }
  1249. /**
  1250. * Registers a function to be executed when the scene is ready.
  1251. * @param {Function} func - the function to be executed.
  1252. */
  1253. public executeWhenReady(func: () => void): void {
  1254. this.onReadyObservable.add(func);
  1255. if (this._executeWhenReadyTimeoutId !== -1) {
  1256. return;
  1257. }
  1258. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1259. this._checkIsReady();
  1260. }, 150);
  1261. }
  1262. public _checkIsReady() {
  1263. if (this.isReady()) {
  1264. this.onReadyObservable.notifyObservers(this);
  1265. this.onReadyObservable.clear();
  1266. this._executeWhenReadyTimeoutId = -1;
  1267. return;
  1268. }
  1269. this._executeWhenReadyTimeoutId = setTimeout(() => {
  1270. this._checkIsReady();
  1271. }, 150);
  1272. }
  1273. // Animations
  1274. /**
  1275. * Will start the animation sequence of a given target
  1276. * @param target - the target
  1277. * @param {number} from - from which frame should animation start
  1278. * @param {number} to - till which frame should animation run.
  1279. * @param {boolean} [loop] - should the animation loop
  1280. * @param {number} [speedRatio] - the speed in which to run the animation
  1281. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  1282. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  1283. * @return {BABYLON.Animatable} the animatable object created for this animation
  1284. * @see BABYLON.Animatable
  1285. * @see http://doc.babylonjs.com/page.php?p=22081
  1286. */
  1287. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio: number = 1.0, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  1288. this.stopAnimation(target);
  1289. if (!animatable) {
  1290. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  1291. }
  1292. // Local animations
  1293. if (target.animations) {
  1294. animatable.appendAnimations(target, target.animations);
  1295. }
  1296. // Children animations
  1297. if (target.getAnimatables) {
  1298. var animatables = target.getAnimatables();
  1299. for (var index = 0; index < animatables.length; index++) {
  1300. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  1301. }
  1302. }
  1303. animatable.reset();
  1304. return animatable;
  1305. }
  1306. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  1307. if (speedRatio === undefined) {
  1308. speedRatio = 1.0;
  1309. }
  1310. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  1311. return animatable;
  1312. }
  1313. public getAnimatableByTarget(target: any): Animatable {
  1314. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1315. if (this._activeAnimatables[index].target === target) {
  1316. return this._activeAnimatables[index];
  1317. }
  1318. }
  1319. return null;
  1320. }
  1321. public get Animatables(): Animatable[] {
  1322. return this._activeAnimatables;
  1323. }
  1324. /**
  1325. * Will stop the animation of the given target
  1326. * @param target - the target
  1327. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  1328. * @see beginAnimation
  1329. */
  1330. public stopAnimation(target: any, animationName?: string): void {
  1331. var animatable = this.getAnimatableByTarget(target);
  1332. if (animatable) {
  1333. animatable.stop(animationName);
  1334. }
  1335. }
  1336. private _animate(): void {
  1337. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1338. return;
  1339. }
  1340. // Getting time
  1341. var now = Tools.Now;
  1342. if (!this._animationTimeLast) {
  1343. if (this._pendingData.length > 0) {
  1344. return;
  1345. }
  1346. this._animationTimeLast = now;
  1347. }
  1348. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  1349. this._animationTime += deltaTime;
  1350. this._animationTimeLast = now;
  1351. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1352. this._activeAnimatables[index]._animate(this._animationTime);
  1353. }
  1354. }
  1355. // Matrix
  1356. public getViewMatrix(): Matrix {
  1357. return this._viewMatrix;
  1358. }
  1359. public getProjectionMatrix(): Matrix {
  1360. return this._projectionMatrix;
  1361. }
  1362. public getTransformMatrix(): Matrix {
  1363. return this._transformMatrix;
  1364. }
  1365. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  1366. this._viewMatrix = view;
  1367. this._projectionMatrix = projection;
  1368. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1369. // Update frustum
  1370. if (!this._frustumPlanes) {
  1371. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  1372. } else {
  1373. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1374. }
  1375. }
  1376. // Methods
  1377. public addMesh(newMesh: AbstractMesh) {
  1378. newMesh.uniqueId = this._uniqueIdCounter++;
  1379. var position = this.meshes.push(newMesh);
  1380. //notify the collision coordinator
  1381. this.collisionCoordinator.onMeshAdded(newMesh);
  1382. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1383. }
  1384. public removeMesh(toRemove: AbstractMesh): number {
  1385. var index = this.meshes.indexOf(toRemove);
  1386. if (index !== -1) {
  1387. // Remove from the scene if mesh found
  1388. this.meshes.splice(index, 1);
  1389. }
  1390. //notify the collision coordinator
  1391. this.collisionCoordinator.onMeshRemoved(toRemove);
  1392. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1393. return index;
  1394. }
  1395. public removeSkeleton(toRemove: Skeleton): number {
  1396. var index = this.skeletons.indexOf(toRemove);
  1397. if (index !== -1) {
  1398. // Remove from the scene if mesh found
  1399. this.skeletons.splice(index, 1);
  1400. }
  1401. return index;
  1402. }
  1403. public removeLight(toRemove: Light): number {
  1404. var index = this.lights.indexOf(toRemove);
  1405. if (index !== -1) {
  1406. // Remove from the scene if mesh found
  1407. this.lights.splice(index, 1);
  1408. }
  1409. this.onLightRemovedObservable.notifyObservers(toRemove);
  1410. return index;
  1411. }
  1412. public removeCamera(toRemove: Camera): number {
  1413. var index = this.cameras.indexOf(toRemove);
  1414. if (index !== -1) {
  1415. // Remove from the scene if mesh found
  1416. this.cameras.splice(index, 1);
  1417. }
  1418. // Remove from activeCameras
  1419. var index2 = this.activeCameras.indexOf(toRemove);
  1420. if (index2 !== -1) {
  1421. // Remove from the scene if mesh found
  1422. this.activeCameras.splice(index2, 1);
  1423. }
  1424. // Reset the activeCamera
  1425. if (this.activeCamera === toRemove) {
  1426. if (this.cameras.length > 0) {
  1427. this.activeCamera = this.cameras[0];
  1428. } else {
  1429. this.activeCamera = null;
  1430. }
  1431. }
  1432. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1433. return index;
  1434. }
  1435. public addLight(newLight: Light) {
  1436. newLight.uniqueId = this._uniqueIdCounter++;
  1437. var position = this.lights.push(newLight);
  1438. this.onNewLightAddedObservable.notifyObservers(newLight);
  1439. }
  1440. public addCamera(newCamera: Camera) {
  1441. newCamera.uniqueId = this._uniqueIdCounter++;
  1442. var position = this.cameras.push(newCamera);
  1443. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  1444. }
  1445. /**
  1446. * Switch active camera
  1447. * @param {Camera} newCamera - new active camera
  1448. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  1449. */
  1450. public switchActiveCamera(newCamera: Camera, attachControl = true) {
  1451. var canvas = this._engine.getRenderingCanvas();
  1452. this.activeCamera.detachControl(canvas);
  1453. this.activeCamera = newCamera;
  1454. if (attachControl) {
  1455. newCamera.attachControl(canvas);
  1456. }
  1457. }
  1458. /**
  1459. * sets the active camera of the scene using its ID
  1460. * @param {string} id - the camera's ID
  1461. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1462. * @see activeCamera
  1463. */
  1464. public setActiveCameraByID(id: string): Camera {
  1465. var camera = this.getCameraByID(id);
  1466. if (camera) {
  1467. this.activeCamera = camera;
  1468. return camera;
  1469. }
  1470. return null;
  1471. }
  1472. /**
  1473. * sets the active camera of the scene using its name
  1474. * @param {string} name - the camera's name
  1475. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1476. * @see activeCamera
  1477. */
  1478. public setActiveCameraByName(name: string): Camera {
  1479. var camera = this.getCameraByName(name);
  1480. if (camera) {
  1481. this.activeCamera = camera;
  1482. return camera;
  1483. }
  1484. return null;
  1485. }
  1486. /**
  1487. * get a material using its id
  1488. * @param {string} the material's ID
  1489. * @return {BABYLON.Material|null} the material or null if none found.
  1490. */
  1491. public getMaterialByID(id: string): Material {
  1492. for (var index = 0; index < this.materials.length; index++) {
  1493. if (this.materials[index].id === id) {
  1494. return this.materials[index];
  1495. }
  1496. }
  1497. return null;
  1498. }
  1499. /**
  1500. * get a material using its name
  1501. * @param {string} the material's name
  1502. * @return {BABYLON.Material|null} the material or null if none found.
  1503. */
  1504. public getMaterialByName(name: string): Material {
  1505. for (var index = 0; index < this.materials.length; index++) {
  1506. if (this.materials[index].name === name) {
  1507. return this.materials[index];
  1508. }
  1509. }
  1510. return null;
  1511. }
  1512. public getLensFlareSystemByName(name: string): LensFlareSystem {
  1513. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1514. if (this.lensFlareSystems[index].name === name) {
  1515. return this.lensFlareSystems[index];
  1516. }
  1517. }
  1518. return null;
  1519. }
  1520. public getLensFlareSystemByID(id: string): LensFlareSystem {
  1521. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1522. if (this.lensFlareSystems[index].id === id) {
  1523. return this.lensFlareSystems[index];
  1524. }
  1525. }
  1526. return null;
  1527. }
  1528. public getCameraByID(id: string): Camera {
  1529. for (var index = 0; index < this.cameras.length; index++) {
  1530. if (this.cameras[index].id === id) {
  1531. return this.cameras[index];
  1532. }
  1533. }
  1534. return null;
  1535. }
  1536. public getCameraByUniqueID(uniqueId: number): Camera {
  1537. for (var index = 0; index < this.cameras.length; index++) {
  1538. if (this.cameras[index].uniqueId === uniqueId) {
  1539. return this.cameras[index];
  1540. }
  1541. }
  1542. return null;
  1543. }
  1544. /**
  1545. * get a camera using its name
  1546. * @param {string} the camera's name
  1547. * @return {BABYLON.Camera|null} the camera or null if none found.
  1548. */
  1549. public getCameraByName(name: string): Camera {
  1550. for (var index = 0; index < this.cameras.length; index++) {
  1551. if (this.cameras[index].name === name) {
  1552. return this.cameras[index];
  1553. }
  1554. }
  1555. return null;
  1556. }
  1557. /**
  1558. * get a bone using its id
  1559. * @param {string} the bone's id
  1560. * @return {BABYLON.Bone|null} the bone or null if not found
  1561. */
  1562. public getBoneByID(id: string): Bone {
  1563. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1564. var skeleton = this.skeletons[skeletonIndex];
  1565. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1566. if (skeleton.bones[boneIndex].id === id) {
  1567. return skeleton.bones[boneIndex];
  1568. }
  1569. }
  1570. }
  1571. return null;
  1572. }
  1573. /**
  1574. * get a bone using its id
  1575. * @param {string} the bone's name
  1576. * @return {BABYLON.Bone|null} the bone or null if not found
  1577. */
  1578. public getBoneByName(name: string): Bone {
  1579. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1580. var skeleton = this.skeletons[skeletonIndex];
  1581. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1582. if (skeleton.bones[boneIndex].name === name) {
  1583. return skeleton.bones[boneIndex];
  1584. }
  1585. }
  1586. }
  1587. return null;
  1588. }
  1589. /**
  1590. * get a light node using its name
  1591. * @param {string} the light's name
  1592. * @return {BABYLON.Light|null} the light or null if none found.
  1593. */
  1594. public getLightByName(name: string): Light {
  1595. for (var index = 0; index < this.lights.length; index++) {
  1596. if (this.lights[index].name === name) {
  1597. return this.lights[index];
  1598. }
  1599. }
  1600. return null;
  1601. }
  1602. /**
  1603. * get a light node using its ID
  1604. * @param {string} the light's id
  1605. * @return {BABYLON.Light|null} the light or null if none found.
  1606. */
  1607. public getLightByID(id: string): Light {
  1608. for (var index = 0; index < this.lights.length; index++) {
  1609. if (this.lights[index].id === id) {
  1610. return this.lights[index];
  1611. }
  1612. }
  1613. return null;
  1614. }
  1615. /**
  1616. * get a light node using its scene-generated unique ID
  1617. * @param {number} the light's unique id
  1618. * @return {BABYLON.Light|null} the light or null if none found.
  1619. */
  1620. public getLightByUniqueID(uniqueId: number): Light {
  1621. for (var index = 0; index < this.lights.length; index++) {
  1622. if (this.lights[index].uniqueId === uniqueId) {
  1623. return this.lights[index];
  1624. }
  1625. }
  1626. return null;
  1627. }
  1628. /**
  1629. * get a particle system by id
  1630. * @param id {number} the particle system id
  1631. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  1632. */
  1633. public getParticleSystemByID(id: string): ParticleSystem {
  1634. for (var index = 0; index < this.particleSystems.length; index++) {
  1635. if (this.particleSystems[index].id === id) {
  1636. return this.particleSystems[index];
  1637. }
  1638. }
  1639. return null;
  1640. }
  1641. /**
  1642. * get a geometry using its ID
  1643. * @param {string} the geometry's id
  1644. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  1645. */
  1646. public getGeometryByID(id: string): Geometry {
  1647. for (var index = 0; index < this._geometries.length; index++) {
  1648. if (this._geometries[index].id === id) {
  1649. return this._geometries[index];
  1650. }
  1651. }
  1652. return null;
  1653. }
  1654. /**
  1655. * add a new geometry to this scene.
  1656. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  1657. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  1658. * @return {boolean} was the geometry added or not
  1659. */
  1660. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  1661. if (!force && this.getGeometryByID(geometry.id)) {
  1662. return false;
  1663. }
  1664. this._geometries.push(geometry);
  1665. //notify the collision coordinator
  1666. this.collisionCoordinator.onGeometryAdded(geometry);
  1667. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  1668. return true;
  1669. }
  1670. /**
  1671. * Removes an existing geometry
  1672. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  1673. * @return {boolean} was the geometry removed or not
  1674. */
  1675. public removeGeometry(geometry: Geometry): boolean {
  1676. var index = this._geometries.indexOf(geometry);
  1677. if (index > -1) {
  1678. this._geometries.splice(index, 1);
  1679. //notify the collision coordinator
  1680. this.collisionCoordinator.onGeometryDeleted(geometry);
  1681. this.onGeometryRemovedObservable.notifyObservers(geometry);
  1682. return true;
  1683. }
  1684. return false;
  1685. }
  1686. public getGeometries(): Geometry[] {
  1687. return this._geometries;
  1688. }
  1689. /**
  1690. * Get the first added mesh found of a given ID
  1691. * @param {string} id - the id to search for
  1692. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1693. */
  1694. public getMeshByID(id: string): AbstractMesh {
  1695. for (var index = 0; index < this.meshes.length; index++) {
  1696. if (this.meshes[index].id === id) {
  1697. return this.meshes[index];
  1698. }
  1699. }
  1700. return null;
  1701. }
  1702. public getMeshesByID(id: string): Array<AbstractMesh> {
  1703. return this.meshes.filter(function (m) {
  1704. return m.id === id;
  1705. })
  1706. }
  1707. /**
  1708. * Get a mesh with its auto-generated unique id
  1709. * @param {number} uniqueId - the unique id to search for
  1710. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1711. */
  1712. public getMeshByUniqueID(uniqueId: number): AbstractMesh {
  1713. for (var index = 0; index < this.meshes.length; index++) {
  1714. if (this.meshes[index].uniqueId === uniqueId) {
  1715. return this.meshes[index];
  1716. }
  1717. }
  1718. return null;
  1719. }
  1720. /**
  1721. * Get a the last added mesh found of a given ID
  1722. * @param {string} id - the id to search for
  1723. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1724. */
  1725. public getLastMeshByID(id: string): AbstractMesh {
  1726. for (var index = this.meshes.length - 1; index >= 0; index--) {
  1727. if (this.meshes[index].id === id) {
  1728. return this.meshes[index];
  1729. }
  1730. }
  1731. return null;
  1732. }
  1733. /**
  1734. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  1735. * @param {string} id - the id to search for
  1736. * @return {BABYLON.Node|null} the node found or null if not found at all.
  1737. */
  1738. public getLastEntryByID(id: string): Node {
  1739. var index: number;
  1740. for (index = this.meshes.length - 1; index >= 0; index--) {
  1741. if (this.meshes[index].id === id) {
  1742. return this.meshes[index];
  1743. }
  1744. }
  1745. for (index = this.cameras.length - 1; index >= 0; index--) {
  1746. if (this.cameras[index].id === id) {
  1747. return this.cameras[index];
  1748. }
  1749. }
  1750. for (index = this.lights.length - 1; index >= 0; index--) {
  1751. if (this.lights[index].id === id) {
  1752. return this.lights[index];
  1753. }
  1754. }
  1755. return null;
  1756. }
  1757. public getNodeByID(id: string): Node {
  1758. var mesh = this.getMeshByID(id);
  1759. if (mesh) {
  1760. return mesh;
  1761. }
  1762. var light = this.getLightByID(id);
  1763. if (light) {
  1764. return light;
  1765. }
  1766. var camera = this.getCameraByID(id);
  1767. if (camera) {
  1768. return camera;
  1769. }
  1770. var bone = this.getBoneByID(id);
  1771. return bone;
  1772. }
  1773. public getNodeByName(name: string): Node {
  1774. var mesh = this.getMeshByName(name);
  1775. if (mesh) {
  1776. return mesh;
  1777. }
  1778. var light = this.getLightByName(name);
  1779. if (light) {
  1780. return light;
  1781. }
  1782. var camera = this.getCameraByName(name);
  1783. if (camera) {
  1784. return camera;
  1785. }
  1786. var bone = this.getBoneByName(name);
  1787. return bone;
  1788. }
  1789. public getMeshByName(name: string): AbstractMesh {
  1790. for (var index = 0; index < this.meshes.length; index++) {
  1791. if (this.meshes[index].name === name) {
  1792. return this.meshes[index];
  1793. }
  1794. }
  1795. return null;
  1796. }
  1797. public getSoundByName(name: string): Sound {
  1798. var index: number;
  1799. if (AudioEngine) {
  1800. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  1801. if (this.mainSoundTrack.soundCollection[index].name === name) {
  1802. return this.mainSoundTrack.soundCollection[index];
  1803. }
  1804. }
  1805. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  1806. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  1807. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  1808. return this.soundTracks[sdIndex].soundCollection[index];
  1809. }
  1810. }
  1811. }
  1812. }
  1813. return null;
  1814. }
  1815. public getLastSkeletonByID(id: string): Skeleton {
  1816. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  1817. if (this.skeletons[index].id === id) {
  1818. return this.skeletons[index];
  1819. }
  1820. }
  1821. return null;
  1822. }
  1823. public getSkeletonById(id: string): Skeleton {
  1824. for (var index = 0; index < this.skeletons.length; index++) {
  1825. if (this.skeletons[index].id === id) {
  1826. return this.skeletons[index];
  1827. }
  1828. }
  1829. return null;
  1830. }
  1831. public getSkeletonByName(name: string): Skeleton {
  1832. for (var index = 0; index < this.skeletons.length; index++) {
  1833. if (this.skeletons[index].name === name) {
  1834. return this.skeletons[index];
  1835. }
  1836. }
  1837. return null;
  1838. }
  1839. public isActiveMesh(mesh: Mesh): boolean {
  1840. return (this._activeMeshes.indexOf(mesh) !== -1);
  1841. }
  1842. /**
  1843. * Return a the first highlight layer of the scene with a given name.
  1844. * @param name The name of the highlight layer to look for.
  1845. * @return The highlight layer if found otherwise null.
  1846. */
  1847. public getHighlightLayerByName(name: string): HighlightLayer {
  1848. for (var index = 0; index < this.highlightLayers.length; index++) {
  1849. if (this.highlightLayers[index].name === name) {
  1850. return this.highlightLayers[index];
  1851. }
  1852. }
  1853. return null;
  1854. }
  1855. /**
  1856. * Return a unique id as a string which can serve as an identifier for the scene
  1857. */
  1858. public get uid(): string {
  1859. if (!this._uid) {
  1860. this._uid = Tools.RandomId();
  1861. }
  1862. return this._uid;
  1863. }
  1864. /**
  1865. * Add an externaly attached data from its key.
  1866. * This method call will fail and return false, if such key already exists.
  1867. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  1868. * @param key the unique key that identifies the data
  1869. * @param data the data object to associate to the key for this Engine instance
  1870. * @return true if no such key were already present and the data was added successfully, false otherwise
  1871. */
  1872. public addExternalData<T>(key: string, data: T): boolean {
  1873. return this._externalData.add(key, data);
  1874. }
  1875. /**
  1876. * Get an externaly attached data from its key
  1877. * @param key the unique key that identifies the data
  1878. * @return the associated data, if present (can be null), or undefined if not present
  1879. */
  1880. public getExternalData<T>(key: string): T {
  1881. return <T>this._externalData.get(key);
  1882. }
  1883. /**
  1884. * Get an externaly attached data from its key, create it using a factory if it's not already present
  1885. * @param key the unique key that identifies the data
  1886. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  1887. * @return the associated data, can be null if the factory returned null.
  1888. */
  1889. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  1890. return <T>this._externalData.getOrAddWithFactory(key, factory);
  1891. }
  1892. /**
  1893. * Remove an externaly attached data from the Engine instance
  1894. * @param key the unique key that identifies the data
  1895. * @return true if the data was successfully removed, false if it doesn't exist
  1896. */
  1897. public removeExternalData(key): boolean {
  1898. return this._externalData.remove(key);
  1899. }
  1900. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  1901. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  1902. var material = subMesh.getMaterial();
  1903. if (mesh.showSubMeshesBoundingBox) {
  1904. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  1905. }
  1906. if (material) {
  1907. // Render targets
  1908. if (material.getRenderTargetTextures) {
  1909. if (this._processedMaterials.indexOf(material) === -1) {
  1910. this._processedMaterials.push(material);
  1911. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  1912. }
  1913. }
  1914. // Dispatch
  1915. this._activeIndices.addCount(subMesh.indexCount, false);
  1916. this._renderingManager.dispatch(subMesh);
  1917. }
  1918. }
  1919. }
  1920. public _isInIntermediateRendering(): boolean {
  1921. return this._intermediateRendering
  1922. }
  1923. private _evaluateActiveMeshes(): void {
  1924. this.activeCamera._activeMeshes.reset();
  1925. this._activeMeshes.reset();
  1926. this._renderingManager.reset();
  1927. this._processedMaterials.reset();
  1928. this._activeParticleSystems.reset();
  1929. this._activeSkeletons.reset();
  1930. this._softwareSkinnedMeshes.reset();
  1931. this._boundingBoxRenderer.reset();
  1932. this._edgesRenderers.reset();
  1933. // Meshes
  1934. var meshes: AbstractMesh[];
  1935. var len: number;
  1936. if (this._selectionOctree) { // Octree
  1937. var selection = this._selectionOctree.select(this._frustumPlanes);
  1938. meshes = selection.data;
  1939. len = selection.length;
  1940. } else { // Full scene traversal
  1941. len = this.meshes.length;
  1942. meshes = this.meshes;
  1943. }
  1944. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  1945. var mesh = meshes[meshIndex];
  1946. if (mesh.isBlocked) {
  1947. continue;
  1948. }
  1949. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  1950. if (!mesh.isReady() || !mesh.isEnabled()) {
  1951. continue;
  1952. }
  1953. mesh.computeWorldMatrix();
  1954. // Intersections
  1955. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  1956. this._meshesForIntersections.pushNoDuplicate(mesh);
  1957. }
  1958. // Switch to current LOD
  1959. var meshLOD = mesh.getLOD(this.activeCamera);
  1960. if (!meshLOD) {
  1961. continue;
  1962. }
  1963. mesh._preActivate();
  1964. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  1965. this._activeMeshes.push(mesh);
  1966. this.activeCamera._activeMeshes.push(mesh);
  1967. mesh._activate(this._renderId);
  1968. this._activeMesh(mesh, meshLOD);
  1969. }
  1970. }
  1971. // Particle systems
  1972. this._particlesDuration.beginMonitoring();
  1973. var beforeParticlesDate = Tools.Now;
  1974. if (this.particlesEnabled) {
  1975. Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  1976. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  1977. var particleSystem = this.particleSystems[particleIndex];
  1978. if (!particleSystem.isStarted()) {
  1979. continue;
  1980. }
  1981. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  1982. this._activeParticleSystems.push(particleSystem);
  1983. particleSystem.animate();
  1984. this._renderingManager.dispatchParticles(particleSystem);
  1985. }
  1986. }
  1987. Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  1988. }
  1989. this._particlesDuration.endMonitoring(false);
  1990. }
  1991. private _activeMesh(sourceMesh: AbstractMesh, mesh: AbstractMesh): void {
  1992. if (mesh.skeleton && this.skeletonsEnabled) {
  1993. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  1994. mesh.skeleton.prepare();
  1995. }
  1996. if (!mesh.computeBonesUsingShaders) {
  1997. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  1998. }
  1999. }
  2000. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  2001. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  2002. }
  2003. if (sourceMesh._edgesRenderer) {
  2004. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  2005. }
  2006. if (mesh && mesh.subMeshes) {
  2007. // Submeshes Octrees
  2008. var len: number;
  2009. var subMeshes: SubMesh[];
  2010. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  2011. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  2012. len = intersections.length;
  2013. subMeshes = intersections.data;
  2014. } else {
  2015. subMeshes = mesh.subMeshes;
  2016. len = subMeshes.length;
  2017. }
  2018. for (var subIndex = 0; subIndex < len; subIndex++) {
  2019. var subMesh = subMeshes[subIndex];
  2020. this._evaluateSubMesh(subMesh, mesh);
  2021. }
  2022. }
  2023. }
  2024. public updateTransformMatrix(force?: boolean): void {
  2025. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  2026. }
  2027. private _renderForCamera(camera: Camera): void {
  2028. var engine = this._engine;
  2029. var startTime = Tools.Now;
  2030. this.activeCamera = camera;
  2031. if (!this.activeCamera)
  2032. throw new Error("Active camera not set");
  2033. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2034. // Viewport
  2035. engine.setViewport(this.activeCamera.viewport);
  2036. // Camera
  2037. this.resetCachedMaterial();
  2038. this._renderId++;
  2039. this.updateTransformMatrix();
  2040. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  2041. // Meshes
  2042. this._evaluateActiveMeshesDuration.beginMonitoring();
  2043. Tools.StartPerformanceCounter("Active meshes evaluation");
  2044. this._evaluateActiveMeshes();
  2045. this._evaluateActiveMeshesDuration.endMonitoring(false);
  2046. Tools.EndPerformanceCounter("Active meshes evaluation");
  2047. // Software skinning
  2048. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  2049. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  2050. mesh.applySkeleton(mesh.skeleton);
  2051. }
  2052. // Render targets
  2053. this._renderTargetsDuration.beginMonitoring();
  2054. var needsRestoreFrameBuffer = false;
  2055. var beforeRenderTargetDate = Tools.Now;
  2056. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  2057. this._intermediateRendering = true;
  2058. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2059. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  2060. var renderTarget = this._renderTargets.data[renderIndex];
  2061. if (renderTarget._shouldRender()) {
  2062. this._renderId++;
  2063. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  2064. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  2065. }
  2066. }
  2067. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  2068. this._intermediateRendering = false;
  2069. this._renderId++;
  2070. needsRestoreFrameBuffer = true; // Restore back buffer
  2071. }
  2072. // Render HighlightLayer Texture
  2073. var stencilState = this._engine.getStencilBuffer();
  2074. var renderhighlights = false;
  2075. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  2076. this._intermediateRendering = true;
  2077. for (let i = 0; i < this.highlightLayers.length; i++) {
  2078. let highlightLayer = this.highlightLayers[i];
  2079. if (highlightLayer.shouldRender() &&
  2080. (!highlightLayer.camera ||
  2081. (highlightLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  2082. (highlightLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  2083. renderhighlights = true;
  2084. var renderTarget = (<RenderTargetTexture>(<any>highlightLayer)._mainTexture);
  2085. if (renderTarget._shouldRender()) {
  2086. this._renderId++;
  2087. renderTarget.render(false, false);
  2088. needsRestoreFrameBuffer = true;
  2089. }
  2090. }
  2091. }
  2092. this._intermediateRendering = false;
  2093. this._renderId++;
  2094. }
  2095. if (needsRestoreFrameBuffer) {
  2096. engine.restoreDefaultFramebuffer();
  2097. }
  2098. this._renderTargetsDuration.endMonitoring(false);
  2099. // Prepare Frame
  2100. this.postProcessManager._prepareFrame();
  2101. this._renderDuration.beginMonitoring();
  2102. // Backgrounds
  2103. var layerIndex;
  2104. var layer;
  2105. if (this.layers.length) {
  2106. engine.setDepthBuffer(false);
  2107. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2108. layer = this.layers[layerIndex];
  2109. if (layer.isBackground) {
  2110. layer.render();
  2111. }
  2112. }
  2113. engine.setDepthBuffer(true);
  2114. }
  2115. // Render
  2116. Tools.StartPerformanceCounter("Main render");
  2117. // Activate HighlightLayer stencil
  2118. if (renderhighlights) {
  2119. this._engine.setStencilBuffer(true);
  2120. }
  2121. this._renderingManager.render(null, null, true, true);
  2122. // Restore HighlightLayer stencil
  2123. if (renderhighlights) {
  2124. this._engine.setStencilBuffer(stencilState);
  2125. }
  2126. Tools.EndPerformanceCounter("Main render");
  2127. // Bounding boxes
  2128. this._boundingBoxRenderer.render();
  2129. // Edges
  2130. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  2131. this._edgesRenderers.data[edgesRendererIndex].render();
  2132. }
  2133. // Lens flares
  2134. if (this.lensFlaresEnabled) {
  2135. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2136. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  2137. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  2138. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  2139. lensFlareSystem.render();
  2140. }
  2141. }
  2142. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  2143. }
  2144. // Foregrounds
  2145. if (this.layers.length) {
  2146. engine.setDepthBuffer(false);
  2147. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  2148. layer = this.layers[layerIndex];
  2149. if (!layer.isBackground) {
  2150. layer.render();
  2151. }
  2152. }
  2153. engine.setDepthBuffer(true);
  2154. }
  2155. // Highlight Layer
  2156. if (renderhighlights) {
  2157. engine.setDepthBuffer(false);
  2158. for (let i = 0; i < this.highlightLayers.length; i++) {
  2159. if (this.highlightLayers[i].shouldRender()) {
  2160. this.highlightLayers[i].render();
  2161. }
  2162. }
  2163. engine.setDepthBuffer(true);
  2164. }
  2165. this._renderDuration.endMonitoring(false);
  2166. // Finalize frame
  2167. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  2168. // Update camera
  2169. this.activeCamera._updateFromScene();
  2170. // Reset some special arrays
  2171. this._renderTargets.reset();
  2172. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  2173. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  2174. }
  2175. private _processSubCameras(camera: Camera): void {
  2176. if (camera.cameraRigMode === Camera.RIG_MODE_NONE) {
  2177. this._renderForCamera(camera);
  2178. return;
  2179. }
  2180. // rig cameras
  2181. for (var index = 0; index < camera._rigCameras.length; index++) {
  2182. this._renderForCamera(camera._rigCameras[index]);
  2183. }
  2184. this.activeCamera = camera;
  2185. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  2186. // Update camera
  2187. this.activeCamera._updateFromScene();
  2188. }
  2189. private _checkIntersections(): void {
  2190. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  2191. var sourceMesh = this._meshesForIntersections.data[index];
  2192. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  2193. var action = sourceMesh.actionManager.actions[actionIndex];
  2194. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2195. var parameters = action.getTriggerParameter();
  2196. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  2197. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  2198. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  2199. if (areIntersecting && currentIntersectionInProgress === -1) {
  2200. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  2201. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  2202. sourceMesh._intersectionsInProgress.push(otherMesh);
  2203. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2204. sourceMesh._intersectionsInProgress.push(otherMesh);
  2205. }
  2206. } else if (!areIntersecting && currentIntersectionInProgress > -1) {
  2207. //They intersected, and now they don't.
  2208. //is this trigger an exit trigger? execute an event.
  2209. if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2210. action._executeCurrent(ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  2211. }
  2212. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  2213. if (!sourceMesh.actionManager.hasSpecificTrigger(ActionManager.OnIntersectionExitTrigger) || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  2214. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  2215. }
  2216. }
  2217. }
  2218. }
  2219. }
  2220. }
  2221. public render(): void {
  2222. if (this.isDisposed) {
  2223. return;
  2224. }
  2225. this._lastFrameDuration.beginMonitoring();
  2226. this._particlesDuration.fetchNewFrame();
  2227. this._spritesDuration.fetchNewFrame();
  2228. this._activeParticles.fetchNewFrame();
  2229. this._renderDuration.fetchNewFrame();
  2230. this._renderTargetsDuration.fetchNewFrame();
  2231. this._evaluateActiveMeshesDuration.fetchNewFrame();
  2232. this._totalVertices.fetchNewFrame();
  2233. this._activeIndices.fetchNewFrame();
  2234. this._activeBones.fetchNewFrame();
  2235. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  2236. this._meshesForIntersections.reset();
  2237. this.resetCachedMaterial();
  2238. Tools.StartPerformanceCounter("Scene rendering");
  2239. // Actions
  2240. if (this.actionManager) {
  2241. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  2242. }
  2243. //Simplification Queue
  2244. if (this.simplificationQueue && !this.simplificationQueue.running) {
  2245. this.simplificationQueue.executeNext();
  2246. }
  2247. // Animations
  2248. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  2249. this._animationRatio = deltaTime * (60.0 / 1000.0);
  2250. this._animate();
  2251. // Physics
  2252. if (this._physicsEngine) {
  2253. Tools.StartPerformanceCounter("Physics");
  2254. this._physicsEngine._step(deltaTime / 1000.0);
  2255. Tools.EndPerformanceCounter("Physics");
  2256. }
  2257. // Before render
  2258. this.onBeforeRenderObservable.notifyObservers(this);
  2259. // Customs render targets
  2260. this._renderTargetsDuration.beginMonitoring();
  2261. var beforeRenderTargetDate = Tools.Now;
  2262. var engine = this.getEngine();
  2263. var currentActiveCamera = this.activeCamera;
  2264. if (this.renderTargetsEnabled) {
  2265. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2266. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  2267. var renderTarget = this.customRenderTargets[customIndex];
  2268. if (renderTarget._shouldRender()) {
  2269. this._renderId++;
  2270. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  2271. if (!this.activeCamera)
  2272. throw new Error("Active camera not set");
  2273. // Viewport
  2274. engine.setViewport(this.activeCamera.viewport);
  2275. // Camera
  2276. this.updateTransformMatrix();
  2277. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  2278. }
  2279. }
  2280. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  2281. this._renderId++;
  2282. }
  2283. if (this.customRenderTargets.length > 0) { // Restore back buffer
  2284. engine.restoreDefaultFramebuffer();
  2285. }
  2286. this._renderTargetsDuration.endMonitoring();
  2287. this.activeCamera = currentActiveCamera;
  2288. // Procedural textures
  2289. if (this.proceduralTexturesEnabled) {
  2290. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2291. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  2292. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  2293. if (proceduralTexture._shouldRender()) {
  2294. proceduralTexture.render();
  2295. }
  2296. }
  2297. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  2298. }
  2299. // Clear
  2300. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  2301. // Shadows
  2302. if (this.shadowsEnabled) {
  2303. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  2304. var light = this.lights[lightIndex];
  2305. var shadowGenerator = light.getShadowGenerator();
  2306. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  2307. this._renderTargets.push(shadowGenerator.getShadowMap());
  2308. }
  2309. }
  2310. }
  2311. // Depth renderer
  2312. if (this._depthRenderer) {
  2313. this._renderTargets.push(this._depthRenderer.getDepthMap());
  2314. }
  2315. // RenderPipeline
  2316. this.postProcessRenderPipelineManager.update();
  2317. // Multi-cameras?
  2318. if (this.activeCameras.length > 0) {
  2319. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  2320. if (cameraIndex > 0) {
  2321. this._engine.clear(null, false, true, true);
  2322. }
  2323. this._processSubCameras(this.activeCameras[cameraIndex]);
  2324. }
  2325. } else {
  2326. if (!this.activeCamera) {
  2327. throw new Error("No camera defined");
  2328. }
  2329. this._processSubCameras(this.activeCamera);
  2330. }
  2331. // Intersection checks
  2332. this._checkIntersections();
  2333. // Update the audio listener attached to the camera
  2334. if (AudioEngine) {
  2335. this._updateAudioParameters();
  2336. }
  2337. // After render
  2338. if (this.afterRender) {
  2339. this.afterRender();
  2340. }
  2341. this.onAfterRenderObservable.notifyObservers(this);
  2342. // Cleaning
  2343. for (var index = 0; index < this._toBeDisposed.length; index++) {
  2344. this._toBeDisposed.data[index].dispose();
  2345. this._toBeDisposed[index] = null;
  2346. }
  2347. this._toBeDisposed.reset();
  2348. if (this.dumpNextRenderTargets) {
  2349. this.dumpNextRenderTargets = false;
  2350. }
  2351. Tools.EndPerformanceCounter("Scene rendering");
  2352. this._lastFrameDuration.endMonitoring();
  2353. this._totalMeshesCounter.addCount(this.meshes.length, true);
  2354. this._totalLightsCounter.addCount(this.lights.length, true);
  2355. this._totalMaterialsCounter.addCount(this.materials.length, true);
  2356. this._totalTexturesCounter.addCount(this.textures.length, true);
  2357. this._activeBones.addCount(0, true);
  2358. this._activeIndices.addCount(0, true);
  2359. this._activeParticles.addCount(0, true);
  2360. }
  2361. private _updateAudioParameters() {
  2362. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  2363. return;
  2364. }
  2365. var listeningCamera: Camera;
  2366. var audioEngine = Engine.audioEngine;
  2367. if (this.activeCameras.length > 0) {
  2368. listeningCamera = this.activeCameras[0];
  2369. } else {
  2370. listeningCamera = this.activeCamera;
  2371. }
  2372. if (listeningCamera && audioEngine.canUseWebAudio) {
  2373. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  2374. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  2375. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  2376. cameraDirection.normalize();
  2377. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  2378. var i: number;
  2379. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2380. var sound = this.mainSoundTrack.soundCollection[i];
  2381. if (sound.useCustomAttenuation) {
  2382. sound.updateDistanceFromListener();
  2383. }
  2384. }
  2385. for (i = 0; i < this.soundTracks.length; i++) {
  2386. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2387. sound = this.soundTracks[i].soundCollection[j];
  2388. if (sound.useCustomAttenuation) {
  2389. sound.updateDistanceFromListener();
  2390. }
  2391. }
  2392. }
  2393. }
  2394. }
  2395. // Audio
  2396. public get audioEnabled(): boolean {
  2397. return this._audioEnabled;
  2398. }
  2399. public set audioEnabled(value: boolean) {
  2400. this._audioEnabled = value;
  2401. if (AudioEngine) {
  2402. if (this._audioEnabled) {
  2403. this._enableAudio();
  2404. }
  2405. else {
  2406. this._disableAudio();
  2407. }
  2408. }
  2409. }
  2410. private _disableAudio() {
  2411. var i: number;
  2412. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2413. this.mainSoundTrack.soundCollection[i].pause();
  2414. }
  2415. for (i = 0; i < this.soundTracks.length; i++) {
  2416. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2417. this.soundTracks[i].soundCollection[j].pause();
  2418. }
  2419. }
  2420. }
  2421. private _enableAudio() {
  2422. var i: number;
  2423. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2424. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  2425. this.mainSoundTrack.soundCollection[i].play();
  2426. }
  2427. }
  2428. for (i = 0; i < this.soundTracks.length; i++) {
  2429. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2430. if (this.soundTracks[i].soundCollection[j].isPaused) {
  2431. this.soundTracks[i].soundCollection[j].play();
  2432. }
  2433. }
  2434. }
  2435. }
  2436. public get headphone(): boolean {
  2437. return this._headphone;
  2438. }
  2439. public set headphone(value: boolean) {
  2440. this._headphone = value;
  2441. if (AudioEngine) {
  2442. if (this._headphone) {
  2443. this._switchAudioModeForHeadphones();
  2444. }
  2445. else {
  2446. this._switchAudioModeForNormalSpeakers();
  2447. }
  2448. }
  2449. }
  2450. private _switchAudioModeForHeadphones() {
  2451. this.mainSoundTrack.switchPanningModelToHRTF();
  2452. for (var i = 0; i < this.soundTracks.length; i++) {
  2453. this.soundTracks[i].switchPanningModelToHRTF();
  2454. }
  2455. }
  2456. private _switchAudioModeForNormalSpeakers() {
  2457. this.mainSoundTrack.switchPanningModelToEqualPower();
  2458. for (var i = 0; i < this.soundTracks.length; i++) {
  2459. this.soundTracks[i].switchPanningModelToEqualPower();
  2460. }
  2461. }
  2462. public enableDepthRenderer(): DepthRenderer {
  2463. if (this._depthRenderer) {
  2464. return this._depthRenderer;
  2465. }
  2466. this._depthRenderer = new DepthRenderer(this);
  2467. return this._depthRenderer;
  2468. }
  2469. public disableDepthRenderer(): void {
  2470. if (!this._depthRenderer) {
  2471. return;
  2472. }
  2473. this._depthRenderer.dispose();
  2474. this._depthRenderer = null;
  2475. }
  2476. public freezeMaterials(): void {
  2477. for (var i = 0; i < this.materials.length; i++) {
  2478. this.materials[i].freeze();
  2479. }
  2480. }
  2481. public unfreezeMaterials(): void {
  2482. for (var i = 0; i < this.materials.length; i++) {
  2483. this.materials[i].unfreeze();
  2484. }
  2485. }
  2486. public dispose(): void {
  2487. this.beforeRender = null;
  2488. this.afterRender = null;
  2489. this.skeletons = [];
  2490. this._boundingBoxRenderer.dispose();
  2491. if (this._depthRenderer) {
  2492. this._depthRenderer.dispose();
  2493. }
  2494. // Smart arrays
  2495. if (this.activeCamera) {
  2496. this.activeCamera._activeMeshes.dispose();
  2497. this.activeCamera = null;
  2498. }
  2499. this._activeMeshes.dispose();
  2500. this._renderingManager.dispose();
  2501. this._processedMaterials.dispose();
  2502. this._activeParticleSystems.dispose();
  2503. this._activeSkeletons.dispose();
  2504. this._softwareSkinnedMeshes.dispose();
  2505. this._boundingBoxRenderer.dispose();
  2506. this._edgesRenderers.dispose();
  2507. this._meshesForIntersections.dispose();
  2508. this._toBeDisposed.dispose();
  2509. // Debug layer
  2510. if (this._debugLayer) {
  2511. this._debugLayer.hide();
  2512. }
  2513. // Events
  2514. this.onDisposeObservable.notifyObservers(this);
  2515. this.onDisposeObservable.clear();
  2516. this.onBeforeRenderObservable.clear();
  2517. this.onAfterRenderObservable.clear();
  2518. this.detachControl();
  2519. // Release sounds & sounds tracks
  2520. if (AudioEngine) {
  2521. this.disposeSounds();
  2522. }
  2523. // Detach cameras
  2524. var canvas = this._engine.getRenderingCanvas();
  2525. var index;
  2526. for (index = 0; index < this.cameras.length; index++) {
  2527. this.cameras[index].detachControl(canvas);
  2528. }
  2529. // Release lights
  2530. while (this.lights.length) {
  2531. this.lights[0].dispose();
  2532. }
  2533. // Release meshes
  2534. while (this.meshes.length) {
  2535. this.meshes[0].dispose(true);
  2536. }
  2537. // Release cameras
  2538. while (this.cameras.length) {
  2539. this.cameras[0].dispose();
  2540. }
  2541. // Release materials
  2542. while (this.materials.length) {
  2543. this.materials[0].dispose();
  2544. }
  2545. // Release particles
  2546. while (this.particleSystems.length) {
  2547. this.particleSystems[0].dispose();
  2548. }
  2549. // Release sprites
  2550. while (this.spriteManagers.length) {
  2551. this.spriteManagers[0].dispose();
  2552. }
  2553. // Release layers
  2554. while (this.layers.length) {
  2555. this.layers[0].dispose();
  2556. }
  2557. while (this.highlightLayers.length) {
  2558. this.highlightLayers[0].dispose();
  2559. }
  2560. // Release textures
  2561. while (this.textures.length) {
  2562. this.textures[0].dispose();
  2563. }
  2564. // Post-processes
  2565. this.postProcessManager.dispose();
  2566. // Physics
  2567. if (this._physicsEngine) {
  2568. this.disablePhysicsEngine();
  2569. }
  2570. // Remove from engine
  2571. index = this._engine.scenes.indexOf(this);
  2572. if (index > -1) {
  2573. this._engine.scenes.splice(index, 1);
  2574. }
  2575. this._engine.wipeCaches();
  2576. this._engine = null;
  2577. }
  2578. public get isDisposed(): boolean {
  2579. return !this._engine;
  2580. }
  2581. // Release sounds & sounds tracks
  2582. public disposeSounds() {
  2583. this.mainSoundTrack.dispose();
  2584. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  2585. this.soundTracks[scIndex].dispose();
  2586. }
  2587. }
  2588. // Octrees
  2589. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  2590. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2591. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2592. for (var index = 0; index < this.meshes.length; index++) {
  2593. var mesh = this.meshes[index];
  2594. mesh.computeWorldMatrix(true);
  2595. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  2596. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  2597. Tools.CheckExtends(minBox, min, max);
  2598. Tools.CheckExtends(maxBox, min, max);
  2599. }
  2600. return {
  2601. min: min,
  2602. max: max
  2603. };
  2604. }
  2605. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  2606. if (!this._selectionOctree) {
  2607. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  2608. }
  2609. var worldExtends = this.getWorldExtends();
  2610. // Update octree
  2611. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  2612. return this._selectionOctree;
  2613. }
  2614. // Picking
  2615. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera, cameraViewSpace = false): Ray {
  2616. var engine = this._engine;
  2617. if (!camera) {
  2618. if (!this.activeCamera)
  2619. throw new Error("Active camera not set");
  2620. camera = this.activeCamera;
  2621. }
  2622. var cameraViewport = camera.viewport;
  2623. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  2624. // Moving coordinates to local viewport world
  2625. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  2626. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  2627. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), cameraViewSpace ? Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  2628. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  2629. }
  2630. public createPickingRayInCameraSpace(x: number, y: number, camera: Camera): Ray {
  2631. var engine = this._engine;
  2632. if (!camera) {
  2633. if (!this.activeCamera)
  2634. throw new Error("Active camera not set");
  2635. camera = this.activeCamera;
  2636. }
  2637. var cameraViewport = camera.viewport;
  2638. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  2639. var identity = Matrix.Identity();
  2640. // Moving coordinates to local viewport world
  2641. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  2642. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  2643. return Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  2644. }
  2645. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  2646. var pickingInfo = null;
  2647. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  2648. var mesh = this.meshes[meshIndex];
  2649. if (predicate) {
  2650. if (!predicate(mesh)) {
  2651. continue;
  2652. }
  2653. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  2654. continue;
  2655. }
  2656. var world = mesh.getWorldMatrix();
  2657. var ray = rayFunction(world);
  2658. var result = mesh.intersects(ray, fastCheck);
  2659. if (!result || !result.hit)
  2660. continue;
  2661. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  2662. continue;
  2663. pickingInfo = result;
  2664. if (fastCheck) {
  2665. break;
  2666. }
  2667. }
  2668. return pickingInfo || new PickingInfo();
  2669. }
  2670. private _internalMultiPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean): PickingInfo[] {
  2671. var pickingInfos = new Array<PickingInfo>();
  2672. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  2673. var mesh = this.meshes[meshIndex];
  2674. if (predicate) {
  2675. if (!predicate(mesh)) {
  2676. continue;
  2677. }
  2678. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  2679. continue;
  2680. }
  2681. var world = mesh.getWorldMatrix();
  2682. var ray = rayFunction(world);
  2683. var result = mesh.intersects(ray, false);
  2684. if (!result || !result.hit)
  2685. continue;
  2686. pickingInfos.push(result);
  2687. }
  2688. return pickingInfos;
  2689. }
  2690. private _internalPickSprites(ray: Ray, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  2691. var pickingInfo = null;
  2692. camera = camera || this.activeCamera;
  2693. if (this.spriteManagers.length > 0) {
  2694. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  2695. var spriteManager = this.spriteManagers[spriteIndex];
  2696. if (!spriteManager.isPickable) {
  2697. continue;
  2698. }
  2699. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  2700. if (!result || !result.hit)
  2701. continue;
  2702. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  2703. continue;
  2704. pickingInfo = result;
  2705. if (fastCheck) {
  2706. break;
  2707. }
  2708. }
  2709. }
  2710. return pickingInfo || new PickingInfo();
  2711. }
  2712. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  2713. /// <param name="x">X position on screen</param>
  2714. /// <param name="y">Y position on screen</param>
  2715. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  2716. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  2717. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  2718. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  2719. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  2720. }
  2721. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  2722. /// <param name="x">X position on screen</param>
  2723. /// <param name="y">Y position on screen</param>
  2724. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  2725. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  2726. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  2727. public pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  2728. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  2729. }
  2730. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean): PickingInfo {
  2731. return this._internalPick(world => {
  2732. if (!this._pickWithRayInverseMatrix) {
  2733. this._pickWithRayInverseMatrix = Matrix.Identity();
  2734. }
  2735. world.invertToRef(this._pickWithRayInverseMatrix);
  2736. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  2737. }, predicate, fastCheck);
  2738. }
  2739. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  2740. /// <param name="x">X position on screen</param>
  2741. /// <param name="y">Y position on screen</param>
  2742. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  2743. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  2744. public multiPick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, camera?: Camera): PickingInfo[] {
  2745. return this._internalMultiPick(world => this.createPickingRay(x, y, world, camera), predicate);
  2746. }
  2747. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  2748. /// <param name="ray">Ray to use</param>
  2749. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  2750. public multiPickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean): PickingInfo[] {
  2751. return this._internalMultiPick(world => {
  2752. if (!this._pickWithRayInverseMatrix) {
  2753. this._pickWithRayInverseMatrix = Matrix.Identity();
  2754. }
  2755. world.invertToRef(this._pickWithRayInverseMatrix);
  2756. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  2757. }, predicate);
  2758. }
  2759. public setPointerOverMesh(mesh: AbstractMesh): void {
  2760. if (this._pointerOverMesh === mesh) {
  2761. return;
  2762. }
  2763. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  2764. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  2765. }
  2766. this._pointerOverMesh = mesh;
  2767. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  2768. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  2769. }
  2770. }
  2771. public getPointerOverMesh(): AbstractMesh {
  2772. return this._pointerOverMesh;
  2773. }
  2774. public setPointerOverSprite(sprite: Sprite): void {
  2775. if (this._pointerOverSprite === sprite) {
  2776. return;
  2777. }
  2778. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  2779. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  2780. }
  2781. this._pointerOverSprite = sprite;
  2782. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  2783. this._pointerOverSprite.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  2784. }
  2785. }
  2786. public getPointerOverSprite(): Sprite {
  2787. return this._pointerOverSprite;
  2788. }
  2789. // Physics
  2790. public getPhysicsEngine(): PhysicsEngine {
  2791. return this._physicsEngine;
  2792. }
  2793. /**
  2794. * Enables physics to the current scene
  2795. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  2796. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  2797. * @return {boolean} was the physics engine initialized
  2798. */
  2799. public enablePhysics(gravity?: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  2800. if (this._physicsEngine) {
  2801. return true;
  2802. }
  2803. try {
  2804. this._physicsEngine = new PhysicsEngine(gravity, plugin);
  2805. return true;
  2806. } catch (e) {
  2807. Tools.Error(e.message);
  2808. return false;
  2809. }
  2810. }
  2811. public disablePhysicsEngine(): void {
  2812. if (!this._physicsEngine) {
  2813. return;
  2814. }
  2815. this._physicsEngine.dispose();
  2816. this._physicsEngine = undefined;
  2817. }
  2818. public isPhysicsEnabled(): boolean {
  2819. return this._physicsEngine !== undefined;
  2820. }
  2821. public deleteCompoundImpostor(compound: any): void {
  2822. var mesh: AbstractMesh = compound.parts[0].mesh;
  2823. mesh.physicsImpostor.dispose(/*true*/);
  2824. mesh.physicsImpostor = null;
  2825. }
  2826. // Misc.
  2827. public createDefaultCameraOrLight(createArcRotateCamera = false) {
  2828. // Light
  2829. if (this.lights.length === 0) {
  2830. new HemisphericLight("default light", Vector3.Up(), this);
  2831. }
  2832. // Camera
  2833. if (!this.activeCamera) {
  2834. // Compute position
  2835. var worldExtends = this.getWorldExtends();
  2836. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  2837. var camera;
  2838. if (createArcRotateCamera) {
  2839. camera = new ArcRotateCamera("default camera", 0, 0, 10, Vector3.Zero(), this);
  2840. camera.setPosition(new Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  2841. camera.setTarget(worldCenter);
  2842. } else {
  2843. camera = new FreeCamera("default camera", Vector3.Zero(), this);
  2844. camera.position = new Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  2845. camera.setTarget(worldCenter);
  2846. }
  2847. this.activeCamera = camera;
  2848. }
  2849. }
  2850. // Tags
  2851. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  2852. if (tagsQuery === undefined) {
  2853. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  2854. return list;
  2855. }
  2856. var listByTags = [];
  2857. forEach = forEach || ((item: any) => { return; });
  2858. for (var i in list) {
  2859. var item = list[i];
  2860. if (Tags.MatchesQuery(item, tagsQuery)) {
  2861. listByTags.push(item);
  2862. forEach(item);
  2863. }
  2864. }
  2865. return listByTags;
  2866. }
  2867. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  2868. return this._getByTags(this.meshes, tagsQuery, forEach);
  2869. }
  2870. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  2871. return this._getByTags(this.cameras, tagsQuery, forEach);
  2872. }
  2873. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  2874. return this._getByTags(this.lights, tagsQuery, forEach);
  2875. }
  2876. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  2877. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  2878. }
  2879. /**
  2880. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  2881. * This allowed control for front to back rendering or reversly depending of the special needs.
  2882. *
  2883. * @param renderingGroupId The rendering group id corresponding to its index
  2884. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  2885. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  2886. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  2887. */
  2888. public setRenderingOrder(renderingGroupId: number,
  2889. opaqueSortCompareFn: (a: SubMesh, b: SubMesh) => number = null,
  2890. alphaTestSortCompareFn: (a: SubMesh, b: SubMesh) => number = null,
  2891. transparentSortCompareFn: (a: SubMesh, b: SubMesh) => number = null): void {
  2892. this._renderingManager.setRenderingOrder(renderingGroupId,
  2893. opaqueSortCompareFn,
  2894. alphaTestSortCompareFn,
  2895. transparentSortCompareFn);
  2896. }
  2897. /**
  2898. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  2899. *
  2900. * @param renderingGroupId The rendering group id corresponding to its index
  2901. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  2902. * @param depth Automatically clears depth between groups if true and autoClear is true.
  2903. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  2904. */
  2905. public setRenderingAutoClearDepthStencil(renderingGroupId: number, autoClearDepthStencil: boolean,
  2906. depth = true,
  2907. stencil = true): void {
  2908. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  2909. }
  2910. /**
  2911. * Will flag all materials as dirty to trigger new shader compilation
  2912. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  2913. */
  2914. public markAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  2915. for (var material of this.materials) {
  2916. if (predicate && !predicate(material)) {
  2917. continue;
  2918. }
  2919. material.markAsDirty(flag);
  2920. }
  2921. }
  2922. }
  2923. }