aframe-components.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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. ////ARJS///
  610. //////////////////////////////////////////////////////////////////////////////
  611. // arjs-anchor
  612. //////////////////////////////////////////////////////////////////////////////
  613. AFRAME.registerComponent('arjs-anchor', {
  614. dependencies: ['arjs', 'artoolkit'],
  615. schema: {
  616. preset: {
  617. type: 'string',
  618. },
  619. markerhelpers: { // IIF preset === 'area'
  620. type: 'boolean',
  621. default: false,
  622. },
  623. // controls parameters
  624. size: {
  625. type: 'number',
  626. default: 1
  627. },
  628. type: {
  629. type: 'string',
  630. },
  631. patternUrl: {
  632. type: 'string',
  633. },
  634. barcodeValue: {
  635. type: 'number'
  636. },
  637. changeMatrixMode: {
  638. type: 'string',
  639. default: 'modelViewMatrix',
  640. },
  641. minConfidence: {
  642. type: 'number',
  643. default: 0.6,
  644. },
  645. smooth: {
  646. type: 'boolean',
  647. default: false,
  648. },
  649. smoothCount: {
  650. type: 'number',
  651. default: 5,
  652. },
  653. smoothTolerance: {
  654. type: 'number',
  655. default: 0.01,
  656. },
  657. smoothThreshold: {
  658. type: 'number',
  659. default: 2,
  660. },
  661. },
  662. init: function () {
  663. var _this = this
  664. // get arjsSystem
  665. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  666. //////////////////////////////////////////////////////////////////////////////
  667. // Code Separator
  668. //////////////////////////////////////////////////////////////////////////////
  669. _this.isReady = false
  670. _this._arAnchor = null
  671. //LiveCoding.space fix for editor mode
  672. if(arjsSystem) {
  673. // honor object visibility
  674. if (_this.data.changeMatrixMode === 'modelViewMatrix') {
  675. _this.el.object3D.visible = false
  676. } else if (_this.data.changeMatrixMode === 'cameraTransformMatrix') {
  677. _this.el.sceneEl.object3D.visible = false
  678. } else console.assert(false)
  679. // trick to wait until arjsSystem is isReady
  680. var startedAt = Date.now()
  681. var timerId = setInterval(function () {
  682. // wait until the system is isReady
  683. if (arjsSystem.isReady === false) return
  684. clearInterval(timerId)
  685. //////////////////////////////////////////////////////////////////////////////
  686. // update arProfile
  687. //////////////////////////////////////////////////////////////////////////////
  688. var arProfile = arjsSystem._arProfile
  689. // arProfile.changeMatrixMode('modelViewMatrix')
  690. arProfile.changeMatrixMode(_this.data.changeMatrixMode)
  691. // honor this.data.preset
  692. var markerParameters = Object.assign({}, arProfile.defaultMarkerParameters)
  693. if (_this.data.preset === 'hiro') {
  694. markerParameters.type = 'pattern'
  695. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-hiro.patt'
  696. markerParameters.markersAreaEnabled = false
  697. } else if (_this.data.preset === 'kanji') {
  698. markerParameters.type = 'pattern'
  699. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-kanji.patt'
  700. markerParameters.markersAreaEnabled = false
  701. } else if (_this.data.preset === 'area') {
  702. markerParameters.type = 'barcode'
  703. markerParameters.barcodeValue = 1001
  704. markerParameters.markersAreaEnabled = true
  705. } else if (_this.data.type === 'barcode') {
  706. markerParameters = {
  707. type: _this.data.type,
  708. changeMatrixMode: 'modelViewMatrix',
  709. barcodeValue: _this.data.barcodeValue,
  710. markersAreaEnabled: false
  711. }
  712. } else if (_this.data.type === 'pattern') {
  713. markerParameters.type = _this.data.type
  714. markerParameters.patternUrl = _this.data.patternUrl;
  715. markerParameters.markersAreaEnabled = false
  716. }
  717. markerParameters.smooth = _this.data.smooth;
  718. markerParameters.smoothCount = _this.data.smoothCount;
  719. markerParameters.smoothTolerance = _this.data.smoothTolerance;
  720. markerParameters.smoothThreshold = _this.data.smoothThreshold;
  721. //////////////////////////////////////////////////////////////////////////////
  722. // create arAnchor
  723. //////////////////////////////////////////////////////////////////////////////
  724. var arSession = arjsSystem._arSession
  725. var arAnchor = _this._arAnchor = new ARjs.Anchor(arSession, markerParameters)
  726. // it is now considered isReady
  727. _this.isReady = true
  728. //////////////////////////////////////////////////////////////////////////////
  729. // honor .debugUIEnabled
  730. //////////////////////////////////////////////////////////////////////////////
  731. if (arjsSystem.data.debugUIEnabled) {
  732. // get or create containerElement
  733. var containerElement = document.querySelector('#arjsDebugUIContainer')
  734. if (containerElement === null) {
  735. containerElement = document.createElement('div')
  736. containerElement.id = 'arjsDebugUIContainer'
  737. containerElement.setAttribute('style', 'position: fixed; bottom: 10px; width:100%; text-align: center; z-index: 1; color: grey;')
  738. document.body.appendChild(containerElement)
  739. }
  740. // create anchorDebugUI
  741. var anchorDebugUI = new ARjs.AnchorDebugUI(arAnchor)
  742. containerElement.appendChild(anchorDebugUI.domElement)
  743. }
  744. }, 1000 / 60)
  745. }
  746. },
  747. remove: function () {
  748. },
  749. update: function () {
  750. },
  751. tick: function () {
  752. var _this = this
  753. // if not yet isReady, do nothing
  754. if (this.isReady === false) return
  755. //////////////////////////////////////////////////////////////////////////////
  756. // update arAnchor
  757. //////////////////////////////////////////////////////////////////////////////
  758. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  759. this._arAnchor.update()
  760. //////////////////////////////////////////////////////////////////////////////
  761. // honor pose
  762. //////////////////////////////////////////////////////////////////////////////
  763. var arWorldRoot = this._arAnchor.object3d
  764. arWorldRoot.updateMatrixWorld(true)
  765. arWorldRoot.matrixWorld.decompose(this.el.object3D.position, this.el.object3D.quaternion, this.el.object3D.scale)
  766. //////////////////////////////////////////////////////////////////////////////
  767. // honor visibility
  768. //////////////////////////////////////////////////////////////////////////////
  769. if (_this._arAnchor.parameters.changeMatrixMode === 'modelViewMatrix') {
  770. var wasVisible = _this.el.object3D.visible
  771. _this.el.object3D.visible = this._arAnchor.object3d.visible
  772. } else if (_this._arAnchor.parameters.changeMatrixMode === 'cameraTransformMatrix') {
  773. var wasVisible = _this.el.sceneEl.object3D.visible
  774. _this.el.sceneEl.object3D.visible = this._arAnchor.object3d.visible
  775. } else console.assert(false)
  776. // emit markerFound markerLost
  777. if (_this._arAnchor.object3d.visible === true && wasVisible === false) {
  778. _this.el.emit('markerFound')
  779. } else if (_this._arAnchor.object3d.visible === false && wasVisible === true) {
  780. _this.el.emit('markerLost')
  781. }
  782. }
  783. })
  784. //////////////////////////////////////////////////////////////////////////////
  785. // define some primitives shortcuts
  786. //////////////////////////////////////////////////////////////////////////////
  787. AFRAME.registerPrimitive('a-anchor', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  788. defaultComponents: {
  789. 'arjs-anchor': {},
  790. 'arjs-hit-testing': {},
  791. },
  792. mappings: {
  793. 'type': 'arjs-anchor.type',
  794. 'size': 'arjs-anchor.size',
  795. 'url': 'arjs-anchor.patternUrl',
  796. 'value': 'arjs-anchor.barcodeValue',
  797. 'preset': 'arjs-anchor.preset',
  798. 'min-confidence': 'arjs-anchor.minConfidence',
  799. 'marker-helpers': 'arjs-anchor.markerhelpers',
  800. 'smooth': 'arjs-anchor.smooth',
  801. 'smooth-count': 'arjs-anchor.smoothCount',
  802. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  803. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  804. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  805. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  806. }
  807. }))
  808. AFRAME.registerPrimitive('a-camera-static', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  809. defaultComponents: {
  810. 'camera': {},
  811. },
  812. mappings: {
  813. }
  814. }))
  815. //////////////////////////////////////////////////////////////////////////////
  816. // backward compatibility
  817. //////////////////////////////////////////////////////////////////////////////
  818. // FIXME
  819. AFRAME.registerPrimitive('a-marker', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  820. defaultComponents: {
  821. 'arjs-anchor': {},
  822. 'arjs-hit-testing': {},
  823. },
  824. mappings: {
  825. 'type': 'arjs-anchor.type',
  826. 'size': 'arjs-anchor.size',
  827. 'url': 'arjs-anchor.patternUrl',
  828. 'value': 'arjs-anchor.barcodeValue',
  829. 'preset': 'arjs-anchor.preset',
  830. 'min-confidence': 'arjs-anchor.minConfidence',
  831. 'marker-helpers': 'arjs-anchor.markerhelpers',
  832. 'smooth': 'arjs-anchor.smooth',
  833. 'smooth-count': 'arjs-anchor.smoothCount',
  834. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  835. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  836. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  837. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  838. }
  839. }))
  840. AFRAME.registerPrimitive('a-marker-camera', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  841. defaultComponents: {
  842. 'arjs-anchor': {
  843. changeMatrixMode: 'cameraTransformMatrix'
  844. },
  845. 'camera': {},
  846. },
  847. mappings: {
  848. 'type': 'arjs-anchor.type',
  849. 'size': 'arjs-anchor.size',
  850. 'url': 'arjs-anchor.patternUrl',
  851. 'value': 'arjs-anchor.barcodeValue',
  852. 'preset': 'arjs-anchor.preset',
  853. 'min-confidence': 'arjs-anchor.minConfidence',
  854. 'marker-helpers': 'arjs-anchor.markerhelpers',
  855. }
  856. }))
  857. //////////////////////////////////////////////////////////////////////////////
  858. // arjs-hit-testing
  859. //////////////////////////////////////////////////////////////////////////////
  860. AFRAME.registerComponent('arjs-hit-testing', {
  861. dependencies: ['arjs', 'artoolkit'],
  862. schema: {
  863. enabled : {
  864. type: 'boolean',
  865. default: false,
  866. },
  867. renderDebug : {
  868. type: 'boolean',
  869. default: false,
  870. },
  871. },
  872. init: function () {
  873. var _this = this
  874. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  875. // TODO make it work on cameraTransformMatrix too
  876. //
  877. _this.isReady = false
  878. _this._arAnchor = null
  879. _this._arHitTesting = null
  880. //LiveCdoing.space fix for editor mode
  881. if(arjsSystem) {
  882. // trick to wait until arjsSystem is isReady
  883. var startedAt = Date.now()
  884. var timerId = setInterval(function(){
  885. var anchorEl = _this.el
  886. var anchorComponent = anchorEl.components['arjs-anchor']
  887. // wait until anchorComponent is isReady
  888. if( anchorComponent === undefined || anchorComponent.isReady === false ) return
  889. clearInterval(timerId)
  890. //////////////////////////////////////////////////////////////////////////////
  891. // create arAnchor
  892. //////////////////////////////////////////////////////////////////////////////
  893. var arAnchor = anchorComponent._arAnchor
  894. var arSession = arjsSystem._arSession
  895. var renderer = arSession.parameters.renderer
  896. var hitTesting = _this._arHitTesting = new ARjs.HitTesting(arSession)
  897. hitTesting.enabled = _this.data.enabled
  898. _this.isReady = true
  899. }, 1000/60)
  900. }
  901. },
  902. remove : function(){
  903. },
  904. update: function () {
  905. },
  906. tick: function(){
  907. var _this = this
  908. // if not yet isReady, do nothing
  909. if( this.isReady === false ) return
  910. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  911. var arSession = arjsSystem._arSession
  912. var anchorEl = _this.el
  913. var anchorComponent = anchorEl.components['arjs-anchor']
  914. var arAnchor = anchorComponent._arAnchor
  915. var hitTesting = this._arHitTesting
  916. var camera = arSession.parameters.camera
  917. // console.log(camera.position)
  918. hitTesting.update(camera, arAnchor.object3d, arAnchor.parameters.changeMatrixMode)
  919. }
  920. });
  921. ///////////////END ARJS/////////
  922. ///MIRROR//
  923. THREE.ShaderLib[ 'mirror' ] = {
  924. uniforms: {
  925. "mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
  926. "mirrorSampler": { value: null },
  927. "textureMatrix" : { value: new THREE.Matrix4() }
  928. },
  929. vertexShader: [
  930. "uniform mat4 textureMatrix;",
  931. "varying vec4 mirrorCoord;",
  932. "void main() {",
  933. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  934. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  935. "mirrorCoord = textureMatrix * worldPosition;",
  936. "gl_Position = projectionMatrix * mvPosition;",
  937. "}"
  938. ].join( "\n" ),
  939. fragmentShader: [
  940. "uniform vec3 mirrorColor;",
  941. "uniform sampler2D mirrorSampler;",
  942. "varying vec4 mirrorCoord;",
  943. "float blendOverlay(float base, float blend) {",
  944. "return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
  945. "}",
  946. "void main() {",
  947. "vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
  948. "color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",
  949. "gl_FragColor = color;",
  950. "}"
  951. ].join( "\n" )
  952. };
  953. THREE.Mirror = function ( renderer, camera, options ) {
  954. THREE.Object3D.call( this );
  955. this.name = 'mirror_' + this.id;
  956. options = options || {};
  957. this.matrixNeedsUpdate = true;
  958. var width = options.textureWidth !== undefined ? options.textureWidth : 512;
  959. var height = options.textureHeight !== undefined ? options.textureHeight : 512;
  960. this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
  961. var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
  962. this.renderer = renderer;
  963. this.mirrorPlane = new THREE.Plane();
  964. this.normal = new THREE.Vector3( 0, 0, 1 );
  965. this.mirrorWorldPosition = new THREE.Vector3();
  966. this.cameraWorldPosition = new THREE.Vector3();
  967. this.rotationMatrix = new THREE.Matrix4();
  968. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  969. this.clipPlane = new THREE.Vector4();
  970. // For debug only, show the normal and plane of the mirror
  971. var debugMode = options.debugMode !== undefined ? options.debugMode : false;
  972. if ( debugMode ) {
  973. var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
  974. var planeGeometry = new THREE.Geometry();
  975. planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
  976. planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
  977. planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
  978. planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
  979. planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
  980. var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );
  981. this.add( arrow );
  982. this.add( plane );
  983. }
  984. if ( camera instanceof THREE.PerspectiveCamera ) {
  985. this.camera = camera;
  986. } else {
  987. this.camera = new THREE.PerspectiveCamera();
  988. console.log( this.name + ': camera is not a Perspective Camera!' );
  989. }
  990. this.textureMatrix = new THREE.Matrix4();
  991. this.mirrorCamera = this.camera.clone();
  992. this.mirrorCamera.matrixAutoUpdate = true;
  993. var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
  994. //this.currentRenderTarget = this.renderer.getRenderTarget();
  995. this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
  996. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );
  997. var mirrorShader = THREE.ShaderLib[ "mirror" ];
  998. var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
  999. this.material = new THREE.ShaderMaterial( {
  1000. fragmentShader: mirrorShader.fragmentShader,
  1001. vertexShader: mirrorShader.vertexShader,
  1002. uniforms: mirrorUniforms
  1003. } );
  1004. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  1005. this.material.uniforms.mirrorColor.value = mirrorColor;
  1006. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  1007. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  1008. this.renderTarget.texture.generateMipmaps = false;
  1009. this.renderTarget2.texture.generateMipmaps = false;
  1010. }
  1011. this.updateTextureMatrix();
  1012. this.render();
  1013. };
  1014. THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
  1015. THREE.Mirror.prototype.constructor = THREE.Mirror;
  1016. THREE.Mirror.prototype.renderWithMirror = function ( otherMirror, aScene ) {
  1017. // update the mirror matrix to mirror the current view
  1018. this.updateTextureMatrix();
  1019. this.matrixNeedsUpdate = false;
  1020. // set the camera of the other mirror so the mirrored view is the reference view
  1021. var tempCamera = otherMirror.camera;
  1022. otherMirror.camera = this.mirrorCamera;
  1023. // render the other mirror in temp texture
  1024. otherMirror.renderTemp(aScene);
  1025. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;
  1026. // render the current mirror
  1027. this.render(aScene);
  1028. this.matrixNeedsUpdate = true;
  1029. // restore material and camera of other mirror
  1030. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
  1031. otherMirror.camera = tempCamera;
  1032. // restore texture matrix of other mirror
  1033. otherMirror.updateTextureMatrix();
  1034. };
  1035. THREE.Mirror.prototype.updateTextureMatrix = function () {
  1036. this.updateMatrixWorld();
  1037. this.camera.updateMatrixWorld();
  1038. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  1039. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  1040. this.rotationMatrix.extractRotation( this.matrixWorld );
  1041. this.normal.set( 0, 0, 1 );
  1042. this.normal.applyMatrix4( this.rotationMatrix );
  1043. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  1044. view.reflect( this.normal ).negate();
  1045. view.add( this.mirrorWorldPosition );
  1046. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  1047. this.lookAtPosition.set( 0, 0, - 1 );
  1048. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  1049. this.lookAtPosition.add( this.cameraWorldPosition );
  1050. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  1051. target.reflect( this.normal ).negate();
  1052. target.add( this.mirrorWorldPosition );
  1053. this.up.set( 0, - 1, 0 );
  1054. this.up.applyMatrix4( this.rotationMatrix );
  1055. this.up.reflect( this.normal ).negate();
  1056. this.mirrorCamera.position.copy( view );
  1057. this.mirrorCamera.up = this.up;
  1058. this.mirrorCamera.lookAt( target );
  1059. this.mirrorCamera.updateProjectionMatrix();
  1060. this.mirrorCamera.updateMatrixWorld();
  1061. this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
  1062. // Update the texture matrix
  1063. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  1064. 0.0, 0.5, 0.0, 0.5,
  1065. 0.0, 0.0, 0.5, 0.5,
  1066. 0.0, 0.0, 0.0, 1.0 );
  1067. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  1068. this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
  1069. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  1070. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  1071. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  1072. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  1073. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  1074. var q = new THREE.Vector4();
  1075. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  1076. q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  1077. q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  1078. q.z = - 1.0;
  1079. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  1080. // Calculate the scaled plane vector
  1081. var c = new THREE.Vector4();
  1082. c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  1083. // Replacing the third row of the projection matrix
  1084. projectionMatrix.elements[ 2 ] = c.x;
  1085. projectionMatrix.elements[ 6 ] = c.y;
  1086. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  1087. projectionMatrix.elements[ 14 ] = c.w;
  1088. };
  1089. THREE.Mirror.prototype.render = function (aScene) {
  1090. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1091. this.matrixNeedsUpdate = true;
  1092. // Render the mirrored view of the current scene into the target texture
  1093. //var scene = aScene //this;
  1094. // while ( scene.parent !== null ) {
  1095. // scene = scene.parent;
  1096. // }
  1097. //this.renderer.setRenderTarget( null );
  1098. if ( aScene !== undefined) //&& scene instanceof THREE.Scene )
  1099. {
  1100. // We can't render ourself to ourself
  1101. var visible = this.material.visible;
  1102. this.material.visible = false;
  1103. this.renderer.clear();
  1104. this.renderer.setRenderTarget( this.renderTarget);
  1105. this.renderer.render( aScene.object3D, this.mirrorCamera);
  1106. this.renderer.setRenderTarget(null);
  1107. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
  1108. this.material.visible = visible;
  1109. }
  1110. };
  1111. THREE.Mirror.prototype.renderTemp = function (aScene) {
  1112. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1113. this.matrixNeedsUpdate = true;
  1114. // Render the mirrored view of the current scene into the target texture
  1115. // var scene = this;
  1116. // while ( scene.parent !== null ) {
  1117. // scene = scene.parent;
  1118. // }
  1119. if ( aScene !== undefined) //&& scene instanceof THREE.Scene ) {
  1120. {
  1121. this.renderer.clear();
  1122. this.renderer.setRenderTarget( this.renderTarget2);
  1123. this.renderer.render( aScene.object3D, this.mirrorCamera );
  1124. this.renderer.setRenderTarget( null );
  1125. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );
  1126. }
  1127. };
  1128. AFRAME.registerComponent('mirror', {
  1129. schema:{
  1130. renderothermirror:{default:true},
  1131. camera:{default: 'avatarControl'}
  1132. },
  1133. init: function () {
  1134. var scene = this.el.sceneEl;
  1135. this.cameraID = this.data.camera;
  1136. scene.addEventListener('render-target-loaded',this.OnRenderLoaded()); //this.OnRenderLoaded.bind(this)
  1137. },
  1138. // update: function (old) {
  1139. // this.cameraID = this.data.camera;
  1140. // this.OnRenderLoaded();
  1141. // },
  1142. OnRenderLoaded: function()
  1143. {
  1144. var mirrorObj = this.el.getOrCreateObject3D('mesh',THREE.Mesh);
  1145. // var cameraEl = document.querySelector('a-entity[camera]')
  1146. // if(!cameraEl)
  1147. // {
  1148. // cameraEl = document.querySelector('a-camera');
  1149. // }
  1150. // var camera = cameraEl.components.camera.camera;
  1151. let cameraEl = document.querySelector("[id='" + this.cameraID + "']")
  1152. if (cameraEl){
  1153. let camera = cameraEl.getObject3D('camera'); //document.querySelector('#avatarControl').getObject3D('camera');
  1154. var scene = this.el.sceneEl;
  1155. // this.renderer = new THREE.WebGLRenderer({
  1156. // antialias: true,
  1157. // });
  1158. this.renderer = scene.renderer;
  1159. this.mirror = new THREE.Mirror( this.renderer, camera, { clipBias: 0.003, textureWidth: window.innerWidth, textureHeight: window.innerHeight, color: 0x777777, debugMode: false} );
  1160. mirrorObj.material = this.mirror.material;
  1161. //mirrorObj.children = [];
  1162. mirrorObj.add(this.mirror);
  1163. }
  1164. //As of A-Frame tick (behaviours) priority issue need to place mirror tick onto upper tick()
  1165. this.el.sceneEl.components['scene-utils'].mirrors[this.el.id] = this;
  1166. },
  1167. remove: function () {
  1168. delete this.el.sceneEl.components['scene-utils'].mirrors[this.el.id]
  1169. },
  1170. mirrorTick: function () {
  1171. // //this.mirror.render();
  1172. if(!this.data.renderothermirror)
  1173. {
  1174. this.mirror.render(this.el.sceneEl);
  1175. }
  1176. else
  1177. {
  1178. var mirrors = [];
  1179. var mirrorEls = document.querySelectorAll("[mirror]");
  1180. for(var i=0;i<mirrorEls.length;i++)
  1181. {
  1182. if(mirrorEls[i]!=this.el)
  1183. {
  1184. mirrors.push(mirrorEls[i].components.mirror.mirror);
  1185. }
  1186. }
  1187. if(mirrors.length === 0)
  1188. {
  1189. this.mirror.render(this.el.sceneEl);
  1190. }
  1191. for(var i = 0; i<mirrors.length;i++)
  1192. {
  1193. this.mirror.renderWithMirror(mirrors[i], this.el.sceneEl);
  1194. }
  1195. }
  1196. },
  1197. // tick: function () {
  1198. // }
  1199. });