aframe-components.js 46 KB

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