Add flame graph visualization

This commit is contained in:
Riyyi
2026-11-14 22:11:49 +01:00
parent e7966cac80
commit 48fe768689
5 changed files with 684 additions and 0 deletions
+7
View File
@@ -54,3 +54,10 @@ skips building the engine if its already running (pgrep).
no hot reload does not use game.dll, instead it imports the game source
as a normal Odin package during build.
## License
This project is licensed under the [MIT License](LICENSE), unless otherwise
noted. Individual files or subdirectories may carry a different license (for
example, the [Unlicense](https://unlicense.org)); in those cases, the license
terms specified in the file or directory take precedence.
+1
View File
@@ -0,0 +1 @@
../../out/arena_log.json
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

+662
View File
@@ -0,0 +1,662 @@
<!-- SPDX-License-Identifier: Unlicense -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arena Memory Flame Graph</title>
<style>
:root {
--bg: #0f1115;
--panel: #16181d;
--text: #e0e2e8;
--muted: #8b8f98;
--push: #3b82f6;
--pop: #ef4444;
--clear: #f59e0b;
--border: #2a2d35;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--bg);
color: var(--text);
display: flex;
flex-direction: column;
}
header {
padding: 1rem 1.5rem;
border-bottom: 1px solid var(--border);
background: var(--panel);
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
h1 { margin: 0; font-size: 1.25rem; }
.stats {
display: flex;
gap: 1.5rem;
color: var(--muted);
font-size: 0.875rem;
}
.stats span strong {
color: var(--text);
margin-left: 0.25rem;
}
main {
flex: 1;
padding: 1rem;
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: auto 1fr;
gap: 1rem;
min-height: 0;
}
.controls { grid-column: 1 / -1; }
.controls {
display: flex;
gap: 0.75rem;
align-items: center;
flex-wrap: wrap;
}
.controls label {
color: var(--muted);
font-size: 0.875rem;
}
.controls input[type="range"] {
width: 160px;
}
button {
background: #252830;
border: 1px solid var(--border);
color: var(--text);
padding: 0.4rem 0.8rem;
border-radius: 0.375rem;
cursor: pointer;
font-size: 0.875rem;
}
button:hover { background: #2e323b; }
#viewport {
grid-row: 2;
grid-column: 2;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 0.5rem;
overflow: hidden;
position: relative;
cursor: grab;
min-height: 0;
height: 100%;
}
#viewport.grabbing { cursor: grabbing; }
#viewport svg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
shape-rendering: crispEdges;
}
#y-axis {
grid-row: 2;
grid-column: 1;
display: flex;
flex-direction: column;
padding-right: 0.5rem;
color: var(--muted);
font-size: 0.75rem;
min-width: 4rem;
}
#y-axis .labels {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-end;
}
#y-axis .spacer {
flex: 0.12;
}
#y-axis .tick {
position: relative;
text-align: right;
line-height: 1;
}
#timeline-axis {
grid-row: 3;
grid-column: 2;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.25rem 0;
color: var(--muted);
font-size: 0.75rem;
border-top: 1px solid var(--border);
position: relative;
}
#timeline-axis::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 1px;
background: var(--border);
}
#timeline-axis .tick {
position: relative;
padding-top: 0.25rem;
text-align: center;
flex: 1;
}
#timeline-axis .tick::before {
content: '';
position: absolute;
top: -3px;
left: 50%;
width: 1px;
height: 6px;
background: var(--muted);
}
.frame {
stroke: rgba(0, 0, 0, 0.25);
stroke-width: 0.5px;
transition: opacity 0.1s;
}
.frame:hover {
stroke: #fff;
stroke-width: 1px;
opacity: 0.9;
}
#tooltip {
position: fixed;
pointer-events: none;
background: rgba(15, 17, 21, 0.95);
border: 1px solid var(--border);
border-radius: 0.375rem;
padding: 0.75rem;
font-size: 0.8rem;
line-height: 1.5;
color: var(--text);
box-shadow: 0 8px 24px rgba(0,0,0,0.35);
opacity: 0;
transition: opacity 0.1s;
max-width: 320px;
z-index: 100;
}
#tooltip .row { display: flex; gap: 0.5rem; }
#tooltip .key { color: var(--muted); min-width: 3.5rem; }
#tooltip .value { word-break: break-all; }
#tooltip .kind { font-weight: 600; text-transform: uppercase; font-size: 0.75rem; }
.legend {
display: flex;
gap: 1rem;
align-items: center;
font-size: 0.875rem;
color: var(--muted);
}
.legend .swatch {
display: inline-block;
width: 0.75rem;
height: 0.75rem;
border-radius: 2px;
margin-right: 0.35rem;
}
.error {
padding: 2rem;
color: #f87171;
text-align: center;
}
.hint {
color: var(--muted);
font-size: 0.8rem;
margin-left: auto;
}
</style>
</head>
<body>
<header>
<h1>Arena Memory Flame Graph</h1>
<div class="stats">
<span>Entries<strong id="stat-entries">-</strong></span>
<span>Live at peak<strong id="stat-peak">-</strong></span>
<span>Max bytes<strong id="stat-bytes">-</strong></span>
<span>Timeline<strong id="stat-time">-</strong></span>
</div>
</header>
<main>
<div class="controls">
<label>Zoom X <input id="zoomX" type="range" min="0.5" max="20" step="0.5" value="1"></label>
<label>Zoom Y <input id="zoomY" type="range" min="0.5" max="10" step="0.5" value="1"></label>
<button id="reset">Reset view</button>
<div class="legend">
<span><span class="swatch" style="background:linear-gradient(180deg,#60a5fa,#2563eb)"></span>Allocation</span>
<span><span class="swatch" style="background:#ef4444"></span>Pop</span>
<span><span class="swatch" style="background:#f59e0b"></span>Clear</span>
</div>
<span class="hint">Pan by dragging. Hover a block for details.</span>
</div>
<div id="y-axis"></div>
<div id="viewport"></div>
<div id="timeline-axis"></div>
</main>
<div id="tooltip"></div>
<script>
const LOG_URL = 'arena_log.json';
const viewport = document.getElementById('viewport');
const tooltip = document.getElementById('tooltip');
const zoomXInput = document.getElementById('zoomX');
const zoomYInput = document.getElementById('zoomY');
const KIND_COLORS = {
Push: '#3b82f6',
Pop: '#ef4444',
Clear: '#f59e0b',
};
function formatBytes(n) {
if (n >= 1024 * 1024) return (n / (1024 * 1024)).toFixed(2) + ' MiB';
if (n >= 1024) return (n / 1024).toFixed(2) + ' KiB';
return n + ' B';
}
async function loadLog() {
const res = await fetch(LOG_URL);
if (!res.ok) throw new Error(`Failed to load ${LOG_URL}: ${res.status} ${res.statusText}`);
return await res.text();
}
function parseTime(t) {
// Odin time format: "2006-01-02 15:04:05.999999999 +0000 UTC"
const iso = t
.replace(' ', 'T')
.replace(/(\.\d{3})\d*/, '$1')
.replace(' +0000 UTC', 'Z');
return Date.parse(iso);
}
function parseLog(text) {
// Try real JSON first; fall back to tolerant regex for Odin's "key = value" output.
try {
const data = JSON.parse(text);
if (Array.isArray(data)) {
return data.map(e => ({ ...e, timeMs: parseTime(e.time) }));
}
} catch (_) {}
const entries = [];
const re = /\{\s*"kind"\s*[:=]\s*"?(\w+)"?\s*,\s*"time"\s*[:=]\s*"?([^",]+)"?\s*,\s*"loc"\s*[:=]\s*"?([^",]+)"?\s*,\s*"pos"\s*[:=]\s*(\d+)\s*,\s*"size"\s*[:=]\s*(\d+)\s*\}/g;
let m;
while ((m = re.exec(text)) !== null) {
const time = m[2].trim();
entries.push({
kind: m[1],
time: time,
timeMs: parseTime(time),
loc: m[3].trim(),
pos: parseInt(m[4], 10),
size: parseInt(m[5], 10),
});
}
return entries;
}
function buildFrames(entries) {
const stack = [];
const frames = [];
let currentY = 0;
let peakY = 0;
let nextId = 0;
const minTimeMs = entries.length > 0 ? entries[0].timeMs : 0;
const lastTimeMs = entries.length > 0 ? entries[entries.length - 1].timeMs : 0;
const timeSpan = lastTimeMs - minTimeMs;
const tailPadding = timeSpan > 0 ? timeSpan * 0.1 : 100;
for (let i = 0; i < entries.length; i++) {
const e = entries[i];
if (e.kind === 'Push') {
const id = nextId++;
const frame = {
id,
startTime: e.timeMs,
endTime: lastTimeMs + tailPadding,
size: e.size,
origSize: e.size,
y: currentY,
kind: e.kind,
time: e.time,
loc: e.loc,
pos: e.pos,
isFreedTail: false,
};
stack.push(frame);
frames.push(frame);
currentY += e.size;
if (currentY > peakY) peakY = currentY;
} else if (e.kind === 'Pop') {
let remaining = e.size;
while (remaining > 0 && stack.length > 0) {
const top = stack[stack.length - 1];
if (top.size > remaining) {
// Partial reset: the top allocation is only partly freed.
// Keep the lower portion alive and record the freed tail as its own frame.
const freed = {
id: top.id,
startTime: top.startTime,
endTime: e.timeMs,
size: remaining,
origSize: top.origSize,
y: currentY - remaining,
kind: top.kind,
time: top.time,
loc: top.loc,
pos: top.pos + (top.size - remaining),
isFreedTail: true,
};
frames.push(freed);
top.size -= remaining;
currentY -= remaining;
remaining = 0;
} else {
stack.pop();
top.endTime = e.timeMs;
currentY -= top.size;
remaining -= top.size;
}
}
} else if (e.kind === 'Clear') {
while (stack.length > 0) {
const top = stack.pop();
top.endTime = e.timeMs;
currentY -= top.size;
}
}
}
return { frames, peakY };
}
function render(entries, frames, peakY) {
const minTime = entries.length > 0 ? entries[0].timeMs : 0;
const maxTime = entries.length > 0 ? entries[entries.length - 1].timeMs : 0;
const timeSpan = maxTime - minTime;
document.getElementById('stat-entries').textContent = entries.length;
document.getElementById('stat-peak').textContent = formatBytes(peakY);
document.getElementById('stat-bytes').textContent = formatBytes(Math.max(...entries.filter(e => e.kind === 'Push').map(e => e.pos + e.size), 0));
document.getElementById('stat-time').textContent = (timeSpan / 1000).toFixed(2) + ' s';
const xAxis = document.getElementById('timeline-axis');
xAxis.innerHTML = '';
const seconds = Math.max(1, Math.floor(timeSpan / 1000));
for (let s = 0; s <= seconds; s++) {
const tick = document.createElement('div');
tick.className = 'tick';
tick.textContent = s + 's';
xAxis.appendChild(tick);
}
const yAxis = document.getElementById('y-axis');
yAxis.innerHTML = '';
const labels = document.createElement('div');
labels.className = 'labels';
const yTicks = 5;
for (let i = yTicks; i >= 0; i--) {
const value = Math.round((peakY * i) / yTicks);
const tick = document.createElement('div');
tick.className = 'tick';
tick.textContent = formatBytes(value);
labels.appendChild(tick);
}
yAxis.appendChild(labels);
const spacer = document.createElement('div');
spacer.className = 'spacer';
yAxis.appendChild(spacer);
const baseWidth = timeSpan || 1;
const flameHeight = peakY || 1;
const axisMargin = flameHeight * 0.12;
const baseHeight = flameHeight + axisMargin;
const svgNS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(svgNS, 'svg');
const g = document.createElementNS(svgNS, 'g');
svg.appendChild(g);
viewport.innerHTML = '';
viewport.appendChild(svg);
let zoomX = parseFloat(zoomXInput.value);
let zoomY = parseFloat(zoomYInput.value);
let panX = 0;
let panY = 0;
let scaleX = 1;
let scaleY = 1;
function updateScale() {
const rect = viewport.getBoundingClientRect();
scaleX = rect.width / baseWidth;
scaleY = rect.height / baseHeight;
updateTransform();
}
function updateTransform() {
g.setAttribute('transform', `translate(${panX}, ${panY}) scale(${zoomX * scaleX}, ${zoomY * scaleY})`);
}
function draw() {
// Remove existing rects
while (g.firstChild) g.removeChild(g.firstChild);
function colorFor(kind) {
return KIND_COLORS[kind] || '#888';
}
function allocationColor(frame) {
const hue = 215;
const lightness = 45 + ((frame.id * 7) % 25);
if (frame.isFreedTail) {
return `hsla(${hue}, 70%, ${lightness + 25}%, 0.45)`;
}
return `hsla(${hue}, 75%, ${lightness}%, 1)`;
}
// Flame graph frames (only pushes produce live allocations)
for (const f of frames) {
const x = f.startTime - minTime;
const w = f.endTime - f.startTime;
if (w <= 0) continue;
const rect = document.createElementNS(svgNS, 'rect');
rect.setAttribute('x', x);
rect.setAttribute('y', flameHeight - (f.y + f.size));
rect.setAttribute('width', w);
rect.setAttribute('height', f.size);
rect.setAttribute('fill', allocationColor(f));
rect.setAttribute('class', 'frame');
rect.setAttribute('vector-effect', 'non-scaling-stroke');
rect.dataset.kind = f.kind;
rect.dataset.size = f.size;
rect.dataset.origSize = f.origSize;
rect.dataset.pos = f.pos;
rect.dataset.time = f.time;
rect.dataset.loc = f.loc;
rect.dataset.isFreedTail = f.isFreedTail;
g.appendChild(rect);
}
// Operation markers at the bottom so Pop/Clear are visible too
const markerY = flameHeight + axisMargin * 0.35;
for (const e of entries) {
const x = e.timeMs - minTime;
const marker = document.createElementNS(svgNS, 'line');
marker.setAttribute('x1', x);
marker.setAttribute('y1', markerY - axisMargin * 0.25);
marker.setAttribute('x2', x);
marker.setAttribute('y2', markerY + axisMargin * 0.25);
marker.setAttribute('stroke', colorFor(e.kind));
marker.setAttribute('stroke-width', '1.5');
marker.setAttribute('vector-effect', 'non-scaling-stroke');
g.appendChild(marker);
}
updateTransform();
}
draw();
updateScale();
window.addEventListener('resize', updateScale);
// Pan / zoom interaction
let isDragging = false;
let lastX = 0;
let lastY = 0;
viewport.addEventListener('mousedown', e => {
isDragging = true;
viewport.classList.add('grabbing');
lastX = e.clientX;
lastY = e.clientY;
});
window.addEventListener('mouseup', () => {
isDragging = false;
viewport.classList.remove('grabbing');
});
viewport.addEventListener('mousemove', e => {
if (isDragging) {
const dx = e.clientX - lastX;
const dy = e.clientY - lastY;
panX += dx;
panY += dy;
lastX = e.clientX;
lastY = e.clientY;
updateTransform();
}
if (e.target.classList.contains('frame')) {
const size = parseInt(e.target.dataset.size, 10);
const origSize = parseInt(e.target.dataset.origSize, 10);
const isFreedTail = e.target.dataset.isFreedTail === 'true';
let extra = '';
if (isFreedTail) {
extra = `<div class="row"><span class="key">Note</span><span class="value">Freed tail of a ${formatBytes(origSize)} allocation</span></div>`;
} else if (size !== origSize) {
extra = `<div class="row"><span class="key">Original</span><span class="value">${formatBytes(origSize)}</span></div>`;
}
tooltip.style.opacity = '1';
tooltip.innerHTML = `
<div class="kind" style="color:${KIND_COLORS[e.target.dataset.kind] || '#fff'}">${e.target.dataset.kind}</div>
${extra}
<div class="row"><span class="key">Size</span><span class="value">${formatBytes(size)}</span></div>
<div class="row"><span class="key">Pos</span><span class="value">${formatBytes(parseInt(e.target.dataset.pos, 10))}</span></div>
<div class="row"><span class="key">Loc</span><span class="value">${e.target.dataset.loc}</span></div>
<div class="row"><span class="key">Time</span><span class="value">${e.target.dataset.time}</span></div>
`;
tooltip.style.left = (e.clientX + 12) + 'px';
tooltip.style.top = (e.clientY + 12) + 'px';
} else {
tooltip.style.opacity = '0';
}
});
viewport.addEventListener('mouseleave', () => {
tooltip.style.opacity = '0';
});
viewport.addEventListener('wheel', e => {
e.preventDefault();
const delta = e.deltaY > 0 ? 0.9 : 1.1;
zoomX *= delta;
zoomY *= delta;
zoomX = Math.max(0.5, Math.min(20, zoomX));
zoomY = Math.max(0.5, Math.min(10, zoomY));
zoomXInput.value = zoomX;
zoomYInput.value = zoomY;
updateTransform();
});
zoomXInput.addEventListener('input', () => {
zoomX = parseFloat(zoomXInput.value);
updateTransform();
});
zoomYInput.addEventListener('input', () => {
zoomY = parseFloat(zoomYInput.value);
updateTransform();
});
document.getElementById('reset').addEventListener('click', () => {
zoomX = 1;
zoomY = 1;
panX = 0;
panY = 0;
zoomXInput.value = zoomX;
zoomYInput.value = zoomY;
updateTransform();
});
}
async function init() {
try {
const text = await loadLog();
const entries = parseLog(text);
if (entries.length === 0) throw new Error('No log entries found. Is arena_log.json in the same directory?');
const { frames, peakY } = buildFrames(entries);
render(entries, frames, peakY);
} catch (err) {
viewport.innerHTML = `<div class="error">${err.message}<br><br>Make sure you serve this page from a local web server so it can fetch arena_log.json.</div>`;
console.error(err);
}
}
init();
</script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
cd arena-flame-graph || ( echo "failed to cd"; exit 1 )
if command -v python3 >/dev/null 2>&1; then
PYTHON=python3
elif command -v python >/dev/null 2>&1; then
PYTHON=python
else
echo "error: Python not found" >&2
exit 1
fi
$PYTHON -m http.server