Files
nt-lite/code/user/apps/doom/doom.c
T
maksw 73abd6f90d isolate POSIX builds from the host UCRT, wire lwext4 and ntfs-3g as ext4.sys and ntfs.sys, split the FAT driver into directory/file/async/driver/mount units, add posixsrv and dwm plus input/console/desktop syscall clients and a pile of new smoke targets, rename serial.sys to cereal.sys, name HDA/USB/lwIP/AHCI workers, harden ATA probing/reset/removal around actual hardware deadlines, absent-channel detection, diagnostics and explicit worker lifetime, redo ACPI S5 shutdown around GAS/MMIO and HW-reduced firmware, scan SSDTs for _S5 and deal with Intel SMI sleep trapping, make serial and SMP timeouts use real monotonic deadlines, add thread names and fix terminal thread teardown, scheduler and APC prepare/commit races, make advisory file locks queryable and preserve split ranges and add mutable file append state, add shared-memory pipes with kernel-assisted wait/wake, introduce capability-scoped input and display managers, split surface map rights into read/write, add explicit unmap and replace present with commit/generation/damage tracking while keeping physical presentation under the display manager, decouple native exception classes from Win32 exception numbers and translate them in kernel32, add opaque process startup data, bump the resource protocol to v3 with namespace directories, symlinks and enumeration and service control to v2 with generic READY handle exports, add the new POSIX errno/status surface and rebuild fds around posixsrv-owned shared open descriptions, descriptor-local flags, exact inheritance snapshots, dup/fcntl/record locks and shared-ring pipes, add waitpid, POSIX credentials/groups/sessions/passwd/group lookups and move sockets onto stable open descriptions, port the shells and apps to the new console/input services and surface commit API, teach init to load services.ini and start/supervise RSSRV, DWM and generic services under restricted capabilities while publishing their endpoints through RSSRV, split RSSRV into namespace, volume, display, session, input, console and resource components and make /SystemRoot a real symlink to the independently published system volume, shift the syscall table again, expand lock/resource/surface/POSIX/service/thread smoke coverage, make docs scream ASK QUESTIONS and DISCUSS at LLMs, replace MIT No Attribution with WTFPL+.
2026-09-16 10:33:20 +02:00

532 lines
17 KiB
C

