aframe-components.js 35 KB

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