Compare commits

..

2 commits

Author SHA1 Message Date
b94c7dd3ac Add post: Why My Git Server 502'd (K8s Disk Pressure in Homelab)
Some checks are pending
Deploy Hugo site to Pages / build (push) Waiting to run
Deploy Hugo site to Pages / deploy (push) Blocked by required conditions
2026-11-10 01:37:31 +05:30
b1773b88c2 Update blog: add CHIP-8 and Snake Wasm posts, clean up placeholders 2026-11-10 01:08:36 +05:30
8 changed files with 493 additions and 57 deletions

View file

@ -0,0 +1,164 @@
---
title: "Why My Git Server 502'd: A Journey Through Kubernetes Disk Pressure"
date: 2024-11-10T01:35:00Z
draft: false
tags: ["Kubernetes", "Homelab", "DevOps", "Linux", "Networking"]
---
I went to push some changes to my self-hosted Git server tonight, and was greeted by a familiar, sinking HTTP status:
```bash
fatal: unable to access 'https://git.divyam.dev/divyam/divyam.dev/': The requested URL returned error: 502
```
502 Bad Gateway.
My homelab setup runs on a Raspberry Pi 5 cluster with Caddy acting as a reverse proxy in front of services hosted in Kubernetes (k3s). Whenever Caddy spits back a 502, it means Caddy itself is alive and well, but whatever upstream service it's trying to reach is either completely dead or refusing connections.
What started as a quick "let me check why the container died" turned into a neat tour of how Kubelet protects nodes from catastrophic disk failures.
---
## Down the Rabbit Hole
First, I checked if the Git namespace was even up:
```bash
kubectl get pod -n forgejo
```
The output was not encouraging:
```
NAME READY STATUS RESTARTS AGE
forgejo-9f576bf5f-5pcpq 0/1 Pending 0 10d
forgejo-9f576bf5f-dqp8l 0/1 ContainerStatusUnknown 7 (43d ago) 187d
forgejo-9f576bf5f-rtddd 0/1 Completed 0 37d
```
Not a single pod was running. Even worse, the newest replacement pod had been sitting in `Pending` for **ten days**.
A pod stuck in `Pending` means the Kubernetes scheduler hasn't assigned it to a node. To find out why, `kubectl describe` is always the first move:
```bash
kubectl describe pod forgejo-9f576bf5f-5pcpq -n forgejo
```
Down in the `Events` section:
```
Warning FailedScheduling default-scheduler
0/1 nodes are available: 1 node(s) had untolerated taint(s).
```
In Kubernetes, a **taint** allows a node to repel a set of pods. Unless a pod explicitly has a matching *toleration* in its spec, the scheduler refuses to put it there. On a multi-node cluster, the scheduler would simply place the pod on another healthy worker node. But on a single-node homelab machine, if your only node is tainted, everything grinds to a halt.
---
## Inspecting the Taint
To see what taint was placed on the node:
```bash
kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints
```
Output:
```
NAME TAINTS
reze [map[effect:NoSchedule key:node.kubernetes.io/disk-pressure timeAdded:2026-10-30T18:21:12Z]]
```
`node.kubernetes.io/disk-pressure`. And look at the timestamp: added on October 30th, exactly 10 days ago when the pod went pending.
---
## The Kubelet Eviction Threshold
Kubelet constantly monitors node resources (disk, memory, PID exhaustion). By default, if the root filesystem drops below a specific free-space threshold (typically 10% to 15% available space), Kubelet steps in:
1. It immediately marks the node with a `disk-pressure:NoSchedule` taint so no new workloads land on the starving drive.
2. It starts evicting pods that exceed their local storage limits or don't have guaranteed QoS to prevent the node from kernel-panicking or corrupting its filesystem.
Checking the disk on the Pi:
```bash
df -h /
```
```
Filesystem Size Used Avail Use% Mounted on
/dev/mmcblk0p2 117G 106G 6.7G 95% /
```
**95% full.** With only 6.7GB of free headroom on a 120GB drive, Kubelet had slammed the brakes to protect the system.
Between accumulated container layers in `/var/lib/containerd`, stale systemd journal logs, and miscellaneous large files that had piled up in user directories over months of uptime, the drive was completely starved.
---
## Clearing the Pressure
Recovering from disk pressure requires getting disk usage safely below Kubelet's eviction threshold. Once the available space rises back above the recovery margin, Kubelet automatically removes the taint without needing a node reboot.
A few quick cleanup steps reclaimed immediate space:
### 1. Pruning stale container images
Container runtimes tend to hoard old image layers from previous deployments:
```bash
sudo crictl rmi --prune
```
On a small node that's pulled multiple versions of apps, this can easily reclaim 10 to 20 GB.
### 2. Trimming systemd journal logs
If your services are chatty, systemd journals can quietly eat gigabytes of storage over a few months:
```bash
sudo journalctl --vacuum-size=100M
```
### 3. Evicting dead pods
Cleaning up orphaned pods in `Unknown` status allows Kubernetes to cleanly release their volume claim locks:
```bash
kubectl delete pod <old-pod-name> -n forgejo --force --grace-period=0
```
### 4. Clearing large local files
Finding and removing bulky, forgotten downloads and old archive dumps across the filesystem brought usage down well under 80%.
---
## The Recovery
Within roughly 60 seconds of the disk usage dropping below the threshold, Kubelet noticed the recovery:
```bash
kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints
```
```
NAME TAINTS
reze <none>
```
The taint vanished. The Kubernetes scheduler immediately woke up, evaluated the pending Forgejo pod, found an available node, and transitioned it:
```
Pending -> ContainerCreating -> Running (1/1)
```
Caddy detected the upstream backend was healthy again, 502s disappeared, and `git push` succeeded on the first try.
---
## What I Liked About This
A lot of people complain about Kubernetes being "overcomplicated for a homelab." And sure, if you just want to run a script, it's overkill.
But situations like this are a great reminder of why these mechanisms exist in the first place. Kubelet didn't crash, the Pi didn't lock up with a read-only filesystem, and SQLite didn't corrupt its database mid-write. The node saw danger, cordoned itself off gracefully, waited for human intervention to fix the underlying physical storage, and recovered autonomously the moment space was freed.
Understanding the layers—from reverse proxy down through the container scheduler to local inode usage—turns a mysterious 502 into a logical, predictable sequence of dominoes to follow.

