aframe.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2020 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. */
  5. // VWF & A-Frame view driver
  6. import {Fabric} from '/core/vwf/fabric.js';
  7. class AFrameView extends Fabric {
  8. constructor(module) {
  9. console.log("AFrameView constructor");
  10. super(module, 'View');
  11. }
  12. factory() {
  13. let _self_ = this;
  14. return this.load(this.module,
  15. {
  16. // == Module Definition ====================================================================
  17. initialize: function (options) {
  18. let self = this;
  19. this.fabric = _self_;
  20. this.nodes = {};
  21. // this.tickTime = 0;
  22. // this.realTickDif = 50;
  23. // this.lastrealTickDif = 50;
  24. // this.lastRealTick = performance.now();
  25. this.state.appInitialized = false;
  26. this.state.showMobileJoystick = function(){
  27. let controlEl = document.querySelector('#avatarControl');
  28. if(controlEl){
  29. controlEl.setAttribute("virtual-gamepad-controls", {});
  30. controlEl.addEventListener("move", _self_.setJoystickMoveInput.bind(_self_));
  31. }
  32. }
  33. this.state.hideMobileJoystick = function(){
  34. let controlEl = document.querySelector('#avatarControl');
  35. if(controlEl){
  36. controlEl.removeAttribute("virtual-gamepad-controls");
  37. controlEl.removeEventListener("move", _self_.setJoystickMoveInput.bind(_self_));
  38. }
  39. }
  40. if (options === undefined) { options = {}; }
  41. if (typeof options == "object") {
  42. this.rootSelector = options["application-root"];
  43. }
  44. else {
  45. this.rootSelector = options;
  46. }
  47. // this.gearvr = options.gearvr !== undefined ? options.gearvr : false;
  48. // this.wmrright = options.wmrright !== undefined ? options.wmrright : false;
  49. // this.wmrleft = options.wmrleft !== undefined ? options.wmrleft : false;
  50. this.xrType = undefined;
  51. //TODO: FIX detection in better way! (now works for Oculus Browser only)
  52. this.hmd = false;
  53. this.threeDoF = false;
  54. this.sixDoF = false;
  55. this.threeDoFMobile = AFRAME.utils.device.isMobileVR() && AFRAME.utils.device.checkHeadsetConnected() && !navigator.userAgent.includes('Quest');
  56. this.sixDoFMobile = AFRAME.utils.device.checkHeadsetConnected() && navigator.userAgent.includes('Quest');
  57. this.sixDoFDesktop = !AFRAME.utils.device.isMobile() && !AFRAME.utils.device.isMobileVR() && AFRAME.utils.device.checkHeadsetConnected();
  58. this.isDesktop = !this.threeDoFMobile && !this.sixDoFMobile && !this.sixDoFDesktop && !_app.config.d3DoF && !_app.config.d6DoF;
  59. this.isMobile = AFRAME.utils.device.isMobile() && !AFRAME.utils.device.isMobileVR()
  60. //!AFRAME.utils.device.isMobile() &&
  61. },
  62. createdNode: function (nodeID, childID, childExtendsID, childImplementsIDs,
  63. childSource, childType, childIndex, childName, callback /* ( ready ) */) {
  64. let self = this;
  65. var node = this.state.nodes[childID];
  66. // If the "nodes" object does not have this object in it, it must not be one that
  67. // this driver cares about
  68. if (!node) {
  69. return;
  70. }
  71. if (this.state.scenes[childID]) {
  72. let scene = this.state.scenes[childID];
  73. //TODO: FIX
  74. let prepairAvatar = new Promise((resolve, reject) => {
  75. document.body.appendChild(scene);
  76. let createAvatarPromise = new Promise(r=> r(_self_.createAvatarControl(scene)));
  77. return resolve(createAvatarPromise)
  78. });
  79. prepairAvatar.then(res => {
  80. if (self.threeDoFMobile || _app.config.d3DoF ) {
  81. console.log("CREATE GEARVR HERE!!");
  82. //this.xrType = 'mobileVR';
  83. let nodeName = 'gearvr-' + self.kernel.moniker();
  84. _self_.createGearVRControls();
  85. _self_.createXR.call(self, childID, nodeName, {});
  86. //_self_.createGearVRController.call(self, childID, nodeName);
  87. }
  88. // if (!AFRAME.utils.device.isMobileVR()) {
  89. else if (self.sixDoFMobile || self.sixDoFDesktop || _app.config.d6DoF ) {
  90. console.log("CREATE XRController RIGHT HERE!!");
  91. let nodeRight = 'xrcontroller-right-' + self.kernel.moniker();
  92. _self_.createXRControls('right');
  93. _self_.createXR.call(this, childID, nodeRight, {});
  94. // if (!AFRAME.utils.device.isMobileVR()) {
  95. console.log("CREATE XRController LEFT HERE!!");
  96. let nodeLeft = 'xrcontroller-left-' + self.kernel.moniker();
  97. _self_.createXRControls('left');
  98. _self_.createXR.call(this, childID, nodeLeft, {});
  99. }
  100. else if (this.isDesktop){
  101. let nodeName = 'mouse-' + self.kernel.moniker();
  102. _self_.createDesktopControls();
  103. _self_.createXR.call(this, childID, nodeName, {position: [0, 0, -0.8]});
  104. }
  105. // }
  106. // console.log(res);
  107. _self_.createAvatar.call(self, childID);
  108. _self_.postLoadAction.call(self, childID);
  109. }).then(res=>{
  110. //document.body.appendChild(scene);
  111. })
  112. // this.state.appInitialized = true;
  113. //document.body.appendChild(scene); //append is not working in Edge browser
  114. }
  115. if (this.state.nodes[childID] && this.state.nodes[childID].aframeObj) {
  116. this.nodes[childID] = {
  117. id: childID,
  118. extends: childExtendsID,
  119. liveBindings: {}
  120. // lastTransformStep: 0,
  121. // lastAnimationStep: 0
  122. };
  123. }
  124. // if(this.state.nodes[childID]) {
  125. // this.nodes[childID] = {id:childID,extends:childExtendsID};
  126. // }
  127. // else if (this.state.nodes[childID] && this.state.nodes[childID].aframeObj.object3D instanceof THREE.Object3D) {
  128. // this.nodes[childID] = {id:childID,extends:childExtendsID};
  129. // }
  130. },
  131. executed: function (nodeID, scriptText, scriptType) {
  132. let self = this;
  133. let node = this.state.nodes[nodeID];
  134. if (!(node)) {
  135. return;
  136. }
  137. },
  138. initializedNode: function (nodeID, childID) {
  139. let self = this;
  140. var node = this.state.nodes[childID];
  141. if (!node) {
  142. return;
  143. }
  144. if (node.extendsID == "proxy/aframe/gearvrcontroller.vwf") {
  145. console.log("gearVR controller initialized")
  146. }
  147. // if (node.extendsID == "proxy/aframe/atext.vwf") {
  148. // console.log("Text component initialized");
  149. // node.aframeObj.play();
  150. // }
  151. // if (node.prototypes.includes("proxy/aframe/aentity.vwf")) {
  152. // var clientThatSatProperty = self.kernel.client();
  153. // var me = self.kernel.moniker();
  154. // // If the transform property was initially updated by this view....
  155. // if (clientThatSatProperty == me) {
  156. // self.kernel.callMethod(childID, "setOwner", [me]);
  157. // }
  158. // }
  159. // if (propertyName == 'ownedBy')
  160. // {
  161. // // if (!node.aframeObj.el.getAttribute('ownedBy')){
  162. // // }
  163. // }
  164. },
  165. createdProperty: function (nodeId, propertyName, propertyValue) {
  166. return this.satProperty(nodeId, propertyName, propertyValue);
  167. },
  168. initializedProperty: function (nodeId, propertyName, propertyValue) {
  169. return this.satProperty(nodeId, propertyName, propertyValue);
  170. },
  171. gotProperty: function (nodeId, propertyName, propertyValue) {
  172. var node = this.state.nodes[nodeId];
  173. if (!(node && node.aframeObj)) {
  174. return;
  175. }
  176. },
  177. satProperty: function (nodeId, propertyName, propertyValue) {
  178. let self = this;
  179. var node = this.state.nodes[nodeId];
  180. if (!(node && node.aframeObj)) {
  181. return;
  182. }
  183. // if (propertyName == 'arjs') {
  184. // if(propertyValue) {
  185. // node.aframeObj.setAttribute('arjs', {trackingMethod: "best", sourceType: "webcam", debugUIEnabled: "true"});
  186. // // let sceneEl = document.querySelector('a-scene');
  187. // // let marker = document.createElement('a-marker-camera');
  188. // // marker.setAttribute('preset', 'hiro');
  189. // // sceneEl.appendChild(marker);
  190. // //<a-marker-camera preset='hiro'></a-marker-camera>
  191. // } else {
  192. // if(node.aframeObj.getAttribute('arjs')){
  193. // node.aframeObj.removeAttribute('arjs')
  194. // }
  195. // }
  196. // }
  197. if (propertyName == 'position') {
  198. _self_.receiveModelTransformChanges(nodeId, 'position', propertyValue);
  199. }
  200. if (propertyName == 'rotation') {
  201. _self_.receiveModelTransformChanges(nodeId, 'rotation', propertyValue);
  202. }
  203. if (propertyName == 'scale') {
  204. _self_.receiveModelTransformChanges(nodeId, 'scale', propertyValue);
  205. }
  206. if (node.aframeObj.nodeName == "AUDIO" && propertyName == 'itemSrc') {
  207. //console.log("sat new item");
  208. let elID = '#' + node.aframeObj.getAttribute('id');
  209. Object.entries(this.state.nodes).forEach(el => {
  210. let sound = el[1].aframeObj.getAttribute('sound');
  211. if (sound) {
  212. let soundID = vwf.find(el[0], 'sound');
  213. self.kernel.callMethod(soundID, "refreshSrc", [elID])
  214. // if (sound.src !== ""){
  215. // let src = '#' + sound.src.id;
  216. // if (src == elID){
  217. // let soundID = vwf.find(el[0], 'sound');
  218. // self.kernel.callMethod(soundID, "updateSrc", [elID])
  219. // }
  220. // }
  221. }
  222. })
  223. }
  224. if (node.aframeObj.nodeName == "IMG" && propertyName == 'itemSrc') {
  225. _self_.updateMaterial(node);
  226. }
  227. if (node.aframeObj.nodeName == "VIDEO" && propertyName == 'itemSrc') {
  228. _self_.updateMaterial(node);
  229. }
  230. if (node.aframeObj.nodeName == "A-ASSET-ITEM" && propertyName == 'itemSrc') {
  231. //console.log("sat new item");
  232. let elID = '#' + node.aframeObj.getAttribute('id');
  233. Object.entries(this.state.nodes).forEach(el => {
  234. let src = el[1].aframeObj.getAttribute('src');
  235. let mtl = el[1].aframeObj.getAttribute('mtl');
  236. if (src) {
  237. // console.log("my: " + src);
  238. if (src == elID)
  239. self.kernel.callMethod(el[0], "updateModel", [elID])
  240. }
  241. if (mtl) {
  242. // console.log("my: " + mtl);
  243. if (mtl == elID)
  244. self.kernel.callMethod(el[0], "updateModelMtl", [elID])
  245. }
  246. })
  247. }
  248. // var aframeObject = node.aframeObj;
  249. // switch (propertyName) {
  250. // case "clickable":
  251. // if (propertyValue) {
  252. // aframeObject.addEventListener('click', function (evt) {
  253. // let cursorID = 'cursor-avatar-'+selfs.kernel.moniker();
  254. // if (evt.detail.cursorEl.id == cursorID) {
  255. // vwf_view.kernel.fireEvent(nodeId, "clickEvent")
  256. // }
  257. // });
  258. // }
  259. // break;
  260. // }
  261. },
  262. deletedNode: function (childID) {
  263. delete this.nodes[childID];
  264. },
  265. firedEvent: function (nodeID, eventName, eventParameters) {
  266. let self = this;
  267. var node = this.state.nodes[nodeID];
  268. if (!(node)) {
  269. return;
  270. }
  271. var clientThatSatProperty = self.kernel.client();
  272. var me = self.kernel.moniker();
  273. if (eventName == "changingTransformFromView") {
  274. // If the transform property was initially updated by this view....
  275. if (clientThatSatProperty == me) {
  276. var node = this.state.nodes[nodeID];
  277. node.ignoreNextTransformUpdate = true;
  278. }
  279. }
  280. //var avatarID = vwf_view.kernel.find("", avatarName)
  281. // if (eventName == "postLoadAction") {
  282. // Object.entries(self.state.nodes).forEach(el => {
  283. // if (el[1].prototypes.includes("proxy/aframe/aentity.vwf")) {
  284. // vwf_view.kernel.callMethod(el[0], "setOwner", [self.kernel.moniker()]);
  285. // }
  286. // });
  287. // }
  288. var avatarName = 'avatar-' + self.kernel.moniker();
  289. if (eventName == "clickEvent" ||
  290. eventName == 'mousedownEvent' ||
  291. eventName == 'mouseupEvent'){
  292. if (clientThatSatProperty == me) {
  293. let methodName = eventName +'Method';
  294. self.kernel.callMethod(nodeID, methodName, eventParameters);
  295. if (eventName == "clickEvent"){
  296. let mode = vwf.getProperty(avatarName, 'selectMode');
  297. if (mode) {
  298. console.log("allow to click!!!")
  299. vwf_view.kernel.setProperty(avatarName, 'selectMode', false);
  300. let editorDriver = vwf.views["/drivers/view/editor"];
  301. if (editorDriver) {
  302. let selectSwitch = document.querySelector('#selectNodeSwitch');
  303. // const selectSwitchComp = new mdc.iconButton.MDCIconButtonToggle(selectSwitch); //new mdc.select.MDCIconToggle
  304. selectSwitch._comp.on = false;
  305. let currentNodeDIV = document.querySelector('#currentNode');
  306. if (currentNodeDIV) currentNodeDIV._setNode(nodeID);
  307. }
  308. }
  309. }
  310. }
  311. }
  312. let intersectEvents = ['fromhitstart', 'fromhitend', 'hitstart', 'hitend', 'intersect', 'clearIntersect']; //'intersect',
  313. let hitEvent = intersectEvents.filter(el=> el == eventName.slice(0,-5))[0]; //slice Event word
  314. if (hitEvent)
  315. {
  316. // If the transform property was initially updated by this view....
  317. if (clientThatSatProperty == me) {
  318. let methodName = eventName +'Method';
  319. self.kernel.callMethod(nodeID, methodName, eventParameters);
  320. }
  321. }
  322. // if (eventName == "clickEvent") {
  323. // if (self.kernel.moniker() == eventParameters[0]) {
  324. // let avatar = self.nodes[avatarName];
  325. // let mode = vwf.getProperty(avatarName, 'selectMode');
  326. // vwf_view.kernel.callMethod(nodeID, "clickEventMethod", [])
  327. // }
  328. // }
  329. },
  330. ticked: function (vwfTime) {
  331. let self = this;
  332. _self_.updateAvatarPosition();
  333. //update vr controllers
  334. if(self.hmd){
  335. if(self.threeDoF )
  336. _self_.updateHandControllerVR('gearvr-', '#gearvrcontrol');
  337. if(this.sixDoF ) {
  338. _self_.updateHandControllerVR('xrcontroller-right-', '#xrcontrollerright');
  339. _self_.updateHandControllerVR('xrcontroller-left-', '#xrcontrollerleft');
  340. }
  341. }
  342. if (this.isDesktop){
  343. _self_.updateDesktopController('mouse-', '#mouse');
  344. }
  345. //lerpTick ();
  346. },
  347. calledMethod: function (nodeID, methodName, methodParameters, methodValue) {
  348. let self = this;
  349. var node = this.state.nodes[nodeID];
  350. if (!(node && node.aframeObj)) {
  351. return;
  352. }
  353. switch (methodName) {
  354. case "translateBy":
  355. case "translateTo":
  356. //resetInterpolationFromViewDriver(nodeID, methodParameters, 'position')
  357. break;
  358. // No need for rotateBy or rotateTo because they call the quaternion methods
  359. case "quaterniateBy":
  360. case "quaterniateTo":
  361. //resetInterpolationFromViewDriver(nodeID, methodParameters, 'rotation')
  362. break;
  363. case "scaleBy":
  364. case "scaleTo":
  365. // No need for transformBy or worldTransformBy because they call transformTo and worldTransformTo
  366. case "transformTo":
  367. case "worldTransformTo":
  368. //resetInterpolationFromViewDriver(nodeID, methodParameters, 'rotation')
  369. break;
  370. }
  371. if (this.nodes[nodeID].extends == "proxy/aframe/acamera.vwf") {
  372. if (methodName == "setCameraToActive") {
  373. if (methodParameters[0] == vwf.moniker_) {
  374. console.log("set active");
  375. let offsetComp = node.aframeObj.getAttribute('viewoffset');
  376. if (offsetComp) {
  377. let offsetCompID = vwf.find(nodeID, 'viewoffset');
  378. self.kernel.callMethod(offsetCompID, "setParams", []);
  379. }
  380. node.aframeObj.setAttribute('camera', 'active', true);
  381. document.querySelector('a-scene').emit('makeActiveCamera');
  382. }
  383. }
  384. }
  385. // if (methodName == "createGooglePoly") {
  386. // }
  387. if (methodName == "createLocalRaycaster") {
  388. //var clientThatSatProperty = self.kernel.client();
  389. var me = self.kernel.moniker();
  390. // If the transform property was initially updated by this view....
  391. if (nodeID.includes(me)) {
  392. console.log('Creating raycaster for ME: ', nodeID);
  393. let xrcontroller = document.querySelector('#'+nodeID);
  394. xrcontroller.setAttribute('raycaster', {
  395. objects: '.intersectable',
  396. showLine: false,
  397. far: 100,
  398. recursive: false,
  399. interval: 10});
  400. // xrcontroller.addEventListener('raycaster-intersection', function (evt) {
  401. // let int = evt.detail.intersections[0];
  402. // let idata = {
  403. // point: int.point,
  404. // elID: int.object.el.id
  405. // }
  406. // console.log(idata)
  407. // })
  408. // xrcontroller.addEventListener('raycaster-intersection-cleared', function (evt) {
  409. // })
  410. }
  411. }
  412. }
  413. });
  414. }
  415. resetInterpolationFromViewDriver(nodeID, methodParameters, propertyName) {
  416. if (methodParameters.length < 2 || methodParameters[1] == 0) {
  417. let viewNode = self.nodes[nodeID];
  418. if (viewNode.components.interpolation) {
  419. let interID = viewNode.components.interpolation;
  420. let viewComponentDriver = vwf.views["/drivers/view/aframeComponent"];
  421. viewComponentDriver.resetInterpolation(interID, propertyName);
  422. }
  423. }
  424. }
  425. // Receive Model Transform Changes algorithm
  426. // 1.0 If (own view changes) then IGNORE (only if no external changes have occurred since the user’s view
  427. // requested this change – otherwise, will need to treat like 1.1 or 1.2)
  428. // 1.1 Elseif (other external changes and no outstanding own view changes) then ADOPT
  429. // 1.2 Else Interpolate to the model’s transform (conflict b/w own view and external sourced model changes)
  430. receiveModelTransformChanges(nodeID, propertyName, propertyValue) {
  431. let self = this.instance;
  432. var node = self.state.nodes[nodeID];
  433. // If the node does not exist in the state's list of nodes, then this update is from a prototype and we
  434. // should ignore it
  435. if (!node ) {
  436. return;
  437. }
  438. if(node.aframeObj.object3D) {
  439. // If the transform property was initially updated by this view....
  440. if (node.ignoreNextTransformUpdate) {
  441. node.outstandingTransformRequests.shift();
  442. node.ignoreNextTransformUpdate = false;
  443. } else {
  444. // adoptTransform( node, transformMatrix );
  445. let prop = self.state.setFromValue(propertyValue);
  446. if (propertyName == 'position') {
  447. let pos = prop.clone();
  448. node.aframeObj.object3D.position.copy(pos);
  449. } else if (propertyName == 'rotation') {
  450. let rot = prop.clone();
  451. node.aframeObj.object3D.rotation.set(
  452. THREE.Math.degToRad(rot.x),
  453. THREE.Math.degToRad(rot.y),
  454. THREE.Math.degToRad(rot.z)
  455. )
  456. //node.aframeObj.object3D.rotation.set(rot[0], rot[1], rot[2]);
  457. } else if (propertyName == 'scale') {
  458. let scale = prop.clone();
  459. node.aframeObj.object3D.scale.copy(scale);
  460. }
  461. }
  462. }
  463. }
  464. compareCoordinates(a, b, delta) {
  465. return Math.abs(a.x - b.x) > delta || Math.abs(a.y - b.y) > delta || Math.abs(a.z - b.z) > delta
  466. }
  467. getWorldRotation(el, order) {
  468. var worldQuat = new THREE.Quaternion();
  469. el.object3D.getWorldQuaternion(worldQuat);
  470. //console.log(worldQuat);
  471. let angle = (new THREE.Euler()).setFromQuaternion(worldQuat, order);
  472. let rotation = (new THREE.Vector3(THREE.Math.radToDeg(angle.x),
  473. THREE.Math.radToDeg(angle.y), THREE.Math.radToDeg(angle.z)));
  474. return rotation
  475. }
  476. updateAvatarPosition() {
  477. let self = this.instance;
  478. let delta = 0.001;
  479. let avatarName = 'avatar-' + self.kernel.moniker();
  480. var node = self.state.nodes[avatarName];
  481. if (!node) return;
  482. if (!node.aframeObj) return;
  483. let el = document.querySelector('#avatarControl');
  484. let elA = document.querySelector('#avatarControlParent');
  485. if (el && elA) {
  486. var position;
  487. if((self.hmd && self.sixDoF) || (self.hmd && self.threeDoF) || _app.config.d6DoF || _app.config.d3DoF){
  488. let positionC = el.object3D.position.clone();
  489. let positionA = elA.object3D.position.clone();
  490. position = positionC.add(positionA);
  491. } else {
  492. position = el.object3D.position;
  493. }
  494. //let position = el.object3D.position.add(elA.object3D.position);
  495. let rotation = el.getAttribute('rotation'); //getWorldRotation(el, 'YXZ');
  496. let lastRotation = self.nodes[avatarName].selfTickRotation;
  497. let lastPosition = self.nodes[avatarName].selfTickPosition ? self.nodes[avatarName].selfTickPosition: new THREE.Vector3(0, 0, 0);
  498. // let currentPosition = node.aframeObj.getAttribute('position');
  499. // let currentRotation = node.aframeObj.getAttribute('rotation');
  500. // compareCoordinates(position, lastPosition, delta)
  501. if(position && lastPosition ) {
  502. let distance = lastPosition.distanceTo(position);
  503. if (distance > delta)
  504. {
  505. // console.log("position not equal");
  506. self.kernel.setProperty(avatarName, "position", position);
  507. }
  508. }
  509. if (rotation && lastRotation) {
  510. let distance = Math.abs(rotation.y - lastRotation.y);
  511. if ( distance > delta) {
  512. //console.log("rotation not equal")
  513. if (self.isDesktop) {
  514. self.kernel.callMethod(avatarName, "updateAvatarBodyRotation", [rotation]);
  515. } else {
  516. self.kernel.callMethod(avatarName, "updateAvatarRotation", [rotation]);
  517. }
  518. }
  519. }
  520. self.nodes[avatarName].selfTickRotation = Object.assign({}, rotation);
  521. //self.nodes[avatarName].selfTickPosition = Object.assign({}, position);
  522. self.nodes[avatarName].selfTickPosition = position.clone();
  523. }
  524. }
  525. updateDesktopController(aName, aSelector) {
  526. let self = this.instance;
  527. //let avatarName = 'avatar-' + self.kernel.moniker();
  528. let delta = 0.001
  529. let avatarID = 'avatar-' + self.kernel.moniker();
  530. let avatarName = aName + self.kernel.moniker();
  531. var node = self.state.nodes[avatarName];
  532. if (!node) return;
  533. if (!node.aframeObj) return;
  534. //let elA = document.querySelector('#avatarControlParent');
  535. let elA = document.querySelector('#avatarControl');
  536. let el = document.querySelector(aSelector);
  537. let xrController = document.querySelector('#' + avatarName);
  538. if (el && elA) {
  539. // let positionC = el.object3D.position.clone();
  540. // let positionA = elA.object3D.position.clone();
  541. // let position = positionC.add(positionA);
  542. let position = elA.object3D.position;
  543. //new THREE.Vector3(elA.object3D.position.x, elA.object3D.position.y-0.05, elA.object3D.position.z);
  544. //let position = elA.object3D.position;
  545. // let mouse = el.components["desktop-controls"]._mouse;
  546. // self.kernel.callMethod(avatarName, "trackMouse",[mouse]);
  547. var rotation = el.getAttribute('rotation');
  548. var headRotation = el.object3D.quaternion;
  549. if (self.isMobile) {
  550. var headWorldQuat = new THREE.Quaternion();
  551. elA.object3D.getWorldQuaternion(headWorldQuat);
  552. rotation = this.getWorldRotation(elA, 'XYZ');
  553. headRotation = headWorldQuat;
  554. }
  555. //let rotation = el.getAttribute('rotation');
  556. //((AFRAME.utils.device.isMobile() && !AFRAME.utils.device.isMobileVR()) || self.isDesktop) ? elA.getAttribute('rotation') : el.getAttribute('rotation');
  557. //let rotation = el.getAttribute('rotation'); //this.getWorldRotation(el, 'YXZ');
  558. let lastRotation = self.nodes[avatarName].selfTickRotation;
  559. let lastPosition = self.nodes[avatarName].selfTickPosition ? self.nodes[avatarName].selfTickPosition: new THREE.Vector3(0, 0, 0);
  560. // let currentPosition = node.aframeObj.getAttribute('position');
  561. //let currentRotation = node.aframeObj.getAttribute('rotation');
  562. if (position && lastPosition) {
  563. let distance = lastPosition.distanceTo(position);
  564. if (distance > delta)
  565. {
  566. // console.log("position not equal");
  567. let idata = el.components["desktop-controls"].intersectionData;
  568. //if(idata) console.log('Point to: ', idata.point, ' intersect ', idata.elID);
  569. self.kernel.setProperty(avatarName, "position", position);
  570. self.kernel.callMethod(avatarName, "moveVRController",[idata]);
  571. }
  572. }
  573. if (rotation && lastRotation) {
  574. let distance = this.compareCoordinates(rotation, lastRotation, delta)
  575. if (distance)
  576. {
  577. //console.log("rotation not equal");
  578. let idata = el.components["desktop-controls"].intersectionData;
  579. //if(idata) console.log('Point to: ', idata.point, ' intersect ', idata.elID);
  580. self.kernel.setProperty(avatarName, "rotation", rotation);
  581. self.kernel.callMethod(avatarName, "moveVRController",[idata]);
  582. self.kernel.callMethod(avatarID, "moveHead", [headRotation]);
  583. }
  584. }
  585. self.nodes[avatarName].selfTickPosition = position.clone();
  586. self.nodes[avatarName].selfTickRotation = Object.assign({}, rotation);
  587. }
  588. }
  589. updateHandControllerVR(aName, aSelector) {
  590. let self = this.instance;
  591. //let avatarName = 'avatar-' + self.kernel.moniker();
  592. let delta = 0.001
  593. let avatarName = aName + self.kernel.moniker();
  594. var node = self.state.nodes[avatarName];
  595. if (!node) return;
  596. if (!node.aframeObj) return;
  597. let elA = document.querySelector('#avatarControlParent');
  598. let el = document.querySelector(aSelector);
  599. if (el && elA) {
  600. let positionC = el.object3D.position.clone();
  601. let positionA = elA.object3D.position.clone();
  602. let position = positionC.add(positionA);
  603. let rotation = el.getAttribute('rotation'); //getWorldRotation(el, 'YXZ');
  604. let lastRotation = self.nodes[avatarName].selfTickRotation;
  605. let lastPosition = self.nodes[avatarName].selfTickPosition ? self.nodes[avatarName].selfTickPosition: new THREE.Vector3(0, 0, 0);
  606. // let currentPosition = node.aframeObj.getAttribute('position');
  607. //let currentRotation = node.aframeObj.getAttribute('rotation');
  608. if (position && lastPosition) {
  609. let distance = lastPosition.distanceTo(position);
  610. if (distance > delta)
  611. {
  612. //let idata = el.components["xrcontroller"].intersectionData;
  613. let intersection = el.components.raycaster.intersections[0];
  614. let point = intersection ? intersection.point : null;
  615. let elID = intersection ? intersection.object.el.id : null;
  616. let idata = point ? {
  617. point: point,
  618. elID: elID
  619. } : null;
  620. // console.log("position not equal");
  621. self.kernel.setProperty(avatarName, "position", position);
  622. self.kernel.callMethod(avatarName, "moveVRController",[idata]);
  623. }
  624. }
  625. if (rotation && lastRotation) {
  626. let distance = this.compareCoordinates(rotation, lastRotation, delta)
  627. if (distance)
  628. {
  629. let intersection = el.components.raycaster.intersections[0];
  630. let point = intersection ? intersection.point : null;
  631. let elID = intersection ? intersection.object.el.id : null;
  632. let idata = point ? {
  633. point: point,
  634. elID: elID
  635. } : null;
  636. //console.log("rotation not equal");
  637. self.kernel.setProperty(avatarName, "rotation", rotation);
  638. self.kernel.callMethod(avatarName, "moveVRController",[idata]);
  639. }
  640. }
  641. // if (position && rotation && lastRotation && lastPosition) {
  642. // if (compareCoordinates(position, lastPosition, delta) || compareCoordinates(rotation, lastRotation, delta)) {
  643. // console.log("not equal!!");
  644. // vwf_view.kernel.callMethod(avatarName, "updateVRControl", [position, rotation]);
  645. // }
  646. // }
  647. //vwf_view.kernel.callMethod(avatarName, "updateVRControl", [position, rotation]);
  648. self.nodes[avatarName].selfTickPosition = position.clone();
  649. self.nodes[avatarName].selfTickRotation = Object.assign({}, rotation);
  650. }
  651. }
  652. getMovementVector(el, vel) {
  653. var directionVector = new THREE.Vector3(0, 0, 0);
  654. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  655. var rotation = el.getAttribute('rotation');
  656. var velocity = vel;
  657. directionVector.copy(velocity);
  658. directionVector.multiplyScalar(0.05);
  659. // Absolute.
  660. if (!rotation) { return directionVector; }
  661. //xRotation = this.data.fly ? rotation.x : 0;
  662. // Transform direction relative to heading.
  663. rotationEuler.set(THREE.Math.degToRad(0), THREE.Math.degToRad(rotation.y), 0);
  664. directionVector.applyEuler(rotationEuler);
  665. return directionVector;
  666. }
  667. setJoystickMoveInput (event) {
  668. const axes = event.detail.axis;
  669. //console.log(axes);
  670. let el = document.querySelector('#avatarControl');
  671. let position = new THREE.Vector3();
  672. el.object3D.localToWorld(position);//getWorldPosition(position);
  673. let vel = new THREE.Vector3(axes[0], 0, -axes[1]);
  674. el.object3D.position.add(this.getMovementVector(el,vel));
  675. }
  676. setJoystickRotateY (event) {
  677. const val = event.detail.value;
  678. //console.log(val);
  679. let el = document.querySelector('#avatarControl');
  680. let rotation = el.object3D.rotation;
  681. el.object3D.rotation.y += (-val)+rotation.y;
  682. //el.object3D.rotation.set(rotation.x,-val+rotation.y, rotation.z)
  683. }
  684. setJoystickRotateX (event) {
  685. const val = event.detail.value;
  686. //console.log(val);
  687. let el = document.querySelector('#avatarControl');
  688. let rotation = el.object3D.rotation;
  689. el.object3D.rotation.x += val+rotation.x;
  690. //el.object3D.rotation.set(val+rotation.x, rotation.y, rotation.z)
  691. }
  692. async createAvatarControl(aScene) {
  693. let self = this.instance;
  694. let avatarName = 'avatar-' + self.kernel.moniker();
  695. let avatarEl = document.createElement('a-entity');
  696. avatarEl.setAttribute('id', 'avatarControlParent');
  697. //avatarEl.setAttribute('position', '0 1.6 0');
  698. let controlEl = document.createElement('a-camera');
  699. controlEl.setAttribute('id', 'avatarControl');
  700. controlEl.setAttribute('wasd-controls', {acceleration:20});
  701. controlEl.setAttribute('look-controls', { pointerLockEnabled: false});
  702. controlEl.setAttribute('look-controls', 'enabled', true );
  703. controlEl.setAttribute('camera', 'near', 0.1 );
  704. //controlEl.setAttribute('gamepad-controls', {'controller': 0});
  705. let cursorEl = document.createElement('a-cursor');
  706. cursorEl.setAttribute('id', 'cursor-' + avatarName);
  707. cursorEl.setAttribute('raycaster', {});
  708. cursorEl.setAttribute('raycaster', 'objects', '.clickable');
  709. cursorEl.setAttribute('raycaster', 'showLine', false);
  710. if (self.d3DoF || _app.config.d3DoF) {
  711. //avatarEl.setAttribute('gearvr-controls', {});
  712. avatarEl.setAttribute('movement-controls', {});//{'controls': 'gamepad'});
  713. //avatarEl.setAttribute("gamepad-controls", {});
  714. //avatarEl.setAttribute('position', '0 0 0');
  715. }
  716. else if (AFRAME.utils.device.isMobile()) {
  717. //self.state.showMobileJoystick()
  718. //controlEl.setAttribute('look-controls', 'enabled', true );
  719. controlEl.setAttribute("virtual-gamepad-controls", {});
  720. controlEl.addEventListener("move", this.setJoystickMoveInput.bind(this));
  721. }
  722. //controlEl.addEventListener("rotateY", setJoystickRotateY);
  723. //controlEl.addEventListener("rotateX", setJoystickRotateX);
  724. //controlEl.setAttribute('gearvr-controls',{});
  725. else if (self.isDesktop){
  726. cursorEl.setAttribute('cursor',
  727. {
  728. rayOrigin: 'mouse'
  729. });
  730. cursorEl.setAttribute('visible', false);
  731. }
  732. // cursorEl.setAttribute('raycaster', {objects: '.intersectable', showLine: true, far: 100});
  733. // cursorEl.setAttribute('raycaster', 'showLine', true);
  734. controlEl.appendChild(cursorEl);
  735. avatarEl.appendChild(controlEl);
  736. aScene.appendChild(avatarEl);
  737. controlEl.setAttribute('camera', 'active', true);
  738. //avatarEl.setAttribute('avatar', {});
  739. // let arControl = document.createElement('a-entity');
  740. // arControl.setAttribute('id', 'arControlParent');
  741. // arControl.setAttribute('camera', {
  742. // active: true,
  743. // "look-controls-enabled": false,
  744. // "wasd-controls-enabled": false,
  745. // "user-height": 0
  746. // });
  747. // aScene.appendChild(arControl);
  748. return "OK!"
  749. // cb();
  750. }
  751. createXR(nodeID, nodeName, props) {
  752. let self = this;
  753. var newNode = {
  754. "id": nodeName,
  755. "uri": nodeName,
  756. "extends": "proxy/aframe/xrcontroller.vwf",
  757. "properties": {
  758. }
  759. }
  760. if (!self.state.nodes[nodeName]) {
  761. vwf_view.kernel.createChild(nodeID, nodeName, newNode);
  762. vwf_view.kernel.callMethod(nodeName, "createController", [props.position]);
  763. //"/../assets/controller/wmrvr.gltf"
  764. }
  765. }
  766. createGearVRController(nodeID, nodeName) {
  767. let self = this;
  768. var newNode = {
  769. "id": nodeName,
  770. "uri": nodeName,
  771. "extends": "proxy/aframe/gearvrcontroller.vwf",
  772. "properties": {
  773. }
  774. }
  775. if (!self.state.nodes[nodeName]) {
  776. vwf_view.kernel.createChild(nodeID, nodeName, newNode);
  777. vwf_view.kernel.callMethod(nodeName, "createController", []);
  778. //"/../assets/controller/gearvr.gltf"
  779. }
  780. }
  781. postLoadAction(nodeID) {
  782. //vwf_view.kernel.fireEvent(nodeID, "postLoadAction")
  783. }
  784. createAvatar(nodeID) {
  785. let self = this;
  786. // vwf_view.kernel.fireEvent(nodeID, "createAvatar");
  787. var avatarName = 'avatar-' + self.kernel.moniker();
  788. console.log("creating avatar...");
  789. // let avatarID = self.kernel.moniker();
  790. // var nodeName = 'avatar-' + avatarID;
  791. var newNode = {
  792. "id": avatarName,
  793. "uri": avatarName,
  794. "extends": "proxy/aframe/avatar.vwf",
  795. "properties": {
  796. "localUrl": '',
  797. "remoteUrl": '',
  798. // "displayName": 'Avatar ' + randId(),
  799. "sharing": { audio: true, video: true },
  800. "selectMode": false,
  801. "position": [0, 1.6, 0]
  802. }
  803. }
  804. if (!self.state.nodes[avatarName]) {
  805. if (_LCSDB.user().is) {
  806. _LCSDB.user().get('profile').get('alias').once(alias => {
  807. if (alias){
  808. newNode.properties.displayName = alias;
  809. //vwf_view.kernel.callMethod(avatarName, "setMyName", [alias]);
  810. }
  811. vwf_view.kernel.createChild(nodeID, avatarName, newNode);
  812. });
  813. _LCSDB.user().get('profile').get('avatarNode').not(res=>{
  814. //vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  815. })
  816. _LCSDB.user().get('profile').get('avatarNode').once(res => {
  817. var myNode = null;
  818. if (res) {
  819. //myNode = JSON.parse(res.avatarNode);
  820. var myNode = res;
  821. if (_app.helpers.testJSON(res)){
  822. myNode = JSON.parse(res);
  823. }
  824. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", [myNode, null]);
  825. } else {
  826. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  827. }
  828. // newNode.properties.displayName = res.alias;
  829. //"/../assets/avatars/male/avatar1.gltf"
  830. //vwf_view.kernel.callMethod(avatarName, 'setUserAvatar', [res] );
  831. });
  832. } else {
  833. vwf_view.kernel.createChild(nodeID, avatarName, newNode);
  834. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  835. //"/../assets/avatars/male/avatar1.gltf"
  836. }
  837. //
  838. }
  839. }
  840. createGearVRControls() {
  841. let avatarControl = document.querySelector('#avatarControlParent');
  842. let el = document.createElement('a-entity');
  843. el.setAttribute('id', 'gearvrcontrol');
  844. el.setAttribute('gearvr-controls', {
  845. 'hand': 'right',
  846. 'model': true
  847. });
  848. //el.setAttribute('laser-controls', {hand: "right"});
  849. // gearvr.setAttribute('gearvr-controls', 'hand', 'right');
  850. el.setAttribute('teleport-controls', {
  851. cameraRig: '#avatarControlParent',
  852. teleportOrigin: '#avatarControl',
  853. startEvents: 'teleportstart',
  854. endEvents: 'teleportend'
  855. });
  856. el.setAttribute('gearvrcontrol', {});
  857. avatarControl.appendChild(el);
  858. }
  859. createDesktopControls() {
  860. let self = this.instance;
  861. let avatarControl = document.querySelector('#avatarControlParent');
  862. let el = document.createElement('a-entity');
  863. el.setAttribute('id', 'mouse');
  864. // el.setAttribute('geometry', {
  865. // primitive: 'box', width: 0.2, height: 0.2, depth: 1
  866. // });
  867. // el.setAttribute('position', {
  868. // x: 0, y: 0, z: -1
  869. // });
  870. el.setAttribute('desktop-controls', {});
  871. // el.setAttribute('raycaster', {objects: ".intersectable", far: 1000, showLine: true});
  872. avatarControl.appendChild(el);
  873. }
  874. createXRControls(hand) {
  875. let self = this.instance;
  876. let avatarControl = document.querySelector('#avatarControlParent');
  877. let el = document.createElement('a-entity');
  878. el.setAttribute('id', 'xrcontroller' + hand);
  879. el.setAttribute('hand-controls', {
  880. 'hand': hand,
  881. 'handModelStyle': 'lowPoly',
  882. 'color': '#ffcccc'
  883. });
  884. el.setAttribute('laser-controls', {hand: hand, model:false});
  885. //el.setAttribute('raycaster', {objects: ".collidable", far: 5, showLine: false});
  886. // wmrvr.setAttribute('windows-motion-controls', '');
  887. // wmrvr.setAttribute('windows-motion-controls', 'hand', hand);
  888. el.setAttribute('xrcontroller', { 'hand': hand });
  889. //add teleport controls
  890. el.setAttribute('teleport-controls', {
  891. cameraRig: '#avatarControlParent',
  892. teleportOrigin: '#avatarControl',
  893. startEvents: 'teleportstart',
  894. endEvents: 'teleportend'
  895. });
  896. avatarControl.appendChild(el);
  897. }
  898. updateMaterial(node) {
  899. let self = this.instance;
  900. let elID = '#' + node.aframeObj.getAttribute('id');
  901. Object.entries(self.state.nodes).forEach(el => {
  902. let material = el[1].aframeObj.getAttribute('material');
  903. if (material) {
  904. if (!material.src) {
  905. let materialID = vwf.find(el[0], 'material');
  906. self.kernel.callMethod(materialID, "refreshSrc", []);
  907. }
  908. else if (material.src) {
  909. if (material.src !== "") {
  910. let src = '#' + material.src.id;
  911. if (src == elID) {
  912. let materialID = vwf.find(el[0], 'material');
  913. self.kernel.callMethod(materialID, "updateSrc", [elID])
  914. }
  915. }
  916. }
  917. }
  918. })
  919. }
  920. }
  921. export { AFrameView as default }