ConcernementMapItem.vue 71 KB

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