aframe-components.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2018 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. */
  5. if (typeof AFRAME === 'undefined') {
  6. throw new Error('Component attempted to register before AFRAME was available.');
  7. }
  8. AFRAME.registerComponent('scene-utils', {
  9. init: function () {
  10. const sceneEnterVR = (e) => {
  11. //vwf_view.kernel.callMethod(vwf.application(), "enterVR");
  12. let avatarEl = document.querySelector('#avatarControlParent');
  13. if (AFRAME.utils.device.isMobileVR()) {
  14. } else if (AFRAME.utils.device.isMobile()) {
  15. avatarEl.setAttribute('position', '0 0 0')
  16. } else {
  17. avatarEl.setAttribute('position', '0 0 0'); //'0 1.6 0'
  18. }
  19. // if (!AFRAME.utils.device.isGearVR() && !AFRAME.utils.device.isMobile()) {
  20. // avatarEl.setAttribute('position', '0 1.6 0');
  21. // }
  22. }
  23. const sceneExitVR = (e) => {
  24. //vwf_view.kernel.callMethod(vwf.application(), "exitVR");
  25. let avatarEl = document.querySelector('#avatarControlParent');
  26. if (AFRAME.utils.device.isMobileVR()) {
  27. //avatarEl.setAttribute('position', '0 0 0');
  28. } else if (AFRAME.utils.device.isMobile()) {
  29. avatarEl.setAttribute('position', '0 1.6 0');
  30. } else {
  31. avatarEl.setAttribute('position', '0 0 0');
  32. }
  33. }
  34. this.el.sceneEl.addEventListener('enter-vr', sceneEnterVR);
  35. this.el.sceneEl.addEventListener('exit-vr', sceneExitVR);
  36. },
  37. update: function () {
  38. },
  39. tick: function (t) {
  40. }
  41. })
  42. AFRAME.registerComponent('linepath', {
  43. schema: {
  44. color: { default: '#000' },
  45. width: { default: 0.01 },
  46. path: {
  47. default: [
  48. { x: -0.5, y: 0, z: 0 },
  49. { x: 0.5, y: 0, z: 0 }
  50. ]
  51. // Deserialize path in the form of comma-separated vec3s: `0 0 0, 1 1 1, 2 0 3`.
  52. // parse: function (value) {
  53. // return value.split(',').map(coordinates.parse);
  54. // },
  55. // Serialize array of vec3s in case someone does setAttribute('line', 'path', [...]).
  56. // stringify: function (data) {
  57. // return data.map(coordinates.stringify).join(',');
  58. // }
  59. }
  60. },
  61. update: function () {
  62. var material = new MeshLineMaterial({
  63. color: new THREE.Color(this.data.color), //this.data.color
  64. lineWidth: this.data.width
  65. });
  66. var geometry = new THREE.Geometry();
  67. this.data.path.forEach(function (vec3) {
  68. geometry.vertices.push(
  69. new THREE.Vector3(vec3.x, vec3.y, vec3.z)
  70. );
  71. });
  72. let line = new MeshLine();
  73. line.setGeometry(geometry);
  74. //new THREE.Line(geometry, material)
  75. this.el.setObject3D('mesh', new THREE.Mesh(line.geometry, material));
  76. },
  77. remove: function () {
  78. this.el.removeObject3D('mesh');
  79. }
  80. });
  81. AFRAME.registerComponent('gizmo', {
  82. schema: {
  83. mode: { default: 'translate' }
  84. },
  85. update: function (old) {
  86. let modes = ['translate', 'rotate', 'scale'];
  87. if (!this.gizmo) {
  88. let newMode = modes.filter(el => {
  89. return el == this.data.mode
  90. })
  91. if (newMode.length !== 0) {
  92. this.mode = this.data.mode
  93. this.transformControls.setMode(this.mode)
  94. }
  95. }
  96. },
  97. init: function () {
  98. let self = this
  99. this.mode = this.data.mode
  100. let activeCamera = document.querySelector('#avatarControl').getObject3D('camera');
  101. let renderer = this.el.sceneEl.renderer;
  102. this.transformControls = new THREE.TransformControls(activeCamera, renderer.domElement);
  103. this.transformControls.attach(this.el.object3D);
  104. this.el.sceneEl.setObject3D('control-' + this.el.id, this.transformControls);
  105. this.transformControls.addEventListener('change', function (evt) {
  106. // console.log('changed');
  107. var object = self.transformControls.object;
  108. if (object === undefined) {
  109. return;
  110. }
  111. var transformMode = self.transformControls.getMode();
  112. switch (transformMode) {
  113. case 'translate':
  114. vwf_view.kernel.setProperty(object.el.id, 'position',
  115. [object.position.x, object.position.y, object.position.z])
  116. break;
  117. case 'rotate':
  118. // let q = (new THREE.Quaternion()).setFromEuler(new THREE.Euler(
  119. // (object.rotation.x),
  120. // (object.rotation.y),
  121. // (object.rotation.z), 'XYZ'
  122. // ));
  123. // let angle = (new THREE.Euler()).setFromQuaternion(q, 'YXZ');
  124. // vwf_view.kernel.setProperty(object.el.id, 'rotation', [THREE.Math.radToDeg(angle.x), THREE.Math.radToDeg(angle.y), THREE.Math.radToDeg(angle.z)])
  125. vwf_view.kernel.setProperty(object.el.id, 'rotation',
  126. [THREE.Math.radToDeg(object.rotation.x), THREE.Math.radToDeg(object.rotation.y), THREE.Math.radToDeg(object.rotation.z)])
  127. break;
  128. case 'scale':
  129. vwf_view.kernel.setProperty(object.el.id, 'scale',
  130. [object.scale.x, object.scale.y, object.scale.z])
  131. break;
  132. }
  133. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  134. });
  135. },
  136. remove: function () {
  137. this.transformControls.detach();
  138. this.el.sceneEl.removeObject3D('control-' + this.el.id);
  139. },
  140. tick: function (t) {
  141. // this.transformControls.update();
  142. }
  143. });
  144. AFRAME.registerComponent('cursor-listener', {
  145. init: function () {
  146. this.el.addEventListener('click', function (evt) {
  147. console.log('I was clicked at: ', evt.detail.intersection.point);
  148. let cursorID = 'cursor-avatar-' + vwf_view.kernel.moniker();
  149. if (evt.detail.cursorEl.id.includes(vwf_view.kernel.moniker())) {
  150. vwf_view.kernel.fireEvent(evt.detail.intersection.object.el.id, "clickEvent", [vwf_view.kernel.moniker()])
  151. }
  152. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  153. });
  154. }
  155. });
  156. AFRAME.registerComponent('aabb-collider-listener', {
  157. init: function () {
  158. // let self = this;
  159. // this.me = vwf_view.kernel.moniker();
  160. this.el.addEventListener('hitstart', function (evt) {
  161. vwf_view.kernel.fireEvent(evt.target.id, "hitstartEvent");
  162. })
  163. this.el.addEventListener('hitend', function (evt) {
  164. vwf_view.kernel.fireEvent(evt.target.id, "hitendEvent");
  165. })
  166. }
  167. });
  168. AFRAME.registerComponent('raycaster-listener', {
  169. init: function () {
  170. let self = this;
  171. this.intersected = false;
  172. this.casters = {}
  173. this.me = vwf_view.kernel.moniker();
  174. this.driver = vwf.views["vwf/view/aframe"];
  175. this.el.addEventListener('raycaster-intersected', function (evt) {
  176. if (evt.detail.el.nodeName == 'A-CURSOR') {
  177. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  178. } else {
  179. if (self.intersected) {
  180. } else {
  181. console.log('I was intersected at: ', evt.target);//evt.detail.getIntersection().point);
  182. vwf_view.kernel.fireEvent(evt.target.id, "intersectEvent");
  183. }
  184. self.casters[evt.target.id] = evt.target;
  185. self.intersected = true;
  186. }
  187. });
  188. this.el.addEventListener('raycaster-intersected-cleared', function (evt) {
  189. if (evt.detail.el.nodeName == 'A-CURSOR') {
  190. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  191. } else {
  192. if (self.intersected) {
  193. console.log('Clear intersection');
  194. if (Object.entries(self.casters).length == 1 && (self.casters[evt.target.id] !== undefined)) {
  195. vwf_view.kernel.fireEvent(evt.target.id, "clearIntersectEvent")
  196. }
  197. delete self.casters[evt.target.id]
  198. } else { }
  199. self.intersected = false;
  200. }
  201. });
  202. }
  203. });
  204. AFRAME.registerComponent('envmap', {
  205. /**
  206. * Creates a new THREE.ShaderMaterial using the two shaders defined
  207. * in vertex.glsl and fragment.glsl.
  208. */
  209. init: function () {
  210. const data = this.data;
  211. //this.applyToMesh();
  212. this.el.addEventListener('model-loaded', () => this.applyToMesh());
  213. },
  214. /**
  215. * Update the ShaderMaterial when component data changes.
  216. */
  217. update: function () {
  218. },
  219. getEnvMap: function () {
  220. var path = './assets/textures/skybox2/';
  221. var format = '.jpg';
  222. var urls = [
  223. path + 'px' + format, path + 'nx' + format,
  224. path + 'py' + format, path + 'ny' + format,
  225. path + 'pz' + format, path + 'nz' + format
  226. ];
  227. envMap = new THREE.CubeTextureLoader().load(urls);
  228. envMap.format = THREE.RGBFormat;
  229. return envMap;
  230. },
  231. /**
  232. * Apply the material to the current entity.
  233. */
  234. applyToMesh: function () {
  235. const mesh = this.el.getObject3D('mesh');
  236. //var scene = mesh;
  237. var envMap = this.getEnvMap();
  238. mesh.traverse(function (node) {
  239. if (node.material) {
  240. node.material.side = THREE.BackSide;
  241. node.material.needsUpdate = true;
  242. //side = THREE.DoubleSide; break;
  243. }
  244. });
  245. mesh.traverse(function (node) {
  246. if (node.material && (node.material.isMeshStandardMaterial ||
  247. (node.material.isShaderMaterial && node.material.envMap !== undefined))) {
  248. node.material.envMap = envMap;
  249. node.material.needsUpdate = true;
  250. }
  251. });
  252. // const mesh = this.el.getObject3D('mesh');
  253. // if (mesh) {
  254. // mesh.material = this.material;
  255. // }
  256. },
  257. /**
  258. * On each frame, update the 'time' uniform in the shaders.
  259. */
  260. tick: function (t) {
  261. }
  262. })
  263. //https://threejs.org/examples/webgl_shaders_sky.html
  264. AFRAME.registerComponent('skyshader', {
  265. makeSun: function () {
  266. let sunSphere = new THREE.Mesh(
  267. new THREE.SphereBufferGeometry(20000, 16, 8),
  268. new THREE.MeshBasicMaterial({ color: 0xffffff })
  269. );
  270. sunSphere.position.y = - 700000;
  271. sunSphere.visible = true;
  272. let scene = this.el.sceneEl;
  273. this.el.sceneEl.setObject3D('sun', sunSphere);
  274. },
  275. init: function () {
  276. //let sunSphereEl = document.querySelector('a-scene').querySelector('#sun');
  277. //this.sunSphere = sunSphereEl.object3D;
  278. this.makeSun();
  279. this.sunSphere = this.el.sceneEl.getObject3D('sun');
  280. this.sky = new THREE.Sky();
  281. let scene = this.el.sceneEl;
  282. let effectController = {
  283. turbidity: 5,
  284. rayleigh: 2,
  285. mieCoefficient: 0.005,
  286. mieDirectionalG: 0.8,
  287. luminance: 1,
  288. inclination: 0, // elevation / inclination
  289. azimuth: 0.25, // Facing front,
  290. sun: ! true
  291. };
  292. let uniforms = this.sky.uniforms;
  293. uniforms.turbidity.value = effectController.turbidity;
  294. uniforms.rayleigh.value = effectController.rayleigh;
  295. uniforms.luminance.value = effectController.luminance;
  296. uniforms.mieCoefficient.value = effectController.mieCoefficient;
  297. uniforms.mieDirectionalG.value = effectController.mieDirectionalG;
  298. this.el.setObject3D('mesh', this.sky.mesh);
  299. let distance = 400000;
  300. var theta = Math.PI * (effectController.inclination - 0.5);
  301. var phi = 2 * Math.PI * (effectController.azimuth - 0.5);
  302. this.sunSphere.position.x = distance * Math.cos(phi);
  303. this.sunSphere.position.y = distance * Math.sin(phi) * Math.sin(theta);
  304. this.sunSphere.position.z = distance * Math.sin(phi) * Math.cos(theta);
  305. this.sunSphere.visible = effectController.sun;
  306. this.sky.uniforms.sunPosition.value.copy(this.sunSphere.position);
  307. },
  308. update: function () {
  309. },
  310. tick: function (t) {
  311. }
  312. })
  313. AFRAME.registerComponent('sun', {
  314. init: function () {
  315. this.sunSphere = new THREE.Mesh(
  316. new THREE.SphereBufferGeometry(20000, 16, 8),
  317. new THREE.MeshBasicMaterial({ color: 0xffffff })
  318. );
  319. this.sunSphere.position.y = - 700000;
  320. this.sunSphere.visible = true;
  321. this.el.setObject3D('mesh', this.sunSphere);
  322. },
  323. update: function () {
  324. },
  325. tick: function (t) {
  326. }
  327. })
  328. AFRAME.registerComponent('gearvrcontrol', {
  329. init: function () {
  330. var self = this;
  331. var controllerID = 'gearvr-' + vwf_view.kernel.moniker();
  332. this.el.addEventListener('triggerdown', function (event) {
  333. vwf_view.kernel.callMethod(controllerID, "triggerdown", []);
  334. });
  335. this.el.addEventListener('triggerup', function (event) {
  336. vwf_view.kernel.callMethod(controllerID, "triggerup", []);
  337. });
  338. },
  339. update: function () {
  340. },
  341. tick: function (t) {
  342. }
  343. })
  344. AFRAME.registerComponent('wmrvrcontrol', {
  345. schema: {
  346. hand: { default: 'right' }
  347. },
  348. update: function (old) {
  349. this.hand = this.data.hand;
  350. },
  351. init: function () {
  352. var self = this;
  353. this.hand = this.data.hand;
  354. var controllerID = 'wrmr-' + this.hand + '-' + vwf_view.kernel.moniker();
  355. //this.gearel = document.querySelector('#gearvrcontrol');
  356. this.el.addEventListener('triggerdown', function (event) {
  357. vwf_view.kernel.callMethod(controllerID, "triggerdown", []);
  358. });
  359. this.el.addEventListener('triggerup', function (event) {
  360. vwf_view.kernel.callMethod(controllerID, "triggerup", []);
  361. });
  362. },
  363. tick: function (t) {
  364. }
  365. })
  366. AFRAME.registerComponent('streamsound', {
  367. schema: {
  368. positional: { default: true }
  369. },
  370. init: function () {
  371. var self = this;
  372. let driver = vwf.views["vwf/view/webrtc"];
  373. this.listener = null;
  374. this.stream = null;
  375. if (!this.sound) {
  376. this.setupSound();
  377. }
  378. if (driver) {
  379. //let avatarID = 'avatar-' + vwf.moniker();
  380. let avatarID = this.el.id.slice(0, 27); //avatar-0RtnYBBTBU84OCNcAAFY
  381. let client = driver.state.clients[avatarID];
  382. if (client) {
  383. if (client.connection) {
  384. this.stream = client.connection.stream;
  385. if (this.stream) {
  386. this.audioEl = new Audio();
  387. this.audioEl.srcObject = this.stream;
  388. this.sound.setNodeSource(this.sound.context.createMediaStreamSource(this.stream));
  389. }
  390. }
  391. }
  392. }
  393. },
  394. setupSound: function () {
  395. var el = this.el;
  396. var sceneEl = el.sceneEl;
  397. if (this.sound) {
  398. el.removeObject3D(this.attrName);
  399. }
  400. if (!sceneEl.audioListener) {
  401. sceneEl.audioListener = new THREE.AudioListener();
  402. sceneEl.camera && sceneEl.camera.add(sceneEl.audioListener);
  403. sceneEl.addEventListener('camera-set-active', function (evt) {
  404. evt.detail.cameraEl.getObject3D('camera').add(sceneEl.audioListener);
  405. });
  406. }
  407. this.listener = sceneEl.audioListener;
  408. this.sound = this.data.positional
  409. ? new THREE.PositionalAudio(this.listener)
  410. : new THREE.Audio(this.listener);
  411. el.setObject3D(this.attrName, this.sound);
  412. },
  413. remove: function () {
  414. if (!this.sound) return;
  415. this.el.removeObject3D(this.attrName);
  416. if (this.stream) {
  417. this.sound.disconnect();
  418. }
  419. },
  420. update: function (old) {
  421. },
  422. tick: function (t) {
  423. }
  424. })
  425. AFRAME.registerComponent('viewoffset', {
  426. // fullWidth:
  427. // fullHeight:
  428. // xoffset:
  429. // yoffset:
  430. // width:
  431. // height:
  432. schema: {
  433. fullWidth: { default: window.innerWidth },
  434. fullHeight: { default: window.innerHeight },
  435. xoffset: { default: window.innerWidth / 2 },
  436. yoffset: { default: window.innerHeight / 2 },
  437. width: { default: window.innerWidth },
  438. height: { default: window.innerHeight }
  439. },
  440. init: function () {
  441. var self = this;
  442. this.el.sceneEl.addEventListener('loaded', setOffset);
  443. function setOffset() {
  444. this.setNewOffset();
  445. }
  446. },
  447. update: function (old) {
  448. this.fullWidth = this.data.fullWidth;
  449. this.fullHeight = this.data.fullHeight;
  450. this.xoffset = this.data.xoffset;
  451. this.yoffset = this.data.yoffset;
  452. this.width = this.data.width;
  453. this.height = this.data.height;
  454. //console.log(this.data);
  455. this.setNewOffset();
  456. },
  457. setNewOffset: function () {
  458. this.el.object3DMap.camera.setViewOffset(
  459. this.data.fullWidth,
  460. this.data.fullHeight,
  461. this.data.xoffset,
  462. this.data.yoffset,
  463. this.data.width,
  464. this.data.height)
  465. },
  466. tick: function (t) {
  467. }
  468. })
  469. AFRAME.registerComponent("virtual-gamepad-controls", {
  470. schema: {},
  471. init() {
  472. this.onEnterVr = this.onEnterVr.bind(this);
  473. this.onExitVr = this.onExitVr.bind(this);
  474. this.onFirstInteraction = this.onFirstInteraction.bind(this);
  475. this.onMoveJoystickChanged = this.onMoveJoystickChanged.bind(this);
  476. this.onMoveJoystickEnd = this.onMoveJoystickEnd.bind(this);
  477. // this.onLookJoystickChanged = this.onLookJoystickChanged.bind(this);
  478. // this.onLookJoystickEnd = this.onLookJoystickEnd.bind(this);
  479. this.mockJoystickContainer = document.createElement("div");
  480. this.mockJoystickContainer.classList.add('mockJoystickContainer');
  481. const leftMock = document.createElement("div");
  482. leftMock.classList.add('mockJoystick');
  483. const leftMockSmall = document.createElement("div");
  484. leftMockSmall.classList.add('mockJoystick', 'inner');
  485. leftMock.appendChild(leftMockSmall);
  486. this.mockJoystickContainer.appendChild(leftMock);
  487. // const rightMock = document.createElement("div");
  488. // rightMock.classList.add('mockJoystick');
  489. // const rightMockSmall = document.createElement("div");
  490. // rightMockSmall.classList.add('mockJoystick', 'inner');
  491. // rightMock.appendChild(rightMockSmall);
  492. // this.mockJoystickContainer.appendChild(rightMock);
  493. document.body.appendChild(this.mockJoystickContainer);
  494. // Setup gamepad elements
  495. const leftTouchZone = document.createElement("div");
  496. leftTouchZone.classList.add('touchZone', 'left');
  497. document.body.appendChild(leftTouchZone);
  498. this.leftTouchZone = leftTouchZone;
  499. this.leftStick = nipplejs.create({
  500. zone: this.leftTouchZone,
  501. color: "white",
  502. fadeTime: 0
  503. });
  504. this.leftStick.on("start", this.onFirstInteraction);
  505. this.leftStick.on("move", this.onMoveJoystickChanged);
  506. this.leftStick.on("end", this.onMoveJoystickEnd);
  507. // const rightTouchZone = document.createElement("div");
  508. // rightTouchZone.classList.add('touchZone', 'right');
  509. // document.body.appendChild(rightTouchZone);
  510. // this.rightTouchZone = rightTouchZone;
  511. // this.rightStick = nipplejs.create({
  512. // zone: this.rightTouchZone,
  513. // color: "white",
  514. // fadeTime: 0
  515. // });
  516. // this.rightStick.on("start", this.onFirstInteraction);
  517. // this.rightStick.on("move", this.onLookJoystickChanged);
  518. // this.rightStick.on("end", this.onLookJoystickEnd);
  519. this.inVr = false;
  520. this.moving = false;
  521. this.rotating = false;
  522. this.moveEvent = {
  523. axis: [0, 0]
  524. };
  525. // this.rotateYEvent = {
  526. // value: 0
  527. // };
  528. // this.rotateXEvent = {
  529. // value: 0
  530. // };
  531. this.el.sceneEl.addEventListener("enter-vr", this.onEnterVr);
  532. this.el.sceneEl.addEventListener("exit-vr", this.onExitVr);
  533. },
  534. onFirstInteraction() {
  535. this.leftStick.off("start", this.onFirstInteraction);
  536. //this.rightStick.off("start", this.onFirstInteraction);
  537. document.body.removeChild(this.mockJoystickContainer);
  538. },
  539. onMoveJoystickChanged(event, joystick) {
  540. const angle = joystick.angle.radian;
  541. const force = joystick.force < 1 ? joystick.force : 1;
  542. const moveStrength = 1.85;
  543. const x = Math.cos(angle) * force * moveStrength;
  544. const z = Math.sin(angle) * force * moveStrength;
  545. this.moving = true;
  546. this.moveEvent.axis[0] = x;
  547. this.moveEvent.axis[1] = z;
  548. },
  549. onMoveJoystickEnd() {
  550. this.moving = false;
  551. this.moveEvent.axis[0] = 0;
  552. this.moveEvent.axis[1] = 0;
  553. this.el.emit("move", this.moveEvent);
  554. },
  555. onLookJoystickChanged(event, joystick) {
  556. // Set pitch and yaw angles on right stick move
  557. const angle = joystick.angle.radian;
  558. const force = joystick.force < 1 ? joystick.force : 1;
  559. const turnStrength = 0.5;
  560. this.rotating = true;
  561. this.rotateYEvent.value = Math.cos(angle) * force * turnStrength;
  562. this.rotateXEvent.value = Math.sin(angle) * force * turnStrength;
  563. },
  564. onLookJoystickEnd() {
  565. this.rotating = false;
  566. this.rotateYEvent.value = 0;
  567. this.rotateXEvent.value = 0;
  568. this.el.emit("rotateY", this.rotateYEvent);
  569. this.el.emit("rotateX", this.rotateXEvent);
  570. },
  571. tick() {
  572. if (!this.inVr) {
  573. if (this.moving) {
  574. this.el.emit("move", this.moveEvent);
  575. }
  576. // if (this.rotating) {
  577. // this.el.emit("rotateY", this.rotateYEvent);
  578. // this.el.emit("rotateX", this.rotateXEvent);
  579. // }
  580. }
  581. },
  582. onEnterVr() {
  583. // Hide the joystick controls
  584. this.inVr = true;
  585. this.leftTouchZone.style.display = "none";
  586. // this.rightTouchZone.style.display = "none";
  587. },
  588. onExitVr() {
  589. // Show the joystick controls
  590. this.inVr = false;
  591. this.leftTouchZone.style.display = "block";
  592. // this.rightTouchZone.style.display = "block";
  593. },
  594. remove() {
  595. this.el.sceneEl.removeEventListener("entervr", this.onEnterVr);
  596. this.el.sceneEl.removeEventListener("exitvr", this.onExitVr);
  597. if (document.getElementsByClassName('mockJoystickContainer').length > 0){
  598. document.body.removeChild(this.mockJoystickContainer);
  599. }
  600. document.body.removeChild(this.leftTouchZone);
  601. // document.body.removeChild(this.rightTouchZone);
  602. }
  603. });
  604. /////////////////////////////////AR_JS/////////////////////////////////////////////
  605. // arjs-anchor
  606. //////////////////////////////////////////////////////////////////////////////
  607. AFRAME.registerComponent('arjs-anchor', {
  608. dependencies: ['arjs', 'artoolkit'],
  609. schema: {
  610. preset: {
  611. type: 'string',
  612. },
  613. markerhelpers : { // IIF preset === 'area'
  614. type: 'boolean',
  615. default: false,
  616. },
  617. // controls parameters
  618. size: {
  619. type: 'number',
  620. default: 1
  621. },
  622. type: {
  623. type: 'string',
  624. },
  625. patternUrl: {
  626. type: 'string',
  627. },
  628. barcodeValue: {
  629. type: 'number'
  630. },
  631. changeMatrixMode: {
  632. type: 'string',
  633. default : 'modelViewMatrix',
  634. },
  635. minConfidence: {
  636. type: 'number',
  637. default: 0.6,
  638. },
  639. },
  640. init: function () {
  641. var _this = this
  642. // get arjsSystem
  643. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit;
  644. //////////////////////////////////////////////////////////////////////////////
  645. // Code Separator
  646. //////////////////////////////////////////////////////////////////////////////
  647. _this.isReady = false
  648. _this._arAnchor = null
  649. if(arjsSystem) {
  650. // honor object visibility
  651. if( _this.data.changeMatrixMode === 'modelViewMatrix' ){
  652. _this.el.object3D.visible = false
  653. }else if( _this.data.changeMatrixMode === 'cameraTransformMatrix' ){
  654. _this.el.sceneEl.object3D.visible = false
  655. }else console.assert(false)
  656. // trick to wait until arjsSystem is isReady
  657. var startedAt = Date.now()
  658. var timerId = setInterval(function(){
  659. // wait until the system is isReady
  660. if( arjsSystem.isReady === false ) return
  661. clearInterval(timerId)
  662. //////////////////////////////////////////////////////////////////////////////
  663. // update arProfile
  664. //////////////////////////////////////////////////////////////////////////////
  665. var arProfile = arjsSystem._arProfile
  666. // arProfile.changeMatrixMode('modelViewMatrix')
  667. arProfile.changeMatrixMode(_this.data.changeMatrixMode)
  668. // honor this.data.preset
  669. var markerParameters = Object.assign({}, arProfile.defaultMarkerParameters)
  670. if( _this.data.preset === 'hiro' ){
  671. markerParameters.type = 'pattern'
  672. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL+'examples/marker-training/examples/pattern-files/pattern-hiro.patt'
  673. markerParameters.markersAreaEnabled = false
  674. }else if( _this.data.preset === 'kanji' ){
  675. markerParameters.type = 'pattern'
  676. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL+'examples/marker-training/examples/pattern-files/pattern-kanji.patt'
  677. markerParameters.markersAreaEnabled = false
  678. }else if( _this.data.preset === 'area' ){
  679. markerParameters.type = 'barcode'
  680. markerParameters.barcodeValue = 1001
  681. markerParameters.markersAreaEnabled = true
  682. }else if( _this.data.type === 'barcode' ){
  683. markerParameters = {
  684. type: _this.data.type,
  685. changeMatrixMode: 'modelViewMatrix',
  686. barcodeValue: _this.data.barcodeValue,
  687. markersAreaEnabled: false
  688. }
  689. }else if( _this.data.type === 'pattern' ){
  690. markerParameters.type = _this.data.type
  691. markerParameters.patternUrl = _this.data.patternUrl;
  692. markerParameters.markersAreaEnabled = false
  693. }else {
  694. // console.assert( this.data.preset === '', 'illegal preset value '+this.data.preset)
  695. }
  696. //////////////////////////////////////////////////////////////////////////////
  697. // create arAnchor
  698. //////////////////////////////////////////////////////////////////////////////
  699. var arSession = arjsSystem._arSession
  700. var arAnchor = _this._arAnchor = new ARjs.Anchor(arSession, markerParameters)
  701. // it is now considered isReady
  702. _this.isReady = true
  703. //////////////////////////////////////////////////////////////////////////////
  704. // honor .debugUIEnabled
  705. //////////////////////////////////////////////////////////////////////////////
  706. if( arjsSystem.data.debugUIEnabled ){
  707. // get or create containerElement
  708. var containerElement = document.querySelector('#arjsDebugUIContainer')
  709. if( containerElement === null ){
  710. containerElement = document.createElement('div')
  711. containerElement.id = 'arjsDebugUIContainer'
  712. containerElement.setAttribute('style', 'position: fixed; bottom: 10px; width:100%; text-align: center; z-index: 1; color: grey;')
  713. document.body.appendChild(containerElement)
  714. }
  715. // create anchorDebugUI
  716. var anchorDebugUI = new ARjs.AnchorDebugUI(arAnchor)
  717. containerElement.appendChild(anchorDebugUI.domElement)
  718. }
  719. }, 1000/60)
  720. }
  721. },
  722. remove : function(){
  723. },
  724. update: function () {
  725. },
  726. tick: function(){
  727. var _this = this
  728. // if not yet isReady, do nothing
  729. if( this.isReady === false ) return
  730. //////////////////////////////////////////////////////////////////////////////
  731. // update arAnchor
  732. //////////////////////////////////////////////////////////////////////////////
  733. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  734. this._arAnchor.update()
  735. //////////////////////////////////////////////////////////////////////////////
  736. // honor pose
  737. //////////////////////////////////////////////////////////////////////////////
  738. var arWorldRoot = this._arAnchor.object3d
  739. arWorldRoot.updateMatrixWorld(true)
  740. arWorldRoot.matrixWorld.decompose(this.el.object3D.position, this.el.object3D.quaternion, this.el.object3D.scale)
  741. //////////////////////////////////////////////////////////////////////////////
  742. // honor visibility
  743. //////////////////////////////////////////////////////////////////////////////
  744. if( _this._arAnchor.parameters.changeMatrixMode === 'modelViewMatrix' ){
  745. var wasVisible = _this.el.object3D.visible
  746. _this.el.object3D.visible = this._arAnchor.object3d.visible
  747. }else if( _this._arAnchor.parameters.changeMatrixMode === 'cameraTransformMatrix' ){
  748. var wasVisible = _this.el.sceneEl.object3D.visible
  749. _this.el.sceneEl.object3D.visible = this._arAnchor.object3d.visible
  750. }else console.assert(false)
  751. // emit markerFound markerLost
  752. if( _this._arAnchor.object3d.visible === true && wasVisible === false ){
  753. _this.el.emit('markerFound')
  754. }else if( _this._arAnchor.object3d.visible === false && wasVisible === true ){
  755. _this.el.emit('markerLost')
  756. }
  757. }
  758. })
  759. //////////////////////////////////////////////////////////////////////////////
  760. // define some primitives shortcuts
  761. //////////////////////////////////////////////////////////////////////////////
  762. AFRAME.registerPrimitive('a-anchor', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  763. defaultComponents: {
  764. 'arjs-anchor': {},
  765. 'arjs-hit-testing': {},
  766. },
  767. mappings: {
  768. 'type': 'arjs-anchor.type',
  769. 'size': 'arjs-anchor.size',
  770. 'url': 'arjs-anchor.patternUrl',
  771. 'value': 'arjs-anchor.barcodeValue',
  772. 'preset': 'arjs-anchor.preset',
  773. 'minConfidence': 'arjs-anchor.minConfidence',
  774. 'markerhelpers': 'arjs-anchor.markerhelpers',
  775. 'hit-testing-renderDebug': 'arjs-hit-testing.renderDebug',
  776. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  777. }
  778. }))
  779. AFRAME.registerPrimitive('a-camera-static', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  780. defaultComponents: {
  781. 'camera': {},
  782. },
  783. mappings: {
  784. }
  785. }))
  786. //////////////////////////////////////////////////////////////////////////////
  787. // backward compatibility
  788. //////////////////////////////////////////////////////////////////////////////
  789. // FIXME
  790. AFRAME.registerPrimitive('a-marker', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  791. defaultComponents: {
  792. 'arjs-anchor': {},
  793. 'arjs-hit-testing': {},
  794. },
  795. mappings: {
  796. 'type': 'arjs-anchor.type',
  797. 'size': 'arjs-anchor.size',
  798. 'url': 'arjs-anchor.patternUrl',
  799. 'value': 'arjs-anchor.barcodeValue',
  800. 'preset': 'arjs-anchor.preset',
  801. 'minConfidence': 'arjs-anchor.minConfidence',
  802. 'markerhelpers': 'arjs-anchor.markerhelpers',
  803. 'hit-testing-renderDebug': 'arjs-hit-testing.renderDebug',
  804. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  805. }
  806. }))
  807. AFRAME.registerPrimitive('a-marker-camera', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  808. defaultComponents: {
  809. 'arjs-anchor': {
  810. changeMatrixMode: 'cameraTransformMatrix'
  811. },
  812. 'camera': {},
  813. },
  814. mappings: {
  815. 'type': 'arjs-anchor.type',
  816. 'size': 'arjs-anchor.size',
  817. 'url': 'arjs-anchor.patternUrl',
  818. 'value': 'arjs-anchor.barcodeValue',
  819. 'preset': 'arjs-anchor.preset',
  820. 'minConfidence': 'arjs-anchor.minConfidence',
  821. 'markerhelpers': 'arjs-anchor.markerhelpers',
  822. }
  823. }))
  824. //////////////////////////////////////////////////////////////////////////////
  825. // arjs-hit-testing
  826. //////////////////////////////////////////////////////////////////////////////
  827. AFRAME.registerComponent('arjs-hit-testing', {
  828. dependencies: ['arjs', 'artoolkit'],
  829. schema: {
  830. enabled : {
  831. type: 'boolean',
  832. default: false,
  833. },
  834. renderDebug : {
  835. type: 'boolean',
  836. default: false,
  837. },
  838. },
  839. init: function () {
  840. var _this = this
  841. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit;
  842. // TODO make it work on cameraTransformMatrix too
  843. //
  844. _this.isReady = false
  845. _this._arAnchor = null
  846. _this._arHitTesting = null
  847. if(arjsSystem) {
  848. // trick to wait until arjsSystem is isReady
  849. var startedAt = Date.now()
  850. var timerId = setInterval(function(){
  851. var anchorEl = _this.el
  852. var anchorComponent = anchorEl.components['arjs-anchor']
  853. // wait until anchorComponent is isReady
  854. if( anchorComponent === undefined || anchorComponent.isReady === false ) return
  855. clearInterval(timerId)
  856. //////////////////////////////////////////////////////////////////////////////
  857. // create arAnchor
  858. //////////////////////////////////////////////////////////////////////////////
  859. var arAnchor = anchorComponent._arAnchor
  860. var arSession = arjsSystem._arSession
  861. var renderer = arSession.parameters.renderer
  862. var hitTesting = _this._arHitTesting = new ARjs.HitTesting(arSession)
  863. hitTesting.enabled = _this.data.enabled
  864. // tango only - picking to set object position
  865. // renderer.domElement.addEventListener("click", function(domEvent){
  866. // var hitTestResults = hitTesting.testDomEvent(domEvent)
  867. // if( hitTestResults.length === 0 ) return
  868. // var hitTestResult = hitTestResults[0]
  869. // hitTestResult.apply(arAnchor.object3d)
  870. // })
  871. _this.isReady = true
  872. }, 1000/60)
  873. }
  874. },
  875. remove : function(){
  876. },
  877. update: function () {
  878. },
  879. tick: function(){
  880. var _this = this
  881. // if not yet isReady, do nothing
  882. if( this.isReady === false ) return
  883. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  884. var arSession = arjsSystem._arSession
  885. var anchorEl = _this.el
  886. var anchorComponent = anchorEl.components['arjs-anchor']
  887. var arAnchor = anchorComponent._arAnchor
  888. var hitTesting = this._arHitTesting
  889. var camera = arSession.parameters.camera
  890. // console.log(camera.position)
  891. hitTesting.update(camera, arAnchor.object3d, arAnchor.parameters.changeMatrixMode)
  892. }
  893. });