View file

@ -5,17 +5,15 @@ draft: false
tags: ["WebAssembly", "C", "C++", "Emscripten"] tags: ["WebAssembly", "C", "C++", "Emscripten"]
--- ---
If you've spent any time working on performance-critical web applications, you've probably hit the performance ceiling of JavaScript. I ran into this heavily during my Google Summer of Code project working on Chromium's audio processing pipeline. We needed near-native speeds to process audio without stuttering, and standard JavaScript just wasn't going to cut it. If you've spent any time working on performance-critical web applications, you've probably hit the performance ceiling of JavaScript. I ran into this heavily during my Google Summer of Code project working on Chromium's audio processing pipeline. We needed near-native speeds to process audio buffers without dropping frames, and standard JavaScript just wasn't going to cut it.
Enter **WebAssembly** (Wasm). That's where **WebAssembly** (Wasm) comes in. It's a low-level bytecode format designed to run inside the browser sandbox at near-native speeds. It lets you write performance-sensitive routines in C, C++, or Rust, compile them to a `.wasm` module, and call them directly from your JavaScript frontend.
WebAssembly is essentially a low-level binary format that runs directly in the browser at near-native speeds. It lets us write code in systems languages like C, C++, or Rust, compile it, and run it right alongside our JavaScript. Here's a minimal walkthrough of taking a plain C program, compiling it to Wasm, and running it in a browser.
Today, I want to walk you through the absolute basics: taking a simple C program and running it in your browser. ## The Toolchain: Emscripten
## The Magic Tool: Emscripten To compile C or C++ targeting the web, you need an LLVM toolchain that outputs WebAssembly instead of native x86/ARM machine code. The standard toolchain for this is **Emscripten**. It takes your C/C++ source, compiles it into a `.wasm` binary, and generates the JavaScript loader code that allocates memory and boots up the module.
To bridge the gap between C/C++ and the web, we need a toolchain. The undisputed heavyweight champion here is **Emscripten**. It takes your C/C++ code, compiles it into a `.wasm` binary, and even generates the JavaScript "glue" code needed to load it into the browser.
Let's get it installed. Open your terminal and run: Let's get it installed. Open your terminal and run:
@ -77,8 +75,8 @@ Now, open your browser and head to `http://localhost:8000/hello.html`. If everyt
## Wrapping up ## Wrapping up
This is obviously just the tip of the iceberg. Printing a string is fun, but the real power of WebAssembly comes from porting massive C++ codebases (like audio engines, physics simulators, or databases) directly into the browser. This is obviously just the tip of the iceberg. Printing a string is fun, but the real power of WebAssembly comes from porting real C++ codebases (like game engines, audio processors, or physics simulators) directly into the browser.
In future posts, I'll dive into more realistic use cases—like how I used Wasm and WebWorkers to build lock-free ring buffers for Chromium, passing complex memory structures back and forth between JavaScript and C++. If you want to see a full interactive project in action, check out my follow-up post on [Porting a C++ Snake Game to the Browser with WebAssembly](/posts/snake-game-in-cpp-and-webassembly/).
Until then, happy hacking! Until then, happy hacking!

