-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChandy-Lambert-Simulation.html
More file actions
705 lines (617 loc) · 35.1 KB
/
Chandy-Lambert-Simulation.html
File metadata and controls
705 lines (617 loc) · 35.1 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chandy-Lambert Snapshot Algorithm</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
</head>
<body class="bg-gray-900 text-white flex flex-col items-center justify-center h-screen p-4">
<div class="w-full max-w-7xl mx-auto flex flex-col lg:flex-row gap-4 h-full">
<!-- Main Visualization Area -->
<div class="flex-grow bg-gray-800 rounded-lg relative overflow-hidden shadow-2xl match-vis-height" id="visualization-container">
<svg id="channel-svg" class="absolute top-0 left-0 w-full h-full"></svg>
</div>
<!-- Control and Log Panel -->
<div class="lg:w-1/3 w-full bg-gray-800 rounded-lg p-6 flex flex-col shadow-2xl h-full lg:max-h-[90vh] match-vis-height">
<h1 class="text-2xl font-bold text-center mb-4 text-cyan-400">Chandy-Lambert Snapshot</h1>
<p class="text-sm text-gray-400 text-center mb-6">A distributed algorithm to capture a consistent global state.</p>
<div id="main-controls">
<div class="mb-4">
<label for="node-count-selector" class="block text-sm font-medium text-gray-400 text-center mb-2">Number of Processes:</label>
<select id="node-count-selector" class="bg-gray-700 border border-gray-600 text-white text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5">
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="flex justify-center mb-4">
<button id="toggle-simulation" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition-colors w-full">Start Simulation</button>
</div>
<p class="text-sm text-gray-400 text-center mb-6">Click on a process (circle) to initiate a snapshot.</p>
</div>
<div id="replay-controls" class="hidden">
<p class="text-lg font-semibold text-center mb-2 text-yellow-400">Replay Mode</p>
<div class="flex justify-between items-center mb-2 gap-2">
<button id="prev-step" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition-colors w-full">Prev</button>
<div id="step-counter" class="text-center font-mono whitespace-nowrap">Step 0 / 0</div>
<button id="next-step" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition-colors w-full">Next</button>
</div>
<div class="flex justify-center mb-4">
<button id="exit-replay" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition-colors w-full mt-2">Exit Replay & Reset</button>
</div>
</div>
<h2 class="text-lg font-semibold mb-2 text-cyan-400 border-b border-gray-600 pb-1">Event Log</h2>
<div id="log-container" class="flex-grow bg-gray-900 rounded-md p-3 overflow-y-auto text-sm space-y-2 h-40">
<!-- Log messages will appear here -->
</div>
<h2 class="text-lg font-semibold mt-6 mb-2 text-cyan-400 border-b border-gray-600 pb-1">Global Snapshot</h2>
<div id="snapshot-container" class="bg-gray-900 rounded-md p-3 overflow-y-auto h-40">
<p class="text-gray-500 italic">No snapshot taken yet.</p>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const container = document.getElementById('visualization-container');
const svg = document.getElementById('channel-svg');
const logContainer = document.getElementById('log-container');
const snapshotContainer = document.getElementById('snapshot-container');
const toggleButton = document.getElementById('toggle-simulation');
const mainControls = document.getElementById('main-controls');
const replayControls = document.getElementById('replay-controls');
const prevStepBtn = document.getElementById('prev-step');
const nextStepBtn = document.getElementById('next-step');
const exitReplayBtn = document.getElementById('exit-replay');
const stepCounter = document.getElementById('step-counter');
const nodeCountSelector = document.getElementById('node-count-selector');
// --- State Variables ---
let processCount = 3;
let processes = [];
let channels = new Map();
let messages = [];
let simulationRunning = false;
let messageIdCounter = 0;
let snapshotInProgress = false;
let snapshotInitiator = -1;
let snapshotId = 0;
// Replay state
let isReplaying = false;
let replayQueue = [];
let currentStep = -1;
let preSnapshotStates = {};
let collectedSnapshot = {};
class Process {
constructor(id, x, y) {
this.id = id;
this.state = 0;
this.pos = { x, y };
this.el = this.createElement();
}
createElement() {
const el = document.createElement('div');
el.className = 'process absolute flex flex-col items-center justify-center w-24 h-24 rounded-full border-4 border-cyan-500 bg-gray-700 cursor-pointer';
el.style.left = `${this.pos.x}%`;
el.style.top = `${this.pos.y}%`;
el.style.transform = 'translate(-50%, -50%)';
const idEl = document.createElement('div');
idEl.className = 'text-lg font-bold';
idEl.textContent = `P${this.id}`;
const stateEl = document.createElement('div');
stateEl.className = 'text-2xl font-mono';
stateEl.id = `state-${this.id}`;
stateEl.textContent = this.state;
el.appendChild(idEl);
el.appendChild(stateEl);
el.onclick = () => this.initiateSnapshot();
container.appendChild(el);
return el;
}
updateStateDisplay() {
document.getElementById(`state-${this.id}`).textContent = this.state;
}
incrementState() {
this.state++;
this.updateStateDisplay();
}
initiateSnapshot() {
if (snapshotInProgress) {
logMessage('Snapshot already in progress.', 'error');
return;
}
if (isReplaying) {
logMessage('Cannot start a snapshot during replay.', 'error');
return;
}
snapshotInProgress = true;
isReplaying = true;
snapshotId++;
snapshotInitiator = this.id;
collectedSnapshot = { processStates: new Map(), channelStates: new Map() };
buildReplayQueue(this.id);
simulationRunning = false;
toggleButton.textContent = 'Simulation Paused';
toggleButton.classList.add('btn-disabled');
nodeCountSelector.disabled = true;
mainControls.classList.add('hidden');
replayControls.classList.remove('hidden');
logContainer.innerHTML = '';
snapshotContainer.innerHTML = '<p class="text-gray-500 italic">Replay in progress...</p>';
messages.forEach(msg => msg.el.style.display = 'none');
processes.forEach(p => preSnapshotStates[p.id] = { state: p.state });
currentStep = -1;
updateReplayUI();
logMessage(`Snapshot #${snapshotId} initiated by P${this.id}. Starting replay...`, 'snapshot');
}
resetVisuals() {
this.el.classList.remove('border-red-500', 'bg-red-900');
this.el.classList.add('border-cyan-500', 'bg-gray-700');
channels.forEach(c => c.line.classList.remove('recording'));
}
}
// --- Simulation Logic ---
function buildReplayQueue(initiatorId) {
replayQueue = [];
let virtualProcesses = {};
const initialStates = {};
processes.forEach(p => {
initialStates[p.id] = p.state;
virtualProcesses[p.id] = {
id: p.id,
state: p.state,
markerReceived: false,
isRecording: new Map(),
};
});
let eventQueue = [];
eventQueue.push({ time: 0, type: 'RECEIVE_MARKER', from: null, to: initiatorId, channelId: null });
messages.forEach(msg => {
const arrivalTime = (1 - msg.progress) * 100;
eventQueue.push({ time: arrivalTime, type: 'MESSAGE_ARRIVAL', message: msg });
});
eventQueue.sort((a,b) => a.time - b.time);
while(eventQueue.length > 0) {
const event = eventQueue.shift();
const vp = virtualProcesses[event.to] || virtualProcesses[event.message?.to];
switch(event.type) {
case 'RECEIVE_MARKER': {
if (vp.markerReceived) {
replayQueue.push({ type: 'STOP_RECORDING', from: event.from, to: event.to });
vp.isRecording.set(event.channelId, false);
} else {
vp.markerReceived = true;
replayQueue.push({ type: 'RECORD_STATE', processId: vp.id, state: initialStates[vp.id] });
channels.forEach(channel => {
if (channel.to === vp.id) {
// For snapshot initiator (event.channelId is null), record on all incoming channels
// For other processes, record on all channels except the one the marker came from
if (event.channelId === null || channel.id !== event.channelId) {
vp.isRecording.set(channel.id, true);
replayQueue.push({ type: 'START_RECORDING', from: channel.from, to: channel.to });
}
}
});
channels.forEach(channel => {
if (channel.from === vp.id) {
replayQueue.push({ type: 'SEND_MARKER', from: vp.id, to: channel.to });
eventQueue.push({ time: event.time + 50, type: 'RECEIVE_MARKER', from: vp.id, to: channel.to, channelId: `ch-${vp.id}-${channel.to}`});
}
});
}
break;
}
case 'MESSAGE_ARRIVAL': {
const msg = event.message;
if (vp.isRecording.get(msg.channelId)) {
replayQueue.push({ type: 'RECORD_MESSAGE', from: msg.from, to: msg.to, channelId: msg.channelId });
}
vp.state++;
break;
}
}
eventQueue.sort((a,b) => a.time - b.time);
}
replayQueue.push({ type: 'SNAPSHOT_COMPLETE' });
}
function createProcesses() {
const layouts = {
2: [{ x: 30, y: 50 }, { x: 70, y: 50 }],
3: [{ x: 50, y: 15 }, { x: 20, y: 75 }, { x: 80, y: 75 }],
4: [{ x: 25, y: 25 }, { x: 75, y: 25 }, { x: 25, y: 75 }, { x: 75, y: 75 }],
5: [{ x: 50, y: 15 }, { x: 15, y: 45 }, { x: 85, y: 45 }, { x: 30, y: 85 }, { x: 70, y: 85 }]
};
const positions = layouts[processCount];
for (let i = 0; i < processCount; i++) {
processes.push(new Process(i, positions[i].x, positions[i].y));
}
}
function createChannels() {
const connections = [];
for(let i=0; i < processCount; i++) {
for(let j=0; j < processCount; j++) {
if (i !== j) connections.push([i,j]);
}
}
connections.forEach(([from, to]) => {
const id = `ch-${from}-${to}`;
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('class', 'channel-line');
line.setAttribute('marker-end', 'url(#arrowhead)');
svg.appendChild(line);
channels.set(id, { id, from, to, line });
});
const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
marker.setAttribute('id', 'arrowhead');
marker.setAttribute('viewBox', '0 -5 10 10');
marker.setAttribute('refX', 18); marker.setAttribute('refY', 0);
marker.setAttribute('markerWidth', 6); marker.setAttribute('markerHeight', 6);
marker.setAttribute('orient', 'auto');
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', 'M0,-5L10,0L0,5');
path.setAttribute('fill', '#9ca3af');
marker.appendChild(path); defs.appendChild(marker); svg.appendChild(defs);
onResize();
}
// --- Replay Logic ---
function applyStep(index) {
if (index < 0 || index >= replayQueue.length) return Promise.resolve();
return new Promise(resolve => {
const event = replayQueue[index];
const p = event.processId !== undefined ? processes[event.processId] : processes[event.to];
const channel = event.to !== undefined ? channels.get(`ch-${event.from}-${event.to}`) : null;
switch (event.type) {
case 'RECORD_STATE':
p.el.classList.remove('border-cyan-500', 'bg-gray-700');
p.el.classList.add('border-red-500', 'bg-red-900');
collectedSnapshot.processStates.set(event.processId, event.state);
logMessage(`P${p.id} records its state: ${event.state}.`, 'snapshot');
updateSnapshotDisplay();
resolve();
break;
case 'START_RECORDING':
if (channel) {
channel.line.classList.add('recording');
// Move recording line to front (last child = on top in SVG)
channel.line.parentNode.appendChild(channel.line);
collectedSnapshot.channelStates.set(channel.id, []);
}
logMessage(`P${event.to} starts recording on channel P${event.from}->P${event.to}.`);
updateSnapshotDisplay();
resolve();
break;
case 'SEND_MARKER':
logMessage(`Marker sent from P${event.from} to P${event.to}.`, 'info');
animateMarker(event.from, event.to).then(resolve);
break;
case 'STOP_RECORDING':
if (channel) channel.line.classList.remove('recording');
logMessage(`P${event.to} stops recording on channel P${event.from}->P${event.to}.`);
resolve();
break;
case 'RECORD_MESSAGE':
collectedSnapshot.channelStates.get(event.channelId).push('M');
logMessage(`P${event.to} recorded in-flight message from P${event.from}.`, 'snapshot');
updateSnapshotDisplay();
animateInFlightMessage(event.from, event.to).then(resolve);
break;
case 'SNAPSHOT_COMPLETE':
logMessage('Global snapshot complete!', 'success');
updateSnapshotDisplay(true);
resolve();
break;
default:
resolve();
}
});
}
function undoStep(index) {
if (index < 0 || index >= replayQueue.length) return;
processes.forEach(proc => {
proc.resetVisuals();
proc.state = preSnapshotStates[proc.id].state;
proc.updateStateDisplay();
});
logContainer.innerHTML = '';
snapshotContainer.innerHTML = '<p class="text-gray-500 italic">Replay in progress...</p>';
collectedSnapshot = { processStates: new Map(), channelStates: new Map() };
for (let i = 0; i < index; i++) {
const event = replayQueue[i];
const p = event.processId !== undefined ? processes[event.processId] : processes[event.to];
const channel = event.to !== undefined ? channels.get(`ch-${event.from}-${event.to}`) : null;
switch (event.type) {
case 'RECORD_STATE':
p.el.classList.remove('border-cyan-500', 'bg-gray-700');
p.el.classList.add('border-red-500', 'bg-red-900');
collectedSnapshot.processStates.set(event.processId, event.state);
logMessage(`P${p.id} records state: ${event.state}.`, 'snapshot');
break;
case 'START_RECORDING':
if (channel) {
channel.line.classList.add('recording');
// Move recording line to front (last child = on top in SVG)
channel.line.parentNode.appendChild(channel.line);
collectedSnapshot.channelStates.set(channel.id, []);
}
logMessage(`P${event.to} starts recording on channel P${event.from}->P${event.to}.`);
break;
case 'SEND_MARKER':
logMessage(`Marker sent from P${event.from} to P${event.to}.`, 'info');
break;
case 'STOP_RECORDING':
if (channel) channel.line.classList.remove('recording');
logMessage(`P${event.to} stops recording on channel P${event.from}->P${event.to}.`);
break;
case 'RECORD_MESSAGE':
collectedSnapshot.channelStates.get(event.channelId).push('M');
logMessage(`P${event.to} recorded in-flight message from P${event.from}.`, 'snapshot');
break;
case 'SNAPSHOT_COMPLETE':
logMessage('Global snapshot complete!', 'success');
break;
}
}
updateSnapshotDisplay(index >= replayQueue.length-1);
}
function updateReplayUI() {
stepCounter.textContent = `Step ${currentStep + 1} / ${replayQueue.length}`;
const isFirstStep = currentStep < 0;
const isLastStep = currentStep >= replayQueue.length - 1;
prevStepBtn.classList.toggle('btn-disabled', isFirstStep);
nextStepBtn.classList.toggle('btn-disabled', isLastStep);
}
function toggleReplayButtons(disabled) {
prevStepBtn.disabled = disabled;
nextStepBtn.disabled = disabled;
exitReplayBtn.disabled = disabled;
prevStepBtn.classList.toggle('btn-disabled', disabled);
nextStepBtn.classList.toggle('btn-disabled', disabled);
exitReplayBtn.classList.toggle('btn-disabled', disabled);
}
function animateInFlightMessage(fromId, toId) {
return new Promise(resolve => {
const el = document.createElement('div');
el.className = 'message';
el.textContent = 'M';
container.appendChild(el);
const containerRect = container.getBoundingClientRect();
const fromP = processes[fromId];
const toP = processes[toId];
const startX = fromP.pos.x * containerRect.width / 100;
const startY = fromP.pos.y * containerRect.height / 100;
const endX = toP.pos.x * containerRect.width / 100;
const endY = toP.pos.y * containerRect.height / 100;
let progress = 0;
const duration = 500;
let startTime = null;
toggleReplayButtons(true);
function step(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
progress = Math.min(elapsed / duration, 1);
const currentX = startX + (endX - startX) * progress;
const currentY = startY + (endY - startY) * progress;
el.style.left = `${currentX}px`;
el.style.top = `${currentY}px`;
el.style.transform = 'translate(-50%, -50%)';
if (progress < 1) {
requestAnimationFrame(step);
} else {
el.remove();
toggleReplayButtons(false);
updateReplayUI();
resolve();
}
}
requestAnimationFrame(step);
});
}
function animateMarker(fromId, toId) {
return new Promise(resolve => {
const el = document.createElement('div');
el.className = 'marker';
el.textContent = 'S';
container.appendChild(el);
const containerRect = container.getBoundingClientRect();
const fromP = processes[fromId];
const toP = processes[toId];
const startX = fromP.pos.x * containerRect.width / 100;
const startY = fromP.pos.y * containerRect.height / 100;
const endX = toP.pos.x * containerRect.width / 100;
const endY = toP.pos.y * containerRect.height / 100;
let progress = 0;
const duration = 500;
let startTime = null;
toggleReplayButtons(true);
function step(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
progress = Math.min(elapsed / duration, 1);
const currentX = startX + (endX - startX) * progress;
const currentY = startY + (endY - startY) * progress;
el.style.left = `${currentX}px`;
el.style.top = `${currentY}px`;
el.style.transform = 'translate(-50%, -50%)';
if (progress < 1) {
requestAnimationFrame(step);
} else {
el.remove();
toggleReplayButtons(false);
updateReplayUI();
resolve();
}
}
requestAnimationFrame(step);
});
}
function updateSnapshotDisplay(isComplete = false) {
snapshotContainer.innerHTML = '';
const title = document.createElement('p');
title.className = 'text-lg font-bold text-yellow-300 mb-2';
title.textContent = `Snapshot #${snapshotId} (Initiated by P${snapshotInitiator})`;
snapshotContainer.appendChild(title);
collectedSnapshot.processStates.forEach((state, processId) => {
const pStateDiv = document.createElement('div');
pStateDiv.className = 'mb-1';
pStateDiv.innerHTML = `<span class="font-semibold text-white">P${processId} State:</span> <span class="font-mono text-cyan-400">${state}</span>`;
snapshotContainer.appendChild(pStateDiv);
});
collectedSnapshot.channelStates.forEach((messages, channelId) => {
const ch = channels.get(channelId);
const chStateDiv = document.createElement('div');
chStateDiv.className = 'ml-4 text-sm';
const messageCount = messages.length;
chStateDiv.innerHTML = `<span class="text-gray-400">Channel P${ch.from}->P${ch.to}:</span> <span class="font-mono text-blue-400">{${messageCount > 0 ? `${messageCount} message(s)` : 'empty'}}</span>`;
snapshotContainer.appendChild(chStateDiv);
});
if(!isComplete) {
const notice = document.createElement('p');
notice.className = "text-gray-500 italic mt-4";
notice.textContent = "Snapshot in progress...";
snapshotContainer.appendChild(notice);
}
}
function exitReplay() {
isReplaying = false;
snapshotInProgress = false;
replayQueue = [];
currentStep = -1;
mainControls.classList.remove('hidden');
replayControls.classList.add('hidden');
toggleButton.classList.remove('btn-disabled');
nodeCountSelector.disabled = false;
processes.forEach(p => {
const preState = preSnapshotStates[p.id];
p.state = preState.state;
p.updateStateDisplay();
p.resetVisuals();
});
messages.forEach(msg => msg.el.style.display = 'flex');
logContainer.innerHTML = '';
snapshotContainer.innerHTML = '<p class="text-gray-500 italic">No snapshot taken yet.</p>';
logMessage('Exited replay mode. System reset.', 'info');
}
function createMessage(from, to) {
if (!processes[from] || !processes[to]) return;
const el = document.createElement('div');
el.className = 'message';
el.textContent = 'M';
container.appendChild(el);
messages.push({ id: messageIdCounter++, el, from, to, channelId: `ch-${from}-${to}`, progress: 0 });
}
function updateMessages() {
if (isReplaying) return;
const containerRect = container.getBoundingClientRect();
messages.forEach((msg, index) => {
msg.progress += 0.01;
const fromP = processes[msg.from]; const toP = processes[msg.to];
const startX = fromP.pos.x * containerRect.width / 100;
const startY = fromP.pos.y * containerRect.height / 100;
const endX = toP.pos.x * containerRect.width / 100;
const endY = toP.pos.y * containerRect.height / 100;
msg.el.style.left = `${startX + (endX - startX) * msg.progress}px`;
msg.el.style.top = `${startY + (endY - startY) * msg.progress}px`;
msg.el.style.transform = 'translate(-50%, -50%)';
if (msg.progress >= 1) {
msg.el.remove();
messages.splice(index, 1);
toP.incrementState();
}
});
}
function logMessage(msg, type = 'info') {
const p = document.createElement('p');
let colorClass = 'text-gray-300';
if (type === 'snapshot') colorClass = 'text-yellow-400 font-semibold';
if (type === 'error') colorClass = 'text-red-400';
if (type === 'success') colorClass = 'text-green-400 font-bold';
p.className = `${colorClass} transition-opacity duration-300 opacity-0`;
setTimeout(()=> p.style.opacity = '1', 10);
const time = new Date().toLocaleTimeString();
p.innerHTML = `<span class="text-gray-500 mr-2">[${time}]</span> ${msg}`;
logContainer.appendChild(p);
logContainer.scrollTop = logContainer.scrollHeight;
}
function simulationLoop() {
if (Math.random() < 0.05 && simulationRunning && !isReplaying) {
const from = Math.floor(Math.random() * processCount);
let to;
do { to = Math.floor(Math.random() * processCount); } while (to === from);
createMessage(from, to);
}
updateMessages();
requestAnimationFrame(simulationLoop);
}
function onResize() {
const containerRect = container.getBoundingClientRect();
channels.forEach(channel => {
const p1 = processes[channel.from]; const p2 = processes[channel.to];
const x1 = p1.pos.x * containerRect.width / 100; const y1 = p1.pos.y * containerRect.height / 100;
const x2 = p2.pos.x * containerRect.width / 100; const y2 = p2.pos.y * containerRect.height / 100;
channel.line.setAttribute('x1', x1); channel.line.setAttribute('y1', y1);
channel.line.setAttribute('x2', x2); channel.line.setAttribute('y2', y2);
});
}
function resetAndSetupSimulation() {
simulationRunning = false;
toggleButton.textContent = 'Start Simulation';
toggleButton.classList.remove('bg-yellow-600', 'hover:bg-yellow-700');
toggleButton.classList.add('bg-blue-600', 'hover:bg-blue-700');
nodeCountSelector.disabled = false;
processes.forEach(p => p.el.remove());
messages.forEach(msg => msg.el.remove());
if (svg.firstElementChild) svg.innerHTML = '';
processes = [];
messages = [];
channels.clear();
messageIdCounter = 0;
snapshotInProgress = false;
isReplaying = false;
logContainer.innerHTML = '';
snapshotContainer.innerHTML = '<p class="text-gray-500 italic">No snapshot taken yet.</p>';
mainControls.classList.remove('hidden');
replayControls.classList.add('hidden');
processCount = parseInt(nodeCountSelector.value, 10);
createProcesses();
createChannels();
}
// --- Event Listeners ---
toggleButton.addEventListener('click', () => {
if (isReplaying) return;
simulationRunning = !simulationRunning;
toggleButton.textContent = simulationRunning ? 'Pause Simulation' : 'Start Simulation';
toggleButton.classList.toggle('bg-blue-600', !simulationRunning);
toggleButton.classList.toggle('hover:bg-blue-700', !simulationRunning);
toggleButton.classList.toggle('bg-yellow-600', simulationRunning);
toggleButton.classList.toggle('hover:bg-yellow-700', simulationRunning);
nodeCountSelector.disabled = simulationRunning;
});
nodeCountSelector.addEventListener('change', resetAndSetupSimulation);
nextStepBtn.addEventListener('click', () => {
if(nextStepBtn.disabled) return;
if (currentStep < replayQueue.length - 1) {
currentStep++;
applyStep(currentStep).then(() => updateReplayUI());
}
});
prevStepBtn.addEventListener('click', () => {
if(prevStepBtn.disabled) return;
if (currentStep >= 0) {
currentStep--;
undoStep(currentStep + 1);
updateReplayUI();
}
});
exitReplayBtn.addEventListener('click', exitReplay);
window.addEventListener('resize', onResize);
// Initialization
resetAndSetupSimulation();
simulationLoop();
});
</script>
</body>
</html>