webvr-polyfill.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331
  1. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. /*
  3. * Copyright 2015 Google Inc. All Rights Reserved.
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /**
  17. * The base class for all VR devices.
  18. */
  19. function VRDevice() {
  20. this.hardwareUnitId = 'webvr-polyfill hardwareUnitId';
  21. this.deviceId = 'webvr-polyfill deviceId';
  22. this.deviceName = 'webvr-polyfill deviceName';
  23. }
  24. /**
  25. * The base class for all VR HMD devices.
  26. */
  27. function HMDVRDevice() {
  28. }
  29. HMDVRDevice.prototype = new VRDevice();
  30. /**
  31. * The base class for all VR position sensor devices.
  32. */
  33. function PositionSensorVRDevice() {
  34. }
  35. PositionSensorVRDevice.prototype = new VRDevice();
  36. module.exports.VRDevice = VRDevice;
  37. module.exports.HMDVRDevice = HMDVRDevice;
  38. module.exports.PositionSensorVRDevice = PositionSensorVRDevice;
  39. },{}],2:[function(_dereq_,module,exports){
  40. /*
  41. * Copyright 2015 Google Inc. All Rights Reserved.
  42. * Licensed under the Apache License, Version 2.0 (the "License");
  43. * you may not use this file except in compliance with the License.
  44. * You may obtain a copy of the License at
  45. *
  46. * http://www.apache.org/licenses/LICENSE-2.0
  47. *
  48. * Unless required by applicable law or agreed to in writing, software
  49. * distributed under the License is distributed on an "AS IS" BASIS,
  50. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  51. * See the License for the specific language governing permissions and
  52. * limitations under the License.
  53. */
  54. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  55. // Constants from vrtoolkit: https://github.com/googlesamples/cardboard-java.
  56. var DEFAULT_INTERPUPILLARY_DISTANCE = 0.06;
  57. var DEFAULT_FIELD_OF_VIEW = 40;
  58. var Eye = {
  59. LEFT: 'left',
  60. RIGHT: 'right'
  61. };
  62. /**
  63. * The HMD itself, providing rendering parameters.
  64. */
  65. function CardboardHMDVRDevice() {
  66. // From com/google/vrtoolkit/cardboard/FieldOfView.java.
  67. this.setMonocularFieldOfView_(DEFAULT_FIELD_OF_VIEW);
  68. // Set display constants.
  69. this.setInterpupillaryDistance(DEFAULT_INTERPUPILLARY_DISTANCE);
  70. }
  71. CardboardHMDVRDevice.prototype = new HMDVRDevice();
  72. CardboardHMDVRDevice.prototype.getEyeParameters = function(whichEye) {
  73. var eyeTranslation;
  74. var fieldOfView;
  75. var renderRect;
  76. if (whichEye == Eye.LEFT) {
  77. eyeTranslation = this.eyeTranslationLeft;
  78. fieldOfView = this.fieldOfViewLeft;
  79. renderRect = this.renderRectLeft;
  80. } else if (whichEye == Eye.RIGHT) {
  81. eyeTranslation = this.eyeTranslationRight;
  82. fieldOfView = this.fieldOfViewRight;
  83. renderRect = this.renderRectRight;
  84. } else {
  85. console.error('Invalid eye provided: %s', whichEye);
  86. return null;
  87. }
  88. return {
  89. recommendedFieldOfView: fieldOfView,
  90. eyeTranslation: eyeTranslation,
  91. renderRect: renderRect
  92. };
  93. };
  94. /**
  95. * Sets the field of view for both eyes. This is according to WebVR spec:
  96. *
  97. * @param {FieldOfView} opt_fovLeft Field of view of the left eye.
  98. * @param {FieldOfView} opt_fovRight Field of view of the right eye.
  99. * @param {Number} opt_zNear The near plane.
  100. * @param {Number} opt_zFar The far plane.
  101. *
  102. * http://mozvr.github.io/webvr-spec/webvr.html#dom-hmdvrdevice-setfieldofviewleftfov-rightfov-znear-zfar
  103. */
  104. CardboardHMDVRDevice.prototype.setFieldOfView =
  105. function(opt_fovLeft, opt_fovRight, opt_zNear, opt_zFar) {
  106. if (opt_fovLeft) {
  107. this.fieldOfViewLeft = opt_fovLeft;
  108. }
  109. if (opt_fovRight) {
  110. this.fieldOfViewRight = opt_fovRight;
  111. }
  112. if (opt_zNear) {
  113. this.zNear = opt_zNear;
  114. }
  115. if (opt_zFar) {
  116. this.zFar = opt_zFar;
  117. }
  118. };
  119. /**
  120. * Changes the interpupillary distance of the rendered scene. This is useful for
  121. * changing Cardboard viewers.
  122. *
  123. * Possibly a useful addition to the WebVR spec?
  124. *
  125. * @param {Number} ipd Distance between eyes.
  126. */
  127. CardboardHMDVRDevice.prototype.setInterpupillaryDistance = function(ipd) {
  128. this.eyeTranslationLeft = {
  129. x: ipd * -0.5,
  130. y: 0,
  131. z: 0
  132. };
  133. this.eyeTranslationRight = {
  134. x: ipd * 0.5,
  135. y: 0,
  136. z: 0
  137. };
  138. };
  139. /**
  140. * Changes the render rect (ie. viewport) where each eye is rendered. Again,
  141. * useful for changing Cardboard viewers.
  142. *
  143. * @param {Rect} opt_rectLeft Viewport for left eye.
  144. * @param {Rect} opt_rectRight Viewport for right eye.
  145. */
  146. CardboardHMDVRDevice.prototype.setRenderRect = function(opt_rectLeft, opt_rectRight) {
  147. if (opt_rectLeft) {
  148. this.renderRectLeft = opt_rectLeft;
  149. }
  150. if (opt_rectRight) {
  151. this.renderRectRight = opt_rectRight;
  152. }
  153. };
  154. /**
  155. * Sets a symmetrical field of view for both eyes, with just one angle.
  156. *
  157. * @param {Number} angle Angle in degrees of left, right, top and bottom for
  158. * both eyes.
  159. */
  160. CardboardHMDVRDevice.prototype.setMonocularFieldOfView_ = function(angle) {
  161. this.setFieldOfView(this.createSymmetricalFieldOfView_(angle),
  162. this.createSymmetricalFieldOfView_(angle));
  163. };
  164. CardboardHMDVRDevice.prototype.createSymmetricalFieldOfView_ = function(angle) {
  165. return {
  166. upDegrees: angle,
  167. downDegrees: angle,
  168. leftDegrees: angle,
  169. rightDegrees: angle
  170. };
  171. };
  172. module.exports = CardboardHMDVRDevice;
  173. },{"./base.js":1}],3:[function(_dereq_,module,exports){
  174. /*
  175. * Copyright 2015 Google Inc. All Rights Reserved.
  176. * Licensed under the Apache License, Version 2.0 (the "License");
  177. * you may not use this file except in compliance with the License.
  178. * You may obtain a copy of the License at
  179. *
  180. * http://www.apache.org/licenses/LICENSE-2.0
  181. *
  182. * Unless required by applicable law or agreed to in writing, software
  183. * distributed under the License is distributed on an "AS IS" BASIS,
  184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  185. * See the License for the specific language governing permissions and
  186. * limitations under the License.
  187. */
  188. /**
  189. * TODO: Fix up all "new THREE" instantiations to improve performance.
  190. */
  191. var SensorSample = _dereq_('./sensor-sample.js');
  192. var THREE = _dereq_('./three-math.js');
  193. var Util = _dereq_('./util.js');
  194. var DEBUG = false;
  195. /**
  196. * An implementation of a simple complementary filter, which fuses gyroscope and
  197. * accelerometer data from the 'devicemotion' event.
  198. *
  199. * Accelerometer data is very noisy, but stable over the long term.
  200. * Gyroscope data is smooth, but tends to drift over the long term.
  201. *
  202. * This fusion is relatively simple:
  203. * 1. Get orientation estimates from accelerometer by applying a low-pass filter
  204. * on that data.
  205. * 2. Get orientation estimates from gyroscope by integrating over time.
  206. * 3. Combine the two estimates, weighing (1) in the long term, but (2) for the
  207. * short term.
  208. */
  209. function ComplementaryFilter(kFilter) {
  210. this.kFilter = kFilter;
  211. // Raw sensor measurements.
  212. this.currentAccelMeasurement = new SensorSample();
  213. this.currentGyroMeasurement = new SensorSample();
  214. this.previousGyroMeasurement = new SensorSample();
  215. // Current filter orientation
  216. this.filterQ = new THREE.Quaternion();
  217. this.previousFilterQ = new THREE.Quaternion();
  218. // Orientation based on the accelerometer.
  219. this.accelQ = new THREE.Quaternion();
  220. // Whether or not the orientation has been initialized.
  221. this.isOrientationInitialized = false;
  222. // Running estimate of gravity based on the current orientation.
  223. this.estimatedGravity = new THREE.Vector3();
  224. // Measured gravity based on accelerometer.
  225. this.measuredGravity = new THREE.Vector3();
  226. // Debug only quaternion of gyro-based orientation.
  227. this.gyroIntegralQ = new THREE.Quaternion();
  228. }
  229. ComplementaryFilter.prototype.addAccelMeasurement = function(vector, timestampS) {
  230. this.currentAccelMeasurement.set(vector, timestampS);
  231. };
  232. ComplementaryFilter.prototype.addGyroMeasurement = function(vector, timestampS) {
  233. this.currentGyroMeasurement.set(vector, timestampS);
  234. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  235. if (Util.isTimestampDeltaValid(deltaT)) {
  236. this.run_();
  237. }
  238. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  239. };
  240. ComplementaryFilter.prototype.run_ = function() {
  241. if (!this.isOrientationInitialized) {
  242. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  243. this.previousFilterQ.copy(this.accelQ);
  244. this.isOrientationInitialized = true;
  245. return;
  246. }
  247. var deltaT = this.currentGyroMeasurement.timestampS -
  248. this.previousGyroMeasurement.timestampS;
  249. // Convert gyro rotation vector to a quaternion delta.
  250. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  251. this.gyroIntegralQ.multiply(gyroDeltaQ);
  252. // filter_1 = K * (filter_0 + gyro * dT) + (1 - K) * accel.
  253. this.filterQ.copy(this.previousFilterQ);
  254. this.filterQ.multiply(gyroDeltaQ);
  255. // Calculate the delta between the current estimated gravity and the real
  256. // gravity vector from accelerometer.
  257. var invFilterQ = new THREE.Quaternion();
  258. invFilterQ.copy(this.filterQ);
  259. invFilterQ.inverse();
  260. this.estimatedGravity.set(0, 0, -1);
  261. this.estimatedGravity.applyQuaternion(invFilterQ);
  262. this.estimatedGravity.normalize();
  263. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  264. this.measuredGravity.normalize();
  265. // Compare estimated gravity with measured gravity, get the delta quaternion
  266. // between the two.
  267. var deltaQ = new THREE.Quaternion();
  268. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  269. deltaQ.inverse();
  270. if (DEBUG) {
  271. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)',
  272. THREE.Math.radToDeg(Util.getQuaternionAngle(deltaQ)),
  273. (this.estimatedGravity.x).toFixed(1),
  274. (this.estimatedGravity.y).toFixed(1),
  275. (this.estimatedGravity.z).toFixed(1),
  276. (this.measuredGravity.x).toFixed(1),
  277. (this.measuredGravity.y).toFixed(1),
  278. (this.measuredGravity.z).toFixed(1));
  279. }
  280. // Calculate the SLERP target: current orientation plus the measured-estimated
  281. // quaternion delta.
  282. var targetQ = new THREE.Quaternion();
  283. targetQ.copy(this.filterQ);
  284. targetQ.multiply(deltaQ);
  285. // SLERP factor: 0 is pure gyro, 1 is pure accel.
  286. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  287. this.previousFilterQ.copy(this.filterQ);
  288. };
  289. ComplementaryFilter.prototype.getOrientation = function() {
  290. return this.filterQ;
  291. };
  292. ComplementaryFilter.prototype.accelToQuaternion_ = function(accel) {
  293. var normAccel = new THREE.Vector3();
  294. normAccel.copy(accel);
  295. normAccel.normalize();
  296. var quat = new THREE.Quaternion();
  297. quat.setFromUnitVectors(new THREE.Vector3(0, 0, -1), normAccel);
  298. quat.inverse();
  299. return quat;
  300. };
  301. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function(gyro, dt) {
  302. // Extract axis and angle from the gyroscope data.
  303. var quat = new THREE.Quaternion();
  304. var axis = new THREE.Vector3();
  305. axis.copy(gyro);
  306. axis.normalize();
  307. quat.setFromAxisAngle(axis, gyro.length() * dt);
  308. return quat;
  309. };
  310. module.exports = ComplementaryFilter;
  311. },{"./sensor-sample.js":8,"./three-math.js":9,"./util.js":11}],4:[function(_dereq_,module,exports){
  312. /*
  313. * Copyright 2015 Google Inc. All Rights Reserved.
  314. * Licensed under the Apache License, Version 2.0 (the "License");
  315. * you may not use this file except in compliance with the License.
  316. * You may obtain a copy of the License at
  317. *
  318. * http://www.apache.org/licenses/LICENSE-2.0
  319. *
  320. * Unless required by applicable law or agreed to in writing, software
  321. * distributed under the License is distributed on an "AS IS" BASIS,
  322. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  323. * See the License for the specific language governing permissions and
  324. * limitations under the License.
  325. */
  326. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  327. var ComplementaryFilter = _dereq_('./complementary-filter.js');
  328. var PosePredictor = _dereq_('./pose-predictor.js');
  329. var TouchPanner = _dereq_('./touch-panner.js');
  330. var THREE = _dereq_('./three-math.js');
  331. var Util = _dereq_('./util.js');
  332. /**
  333. * The positional sensor, implemented using DeviceMotion APIs.
  334. */
  335. function FusionPositionSensorVRDevice() {
  336. this.deviceId = 'webvr-polyfill:fused';
  337. this.deviceName = 'VR Position Device (webvr-polyfill:fused)';
  338. this.accelerometer = new THREE.Vector3();
  339. this.gyroscope = new THREE.Vector3();
  340. window.addEventListener('devicemotion', this.onDeviceMotionChange_.bind(this));
  341. window.addEventListener('orientationchange', this.onScreenOrientationChange_.bind(this));
  342. this.filter = new ComplementaryFilter(WebVRConfig.K_FILTER || 0.98);
  343. this.posePredictor = new PosePredictor(WebVRConfig.PREDICTION_TIME_S || 0.040);
  344. this.touchPanner = new TouchPanner();
  345. this.filterToWorldQ = new THREE.Quaternion();
  346. // Set the filter to world transform, depending on OS.
  347. if (Util.isIOS()) {
  348. this.filterToWorldQ.setFromAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI/2);
  349. } else {
  350. this.filterToWorldQ.setFromAxisAngle(new THREE.Vector3(1, 0, 0), -Math.PI/2);
  351. }
  352. this.worldToScreenQ = new THREE.Quaternion();
  353. this.setScreenTransform_();
  354. // Keep track of a reset transform for resetSensor.
  355. this.resetQ = new THREE.Quaternion();
  356. this.isFirefoxAndroid = Util.isFirefoxAndroid();
  357. this.isIOS = Util.isIOS();
  358. }
  359. FusionPositionSensorVRDevice.prototype = new PositionSensorVRDevice();
  360. /**
  361. * Returns {orientation: {x,y,z,w}, position: null}.
  362. * Position is not supported since we can't do 6DOF.
  363. */
  364. FusionPositionSensorVRDevice.prototype.getState = function() {
  365. return {
  366. hasOrientation: true,
  367. orientation: this.getOrientation(),
  368. hasPosition: false,
  369. position: null
  370. }
  371. };
  372. FusionPositionSensorVRDevice.prototype.getOrientation = function() {
  373. // Convert from filter space to the the same system used by the
  374. // deviceorientation event.
  375. var orientation = this.filter.getOrientation();
  376. // Predict orientation.
  377. this.predictedQ = this.posePredictor.getPrediction(orientation, this.gyroscope, this.previousTimestampS);
  378. // Convert to THREE coordinate system: -Z forward, Y up, X right.
  379. var out = new THREE.Quaternion();
  380. out.copy(this.filterToWorldQ);
  381. out.multiply(this.resetQ);
  382. if (!WebVRConfig.TOUCH_PANNER_DISABLED) {
  383. out.multiply(this.touchPanner.getOrientation());
  384. }
  385. out.multiply(this.predictedQ);
  386. out.multiply(this.worldToScreenQ);
  387. // Handle the yaw-only case.
  388. if (WebVRConfig.YAW_ONLY) {
  389. // Make a quaternion that only turns around the Y-axis.
  390. out.x = 0;
  391. out.z = 0;
  392. out.normalize();
  393. }
  394. return out;
  395. };
  396. FusionPositionSensorVRDevice.prototype.resetSensor = function() {
  397. var euler = new THREE.Euler();
  398. euler.setFromQuaternion(this.filter.getOrientation());
  399. var yaw = euler.y;
  400. console.log('resetSensor with yaw: %f', yaw);
  401. this.resetQ.setFromAxisAngle(new THREE.Vector3(0, 0, 1), -yaw);
  402. if (!WebVRConfig.TOUCH_PANNER_DISABLED) {
  403. this.touchPanner.resetSensor();
  404. }
  405. };
  406. FusionPositionSensorVRDevice.prototype.onDeviceMotionChange_ = function(deviceMotion) {
  407. var accGravity = deviceMotion.accelerationIncludingGravity;
  408. var rotRate = deviceMotion.rotationRate;
  409. var timestampS = deviceMotion.timeStamp / 1000;
  410. // Firefox Android timeStamp returns one thousandth of a millisecond.
  411. if (this.isFirefoxAndroid) {
  412. timestampS /= 1000;
  413. }
  414. var deltaS = timestampS - this.previousTimestampS;
  415. if (deltaS <= Util.MIN_TIMESTEP || deltaS > Util.MAX_TIMESTEP) {
  416. console.warn('Invalid timestamps detected. Time step between successive ' +
  417. 'gyroscope sensor samples is very small or not monotonic');
  418. this.previousTimestampS = timestampS;
  419. return;
  420. }
  421. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  422. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  423. // With iOS and Firefox Android, rotationRate is reported in degrees,
  424. // so we first convert to radians.
  425. if (this.isIOS || this.isFirefoxAndroid) {
  426. this.gyroscope.multiplyScalar(Math.PI / 180);
  427. }
  428. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  429. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  430. this.previousTimestampS = timestampS;
  431. };
  432. FusionPositionSensorVRDevice.prototype.onScreenOrientationChange_ =
  433. function(screenOrientation) {
  434. this.setScreenTransform_();
  435. };
  436. FusionPositionSensorVRDevice.prototype.setScreenTransform_ = function() {
  437. this.worldToScreenQ.set(0, 0, 0, 1);
  438. switch (window.orientation) {
  439. case 0:
  440. break;
  441. case 90:
  442. this.worldToScreenQ.setFromAxisAngle(new THREE.Vector3(0, 0, 1), -Math.PI/2);
  443. break;
  444. case -90:
  445. this.worldToScreenQ.setFromAxisAngle(new THREE.Vector3(0, 0, 1), Math.PI/2);
  446. break;
  447. case 180:
  448. // TODO.
  449. break;
  450. }
  451. };
  452. module.exports = FusionPositionSensorVRDevice;
  453. },{"./base.js":1,"./complementary-filter.js":3,"./pose-predictor.js":7,"./three-math.js":9,"./touch-panner.js":10,"./util.js":11}],5:[function(_dereq_,module,exports){
  454. /*
  455. * Copyright 2015 Google Inc. All Rights Reserved.
  456. * Licensed under the Apache License, Version 2.0 (the "License");
  457. * you may not use this file except in compliance with the License.
  458. * You may obtain a copy of the License at
  459. *
  460. * http://www.apache.org/licenses/LICENSE-2.0
  461. *
  462. * Unless required by applicable law or agreed to in writing, software
  463. * distributed under the License is distributed on an "AS IS" BASIS,
  464. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  465. * See the License for the specific language governing permissions and
  466. * limitations under the License.
  467. */
  468. var WebVRPolyfill = _dereq_('./webvr-polyfill.js');
  469. // Initialize a WebVRConfig just in case.
  470. window.WebVRConfig = window.WebVRConfig || {};
  471. new WebVRPolyfill();
  472. },{"./webvr-polyfill.js":12}],6:[function(_dereq_,module,exports){
  473. /*
  474. * Copyright 2015 Google Inc. All Rights Reserved.
  475. * Licensed under the Apache License, Version 2.0 (the "License");
  476. * you may not use this file except in compliance with the License.
  477. * You may obtain a copy of the License at
  478. *
  479. * http://www.apache.org/licenses/LICENSE-2.0
  480. *
  481. * Unless required by applicable law or agreed to in writing, software
  482. * distributed under the License is distributed on an "AS IS" BASIS,
  483. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  484. * See the License for the specific language governing permissions and
  485. * limitations under the License.
  486. */
  487. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  488. var THREE = _dereq_('./three-math.js');
  489. var Util = _dereq_('./util.js');
  490. // How much to rotate per key stroke.
  491. var KEY_SPEED = 0.15;
  492. var KEY_ANIMATION_DURATION = 80;
  493. // How much to rotate for mouse events.
  494. var MOUSE_SPEED_X = 0.5;
  495. var MOUSE_SPEED_Y = 0.3;
  496. /**
  497. * A virtual position sensor, implemented using keyboard and
  498. * mouse APIs. This is designed as for desktops/laptops where no Device*
  499. * events work.
  500. */
  501. function MouseKeyboardPositionSensorVRDevice() {
  502. this.deviceId = 'webvr-polyfill:mouse-keyboard';
  503. this.deviceName = 'VR Position Device (webvr-polyfill:mouse-keyboard)';
  504. // Attach to mouse and keyboard events.
  505. window.addEventListener('keydown', this.onKeyDown_.bind(this));
  506. window.addEventListener('mousemove', this.onMouseMove_.bind(this));
  507. window.addEventListener('mousedown', this.onMouseDown_.bind(this));
  508. window.addEventListener('mouseup', this.onMouseUp_.bind(this));
  509. this.phi = 0;
  510. this.theta = 0;
  511. // Variables for keyboard-based rotation animation.
  512. this.targetAngle = null;
  513. // State variables for calculations.
  514. this.euler = new THREE.Euler();
  515. this.orientation = new THREE.Quaternion();
  516. // Variables for mouse-based rotation.
  517. this.rotateStart = new THREE.Vector2();
  518. this.rotateEnd = new THREE.Vector2();
  519. this.rotateDelta = new THREE.Vector2();
  520. }
  521. MouseKeyboardPositionSensorVRDevice.prototype = new PositionSensorVRDevice();
  522. /**
  523. * Returns {orientation: {x,y,z,w}, position: null}.
  524. * Position is not supported for parity with other PositionSensors.
  525. */
  526. MouseKeyboardPositionSensorVRDevice.prototype.getState = function() {
  527. this.euler.set(this.phi, this.theta, 0, 'YXZ');
  528. this.orientation.setFromEuler(this.euler);
  529. return {
  530. hasOrientation: true,
  531. orientation: this.orientation,
  532. hasPosition: false,
  533. position: null
  534. }
  535. };
  536. MouseKeyboardPositionSensorVRDevice.prototype.onKeyDown_ = function(e) {
  537. // Track WASD and arrow keys.
  538. if (e.keyCode == 38) { // Up key.
  539. this.animatePhi_(this.phi + KEY_SPEED);
  540. } else if (e.keyCode == 39) { // Right key.
  541. this.animateTheta_(this.theta - KEY_SPEED);
  542. } else if (e.keyCode == 40) { // Down key.
  543. this.animatePhi_(this.phi - KEY_SPEED);
  544. } else if (e.keyCode == 37) { // Left key.
  545. this.animateTheta_(this.theta + KEY_SPEED);
  546. }
  547. };
  548. MouseKeyboardPositionSensorVRDevice.prototype.animateTheta_ = function(targetAngle) {
  549. this.animateKeyTransitions_('theta', targetAngle);
  550. };
  551. MouseKeyboardPositionSensorVRDevice.prototype.animatePhi_ = function(targetAngle) {
  552. // Prevent looking too far up or down.
  553. targetAngle = Util.clamp(targetAngle, -Math.PI/2, Math.PI/2);
  554. this.animateKeyTransitions_('phi', targetAngle);
  555. };
  556. /**
  557. * Start an animation to transition an angle from one value to another.
  558. */
  559. MouseKeyboardPositionSensorVRDevice.prototype.animateKeyTransitions_ = function(angleName, targetAngle) {
  560. // If an animation is currently running, cancel it.
  561. if (this.angleAnimation) {
  562. clearInterval(this.angleAnimation);
  563. }
  564. var startAngle = this[angleName];
  565. var startTime = new Date();
  566. // Set up an interval timer to perform the animation.
  567. this.angleAnimation = setInterval(function() {
  568. // Once we're finished the animation, we're done.
  569. var elapsed = new Date() - startTime;
  570. if (elapsed >= KEY_ANIMATION_DURATION) {
  571. this[angleName] = targetAngle;
  572. clearInterval(this.angleAnimation);
  573. return;
  574. }
  575. // Linearly interpolate the angle some amount.
  576. var percent = elapsed / KEY_ANIMATION_DURATION;
  577. this[angleName] = startAngle + (targetAngle - startAngle) * percent;
  578. }.bind(this), 1000/60);
  579. };
  580. MouseKeyboardPositionSensorVRDevice.prototype.onMouseDown_ = function(e) {
  581. this.rotateStart.set(e.clientX, e.clientY);
  582. this.isDragging = true;
  583. };
  584. // Very similar to https://gist.github.com/mrflix/8351020
  585. MouseKeyboardPositionSensorVRDevice.prototype.onMouseMove_ = function(e) {
  586. if (!this.isDragging && !this.isPointerLocked_()) {
  587. return;
  588. }
  589. // Support pointer lock API.
  590. if (this.isPointerLocked_()) {
  591. var movementX = e.movementX || e.mozMovementX || 0;
  592. var movementY = e.movementY || e.mozMovementY || 0;
  593. this.rotateEnd.set(this.rotateStart.x - movementX, this.rotateStart.y - movementY);
  594. } else {
  595. this.rotateEnd.set(e.clientX, e.clientY);
  596. }
  597. // Calculate how much we moved in mouse space.
  598. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  599. this.rotateStart.copy(this.rotateEnd);
  600. // Keep track of the cumulative euler angles.
  601. var element = document.body;
  602. this.phi += 2 * Math.PI * this.rotateDelta.y / element.clientHeight * MOUSE_SPEED_Y;
  603. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * MOUSE_SPEED_X;
  604. // Prevent looking too far up or down.
  605. this.phi = Util.clamp(this.phi, -Math.PI/2, Math.PI/2);
  606. };
  607. MouseKeyboardPositionSensorVRDevice.prototype.onMouseUp_ = function(e) {
  608. this.isDragging = false;
  609. };
  610. MouseKeyboardPositionSensorVRDevice.prototype.isPointerLocked_ = function() {
  611. var el = document.pointerLockElement || document.mozPointerLockElement ||
  612. document.webkitPointerLockElement;
  613. return el !== undefined;
  614. };
  615. MouseKeyboardPositionSensorVRDevice.prototype.resetSensor = function() {
  616. console.error('Not implemented yet.');
  617. };
  618. module.exports = MouseKeyboardPositionSensorVRDevice;
  619. },{"./base.js":1,"./three-math.js":9,"./util.js":11}],7:[function(_dereq_,module,exports){
  620. /*
  621. * Copyright 2015 Google Inc. All Rights Reserved.
  622. * Licensed under the Apache License, Version 2.0 (the "License");
  623. * you may not use this file except in compliance with the License.
  624. * You may obtain a copy of the License at
  625. *
  626. * http://www.apache.org/licenses/LICENSE-2.0
  627. *
  628. * Unless required by applicable law or agreed to in writing, software
  629. * distributed under the License is distributed on an "AS IS" BASIS,
  630. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  631. * See the License for the specific language governing permissions and
  632. * limitations under the License.
  633. */
  634. var THREE = _dereq_('./three-math.js');
  635. var DEBUG = false;
  636. /**
  637. * Given an orientation and the gyroscope data, predicts the future orientation
  638. * of the head. This makes rendering appear faster.
  639. *
  640. * Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf
  641. *
  642. * @param {Number} predictionTimeS time from head movement to the appearance of
  643. * the corresponding image.
  644. */
  645. function PosePredictor(predictionTimeS) {
  646. this.predictionTimeS = predictionTimeS;
  647. // The quaternion corresponding to the previous state.
  648. this.previousQ = new THREE.Quaternion();
  649. // Previous time a prediction occurred.
  650. this.previousTimestampS = null;
  651. // The delta quaternion that adjusts the current pose.
  652. this.deltaQ = new THREE.Quaternion();
  653. // The output quaternion.
  654. this.outQ = new THREE.Quaternion();
  655. }
  656. PosePredictor.prototype.getPrediction = function(currentQ, gyro, timestampS) {
  657. if (!this.previousTimestampS) {
  658. this.previousQ.copy(currentQ);
  659. this.previousTimestampS = timestampS;
  660. return currentQ;
  661. }
  662. // Calculate axis and angle based on gyroscope rotation rate data.
  663. var axis = new THREE.Vector3();
  664. axis.copy(gyro);
  665. axis.normalize();
  666. var angularSpeed = gyro.length();
  667. // If we're rotating slowly, don't do prediction.
  668. if (angularSpeed < THREE.Math.degToRad(20)) {
  669. if (DEBUG) {
  670. console.log('Moving slowly, at %s deg/s: no prediction',
  671. THREE.Math.radToDeg(angularSpeed).toFixed(1));
  672. }
  673. this.outQ.copy(currentQ);
  674. this.previousQ.copy(currentQ);
  675. return this.outQ;
  676. }
  677. // Get the predicted angle based on the time delta and latency.
  678. var deltaT = timestampS - this.previousTimestampS;
  679. var predictAngle = angularSpeed * this.predictionTimeS;
  680. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  681. this.outQ.copy(this.previousQ);
  682. this.outQ.multiply(this.deltaQ);
  683. this.previousQ.copy(currentQ);
  684. return this.outQ;
  685. };
  686. module.exports = PosePredictor;
  687. },{"./three-math.js":9}],8:[function(_dereq_,module,exports){
  688. function SensorSample(sample, timestampS) {
  689. this.set(sample, timestampS);
  690. };
  691. SensorSample.prototype.set = function(sample, timestampS) {
  692. this.sample = sample;
  693. this.timestampS = timestampS;
  694. };
  695. SensorSample.prototype.copy = function(sensorSample) {
  696. this.set(sensorSample.sample, sensorSample.timestampS);
  697. };
  698. module.exports = SensorSample;
  699. },{}],9:[function(_dereq_,module,exports){
  700. /*
  701. * A subset of THREE.js, providing mostly quaternion and euler-related
  702. * operations, manually lifted from
  703. * https://github.com/mrdoob/three.js/tree/master/src/math, as of 9c30286b38df039fca389989ff06ea1c15d6bad1
  704. */
  705. // Only use if the real THREE is not provided.
  706. var THREE = window.THREE || {};
  707. // If some piece of THREE is missing, fill it in here.
  708. if (!THREE.Quaternion || !THREE.Vector3 || !THREE.Vector2 || !THREE.Euler || !THREE.Math) {
  709. console.log('No THREE.js found.');
  710. /*** START Quaternion ***/
  711. /**
  712. * @author mikael emtinger / http://gomo.se/
  713. * @author alteredq / http://alteredqualia.com/
  714. * @author WestLangley / http://github.com/WestLangley
  715. * @author bhouston / http://exocortex.com
  716. */
  717. THREE.Quaternion = function ( x, y, z, w ) {
  718. this._x = x || 0;
  719. this._y = y || 0;
  720. this._z = z || 0;
  721. this._w = ( w !== undefined ) ? w : 1;
  722. };
  723. THREE.Quaternion.prototype = {
  724. constructor: THREE.Quaternion,
  725. _x: 0,_y: 0, _z: 0, _w: 0,
  726. get x () {
  727. return this._x;
  728. },
  729. set x ( value ) {
  730. this._x = value;
  731. this.onChangeCallback();
  732. },
  733. get y () {
  734. return this._y;
  735. },
  736. set y ( value ) {
  737. this._y = value;
  738. this.onChangeCallback();
  739. },
  740. get z () {
  741. return this._z;
  742. },
  743. set z ( value ) {
  744. this._z = value;
  745. this.onChangeCallback();
  746. },
  747. get w () {
  748. return this._w;
  749. },
  750. set w ( value ) {
  751. this._w = value;
  752. this.onChangeCallback();
  753. },
  754. set: function ( x, y, z, w ) {
  755. this._x = x;
  756. this._y = y;
  757. this._z = z;
  758. this._w = w;
  759. this.onChangeCallback();
  760. return this;
  761. },
  762. copy: function ( quaternion ) {
  763. this._x = quaternion.x;
  764. this._y = quaternion.y;
  765. this._z = quaternion.z;
  766. this._w = quaternion.w;
  767. this.onChangeCallback();
  768. return this;
  769. },
  770. setFromEuler: function ( euler, update ) {
  771. if ( euler instanceof THREE.Euler === false ) {
  772. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  773. }
  774. // http://www.mathworks.com/matlabcentral/fileexchange/
  775. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  776. // content/SpinCalc.m
  777. var c1 = Math.cos( euler._x / 2 );
  778. var c2 = Math.cos( euler._y / 2 );
  779. var c3 = Math.cos( euler._z / 2 );
  780. var s1 = Math.sin( euler._x / 2 );
  781. var s2 = Math.sin( euler._y / 2 );
  782. var s3 = Math.sin( euler._z / 2 );
  783. if ( euler.order === 'XYZ' ) {
  784. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  785. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  786. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  787. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  788. } else if ( euler.order === 'YXZ' ) {
  789. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  790. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  791. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  792. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  793. } else if ( euler.order === 'ZXY' ) {
  794. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  795. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  796. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  797. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  798. } else if ( euler.order === 'ZYX' ) {
  799. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  800. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  801. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  802. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  803. } else if ( euler.order === 'YZX' ) {
  804. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  805. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  806. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  807. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  808. } else if ( euler.order === 'XZY' ) {
  809. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  810. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  811. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  812. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  813. }
  814. if ( update !== false ) this.onChangeCallback();
  815. return this;
  816. },
  817. setFromAxisAngle: function ( axis, angle ) {
  818. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  819. // assumes axis is normalized
  820. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  821. this._x = axis.x * s;
  822. this._y = axis.y * s;
  823. this._z = axis.z * s;
  824. this._w = Math.cos( halfAngle );
  825. this.onChangeCallback();
  826. return this;
  827. },
  828. setFromRotationMatrix: function ( m ) {
  829. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  830. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  831. var te = m.elements,
  832. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  833. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  834. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  835. trace = m11 + m22 + m33,
  836. s;
  837. if ( trace > 0 ) {
  838. s = 0.5 / Math.sqrt( trace + 1.0 );
  839. this._w = 0.25 / s;
  840. this._x = ( m32 - m23 ) * s;
  841. this._y = ( m13 - m31 ) * s;
  842. this._z = ( m21 - m12 ) * s;
  843. } else if ( m11 > m22 && m11 > m33 ) {
  844. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  845. this._w = ( m32 - m23 ) / s;
  846. this._x = 0.25 * s;
  847. this._y = ( m12 + m21 ) / s;
  848. this._z = ( m13 + m31 ) / s;
  849. } else if ( m22 > m33 ) {
  850. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  851. this._w = ( m13 - m31 ) / s;
  852. this._x = ( m12 + m21 ) / s;
  853. this._y = 0.25 * s;
  854. this._z = ( m23 + m32 ) / s;
  855. } else {
  856. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  857. this._w = ( m21 - m12 ) / s;
  858. this._x = ( m13 + m31 ) / s;
  859. this._y = ( m23 + m32 ) / s;
  860. this._z = 0.25 * s;
  861. }
  862. this.onChangeCallback();
  863. return this;
  864. },
  865. setFromUnitVectors: function () {
  866. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  867. // assumes direction vectors vFrom and vTo are normalized
  868. var v1, r;
  869. var EPS = 0.000001;
  870. return function ( vFrom, vTo ) {
  871. if ( v1 === undefined ) v1 = new THREE.Vector3();
  872. r = vFrom.dot( vTo ) + 1;
  873. if ( r < EPS ) {
  874. r = 0;
  875. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  876. v1.set( - vFrom.y, vFrom.x, 0 );
  877. } else {
  878. v1.set( 0, - vFrom.z, vFrom.y );
  879. }
  880. } else {
  881. v1.crossVectors( vFrom, vTo );
  882. }
  883. this._x = v1.x;
  884. this._y = v1.y;
  885. this._z = v1.z;
  886. this._w = r;
  887. this.normalize();
  888. return this;
  889. }
  890. }(),
  891. inverse: function () {
  892. this.conjugate().normalize();
  893. return this;
  894. },
  895. conjugate: function () {
  896. this._x *= - 1;
  897. this._y *= - 1;
  898. this._z *= - 1;
  899. this.onChangeCallback();
  900. return this;
  901. },
  902. dot: function ( v ) {
  903. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  904. },
  905. lengthSq: function () {
  906. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  907. },
  908. length: function () {
  909. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  910. },
  911. normalize: function () {
  912. var l = this.length();
  913. if ( l === 0 ) {
  914. this._x = 0;
  915. this._y = 0;
  916. this._z = 0;
  917. this._w = 1;
  918. } else {
  919. l = 1 / l;
  920. this._x = this._x * l;
  921. this._y = this._y * l;
  922. this._z = this._z * l;
  923. this._w = this._w * l;
  924. }
  925. this.onChangeCallback();
  926. return this;
  927. },
  928. multiply: function ( q, p ) {
  929. if ( p !== undefined ) {
  930. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  931. return this.multiplyQuaternions( q, p );
  932. }
  933. return this.multiplyQuaternions( this, q );
  934. },
  935. multiplyQuaternions: function ( a, b ) {
  936. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  937. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  938. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  939. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  940. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  941. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  942. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  943. this.onChangeCallback();
  944. return this;
  945. },
  946. multiplyVector3: function ( vector ) {
  947. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  948. return vector.applyQuaternion( this );
  949. },
  950. slerp: function ( qb, t ) {
  951. if ( t === 0 ) return this;
  952. if ( t === 1 ) return this.copy( qb );
  953. var x = this._x, y = this._y, z = this._z, w = this._w;
  954. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  955. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  956. if ( cosHalfTheta < 0 ) {
  957. this._w = - qb._w;
  958. this._x = - qb._x;
  959. this._y = - qb._y;
  960. this._z = - qb._z;
  961. cosHalfTheta = - cosHalfTheta;
  962. } else {
  963. this.copy( qb );
  964. }
  965. if ( cosHalfTheta >= 1.0 ) {
  966. this._w = w;
  967. this._x = x;
  968. this._y = y;
  969. this._z = z;
  970. return this;
  971. }
  972. var halfTheta = Math.acos( cosHalfTheta );
  973. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  974. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  975. this._w = 0.5 * ( w + this._w );
  976. this._x = 0.5 * ( x + this._x );
  977. this._y = 0.5 * ( y + this._y );
  978. this._z = 0.5 * ( z + this._z );
  979. return this;
  980. }
  981. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  982. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  983. this._w = ( w * ratioA + this._w * ratioB );
  984. this._x = ( x * ratioA + this._x * ratioB );
  985. this._y = ( y * ratioA + this._y * ratioB );
  986. this._z = ( z * ratioA + this._z * ratioB );
  987. this.onChangeCallback();
  988. return this;
  989. },
  990. equals: function ( quaternion ) {
  991. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  992. },
  993. fromArray: function ( array, offset ) {
  994. if ( offset === undefined ) offset = 0;
  995. this._x = array[ offset ];
  996. this._y = array[ offset + 1 ];
  997. this._z = array[ offset + 2 ];
  998. this._w = array[ offset + 3 ];
  999. this.onChangeCallback();
  1000. return this;
  1001. },
  1002. toArray: function ( array, offset ) {
  1003. if ( array === undefined ) array = [];
  1004. if ( offset === undefined ) offset = 0;
  1005. array[ offset ] = this._x;
  1006. array[ offset + 1 ] = this._y;
  1007. array[ offset + 2 ] = this._z;
  1008. array[ offset + 3 ] = this._w;
  1009. return array;
  1010. },
  1011. onChange: function ( callback ) {
  1012. this.onChangeCallback = callback;
  1013. return this;
  1014. },
  1015. onChangeCallback: function () {},
  1016. clone: function () {
  1017. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  1018. }
  1019. };
  1020. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  1021. return qm.copy( qa ).slerp( qb, t );
  1022. }
  1023. /*** END Quaternion ***/
  1024. /*** START Vector2 ***/
  1025. /**
  1026. * @author mrdoob / http://mrdoob.com/
  1027. * @author philogb / http://blog.thejit.org/
  1028. * @author egraether / http://egraether.com/
  1029. * @author zz85 / http://www.lab4games.net/zz85/blog
  1030. */
  1031. THREE.Vector2 = function ( x, y ) {
  1032. this.x = x || 0;
  1033. this.y = y || 0;
  1034. };
  1035. THREE.Vector2.prototype = {
  1036. constructor: THREE.Vector2,
  1037. set: function ( x, y ) {
  1038. this.x = x;
  1039. this.y = y;
  1040. return this;
  1041. },
  1042. setX: function ( x ) {
  1043. this.x = x;
  1044. return this;
  1045. },
  1046. setY: function ( y ) {
  1047. this.y = y;
  1048. return this;
  1049. },
  1050. setComponent: function ( index, value ) {
  1051. switch ( index ) {
  1052. case 0: this.x = value; break;
  1053. case 1: this.y = value; break;
  1054. default: throw new Error( 'index is out of range: ' + index );
  1055. }
  1056. },
  1057. getComponent: function ( index ) {
  1058. switch ( index ) {
  1059. case 0: return this.x;
  1060. case 1: return this.y;
  1061. default: throw new Error( 'index is out of range: ' + index );
  1062. }
  1063. },
  1064. copy: function ( v ) {
  1065. this.x = v.x;
  1066. this.y = v.y;
  1067. return this;
  1068. },
  1069. add: function ( v, w ) {
  1070. if ( w !== undefined ) {
  1071. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1072. return this.addVectors( v, w );
  1073. }
  1074. this.x += v.x;
  1075. this.y += v.y;
  1076. return this;
  1077. },
  1078. addVectors: function ( a, b ) {
  1079. this.x = a.x + b.x;
  1080. this.y = a.y + b.y;
  1081. return this;
  1082. },
  1083. addScalar: function ( s ) {
  1084. this.x += s;
  1085. this.y += s;
  1086. return this;
  1087. },
  1088. sub: function ( v, w ) {
  1089. if ( w !== undefined ) {
  1090. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1091. return this.subVectors( v, w );
  1092. }
  1093. this.x -= v.x;
  1094. this.y -= v.y;
  1095. return this;
  1096. },
  1097. subVectors: function ( a, b ) {
  1098. this.x = a.x - b.x;
  1099. this.y = a.y - b.y;
  1100. return this;
  1101. },
  1102. multiply: function ( v ) {
  1103. this.x *= v.x;
  1104. this.y *= v.y;
  1105. return this;
  1106. },
  1107. multiplyScalar: function ( s ) {
  1108. this.x *= s;
  1109. this.y *= s;
  1110. return this;
  1111. },
  1112. divide: function ( v ) {
  1113. this.x /= v.x;
  1114. this.y /= v.y;
  1115. return this;
  1116. },
  1117. divideScalar: function ( scalar ) {
  1118. if ( scalar !== 0 ) {
  1119. var invScalar = 1 / scalar;
  1120. this.x *= invScalar;
  1121. this.y *= invScalar;
  1122. } else {
  1123. this.x = 0;
  1124. this.y = 0;
  1125. }
  1126. return this;
  1127. },
  1128. min: function ( v ) {
  1129. if ( this.x > v.x ) {
  1130. this.x = v.x;
  1131. }
  1132. if ( this.y > v.y ) {
  1133. this.y = v.y;
  1134. }
  1135. return this;
  1136. },
  1137. max: function ( v ) {
  1138. if ( this.x < v.x ) {
  1139. this.x = v.x;
  1140. }
  1141. if ( this.y < v.y ) {
  1142. this.y = v.y;
  1143. }
  1144. return this;
  1145. },
  1146. clamp: function ( min, max ) {
  1147. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1148. if ( this.x < min.x ) {
  1149. this.x = min.x;
  1150. } else if ( this.x > max.x ) {
  1151. this.x = max.x;
  1152. }
  1153. if ( this.y < min.y ) {
  1154. this.y = min.y;
  1155. } else if ( this.y > max.y ) {
  1156. this.y = max.y;
  1157. }
  1158. return this;
  1159. },
  1160. clampScalar: ( function () {
  1161. var min, max;
  1162. return function ( minVal, maxVal ) {
  1163. if ( min === undefined ) {
  1164. min = new THREE.Vector2();
  1165. max = new THREE.Vector2();
  1166. }
  1167. min.set( minVal, minVal );
  1168. max.set( maxVal, maxVal );
  1169. return this.clamp( min, max );
  1170. };
  1171. } )(),
  1172. floor: function () {
  1173. this.x = Math.floor( this.x );
  1174. this.y = Math.floor( this.y );
  1175. return this;
  1176. },
  1177. ceil: function () {
  1178. this.x = Math.ceil( this.x );
  1179. this.y = Math.ceil( this.y );
  1180. return this;
  1181. },
  1182. round: function () {
  1183. this.x = Math.round( this.x );
  1184. this.y = Math.round( this.y );
  1185. return this;
  1186. },
  1187. roundToZero: function () {
  1188. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1189. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1190. return this;
  1191. },
  1192. negate: function () {
  1193. this.x = - this.x;
  1194. this.y = - this.y;
  1195. return this;
  1196. },
  1197. dot: function ( v ) {
  1198. return this.x * v.x + this.y * v.y;
  1199. },
  1200. lengthSq: function () {
  1201. return this.x * this.x + this.y * this.y;
  1202. },
  1203. length: function () {
  1204. return Math.sqrt( this.x * this.x + this.y * this.y );
  1205. },
  1206. normalize: function () {
  1207. return this.divideScalar( this.length() );
  1208. },
  1209. distanceTo: function ( v ) {
  1210. return Math.sqrt( this.distanceToSquared( v ) );
  1211. },
  1212. distanceToSquared: function ( v ) {
  1213. var dx = this.x - v.x, dy = this.y - v.y;
  1214. return dx * dx + dy * dy;
  1215. },
  1216. setLength: function ( l ) {
  1217. var oldLength = this.length();
  1218. if ( oldLength !== 0 && l !== oldLength ) {
  1219. this.multiplyScalar( l / oldLength );
  1220. }
  1221. return this;
  1222. },
  1223. lerp: function ( v, alpha ) {
  1224. this.x += ( v.x - this.x ) * alpha;
  1225. this.y += ( v.y - this.y ) * alpha;
  1226. return this;
  1227. },
  1228. equals: function ( v ) {
  1229. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1230. },
  1231. fromArray: function ( array, offset ) {
  1232. if ( offset === undefined ) offset = 0;
  1233. this.x = array[ offset ];
  1234. this.y = array[ offset + 1 ];
  1235. return this;
  1236. },
  1237. toArray: function ( array, offset ) {
  1238. if ( array === undefined ) array = [];
  1239. if ( offset === undefined ) offset = 0;
  1240. array[ offset ] = this.x;
  1241. array[ offset + 1 ] = this.y;
  1242. return array;
  1243. },
  1244. fromAttribute: function ( attribute, index, offset ) {
  1245. if ( offset === undefined ) offset = 0;
  1246. index = index * attribute.itemSize + offset;
  1247. this.x = attribute.array[ index ];
  1248. this.y = attribute.array[ index + 1 ];
  1249. return this;
  1250. },
  1251. clone: function () {
  1252. return new THREE.Vector2( this.x, this.y );
  1253. }
  1254. };
  1255. /*** END Vector2 ***/
  1256. /*** START Vector3 ***/
  1257. /**
  1258. * @author mrdoob / http://mrdoob.com/
  1259. * @author *kile / http://kile.stravaganza.org/
  1260. * @author philogb / http://blog.thejit.org/
  1261. * @author mikael emtinger / http://gomo.se/
  1262. * @author egraether / http://egraether.com/
  1263. * @author WestLangley / http://github.com/WestLangley
  1264. */
  1265. THREE.Vector3 = function ( x, y, z ) {
  1266. this.x = x || 0;
  1267. this.y = y || 0;
  1268. this.z = z || 0;
  1269. };
  1270. THREE.Vector3.prototype = {
  1271. constructor: THREE.Vector3,
  1272. set: function ( x, y, z ) {
  1273. this.x = x;
  1274. this.y = y;
  1275. this.z = z;
  1276. return this;
  1277. },
  1278. setX: function ( x ) {
  1279. this.x = x;
  1280. return this;
  1281. },
  1282. setY: function ( y ) {
  1283. this.y = y;
  1284. return this;
  1285. },
  1286. setZ: function ( z ) {
  1287. this.z = z;
  1288. return this;
  1289. },
  1290. setComponent: function ( index, value ) {
  1291. switch ( index ) {
  1292. case 0: this.x = value; break;
  1293. case 1: this.y = value; break;
  1294. case 2: this.z = value; break;
  1295. default: throw new Error( 'index is out of range: ' + index );
  1296. }
  1297. },
  1298. getComponent: function ( index ) {
  1299. switch ( index ) {
  1300. case 0: return this.x;
  1301. case 1: return this.y;
  1302. case 2: return this.z;
  1303. default: throw new Error( 'index is out of range: ' + index );
  1304. }
  1305. },
  1306. copy: function ( v ) {
  1307. this.x = v.x;
  1308. this.y = v.y;
  1309. this.z = v.z;
  1310. return this;
  1311. },
  1312. add: function ( v, w ) {
  1313. if ( w !== undefined ) {
  1314. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1315. return this.addVectors( v, w );
  1316. }
  1317. this.x += v.x;
  1318. this.y += v.y;
  1319. this.z += v.z;
  1320. return this;
  1321. },
  1322. addScalar: function ( s ) {
  1323. this.x += s;
  1324. this.y += s;
  1325. this.z += s;
  1326. return this;
  1327. },
  1328. addVectors: function ( a, b ) {
  1329. this.x = a.x + b.x;
  1330. this.y = a.y + b.y;
  1331. this.z = a.z + b.z;
  1332. return this;
  1333. },
  1334. sub: function ( v, w ) {
  1335. if ( w !== undefined ) {
  1336. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1337. return this.subVectors( v, w );
  1338. }
  1339. this.x -= v.x;
  1340. this.y -= v.y;
  1341. this.z -= v.z;
  1342. return this;
  1343. },
  1344. subVectors: function ( a, b ) {
  1345. this.x = a.x - b.x;
  1346. this.y = a.y - b.y;
  1347. this.z = a.z - b.z;
  1348. return this;
  1349. },
  1350. multiply: function ( v, w ) {
  1351. if ( w !== undefined ) {
  1352. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1353. return this.multiplyVectors( v, w );
  1354. }
  1355. this.x *= v.x;
  1356. this.y *= v.y;
  1357. this.z *= v.z;
  1358. return this;
  1359. },
  1360. multiplyScalar: function ( scalar ) {
  1361. this.x *= scalar;
  1362. this.y *= scalar;
  1363. this.z *= scalar;
  1364. return this;
  1365. },
  1366. multiplyVectors: function ( a, b ) {
  1367. this.x = a.x * b.x;
  1368. this.y = a.y * b.y;
  1369. this.z = a.z * b.z;
  1370. return this;
  1371. },
  1372. applyEuler: function () {
  1373. var quaternion;
  1374. return function ( euler ) {
  1375. if ( euler instanceof THREE.Euler === false ) {
  1376. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1377. }
  1378. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1379. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1380. return this;
  1381. };
  1382. }(),
  1383. applyAxisAngle: function () {
  1384. var quaternion;
  1385. return function ( axis, angle ) {
  1386. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1387. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1388. return this;
  1389. };
  1390. }(),
  1391. applyMatrix3: function ( m ) {
  1392. var x = this.x;
  1393. var y = this.y;
  1394. var z = this.z;
  1395. var e = m.elements;
  1396. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1397. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1398. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1399. return this;
  1400. },
  1401. applyMatrix4: function ( m ) {
  1402. // input: THREE.Matrix4 affine matrix
  1403. var x = this.x, y = this.y, z = this.z;
  1404. var e = m.elements;
  1405. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1406. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1407. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1408. return this;
  1409. },
  1410. applyProjection: function ( m ) {
  1411. // input: THREE.Matrix4 projection matrix
  1412. var x = this.x, y = this.y, z = this.z;
  1413. var e = m.elements;
  1414. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1415. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1416. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1417. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1418. return this;
  1419. },
  1420. applyQuaternion: function ( q ) {
  1421. var x = this.x;
  1422. var y = this.y;
  1423. var z = this.z;
  1424. var qx = q.x;
  1425. var qy = q.y;
  1426. var qz = q.z;
  1427. var qw = q.w;
  1428. // calculate quat * vector
  1429. var ix = qw * x + qy * z - qz * y;
  1430. var iy = qw * y + qz * x - qx * z;
  1431. var iz = qw * z + qx * y - qy * x;
  1432. var iw = - qx * x - qy * y - qz * z;
  1433. // calculate result * inverse quat
  1434. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1435. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1436. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1437. return this;
  1438. },
  1439. project: function () {
  1440. var matrix;
  1441. return function ( camera ) {
  1442. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1443. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1444. return this.applyProjection( matrix );
  1445. };
  1446. }(),
  1447. unproject: function () {
  1448. var matrix;
  1449. return function ( camera ) {
  1450. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1451. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1452. return this.applyProjection( matrix );
  1453. };
  1454. }(),
  1455. transformDirection: function ( m ) {
  1456. // input: THREE.Matrix4 affine matrix
  1457. // vector interpreted as a direction
  1458. var x = this.x, y = this.y, z = this.z;
  1459. var e = m.elements;
  1460. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1461. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1462. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1463. this.normalize();
  1464. return this;
  1465. },
  1466. divide: function ( v ) {
  1467. this.x /= v.x;
  1468. this.y /= v.y;
  1469. this.z /= v.z;
  1470. return this;
  1471. },
  1472. divideScalar: function ( scalar ) {
  1473. if ( scalar !== 0 ) {
  1474. var invScalar = 1 / scalar;
  1475. this.x *= invScalar;
  1476. this.y *= invScalar;
  1477. this.z *= invScalar;
  1478. } else {
  1479. this.x = 0;
  1480. this.y = 0;
  1481. this.z = 0;
  1482. }
  1483. return this;
  1484. },
  1485. min: function ( v ) {
  1486. if ( this.x > v.x ) {
  1487. this.x = v.x;
  1488. }
  1489. if ( this.y > v.y ) {
  1490. this.y = v.y;
  1491. }
  1492. if ( this.z > v.z ) {
  1493. this.z = v.z;
  1494. }
  1495. return this;
  1496. },
  1497. max: function ( v ) {
  1498. if ( this.x < v.x ) {
  1499. this.x = v.x;
  1500. }
  1501. if ( this.y < v.y ) {
  1502. this.y = v.y;
  1503. }
  1504. if ( this.z < v.z ) {
  1505. this.z = v.z;
  1506. }
  1507. return this;
  1508. },
  1509. clamp: function ( min, max ) {
  1510. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1511. if ( this.x < min.x ) {
  1512. this.x = min.x;
  1513. } else if ( this.x > max.x ) {
  1514. this.x = max.x;
  1515. }
  1516. if ( this.y < min.y ) {
  1517. this.y = min.y;
  1518. } else if ( this.y > max.y ) {
  1519. this.y = max.y;
  1520. }
  1521. if ( this.z < min.z ) {
  1522. this.z = min.z;
  1523. } else if ( this.z > max.z ) {
  1524. this.z = max.z;
  1525. }
  1526. return this;
  1527. },
  1528. clampScalar: ( function () {
  1529. var min, max;
  1530. return function ( minVal, maxVal ) {
  1531. if ( min === undefined ) {
  1532. min = new THREE.Vector3();
  1533. max = new THREE.Vector3();
  1534. }
  1535. min.set( minVal, minVal, minVal );
  1536. max.set( maxVal, maxVal, maxVal );
  1537. return this.clamp( min, max );
  1538. };
  1539. } )(),
  1540. floor: function () {
  1541. this.x = Math.floor( this.x );
  1542. this.y = Math.floor( this.y );
  1543. this.z = Math.floor( this.z );
  1544. return this;
  1545. },
  1546. ceil: function () {
  1547. this.x = Math.ceil( this.x );
  1548. this.y = Math.ceil( this.y );
  1549. this.z = Math.ceil( this.z );
  1550. return this;
  1551. },
  1552. round: function () {
  1553. this.x = Math.round( this.x );
  1554. this.y = Math.round( this.y );
  1555. this.z = Math.round( this.z );
  1556. return this;
  1557. },
  1558. roundToZero: function () {
  1559. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1560. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1561. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1562. return this;
  1563. },
  1564. negate: function () {
  1565. this.x = - this.x;
  1566. this.y = - this.y;
  1567. this.z = - this.z;
  1568. return this;
  1569. },
  1570. dot: function ( v ) {
  1571. return this.x * v.x + this.y * v.y + this.z * v.z;
  1572. },
  1573. lengthSq: function () {
  1574. return this.x * this.x + this.y * this.y + this.z * this.z;
  1575. },
  1576. length: function () {
  1577. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1578. },
  1579. lengthManhattan: function () {
  1580. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1581. },
  1582. normalize: function () {
  1583. return this.divideScalar( this.length() );
  1584. },
  1585. setLength: function ( l ) {
  1586. var oldLength = this.length();
  1587. if ( oldLength !== 0 && l !== oldLength ) {
  1588. this.multiplyScalar( l / oldLength );
  1589. }
  1590. return this;
  1591. },
  1592. lerp: function ( v, alpha ) {
  1593. this.x += ( v.x - this.x ) * alpha;
  1594. this.y += ( v.y - this.y ) * alpha;
  1595. this.z += ( v.z - this.z ) * alpha;
  1596. return this;
  1597. },
  1598. cross: function ( v, w ) {
  1599. if ( w !== undefined ) {
  1600. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1601. return this.crossVectors( v, w );
  1602. }
  1603. var x = this.x, y = this.y, z = this.z;
  1604. this.x = y * v.z - z * v.y;
  1605. this.y = z * v.x - x * v.z;
  1606. this.z = x * v.y - y * v.x;
  1607. return this;
  1608. },
  1609. crossVectors: function ( a, b ) {
  1610. var ax = a.x, ay = a.y, az = a.z;
  1611. var bx = b.x, by = b.y, bz = b.z;
  1612. this.x = ay * bz - az * by;
  1613. this.y = az * bx - ax * bz;
  1614. this.z = ax * by - ay * bx;
  1615. return this;
  1616. },
  1617. projectOnVector: function () {
  1618. var v1, dot;
  1619. return function ( vector ) {
  1620. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1621. v1.copy( vector ).normalize();
  1622. dot = this.dot( v1 );
  1623. return this.copy( v1 ).multiplyScalar( dot );
  1624. };
  1625. }(),
  1626. projectOnPlane: function () {
  1627. var v1;
  1628. return function ( planeNormal ) {
  1629. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1630. v1.copy( this ).projectOnVector( planeNormal );
  1631. return this.sub( v1 );
  1632. }
  1633. }(),
  1634. reflect: function () {
  1635. // reflect incident vector off plane orthogonal to normal
  1636. // normal is assumed to have unit length
  1637. var v1;
  1638. return function ( normal ) {
  1639. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1640. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1641. }
  1642. }(),
  1643. angleTo: function ( v ) {
  1644. var theta = this.dot( v ) / ( this.length() * v.length() );
  1645. // clamp, to handle numerical problems
  1646. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1647. },
  1648. distanceTo: function ( v ) {
  1649. return Math.sqrt( this.distanceToSquared( v ) );
  1650. },
  1651. distanceToSquared: function ( v ) {
  1652. var dx = this.x - v.x;
  1653. var dy = this.y - v.y;
  1654. var dz = this.z - v.z;
  1655. return dx * dx + dy * dy + dz * dz;
  1656. },
  1657. setEulerFromRotationMatrix: function ( m, order ) {
  1658. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1659. },
  1660. setEulerFromQuaternion: function ( q, order ) {
  1661. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1662. },
  1663. getPositionFromMatrix: function ( m ) {
  1664. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1665. return this.setFromMatrixPosition( m );
  1666. },
  1667. getScaleFromMatrix: function ( m ) {
  1668. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1669. return this.setFromMatrixScale( m );
  1670. },
  1671. getColumnFromMatrix: function ( index, matrix ) {
  1672. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1673. return this.setFromMatrixColumn( index, matrix );
  1674. },
  1675. setFromMatrixPosition: function ( m ) {
  1676. this.x = m.elements[ 12 ];
  1677. this.y = m.elements[ 13 ];
  1678. this.z = m.elements[ 14 ];
  1679. return this;
  1680. },
  1681. setFromMatrixScale: function ( m ) {
  1682. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1683. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1684. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1685. this.x = sx;
  1686. this.y = sy;
  1687. this.z = sz;
  1688. return this;
  1689. },
  1690. setFromMatrixColumn: function ( index, matrix ) {
  1691. var offset = index * 4;
  1692. var me = matrix.elements;
  1693. this.x = me[ offset ];
  1694. this.y = me[ offset + 1 ];
  1695. this.z = me[ offset + 2 ];
  1696. return this;
  1697. },
  1698. equals: function ( v ) {
  1699. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1700. },
  1701. fromArray: function ( array, offset ) {
  1702. if ( offset === undefined ) offset = 0;
  1703. this.x = array[ offset ];
  1704. this.y = array[ offset + 1 ];
  1705. this.z = array[ offset + 2 ];
  1706. return this;
  1707. },
  1708. toArray: function ( array, offset ) {
  1709. if ( array === undefined ) array = [];
  1710. if ( offset === undefined ) offset = 0;
  1711. array[ offset ] = this.x;
  1712. array[ offset + 1 ] = this.y;
  1713. array[ offset + 2 ] = this.z;
  1714. return array;
  1715. },
  1716. fromAttribute: function ( attribute, index, offset ) {
  1717. if ( offset === undefined ) offset = 0;
  1718. index = index * attribute.itemSize + offset;
  1719. this.x = attribute.array[ index ];
  1720. this.y = attribute.array[ index + 1 ];
  1721. this.z = attribute.array[ index + 2 ];
  1722. return this;
  1723. },
  1724. clone: function () {
  1725. return new THREE.Vector3( this.x, this.y, this.z );
  1726. }
  1727. };
  1728. /*** END Vector3 ***/
  1729. /*** START Euler ***/
  1730. /**
  1731. * @author mrdoob / http://mrdoob.com/
  1732. * @author WestLangley / http://github.com/WestLangley
  1733. * @author bhouston / http://exocortex.com
  1734. */
  1735. THREE.Euler = function ( x, y, z, order ) {
  1736. this._x = x || 0;
  1737. this._y = y || 0;
  1738. this._z = z || 0;
  1739. this._order = order || THREE.Euler.DefaultOrder;
  1740. };
  1741. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1742. THREE.Euler.DefaultOrder = 'XYZ';
  1743. THREE.Euler.prototype = {
  1744. constructor: THREE.Euler,
  1745. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1746. get x () {
  1747. return this._x;
  1748. },
  1749. set x ( value ) {
  1750. this._x = value;
  1751. this.onChangeCallback();
  1752. },
  1753. get y () {
  1754. return this._y;
  1755. },
  1756. set y ( value ) {
  1757. this._y = value;
  1758. this.onChangeCallback();
  1759. },
  1760. get z () {
  1761. return this._z;
  1762. },
  1763. set z ( value ) {
  1764. this._z = value;
  1765. this.onChangeCallback();
  1766. },
  1767. get order () {
  1768. return this._order;
  1769. },
  1770. set order ( value ) {
  1771. this._order = value;
  1772. this.onChangeCallback();
  1773. },
  1774. set: function ( x, y, z, order ) {
  1775. this._x = x;
  1776. this._y = y;
  1777. this._z = z;
  1778. this._order = order || this._order;
  1779. this.onChangeCallback();
  1780. return this;
  1781. },
  1782. copy: function ( euler ) {
  1783. this._x = euler._x;
  1784. this._y = euler._y;
  1785. this._z = euler._z;
  1786. this._order = euler._order;
  1787. this.onChangeCallback();
  1788. return this;
  1789. },
  1790. setFromRotationMatrix: function ( m, order, update ) {
  1791. var clamp = THREE.Math.clamp;
  1792. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1793. var te = m.elements;
  1794. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1795. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1796. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1797. order = order || this._order;
  1798. if ( order === 'XYZ' ) {
  1799. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1800. if ( Math.abs( m13 ) < 0.99999 ) {
  1801. this._x = Math.atan2( - m23, m33 );
  1802. this._z = Math.atan2( - m12, m11 );
  1803. } else {
  1804. this._x = Math.atan2( m32, m22 );
  1805. this._z = 0;
  1806. }
  1807. } else if ( order === 'YXZ' ) {
  1808. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1809. if ( Math.abs( m23 ) < 0.99999 ) {
  1810. this._y = Math.atan2( m13, m33 );
  1811. this._z = Math.atan2( m21, m22 );
  1812. } else {
  1813. this._y = Math.atan2( - m31, m11 );
  1814. this._z = 0;
  1815. }
  1816. } else if ( order === 'ZXY' ) {
  1817. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1818. if ( Math.abs( m32 ) < 0.99999 ) {
  1819. this._y = Math.atan2( - m31, m33 );
  1820. this._z = Math.atan2( - m12, m22 );
  1821. } else {
  1822. this._y = 0;
  1823. this._z = Math.atan2( m21, m11 );
  1824. }
  1825. } else if ( order === 'ZYX' ) {
  1826. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1827. if ( Math.abs( m31 ) < 0.99999 ) {
  1828. this._x = Math.atan2( m32, m33 );
  1829. this._z = Math.atan2( m21, m11 );
  1830. } else {
  1831. this._x = 0;
  1832. this._z = Math.atan2( - m12, m22 );
  1833. }
  1834. } else if ( order === 'YZX' ) {
  1835. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1836. if ( Math.abs( m21 ) < 0.99999 ) {
  1837. this._x = Math.atan2( - m23, m22 );
  1838. this._y = Math.atan2( - m31, m11 );
  1839. } else {
  1840. this._x = 0;
  1841. this._y = Math.atan2( m13, m33 );
  1842. }
  1843. } else if ( order === 'XZY' ) {
  1844. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1845. if ( Math.abs( m12 ) < 0.99999 ) {
  1846. this._x = Math.atan2( m32, m22 );
  1847. this._y = Math.atan2( m13, m11 );
  1848. } else {
  1849. this._x = Math.atan2( - m23, m33 );
  1850. this._y = 0;
  1851. }
  1852. } else {
  1853. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1854. }
  1855. this._order = order;
  1856. if ( update !== false ) this.onChangeCallback();
  1857. return this;
  1858. },
  1859. setFromQuaternion: function () {
  1860. var matrix;
  1861. return function ( q, order, update ) {
  1862. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1863. matrix.makeRotationFromQuaternion( q );
  1864. this.setFromRotationMatrix( matrix, order, update );
  1865. return this;
  1866. };
  1867. }(),
  1868. setFromVector3: function ( v, order ) {
  1869. return this.set( v.x, v.y, v.z, order || this._order );
  1870. },
  1871. reorder: function () {
  1872. // WARNING: this discards revolution information -bhouston
  1873. var q = new THREE.Quaternion();
  1874. return function ( newOrder ) {
  1875. q.setFromEuler( this );
  1876. this.setFromQuaternion( q, newOrder );
  1877. };
  1878. }(),
  1879. equals: function ( euler ) {
  1880. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1881. },
  1882. fromArray: function ( array ) {
  1883. this._x = array[ 0 ];
  1884. this._y = array[ 1 ];
  1885. this._z = array[ 2 ];
  1886. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1887. this.onChangeCallback();
  1888. return this;
  1889. },
  1890. toArray: function () {
  1891. return [ this._x, this._y, this._z, this._order ];
  1892. },
  1893. toVector3: function ( optionalResult ) {
  1894. if ( optionalResult ) {
  1895. return optionalResult.set( this._x, this._y, this._z );
  1896. } else {
  1897. return new THREE.Vector3( this._x, this._y, this._z );
  1898. }
  1899. },
  1900. onChange: function ( callback ) {
  1901. this.onChangeCallback = callback;
  1902. return this;
  1903. },
  1904. onChangeCallback: function () {},
  1905. clone: function () {
  1906. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1907. }
  1908. };
  1909. /*** END Euler ***/
  1910. /*** START Math ***/
  1911. /**
  1912. * @author alteredq / http://alteredqualia.com/
  1913. * @author mrdoob / http://mrdoob.com/
  1914. */
  1915. THREE.Math = {
  1916. generateUUID: function () {
  1917. // http://www.broofa.com/Tools/Math.uuid.htm
  1918. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  1919. var uuid = new Array( 36 );
  1920. var rnd = 0, r;
  1921. return function () {
  1922. for ( var i = 0; i < 36; i ++ ) {
  1923. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  1924. uuid[ i ] = '-';
  1925. } else if ( i == 14 ) {
  1926. uuid[ i ] = '4';
  1927. } else {
  1928. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  1929. r = rnd & 0xf;
  1930. rnd = rnd >> 4;
  1931. uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  1932. }
  1933. }
  1934. return uuid.join( '' );
  1935. };
  1936. }(),
  1937. // Clamp value to range <a, b>
  1938. clamp: function ( x, a, b ) {
  1939. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  1940. },
  1941. // Clamp value to range <a, inf)
  1942. clampBottom: function ( x, a ) {
  1943. return x < a ? a : x;
  1944. },
  1945. // Linear mapping from range <a1, a2> to range <b1, b2>
  1946. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1947. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1948. },
  1949. // http://en.wikipedia.org/wiki/Smoothstep
  1950. smoothstep: function ( x, min, max ) {
  1951. if ( x <= min ) return 0;
  1952. if ( x >= max ) return 1;
  1953. x = ( x - min ) / ( max - min );
  1954. return x * x * ( 3 - 2 * x );
  1955. },
  1956. smootherstep: function ( x, min, max ) {
  1957. if ( x <= min ) return 0;
  1958. if ( x >= max ) return 1;
  1959. x = ( x - min ) / ( max - min );
  1960. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1961. },
  1962. // Random float from <0, 1> with 16 bits of randomness
  1963. // (standard Math.random() creates repetitive patterns when applied over larger space)
  1964. random16: function () {
  1965. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  1966. },
  1967. // Random integer from <low, high> interval
  1968. randInt: function ( low, high ) {
  1969. return Math.floor( this.randFloat( low, high ) );
  1970. },
  1971. // Random float from <low, high> interval
  1972. randFloat: function ( low, high ) {
  1973. return low + Math.random() * ( high - low );
  1974. },
  1975. // Random float from <-range/2, range/2> interval
  1976. randFloatSpread: function ( range ) {
  1977. return range * ( 0.5 - Math.random() );
  1978. },
  1979. degToRad: function () {
  1980. var degreeToRadiansFactor = Math.PI / 180;
  1981. return function ( degrees ) {
  1982. return degrees * degreeToRadiansFactor;
  1983. };
  1984. }(),
  1985. radToDeg: function () {
  1986. var radianToDegreesFactor = 180 / Math.PI;
  1987. return function ( radians ) {
  1988. return radians * radianToDegreesFactor;
  1989. };
  1990. }(),
  1991. isPowerOfTwo: function ( value ) {
  1992. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1993. },
  1994. nextPowerOfTwo: function ( value ) {
  1995. value --;
  1996. value |= value >> 1;
  1997. value |= value >> 2;
  1998. value |= value >> 4;
  1999. value |= value >> 8;
  2000. value |= value >> 16;
  2001. value ++;
  2002. return value;
  2003. }
  2004. };
  2005. /*** END Math ***/
  2006. }
  2007. module.exports = THREE;
  2008. },{}],10:[function(_dereq_,module,exports){
  2009. /*
  2010. * Copyright 2015 Google Inc. All Rights Reserved.
  2011. * Licensed under the Apache License, Version 2.0 (the "License");
  2012. * you may not use this file except in compliance with the License.
  2013. * You may obtain a copy of the License at
  2014. *
  2015. * http://www.apache.org/licenses/LICENSE-2.0
  2016. *
  2017. * Unless required by applicable law or agreed to in writing, software
  2018. * distributed under the License is distributed on an "AS IS" BASIS,
  2019. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2020. * See the License for the specific language governing permissions and
  2021. * limitations under the License.
  2022. */
  2023. var THREE = _dereq_('./three-math.js');
  2024. var Util = _dereq_('./util.js');
  2025. var ROTATE_SPEED = 0.5;
  2026. /**
  2027. * Provides a quaternion responsible for pre-panning the scene before further
  2028. * transformations due to device sensors.
  2029. */
  2030. function TouchPanner() {
  2031. window.addEventListener('touchstart', this.onTouchStart_.bind(this));
  2032. window.addEventListener('touchmove', this.onTouchMove_.bind(this));
  2033. window.addEventListener('touchend', this.onTouchEnd_.bind(this));
  2034. this.isTouching = false;
  2035. this.rotateStart = new THREE.Vector2();
  2036. this.rotateEnd = new THREE.Vector2();
  2037. this.rotateDelta = new THREE.Vector2();
  2038. this.theta = 0;
  2039. this.orientation = new THREE.Quaternion();
  2040. }
  2041. TouchPanner.prototype.getOrientation = function() {
  2042. this.orientation.setFromEuler(new THREE.Euler(0, 0, this.theta));
  2043. return this.orientation;
  2044. };
  2045. TouchPanner.prototype.resetSensor = function() {
  2046. this.theta = 0;
  2047. };
  2048. TouchPanner.prototype.onTouchStart_ = function(e) {
  2049. // Only respond if there is exactly one touch.
  2050. if (e.touches.length != 1) {
  2051. return;
  2052. }
  2053. this.rotateStart.set(e.touches[0].pageX, e.touches[0].pageY);
  2054. this.isTouching = true;
  2055. };
  2056. TouchPanner.prototype.onTouchMove_ = function(e) {
  2057. if (!this.isTouching) {
  2058. return;
  2059. }
  2060. this.rotateEnd.set(e.touches[0].pageX, e.touches[0].pageY);
  2061. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  2062. this.rotateStart.copy(this.rotateEnd);
  2063. // On iOS, direction is inverted.
  2064. if (Util.isIOS()) {
  2065. this.rotateDelta.x *= -1;
  2066. }
  2067. var element = document.body;
  2068. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * ROTATE_SPEED;
  2069. };
  2070. TouchPanner.prototype.onTouchEnd_ = function(e) {
  2071. this.isTouching = false;
  2072. };
  2073. module.exports = TouchPanner;
  2074. },{"./three-math.js":9,"./util.js":11}],11:[function(_dereq_,module,exports){
  2075. /*
  2076. * Copyright 2015 Google Inc. All Rights Reserved.
  2077. * Licensed under the Apache License, Version 2.0 (the "License");
  2078. * you may not use this file except in compliance with the License.
  2079. * You may obtain a copy of the License at
  2080. *
  2081. * http://www.apache.org/licenses/LICENSE-2.0
  2082. *
  2083. * Unless required by applicable law or agreed to in writing, software
  2084. * distributed under the License is distributed on an "AS IS" BASIS,
  2085. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2086. * See the License for the specific language governing permissions and
  2087. * limitations under the License.
  2088. */
  2089. var Util = window.Util || {};
  2090. Util.MIN_TIMESTEP = 0.001;
  2091. Util.MAX_TIMESTEP = 1;
  2092. Util.clamp = function(value, min, max) {
  2093. return Math.min(Math.max(min, value), max);
  2094. };
  2095. Util.isIOS = function() {
  2096. return /iPad|iPhone|iPod/.test(navigator.platform);
  2097. };
  2098. Util.isFirefoxAndroid = function() {
  2099. return navigator.userAgent.indexOf('Firefox') !== -1 && navigator.userAgent.indexOf('Android') !== -1;
  2100. }
  2101. // Helper method to validate the time steps of sensor timestamps.
  2102. Util.isTimestampDeltaValid = function(timestampDeltaS) {
  2103. if (isNaN(timestampDeltaS)) {
  2104. return false;
  2105. }
  2106. if (timestampDeltaS <= Util.MIN_TIMESTEP) {
  2107. return false;
  2108. }
  2109. if (timestampDeltaS > Util.MAX_TIMESTEP) {
  2110. return false;
  2111. }
  2112. return true;
  2113. }
  2114. module.exports = Util;
  2115. },{}],12:[function(_dereq_,module,exports){
  2116. /*
  2117. * Copyright 2015 Google Inc. All Rights Reserved.
  2118. * Licensed under the Apache License, Version 2.0 (the "License");
  2119. * you may not use this file except in compliance with the License.
  2120. * You may obtain a copy of the License at
  2121. *
  2122. * http://www.apache.org/licenses/LICENSE-2.0
  2123. *
  2124. * Unless required by applicable law or agreed to in writing, software
  2125. * distributed under the License is distributed on an "AS IS" BASIS,
  2126. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2127. * See the License for the specific language governing permissions and
  2128. * limitations under the License.
  2129. */
  2130. var CardboardHMDVRDevice = _dereq_('./cardboard-hmd-vr-device.js');
  2131. //var OrientationPositionSensorVRDevice = require('./orientation-position-sensor-vr-device.js');
  2132. var FusionPositionSensorVRDevice = _dereq_('./fusion-position-sensor-vr-device.js');
  2133. var MouseKeyboardPositionSensorVRDevice = _dereq_('./mouse-keyboard-position-sensor-vr-device.js');
  2134. // Uncomment to add positional tracking via webcam.
  2135. //var WebcamPositionSensorVRDevice = require('./webcam-position-sensor-vr-device.js');
  2136. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  2137. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  2138. function WebVRPolyfill() {
  2139. this.devices = [];
  2140. if (!this.isWebVRAvailable()) {
  2141. this.enablePolyfill();
  2142. }
  2143. }
  2144. WebVRPolyfill.prototype.isWebVRAvailable = function() {
  2145. return ('getVRDevices' in navigator) || ('mozGetVRDevices' in navigator);
  2146. };
  2147. WebVRPolyfill.prototype.enablePolyfill = function() {
  2148. // Initialize our virtual VR devices.
  2149. if (this.isCardboardCompatible()) {
  2150. this.devices.push(new CardboardHMDVRDevice());
  2151. }
  2152. // Polyfill using the right position sensor.
  2153. if (this.isMobile()) {
  2154. //this.devices.push(new OrientationPositionSensorVRDevice());
  2155. this.devices.push(new FusionPositionSensorVRDevice());
  2156. } else {
  2157. if (!WebVRConfig.MOUSE_KEYBOARD_CONTROLS_DISABLED) {
  2158. this.devices.push(new MouseKeyboardPositionSensorVRDevice());
  2159. }
  2160. // Uncomment to add positional tracking via webcam.
  2161. //this.devices.push(new WebcamPositionSensorVRDevice());
  2162. }
  2163. // Provide navigator.getVRDevices.
  2164. navigator.getVRDevices = this.getVRDevices.bind(this);
  2165. // Provide the CardboardHMDVRDevice and PositionSensorVRDevice objects.
  2166. window.HMDVRDevice = HMDVRDevice;
  2167. window.PositionSensorVRDevice = PositionSensorVRDevice;
  2168. };
  2169. WebVRPolyfill.prototype.getVRDevices = function() {
  2170. var devices = this.devices;
  2171. return new Promise(function(resolve, reject) {
  2172. try {
  2173. resolve(devices);
  2174. } catch (e) {
  2175. reject(e);
  2176. }
  2177. });
  2178. };
  2179. /**
  2180. * Determine if a device is mobile.
  2181. */
  2182. WebVRPolyfill.prototype.isMobile = function() {
  2183. return /Android/i.test(navigator.userAgent) ||
  2184. /iPhone|iPad|iPod/i.test(navigator.userAgent);
  2185. };
  2186. WebVRPolyfill.prototype.isCardboardCompatible = function() {
  2187. // For now, support all iOS and Android devices.
  2188. // Also enable the WebVRConfig.FORCE_VR flag for debugging.
  2189. return this.isMobile() || WebVRConfig.FORCE_ENABLE_VR;
  2190. };
  2191. module.exports = WebVRPolyfill;
  2192. },{"./base.js":1,"./cardboard-hmd-vr-device.js":2,"./fusion-position-sensor-vr-device.js":4,"./mouse-keyboard-position-sensor-vr-device.js":6}]},{},[5]);