aframe.js 44 KB

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