aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/linux_graphics.c (123521B)


      1 #include "browser_profile.h"
      2 #include "linux_graphics.h"
      3 #include "linux_window.h"
      4 #include "guest_heap.h"
      5 #include "gl_renderer.h"
      6 #include <SDL2/SDL.h>
      7 #ifdef __EMSCRIPTEN__
      8 #include <GLES3/gl3.h>
      9 #include <emscripten.h>
     10 #include <emscripten/html5.h>
     11 #include <stdatomic.h>
     12 #else
     13 #include <SDL2/SDL_opengl.h>
     14 #endif
     15 #include <errno.h>
     16 #include <time.h>
     17 #include <math.h>
     18 #include <assert.h>
     19 
     20 /* Native graphics resources never appear in guest COM objects or vtables. */
     21 static SDL_Window *window;
     22 static GLint maximum_texture_size;
     23 #ifdef __EMSCRIPTEN__
     24 static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context;
     25 static SDL_DisplayMode browser_display;
     26 static _Atomic int graphics_lost;
     27 static int proxied_context;
     28 void ao_graphics_initialize(void);
     29 void ao_graphics_status(int lost);
     30 
     31 EMSCRIPTEN_KEEPALIVE void browser_graphics_lost(void)
     32 {
     33     graphics_lost = 1;
     34     ao_graphics_status(1);
     35 }
     36 
     37 int browser_graphics_ready(void)
     38 {
     39     /* Only poll the owning thread while recovering from a notified loss. */
     40     if (!atomic_load(&graphics_lost)) return 1;
     41     if (context && emscripten_is_webgl_context_lost(context)) return 0;
     42     if (atomic_exchange(&graphics_lost, 0)) {
     43         gl_renderer_restore();
     44         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximum_texture_size);
     45         ao_graphics_status(0);
     46         fprintf(stderr, "[browser-graphics] WebGL resources restored\n");
     47     }
     48     return 1;
     49 }
     50 #else
     51 static SDL_GLContext context;
     52 #endif
     53 static struct draw_object {
     54     uint32_t interfaces[3], references[2];
     55     struct draw_object *next;
     56 } *objects;
     57 static struct clipper_object {
     58     uint32_t interface, references, window;
     59     struct draw_object *owner;
     60     struct clipper_object *next;
     61 } *clippers;
     62 static struct palette_object {
     63     uint32_t interface, references, caps, count, entry_size;
     64     unsigned char entries[1024];
     65     struct draw_object *owner;
     66     struct palette_object *next;
     67 } *palettes;
     68 struct surface_data {
     69     uint32_t guid[4], size;
     70     struct surface_data *next;
     71     unsigned char bytes[];
     72 };
     73 static struct surface_object {
     74     uint32_t interfaces[2], references[2];
     75     uint32_t width, height, caps, pixels, lock_flags, depth_bits, alpha, rgb_bits;
     76     uint32_t caps2, description_flags, pitch, mip_count;
     77     int32_t lock_rectangle[4];
     78     int locked, texture_updates, pending_write;
     79     struct draw_object *owner;
     80     struct clipper_object *clipper;
     81     struct gl_target *target;
     82     struct gl_depth *depth;
     83     struct surface_object *attached;
     84     struct surface_data *data;
     85     struct surface_object *next, *bucket_next[2];
     86 } *surfaces;
     87 static struct surface_object *surface_buckets[2][4096];
     88 struct device_light {
     89     uint32_t index, enabled, data[26];
     90     float camera_vector[4], spot_direction[4], spot_inner, spot_outer;
     91     struct device_light *next, *next_enabled;
     92 };
     93 struct texture_stage {
     94     uint32_t min_filter, mag_filter, mip_filter, address, address_u, address_v, color_op, alpha_op;
     95     uint32_t sampler_u, sampler_v, texture_transform, texture_coordinate;
     96     uint32_t color_arg1, alpha_arg1, color_arg2, alpha_arg2;
     97     struct surface_object *texture;
     98 };
     99 static struct device_object {
    100     uint32_t interface, references, cull;
    101     struct texture_stage stages[2];
    102     uint32_t fog_enabled, fog_color, fog_start, fog_end, fog_density, fog_vertex_mode;
    103     uint32_t blend, source_blend, destination_blend, depth_enabled, depth_write, depth_function, clipping, lighting;
    104     uint32_t depth_bias;
    105     uint32_t texture_factor;
    106     uint32_t specular;
    107     uint32_t alpha_test, alpha_reference, alpha_function;
    108     float specular_power;
    109     uint32_t diffuse_source, specular_source, emissive_source;
    110     uint32_t ambient, normalize_normals, material[17], viewport[6], transforms[5][16];
    111     int scene;
    112     struct draw_object *owner;
    113     struct surface_object *target;
    114     struct device_light *lights, *enabled_lights;
    115     struct device_object *next;
    116 } *devices;
    117 static struct vertex_buffer {
    118     uint32_t interface, references, caps, fvf, count, size, data;
    119     struct draw_object *owner;
    120     struct gl_vertex_buffer *gpu;
    121     struct vertex_buffer *next;
    122 } *vertex_buffers[4096];
    123 static uint32_t vtables[9];
    124 static const unsigned interface_slots[] = {23, 30, 8, 49, 36, 9, 49, 9, 7};
    125 static unsigned current_interface, current_slot;
    126 
    127 void linux_graphics_shutdown(void)
    128 {
    129     if (context) gl_renderer_shutdown();
    130 #ifdef __EMSCRIPTEN__
    131     if (context) emscripten_webgl_destroy_context(context);
    132     graphics_lost = 0;
    133     proxied_context = 0;
    134 #else
    135     SDL_GL_DeleteContext(context);
    136 #endif
    137     SDL_DestroyWindow(window);
    138     SDL_QuitSubSystem(SDL_INIT_VIDEO);
    139     context = 0;
    140     window = NULL;
    141 }
    142 
    143 static int initialize_graphics(void)
    144 {
    145 #ifdef __EMSCRIPTEN__
    146     if (context) browser_graphics_ready();
    147 #endif
    148     if (context) return 1;
    149     if (SDL_InitSubSystem(SDL_INIT_VIDEO)) goto failed;
    150 #ifdef __EMSCRIPTEN__
    151     /* The canvas is the browser's virtual desktop, independent of the monitor. */
    152     browser_display.format = SDL_PIXELFORMAT_RGB888;
    153     if (emscripten_get_canvas_element_size("#canvas", &browser_display.w,
    154                                           &browser_display.h) != EMSCRIPTEN_RESULT_SUCCESS) goto failed;
    155 #endif
    156 #ifndef __EMSCRIPTEN__
    157     if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3) ||
    158         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3) ||
    159         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE) ||
    160         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)) goto failed;
    161 #endif
    162     window = SDL_CreateWindow("Anarchy Online", SDL_WINDOWPOS_UNDEFINED,
    163                               SDL_WINDOWPOS_UNDEFINED, 32, 32, SDL_WINDOW_HIDDEN
    164 #ifndef __EMSCRIPTEN__
    165                               | SDL_WINDOW_OPENGL
    166 #endif
    167                               );
    168     if (!window) goto failed;
    169 #ifdef __EMSCRIPTEN__
    170     /* Keep rendering local when the canvas was transferred to this worker. */
    171     proxied_context = EM_ASM_INT({ return !Module.canvas; });
    172     EmscriptenWebGLContextAttributes attributes;
    173     emscripten_webgl_init_context_attributes(&attributes);
    174     attributes.majorVersion = 2;
    175     attributes.alpha = attributes.antialias = 0;
    176     attributes.proxyContextToMainThread = proxied_context ?
    177         EMSCRIPTEN_WEBGL_CONTEXT_PROXY_ALWAYS : EMSCRIPTEN_WEBGL_CONTEXT_PROXY_DISALLOW;
    178     attributes.explicitSwapControl = attributes.renderViaOffscreenBackBuffer = proxied_context;
    179     context = emscripten_webgl_create_context("#canvas", &attributes);
    180     if (context <= 0) { context = 0; goto failed; }
    181     if (emscripten_webgl_make_context_current(context) != EMSCRIPTEN_RESULT_SUCCESS) goto failed;
    182     ao_graphics_initialize();
    183     fprintf(stderr, "[browser-graphics] WebGL on %s\n", proxied_context ? "page thread" : "game worker");
    184 #else
    185     context = SDL_GL_CreateContext(window);
    186     if (!context) goto failed;
    187     /* The guest's WaitForVerticalBlank already controls frame pacing. */
    188     if (SDL_GL_SetSwapInterval(0))
    189         fprintf(stderr, "[linux-graphics] Cannot disable implicit swap pacing: %s\n", SDL_GetError());
    190 #endif
    191     if (!gl_renderer_initialize()) {
    192 #ifdef __EMSCRIPTEN__
    193         if (!emscripten_is_webgl_context_lost(context)) goto failed;
    194         browser_graphics_ready();
    195 #else
    196         goto failed;
    197 #endif
    198     }
    199     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximum_texture_size);
    200     fprintf(stderr, "[linux-graphics] %s; OpenGL %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
    201 #ifndef __EMSCRIPTEN__
    202     atexit(linux_graphics_shutdown);
    203 #endif
    204     return 1;
    205 failed:
    206     fprintf(stderr, "Native graphics initialization failed: %s\n", SDL_GetError());
    207     linux_graphics_shutdown();
    208     return 0;
    209 }
    210 
    211 SDL_Window *linux_graphics_window(void)
    212 {
    213     return initialize_graphics() ? window : NULL;
    214 }
    215 
    216 int linux_graphics_display_mode(SDL_DisplayMode *mode)
    217 {
    218 #ifdef __EMSCRIPTEN__
    219     *mode = browser_display;
    220     return 0;
    221 #else
    222     return SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), mode);
    223 #endif
    224 }
    225 
    226 #ifdef __EMSCRIPTEN__
    227 int linux_graphics_resize(unsigned width, unsigned height, uint32_t drawing_surface)
    228 {
    229     if (!context || !width || !height || width > (unsigned)maximum_texture_size ||
    230         height > (unsigned)maximum_texture_size) return 0;
    231     browser_graphics_ready();
    232     for (struct device_object *device = devices; device; device = device->next)
    233         if (device->scene) return 0;
    234 
    235     /* Keep the desktop and CPU drawing surface identities while replacing storage. */
    236     for (struct surface_object *surface = surfaces; surface; surface = surface->next) {
    237         if (!(surface->caps & 0x200) && surface->interfaces[0] != drawing_surface) continue;
    238         assert(!surface->locked && !surface->depth && !surface->attached);
    239         struct gl_target *target = gl_target_create(width, height, 1);
    240         if (!target) abort();
    241         gl_target_destroy(surface->target);
    242         surface->target = target;
    243         surface->width = width;
    244         surface->height = height;
    245         surface->pitch = width * 4;
    246         if (surface->pixels) {
    247             guest_free(surface->pixels);
    248             surface->pixels = guest_malloc(surface->pitch * height);
    249             if (!surface->pixels) abort();
    250             memset((void *)ADDR(surface->pixels), 0, surface->pitch * height);
    251             gl_target_write(surface->target, (void *)ADDR(surface->pixels));
    252         }
    253     }
    254     browser_display.w = width;
    255     browser_display.h = height;
    256     linux_window_resize(width, height);
    257     return 1;
    258 }
    259 #endif
    260 
    261 static struct draw_object *find_object(uint32_t address)
    262 {
    263     for (struct draw_object *object = objects; object; object = object->next)
    264         for (unsigned i = 0; i < 3; ++i)
    265             if (object->interfaces[i] == address && object->references[i ? 1 : 0]) return object;
    266     fprintf(stderr, "Invalid guest DirectDraw interface %08x\n", address);
    267     abort();
    268 }
    269 
    270 static uint32_t create_interface(unsigned index)
    271 {
    272     if (!vtables[index]) {
    273         unsigned slots = interface_slots[index];
    274         vtables[index] = guest_malloc(slots * 4);
    275         if (!vtables[index]) abort();
    276         for (unsigned slot = 0; slot < slots; ++slot)
    277             MEM32(vtables[index] + slot * 4) = 0xf3000000u + index * 0x100 + slot * 4;
    278     }
    279     uint32_t address = guest_malloc(4);
    280     if (!address) abort();
    281     MEM32(address) = vtables[index];
    282     return address;
    283 }
    284 
    285 static uint32_t interface_pointer(struct draw_object *object, unsigned index)
    286 {
    287     if (!object->interfaces[index]) object->interfaces[index] = create_interface(index);
    288     /* Direct3D7 and DirectDraw7 share a count; DirectDraw has its own. */
    289     ++object->references[index ? 1 : 0];
    290     return object->interfaces[index];
    291 }
    292 
    293 static void create_draw(uint32_t adapter, uint32_t output, uint32_t outer, unsigned index)
    294 {
    295     if (!output || outer) g_eax = 0x80070057u; /* DDERR_INVALIDPARAMS */
    296     else if (adapter) {
    297         fprintf(stderr, "Selecting a non-default DirectDraw adapter is not implemented\n");
    298         exit(3);
    299     } else if (!initialize_graphics()) { MEM32(output) = 0; g_eax = 0x80004005u; }
    300     else {
    301         struct draw_object *object = calloc(1, sizeof(*object));
    302         if (!object) abort();
    303         object->next = objects;
    304         objects = object;
    305         MEM32(output) = interface_pointer(object, index);
    306         g_eax = 0;
    307     }
    308 }
    309 
    310 static void direct_draw_create(void)
    311 {
    312     create_draw(MEM32(g_esp + 4), MEM32(g_esp + 8), MEM32(g_esp + 12), 0);
    313     g_esp += 16;
    314 }
    315 
    316 static void direct_draw_create_ex(void)
    317 {
    318     uint32_t iid = MEM32(g_esp + 12);
    319     static const uint32_t draw7[] = {0x15e65ec0, 0x11d23b9c, 0x60002fb9, 0x5bea9797};
    320     if (!iid || memcmp((const void *)ADDR(iid), draw7, 16)) g_eax = 0x80070057u;
    321     else if (MEM32(g_esp + 16)) g_eax = 0x80040110u; /* CLASS_E_NOAGGREGATION */
    322     else create_draw(MEM32(g_esp + 4), MEM32(g_esp + 8), MEM32(g_esp + 16), 1);
    323     g_esp += 20;
    324 }
    325 
    326 static void set_cooperative_level(void)
    327 {
    328     find_object(MEM32(g_esp + 4));
    329     uint32_t handle = MEM32(g_esp + 8), flags = MEM32(g_esp + 12);
    330     /* DDSCL_FPUSETUP says the caller maintains its FPU state; leave guest state intact. */
    331     if (handle || (flags != 8 && flags != 0x808)) {
    332         fprintf(stderr, "Unsupported DirectDraw cooperative level: window=%08x flags=%08x\n", handle, flags);
    333         exit(3);
    334     }
    335     g_eax = SDL_SetWindowFullscreen(window, 0) ? 0x80004005u : 0;
    336     g_esp += 16;
    337 }
    338 
    339 static void test_cooperative_level(void)
    340 {
    341     find_object(MEM32(g_esp + 4));
    342     /* Windowed rendering keeps its context/resources across focus changes. */
    343     g_eax = 0;
    344     g_esp += 8;
    345 }
    346 
    347 static void restore_display_mode(void)
    348 {
    349     find_object(MEM32(g_esp + 4));
    350     /* Windowed rendering never changes the display mode, so nothing needs restoring. */
    351     g_eax = 0;
    352     g_esp += 8;
    353 }
    354 
    355 static void wait_for_vertical_blank(void)
    356 {
    357     find_object(MEM32(g_esp + 4));
    358     uint32_t flags = MEM32(g_esp + 8), event = MEM32(g_esp + 12);
    359     g_esp += 16;
    360     g_eax = 0x80070057u;
    361     if (flags != 1 || event) return;
    362 #ifndef __EMSCRIPTEN__
    363     /* Disconnected displays may not report a refresh rate. */
    364     unsigned refresh_rate = 60;
    365     SDL_DisplayMode mode;
    366     if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(window), &mode)) {
    367         fprintf(stderr, "Cannot determine native display refresh rate\n"); exit(3);
    368     }
    369     if (mode.refresh_rate > 0) refresh_rate = mode.refresh_rate;
    370     /* Pace a virtual refresh clock where there is no retrace wait API. */
    371     struct timespec now;
    372     if (clock_gettime(CLOCK_MONOTONIC, &now)) abort();
    373     uint64_t period = 1000000000u / refresh_rate;
    374     uint64_t ticks = (uint64_t)now.tv_sec * 1000000000u + now.tv_nsec;
    375     uint64_t next = ticks + period - ticks % period;
    376     struct timespec deadline = {next / 1000000000u, next % 1000000000u};
    377     int error;
    378     do { error = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &deadline, NULL); } while (error == EINTR);
    379     if (error) { fprintf(stderr, "Native refresh wait failed: %d\n", error); abort(); }
    380 #endif
    381     g_eax = 0;
    382 }
    383 
    384 static void get_device_identifier(void)
    385 {
    386     find_object(MEM32(g_esp + 4));
    387     uint32_t output = MEM32(g_esp + 8), flags = MEM32(g_esp + 12);
    388     g_eax = 0x80070057u;
    389     if (output) {
    390         char *information = (char *)ADDR(output);
    391         /* DDDEVICEIDENTIFIER2 has 1068 bytes of fields, then four untouched
    392          * alignment bytes. Unknown PCI/driver-version fields and WHQL are zero. */
    393         memset(information, 0, 1068);
    394         if (!(flags & ~1u)) {
    395             strcpy(information, "ao-sdl-opengl");
    396             snprintf(information + 512, 512, "%s", (const char *)glGetString(GL_RENDERER));
    397             /* Stable identity of our single virtual adapter, not a physical GPU
    398              * GUID. Legacy hardware-specific driver workarounds must not apply. */
    399             static const uint32_t identifier[] = {0xc5cef85a, 0x4fae871b, 0x6942f28a, 0x0d55ec3f};
    400             memcpy(information + 1048, identifier, 16);
    401             g_eax = 0;
    402         }
    403     }
    404     g_esp += 16;
    405 }
    406 
    407 static void get_caps(void)
    408 {
    409     find_object(MEM32(g_esp + 4));
    410     uint32_t outputs[] = {MEM32(g_esp + 8), MEM32(g_esp + 12)};
    411     g_eax = 0x80070057u;
    412     if (!outputs[0] && !outputs[1]) { g_esp += 16; return; }
    413     for (unsigned i = 0; i < 2; ++i) if (outputs[i]) {
    414         uint32_t size = MEM32(outputs[i]);
    415         if (size != 172 && size != 316 && size != 364 && size != 380) {
    416             g_esp += 16;
    417             return;
    418         }
    419     }
    420     for (unsigned i = 0; i < 2; ++i) if (outputs[i]) {
    421         uint32_t size = MEM32(outputs[i]);
    422         memset((void *)ADDR(outputs[i]), 0, size);
    423         MEM32(outputs[i]) = size;
    424         /* Windowed rasterization and texture mip chains; no software device. */
    425         if (!i) {
    426             MEM32(outputs[i] + 4) = 1; /* DDCAPS_3D */
    427             MEM32(outputs[i] + 8) = 0x80000u; /* DDCAPS2_CANRENDERWINDOWED */
    428             MEM32(outputs[i] + 132) = 0x401008; /* Legacy DDSCAPS: texture mip chains. */
    429             if (size == 380) MEM32(outputs[i] + 364) = 0x401008;
    430         }
    431     }
    432     g_eax = 0;
    433     g_esp += 16;
    434 }
    435 
    436 static void get_display_mode(void)
    437 {
    438     find_object(MEM32(g_esp + 4));
    439     uint32_t output = MEM32(g_esp + 8);
    440     g_esp += 12;
    441     g_eax = 0x80070057u;
    442     if (!output || (MEM32(output) != 108 && MEM32(output) != 124)) return;
    443     SDL_DisplayMode mode;
    444     if (linux_graphics_display_mode(&mode)) abort();
    445     int bits;
    446     Uint32 red, green, blue, alpha;
    447     if (!SDL_PixelFormatEnumToMasks(mode.format, &bits, &red, &green, &blue, &alpha)) abort();
    448     memset((void *)ADDR(output), 0, MEM32(output));
    449     MEM32(output) = 124;
    450     MEM32(output + 4) = 0x4100e; /* Dimensions, pitch, pixel format and refresh. */
    451     MEM32(output + 8) = mode.h;
    452     MEM32(output + 12) = mode.w;
    453     MEM32(output + 16) = (mode.w * SDL_BYTESPERPIXEL(mode.format) + 3) & ~3u;
    454     MEM32(output + 24) = mode.refresh_rate;
    455     MEM32(output + 72) = 32;
    456     MEM32(output + 76) = 0x40;
    457     MEM32(output + 84) = SDL_BYTESPERPIXEL(mode.format) * 8;
    458     MEM32(output + 88) = red;
    459     MEM32(output + 92) = green;
    460     MEM32(output + 96) = blue;
    461     g_eax = 0;
    462 }
    463 
    464 static void enumerate_display_modes(void)
    465 {
    466     find_object(MEM32(g_esp + 4));
    467     uint32_t flags = MEM32(g_esp + 8), filter = MEM32(g_esp + 12);
    468     uint32_t data = MEM32(g_esp + 16), callback = MEM32(g_esp + 20);
    469     if (!callback || (flags & ~3u)) { g_eax = 0x80070057u; g_esp += 24; return; }
    470     if (filter) { fprintf(stderr, "Filtered DirectDraw mode enumeration is not implemented\n"); exit(3); }
    471 #ifdef __EMSCRIPTEN__
    472     int count = 1;
    473 #else
    474     int display = SDL_GetWindowDisplayIndex(window), count = SDL_GetNumDisplayModes(display);
    475 #endif
    476     if (count < 0) { fprintf(stderr, "SDL mode query failed: %s\n", SDL_GetError()); abort(); }
    477     uint32_t description = guest_malloc(124);
    478     if (!description) abort();
    479     recomp_func_t function = recomp_lookup(callback);
    480     if (!function) function = recomp_lookup_import(callback);
    481     uint32_t stack = g_esp, caller = g_cur_func;
    482     SDL_DisplayMode previous = {0};
    483     for (int i = 0; i < count; ++i) {
    484         SDL_DisplayMode mode;
    485 #ifdef __EMSCRIPTEN__
    486         if (linux_graphics_display_mode(&mode)) {
    487 #else
    488         if (SDL_GetDisplayMode(display, i, &mode)) {
    489 #endif
    490             fprintf(stderr, "SDL mode query failed: %s\n", SDL_GetError()); abort();
    491         }
    492         /* SDL sorts refresh variants together. Without DDEDM_REFRESHRATES,
    493          * report each resolution/format once with a zero refresh rate. */
    494         if (!(flags & 1) && mode.w == previous.w && mode.h == previous.h && mode.format == previous.format) continue;
    495         previous = mode;
    496         int bits;
    497         Uint32 red, green, blue, alpha;
    498         if (!SDL_PixelFormatEnumToMasks(mode.format, &bits, &red, &green, &blue, &alpha) || !red || !green || !blue) continue;
    499         memset((void *)ADDR(description), 0, 124);
    500         MEM32(description) = 124;
    501         MEM32(description + 4) = 0x4100eu; /* dimensions, pitch, pixel format, refresh */
    502         MEM32(description + 8) = mode.h;
    503         MEM32(description + 12) = mode.w;
    504         MEM32(description + 16) = (mode.w * SDL_BYTESPERPIXEL(mode.format) + 3) & ~3u;
    505         MEM32(description + 24) = (flags & 1) ? mode.refresh_rate : 0;
    506         MEM32(description + 72) = 32; /* DDPIXELFORMAT */
    507         MEM32(description + 76) = 0x40; /* DDPF_RGB; display alpha is unused */
    508         MEM32(description + 84) = SDL_BYTESPERPIXEL(mode.format) * 8;
    509         MEM32(description + 88) = red;
    510         MEM32(description + 92) = green;
    511         MEM32(description + 96) = blue;
    512         PUSH32(g_esp, data);
    513         PUSH32(g_esp, description);
    514         PUSH32(g_esp, RECOMP_RETADDR);
    515         function();
    516         if (g_esp != stack) { fprintf(stderr, "DirectDraw mode callback unbalanced the guest stack\n"); abort(); }
    517         g_cur_func = caller;
    518         if (!g_eax) break;
    519     }
    520     guest_free(description);
    521     g_eax = 0;
    522     g_esp += 24;
    523 }
    524 
    525 static void enumerate_adapters(void)
    526 {
    527     uint32_t callback = MEM32(g_esp + 4), data = MEM32(g_esp + 8), flags = MEM32(g_esp + 12);
    528     if (!callback || (flags & ~7u)) { g_eax = 0x80070057u; g_esp += 16; return; }
    529     if (!initialize_graphics()) { g_eax = 0x80004005u; g_esp += 16; return; }
    530 
    531     /* This backend exposes its active primary adapter. Secondary, detached and
    532      * non-display adapters are not implemented. Names come from the real backend. */
    533     int display = SDL_GetWindowDisplayIndex(window);
    534     const char *name = display < 0 ? NULL : SDL_GetDisplayName(display);
    535     if (!name) { fprintf(stderr, "SDL display query failed: %s\n", SDL_GetError()); abort(); }
    536     const char *description = (const char *)glGetString(GL_RENDERER);
    537     size_t description_size = strlen(description) + 1, name_size = strlen(name) + 1;
    538     uint32_t text = guest_malloc(description_size + name_size);
    539     if (!text) abort();
    540     memcpy((void *)ADDR(text), description, description_size);
    541     memcpy((void *)ADDR(text + description_size), name, name_size);
    542 
    543     recomp_func_t function = recomp_lookup(callback);
    544     if (!function) function = recomp_lookup_import(callback);
    545     uint32_t stack = g_esp, caller = g_cur_func;
    546     PUSH32(g_esp, 0); /* The primary adapter has a null monitor and GUID. */
    547     PUSH32(g_esp, data);
    548     PUSH32(g_esp, text + description_size);
    549     PUSH32(g_esp, text);
    550     PUSH32(g_esp, 0);
    551     PUSH32(g_esp, RECOMP_RETADDR);
    552     function();
    553     if (g_esp != stack) { fprintf(stderr, "DirectDraw enumeration callback unbalanced the guest stack\n"); abort(); }
    554     g_cur_func = caller;
    555     guest_free(text);
    556     /* There is only one supported adapter, whether the callback continues or stops. */
    557     g_eax = 0;
    558     g_esp += 16;
    559 }
    560 
    561 static void describe_device(uint32_t record)
    562 {
    563     memset((void *)ADDR(record), 0, 236);
    564     MEM32(record) = 0x80200; /* HWRASTERIZATION | TEXTUREVIDEOMEMORY */
    565     MEM32(record + 4) = MEM32(record + 60) = 56; /* D3DPRIMCAPS sizes */
    566     MEM32(record + 64) = 0x10; /* Triangle culling: NONE */
    567     MEM32(record + 68) = 0x10; /* Triangle rasterization: ZTEST */
    568     MEM32(record + 72) = 8; /* Depth comparison: LESSEQUAL */
    569     MEM32(record + 76) = MEM32(record + 80) = 0x137; /* ZERO, ONE, SRCCOLOR, SRCALPHA, INVSRCALPHA, DESTCOLOR. */
    570     MEM32(record + 84) = 0xff; /* All eight alpha comparison functions. */
    571     MEM32(record + 88) = 8; /* Gouraud RGB interpolation */
    572     MEM32(record + 92) = 0x45; /* Perspective, alpha, normalized repeat range. */
    573     MEM32(record + 96) = 0x03010317; /* Point/linear filtering with nearest mip selection. */
    574     MEM32(record + 104) = 0x15; /* Independent U/V, wrap and clamp. */
    575     MEM32(record + 116) = 0x100; /* DDBD_32 color */
    576     MEM32(record + 120) = 0x600; /* DDBD_16 | DDBD_24 depth */
    577     MEM32(record + 124) = MEM32(record + 128) = 1;
    578     MEM32(record + 132) = MEM32(record + 136) = maximum_texture_size;
    579     MEM32(record + 140) = UINT32_MAX; /* Float UV range exceeds this DWORD limit. */
    580     MEM32(record + 144) = maximum_texture_size; /* A 1-by-maximum texture is supported. */
    581     MEM32(record + 148) = 1; /* No anisotropic filtering. */
    582     MEM32(record + 176) = 2; /* Two texture-coordinate sets. */
    583     MEM32(record + 180) = 0x8004b; /* Disable, select argument 1, modulate, add, inverse-alpha add. */
    584     MEM16(record + 184) = MEM16(record + 186) = 2;
    585     /* HAL denotes rasterization without hardware transform-and-lighting.
    586      * Lighting, W buffering and other unimplemented features stay zero. */
    587     static const uint32_t hal[] = {0x84e63de0, 0x11cf46aa, 0x00006f81, 0x6e1520c0};
    588     memcpy((void *)ADDR(record + 196), hal, 16);
    589 }
    590 
    591 static void enumerate_devices(void)
    592 {
    593     find_object(MEM32(g_esp + 4));
    594     uint32_t callback = MEM32(g_esp + 8), data = MEM32(g_esp + 12);
    595     if (!callback) { g_eax = 0x80070057u; g_esp += 16; return; }
    596     const char *description = (const char *)glGetString(GL_RENDERER);
    597     const char *name = "Native OpenGL";
    598     size_t description_size = strlen(description) + 1;
    599     uint32_t record = guest_malloc(236 + description_size + strlen(name) + 1);
    600     if (!record) abort();
    601     describe_device(record);
    602     memcpy((void *)ADDR(record + 236), description, description_size);
    603     strcpy((char *)ADDR(record + 236 + description_size), name);
    604     recomp_func_t function = recomp_lookup(callback);
    605     if (!function) function = recomp_lookup_import(callback);
    606     uint32_t stack = g_esp, caller = g_cur_func;
    607     PUSH32(g_esp, data);
    608     PUSH32(g_esp, record);
    609     PUSH32(g_esp, record + 236 + description_size);
    610     PUSH32(g_esp, record + 236);
    611     PUSH32(g_esp, RECOMP_RETADDR);
    612     function();
    613     if (g_esp != stack) { fprintf(stderr, "Direct3D device callback unbalanced the guest stack\n"); abort(); }
    614     g_cur_func = caller;
    615     guest_free(record);
    616     g_eax = 0;
    617     g_esp += 16;
    618 }
    619 
    620 static void query_interface(void)
    621 {
    622     struct draw_object *object = find_object(MEM32(g_esp + 4));
    623     uint32_t iid = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
    624     static const uint32_t unknown[] = {0, 0, 0xc0, 0x46000000};
    625     static const uint32_t draw1[] = {0x6c14db80, 0x11cea733, 0x200021a5, 0x60e50baf};
    626     static const uint32_t draw7[] = {0x15e65ec0, 0x11d23b9c, 0x60002fb9, 0x5bea9797};
    627     static const uint32_t d3d7[] = {0xf5049e77, 0x11d24861, 0xa00007a4, 0xa82906c9};
    628     if (!output) g_eax = 0x80070057u;
    629     else if (!memcmp((const void *)ADDR(iid), unknown, 16) || !memcmp((const void *)ADDR(iid), draw1, 16)) {
    630         MEM32(output) = interface_pointer(object, 0);
    631         g_eax = 0;
    632     } else if (!memcmp((const void *)ADDR(iid), draw7, 16)) {
    633         MEM32(output) = interface_pointer(object, 1);
    634         g_eax = 0;
    635     } else if (!memcmp((const void *)ADDR(iid), d3d7, 16)) {
    636         MEM32(output) = interface_pointer(object, 2);
    637         g_eax = 0;
    638     } else { MEM32(output) = 0; g_eax = 0x80004002u; }
    639     g_esp += 16;
    640 }
    641 
    642 static void add_reference(void)
    643 {
    644     uint32_t address = MEM32(g_esp + 4);
    645     struct draw_object *object = find_object(address);
    646     g_eax = ++object->references[address == object->interfaces[0] ? 0 : 1];
    647     g_esp += 8;
    648 }
    649 
    650 static uint32_t release_draw(struct draw_object *object, unsigned index)
    651 {
    652     uint32_t remaining = --object->references[index];
    653     if (!remaining) {
    654         for (unsigned i = 0; i < 3; ++i) if ((i ? 1 : 0) == index) {
    655             guest_free(object->interfaces[i]);
    656             object->interfaces[i] = 0;
    657         }
    658     }
    659     if (!object->references[0] && !object->references[1]) {
    660         struct draw_object **link = &objects;
    661         while (*link != object) link = &(*link)->next;
    662         *link = object->next;
    663         free(object);
    664     }
    665     return remaining;
    666 }
    667 
    668 static void release_reference(void)
    669 {
    670     uint32_t address = MEM32(g_esp + 4);
    671     struct draw_object *object = find_object(address);
    672     g_eax = release_draw(object, address == object->interfaces[0] ? 0 : 1);
    673     g_esp += 8;
    674 }
    675 
    676 static struct clipper_object *find_clipper(uint32_t address)
    677 {
    678     for (struct clipper_object *clipper = clippers; clipper; clipper = clipper->next)
    679         if (clipper->interface == address) return clipper;
    680     fprintf(stderr, "Invalid guest clipper interface %08x\n", address);
    681     abort();
    682 }
    683 
    684 static struct palette_object *find_palette(uint32_t address)
    685 {
    686     for (struct palette_object *palette = palettes; palette; palette = palette->next)
    687         if (palette->interface == address) return palette;
    688     fprintf(stderr, "Invalid guest palette interface %08x\n", address);
    689     abort();
    690 }
    691 
    692 static void palette_fixed_colors(struct palette_object *palette)
    693 {
    694     /* Without ALLOW256, the 8-bit palette's endpoints remain black and white. */
    695     if (palette->count == 256 && !(palette->caps & 0x40)) {
    696         memset(palette->entries, 0, 3);
    697         memset(palette->entries + 255 * 4, 255, 3);
    698     }
    699 }
    700 
    701 static void create_palette(void)
    702 {
    703     struct draw_object *owner = find_object(MEM32(g_esp + 4));
    704     uint32_t caps = MEM32(g_esp + 8), entries = MEM32(g_esp + 12);
    705     uint32_t output = MEM32(g_esp + 16), outer = MEM32(g_esp + 20);
    706     g_esp += 24;
    707     g_eax = 0x80070057u;
    708     if (!output) return;
    709     MEM32(output) = 0;
    710     uint32_t size = caps & 0x305;
    711     uint32_t count = size == 0x100 ? 2 : size == 0x200 ? 4 : size == 1 ? 16 : size == 4 ? 256 : 0;
    712     if (!entries || outer || !count || (caps & ~0x74fu) ||
    713         ((caps & 0x40) && count != 256) || ((caps & 2) && count == 256)) return;
    714     struct palette_object *palette = calloc(1, sizeof(*palette));
    715     if (!palette) abort();
    716     palette->interface = create_interface(8);
    717     palette->references = 1;
    718     palette->caps = caps & ~(0x400u | 8u);
    719     palette->count = count;
    720     palette->entry_size = caps & 2 ? 1 : 4;
    721     memcpy(palette->entries, (void *)ADDR(entries), count * palette->entry_size);
    722     palette_fixed_colors(palette);
    723     palette->owner = owner;
    724     ++owner->references[1];
    725     palette->next = palettes;
    726     palettes = palette;
    727     MEM32(output) = palette->interface;
    728     g_eax = 0;
    729 }
    730 
    731 static void palette_query_interface(void)
    732 {
    733     struct palette_object *palette = find_palette(MEM32(g_esp + 4));
    734     uint32_t iid = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
    735     const uint32_t unknown[] = {0, 0, 0xc0, 0x46000000};
    736     const uint32_t palette_iid[] = {0x6c14db84, 0x11cea733, 0x200021a5, 0x60e50baf};
    737     g_esp += 16;
    738     g_eax = 0x80070057u;
    739     if (!output) return;
    740     MEM32(output) = 0;
    741     g_eax = 0x80004002u;
    742     if (memcmp((void *)ADDR(iid), unknown, 16) && memcmp((void *)ADDR(iid), palette_iid, 16)) return;
    743     MEM32(output) = palette->interface;
    744     ++palette->references;
    745     g_eax = 0;
    746 }
    747 
    748 static void palette_add_reference(void)
    749 {
    750     g_eax = ++find_palette(MEM32(g_esp + 4))->references;
    751     g_esp += 8;
    752 }
    753 
    754 static void palette_release_reference(void)
    755 {
    756     struct palette_object *palette = find_palette(MEM32(g_esp + 4));
    757     g_eax = --palette->references;
    758     if (!g_eax) {
    759         struct palette_object **link = &palettes;
    760         while (*link != palette) link = &(*link)->next;
    761         *link = palette->next;
    762         release_draw(palette->owner, 1);
    763         guest_free(palette->interface);
    764         free(palette);
    765     }
    766     g_esp += 8;
    767 }
    768 
    769 static void palette_caps(void)
    770 {
    771     struct palette_object *palette = find_palette(MEM32(g_esp + 4));
    772     uint32_t output = MEM32(g_esp + 8);
    773     g_eax = 0x80070057u;
    774     if (output) { MEM32(output) = palette->caps; g_eax = 0; }
    775     g_esp += 12;
    776 }
    777 
    778 static void palette_entries(void)
    779 {
    780     struct palette_object *palette = find_palette(MEM32(g_esp + 4));
    781     uint32_t flags = MEM32(g_esp + 8), start = MEM32(g_esp + 12);
    782     uint32_t count = MEM32(g_esp + 16), entries = MEM32(g_esp + 20);
    783     g_esp += 24;
    784     g_eax = 0x80070057u;
    785     if (flags || !entries || !count || start >= palette->count || count > palette->count - start) return;
    786     unsigned char *data = palette->entries + start * palette->entry_size;
    787     if (current_slot == 4) memcpy((void *)ADDR(entries), data, count * palette->entry_size);
    788     else {
    789         memcpy(data, (void *)ADDR(entries), count * palette->entry_size);
    790         palette_fixed_colors(palette);
    791     }
    792     g_eax = 0;
    793 }
    794 
    795 static void palette_initialize(void)
    796 {
    797     find_palette(MEM32(g_esp + 4));
    798     g_eax = 0x88760005u; /* DDERR_ALREADYINITIALIZED */
    799     g_esp += 20;
    800 }
    801 
    802 static uint32_t release_clipper(struct clipper_object *clipper)
    803 {
    804     uint32_t remaining = --clipper->references;
    805     if (!remaining) {
    806         struct clipper_object **link = &clippers;
    807         while (*link != clipper) link = &(*link)->next;
    808         *link = clipper->next;
    809         release_draw(clipper->owner, 1);
    810         guest_free(clipper->interface);
    811         free(clipper);
    812     }
    813     return remaining;
    814 }
    815 
    816 static void create_clipper(void)
    817 {
    818     struct draw_object *owner = find_object(MEM32(g_esp + 4));
    819     uint32_t flags = MEM32(g_esp + 8), output = MEM32(g_esp + 12), outer = MEM32(g_esp + 16);
    820     g_esp += 20;
    821     g_eax = 0x80070057u;
    822     if (!output || flags || outer) return;
    823     struct clipper_object *clipper = calloc(1, sizeof(*clipper));
    824     if (!clipper) abort();
    825     clipper->interface = create_interface(5);
    826     clipper->references = 1;
    827     clipper->owner = owner;
    828     ++owner->references[1];
    829     clipper->next = clippers;
    830     clippers = clipper;
    831     MEM32(output) = clipper->interface;
    832     g_eax = 0;
    833 }
    834 
    835 static void clipper_query_interface(void)
    836 {
    837     struct clipper_object *clipper = find_clipper(MEM32(g_esp + 4));
    838     uint32_t iid = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
    839     const uint32_t unknown[] = {0, 0, 0xc0, 0x46000000};
    840     const uint32_t clipper_iid[] = {0x6c14db85, 0x11cea733, 0x200021a5, 0x60e50baf};
    841     g_esp += 16;
    842     g_eax = 0x80070057u;
    843     if (!output) return;
    844     MEM32(output) = 0;
    845     g_eax = 0x80004002u;
    846     if (memcmp((void *)ADDR(iid), unknown, 16) && memcmp((void *)ADDR(iid), clipper_iid, 16)) return;
    847     MEM32(output) = clipper->interface;
    848     ++clipper->references;
    849     g_eax = 0;
    850 }
    851 
    852 static void clipper_add_reference(void)
    853 {
    854     g_eax = ++find_clipper(MEM32(g_esp + 4))->references;
    855     g_esp += 8;
    856 }
    857 
    858 static void clipper_release_reference(void)
    859 {
    860     g_eax = release_clipper(find_clipper(MEM32(g_esp + 4)));
    861     g_esp += 8;
    862 }
    863 
    864 static void clipper_set_window(void)
    865 {
    866     struct clipper_object *clipper = find_clipper(MEM32(g_esp + 4));
    867     uint32_t flags = MEM32(g_esp + 8), handle = MEM32(g_esp + 12);
    868     g_eax = 0x80070057u;
    869     if (!flags && (!handle || linux_window_native(handle))) { clipper->window = handle; g_eax = 0; }
    870     g_esp += 16;
    871 }
    872 
    873 static void clipper_get_window(void)
    874 {
    875     struct clipper_object *clipper = find_clipper(MEM32(g_esp + 4));
    876     uint32_t output = MEM32(g_esp + 8);
    877     g_eax = 0x80070057u;
    878     if (output) { MEM32(output) = clipper->window; g_eax = 0; }
    879     g_esp += 12;
    880 }
    881 
    882 static void clipper_get_list(void)
    883 {
    884     struct clipper_object *clipper = find_clipper(MEM32(g_esp + 4));
    885     uint32_t filter = MEM32(g_esp + 8), output = MEM32(g_esp + 12), size = MEM32(g_esp + 16);
    886     g_esp += 20;
    887     g_eax = 0x80070057u;
    888     if (!size) return;
    889     if (output && MEM32(size) >= 12) MEM32(output + 8) = 0;
    890     if (!clipper->window) { g_eax = 0x887600cdu; return; }
    891     SDL_Window *native = linux_window_native(clipper->window);
    892     if (!native) { g_eax = 0x80004005u; return; }
    893 
    894     /* SDL/compositor owns occlusion; the virtual primary clips to our client area. */
    895     SDL_Rect bounds = {0};
    896     if (!(SDL_GetWindowFlags(native) & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED))) {
    897         SDL_GetWindowPosition(native, &bounds.x, &bounds.y);
    898         SDL_GetWindowSize(native, &bounds.w, &bounds.h);
    899     }
    900     if (filter) {
    901         SDL_Rect subset = {(int32_t)MEM32(filter), (int32_t)MEM32(filter + 4),
    902             (int32_t)(MEM32(filter + 8) - MEM32(filter)), (int32_t)(MEM32(filter + 12) - MEM32(filter + 4))};
    903         SDL_Rect intersection;
    904         if (SDL_IntersectRect(&bounds, &subset, &intersection)) bounds = intersection;
    905         else bounds = (SDL_Rect){0};
    906     }
    907     unsigned count = bounds.w > 0 && bounds.h > 0 ? 1 : 0;
    908     uint32_t required = 32 + count * 16;
    909     if (!output) { MEM32(size) = required; g_eax = 0; return; }
    910     if (MEM32(size) < required) { g_eax = 0x88760236u; return; }
    911     memset((void *)ADDR(output), 0, required);
    912     MEM32(output) = 32;
    913     MEM32(output + 4) = 1; /* RDH_RECTANGLES */
    914     MEM32(output + 8) = count;
    915     MEM32(output + 12) = count * 16;
    916     if (count) {
    917         MEM32(output + 16) = bounds.x;
    918         MEM32(output + 20) = bounds.y;
    919         MEM32(output + 24) = bounds.x + bounds.w;
    920         MEM32(output + 28) = bounds.y + bounds.h;
    921         memcpy((void *)ADDR(output + 32), (void *)ADDR(output + 16), 16);
    922     }
    923     g_eax = 0;
    924 }
    925 
    926 /* Mix arena and block offsets so interfaces 64 KiB apart do not share a bucket. */
    927 static unsigned interface_bucket(uint32_t address)
    928 {
    929     return ((address >> 4) * 2654435761u) >> 20;
    930 }
    931 
    932 static struct surface_object *find_surface(uint32_t address)
    933 {
    934     unsigned bucket = interface_bucket(address);
    935     for (unsigned i = 0; i < 2; ++i)
    936         for (struct surface_object *surface = surface_buckets[i][bucket]; surface; surface = surface->bucket_next[i])
    937             if (surface->interfaces[i] == address) return surface;
    938     fprintf(stderr, "Invalid guest surface interface %08x\n", address);
    939     abort();
    940 }
    941 
    942 /* Each live COM identity has its own chain, including older surface aliases. */
    943 static void create_surface_interface(struct surface_object *surface, unsigned index)
    944 {
    945     surface->interfaces[index] = create_interface(index + 3);
    946     unsigned bucket = interface_bucket(surface->interfaces[index]);
    947     surface->bucket_next[index] = surface_buckets[index][bucket];
    948     surface_buckets[index][bucket] = surface;
    949 }
    950 
    951 static void destroy_surface_interface(struct surface_object *surface, unsigned index)
    952 {
    953     struct surface_object **link = &surface_buckets[index][interface_bucket(surface->interfaces[index])];
    954     while (*link != surface) link = &(*link)->bucket_next[index];
    955     *link = surface->bucket_next[index];
    956     guest_free(surface->interfaces[index]);
    957     surface->interfaces[index] = 0;
    958 }
    959 
    960 static uint32_t release_surface(struct surface_object *surface, unsigned index);
    961 enum surface_transfer { SURFACE_READ, SURFACE_WRITE, SURFACE_EVICT };
    962 static void transfer_surface_pixels(struct surface_object *surface, enum surface_transfer operation);
    963 
    964 static void create_surface(void)
    965 {
    966     struct draw_object *owner = find_object(MEM32(g_esp + 4));
    967     uint32_t desc = MEM32(g_esp + 8), output = MEM32(g_esp + 12), outer = MEM32(g_esp + 16);
    968     g_eax = 0x80070057u;
    969     g_esp += 20;
    970     if (!output || !desc || MEM32(desc) != 124) return;
    971     MEM32(output) = 0;
    972     uint32_t flags = MEM32(desc + 4), caps = MEM32(desc + 104);
    973     uint32_t width = MEM32(desc + 12), height = MEM32(desc + 8);
    974     int depth = flags == 0x1007 && caps == 0x24000;
    975     int mip = (caps & 0x400008) == 0x400008;
    976     int texture = (mip || !(caps & 0x400008)) && ((flags & ~0x20000u) == 0x1007 || (flags & ~0x20000u) == 0x101007) &&
    977         ((caps & ~0x400008u) == 0x1000 || (caps & ~0x400008u) == 0x5000);
    978     if (outer || !((flags == 1 && caps == 0x200) || depth || texture ||
    979         (flags == 7 && (caps == 0x40 || caps == 0x840 || caps == 0x2040 || caps == 0x6040)))) {
    980         fprintf(stderr, "Unsupported DirectDraw surface flags=%08x caps=%08x outer=%08x\n", flags, caps, outer);
    981         exit(3);
    982     }
    983     if (texture) {
    984         const uint32_t rgb[] = {32, 0x40, 0, 32, 0xff0000, 0xff00, 0xff, 0};
    985         const uint32_t argb[] = {32, 0x41, 0, 32, 0xff0000, 0xff00, 0xff, 0xff000000};
    986         const uint32_t rgb565[] = {32, 0x40, 0, 16, 0xf800, 0x7e0, 0x1f, 0};
    987         if ((memcmp((void *)ADDR(desc + 72), rgb, 32) && memcmp((void *)ADDR(desc + 72), argb, 32) &&
    988              memcmp((void *)ADDR(desc + 72), rgb565, 32)) ||
    989             (MEM32(desc + 108) != 0 && MEM32(desc + 108) != 0x10) ||
    990             MEM32(desc + 112) || MEM32(desc + 116) || ((flags & 0x100000) && MEM32(desc + 120)) ||
    991             (MEM32(desc + 108) && (caps & ~0x400008u) != 0x1000)) {
    992             fprintf(stderr, "Unsupported texture format or extended caps\n"); exit(3);
    993         }
    994     }
    995     if (depth) {
    996         const uint32_t format16[] = {32, 0x400, 0, 16, 0, 0xffff, 0, 0};
    997         const uint32_t format24[] = {32, 0x400, 0, 24, 0, 0xffffff, 0, 0};
    998         const uint32_t format32[] = {32, 0x400, 0, 32, 0, 0xffffffffu, 0, 0};
    999         /* Match the unsupported format response and allow AO's depth fallback. */
   1000         if (!memcmp((void *)ADDR(desc + 72), format32, 32)) { g_eax = 0x80004001u; return; }
   1001         if (memcmp((void *)ADDR(desc + 72), format24, 32) && memcmp((void *)ADDR(desc + 72), format16, 32)) {
   1002             fprintf(stderr, "Unsupported depth pixel format flags=%08x bits=%u\n", MEM32(desc + 76), MEM32(desc + 84));
   1003             exit(3);
   1004         }
   1005     }
   1006     if (caps == 0x200) {
   1007         for (struct surface_object *surface = surfaces; surface; surface = surface->next)
   1008             if (surface->owner == owner && (surface->caps & 0x200)) { g_eax = 0x88760234u; return; }
   1009         SDL_DisplayMode mode;
   1010         if (linux_graphics_display_mode(&mode)) abort();
   1011         width = mode.w;
   1012         height = mode.h;
   1013         caps |= 0x8000; /* DDSCAPS_VISIBLE */
   1014     }
   1015     if (!width || !height || width > (uint32_t)maximum_texture_size || height > (uint32_t)maximum_texture_size ||
   1016         (uint64_t)width * height * 4 > UINT32_MAX) return;
   1017     unsigned levels = 1;
   1018     if (mip) {
   1019         for (unsigned extent = width > height ? width : height; extent > 1; extent >>= 1) ++levels;
   1020         if ((flags & 0x20000) && MEM32(desc + 24)) {
   1021             if (MEM32(desc + 24) > levels) return;
   1022             levels = MEM32(desc + 24);
   1023         }
   1024     }
   1025     struct surface_object *first = NULL, *previous = NULL;
   1026     for (unsigned level = 0; level < levels; ++level) {
   1027         struct surface_object *surface = calloc(1, sizeof(*surface));
   1028         if (!surface) abort();
   1029         if (depth) {
   1030             surface->depth_bits = MEM32(desc + 84);
   1031             surface->depth = gl_depth_create(width, height, surface->depth_bits);
   1032         }
   1033         else surface->target = gl_target_create(width, height, !texture);
   1034         if (!surface->target && !surface->depth) { free(surface); if (first) release_surface(first, 0); g_eax = 0x8007000eu; return; }
   1035         if (texture) {
   1036             surface->alpha = MEM32(desc + 76) & 1;
   1037             surface->caps2 = MEM32(desc + 108);
   1038         }
   1039         surface->width = width;
   1040         surface->height = height;
   1041         surface->rgb_bits = texture ? MEM32(desc + 84) : 32;
   1042         surface->pitch = width * (surface->rgb_bits / 8);
   1043         if (mip) surface->pitch = (surface->pitch + 7) & ~7u;
   1044         surface->mip_count = mip ? levels - level : 0;
   1045         if (level) surface->caps2 |= 0x10000; /* DDSCAPS2_MIPMAPSUBLEVEL */
   1046         surface->caps = caps | (((surface->caps2 & 0x10) || (caps & 0x800)) ? 0x800u : 0x10004000u);
   1047         if (surface->caps & 0x800) {
   1048             /* System-memory surfaces retain CPU storage and upload writes on unlock. */
   1049             surface->pixels = guest_malloc(surface->pitch * height);
   1050             if (!surface->pixels) {
   1051                 gl_target_destroy(surface->target); free(surface); if (first) release_surface(first, 0); g_eax = 0x8007000eu; return;
   1052             }
   1053             memset((void *)ADDR(surface->pixels), 0, surface->pitch * height);
   1054             transfer_surface_pixels(surface, SURFACE_WRITE);
   1055         }
   1056         surface->description_flags = 0x100f | (flags & 0x100000) | (mip ? 0x20000 : 0);
   1057         surface->owner = owner;
   1058         owner->references[1] += mip ? (level ? 0 : 2) : 1;
   1059         create_surface_interface(surface, 0);
   1060         surface->references[0] = 1;
   1061         surface->next = surfaces;
   1062         surfaces = surface;
   1063         if (!first) first = surface;
   1064         else {
   1065             previous->attached = surface;
   1066             gl_target_set_mip(previous->target, surface->target);
   1067         }
   1068         previous = surface;
   1069         width = width > 1 ? width / 2 : 1;
   1070         height = height > 1 ? height / 2 : 1;
   1071     }
   1072     MEM32(output) = first->interfaces[0];
   1073     g_eax = 0;
   1074 }
   1075 
   1076 static void surface_query_interface(void)
   1077 {
   1078     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1079     uint32_t iid = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   1080     static const uint32_t unknown[] = {0, 0, 0xc0, 0x46000000};
   1081     static const uint32_t surface1[] = {0x6c14db81, 0x11cea733, 0x200021a5, 0x60e50baf};
   1082     static const uint32_t surface7[] = {0x06675a80, 0x11d23b9b, 0x60002fb9, 0x5bea9797};
   1083     g_esp += 16;
   1084     if (!output) { g_eax = 0x80070057u; return; }
   1085     unsigned index;
   1086     if (!memcmp((void *)ADDR(iid), surface7, 16)) index = 0;
   1087     else if (!memcmp((void *)ADDR(iid), unknown, 16) || !memcmp((void *)ADDR(iid), surface1, 16)) index = 1;
   1088     else { MEM32(output) = 0; g_eax = 0x80004002u; return; }
   1089     if (!surface->interfaces[index]) create_surface_interface(surface, index);
   1090     ++surface->references[index];
   1091     MEM32(output) = surface->interfaces[index];
   1092     g_eax = 0;
   1093 }
   1094 
   1095 static void surface_add_reference(void)
   1096 {
   1097     uint32_t address = MEM32(g_esp + 4);
   1098     struct surface_object *surface = find_surface(address);
   1099     g_eax = ++surface->references[address == surface->interfaces[0] ? 0 : 1];
   1100     g_esp += 8;
   1101 }
   1102 
   1103 static uint32_t release_surface(struct surface_object *surface, unsigned index)
   1104 {
   1105     uint32_t remaining = --surface->references[index];
   1106     if (!remaining) destroy_surface_interface(surface, index);
   1107     if (!surface->references[0] && !surface->references[1]) {
   1108         struct surface_object **link = &surfaces;
   1109         while (*link != surface) link = &(*link)->next;
   1110         *link = surface->next;
   1111         while (surface->data) {
   1112             struct surface_data *next = surface->data->next;
   1113             free(surface->data);
   1114             surface->data = next;
   1115         }
   1116         if (surface->attached) {
   1117             /* Implicit mip attachments are destroyed with their parent even if
   1118              * callers retain a sublevel interface, as in DirectDraw. */
   1119             if (surface->mip_count) {
   1120                 if (surface->attached->interfaces[1]) destroy_surface_interface(surface->attached, 1);
   1121                 surface->attached->references[1] = 0;
   1122                 surface->attached->references[0] = 1;
   1123             }
   1124             release_surface(surface->attached, 0);
   1125         }
   1126         /* Release implicit children before the texture backing their mip levels. */
   1127         if (surface->target) gl_target_destroy(surface->target);
   1128         if (surface->depth) gl_depth_destroy(surface->depth);
   1129         if (surface->clipper) release_clipper(surface->clipper);
   1130         guest_free(surface->pixels);
   1131         if (!(surface->caps2 & 0x10000)) {
   1132             if (surface->mip_count) release_draw(surface->owner, 1);
   1133             release_draw(surface->owner, 1);
   1134         }
   1135         free(surface);
   1136     }
   1137     return remaining;
   1138 }
   1139 
   1140 static void surface_release_reference(void)
   1141 {
   1142     uint32_t address = MEM32(g_esp + 4);
   1143     struct surface_object *surface = find_surface(address);
   1144     g_eax = release_surface(surface, address == surface->interfaces[0] ? 0 : 1);
   1145     g_esp += 8;
   1146 }
   1147 
   1148 static struct surface_data **surface_data_link(struct surface_object *surface, uint32_t guid)
   1149 {
   1150     struct surface_data **link = &surface->data;
   1151     while (*link && memcmp((*link)->guid, (void *)ADDR(guid), 16)) link = &(*link)->next;
   1152     return link;
   1153 }
   1154 
   1155 static void surface_set_private_data(void)
   1156 {
   1157     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1158     uint32_t guid = MEM32(g_esp + 8), input = MEM32(g_esp + 12);
   1159     uint32_t size = MEM32(g_esp + 16), flags = MEM32(g_esp + 20);
   1160     g_esp += 24;
   1161     if (flags) { fprintf(stderr, "Unsupported surface private-data flags=%08x\n", flags); exit(3); }
   1162     g_eax = 0x80070057u;
   1163     if (!guid || !input || !size) return;
   1164     struct surface_data *data = malloc(sizeof(*data) + (size_t)size);
   1165     if (!data) { g_eax = 0x8007000eu; return; }
   1166     memcpy(data->guid, (void *)ADDR(guid), 16);
   1167     memcpy(data->bytes, (void *)ADDR(input), size);
   1168     data->size = size;
   1169     struct surface_data **link = surface_data_link(surface, guid);
   1170     data->next = *link ? (*link)->next : NULL;
   1171     free(*link);
   1172     *link = data;
   1173     g_eax = 0;
   1174 }
   1175 
   1176 static void surface_get_private_data(void)
   1177 {
   1178     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1179     uint32_t guid = MEM32(g_esp + 8), output = MEM32(g_esp + 12), size = MEM32(g_esp + 16);
   1180     g_esp += 20;
   1181     g_eax = 0x80070057u;
   1182     if (!guid || !size) return;
   1183     struct surface_data *data = *surface_data_link(surface, guid);
   1184     g_eax = 0x887600ffu; /* DDERR_NOTFOUND leaves the size unchanged. */
   1185     if (!data) return;
   1186     uint32_t capacity = MEM32(size);
   1187     MEM32(size) = data->size;
   1188     if (capacity < data->size) { g_eax = 0x887602b2u; return; }
   1189     g_eax = 0x80070057u;
   1190     if (!output) return;
   1191     memcpy((void *)ADDR(output), data->bytes, data->size);
   1192     g_eax = 0;
   1193 }
   1194 
   1195 static void surface_free_private_data(void)
   1196 {
   1197     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1198     uint32_t guid = MEM32(g_esp + 8);
   1199     g_esp += 12;
   1200     g_eax = 0x80070057u;
   1201     if (!guid) return;
   1202     struct surface_data **link = surface_data_link(surface, guid);
   1203     g_eax = 0x887600ffu;
   1204     if (!*link) return;
   1205     struct surface_data *data = *link;
   1206     *link = data->next;
   1207     free(data);
   1208     g_eax = 0;
   1209 }
   1210 
   1211 static void surface_pixel_format(struct surface_object *surface, uint32_t output)
   1212 {
   1213     const uint32_t format[] = {32, 0x40 | surface->alpha, 0, 32, 0xff0000, 0xff00, 0xff,
   1214         surface->alpha ? 0xff000000u : 0};
   1215     const uint32_t depth[] = {32, 0x400, 0, surface->depth_bits, 0,
   1216         surface->depth_bits == 16 ? 0xffff : 0xffffff, 0, 0};
   1217     const uint32_t rgb565[] = {32, 0x40, 0, 16, 0xf800, 0x7e0, 0x1f, 0};
   1218     memcpy((void *)ADDR(output), surface->depth ? depth : surface->rgb_bits == 16 ? rgb565 : format, sizeof(format));
   1219 }
   1220 
   1221 static void describe_surface(struct surface_object *surface, uint32_t output)
   1222 {
   1223     memset((void *)ADDR(output), 0, 124);
   1224     MEM32(output) = 124;
   1225     MEM32(output + 4) = surface->description_flags;
   1226     MEM32(output + 8) = surface->height;
   1227     MEM32(output + 12) = surface->width;
   1228     MEM32(output + 16) = surface->pitch;
   1229     MEM32(output + 24) = surface->mip_count;
   1230     surface_pixel_format(surface, output + 72);
   1231     MEM32(output + 104) = surface->caps;
   1232     MEM32(output + 108) = surface->caps2;
   1233 }
   1234 
   1235 static void surface_description(void)
   1236 {
   1237     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1238     uint32_t output = MEM32(g_esp + 8);
   1239     g_eax = 0x80070057u;
   1240     if (output && MEM32(output) == 124) { describe_surface(surface, output); g_eax = 0; }
   1241     g_esp += 12;
   1242 }
   1243 
   1244 static void surface_get_pixel_format(void)
   1245 {
   1246     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1247     uint32_t output = MEM32(g_esp + 8);
   1248     g_eax = 0x80070057u;
   1249     if (output && MEM32(output) == 32) { surface_pixel_format(surface, output); g_eax = 0; }
   1250     g_esp += 12;
   1251 }
   1252 
   1253 static void surface_owner(void)
   1254 {
   1255     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1256     uint32_t output = MEM32(g_esp + 8);
   1257     g_eax = 0x80070057u;
   1258     if (output) { MEM32(output) = interface_pointer(surface->owner, 1); g_eax = 0; }
   1259     g_esp += 12;
   1260 }
   1261 
   1262 static void surface_set_clipper(void)
   1263 {
   1264     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1265     uint32_t address = MEM32(g_esp + 8);
   1266     struct clipper_object *clipper = address ? find_clipper(address) : NULL;
   1267     g_eax = 0;
   1268     if (!clipper && !surface->clipper) g_eax = 0x88760238u;
   1269     if (clipper != surface->clipper) {
   1270         if (clipper) ++clipper->references;
   1271         if (surface->clipper) release_clipper(surface->clipper);
   1272         surface->clipper = clipper;
   1273     }
   1274     g_esp += 12;
   1275 }
   1276 
   1277 static void surface_get_clipper(void)
   1278 {
   1279     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1280     uint32_t output = MEM32(g_esp + 8);
   1281     g_eax = 0x80070057u;
   1282     if (output) {
   1283         MEM32(output) = 0;
   1284         g_eax = 0x88760238u;
   1285         if (surface->clipper) {
   1286             MEM32(output) = surface->clipper->interface;
   1287             ++surface->clipper->references;
   1288             g_eax = 0;
   1289         }
   1290     }
   1291     g_esp += 12;
   1292 }
   1293 
   1294 static void surface_not_lost(void)
   1295 {
   1296     find_surface(MEM32(g_esp + 4));
   1297     /* Windowed FBOs survive focus and size changes in this persistent context. */
   1298     g_eax = 0;
   1299     g_esp += 8;
   1300 }
   1301 
   1302 static void surface_attach(void)
   1303 {
   1304     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1305     struct surface_object *depth = find_surface(MEM32(g_esp + 8));
   1306     g_esp += 12;
   1307     if (!surface->target || !depth->depth || surface->width != depth->width || surface->height != depth->height) {
   1308         fprintf(stderr, "Unsupported surface attachment\n"); exit(3);
   1309     }
   1310     if (surface->attached) { g_eax = 0x8876019au; return; }
   1311     surface->attached = depth;
   1312     ++depth->references[0];
   1313     gl_target_set_depth(surface->target, depth->depth);
   1314     g_eax = 0;
   1315 }
   1316 
   1317 static void surface_get_attached(void)
   1318 {
   1319     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1320     uint32_t caps = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   1321     g_esp += 16;
   1322     g_eax = 0x80070057u;
   1323     if (!caps || !output) return;
   1324     MEM32(output) = 0;
   1325     g_eax = 0x887600ffu; /* DDERR_NOTFOUND */
   1326     if (surface->attached && (surface->attached->caps & MEM32(caps)) == MEM32(caps) &&
   1327         (surface->attached->caps2 & MEM32(caps + 4)) == MEM32(caps + 4) &&
   1328         !MEM32(caps + 8) && !MEM32(caps + 12)) {
   1329         MEM32(output) = surface->attached->interfaces[0];
   1330         ++surface->attached->references[0];
   1331         g_eax = 0;
   1332     }
   1333 }
   1334 
   1335 static void surface_detach(void)
   1336 {
   1337     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1338     uint32_t flags = MEM32(g_esp + 8), address = MEM32(g_esp + 12);
   1339     g_esp += 16;
   1340     g_eax = 0x80070057u;
   1341     if (flags) return;
   1342     if (!surface->attached || surface->attached->interfaces[0] != address) { g_eax = 0x887601ccu; return; }
   1343     if (surface->mip_count) { g_eax = 0x88760014u; return; } /* DDERR_CANNOTDETACHSURFACE */
   1344     gl_target_set_depth(surface->target, NULL);
   1345     release_surface(surface->attached, 0);
   1346     surface->attached = NULL;
   1347     g_eax = 0;
   1348 }
   1349 
   1350 static void swap_surface_channels(struct surface_object *surface)
   1351 {
   1352     if (surface->rgb_bits == 16) return;
   1353     unsigned char *pixels = (void *)ADDR(surface->pixels);
   1354     unsigned width = surface->width, height = surface->height, pitch = surface->pitch;
   1355     for (unsigned y = 0; y < height; ++y)
   1356     for (unsigned x = 0; x < width; ++x) {
   1357         size_t i = (size_t)y * pitch + x * 4;
   1358         unsigned char red = pixels[i];
   1359         pixels[i] = pixels[i + 2];
   1360         pixels[i + 2] = red;
   1361     }
   1362 }
   1363 
   1364 static void transfer_surface_pixels(struct surface_object *surface, enum surface_transfer operation)
   1365 {
   1366     unsigned char *pixels = (void *)ADDR(surface->pixels), *packed = pixels;
   1367     if (surface->rgb_bits == 16) {
   1368         /* Keep the guest's RGB565 lock layout while the renderer stores RGBA8. */
   1369         packed = malloc((size_t)surface->width * surface->height * 4);
   1370         if (!packed) abort();
   1371         if (operation == SURFACE_READ) gl_target_read(surface->target, packed);
   1372         for (unsigned y = 0; y < surface->height; ++y)
   1373         for (unsigned x = 0; x < surface->width; ++x) {
   1374             uint16_t *pixel = (void *)(pixels + y * surface->pitch + x * 2);
   1375             unsigned char *rgba = packed + (y * surface->width + x) * 4;
   1376             if (operation == SURFACE_READ) {
   1377                 *pixel = (rgba[0] >> 3 << 11) | (rgba[1] >> 2 << 5) | (rgba[2] >> 3);
   1378             } else {
   1379                 unsigned red = *pixel >> 11, green = (*pixel >> 5) & 63, blue = *pixel & 31;
   1380                 rgba[0] = (red << 3) | (red >> 2);
   1381                 rgba[1] = (green << 2) | (green >> 4);
   1382                 rgba[2] = (blue << 3) | (blue >> 2);
   1383                 rgba[3] = 255;
   1384             }
   1385         }
   1386         if (operation == SURFACE_WRITE) gl_target_write(surface->target, packed);
   1387         else if (operation == SURFACE_EVICT) gl_target_evict(surface->target, packed);
   1388         free(packed);
   1389         return;
   1390     }
   1391     if (surface->pitch != surface->width * 4) {
   1392         packed = malloc((size_t)surface->width * surface->height * 4);
   1393         if (!packed) abort();
   1394         if (operation != SURFACE_READ) for (unsigned y = 0; y < surface->height; ++y)
   1395             memcpy(packed + y * surface->width * 4, pixels + y * surface->pitch, surface->width * 4);
   1396     }
   1397     if (operation == SURFACE_EVICT) gl_target_evict(surface->target, packed);
   1398     else if (operation == SURFACE_WRITE) gl_target_write(surface->target, packed);
   1399     else gl_target_read(surface->target, packed);
   1400     if (packed != pixels) {
   1401         if (operation == SURFACE_READ) for (unsigned y = 0; y < surface->height; ++y)
   1402             memcpy(pixels + y * surface->pitch, packed + y * surface->width * 4, surface->width * 4);
   1403         free(packed);
   1404     }
   1405 }
   1406 
   1407 /* Keep intermediate mip pixels in guest format until a complete update finishes. */
   1408 static void flush_surface_write(struct surface_object *surface)
   1409 {
   1410     if (!surface->pending_write) return;
   1411     swap_surface_channels(surface);
   1412     transfer_surface_pixels(surface, SURFACE_WRITE);
   1413     if (surface->texture_updates || ((surface->caps & 0x800) && !(surface->caps2 & 0x10)))
   1414         swap_surface_channels(surface);
   1415     surface->pending_write = 0;
   1416 }
   1417 
   1418 uint32_t linux_graphics_begin_texture_update(uint32_t address)
   1419 {
   1420     struct surface_object *surface = find_surface(address);
   1421     if (!(surface->caps & 0x1000)) return 0;
   1422     for (struct surface_object *mip = surface; mip; mip = mip->attached)
   1423         if (mip->locked || mip->depth) return 0;
   1424     for (struct surface_object *mip = surface; mip; mip = mip->attached) ++mip->texture_updates;
   1425     return address;
   1426 }
   1427 
   1428 void linux_graphics_end_texture_update(uint32_t address)
   1429 {
   1430     if (!address) return;
   1431     for (struct surface_object *surface = find_surface(address); surface; surface = surface->attached) {
   1432         assert(surface->texture_updates && !surface->locked);
   1433         if (--surface->texture_updates) continue;
   1434         flush_surface_write(surface);
   1435         if (!(surface->caps & 0x800) || (surface->caps2 & 0x10)) {
   1436             guest_free(surface->pixels);
   1437             surface->pixels = 0;
   1438         }
   1439     }
   1440 }
   1441 
   1442 static void evict_managed_textures(void)
   1443 {
   1444     struct draw_object *owner = find_object(MEM32(g_esp + 4));
   1445     /* Preserve managed contents on the CPU only while GPU storage is evicted. */
   1446     for (struct surface_object *surface = surfaces; surface; surface = surface->next) {
   1447         if (surface->owner != owner || !(surface->caps2 & 0x10)) continue;
   1448         if (surface->pixels) {
   1449             swap_surface_channels(surface);
   1450             transfer_surface_pixels(surface, SURFACE_EVICT);
   1451             swap_surface_channels(surface);
   1452             surface->pending_write = 0;
   1453         } else gl_target_evict(surface->target, NULL);
   1454         if (!surface->locked) {
   1455             guest_free(surface->pixels);
   1456             surface->pixels = 0;
   1457         }
   1458     }
   1459     g_eax = 0;
   1460     g_esp += 8;
   1461 }
   1462 
   1463 static void surface_lock(void)
   1464 {
   1465     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1466     uint32_t rect = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   1467     uint32_t flags = MEM32(g_esp + 16), event = MEM32(g_esp + 20);
   1468     g_esp += 24;
   1469     g_eax = 0x80070057u;
   1470     if (!output || MEM32(output) != 124) return;
   1471     MEM32(output + 36) = 0;
   1472     if (surface->depth || event || (flags & ~0x831u)) {
   1473         fprintf(stderr, "Unsupported surface lock rect=%08x flags=%08x event=%08x\n", rect, flags, event);
   1474         exit(3);
   1475     }
   1476     if (surface->locked) { g_eax = 0x887601aeu; return; }
   1477     int32_t rectangle[] = {0, 0, surface->width, surface->height};
   1478     if (rect) memcpy(rectangle, (void *)ADDR(rect), 16);
   1479     if (rectangle[0] < 0 || rectangle[1] < 0 || rectangle[2] < rectangle[0] || rectangle[3] < rectangle[1] ||
   1480         rectangle[2] > (int32_t)surface->width || rectangle[3] > (int32_t)surface->height) return;
   1481     int readback = !surface->pixels || (!(surface->caps & 0x800) && !surface->texture_updates);
   1482     if (!surface->pixels) surface->pixels = guest_malloc(surface->pitch * surface->height);
   1483     if (!surface->pixels) { g_eax = 0x8007000eu; return; }
   1484     if (readback) {
   1485         transfer_surface_pixels(surface, SURFACE_READ);
   1486         swap_surface_channels(surface);
   1487     }
   1488     surface->locked = 1;
   1489     surface->lock_flags = flags;
   1490     memcpy(surface->lock_rectangle, rectangle, 16);
   1491     describe_surface(surface, output);
   1492     MEM32(output + 36) = surface->pixels + rectangle[1] * surface->pitch + rectangle[0] * (surface->rgb_bits / 8);
   1493     g_eax = 0;
   1494 }
   1495 
   1496 static void surface_unlock(void)
   1497 {
   1498     struct surface_object *surface = find_surface(MEM32(g_esp + 4));
   1499     uint32_t rect = MEM32(g_esp + 8);
   1500     g_esp += 12;
   1501     if (!surface->locked || (rect && memcmp((void *)ADDR(rect), surface->lock_rectangle, 16))) {
   1502         g_eax = 0x88760248u; return;
   1503     }
   1504     if (surface->texture_updates) {
   1505         if (!(surface->lock_flags & 0x10)) surface->pending_write = 1;
   1506         surface->locked = 0;
   1507         g_eax = 0;
   1508         return;
   1509     }
   1510     int temporary = !(surface->caps & 0x800) || (surface->caps2 & 0x10);
   1511     if (!(surface->lock_flags & 0x10)) {
   1512         swap_surface_channels(surface);
   1513         transfer_surface_pixels(surface, SURFACE_WRITE);
   1514         if (!temporary) swap_surface_channels(surface);
   1515     }
   1516     surface->locked = 0;
   1517     /* GPU-backed pixels are temporary; ordinary system-memory surfaces retain them. */
   1518     if (temporary) {
   1519         guest_free(surface->pixels);
   1520         surface->pixels = 0;
   1521     }
   1522     g_eax = 0;
   1523 }
   1524 
   1525 static void surface_blit(void)
   1526 {
   1527     struct surface_object *target = find_surface(MEM32(g_esp + 4));
   1528     uint32_t target_rect = MEM32(g_esp + 8), source_address = MEM32(g_esp + 12);
   1529     uint32_t source_rect = MEM32(g_esp + 16), flags = MEM32(g_esp + 20), effects = MEM32(g_esp + 24);
   1530     g_esp += 28;
   1531     int primary = (target->caps & 0x200) != 0;
   1532     if (!source_address || (flags & ~0x01000200u) || effects ||
   1533         (target->clipper && !primary) || (primary && !target->clipper)) {
   1534         fprintf(stderr, "Unsupported surface blit flags=%08x effects=%08x caps=%08x\n", flags, effects, target->caps); exit(3);
   1535     }
   1536     struct surface_object *source = find_surface(source_address);
   1537     if (source == target || source->depth || target->depth) {
   1538         fprintf(stderr, "Self/depth surface blits are not implemented\n"); exit(3);
   1539     }
   1540     if (source->alpha != target->alpha) {
   1541         fprintf(stderr, "Surface blit format conversion is not implemented\n"); exit(3);
   1542     }
   1543     if (source->locked || target->locked) { g_eax = 0x887601aeu; return; }
   1544     int32_t from[] = {0, 0, source->width, source->height}, to[] = {0, 0, target->width, target->height};
   1545     if (source_rect) memcpy(from, (void *)ADDR(source_rect), 16);
   1546     if (target_rect) memcpy(to, (void *)ADDR(target_rect), 16);
   1547     g_eax = 0x80070057u;
   1548     if (from[0] < 0 || from[1] < 0 || from[2] <= from[0] || from[3] <= from[1] ||
   1549         from[2] > (int32_t)source->width || from[3] > (int32_t)source->height ||
   1550         to[2] <= to[0] || to[3] <= to[1]) return;
   1551     if ((int64_t)from[2] - from[0] != (int64_t)to[2] - to[0] || (int64_t)from[3] - from[1] != (int64_t)to[3] - to[1]) {
   1552         fprintf(stderr, "Stretched surface blits are not implemented\n"); exit(3);
   1553     }
   1554     SDL_Window *native = NULL;
   1555     int32_t client[4];
   1556     if (primary) {
   1557         native = linux_window_native(target->clipper->window);
   1558         if (!native) { g_eax = 0x80004005u; return; }
   1559         if (SDL_GetWindowFlags(native) & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED)) goto done;
   1560         int x, y, width, height;
   1561         SDL_GetWindowPosition(native, &x, &y);
   1562         SDL_GetWindowSize(native, &width, &height);
   1563         client[0] = x; client[1] = y; client[2] = x + width; client[3] = y + height;
   1564         int32_t clipped[] = {x < 0 ? 0 : x, y < 0 ? 0 : y,
   1565             client[2] > (int32_t)target->width ? (int32_t)target->width : client[2],
   1566             client[3] > (int32_t)target->height ? (int32_t)target->height : client[3]};
   1567         for (unsigned i = 0; i < 4; ++i)
   1568             if (i < 2 ? clipped[i] < to[i] : clipped[i] > to[i]) clipped[i] = to[i];
   1569         if (clipped[0] >= clipped[2] || clipped[1] >= clipped[3]) goto done;
   1570         for (unsigned i = 0; i < 4; ++i) {
   1571             from[i] += clipped[i] - to[i];
   1572             to[i] = clipped[i];
   1573         }
   1574     } else if (to[0] < 0 || to[1] < 0 || to[2] > (int32_t)target->width || to[3] > (int32_t)target->height) return;
   1575     flush_surface_write(source);
   1576     flush_surface_write(target);
   1577     gl_target_blit(source->target, target->target, from, to);
   1578     if (target->rgb_bits == 16) {
   1579         /* A blit into RGB565 also loses the low channel bits before rendering. */
   1580         if (!target->pixels) target->pixels = guest_malloc(target->pitch * target->height);
   1581         if (!target->pixels) abort();
   1582         transfer_surface_pixels(target, SURFACE_READ);
   1583         transfer_surface_pixels(target, SURFACE_WRITE);
   1584     }
   1585     if ((target->caps2 & 0x10) || ((target->rgb_bits == 16 || target->texture_updates) && !(target->caps & 0x800))) {
   1586         guest_free(target->pixels);
   1587         target->pixels = 0;
   1588     } else if ((target->caps & 0x800) && target->rgb_bits != 16) {
   1589         transfer_surface_pixels(target, SURFACE_READ);
   1590         swap_surface_channels(target);
   1591     }
   1592     if (primary) {
   1593         int width, height;
   1594 #ifdef __EMSCRIPTEN__
   1595         if (emscripten_get_canvas_element_size("#canvas", &width, &height) != EMSCRIPTEN_RESULT_SUCCESS) abort();
   1596 #else
   1597         SDL_GL_GetDrawableSize(native, &width, &height);
   1598 #endif
   1599         gl_target_present(target->target, client, width, height);
   1600 #ifdef __EMSCRIPTEN__
   1601         if (proxied_context && emscripten_webgl_commit_frame() != EMSCRIPTEN_RESULT_SUCCESS) abort();
   1602 #else
   1603         SDL_GL_SwapWindow(native);
   1604 #endif
   1605     }
   1606 done:
   1607     g_eax = 0;
   1608 }
   1609 
   1610 static struct device_object *find_device(uint32_t address)
   1611 {
   1612     for (struct device_object *device = devices; device; device = device->next)
   1613         if (device->interface == address) return device;
   1614     fprintf(stderr, "Invalid guest Direct3D device %08x\n", address);
   1615     abort();
   1616 }
   1617 
   1618 static void create_device(void)
   1619 {
   1620     struct draw_object *owner = find_object(MEM32(g_esp + 4));
   1621     uint32_t iid = MEM32(g_esp + 8), target = MEM32(g_esp + 12), output = MEM32(g_esp + 16);
   1622     const uint32_t hal[] = {0x84e63de0, 0x11cf46aa, 0x00006f81, 0x6e1520c0};
   1623     g_esp += 20;
   1624     g_eax = 0x80070057u;
   1625     if (!iid || !target || !output) return;
   1626     MEM32(output) = 0;
   1627     if (memcmp((void *)ADDR(iid), hal, 16)) { g_eax = 0x887602c1u; return; }
   1628     struct surface_object *surface = find_surface(target);
   1629     if (!surface->target || !(surface->caps & 0x2000) || surface->owner != owner) return;
   1630     struct device_object *device = calloc(1, sizeof(*device));
   1631     if (!device) abort();
   1632     device->interface = create_interface(6);
   1633     device->references = 1;
   1634     device->cull = 3; /* D3DCULL_CCW */
   1635     for (unsigned i = 0; i < 2; ++i) {
   1636         struct texture_stage *stage = &device->stages[i];
   1637         stage->min_filter = stage->mag_filter = stage->address = stage->address_u = stage->address_v = 1;
   1638         stage->sampler_u = stage->sampler_v = stage->mip_filter = 1;
   1639         stage->color_op = i ? 1 : 4;
   1640         stage->alpha_op = i ? 1 : 2;
   1641         stage->color_arg2 = stage->alpha_arg2 = 1;
   1642         stage->color_arg1 = stage->alpha_arg1 = 2;
   1643     }
   1644     device->source_blend = 2;
   1645     device->alpha_function = 8;
   1646     device->destination_blend = 1;
   1647     device->depth_enabled = 1;
   1648     device->depth_write = 1;
   1649     device->depth_function = 4;
   1650     device->clipping = 1;
   1651     device->lighting = 1;
   1652     device->diffuse_source = 1;
   1653     device->specular_source = 2;
   1654     device->texture_factor = UINT32_MAX;
   1655     device->fog_end = device->fog_density = 0x3f800000;
   1656     for (unsigned matrix = 0; matrix < 5; ++matrix)
   1657         for (unsigned i = 0; i < 16; i += 5) device->transforms[matrix][i] = 0x3f800000;
   1658     device->owner = owner;
   1659     device->target = surface;
   1660     device->viewport[2] = surface->width;
   1661     device->viewport[3] = surface->height;
   1662     device->viewport[5] = 0x3f800000;
   1663     ++owner->references[1];
   1664     ++surface->references[0];
   1665     gl_target_set_depth(surface->target, surface->attached ? surface->attached->depth : NULL);
   1666     device->next = devices;
   1667     devices = device;
   1668     MEM32(output) = device->interface;
   1669     g_eax = 0;
   1670 }
   1671 
   1672 static void device_query_interface(void)
   1673 {
   1674     struct device_object *device = find_device(MEM32(g_esp + 4));
   1675     uint32_t iid = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   1676     const uint32_t unknown[] = {0, 0, 0xc0, 0x46000000};
   1677     const uint32_t device7[] = {0xf5049e79, 0x11d24861, 0xa00007a4, 0xa82906c9};
   1678     g_esp += 16;
   1679     g_eax = 0x80070057u;
   1680     if (!output) return;
   1681     MEM32(output) = 0;
   1682     g_eax = 0x80004002u;
   1683     if (memcmp((void *)ADDR(iid), unknown, 16) && memcmp((void *)ADDR(iid), device7, 16)) return;
   1684     MEM32(output) = device->interface;
   1685     ++device->references;
   1686     g_eax = 0;
   1687 }
   1688 
   1689 static void device_add_reference(void)
   1690 {
   1691     g_eax = ++find_device(MEM32(g_esp + 4))->references;
   1692     g_esp += 8;
   1693 }
   1694 
   1695 static void device_release_reference(void)
   1696 {
   1697     struct device_object *device = find_device(MEM32(g_esp + 4));
   1698     g_eax = --device->references;
   1699     if (!g_eax) {
   1700         struct device_object **link = &devices;
   1701         while (*link != device) link = &(*link)->next;
   1702         *link = device->next;
   1703         release_surface(device->target, 0);
   1704         for (unsigned i = 0; i < 2; ++i)
   1705             if (device->stages[i].texture) release_surface(device->stages[i].texture, 0);
   1706         release_draw(device->owner, 1);
   1707         guest_free(device->interface);
   1708         while (device->lights) {
   1709             struct device_light *light = device->lights;
   1710             device->lights = light->next;
   1711             free(light);
   1712         }
   1713         free(device);
   1714     }
   1715     g_esp += 8;
   1716 }
   1717 
   1718 static void device_caps(void)
   1719 {
   1720     find_device(MEM32(g_esp + 4));
   1721     uint32_t output = MEM32(g_esp + 8);
   1722     g_eax = 0x80070057u;
   1723     if (output) { describe_device(output); g_eax = 0; }
   1724     g_esp += 12;
   1725 }
   1726 
   1727 static double scene_profile_start;
   1728 
   1729 static void device_begin_scene(void)
   1730 {
   1731     struct device_object *device = find_device(MEM32(g_esp + 4));
   1732     g_eax = device->scene ? 0x887602f8u : 0;
   1733     if (!device->scene) scene_profile_start = ao_profile_begin("render scene");
   1734     device->scene = 1;
   1735     g_esp += 8;
   1736 }
   1737 
   1738 static void device_end_scene(void)
   1739 {
   1740     struct device_object *device = find_device(MEM32(g_esp + 4));
   1741     g_eax = device->scene ? 0 : 0x887602f9u;
   1742     if (device->scene) ao_profile_end("render scene", scene_profile_start, NULL);
   1743     device->scene = 0;
   1744     g_esp += 8;
   1745 }
   1746 
   1747 static void device_parent(void)
   1748 {
   1749     struct device_object *device = find_device(MEM32(g_esp + 4));
   1750     uint32_t output = MEM32(g_esp + 8);
   1751     g_eax = 0x80070057u;
   1752     if (output) { MEM32(output) = interface_pointer(device->owner, 2); g_eax = 0; }
   1753     g_esp += 12;
   1754 }
   1755 
   1756 static void device_get_target(void)
   1757 {
   1758     struct device_object *device = find_device(MEM32(g_esp + 4));
   1759     uint32_t output = MEM32(g_esp + 8);
   1760     g_eax = 0x80070057u;
   1761     if (output) {
   1762         MEM32(output) = device->target->interfaces[0];
   1763         ++device->target->references[0];
   1764         g_eax = 0;
   1765     }
   1766     g_esp += 12;
   1767 }
   1768 
   1769 static void device_set_target(void)
   1770 {
   1771     struct device_object *device = find_device(MEM32(g_esp + 4));
   1772     uint32_t target = MEM32(g_esp + 8), flags = MEM32(g_esp + 12);
   1773     g_esp += 16;
   1774     g_eax = 0x80070057u;
   1775     if (!target || flags) return;
   1776     struct surface_object *surface = find_surface(target);
   1777     if (!surface->target || !(surface->caps & 0x2000) || surface->owner != device->owner) return;
   1778 
   1779     /* Retain before releasing, including when the device selects its current target. */
   1780     ++surface->references[0];
   1781     release_surface(device->target, 0);
   1782     device->target = surface;
   1783     gl_target_set_depth(surface->target, surface->attached ? surface->attached->depth : NULL);
   1784     g_eax = 0;
   1785 }
   1786 
   1787 static void device_viewport(void)
   1788 {
   1789     struct device_object *device = find_device(MEM32(g_esp + 4));
   1790     uint32_t output = MEM32(g_esp + 8);
   1791     g_eax = 0x80070057u;
   1792     if (output) {
   1793         memcpy((void *)ADDR(output), device->viewport, sizeof(device->viewport));
   1794         g_eax = 0;
   1795     }
   1796     g_esp += 12;
   1797 }
   1798 
   1799 static void device_set_viewport(void)
   1800 {
   1801     struct device_object *device = find_device(MEM32(g_esp + 4));
   1802     uint32_t input = MEM32(g_esp + 8);
   1803     g_eax = 0x80070057u;
   1804     if (input) {
   1805         uint32_t viewport[6];
   1806         memcpy(viewport, (void *)ADDR(input), sizeof(viewport));
   1807         if (viewport[0] > device->target->width || viewport[1] > device->target->height ||
   1808             viewport[2] > device->target->width - viewport[0] || viewport[3] > device->target->height - viewport[1]) {
   1809             g_esp += 12; return;
   1810         }
   1811         if (viewport[4] || viewport[5] != 0x3f800000) {
   1812             fprintf(stderr, "Unsupported Direct3D viewport depth range\n"); exit(3);
   1813         }
   1814         memcpy(device->viewport, viewport, sizeof(viewport));
   1815         g_eax = 0;
   1816     }
   1817     g_esp += 12;
   1818 }
   1819 
   1820 static void device_material(void)
   1821 {
   1822     struct device_object *device = find_device(MEM32(g_esp + 4));
   1823     uint32_t address = MEM32(g_esp + 8);
   1824     g_esp += 12;
   1825     g_eax = 0x80070057u;
   1826     if (!address) return;
   1827     /* Material colors and power are copied into device-owned storage. */
   1828     if (current_slot == 16) {
   1829         memcpy(device->material, (void *)ADDR(address), sizeof(device->material));
   1830         float power;
   1831         memcpy(&power, device->material + 16, 4);
   1832         if (power) device->specular_power = power;
   1833     }
   1834     else memcpy((void *)ADDR(address), device->material, sizeof(device->material));
   1835     g_eax = 0;
   1836 }
   1837 
   1838 static void device_clear(void)
   1839 {
   1840     struct device_object *device = find_device(MEM32(g_esp + 4));
   1841     uint32_t count = MEM32(g_esp + 8), rectangles = MEM32(g_esp + 12), flags = MEM32(g_esp + 16);
   1842     uint32_t color = MEM32(g_esp + 20), depth = MEM32(g_esp + 24), stencil = MEM32(g_esp + 28);
   1843     g_esp += 32;
   1844     if ((count && !rectangles) || (flags & ~3u)) {
   1845         fprintf(stderr, "Unsupported Direct3D clear count=%u flags=%08x stencil=%u\n", count, flags, stencil); exit(3);
   1846     }
   1847     float z;
   1848     memcpy(&z, &depth, 4);
   1849     const int32_t viewport[] = {device->viewport[0], device->viewport[1],
   1850         device->viewport[0] + device->viewport[2], device->viewport[1] + device->viewport[3]};
   1851     if (!count) gl_target_clear_rect(device->target->target, flags, color, z, viewport);
   1852     for (uint32_t i = 0; i < count; ++i) {
   1853         int32_t rectangle[4];
   1854         memcpy(rectangle, (void *)ADDR(rectangles + i * 16), 16);
   1855         if (rectangle[2] < rectangle[0] || rectangle[3] < rectangle[1]) {
   1856             g_eax = 0x80070057u; return;
   1857         }
   1858         for (unsigned j = 0; j < 4; ++j)
   1859             if (j < 2 ? rectangle[j] < viewport[j] : rectangle[j] > viewport[j]) rectangle[j] = viewport[j];
   1860         gl_target_clear_rect(device->target->target, flags, color, z, rectangle);
   1861     }
   1862     g_eax = 0;
   1863 }
   1864 
   1865 static uint32_t device_state(struct device_object *device, uint32_t state)
   1866 {
   1867     switch (state) {
   1868     /* Inactive legacy states retain the values returned by Direct3D7. */
   1869     case 2: case 40: return UINT32_MAX; /* Retired antialias state sentinels. */
   1870     case 4: case 16: return 1; /* Perspective textures and last line pixel. */
   1871     case 10: case 30: case 33: return 0;
   1872     case 15: return device->alpha_test;
   1873     case 24: return device->alpha_reference;
   1874     case 25: return device->alpha_function;
   1875     case 29: return device->specular;
   1876     case 35: case 48: return 0; /* Table/range fog. */
   1877     case 47: return device->depth_bias;
   1878     case 36: return device->fog_start;
   1879     case 37: return device->fog_end;
   1880     case 38: return device->fog_density;
   1881     case 56: return 8; /* ALWAYS stencil comparison. */
   1882     case 41: case 52: case 57: return 0; /* Color key and stencil disabled. */
   1883     case 53: case 54: case 55: return 1; /* KEEP stencil operations. */
   1884     case 58: case 59: return UINT32_MAX; /* Stencil masks. */
   1885     case 60: return device->texture_factor;
   1886     case 128: case 129: case 130: case 131:
   1887     case 132: case 133: case 134: case 135: return 0; /* Coordinate wrapping. */
   1888     case 141: case 142: return 1;
   1889     case 145: return device->diffuse_source;
   1890     case 136: return device->clipping;
   1891     case 139: return device->ambient;
   1892     case 140: return device->fog_vertex_mode;
   1893     case 143: return device->normalize_normals;
   1894     case 138: case 144:
   1895     case 147: case 151: case 152: return 0;
   1896     case 148: return device->emissive_source;
   1897     case 146: return device->specular_source;
   1898     case 7: return device->depth_enabled;
   1899     case 137: return device->lighting;
   1900     case 14: return device->depth_write;
   1901     case 8: return 3; /* Solid fill. */
   1902     case 9: return 2; /* Gouraud shading. */
   1903     case 19: return device->source_blend;
   1904     case 20: return device->destination_blend;
   1905     case 22: return device->cull;
   1906     case 23: return device->depth_function;
   1907     case 27: return device->blend;
   1908     case 26: return 0; /* Dither. */
   1909     case 28: return device->fog_enabled;
   1910     case 34: return device->fog_color;
   1911     default: fprintf(stderr, "Unsupported Direct3D render state %u\n", state); exit(3);
   1912     }
   1913 }
   1914 
   1915 static void device_light_state(void)
   1916 {
   1917     struct device_object *device = find_device(MEM32(g_esp + 4));
   1918     uint32_t index = MEM32(g_esp + 8), data = MEM32(g_esp + 12);
   1919     g_esp += 16;
   1920     g_eax = 0x80070057u;
   1921     if (current_slot != 44 && !data) return;
   1922     if (current_slot == 18) {
   1923         uint32_t type = MEM32(data);
   1924         if (type < 1 || type > 3) return;
   1925         if (type != 1 && !MEMF(data + 64) && !MEMF(data + 68) && !MEMF(data + 72)) return;
   1926     }
   1927     struct device_light *light = device->lights;
   1928     while (light && light->index != index) light = light->next;
   1929     if (!light) {
   1930         if (current_slot == 19 || current_slot == 45) return;
   1931         light = calloc(1, sizeof(*light));
   1932         if (!light) abort();
   1933         light->index = index;
   1934         /* LightEnable creates a white directional light pointing along +Z. */
   1935         light->data[0] = 3;
   1936         light->data[1] = light->data[2] = light->data[3] = light->data[18] = 0x3f800000;
   1937         light->next = device->lights;
   1938         device->lights = light;
   1939     }
   1940     if (current_slot == 18) memcpy(light->data, (void *)ADDR(data), 104);
   1941     else if (current_slot == 19) memcpy((void *)ADDR(data), light->data, 104);
   1942     else if (current_slot == 44) light->enabled = data ? 128 : 0;
   1943     else MEM32(data) = light->enabled;
   1944     g_eax = 0;
   1945 }
   1946 
   1947 static void device_transform(void)
   1948 {
   1949     struct device_object *device = find_device(MEM32(g_esp + 4));
   1950     uint32_t state = MEM32(g_esp + 8), matrix = MEM32(g_esp + 12);
   1951     g_esp += 16;
   1952     if ((state < 1 || state > 3) && state != 16 && state != 17) {
   1953         fprintf(stderr, "Unsupported Direct3D transform state %u\n", state); exit(3);
   1954     }
   1955     g_eax = 0x80070057u;
   1956     if (!matrix) return;
   1957     unsigned index = state >= 16 ? state - 13 : state - 1;
   1958     if (current_slot == 11) memcpy(device->transforms[index], (void *)ADDR(matrix), 64);
   1959     else memcpy((void *)ADDR(matrix), device->transforms[index], 64);
   1960     g_eax = 0;
   1961 }
   1962 
   1963 static void device_get_state(void)
   1964 {
   1965     struct device_object *device = find_device(MEM32(g_esp + 4));
   1966     uint32_t state = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   1967     g_eax = 0x80070057u;
   1968     if (output) { MEM32(output) = device_state(device, state); g_eax = 0; }
   1969     g_esp += 16;
   1970 }
   1971 
   1972 static void device_set_state(void)
   1973 {
   1974     struct device_object *device = find_device(MEM32(g_esp + 4));
   1975     uint32_t state = MEM32(g_esp + 8), value = MEM32(g_esp + 12);
   1976     if (state == 7 && value <= 1) device->depth_enabled = value;
   1977     else if (state == 22 && value >= 1 && value <= 3) device->cull = value;
   1978     else if (state == 27 && value <= 1) device->blend = value;
   1979     else if (state == 28 && value <= 1) device->fog_enabled = value;
   1980     else if (state == 29 && value <= 1) device->specular = value;
   1981     else if (state == 34) device->fog_color = value;
   1982     else if (state == 36) device->fog_start = value;
   1983     else if (state == 37) device->fog_end = value;
   1984     else if (state == 38) device->fog_density = value;
   1985     else if (state == 14 && value <= 1) device->depth_write = value;
   1986     else if (state == 15 && value <= 1) device->alpha_test = value;
   1987     else if (state == 24 && value <= 255) device->alpha_reference = value;
   1988     else if (state == 25 && value >= 1 && value <= 8) device->alpha_function = value;
   1989     else if (state == 23 && value >= 1 && value <= 8) device->depth_function = value;
   1990     else if (state == 47 && value <= 16) device->depth_bias = value;
   1991     else if (state == 60) device->texture_factor = value;
   1992     else if (state == 136 && value <= 1) device->clipping = value;
   1993     else if (state == 137 && value <= 1) device->lighting = value;
   1994     else if (state == 139) device->ambient = value;
   1995     else if (state == 140 && (value == 0 || value == 3)) device->fog_vertex_mode = value;
   1996     else if (state == 143 && value <= 1) device->normalize_normals = value;
   1997     else if (state == 145 && value <= 2) device->diffuse_source = value;
   1998     /* Supported untransformed formats omit color 2, which falls back to the material. */
   1999     else if (state == 146 && (value == 0 || value == 2)) device->specular_source = value;
   2000     else if (state == 148 && value <= 2) device->emissive_source = value;
   2001     else if (state == 19 && (value == 1 || value == 2 || value == 3 || value == 5 || value == 6 || value == 9)) device->source_blend = value;
   2002     else if (state == 20 && (value == 1 || value == 2 || value == 3 || value == 5 || value == 6 || value == 9)) device->destination_blend = value;
   2003     else if (value != device_state(device, state)) {
   2004         fprintf(stderr, "Unsupported Direct3D render state %u value=%08x\n", state, value); exit(3);
   2005     }
   2006     g_eax = 0;
   2007     g_esp += 16;
   2008 }
   2009 
   2010 static void transform_vector(const float input[4], const float matrix[16], float output[4])
   2011 {
   2012     for (unsigned j = 0; j < 4; ++j)
   2013         output[j] = input[0] * matrix[j] + input[1] * matrix[4 + j] +
   2014                     input[2] * matrix[8 + j] + input[3] * matrix[12 + j];
   2015 }
   2016 
   2017 int linux_graphics_project(const float position[3], float screen[3])
   2018 {
   2019     if (!devices) return 0;
   2020     float camera[4], clip[4];
   2021     transform_vector((float[]){position[0], position[1], position[2], 1},
   2022         (const float *)devices->transforms[1], camera);
   2023     transform_vector(camera, (const float *)devices->transforms[2], clip);
   2024     if (clip[3] <= 0 || !isfinite(clip[3])) return 0;
   2025     screen[0] = devices->viewport[0] + (1 + clip[0] / clip[3]) * devices->viewport[2] / 2;
   2026     screen[1] = devices->viewport[1] + (1 - clip[1] / clip[3]) * devices->viewport[3] / 2;
   2027     screen[2] = clip[2] / clip[3];
   2028     return 1;
   2029 }
   2030 
   2031 static int projective_normal_matrix(const float matrix[16], float normal[9])
   2032 {
   2033     /* Invert the complete world/view matrix before taking its normal portion. */
   2034     float rows[4][8] = {0};
   2035     for (unsigned i = 0; i < 4; ++i) {
   2036         memcpy(rows[i], matrix + i * 4, 16);
   2037         rows[i][i + 4] = 1;
   2038     }
   2039     for (unsigned column = 0; column < 4; ++column) {
   2040         unsigned pivot = column;
   2041         for (unsigned row = column + 1; row < 4; ++row)
   2042             if (fabsf(rows[row][column]) > fabsf(rows[pivot][column])) pivot = row;
   2043         if (!rows[pivot][column]) return 0;
   2044         if (pivot != column) for (unsigned i = 0; i < 8; ++i) {
   2045             float value = rows[column][i];
   2046             rows[column][i] = rows[pivot][i];
   2047             rows[pivot][i] = value;
   2048         }
   2049 
   2050         /* Eliminate this column from the remaining rows. */
   2051         float divisor = rows[column][column];
   2052         for (unsigned i = 0; i < 8; ++i) rows[column][i] /= divisor;
   2053         for (unsigned row = 0; row < 4; ++row) if (row != column) {
   2054             float factor = rows[row][column];
   2055             for (unsigned i = 0; i < 8; ++i) rows[row][i] -= factor * rows[column][i];
   2056         }
   2057     }
   2058     for (unsigned row = 0; row < 3; ++row)
   2059         for (unsigned column = 0; column < 3; ++column)
   2060             normal[row * 3 + column] = rows[column][row + 4];
   2061     return 1;
   2062 }
   2063 
   2064 static float normalize_vector(float vector[3])
   2065 {
   2066     float length = sqrtf(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]);
   2067     if (length) for (unsigned j = 0; j < 3; ++j) vector[j] /= length;
   2068     return length;
   2069 }
   2070 
   2071 static void light_vertex(struct device_object *device, const float position[4], const float normal[3], const float diffuse_color[4], const float emissive_color[3], float color[4], float specular[3])
   2072 {
   2073     const float *material = (const float *)device->material;
   2074     for (unsigned j = 0; j < 3; ++j)
   2075         color[j] = emissive_color[j] + material[4 + j] * ((device->ambient >> (16 - j * 8)) & 255) / 255.0f;
   2076     color[3] = diffuse_color[3];
   2077     for (struct device_light *light = device->enabled_lights; light; light = light->next_enabled) {
   2078         const float *data = (const float *)light->data;
   2079         float direction[4], attenuation = 1;
   2080         memcpy(direction, light->camera_vector, sizeof(direction));
   2081         if (light->data[0] != 3) {
   2082             for (unsigned j = 0; j < 3; ++j) direction[j] -= position[j];
   2083             float distance = normalize_vector(direction);
   2084             if (distance > data[19]) continue;
   2085             attenuation = 1 / (data[21] + distance * data[22] + distance * distance * data[23]);
   2086             if (light->data[0] == 2) {
   2087                 float cosine = -(light->spot_direction[0] * direction[0] +
   2088                     light->spot_direction[1] * direction[1] + light->spot_direction[2] * direction[2]);
   2089                 if (cosine <= light->spot_outer) continue;
   2090                 if (cosine < light->spot_inner)
   2091                     attenuation *= powf((cosine - light->spot_outer) /
   2092                         (light->spot_inner - light->spot_outer), data[20]);
   2093             }
   2094         }
   2095         float diffuse = fmaxf(0, normal[0] * direction[0] + normal[1] * direction[1] + normal[2] * direction[2]);
   2096         for (unsigned j = 0; j < 3; ++j)
   2097             color[j] += attenuation * (diffuse_color[j] * data[1 + j] * diffuse + material[4 + j] * data[9 + j]);
   2098         if (device->specular && diffuse > 0) {
   2099             float viewer[] = {-position[0], -position[1], -position[2]};
   2100             normalize_vector(viewer);
   2101             for (unsigned j = 0; j < 3; ++j) viewer[j] += direction[j];
   2102             normalize_vector(viewer);
   2103             float reflection = fminf(1, fmaxf(0, normal[0] * viewer[0] + normal[1] * viewer[1] + normal[2] * viewer[2]));
   2104             float highlight = powf(reflection, device->specular_power) * attenuation;
   2105             for (unsigned j = 0; j < 3; ++j) specular[j] += material[8 + j] * data[5 + j] * highlight;
   2106         }
   2107     }
   2108     for (unsigned j = 0; j < 4; ++j) color[j] = fminf(1, fmaxf(0, color[j]));
   2109     for (unsigned j = 0; j < 3; ++j) specular[j] = fminf(1, fmaxf(0, specular[j]));
   2110 }
   2111 
   2112 static void draw_primitive(struct device_object *device, uint32_t primitive, uint32_t fvf,
   2113                            uint32_t input, uint32_t count, uint32_t flags,
   2114                            uint32_t input_indices, uint32_t element_count, struct vertex_buffer *buffer)
   2115 {
   2116     unsigned texture_count = (fvf >> 8) & 15, format = fvf & ~0x300u;
   2117     int untransformed = texture_count >= 1 && (format == 0x12 || format == 0x52 || format == 0x42);
   2118     if ((primitive != 2 && primitive != 4 && primitive != 5 && primitive != 6) || texture_count > 2 ||
   2119         ((format & ~0xc0u) != 4 && !untransformed) || flags) {
   2120         fprintf(stderr, "Unsupported Direct3D draw primitive=%u fvf=%08x flags=%08x cull=%u\n", primitive, fvf, flags, device->cull); exit(3);
   2121     }
   2122     g_eax = 0x80070057u;
   2123     if (!input_indices) element_count = count;
   2124     if (!input || !count || element_count < (primitive == 2 ? 2 : 3) || (primitive == 4 && element_count % 3) || count > 65535) return;
   2125     for (uint32_t i = 0; input_indices && i < element_count; ++i)
   2126         if (MEM16(input_indices + i * 2) >= count) return;
   2127     uint32_t index_count = primitive == 2 || primitive == 4 ? element_count : (element_count - 2) * 3;
   2128     uint16_t *indices = malloc(index_count * sizeof(*indices));
   2129     if (!indices) abort();
   2130     /* World/view transforms also determine the inverse-transpose normal matrix. */
   2131     float world_view[16], normal_matrix[9] = {0};
   2132     if (untransformed) {
   2133         const float *world = (const float *)device->transforms[0], *view = (const float *)device->transforms[1];
   2134         for (unsigned i = 0; i < 4; ++i) transform_vector(world + i * 4, view, world_view + i * 4);
   2135         int transform_normals = device->lighting;
   2136         for (unsigned stage = 0; stage < 2 && device->stages[stage].color_op != 1; ++stage)
   2137             transform_normals |= device->stages[stage].texture_coordinate == 0x10000;
   2138         if ((fvf & 0x10) && transform_normals) {
   2139             if (world_view[3] || world_view[7] || world_view[11] || world_view[15] != 1) {
   2140                 if (!projective_normal_matrix(world_view, normal_matrix)) {
   2141                     fprintf(stderr, "Unsupported singular world/view transform\n"); exit(3);
   2142                 }
   2143             } else {
   2144                 const float *m = world_view;
   2145                 float cofactors[] = {m[5]*m[10]-m[6]*m[9], m[6]*m[8]-m[4]*m[10], m[4]*m[9]-m[5]*m[8],
   2146                                      m[2]*m[9]-m[1]*m[10], m[0]*m[10]-m[2]*m[8], m[1]*m[8]-m[0]*m[9],
   2147                                      m[1]*m[6]-m[2]*m[5], m[2]*m[4]-m[0]*m[6], m[0]*m[5]-m[1]*m[4]};
   2148                 float determinant = m[0]*cofactors[0] + m[1]*cofactors[1] + m[2]*cofactors[2];
   2149                 if (!determinant) { fprintf(stderr, "Unsupported singular world/view transform\n"); exit(3); }
   2150                 for (unsigned i = 0; i < 9; ++i) normal_matrix[i] = cofactors[i] / determinant;
   2151             }
   2152         }
   2153     }
   2154     /* Prepare enabled lights and their transforms in the original accumulation order. */
   2155     device->enabled_lights = NULL;
   2156     struct device_light *last_enabled = NULL;
   2157     if (untransformed && device->lighting) {
   2158         for (struct device_light *light = device->lights; light; light = light->next) {
   2159             if (!light->enabled) continue;
   2160             if (last_enabled) last_enabled->next_enabled = light;
   2161             else device->enabled_lights = light;
   2162             last_enabled = light;
   2163             light->next_enabled = NULL;
   2164             const float *data = (const float *)light->data;
   2165             float source[4];
   2166             if (light->data[0] == 3) {
   2167                 for (unsigned j = 0; j < 3; ++j) source[j] = -data[16 + j];
   2168                 source[3] = 0;
   2169             } else {
   2170                 memcpy(source, data + 13, 12);
   2171                 source[3] = 1;
   2172             }
   2173             transform_vector(source, (const float *)device->transforms[1], light->camera_vector);
   2174             if (light->data[0] == 3) normalize_vector(light->camera_vector);
   2175             if (light->data[0] == 2) {
   2176                 memcpy(source, data + 16, 12);
   2177                 source[3] = 0;
   2178                 transform_vector(source, (const float *)device->transforms[1], light->spot_direction);
   2179                 normalize_vector(light->spot_direction);
   2180                 light->spot_inner = cosf(data[24] * .5f);
   2181                 light->spot_outer = cosf(data[25] * .5f);
   2182             }
   2183         }
   2184     }
   2185     /* Use GPU transforms for draws with no specular or generated texture coordinates. */
   2186     int gpu_transform = untransformed && !device->specular &&
   2187         !device->stages[0].texture_transform && !device->stages[1].texture_transform &&
   2188         device->stages[0].texture_coordinate < 0x10000 && device->stages[1].texture_coordinate < 0x10000;
   2189     struct gl_vertex_transform gpu = {0};
   2190     /* Keep spotlights and light sets beyond the shader capacity on the CPU. */
   2191     unsigned light_count = 0;
   2192     for (struct device_light *light = device->enabled_lights; gpu_transform && light; light = light->next_enabled) {
   2193         if (light->data[0] == 2 || light_count == sizeof(gpu.lights) / sizeof(gpu.lights[0])) {
   2194             gpu_transform = 0;
   2195             break;
   2196         }
   2197         memcpy(gpu.lights[light_count].vector, light->camera_vector, 12);
   2198         gpu.lights[light_count].vector[3] = light->data[0];
   2199         memcpy(gpu.lights[light_count].diffuse, light->data + 1, 16);
   2200         memcpy(gpu.lights[light_count].ambient, light->data + 9, 16);
   2201         memcpy(gpu.lights[light_count].attenuation, light->data + 21, 12);
   2202         memcpy(gpu.lights[light_count].attenuation + 3, light->data + 19, 4);
   2203         ++light_count;
   2204     }
   2205     if (gpu_transform) {
   2206         memcpy(gpu.world_view, world_view, 64);
   2207         memcpy(gpu.projection, device->transforms[2], 64);
   2208         for (unsigned i = 0; i < 3; ++i) memcpy(gpu.normal + i * 4, normal_matrix + i * 3, 12);
   2209         float width = device->target->width, height = device->target->height;
   2210         gpu.viewport[0] = device->viewport[2] / width;
   2211         gpu.viewport[1] = device->viewport[3] / height;
   2212         gpu.viewport[2] = (2.0f * device->viewport[0] + device->viewport[2] + 1) / width - 1;
   2213         gpu.viewport[3] = 1 - (2.0f * device->viewport[1] + device->viewport[3] + 1) / height;
   2214         memcpy(gpu.material_diffuse, device->material, 16);
   2215         memcpy(gpu.material_ambient, device->material + 4, 16);
   2216         memcpy(gpu.material_emissive, device->material + 12, 16);
   2217         for (unsigned i = 0; i < 3; ++i) gpu.ambient[i] = ((device->ambient >> (16 - i * 8)) & 255) / 255.0f;
   2218         memcpy(gpu.fog, &device->fog_start, 4);
   2219         memcpy(gpu.fog + 1, &device->fog_end, 4);
   2220         gpu.fog[2] = device->fog_vertex_mode == 3;
   2221         gpu.flags[0] = device->lighting;
   2222         gpu.flags[1] = device->normalize_normals;
   2223         gpu.flags[2] = device->diffuse_source == 1 && (fvf & 0x40);
   2224         gpu.flags[3] = device->emissive_source == 1 && (fvf & 0x40);
   2225     }
   2226     gl_renderer_set_vertex_transform(gpu_transform ? &gpu : NULL);
   2227     /* Pretransformed vertices place optional colors before their UV sets. */
   2228     uint32_t uv_offset = 16 + (fvf & 0x40 ? 4 : 0) + (fvf & 0x80 ? 4 : 0), stride = uv_offset + texture_count * 8;
   2229     if (untransformed) stride = 12 + (fvf & 0x10 ? 12 : 0) + (fvf & 0x40 ? 4 : 0) + texture_count * 8;
   2230     const void *raw_vertices = gpu_transform ? (const void *)ADDR(input) : NULL;
   2231     if (raw_vertices) {
   2232         uint64_t end = (uint64_t)input + count * stride;
   2233         for (uint64_t page = ((uint64_t)input | 0xffffu) + 1; page < end; page += 0x10000) {
   2234             if (page > UINT32_MAX || ADDR((uint32_t)page) != (uintptr_t)raw_vertices + page - input) {
   2235                 raw_vertices = NULL;
   2236                 break;
   2237             }
   2238         }
   2239     }
   2240     struct gl_vertex *vertices = raw_vertices ? NULL : malloc(count * sizeof(*vertices));
   2241     if (!raw_vertices && !vertices) abort();
   2242     for (uint32_t i = 0; !raw_vertices && i < count; ++i) {
   2243         memset(vertices[i].specular, 0, sizeof(vertices[i].specular));
   2244         if (untransformed) {
   2245             const unsigned char *vertex = (const unsigned char *)ADDR(input + i * stride);
   2246             if (gpu_transform) {
   2247                 /* GPU inputs can go directly to the draw buffer without a temporary vertex. */
   2248                 memcpy(vertices[i].position, vertex, 12);
   2249                 vertices[i].position[3] = 1;
   2250                 if (fvf & 0x10) memcpy(vertices[i].specular, vertex + 12, 12);
   2251                 if (fvf & 0x40) {
   2252                     uint32_t color;
   2253                     memcpy(&color, vertex + (fvf & 0x10 ? 24 : 12), 4);
   2254                     vertices[i].color[0] = ((color >> 16) & 255) / 255.0f;
   2255                     vertices[i].color[1] = ((color >> 8) & 255) / 255.0f;
   2256                     vertices[i].color[2] = (color & 255) / 255.0f;
   2257                     vertices[i].color[3] = (color >> 24) / 255.0f;
   2258                 } else if (device->lighting) memcpy(vertices[i].color, device->material, 16);
   2259                 else for (unsigned j = 0; j < 4; ++j) vertices[i].color[j] = 1;
   2260                 vertices[i].fog = 0;
   2261                 for (unsigned stage = 0; stage < 2; ++stage) {
   2262                     float *uv = stage ? vertices[i].uv_second : vertices[i].uv;
   2263                     unsigned coordinate = device->stages[stage].texture_coordinate;
   2264                     uv[0] = uv[1] = 0;
   2265                     if (coordinate < texture_count)
   2266                         memcpy(uv, vertex + stride - texture_count * 8 + coordinate * 8, 8);
   2267                 }
   2268                 continue;
   2269             }
   2270             float input_vertex[11], position[4], camera[4], projected[4], normal[3], diffuse[4];
   2271             memcpy(input_vertex, vertex, stride);
   2272             memcpy(position, input_vertex, 12); position[3] = 1;
   2273             transform_vector(position, world_view, camera);
   2274             transform_vector(camera, (const float *)device->transforms[2], projected);
   2275             float w = projected[3], width = device->target->width, height = device->target->height;
   2276             vertices[i].position[0] = projected[0] * device->viewport[2] / width +
   2277                                      w * ((2.0f * device->viewport[0] + device->viewport[2] + 1) / width - 1);
   2278             vertices[i].position[1] = projected[1] * device->viewport[3] / height +
   2279                                      w * (1 - (2.0f * device->viewport[1] + device->viewport[3] + 1) / height);
   2280             vertices[i].position[2] = projected[2]; vertices[i].position[3] = w;
   2281             for (unsigned j = 0; j < 3; ++j)
   2282                 normal[j] = fvf & 0x10 ? input_vertex[3] * normal_matrix[j] + input_vertex[4] * normal_matrix[3+j] + input_vertex[5] * normal_matrix[6+j] : 0;
   2283             if (device->normalize_normals) normalize_vector(normal);
   2284             if (fvf & 0x40) {
   2285                 uint32_t color = MEM32(input + i * stride + (fvf & 0x10 ? 24 : 12));
   2286                 diffuse[0] = ((color >> 16) & 255) / 255.0f;
   2287                 diffuse[1] = ((color >> 8) & 255) / 255.0f;
   2288                 diffuse[2] = (color & 255) / 255.0f;
   2289                 diffuse[3] = (color >> 24) / 255.0f;
   2290             } else if (device->lighting) memcpy(diffuse, device->material, 16);
   2291             else for (unsigned j = 0; j < 4; ++j) diffuse[j] = 1;
   2292             /* Missing vertex color fields fall back to the material's emissive RGB. */
   2293             const float *emissive = device->emissive_source == 1 && (fvf & 0x40) ? diffuse : (const float *)device->material + 12;
   2294             const float *lit_diffuse = device->diffuse_source == 1 && (fvf & 0x40) ? diffuse : (const float *)device->material;
   2295             if (device->lighting) light_vertex(device, camera, normal, lit_diffuse, emissive, vertices[i].color, vertices[i].specular);
   2296             else memcpy(vertices[i].color, diffuse, 16);
   2297             vertices[i].fog = 0;
   2298             if (device->fog_vertex_mode == 3) {
   2299                 float start, end;
   2300                 memcpy(&start, &device->fog_start, 4); memcpy(&end, &device->fog_end, 4);
   2301                 vertices[i].fog = fminf(1, fmaxf(0, (end - fabsf(camera[2])) / (end - start)));
   2302             }
   2303             for (unsigned stage = 0; stage < 2; ++stage) {
   2304                 float *uv = stage ? vertices[i].uv_second : vertices[i].uv;
   2305                 unsigned coordinate = device->stages[stage].texture_coordinate;
   2306                 float input_uv[] = {0, 0, 1, 0}, transformed[4];
   2307                 if (coordinate == 0x20000) memcpy(input_uv, camera, 16);
   2308                 else if (coordinate == 0x10000) { memcpy(input_uv, normal, 12); input_uv[3] = 1; }
   2309                 else if (coordinate < texture_count)
   2310                     memcpy(input_uv, (const unsigned char *)input_vertex + stride - texture_count * 8 + coordinate * 8, 8);
   2311                 memcpy(uv, input_uv, 8);
   2312                 if (device->stages[stage].texture_transform) {
   2313                     transform_vector(input_uv, (const float *)device->transforms[3 + stage], transformed);
   2314                     memcpy(uv, transformed, 8);
   2315                 }
   2316             }
   2317             continue;
   2318         }
   2319         float position[4];
   2320         memcpy(position, (void *)ADDR(input + i * stride), 16);
   2321         float w = 1.0f / position[3];
   2322         /* D3D transformed coordinates put integer positions at pixel centers. */
   2323         vertices[i].position[0] = (2 * (position[0] + 0.5f) / device->target->width - 1) * w;
   2324         vertices[i].position[1] = (1 - 2 * (position[1] + 0.5f) / device->target->height) * w;
   2325         vertices[i].position[2] = position[2] * w;
   2326         vertices[i].position[3] = w;
   2327         uint32_t color = fvf & 0x40 ? MEM32(input + i * stride + 16) : UINT32_MAX;
   2328         vertices[i].color[0] = ((color >> 16) & 255) / 255.0f;
   2329         vertices[i].color[1] = ((color >> 8) & 255) / 255.0f;
   2330         vertices[i].color[2] = (color & 255) / 255.0f;
   2331         vertices[i].color[3] = (color >> 24) / 255.0f;
   2332         uint32_t specular = fvf & 0x80 ? MEM32(input + i * stride + uv_offset - 4) : 0;
   2333         vertices[i].fog = (specular >> 24) / 255.0f;
   2334         if (device->specular && (fvf & 0x80)) {
   2335             for (unsigned j = 0; j < 3; ++j) vertices[i].specular[j] = ((specular >> (16 - j * 8)) & 255) / 255.0f;
   2336         }
   2337         for (unsigned stage = 0; stage < 2; ++stage) {
   2338             float *uv = stage ? vertices[i].uv_second : vertices[i].uv;
   2339             unsigned coordinate = device->stages[stage].texture_coordinate;
   2340             /* Pretransformed vertices use the stage's own UV set for generation modes. */
   2341             if (coordinate == 0x10000 || coordinate == 0x20000) coordinate = stage;
   2342             uv[0] = uv[1] = 0;
   2343             if (coordinate < texture_count)
   2344                 memcpy(uv, (void *)ADDR(input + i * stride + uv_offset + coordinate * 8), 8);
   2345         }
   2346     }
   2347     /* Line and triangle lists retain their independent vertex groups. */
   2348     if (primitive == 2 || primitive == 4) for (uint32_t i = 0; i < element_count; ++i) indices[i] = input_indices ? MEM16(input_indices + i * 2) : i;
   2349     else for (uint32_t i = 0; i < element_count - 2; ++i) {
   2350         /* Fans share vertex zero; strips alternate winding for each triangle. */
   2351         uint32_t a = primitive == 6 ? 0 : i + (i & 1);
   2352         uint32_t b = primitive == 6 ? i + 1 : i + !(i & 1), c = i + 2;
   2353         indices[i * 3] = input_indices ? MEM16(input_indices + a * 2) : a;
   2354         indices[i * 3 + 1] = input_indices ? MEM16(input_indices + b * 2) : b;
   2355         indices[i * 3 + 2] = input_indices ? MEM16(input_indices + c * 2) : c;
   2356     }
   2357     for (unsigned i = 0; i < 2; ++i) {
   2358         struct texture_stage *stage = &device->stages[i];
   2359         int needs_texture = (stage->color_arg1 & 15) == 2 || (stage->color_op != 2 && (stage->color_arg2 & 15) == 2);
   2360         if (stage->color_op != 1 && (stage->texture || !needs_texture)) {
   2361             for (struct surface_object *mip = stage->texture; mip; mip = mip->attached)
   2362                 flush_surface_write(mip);
   2363             struct gl_texture_state state = {stage->texture ? stage->texture->target : NULL,
   2364                 stage->min_filter == 2, stage->mag_filter == 2,
   2365                 stage->sampler_u == 3, stage->sampler_v == 3,
   2366                 stage->texture && stage->texture->alpha, stage->color_op, stage->alpha_op, stage->mip_filter == 2,
   2367                 stage->color_arg2, stage->alpha_arg2, stage->color_arg1, stage->alpha_arg1, device->texture_factor};
   2368             gl_renderer_set_texture(i, &state);
   2369         } else gl_renderer_set_texture(i, NULL);
   2370     }
   2371     gl_renderer_set_fog(device->fog_enabled, device->fog_color);
   2372     gl_renderer_set_alpha_test(device->alpha_test, device->alpha_function, device->alpha_reference);
   2373     gl_renderer_set_blend(device->blend, device->source_blend, device->destination_blend);
   2374     gl_renderer_set_depth(device->depth_enabled, device->depth_write, device->depth_function, device->depth_bias);
   2375     gl_renderer_set_cull(device->cull);
   2376     const int32_t clip[] = {device->viewport[0], device->viewport[1], device->viewport[2], device->viewport[3]};
   2377     if (raw_vertices) {
   2378         /* Retain a vertex buffer only when its whole guest allocation is contiguous. */
   2379         unsigned offset = 0;
   2380         if (buffer && !buffer->gpu) {
   2381             const void *data = (const void *)ADDR(buffer->data);
   2382             uint64_t end = (uint64_t)buffer->data + buffer->size;
   2383             for (uint64_t page = ((uint64_t)buffer->data | 0xffffu) + 1; page < end; page += 0x10000) {
   2384                 if (page > UINT32_MAX || ADDR((uint32_t)page) != (uintptr_t)data + page - buffer->data) {
   2385                     buffer = NULL;
   2386                     break;
   2387                 }
   2388             }
   2389             if (buffer) buffer->gpu = gl_vertex_buffer_create(data, buffer->size);
   2390         }
   2391         if (buffer) offset = input - buffer->data;
   2392         const unsigned coordinates[] = {device->stages[0].texture_coordinate, device->stages[1].texture_coordinate};
   2393         const float white[] = {1, 1, 1, 1};
   2394         gl_target_draw_fvf(device->target->target, primitive == 2 ? 2 : 4, raw_vertices, fvf, coordinates,
   2395             device->lighting ? (const float *)device->material : white, count, indices, index_count, clip,
   2396             buffer ? buffer->gpu : NULL, offset);
   2397     } else gl_target_draw(device->target->target, primitive == 2 ? 2 : 4, vertices, count, indices, index_count, clip);
   2398     free(indices);
   2399     free(vertices);
   2400     g_eax = 0;
   2401 }
   2402 
   2403 static void device_draw_primitive(void)
   2404 {
   2405     struct device_object *device = find_device(MEM32(g_esp + 4));
   2406     uint32_t primitive = MEM32(g_esp + 8), fvf = MEM32(g_esp + 12), input = MEM32(g_esp + 16);
   2407     uint32_t count = MEM32(g_esp + 20), flags = MEM32(g_esp + 24);
   2408     g_esp += 28;
   2409     draw_primitive(device, primitive, fvf, input, count, flags, 0, 0, NULL);
   2410 }
   2411 
   2412 static void device_set_texture(void)
   2413 {
   2414     struct device_object *device = find_device(MEM32(g_esp + 4));
   2415     uint32_t stage = MEM32(g_esp + 8), address = MEM32(g_esp + 12);
   2416     if (stage >= 2) { fprintf(stderr, "Unsupported texture stage %u\n", stage); exit(3); }
   2417     struct surface_object *texture = address ? find_surface(address) : NULL;
   2418     g_eax = 0x80070057u;
   2419     g_esp += 16;
   2420     if (texture && !(texture->caps & 0x1000)) return;
   2421     if (device->stages[stage].texture != texture) {
   2422         if (texture) ++texture->references[0];
   2423         if (device->stages[stage].texture) release_surface(device->stages[stage].texture, 0);
   2424         device->stages[stage].texture = texture;
   2425     }
   2426     g_eax = 0;
   2427 }
   2428 
   2429 static void device_validate(void)
   2430 {
   2431     find_device(MEM32(g_esp + 4));
   2432     uint32_t output = MEM32(g_esp + 8);
   2433     g_esp += 12;
   2434     g_eax = 0x80070057u;
   2435     if (!output) return;
   2436     /* Setters reject unsupported states; the accepted pipeline uses one pass. */
   2437     MEM32(output) = 1;
   2438     g_eax = 0;
   2439 }
   2440 
   2441 static void device_get_texture(void)
   2442 {
   2443     struct device_object *device = find_device(MEM32(g_esp + 4));
   2444     uint32_t stage = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   2445     if (stage >= 2) { fprintf(stderr, "Unsupported texture stage %u\n", stage); exit(3); }
   2446     g_eax = 0x80070057u;
   2447     if (output) {
   2448         MEM32(output) = device->stages[stage].texture ? device->stages[stage].texture->interfaces[0] : 0;
   2449         if (device->stages[stage].texture) ++device->stages[stage].texture->references[0];
   2450         g_eax = 0;
   2451     }
   2452     g_esp += 16;
   2453 }
   2454 
   2455 static uint32_t texture_stage_state(struct texture_stage *stage, uint32_t state)
   2456 {
   2457     switch (state) {
   2458     case 1: return stage->color_op;
   2459     case 2: return stage->color_arg1;
   2460     case 5: return stage->alpha_arg1;
   2461     case 3: return stage->color_arg2;
   2462     case 6: return stage->alpha_arg2;
   2463     case 4: return stage->alpha_op;
   2464     case 7: case 8: case 9: case 10: /* Inactive bump matrix. */
   2465     case 15: case 19: case 20: case 22: case 23: return 0;
   2466     case 11: return stage->texture_coordinate;
   2467     case 24: return stage->texture_transform;
   2468     case 12: return stage->address;
   2469     case 13: return stage->address_u;
   2470     case 14: return stage->address_v;
   2471     case 16: return stage->mag_filter;
   2472     case 17: return stage->min_filter;
   2473     case 18: return stage->mip_filter;
   2474     case 21: return 1; /* No anisotropic filtering. */
   2475     default: fprintf(stderr, "Unsupported texture-stage state %u\n", state); exit(3);
   2476     }
   2477 }
   2478 
   2479 static void device_get_texture_state(void)
   2480 {
   2481     struct device_object *device = find_device(MEM32(g_esp + 4));
   2482     uint32_t stage = MEM32(g_esp + 8), state = MEM32(g_esp + 12), output = MEM32(g_esp + 16);
   2483     g_eax = 0x80070057u;
   2484     if (output && stage < 8 && state >= 1 && state <= 24) {
   2485         /* Disabled stages still have queryable defaults for game state caches. */
   2486         const uint32_t inactive[] = {1, 2, 1, 1, 2, 1, 0, 0, 0, 0, 0, 1,
   2487                                     1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0};
   2488         MEM32(output) = stage >= 2 ? inactive[state - 1] : texture_stage_state(&device->stages[stage], state);
   2489         g_eax = 0;
   2490     }
   2491     g_esp += 20;
   2492 }
   2493 
   2494 static void device_set_texture_state(void)
   2495 {
   2496     struct device_object *device = find_device(MEM32(g_esp + 4));
   2497     uint32_t stage = MEM32(g_esp + 8), state = MEM32(g_esp + 12), value = MEM32(g_esp + 16);
   2498     if (stage >= 2) { fprintf(stderr, "Unsupported texture stage %u\n", stage); exit(3); }
   2499     if (state == 11 && (value <= 1 || value == 0x10000 || value == 0x20000)) device->stages[stage].texture_coordinate = value;
   2500     else if (state == 16 && (value == 1 || value == 2)) device->stages[stage].mag_filter = value;
   2501     else if (state == 17 && (value == 1 || value == 2)) device->stages[stage].min_filter = value;
   2502     else if (state == 18 && (value == 1 || value == 2)) device->stages[stage].mip_filter = value;
   2503     else if (state == 24 && (value == 0 || value == 2 || value == 3)) device->stages[stage].texture_transform = value;
   2504     /* ADDRESS has an independent cache; only changed states update the sampler. */
   2505     else if (state == 12 && (value == 1 || value == 3)) {
   2506         if (device->stages[stage].address != value) device->stages[stage].sampler_u = device->stages[stage].sampler_v = value;
   2507         device->stages[stage].address = value;
   2508     } else if (state == 13 && (value == 1 || value == 3)) {
   2509         if (device->stages[stage].address_u != value) device->stages[stage].sampler_u = value;
   2510         device->stages[stage].address_u = value;
   2511     } else if (state == 14 && (value == 1 || value == 3)) {
   2512         if (device->stages[stage].address_v != value) device->stages[stage].sampler_v = value;
   2513         device->stages[stage].address_v = value;
   2514     }
   2515     else if (state == 1 && (value == 1 || value == 2 || value == 4 || value == 6 || value == 7 || value == 20)) device->stages[stage].color_op = value;
   2516     else if (state == 4 && ((value >= 1 && value <= 4) || value == 6)) device->stages[stage].alpha_op = value;
   2517     /* CURRENT selects the preceding stage; DIFFUSE selects vertex color. */
   2518     else if (state == 2 && (value & ~0x20u) <= 3) device->stages[stage].color_arg1 = value;
   2519     else if (state == 5 && (value & ~0x20u) <= 3) device->stages[stage].alpha_arg1 = value;
   2520     else if (state == 3 && (value & ~0x20u) <= 3) device->stages[stage].color_arg2 = value;
   2521     else if (state == 6 && (value & ~0x20u) <= 3) device->stages[stage].alpha_arg2 = value;
   2522     else if (value != texture_stage_state(&device->stages[stage], state)) {
   2523         fprintf(stderr, "Unsupported texture-stage state %u value=%08x\n", state, value); exit(3);
   2524     }
   2525     g_eax = 0;
   2526     g_esp += 20;
   2527 }
   2528 
   2529 static void device_texture_formats(void)
   2530 {
   2531     find_device(MEM32(g_esp + 4));
   2532     uint32_t callback = MEM32(g_esp + 8), data = MEM32(g_esp + 12);
   2533     if (!callback) { g_eax = 0x80070057u; g_esp += 16; return; }
   2534     uint32_t record = guest_malloc(32);
   2535     if (!record) abort();
   2536     recomp_func_t function = recomp_lookup(callback);
   2537     if (!function) function = recomp_lookup_import(callback);
   2538     uint32_t stack = g_esp, caller = g_cur_func;
   2539     const uint32_t formats[][8] = {
   2540         {32, 0x40, 0, 32, 0xff0000, 0xff00, 0xff, 0},
   2541         {32, 0x41, 0, 32, 0xff0000, 0xff00, 0xff, 0xff000000},
   2542         {32, 0x40, 0, 16, 0xf800, 0x7e0, 0x1f, 0},
   2543     };
   2544     for (unsigned i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) {
   2545         memcpy((void *)ADDR(record), formats[i], 32);
   2546         PUSH32(g_esp, data);
   2547         PUSH32(g_esp, record);
   2548         PUSH32(g_esp, RECOMP_RETADDR);
   2549         function();
   2550         if (g_esp != stack) { fprintf(stderr, "Texture-format callback unbalanced the guest stack\n"); abort(); }
   2551         g_cur_func = caller;
   2552         if (!g_eax) break;
   2553     }
   2554     guest_free(record);
   2555     g_eax = 0;
   2556     g_esp += 16;
   2557 }
   2558 
   2559 static struct vertex_buffer *find_vertex_buffer(uint32_t address)
   2560 {
   2561     for (struct vertex_buffer *buffer = vertex_buffers[interface_bucket(address)]; buffer; buffer = buffer->next)
   2562         if (buffer->interface == address) return buffer;
   2563     fprintf(stderr, "Invalid guest vertex buffer %08x\n", address);
   2564     abort();
   2565 }
   2566 
   2567 static unsigned vertex_stride(uint32_t fvf)
   2568 {
   2569     unsigned position = fvf & 14, textures = (fvf >> 8) & 15;
   2570     if (!position || textures > 8 || (fvf & 0xf001)) return 0;
   2571     unsigned size = position == 2 ? 12 : position == 4 ? 16 : (position / 2 + 1) * 4;
   2572     if (fvf & 16) size += 12;
   2573     if (fvf & 32) size += 4;
   2574     if (fvf & 64) size += 4;
   2575     if (fvf & 128) size += 4;
   2576     const unsigned dimensions[] = {2, 3, 4, 1};
   2577     for (unsigned i = 0; i < textures; ++i) size += dimensions[(fvf >> (16 + i * 2)) & 3] * 4;
   2578     return size;
   2579 }
   2580 
   2581 static void create_vertex_buffer(void)
   2582 {
   2583     struct draw_object *owner = find_object(MEM32(g_esp + 4));
   2584     uint32_t desc = MEM32(g_esp + 8), output = MEM32(g_esp + 12), flags = MEM32(g_esp + 16);
   2585     g_esp += 20;
   2586     g_eax = 0x80070057u;
   2587     if (!output) return;
   2588     MEM32(output) = 0;
   2589     if (!desc || MEM32(desc) != 16 || flags) return;
   2590     uint32_t caps = MEM32(desc + 4), fvf = MEM32(desc + 8), count = MEM32(desc + 12);
   2591     unsigned stride = vertex_stride(fvf);
   2592     if (!stride || !count || count > UINT32_MAX / stride) return;
   2593     if (caps & ~0x10801u) { fprintf(stderr, "Unsupported vertex buffer caps %08x\n", caps); exit(3); }
   2594     struct vertex_buffer *buffer = calloc(1, sizeof(*buffer));
   2595     if (!buffer) abort();
   2596     buffer->size = stride * count;
   2597     buffer->data = guest_malloc(buffer->size);
   2598     if (!buffer->data) { free(buffer); g_eax = 0x8007000eu; return; }
   2599     buffer->interface = create_interface(7);
   2600     buffer->references = 1;
   2601     buffer->caps = caps; buffer->fvf = fvf; buffer->count = count;
   2602     buffer->owner = owner;
   2603     ++owner->references[1];
   2604     unsigned bucket = interface_bucket(buffer->interface);
   2605     buffer->next = vertex_buffers[bucket];
   2606     vertex_buffers[bucket] = buffer;
   2607     MEM32(output) = buffer->interface;
   2608     g_eax = 0;
   2609 }
   2610 
   2611 static void device_draw_vertex_buffer(void)
   2612 {
   2613     struct device_object *device = find_device(MEM32(g_esp + 4));
   2614     uint32_t primitive = MEM32(g_esp + 8);
   2615     struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 12));
   2616     uint32_t start = MEM32(g_esp + 16), count = MEM32(g_esp + 20), flags = MEM32(g_esp + 24);
   2617     uint32_t indices = 0, index_count = 0;
   2618     if (current_slot == 32) {
   2619         indices = MEM32(g_esp + 24);
   2620         index_count = MEM32(g_esp + 28);
   2621         flags = MEM32(g_esp + 32);
   2622     }
   2623     g_esp += current_slot == 32 ? 36 : 28;
   2624     g_eax = 0x80070057u;
   2625     if (current_slot == 32 && !indices) return;
   2626     if (start > buffer->count || count > buffer->count - start) return;
   2627     draw_primitive(device, primitive, buffer->fvf,
   2628                    buffer->data + start * vertex_stride(buffer->fvf), count, flags, indices, index_count, buffer);
   2629 }
   2630 
   2631 static void vertex_buffer_query_interface(void)
   2632 {
   2633     struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 4));
   2634     uint32_t iid = MEM32(g_esp + 8), output = MEM32(g_esp + 12);
   2635     const uint32_t unknown[] = {0, 0, 0xc0, 0x46000000};
   2636     const uint32_t buffer7[] = {0xf5049e7d, 0x11d24861, 0xa00007a4, 0xa82906c9};
   2637     g_esp += 16;
   2638     g_eax = 0x80070057u;
   2639     if (!output) return;
   2640     MEM32(output) = 0;
   2641     g_eax = 0x80004002u;
   2642     if (memcmp((void *)ADDR(iid), unknown, 16) && memcmp((void *)ADDR(iid), buffer7, 16)) return;
   2643     MEM32(output) = buffer->interface;
   2644     ++buffer->references;
   2645     g_eax = 0;
   2646 }
   2647 
   2648 static void vertex_buffer_add_reference(void)
   2649 {
   2650     g_eax = ++find_vertex_buffer(MEM32(g_esp + 4))->references;
   2651     g_esp += 8;
   2652 }
   2653 
   2654 static void vertex_buffer_release_reference(void)
   2655 {
   2656     struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 4));
   2657     g_eax = --buffer->references;
   2658     if (!g_eax) {
   2659         struct vertex_buffer **link = &vertex_buffers[interface_bucket(buffer->interface)];
   2660         while (*link != buffer) link = &(*link)->next;
   2661         *link = buffer->next;
   2662         release_draw(buffer->owner, 1);
   2663         if (buffer->gpu) gl_vertex_buffer_destroy(buffer->gpu);
   2664         guest_free(buffer->data);
   2665         guest_free(buffer->interface);
   2666         free(buffer);
   2667     }
   2668     g_esp += 8;
   2669 }
   2670 
   2671 static void vertex_buffer_lock(void)
   2672 {
   2673     struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 4));
   2674     uint32_t flags = MEM32(g_esp + 8), output = MEM32(g_esp + 12), size = MEM32(g_esp + 16);
   2675     g_esp += 20;
   2676     g_eax = 0x80070057u;
   2677     if (!output) return;
   2678     if (flags & ~0x3831u) { fprintf(stderr, "Unsupported vertex buffer lock flags %08x\n", flags); exit(3); }
   2679     if (buffer->gpu && !(flags & 0x10)) gl_vertex_buffer_invalidate(buffer->gpu);
   2680     MEM32(output) = buffer->data;
   2681     if (size) MEM32(size) = buffer->size;
   2682     g_eax = 0;
   2683 }
   2684 
   2685 static void vertex_buffer_unlock(void)
   2686 {
   2687     find_vertex_buffer(MEM32(g_esp + 4));
   2688     g_eax = 0;
   2689     g_esp += 8;
   2690 }
   2691 
   2692 static void vertex_buffer_description(void)
   2693 {
   2694     struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 4));
   2695     uint32_t output = MEM32(g_esp + 8);
   2696     g_eax = 0x80070057u;
   2697     if (output) {
   2698         MEM32(output + 4) = buffer->caps;
   2699         MEM32(output + 8) = buffer->fvf;
   2700         MEM32(output + 12) = buffer->count;
   2701         g_eax = 0;
   2702     }
   2703     g_esp += 12;
   2704 }
   2705 
   2706 static void vertex_buffer_optimize(void)
   2707 {
   2708     struct vertex_buffer *buffer = find_vertex_buffer(MEM32(g_esp + 4));
   2709     /* The renderer consumes the existing layout directly; no conversion is needed. */
   2710     buffer->caps |= 0x80000000u;
   2711     g_eax = 0;
   2712     g_esp += 16;
   2713 }
   2714 
   2715 static void unavailable_method(void)
   2716 {
   2717     const char *names[] = {"IDirectDraw", "IDirectDraw7", "IDirect3D7", "IDirectDrawSurface7", "IDirectDrawSurface", "IDirectDrawClipper", "IDirect3DDevice7", "IDirect3DVertexBuffer7", "IDirectDrawPalette"};
   2718     fprintf(stderr, "Unimplemented %s method slot %u caller=%08x\n",
   2719             names[current_interface], current_slot, g_cur_func);
   2720     exit(3);
   2721 }
   2722 
   2723 recomp_func_t linux_graphics_virtual(uint32_t address)
   2724 {
   2725     if (address < 0xf3000000u || address >= 0xf3000900u || (address & 3)) return NULL;
   2726 #ifdef __EMSCRIPTEN__
   2727     browser_graphics_ready();
   2728 #endif
   2729     current_interface = (address - 0xf3000000u) / 0x100;
   2730     current_slot = (address & 0xff) / 4;
   2731     if (current_slot >= interface_slots[current_interface]) return NULL;
   2732     if (current_interface == 8) {
   2733         if (current_slot == 0) return palette_query_interface;
   2734         if (current_slot == 1) return palette_add_reference;
   2735         if (current_slot == 2) return palette_release_reference;
   2736         if (current_slot == 3) return palette_caps;
   2737         if (current_slot == 4 || current_slot == 6) return palette_entries;
   2738         if (current_slot == 5) return palette_initialize;
   2739     }
   2740     if (current_interface == 7) {
   2741         if (current_slot == 0) return vertex_buffer_query_interface;
   2742         if (current_slot == 1) return vertex_buffer_add_reference;
   2743         if (current_slot == 2) return vertex_buffer_release_reference;
   2744         if (current_slot == 3) return vertex_buffer_lock;
   2745         if (current_slot == 4) return vertex_buffer_unlock;
   2746         if (current_slot == 6) return vertex_buffer_description;
   2747         if (current_slot == 7) return vertex_buffer_optimize;
   2748         return unavailable_method;
   2749     }
   2750     if (current_interface == 6) {
   2751         if (current_slot == 0) return device_query_interface;
   2752         if (current_slot == 1) return device_add_reference;
   2753         if (current_slot == 2) return device_release_reference;
   2754         if (current_slot == 3) return device_caps;
   2755         if (current_slot == 4) return device_texture_formats;
   2756         if (current_slot == 5) return device_begin_scene;
   2757         if (current_slot == 6) return device_end_scene;
   2758         if (current_slot == 7) return device_parent;
   2759         if (current_slot == 8) return device_set_target;
   2760         if (current_slot == 9) return device_get_target;
   2761         if (current_slot == 10) return device_clear;
   2762         if (current_slot == 11 || current_slot == 12) return device_transform;
   2763         if (current_slot == 13) return device_set_viewport;
   2764         if (current_slot == 15) return device_viewport;
   2765         if (current_slot == 16 || current_slot == 17) return device_material;
   2766         if (current_slot == 18 || current_slot == 19 || current_slot == 44 || current_slot == 45) return device_light_state;
   2767         if (current_slot == 20) return device_set_state;
   2768         if (current_slot == 21) return device_get_state;
   2769         if (current_slot == 25) return device_draw_primitive;
   2770         if (current_slot == 34) return device_get_texture;
   2771         if (current_slot == 35) return device_set_texture;
   2772         if (current_slot == 38) return device_validate;
   2773         if (current_slot == 31 || current_slot == 32) return device_draw_vertex_buffer;
   2774         if (current_slot == 36) return device_get_texture_state;
   2775         if (current_slot == 37) return device_set_texture_state;
   2776         return unavailable_method;
   2777     }
   2778     if (current_interface == 5) {
   2779         if (current_slot == 0) return clipper_query_interface;
   2780         if (current_slot == 1) return clipper_add_reference;
   2781         if (current_slot == 2) return clipper_release_reference;
   2782         if (current_slot == 3) return clipper_get_list;
   2783         if (current_slot == 4) return clipper_get_window;
   2784         if (current_slot == 8) return clipper_set_window;
   2785         return unavailable_method;
   2786     }
   2787     if (current_interface >= 3) {
   2788         if (current_slot == 0) return surface_query_interface;
   2789         if (current_slot == 1) return surface_add_reference;
   2790         if (current_slot == 2) return surface_release_reference;
   2791         if (current_interface == 3) {
   2792             if (current_slot == 3) return surface_attach;
   2793             if (current_slot == 5) return surface_blit;
   2794             if (current_slot == 8) return surface_detach;
   2795             if (current_slot == 12) return surface_get_attached;
   2796             if (current_slot == 15) return surface_get_clipper;
   2797             if (current_slot == 21) return surface_get_pixel_format;
   2798             if (current_slot == 22) return surface_description;
   2799             if (current_slot == 24 || current_slot == 27) return surface_not_lost;
   2800             if (current_slot == 25) return surface_lock;
   2801             if (current_slot == 28) return surface_set_clipper;
   2802             if (current_slot == 32) return surface_unlock;
   2803             if (current_slot == 36) return surface_owner;
   2804             if (current_slot == 40) return surface_set_private_data;
   2805             if (current_slot == 41) return surface_get_private_data;
   2806             if (current_slot == 42) return surface_free_private_data;
   2807         }
   2808         return unavailable_method;
   2809     }
   2810     if (current_slot == 0) return query_interface;
   2811     if (current_slot == 1) return add_reference;
   2812     if (current_slot == 2) return release_reference;
   2813     if (current_interface == 2 && current_slot == 3) return enumerate_devices;
   2814     if (current_interface == 2 && current_slot == 4) return create_device;
   2815     if (current_interface == 2 && current_slot == 5) return create_vertex_buffer;
   2816     if (current_interface == 2 && current_slot == 7) return evict_managed_textures;
   2817     if (current_interface == 1 && current_slot == 4) return create_clipper;
   2818     if (current_interface == 1 && current_slot == 5) return create_palette;
   2819     if (current_interface == 1 && current_slot == 6) return create_surface;
   2820     if (current_interface == 1 && current_slot == 8) return enumerate_display_modes;
   2821     if (current_interface == 1 && current_slot == 12) return get_display_mode;
   2822     if (current_interface == 1 && current_slot == 19) return restore_display_mode;
   2823     if (current_slot == 11) return get_caps;
   2824     if (current_slot == 20) return set_cooperative_level;
   2825     if (current_interface == 1 && current_slot == 22) return wait_for_vertical_blank;
   2826     if (current_interface == 1 && current_slot == 26) return test_cooperative_level;
   2827     if (current_interface == 1 && current_slot == 27) return get_device_identifier;
   2828     return unavailable_method;
   2829 }
   2830 
   2831 recomp_func_t linux_graphics_lookup(const char *name)
   2832 {
   2833     if (!strcmp(name, "DirectDrawCreate")) return direct_draw_create;
   2834     if (!strcmp(name, "DirectDrawCreateEx")) return direct_draw_create_ex;
   2835     if (!strcmp(name, "DirectDrawEnumerateExA")) return enumerate_adapters;
   2836     return NULL;
   2837 }