Developing Graphical Applications in a UEFI Environment: A Practical Guide with AI Programming Assistants
This guide walks through building a vertical scrolling shooter game that runs in the UEFI firmware layer, using AI programming assistants as a core part of the workflow. It covers the five technical constraints of UEFI graphics development, two rounds of iterative implementation (a runnable baseline, then Chinese rendering, art, and gameplay enhancements), and a retrospective on what AI assistants handle well versus what developers must own. You will find reusable prompt strategies, engineering practices, validation checklists, and a six-dimension framework for evaluating AI assistants in firmware projects. It is written for developers who want to understand both how to ship low-level graphics software and how to work effectively with AI coding tools on high-constraint tasks.
1. Background: What Does It Mean to Write a Graphical Application at the Firmware Layer?
When many developers hear “UEFI,” the first image that comes to mind is the motherboard setup screen and the boot menu. UEFI is the firmware interface specification that runs before the operating system loads, but its capabilities extend far beyond bootstrapping. Vendors commonly use it to build graphical diagnostic interfaces, system recovery tools, boot-branding animations, and touch interactions. In the industry, graphical applications running under the UEFI Shell are also popular as practice projects, used to test a developer’s understanding of the low-level platform.
You can push such a practice project one step further: instead of a simple Breakout clone or Snake, build a vertical scrolling shooter. The reason is that a shooter introduces dynamic spawning and destruction of entities, multiple target types, collision detection, wave progression, and staged levels. Together these expose far more edge cases at the platform boundary.
Building a graphical application under UEFI means satisfying several tightly coupled constraints at once:
- Runtime: No operating system, no standard C library, no processes, and no scheduler.
- Display: No OS-level graphics framework. You rely only on the graphics output protocol (Graphics Output Protocol, GOP) provided by the firmware.
- Resources: Assets such as glyph tables and textures must be bundled in, and memory is limited to what the firmware reserves.
- Correctness: A single crash means the user sees a frozen black screen or cannot even reach the boot menu, so error handling must be designed up front.
Precisely because the constraints are numerous and the documentation is scattered, this kind of project has often been treated as an “expert-level” task. Lately, however, AI programming assistants are becoming a routine part of how developers approach this work. This article follows one complete shooter-game development process, structured in two rounds of progress—environment setup with a baseline version, then a round of Chinese language, art, and gameplay enhancements. From this, it abstracts reusable prompt methods, engineering practices, and a framework for evaluating capabilities. In doing so, it answers a more fundamental question: what does an AI programming assistant actually do for the developer, and what must the developer still get right on their own?
2. The Technical Foundation: Five Key Constraints of UEFI Graphical Applications
2.1 The Runtime Model: No main, No libc
A UEFI application has no main function and no notion of a process in the operating-system sense. It is essentially an executable module in PE/COFF format, loaded and executed by the firmware within the UEFI Shell or during the boot flow. The entry point is defined by the platform firmware or the build system of the firmware framework. A common entry signature in UEFI C development looks like this:
EFI_STATUSEFIAPIGameMain (IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE *SystemTable);
There are two parameters. ImageHandle identifies the current image and is used for follow-up operations such as unloading. SystemTable is the gateway through which the application accesses all firmware capabilities; console input and output (ConIn, ConOut), boot services, and runtime services all hang off it.
The entry point typically returns an EFI_STATUS: EFI_SUCCESS on success, or an EFI_ERROR with an error mask on failure. But the return value does not fully capture how the program actually ran. Once the Shell receives EFI_SUCCESS, it returns directly to the prompt. The game may have flashed a single frame and ended, yet the Shell reports no error at all. For this reason, you must define clear exit conditions and clean up resources on exit.
Three more points related to the runtime model tend to be hotspots for coding-standard accidents:
- Standard library disabled: The UEFI build environment has no
malloc/freeand no string library by default. You need to switch toAllocatePool/FreePool, together with the memory and string functions provided by the firmware libraries, and confirm whether the relevant dependencies must be pulled into the template files. - Explicit calling convention: UEFI C uses the
EFIAPImacro to mark functions called by the firmware; the calling convention is decided by compiler options according to the architecture. On certain platforms, omittingEFIAPIcan cause argument-passing errors and other crashes that are difficult to trace. - Memory types and lifetimes: When allocating memory, you must choose among the memory types provided by the firmware. Boot-related memory (such as
EfiBootServicesData) becomes unavailable once the firmware’s boot services are torn down. Large static data such as glyph tables and atlases requires estimating firmware capacity.
VOID *Buffer = NULL;UINTN BufferSize = Width * Height * sizeof (UINT32);/* Allocate the off-screen canvas: pick EfiBootServicesData so it staysvalid after Boot Services exit */Status = gBS->AllocatePool (EfiBootServicesData, BufferSize, &Buffer);if (EFI_ERROR (Status)) {return Status; /* Fail immediately on low memory; never dereference a null pointer */}
2.2 Graphics Output: GOP and the Kernel-Mode Framebuffer
GOP is the standard graphics output protocol defined by the UEFI specification, and it is the most common route for a UEFI application to draw a user interface. Its core interfaces fall into two groups:
QueryMode/SetMode: enumerate and set display modes.Blt: complete fill, copy, and readback operations via block transfer.
Blt supports three operations:
EfiBltVideoFill: fill a rectangle with a specified color.EfiBltBufferToVideo: draw a memory buffer to the screen.EfiBltVideoToBltBuffer: read screen content back into a buffer.
There is also a direct path. After SetMode succeeds, Mode->FrameBufferBase and FrameBufferSize on the protocol instance give you the framebuffer address and size for the current mode. You can write pixels just like a plain array, skipping the call overhead of Blt.
Below is a common depth structure that suits most vertical scrolling shooters:
- Fix the logical resolution to a vertical canvas, such as 240×320.
- Each frame, complete all drawing into the off-screen canvas first.
- Then blit the whole thing to the screen via
EfiBltBufferToVideo, or scale it up to the screen width and center it, placing the status bar in the padding on either side.
There are three reasons to adopt this structure:
- Default resolutions differ widely across platforms, so a fixed resolution avoids coordinate transforms at arbitrary resolutions.
- A single
Bltputs everything on screen at once, so the image never shows a “drawing as it displays” tearing effect. - The same rendering logic migrates between an emulator and real hardware.
A few points deserve extra attention in practice:
- Pixel format: The UEFI C framebuffer is a byte-order structure grouped into 32-bit units, and the integer value it maps to may differ across architectures. Avoid performing integer-level color arithmetic.
- Default color meaning: The color used by
EfiBltVideoFillcomes from the first 3 bytes of the color parameter passed to theBltoperation. Under different_PIXEL_formats, the RGB channel order it corresponds to may differ, so you should verify the actual colors after drawing. - Mode differences: The mode number for a given resolution is not necessarily the same across platforms. First iterate the available modes via
MaxModeandQueryMode, matching by width and height, rather than hardcoding a mode number.
2.3 Input: Polling-Based Keyboard, No Event Queue
Console input in UEFI provides key codes through ConIn. Control characters such as arrow keys and function keys are reflected in the scan code (ScanCode), while ordinary characters land in the UnicodeChar field. The key code is a single-byte CHAR16 and cannot directly carry all Chinese characters, so menu text should use Unicode-encoded resources, or switch Chinese to icons, abbreviated pinyin keys, and other schemes based on common key codes.
Each call to Read returns only one key code, and EFI_NOT_READY means no key is currently pressed. This has three implications:
- It is a polling model with no keyboard event queue, so the program must maintain key state itself.
- To keep responding to arrow keys, you typically poll several times per second, so the render cadence should be decoupled from input polling.
- Repeated key events from a long press can flood the game loop, so you need debouncing and rate limiting.
The most direct approach is to read at least once per frame and use the repeated reports to build a “pressed / held / released” state machine. If you need to capture modifier combinations such as Ctrl and Alt, you can choose the protocol with input extensions (EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL). Beyond the extended key codes, it also provides key state, toggle state, and a reset function. Whether you can use it depends on whether the platform has the protocol installed, so you must check before use.
2.4 Resources and Rendering: Glyph Tables, Atlases, and Dirty Rectangles
In an OS application, resources such as fonts and images are generally supplied by the system. Under UEFI, displaying Chinese requires bundling bitmap glyph tables, and assets usually need to be exported as a resource table in advance, flashed with the image or packaged for distribution. Where the resources come from, how much space they occupy, and what encoding they use all require decisions made up front.
On the rendering side, there is a common misconception: that per-pixel drawing can be moved to UEFI directly. When writing to the framebuffer, every pixel drawn means recomputing the row offset and writing to memory. Blt also has fixed overhead, especially when vertically mirroring or scaling an entire full-screen region.
Two general optimization approaches:
- Dirty rectangles: Draw only the rectangles that changed this frame to the screen.
- Fixed frame rate: You do not need to chase the maximum frame rate; what matters is a stable frame interval.
/* Draw the changed region of the off-screen canvas (BltBuffer) to the screen (Video).SrcX/Y and DstX/DstW describe the source and target regions respectively,so even if the canvas is centered and scaled, no coordinate conversion isneeded on the drawing side */Status = Gop->Blt (Gop,&Canvas, /* off-screen canvas */EfiBltBufferToVideo,DirtyRect->X, DirtyRect->Y, /* source region origin */DirtyRect->X, DirtyRect->Y, /* target region origin */DirtyRect->W, DirtyRect->H, /* region dimensions */0);if (EFI_ERROR (Status)) {/* Log, then decide whether to exit; never keep using this framebuffer */}
2.5 Validation: The Simulator Is Not a Universal Answer
Developing firmware applications on real hardware means one cycle of build, flash, plug/unplug, boot, and observe—validating a single change can take several minutes, with no way to set breakpoints. Emulating the firmware environment in a virtual machine dramatically shortens this loop, but it cannot validate real GPU drivers, display synchronization, USB input-device differences, or performance issues.
A pragmatic approach is to establish a layered validation flow of “fast iteration on the simulator → confirm key milestones on real hardware,” supported by the following mechanisms:
- Zero tolerance for compiler warnings: Treating warnings as errors makes the development process far more solid.
- Deterministic input replay: Write input sequences into a script and replay them automatically to guarantee repeatability of each validation run.
- Observable errors: Output logs at key failure points; the serial port or the emulator console are common channels.
3. Round One: Building a Runnable Baseline from Scratch
3.1 Stating the Goal Clearly Up Front: Requirement Boundaries and Acceptance Criteria
An AI programming assistant tends to “freestyle” on vague requirements. The more explicit you are about the game theme, gameplay mechanics, graphics approach, platform limits, and deliverables, the less rework you will incur.
Start with a structured requirement description that covers at least: runtime environment (UEFI Shell), graphics approach (GOP), gameplay (vertical shooter, including player movement and firing, enemy spawning, collision detection, health bar, lives, score), constraints (no audio, Simplified Chinese UI), how it runs (firmware emulation environment), and acceptance criteria (it boots, is interactive, and runs repeatably).
Alongside this, maintain a project conventions file that acts as the assistant’s “long-term memory” across multiple rounds of conversation. It should cover at least:
- Target platform, firmware build system, and emulator build steps.
- Directory structure and module division.
- Coding conventions (explicit types,
EFIAPImarking, disabled standard library, and so on). - A unified rule: every functional module includes
.c/.hsource files, the corresponding build-description fragment, and a unit-test entry point. - After each feature is completed, update the conventions file and the run instructions in the README.
3.2 Environment Setup: Have the Assistant Survey First, Then Act
Setting up a firmware development environment often takes more time than writing the game logic. Common tasks include: installing the toolchain, obtaining the source of an open-source firmware framework, configuring the build environment for the emulation platform components, and resolving issues such as missing dependencies, invalid paths, and environment variables that did not take effect.
For an AI programming assistant, this kind of problem is a typical “high information density, low innovation” task—provided the assistant can see the environment clearly first. A recommended order:
- Survey first: Have the assistant check the OS, existing compiler version, target architecture, and disk space.
- Then plan: Produce a step-by-step installation and configuration list, marking steps that require network access or administrator privileges.
- Then execute: Run the list step by step, verifying the artifact after each step.
- Finally confirm: Record a reproducible “environment setup command list” in the project documentation.
Draw one boundary in advance. An AI programming assistant can look up documentation, generate scripts, and locate errors, but it cannot replace the developer’s judgment on the following: the target platform architecture, the firmware’s secure-boot policy, signing requirements, license compliance, and resource copyright.
Building a minimal firmware package in the emulation platform as a “compiles, boots, and displays” baseline is also well worth doing. It surfaces most environment-related problems, avoiding later interference from environment faults while debugging game logic.
3.3 Baseline Implementation: A Minimal Skeleton with Clear Layering
A playable baseline does not need a complex architecture, but it must have several clear boundaries:
- Platform layer: Initialize GOP, read keys, timing, logging, and abstract away platform differences.
- Rendering layer: Canvas, dirty rectangles, sprite drawing.
- Entity and logic layer: Player, enemies, bullets, collisions.
- Flow layer: Initialization, main loop, exit cleanup.
A reusable main-loop skeleton looks like this:
EFI_STATUSEFIAPIGameMain (IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE *SystemTable){EFI_STATUS Status;UINT64 Deadline = 0;/* 1. Init: select mode, allocate the off-screen canvas, load resources.Exit immediately if any step fails */Status = GameInit (SystemTable);if (EFI_ERROR (Status)) {return Status;}/* 2. Main loop: fixed logical step + fixed-frame-rate present,with input polling running independently */while (!GameShouldExit ()) {UINT64 Now;Status = GetCurrentTick (&Now); /* timing service from the platform */if (EFI_ERROR (Status)) {break;}if (Now < Deadline) {GamePollInput (); /* sample input independent of render cadence */gBS->Stall (2000); /* microseconds; yield the CPU, avoid busy-wait */continue;}Deadline = Now + TICKS_PER_FRAME; /* TICKS_PER_FRAME is the duration of one frame */GamePollInput ();GameUpdate (); /* logic advance: move, collide, spawn, score */GameRender (); /* draw into the off-screen canvas first */GamePresent (); /* present only dirty rects; end if GOP Blt fails */}/* 3. Exit: release resources first, then return a clear exit code */GameCleanup ();return EFI_SUCCESS;}
Four points in the skeleton are easy to get wrong:
- Handling a failed present: GOP’s
Bltreturns error codes such asEFI_INVALID_PARAMETER. If the loop only prints the error without exiting, the game spins idle while flooding the log. A safer approach is to record the error, clean up resources, and return a failure. - Busy-waiting: Most firmware environments have no idle task, so a busy-wait pins the CPU at 100% and noticeably raises power consumption. A sleep interval under a fixed frame rate both yields the CPU and stabilizes the frame rate.
- Object lifetimes: Enemies, bullets, and explosion particles are objects created and destroyed frequently. Using an object pool avoids the memory fragmentation caused by frequent allocation and deallocation, and keeps memory-management complexity out of the game logic.
- Collision detection: A vertical shooter has many bullets, and naive pairwise comparison grows quadratically with the object count. First classify by “player bullets vs. enemies,” “enemy bullets/enemies vs. player,” and “player vs. items,” then use bounding-box broad-phase culling followed by pixel-level precise checks.
3.4 The Round-One Validation Checklist
A baseline that “runs” is not the same as one that is “correct.” Cover at least the following validation items:
- Launch at a non-target resolution and confirm the image is not cropped and there is no misaligned black border.
- Hold the arrow keys for 30 seconds and check for dropped or sticky key codes.
- Idle for a long time (for example, ten minutes) and watch whether memory usage keeps growing.
- Confirm the game exits normally after the player dies, after lives run out, and after clearing the game, and that the Shell returns to normal afterward.
- Relaunch after exit and confirm the state is clean (no leftover data from the previous session).
4. Round Two: Engineering Improvements for Chinese, Art, and Gameplay
4.1 Chinese Rendering: Treating Glyphs as Resources
The difficulty of Chinese display is not “whether it can be shown” but the balance among glyph source, encoding, and size.
- Source: You need a glyph set covering all UI text. Given the licensing scope of font files, an open-source commercially usable font or self-drawn bitmap is the safer choice.
- Encoding: In-game strings should uniformly use UCS-2 or UTF-16 encoding, with the rendering layer indexing glyphs by code point to avoid repeated encoding conversion on the rendering path.
- Size: An on-demand glyph strategy packages only the characters actually used; common characters use a 16×16 bitmap while titles and other large text use a higher resolution, located via binary search in a sorted code-point table.
typedef struct {CHAR16 CodePoint; /* character code point */UINTN Offset; /* start index in the glyph table */UINTN Count; /* number of characters in this block */} GLYPH_INDEX;/* Binary search in the code-point-sorted index table;on a hit, write the corresponding glyph block */STATICBOOLEANGlyphLookup (IN CONST GLYPH_INDEX *Table,IN UINTN Count,IN CHAR16 CodePoint,OUT UINTN *Offset){UINTN Left = 0;UINTN Right = Count;while (Left < Right) {UINTN Mid = (Left + Right) >> 1;if (Table[Mid].CodePoint < CodePoint) {Left = Mid + 1;} else {Right = Mid;}}if ((Left < Count) && (Table[Left].CodePoint == CodePoint)) {*Offset = Table[Left].Offset;return TRUE;}return FALSE;}
4.2 Art and Composition: Making It Readable and Clear
The focus of visual design is not “how finely it is drawn” but clear information hierarchy.
- Distinguish sides by color and shape: The player’s ship and enemy units should form a clear contrast in both color and outline.
- Consistent sprite orientation: Hit and explosion feedback in a vertical game needs a clear sense of direction.
- Fixed status-bar position: Place the health bar, lives, and score in fixed regions at the screen edges so dynamic elements do not obscure the combat area.
- Subtract from effects: Keep explosion particles, screen shake, and similar effects within the resource and frame-rate budget, and avoid trading response speed for visual flourish.
4.3 Gameplay Systems: Rhythmic Upgrades and Staged Bosses
The “feel-good” factor of a shooter comes from the progression of numbers and pacing. Organize weapon and enemy configuration with data-driven tables to make balancing easier:
typedef struct {UINTN Level; /* weapon level */UINTN BulletCount; /* number of trajectories fired at once */UINTN FireIntervalTicks; /* firing interval; smaller means denser */UINT32 BulletSpeed; /* bullet speed */} WEAPON_CONFIG;STATIC CONST WEAPON_CONFIG mWeaponTable[] = {{ 1, 1, 8, 4 },{ 2, 2, 7, 4 },{ 3, 3, 6, 5 },{ 4, 4, 5, 5 },{ 5, 5, 4, 6 } /* level 5: widest coverage, fastest fire rate */};
The place most likely to go wrong at this layer is a lack of constraints between numbers and pacing:
- Upgrade rhythm: Each upgrade should produce a perceptible change, not just “damage +1.”
- Difficulty curve: Enemy health, count, and movement speed should grow in step with the player’s firepower.
- Item drops: Drop rates and placement must give players a real chance to experience the upgrade.
- Boss battles: Use a multi-stage design to create changes in rhythm, for example “bullet-hell phase → summon phase → berserk phase,” with clear presentation and cues when stages switch.
4.4 Regression Validation After One Round of Changes
The second round of changes involves resources, rendering, and gameplay, so the focus shifts from “can it run” to “will it regress”:
- After changing the theme or resolution, is the text still fully displayed without truncation?
- Does Chinese appear as garbled text or boxes in a non-target font environment?
- Does increasing the bullet count after an upgrade cause a noticeable drop in frame rate?
- After a boss battle ends, does it correctly return to the next level or the results screen?
- After a character dies, is the state completely reset?
5. Review: What the AI Programming Assistant Changed, and What the Developer Must Add
5.1 Three Things the Assistant Can Do for You
- Initial integration of cross-domain knowledge: Consolidate knowledge scattered across firmware, graphics, and game-development documentation into a runnable skeleton.
- Boilerplate code and interface adaptation: Repetitive work such as interface signatures, struct fields, and build-configuration fragments.
- Localization help during iteration: Narrow the investigation scope based on errors and logs.
5.2 Four Dimensions the Developer Must Own
- Architecture decisions: Whether to use an off-screen canvas, whether to use an object pool, whether to introduce a state machine—all depend on the target platform and runtime scenario.
- Correctness validation: Passing on the simulator does not mean passing on real hardware; graphics modes, input devices, and memory layout all need confirmation on real hardware.
- Compliance and security: Resource copyright, open-source licenses, firmware signing, and secure-boot policy.
- Maintainability: Module boundaries, naming conventions, comments, and documentation determine whether the next developer can take over the project.
5.3 Three Prompt Strategies You Can Apply Immediately
- Set conventions before writing code: Write the directory structure, coding standards, and build/run approach into a project conventions file so the assistant stays aligned in every iteration.
- Advance one verifiable goal at a time: Break “finish the game” into “can display → can control → has enemies → has collisions → has Chinese → has upgrades and bosses,” attaching acceptance criteria to each goal.
- Hand validation to reproducible input scripts: Fix the input sequence so every regression replays under the same conditions, reducing “depends on luck” debugging.
6. Conclusion: Shifting Focus from “Can It Generate” to “Can It Deliver”
The value of an AI programming assistant in this kind of low-level project is not whether it gives the correct answer in one shot, but whether it substantially shortens the distance from requirement to runnable prototype. Environment setup, boilerplate code, resource handling, and repeated iteration are the parts it is best at replacing; platform differences, real-hardware validation, compliance, and architecture trade-offs remain the developer’s non-transferable judgments.
For developers, the more meaningful approach is to distill each practice into reusable assets: a project conventions file, a layered validation checklist, and a simulator-plus-real-hardware validation flow. Once these assets are in place, a new project no longer starts from zero but iterates from a verifiable baseline.
Appendix: Dimensions for Measuring an AI Programming Assistant’s Performance in Firmware Projects
If you need to compare different AI programming assistants within a team, start from the following six dimensions, and design observable metrics for each rather than relying on subjective impressions:
- Environment-adaptation ability: Can it correctly identify the firmware framework’s build approach on the target platform, instead of applying a generic build script?
- Platform-semantic accuracy: Does it correctly handle low-level details such as pointer width, integer width, byte order, and struct alignment?
- Iteration stability: After multiple consecutive rounds of changes, does it still preserve existing functionality rather than introducing regressions?
- Resource awareness: Does it proactively consider glyph-set size, frame-rate budget, and memory-allocation limits?
- Maintainability: Is the code organized in clear layers, and do naming and comments follow the conventions?
- Validation completeness: Does it proactively provide validation methods and failure paths, rather than only “it should run”?
