aframe.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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. if (eventName == "changingTransformFromView") {
  272. var clientThatSatProperty = self.kernel.client();
  273. var me = self.kernel.moniker();
  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. let methodName = eventName +'Method';
  293. self.kernel.callMethod(nodeID, methodName, eventParameters);
  294. if (eventName == "clickEvent"){
  295. let mode = vwf.getProperty(avatarName, 'selectMode');
  296. if (mode) {
  297. console.log("allow to click!!!")
  298. vwf_view.kernel.setProperty(avatarName, 'selectMode', false);
  299. let editorDriver = vwf.views["/drivers/view/editor"];
  300. if (editorDriver) {
  301. let selectSwitch = document.querySelector('#selectNodeSwitch');
  302. // const selectSwitchComp = new mdc.iconButton.MDCIconButtonToggle(selectSwitch); //new mdc.select.MDCIconToggle
  303. selectSwitch._comp.on = false;
  304. let currentNodeDIV = document.querySelector('#currentNode');
  305. if (currentNodeDIV) currentNodeDIV._setNode(nodeID);
  306. }
  307. }
  308. }
  309. }
  310. let intersectEvents = ['hitstart', 'hitend', 'intersect', 'clearIntersect']; //'intersect',
  311. let hitEvent = intersectEvents.filter(el=> el == eventName.slice(0,-5))[0]; //slice Event word
  312. if (hitEvent)
  313. {
  314. var clientThatSatProperty = self.kernel.client();
  315. var me = self.kernel.moniker();
  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. // console.log("position not equal");
  613. self.kernel.setProperty(avatarName, "position", position);
  614. self.kernel.callMethod(avatarName, "moveVRController",[]);
  615. }
  616. }
  617. if (rotation && lastRotation) {
  618. let distance = this.compareCoordinates(rotation, lastRotation, delta)
  619. if (distance)
  620. {
  621. //console.log("rotation not equal");
  622. self.kernel.setProperty(avatarName, "rotation", rotation);
  623. self.kernel.callMethod(avatarName, "moveVRController",[]);
  624. }
  625. }
  626. // if (position && rotation && lastRotation && lastPosition) {
  627. // if (compareCoordinates(position, lastPosition, delta) || compareCoordinates(rotation, lastRotation, delta)) {
  628. // console.log("not equal!!");
  629. // vwf_view.kernel.callMethod(avatarName, "updateVRControl", [position, rotation]);
  630. // }
  631. // }
  632. //vwf_view.kernel.callMethod(avatarName, "updateVRControl", [position, rotation]);
  633. self.nodes[avatarName].selfTickPosition = position.clone();
  634. self.nodes[avatarName].selfTickRotation = Object.assign({}, rotation);
  635. }
  636. }
  637. getMovementVector(el, vel) {
  638. var directionVector = new THREE.Vector3(0, 0, 0);
  639. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  640. var rotation = el.getAttribute('rotation');
  641. var velocity = vel;
  642. directionVector.copy(velocity);
  643. directionVector.multiplyScalar(0.05);
  644. // Absolute.
  645. if (!rotation) { return directionVector; }
  646. //xRotation = this.data.fly ? rotation.x : 0;
  647. // Transform direction relative to heading.
  648. rotationEuler.set(THREE.Math.degToRad(0), THREE.Math.degToRad(rotation.y), 0);
  649. directionVector.applyEuler(rotationEuler);
  650. return directionVector;
  651. }
  652. setJoystickMoveInput (event) {
  653. const axes = event.detail.axis;
  654. //console.log(axes);
  655. let el = document.querySelector('#avatarControl');
  656. let position = new THREE.Vector3();
  657. el.object3D.localToWorld(position);//getWorldPosition(position);
  658. let vel = new THREE.Vector3(axes[0], 0, -axes[1]);
  659. el.object3D.position.add(this.getMovementVector(el,vel));
  660. }
  661. setJoystickRotateY (event) {
  662. const val = event.detail.value;
  663. //console.log(val);
  664. let el = document.querySelector('#avatarControl');
  665. let rotation = el.object3D.rotation;
  666. el.object3D.rotation.y += (-val)+rotation.y;
  667. //el.object3D.rotation.set(rotation.x,-val+rotation.y, rotation.z)
  668. }
  669. setJoystickRotateX (event) {
  670. const val = event.detail.value;
  671. //console.log(val);
  672. let el = document.querySelector('#avatarControl');
  673. let rotation = el.object3D.rotation;
  674. el.object3D.rotation.x += val+rotation.x;
  675. //el.object3D.rotation.set(val+rotation.x, rotation.y, rotation.z)
  676. }
  677. async createAvatarControl(aScene) {
  678. let self = this.instance;
  679. let avatarName = 'avatar-' + self.kernel.moniker();
  680. let avatarEl = document.createElement('a-entity');
  681. avatarEl.setAttribute('id', 'avatarControlParent');
  682. //avatarEl.setAttribute('position', '0 1.6 0');
  683. let controlEl = document.createElement('a-camera');
  684. controlEl.setAttribute('id', 'avatarControl');
  685. controlEl.setAttribute('wasd-controls', {acceleration:20});
  686. controlEl.setAttribute('look-controls', { pointerLockEnabled: false});
  687. controlEl.setAttribute('look-controls', 'enabled', true );
  688. controlEl.setAttribute('camera', 'near', 0.1 );
  689. //controlEl.setAttribute('gamepad-controls', {'controller': 0});
  690. let cursorEl = document.createElement('a-cursor');
  691. cursorEl.setAttribute('id', 'cursor-' + avatarName);
  692. cursorEl.setAttribute('raycaster', {});
  693. cursorEl.setAttribute('raycaster', 'objects', '.clickable');
  694. cursorEl.setAttribute('raycaster', 'showLine', false);
  695. if (self.d3DoF || _app.config.d3DoF) {
  696. //avatarEl.setAttribute('gearvr-controls', {});
  697. avatarEl.setAttribute('movement-controls', {});//{'controls': 'gamepad'});
  698. //avatarEl.setAttribute("gamepad-controls", {});
  699. //avatarEl.setAttribute('position', '0 0 0');
  700. }
  701. else if (AFRAME.utils.device.isMobile()) {
  702. //self.state.showMobileJoystick()
  703. //controlEl.setAttribute('look-controls', 'enabled', true );
  704. controlEl.setAttribute("virtual-gamepad-controls", {});
  705. controlEl.addEventListener("move", this.setJoystickMoveInput.bind(this));
  706. }
  707. //controlEl.addEventListener("rotateY", setJoystickRotateY);
  708. //controlEl.addEventListener("rotateX", setJoystickRotateX);
  709. //controlEl.setAttribute('gearvr-controls',{});
  710. else if (self.isDesktop){
  711. cursorEl.setAttribute('cursor', {rayOrigin: 'mouse'});
  712. }
  713. // cursorEl.setAttribute('raycaster', {objects: '.intersectable', showLine: true, far: 100});
  714. // cursorEl.setAttribute('raycaster', 'showLine', true);
  715. controlEl.appendChild(cursorEl);
  716. avatarEl.appendChild(controlEl);
  717. aScene.appendChild(avatarEl);
  718. controlEl.setAttribute('camera', 'active', true);
  719. //avatarEl.setAttribute('avatar', {});
  720. // let arControl = document.createElement('a-entity');
  721. // arControl.setAttribute('id', 'arControlParent');
  722. // arControl.setAttribute('camera', {
  723. // active: true,
  724. // "look-controls-enabled": false,
  725. // "wasd-controls-enabled": false,
  726. // "user-height": 0
  727. // });
  728. // aScene.appendChild(arControl);
  729. return "OK!"
  730. // cb();
  731. }
  732. createXR(nodeID, nodeName, props) {
  733. let self = this;
  734. var newNode = {
  735. "id": nodeName,
  736. "uri": nodeName,
  737. "extends": "proxy/aframe/xrcontroller.vwf",
  738. "properties": {
  739. }
  740. }
  741. if (!self.state.nodes[nodeName]) {
  742. vwf_view.kernel.createChild(nodeID, nodeName, newNode);
  743. vwf_view.kernel.callMethod(nodeName, "createController", [props.position]);
  744. //"/../assets/controller/wmrvr.gltf"
  745. }
  746. }
  747. createGearVRController(nodeID, nodeName) {
  748. let self = this;
  749. var newNode = {
  750. "id": nodeName,
  751. "uri": nodeName,
  752. "extends": "proxy/aframe/gearvrcontroller.vwf",
  753. "properties": {
  754. }
  755. }
  756. if (!self.state.nodes[nodeName]) {
  757. vwf_view.kernel.createChild(nodeID, nodeName, newNode);
  758. vwf_view.kernel.callMethod(nodeName, "createController", []);
  759. //"/../assets/controller/gearvr.gltf"
  760. }
  761. }
  762. postLoadAction(nodeID) {
  763. //vwf_view.kernel.fireEvent(nodeID, "postLoadAction")
  764. }
  765. createAvatar(nodeID) {
  766. let self = this;
  767. // vwf_view.kernel.fireEvent(nodeID, "createAvatar");
  768. var avatarName = 'avatar-' + self.kernel.moniker();
  769. console.log("creating avatar...");
  770. // let avatarID = self.kernel.moniker();
  771. // var nodeName = 'avatar-' + avatarID;
  772. var newNode = {
  773. "id": avatarName,
  774. "uri": avatarName,
  775. "extends": "proxy/aframe/avatar.vwf",
  776. "properties": {
  777. "localUrl": '',
  778. "remoteUrl": '',
  779. // "displayName": 'Avatar ' + randId(),
  780. "sharing": { audio: true, video: true },
  781. "selectMode": false,
  782. "position": [0, 1.6, 0]
  783. }
  784. }
  785. if (!self.state.nodes[avatarName]) {
  786. if (_LCSDB.user().is) {
  787. _LCSDB.user().get('profile').get('alias').once(alias => {
  788. if (alias){
  789. newNode.properties.displayName = alias;
  790. //vwf_view.kernel.callMethod(avatarName, "setMyName", [alias]);
  791. }
  792. vwf_view.kernel.createChild(nodeID, avatarName, newNode);
  793. });
  794. _LCSDB.user().get('profile').get('avatarNode').not(res=>{
  795. //vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  796. })
  797. _LCSDB.user().get('profile').get('avatarNode').once(res => {
  798. var myNode = null;
  799. if (res) {
  800. //myNode = JSON.parse(res.avatarNode);
  801. var myNode = res;
  802. if (_app.helpers.testJSON(res)){
  803. myNode = JSON.parse(res);
  804. }
  805. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", [myNode, null]);
  806. } else {
  807. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  808. }
  809. // newNode.properties.displayName = res.alias;
  810. //"/../assets/avatars/male/avatar1.gltf"
  811. //vwf_view.kernel.callMethod(avatarName, 'setUserAvatar', [res] );
  812. });
  813. } else {
  814. vwf_view.kernel.createChild(nodeID, avatarName, newNode);
  815. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  816. //"/../assets/avatars/male/avatar1.gltf"
  817. }
  818. //
  819. }
  820. }
  821. createGearVRControls() {
  822. let avatarControl = document.querySelector('#avatarControlParent');
  823. let el = document.createElement('a-entity');
  824. el.setAttribute('id', 'gearvrcontrol');
  825. el.setAttribute('gearvr-controls', {
  826. 'hand': 'right',
  827. 'model': true
  828. });
  829. //el.setAttribute('laser-controls', {hand: "right"});
  830. // gearvr.setAttribute('gearvr-controls', 'hand', 'right');
  831. el.setAttribute('teleport-controls', {
  832. cameraRig: '#avatarControlParent',
  833. teleportOrigin: '#avatarControl',
  834. startEvents: 'teleportstart',
  835. endEvents: 'teleportend'
  836. });
  837. el.setAttribute('gearvrcontrol', {});
  838. avatarControl.appendChild(el);
  839. }
  840. createDesktopControls() {
  841. let self = this.instance;
  842. let avatarControl = document.querySelector('#avatarControlParent');
  843. let el = document.createElement('a-entity');
  844. el.setAttribute('id', 'mouse');
  845. // el.setAttribute('geometry', {
  846. // primitive: 'box', width: 0.2, height: 0.2, depth: 1
  847. // });
  848. // el.setAttribute('position', {
  849. // x: 0, y: 0, z: -1
  850. // });
  851. el.setAttribute('desktop-controls', {});
  852. // el.setAttribute('raycaster', {objects: ".intersectable", far: 1000, showLine: true});
  853. avatarControl.appendChild(el);
  854. }
  855. createXRControls(hand) {
  856. let self = this.instance;
  857. let avatarControl = document.querySelector('#avatarControlParent');
  858. let el = document.createElement('a-entity');
  859. el.setAttribute('id', 'xrcontroller' + hand);
  860. el.setAttribute('hand-controls', {
  861. 'hand': hand,
  862. 'handModelStyle': 'lowPoly',
  863. 'color': '#ffcccc'
  864. });
  865. el.setAttribute('laser-controls', {hand: hand, model:false});
  866. //el.setAttribute('raycaster', {objects: ".collidable", far: 5, showLine: false});
  867. // wmrvr.setAttribute('windows-motion-controls', '');
  868. // wmrvr.setAttribute('windows-motion-controls', 'hand', hand);
  869. el.setAttribute('xrcontroller', { 'hand': hand });
  870. //add teleport controls
  871. el.setAttribute('teleport-controls', {
  872. cameraRig: '#avatarControlParent',
  873. teleportOrigin: '#avatarControl',
  874. startEvents: 'teleportstart',
  875. endEvents: 'teleportend'
  876. });
  877. avatarControl.appendChild(el);
  878. }
  879. updateMaterial(node) {
  880. let self = this.instance;
  881. let elID = '#' + node.aframeObj.getAttribute('id');
  882. Object.entries(self.state.nodes).forEach(el => {
  883. let material = el[1].aframeObj.getAttribute('material');
  884. if (material) {
  885. if (!material.src) {
  886. let materialID = vwf.find(el[0], 'material');
  887. self.kernel.callMethod(materialID, "refreshSrc", []);
  888. }
  889. else if (material.src) {
  890. if (material.src !== "") {
  891. let src = '#' + material.src.id;
  892. if (src == elID) {
  893. let materialID = vwf.find(el[0], 'material');
  894. self.kernel.callMethod(materialID, "updateSrc", [elID])
  895. }
  896. }
  897. }
  898. }
  899. })
  900. }
  901. }
  902. export { AFrameView as default }