City in a Bottle: 256-Byte Raycasting Marvel

BY Mark Howell 21 May 20244 MINS READ
article cover

Hello size coding fans. Today, I have something amazing to share: A tiny raycasting engine and city generator that fits in a standalone 256-byte HTML file. Here, I’ll share the secrets of how this magical program works.

Overview

This incredible program combines various concepts into a compact, 256-byte block of code. It's akin to solving a puzzle with several main pieces: the HTML code, frame update loop, rendering system, raycasting engine, and the representation of the city itself. Despite the complexities involved, the code mostly employs basic algebra, making it accessible even for those new to programming.
Below is a breakdown of the key elements and how they contribute to the program's dazzling output.

The Code Components

HTML Code

The HTML is minimalist, consisting of a canvas element with an `onclick` event to initiate the program. Here's a stripped-down version:
```html
<canvas style="width:99%" id="c" onclick="setInterval('for(…code…)', t=9)"></canvas>
The canvas ID is set to 'c' for easy JavaScript access, and the `onclick` event starts the update loop. The setInterval call initiates the frame updates every 9 milliseconds. This minor bug can cause multiple slow-running intervals if the canvas is clicked multiple times, but it’s non-critical for this tiny project.

JavaScript Code

The script encompasses a 199-byte payload that executes upon canvas click. This snippet is compatible with platforms like Dwitter and CapJS, making it easy to test and modify.
Key functions include:

  • Clearing and setting up the canvas dimensions.

  • Animating the scene by incrementing a time variable.

  • Calculating camera vectors for horizontal and vertical components.

  • Rendering the cityscape by iterating through loop variables to adjust pixel brightness based on raycasting principles.

Drawing each pixel based on calculated coordinates and brightness.

  • An illustration showing the step-by-step code execution and resulting visual output.

Breakdown of the Code

Camera Vector Calculation

  • Horizontal component 'a' is derived by mod operation and normalized between -1 and 1.

  • Vertical component 'b' uses similar calculations, adjusted for vertical perspective slant and offset.

Scene Animation

  • Initial positions (X, Y, Z) and a fog blending variable 'd' are set.

  • The scene shifts rightward over time using the time variable 't'.

Raycasting System

  • The inner loop handles ray advancement and collision checks.

  • Building heights and details are determined dynamically to shape the cityscape.

Shadow and Texture Creation

  • The dual-purpose loop handles initial raycasting and subsequent shadow checks by bouncing rays toward a light source.

  • Pixel textures are applied using bitwise operations and distance fading.

Visualization and Realism

Each pixel is drawn by combining several calculated values for grayscale rendering. Shadows are dynamically created to simulate ambient occlusion, noteworthy given the minuscule code size.

Achievement and Expansion

Even though it didn't rank high due to category errors at the Revision 2022 demo party, "City In A Bottle" stands as a remarkable example of ultra-compact coding. Further expansions include:

  • HD version on Shadertoy

  • Interactive tool by Daniel Darabos on Observable

Conclusion

This tiny 256-byte raycasting engine and city generator showcase immense potential within minimal code constraints. Keep experimenting and pushing technical boundaries, whether you're remixing on Dwitter or exploring new paradigms.

Continued Learning

If you’re interested:

  • Remix the code on Dwitter.

  • Explore further on CapJS.

  • Check out the real-time interactive tool on Observable.

Remember these 3 key ideas for your startup:

  1. Efficiency in Code: Achieving impressive results with minimal code helps save resources and accelerates development cycles. This demonstration proves that less can indeed be more.

  2. Innovative Thinking: Embracing unconventional coding challenges can lead to creative solutions and differentiate your products. Consider experimenting with ultra-compact coding to stand out in the market.

  3. Collaboration and Expansion: Leverage community platforms like Shadertoy and Observable for collaborative growth. Enhancing these initial innovations can lead to further breakthroughs.

    Edworking is the best and smartest decision for SMEs and startups to be more productive. Edworking is a FREE superapp of productivity that includes all you need for work powered by AI in the same superapp, connecting Task Management, Docs, Chat, Videocall, and File Management. Save money today by not paying for Slack, Trello, Dropbox, Zoom, and Notion.
    Let's continue to innovate with small yet impactful coding marvels! Keep coding, exploring, and pushing the boundaries of what can be achieved with concise codebases. Follow Frank Force on Twitter to stay updated on more coding magic.

article cover
About the Author: Mark Howell Linkedin

Mark Howell is a talented content writer for Edworking's blog, consistently producing high-quality articles on a daily basis. As a Sales Representative, he brings a unique perspective to his writing, providing valuable insights and actionable advice for readers in the education industry. With a keen eye for detail and a passion for sharing knowledge, Mark is an indispensable member of the Edworking team. His expertise in task management ensures that he is always on top of his assignments and meets strict deadlines. Furthermore, Mark's skills in project management enable him to collaborate effectively with colleagues, contributing to the team's overall success and growth. As a reliable and diligent professional, Mark Howell continues to elevate Edworking's blog and brand with his well-researched and engaging content.

Trendy NewsSee All Articles
CoverDecoding R1: The Future of AI Reasoning ModelsR1 is an affordable, open-source AI model emphasizing reasoning, enabling innovation and efficiency, while influencing AI advancements and geopolitical dynamics.
BY Mark Howell 26 January 2025
CoverSteam Brick: A Minimalist Gaming Console Redefines PortabilitySteam Brick: A modified, screenless Steam Deck for travel, focusing on portability by using external displays and inputs. A creative yet impractical DIY project with potential risks.
BY Mark Howell 26 January 2025
CoverVisual Prompt Injections: Essential Guide for StartupsThe Beginner's Guide to Visual Prompt Injections explores vulnerabilities in AI models like GPT-4V, highlighting security risks for startups and offering strategies to mitigate potential data compromises.
BY Mark Howell 13 November 2024
CoverGraph-Based AI: Pioneering Future Innovation PathwaysGraph-based AI, developed by MIT's Markus J. Buehler, bridges unrelated fields, revealing shared complexity patterns, accelerating innovation by uncovering novel ideas and designs, fostering unprecedented growth opportunities.
BY Mark Howell 13 November 2024
CoverRevolutionary Image Protection: Watermark Anything with Localized MessagesWatermark Anything enables embedding multiple localized watermarks in images, balancing imperceptibility and robustness. It uses Python, PyTorch, and CUDA, with COCO dataset, under CC-BY-NC license.
BY Mark Howell 13 November 2024
CoverJungle Music's Role in Shaping 90s Video Game SoundtracksJungle music in the 90s revolutionized video game soundtracks, enhancing fast-paced gameplay on PlayStation and Nintendo 64, and fostering a cultural revolution through its energetic beats and immersive experiences.
BY Mark Howell 13 November 2024
CoverMastering Probability-Generating Functions: A Guide for EntrepreneursProbability-generating functions (pgfs) are mathematical tools used in probability theory for data analysis, risk management, and predictive modeling, crucial for startups and SMEs in strategic decision-making.
BY Mark Howell 31 October 2024
CoverMastering Tokenization: Key to Successful AI ApplicationsTokenization is crucial in NLP for AI apps, influencing data processing. Understanding tokenizers enhances AI performance, ensuring meaningful interactions and minimizing Garbage In, Garbage Out issues.
BY Mark Howell 23 October 2024
Try EdworkingA new way to work from  anywhere, for everyone for Free!
Sign up Now