aframe.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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 = ['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. // 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 }