server.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. const express = require('express');
  2. const dgram = require('dgram');
  3. const oscParser = require('./osc-parser');
  4. const bodyParser = require('body-parser');
  5. const { Bundle, Client } = require('node-osc');
  6. const path = require('path');
  7. const config = require('../frontend/assets/config.json');
  8. const app = express();
  9. app.use(bodyParser.json());
  10. app.use(bodyParser.urlencoded({extended:true}));
  11. app.use(express.static('./frontend/assets'));
  12. app.get('/', function (req, res) {
  13. res.sendFile('./frontend/index.html', {
  14. root: path.resolve(__dirname + '/..')
  15. });
  16. });
  17. const httpServer = require('http').Server(app);
  18. /* --------
  19. * RECEIVER
  20. * --------
  21. */
  22. const receiverIo = require('socket.io')(httpServer, {
  23. transports: ['websocket']
  24. });
  25. const onSocketListening = function() {
  26. const address = receiverUdpSocket.address();
  27. console.log('Serveur TUIO en écoute sur : ' + address.address + ':' + address.port);
  28. };
  29. const onSocketConnection = function(socket) {
  30. receiverUdpSocket.on('message', function(msg) {
  31. socket.emit('osc', oscParser.decode(msg));
  32. });
  33. };
  34. const receiverUdpSocket = dgram.createSocket('udp4');
  35. receiverUdpSocket.on('listening', onSocketListening);
  36. receiverUdpSocket.bind(config.app.oscUdpPort, '127.0.0.1');
  37. app.get('/receiver/json', function (req, res) {
  38. res.status(200).send();
  39. });
  40. receiverIo.sockets.on('connection', (socket) =>{
  41. console.log(`Connecté au client ${socket.id}`);
  42. const dgramCallback = function (buf) {
  43. // console.log(oscParser.decode(buf));
  44. socket.emit('osc', oscParser.decode(buf));
  45. };
  46. // forward UDP packets via socket.io
  47. receiverUdpSocket.on('message', dgramCallback);
  48. // prevent memory leak on disconnect
  49. socket.on('disconnect', function (socket) {
  50. receiverUdpSocket.removeListener('message', dgramCallback);
  51. });
  52. });
  53. /* -------
  54. * EMITTER
  55. * -------
  56. */
  57. const emitterOscClient = new Client('127.0.0.1', config.app.oscUdpPort);
  58. let alive = [];
  59. let fseq;
  60. let objTriangle = [] ;
  61. function getHypotenuse(touch1, touch2) {
  62. const x = Math.abs(touch1.x - touch2.x);
  63. const y = Math.abs(touch1.y - touch2.y);
  64. return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
  65. }
  66. function getTop(dotTrio) {
  67. const dist01 = getHypotenuse(dotTrio[0], dotTrio[1]);
  68. const dist02 = getHypotenuse(dotTrio[0], dotTrio[2]);
  69. const dist12 = getHypotenuse(dotTrio[1], dotTrio[2]);
  70. const diff01m02 = Math.abs(dist01 - dist02);
  71. const diff01m12 = Math.abs(dist01 - dist12);
  72. const diff02m12 = Math.abs(dist02 - dist12);
  73. if (diff01m02 < diff02m12 && diff01m02 < diff01m12) {
  74. return 0;
  75. }
  76. else if (diff01m12 < diff01m02 && diff01m12 < diff02m12) {
  77. return 1;
  78. }
  79. else if (diff02m12 < diff01m02 && diff02m12 < diff01m12) {
  80. return 2;
  81. }
  82. }
  83. function getAngleApex(dotTrio, topIndex) {
  84. let dotA;
  85. let dotB;
  86. let dotC;
  87. dotB = dotTrio[topIndex];
  88. if (topIndex == 0) {
  89. dotA = dotTrio[1];
  90. dotC = dotTrio[2];
  91. }
  92. else if (topIndex == 1) {
  93. dotA = dotTrio[0];
  94. dotC = dotTrio[2];
  95. }
  96. else if (topIndex == 2) {
  97. dotA = dotTrio[0];
  98. dotC = dotTrio[1];
  99. }
  100. const AB = [dotB.x - dotA.x, dotB.y - dotA.y];
  101. const CB = [dotB.x - dotC.x, dotB.y - dotC.y];
  102. const dotProd = (AB[0] * CB[0] + AB[1] * CB[1]);
  103. const crossProd = (AB[0] * CB[1] - AB[1] * CB[0]);
  104. const alpha = Math.atan2(crossProd, dotProd);
  105. //return alpha ;
  106. return Math.floor(alpha * 180. / Math.PI + 0.5) ;
  107. }
  108. function getOrientation(dotTrio, topIndex) {
  109. let dotA;
  110. let dotB;
  111. let dotC;
  112. dotB = dotTrio[topIndex];
  113. if (topIndex == 0) {
  114. dotA = dotTrio[1];
  115. dotC = dotTrio[2];
  116. }
  117. else if (topIndex == 1) {
  118. dotA = dotTrio[0];
  119. dotC = dotTrio[2];
  120. }
  121. else if (topIndex == 2) {
  122. dotA = dotTrio[0];
  123. dotC = dotTrio[1];
  124. }
  125. const middlePt = [(dotA.x + dotC.x) / 2, (dotA.y + dotC.y) / 2 ] ;
  126. let diff = [dotB.x - middlePt[0], dotB.y - middlePt[1]] ;
  127. const length = Math.sqrt(Math.pow(diff[0], 2) + Math.pow(diff[1], 2) ) ;
  128. //normalize diff
  129. diff = [diff[0] / length, diff[1] / length];
  130. const rad = Math.atan2(diff[0], diff[1]) ;
  131. return Math.floor(-1 * rad * 180 / Math.PI) ;
  132. //return length ;
  133. }
  134. app.post('/emitter/json', function (req, res) {
  135. if (req.body.debug) {
  136. //console.log(req.body);
  137. }
  138. let oscBundle;
  139. if (req.body.event === 'touchend') {
  140. fseq = fseq ? fseq + 1 : 1;
  141. const aliveMessage = [ '/tuio/2Dcur', 'alive' ].concat(alive);
  142. oscBundle = new Bundle(
  143. [ '/tuio/2Dcur', 'source', `tangibles${req.body.section.toString()}@127.0.0.1` ],
  144. aliveMessage,
  145. [ '/tuio/2Dcur', 'fseq', fseq ],
  146. [
  147. '/tuio/2Dcur',
  148. 'del',
  149. req.body.changedTouches[0].identifier
  150. ]
  151. );
  152. emitterOscClient.send(oscBundle, () => {
  153. const index = alive.indexOf(req.body.changedTouches[0].identifier);
  154. alive.splice(index, 1);
  155. if (alive.length === 0) {
  156. oscBundle = new Bundle(
  157. [ '/tuio/2Dcur', 'source', `tangibles${req.body.section.toString()}@127.0.0.1` ],
  158. [ '/tuio/2Dcur', 'alive' ],
  159. [ '/tuio/2Dcur', 'fseq', fseq ]
  160. );
  161. emitterOscClient.send(oscBundle, () => {
  162. res.status(200).send();
  163. fseq = 0;
  164. });
  165. } else {
  166. res.status(200).send();
  167. }
  168. });
  169. } else {
  170. if (req.body.changedTouches && req.body.changedTouches.length && req.body.changedTouches.length > 0) {
  171. fseq = fseq ? fseq + 1 : 1;
  172. const touches = Object.keys(req.body.changedTouches);
  173. const aliveMessage = [ '/tuio/2Dcur', 'alive' ].concat(alive);
  174. touches.forEach(touch => {
  175. const id = req.body.changedTouches[touch].identifier;
  176. if (!alive.includes(id)) {
  177. alive.push(id);
  178. aliveMessage.push(id);
  179. }
  180. });
  181. /* Listage de tous les points */
  182. const dots = [];
  183. touches.forEach(function(touch) {
  184. dots.push({
  185. id: req.body.changedTouches[touch].identifier,
  186. x: req.body.changedTouches[touch].clientX,
  187. y: req.body.changedTouches[touch].clientY
  188. });
  189. });
  190. // console.log(dots, dots.length);
  191. /* Listage des segments */
  192. const segments = [];
  193. if (dots.length > 2) {
  194. for (var i = 0; i < dots.length; i++) {
  195. for (var j = 0; j < dots.length; j++) {
  196. if (j !== i) {
  197. /* on vérifie que le segment n'est pas déjà listé */
  198. const alreadyExists = segments.find(segment => {
  199. return segment.identifiers.includes(i) && segment.identifiers.includes(j);
  200. });
  201. /* on calcule la taille du segment (l'hypoténuse) */
  202. var hyp = getHypotenuse(dots[i], dots[j]);
  203. /* on garde uniquement les segments inférieurs à 750px (valeur par défaut)
  204. * cette valeur est la variable de configuration "maxDistanceBetweenPoints" */
  205. if (!alreadyExists && hyp <= config.app.maxDistanceBetweenPoints) {
  206. segments.push({
  207. identifiers: [i, j],
  208. x1: dots[i].x,
  209. x2: dots[j].x,
  210. y1: dots[i].y,
  211. y2: dots[j].y,
  212. hyp
  213. });
  214. }
  215. }
  216. }
  217. }
  218. }
  219. // console.log(segments, segments.length);
  220. /* Listage des triangles */
  221. const triangles = [];
  222. /* on boucle sur les segments */
  223. segments.forEach((segment) => {
  224. const dot1 = segment.identifiers[0];
  225. const dot2 = segment.identifiers[1];
  226. /* on vérifie que le triangle n'est pas déjà listé */
  227. const alreadyExists = triangles.find(triangle => {
  228. return triangle.includes(dot1) && triangle.includes(dot2);
  229. });
  230. if (!alreadyExists) {
  231. /* on cherche les segments qui contiennent un des 2 points du segment actuel
  232. * ex: si le segment actuel est AB, on cherche un segment contenant A (pour AC) et un autre contenant B (pour BC) */
  233. const found1 = segments.findIndex(seg => {
  234. return (seg.identifiers.includes(dot1) && !seg.identifiers.includes(dot2));
  235. });
  236. const found2 = segments.findIndex(seg => {
  237. return (seg.identifiers.includes(dot2) && !seg.identifiers.includes(dot1));
  238. });
  239. /* si on trouve bien les 2 segments (AC et BC), on peut créer un triangle */
  240. if (found1 !== -1 && found2 !== -1) {
  241. /* on devine quel est le 3ème point du triangle par rapport au segment actuel (le point C par rapport au segment AB) */
  242. const dot3 = segments[found1].identifiers.find(identifier => {
  243. return identifier !== dot1 && identifier !== dot2;
  244. });
  245. triangles.push([dot1, dot2, dot3]);
  246. }
  247. }
  248. });
  249. console.log(triangles, triangles.length);
  250. //MOD TITI
  251. //objet pour stocker les informations des triangles identifiés (points, centre, apexAngle, orientation, indice apex, width, height)
  252. objTriangle = {} ;
  253. /* Définition de l'apex */
  254. triangles.forEach(triangle => {
  255. objTriangle.dots = [];
  256. objTriangle.dots[0] = dots[triangle[0]];
  257. objTriangle.dots[1] = dots[triangle[1]];
  258. objTriangle.dots[2] = dots[triangle[2]];
  259. objTriangle.apex = getTop(objTriangle.dots);
  260. objTriangle.center = [
  261. (objTriangle.dots[0].x+objTriangle.dots[1].x+objTriangle.dots[2].x)/3 ,
  262. (objTriangle.dots[0].y+objTriangle.dots[1].y+objTriangle.dots[2].y)/3
  263. ];
  264. objTriangle.angleApex = getAngleApex(objTriangle.dots, objTriangle.apex) ;
  265. objTriangle.orientation = getOrientation(objTriangle.dots, objTriangle.apex) ;
  266. // /* on récupère les 3 côtés (segments) du triangle */
  267. // const segment1 = segments.find(segment => {
  268. // return segment.identifiers.includes(triangle[0]) && segment.identifiers.includes(triangle[1]);
  269. // });
  270. // const segment2 = segments.find(segment => {
  271. // return segment.identifiers.includes(triangle[1]) && segment.identifiers.includes(triangle[2]);
  272. // });
  273. // const segment3 = segments.find(segment => {
  274. // return segment.identifiers.includes(triangle[0]) && segment.identifiers.includes(triangle[2]);
  275. // });
  276. // /* on trouve quel côté est le plus court
  277. // * NOTE: dans notre cas, l'apex sera toujours le point opposé au plus petit côté
  278. // * cette méthode n'est pas généralisable à d'autres projets */
  279. // const smallestSegment = [segment1, segment2, segment3].reduce(function(prev, current) {
  280. // return (prev.hyp < current.hyp) ? prev : current
  281. // });
  282. // /* on déduit quel point du triangle est l'apex */
  283. // const apexDot = triangle.find(dot => {
  284. // return dot !== smallestSegment.identifiers[0] && dot !== smallestSegment.identifiers[1];
  285. // });
  286. console.log(objTriangle.apex);
  287. console.log('centerPos : ' + objTriangle.center + ' orientation : ' + objTriangle.orientation);
  288. /* Reste à faire:
  289. * trouver la valeur de l'angle de l'apex (théorème des cosinus)
  290. * trouver le "centre" du triangle (via les orthocentres ou médianes??)
  291. * déduire l'orientation du triangle
  292. */
  293. });
  294. //plante vite
  295. // if (objTriangle.dots != undefined){
  296. // let oscBundleObj ;
  297. // oscBundleObj = new Bundle(
  298. // [ '/tuio/2Dobj', 'source', `tangibles${req.body.section.toString()}@127.0.0.1` ],
  299. // [ '/tuio/2Dobj', 'alive', 1 ],
  300. // [
  301. // '/tuio/2Dobj',
  302. // 'set',
  303. // 1,
  304. // 1,
  305. // objTriangle.center[0],
  306. // objTriangle.center[1],
  307. // objTriangle.orientation,
  308. // 0.0,
  309. // 0.0,
  310. // 0.0,
  311. // 0.0,
  312. // 0.0
  313. // ],
  314. // [ '/tuio/2Dobj', 'fseq', fseq ]
  315. // );
  316. // // // objTriangle.forEach(triangleIndex => {
  317. // // // oscBundle.append(
  318. // // // [
  319. // // // '/tuio/2Dobj',
  320. // // // 'set',
  321. // // // triangleIndex,
  322. // // // triangleIndex,
  323. // // // objTriangle[triangleIndex].center[0],
  324. // // // objTriangle[triangleIndex].center[1],
  325. // // // objTriangle[triangleIndex].orientation,
  326. // // // 0.0,
  327. // // // 0.0,
  328. // // // 0.0,
  329. // // // 0.0,
  330. // // // 0.0
  331. // // // ]
  332. // // // );
  333. // // // });
  334. // console.log(oscBundleObj);
  335. // emitterOscClient.send(oscBundleObj, () => {
  336. // res.status(200).send();
  337. // });
  338. // }
  339. // oscBundle = new Bundle(
  340. // [ '/tuio/2Dcur', 'source', `tangibles${req.body.section.toString()}@127.0.0.1` ],
  341. // aliveMessage,
  342. // [ '/tuio/2Dcur', 'fseq', fseq ]
  343. // );
  344. // touches.forEach(touch => {
  345. // oscBundle.append(
  346. // [
  347. // '/tuio/2Dcur',
  348. // 'set',
  349. // req.body.changedTouches[touch].identifier,
  350. // req.body.changedTouches[touch].clientX / req.body.screenW,
  351. // req.body.changedTouches[touch].clientY / req.body.screenH,
  352. // 0.0,
  353. // 0.0
  354. // ]
  355. // );
  356. // });
  357. oscBundle = new Bundle ;
  358. oscBundle.append([ '/tuio/2Dobj', 'alive', 1 ]);
  359. if (objTriangle.dots != undefined) {
  360. oscBundle.append([
  361. '/tuio/2Dobj',
  362. 'set',
  363. 1,
  364. 1,
  365. objTriangle.center[0],
  366. objTriangle.center[1],
  367. objTriangle.orientation,
  368. 0.0,
  369. 0.0,
  370. 0.0,
  371. 0.0,
  372. 0.0
  373. ]);
  374. }
  375. oscBundle.append([ '/tuio/2Dobj', 'fseq', fseq ]);
  376. emitterOscClient.send(oscBundle, () => {
  377. res.status(200).send();
  378. });
  379. } else {
  380. res.status(400).send();
  381. }
  382. }
  383. });
  384. httpServer.listen(config.app.httpPort, function () {
  385. console.log(`Votre app est disponible sur http://localhost:${config.app.httpPort} !`)
  386. });