babylon.scene.ts 154 KB

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