aframe-components.js 45 KB

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