// doom.c — PureDOOM port
// Native personality carrying all the weight.
// Place the Doom WAD and optional doom.sf2 in the process working directory.
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <intrin.h>
#include <ntlite/syscall.h>
#include <ntlite/console_service.h>
#include <ntlite/input_service.h>
#include <ntlite/path.h>
#include "doom_audio.h"
#define DOOM_IMPLEMENTATION
#include "PureDOOM.h"
int _fltused;
// ---------------------------------------------------------------------------
// doom_print_fn
// ---------------------------------------------------------------------------
static void doom_print_wrapper(const char* msg)
{
if (msg) (void)NtlConsoleWrite(SYS_HANDLE_INVALID, msg, strlen(msg), NULL);
}
// ---------------------------------------------------------------------------
// doom_malloc_fn / doom_free_fn
// ---------------------------------------------------------------------------
static void* doom_malloc_wrapper(int size)
{
void* p = malloc(size);
if (!p) SysExitProcess(1);
return p;
}
static void doom_free_wrapper(void* ptr)
{
if (!ptr) return;
free(ptr);
}
// ---------------------------------------------------------------------------
// File I/O wrappers
// ---------------------------------------------------------------------------
typedef struct DOOM_FILE_HANDLE {
uint32_t Handle;
uint64_t Pos;
uint64_t Size;
} DOOM_FILE_HANDLE;
static void* doom_open_wrapper(const char* path, const char* mode)
{
uint32_t handle = 0;
uint32_t result;
uint32_t access = SYS_FILE_ACCESS_QUERY;
uint32_t disposition = SYS_FILE_OPEN_EXISTING;
if (mode[0] == 'w') {
access |= SYS_FILE_ACCESS_WRITE;
disposition = SYS_FILE_CREATE_ALWAYS;
} else {
access |= SYS_FILE_ACCESS_READ;
}
result = NtlOpenFile(SysSvFromCstr(path), access, disposition,
SYS_FILE_FLAG_NONE, &handle);
if (result != 0) return 0;
DOOM_FILE_HANDLE* f = (DOOM_FILE_HANDLE*)malloc(sizeof(DOOM_FILE_HANDLE));
if (!f) {
SysCloseHandle(handle);
return 0;
}
uint64_t size = 0;
result = SysGetFileSize(handle, &size);
if (result != 0) {
SysCloseHandle(handle);
free(f);
return 0;
}
f->Handle = handle;
f->Pos = 0;
f->Size = size;
return f;
}
static void doom_close_wrapper(void* handle)
{
if (!handle) return;
DOOM_FILE_HANDLE* f = (DOOM_FILE_HANDLE*)handle;
SysCloseHandle(f->Handle);
free(f);
}
static int doom_read_wrapper(void* handle, void* buf, int count)
{
if (!handle || count <= 0) return 0;
DOOM_FILE_HANDLE* f = (DOOM_FILE_HANDLE*)handle;
size_t read = 0;
SYS_FILE_IO_REQUEST req = SysMakeFileIoRequest(f->Handle, buf, (size_t)count, &read);
SysReadFile(&req);
f->Pos += read;
if (f->Pos > f->Size) f->Size = f->Pos;
return (int)read;
}
static int doom_write_wrapper(void* handle, const void* buf, int count)
{
if (!handle || count <= 0) return 0;
DOOM_FILE_HANDLE* f = (DOOM_FILE_HANDLE*)handle;
size_t written = 0;
SYS_FILE_IO_REQUEST req = SysMakeFileIoRequest(f->Handle, buf, (size_t)count, &written);
SysWriteFile(&req);
f->Pos += written;
if (f->Pos > f->Size) f->Size = f->Pos;
return (int)written;
}
static int doom_seek_wrapper(void* handle, int offset, doom_seek_t origin)
{
if (!handle) return -1;
DOOM_FILE_HANDLE* f = (DOOM_FILE_HANDLE*)handle;
int64_t base = 0;
switch (origin) {
case DOOM_SEEK_SET:
base = 0;
break;
case DOOM_SEEK_CUR:
base = (int64_t)f->Pos;
break;
case DOOM_SEEK_END:
base = (int64_t)f->Size;
break;
default:
base = 0;
break;
}
int64_t target = base + (int64_t)offset;
if (target < 0) target = 0;
uint32_t s = SysSeekFile(f->Handle, (uint64_t)target);
if (s != 0) return -1;
f->Pos = (uint64_t)target;
return 0;
}
static int doom_tell_wrapper(void* handle)
{
if (!handle) return -1;
return (int)((DOOM_FILE_HANDLE*)handle)->Pos;
}
static int doom_eof_wrapper(void* handle)
{
if (!handle) return 1;
DOOM_FILE_HANDLE* f = (DOOM_FILE_HANDLE*)handle;
return (f->Pos >= f->Size) ? 1 : 0;
}
// ---------------------------------------------------------------------------
// doom_gettime_fn
// ---------------------------------------------------------------------------
static void doom_gettime_wrapper(int* sec, int* usec)
{
uint64_t frequency = 0;
if (SysGetTickFrequency(&frequency) != NTLSTATUS_SUCCESS || !frequency) {
*sec = 0;
*usec = 0;
return;
}
uint64_t totalUs = SysTicksToMicroseconds(SysGetTick(), frequency);
*sec = (int)(totalUs / 1000000);
*usec = (int)(totalUs % 1000000);
}
// ---------------------------------------------------------------------------
// doom_exit_fn
// ---------------------------------------------------------------------------
static void doom_exit_wrapper(int code)
{
DoomAudioAbort();
SysExitProcess(code);
}
// ---------------------------------------------------------------------------
// doom_getenv_fn
// ---------------------------------------------------------------------------
static char* doom_getenv_wrapper(const char* name)
{
if (strcmp(name, "HOME") == 0) {
static char home[] = ".";
doom_print_wrapper("getenv: Returning HOME="); doom_print_wrapper(home); doom_print_wrapper("\n");
return home;
}
doom_print_wrapper("getenv: Unknown variable "); doom_print_wrapper(name); doom_print_wrapper("\n");
return NULL;
}
// ---------------------------------------------------------------------------
// Input — Maps canonical input keys to PureDOOM
// ---------------------------------------------------------------------------
typedef struct { INPUT_KEY inputKey; doom_key_t key; } KeyMap;
static const KeyMap g_keymap[] = {
// Letters
{ INPUT_KEY_W, DOOM_KEY_W },
{ INPUT_KEY_A, DOOM_KEY_A },
{ INPUT_KEY_S, DOOM_KEY_S },
{ INPUT_KEY_D, DOOM_KEY_D },
{ INPUT_KEY_E, DOOM_KEY_E },
{ INPUT_KEY_Q, DOOM_KEY_Q },
{ INPUT_KEY_Y, DOOM_KEY_Y },
{ INPUT_KEY_N, DOOM_KEY_N },
// Arrow keys
{ INPUT_KEY_UP, DOOM_KEY_UP_ARROW },
{ INPUT_KEY_DOWN, DOOM_KEY_DOWN_ARROW },
{ INPUT_KEY_LEFT, DOOM_KEY_LEFT_ARROW },
{ INPUT_KEY_RIGHT, DOOM_KEY_RIGHT_ARROW },
// Action keys
{ INPUT_KEY_LEFT_CTRL, DOOM_KEY_CTRL },
{ INPUT_KEY_SPACE, DOOM_KEY_SPACE },
{ INPUT_KEY_LEFT_SHIFT, DOOM_KEY_SHIFT },
{ INPUT_KEY_LEFT_ALT, DOOM_KEY_ALT },
// Navigation
{ INPUT_KEY_ESCAPE, DOOM_KEY_ESCAPE },
{ INPUT_KEY_ENTER, DOOM_KEY_ENTER },
{ INPUT_KEY_TAB, DOOM_KEY_TAB },
{ INPUT_KEY_BACKSPACE, DOOM_KEY_BACKSPACE },
// Weapon slots
{ INPUT_KEY_1, DOOM_KEY_1 },
{ INPUT_KEY_2, DOOM_KEY_2 },
{ INPUT_KEY_3, DOOM_KEY_3 },
{ INPUT_KEY_4, DOOM_KEY_4 },
{ INPUT_KEY_5, DOOM_KEY_5 },
{ INPUT_KEY_6, DOOM_KEY_6 },
{ INPUT_KEY_7, DOOM_KEY_7 },
// Misc
{ INPUT_KEY_MINUS, DOOM_KEY_MINUS },
{ INPUT_KEY_EQUAL, DOOM_KEY_EQUALS },
{ INPUT_KEY_COMMA, DOOM_KEY_COMMA },
{ INPUT_KEY_PERIOD, DOOM_KEY_PERIOD },
// Function keys
{ INPUT_KEY_F1, DOOM_KEY_F1 },
{ INPUT_KEY_F2, DOOM_KEY_F2 },
{ INPUT_KEY_F3, DOOM_KEY_F3 },
{ INPUT_KEY_F4, DOOM_KEY_F4 },
{ INPUT_KEY_F5, DOOM_KEY_F5 },
{ INPUT_KEY_F6, DOOM_KEY_F6 },
{ INPUT_KEY_F7, DOOM_KEY_F7 },
{ INPUT_KEY_F8, DOOM_KEY_F8 },
{ INPUT_KEY_F9, DOOM_KEY_F9 },
{ INPUT_KEY_F10, DOOM_KEY_F10 },
{ INPUT_KEY_F11, DOOM_KEY_F11 },
{ INPUT_KEY_F12, DOOM_KEY_F12 },
};
#define KEYMAP_COUNT (sizeof(g_keymap) / sizeof(g_keymap[0]))
static bool g_prev_key[KEYMAP_COUNT];
// Returns whether one key bit is set in a global input snapshot.
static bool ntlite_snapshot_key_down(const NTL_INPUT_STATE* state, INPUT_KEY key)
{
if (!state || key >= 256u) return false;
return (state->KeyDown[key >> 3] & (uint8_t)(1u << (key & 7u))) != 0;
}
static void poll_input(void)
{
NTL_INPUT_STATE input;
memset(&input, 0, sizeof(input));
input.Size = sizeof(input);
input.Flags = NTL_INPUT_STATE_FLAG_NONE;
if (NtlInputQueryDefaultState(&input) != NTLSTATUS_SUCCESS)
return;
for (int i = 0; i < (int)KEYMAP_COUNT; i++) {
bool cur_down = ntlite_snapshot_key_down(&input, g_keymap[i].inputKey);
bool prev_down = g_prev_key[i];
if (cur_down && !prev_down) doom_key_down(g_keymap[i].key);
if (!cur_down && prev_down) doom_key_up (g_keymap[i].key);
g_prev_key[i] = cur_down;
}
}
// ---------------------------------------------------------------------------
// Render — writes directly into a mapped kernel surface and presents it.
// ---------------------------------------------------------------------------
#define DOOM_W 320
#define DOOM_H 200
#define SCALE 3
#define DISP_W (DOOM_W * SCALE)
#define DISP_H (DOOM_H * SCALE)
static uint32_t g_surface_handle;
static uint32_t g_display_clock_handle;
static uint32_t* g_surface_pixels;
static uint32_t g_surface_pitch_pixels;
static void init_surface(void)
{
SYS_CREATE_SURFACE_REQUEST req;
memset(&req, 0, sizeof(req));
req.Size = sizeof(req);
req.Width = DISP_W;
req.Height = DISP_H;
req.Format = SYS_SURFACE_FORMAT_XRGB8888;
req.Flags = SYS_SURFACE_FLAG_NONE;
req.HandleOut = &g_surface_handle;
uint32_t s = SysCreateSurface(&req);
if (s != NTLSTATUS_SUCCESS || !g_surface_handle) {
doom_print_wrapper("doom: SysCreateSurface failed\n");
SysExitProcess(1);
}
void* base = 0;
uint32_t pitchBytes = 0;
s = SysMapSurface(g_surface_handle, SYS_SURFACE_MAP_READ | SYS_SURFACE_MAP_WRITE,
&base, &pitchBytes);
if (s != NTLSTATUS_SUCCESS || !base || pitchBytes < DISP_W * sizeof(uint32_t)) {
doom_print_wrapper("doom: SysMapSurface failed\n");
SysExitProcess(1);
}
g_surface_pixels = (uint32_t*)base;
g_surface_pitch_pixels = pitchBytes / sizeof(uint32_t);
}
static void init_display_clock(void)
{
SYS_OPEN_DISPLAY_CLOCK_REQUEST req;
memset(&req, 0, sizeof(req));
req.Size = sizeof(req);
req.Flags = SYS_DISPLAY_CLOCK_FLAG_NONE;
req.PeriodMilliseconds = 1;
req.HandleOut = &g_display_clock_handle;
uint32_t s = SysOpenDisplayClock(&req);
if (s != NTLSTATUS_SUCCESS) {
g_display_clock_handle = 0;
doom_print_wrapper("doom: display clock unavailable, using sleep pacing\n");
}
}
static void render_frame(const uint8_t* rgba)
{
const uint32_t* src = (const uint32_t*)rgba;
uint32_t* dstBase = g_surface_pixels;
uint32_t dstPitch = g_surface_pitch_pixels;
if (!dstBase || dstPitch < DISP_W) {
doom_print_wrapper("doom: surface not initialized\n");
SysExitProcess(1);
}
for (int y = 0; y < DOOM_H; y++) {
for (int x = 0; x < DOOM_W; x++) {
uint32_t p = src[y * DOOM_W + x];
// RGBA -> BGRA/XRGB8888 conversion for the current display path.
uint32_t bgra = (p & 0xFF00FF00u)
| ((p & 0x00FF0000u) >> 16)
| ((p & 0x000000FFu) << 16);
uint32_t* block = dstBase + (size_t)(y * SCALE) * dstPitch + (size_t)(x * SCALE);
for (int sy = 0; sy < SCALE; sy++) {
for (int sx = 0; sx < SCALE; sx++) {
block[(size_t)sy * dstPitch + sx] = bgra;
}
}
}
}
DISPLAY_RECT rect = { 0, 0, DISP_W, DISP_H };
uint32_t code = SysCommitSurface(g_surface_handle, &rect, 1, 0);
if (code != NTLSTATUS_SUCCESS)
SysExitProcess(code);
}
static int build_argv_from_command_line(const char* cmdline, char* storage, size_t storageSize,
const char** argv, int maxArgv) {
if (!storage || storageSize == 0 || !argv || maxArgv <= 1) return 0;
if (!cmdline || cmdline[0] == '\0') cmdline = "doom";
size_t len = strlen(cmdline);
if (len >= storageSize) len = storageSize - 1;
memcpy(storage, cmdline, len);
storage[len] = '\0';
int argc = 0;
char* p = storage;
while (*p && argc < maxArgv - 1) {
while (*p == ' ' || *p == '\t') p++;
if (!*p) break;
if (*p == '"') {
p++;
argv[argc++] = p;
while (*p && *p != '"') p++;
if (*p) *p++ = '\0';
} else {
argv[argc++] = p;
while (*p && *p != ' ' && *p != '\t') p++;
if (*p) *p++ = '\0';
}
}
argv[argc] = 0;
if (argc == 0) {
argv[0] = "doom";
argv[1] = 0;
argc = 1;
}
return argc;
}
// ---------------------------------------------------------------------------
// Timing
// ---------------------------------------------------------------------------
static int doom_now_tic(void)
{
return I_GetTime();
}
// Waits until Doom has a new simulation tic to render.
static int wait_for_next_doom_tic(int lastTic)
{
while (true) {
int now = doom_now_tic();
if (now != lastTic)
return now;
if (g_display_clock_handle) {
(void)SysWaitSingle(g_display_clock_handle, SYS_WAIT_FLAG_NONE, SYS_WAIT_TIMEOUT_INFINITE);
} else {
SysSleep(1);
}
}
}
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
int main(void)
{
const char* cmdline = SysGetPeb()->CommandLine.Data;
(void)NtlConsoleWrite(SYS_HANDLE_INVALID, "doom: starting\n", sizeof("doom: starting\n") - 1u, NULL);
// Wire up PureDOOM core mechanics
doom_set_print(doom_print_wrapper);
doom_set_malloc(doom_malloc_wrapper, doom_free_wrapper);
doom_set_file_io(
doom_open_wrapper,
doom_close_wrapper,
doom_read_wrapper,
doom_write_wrapper,
doom_seek_wrapper,
doom_tell_wrapper,
doom_eof_wrapper
);
doom_set_gettime(doom_gettime_wrapper);
doom_set_exit(doom_exit_wrapper);
doom_set_getenv(doom_getenv_wrapper);
// Resolution + modern WASD bindings
doom_set_resolution(DOOM_W, DOOM_H);
doom_set_default_int("key_up", DOOM_KEY_W);
doom_set_default_int("key_down", DOOM_KEY_S);
doom_set_default_int("key_strafeleft", DOOM_KEY_A);
doom_set_default_int("key_straferight", DOOM_KEY_D);
doom_set_default_int("key_use", DOOM_KEY_E);
doom_set_default_int("mouse_move", 0);
char argvStorage[512];
const char* argv[32];
int argc = build_argv_from_command_line(cmdline, argvStorage, sizeof(argvStorage), argv, 32);
if (argc == 1)
doom_print_wrapper("doom: parsed argc == 1\n");
else if (argc > 1)
doom_print_wrapper("doom: parsed argc > 1\n");
else
doom_print_wrapper("doom: parsed argc <= 0\n");
init_surface();
init_display_clock();
(void)NtlConsoleWrite(SYS_HANDLE_INVALID, "doom: starting doom\n", sizeof("doom: starting doom\n") - 1u, NULL);
doom_init(argc, argv, 0);
(void)NtlConsoleWrite(SYS_HANDLE_INVALID, "doom: starting audio\n", sizeof("doom: starting audio\n") - 1u, NULL);
DoomAudioStart();
(void)NtlConsoleWrite(SYS_HANDLE_INVALID, "doom: entering game loop\n", sizeof("doom: entering game loop\n") - 1u, NULL);
// Core execution loop. Doom advances at TICRATE, so rendering duplicate
// frames as fast as possible only amplifies scheduler and input jitter.
int lastFrameTic = doom_now_tic();
while (1) {
int frameTic = wait_for_next_doom_tic(lastFrameTic);
lastFrameTic = frameTic;
DoomAudioLockCore();
poll_input();
doom_update();
const uint8_t* framebuffer = (const uint8_t*)doom_get_framebuffer(4 /* RGBA */);
DoomAudioUnlockCore();
render_frame(framebuffer);
}
SysExitProcess(0);
return 0;
}