-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderFunctions.js
504 lines (433 loc) · 16.3 KB
/
renderFunctions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
import * as ImpactFunctions from './impactFunctions.js';
import * as PolicyFunctions from './policyFunctions.js';
// Render game state
export function renderGameState(gameState) {
const creditsDisplay = `<p class="game-info">Political Credits: ${gameState.credits}</p>`;
const roundDisplay = `<p class="game-info">Round # ${gameState.currentRound}</p>`;
$('#policy-actions').html(`
<div class="game-info-container">
${creditsDisplay}
${roundDisplay}
</div>
<div class="game-actions-container">
<button id="add-policy">Add Policy</button>
<button id="end-round">End Round</button>
</div>
`);
renderSVGCirclesAndLines(gameState);
}
export function renderSVGCirclesAndLines(gameState) {
const svgContainer = "#svg-container";
const width = 1500;
const height = 750;
clearSVGContainer(svgContainer);
const svg = createSVG(svgContainer, width, height);
const drag = createDragBehavior(svg);
calculateNodePositions(filterStateAndPolicyNodes(gameState));
calculateVoterNodePositions(filterVoterNodes(gameState));
drawImpactLines(svg, gameState, groupImpacts(gameState.impacts));
drawVoterNodesAndLabels(svg, filterVoterNodes(gameState), gameState);
drawNodesAndLabels(svg, filterStateAndPolicyNodes(gameState), gameState, drag);
}
export function drawCategoryBackground(svg, startAngle, endAngle, radius, category) {
const centerX = 700; // Center X coordinate of the canvas
const centerY = 320; // Center Y coordinate of the canvas
// Create an arc generator for the text path
const textPathArcGenerator = d3.arc()
.innerRadius(radius - 20) // Adjust as needed
.outerRadius(radius)
.startAngle(startAngle)
.endAngle(endAngle);
// Create an arc generator for the background path
const bgArcGenerator = d3.arc()
.innerRadius(0)
.outerRadius(radius)
.startAngle(startAngle)
.endAngle(endAngle);
// Define the text path in the SVG's defs
const defs = svg.append('defs');
const textPathId = `text-path-${category}`;
defs.append("path")
.attr("id", textPathId)
.attr("d", textPathArcGenerator())
.attr("transform", `translate(${centerX}, ${centerY})`);
// Draw the arc
const arcPath = svg.insert("path", ":first-child") // Insert the path as the first child of the SVG
.attr("d", bgArcGenerator())
.attr("transform", `translate(${centerX}, ${centerY})`)
.style("fill", 'white')
.style("stroke", "gray")
.style("stroke-width", 1);
// Add the category name to the arc
svg.append("text")
.append("textPath") //append a textPath to the text element
.attr("xlink:href", `#${textPathId}`) //place the ID of the path here
.style("text-anchor","middle") //place the text halfway on the arc
.attr("startOffset", "20%")
.text(category !== undefined ? category.toUpperCase() : "");
}
export function drawNodesAndLabels(svg, stateAndPolicyNodes, gameState, drag) {
// Draw category backgrounds
let uniqueCategories = Array.from(new Set(stateAndPolicyNodes.map(node => node.category)));
const centerX = 700; // Center X coordinate of the canvas
const centerY = 320; // Center Y coordinate of the canvas
const radius = 300;
const segmentCount = 10; // Adjust as needed, determines the number of segments within each category
let categoryArcs = {};
uniqueCategories.forEach((category, index) => {
const anglePerCategory = 2 * Math.PI / uniqueCategories.length;
const startAngle = index * anglePerCategory;
const endAngle = (index + 1) * anglePerCategory;
const arc = d3.arc()
.innerRadius(radius - 20) // Adjust as needed
.outerRadius(radius)
.startAngle(startAngle)
.endAngle(endAngle);
categoryArcs[category] = arc;
drawCategoryBackground(svg, startAngle, endAngle, radius, category);
});
stateAndPolicyNodes.forEach((node) => {
const x = node.pos.x;
const y = node.pos.y;
// Draw circle
svg.append("circle")
.datum(node)
.attr("cx", x)
.attr("cy", y)
.attr("r", node.radius)
.style("fill", node.type === 'state' ? "blue" : "green")
.classed("node-circle", true)
.classed("node-circle-state", node.type === "state")
.classed("node-circle-policy", node.type === "policy")
.on("click", () => {
showDetails(gameState, node);
})
.on("mouseover", () => {
ImpactFunctions.showImpactStrength(node);
// Adjust opacity of lines
svg.selectAll(`.flowing-line`).attr('stroke-opacity', 0.2);
svg.selectAll(`.line-${node.id}`).attr('stroke-opacity', 1);
})
.on("mouseout", () => {
ImpactFunctions.hideImpactStrength();
// Reset opacity of lines
svg.selectAll(`.flowing-line`).attr('stroke-opacity', function () {
return d3.select(this).attr("data-default-opacity");
});
})
.call(drag);
// Draw text label
svg.append("text")
.datum(node)
.attr("x", x)
.attr("y", y + 30)
.attr("text-anchor", "middle")
.text(node.name)
.classed("node-label", true)
.classed("node-label-state", node.type === "state")
.classed("node-label-policy", node.type === "policy")
.classed("node-label-voter", node.type === "voter");
});
}
export function groupImpacts(impacts) {
let groupedImpacts = {};
impacts.forEach((impact) => {
let key = [impact.from, impact.to].sort().join('-');
if (!groupedImpacts[key]) {
groupedImpacts[key] = [];
}
groupedImpacts[key].push(impact);
});
return groupedImpacts;
}
export function clearSVGContainer(svgContainer) {
d3.select(svgContainer).html("");
}
export function createSVG(svgContainer, width, height) {
return d3.select(svgContainer)
.append("svg")
.attr("width", width)
.attr("height", height);
}
// Function to show details
export function showDetails(gameState, item) {
const impactMatrix = ImpactFunctions.createImpactMatrix(gameState, item.id);
var deletionCost = 20;
Swal.fire({
title: item.name,
html: `
<p>Description: ${item.description}</p>
${ImpactFunctions.renderImpactMatrix(impactMatrix)}
`,
confirmButtonText: 'Close',
showCancelButton: item.type === 'policy',
cancelButtonText: 'Delete Policy ('+deletionCost+')'
}).then((result) => {
if (item.type === 'policy' && result.isDismissed && result.dismiss === Swal.DismissReason.cancel) {
PolicyFunctions.deletePolicy(gameState, item, deletionCost);
}
});
}
export function createDragBehavior(svg) {
let drag = d3.drag()
.on("start", function(event, d) {
d3.select(this).attr("stroke", "black").classed("node-dragging", true);;
})
.on("drag", function(event, d) {
d.pos.x = d.x = event.x;
d.pos.y = d.y = event.y;
d3.select(this)
.attr("cx", d.x)
.attr("cy", d.y);
updateLines(svg, d);
updateLabels(svg, d);
})
.on("end", function(event, d) {
d3.select(this).attr("stroke", null).classed("node-dragging", false);;
});
return drag;
}
export function calculateNodePositions(nodes) {
let uniqueCategories = Array.from(new Set(nodes.map(node => node.category)));
const centerX = 700; // Center X coordinate of the canvas
const centerY = 320; // Center Y coordinate of the canvas
const radius = Math.min(1500, 500) / 3; // Adjust the radius based on the canvas size
let categoryArcs = {};
uniqueCategories.forEach((category, index) => {
const anglePerCategory = 2 * Math.PI / uniqueCategories.length;
const startAngle = index * anglePerCategory;
const endAngle = (index + 1) * anglePerCategory;
const arc = d3.arc()
.innerRadius(radius - 20) // Adjust as needed
.outerRadius(radius)
.startAngle(startAngle)
.endAngle(endAngle);
categoryArcs[category] = arc;
});
nodes.forEach((node) => {
const category = node.category;
const arc = categoryArcs[category];
const angle = Math.random() * (arc.endAngle() - arc.startAngle()) + arc.startAngle();
const position = arc.centroid(angle);
const x = centerX + position[0] + Math.random() * 20; // Add random offset to X coordinate
const y = centerY + position[1] + Math.random() * 20; // Add random offset to Y coordinate
node.pos = {
x: x,
y: y,
fx: x, // Set initial position for dragging
fy: y
}; // Save the node's position
node.radius = node.type === 'state' ? node.value / 5 : 20; // Save the node's radius
});
// Check for collisions and adjust positions
nodes.forEach((node, index) => {
const x = node.pos.x;
const y = node.pos.y;
const radius = node.radius;
const collision = checkCollision(nodes, node, x, y, radius);
if (collision) {
// Collision detected: Adjust position by moving the node towards or away from the center by at least the radius length
const category = node.category;
const arc = categoryArcs[category];
const angle = Math.random() * (arc.endAngle() - arc.startAngle()) + arc.startAngle();
const position = arc.centroid(angle);
const nodeX = centerX + position[0]; // X coordinate without random offset
const nodeY = centerY + position[1]; // Y coordinate without random offset
const dx = nodeX - centerX;
const dy = nodeY - centerY;
const distance = Math.sqrt(dx * dx + dy * dy);
const offsetX = (dx / distance) * 5 * radius; // Offset towards or away from the center in the X direction
const offsetY = (dy / distance) * 5 * radius; // Offset towards or away from the center in the Y direction
const newX = centerX + offsetX; // Adjusted X coordinate
const newY = centerY + offsetY; // Adjusted Y coordinate
node.pos.x = newX;
node.pos.y = newY;
}
});
}
function checkCollision(nodes, currentNode, x, y, radius) {
for (let i = 0; i < nodes.length; i++) {
const otherNode = nodes[i];
if (otherNode !== currentNode) {
const otherX = otherNode.pos.x;
const otherY = otherNode.pos.y;
const otherRadius = otherNode.radius;
const dx = otherX - x;
const dy = otherY - y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < otherRadius + radius) {
return true; // Collision detected
}
}
}
return false; // No collision detected
}
export function updateLines(svg, d) {
svg.selectAll('.flowing-line')
.filter(function(lineData) {
return lineData.from === d.id;
})
.attr("x1", a => d.x)
.attr("y1", a => d.y);
svg.selectAll('.flowing-line')
.filter(function(lineData) {
return lineData.to === d.id;
})
.attr("x2", a => d.x)
.attr("y2", a => d.y);
}
export function updateLabels(svg, d) {
svg.selectAll('.node-label')
.filter(function(nodeData) {
return nodeData && nodeData.id === d.id;
})
.attr("x", a => d.x)
.attr("y", a => d.y+30);
}
export function filterVoterNodes(gameState) {
return gameState.nodes.filter(node => node.type === "voter");
}
export function filterStateAndPolicyNodes(gameState) {
return gameState.nodes.filter(node => node.type !== "voter");
}
export function calculateVoterNodePositions(voterNodes) {
voterNodes.forEach((node, index) => {
const x = 50;
const y = 10 + index * 35;
const width = 140;
const height = 30;
node.pos = {
x: x+width-20,
y: y+height/2-2
};
});
}
export function drawVoterNodesAndLabels(svg, voterNodes, gameState) {
voterNodes.forEach((node, index) => {
const x = 50;
const y = 10 + index * 35;
const width = 140;
const height = 30;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", width)
.attr("height", height)
.style("fill", "lightgray")
.classed("node-rectangle", true)
.on("click", function() {
showDetails(gameState, node);
})
.on("mouseover", () => {
ImpactFunctions.showImpactStrength(node);
// Adjust opacity of lines
svg.selectAll(`.flowing-line`).attr('stroke-opacity', 0.2);
svg.selectAll(`.line-${node.id}`).attr('stroke-opacity', 1);
})
.on("mouseout", () => {
ImpactFunctions.hideImpactStrength();
// Reset opacity of lines
svg.selectAll(`.flowing-line`).attr('stroke-opacity', function() {
return d3.select(this).attr("data-default-opacity");
});
})
// Draw the approval rating rectangle
let approvalColor;
if (node.finalApproval > 70) {
approvalColor = "green";
} else if (node.finalApproval >= 30) {
approvalColor = "orange";
} else {
approvalColor = "red";
}
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", width * node.finalApproval / 100) // approval attribute is a percentage
.attr("height", height)
.style("fill", approvalColor)
.style("opacity", 0.5) // make the rectangle semi-transparent
.classed("approval-rating-rectangle", true)
.on("click", function() {
showDetails(gameState, node);
})
.on("mouseover", () => {
ImpactFunctions.showImpactStrength(node);
// Adjust opacity of lines
svg.selectAll(`.flowing-line`).attr('stroke-opacity', 0.2);
svg.selectAll(`.line-${node.id}`).attr('stroke-opacity', 1);
})
.on("mouseout", () => {
ImpactFunctions.hideImpactStrength();
// Reset opacity of lines
svg.selectAll(`.flowing-line`).attr('stroke-opacity', function() {
return d3.select(this).attr("data-default-opacity");
});
})
// Draw the label
svg.append("text")
.attr("x", x + width / 2)
.attr("y", y + height / 2)
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle")
.text(node.name)
.classed("node-label", true)
.classed("node-label-voter", true);
});
}
export function drawImpactLines(svg, gameState, groupedImpacts) {
for (let key in groupedImpacts) {
let impacts = groupedImpacts[key];
let node1 = gameState.nodes.find(node => node.id === impacts[0].from);
let node2 = gameState.nodes.find(node => node.id === impacts[0].to);
// Check if the nodes have positions
if (node1 && node2 && node1.pos && node2.pos) {
// Calculate offset for parallel lines
let dx = node2.pos.x - node1.pos.x;
let dy = node2.pos.y - node1.pos.y;
let len = Math.max(Math.sqrt(dx * dx + dy * dy), 0.0000001);
let offset = 5;
// Calculate offset vector
let ox = (dy / len) * offset;
let oy = -(dx / len) * offset;
impacts.forEach((impact, index) => {
// Calculate position of the line
let posX = index === 0 ? 1 : -1;
// Draw line
let opacity = Math.abs(impact.impact) / 100;
let line = svg.append("line")
.datum(impact) // Bind the data to the line
.attr("x1", node1.pos.x + posX * ox)
.attr("y1", node1.pos.y + posX * oy)
.attr("x2", node2.pos.x + posX * ox)
.attr("y2", node2.pos.y + posX * oy)
.attr("stroke", impact.impact > 0 ? "green" : "red")
.attr("stroke-opacity", opacity+0.1) // make the line transparent
.attr("data-default-opacity", opacity+0.1)
.attr("stroke-width", 15)
.attr("marker-end", "url(#triangle)")
.attr("class", `line-${node1.id} line-${node2.id}`)
.classed("flowing-line", true)
// Calculate the number of gaps
const lineLength = line.node().getTotalLength();
const totalGaps = Math.floor(lineLength / 10); // Adjust the gap width as needed
const gapLength = lineLength / totalGaps;
const gapArray = Array.from({
length: totalGaps
}, (_, i) => `${gapLength} ${gapLength}`).join(" ");
// Calculate the animation duration based on the impact value
const animationDuration = Math.max(100 - Math.abs(impact.impact), 0); // Adjust the scaling factor as needed
// Determine the direction of the line
const isForward = impact.from === node1.id && impact.to === node2.id;
// Set the animation properties
line.style("animation-duration", `${animationDuration}s`)
.style("animation-timing-function", "linear")
.style("animation-iteration-count", "infinite")
.style("animation-name", isForward ? "flowAnimationForwards" : "flowAnimationBackwards")
.style("animation-fill-mode", "forwards");
// Animate the gaps
line.attr("stroke-dasharray", gapArray);
});
}
}
}