babylon.scene.ts 141 KB

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