ConcernementMapItem.vue 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103
  1. <script>
  2. import { nextTick } from 'vue'
  3. import Matter from "matter-js";
  4. import MatterAttractors from "matter-attractors";
  5. // Matter.use(MatterAttractors);
  6. // import polydecomp from "poly-decomp";
  7. import paper from 'paper';
  8. // import { easeInOutQuad, easeInOutQuart } from 'easing-utils';
  9. import Tween from "@tweenjs/tween.js";
  10. import { mapState, mapActions } from 'pinia'
  11. import { ConcernementsStore } from '@/stores/concernements'
  12. import { CommonStore } from '@/stores/common'
  13. import { mdiPictureInPictureBottomRight } from '@mdi/js';
  14. export default {
  15. inject: ['canvasMap', 'matterEngine'],
  16. data() {
  17. return {
  18. id: null,
  19. cid: null,
  20. concernement: null,
  21. active_revision: null,
  22. entities: null,
  23. superposedEntitesIDsList: [],
  24. canvas: null,
  25. ctx: null,
  26. pos : {
  27. x: 0,
  28. y: 0
  29. },
  30. ray: 100,
  31. time: 0,
  32. salientPoints: [],
  33. scale: 1,
  34. prev_scale: 1,
  35. opacity: 0,
  36. tween: null,
  37. is_open: false,
  38. is_opening: false,
  39. is_closing: false,
  40. is_hover: false,
  41. //
  42. body: null,
  43. body_parts: [],
  44. constraint: null,
  45. //
  46. paper_main_object: {},
  47. paper_groups: {}
  48. }
  49. },
  50. props: ['mapitem'],
  51. computed: {
  52. ...mapState(ConcernementsStore,['map_mode',
  53. 'concernementsByID',
  54. 'allSuperpositions_byid',
  55. 'allMapItems_byid',
  56. 'opened_concernement',
  57. 'opened_entite_id']),
  58. ...mapState(CommonStore,['hover_elmt',
  59. 'map_item_ray',
  60. 'cartouch_width',
  61. 'cartouch_is_opened',
  62. 'paper_symbol_definitions'])
  63. },
  64. created () {
  65. // console.log('ConcernementMapItem created', this.mapitem);
  66. // this.id = this.superposition_id ? `${this.cid}___${this.superposition_id}` : this.cid;
  67. this.id = this.mapitem.id;
  68. this.concernement = this.mapitem.concernement;
  69. this.cid = this.concernement.id;
  70. // console.log('mapitem this.cid', this.cid);
  71. this.active_revision = this.concernement.active_revision;
  72. // console.log(`ConcernementsMapItem ${this.id} created`);
  73. // this.entites = this.concernement.entites
  74. this.entites = this.concernement.revisions_byid[this.concernement.revision_id].entites;
  75. // disable concernement if less than 3 entite
  76. if(this.entites.length < 3){
  77. this.hideShowConcernement(this.concernement.id, false);
  78. } else{
  79. // record canvas and ctx for rendering (drawing)
  80. this.canvas = this.canvasMap.canvas
  81. this.ctx = this.canvasMap.ctx
  82. // define the ray regarding the width and height of screen
  83. this.ray = this.map_item_ray;
  84. // console.log(`this.ray: ${this.ray}`);
  85. //
  86. this.parseEntityPointsValues()
  87. // this.getSalientPoints()
  88. this.getJarvisEnvelopeConvexe()
  89. // define init position of the item
  90. this.pos = this.getRandomPos();
  91. //
  92. this.getSuperposedEntitesIDsList();
  93. //
  94. this.initMatterBody()
  95. //
  96. this.initPaperObjects()
  97. }
  98. // this.setConcernementMapItem(this.cid, this);
  99. },
  100. // mounted() {
  101. // console.log(`ConcernementsMapItem ${this.concernement.id} mounted`, this.canvasMap.canvas);
  102. // },
  103. // beforeUnmount () {
  104. unmounted () {
  105. // console.log(`mapitem ${this.id} unmounted`);
  106. if(this.mapitem.clone) {
  107. // console.log(`this.paper_main_object ${this.paper_main_object.id}`, this.paper_main_object);
  108. paper.project.getItem({id:this.paper_main_object.id}).remove();
  109. };
  110. if (this.body) {
  111. Matter.Composite.remove(this.matterEngine.world, this.body);
  112. }
  113. },
  114. watch: {
  115. // canvasMap (n, o) {
  116. // console.log("concernementItem watch canvasMap", o, n);
  117. // }
  118. canvasMap: {
  119. handler (n, o){
  120. // console.log("concernementItem watch canvasMap.ctx", typeof this.canvas, o, n);
  121. if (!this.canvas) {
  122. this.initCanvasMap()
  123. }
  124. },
  125. deep: true
  126. },
  127. opened_concernement: {
  128. handler (n, o) {
  129. if (!n) { // if there is no opened concernement
  130. this.is_open = false;
  131. this.applyShuffleForces();
  132. } else {
  133. if(this.cid === n.id && this.id === n.opened_mapitem_id){
  134. this.is_open = true;
  135. }else{
  136. this.is_open = false;
  137. }
  138. }
  139. },
  140. deep: true
  141. },
  142. is_open: {
  143. handler (n, o) {
  144. // console.log('mapItem watch is_open', n, this.is_open);
  145. if(n){ // opened
  146. this.openClose(true);
  147. }else if(o) { // closed if was opened
  148. this.openClose(false);
  149. }
  150. },
  151. deep: true
  152. },
  153. map_mode: {
  154. handler (n, o) {
  155. console.log('concernementMapItem watch map_mode', o, n);
  156. if (n === 'terraindevie' && !this.opened_concernement) {
  157. this.applyShuffleForces(); // apply a little force to check the map when returning to terrain de vie
  158. }
  159. if (this.is_open & n !== o) {
  160. this.setPaperContents();
  161. }
  162. if (n !== o) {
  163. this.handlePaperVisibilityOnMapMode()
  164. }
  165. },
  166. deep: true
  167. },
  168. hover_elmt: {
  169. handler (n, o) {
  170. // console.log(`watch hover_elmt ${this.id}`, o, n);
  171. if (n && (n.type === 'concernement' || n.type === 'superposition') && n.id === this.id) {
  172. this.is_hover = true;
  173. } else {
  174. this.is_hover = false;
  175. }
  176. },
  177. deep: true
  178. },
  179. is_hover: {
  180. handler (n, o) {
  181. this.onIsHover(n);
  182. },
  183. deep: true
  184. },
  185. concernement: {
  186. handler (n, o){
  187. // check for active_revision changes
  188. // do not trigger on first variable filling (if o is null)
  189. if(this.is_open && o && o.active_revision && n.active_revision && this.map_mode === "terraindevie"){
  190. // be aware that here o & n active_revision are already the same :( !?
  191. console.log(`concernementMapItem watch concernement o.active_revision:${o.active_revision}, n.active_revision:${n.active_revision}`);
  192. this.resetPaperActiveRevision();
  193. }
  194. },
  195. deep: true
  196. }
  197. },
  198. methods: {
  199. ...mapActions(CommonStore,['setHoverElmt']),
  200. ...mapActions(ConcernementsStore,['openCloseConcernements',
  201. // 'setConcernementMapItem',
  202. 'hideShowConcernement',
  203. 'setBesoinPaperId',
  204. 'setOpenedDoleanceField',
  205. 'setOpenedRecit']),
  206. // getResponsiveRay(){
  207. // return Math.min(this.canvas.width, this.canvas.height) * 0.08;
  208. // },
  209. parseEntityPointsValues (){
  210. // converts data (menace/maintien, actuel/future, prise) into atcual position x,y
  211. for (let r = 0; r < this.concernement.revisions.length; r++) { // loop through all revisions
  212. for (let i = 0; i < this.concernement.revisions[r].entites.length; i++) { // loop through all entite for each revision
  213. let entite = this.concernement.revisions[r].entites[i]
  214. // console.log('entite', entite);
  215. entite.display = {
  216. alpha: null,
  217. ray: null
  218. }
  219. // RAYON
  220. // https://stackoverflow.com/questions/5731863/mapping-a-numeric-range-onto-another
  221. // slope = (output_end - output_start) / (input_end - input_start)
  222. // output = output_start + slope * (input - input_start)
  223. // from range 0 -> 100 to range 0 -> this.ray
  224. let init_max = 100
  225. let slope = this.ray / init_max
  226. entite.display.ray = slope * (init_max - entite.prise);
  227. // if (this.concernement.id === 28) {
  228. // console.log(`entity prise: ${entite.prise} | ray: ${entite.display.ray}`);
  229. // }
  230. // ANGLE
  231. // -90 <= mm <= 90
  232. if (entite.actuelfuture) {
  233. // future en haut : 180 <= a <= 360
  234. // from -90 -> 90 to range 180 -> 360
  235. entite.display.alpha = entite.menacemaintien + 270
  236. } else {
  237. // actuel: en bas : O <= a <= 180
  238. // from -90 -> 90 to range 180 -> 0
  239. entite.display.alpha = -1 * entite.menacemaintien + 90
  240. }
  241. // POSITION X Y (par rapport au centre du concernement)
  242. entite.display.pos = {
  243. x: entite.display.ray * Math.cos(entite.display.alpha * (Math.PI/180)),
  244. y: entite.display.ray * Math.sin(entite.display.alpha * (Math.PI/180))
  245. }
  246. // if (entite.entite) {
  247. // this.entites_byid[entite.entite.id].display = entite.display;
  248. // }
  249. }
  250. }
  251. },
  252. getSalientPoints_OLD() {
  253. // debugger
  254. // console.log(this.entites);
  255. let arc = 360/30;
  256. // loop through arcs
  257. // for (let i = 360/arc; i >= 0 ; i--) {
  258. for (let i = 0; i <= 360/arc ; i++) {
  259. // loop through entities to find the farest on the arc
  260. let max_r = 0;
  261. let farest = null;
  262. for (let j = 0; j < this.entites.length; j++) {
  263. let entite = this.entites[j];
  264. if(arc*i <= entite.display.alpha && entite.display.alpha <= arc*i+arc) { // if entity is in arc
  265. if (entite.display.ray > max_r) { // && entite.display.ray > this.ray/2 // and farest from minimu
  266. // if entity is farest from precedent one
  267. max_r = entite.display.ray;
  268. // recalcul x & y to get a little padding between entite and contour by increasing ray
  269. farest = {
  270. alpha: entite.display.alpha,
  271. ray: entite.display.ray,
  272. pos: {
  273. x: (entite.display.ray + 3) * Math.cos(entite.display.alpha * (Math.PI/180)),
  274. y: (entite.display.ray + 3) * Math.sin(entite.display.alpha * (Math.PI/180))
  275. }
  276. };
  277. }
  278. }
  279. }
  280. if (farest) {
  281. this.salientPoints.push(farest)
  282. }
  283. }
  284. // console.log(`this.salientPoints ${this.concernement.id}`, this.salientPoints);
  285. },
  286. getJarvisEnvelopeConvexe(){
  287. this.salientPoints = [];
  288. let entites = this.concernement.revisions_byid[this.concernement.active_revision].entites;
  289. // console.log(`getJarvisEnvelopeConvexe ${this.id}`, this.entites.length);
  290. // https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/
  291. // find the most left point
  292. let l, min_x = null;
  293. for (let i = 0; i < entites.length; i++) {
  294. let entite = entites[i];
  295. let x = entite.display.ray * Math.cos(entite.display.alpha * (Math.PI/180));
  296. if(!min_x || min_x > x){
  297. l = i;
  298. min_x = x;
  299. }
  300. }
  301. // Start from leftmost point, keep moving clockwise
  302. // until reach the start point again. This loop runs O(h)
  303. // times where h is number of points in result or output.
  304. let p = l, q;
  305. do {
  306. // console.log(`do while ${this.id}`, p);
  307. // Add current point to result
  308. let entite = entites[p];
  309. let farest = {
  310. alpha: entite.display.alpha,
  311. ray: entite.display.ray,
  312. pos: {
  313. x: (entite.display.ray) * Math.cos(entite.display.alpha * (Math.PI/180)),
  314. y: (entite.display.ray) * Math.sin(entite.display.alpha * (Math.PI/180))
  315. }
  316. };
  317. this.salientPoints.push(farest);
  318. // Search for a point 'q' such that
  319. // orientation(p, q, x) is clockwise
  320. // for all points 'x'. The idea is to keep
  321. // track of last visited most clockwise
  322. // point in q. If any point 'i' is more
  323. // clockwise than q, then update q.
  324. q = (p + 1) % entites.length;
  325. for (let i = 0; i < entites.length; i++) {
  326. let p_x = (entites[p].display.ray) * Math.cos(entites[p].display.alpha * (Math.PI/180));
  327. let p_y = (entites[p].display.ray) * Math.sin(entites[p].display.alpha * (Math.PI/180));
  328. let i_x = (entites[i].display.ray) * Math.cos(entites[i].display.alpha * (Math.PI/180));
  329. let i_y = (entites[i].display.ray) * Math.sin(entites[i].display.alpha * (Math.PI/180));
  330. let q_x = (entites[q].display.ray) * Math.cos(entites[q].display.alpha * (Math.PI/180));
  331. let q_y = (entites[q].display.ray) * Math.sin(entites[q].display.alpha * (Math.PI/180));
  332. let val = (i_y - p_y) * (q_x - i_x) - (i_x - p_x) * (q_y - i_y);
  333. // If i is more clockwise than current q, then update q
  334. if (val > 0){
  335. q = i;
  336. }
  337. }
  338. // Now q is the most clockwise with
  339. // respect to p. Set p as q for next iteration,
  340. // so that q is added to result 'hull'
  341. p = q;
  342. } while (p != l);
  343. },
  344. getRandomPos(){
  345. let pad = 200;
  346. // if (this.concernement.id === 56) {
  347. // return {
  348. // x: Math.random() > 0.5 ? pad : this.canvas.width - pad,
  349. // y: pad + this.ray/2 + Math.random()*(this.canvas.height - this.ray - pad)
  350. // };
  351. // } else {
  352. return {
  353. x: pad + this.getGaussianRandom()*(this.canvas.width - pad*2),
  354. y: pad + this.getGaussianRandom()*(this.canvas.height - pad*2)
  355. };
  356. // }
  357. },
  358. getGaussianRandom(){
  359. // INFO https://stackoverflow.com/a/49434653
  360. let u = 0, v = 0;
  361. while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
  362. while(v === 0) v = Math.random();
  363. let num = Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
  364. num = num / 10.0 + 0.5; // Translate to 0 -> 1
  365. if (num > 1 || num < 0) return this.getGaussianRandom() // resample between 0 and 1
  366. return num
  367. },
  368. getSuperposedEntitesIDsList(){
  369. if (this.concernement.superpositions) {
  370. // loop through all concernement superpositions couples of this concernement
  371. for(let [couple_id, superpositions] of Object.entries(this.concernement.superpositions)){
  372. // loop through all superpositions of each couple
  373. for(let [superposition_id, superposition] of Object.entries(superpositions)){
  374. if (this.mapitem.superposition_ids.indexOf(superposition_id) >= 0) {
  375. switch (this.cid) { // get the right eid regarding the cid
  376. case superposition[0].cid:
  377. this.superposedEntitesIDsList.push(superposition[0].eid);
  378. break;
  379. case superposition[1].cid:
  380. this.superposedEntitesIDsList.push(superposition[1].eid);
  381. break;
  382. }
  383. }
  384. }
  385. }
  386. }
  387. // console.log('superposedEntitesIDsList', this.superposedEntitesIDsList);
  388. },
  389. // MATTER BODY
  390. initMatterBody (){
  391. // MATTER
  392. // create the matter body and add it to the engine
  393. if (!this.body) {
  394. // console.log('concernementItem creating body');
  395. // INFO https://github.com/liabru/matter-attractors/issues/8
  396. // INFO https://github.com/liabru/matter-attractors/blob/master/index.js
  397. // INFO https://github.com/liabru/matter-attractors/blob/master/build/matter-attractors.js#L180
  398. MatterAttractors.Attractors.gravityConstant = -20;
  399. // Create parts of the body : main big circle & entities
  400. // INFO map a range of numbers to another range of numbers https://stackoverflow.com/a/46462321
  401. let entite_range = [3, 100];
  402. let ray_range = [this.ray*0.8,this.ray*1.2];
  403. let ray = ray_range[0] + (this.entites.length - entite_range[0]) * (ray_range[1] - ray_range[0]) / (entite_range[1] - entite_range[0]);
  404. this.body_parts = [
  405. Matter.Bodies.circle(0, 0, ray, {
  406. // item_type: 'concernement',
  407. // id: this.concernement.id,
  408. })
  409. ];
  410. // INFO map a range of numbers to another range of numbers https://stackoverflow.com/a/46462321
  411. let mass_range = [5,15];
  412. let mass = mass_range[0] + (this.entites.length - entite_range[0]) * (mass_range[1] - mass_range[0]) / (entite_range[1] - entite_range[0]);
  413. // create the body
  414. this.body = Matter.Body.create({
  415. parts: this.body_parts,
  416. item_type: 'concernement',
  417. id: this.id,
  418. frictionAir: 0,
  419. // mass: Math.pow(3, this.entites.length),
  420. // mass: 10,
  421. mass: mass,
  422. restitution: 0.06,
  423. collisionFilter: {
  424. group: -1
  425. },
  426. plugin: {
  427. attractors: [
  428. // // there is a built in helper function for Newtonian gravity!
  429. // // you can find out how it works in index.js
  430. MatterAttractors.Attractors.gravity
  431. // function(bodyA, bodyB) {
  432. // var force = {
  433. // x: (bodyA.position.x - bodyB.position.x) * 1e-6,
  434. // y: (bodyA.position.y - bodyB.position.y) * 1e-6
  435. // }
  436. // // apply force to both bodies
  437. // Matter.Body.applyForce(bodyA, bodyA.position, force);
  438. // Matter.Body.applyForce(bodyB, bodyB.position, Matter.Vector.neg(force));
  439. // }
  440. // INFO https://github.com/liabru/matter-attractors/blob/master/build/matter-attractors.js#L192
  441. // function (bodyA, bodyB){
  442. // // use Newton's law of gravitation
  443. // var bToA = Matter.Vector.sub(bodyB.position, bodyA.position),
  444. // distanceSq = Matter.Vector.magnitudeSquared(bToA) || 0.0001,
  445. // normal = Matter.Vector.normalise(bToA),
  446. // magnitude = -MatterAttractors.Attractors.gravityConstant * (bodyA.mass * bodyB.mass / distanceSq),
  447. // force = Matter.Vector.mult(normal, magnitude);
  448. // // to apply forces to both bodies
  449. // Matter.Body.applyForce(bodyA, bodyA.position, Matter.Vector.neg(force));
  450. // Matter.Body.applyForce(bodyB, bodyB.position, force);
  451. // }
  452. ]
  453. }
  454. });
  455. Matter.Body.setPosition(this.body, this.pos);
  456. // add init velocity
  457. this.setInitBodyVelocity()
  458. // console.log('concernementItem mass', this.body.mass);
  459. Matter.Composite.add(this.matterEngine.world, this.body);
  460. // console.log('concernement body', this.body);
  461. // listen for afterUpdate event from Matter.Engine object
  462. Matter.Events.on(this.matterEngine, "beforeUpdate", this.onBeforeEngineUpdate);
  463. Matter.Events.on(this.matterEngine, "afterUpdate", this.onAfterEngineUpdate);
  464. }
  465. },
  466. setInitBodyVelocity(){
  467. let delta = 50;
  468. Matter.Body.setVelocity(this.body, {
  469. x: -delta + Math.random()*delta*2,
  470. y: -delta + Math.random()*delta*2
  471. });
  472. },
  473. // PAPER OBJECTS
  474. initPaperObjects(){
  475. // the main paper group containing all paper graphical items for one concernement
  476. this.paper_main_object = new paper.Group({
  477. pivot: new paper.Point(this.pos),
  478. name: `main_${this.id}`,
  479. cid: this.cid,
  480. superposition_id: this.mapitem.superposition_ids[0] // TODO what to do with multiples superpositions ids
  481. });
  482. // the sub items for one concernement
  483. this.paper_main_object.addChild(this.setPaperContour());
  484. if (this.concernement.has_superpositions) {
  485. this.paper_main_object.addChild(this.setPaperEntitesSuperposees());
  486. }
  487. if (this.concernement.has_puissancedagir) {
  488. this.addNewPaperSymbolInstance('puissanceagir_icon', false, 0.7);
  489. }
  490. if (this.concernement.has_agissantes) {
  491. this.paper_main_object.addChild(this.setPaperAgissantesIcons());
  492. }
  493. if (this.concernement.has_doleance) {
  494. this.addNewPaperSymbolInstance('doleance_icon', false, 0.7);
  495. }
  496. this.initPaperEvents()
  497. },
  498. setPaperContents(){
  499. // trigered once opening tween is complete
  500. this.clearPaperContents();
  501. switch(this.map_mode){
  502. case 'terraindevie':
  503. this.addNewPaperSymbolInstance('boussole_bg', true);
  504. this.paper_main_object.addChild(this.setPaperEntites());
  505. break;
  506. case 'superposition':
  507. this.addNewPaperSymbolInstance('boussole_bg', true);
  508. break;
  509. case 'puissancedagir':
  510. this.addNewPaperSymbolInstance('puissanceagir_bg', true);
  511. this.paper_main_object.addChild(this.setPaperPuissanceagirBesoins());
  512. break;
  513. case 'action':
  514. this.addNewPaperSymbolInstance('boussole_bg', true);
  515. this.paper_main_object.addChild(this.setPaperAgissantes());
  516. break;
  517. case 'doleancer':
  518. this.addNewPaperSymbolInstance('doleance_bg');
  519. this.paper_main_object.addChild(this.setPaperDoleances());
  520. break;
  521. }
  522. },
  523. resetPaperActiveRevision(){
  524. console.log('resetPaperActiveRevision');
  525. this.getJarvisEnvelopeConvexe();
  526. // remove contours if already exists
  527. if (this.paper_main_object.children.contours) {
  528. this.paper_main_object.children.contours.remove();
  529. }
  530. // redraw contours
  531. this.paper_main_object.addChild(this.setPaperContour());
  532. // remove entites if already exists
  533. if (this.paper_main_object.children.entites) {
  534. this.paper_main_object.children.entites.remove();
  535. }
  536. // redraw entites
  537. this.paper_main_object.addChild(this.setPaperEntites());
  538. },
  539. clearPaperContents(){
  540. let clearable_children = ['boussole_bg', 'entites',
  541. 'puissanceagir_bg','puissanceagir_besoins',
  542. 'agissantes',
  543. 'doleance_bg', 'doleances'];
  544. clearable_children.forEach(child_name => {
  545. if (this.paper_main_object.children[child_name]) {
  546. this.paper_main_object.children[child_name].remove();
  547. }
  548. });
  549. },
  550. addNewPaperSymbolInstance(name, back, scale){
  551. let instance = new paper.SymbolItem(this.paper_symbol_definitions[name]); // , {x:0,y:0}
  552. instance.name = name;
  553. // instance.pivot = new paper.Point({x:0,y:0});
  554. instance.position = this.pos;
  555. let s = scale ? this.scale * scale : this.scale;
  556. instance.scale(s);
  557. // instance.locked = true;
  558. this.paper_main_object.addChild(instance);
  559. if (back) {
  560. this.paper_main_object.children[name].sendToBack();
  561. } else {
  562. this.paper_main_object.children[name].bringToFront();
  563. }
  564. },
  565. setPaperContour(){
  566. // console.log(`setPaperContour ${this.concernement.id}`);
  567. let getPaddedRoundedSegments = (b,a,c,d) => {
  568. const ac = { x: c.x - a.x, y: c.y - a.y } // get ac vecteur
  569. const lac = Math.sqrt(Math.pow(ac.x, 2) + Math.pow(ac.y, 2)); // get ac longueur ac
  570. const ab = { x: b.x - a.x, y: b.y - a.y } // get ab vecteur
  571. const lab = Math.sqrt(Math.pow(ab.x, 2) + Math.pow(ab.y, 2)); // get ab longeur
  572. const vab = { x: ab.x/lab, y: ab.y/lab } // get unit vecteur ab
  573. const an = { x: vab.x*lac, y: vab.y*lac } // get an vecteur
  574. const n = { x: a.x + an.x, y: a.y+an.y } // get n point
  575. const m = { x: (c.x + n.x)/2, y: (c.y + n.y)/2 } // get nc midle point
  576. const ma = { x:a.x - m.x, y: a.y - m.y } // get ma vecteur
  577. const lma = Math.sqrt(Math.pow(ma.x, 2)+Math.pow(ma.y, 2)) // get longeur m->a
  578. const vma = { x: ma.x/lma, y: ma.y/lma } // get ma vecteur unitaire
  579. // console.log(`vma x:${vma.x}, y:${vma.y}`);
  580. const pad = 4; // exterior padding
  581. // the final padded point
  582. const pa = [
  583. this.pos.x+(a.x+vma.x*pad)*this.scale,
  584. this.pos.y+(a.y+vma.y*pad)*this.scale
  585. ]
  586. // handles
  587. const delta = 0.05;
  588. // handle IN
  589. const hli = Math.abs(lab)*delta; // handle longeur
  590. const vnai = { x: -vma.y, y: vma.x } // get the ma normal unit vector IN
  591. const hai = [ vnai.x*hli, vnai.y*hli ]; // get the handleIn point
  592. // handle OUT
  593. const hlo = Math.abs(lac)*delta; // handle longeur
  594. const vnao = { x: vma.y, y: -vma.x } // get the ma normal vector Out
  595. const hao = [ vnao.x*hlo, vnao.y*hlo ]; // get the handleOut point
  596. return new paper.Segment({
  597. point: pa,
  598. handleIn: hai,
  599. handleOut: hao
  600. })
  601. }
  602. const first_point = getPaddedRoundedSegments(
  603. this.salientPoints[this.salientPoints.length-1].pos,
  604. this.salientPoints[0].pos,
  605. this.salientPoints[1].pos
  606. );
  607. let segments = [first_point];
  608. for (let j = 1; j < this.salientPoints.length-1; j++) {
  609. // segments.push([this.pos.x+this.salientPoints[j].pos.x*this.scale*gap, this.pos.y+this.salientPoints[j].pos.y*this.scale*gap])
  610. segments.push(getPaddedRoundedSegments(
  611. this.salientPoints[j-1].pos,
  612. this.salientPoints[j].pos,
  613. this.salientPoints[j+1].pos
  614. ))
  615. }
  616. const last_point = getPaddedRoundedSegments(
  617. this.salientPoints[this.salientPoints.length-2].pos,
  618. this.salientPoints[this.salientPoints.length-1].pos,
  619. this.salientPoints[0].pos
  620. );
  621. segments.push(last_point)
  622. segments.push(first_point)
  623. const contrs = new paper.Path({
  624. name: 'contours',
  625. segments: segments,
  626. fillColor: 'rgba(255,255,255,0.4)',
  627. // selected: true,
  628. strokeColor: '#fff',
  629. strokeWidth: 1,
  630. pivot: new paper.Point(this.pos),
  631. cid: this.cid
  632. });
  633. return contrs;
  634. },
  635. setPaperEntites(){
  636. let g = new paper.Group({
  637. pivot: new paper.Point(this.pos),
  638. name: 'entites'
  639. });
  640. // for (let i = 0; i < this.entites.length; i++) {
  641. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.active_revision].entites.length; i++) {
  642. let entite = this.concernement.revisions_byid[this.concernement.active_revision].entites[i];
  643. // use paper symbol
  644. let symbol_name = entite.entite ? entite.entite.agissante ? 'entite_action' : 'entite' : 'entite_hidden';
  645. let instance = new paper.SymbolItem(this.paper_symbol_definitions[symbol_name]);
  646. instance.name = 'entite';
  647. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  648. instance.scale(this.scale);
  649. instance.fillColor = '#000';
  650. instance.item_id = entite.entite ? entite.entite.id : null;
  651. instance.item_type = symbol_name;
  652. instance.is_symbol_instance = true;
  653. g.addChild(instance)
  654. }
  655. return g;
  656. },
  657. setPaperEntitesSuperposees(){
  658. // console.log('setPaperSuperpositions, superpositions', this.concernement.superpositions);
  659. let g = new paper.Group({
  660. pivot: new paper.Point(this.pos),
  661. name: 'entites_superposes'
  662. });
  663. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.active_revision].entites.length; i++) {
  664. let entite = this.concernement.revisions_byid[this.concernement.active_revision].entites[i];
  665. if (entite.entite // check if we have an entite object with all the contents
  666. && this.superposedEntitesIDsList.indexOf(entite.entite.id) >= 0) // check if entite id is in the list builded above
  667. {
  668. // console.log(`entite ${entite.entite.id}`, entite, entite.entite.superposition);
  669. // use paper symbol
  670. let instance = new paper.SymbolItem(this.paper_symbol_definitions['entite']);
  671. instance.name = 'entite';
  672. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  673. // instance.scale(this.scale);
  674. instance.scale(3);
  675. instance.fillColor = '#000';
  676. instance.item_id = entite.entite.id;
  677. instance.item_type = 'entite_superpose';
  678. instance.is_symbol_instance = true;
  679. g.addChild(instance)
  680. }
  681. }
  682. return g;
  683. },
  684. setPaperAgissantes(){
  685. console.log('setPaperAgissantes');
  686. let g = new paper.Group({
  687. pivot: new paper.Point(this.pos),
  688. name: 'agissantes'
  689. });
  690. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.revision_id].entites.length; i++) {
  691. let entite = this.concernement.revisions_byid[this.concernement.revision_id].entites[i];
  692. console.log('agissantes', entite);
  693. if (entite.entite && entite.entite.agissante) {
  694. let instance = new paper.SymbolItem(this.paper_symbol_definitions['entite_action']);
  695. instance.name = 'entite_action';
  696. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  697. instance.fillColor = '#000';
  698. // instance.scale(0.2);
  699. instance.scale(this.scale);
  700. instance.item_id = entite.entite.id;
  701. instance.item_type = 'entite_action';
  702. instance.is_symbol_instance = true;
  703. g.addChild(instance)
  704. }
  705. }
  706. return g;
  707. },
  708. setPaperAgissantesIcons(){
  709. let g = new paper.Group({
  710. pivot: new paper.Point(this.pos),
  711. name: 'agissantes_icons'
  712. });
  713. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.revision_id].entites.length; i++) {
  714. let entite = this.concernement.revisions_byid[this.concernement.active_revision].entites[i];
  715. if (entite.entite && entite.entite.agissante) {
  716. let instance = new paper.SymbolItem(this.paper_symbol_definitions['entite_action_icon']);
  717. instance.name = 'entite_action';
  718. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  719. instance.fillColor = '#000';
  720. // instance.scale(0.2);
  721. instance.scale(this.scale);
  722. instance.item_id = entite.entite.id;
  723. instance.item_type = 'entite_action';
  724. instance.is_symbol_instance = true;
  725. g.addChild(instance)
  726. }
  727. }
  728. return g;
  729. },
  730. setPaperPuissanceagirBesoins(){
  731. let g = new paper.Group({
  732. pivot: new paper.Point(this.pos),
  733. name: 'puissanceagir_besoins'
  734. });
  735. let res_fields = ['qui','quoi','ou','avec'];
  736. let arc = (360 / 16); // unit arc
  737. let r = (this.ray * this.scale)/5; // unit ray
  738. let br = r - r/3; // besoin ray
  739. for (let i = 0; i < this.concernement.besoins.length; i++) {
  740. let start_a = arc * i; // angle depart (for reponses)
  741. let center_a = start_a + arc/2; // angle central
  742. let x = Math.cos(center_a*(Math.PI/180)) * br;
  743. let y = Math.sin(center_a*(Math.PI/180)) * br;
  744. // use paper symbol
  745. let besoin = new paper.SymbolItem(this.paper_symbol_definitions['besoin']);
  746. besoin.position = new paper.Point([this.pos.x + x, this.pos.y + y]);
  747. besoin.scale(this.scale);
  748. besoin.item_id = this.concernement.besoins[i].id;
  749. besoin.item_cid = this.concernement.id;
  750. besoin.item_type = 'besoin';
  751. besoin.is_symbol_instance = true;
  752. console.log(`paper besoin id:${besoin.id}`);
  753. this.setBesoinPaperId(besoin.id, this.cid, this.concernement.besoins[i].id);
  754. g.addChild(besoin)
  755. let res_arc = arc / (1 + this.concernement.besoins[i].reponses.length); // unit arc for responses depending responses number
  756. for (let j = 0; j < this.concernement.besoins[i].reponses.length; j++) {
  757. let res_a = start_a + res_arc * (j+1); // angle for response line
  758. for (let f = 0; f < res_fields.length; f++) { // loop through all 4 fields, keep only the last one filled
  759. if( this.concernement.besoins[i].reponses[j][res_fields[f]] // if field filled
  760. && (f === res_fields.length -1 || !this.concernement.besoins[i].reponses[j][res_fields[f+1]]) // and is last field or last field filled
  761. ){
  762. let rr = this.ray * this.scale - r*f - r/2; // reponse field ray
  763. let rx = Math.cos(res_a*(Math.PI/180)) * rr;
  764. let ry = Math.sin(res_a*(Math.PI/180)) * rr;
  765. // use paper symbol
  766. let reponse = new paper.SymbolItem(this.paper_symbol_definitions['reponse']);
  767. reponse.position = new paper.Point([this.pos.x + rx, this.pos.y + ry]);
  768. reponse.scale(this.scale);
  769. reponse.item_id = this.concernement.besoins[i].reponses[j].id;
  770. reponse.item_bid = this.concernement.besoins[i].id;
  771. reponse.item_cid = this.concernement.id;
  772. reponse.item_type = 'reponse';
  773. reponse.is_symbol_instance = true;
  774. this.setBesoinPaperId(reponse.id, this.cid, this.concernement.besoins[i].id, this.concernement.besoins[i].reponses[j].id);
  775. g.addChild(reponse)
  776. }
  777. }
  778. }
  779. }
  780. return g;
  781. },
  782. setPaperDoleances(){
  783. let g = new paper.Group({
  784. pivot: new paper.Point({x:0,y:0}),
  785. name: `doleances`
  786. });
  787. this.concernement.doleances.forEach((d) => {
  788. g.addChild(this.setPaperDoleanceSteps(d))
  789. });
  790. return g;
  791. },
  792. setPaperDoleanceSteps(doleance){
  793. let g = new paper.Group({
  794. pivot: new paper.Point({x:0,y:0}),
  795. name: `doleance_${doleance.id}`,
  796. doleance_id: doleance.id
  797. });
  798. // let doleance = this.concernement.doleances[0];
  799. let all_fields = [
  800. [
  801. 'leprobleme',
  802. 'lenquete',
  803. {
  804. fieldname: 'groupesinterets',
  805. fields: [
  806. 'groupe_interets',
  807. 'accorder_interets',
  808. 'formuler',
  809. ]
  810. }
  811. ],
  812. [
  813. 'entite_addresse_doleance',
  814. 'comment_ennonce_doleance',
  815. 'aqui_addresse_doleance',
  816. {
  817. fieldname: 'reception_traitement',
  818. fields: [
  819. 'entite_adressee',
  820. 'doleance_formulee',
  821. 'traite_doleance',
  822. 'entite_recoit_doleance',
  823. ]
  824. }
  825. ],
  826. [
  827. 'entites_decisionnaires',
  828. 'decision_formule',
  829. {
  830. fieldname: 'mise_en_oeuvre_decision',
  831. fields: [
  832. 'entite_adresse_decision',
  833. 'formule_decision',
  834. 'entite_metenoeuvre_decisio',
  835. ]
  836. }
  837. ],
  838. [
  839. 'entite_adresse_application',
  840. 'aqui_adresse_decision',
  841. 'comment_formule_decision',
  842. {
  843. fieldname: 'receptions_et_applications',
  844. fields: [
  845. 'applique_decision',
  846. 'formule_decision_applic',
  847. 'entite_recoit_decision',
  848. ]
  849. },
  850. 'probleme_initial_resolu',
  851. 'oui_nouvelle_situation',
  852. 'non_adresse_doleance',
  853. ]
  854. ];
  855. var r = this.ray * this.scale * 0.8; // ray
  856. var dr = r/2; // demi ray
  857. // var pcr = 2*this.scale; // petits cercle rayon
  858. // https://fr.wikipedia.org/wiki/Trigonom%C3%A9trie#/media/Fichier:Unit_circle_angles_color.svg
  859. // https://fr.wikipedia.org/wiki/Identit%C3%A9_trigonom%C3%A9trique_pythagoricienne#Preuve_utilisant_le_cercle_unit%C3%A9
  860. // radians = degrees * (pi/180)
  861. // degrees = radians * (180/pi)
  862. // Points for 45° axes
  863. let m = Math.sin(45*(Math.PI/180)) * r; // x = y for rayon
  864. let n = Math.sin(45*(Math.PI/180)) * r/2; // x = y for demi rayon
  865. let o = Math.cos(22.5*(Math.PI/180)) * r; // x @ 22.5° for rayon
  866. let p = Math.sin(22.5*(Math.PI/180)) * r; // y @ 22.5° for rayon
  867. let o_d = Math.cos(22.5*(Math.PI/180)) * r/2; // x @ 22.5° for demi rayon
  868. let p_d = Math.sin(22.5*(Math.PI/180)) * r/2; // y @ 22.5° for demi rayon
  869. // let fontsize = 4;
  870. //
  871. // CAMENBERT STATIQUES
  872. //
  873. // l'enquete
  874. //
  875. // camenbert
  876. let cam = new paper.Path({
  877. strokeColor: '#fff',
  878. strokeWidth: 2,
  879. fillColor: "rgba(255, 255, 255, 0.4)",
  880. item_type: 'doleance_step',
  881. item_id: `lenquete`,
  882. did: doleance.id,
  883. field: 'lenquete',
  884. field_index: null
  885. });
  886. cam.add({x: this.pos.x , y: this.pos.y + dr});
  887. cam.lineTo({x: this.pos.x, y: this.pos.y + r});
  888. cam.arcTo({x: this.pos.x - p, y: this.pos.y + o}, {x: this.pos.x - m, y: this.pos.y + m});
  889. cam.lineTo({x: this.pos.x - n, y: this.pos.y + n});
  890. cam.arcTo({x: this.pos.x - p_d, y: this.pos.y + o_d}, {x: this.pos.x , y: this.pos.y + dr});
  891. // texte
  892. // enquete.addChild(new paper.PointText({
  893. // point: {
  894. // x:this.pos.x + Math.sin(22.5*(Math.PI/180)) * r*0.75,
  895. // y:this.pos.y + Math.cos(22.5*(Math.PI/180)) * r*0.75
  896. // },
  897. // content: doleance['lenquete'],
  898. // fontSize: fontsize,
  899. // fillColor: '#fff',
  900. // justification: 'center',
  901. // locked: true
  902. // }));
  903. g.addChild(cam);
  904. //
  905. // probleme_initial_resolu
  906. //
  907. // camenbert
  908. let rescam = new paper.Path({
  909. strokeColor: '#fff',
  910. strokeWidth: 2,
  911. fillColor: "rgba(255, 255, 255, 0.4)",
  912. closed: true,
  913. item_type: 'doleance_step',
  914. item_id: `probleme_initial_resolu`,
  915. did: doleance.id,
  916. field: 'probleme_initial_resolu',
  917. field_index: null
  918. });
  919. rescam.add({x: this.pos.x + n, y: this.pos.y + n});
  920. rescam.lineTo({x: this.pos.x + m , y: this.pos.y + m});
  921. rescam.arcTo({x: this.pos.x + p, y: this.pos.y + o}, {x: this.pos.x, y: this.pos.y + r});
  922. rescam.lineTo({x: this.pos.x, y: this.pos.y + dr});
  923. rescam.arcTo({x: this.pos.x + p_d, y: this.pos.y + o_d}, {x: this.pos.x + n, y: this.pos.y + n});
  924. // texte
  925. // resolution.addChild(new paper.PointText({
  926. // point: {
  927. // x:this.pos.x - Math.sin(22.5*(Math.PI/180)) * r*0.75,
  928. // y:this.pos.y + Math.cos(22.5*(Math.PI/180)) * r*0.75
  929. // },
  930. // content: doleance['probleme_initial_resolu'] ? doleance['oui_nouvelle_situation'] : doleance['non_adresse_doleance'],
  931. // fontSize: fontsize,
  932. // fillColor: '#fff',
  933. // justification: 'center'
  934. // }));
  935. g.addChild(rescam)
  936. //
  937. // MULTIPLE FIELDS
  938. //
  939. let multiple_fields = [
  940. { field_name: 'groupesinterets', arc: 45, decalage: -45 },
  941. { field_name: 'reception_traitement', arc: 90, decalage: -90 },
  942. { field_name: 'mise_en_oeuvre_decision', arc: 90, decalage: -180 },
  943. { field_name: 'receptions_et_applications', arc: 45, decalage: 90 }
  944. ]
  945. multiple_fields.forEach((mf, j) => {
  946. for (let i = 0, l = doleance[mf.field_name].length, a = mf.arc/l; i < l; i++) {
  947. // let gi = new paper.Group({
  948. // item_type: 'doleance_step',
  949. // item_id: 'lenquete',
  950. // item_field: mf.field_name,
  951. // item_index: i
  952. // });
  953. //camenbert
  954. let x1= this.pos.x + Math.sin((mf.decalage- a*i)*(Math.PI/180)) * dr,
  955. y1= this.pos.y + Math.cos((mf.decalage- a*i)*(Math.PI/180)) * dr;
  956. let x2= this.pos.x + Math.sin((mf.decalage- a*i)*(Math.PI/180)) * r,
  957. y2= this.pos.y + Math.cos((mf.decalage- a*i)*(Math.PI/180)) * r;
  958. let x3= this.pos.x + Math.sin((mf.decalage- a*(i+1))*(Math.PI/180)) * r,
  959. y3= this.pos.y + Math.cos((mf.decalage- a*(i+1))*(Math.PI/180)) * r;
  960. let x3t= this.pos.x + Math.sin((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r,
  961. y3t= this.pos.y + Math.cos((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r;
  962. let x4= this.pos.x + Math.sin((mf.decalage- a*(i+1))*(Math.PI/180)) * dr,
  963. y4= this.pos.y + Math.cos((mf.decalage- a*(i+1))*(Math.PI/180)) * dr;
  964. let x4t= this.pos.x + Math.sin((mf.decalage- a*(i+0.5))*(Math.PI/180)) * dr,
  965. y4t= this.pos.y + Math.cos((mf.decalage- a*(i+0.5))*(Math.PI/180)) * dr;
  966. let x5= this.pos.x + Math.sin((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r*0.75,
  967. y5= this.pos.y + Math.cos((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r*0.75;
  968. let p = new paper.Path({
  969. strokeColor: '#fff',
  970. strokeWidth: 2,
  971. fillColor: "rgba(255, 255, 255, 0.4)",
  972. item_type: 'doleance_step',
  973. item_id: `${mf.field_name}-${i}`,
  974. did: doleance.id,
  975. field: mf.field_name,
  976. field_index: i
  977. });
  978. p.add([x1,y1]);
  979. p.lineTo([x2,y2]);
  980. p.arcTo([x3t,y3t], [x3,y3]);
  981. p.lineTo([x4,y4]);
  982. p.arcTo([x4t,y4t], [x1,y1]);
  983. g.addChild(p);
  984. // gi.addChild(p);
  985. // // text
  986. // gi.addChild(new paper.PointText({
  987. // point: {x:x5,y:y5},
  988. // content: `${j}-${i}`,
  989. // fontSize: fontsize,
  990. // fillColor: '#fff',
  991. // justification: 'center'
  992. // }))
  993. // g.addChild(gi)
  994. }
  995. });
  996. // POINTS CARDINAUX
  997. // leprobleme
  998. g.addChild(new paper.Path.Circle({
  999. center: [this.pos.x, this.pos.y + r],
  1000. radius: 3 * this.scale,
  1001. style: {
  1002. strokeColor: '#fff',
  1003. strokeWidth: 2,
  1004. fillColor: "rgba(255, 255, 255, 0.9)",
  1005. },
  1006. item_type: 'doleance_step',
  1007. item_id: `leprobleme`,
  1008. did: doleance.id,
  1009. field: 'leprobleme'
  1010. }));
  1011. // adresse de la doleance
  1012. g.addChild(new paper.Path.Circle({
  1013. center: [this.pos.x - r, this.pos.y],
  1014. radius: 3 * this.scale,
  1015. style: {
  1016. strokeColor: '#fff',
  1017. strokeWidth: 2,
  1018. fillColor: "rgba(255, 255, 255, 0.9)",
  1019. },
  1020. item_type: 'doleance_step',
  1021. item_id: `adresse_de_la_doleance`,
  1022. did: doleance.id,
  1023. field: 'adresse_de_la_doleance'
  1024. }));
  1025. // decision
  1026. g.addChild(new paper.Path.Circle({
  1027. center: [this.pos.x, this.pos.y - r],
  1028. radius: 3 * this.scale,
  1029. style: {
  1030. strokeColor: '#fff',
  1031. strokeWidth: 2,
  1032. fillColor: "rgba(255, 255, 255, 0.9)",
  1033. },
  1034. item_type: 'doleance_step',
  1035. item_id: `decision`,
  1036. did: doleance.id,
  1037. field: 'decision'
  1038. }));
  1039. // adresse_de_la_decision
  1040. g.addChild(new paper.Path.Circle({
  1041. center: [this.pos.x + r, this.pos.y],
  1042. radius: 3 * this.scale,
  1043. style: {
  1044. strokeColor: '#fff',
  1045. strokeWidth: 2,
  1046. fillColor: "rgba(255, 255, 255, 0.9)",
  1047. },
  1048. item_type: 'doleance_step',
  1049. item_id: `adresse_de_la_decision`,
  1050. did: doleance.id,
  1051. field: 'adresse_de_la_decision'
  1052. }));
  1053. return g;
  1054. },
  1055. // PAPER VISIBILITY
  1056. handlePaperVisibilityOnBeforeOpen(){
  1057. // agissantes
  1058. if (this.concernement.has_agissantes && this.map_mode === "action") {
  1059. if (!this.is_open) {
  1060. this.paper_main_object.children.agissantes_icons.visible = true;
  1061. } else {
  1062. this.paper_main_object.children.agissantes_icons.visible = false;
  1063. }
  1064. }
  1065. // superposition
  1066. // scale down superposed entites on open
  1067. let entites_superposes = this.paper_main_object.children['entites_superposes'];
  1068. // console.log('entites_superposes.children', entites_superposes.children);
  1069. if(entites_superposes){
  1070. for(let paper_item of entites_superposes.children) {
  1071. // paper_item.definition = this.paper_symbol_definitions.entite_hover;
  1072. paper_item.scale(0.25)
  1073. }
  1074. }
  1075. },
  1076. handlePaperVisibilityOnOpened(){},
  1077. handlePaperVisibilityOnBeforeClose(){
  1078. // superposition
  1079. // scale up superposed entites on open
  1080. let entites_superposes = this.paper_main_object.children['entites_superposes'];
  1081. // console.log('entites_superposes.children', entites_superposes.children);
  1082. if(entites_superposes){
  1083. for(let paper_item of entites_superposes.children) {
  1084. // paper_item.definition = this.paper_symbol_definitions.entite_hover;
  1085. paper_item.scale(4)
  1086. }
  1087. }
  1088. },
  1089. handlePaperVisibilityOnClosed(){
  1090. // agissantes
  1091. if (this.concernement.has_agissantes && this.map_mode === "action") {
  1092. if (!this.is_open) {
  1093. this.paper_main_object.children.agissantes_icons.visible = true;
  1094. } else {
  1095. this.paper_main_object.children.agissantes_icons.visible = false;
  1096. }
  1097. }
  1098. },
  1099. handlePaperVisibilityOnMapMode(){},
  1100. handlePaperVisibilityOnAfterEnginUpdate(){
  1101. // contours focused
  1102. if (!this.isFocused()){
  1103. this.paper_main_object.children['contours'].fillColor = "rgba(255,255,255,0.1)"; //this.mapitem.clone ? "rgba(255,0,0,0.1)" : "rgba(255,255,255,0.1)";
  1104. }else{
  1105. this.paper_main_object.children['contours'].fillColor = "rgba(255,255,255,0.4)"; //this.mapitem.clone ? "rgba(255,0,0,0.4)" : "rgba(255,255,255,0.4)";
  1106. if (this.is_hover) {
  1107. this.paper_main_object.children['contours'].strokeColor = "#01ffe2";
  1108. this.paper_main_object.children['contours'].strokeWidth = 2;
  1109. }else{
  1110. this.paper_main_object.children['contours'].strokeColor = "#fff";
  1111. this.paper_main_object.children['contours'].strokeWidth = 1;
  1112. }
  1113. }
  1114. // contours visibility
  1115. if (!this.is_open
  1116. || (this.is_open && this.map_mode !== "puissancedagir" && this.map_mode !== "doleancer")) {
  1117. this.paper_main_object.children['contours'].visible = true;
  1118. } else {
  1119. this.paper_main_object.children['contours'].visible = false;
  1120. }
  1121. // proximite
  1122. // superposition
  1123. if (this.concernement.has_superpositions) {
  1124. if (this.map_mode === "superposition") {
  1125. this.paper_main_object.children.entites_superposes.visible = true;
  1126. // highlight of entite part of opened superposition
  1127. let group = this.paper_main_object.children['entites_superposes'];
  1128. if(group){
  1129. if (this.$route.query.superposition_id) {
  1130. let superposition_id = this.$route.query.superposition_id;
  1131. if(superposition_id){
  1132. let ids = superposition_id.match(/(\d+)_(\d+)__(\d+)_(\d+)/i)
  1133. group.children.forEach((item) => {
  1134. if ( (this.cid === parseInt(ids[1]) && item.item_id === parseInt(ids[2]))
  1135. || (this.cid === parseInt(ids[3]) && item.item_id === parseInt(ids[4])) ) {
  1136. item.definition = this.paper_symbol_definitions.entite_hover;
  1137. if(!item.focused){
  1138. item.scale(2)
  1139. item.focused = true;
  1140. }
  1141. } else if(!this.is_hover) {
  1142. item.definition = this.paper_symbol_definitions.entite;
  1143. if (item.focused) {
  1144. item.scale(0.5)
  1145. item.focused = false;
  1146. }
  1147. }
  1148. })
  1149. }
  1150. }else{
  1151. group.children.forEach((item) => {
  1152. if(!this.is_hover) {
  1153. item.definition = this.paper_symbol_definitions.entite;
  1154. if (item.focused) {
  1155. item.scale(0.5)
  1156. item.focused = false;
  1157. }
  1158. }
  1159. })
  1160. }
  1161. }
  1162. } else {
  1163. this.paper_main_object.children.entites_superposes.visible = false;
  1164. }
  1165. }
  1166. // puissance d'agir
  1167. if (this.concernement.has_puissancedagir) {
  1168. if (this.map_mode === "puissancedagir") {
  1169. if (!this.is_open) {
  1170. this.paper_main_object.children.puissanceagir_icon.visible = true; // if not opened and has_puissancedagir draw the puissance d'agir icone
  1171. } else {
  1172. this.paper_main_object.children.puissanceagir_icon.visible = false;
  1173. }
  1174. } else {
  1175. this.paper_main_object.children.puissanceagir_icon.visible = false;
  1176. }
  1177. }
  1178. // agissantes
  1179. if (this.concernement.has_agissantes) {
  1180. if (this.map_mode !== "action") {
  1181. this.paper_main_object.children.agissantes_icons.visible = false;
  1182. } else if(!this.is_open && !this.is_closing){
  1183. this.paper_main_object.children.agissantes_icons.visible = true;
  1184. }
  1185. }
  1186. // doleance
  1187. if (this.concernement.has_doleance) {
  1188. if (this.map_mode === "doleancer") {
  1189. if (!this.is_open) {
  1190. this.paper_main_object.children.doleance_icon.visible = true;
  1191. } else {
  1192. this.paper_main_object.children.doleance_icon.visible = false;
  1193. // display the right (opened) doleance
  1194. this.concernement.doleances.forEach((d) => {
  1195. this.paper_main_object.children.doleances.children[`doleance_${d.id}`].visible = d.id === this.concernement.opened_doleance.id;
  1196. })
  1197. }
  1198. } else {
  1199. this.paper_main_object.children.doleance_icon.visible = false;
  1200. }
  1201. }
  1202. // focus on opened entite
  1203. if (this.is_open && this.opened_entite_id && (this.map_mode === 'terraindevie' || this.map_mode === 'action')) {
  1204. let group = this.map_mode === 'terraindevie' ? this.paper_main_object.children['entites'] : this.paper_main_object.children['agissantes'];
  1205. if(group){
  1206. group.children.forEach((item) => {
  1207. if (item.item_id === this.opened_entite_id) {
  1208. item.definition = item.item_type === 'entite' ? this.paper_symbol_definitions.entite_hover : this.paper_symbol_definitions.entite_action_hover;
  1209. } else {
  1210. if (!this.hover_elmt || item.item_id !== this.hover_elmt.id) {
  1211. item.definition = item.item_type === 'entite' ? this.paper_symbol_definitions.entite : this.paper_symbol_definitions.entite_action;
  1212. }
  1213. }
  1214. })
  1215. }
  1216. }
  1217. },
  1218. onIsHover(){
  1219. // handle layer z-index
  1220. if (this.is_hover) {
  1221. this.paper_main_object.bringToFront();
  1222. } else {
  1223. // mapitem can be hover while an other mapitem is open if it is superposed (superposition) to the currently opened mapitem
  1224. // in this case don't send it back
  1225. if (!this.opened_concernement) {
  1226. this.paper_main_object.sendToBack();
  1227. }
  1228. }
  1229. // hightlight superposed entites on focus
  1230. let entites_superposes = this.paper_main_object.children['entites_superposes'];
  1231. // console.log('entites_superposes.children', entites_superposes.children);
  1232. if(entites_superposes){
  1233. for(let paper_item of entites_superposes.children) {
  1234. if (this.is_hover) {
  1235. paper_item.definition = this.paper_symbol_definitions.entite_hover;
  1236. // paper_item.scale(2)
  1237. } else {
  1238. paper_item.definition = this.paper_symbol_definitions.entite;
  1239. // paper_item.scale(0.5)
  1240. }
  1241. }
  1242. }
  1243. },
  1244. // PAPER EVENTS
  1245. initPaperEvents(){
  1246. this.paper_main_object.onMouseLeave = function(event){
  1247. if (!this.opened_concernement && this.isFocused()) { // only if no concernement is opened
  1248. this.resetHoverElmt();
  1249. document.body.style.cursor = "auto";
  1250. }
  1251. }.bind(this);
  1252. this.paper_main_object.onMouseMove = function(event){
  1253. console.log(`onmousemove ${this.id}`, this.cartouch_is_opened);
  1254. // prevent hover map item mouse event if cartouch is opened
  1255. if (this.cartouch_is_opened && this.map_mode !== "superposition") return;
  1256. if (!this.is_open) {
  1257. if (!this.opened_concernement) { // only if no concernement is opened and is this focused
  1258. if(this.isFocused()){
  1259. if (this.map_mode === 'superposition') {
  1260. // get the superposed entite
  1261. this.setHoverElmt({
  1262. type: 'superposition',
  1263. id: this.id,
  1264. cid: this.cid,
  1265. eids: this.superposedEntitesIDsList
  1266. });
  1267. } else{
  1268. this.setHoverElmt({
  1269. type: 'concernement',
  1270. id: this.id,
  1271. cid: this.cid
  1272. });
  1273. }
  1274. document.body.style.cursor = "pointer";
  1275. }
  1276. } else if (this.map_mode === 'superposition'){
  1277. // if this mapitem is superposed to the opened mapitem
  1278. if(this.opened_concernement.all_superposed_concernements_id.indexOf(this.cid) >= 0){
  1279. this.setHoverElmt({
  1280. type: 'superposition',
  1281. id: this.id,
  1282. cid: this.cid,
  1283. eids: this.superposedEntitesIDsList
  1284. });
  1285. document.body.style.cursor = "pointer";
  1286. }
  1287. }
  1288. } else {
  1289. // lets define some options regarding the map_mode
  1290. let paper_group_tohit;
  1291. switch (this.map_mode) {
  1292. case "terraindevie":
  1293. paper_group_tohit = this.paper_main_object.children['entites'];
  1294. break;
  1295. case "superposition":
  1296. paper_group_tohit = this.paper_main_object.children['entites_superposes'];
  1297. break;
  1298. case "action":
  1299. paper_group_tohit = this.paper_main_object.children['agissantes'];
  1300. break;
  1301. case "puissancedagir":
  1302. paper_group_tohit = this.paper_main_object.children['puissanceagir_besoins'];
  1303. break;
  1304. case "doleancer":
  1305. if(this.paper_main_object.children['doleances']){
  1306. paper_group_tohit = this.paper_main_object.children['doleances'].children[`doleance_${this.concernement.opened_doleance.id}`];
  1307. }
  1308. break;
  1309. }
  1310. let result = paper_group_tohit ? paper_group_tohit.hitTest(event.point) : null;
  1311. // console.log('move result', result);
  1312. if (result && result.item.item_id) {
  1313. // console.log('move has result', result);
  1314. let new_hover_elmt = {
  1315. paper_id: result.item.id,
  1316. type: result.item.item_type,
  1317. id: result.item.item_id
  1318. };
  1319. switch (result.item.item_type) {
  1320. case "besoin":
  1321. new_hover_elmt.no_popup = true;
  1322. break;
  1323. case "reponse":
  1324. new_hover_elmt.bid = result.item.item_bid;
  1325. new_hover_elmt.cid = result.item.item_cid;
  1326. new_hover_elmt.no_popup = true;
  1327. break;
  1328. }
  1329. if (!this.hover_elmt || new_hover_elmt.paper_id !== this.hover_elmt.paper_id) {
  1330. // console.log(`before setHoverElmt ${this.id}`);
  1331. this.setHoverElmt(new_hover_elmt);
  1332. }
  1333. document.body.style.cursor = "pointer";
  1334. } else {
  1335. // console.log('move no result');
  1336. this.resetHoverElmt();
  1337. document.body.style.cursor = "auto";
  1338. }
  1339. }
  1340. }.bind(this);
  1341. this.paper_main_object.onClick = async function(event){
  1342. console.log('paper concernement onClick');
  1343. // prevent hover map item mouse event if cartouch is opened
  1344. if (this.cartouch_is_opened) return;
  1345. if (!this.is_open) { // si ce concernement n'est pas ouvet
  1346. console.log('mapitem is NOT opened');
  1347. if (!this.opened_concernement) { // si aucun concernement n'est ouvert
  1348. console.log(`Open me ${this.id}`);
  1349. // push route (keep the hash for map_mode)
  1350. // wait for routing to be finished before opening the mapItem
  1351. await this.$router.push({
  1352. name: 'concernement',
  1353. params: {cid: parseInt(this.cid)},
  1354. query: {
  1355. mapitemid: this.id,
  1356. superposition_id: this.mapitem.superposition_ids[0]
  1357. },
  1358. hash: `#${this.map_mode}`
  1359. });
  1360. // open/close all concernements
  1361. this.openCloseConcernements(this.cid, this.id)
  1362. // reset the mousehover
  1363. this.resetHoverElmt();
  1364. } else if (this.map_mode === 'superposition'){
  1365. // if this mapitem is superposed to the opened mapitem
  1366. if(this.opened_concernement.all_superposed_concernements_id.indexOf(this.cid) >= 0){
  1367. // push route (keep the hash for map_mode)
  1368. // wait for routing to be finished before opening the mapItem
  1369. console.log('click on superposed this.mapitem.superposition_ids', this.mapitem.superposition_ids);
  1370. await this.$router.push({
  1371. name: 'concernement',
  1372. params: {cid: this.opened_concernement.cid},
  1373. query: {
  1374. mapitemid: this.opened_concernement.opened_mapitem_id,
  1375. superposition_id: this.mapitem.superposition_ids[0]
  1376. },
  1377. hash: `#${this.map_mode}`
  1378. });
  1379. }
  1380. }
  1381. } else { // si ce concernement est ouvert
  1382. console.log('mapitem is opened');
  1383. // lets define some options regarding the map_mode
  1384. let group_to_hit = null;
  1385. switch (this.map_mode) {
  1386. case "terraindevie":
  1387. group_to_hit = this.paper_main_object.children['entites'];
  1388. break;
  1389. case "superposition":
  1390. group_to_hit = this.paper_main_object.children['entites_superposes'];
  1391. break;
  1392. case "action":
  1393. group_to_hit = this.paper_main_object.children['agissantes'];
  1394. break;
  1395. case "doleancer":
  1396. group_to_hit = this.paper_main_object.children['doleances'].children[`doleance_${this.concernement.opened_doleance.id}`];
  1397. break;
  1398. }
  1399. if (group_to_hit) {
  1400. let result = group_to_hit.hitTest(event.point);
  1401. console.log('click result', result);
  1402. if (result) {
  1403. switch (this.map_mode) {
  1404. case "terraindevie":
  1405. case "superposition":
  1406. case "action":
  1407. // we have clicked on an entite
  1408. this.$router.push({
  1409. name: 'concernement',
  1410. params: {cid: this.cid, eid: result.item.item_id},
  1411. query: {
  1412. mapitemid: this.id,
  1413. superposition_id: this.mapitem.superposition_ids[0]
  1414. },
  1415. hash: `#${this.map_mode}`,
  1416. });
  1417. break;
  1418. case "doleancer":
  1419. this.setOpenedDoleanceField(this.cid, result.item.did, result.item.field, result.item.field_index);
  1420. break;
  1421. }
  1422. } else {
  1423. // otherwise we close the entite and come back to the concernement
  1424. this.$router.push({
  1425. name: 'concernement',
  1426. hash: `#${this.map_mode}`,
  1427. params: {id: this.cid, mapitemid: this.id}
  1428. });
  1429. // reset the mousehover
  1430. this.resetHoverElmt();
  1431. }
  1432. }
  1433. }
  1434. }.bind(this);
  1435. },
  1436. resetHoverElmt(){
  1437. // console.log('resetHoverElmt');
  1438. setTimeout(()=>{
  1439. this.setHoverElmt(null);
  1440. }, 100);
  1441. },
  1442. // OPEN / CLOSE (with tween)
  1443. openClose(open) { // async
  1444. // await nextTick(); // not working
  1445. console.log(`ConcernementsMapItem ${this.id} openClose: ${open}`);
  1446. if (this.tween) {
  1447. this.tween.stop();
  1448. }
  1449. if (open) {
  1450. this.is_opening = true;
  1451. // create the paper objects to display (like entite, besoin, etc)
  1452. this.setPaperContents();
  1453. this.handlePaperVisibilityOnBeforeOpen();
  1454. // calcul opened size regarding window size and surounding contents
  1455. let header = document.querySelector('header#header');
  1456. let header_height = header.clientHeight;
  1457. let map_nav = document.querySelector('nav#map-nav');
  1458. let map_nav_height = map_nav.clientHeight;
  1459. let s_h = (this.canvas.height - header_height - map_nav_height) / (this.ray*2*1.15);
  1460. let s_w = (this.canvas.width - this.cartouch_width) / (this.ray*2*1.7);
  1461. let s = Math.min(s_h, s_w)
  1462. // create once the opening tweening
  1463. this.tween = new Tween.Tween({s: this.scale, x: this.pos.x, y: this.pos.y, o: 0})
  1464. .to({
  1465. s: s,
  1466. x: (this.canvas.width - this.cartouch_width) / 2,
  1467. y: this.canvas.height / 2,
  1468. o: 0.8
  1469. }, 800)
  1470. .onUpdate((obj) => {
  1471. // https://github.com/liabru/matter-js/issues/986#issuecomment-812488873
  1472. // revert to the original size (by reverting the previous scale)
  1473. Matter.Body.scale(this.body, 1 / this.scale, 1 / this.scale)
  1474. this.paper_main_object.scale(1 / this.scale);
  1475. // then scale again to new scale
  1476. Matter.Body.scale(this.body, obj.s, obj.s)
  1477. this.paper_main_object.scale(obj.s);
  1478. // update superposition constraints points poisitions
  1479. if (this.concernement.superposition_constraints_id
  1480. && this.concernement.superposition_constraints_id[this.id]
  1481. && this.concernement.superposition_constraints_id[this.id].length)
  1482. {
  1483. // get all the constraints of the world
  1484. let all_constrains = Matter.Composite.allConstraints(this.matterEngine.world);
  1485. // loop through all constraint ids recorded in the concernement
  1486. // get only the constraint of this concernement mapitem
  1487. for(let constraint_id of this.concernement.superposition_constraints_id[this.id]) {
  1488. // get the right constraint object from matter
  1489. let constraint;
  1490. for (const c of all_constrains) {
  1491. if (c.id === constraint_id) {
  1492. constraint = c;
  1493. break;
  1494. }
  1495. }
  1496. if (constraint) {
  1497. // tween the constraint point
  1498. let ab = this.cid === constraint.concernementA.id ? 'A' : 'B';
  1499. let point = constraint[`point${ab}`];
  1500. // revert to the original point
  1501. let oripoint = Matter.Vector.create(point.x / this.scale, point.y / this.scale)
  1502. // newpoint from original point
  1503. let newpoint = Matter.Vector.create(oripoint.x * obj.s, oripoint.y * obj.s)
  1504. constraint[`point${ab}`] = newpoint;
  1505. }
  1506. }
  1507. }
  1508. // record new scale
  1509. this.prev_scale = this.scale;
  1510. this.scale = obj.s;
  1511. this.opacity = obj.o;
  1512. // console.log('tween update obj.s', obj.s);
  1513. this.pos = {x:obj.x, y:obj.y};
  1514. Matter.Body.setPosition(this.body, this.pos);
  1515. })
  1516. .onComplete((obj) => {
  1517. // console.log('tween complete obj.s', obj.s);
  1518. // record tween one last time
  1519. this.prev_scale = this.scale = obj.s;
  1520. this.opacity = obj.o;
  1521. this.pos = {x:obj.x, y:obj.y};
  1522. Matter.Body.setPosition(this.body, this.pos);
  1523. this.handlePaperVisibilityOnOpened();
  1524. // fix the concernement position with a constraint
  1525. this.constraint = Matter.Constraint.create({
  1526. pointA: this.pos,
  1527. bodyB: this.body,
  1528. stiffness: 1,
  1529. damping: 0,
  1530. length: 0
  1531. });
  1532. Matter.Composite.add(this.matterEngine.world, [this.body, this.constraint]);
  1533. // paper bring to front
  1534. // this.paper_main_object.bringToFront();
  1535. this.paper_main_object.sendToBack();
  1536. this.is_opening = false;
  1537. });
  1538. // recreate the matter engine event to get it a the end of the events stack
  1539. Matter.Events.off(this.matterEngine, "afterUpdate", this.onAfterEngineUpdate);
  1540. Matter.Events.on(this.matterEngine, "afterUpdate", this.onAfterEngineUpdate);
  1541. } else {
  1542. // closing
  1543. this.is_closing = true;
  1544. if(this.constraint){
  1545. Matter.Composite.remove(this.matterEngine.world, this.constraint);
  1546. }
  1547. this.concernement.active_revision = this.concernement.revision_id;
  1548. this.handlePaperVisibilityOnBeforeClose();
  1549. // this.setOpenedRecit(null);
  1550. // create once the closing tween
  1551. this.tween = new Tween.Tween({s: this.scale, o: 1})
  1552. .to({s: 1, o: 0}, 500)
  1553. .onUpdate((obj) => {
  1554. // https://github.com/liabru/matter-js/issues/986#issuecomment-812488873
  1555. // revert to the original size (by reverting the previous scale)
  1556. Matter.Body.scale(this.body, 1 / this.scale, 1 / this.scale)
  1557. this.paper_main_object.scale(1 / this.scale);
  1558. // then scale again to new scale
  1559. Matter.Body.scale(this.body, obj.s, obj.s)
  1560. this.paper_main_object.scale(obj.s);
  1561. // update superposition constraints points positions
  1562. if (this.concernement.superposition_constraints_id
  1563. && this.concernement.superposition_constraints_id[this.id]
  1564. && this.concernement.superposition_constraints_id[this.id].length)
  1565. {
  1566. // get all the constraints of the world
  1567. let all_constrains = Matter.Composite.allConstraints(this.matterEngine.world);
  1568. // loop through all constraint ids recorded in the concernement
  1569. // get only the constraint of this concernement mapitem
  1570. for(let constraint_id of this.concernement.superposition_constraints_id[this.id]) {
  1571. // get the right constraint object from matter
  1572. let constraint;
  1573. for (const c of all_constrains) {
  1574. if (c.id === constraint_id) {
  1575. constraint = c;
  1576. break;
  1577. }
  1578. }
  1579. if (constraint) {
  1580. // tween the constraint point
  1581. let ab = this.cid === constraint.concernementA.id ? 'A' : 'B';
  1582. let point = constraint[`point${ab}`];
  1583. // revert to the original point
  1584. let oripoint = Matter.Vector.create(point.x / this.scale, point.y / this.scale)
  1585. // newpoint from original point
  1586. let newpoint = Matter.Vector.create(oripoint.x * obj.s, oripoint.y * obj.s)
  1587. constraint[`point${ab}`] = newpoint;
  1588. }
  1589. }
  1590. }
  1591. // record new scale
  1592. this.prev_scale = this.scale;
  1593. this.scale = obj.s;
  1594. this.opacity = obj.o;
  1595. })
  1596. .onComplete((obj) => {
  1597. this.prev_scale = this.scale = 1;
  1598. this.handlePaperVisibilityOnClosed();
  1599. this.clearPaperContents();
  1600. this.is_closing = false;
  1601. });
  1602. }
  1603. this.tween.easing(Tween.Easing.Quadratic.InOut).start();
  1604. },
  1605. // ENGINE UPDATE
  1606. onBeforeEngineUpdate (event) {
  1607. // update the opening/closing tweening
  1608. if (this.tween) {
  1609. this.tween.update();
  1610. }
  1611. if (this.opened_concernement) {
  1612. // console.log("try to push aside", this.opened_concernement.opened_mapitem_id, this.id, this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id]);
  1613. // console.log(this.id, this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id].indexOf(this.id));
  1614. if (this.opened_concernement.opened_mapitem_id !== this.id) {
  1615. // push all aside mapitems not superposed the the opened mapitem
  1616. let pushaside = true;
  1617. // BUT NOT push aside mapitems superposed to superposed mapitems
  1618. // opened_mapitem <-- superposed_mapitems <-- superposed_mapitem
  1619. if (this.opened_concernement.superposed_mapitem_id_by_mapitem_id
  1620. && this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id])
  1621. { // if opened mapitem has superposed mapitems
  1622. let superposed_ids = this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id]
  1623. if (superposed_ids.indexOf(this.id) >= 0) { //this mapitem is directly superposed to the opened mapitem
  1624. pushaside = false;
  1625. } else { // else we look for second stage of the rockette ... superposed to superposed to opened
  1626. superposed_ids.forEach(mapitem_id => { // for each superposed map_item, check if this mapitem is in their superposed
  1627. let mapitem = this.allMapItems_byid[mapitem_id]; // get the superposed (stage 1) mapitem
  1628. mapitem.superposition_ids.forEach(sup_id => { // for each superposed (stage 2) of the superposed (stage 1)
  1629. if (this.mapitem.superposition_ids.indexOf(sup_id) >= 0) {
  1630. pushaside = false;
  1631. }
  1632. });
  1633. });
  1634. }
  1635. }
  1636. if (pushaside) {
  1637. this.pushAside()
  1638. }
  1639. }
  1640. } else if (!this.is_hover){
  1641. if (this.map_mode === 'proximite'
  1642. || this.map_mode === 'superposition'
  1643. || this.map_mode === 'puissancedagir'
  1644. || this.map_mode === 'action'
  1645. || this.map_mode === 'doleancer'){ // apply focus forces : move unfocused on the sides and focused on the center
  1646. this.applyFocusForces(); //
  1647. } else {
  1648. this.applyNormalForces(); // if terrain de vie apply force to gently reject items from the sides and so create a continuasly mvmt
  1649. }
  1650. } else {
  1651. // stop movement if is mouse hover
  1652. Matter.Body.setVelocity(this.body, {x:0, y:0})
  1653. }
  1654. // reset all matter rotation forces otherwise items will spin when colide
  1655. Matter.Body.setAngle(this.body, 0);
  1656. Matter.Body.setAngularSpeed(this.body, 0);
  1657. },
  1658. applyFocusForces(){
  1659. if(!this.isFocused()) {
  1660. this.pushAside()
  1661. }else{
  1662. this.bringToCenter()
  1663. }
  1664. },
  1665. isFocused(){
  1666. return this.map_mode === 'terraindevie'
  1667. || (this.map_mode === 'proximite' && this.concernement.has_proximites)
  1668. || (this.map_mode === 'superposition' && this.concernement.has_superpositions)
  1669. || (this.map_mode === 'action' && this.concernement.has_agissantes)
  1670. || (this.map_mode === 'puissancedagir' && this.concernement.has_puissancedagir)
  1671. || (this.map_mode === 'doleancer' && this.concernement.has_doleance);
  1672. },
  1673. pushAside(){
  1674. // console.log('pushAside');
  1675. // apply a force in direction of one side or an other depending of the start position
  1676. // the force is exponentialy proportional to the distance from the side
  1677. // INFO logarithmic force : https://stackoverflow.com/questions/846221/logarithmic-slider/846249#846249
  1678. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1679. let pseudo_center_x = this.opened_concernement
  1680. ? (this.canvas.width - this.cartouch_width) / 2
  1681. : this.canvas.width / 2;
  1682. // get the direction to the closest side
  1683. let dir = this.map_mode === 'superposition'
  1684. && this.concernement.superposition_constraints_id
  1685. && this.concernement.superposition_constraints_id[this.id]
  1686. && this.concernement.superposition_constraints_id[this.id].length // go to the right if has superposition constraint applied
  1687. ? 1 // to the right
  1688. : this.pos.x > pseudo_center_x // else
  1689. ? 1 // to the right
  1690. : -1; // to the left
  1691. // max and min item position
  1692. let minp = 0;
  1693. let maxp = dir < 0
  1694. ? pseudo_center_x
  1695. : this.canvas.width - pseudo_center_x;
  1696. // max and min force
  1697. let minf = 0;
  1698. let maxf = 6;
  1699. // scale factor
  1700. let scale = (maxf-minf) / (maxp-minp);
  1701. // get the inversed distance
  1702. let dist = dir < 0
  1703. ? this.pos.x
  1704. : this.canvas.width - this.pos.x; // get the distance from the side
  1705. // // calculate the force
  1706. // let x_force = Math.pow(dist/700,100) * dir;
  1707. // calculate the logarithmic force
  1708. let x_force = Math.exp(minf + scale*(dist-minp)) * dir;
  1709. let ori_pos = {x:pseudo_center_x, y:this.body.position.y};
  1710. Matter.Body.applyForce(
  1711. this.body,
  1712. ori_pos,
  1713. {
  1714. x: x_force,
  1715. y: 0
  1716. }
  1717. );
  1718. this.body.frictionAir = 0.01;
  1719. },
  1720. bringToCenter(){
  1721. // bring to the centre
  1722. // apply a force in direction of one side or an other depending of the start position
  1723. // the force is exponentialy inversed proportional to the distance from the side
  1724. // INFO logarithmic force : https://stackoverflow.com/questions/846221/logarithmic-slider/846249#846249
  1725. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1726. let pseudo_center_x = this.opened_concernement
  1727. ? (this.canvas.width - this.cartouch_width) / 2
  1728. : this.canvas.width / 2;
  1729. let dir = this.pos.x > pseudo_center_x
  1730. ? -1 // to left
  1731. : 1; // to right
  1732. // get the inversed distance from the side
  1733. let dist = dir < 0
  1734. ? this.pos.x - pseudo_center_x
  1735. : pseudo_center_x - this.pos.x;
  1736. if (dist > this.canvas.width/6) { // apply decreasing forces and increasing friction air only out of center to let the items float in the center zone
  1737. // max & min item position
  1738. let minp = 0;
  1739. let maxp = dir < 0
  1740. ? this.canvas.width - pseudo_center_x
  1741. : pseudo_center_x;
  1742. // X force decrsinsing near the center
  1743. // max and min force
  1744. let xminf = 0;
  1745. let xmaxf = 1 + Math.random()*4;
  1746. // scale factor
  1747. let xscale = (xmaxf-xminf) / (maxp-minp);
  1748. let x_force = Math.exp(xminf + xscale*(dist-minp)) * dir;
  1749. let ori_pos = dir < 0
  1750. ? {x:this.canvas.width, y:this.body.position.y}
  1751. : {x:0, y:this.body.position.y};
  1752. Matter.Body.applyForce(
  1753. this.body,
  1754. ori_pos,
  1755. {
  1756. x: x_force,
  1757. y: 0
  1758. }
  1759. );
  1760. // Friction air fa (increasing near the center)
  1761. let fa_minf = 0;
  1762. let fa_maxf = 6;
  1763. // scale factor
  1764. let fa_scale = (fa_maxf-fa_minf) / (maxp-minp);
  1765. let fa = Math.exp(fa_minf + fa_scale*(dist-minp)*-1);
  1766. this.body.frictionAir = fa;
  1767. // console.log(`bringToCenter dist:${dist}, x_force:${x_force}, friction air:${fa}`);
  1768. } else { // in the ceneter zone let items floats freely
  1769. let fa = 0.01;
  1770. let velocity = Matter.Body.getVelocity(this.body);
  1771. if (velocity.x) {
  1772. let velocityx = Math.abs(velocity.x);
  1773. // map a range of numbers to another range of numbers
  1774. // INFO https://stackoverflow.com/a/46462321
  1775. let velocity_range = [50, 1000];
  1776. let fa_range = [0,3];
  1777. fa = fa_range[0] + (velocityx - velocity_range[0]) * (fa_range[1] - fa_range[0]) / (velocity_range[1] - velocity_range[0]);
  1778. // console.log(`bringToCenter velocityx:${velocityx}, fa:${fa}, velocity`, velocity);
  1779. } else {
  1780. console.warn(`bringToCenter no velocity`, velocity);
  1781. }
  1782. this.body.frictionAir = fa;
  1783. }
  1784. },
  1785. applyShuffleForces() {
  1786. // console.log('applyShuffleForces');
  1787. // var dist, dir, x_velocity;
  1788. // dir = this.pos.x > this.canvas.width/2 ? -1 : 1; // get the direction to the centre
  1789. // dist = (dir < 0 ? this.pos.x - this.canvas.width/2 : this.canvas.width/2 - this.pos.x); // get the distance from the side
  1790. // x_velocity = Math.pow(dist/650,10) * dir;
  1791. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1792. let pseudo_center_x = this.opened_concernement
  1793. ? (this.canvas.width - this.cartouch_width) / 2
  1794. : this.canvas.width / 2;
  1795. // get the direction to the centre
  1796. let dir = this.pos.x > pseudo_center_x
  1797. ? -1 // to left
  1798. : 1; // to right
  1799. // get the inversed distance from the side
  1800. let dist = dir < 0
  1801. ? this.pos.x - pseudo_center_x
  1802. : pseudo_center_x - this.pos.x;
  1803. dist = dist > 1000 ? 1000 : dist;
  1804. if (dist > this.canvas.width/6) { // apply decreasing forces and increasing friction air only out of center to let the items float in the center zone
  1805. // max & min item position
  1806. let minp = 0;
  1807. let maxp = dir < 0
  1808. ? this.canvas.width - pseudo_center_x
  1809. : pseudo_center_x;
  1810. // X max and min force
  1811. let xminf = 0;
  1812. let xmaxf = 4 + Math.random()*3;
  1813. // scale factor
  1814. let xscale = (xmaxf-xminf) / (maxp-minp);
  1815. let x_velocity = Math.exp(xminf + xscale*(dist-minp))*dir;
  1816. // let y_velocity = 30 + Math.random() * 50;
  1817. // y_velocity = Math.random() > 0.5 ? -y_velocity : y_velocity;
  1818. // X max and min force
  1819. let yminf = 1;
  1820. let ymaxf = 2 + Math.random()*4;
  1821. // scale factor
  1822. let yscale = (ymaxf-yminf) / (maxp-minp);
  1823. let y_velocity = Math.exp(yminf + yscale*(dist-minp)) * (Math.random() > 0.5 ? 1 : -1); // let ori_pos = dir < 0
  1824. // ? {x:this.canvas.width, y:this.body.position.y}
  1825. // : {x:0, y:this.body.position.y};
  1826. // let x_force = Math.pow(dist/800,10) * dir;
  1827. console.log(`applyShuffleForces dir:${dir}, maxp:${maxp}, dist:${dist}, x_velocity:${x_velocity}, y_velocity:${y_velocity}`);
  1828. Matter.Body.setVelocity(this.body, {x: x_velocity, y: y_velocity});
  1829. } else { // if in center zone real shuffle velocity
  1830. // x_velocity = -50 + Math.random()*100;
  1831. // y_velocity = -50 + Math.random()*100;
  1832. // this.setInitBodyVelocity();
  1833. }
  1834. this.body.frictionAir = 0.01;
  1835. },
  1836. applyNormalForces () {
  1837. // bring gently to the centre
  1838. // apply a force in direction of one side or an other depending of the start position
  1839. // the force is exponentialy inversed proportional to the distance from the side
  1840. // INFO logarithmic force : https://stackoverflow.com/questions/846221/logarithmic-slider/846249#846249
  1841. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1842. // X
  1843. let pseudo_center_x = this.opened_concernement
  1844. ? (this.canvas.width - this.cartouch_width) / 2
  1845. : this.canvas.width / 2;
  1846. let xdir = this.pos.x > pseudo_center_x
  1847. ? -1 // to left
  1848. : 1; // to right
  1849. // get the inversed distance from the side
  1850. let xdist = xdir < 0
  1851. ? this.pos.x - pseudo_center_x
  1852. : pseudo_center_x - this.pos.x;
  1853. // Y
  1854. let pseudo_center_y = this.canvas.height / 2;
  1855. let ydir = this.pos.y > pseudo_center_y
  1856. ? -1 // to top
  1857. : 1; // to bottom
  1858. // get the inversed distance from the side
  1859. let ydist = ydir < 0
  1860. ? this.pos.y - pseudo_center_y
  1861. : pseudo_center_y - this.pos.y;
  1862. let k = 4;
  1863. if (xdist > this.canvas.width/k || ydist > this.canvas.height/k) { // apply decreasing forces and increasing friction air only out of center to let the items float in the center zone
  1864. // max and min force
  1865. let minf = 0;
  1866. let maxf = 0.1;
  1867. // X
  1868. // max & min item position
  1869. let xminp = 0;
  1870. let xmaxp = xdir < 0
  1871. ? this.canvas.width - pseudo_center_x
  1872. : pseudo_center_x;
  1873. // X force decrsinsing near the center
  1874. // scale factor
  1875. let xscale = (maxf-minf) / (xmaxp-xminp);
  1876. let x_force = Math.exp(minf + xscale*(xdist-xminp)) * xdir;
  1877. let xori_pos = xdir < 0
  1878. ? {x:this.canvas.width, y:this.body.position.y}
  1879. : {x:0, y:this.body.position.y};
  1880. Matter.Body.applyForce(
  1881. this.body,
  1882. xori_pos,
  1883. {
  1884. x: x_force,
  1885. y: 0
  1886. }
  1887. );
  1888. // Y
  1889. // max & min item position
  1890. let yminp = 0;
  1891. let ymaxp = ydir < 0
  1892. ? this.canvas.height - pseudo_center_y
  1893. : pseudo_center_y;
  1894. // X force decrsinsing near the center
  1895. // scale factor
  1896. let yscale = (maxf-minf) / (ymaxp-yminp);
  1897. let y_force = Math.exp(minf + yscale*(ydist-xminp)) * ydir;
  1898. let yori_pos = ydir < 0
  1899. ? {x:this.body.position.x, y:this.canvas.height}
  1900. : {x:this.body.position.x, y:0};
  1901. Matter.Body.applyForce(
  1902. this.body,
  1903. yori_pos,
  1904. {
  1905. x: 0,
  1906. y: y_force
  1907. }
  1908. );
  1909. // // Friction air fa (increasing near the center)
  1910. // let fa_minf = 0;
  1911. // let fa_maxf = 6;
  1912. // // scale factor
  1913. // let fa_scale = (fa_maxf-fa_minf) / (maxp-minp);
  1914. // let fa = Math.exp(fa_minf + fa_scale*(dist-minp)*-1);
  1915. // this.body.frictionAir = fa;
  1916. // console.log(`bringToCenter dist:${xdist}, x_force:${x_force}`);
  1917. } else { // in the ceneter zone let items floats freely
  1918. // let velocity = Matter.Body.getVelocity(this.body);
  1919. // let velocityx = Math.abs(velocity.x);
  1920. // // map a range of numbers to another range of numbers
  1921. // // INFO https://stackoverflow.com/a/46462321
  1922. // let velocity_range = [50, 1000];
  1923. // let fa_range = [0,3];
  1924. // let fa = fa_range[0] + (velocityx - velocity_range[0]) * (fa_range[1] - fa_range[0]) / (velocity_range[1] - velocity_range[0]);
  1925. // console.log(`bringToCenter velocity.x:${velocity.x}, fa:${fa}`);
  1926. // this.body.frictionAir = fa;
  1927. this.body.frictionAir = 0.1;
  1928. }
  1929. },
  1930. respawn() {
  1931. // respawn element if outside screen
  1932. if(this.pos.x <= 0
  1933. || this.pos.x >= this.canvas.width
  1934. || this.pos.y <= 0
  1935. || this.pos.y >= this.canvas.height){
  1936. this.pos = this.getRandomPos()
  1937. Matter.Body.setPosition(this.body, {x:this.pos.x, y:this.pos.y});
  1938. // this.setInitBodyVelocity();
  1939. Matter.Body.setVelocity(this.body, {x:0,y:0});
  1940. }
  1941. },
  1942. onAfterEngineUpdate (event) {
  1943. this.respawn();
  1944. this.paper_main_object.position = this.pos = this.body.position;
  1945. this.handlePaperVisibilityOnAfterEnginUpdate()
  1946. },
  1947. },
  1948. render() {
  1949. // console.log('render()', this.ctx);
  1950. },
  1951. }
  1952. </script>