<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Malik Rashid Ali on Medium]]></title>
        <description><![CDATA[Stories by Malik Rashid Ali on Medium]]></description>
        <link>https://medium.com/@malikrashid82899?source=rss-27eb0a784009------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l8zbk-gnmEve_NRLbLBwvA.jpeg</url>
            <title>Stories by Malik Rashid Ali on Medium</title>
            <link>https://medium.com/@malikrashid82899?source=rss-27eb0a784009------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:16:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@malikrashid82899/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built a 3D Modeling Tool for AI Agents]]></title>
            <link>https://medium.com/@malikrashid82899/i-built-a-3d-modeling-tool-for-ai-agents-685aab026b6e?source=rss-27eb0a784009------2</link>
            <guid isPermaLink="false">https://medium.com/p/685aab026b6e</guid>
            <category><![CDATA[3d-modeling-for-ai]]></category>
            <category><![CDATA[3d-modeling-software]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[3d-modeling-for-agents]]></category>
            <dc:creator><![CDATA[Malik Rashid Ali]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 06:27:48 GMT</pubDate>
            <atom:updated>2026-10-11T06:27:48.443Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I gave Claude, Copilot and Codex the ability to build 3D models, see them, and fix their own mistakes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dFC57tJ98hRxR636pG7lNg.png" /></figure><p>Ask an AI coding agent to “make a 3D model of a chair” and you’ll usually get one of two things: an apology, or a Blender Python script that may or may not run. Even when the script runs, the agent has no idea what it made. It can’t see that a leg is floating, the backrest faces the wrong way, or the seat is twice as tall as it should be.</p><p>I wanted something better: an agent that builds a model, looks at it, measures it, fixes what’s wrong, and hands me a real file. So I built shapeforge, an open-source MCP server that gives AI agents a 3D modeling toolkit designed for how they actually work.</p><h3>Tools built for humans</h3><p>Most ways to make 3D models with AI fall into three buckets.</p><ol><li>Driving a human tool like Blender through scripts. It works, but the agent writes code against a huge API built around human concepts like selection, modes and modifier stacks, and it’s flying blind.</li><li>Code-CAD like OpenSCAD. It’s precise, but it’s a full programming language, and the feedback is mostly compile errors.</li><li>Neural text-to-3D services. They’re impressive, but you get an opaque blob of triangles. You can’t say “move the handle two centimeters left.”</li></ol><p>Research on LLMs generating CAD code pointed me in a clear direction. A <em>render → critique → fix</em> loop helps a lot. But visual feedback alone doesn’t fix wrong dimensions: models misjudge sizes in pictures, just like people do. They need numbers too.</p><p>That became the core idea: give the AI eyes and a ruler.</p><h3>What shapeforge does</h3><p>shapeforge is a single native program that speaks the <a href="https://modelcontextprotocol.io/">Model Context Protocol</a> (MCP), the standard way AI apps talk to tools. Once it’s connected, the agent gets 15 tools. Here’s what a session looks like:</p><ol><li>The agent describes parts with real dimensions: <em>“a box, 120 × 4 × 70 cm, at height 73 cm; four cylinders as legs.”</em> No vertices, no scripts.</li><li>It renders the model and gets one image with front, side, top and perspective views. Each view is labeled with which world axis points right and up, plus a measuring grid.</li><li>It inspects: exact sizes and positions, which parts touch, and warnings like <em>“backrest appears to float 1.2 mm above the seat.”</em></li><li>It fixes things with small edits, or with placement tools like <em>place this on that</em>, <em>mirror the left arm</em>, or <em>make eight spokes around the hub</em>.</li><li>It exports an OBJ file, with every part named and colored.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*1HFSfOzFQ-YDqfEONXCpdw.png" /></figure><p>That floating backrest isn’t a made-up example. While building the demo scenes, the render showed my chair facing backwards and a bowl that came out as a ring, and inspect caught a backrest sitting 1.2 mm above its seat. None of the three was obvious from the description. All three were obvious once the agent could look and measure.</p><h3>Parts, not polygons</h3><p>The scene is a list of named parts, each a small JSON object:</p><pre>{&quot;name&quot;: &quot;leg_front_left&quot;, &quot;shape&quot;: &quot;cylinder&quot;, &quot;radius&quot;: 0.03, &quot;height&quot;: 0.71,<br> &quot;position&quot;: [-0.54, 0.355, 0.29], &quot;parent&quot;: &quot;table&quot;, &quot;color&quot;: &quot;darkwood&quot;}</pre><p>The JSON is the source of truth, and meshes are derived from it on demand. That one decision makes many things simple:</p><ul><li>Undo is a list of snapshots.</li><li>Saving writes the JSON.</li><li>Moving a part never rebuilds its mesh, because meshes are cached by geometry, not position.</li></ul><p>Every edit is also <em>atomic</em>. If one part in a batch of twenty is invalid, nothing changes, and the agent gets a precise error, often with a typo hint: <em>“unknown key ‘sise’, did you mean ‘size’?”</em></p><h3>Two ways to make geometry</h3><p>Simple shapes are generated directly. Spheres, cylinders, cones and capsules are all one idea: a 2D outline spun around an axis, like a potter’s wheel. Extrusions take a polygon, triangulate it with <em>ear clipping</em>, and add walls.</p><p>Complex shapes use signed distance fields. A distance field describes a solid as a function, <em>how far is this point from the surface?</em>, with negative values inside. The beautiful part is that boolean operations become one-liners:</p><ul><li>union = min(a, b)</li><li>subtract = max(a, −b)</li><li>intersect = max(a, b)</li><li>smooth blend = a “soft minimum” that melts two shapes together, which is how a mug handle merges into the body</li></ul><p>To turn a distance field into triangles, I sample it on a 3D grid and use surface nets. Every grid cell the surface passes through gets one vertex, nudged onto the true surface with a few steps of Newton’s method, and neighboring vertices are stitched into quads.</p><p>That gives accurate but very dense meshes: a flat tabletop came out at 10,000 triangles. So a quadric error simplifier merges vertices wherever it doesn’t change the shape. Flat areas collapse to a handful of triangles, curves keep their detail, and the demo scene dropped from 241,000 triangles to 11,000 with the same volume.</p><h3>Rendering for an AI’s eyes</h3><p>The renderer is headless Vulkan: no window, just an offscreen image that’s read back and encoded as a PNG. On macOS, Vulkan runs on Metal through MoltenVK, which I link straight into the binary. Machines without a GPU fall back to a multi-threaded software rasterizer that produces the same picture.</p><p>The more interesting work was making the image <em>readable for a language model</em>:</p><ul><li>Orthographic views for checking proportions, plus a perspective view for depth.</li><li>Text labels saying which axis points where on screen, so the model can reason “the handle is on +X”.</li><li>A ground grid with its spacing printed, and an axis gizmo in every view.</li><li>Optional part labels and a highlight mode (“show only the legs”).</li></ul><h3>Doing the 3D math for the model</h3><p>LLMs are surprisingly bad at spatial arithmetic, so the placement tools do it exactly.</p><ul><li>place_on first rests one part on another&#39;s bounding box. Then it <em>sweeps</em> the part downward, casting rays between the two meshes, until it touches the real surface. A cube placed on a sphere settles onto the curve instead of hovering at the sphere&#39;s bounding box.</li><li>mirror_object reflects a part and all its children, renaming left to right as it goes.</li><li>array_object makes rows or rings of copies, composing rotations correctly.</li></ul><h3>Shipping a C++ tool to people who don’t compile</h3><p>Building it was half the work. The other half was making it one download with zero setup:</p><ul><li>No third-party libraries. The JSON parser, PNG encoder (including a small DEFLATE compressor) and MCP transport are all in the codebase.</li><li>Vulkan loaded at runtime, not linked. The binary starts on any machine and picks the GPU when one is available.</li><li>One binary per platform (macOS universal, Linux x64/arm64, Windows), built and tested by GitHub Actions on every release.</li><li>npm as a delivery truck. It’s not a JavaScript project, but npx is how most AI tools install MCP servers. A tiny Node launcher picks the right native binary for your system. This is the same pattern esbuild and Biome use.</li><li>One command to connect it. shapeforge install &lt;agent&gt; writes the config for Claude Code, Claude Desktop, Cursor, Windsurf, VS Code Copilot, Copilot CLI, OpenCode or Codex. Each one stores MCP settings differently: JSON with different keys, or TOML for Codex.</li></ul><h3>Try it</h3><pre>npx -y shapeforge install claude-code</pre><p>(or cursor, vscode, codex, opencode, claude-desktop, all), restart your agent, and ask:</p><blockquote>Model a small desk lamp with a round base, a two-part arm and a cone shade. Make sure nothing floats, then export it as OBJ.</blockquote><p>The project is open source under the MIT license: <a href="https://github.com/rashid5925/3d-model-generator">https://github.com/rashid5925/3d-model-generator</a></p><p>If you build something fun with it, I’d love to see it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685aab026b6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raycasting — The Old Trick That Never Gets Old]]></title>
            <link>https://medium.com/@malikrashid82899/raycasting-the-old-trick-that-never-gets-old-b8647c1a976c?source=rss-27eb0a784009------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8647c1a976c</guid>
            <dc:creator><![CDATA[Malik Rashid Ali]]></dc:creator>
            <pubDate>Thu, 07 May 2026 18:52:28 GMT</pubDate>
            <atom:updated>2026-05-08T10:38:02.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time I implement raycasting I feel the same thing. It’s not nostalgia exactly it’s respect. Respect for how elegant the solution is, how something so geometrically simple produces something that <em>looks</em> so good. You can go from zero to a first-person 3D world in a couple hundred lines of C, and every step of the way makes sense. That’s rare.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Duu5BLxv_Fjo&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fuu5BLxv_Fjo%3Ffeature%3Doembed" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9860c2c3fb13ed41e7eaee6dfe26b8d8/href">https://medium.com/media/9860c2c3fb13ed41e7eaee6dfe26b8d8/href</a></iframe><p>I’ve built this multiple times naive march, DDA, terminal version. Each time something clicks a little differently. Some connection between the math and the visual output becomes clearer. That’s why I keep coming back to it.</p><p>So let me walk you through how I did it. From the raw idea to colored walls to textures and even a terminal version. Follow along.</p><p>Complete</p><h3>The Core Idea</h3><p>Before any code, you need to understand what we’re actually doing.</p><p>You have a 2D map a grid. Some cells are walls, some are empty. The player stands somewhere in this grid and looks forward. For every vertical strip of pixels on the screen, you shoot a ray from the player’s eye in that direction. When the ray hits a wall, you measure how far it traveled. The farther the wall, the shorter the vertical line you draw on screen. Close wall = tall line, far wall = short line. Do this for every column across the screen width boom, you have a 3D world.</p><p>That’s the entire illusion.</p><h3>Map</h3><p>The world is a 30×30 integer grid. 0 means empty, anything above 0 is a wall type different numbers for different colors later.</p><pre>#define MAP_WIDTH 30<br>#define MAP_HEIGHT 30<br>#define CELL_SIZE 64<br><br>int world_map[MAP_HEIGHT][MAP_WIDTH] = {<br>    {1,1,1,1,1,1,1,1,1,1,...},<br>    {1,0,0,0,0,0,0,0,0,2,...},<br>    ...<br>    {1,1,1,1,1,1,1,1,1,1,...}<br>};</pre><p>Outer border is all 1s the boundary. Inside I have rooms and corridors with wall types 1, 2, 3. CELL_SIZE of 64 means each cell is 64 units wide in world space. The player&#39;s position is measured in those same units, not grid indices.</p><h3>Player</h3><p>Simple struct. Position in world space (floating point) and an angle in degrees.</p><pre>typedef struct {<br>    double x, y;<br>} Vector2D;<br><br>typedef struct {<br>    Vector2D position;<br>    double angle;<br>} Player;<br>Player player = { { 100.0, 100.0 }, 90.0 };</pre><p>Starting at (100, 100) puts us near the top-left corner. Angle 90° is downward in standard math coordinates that’s fine, we handle direction with cos and sin.</p><h3>The Naive Ray March</h3><p>The simplest way to cast a ray: start at the player, walk forward in tiny steps along the ray direction, check every step if you’ve hit a wall. When you do, return the distance.</p><pre>#define STEP_SIZE 0.05<br><br>RayResult cast_ray(Player *player, double ray_angle) {<br>    double distance = 0.0;<br>    RayResult result = {0, 0};<br>    while (1) {<br>        double x = player-&gt;position.x + distance * cos(ray_angle);<br>        double y = player-&gt;position.y + distance * sin(ray_angle);<br>        int map_x = (int)(x / CELL_SIZE);<br>        int map_y = (int)(y / CELL_SIZE);<br>        if (map_x &lt; 0 || map_x &gt;= MAP_WIDTH || map_y &lt; 0 || map_y &gt;= MAP_HEIGHT)<br>            break;<br>        if (world_map[map_y][map_x] &gt; 0) {<br>            result.distance = distance;<br>            result.hit_wall = world_map[map_y][map_x];<br>            return result;<br>        }<br>        distance += STEP_SIZE;<br>        if (distance &gt; 2000) break;<br>    }<br>    result.distance = MAX_DISTANCE;<br>    return result;<br>}</pre><p>x = x₀ + t·cos(θ), y = y₀ + t·sin(θ) that&#39;s a parametric ray equation. You start at the player&#39;s position and walk along the ray direction by t (the distance). At each step, divide by CELL_SIZE to get grid coordinates and check the map.</p><p>It works. It’s simple to understand. The downside is performancea step size of 0.05 means thousands of iterations per ray, and we&#39;re casting one ray per pixel column. For a 1200px window that&#39;s a lot. But for learning perfect.</p><h3>The Math Behind the Wall Height</h3><p>How do we turn a distance into a wall height on screen?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mu4qWKFMQGfpFUr5r27ZJg.png" /></figure><p>The idea is similar triangles. The real wall is CELL_SIZE units tall in the world. The screen is WINDOW_HEIGHT pixels tall. The relationship between them depends on how far away the wall is:</p><pre>line_height = (CELL_SIZE * WINDOW_HEIGHT) / corrected_distance</pre><p>Farther away → smaller line_height. Closer → taller. The wall strip is then centered vertically on screen:</p><pre>int draw_start = (WINDOW_HEIGHT / 2) - (line_height / 2);<br>int draw_end   = (WINDOW_HEIGHT / 2) + (line_height / 2);</pre><h3>The Fisheye Fix</h3><p>Here’s a subtle bug you’ll hit immediately. If you just use the raw ray distance to calculate wall height, you get a fisheye effect walls curve at the edges of the screen like a wide-angle lens. Try it once so you see it, then fix it.</p><p>The fix is to correct the distance by the cosine of the angle between the ray and the player’s forward direction:</p><pre>double corrected_dist = result.distance * cos(ray_angle - deg_to_rad(player.angle));<br>int line_height = (int)(CELL_SIZE * WINDOW_HEIGHT / corrected_dist);</pre><p>Without this, you’re using the radial ray length the actual distance from the player’s eye to the wall point. With it, you’re using the perpendicular distance to the wall plane. The perpendicular distance is what creates a flat, undistorted view.</p><h3>Drawing the Wall Strips</h3><p>For each pixel column i across the screen, we compute the ray angle, cast the ray, get back a distance and wall type, and draw a vertical line:</p><pre>for (int i = 0; i &lt; WINDOW_WIDTH; i++) {<br>    double ray_angle =<br>        deg_to_rad(player.angle) - deg_to_rad(FOV / 2) +<br>        ((double)i / (double)WINDOW_WIDTH) * deg_to_rad(FOV);<br><br>    RayResult result = cast_ray(&amp;player, ray_angle);<br>    double corrected_dist = result.distance * cos(ray_angle - deg_to_rad(player.angle));<br>    int line_height = (int)(CELL_SIZE * WINDOW_HEIGHT / corrected_dist);<br>    int draw_start = (WINDOW_HEIGHT / 2) - (line_height / 2);<br>    int draw_end   = (WINDOW_HEIGHT / 2) + (line_height / 2);<br>    if (draw_start &lt; 0) draw_start = 0;<br>    if (draw_end &gt;= WINDOW_HEIGHT) draw_end = WINDOW_HEIGHT - 1;<br>    Uint32 color;<br>    switch(result.hit_wall) {<br>        case 1: color = 0xFFFF0000; break; // Red<br>        case 2: color = 0xFF00FF00; break; // Green<br>        case 3: color = 0xFF0000FF; break; // Blue<br>        default: color = 0xFF646464; break; // Gray<br>    }<br>    double shading = 1.0 - (corrected_dist / 2000.0);<br>    draw_line(renderer, i, draw_start, i, draw_end, color, shading);<br>}</pre><p>FOV is 60 degrees, spread evenly across the screen width. The ray angle for column i is linearly interpolated across that range. Center of screen → forward direction. Left edge → angle - 30°. Right edge → angle + 30°. The shading is simple distance fog the farther the wall, the dimmer it gets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnT4B8D428Z2eJuF3md-kQ.png" /></figure><p>At this point you have a functioning 3D raycaster. Colored walls, distance shading, movement. It already feels good.</p><h3>DDA: The Right Way to Cast Rays</h3><p>The march-by-tiny-steps approach works but it’s brute force. The proper algorithm the one used in Wolfenstein 3D is DDA, Digital Differential Analysis. Instead of stepping by a tiny fixed amount, you jump directly from grid line to grid line. You only ever check cells you actually cross into. Exact and fast.</p><h3>The Math Behind DDA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2r03BZjVAWdEe1ZoR2xv5w.png" /></figure><p>The core insight: for any given ray direction, the distance between consecutive vertical grid crossings is always the same. Same for horizontal. So you precompute those intervals (delta_dist_x, delta_dist_y) and then just keep jumping.</p><pre>double delta_dist_x = (ray_dir_x == 0) ? 1e30 : fabs(1.0 / ray_dir_x);<br>double delta_dist_y = (ray_dir_y == 0) ? 1e30 : fabs(1.0 / ray_dir_y);</pre><p>1 / ray_dir_xthink about it. If your ray barely moves in x (small ray_dir_x), it takes a very long distance to cross a vertical grid line. If your ray is nearly horizontal (large ray_dir_x), it crosses vertical lines quickly. The reciprocal captures exactly that.</p><p>Then we initialize how far the ray needs to travel to reach the <em>first</em> grid line in each direction from the player’s current sub-cell position:</p><pre>if (ray_dir_x &lt; 0) {<br>    step_x = -1;<br>    side_dist_x = (pos_x - map_x) * delta_dist_x;<br>} else {<br>    step_x = 1;<br>    side_dist_x = (map_x + 1.0 - pos_x) * delta_dist_x;<br>}</pre><p>Then the main loopalways step toward whichever grid intersection is closest:</p><pre>while (1) {<br>    if (side_dist_x &lt; side_dist_y) {<br>        side_dist_x += delta_dist_x;<br>        map_x += step_x;<br>        result.side = 0; // hit a vertical wall side<br>    } else {<br>        side_dist_y += delta_dist_y;<br>        map_y += step_y;<br>        result.side = 1; // hit a horizontal wall side<br>    }<br>    if (world_map[map_y][map_x] &gt; 0) {<br>        result.hit_wall = world_map[map_y][map_x];<br>        break;<br>    }<br>}</pre><p>When we hit a wall, side tells us whether we came in through a vertical face or a horizontal face. That matters for texturing. The exact distance is then computed from which side we hit:</p><pre>if (result.side == 0)<br>    result.distance = (side_dist_x - delta_dist_x) * CELL_SIZE;<br>else<br>    result.distance = (side_dist_y - delta_dist_y) * CELL_SIZE;</pre><p>We subtract delta_dist because side_dist_x already went past the wall when we detected the hit we want the distance to the wall, not beyond it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHJ0SoS3hXBRjmni2teqEA.png" /></figure><p>The key advantage over the naive march: no tiny steps, no approximation errors, and we get the exact fractional position along the wall face (wall_x). That&#39;s what enables texture mapping.</p><h3>Texture Mapping</h3><p>This is where it gets satisfying. wall_x is the fractional position along the wall face a value between 0 and 1 representing where horizontally the ray hit the wall. We use it to pick a column from the texture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvmVajWP3Fnn9QuXHUkyFw.png" /></figure><p>Computing wall_x from the DDA hit:</p><pre>double wall_x;<br>if (result.side == 0)<br>    wall_x = player-&gt;position.y / CELL_SIZE + result.distance / CELL_SIZE * ray_dir_y;<br>else<br>    wall_x = player-&gt;position.x / CELL_SIZE + result.distance / CELL_SIZE * ray_dir_x;<br>result.wall_x -= floor(result.wall_x); // keep only the fractional part</pre><p>Then in the rendering loop:</p><pre>int tex_x = (int)(result.wall_x * (double)TEX_WIDTH);<br>// flip texture direction based on which side we hit and ray direction<br>if (result.side == 0 &amp;&amp; cos(ray_angle) &gt; 0) tex_x = TEX_WIDTH - tex_x - 1;<br>if (result.side == 1 &amp;&amp; sin(ray_angle) &lt; 0) tex_x = TEX_WIDTH - tex_x - 1;<br>double step = 1.0 * TEX_HEIGHT / line_height;<br>double tex_pos = (draw_start - WINDOW_HEIGHT / 2 + line_height / 2) * step;<br>for (int y = draw_start; y &lt;= draw_end; y++) {<br>    int tex_y = (int)tex_pos &amp; (TEX_HEIGHT - 1);<br>    tex_pos += step;<br>    Uint32 color = texture[tex_x][tex_y];<br>    Uint8 r = ((color &gt;&gt; 24) &amp; 0xFF) * shading;<br>    Uint8 g = ((color &gt;&gt; 16) &amp; 0xFF) * shading;<br>    Uint8 b = ((color &gt;&gt; 8) &amp; 0xFF) * shading;<br>    SDL_SetRenderDrawColor(renderer, r, g, b, 0xFF);<br>    SDL_RenderDrawPoint(renderer, i, y);<br>}</pre><p>The textures are loaded from BMP files into a Uint32[TEX_WIDTH][TEX_HEIGHT] array at startup:</p><pre>SDL_Surface* loadedSurface = SDL_LoadBMP(&quot;texture-1.bmp&quot;);<br>SDL_Surface* formattedSurface = SDL_ConvertSurfaceFormat(<br>    loadedSurface, SDL_PIXELFORMAT_RGBA8888, 0<br>);<br>Uint32* pixels = (Uint32*)formattedSurface-&gt;pixels;<br>for (int y = 0; y &lt; TEX_HEIGHT; y++) {<br>    for (int x = 0; x &lt; TEX_WIDTH; x++) {<br>        int src_x = (x * width) / TEX_WIDTH;<br>        int src_y = (y * height) / TEX_HEIGHT;<br>        texture_1[x][y] = pixels[src_y * width + src_x];<br>    }<br>}</pre><p>Different wall types get different textures texture_1, texture_2, texture_3. The texture flip logic on tex_x is easy to miss but important without it, you get mirrored textures on half the walls depending on which direction you hit them from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyvXVb_dUFed1XVwnA_wyA.png" /></figure><h3>Terminal Version</h3><p>Same algorithm, zero dependencies. Instead of SDL pixels you fill a character buffer. Instead of colors you use ASCII characters to represent shading from space (far/dark) to @ (close/bright).</p><pre>char shades[] = &quot; .:-=+*#%@&quot;;<br>int shade_index = (int)(dist / 2000.0 * 9);<br>char c = shades[9 - shade_index];<br>for (int y = start; y &lt;= end; y++) {<br>    screen[y][x] = c;<br>}</pre><p>Clear the terminal with ANSI escape \033[H and print the buffer each frame. Input is handled with termios set to raw non-blocking mode:</p><pre>new_t.c_lflag &amp;= ~(ICANON | ECHO);<br>tcsetattr(STDIN_FILENO, TCSANOW, &amp;new_t);<br>int flags = fcntl(STDIN_FILENO, F_GETFL, 0);<br>fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);</pre><p>WASD to move, q to quit. A loop sleeps for ~16ms between frames. That&#39;s it a 3D raycaster in 150 lines of pure C with zero dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muDU9EW3HCV-yOGe8YKgQA.png" /></figure><p>For the SDL version: W/S to move forward/back, A/D to strafe. Mouse drag (left button held) rotates the camera. Movement is discrete per keypress one thing you&#39;d want to improve for a proper game.</p><p>The terminal version uses A/D to rotate left/right instead of strafe, which makes more sense without a mouse.</p><h3>Final Thoughts</h3><p>Raycasting is one of those algorithms that rewards you immediately. You write 50 lines and you have something visually impressive you can walk around in. You add textures and it looks like an actual game. Every addition has a direct visible payoff.</p><p>That’s rare. Most things you build don’t give you that feedback you work for hours before you see anything meaningful. Raycasting isn’t like that. It’s responsive. Every line you write changes what you see on screen.</p><p><em>Built with C and SDL2. Tested on macOS. The terminal version runs anywhere with a POSIX terminal.</em></p><h3>Source Code</h3><p>You can find the complete implementation, including both the SDL2 and Terminal versions, here:</p><p><a href="https://github.com/rashid5925/raycasting">https://github.com/rashid5925/raycasting</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8647c1a976c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>