aframe-components.js 51 KB

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