aframe-components.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  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('avatar', {
  9. init: function () {
  10. },
  11. tick: function () {
  12. }
  13. })
  14. AFRAME.registerComponent('scene-utils', {
  15. init: function () {
  16. this.mirrors = {};
  17. this.interpolationComponents = {};
  18. //this.setCameraControl();
  19. const sceneEnterVR = (e) => {
  20. let driver = vwf.views["vwf/view/aframe"];
  21. // let avatarEl = document.querySelector('#avatarControlParent');
  22. let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  23. driver.hmd = true;
  24. if (driver.threeDoFMobile || _app.config.d3DoF ) {
  25. driver.threeDoF = true;
  26. vwf_view.kernel.callMethod(avatarID, "updateYPositionForXR", [0.0]);
  27. } else if (driver.sixDoFMobile || driver.sixDoFDesktop || _app.config.d6DoF ) {
  28. driver.sixDoF = true;
  29. }
  30. }
  31. const sceneExitVR = (e) => {
  32. let driver = vwf.views["vwf/view/aframe"];
  33. let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  34. driver.hmd = false;
  35. if (driver.threeDoFMobile || _app.config.d3DoF ) {
  36. driver.threeDoF = false;
  37. vwf_view.kernel.callMethod(avatarID, "updateYPositionForXR", [-1.6]);
  38. } else if (driver.sixDoFMobile || driver.sixDoFDesktop || _app.config.d6DoF ) {
  39. driver.sixDoF = false;
  40. }
  41. }
  42. this.el.sceneEl.addEventListener('enter-vr', sceneEnterVR);
  43. this.el.sceneEl.addEventListener('exit-vr', sceneExitVR);
  44. },
  45. setCameraControl(){
  46. let avatarEl = document.querySelector('#avatarControl');
  47. document.addEventListener('keydown', (event) => {
  48. const keyName = event.key;
  49. if (keyName === 'Alt') {
  50. // do not alert when only Control key is pressed.
  51. console.log(keyName, ' pressed');
  52. avatarEl.setAttribute('look-controls', 'enabled', true)
  53. return;
  54. }
  55. })
  56. document.addEventListener('keyup', (event) => {
  57. const keyName = event.key;
  58. if (keyName === 'Alt') {
  59. // do not alert when only Control key is pressed.
  60. console.log(keyName, ' released');
  61. avatarEl.setAttribute('look-controls', 'enabled', false)
  62. return;
  63. }
  64. })
  65. },
  66. update: function () {
  67. },
  68. tick: function (t, dt) {
  69. Object.values(this.mirrors).forEach(el => {
  70. el.mirrorTick.call(el)
  71. });
  72. // Object.values(this.interpolationComponents).forEach(el => {
  73. // el.interpolationTick.call(el, t, dt)
  74. // });
  75. },
  76. tock: function (t, dt) {
  77. // Object.values(this.interpolationComponents).forEach(el => {
  78. // el.interpolationTock.call(el, t, dt)
  79. // });
  80. }
  81. })
  82. AFRAME.registerComponent('linepath', {
  83. schema: {
  84. color: { default: '#000' },
  85. width: { default: 0.01 },
  86. path: {
  87. default: [
  88. { x: -0.5, y: 0, z: 0 },
  89. { x: 0.5, y: 0, z: 0 }
  90. ]
  91. // Deserialize path in the form of comma-separated vec3s: `0 0 0, 1 1 1, 2 0 3`.
  92. // parse: function (value) {
  93. // return value.split(',').map(coordinates.parse);
  94. // },
  95. // Serialize array of vec3s in case someone does setAttribute('line', 'path', [...]).
  96. // stringify: function (data) {
  97. // return data.map(coordinates.stringify).join(',');
  98. // }
  99. }
  100. },
  101. update: function () {
  102. var material = new MeshLineMaterial({
  103. color: new THREE.Color(this.data.color), //this.data.color
  104. lineWidth: this.data.width
  105. });
  106. var geometry = new THREE.Geometry();
  107. this.data.path.forEach(function (vec3) {
  108. geometry.vertices.push(
  109. new THREE.Vector3(vec3.x, vec3.y, vec3.z)
  110. );
  111. });
  112. let line = new MeshLine();
  113. line.setGeometry(geometry);
  114. //new THREE.Line(geometry, material)
  115. this.el.setObject3D('mesh', new THREE.Mesh(line.geometry, material));
  116. },
  117. remove: function () {
  118. this.el.removeObject3D('mesh');
  119. }
  120. });
  121. AFRAME.registerComponent('gizmo', {
  122. schema: {
  123. mode: { default: 'translate' }
  124. },
  125. update: function (old) {
  126. let modes = ['translate', 'rotate', 'scale'];
  127. if (!this.gizmo) {
  128. let newMode = modes.filter(el => {
  129. return el == this.data.mode
  130. })
  131. if (newMode.length !== 0) {
  132. this.mode = this.data.mode
  133. this.transformControls.setMode(this.mode)
  134. }
  135. }
  136. },
  137. init: function () {
  138. let self = this
  139. this.mode = this.data.mode
  140. let activeCamera = document.querySelector('#avatarControl').getObject3D('camera');
  141. let renderer = this.el.sceneEl.renderer;
  142. this.transformControls = new THREE.TransformControls(activeCamera, renderer.domElement);
  143. this.transformControls.attach(this.el.object3D);
  144. this.el.sceneEl.setObject3D('control-' + this.el.id, this.transformControls);
  145. this.transformControls.addEventListener('change', function (evt) {
  146. // console.log('changed');
  147. var object = self.transformControls.object;
  148. if (object === undefined) {
  149. return;
  150. }
  151. var transformMode = self.transformControls.getMode();
  152. switch (transformMode) {
  153. case 'translate':
  154. vwf_view.kernel.setProperty(object.el.id, 'position',
  155. [object.position.x, object.position.y, object.position.z])
  156. break;
  157. case 'rotate':
  158. // let q = (new THREE.Quaternion()).setFromEuler(new THREE.Euler(
  159. // (object.rotation.x),
  160. // (object.rotation.y),
  161. // (object.rotation.z), 'XYZ'
  162. // ));
  163. // let angle = (new THREE.Euler()).setFromQuaternion(q, 'YXZ');
  164. // vwf_view.kernel.setProperty(object.el.id, 'rotation', [THREE.Math.radToDeg(angle.x), THREE.Math.radToDeg(angle.y), THREE.Math.radToDeg(angle.z)])
  165. vwf_view.kernel.setProperty(object.el.id, 'rotation',
  166. [THREE.Math.radToDeg(object.rotation.x), THREE.Math.radToDeg(object.rotation.y), THREE.Math.radToDeg(object.rotation.z)])
  167. break;
  168. case 'scale':
  169. vwf_view.kernel.setProperty(object.el.id, 'scale',
  170. [object.scale.x, object.scale.y, object.scale.z])
  171. break;
  172. }
  173. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  174. });
  175. },
  176. remove: function () {
  177. this.transformControls.detach();
  178. this.el.sceneEl.removeObject3D('control-' + this.el.id);
  179. },
  180. // tick: function (t) {
  181. // // this.transformControls.update();
  182. // }
  183. });
  184. AFRAME.registerComponent('cursor-listener', {
  185. init: function () {
  186. this.el.addEventListener('click', function (evt) {
  187. console.log('I was clicked at: ', evt.detail.intersection.point);
  188. let cursorID = 'cursor-avatar-' + vwf_view.kernel.moniker();
  189. if (evt.detail.cursorEl.id.includes(vwf_view.kernel.moniker())) {
  190. vwf_view.kernel.fireEvent(evt.detail.intersection.object.el.id, "clickEvent", [vwf_view.kernel.moniker()])
  191. }
  192. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  193. });
  194. }
  195. });
  196. AFRAME.registerComponent('aabb-collider-listener', {
  197. // If the target collidable object is moving, set <a-entity data-aabb-collider-dynamic> on the target. By default, collidable objects are presumed to be static for performance purposes.
  198. init: function () {
  199. // let self = this;
  200. // this.me = vwf_view.kernel.moniker();
  201. this.el.addEventListener('hitstart', function (evt) {
  202. vwf_view.kernel.fireEvent(evt.target.id, "hitstartEvent");
  203. })
  204. this.el.addEventListener('hitend', function (evt) {
  205. vwf_view.kernel.fireEvent(evt.target.id, "hitendEvent");
  206. })
  207. }
  208. });
  209. AFRAME.registerComponent('raycaster-listener', {
  210. init: function () {
  211. let self = this;
  212. this.intersected = false;
  213. this.casters = {}
  214. this.me = vwf_view.kernel.moniker();
  215. this.driver = vwf.views["vwf/view/aframe"];
  216. this.el.addEventListener('raycaster-intersected', function (evt) {
  217. if (evt.detail.el.nodeName == 'A-CURSOR') {
  218. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  219. } else {
  220. if (self.intersected) {
  221. } else {
  222. console.log('I was intersected at: ', evt.target);//evt.detail.getIntersection().point);
  223. vwf_view.kernel.fireEvent(evt.target.id, "intersectEvent");
  224. }
  225. self.casters[evt.target.id] = evt.target;
  226. self.intersected = true;
  227. }
  228. });
  229. this.el.addEventListener('raycaster-intersected-cleared', function (evt) {
  230. if (evt.detail.el.nodeName == 'A-CURSOR') {
  231. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  232. } else {
  233. if (self.intersected) {
  234. console.log('Clear intersection');
  235. if (Object.entries(self.casters).length == 1 && (self.casters[evt.target.id] !== undefined)) {
  236. vwf_view.kernel.fireEvent(evt.target.id, "clearIntersectEvent")
  237. }
  238. delete self.casters[evt.target.id]
  239. } else { }
  240. self.intersected = false;
  241. }
  242. });
  243. }
  244. });
  245. AFRAME.registerComponent('envmap', {
  246. /**
  247. * Creates a new THREE.ShaderMaterial using the two shaders defined
  248. * in vertex.glsl and fragment.glsl.
  249. */
  250. init: function () {
  251. const data = this.data;
  252. //this.applyToMesh();
  253. this.el.addEventListener('model-loaded', () => this.applyToMesh());
  254. },
  255. /**
  256. * Update the ShaderMaterial when component data changes.
  257. */
  258. update: function () {
  259. },
  260. getEnvMap: function () {
  261. var path = './assets/textures/skybox2/';
  262. var format = '.jpg';
  263. var urls = [
  264. path + 'px' + format, path + 'nx' + format,
  265. path + 'py' + format, path + 'ny' + format,
  266. path + 'pz' + format, path + 'nz' + format
  267. ];
  268. envMap = new THREE.CubeTextureLoader().load(urls);
  269. envMap.format = THREE.RGBFormat;
  270. return envMap;
  271. },
  272. /**
  273. * Apply the material to the current entity.
  274. */
  275. applyToMesh: function () {
  276. const mesh = this.el.getObject3D('mesh');
  277. //var scene = mesh;
  278. var envMap = this.getEnvMap();
  279. mesh.traverse(function (node) {
  280. if (node.material) {
  281. node.material.side = THREE.BackSide;
  282. node.material.needsUpdate = true;
  283. //side = THREE.DoubleSide; break;
  284. }
  285. });
  286. mesh.traverse(function (node) {
  287. if (node.material && (node.material.isMeshStandardMaterial ||
  288. (node.material.isShaderMaterial && node.material.envMap !== undefined))) {
  289. node.material.envMap = envMap;
  290. node.material.needsUpdate = true;
  291. }
  292. });
  293. // const mesh = this.el.getObject3D('mesh');
  294. // if (mesh) {
  295. // mesh.material = this.material;
  296. // }
  297. },
  298. /**
  299. * On each frame, update the 'time' uniform in the shaders.
  300. */
  301. // tick: function (t) {
  302. // }
  303. })
  304. //https://threejs.org/examples/webgl_shaders_sky.html
  305. AFRAME.registerComponent('skyshader', {
  306. makeSun: function () {
  307. let sunSphere = new THREE.Mesh(
  308. new THREE.SphereBufferGeometry(20000, 16, 8),
  309. new THREE.MeshBasicMaterial({ color: 0xffffff })
  310. );
  311. sunSphere.position.y = - 700000;
  312. sunSphere.visible = true;
  313. let scene = this.el.sceneEl;
  314. this.el.sceneEl.setObject3D('sun', sunSphere);
  315. },
  316. init: function () {
  317. //let sunSphereEl = document.querySelector('a-scene').querySelector('#sun');
  318. //this.sunSphere = sunSphereEl.object3D;
  319. this.makeSun();
  320. this.sunSphere = this.el.sceneEl.getObject3D('sun');
  321. this.sky = new THREE.Sky();
  322. let scene = this.el.sceneEl;
  323. let effectController = {
  324. turbidity: 5,
  325. rayleigh: 2,
  326. mieCoefficient: 0.005,
  327. mieDirectionalG: 0.8,
  328. luminance: 1,
  329. inclination: 0, // elevation / inclination
  330. azimuth: 0.25, // Facing front,
  331. sun: ! true
  332. };
  333. let uniforms = this.sky.uniforms;
  334. uniforms.turbidity.value = effectController.turbidity;
  335. uniforms.rayleigh.value = effectController.rayleigh;
  336. uniforms.luminance.value = effectController.luminance;
  337. uniforms.mieCoefficient.value = effectController.mieCoefficient;
  338. uniforms.mieDirectionalG.value = effectController.mieDirectionalG;
  339. this.el.setObject3D('mesh', this.sky.mesh);
  340. let distance = 400000;
  341. var theta = Math.PI * (effectController.inclination - 0.5);
  342. var phi = 2 * Math.PI * (effectController.azimuth - 0.5);
  343. this.sunSphere.position.x = distance * Math.cos(phi);
  344. this.sunSphere.position.y = distance * Math.sin(phi) * Math.sin(theta);
  345. this.sunSphere.position.z = distance * Math.sin(phi) * Math.cos(theta);
  346. this.sunSphere.visible = effectController.sun;
  347. this.sky.uniforms.sunPosition.value.copy(this.sunSphere.position);
  348. },
  349. update: function () {
  350. },
  351. // tick: function (t) {
  352. // }
  353. })
  354. AFRAME.registerComponent('sun', {
  355. init: function () {
  356. this.sunSphere = new THREE.Mesh(
  357. new THREE.SphereBufferGeometry(20000, 16, 8),
  358. new THREE.MeshBasicMaterial({ color: 0xffffff })
  359. );
  360. this.sunSphere.position.y = - 700000;
  361. this.sunSphere.visible = true;
  362. this.el.setObject3D('mesh', this.sunSphere);
  363. },
  364. update: function () {
  365. },
  366. // tick: function (t) {
  367. // }
  368. })
  369. AFRAME.registerComponent('gearvrcontrol', {
  370. init: function () {
  371. var self = this;
  372. var controllerID = 'gearvr-' + vwf_view.kernel.moniker();
  373. this.el.addEventListener('triggerdown', function (event) {
  374. vwf_view.kernel.callMethod(controllerID, "triggerdown", []);
  375. });
  376. this.el.addEventListener('triggerup', function (event) {
  377. vwf_view.kernel.callMethod(controllerID, "triggerup", []);
  378. });
  379. //X-buttorn Pressed
  380. this.el.addEventListener('buttondown', function (e) { //xbuttondown
  381. //Start pointing position to teleport
  382. //let buttonID = e.detail.id;
  383. //let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  384. //vwf_view.kernel.callMethod(vwf.application(), "createPrimitive", ['text', buttonID, 'debug', null, avatarID]);
  385. if(e.detail.id == 2){
  386. this.emit('teleportstart');
  387. }
  388. });
  389. //X-buttorn Released
  390. this.el.addEventListener('buttonup', function (e) { //xbuttonup
  391. //Jump to pointed position
  392. if(e.detail.id == 2){
  393. this.emit('teleportend');
  394. }
  395. });
  396. },
  397. update: function () {
  398. },
  399. // tick: function (t) {
  400. // }
  401. })
  402. AFRAME.registerComponent('xrcontroller', {
  403. schema: {
  404. hand: { default: 'right' }
  405. },
  406. update: function (old) {
  407. this.hand = this.data.hand;
  408. },
  409. init: function () {
  410. var self = this;
  411. this.hand = this.data.hand;
  412. this.controllerID = 'xrcontroller-' + this.hand + '-' + vwf_view.kernel.moniker();
  413. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  414. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  415. });
  416. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  417. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  418. });
  419. //X-buttorn Pressed
  420. this.el.addEventListener('xbuttondown', function (e) { //xbuttondown
  421. //Start pointing position to teleport
  422. this.emit('teleportstart');
  423. });
  424. //X-buttorn Released
  425. this.el.addEventListener('xbuttonup', function (e) { //xbuttonup
  426. //Jump to pointed position
  427. this.emit('teleportend');
  428. });
  429. this.el.addEventListener('teleported', function (e) { //xbuttonup
  430. //Teleported
  431. console.log('TELEPORTED: ', e);
  432. });
  433. },
  434. // tick: function (t) {
  435. // }
  436. })
  437. AFRAME.registerComponent('wmrvrcontrol', {
  438. schema: {
  439. hand: { default: 'right' }
  440. },
  441. update: function (old) {
  442. this.hand = this.data.hand;
  443. },
  444. init: function () {
  445. var self = this;
  446. this.hand = this.data.hand;
  447. this.controllerID = 'wmrvr-' + this.hand + '-' + vwf_view.kernel.moniker();
  448. //this.gearel = document.querySelector('#gearvrcontrol');
  449. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  450. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  451. });
  452. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  453. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  454. });
  455. },
  456. // tick: function (t) {
  457. // }
  458. })
  459. AFRAME.registerComponent('streamsound', {
  460. schema: {
  461. positional: { default: true }
  462. },
  463. init: function () {
  464. var self = this;
  465. let driver = vwf.views["vwf/view/webrtc"];
  466. this.listener = null;
  467. this.stream = null;
  468. if (!this.sound) {
  469. this.setupSound();
  470. }
  471. if (driver) {
  472. //let avatarID = 'avatar-' + vwf.moniker();
  473. let avatarID = this.el.id.slice(0, 27); //avatar-0RtnYBBTBU84OCNcAAFY
  474. let client = driver.state.clients[avatarID];
  475. if (client) {
  476. if (client.connection) {
  477. this.stream = client.connection.stream;
  478. if (this.stream) {
  479. this.audioEl = new Audio();
  480. this.audioEl.srcObject = this.stream;
  481. this.sound.setNodeSource(this.sound.context.createMediaStreamSource(this.stream));
  482. }
  483. }
  484. }
  485. }
  486. },
  487. setupSound: function () {
  488. var el = this.el;
  489. var sceneEl = el.sceneEl;
  490. if (this.sound) {
  491. el.removeObject3D(this.attrName);
  492. }
  493. if (!sceneEl.audioListener) {
  494. sceneEl.audioListener = new THREE.AudioListener();
  495. sceneEl.camera && sceneEl.camera.add(sceneEl.audioListener);
  496. sceneEl.addEventListener('camera-set-active', function (evt) {
  497. evt.detail.cameraEl.getObject3D('camera').add(sceneEl.audioListener);
  498. });
  499. }
  500. this.listener = sceneEl.audioListener;
  501. this.sound = this.data.positional
  502. ? new THREE.PositionalAudio(this.listener)
  503. : new THREE.Audio(this.listener);
  504. el.setObject3D(this.attrName, this.sound);
  505. },
  506. remove: function () {
  507. if (!this.sound) return;
  508. this.el.removeObject3D(this.attrName);
  509. if (this.stream) {
  510. this.sound.disconnect();
  511. }
  512. },
  513. update: function (old) {
  514. },
  515. // tick: function (t) {
  516. // }
  517. })
  518. AFRAME.registerComponent('viewoffset', {
  519. // fullWidth:
  520. // fullHeight:
  521. // xoffset:
  522. // yoffset:
  523. // width:
  524. // height:
  525. schema: {
  526. fullWidth: { default: window.innerWidth },
  527. fullHeight: { default: window.innerHeight },
  528. xoffset: { default: window.innerWidth / 2 },
  529. yoffset: { default: window.innerHeight / 2 },
  530. width: { default: window.innerWidth },
  531. height: { default: window.innerHeight }
  532. },
  533. init: function () {
  534. var self = this;
  535. this.el.sceneEl.addEventListener('loaded', setOffset);
  536. function setOffset() {
  537. this.setNewOffset();
  538. }
  539. },
  540. update: function (old) {
  541. this.fullWidth = this.data.fullWidth;
  542. this.fullHeight = this.data.fullHeight;
  543. this.xoffset = this.data.xoffset;
  544. this.yoffset = this.data.yoffset;
  545. this.width = this.data.width;
  546. this.height = this.data.height;
  547. //console.log(this.data);
  548. this.setNewOffset();
  549. },
  550. setNewOffset: function () {
  551. this.el.object3DMap.camera.setViewOffset(
  552. this.data.fullWidth,
  553. this.data.fullHeight,
  554. this.data.xoffset,
  555. this.data.yoffset,
  556. this.data.width,
  557. this.data.height)
  558. },
  559. // tick: function (t) {
  560. // }
  561. })
  562. AFRAME.registerComponent("virtual-gamepad-controls", {
  563. schema: {},
  564. init() {
  565. this.onEnterVr = this.onEnterVr.bind(this);
  566. this.onExitVr = this.onExitVr.bind(this);
  567. this.onFirstInteraction = this.onFirstInteraction.bind(this);
  568. this.onMoveJoystickChanged = this.onMoveJoystickChanged.bind(this);
  569. this.onMoveJoystickEnd = this.onMoveJoystickEnd.bind(this);
  570. // this.onLookJoystickChanged = this.onLookJoystickChanged.bind(this);
  571. // this.onLookJoystickEnd = this.onLookJoystickEnd.bind(this);
  572. this.mockJoystickContainer = document.createElement("div");
  573. this.mockJoystickContainer.classList.add('mockJoystickContainer');
  574. const leftMock = document.createElement("div");
  575. leftMock.classList.add('mockJoystick');
  576. const leftMockSmall = document.createElement("div");
  577. leftMockSmall.classList.add('mockJoystick', 'inner');
  578. leftMock.appendChild(leftMockSmall);
  579. this.mockJoystickContainer.appendChild(leftMock);
  580. // const rightMock = document.createElement("div");
  581. // rightMock.classList.add('mockJoystick');
  582. // const rightMockSmall = document.createElement("div");
  583. // rightMockSmall.classList.add('mockJoystick', 'inner');
  584. // rightMock.appendChild(rightMockSmall);
  585. // this.mockJoystickContainer.appendChild(rightMock);
  586. document.body.appendChild(this.mockJoystickContainer);
  587. // Setup gamepad elements
  588. const leftTouchZone = document.createElement("div");
  589. leftTouchZone.classList.add('touchZone', 'left');
  590. document.body.appendChild(leftTouchZone);
  591. this.leftTouchZone = leftTouchZone;
  592. this.leftStick = nipplejs.create({
  593. zone: this.leftTouchZone,
  594. color: "white",
  595. fadeTime: 0
  596. });
  597. this.leftStick.on("start", this.onFirstInteraction);
  598. this.leftStick.on("move", this.onMoveJoystickChanged);
  599. this.leftStick.on("end", this.onMoveJoystickEnd);
  600. // const rightTouchZone = document.createElement("div");
  601. // rightTouchZone.classList.add('touchZone', 'right');
  602. // document.body.appendChild(rightTouchZone);
  603. // this.rightTouchZone = rightTouchZone;
  604. // this.rightStick = nipplejs.create({
  605. // zone: this.rightTouchZone,
  606. // color: "white",
  607. // fadeTime: 0
  608. // });
  609. // this.rightStick.on("start", this.onFirstInteraction);
  610. // this.rightStick.on("move", this.onLookJoystickChanged);
  611. // this.rightStick.on("end", this.onLookJoystickEnd);
  612. this.inVr = false;
  613. this.moving = false;
  614. this.rotating = false;
  615. this.moveEvent = {
  616. axis: [0, 0]
  617. };
  618. // this.rotateYEvent = {
  619. // value: 0
  620. // };
  621. // this.rotateXEvent = {
  622. // value: 0
  623. // };
  624. this.el.sceneEl.addEventListener("enter-vr", this.onEnterVr);
  625. this.el.sceneEl.addEventListener("exit-vr", this.onExitVr);
  626. },
  627. onFirstInteraction() {
  628. this.leftStick.off("start", this.onFirstInteraction);
  629. //this.rightStick.off("start", this.onFirstInteraction);
  630. document.body.removeChild(this.mockJoystickContainer);
  631. },
  632. onMoveJoystickChanged(event, joystick) {
  633. const angle = joystick.angle.radian;
  634. const force = joystick.force < 1 ? joystick.force : 1;
  635. const moveStrength = 1.85;
  636. const x = Math.cos(angle) * force * moveStrength;
  637. const z = Math.sin(angle) * force * moveStrength;
  638. this.moving = true;
  639. this.moveEvent.axis[0] = x;
  640. this.moveEvent.axis[1] = z;
  641. },
  642. onMoveJoystickEnd() {
  643. this.moving = false;
  644. this.moveEvent.axis[0] = 0;
  645. this.moveEvent.axis[1] = 0;
  646. this.el.emit("move", this.moveEvent);
  647. },
  648. onLookJoystickChanged(event, joystick) {
  649. // Set pitch and yaw angles on right stick move
  650. const angle = joystick.angle.radian;
  651. const force = joystick.force < 1 ? joystick.force : 1;
  652. const turnStrength = 0.5;
  653. this.rotating = true;
  654. this.rotateYEvent.value = Math.cos(angle) * force * turnStrength;
  655. this.rotateXEvent.value = Math.sin(angle) * force * turnStrength;
  656. },
  657. onLookJoystickEnd() {
  658. this.rotating = false;
  659. this.rotateYEvent.value = 0;
  660. this.rotateXEvent.value = 0;
  661. this.el.emit("rotateY", this.rotateYEvent);
  662. this.el.emit("rotateX", this.rotateXEvent);
  663. },
  664. tick() {
  665. if (!this.inVr) {
  666. if (this.moving) {
  667. this.el.emit("move", this.moveEvent);
  668. }
  669. // if (this.rotating) {
  670. // this.el.emit("rotateY", this.rotateYEvent);
  671. // this.el.emit("rotateX", this.rotateXEvent);
  672. // }
  673. }
  674. },
  675. onEnterVr() {
  676. // Hide the joystick controls
  677. this.inVr = true;
  678. this.leftTouchZone.style.display = "none";
  679. // this.rightTouchZone.style.display = "none";
  680. },
  681. onExitVr() {
  682. // Show the joystick controls
  683. this.inVr = false;
  684. this.leftTouchZone.style.display = "block";
  685. // this.rightTouchZone.style.display = "block";
  686. },
  687. remove() {
  688. this.el.sceneEl.removeEventListener("entervr", this.onEnterVr);
  689. this.el.sceneEl.removeEventListener("exitvr", this.onExitVr);
  690. if (document.getElementsByClassName('mockJoystickContainer').length > 0){
  691. document.body.removeChild(this.mockJoystickContainer);
  692. }
  693. document.body.removeChild(this.leftTouchZone);
  694. // document.body.removeChild(this.rightTouchZone);
  695. }
  696. });
  697. ////ARJS///
  698. //////////////////////////////////////////////////////////////////////////////
  699. // arjs-anchor
  700. //////////////////////////////////////////////////////////////////////////////
  701. AFRAME.registerComponent('arjs-anchor', {
  702. dependencies: ['arjs', 'artoolkit'],
  703. schema: {
  704. preset: {
  705. type: 'string',
  706. },
  707. markerhelpers: { // IIF preset === 'area'
  708. type: 'boolean',
  709. default: false,
  710. },
  711. // controls parameters
  712. size: {
  713. type: 'number',
  714. default: 1
  715. },
  716. type: {
  717. type: 'string',
  718. },
  719. patternUrl: {
  720. type: 'string',
  721. },
  722. barcodeValue: {
  723. type: 'number'
  724. },
  725. changeMatrixMode: {
  726. type: 'string',
  727. default: 'modelViewMatrix',
  728. },
  729. minConfidence: {
  730. type: 'number',
  731. default: 0.6,
  732. },
  733. smooth: {
  734. type: 'boolean',
  735. default: false,
  736. },
  737. smoothCount: {
  738. type: 'number',
  739. default: 5,
  740. },
  741. smoothTolerance: {
  742. type: 'number',
  743. default: 0.01,
  744. },
  745. smoothThreshold: {
  746. type: 'number',
  747. default: 2,
  748. },
  749. },
  750. init: function () {
  751. var _this = this
  752. // get arjsSystem
  753. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  754. //////////////////////////////////////////////////////////////////////////////
  755. // Code Separator
  756. //////////////////////////////////////////////////////////////////////////////
  757. _this.isReady = false
  758. _this._arAnchor = null
  759. //LiveCoding.space fix for editor mode
  760. if(arjsSystem) {
  761. // honor object visibility
  762. if (_this.data.changeMatrixMode === 'modelViewMatrix') {
  763. _this.el.object3D.visible = false
  764. } else if (_this.data.changeMatrixMode === 'cameraTransformMatrix') {
  765. _this.el.sceneEl.object3D.visible = false
  766. } else console.assert(false)
  767. // trick to wait until arjsSystem is isReady
  768. var startedAt = Date.now()
  769. var timerId = setInterval(function () {
  770. // wait until the system is isReady
  771. if (arjsSystem.isReady === false) return
  772. clearInterval(timerId)
  773. //////////////////////////////////////////////////////////////////////////////
  774. // update arProfile
  775. //////////////////////////////////////////////////////////////////////////////
  776. var arProfile = arjsSystem._arProfile
  777. // arProfile.changeMatrixMode('modelViewMatrix')
  778. arProfile.changeMatrixMode(_this.data.changeMatrixMode)
  779. // honor this.data.preset
  780. var markerParameters = Object.assign({}, arProfile.defaultMarkerParameters)
  781. if (_this.data.preset === 'hiro') {
  782. markerParameters.type = 'pattern'
  783. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-hiro.patt'
  784. markerParameters.markersAreaEnabled = false
  785. } else if (_this.data.preset === 'kanji') {
  786. markerParameters.type = 'pattern'
  787. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-kanji.patt'
  788. markerParameters.markersAreaEnabled = false
  789. } else if (_this.data.preset === 'area') {
  790. markerParameters.type = 'barcode'
  791. markerParameters.barcodeValue = 1001
  792. markerParameters.markersAreaEnabled = true
  793. } else if (_this.data.type === 'barcode') {
  794. markerParameters = {
  795. type: _this.data.type,
  796. changeMatrixMode: 'modelViewMatrix',
  797. barcodeValue: _this.data.barcodeValue,
  798. markersAreaEnabled: false
  799. }
  800. } else if (_this.data.type === 'pattern') {
  801. markerParameters.type = _this.data.type
  802. markerParameters.patternUrl = _this.data.patternUrl;
  803. markerParameters.markersAreaEnabled = false
  804. }
  805. markerParameters.smooth = _this.data.smooth;
  806. markerParameters.smoothCount = _this.data.smoothCount;
  807. markerParameters.smoothTolerance = _this.data.smoothTolerance;
  808. markerParameters.smoothThreshold = _this.data.smoothThreshold;
  809. //////////////////////////////////////////////////////////////////////////////
  810. // create arAnchor
  811. //////////////////////////////////////////////////////////////////////////////
  812. var arSession = arjsSystem._arSession
  813. var arAnchor = _this._arAnchor = new ARjs.Anchor(arSession, markerParameters)
  814. // it is now considered isReady
  815. _this.isReady = true
  816. //////////////////////////////////////////////////////////////////////////////
  817. // honor .debugUIEnabled
  818. //////////////////////////////////////////////////////////////////////////////
  819. if (arjsSystem.data.debugUIEnabled) {
  820. // get or create containerElement
  821. var containerElement = document.querySelector('#arjsDebugUIContainer')
  822. if (containerElement === null) {
  823. containerElement = document.createElement('div')
  824. containerElement.id = 'arjsDebugUIContainer'
  825. containerElement.setAttribute('style', 'position: fixed; bottom: 10px; width:100%; text-align: center; z-index: 1; color: grey;')
  826. document.body.appendChild(containerElement)
  827. }
  828. // create anchorDebugUI
  829. var anchorDebugUI = new ARjs.AnchorDebugUI(arAnchor)
  830. containerElement.appendChild(anchorDebugUI.domElement)
  831. }
  832. }, 1000 / 60)
  833. }
  834. },
  835. remove: function () {
  836. },
  837. update: function () {
  838. },
  839. tick: function () {
  840. var _this = this
  841. // if not yet isReady, do nothing
  842. if (this.isReady === false) return
  843. //////////////////////////////////////////////////////////////////////////////
  844. // update arAnchor
  845. //////////////////////////////////////////////////////////////////////////////
  846. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  847. this._arAnchor.update()
  848. //////////////////////////////////////////////////////////////////////////////
  849. // honor pose
  850. //////////////////////////////////////////////////////////////////////////////
  851. var arWorldRoot = this._arAnchor.object3d
  852. arWorldRoot.updateMatrixWorld(true)
  853. arWorldRoot.matrixWorld.decompose(this.el.object3D.position, this.el.object3D.quaternion, this.el.object3D.scale)
  854. //////////////////////////////////////////////////////////////////////////////
  855. // honor visibility
  856. //////////////////////////////////////////////////////////////////////////////
  857. if (_this._arAnchor.parameters.changeMatrixMode === 'modelViewMatrix') {
  858. var wasVisible = _this.el.object3D.visible
  859. _this.el.object3D.visible = this._arAnchor.object3d.visible
  860. } else if (_this._arAnchor.parameters.changeMatrixMode === 'cameraTransformMatrix') {
  861. var wasVisible = _this.el.sceneEl.object3D.visible
  862. _this.el.sceneEl.object3D.visible = this._arAnchor.object3d.visible
  863. } else console.assert(false)
  864. // emit markerFound markerLost
  865. if (_this._arAnchor.object3d.visible === true && wasVisible === false) {
  866. _this.el.emit('markerFound')
  867. } else if (_this._arAnchor.object3d.visible === false && wasVisible === true) {
  868. _this.el.emit('markerLost')
  869. }
  870. }
  871. })
  872. //////////////////////////////////////////////////////////////////////////////
  873. // define some primitives shortcuts
  874. //////////////////////////////////////////////////////////////////////////////
  875. AFRAME.registerPrimitive('a-anchor', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  876. defaultComponents: {
  877. 'arjs-anchor': {},
  878. 'arjs-hit-testing': {},
  879. },
  880. mappings: {
  881. 'type': 'arjs-anchor.type',
  882. 'size': 'arjs-anchor.size',
  883. 'url': 'arjs-anchor.patternUrl',
  884. 'value': 'arjs-anchor.barcodeValue',
  885. 'preset': 'arjs-anchor.preset',
  886. 'min-confidence': 'arjs-anchor.minConfidence',
  887. 'marker-helpers': 'arjs-anchor.markerhelpers',
  888. 'smooth': 'arjs-anchor.smooth',
  889. 'smooth-count': 'arjs-anchor.smoothCount',
  890. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  891. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  892. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  893. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  894. }
  895. }))
  896. AFRAME.registerPrimitive('a-camera-static', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  897. defaultComponents: {
  898. 'camera': {},
  899. },
  900. mappings: {
  901. }
  902. }))
  903. //////////////////////////////////////////////////////////////////////////////
  904. // backward compatibility
  905. //////////////////////////////////////////////////////////////////////////////
  906. // FIXME
  907. AFRAME.registerPrimitive('a-marker', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  908. defaultComponents: {
  909. 'arjs-anchor': {},
  910. 'arjs-hit-testing': {},
  911. },
  912. mappings: {
  913. 'type': 'arjs-anchor.type',
  914. 'size': 'arjs-anchor.size',
  915. 'url': 'arjs-anchor.patternUrl',
  916. 'value': 'arjs-anchor.barcodeValue',
  917. 'preset': 'arjs-anchor.preset',
  918. 'min-confidence': 'arjs-anchor.minConfidence',
  919. 'marker-helpers': 'arjs-anchor.markerhelpers',
  920. 'smooth': 'arjs-anchor.smooth',
  921. 'smooth-count': 'arjs-anchor.smoothCount',
  922. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  923. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  924. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  925. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  926. }
  927. }))
  928. AFRAME.registerPrimitive('a-marker-camera', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  929. defaultComponents: {
  930. 'arjs-anchor': {
  931. changeMatrixMode: 'cameraTransformMatrix'
  932. },
  933. 'camera': {},
  934. },
  935. mappings: {
  936. 'type': 'arjs-anchor.type',
  937. 'size': 'arjs-anchor.size',
  938. 'url': 'arjs-anchor.patternUrl',
  939. 'value': 'arjs-anchor.barcodeValue',
  940. 'preset': 'arjs-anchor.preset',
  941. 'min-confidence': 'arjs-anchor.minConfidence',
  942. 'marker-helpers': 'arjs-anchor.markerhelpers',
  943. }
  944. }))
  945. //////////////////////////////////////////////////////////////////////////////
  946. // arjs-hit-testing
  947. //////////////////////////////////////////////////////////////////////////////
  948. AFRAME.registerComponent('arjs-hit-testing', {
  949. dependencies: ['arjs', 'artoolkit'],
  950. schema: {
  951. enabled : {
  952. type: 'boolean',
  953. default: false,
  954. },
  955. renderDebug : {
  956. type: 'boolean',
  957. default: false,
  958. },
  959. },
  960. init: function () {
  961. var _this = this
  962. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  963. // TODO make it work on cameraTransformMatrix too
  964. //
  965. _this.isReady = false
  966. _this._arAnchor = null
  967. _this._arHitTesting = null
  968. //LiveCdoing.space fix for editor mode
  969. if(arjsSystem) {
  970. // trick to wait until arjsSystem is isReady
  971. var startedAt = Date.now()
  972. var timerId = setInterval(function(){
  973. var anchorEl = _this.el
  974. var anchorComponent = anchorEl.components['arjs-anchor']
  975. // wait until anchorComponent is isReady
  976. if( anchorComponent === undefined || anchorComponent.isReady === false ) return
  977. clearInterval(timerId)
  978. //////////////////////////////////////////////////////////////////////////////
  979. // create arAnchor
  980. //////////////////////////////////////////////////////////////////////////////
  981. var arAnchor = anchorComponent._arAnchor
  982. var arSession = arjsSystem._arSession
  983. var renderer = arSession.parameters.renderer
  984. var hitTesting = _this._arHitTesting = new ARjs.HitTesting(arSession)
  985. hitTesting.enabled = _this.data.enabled
  986. _this.isReady = true
  987. }, 1000/60)
  988. }
  989. },
  990. remove : function(){
  991. },
  992. update: function () {
  993. },
  994. tick: function(){
  995. var _this = this
  996. // if not yet isReady, do nothing
  997. if( this.isReady === false ) return
  998. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  999. var arSession = arjsSystem._arSession
  1000. var anchorEl = _this.el
  1001. var anchorComponent = anchorEl.components['arjs-anchor']
  1002. var arAnchor = anchorComponent._arAnchor
  1003. var hitTesting = this._arHitTesting
  1004. var camera = arSession.parameters.camera
  1005. // console.log(camera.position)
  1006. hitTesting.update(camera, arAnchor.object3d, arAnchor.parameters.changeMatrixMode)
  1007. }
  1008. });
  1009. ///////////////END ARJS/////////
  1010. ///MIRROR//
  1011. THREE.ShaderLib[ 'mirror' ] = {
  1012. uniforms: {
  1013. "mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
  1014. "mirrorSampler": { value: null },
  1015. "textureMatrix" : { value: new THREE.Matrix4() }
  1016. },
  1017. vertexShader: [
  1018. "uniform mat4 textureMatrix;",
  1019. "varying vec4 mirrorCoord;",
  1020. "void main() {",
  1021. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1022. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  1023. "mirrorCoord = textureMatrix * worldPosition;",
  1024. "gl_Position = projectionMatrix * mvPosition;",
  1025. "}"
  1026. ].join( "\n" ),
  1027. fragmentShader: [
  1028. "uniform vec3 mirrorColor;",
  1029. "uniform sampler2D mirrorSampler;",
  1030. "varying vec4 mirrorCoord;",
  1031. "float blendOverlay(float base, float blend) {",
  1032. "return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
  1033. "}",
  1034. "void main() {",
  1035. "vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
  1036. "color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",
  1037. "gl_FragColor = color;",
  1038. "}"
  1039. ].join( "\n" )
  1040. };
  1041. THREE.Mirror = function ( renderer, camera, options ) {
  1042. THREE.Object3D.call( this );
  1043. this.name = 'mirror_' + this.id;
  1044. options = options || {};
  1045. this.matrixNeedsUpdate = true;
  1046. var width = options.textureWidth !== undefined ? options.textureWidth : 512;
  1047. var height = options.textureHeight !== undefined ? options.textureHeight : 512;
  1048. this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
  1049. var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
  1050. this.renderer = renderer;
  1051. this.mirrorPlane = new THREE.Plane();
  1052. this.normal = new THREE.Vector3( 0, 0, 1 );
  1053. this.mirrorWorldPosition = new THREE.Vector3();
  1054. this.cameraWorldPosition = new THREE.Vector3();
  1055. this.rotationMatrix = new THREE.Matrix4();
  1056. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  1057. this.clipPlane = new THREE.Vector4();
  1058. // For debug only, show the normal and plane of the mirror
  1059. var debugMode = options.debugMode !== undefined ? options.debugMode : false;
  1060. if ( debugMode ) {
  1061. var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
  1062. var planeGeometry = new THREE.Geometry();
  1063. planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
  1064. planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
  1065. planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
  1066. planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
  1067. planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
  1068. var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );
  1069. this.add( arrow );
  1070. this.add( plane );
  1071. }
  1072. if ( camera instanceof THREE.PerspectiveCamera ) {
  1073. this.camera = camera;
  1074. } else {
  1075. this.camera = new THREE.PerspectiveCamera();
  1076. console.log( this.name + ': camera is not a Perspective Camera!' );
  1077. }
  1078. this.textureMatrix = new THREE.Matrix4();
  1079. this.mirrorCamera = this.camera.clone();
  1080. this.mirrorCamera.matrixAutoUpdate = true;
  1081. var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
  1082. //this.currentRenderTarget = this.renderer.getRenderTarget();
  1083. this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
  1084. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );
  1085. var mirrorShader = THREE.ShaderLib[ "mirror" ];
  1086. var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
  1087. this.material = new THREE.ShaderMaterial( {
  1088. fragmentShader: mirrorShader.fragmentShader,
  1089. vertexShader: mirrorShader.vertexShader,
  1090. uniforms: mirrorUniforms
  1091. } );
  1092. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  1093. this.material.uniforms.mirrorColor.value = mirrorColor;
  1094. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  1095. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  1096. this.renderTarget.texture.generateMipmaps = false;
  1097. this.renderTarget2.texture.generateMipmaps = false;
  1098. }
  1099. this.updateTextureMatrix();
  1100. this.render();
  1101. };
  1102. THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
  1103. THREE.Mirror.prototype.constructor = THREE.Mirror;
  1104. THREE.Mirror.prototype.renderWithMirror = function ( otherMirror, aScene ) {
  1105. // update the mirror matrix to mirror the current view
  1106. this.updateTextureMatrix();
  1107. this.matrixNeedsUpdate = false;
  1108. // set the camera of the other mirror so the mirrored view is the reference view
  1109. var tempCamera = otherMirror.camera;
  1110. otherMirror.camera = this.mirrorCamera;
  1111. // render the other mirror in temp texture
  1112. otherMirror.renderTemp(aScene);
  1113. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;
  1114. // render the current mirror
  1115. this.render(aScene);
  1116. this.matrixNeedsUpdate = true;
  1117. // restore material and camera of other mirror
  1118. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
  1119. otherMirror.camera = tempCamera;
  1120. // restore texture matrix of other mirror
  1121. otherMirror.updateTextureMatrix();
  1122. };
  1123. THREE.Mirror.prototype.updateTextureMatrix = function () {
  1124. this.updateMatrixWorld();
  1125. this.camera.updateMatrixWorld();
  1126. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  1127. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  1128. this.rotationMatrix.extractRotation( this.matrixWorld );
  1129. this.normal.set( 0, 0, 1 );
  1130. this.normal.applyMatrix4( this.rotationMatrix );
  1131. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  1132. view.reflect( this.normal ).negate();
  1133. view.add( this.mirrorWorldPosition );
  1134. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  1135. this.lookAtPosition.set( 0, 0, - 1 );
  1136. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  1137. this.lookAtPosition.add( this.cameraWorldPosition );
  1138. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  1139. target.reflect( this.normal ).negate();
  1140. target.add( this.mirrorWorldPosition );
  1141. this.up.set( 0, - 1, 0 );
  1142. this.up.applyMatrix4( this.rotationMatrix );
  1143. this.up.reflect( this.normal ).negate();
  1144. this.mirrorCamera.position.copy( view );
  1145. this.mirrorCamera.up = this.up;
  1146. this.mirrorCamera.lookAt( target );
  1147. this.mirrorCamera.updateProjectionMatrix();
  1148. this.mirrorCamera.updateMatrixWorld();
  1149. this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
  1150. // Update the texture matrix
  1151. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  1152. 0.0, 0.5, 0.0, 0.5,
  1153. 0.0, 0.0, 0.5, 0.5,
  1154. 0.0, 0.0, 0.0, 1.0 );
  1155. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  1156. this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
  1157. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  1158. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  1159. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  1160. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  1161. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  1162. var q = new THREE.Vector4();
  1163. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  1164. q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  1165. q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  1166. q.z = - 1.0;
  1167. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  1168. // Calculate the scaled plane vector
  1169. var c = new THREE.Vector4();
  1170. c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  1171. // Replacing the third row of the projection matrix
  1172. projectionMatrix.elements[ 2 ] = c.x;
  1173. projectionMatrix.elements[ 6 ] = c.y;
  1174. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  1175. projectionMatrix.elements[ 14 ] = c.w;
  1176. };
  1177. THREE.Mirror.prototype.render = function (aScene) {
  1178. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1179. this.matrixNeedsUpdate = true;
  1180. // Render the mirrored view of the current scene into the target texture
  1181. //var scene = aScene //this;
  1182. // while ( scene.parent !== null ) {
  1183. // scene = scene.parent;
  1184. // }
  1185. //this.renderer.setRenderTarget( null );
  1186. if ( aScene !== undefined) //&& scene instanceof THREE.Scene )
  1187. {
  1188. // We can't render ourself to ourself
  1189. var visible = this.material.visible;
  1190. this.material.visible = false;
  1191. this.renderer.clear();
  1192. this.renderer.setRenderTarget( this.renderTarget);
  1193. this.renderer.render( aScene.object3D, this.mirrorCamera);
  1194. this.renderer.setRenderTarget(null);
  1195. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
  1196. this.material.visible = visible;
  1197. }
  1198. };
  1199. THREE.Mirror.prototype.renderTemp = function (aScene) {
  1200. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1201. this.matrixNeedsUpdate = true;
  1202. // Render the mirrored view of the current scene into the target texture
  1203. // var scene = this;
  1204. // while ( scene.parent !== null ) {
  1205. // scene = scene.parent;
  1206. // }
  1207. if ( aScene !== undefined) //&& scene instanceof THREE.Scene ) {
  1208. {
  1209. this.renderer.clear();
  1210. this.renderer.setRenderTarget( this.renderTarget2);
  1211. this.renderer.render( aScene.object3D, this.mirrorCamera );
  1212. this.renderer.setRenderTarget( null );
  1213. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );
  1214. }
  1215. };
  1216. AFRAME.registerComponent('mirror', {
  1217. schema:{
  1218. renderothermirror:{default:true},
  1219. camera:{default: 'avatarControl'}
  1220. },
  1221. init: function () {
  1222. var scene = this.el.sceneEl;
  1223. this.cameraID = this.data.camera;
  1224. scene.addEventListener('render-target-loaded',this.OnRenderLoaded()); //this.OnRenderLoaded.bind(this)
  1225. },
  1226. // update: function (old) {
  1227. // this.cameraID = this.data.camera;
  1228. // this.OnRenderLoaded();
  1229. // },
  1230. OnRenderLoaded: function()
  1231. {
  1232. var mirrorObj = this.el.getOrCreateObject3D('mesh',THREE.Mesh);
  1233. // var cameraEl = document.querySelector('a-entity[camera]')
  1234. // if(!cameraEl)
  1235. // {
  1236. // cameraEl = document.querySelector('a-camera');
  1237. // }
  1238. // var camera = cameraEl.components.camera.camera;
  1239. let cameraEl = document.querySelector("[id='" + this.cameraID + "']")
  1240. if (cameraEl){
  1241. let camera = cameraEl.getObject3D('camera'); //document.querySelector('#avatarControl').getObject3D('camera');
  1242. var scene = this.el.sceneEl;
  1243. // this.renderer = new THREE.WebGLRenderer({
  1244. // antialias: true,
  1245. // });
  1246. this.renderer = scene.renderer;
  1247. this.mirror = new THREE.Mirror( this.renderer, camera, { clipBias: 0.003, textureWidth: window.innerWidth, textureHeight: window.innerHeight, color: 0x777777, debugMode: false} );
  1248. mirrorObj.material = this.mirror.material;
  1249. //mirrorObj.children = [];
  1250. mirrorObj.add(this.mirror);
  1251. }
  1252. //As of A-Frame tick (behaviours) priority issue need to place mirror tick onto upper tick()
  1253. this.el.sceneEl.components['scene-utils'].mirrors[this.el.id] = this;
  1254. },
  1255. remove: function () {
  1256. delete this.el.sceneEl.components['scene-utils'].mirrors[this.el.id]
  1257. },
  1258. mirrorTick: function () {
  1259. // //this.mirror.render();
  1260. if(!this.data.renderothermirror)
  1261. {
  1262. this.mirror.render(this.el.sceneEl);
  1263. }
  1264. else
  1265. {
  1266. var mirrors = [];
  1267. var mirrorEls = document.querySelectorAll("[mirror]");
  1268. for(var i=0;i<mirrorEls.length;i++)
  1269. {
  1270. if(mirrorEls[i]!=this.el)
  1271. {
  1272. mirrors.push(mirrorEls[i].components.mirror.mirror);
  1273. }
  1274. }
  1275. if(mirrors.length === 0)
  1276. {
  1277. this.mirror.render(this.el.sceneEl);
  1278. }
  1279. for(var i = 0; i<mirrors.length;i++)
  1280. {
  1281. this.mirror.renderWithMirror(mirrors[i], this.el.sceneEl);
  1282. }
  1283. }
  1284. },
  1285. // tick: function () {
  1286. // }
  1287. });