View file

@ -0,0 +1,149 @@
---
title: "I Built a CHIP-8 Emulator in JavaScript"
date: 2024-03-15T10:00:00Z
draft: false
tags: ["JavaScript", "Emulators", "Canvas", "WebAudio"]
---
If you've ever wanted to understand how computers actually work — not the "how to center a div" kind, but the "how does a CPU fetch and execute instructions" kind — building an emulator is one of the best ways to do it.
A while back I built a [CHIP-8 emulator](https://github.com/ahujadivyam/chip_eight.js) in vanilla JavaScript. No frameworks, no build tools, no npm install. Just the browser's Canvas API, Web Audio API, and a few hundred lines of code pretending to be a computer from 1977.
## What's a CHIP-8?
CHIP-8 is an interpreted programming language from the mid-1970s, originally designed for hobbyist microcomputers like the COSMAC VIP. It's not a real CPU — it's more like a virtual machine spec. But it has all the things that make a real system interesting: memory, registers, a stack, timers, input, graphics, and sound.
It's also the "hello world" of emulator development. The instruction set is small (35 opcodes), the display is tiny (64×32 pixels), and there's a massive community of ROMs and documentation. If you can emulate CHIP-8, you'll have the foundation to tackle Game Boy, NES, or anything else.
## The Architecture
Here's what you're emulating:
- **4KB of RAM** — that's it. The entire address space is `0x000` to `0xFFF`.
- **16 general-purpose 8-bit registers** (V0–VF). VF doubles as a flag register.
- **A 16-bit index register (I)** for pointing at memory locations.
- **A program counter (PC)** that starts at `0x200` — because the first 512 bytes are reserved for the interpreter itself (and the built-in font sprites).
- **A stack** for subroutine return addresses (16 levels deep).
- **Two timers** — a delay timer and a sound timer, both counting down at 60Hz.
- **A 16-key hex keypad** for input.
- **A 64×32 monochrome display** where pixels are either on or off.
I modeled each of these as a separate JavaScript class: `CPU`, `Renderer`, `Keyboard`, and `Speaker`. Clean separation of concerns, and it makes the code easy to reason about.
## The Core Loop
The CPU instruction cycle is straightforward: every tick, you fetch, decode, and execute.
Because CHIP-8 opcodes are two bytes long (big-endian), fetching means grabbing two consecutive bytes from memory at the current program counter and combining them into a 16-bit number:
```javascript
let opcode = (this.memory[this.pc] << 8) | this.memory[this.pc + 1];
this.pc += 2;
```
Decoding is just bit-masking. The highest 4 bits tell you the instruction category, and the remaining 12 bits hold register indices or memory offsets:
```javascript
let x = (opcode & 0x0F00) >> 8; // register index
let y = (opcode & 0x00F0) >> 4; // register index
let nn = opcode & 0x00FF; // 8-bit constant
let nnn = opcode & 0x0FFF; // 12-bit address
```
Execution is a switch statement. `6XNN` sets register `Vx = nn`. `1NNN` sets `PC = nnn`. `DXYN` draws a sprite. If the sound timer is greater than zero, you buzz the speaker. That's essentially it.
## Drawing Sprites
The most interesting opcode is `DXYN` — the draw instruction. CHIP-8 graphics are XOR-based. You don't "set" pixels, you *toggle* them.
Each sprite is 8 pixels wide and N pixels tall. The sprite data lives in memory at whatever address the I register points to. Each byte represents one row of 8 pixels, where each bit is a pixel:
```javascript
for (let row = 0; row < height; row++) {
let spriteByte = this.memory[this.I + row];
for (let col = 0; col < 8; col++) {
if (spriteByte & (0x80 >> col)) {
let px = (x + col) % 64;
let py = (y + row) % 32;
// Toggle pixel — if it was ON and gets turned OFF, set VF = 1
if (this.display[py * 64 + px]) {
this.registers[0xF] = 1; // collision!
}
this.display[py * 64 + px] ^= 1;
}
}
}
```
That VF collision flag is how games detect when things hit each other. Pong uses it to know when the ball hits a paddle. It's elegant — one bit of state doing the job of a physics engine.
The display buffer is a flat array of 2048 values (64 × 32). Each frame, I iterate over it and draw scaled-up rectangles on an HTML5 Canvas:
```javascript
render() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (let i = 0; i < this.display.length; i++) {
if (this.display[i]) {
let x = (i % 64) * this.scale;
let y = Math.floor(i / 64) * this.scale;
this.ctx.fillRect(x, y, this.scale, this.scale);
}
}
}
```
At 10× scale, you get a nice chunky 640×320 canvas that looks properly retro.
## The Keyboard Problem
CHIP-8 has a 16-key hex keypad (0–F). Obviously we don't have one of those lying around, so I mapped it to a 4×4 grid on a QWERTY keyboard:
```
CHIP-8 Keypad Keyboard
┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ C │ │ 1 │ 2 │ 3 │ 4 │
├───┼───┼───┼───┤ ├───┼───┼───┼───┤
│ 4 │ 5 │ 6 │ D │ │ Q │ W │ E │ R │
├───┼───┼───┼───┤ ├───┼───┼───┼───┤
│ 7 │ 8 │ 9 │ E │ │ A │ S │ D │ F │
├───┼───┼───┼───┤ ├───┼───┼───┼───┤
│ A │ 0 │ B │ F │ │ Z │ X │ C │ V │
└───┴───┴───┴───┘ └───┴───┴───┴───┘
```
One interesting edge case: the `FX0A` instruction. It's a *blocking* key wait — the CPU literally halts until the user presses a key. In a real system that's just a busy loop. In JavaScript, you can't block the main thread (and you shouldn't), so I used a callback pattern. When the CPU hits `FX0A`, it registers an `onNextKeyPress` callback and stops cycling. When a keydown event fires, the callback resolves, stores the key in the target register, and the CPU resumes.
## Sound
CHIP-8 sound is delightfully simple. There's one sound: a buzzer. It plays when the sound timer is greater than zero.
I used the Web Audio API to create a square wave oscillator at 440Hz — a nice harsh beep that feels appropriately retro. The only tricky part is dealing with browser autoplay policies: you can't start an `AudioContext` without user interaction, so the first keypress initializes the audio.
## The Game Loop
Everything comes together in a `requestAnimationFrame` loop:
```javascript
function step() {
for (let i = 0; i < 10; i++) {
cpu.cycle();
}
renderer.render();
requestAnimationFrame(step);
}
```
Running ~10 CPU cycles per frame at 60fps gives you roughly 600 instructions per second, which is in the ballpark of original CHIP-8 speed. ROMs load via the Fetch API as `ArrayBuffer`, get written into memory starting at `0x200`, and away you go.
Pong, Space Invaders, Tetris, Breakout — they all just work.
## Why Build This
I won't pretend this is useful software. Nobody needs another CHIP-8 emulator. But that's not the point.
The point is that after building this, I understood things I'd only read about before: how program counters work, why instructions are fixed-width, how XOR collision detection works, what "memory-mapped I/O" actually means in practice. You read about fetch-decode-execute in a textbook and it's abstract. You implement it and it clicks.
If you're into systems programming and want a weekend project that'll teach you more about machine architecture than a month of tutorials, build one yourself. Cowgod's [CHIP-8 technical reference](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM) is the canonical spec and has everything you need.
The full code is on GitHub: [github.com/ahujadivyam/chip_eight.js](https://github.com/ahujadivyam/chip_eight.js)

View file

@ -1,12 +1,11 @@
--- ---
title: "Networking Part 1: Why We Need Rules (and the OSI Model)" title: "Demystifying Networking: The OSI Model from a Developer's Perspective"
date: 2026-05-10T10:00:00Z date: 2024-01-10T10:00:00Z
draft: false draft: false
tags: ["Networking", "OSI Model", "Fundamentals"] tags: ["Networking", "OSI Model", "Fundamentals"]
series: ["Networking Fundamentals"]
--- ---
Computer networking is often taught in the most dry, academic way possible. You're immediately thrown a diagram with seven colored boxes (the OSI model) and told to memorize them for a test. Computer networking is often taught in the most dry, academic way possible. You're immediately thrown a diagram with seven colored boxes (the OSI model) and told to memorize them for an exam.
But if you actually build software, understanding *why* networks work the way they do changes how you write code. It changes how you debug timeouts, why you pick UDP over TCP for streaming, and why certain architectures scale while others crash under load. But if you actually build software, understanding *why* networks work the way they do changes how you write code. It changes how you debug timeouts, why you pick UDP over TCP for streaming, and why certain architectures scale while others crash under load.
@ -27,28 +26,29 @@ If *any* of those layers break—if we're in a vacuum, if I speak Russian and yo
Computers face the exact same problem, but they are infinitely dumber than we are. They need explicit, rigidly defined rules for every single step of communication. These rules are called **protocols**. Computers face the exact same problem, but they are infinitely dumber than we are. They need explicit, rigidly defined rules for every single step of communication. These rules are called **protocols**.
## The Stack of Rules (The OSI Model) ## The Seven Layers (and the Three You Actually Care About)
When a computer engineers in the 1970s and 80s were trying to get computers from different manufacturers to talk to each other, it was a nightmare. IBM computers couldn't talk to DEC computers because they didn't agree on the "language." In textbooks, you're taught all seven layers:
To fix this, the International Organization for Standardization (ISO) created a theoretical framework called the **OSI (Open Systems Interconnection) Model**. It breaks the massive problem of "getting a piece of data from Computer A to Computer B" into seven distinct, manageable layers. 1. **Physical:** Bits on a wire, fiber pulse, or radio wave.
2. **Data Link:** Ethernet frames, MAC addresses, local switches.
3. **Network:** IP packets, routing, subnets.
4. **Transport:** TCP, UDP, port numbers.
5. **Session:** Session management (rarely distinct in modern protocols).
6. **Presentation:** Serialization, encoding, TLS (now handled at the app level).
7. **Application:** HTTP, DNS, SSH, and the code you write.
Here they are, from the physical hardware up to the software you write: In practice, almost nobody distinguishes layers 5 and 6 anymore—the practical internet collapsed them into the application layer decades ago. But engineers still use the OSI numbers as universal shorthand:
1. **Physical Layer:** How do we send raw 1s and 0s over a wire, fiber optic cable, or radio wave? (Voltage levels, light pulses). - **Layer 3 (Network):** Can packets find their way from machine A to machine B? When your cloud VPC routing table is misconfigured or an MTU mismatch drops packets silently, that's an L3 problem.
2. **Data Link Layer:** How do two devices directly connected on the same physical network talk without talking over each other? (MAC addresses, Ethernet). - **Layer 4 (Transport):** Are connections establishing and staying alive? When someone talks about an "L4 load balancer," they mean routing raw TCP connections based on IP and port without decrypting or parsing the payload.
3. **Network Layer:** How do we send a message to a computer on a *completely different* network on the other side of the world? (IP addresses, Routers). - **Layer 7 (Application):** What does the data actually say? An "L7 load balancer" terminates TLS, inspects HTTP headers or path prefixes, and routes `/api` to one cluster and `/static` to an S3 bucket.
4. **Transport Layer:** How do we make sure the message actually arrived, and if it broke into pieces, how do we put it back together? (TCP, UDP).
5. **Session Layer:** How do we maintain an ongoing "conversation" between two computers?
6. **Presentation Layer:** How is the data formatted or encrypted? (ASCII, JPEG, TLS).
7. **Application Layer:** What is the actual software trying to do? (HTTP for web browsing, SMTP for email).
### Why do we care? ## Why Leaky Abstractions Matter
You might look at that list and think, *"I'm a web developer, I only care about Layer 7 (HTTP)."* You might spend 99% of your time writing application code at Layer 7. But networking abstractions are notoriously leaky:
But abstraction is a leaky bucket. When your API call drops, is it a Layer 7 problem (your server returned a 500 error)? Is it a Layer 4 problem (the TCP connection timed out)? Or is it a Layer 3 problem (the router dropped the packet because of a bad subnet configuration)? - When an API request hangs for exactly 30 seconds, is it an application deadlock (L7), an unhandled timeout on a pool of sockets (L4), or a firewall silently dropping packets rather than rejecting them (L3)?
- When connections randomly reset under heavy traffic, did your backend crash, or did an intermediate NAT gateway run out of connection tracking table entries?
Knowing how the layers stack on top of each other turns networking from "black magic" into a logical, debuggable system. Having a concrete mental model of the stack changes how you debug. You stop randomly restarting pods or tweaking application timeouts, and you start isolating the specific layer where the failure is actually happening.
In the next part of this series, we're going to dive into the bottom of the stack: **Layers 1 and 2**. We'll look at how your computer actually blasts electricity down an Ethernet cable to talk to your local router.

View file

@ -1,9 +0,0 @@
---
title: "Networking Part 2: Sending Electrons over Wires (Physical & Data Link)"
date: 2026-05-11T10:00:00Z
draft: false
tags: ["Networking", "Ethernet", "MAC"]
series: ["Networking Fundamentals"]
---
*Coming soon! In this post, we will cover MAC addresses, switches, Ethernet frames, and how electrons physically move data from NIC to NIC.*

View file

@ -1,9 +0,0 @@
---
title: "Networking Part 3: Crossing the Internet (The Network Layer)"
date: 2026-05-12T10:00:00Z
draft: false
tags: ["Networking", "IP", "Routing", "Subnets"]
series: ["Networking Fundamentals"]
---
*Coming soon! In this post, we will cover IP addresses, routers, subnets, and how packets travel across the global internet using BGP.*

View file

@ -1,9 +0,0 @@
---
title: "Networking Part 4: Delivering the Payload (Transport & Application)"
date: 2026-05-13T10:00:00Z
draft: false
tags: ["Networking", "TCP", "UDP", "HTTP"]
series: ["Networking Fundamentals"]
---
*Coming soon! In this post, we will cover TCP vs UDP, ports, and how the applications we write (like HTTP or WebSockets) actually consume this data.*

View file

@ -0,0 +1,152 @@
---
title: "Running a C++ Snake Game in the Browser with WebAssembly"
date: 2024-06-20T10:00:00Z
draft: false
tags: ["WebAssembly", "C++", "GameDev", "Emscripten"]
---
Compiling "hello world" from C to WebAssembly is fun for five minutes, but printing text to an emulated terminal doesn't really tell you what it feels like to build something interactive in Wasm.
I wanted to see what happens when you take real desktop C++ game code and shove it into a browser tab. So I built [snake_wasm](https://github.com/ahujadivyam/snake_wasm)—a classic Snake clone written in C++17 using `olcPixelGameEngine`, compiled via Emscripten into a `.wasm` binary that draws directly to an HTML5 canvas at 60 fps. No JavaScript game logic, no hand-written canvas glue.
Here are the parts of the build that were actually interesting to solve.
## The Engine: olcPixelGameEngine
If you've ever set up a C++ graphics project from scratch, you know how annoying dependency management can get. Linking SDL2 or GLFW, hunting down OpenGL loaders, and fighting CMake configurations across OSes gets old fast.
For this, I used **olcPixelGameEngine** (by David Barr / Javidx9). It's an entire 2D game engine packed into a single header file (`olcPixelGameEngine.h`). You `#define OLC_PGE_APPLICATION`, include the header in one `.cpp` file, and you get windowing, keyboard polling, and primitive drawing without installing ten different system packages:
```cpp
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
class Snake : public olc::PixelGameEngine {
public:
Snake() {
sAppName = "Snake WASM";
}
bool OnUserCreate() override {
ResetGame();
return true;
}
bool OnUserUpdate(float fElapsedTime) override {
HandleInput();
UpdateState(fElapsedTime);
Render();
return true;
}
};
```
You inherit from `olc::PixelGameEngine`, override `OnUserCreate()` for initialization and `OnUserUpdate()` for your frame step, and that's the whole harness. Even better: PGE has built-in support for Emscripten.
## Why Your Desktop Game Loop Freezes the Browser
On desktop, your game owns the thread. You typically write a blocking `while` loop that runs until the user closes the window:
```cpp
// Works on desktop. Freezes your browser tab instantly.
while (bGameRunning) {
ProcessInput();
UpdatePhysics();
RenderFrame();
}
```
If you compile that loop straight to WebAssembly, your browser tab dies immediately.
Browsers are single-threaded and event-driven. If your WASM module sits in a tight `while(true)` loop, execution never returns to the browser's JavaScript engine. That means the browser can't process DOM events, can't repaint the canvas, and can't even close the tab cleanly.
To make C++ play nice with the browser, you have to hand control back to the browser on every single frame. Emscripten does this through `emscripten_set_main_loop()`:
```cpp
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
void MainLoop() {
game.Step();
}
int main() {
emscripten_set_main_loop(MainLoop, 0, 1);
return 0;
}
#endif
```
Passing `0` as the frame rate tells Emscripten to hook directly into the browser's `requestAnimationFrame` loop. Each time the screen is ready to paint (~60 times a second on a standard display), the browser calls your C++ frame step, lets you update positions and draw pixels, and then immediately reclaims the thread to do the actual layout and render.
PGE wraps this internally when compiling with `-s __EMSCRIPTEN__`, but understanding *why* you can't have an infinite loop in Wasm saves a lot of head-scratching when porting desktop code.
## A Couple of Annoying Bugs Worth Mentioning
### The 180-Degree Neck Snap
If you store the player's direction and update it immediately on keypress, you run into a classic Snake bug:
Suppose the snake is moving **Right**. The player quickly taps **Up**, then **Left** before the next game tick fires. Both key events process, so `dir` becomes `Left`. The game tick fires, the snake tries to move left into its own neck, and you die instantly.
The fix is buffering the desired direction and only committing it when the logical game tick advances:
```cpp
// In HandleInput():
if (GetKey(olc::Key::UP).bPressed && currentDir != DOWN) nextDir = UP;
if (GetKey(olc::Key::LEFT).bPressed && currentDir != RIGHT) nextDir = LEFT;
// In TickGameLogic():
currentDir = nextDir;
```
### Tick Rate vs. Refresh Rate
Your monitor might refresh at 60Hz, 120Hz, or 144Hz. If you advance the snake's position on every `OnUserUpdate()`, the game runs at twice the speed on a high-refresh monitor.
You have to decouple drawing from game logic by accumulating elapsed time:
```cpp
fSnakeTimer += fElapsedTime;
if (fSnakeTimer >= fSnakeSpeed) { // e.g. 0.12s per grid step
fSnakeTimer -= fSnakeSpeed;
TickGameLogic();
}
```
The game renders at the monitor's native framerate, but the snake only moves once every 120ms.
## How C++ Pixels Actually Reach the Canvas
When you call `FillRect()` or `Draw()` in PGE, how does that reach an HTML `<canvas>`?
1. PGE translates the draw call into standard OpenGL ES 2.0/3.0 commands.
2. Emscripten's runtime intercepts those GLES calls and translates them 1:1 into browser **WebGL 2** calls.
3. The browser passes the WebGL commands directly to your GPU.
So you aren't manually poking an array of RGBA bytes across the WASM boundary into an HTML canvas context. The graphics pipeline is hardware-accelerated the whole way through.
## The Emscripten Build Command
Here is the compiler invocation that puts it all together:
```bash
em++ -std=c++17 -O2 \
-s ALLOW_MEMORY_GROWTH=1 \
-s MAX_WEBGL_VERSION=2 \
-s MIN_WEBGL_VERSION=2 \
main.cpp \
-o snake.html
```
A few flags that matter:
- `-s ALLOW_MEMORY_GROWTH=1`: Emscripten allocates a fixed 16MB heap by default. If your heap usage exceeds that, the app crashes with an out-of-memory error. This flag lets the linear memory page expand dynamically.
- `-s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2`: Forces Emscripten to target WebGL 2 exclusively, stripping out old WebGL 1 fallback glue.
- `-o snake.html`: Emscripten generates `snake.wasm`, `snake.js` (the loader runtime), and a default HTML shell containing the `<canvas>`.
Start a quick static server:
```bash
python3 -m http.server
```
Open `localhost:8000/snake.html`, and you have a native C++ binary running inside a browser tab.
The full source is on GitHub: [github.com/ahujadivyam/snake_wasm](https://github.com/ahujadivyam/snake_wasm)