diff --git a/d2/2d/font.c b/d2/2d/font.c index 5f62f04..3d2f1b9 100644 --- a/d2/2d/font.c +++ b/d2/2d/font.c @@ -701,6 +701,9 @@ int ogl_internal_string(int x, int y, const char *s ) if (grd_curscreen->sc_canvas.cv_bitmap.bm_type != BM_OGL) Error("carp.\n"); + // glyphs drawn several times their size get smooth edges at screen resolution + float glyph_scale = FONTSCALE_X(1) < FONTSCALE_Y(1) ? FONTSCALE_X(1) : FONTSCALE_Y(1); + int sharp = ogl_glyph_begin(glyph_scale); while (next_row != NULL) { text_ptr1 = next_row; @@ -739,10 +742,14 @@ int ogl_internal_string(int x, int y, const char *s ) if (underline) { ubyte save_c = (unsigned char) COLOR; - + + if (sharp) + ogl_shader_end(); gr_setcolor(grd_curcanv->cv_font_fg_color); gr_rect(xx, yy + grd_curcanv->cv_font->ft_baseline + 2, xx + grd_curcanv->cv_font->ft_w, yy + grd_curcanv->cv_font->ft_baseline + 3); gr_setcolor(save_c); + if (sharp) + ogl_glyph_begin(glyph_scale); } continue; @@ -768,6 +775,8 @@ int ogl_internal_string(int x, int y, const char *s ) } } + if (sharp) + ogl_shader_end(); return 0; } diff --git a/d2/arch/include/joy.h b/d2/arch/include/joy.h index 8e3f48d..872cf6a 100644 --- a/d2/arch/include/joy.h +++ b/d2/arch/include/joy.h @@ -23,6 +23,9 @@ struct d_event; extern int joy_num_axes; // set to Joystick.n_axes. solve different? extern void joy_init(); extern void joy_close(); +#ifdef __EMSCRIPTEN__ +extern void joy_rescan(); +#endif extern void event_joystick_get_axis(struct d_event *event, int *axis, int *value); extern void joy_flush(); extern int event_joystick_get_button(struct d_event *event); diff --git a/d2/arch/include/key.h b/d2/arch/include/key.h index 1812c5d..205c346 100644 --- a/d2/arch/include/key.h +++ b/d2/arch/include/key.h @@ -44,6 +44,9 @@ extern unsigned char unicode_frame_buffer[KEY_BUFFER_SIZE]; extern void key_flush(); // Clears the 256 char buffer extern int event_key_get(d_event *event); // Get the keycode from the EVENT_KEY_COMMAND event extern int event_key_get_raw(d_event *event); // same as above but without mod states +#ifdef __EMSCRIPTEN__ +extern void key_send_escape(void); // an Escape press for the window in front (the page's Skip button) +#endif extern unsigned char key_ascii(); // Set to 1 if the key is currently down, else 0 diff --git a/d2/arch/ogl/gr.c b/d2/arch/ogl/gr.c index c5cca0b..c0e7162 100644 --- a/d2/arch/ogl/gr.c +++ b/d2/arch/ogl/gr.c @@ -30,6 +30,7 @@ #include #include +#include "web.h" #include "hudmsg.h" #include "game.h" #include "text.h" @@ -116,6 +117,9 @@ void ogl_swap_buffers_internal(void) #else SDL_GL_SwapBuffers(); #endif +#ifdef __EMSCRIPTEN__ + d2web_frame_wait(); +#endif } #ifdef RPI @@ -424,7 +428,9 @@ int ogl_init_window(int x, int y) con_printf(CON_DEBUG, "EGL: made context current\n"); } #endif +#ifndef __EMSCRIPTEN__ glewInit(); +#endif #ifdef OGL_MERGE ogl_init_prog(); #endif diff --git a/d2/arch/ogl/ogl.c b/d2/arch/ogl/ogl.c index c536c46..58786e5 100644 --- a/d2/arch/ogl/ogl.c +++ b/d2/arch/ogl/ogl.c @@ -10,7 +10,13 @@ #include #include #endif +#ifndef __EMSCRIPTEN__ #include +#else +#define GL_GLEXT_PROTOTYPES +#include +#include +#endif #if defined(__APPLE__) && defined(__MACH__) #include #include @@ -52,6 +58,10 @@ #include "byteswap.h" #include "internal.h" #include "gauges.h" +#include "plight.h" +#ifdef __EMSCRIPTEN__ +#include "../web/web.h" +#endif #include "playsave.h" #include "args.h" #include "xmodel.h" @@ -83,7 +93,7 @@ int GL_texclamp_enabled=-1; GLfloat ogl_maxanisotropy = 0; int r_texcount = 0, r_cachedtexcount = 0; -#ifdef OGLES +#if defined(OGLES) || defined(__EMSCRIPTEN__) // WebGL only takes unsized formats int ogl_rgba_internalformat = GL_RGBA; int ogl_rgb_internalformat = GL_RGB; #else @@ -143,12 +153,18 @@ void ogl_init_texture_stats(ogl_texture* t){ void ogl_init_texture(ogl_texture* t, int w, int h, int flags) { t->handle = 0; + t->nmap = t->gmap = t->emap = 0; #ifndef OGLES if (flags & OGL_FLAG_NOCOLOR) { // use GL_INTENSITY instead of GL_RGB if (flags & OGL_FLAG_ALPHA) { +#ifdef __EMSCRIPTEN__ + // WebGL has no INTENSITY formats; luminance-alpha keeps glyphs white so glColor tints them + t->internalformat = GL_LUMINANCE_ALPHA; + t->format = GL_LUMINANCE_ALPHA; +#else if (GameArg.DbgGlIntensity4Ok) { t->internalformat = GL_INTENSITY4; @@ -169,6 +185,7 @@ void ogl_init_texture(ogl_texture* t, int w, int h, int flags) t->internalformat = ogl_rgba_internalformat; t->format = GL_RGBA; } +#endif } else { @@ -773,6 +790,7 @@ bool g3_draw_tmap(int nv,const g3s_point **pointlist,g3s_uvl *uvl_list,g3s_lrgb int c, index2, index3, index4; GLfloat vertex_array[MAX_VERTS * 3], color_array[MAX_VERTS * 4], texcoord_array[MAX_VERTS * 2]; GLfloat color_alpha = 1.0; + int pl = 0; if (nv > MAX_VERTS) Error("Too many vertices: %d", nv); @@ -785,6 +803,7 @@ bool g3_draw_tmap(int nv,const g3s_point **pointlist,g3s_uvl *uvl_list,g3s_lrgb OGL_ENABLE(TEXTURE_2D); ogl_bindbmtex(bm); ogl_texwrap(bm->gltexture, GL_REPEAT); + pl = plight_bind(bm, 0); // a wall lit per pixel r_tpolyc++; color_alpha = (grd_curcanv->cv_fade_level >= GR_FADE_OFF)?1.0:(1.0 - (float)grd_curcanv->cv_fade_level / ((float)GR_FADE_LEVELS - 1.0)); } else if (tmap_drawer_ptr == draw_tmap_flat) { @@ -827,6 +846,8 @@ bool g3_draw_tmap(int nv,const g3s_point **pointlist,g3s_uvl *uvl_list,g3s_lrgb } glDrawArrays(GL_TRIANGLE_FAN, 0, nv); + if (pl) + plight_unbind(); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); @@ -920,7 +941,11 @@ bool g3_draw_tmap_2(int nv, const g3s_point **pointlist, g3s_uvl *uvl_list, g3s_ glVertexPointer(3, GL_FLOAT, 0, vertex_array); glColorPointer(4, GL_FLOAT, 0, color_array); glTexCoordPointer(2, GL_FLOAT, 0, texcoordovl_array); - glDrawArrays(GL_TRIANGLE_FAN, 0, nv); + if (plight_bind(bmovl, 1)) { + glDrawArrays(GL_TRIANGLE_FAN, 0, nv); + plight_unbind(); + } else + glDrawArrays(GL_TRIANGLE_FAN, 0, nv); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); @@ -952,6 +977,8 @@ bool g3_draw_tmap_2(int nv, const g3s_point **pointlist, g3s_uvl *uvl_list, g3s_ /* * 2d Sprites (Fireaballs, powerups, explosions). NOT hostages */ +float ogl_sprite_glow; + bool g3_draw_bitmap_full(vms_vector *pos,fix width,fix height,grs_bitmap *bm, GLfloat r, GLfloat g, GLfloat b) { @@ -1014,7 +1041,12 @@ bool g3_draw_bitmap_full(vms_vector *pos,fix width,fix height,grs_bitmap *bm, glVertexPointer(3, GL_FLOAT, 0, vertex_array); glColorPointer(4, GL_FLOAT, 0, color_array); glTexCoordPointer(2, GL_FLOAT, 0, texcoord_array); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); // Replaced GL_QUADS + if (ogl_sprite_glow > 0 && ogl_sprite_begin(bm->gltexture, ogl_post_active() ? ogl_sprite_glow : 1, + grd_curcanv->cv_blend_func != GR_BLEND_NORMAL)) { + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + ogl_shader_end(); + } else + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); // Replaced GL_QUADS glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); @@ -1093,7 +1125,11 @@ bool ogl_ubitblt_i(int dw,int dh,int dx,int dy, int sw, int sh, int sx, int sy, glVertexPointer(2, GL_FLOAT, 0, vertex_array); glColorPointer(4, GL_FLOAT, 0, color_array); glTexCoordPointer(2, GL_FLOAT, 0, texcoord_array); + // movies: a sharp upscale instead of a bilinear stretch + int sharp = ogl_upscale_begin(&tex, 0, 0, tex.u, tex.v, dh / (float)sh, 1); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);//replaced GL_QUADS + if (sharp) + ogl_shader_end(); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); @@ -1146,7 +1182,12 @@ void ogl_start_frame(void){ r_polyc=0;r_tpolyc=0;r_bitmapc=0;r_ubitbltc=0;r_upixelc=0; - OGL_VIEWPORT(grd_curcanv->cv_bitmap.bm_x,grd_curcanv->cv_bitmap.bm_y,Canvas_width,Canvas_height); + if (ogl_post_active()) { // drawing into the off-screen view, which starts at its corner + glViewport(0, 0, Canvas_width, Canvas_height); + last_width = Canvas_width; + last_height = Canvas_height; + } else + OGL_VIEWPORT(grd_curcanv->cv_bitmap.bm_x,grd_curcanv->cv_bitmap.bm_y,Canvas_width,Canvas_height); glClearColor(0.0, 0.0, 0.0, 0.0); glLineWidth(linedotscale); @@ -1256,7 +1297,7 @@ void ogl_init_pixel_buffers(int w, int h) if (texbuf) d_free(texbuf); - texbuf = d_malloc(max(w, 1024)*max(h, 1024)*4); // must also fit big font texture + texbuf = d_malloc(max(w, 4096)*max(h, 4096)*4); // must also fit big font texture and the extra-sharp textures if ((pixels == NULL) || (texbuf == NULL)) Error("Not enough memory for current resolution"); @@ -1272,7 +1313,7 @@ void ogl_filltexbuf(unsigned char *data, GLubyte *texp, int truewidth, int width { int x,y,c,i; - if ((width > max(grd_curscreen->sc_w, 1024)) || (height > max(grd_curscreen->sc_h, 1024))) + if ((width > max(grd_curscreen->sc_w, 4096)) || (height > max(grd_curscreen->sc_h, 4096))) Error("Texture is too big: %ix%i", width, height); if (data_format) { // true color bitmap? @@ -1644,6 +1685,247 @@ void ogl_loadpngmask(png_data *pdata, grs_bitmap *bm, int texfilt) } #endif +// the bitmap's palette indices, RLE decoded (into decodebuf) +unsigned char *ogl_bitmap_indices(grs_bitmap *bm) +{ + unsigned char *sbits, *dbits; + int i, data_offset = bm->bm_flags & BM_FLAG_RLE_BIG ? 2 : 1; + + if (!(bm->bm_flags & BM_FLAG_RLE)) + return bm->bm_data; + sbits = &bm->bm_data[4 + (bm->bm_h * data_offset)]; + dbits = decodebuf; + for (i = 0; i < bm->bm_h; i++) { + gr_rle_decode(sbits, dbits); + if (bm->bm_flags & BM_FLAG_RLE_BIG) + sbits += (int)INTEL_SHORT(*((short *)&(bm->bm_data[4 + (i * data_offset)]))); + else + sbits += (int)bm->bm_data[4 + i]; + dbits += bm->bm_w; + } + return decodebuf; +} + +// Scales an RGBA image's colors so its average matches the game bitmap it replaces, as the +// current palette shows that bitmap (orig: its palette indices). +static void ogl_match_colors(grs_bitmap *bm, const unsigned char *orig, unsigned char *rgba, int n) +{ + double osum[3] = { 0, 0, 0 }, psum[3] = { 0, 0, 0 }, gain[3]; + int on = 0, pn = 0, i, k; + + for (i = 0; i < bm->bm_w * bm->bm_h; i++) + if (orig[i] < 254) { + for (k = 0; k < 3; k++) + osum[k] += ogl_pal[orig[i] * 3 + k] * 4; + on++; + } + for (i = 0; i < n; i++) + if (rgba[i * 4 + 3] >= 128) { + for (k = 0; k < 3; k++) + psum[k] += rgba[i * 4 + k]; + pn++; + } + if (!on || !pn) + return; + for (k = 0; k < 3; k++) { + gain[k] = psum[k] > 0 ? (osum[k] / on) / (psum[k] / pn) : 1; + gain[k] = gain[k] < 0.5 ? 0.5 : gain[k] > 3 ? 3 : gain[k]; + } + if (fabs(gain[0] - 1) < 0.03 && fabs(gain[1] - 1) < 0.03 && fabs(gain[2] - 1) < 0.03) + return; + for (i = 0; i < n; i++) + for (k = 0; k < 3; k++) { + double v = rgba[i * 4 + k] * gain[k]; + rgba[i * 4 + k] = v > 255 ? 255 : (unsigned char)v; + } +} + +// The bitmap's average color (0..1) as the current palette shows it (xmodel.cpp). +void ogl_bitmap_average(grs_bitmap *bm, float *rgb) +{ + const unsigned char *orig; + double sum[3] = { 0, 0, 0 }; + int n = 0, i, k; + + rgb[0] = rgb[1] = rgb[2] = 0; + if (!bm || !bm->bm_data || !bm->bm_w || !bm->bm_h) + return; + orig = ogl_bitmap_indices(bm); + for (i = 0; i < bm->bm_w * bm->bm_h; i++) + if (orig[i] < 254) { + for (k = 0; k < 3; k++) + sum[k] += ogl_pal[orig[i] * 3 + k]; + n++; + } + if (n) + for (k = 0; k < 3; k++) + rgb[k] = sum[k] / n / 63; +} + +// For replacements of model textures (xmodel.cpp): match the game bitmap's colors. +void ogl_match_bitmap_colors(grs_bitmap *bm, unsigned char *rgba, int w, int h) +{ + if (bm && bm->bm_data && bm->bm_w && bm->bm_h) + ogl_match_colors(bm, ogl_bitmap_indices(bm), rgba, w * h); +} + +#ifdef HAVE_LIBPNG +// Fits a replacement texture to the game bitmap it stands for. The hi-res packs were made +// from one palette, often come out darker, and some lack the transparency the game needs +// (muzzle flashes on black, say). So the copy takes the original's transparency where the +// image has none, and the original's average color as this level's palette shows it. +// Returns a new RGBA buffer. +static unsigned char *ogl_fit_png(grs_bitmap *bm, png_data *pdata) +{ + int w = pdata->width, h = pdata->height, n = w * h, bpp = pdata->paletted ? 1 : pdata->channels, i; + unsigned char *rgba = malloc(n * 4), *orig = bm->bm_data ? ogl_bitmap_indices(bm) : NULL; + int alpha = pdata->alpha && !pdata->paletted && bpp == 4; + + for (i = 0; i < n; i++) { + const unsigned char *s = pdata->paletted ? pdata->palette + pdata->data[i] * 3 : pdata->data + i * bpp; + unsigned char *d = rgba + i * 4; + d[0] = s[0]; + d[1] = s[1]; + d[2] = s[2]; + d[3] = alpha ? s[3] : 255; + if (orig && !alpha) { + int c = orig[(i / w * bm->bm_h / h) * bm->bm_w + (i % w) * bm->bm_w / w]; + if ((c == 255 && (bm->bm_flags & BM_FLAG_TRANSPARENT)) || (c == 254 && (bm->bm_flags & BM_FLAG_SUPER_TRANSPARENT))) + d[3] = 0; + } + if (d[0] == 120 && d[1] == 88 && d[2] == 128) // D2X-XL's super transparency color + d[3] = 0; + } + if (orig) + ogl_match_colors(bm, orig, rgba, n); + return rgba; +} + +// D2X-XL texture packs store an animation as one vertical strip of frames in name#0.png +// (frame k in row k). Reads the replacement for one frame: name#k.png, or row k of the strip. +// The sharper set (ultra/.jpg or .png, four times D2X-XL's size) when it is on and has +// the texture, else D2X-XL's .png. +static int read_hires_image(const char *name, png_data *pdata) +{ + char filename[80]; +#ifdef __EMSCRIPTEN__ + if (d2web_tune(99, 0) > 0) { // test: list the textures a level loads + FILE *f = fopen("/tmp/d2textures.txt", "a"); + if (f) { + fprintf(f, "%s\n", name); + fclose(f); + } + } + if (d2web_option(D2WEB_OPTION_ULTRA)) { + png_data a; + snprintf(filename, sizeof(filename), "ultra/%s.jpg", name); + if (read_image_stb(filename, pdata)) { + // its transparency, if it has any, comes as a grayscale image beside it + snprintf(filename, sizeof(filename), "ultra/%s.alpha.png", name); + if (read_png(filename, &a)) { + if (a.width == pdata->width && a.height == pdata->height && !a.paletted && a.channels == 1) { + unsigned int i, n = a.width * a.height; + for (i = 0; i < n; i++) + pdata->data[i * 4 + 3] = a.data[i]; + pdata->alpha = 1; + } + free(a.data); + if (a.palette) + free(a.palette); + } + return 1; + } + } +#endif + snprintf(filename, sizeof(filename), "%s.png", name); + return read_png(filename, pdata); +} + +#ifdef __EMSCRIPTEN__ +// Material maps beside a texture in the extra-sharp pack, for the per-pixel walls: ultra/_n.jpg (normal), +// _g.jpg (gloss in green, metal in red), _e.jpg (glow). +static GLuint load_material_map(const char *name, const char *suffix) +{ + char filename[80]; + png_data p; + GLuint t = 0; + + snprintf(filename, sizeof(filename), "ultra/%s_%s.jpg", name, suffix); + if (!read_image_stb(filename, &p)) + return 0; + glGenTextures(1, &t); + OGL_BINDTEXTURE(t); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p.width, p.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, p.data); + glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + if (ogl_maxanisotropy > 1.0) + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, ogl_maxanisotropy); + free(p.data); + return t; +} + +static void load_material_maps(ogl_texture *t, const char *name) +{ + if (strchr(name, '#') || d2web_gl_version() < 2 || !d2web_option(D2WEB_OPTION_ULTRA) || !d2web_option(D2WEB_OPTION_LIGHTING)) + return; + t->nmap = load_material_map(name, "n"); + t->gmap = load_material_map(name, "g"); + t->emap = load_material_map(name, "e"); + if (t->nmap || t->gmap || t->emap) + OGL_BINDTEXTURE(t->handle); +} +#endif + +static int read_texture_png(const char *bitmapname, png_data *pdata) +{ + static char strip_name[64]; + static png_data strip; // the last strip read, kept since its frames load one after another + const char *hash = strchr(bitmapname, '#'); + int frame = hash ? atoi(hash + 1) : 0, bpp, size; + char filename[64]; + + if (read_hires_image(bitmapname, pdata)) { + if (!hash || pdata->height <= pdata->width || pdata->height % pdata->width) + return 1; + frame = 0; // a frame 0 file that holds the whole strip + } else { + if (!hash) + return 0; + snprintf(filename, sizeof(filename), "%.*s#0", (int)(hash - bitmapname), bitmapname); + if (strcmp(filename, strip_name)) { + if (strip.data) + free(strip.data); + if (strip.palette) + free(strip.palette); + strip.data = strip.palette = NULL; + strip_name[0] = 0; + if (!read_hires_image(filename, &strip)) + return 0; + strcpy(strip_name, filename); + } + if (strip.height <= strip.width || strip.height % strip.width) + return 0; + *pdata = strip; + if (strip.palette) { + pdata->palette = malloc(strip.num_palette * 3); + memcpy(pdata->palette, strip.palette, strip.num_palette * 3); + } + pdata->data = NULL; + } + bpp = pdata->paletted ? 1 : pdata->channels; + size = pdata->width * pdata->width * bpp; + frame %= pdata->height / pdata->width; + unsigned char *data = malloc(size); + memcpy(data, (pdata->data ? pdata->data : strip.data) + frame * size, size); + if (pdata->data) + free(pdata->data); + pdata->data = data; + pdata->height = pdata->width; + return 1; +} +#endif + void ogl_loadbmtexture_f(grs_bitmap *bm, int texfilt, const char *bitmapname) { unsigned char *buf; @@ -1663,23 +1945,18 @@ void ogl_loadbmtexture_f(grs_bitmap *bm, int texfilt, const char *bitmapname) png_data pdata; sprintf(filename, /*"textures/"*/ "%s.png", bitmapname); - if (read_png(filename, &pdata)) + if (read_texture_png(bitmapname, &pdata)) { con_printf(CON_DEBUG,"%s: %ux%ux%i p=%i(%i) c=%i a=%i chans=%i\n", filename, pdata.width, pdata.height, pdata.depth, pdata.paletted, pdata.num_palette, pdata.color, pdata.alpha, pdata.channels); - if (pdata.depth == 8 && pdata.color) + if (pdata.depth == 8 && pdata.color && (!pdata.paletted || pdata.palette)) { - if (bm->gltexture == NULL) - ogl_init_texture(bm->gltexture = ogl_get_free_texture(), pdata.width, pdata.height, ((pdata.alpha || bm->bm_flags & BM_FLAG_TRANSPARENT) ? OGL_FLAG_ALPHA : 0)); - unsigned char *data = pdata.data; - if (pdata.palette) { - int size = pdata.width * pdata.height; - data = malloc(size * 3); - for (int i = 0; i < size; i++) - memcpy(&data[i * 3], &pdata.palette[pdata.data[i] * 3], 3); - free(pdata.data); - pdata.data = data; - } - ogl_loadtexture(pdata.data, 0, 0, bm->gltexture, bm->bm_flags, pdata.paletted ? 3 : pdata.channels, texfilt); + ogl_init_texture(bm->gltexture ? bm->gltexture : (bm->gltexture = ogl_get_free_texture()), pdata.width, pdata.height, OGL_FLAG_ALPHA); + unsigned char *data = ogl_fit_png(bm, &pdata); + free(pdata.data); + pdata.data = data; + pdata.channels = 4; + pdata.paletted = 0; + ogl_loadtexture(pdata.data, 0, 0, bm->gltexture, bm->bm_flags, 4, texfilt); #ifdef OGL_MERGE if (bm->bm_flags & BM_FLAG_SUPER_TRANSPARENT) ogl_loadpngmask(&pdata, bm, texfilt); @@ -1688,6 +1965,9 @@ void ogl_loadbmtexture_f(grs_bitmap *bm, int texfilt, const char *bitmapname) if (pdata.palette) free(pdata.palette); bm->gltexture->is_png = 1; +#ifdef __EMSCRIPTEN__ + load_material_maps(bm->gltexture, bitmapname); +#endif return; } else @@ -1842,6 +2122,12 @@ void ogl_loadbmtexture(grs_bitmap *bm) void ogl_freetexture(ogl_texture *gltexture) { + GLuint *maps[3] = { &gltexture->nmap, &gltexture->gmap, &gltexture->emap }; + for (int i = 0; i < 3; i++) + if (*maps[i]) { + glDeleteTextures(1, maps[i]); + *maps[i] = 0; + } if (gltexture->handle>0) { r_texcount--; glmprintf((0,"ogl_freetexture(%p):%i (%i left)\n",gltexture,gltexture->handle,r_texcount)); @@ -1959,7 +2245,12 @@ bool ogl_ubitmapm_cs(int x, int y,int dw, int dh, grs_bitmap *bm,int c, int scal glVertexPointer(2, GL_FLOAT, 0, vertex_array); glColorPointer(4, GL_FLOAT, 0, color_array); glTexCoordPointer(2, GL_FLOAT, 0, texcoord_array); + // HUD, menu and title art drawn larger than its pixels: a sharp upscale + float texels = (v2 - v1) * bm->gltexture->th; + int sharp = texels > 0 && ogl_upscale_begin(bm->gltexture, u1, v1, u2, v2, (yo - yf) * last_height * h / texels, 0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);//replaced GL_QUADS + if (sharp) + ogl_shader_end(); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); @@ -1976,8 +2267,10 @@ void ogl_update_window_clip() Window_clip_right == cw - 1 && Window_clip_bot == ch - 1) { glDisable(GL_SCISSOR_TEST); } else { - glScissor(Window_clip_left + grd_curcanv->cv_bitmap.bm_x, - grd_curscreen->sc_h - grd_curcanv->cv_bitmap.bm_y - Window_clip_bot - 1, + int ox, oy; + ogl_post_origin(&ox, &oy); + glScissor(Window_clip_left + grd_curcanv->cv_bitmap.bm_x - ox, + grd_curscreen->sc_h - grd_curcanv->cv_bitmap.bm_y - Window_clip_bot - 1 - oy, Window_clip_right - Window_clip_left + 1, Window_clip_bot - Window_clip_top + 1); glEnable(GL_SCISSOR_TEST); diff --git a/d2/arch/ogl/ogl_post.c b/d2/arch/ogl/ogl_post.c new file mode 100644 index 0000000..f493a72 --- /dev/null +++ b/d2/arch/ogl/ogl_post.c @@ -0,0 +1,736 @@ +/* + * Post-processing of the 3D view (browser edition, WebGL 2). The mine is drawn into an + * off-screen HDR image (multisampled when the page asks for antialiasing), then ambient + * occlusion darkens creases and contact points, light haze scatters the lights in the air + * (with the headlight's beam), glow (bloom) spreads from everything bright, and a filmic curve + * maps it to the screen, with FXAA when there is no multisampling. + */ + +#define GL_GLEXT_PROTOTYPES +#include +#include +#include +#include "ogl_init.h" +#include "internal.h" +#include "gr.h" +#include "config.h" +#include "console.h" +#include "../../3d/globvars.h" +#include "plight.h" +#ifdef __EMSCRIPTEN__ +#include "../web/web.h" +#endif + +#ifndef GL_READ_FRAMEBUFFER +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#endif +#ifndef GL_DEPTH_COMPONENT24 +#define GL_DEPTH_COMPONENT24 0x81A6 +#endif +#define GL_R11F_G11F_B10F_ 0x8C3A +#define GL_RGBA16F_ 0x881A +#define GL_HALF_FLOAT_ 0x140B +#define GL_MAX_SAMPLES_ 0x8D57 + +void glBlitFramebuffer(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); +void glRenderbufferStorageMultisample(GLenum, GLsizei, GLenum, GLsizei, GLsizei); + +#define BLOOM_LEVELS 6 +#define MAX_HAZE 16 +#define Z_NEAR 0.1f // ogl_start_frame's projection +#define Z_FAR 5000.0f + +#define LOOK_GLOW 1 +#define LOOK_AO 2 +#define LOOK_HAZE 4 + +typedef struct target { + GLuint fbo, tex; + int w, h; +} target; + +static struct { + int tried, ok; + GLenum color_format; // of the HDR images + int w, h, samples; // of the scene buffers now + GLuint ms_fbo, ms_color, ms_depth; // multisampled scene + target scene, ldr; // resolved scene (with depth), tone mapped before FXAA + GLuint depth; // resolved depth texture + target bloom[BLOOM_LEVELS]; + target ao[2]; // half size, before and after blurring one way + int levels; + int x, y; // the view's origin in window coordinates + int active, look; + GLuint down, prefilter, up, ssao, aoblur, fxaa; + GLuint final[8]; // by LOOK_* bits +} P; + +// last frame's view (color and depth) and where it was seen from, for reflections +static struct { + target t; + GLuint depth; + int valid; + vms_vector pos; + vms_matrix orient; + vms_vector scale; +} H; + +static const char *quad_vs = + "in vec4 a_position;\n" + "out vec2 v_uv;\n" + "void main() {\n" + " v_uv = a_position.xy * 0.5 + 0.5;\n" + " gl_Position = vec4(a_position.xy, 0.0, 1.0);\n" + "}\n"; + +// View-space positions from the depth buffer, with the view's zoom and aspect undone (scale) +// so lengths are in mine units, as plight.c gives its lights. +static const char *depth_glsl = + "uniform sampler2D depth;\n" + "uniform vec3 scale;\n" + "uniform vec2 nearfar;\n" + "float dist_at(vec2 uv) {\n" // along the view axis, in the view's scaled units + " float z = texture(depth, uv).r * 2.0 - 1.0;\n" + " return 2.0 * nearfar.x * nearfar.y / (nearfar.y + nearfar.x - z * (nearfar.y - nearfar.x));\n" + "}\n" + "vec3 view_at(vec2 uv) {\n" + " float d = dist_at(uv);\n" + " return vec3((uv * 2.0 - 1.0) * d, -d) / scale;\n" + "}\n" + "vec2 uv_of(vec3 p) {\n" + " vec3 e = p * scale;\n" + " return e.xy / max(-e.z, 1e-3) * 0.5 + 0.5;\n" + "}\n"; + +// 13-tap downsample (Jimenez 2014). The first one keeps only what is brighter than the +// threshold, with a soft knee, and weights its groups by 1/(1+luma) so single bright pixels +// (sparks, far lamps) don't flicker. +static const char *down_fs = + "uniform sampler2D src;\n" + "uniform vec2 texel;\n" + "uniform vec2 thresh;\n" + "in vec2 v_uv;\n" + "out vec4 o;\n" + "vec3 at(vec2 d) { return min(texture(src, v_uv + d * texel).rgb, vec3(64.0)); }\n" + "float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }\n" + "void main() {\n" + " vec3 a = at(vec2(-2.0, -2.0)), b = at(vec2(0.0, -2.0)), c = at(vec2(2.0, -2.0));\n" + " vec3 d = at(vec2(-1.0, -1.0)), e = at(vec2(1.0, -1.0));\n" + " vec3 f = at(vec2(-2.0, 0.0)), g = at(vec2(0.0)), h = at(vec2(2.0, 0.0));\n" + " vec3 i = at(vec2(-1.0, 1.0)), j = at(vec2(1.0, 1.0));\n" + " vec3 k = at(vec2(-2.0, 2.0)), l = at(vec2(0.0, 2.0)), m = at(vec2(2.0, 2.0));\n" + "#ifdef PREFILTER\n" + " vec3 g0 = (d + e + i + j) * 0.25, g1 = (a + b + f + g) * 0.25, g2 = (b + c + g + h) * 0.25;\n" + " vec3 g3 = (f + g + k + l) * 0.25, g4 = (g + h + l + m) * 0.25;\n" + " float w0 = 0.5 / (1.0 + luma(g0)), w1 = 0.125 / (1.0 + luma(g1)), w2 = 0.125 / (1.0 + luma(g2));\n" + " float w3 = 0.125 / (1.0 + luma(g3)), w4 = 0.125 / (1.0 + luma(g4));\n" + " vec3 s = (g0 * w0 + g1 * w1 + g2 * w2 + g3 * w3 + g4 * w4) / (w0 + w1 + w2 + w3 + w4);\n" + " float br = mix(luma(s), max(max(s.r, s.g), s.b), 0.5);\n" // saturated colors glow less + " float soft = clamp(br - thresh.x + thresh.y, 0.0, 2.0 * thresh.y);\n" + " soft = soft * soft / (4.0 * thresh.y + 1e-4);\n" + " o = vec4(s * max(soft, br - thresh.x) / max(br, 1e-4), 1.0);\n" + "#else\n" + " o = vec4((d + e + i + j) * 0.125 + (a + c + k + m) * 0.03125 + (b + f + h + l) * 0.0625 + g * 0.125, 1.0);\n" + "#endif\n" + "}\n"; + +// 3x3 tent upsample, added onto the next larger level +static const char *up_fs = + "uniform sampler2D src;\n" + "uniform vec2 texel;\n" + "uniform float scale;\n" + "in vec2 v_uv;\n" + "out vec4 o;\n" + "vec3 at(vec2 d) { return texture(src, v_uv + d * texel).rgb; }\n" + "void main() {\n" + " vec3 c = at(vec2(-1.0, -1.0)) + at(vec2(1.0, -1.0)) + at(vec2(-1.0, 1.0)) + at(vec2(1.0, 1.0))\n" + " + 2.0 * (at(vec2(0.0, -1.0)) + at(vec2(-1.0, 0.0)) + at(vec2(1.0, 0.0)) + at(vec2(0.0, 1.0)))\n" + " + 4.0 * at(vec2(0.0));\n" + " o = vec4(c * (scale / 16.0), 1.0);\n" + "}\n"; + +// Ambient occlusion at half size: how much of the half-space above each pixel nearby surfaces +// cover, from 12 depth samples on a spiral (turned per pixel; the blur evens that out). +static const char *ssao_fs = + "uniform vec2 texel;\n" // of the depth buffer + "uniform vec2 ao;\n" // radius in units, strength + "in vec2 v_uv;\n" + "out vec4 o;\n" + "void main() {\n" + " vec3 p = view_at(v_uv);\n" + " vec3 pr = view_at(v_uv + vec2(texel.x, 0.0)) - p, pl = p - view_at(v_uv - vec2(texel.x, 0.0));\n" + " vec3 pu = view_at(v_uv + vec2(0.0, texel.y)) - p, pd = p - view_at(v_uv - vec2(0.0, texel.y));\n" + " vec3 n = normalize(cross(abs(pr.z) < abs(pl.z) ? pr : pl, abs(pu.z) < abs(pd.z) ? pu : pd));\n" + " if (dot(n, p) > 0.0) n = -n;\n" + " float d = -p.z * scale.z;\n" + " if (d > 600.0) { o = vec4(1.0); return; }\n" + " vec2 r = min(ao.x * scale.xy / d * 0.5, vec2(0.12));\n" + " float a = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) * 6.2832;\n" + " float occ = 0.0;\n" + " for (int i = 0; i < 12; i++) {\n" + " float t = (float(i) + 0.5) / 12.0;\n" + " float ang = a + float(i) * 2.39996;\n" + " vec3 v = view_at(v_uv + vec2(cos(ang), sin(ang)) * r * sqrt(t)) - p;\n" + " float l = length(v);\n" + " occ += max(dot(v / max(l, 1e-4), n) - 0.15, 0.0) * (1.0 - smoothstep(ao.x * 0.6, ao.x * 1.6, l));\n" + " }\n" + " o = vec4(vec3(clamp(1.0 - ao.y * occ / 12.0 * 1.6, 0.0, 1.0)), 1.0);\n" + "}\n"; + +// separable blur that keeps edges: neighbors at another depth count less +static const char *aoblur_fs = + "uniform sampler2D src;\n" + "uniform vec2 stepv;\n" + "in vec2 v_uv;\n" + "out vec4 o;\n" + "void main() {\n" + " float d0 = dist_at(v_uv), sum = 0.0, wsum = 0.0;\n" + " for (int i = -4; i <= 4; i++) {\n" + " vec2 uv = v_uv + stepv * float(i);\n" + " float w = exp(-float(i * i) / 10.0) * exp(-abs(dist_at(uv) - d0) / (0.04 * d0 + 0.2));\n" + " sum += texture(src, uv).r * w;\n" + " wsum += w;\n" + " }\n" + " o = vec4(vec3(sum / wsum), 1.0);\n" + "}\n"; + +// Occlusion and haze, glow, then the filmic curve: colors up to the knee stay as the game drew +// them, brighter ones roll off smoothly toward white instead of clipping; a little contrast and +// vignette. Haze: light scattered toward the eye along each view ray up to the wall it hits, from +// each light (an inverse-square integral that has a closed form) and the headlight's cone. +static const char *final_fs = + "uniform sampler2D scene;\n" + "uniform sampler2D bloom;\n" + "uniform sampler2D aotex;\n" + "uniform sampler2D fogtex;\n" + "uniform vec4 look;\n" // bloom strength, knee, contrast, vignette + "uniform vec4 hazep;\n" // light haze, beam, fog, - + "uniform int nhaze;\n" + "uniform vec4 hpos[16];\n" + "uniform vec3 hcol[16];\n" + "uniform vec4 headpos;\n" + "uniform vec3 headdir;\n" + "in vec2 v_uv;\n" + "out vec4 o;\n" + "float hash(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\n" + "float lum(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }\n" + "void main() {\n" + " vec3 c = min(texture(scene, v_uv).rgb, vec3(64.0));\n" // no infinite light + "#ifdef AO\n" + " float a = texture(aotex, v_uv).r;\n" + " c *= mix(a, 1.0, smoothstep(0.7, 1.5, lum(c)));\n" // lights themselves stay bright + "#endif\n" + "#ifdef HAZE\n" + " vec3 pe = view_at(v_uv);\n" + " float T = length(pe);\n" + " vec3 D = pe / T;\n" + " vec3 hz = vec3(0.0);\n" + " for (int i = 0; i < 16; i++) {\n" + " if (i >= nhaze) break;\n" + " vec3 L = hpos[i].xyz;\n" + " float t0 = dot(L, D);\n" + " float h = max(length(L - D * t0), 0.4);\n" + " float s = (atan((T - t0) / h) - atan(-t0 / h)) / h;\n" + " vec2 lu = uv_of(L);\n" // is the light itself behind a wall? + " float vis = 0.5;\n" + " if (L.z < 0.0 && all(greaterThan(lu, vec2(0.0))) && all(lessThan(lu, vec2(1.0))))\n" + " vis = smoothstep(-2.0, 2.0, length(view_at(lu)) - length(L));\n" + " hz += hcol[i] * s * vis;\n" + " }\n" + " hz *= hazep.x;\n" + " if (headpos.w > 0.0) {\n" + " float te = min(T, 160.0), beam = 0.0, dt = te / 12.0;\n" + " float j = hash(gl_FragCoord.xy + 0.5);\n" + " for (int i = 0; i < 12; i++) {\n" + " vec3 x = D * ((float(i) + j) * dt) - headpos.xyz;\n" + " float d = length(x);\n" + " float cd = dot(x / max(d, 1e-3), headdir);\n" + " beam += smoothstep(0.62, 0.92, cd) / (1.0 + d * d / 6000.0);\n" + " }\n" + " hz += vec3(1.0, 0.97, 0.9) * beam * dt * hazep.y;\n" + " }\n" + " hz += texture(fogtex, v_uv).rgb * (1.0 - exp(-T * hazep.z));\n" // the room's own glow, far away + " c += hz;\n" + "#endif\n" + "#ifdef GLOW\n" + " c += texture(bloom, v_uv).rgb * look.x;\n" + " float m = max(max(c.r, c.g), c.b);\n" + " float k = look.y;\n" + " float t = m <= k ? m : k + (1.0 - k) * (1.0 - exp((k - m) / (1.0 - k)));\n" + " c *= t / max(m, 1e-4);\n" + " c = mix(c, vec3(t), smoothstep(1.5, 8.0, m) * 0.35);\n" // very bright light burns white + " c = clamp(c, 0.0, 1.0);\n" + " c = mix(c, c * c * (3.0 - 2.0 * c), look.z);\n" + " vec2 q = v_uv - 0.5;\n" + " c *= 1.0 - look.w * dot(q, q) * 2.0;\n" + "#endif\n" + " c += (hash(gl_FragCoord.xy) - 0.5) / 255.0;\n" + " o = vec4(c, 1.0);\n" + "}\n"; + +// FXAA (after Timothy Lottes' console version) when the view isn't multisampled +static const char *fxaa_fs = + "uniform sampler2D src;\n" + "uniform vec2 texel;\n" + "in vec2 v_uv;\n" + "out vec4 o;\n" + "float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }\n" + "void main() {\n" + " vec3 nw = texture(src, v_uv + vec2(-1.0, -1.0) * texel).rgb;\n" + " vec3 ne = texture(src, v_uv + vec2(1.0, -1.0) * texel).rgb;\n" + " vec3 sw = texture(src, v_uv + vec2(-1.0, 1.0) * texel).rgb;\n" + " vec3 se = texture(src, v_uv + vec2(1.0, 1.0) * texel).rgb;\n" + " vec3 mc = texture(src, v_uv).rgb;\n" + " float lnw = luma(nw), lne = luma(ne), lsw = luma(sw), lse = luma(se), lm = luma(mc);\n" + " float lmin = min(lm, min(min(lnw, lne), min(lsw, lse)));\n" + " float lmax = max(lm, max(max(lnw, lne), max(lsw, lse)));\n" + " vec2 dir = vec2(-((lnw + lne) - (lsw + lse)), (lnw + lsw) - (lne + lse));\n" + " float red = max((lnw + lne + lsw + lse) * 0.03125, 1.0 / 128.0);\n" + " float rcp = 1.0 / (min(abs(dir.x), abs(dir.y)) + red);\n" + " dir = clamp(dir * rcp, -8.0, 8.0) * texel;\n" + " vec3 a = 0.5 * (texture(src, v_uv - dir / 6.0).rgb + texture(src, v_uv + dir / 6.0).rgb);\n" + " vec3 b = a * 0.5 + 0.25 * (texture(src, v_uv - dir * 0.5).rgb + texture(src, v_uv + dir * 0.5).rgb);\n" + " float lb = luma(b);\n" + " o = vec4(lb < lmin || lb > lmax ? a : b, 1.0);\n" + "}\n"; + +static GLuint program(const char *defines, const char *fs, int with_depth) +{ + static const char *samplers[] = { "src", "scene", "bloom", "aotex", "fogtex", "depth" }; + static const int units[] = { 0, 0, 1, 2, 3, 4 }; + char body[16384]; + GLuint p; + int i; + snprintf(body, sizeof(body), "%s%s", with_depth ? depth_glsl : "", fs); + if (!(p = ogl_program3(quad_vs, defines, body))) + return 0; + glUseProgram(p); + for (i = 0; i < 6; i++) { + GLint loc = glGetUniformLocation(p, samplers[i]); + if (loc >= 0) + glUniform1i(loc, units[i]); + } + return p; +} + +static int format_renders(GLenum ifmt) +{ + GLuint t, f; + int ok; + glGenTextures(1, &t); + glBindTexture(GL_TEXTURE_2D, t); + glTexImage2D(GL_TEXTURE_2D, 0, ifmt, 4, 4, 0, ifmt == GL_RGBA16F_ ? GL_RGBA : GL_RGB, GL_HALF_FLOAT_, NULL); + glGenFramebuffers(1, &f); + glBindFramebuffer(GL_FRAMEBUFFER, f); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t, 0); + ok = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteFramebuffers(1, &f); + glDeleteTextures(1, &t); + return ok; +} + +static int ready(void) +{ + if (P.tried) + return P.ok; + P.tried = 1; +#ifdef __EMSCRIPTEN__ + if (d2web_gl_version() < 2) + return 0; +#endif + P.down = program("", down_fs, 0); + P.prefilter = program("#define PREFILTER 1\n", down_fs, 0); + P.up = program("", up_fs, 0); + P.ssao = program("", ssao_fs, 1); + P.aoblur = program("", aoblur_fs, 1); + P.fxaa = program("", fxaa_fs, 0); + glUseProgram(0); + P.ok = P.down && P.prefilter && P.up && P.ssao && P.aoblur && P.fxaa; + if (!P.ok) + return 0; + P.color_format = format_renders(GL_R11F_G11F_B10F_) ? GL_R11F_G11F_B10F_ : format_renders(GL_RGBA16F_) ? GL_RGBA16F_ : GL_RGBA; + con_printf(CON_NORMAL, "post: HDR format %#x\n", P.color_format); + return 1; +} + +static GLuint final_program(int look) +{ + if (!P.final[look]) { + char defines[96]; + snprintf(defines, sizeof(defines), "%s%s%s", look & LOOK_GLOW ? "#define GLOW 1\n" : "", + look & LOOK_AO ? "#define AO 1\n" : "", look & LOOK_HAZE ? "#define HAZE 1\n" : ""); + P.final[look] = program(defines, final_fs, 1); + } + return P.final[look]; +} + +static GLuint texture_make(int w, int h, GLenum ifmt) +{ + GLuint t; + GLenum fmt = ifmt == GL_R11F_G11F_B10F_ ? GL_RGB : ifmt == GL_DEPTH_COMPONENT24 ? GL_DEPTH_COMPONENT : GL_RGBA; + GLenum type = ifmt == GL_DEPTH_COMPONENT24 ? GL_UNSIGNED_INT : ifmt == GL_RGBA ? GL_UNSIGNED_BYTE : GL_HALF_FLOAT_; + GLenum filter = ifmt == GL_DEPTH_COMPONENT24 ? GL_NEAREST : GL_LINEAR; + glGenTextures(1, &t); + glBindTexture(GL_TEXTURE_2D, t); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, ifmt, w, h, 0, fmt, type, NULL); + return t; +} + +static void target_make(target *t, int w, int h, GLenum ifmt, GLuint depth) +{ + t->w = w; + t->h = h; + t->tex = texture_make(w, h, ifmt); + glGenFramebuffers(1, &t->fbo); + glBindFramebuffer(GL_FRAMEBUFFER, t->fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t->tex, 0); + if (depth) + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0); +} + +static void target_free(target *t) +{ + if (t->fbo) + glDeleteFramebuffers(1, &t->fbo); + if (t->tex) + glDeleteTextures(1, &t->tex); + t->fbo = t->tex = 0; +} + +static void buffers_free(void) +{ + int i; + target_free(&P.scene); + target_free(&P.ldr); + target_free(&P.ao[0]); + target_free(&P.ao[1]); + for (i = 0; i < BLOOM_LEVELS; i++) + target_free(&P.bloom[i]); + if (P.depth) + glDeleteTextures(1, &P.depth); + if (P.ms_fbo) { + glDeleteFramebuffers(1, &P.ms_fbo); + glDeleteRenderbuffers(1, &P.ms_color); + glDeleteRenderbuffers(1, &P.ms_depth); + } + P.depth = P.ms_fbo = P.ms_color = P.ms_depth = 0; + P.w = P.h = 0; +} + +static void buffers_make(int w, int h, int samples) +{ + int i, bw = w, bh = h; + buffers_free(); + P.w = w; + P.h = h; + P.samples = samples; + P.depth = texture_make(w, h, GL_DEPTH_COMPONENT24); + target_make(&P.scene, w, h, P.color_format, P.depth); + if (samples) { + glGenRenderbuffers(1, &P.ms_color); + glBindRenderbuffer(GL_RENDERBUFFER, P.ms_color); + glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, P.color_format == GL_RGBA ? GL_RGBA8 : P.color_format, w, h); + glGenRenderbuffers(1, &P.ms_depth); + glBindRenderbuffer(GL_RENDERBUFFER, P.ms_depth); + glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT24, w, h); + glGenFramebuffers(1, &P.ms_fbo); + glBindFramebuffer(GL_FRAMEBUFFER, P.ms_fbo); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, P.ms_color); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, P.ms_depth); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + con_printf(CON_URGENT, "post: no multisampling\n"); + glDeleteFramebuffers(1, &P.ms_fbo); + glDeleteRenderbuffers(1, &P.ms_color); + glDeleteRenderbuffers(1, &P.ms_depth); + P.ms_fbo = P.ms_color = P.ms_depth = 0; + P.samples = 0; + } + } + target_make(&P.ldr, w, h, GL_RGBA, 0); + target_make(&P.ao[0], (w + 1) / 2, (h + 1) / 2, GL_RGBA, 0); + target_make(&P.ao[1], (w + 1) / 2, (h + 1) / 2, GL_RGBA, 0); + for (P.levels = 0; P.levels < BLOOM_LEVELS && bw > 16 && bh > 16; P.levels++) { + bw = (bw + 1) / 2; + bh = (bh + 1) / 2; + target_make(&P.bloom[P.levels], bw, bh, P.color_format, 0); + } + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindRenderbuffer(GL_RENDERBUFFER, 0); +} + +int ogl_post_active(void) +{ + return P.active; +} + +// Last frame's view for reflections, and the matrix from this view's space (unscaled, GL axes) +// to that one's. 0 when there is none to use. +int ogl_post_history(unsigned *color, unsigned *depth, float *reproj, float *scale) +{ + float rc[3][3], rp[3][3], dp[3], m[3][3]; + const float s[3] = { 1, 1, -1 }; + const vms_vector *rows_c[3] = { &Unscaled_matrix.rvec, &Unscaled_matrix.uvec, &Unscaled_matrix.fvec }; + const vms_vector *rows_p[3] = { &H.orient.rvec, &H.orient.uvec, &H.orient.fvec }; + int i, j, k; + if (!P.active || !H.valid || H.t.w != P.w || H.t.h != P.h) + return 0; + for (i = 0; i < 3; i++) { + rc[i][0] = f2fl(rows_c[i]->x); rc[i][1] = f2fl(rows_c[i]->y); rc[i][2] = f2fl(rows_c[i]->z); + rp[i][0] = f2fl(rows_p[i]->x); rp[i][1] = f2fl(rows_p[i]->y); rp[i][2] = f2fl(rows_p[i]->z); + } + dp[0] = f2fl(View_position.x - H.pos.x); + dp[1] = f2fl(View_position.y - H.pos.y); + dp[2] = f2fl(View_position.z - H.pos.z); + for (i = 0; i < 3; i++) + for (j = 0; j < 3; j++) { + m[i][j] = 0; + for (k = 0; k < 3; k++) + m[i][j] += rp[i][k] * rc[j][k]; + reproj[j * 4 + i] = s[i] * s[j] * m[i][j]; + } + for (i = 0; i < 3; i++) { + float t = 0; + for (k = 0; k < 3; k++) + t += rp[i][k] * dp[k]; + reproj[12 + i] = s[i] * t; + reproj[i * 4 + 3] = 0; + } + reproj[15] = 1; + scale[0] = f2fl(H.scale.x); + scale[1] = f2fl(H.scale.y); + scale[2] = f2fl(H.scale.z); + *color = H.t.tex; + *depth = H.depth; + return 1; +} + +static void history_keep(void) +{ + int want = 0; +#ifdef __EMSCRIPTEN__ + want = d2web_option(D2WEB_OPTION_REFLECTIONS) && d2web_option(D2WEB_OPTION_LIGHTING); +#endif + H.valid = 0; + if (!want) + return; + if (H.t.w != P.w || H.t.h != P.h) { + target_free(&H.t); + if (H.depth) + glDeleteTextures(1, &H.depth); + H.depth = texture_make(P.w, P.h, GL_DEPTH_COMPONENT24); + target_make(&H.t, P.w, P.h, P.color_format, H.depth); + } + glBindFramebuffer(GL_READ_FRAMEBUFFER, P.scene.fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, H.t.fbo); + glBlitFramebuffer(0, 0, P.w, P.h, 0, 0, P.w, P.h, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + H.pos = View_position; + H.orient = Unscaled_matrix; + H.scale = Matrix_scale; + H.valid = 1; +} + +void ogl_post_origin(int *x, int *y) +{ + *x = P.active ? P.x : 0; + *y = P.active ? P.y : 0; +} + +// Before the 3D view of the main window is drawn into the current canvas. +int ogl_post_begin(void) +{ + grs_bitmap *bm = &grd_curcanv->cv_bitmap; + int samples = 0; + + P.active = 0; + P.look = 0; +#ifdef __EMSCRIPTEN__ + P.look = (d2web_option(D2WEB_OPTION_GLOW) ? LOOK_GLOW : 0) | (d2web_option(D2WEB_OPTION_AO) ? LOOK_AO : 0) | + (d2web_option(D2WEB_OPTION_HAZE) ? LOOK_HAZE : 0); +#endif + if (!P.look || !ready() || bm->bm_w < 64 || bm->bm_h < 64) + return 0; + if (GameCfg.Multisample) { + GLint max = 0; + glGetIntegerv(GL_MAX_SAMPLES_, &max); + samples = max < 4 ? max : 4; + } + if (P.w != bm->bm_w || P.h != bm->bm_h || (P.samples != samples && samples)) + buffers_make(bm->bm_w, bm->bm_h, samples); + P.x = bm->bm_x; + P.y = grd_curscreen->sc_h - bm->bm_y - bm->bm_h; + glBindFramebuffer(GL_FRAMEBUFFER, P.samples ? P.ms_fbo : P.scene.fbo); + glDisable(GL_SCISSOR_TEST); + glViewport(0, 0, P.w, P.h); + last_width = P.w; + last_height = P.h; + glClearColor(0, 0, 0, 1); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + P.active = 1; + return 1; +} + +static void draw_quad(void) +{ + static const GLfloat quad[8] = { -1, -1, 1, -1, 1, 1, -1, 1 }; + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_FLOAT, 0, quad); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + glDisableClientState(GL_VERTEX_ARRAY); +} + +static void bind_target(target *t) +{ + glBindFramebuffer(GL_FRAMEBUFFER, t->fbo); + glViewport(0, 0, t->w, t->h); +} + +static void bind_texture(int unit, GLuint tex) +{ + glActiveTexture(GL_TEXTURE0 + unit); + glBindTexture(GL_TEXTURE_2D, tex); +} + +// the depth-reading programs' view uniforms +static void set_view(GLuint p) +{ + glUniform3f(glGetUniformLocation(p, "scale"), f2fl(Matrix_scale.x), f2fl(Matrix_scale.y), f2fl(Matrix_scale.z)); + glUniform2f(glGetUniformLocation(p, "nearfar"), Z_NEAR, Z_FAR); +} + +static void bloom(void) +{ + int i; + target *src = &P.scene; + for (i = 0; i < P.levels; i++) { + GLuint p = i ? P.down : P.prefilter; + glUseProgram(p); + glUniform2f(glGetUniformLocation(p, "texel"), 1.0f / src->w, 1.0f / src->h); + if (!i) + glUniform2f(glGetUniformLocation(p, "thresh"), d2web_tune(7, 0.6f), d2web_tune(8, 0.36f)); + bind_target(&P.bloom[i]); + bind_texture(0, src->tex); + draw_quad(); + src = &P.bloom[i]; + } + glUseProgram(P.up); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); + for (i = P.levels - 1; i > 0; i--) { + glUniform2f(glGetUniformLocation(P.up, "texel"), 1.0f / P.bloom[i].w, 1.0f / P.bloom[i].h); + glUniform1f(glGetUniformLocation(P.up, "scale"), 1.0f); + bind_target(&P.bloom[i - 1]); + bind_texture(0, P.bloom[i].tex); + draw_quad(); + } + glDisable(GL_BLEND); +} + +static void occlusion(void) +{ + glUseProgram(P.ssao); + set_view(P.ssao); + glUniform2f(glGetUniformLocation(P.ssao, "texel"), 1.0f / P.w, 1.0f / P.h); + glUniform2f(glGetUniformLocation(P.ssao, "ao"), d2web_tune(16, 6.0f), d2web_tune(17, 2.0f)); + bind_target(&P.ao[0]); + bind_texture(4, P.depth); + draw_quad(); + glUseProgram(P.aoblur); + set_view(P.aoblur); + glUniform2f(glGetUniformLocation(P.aoblur, "stepv"), 1.0f / P.ao[0].w, 0); + bind_target(&P.ao[1]); + bind_texture(0, P.ao[0].tex); + draw_quad(); + glUniform2f(glGetUniformLocation(P.aoblur, "stepv"), 0, 1.0f / P.ao[0].h); + bind_target(&P.ao[0]); + bind_texture(0, P.ao[1].tex); + draw_quad(); +} + +static void haze_uniforms(GLuint p) +{ + float pos[MAX_HAZE][4], col[MAX_HAZE][3], hp[3], hd[3]; + int n = plight_haze_lights(pos, col, MAX_HAZE); + glUniform4f(glGetUniformLocation(p, "hazep"), d2web_tune(13, 0.06f), d2web_tune(14, 0.0025f), d2web_tune(15, 0.0015f), 0); + glUniform1i(glGetUniformLocation(p, "nhaze"), n); + if (n) { + glUniform4fv(glGetUniformLocation(p, "hpos"), n, pos[0]); + glUniform3fv(glGetUniformLocation(p, "hcol"), n, col[0]); + } + if (plight_headlight(hp, hd)) { + glUniform4f(glGetUniformLocation(p, "headpos"), hp[0], hp[1], hp[2], 1); + glUniform3f(glGetUniformLocation(p, "headdir"), hd[0], hd[1], hd[2]); + } else + glUniform4f(glGetUniformLocation(p, "headpos"), 0, 0, 0, 0); +} + +// After the 3D view is drawn: process it and show it in its place on the screen. +void ogl_post_end(void) +{ + int fxaa; + GLuint fin; + + if (!P.active) + return; + P.active = 0; + if (P.samples) { + glBindFramebuffer(GL_READ_FRAMEBUFFER, P.ms_fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, P.scene.fbo); + glBlitFramebuffer(0, 0, P.w, P.h, 0, 0, P.w, P.h, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + glDisable(GL_BLEND); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_SCISSOR_TEST); + + history_keep(); + if (P.look & (LOOK_GLOW | LOOK_HAZE)) // haze takes its far glow from the bloom images + bloom(); + if (P.look & LOOK_AO) + occlusion(); + + fxaa = !P.samples; + fin = final_program(P.look); + glUseProgram(fin); + glUniform4f(glGetUniformLocation(fin, "look"), d2web_tune(9, 0.6f), d2web_tune(10, 0.8f), d2web_tune(11, 0.2f), d2web_tune(12, 0.32f)); + set_view(fin); + if (P.look & LOOK_HAZE) + haze_uniforms(fin); + if (fxaa) + bind_target(&P.ldr); + else { + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(P.x, P.y, P.w, P.h); + } + bind_texture(4, P.depth); + bind_texture(3, P.levels ? P.bloom[P.levels - 1].tex : 0); + bind_texture(2, P.ao[0].tex); + bind_texture(1, P.levels ? P.bloom[0].tex : 0); + bind_texture(0, P.scene.tex); + draw_quad(); + if (fxaa) { + glUseProgram(P.fxaa); + glUniform2f(glGetUniformLocation(P.fxaa, "texel"), 1.0f / P.w, 1.0f / P.h); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(P.x, P.y, P.w, P.h); + bind_texture(0, P.ldr.tex); + draw_quad(); + } + + glUseProgram(0); + bind_texture(4, 0); + bind_texture(3, 0); + bind_texture(2, 0); + bind_texture(1, 0); + glActiveTexture(GL_TEXTURE0); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glViewport(0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h); + last_width = grd_curscreen->sc_w; + last_height = grd_curscreen->sc_h; +} diff --git a/d2/arch/ogl/ogl_shader.c b/d2/arch/ogl/ogl_shader.c new file mode 100644 index 0000000..f8df115 --- /dev/null +++ b/d2/arch/ogl/ogl_shader.c @@ -0,0 +1,304 @@ +/* + * Shaders for 2D art drawn much larger than its pixels (browser edition). Movies get an + * edge-aware sharp upscale and HUD, menu and title art a sharp Catmull-Rom one, instead of a + * bilinear stretch; font glyphs keep their shapes with smooth edges at screen resolution + * instead of blurred or blocky pixels. + * + * The GL emulation runs these as user programs: it rewrites the legacy built-ins (gl_Vertex, + * gl_MultiTexCoord0, gl_Color, ftransform()) and keeps feeding the client arrays as usual. + */ + +#define GL_GLEXT_PROTOTYPES +#include +#include +#include +#include +#include +#include "ogl_init.h" +#include "console.h" +#ifdef __EMSCRIPTEN__ +#include "../web/web.h" +#endif + +static const char *vs_src = + "void main() {\n" + " gl_TexCoord[0] = gl_MultiTexCoord0;\n" + " gl_FrontColor = gl_Color;\n" + " gl_Position = ftransform();\n" + "}\n"; + +// Catmull-Rom in nine bilinear taps (positions in texels), the result clamped to the four +// nearest texels so edges stay sharp without halos. lim keeps taps inside the image (textures +// are padded to a power of two, and HUD pieces can share one). Movies (MOVIE defined) also +// blend Catmull-Rom samples along each edge, which smooths the staircase of their low-res +// pixels, then sharpen. Transparent texels are black with alpha 0, so dividing by alpha keeps +// dark fringes off the edges of cut-out art. +static const char *upscale_fs_src = + "uniform sampler2D tex;\n" + "uniform vec2 size;\n" + "uniform vec4 lim;\n" + "vec4 at(vec2 t) { return texture2D(tex, clamp(t / size, lim.xy, lim.zw)); }\n" + "vec4 cr(vec2 p) {\n" + " vec2 t1 = floor(p - 0.5) + 0.5;\n" + " vec2 f = p - t1;\n" + " vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f));\n" + " vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f);\n" + " vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f));\n" + " vec2 w3 = f * f * (-0.5 + 0.5 * f);\n" + " vec2 w12 = w1 + w2;\n" + " vec2 u0 = t1 - 1.0, u3 = t1 + 2.0, u12 = t1 + w2 / w12;\n" + " return (at(vec2(u0.x, u0.y)) * w0.x + at(vec2(u12.x, u0.y)) * w12.x + at(vec2(u3.x, u0.y)) * w3.x) * w0.y\n" + " + (at(vec2(u0.x, u12.y)) * w0.x + at(vec2(u12.x, u12.y)) * w12.x + at(vec2(u3.x, u12.y)) * w3.x) * w12.y\n" + " + (at(vec2(u0.x, u3.y)) * w0.x + at(vec2(u12.x, u3.y)) * w12.x + at(vec2(u3.x, u3.y)) * w3.x) * w3.y;\n" + "}\n" + "float lum(vec4 c) { return dot(c.rgb, vec3(0.3, 0.59, 0.11)); }\n" + "void main() {\n" + " vec2 p = gl_TexCoord[0].xy * size;\n" + " vec4 c = cr(p);\n" + "#ifdef MOVIE\n" + " vec2 g = vec2(lum(at(p + vec2(1.0, 0.0))) - lum(at(p - vec2(1.0, 0.0))),\n" + " lum(at(p + vec2(0.0, 1.0))) - lum(at(p - vec2(0.0, 1.0))));\n" + " float gm = length(g) + 1e-6;\n" + " vec2 t = vec2(-g.y, g.x) / gm;\n" + " vec4 along = (c * 0.4 + (cr(p - t * 0.75) + cr(p + t * 0.75)) * 0.3 + (cr(p - t * 1.5) + cr(p + t * 1.5)) * 0.15) / 1.3;\n" + " c = mix(c, along, clamp(gm * 6.0, 0.0, 1.0));\n" + " vec4 blur = (at(p + vec2(0.7, 0.7)) + at(p + vec2(-0.7, 0.7)) + at(p + vec2(0.7, -0.7)) + at(p + vec2(-0.7, -0.7))) * 0.25;\n" + " c += (c - blur) * 0.6;\n" + "#endif\n" + " vec2 n = floor(p - 0.5) + 0.5;\n" + " vec4 a = at(n), b = at(n + vec2(1.0, 0.0)), d = at(n + vec2(0.0, 1.0)), e = at(n + 1.0);\n" + " c = clamp(c, min(min(a, b), min(d, e)), max(max(a, b), max(d, e)));\n" + " gl_FragColor = vec4(c.rgb / max(c.a, 0.004), c.a) * gl_Color;\n" + "}\n"; + +// The 0.5 coverage edge of the bilinear-filtered glyph, antialiased over one screen pixel. +// Transparent texels are black with alpha 0, so rgb / alpha is the glyph's own color. +static const char *glyph_fs_src = + "uniform sampler2D tex;\n" + "uniform float soft;\n" + "void main() {\n" + " vec4 c = texture2D(tex, gl_TexCoord[0].xy);\n" + " float a = smoothstep(0.5 - soft, 0.5 + soft, c.a);\n" + " gl_FragColor = vec4(c.rgb / max(c.a, 0.004), a) * gl_Color;\n" + "}\n"; + +static GLuint compile(GLenum type, const char *defines, const char *src) +{ + GLint ok = 0; + GLuint s = glCreateShader(type); + const char *parts[2] = { defines, src }; + glShaderSource(s, 2, parts, NULL); + glCompileShader(s); + glGetShaderiv(s, GL_COMPILE_STATUS, &ok); + if (!ok) { + char log[512]; + glGetShaderInfoLog(s, sizeof(log), NULL, log); + con_printf(CON_URGENT, "shader: %s\n", log); + glDeleteShader(s); + return 0; + } + return s; +} + +static GLuint link(const char *defines, const char *fs_src) +{ + GLint ok = 0; + GLuint vs = compile(GL_VERTEX_SHADER, "", vs_src), fs = compile(GL_FRAGMENT_SHADER, defines, fs_src), p; + if (!vs || !fs) + return 0; + p = glCreateProgram(); + glAttachShader(p, vs); + glAttachShader(p, fs); + glLinkProgram(p); + glGetProgramiv(p, GL_LINK_STATUS, &ok); + if (!ok) { + char log[512]; + glGetProgramInfoLog(p, sizeof(log), NULL, log); + con_printf(CON_URGENT, "shader link: %s\n", log); + glDeleteProgram(p); + return 0; + } + return p; +} + +typedef struct upscale_shader { + GLuint prog; + GLint size, lim; +} upscale_shader; +static upscale_shader upscale[2]; // art, movies +static GLuint glyph_prog, active; +static GLint glyph_soft; +static int tried; + +static void upscale_init(upscale_shader *u, const char *defines) +{ + if (!(u->prog = link(defines, upscale_fs_src))) + return; + glUseProgram(u->prog); + glUniform1i(glGetUniformLocation(u->prog, "tex"), 0); + u->size = glGetUniformLocation(u->prog, "size"); + u->lim = glGetUniformLocation(u->prog, "lim"); +} + +static int ogl_shaders_ready(void) +{ + if (!tried) { + tried = 1; + upscale_init(&upscale[0], ""); + upscale_init(&upscale[1], "#define MOVIE 1\n"); + if ((glyph_prog = link("", glyph_fs_src))) { + glUseProgram(glyph_prog); + glUniform1i(glGetUniformLocation(glyph_prog, "tex"), 0); + glyph_soft = glGetUniformLocation(glyph_prog, "soft"); + } + glUseProgram(0); + } + return upscale[0].prog && upscale[1].prog && glyph_prog; +} + +// A WebGL 2 program from GLSL ES 3.00 sources (without #version, which is added), handed to +// WebGL unchanged. Inputs and matrices use the GL emulation's names (a_position, a_texCoord0, +// a_color, a_normal, u_modelView, u_projection), so it feeds them from the usual client arrays. +GLuint ogl_program3(const char *vs_body, const char *defines, const char *fs_body) +{ +#ifdef __EMSCRIPTEN__ + const char *bodies[2] = { vs_body, fs_body }; + GLuint s[2], p; + GLint ok = 0; + int i; + for (i = 0; i < 2; i++) { + const char *head = i ? "#version 300 es\nprecision highp float;\nprecision highp int;\n" : "#version 300 es\nprecision highp float;\n"; + size_t n = strlen(head) + strlen(defines) + strlen(bodies[i]) + 1; + char *src = malloc(n); + snprintf(src, n, "%s%s%s", head, defines, bodies[i]); + s[i] = glCreateShader(i ? GL_FRAGMENT_SHADER : GL_VERTEX_SHADER); + d2web_shader_source(s[i], src); + free(src); + glCompileShader(s[i]); + glGetShaderiv(s[i], GL_COMPILE_STATUS, &ok); + if (!ok) { + char log[1024]; + glGetShaderInfoLog(s[i], sizeof(log), NULL, log); + con_printf(CON_URGENT, "shader: %s\n", log); + return 0; + } + } + p = glCreateProgram(); + glAttachShader(p, s[0]); + glAttachShader(p, s[1]); + glLinkProgram(p); + glGetProgramiv(p, GL_LINK_STATUS, &ok); + if (!ok) { + char log[1024]; + glGetProgramInfoLog(p, sizeof(log), NULL, log); + con_printf(CON_URGENT, "shader link: %s\n", log); + return 0; + } + return p; +#else + return 0; +#endif +} + +// Sprites that give light (explosions, glowing shots): their cut-out edges and the sprite's +// square border fade softly instead of ending in blocky pixels, and with the HDR view they are +// brighter than white so they glow. Additive sprites keep their colors premultiplied. +static const char *sprite_vs = + "in vec4 a_position;\n" + "in vec4 a_texCoord0;\n" + "in vec4 a_color;\n" + "uniform mat4 u_modelView;\n" + "uniform mat4 u_projection;\n" + "out vec2 v_uv;\n" + "out vec4 v_color;\n" + "void main() {\n" + " v_uv = a_texCoord0.xy;\n" + " v_color = a_color;\n" + " gl_Position = u_projection * u_modelView * a_position;\n" + "}\n"; + +static const char *sprite_fs = + "uniform sampler2D tex;\n" + "uniform vec4 sp;\n" // brightness, texture u and v extent, additive + "uniform vec2 texel;\n" + "in vec2 v_uv;\n" + "in vec4 v_color;\n" + "out vec4 o;\n" + "void main() {\n" + // the cut-out mask blurred over a texel and cut again: round outlines, not the + // staircase of the magnified pixels (transparent texels are black, so colors stay true) + " vec2 t = texel * 0.8;\n" + " vec4 c = (texture(tex, v_uv) * 2.0 + texture(tex, v_uv + t) + texture(tex, v_uv - t)\n" + " + texture(tex, v_uv + vec2(t.x, -t.y)) + texture(tex, v_uv + vec2(-t.x, t.y))) / 6.0;\n" + " vec2 q = v_uv / sp.yz;\n" + " float edge = smoothstep(0.0, 0.14, min(min(q.x, 1.0 - q.x), min(q.y, 1.0 - q.y)));\n" + " float a = smoothstep(0.18, 0.62, c.a) * edge * v_color.a;\n" + " if (a < 0.004) discard;\n" + " vec3 rgb = c.rgb / max(c.a, 0.004) * v_color.rgb * sp.x;\n" + " o = sp.w > 0.5 ? vec4(rgb * a, a) : vec4(rgb, a);\n" + "}\n"; + +static GLuint sprite_prog; +static GLint sprite_sp, sprite_texel; + +int ogl_sprite_begin(ogl_texture *tex, float brightness, int additive) +{ + static int tried; + if (!tried) { + tried = 1; +#ifdef __EMSCRIPTEN__ + if (d2web_gl_version() >= 2 && (sprite_prog = ogl_program3(sprite_vs, "", sprite_fs))) { + glUseProgram(sprite_prog); + glUniform1i(glGetUniformLocation(sprite_prog, "tex"), 0); + sprite_sp = glGetUniformLocation(sprite_prog, "sp"); + sprite_texel = glGetUniformLocation(sprite_prog, "texel"); + glUseProgram(0); + } +#endif + } + if (!sprite_prog || active || !tex->u || !tex->v) + return 0; + glUseProgram(active = sprite_prog); + glUniform4f(sprite_sp, brightness, tex->u, tex->v, additive ? 1 : 0); + glUniform2f(sprite_texel, 1.0f / tex->tw, 1.0f / tex->th); + return 1; +} + +int ogl_sharp_enabled(void) +{ +#ifdef __EMSCRIPTEN__ + return d2web_option(D2WEB_OPTION_SHARP) && ogl_shaders_ready(); +#else + return 0; +#endif +} + +#define MIN_SCALE 1.25f + +// For the part u1,v1 - u2,v2 of a texture drawn magnified (scale = screen pixels per texel). +// Not while glyphs are drawn: they have their own shader. +int ogl_upscale_begin(ogl_texture *tex, float u1, float v1, float u2, float v2, float scale, int movie) +{ + upscale_shader *u = &upscale[movie ? 1 : 0]; + if (scale < MIN_SCALE || active || !tex->tw || !tex->th || !ogl_sharp_enabled()) + return 0; + glUseProgram(active = u->prog); + glUniform2f(u->size, tex->tw, tex->th); + glUniform4f(u->lim, u1 + 0.5f / tex->tw, v1 + 0.5f / tex->th, u2 - 0.5f / tex->tw, v2 - 0.5f / tex->th); + return 1; +} + +// scale = screen pixels per glyph texel +int ogl_glyph_begin(float scale) +{ + if (scale < MIN_SCALE || !ogl_sharp_enabled()) + return 0; + glUseProgram(active = glyph_prog); + glUniform1f(glyph_soft, 0.5f / scale); + return 1; +} + +void ogl_shader_end(void) +{ + glUseProgram(active = 0); +} diff --git a/d2/arch/sdl/event.c b/d2/arch/sdl/event.c index 5a20a70..e7b9688 100644 --- a/d2/arch/sdl/event.c +++ b/d2/arch/sdl/event.c @@ -16,6 +16,9 @@ #include "args.h" #include "joy.h" +#ifdef __EMSCRIPTEN__ +#include "web.h" +#endif extern void key_handler(SDL_KeyboardEvent *event); extern void mouse_button_handler(SDL_MouseButtonEvent *mbe); @@ -31,6 +34,10 @@ void event_poll() window *wind = window_get_front(); int idle = 1; +#ifdef __EMSCRIPTEN__ + if (d2web_gamepads_changed()) + joy_rescan(); +#endif // If the front window changes, exit this loop, otherwise unintended behavior can occur // like pressing 'Return' really fast at 'Difficulty Level' causing multiple games to be started while ((wind == window_get_front()) && SDL_PollEvent(&event)) @@ -163,6 +170,10 @@ void event_process(void) timer_update(); event_poll(); // send input events first +#ifdef __EMSCRIPTEN__ + if (d2web_cutscene_skipping()) // the page's Skip button: Escape for the movie, title or briefing + key_send_escape(); +#endif // Doing this prevents problems when a draw event can create a newmenu, // such as some network menus when they report a problem diff --git a/d2/arch/sdl/joy.c b/d2/arch/sdl/joy.c index efbb67c..16ee34d 100644 --- a/d2/arch/sdl/joy.c +++ b/d2/arch/sdl/joy.c @@ -192,11 +192,19 @@ void joy_init() { int i,j,n; char temp[64]; +#ifdef __EMSCRIPTEN__ + // a rescan must not run SDL_Init again: the browser SDL would reset its keyboard state + static int sdl_joystick_ready = 0; + if (!sdl_joystick_ready) +#endif if (SDL_Init(SDL_INIT_JOYSTICK) < 0) { con_printf(CON_NORMAL, "sdl-joystick: initialisation failed: %s.",SDL_GetError()); return; } +#ifdef __EMSCRIPTEN__ + sdl_joystick_ready = 1; +#endif memset(&Joystick,0,sizeof(Joystick)); memset(joyaxis_text, 0, JOY_MAX_AXES * sizeof(char *)); @@ -294,6 +302,23 @@ void joy_init() joy_num_axes = Joystick.n_axes; } +#ifdef __EMSCRIPTEN__ +// Browsers only reveal a gamepad after its first button press, usually after the game started. +void joy_rescan() +{ + int i; + + for (i = 0; i < num_joysticks; i++) + SDL_JoystickClose(SDL_Joysticks[i].handle); + while (Joystick.n_axes-- > 0) + d_free(joyaxis_text[Joystick.n_axes]); + while (Joystick.n_buttons-- > 0) + d_free(joybutton_text[Joystick.n_buttons]); + num_joysticks = 0; + joy_init(); +} +#endif + void joy_close() { SDL_JoystickClose(SDL_Joysticks[num_joysticks].handle); diff --git a/d2/arch/sdl/key.c b/d2/arch/sdl/key.c index 92eee47..e709ef5 100644 --- a/d2/arch/sdl/key.c +++ b/d2/arch/sdl/key.c @@ -448,7 +448,11 @@ void key_init() void key_flush() { int i; +#ifdef __EMSCRIPTEN__ + Uint8 *keystate = NULL; // keycodes are not small array indices in the browser SDL +#else Uint8 *keystate = SDL_GetKeyState(NULL); +#endif if (!Installed) key_init(); @@ -458,7 +462,7 @@ void key_flush() unicode_frame_buffer[i] = '\0'; for (i=0; i<256; i++ ) { - if (key_ismodlck(i) == KEY_ISLCK && keystate[key_properties[i].sym] && !GameArg.CtlNoStickyKeys) // do not flush status of sticky keys + if (key_ismodlck(i) == KEY_ISLCK && keystate && keystate[key_properties[i].sym] && !GameArg.CtlNoStickyKeys) // do not flush status of sticky keys { keyd_pressed[i] = 1; key_data.state[i] = 0; @@ -478,6 +482,17 @@ int event_key_get(d_event *event) } // same as above but without mod states +#ifdef __EMSCRIPTEN__ +void key_send_escape(void) +{ + d_event_keycommand event; + + event.type = EVENT_KEY_COMMAND; + event.keycode = KEY_ESC; + event_send((d_event *)&event); +} +#endif + int event_key_get_raw(d_event *event) { int keycode = ((d_event_keycommand *)event)->keycode; diff --git a/d2/arch/sdl/mouse.c b/d2/arch/sdl/mouse.c index 2cfce11..0bb6b69 100644 --- a/d2/arch/sdl/mouse.c +++ b/d2/arch/sdl/mouse.c @@ -77,6 +77,11 @@ void mouse_button_handler(SDL_MouseButtonEvent *mbe) return; Mouse.cursor_time = timer_query(); +#ifdef __EMSCRIPTEN__ + // a tap on a touch screen presses a button where no mouse moved first + Mouse.x = mbe->x; + Mouse.y = mbe->y; +#endif if (mbe->state == SDL_PRESSED) { d_event_mouse_moved event2 = { EVENT_MOUSE_MOVED, 0, 0, 0 }; diff --git a/d2/arch/sdl/timer.c b/d2/arch/sdl/timer.c index 3e7949c..2dca829 100644 --- a/d2/arch/sdl/timer.c +++ b/d2/arch/sdl/timer.c @@ -5,6 +5,9 @@ */ #include +#ifdef __EMSCRIPTEN__ +#include +#endif #include "maths.h" #include "timer.h" @@ -25,7 +28,14 @@ void timer_update(void) } if (last_tv < cur_tv) // in case SDL_GetTicks wraps, don't update and have a little hickup + { +#ifdef __EMSCRIPTEN__ + // browsers stop the frame loop in background tabs; don't let game time leap ahead on return + if (cur_tv - last_tv > F1_0/5) + last_tv = cur_tv - F1_0/5; +#endif F64_RunTime += (cur_tv - last_tv); // increment! this value will overflow long after we are all dead... so why bother checking? + } last_tv = cur_tv; } @@ -36,13 +46,22 @@ fix64 timer_query(void) void timer_delay(fix seconds) { +#ifdef __EMSCRIPTEN__ + int ms = f2i(fixmul(seconds, i2f(1000))); + if (ms > 0) + emscripten_sleep(ms); +#else SDL_Delay(f2i(fixmul(seconds, i2f(1000)))); +#endif } // Replacement for timer_delay which considers calc time the program needs between frames (not reentrant) void timer_delay2(int fps) { static u_int32_t FrameStart=0; +#ifdef __EMSCRIPTEN__ + return; // frames are paced by requestAnimationFrame in gr_flip +#endif u_int32_t FrameLoop=0; while (FrameLoop < 1000u/(GameCfg.VSync?MAXIMUM_FPS:fps)) diff --git a/d2/arch/web/SDL_keysym.h b/d2/arch/web/SDL_keysym.h new file mode 100644 index 0000000..f8c55f7 --- /dev/null +++ b/d2/arch/web/SDL_keysym.h @@ -0,0 +1,2 @@ +/* SDL 1.2 SDL_keysym.h shim for Emscripten's SDL 1.3-style headers. */ +#include diff --git a/d2/arch/web/library_d2web.js b/d2/arch/web/library_d2web.js new file mode 100644 index 0000000..7e1ff1a --- /dev/null +++ b/d2/arch/web/library_d2web.js @@ -0,0 +1,356 @@ +// Emscripten JS library: browser glue for the Descent II web build. +// The page fills Module.d2cd.tracks[n] with object URLs of the ripped CD tracks +// (index = CD track number; track 1 is the data track and stays empty). + +addToLibrary({ + $D2CD__postset: 'D2CD.init();', + $D2CD: { + audio: null, + first: 0, + last: 0, + cur: 0, + state: 0, // 0 stopped, 1 playing, 2 paused + volume: 1, + // status for the page (and tests): which CD track is playing and where + init() { + Module.cdStatus = () => ({ + state: D2CD.state, + track: D2CD.cur, + time: D2CD.audio ? D2CD.audio.currentTime : 0, + paused: D2CD.audio ? D2CD.audio.paused : true, + volume: D2CD.volume, + }); + }, + tracks() { + return (Module.d2cd && Module.d2cd.tracks) || []; + }, + el() { + if (!D2CD.audio) { + D2CD.audio = new Audio(); + D2CD.audio.preload = 'auto'; + D2CD.audio.addEventListener('ended', () => { + if (D2CD.state !== 1) return; + if (D2CD.cur < D2CD.last && D2CD.start(D2CD.cur + 1)) return; + D2CD.state = 0; + }); + } + return D2CD.audio; + }, + start(n) { + const url = D2CD.tracks()[n]; + if (!url) return false; + const a = D2CD.el(); + D2CD.cur = n; + a.src = url; + a.volume = D2CD.volume; + a.play().catch((e) => console.warn('CD audio play failed', e)); + D2CD.state = 1; + if (Module.onCdTrack) Module.onCdTrack(n); + return true; + }, + }, + + d2web_cd_numtracks__deps: ['$D2CD'], + d2web_cd_numtracks: () => { + const t = D2CD.tracks(); + return t.length ? t.length - 1 : 0; + }, + + d2web_cd_play__deps: ['$D2CD'], + d2web_cd_play: (first, last) => { + const n = D2CD.tracks().length - 1; + if (first < 1 || first > n) return 0; + D2CD.first = first; + D2CD.last = Math.min(Math.max(last, first), n); + return D2CD.start(first) ? 1 : 0; + }, + + d2web_cd_stop__deps: ['$D2CD'], + d2web_cd_stop: () => { + if (D2CD.audio) D2CD.audio.pause(); + D2CD.state = 0; + }, + + d2web_cd_pause__deps: ['$D2CD'], + d2web_cd_pause: () => { + if (D2CD.state === 1 && D2CD.audio) { + D2CD.audio.pause(); + D2CD.state = 2; + } + }, + + d2web_cd_resume__deps: ['$D2CD'], + d2web_cd_resume: () => { + if (D2CD.state === 2 && D2CD.audio) { + D2CD.audio.play().catch(() => {}); + D2CD.state = 1; + } + }, + + d2web_cd_status__deps: ['$D2CD'], + d2web_cd_status: () => D2CD.state, + + d2web_cd_track__deps: ['$D2CD'], + d2web_cd_track: () => D2CD.cur, + + d2web_cd_volume__deps: ['$D2CD'], + d2web_cd_volume: (v) => { + D2CD.volume = Math.max(0, Math.min(8, v)) / 8; + if (D2CD.audio) D2CD.audio.volume = D2CD.volume; + }, + + // MIDI music is played by the page's General MIDI synth (Module.d2midi, see d2loader.js). + d2web_midi_play: (data, len, loop) => { + if (!Module.d2midi) return 0; + Module.d2midi.play(HEAPU8.slice(data, data + len), !!loop); + return 1; + }, + d2web_midi_stop: () => { if (Module.d2midi) Module.d2midi.stop(); }, + d2web_midi_pause: () => { if (Module.d2midi) Module.d2midi.pause(); }, + d2web_midi_resume: () => { if (Module.d2midi) Module.d2midi.resume(); }, + d2web_midi_pause_resume: () => { if (Module.d2midi) Module.d2midi.toggle(); }, + d2web_midi_volume: (v) => { if (Module.d2midi) Module.d2midi.volume(Math.max(0, Math.min(8, v)) / 8); }, + + // Music folder: the page fills Module.d2music with object URLs of the player's own music + // files, songs[SONG_*] (title, briefing, endlevel, endgame, credits) and levels[] in play order. + $D2Music__postset: 'D2Music.init();', + $D2Music: { + audio: null, + state: 0, // 0 stopped, 1 playing, 2 paused + volume: 1, + label: '', // 'song 0' or 'level 3', for the page and tests + level: -1, // levels[] index while level music plays + next: null, // started when the current file ends + init() { + Module.musicStatus = () => ({ + state: D2Music.state, + playing: D2Music.label, + level: D2Music.level, + time: D2Music.audio ? D2Music.audio.currentTime : 0, + paused: D2Music.audio ? D2Music.audio.paused : true, + volume: D2Music.volume, + }); + }, + set() { + return Module.d2music || { songs: [], levels: [] }; + }, + el() { + if (!D2Music.audio) { + D2Music.audio = new Audio(); + D2Music.audio.preload = 'auto'; + D2Music.audio.addEventListener('ended', () => { + if (D2Music.state !== 1) return; + if (D2Music.next) D2Music.next(); + else D2Music.state = 0; + }); + } + return D2Music.audio; + }, + start(url, loop, label, next) { + const a = D2Music.el(); + a.src = url; + a.loop = loop; + a.volume = D2Music.volume; + a.play().catch((e) => console.warn('Music play failed', e)); + D2Music.state = 1; + D2Music.label = label; + D2Music.next = next || null; + if (Module.onMusicTrack) Module.onMusicTrack(label); + }, + // level music plays through the playlist and wraps, like the CD + playLevel(i) { + const levels = D2Music.set().levels; + D2Music.level = ((i % levels.length) + levels.length) % levels.length; + D2Music.start(levels[D2Music.level], levels.length === 1, 'level ' + D2Music.level, + () => D2Music.playLevel(D2Music.level + 1)); + }, + }, + + d2web_music_has__deps: ['$D2Music'], + d2web_music_has: (songnum) => { + const s = D2Music.set(); + if (songnum < 0) return s.levels.length || s.songs.some(Boolean) ? 1 : 0; + if (songnum >= 5) return s.levels.length ? 1 : 0; // SONG_FIRST_LEVEL_SONG + return s.songs[songnum] ? 1 : 0; + }, + + d2web_music_song__deps: ['$D2Music'], + d2web_music_song: (songnum, repeat, thenCredits) => { + const songs = D2Music.set().songs; + const url = songs[songnum]; + if (!url) return 0; + D2Music.level = -1; + // the title plays once and hands over to the looping credits song, as on the CD + if (thenCredits && songs[4] && songnum !== 4) { + D2Music.start(url, false, 'song ' + songnum, () => D2Music.start(songs[4], true, 'song 4')); + } else { + D2Music.start(url, !!repeat, 'song ' + songnum); + } + return 1; + }, + + d2web_music_level__deps: ['$D2Music'], + d2web_music_level: (levelsong, offset) => { + if (!D2Music.set().levels.length) return 0; + D2Music.playLevel(offset && D2Music.level >= 0 ? D2Music.level + offset : levelsong); + return 1; + }, + + d2web_music_stop__deps: ['$D2Music'], + d2web_music_stop: () => { + if (D2Music.audio) D2Music.audio.pause(); + D2Music.state = 0; + D2Music.label = ''; + D2Music.next = null; + }, + + d2web_music_pause__deps: ['$D2Music'], + d2web_music_pause: () => { + if (D2Music.state === 1 && D2Music.audio) { + D2Music.audio.pause(); + D2Music.state = 2; + } + }, + + d2web_music_resume__deps: ['$D2Music'], + d2web_music_resume: () => { + if (D2Music.state === 2 && D2Music.audio) { + D2Music.audio.play().catch(() => {}); + D2Music.state = 1; + } + }, + + d2web_music_pause_resume__deps: ['$D2Music', 'd2web_music_pause', 'd2web_music_resume'], + d2web_music_pause_resume: () => { + if (D2Music.state === 1) _d2web_music_pause(); else _d2web_music_resume(); + }, + + d2web_music_volume__deps: ['$D2Music'], + d2web_music_volume: (v) => { + D2Music.volume = Math.max(0, Math.min(8, v)) / 8; + if (D2Music.audio) D2Music.audio.volume = D2Music.volume; + }, + + // Chrome reports four gamepad slots, empty ones as null, and the stock SDL count includes + // them; count up to the last connected pad so device indices still line up. + SDL_NumJoysticks: () => { + const pads = navigator.getGamepads ? navigator.getGamepads() : []; + let n = 0; + for (let i = 0; i < pads.length; i++) if (pads[i]) n = i + 1; + return n; + }, + + // Browsers reveal a gamepad on its first button press; the engine rescans when this flips. + $D2Pads: { changed: false, hooked: false }, + d2web_gamepads_changed__deps: ['$D2Pads'], + d2web_gamepads_changed: () => { + if (!D2Pads.hooked) { + D2Pads.hooked = true; + const mark = () => { D2Pads.changed = true; }; + window.addEventListener('gamepadconnected', mark); + window.addEventListener('gamepaddisconnected', mark); + } + const changed = D2Pads.changed; + D2Pads.changed = false; + return changed ? 1 : 0; + }, + + // Touch controls: the page keeps their state in Module.d2touch (d2loader.js). The game + // reads controls several times a frame; each read in a frame gets the same stick and look + // values, and the first one the taps. + $D2Touch: { frame: 0, readFrame: -1, look: [0, 0] }, + d2web_touch_read__deps: ['$D2Touch'], + d2web_touch_read: (out) => { + const t = Module.d2touch; + if (!t || !t.enabled) return 0; + t.lastRead = performance.now(); + let taps = 0; + if (D2Touch.readFrame !== D2Touch.frame) { + D2Touch.readFrame = D2Touch.frame; + D2Touch.look = t.takeLook(); + taps = t.takeTaps(); + } + const o = out >> 2; + HEAPF32[o] = t.stickX; + HEAPF32[o + 1] = t.stickY; + HEAPF32[o + 2] = D2Touch.look[0]; + HEAPF32[o + 3] = D2Touch.look[1]; + HEAPF32[o + 4] = t.held; + HEAPF32[o + 5] = taps; + return 1; + }, + + d2web_option: (which) => { + const o = Module.d2options || {}; + return o[['sharp', 'effects', 'glow', 'lighting', 'ao', 'haze', 'surfaces', 'explosions', 'reflections', 'ultra', 'invertPitch'][which]] === false ? 0 : 1; + }, + + // development: Module.d2tune[i] overrides a look constant while the game runs + d2web_tune: (i, def) => { + const t = Module.d2tune; + return t && typeof t[i] === 'number' ? t[i] : def; + }, + + d2web_gl_version: () => (GL.currentContext ? GL.currentContext.version : 0), + + d2web_shader_source__deps: ['$UTF8ToString'], + d2web_shader_source: (shader, src) => { + GLctx.shaderSource(GL.shaders[shader], UTF8ToString(src)); + }, + + d2web_frame_wait__deps: ['$D2Touch'], + d2web_frame_wait__async: true, + d2web_frame_wait: () => Asyncify.handleSleep((wakeUp) => { + D2Touch.frame++; + if (Module.onFrame) Module.onFrame(); + requestAnimationFrame(() => wakeUp()); + }), + + // Relative mouse motion for pointer-locked flight controls. + $D2Mouse: { + dx: 0, + dy: 0, + hooked: false, + hook() { + if (D2Mouse.hooked) return; + D2Mouse.hooked = true; + document.addEventListener('mousemove', (e) => { + if (document.pointerLockElement !== Module.canvas) return; + D2Mouse.dx += e.movementX || 0; + D2Mouse.dy += e.movementY || 0; + }); + }, + }, + SDL_GetRelativeMouseState__deps: ['$D2Mouse'], + SDL_GetRelativeMouseState: (px, py) => { + D2Mouse.hook(); + if (px) HEAP32[px >> 2] = Math.round(D2Mouse.dx); + if (py) HEAP32[py >> 2] = Math.round(D2Mouse.dy); + D2Mouse.dx = 0; + D2Mouse.dy = 0; + return 0; + }, + + d2web_quit: () => { + FS.syncfs(false, (err) => { + if (err) console.warn('Saving to browser storage failed', err); + if (Module.onQuit) Module.onQuit(); + }); + }, + + $D2Saves: { timer: 0, busy: false, again: false }, + d2web_sync_saves__deps: ['$D2Saves'], + d2web_sync_saves: () => { + if (D2Saves.timer) clearTimeout(D2Saves.timer); + D2Saves.timer = setTimeout(function run() { + D2Saves.timer = 0; + if (D2Saves.busy) { D2Saves.again = true; return; } + D2Saves.busy = true; + FS.syncfs(false, (err) => { + D2Saves.busy = false; + if (err) console.warn('Saving to browser storage failed', err); + if (D2Saves.again) { D2Saves.again = false; run(); } + }); + }, 750); + }, +}); diff --git a/d2/arch/web/rbaudio_web.c b/d2/arch/web/rbaudio_web.c new file mode 100644 index 0000000..bc5fa7e --- /dev/null +++ b/d2/arch/web/rbaudio_web.c @@ -0,0 +1,157 @@ +/* + * Redbook (CD audio) for the browser build. + * Tracks come from the player's own Descent II disc image, ripped by the page. + */ + +#include "pstypes.h" +#include "rbaudio.h" +#include "console.h" +#include "timer.h" +#include "web.h" + +static int initialised = 0; +void (*redbook_finished_hook)() = NULL; + +void RBAExit() +{ + d2web_cd_stop(); +} + +void RBAInit() +{ + if (initialised) + return; + if (d2web_cd_numtracks() < 2) + { + con_printf(CON_NORMAL, "RBAudio: no CD audio tracks loaded\n"); + return; + } + initialised = 1; + RBAList(); +} + +int RBAEnabled() +{ + return initialised; +} + +int RBAPlayTrack(int a) +{ + if (!initialised) + return -1; + if (d2web_cd_play(a, a)) + { + con_printf(CON_VERBOSE, "RBAudio: Playing track %i\n", a); + return a; + } + return -1; +} + +void RBAStop() +{ + if (!initialised) + return; + d2web_cd_stop(); + redbook_finished_hook = NULL; +} + +void RBAEjectDisk() +{ + RBAStop(); +} + +void RBASetVolume(int volume) +{ + d2web_cd_volume(volume); +} + +void RBAPause() +{ + if (initialised) + d2web_cd_pause(); +} + +int RBAResume() +{ + if (!initialised) + return -1; + d2web_cd_resume(); + return 1; +} + +int RBAPauseResume() +{ + if (!initialised) + return 0; + switch (d2web_cd_status()) + { + case 1: d2web_cd_pause(); return 1; + case 2: d2web_cd_resume(); return 1; + } + return 0; +} + +int RBAGetNumberOfTracks() +{ + if (!initialised) + return -1; + return d2web_cd_numtracks(); +} + +// the browser reports the end of the requested track range; check from the event loops +void RBACheckFinishedHook() +{ + static fix64 last_check_time = 0; + + if (!initialised) + return; + if ((timer_query() - last_check_time) >= F1_0) + { + if (d2web_cd_status() == 0 && redbook_finished_hook) + { + con_printf(CON_VERBOSE, "RBAudio: Playback done, calling finished-hook\n"); + redbook_finished_hook(); + } + last_check_time = timer_query(); + } +} + +// plays tracks first through last, inclusive +int RBAPlayTracks(int first, int last, void (*hook_finished)(void)) +{ + if (!initialised) + return 0; + redbook_finished_hook = hook_finished; + con_printf(CON_VERBOSE, "RBAudio: Playing tracks %i to %i\n", first, last); + return d2web_cd_play(first, last); +} + +int RBAGetTrackNum() +{ + if (!initialised || d2web_cd_status() != 1) + return 0; + return d2web_cd_track(); +} + +int RBAPeekPlayStatus() +{ + if (!initialised) + return 0; + switch (d2web_cd_status()) + { + case 1: return 1; + case 2: return -1; // hack so it doesn't keep restarting paused music + } + return 0; +} + +// songs.c uses GameCfg.OrigTrackOrder to accept the disc, so no CDDB id is needed +unsigned long RBAGetDiscID() +{ + return 0; +} + +void RBAList(void) +{ + con_printf(CON_VERBOSE, "RBAudio: %d CD tracks available\n", d2web_cd_numtracks()); +} diff --git a/d2/arch/web/web.c b/d2/arch/web/web.c new file mode 100644 index 0000000..83cbef0 --- /dev/null +++ b/d2/arch/web/web.c @@ -0,0 +1,449 @@ +/* + * Browser (Emscripten) replacements for desktop-only pieces: + * message boxes, GLU mipmapping and GL 1.1 calls WebGL lacks. + */ + +#include +#include +#include +#include +#include +#include "ogl_init.h" +#include "messagebox.h" +#include "hmp.h" +#include "u_mem.h" +#include "web.h" + +EM_JS(void, d2web_show_message, (const char *msg, int is_error), { + const text = UTF8ToString(msg); + if (is_error) console.error(text); else console.warn(text); + if (Module.onGameMessage) Module.onGameMessage(text, !!is_error); +}); + +EM_JS(void, d2web_cutscene_changed, (int on), { + if (Module.onCutscene) Module.onCutscene(!!on); +}); + +static int cutscene_depth, cutscene_skip; + +void d2web_cutscene(int begin) +{ + if (begin) { + if (cutscene_depth++ == 0) + d2web_cutscene_changed(1); + } else if (cutscene_depth > 0 && --cutscene_depth == 0) { + cutscene_skip = 0; + d2web_cutscene_changed(0); + } +} + +// the page's Skip button: event_process sends Escape to the screen in front until the whole sequence is over +EMSCRIPTEN_KEEPALIVE void d2web_skip_cutscene(void) +{ + if (cutscene_depth > 0) + cutscene_skip = 1; +} + +int d2web_cutscene_skipping(void) +{ + return cutscene_skip && cutscene_depth > 0; +} + +void msgbox_warning(char *message) +{ + d2web_show_message(message, 0); +} + +void msgbox_error(const char *message) +{ + d2web_show_message(message, 1); +} + +int d2web_play_hmp(const char *filename, int loop) +{ + unsigned char *mid = NULL; + unsigned int len = 0; + int ok; + + hmp2mid((char *)filename, &mid, &len); + if (!mid) + return 0; + ok = len ? d2web_midi_play(mid, len, loop) : 0; + d_free(mid); + return ok; +} + +static int is_pow2(int v) +{ + return v > 0 && (v & (v - 1)) == 0; +} + +GLint gluBuild2DMipmaps(GLenum target, GLint internalFormat, GLsizei width, GLsizei height, + GLenum format, GLenum type, const void *data) +{ + // WebGL wants the internal format to match the upload format + glTexImage2D(target, 0, format, width, height, 0, format, type, data); + if (is_pow2(width) && is_pow2(height)) + glGenerateMipmap(target); + return 0; +} + +void glPrioritizeTextures(GLsizei n, const GLuint *textures, const GLclampf *priorities) +{ +} + +// WebGL always reads back from the buffer being drawn, which is what the game asks for +void glReadBuffer(GLenum mode) +{ +} + +/* + * Emscripten's JS SDL leaves SDL_AllocRW unimplemented and its own RWops can't be + * read through the function pointers SDL_RWread uses, so provide real ones in C. + */ +SDL_RWops *SDL_AllocRW(void) +{ + return calloc(1, sizeof(SDL_RWops)); +} + +void SDL_FreeRW(SDL_RWops *area) +{ + free(area); +} + +static long mem_seek(SDL_RWops *rw, long offset, int whence) +{ + Uint8 *p; + + switch (whence) + { + case RW_SEEK_SET: p = rw->hidden.mem.base + offset; break; + case RW_SEEK_CUR: p = rw->hidden.mem.here + offset; break; + case RW_SEEK_END: p = rw->hidden.mem.stop + offset; break; + default: return -1; + } + if (p < rw->hidden.mem.base) + p = rw->hidden.mem.base; + if (p > rw->hidden.mem.stop) + p = rw->hidden.mem.stop; + rw->hidden.mem.here = p; + return (long)(p - rw->hidden.mem.base); +} + +static size_t mem_read(SDL_RWops *rw, void *ptr, size_t size, size_t maxnum) +{ + size_t avail, n; + + if (!size) + return 0; + avail = (size_t)(rw->hidden.mem.stop - rw->hidden.mem.here); + n = maxnum; + if (n * size > avail) + n = avail / size; + memcpy(ptr, rw->hidden.mem.here, n * size); + rw->hidden.mem.here += n * size; + return n; +} + +static size_t mem_nowrite(SDL_RWops *rw, const void *ptr, size_t size, size_t num) +{ + return 0; +} + +static int mem_close(SDL_RWops *rw) +{ + SDL_FreeRW(rw); + return 0; +} + +SDL_RWops *SDL_RWFromConstMem(const void *mem, int size) +{ + SDL_RWops *rw = SDL_AllocRW(); + + if (!rw) + return NULL; + rw->seek = mem_seek; + rw->read = mem_read; + rw->write = mem_nowrite; + rw->close = mem_close; + rw->hidden.mem.base = (Uint8 *)mem; + rw->hidden.mem.here = rw->hidden.mem.base; + rw->hidden.mem.stop = rw->hidden.mem.base + size; + return rw; +} + +/* Test tools for the page (never called in normal play). */ +#include "object.h" +#include "robot.h" +#include "gameseg.h" +#include "fuelcen.h" +#include "ai.h" +#include "bm.h" +#include "segment.h" +#include "player.h" +#include "wall.h" +#include "polyobj.h" + +/* Puts robot type id dist units ahead of the ship, facing it (replacing the last one put + * there): with ai it moves its joints and fires like any robot, holding its place; without, + * it stays in its rest pose. Returns its object number or -1. */ +EMSCRIPTEN_KEEPALIVE int d2web_test_robot(int id, int dist, int ai) +{ + static int last = -1, last_sig; + vms_vector pos, back; + object *obj; + int seg; + + if (last >= 0 && Objects[last].type == OBJ_ROBOT && Objects[last].signature == last_sig) + obj_delete(last); + last = -1; + if (!ConsoleObject || id < 0 || id >= N_robot_types) + return -1; + vm_vec_scale_add(&pos, &ConsoleObject->pos, &ConsoleObject->orient.fvec, i2f(dist)); + if ((seg = find_point_seg(&pos, ConsoleObject->segnum)) < 0) + return -1; + if (!(obj = create_morph_robot(&Segments[seg], &pos, id))) + return -1; + back = ConsoleObject->orient.fvec; + vm_vec_negate(&back); + vm_vector_2_matrix(&obj->orient, &back, &ConsoleObject->orient.uvec, NULL); + obj->ctype.ai_info.behavior = AIB_STILL; + if (!ai) + obj->control_type = CT_NONE; + last = obj - Objects; + last_sig = obj->signature; + return last; +} + +#define PAST_DOOR_MAX 4 +static int past_doors[PAST_DOOR_MAX], n_past_doors; // seg * 6 + side of each door a robot was put behind (test) + +/* The i-th door d2web_place_robots_past_first_doors used, as seg * 6 + side (for d2web_test_view), or -1. */ +EMSCRIPTEN_KEEPALIVE int d2web_test_past_door(int i) +{ + return i >= 0 && i < n_past_doors ? past_doors[i] : -1; +} + +/* One robot of type id just past the door on side door_side of door_seg, facing the door and holding its place. */ +static int place_robot_past_door(int id, int door_seg, int door_side) +{ + int beyond = Segments[door_seg].children[door_side], seg; + vms_vector door, center, dir, pos, face; + fix rad = Polygon_models[Robot_info[id].model_num].rad, reach; + object *obj; + + compute_center_point_on_side(&door, &Segments[door_seg], door_side); + compute_segment_center(¢er, &Segments[beyond]); + // clear of the door by its size, further in than the next segment's middle if that is too close + reach = vm_vec_normalized_dir(&dir, ¢er, &door); + if (reach < fixmul(rad, F1_0 * 3 / 2)) + reach = fixmul(rad, F1_0 * 3 / 2); + vm_vec_scale_add(&pos, &door, &dir, reach); + if ((seg = find_point_seg(&pos, beyond)) < 0) { + pos = center; + seg = beyond; + } + if (!(obj = create_morph_robot(&Segments[seg], &pos, id))) + return -1; + vm_vec_sub(&face, &door, &pos); + vm_vector_2_matrix(&obj->orient, &face, NULL, NULL); + init_ai_object(obj - Objects, AIB_STILL, -1); + return obj - Objects; +} + +int d2web_place_robots_past_first_doors(int id) +{ + static short queue[MAX_SEGMENTS], depth[MAX_SEGMENTS]; + static ubyte seen[MAX_SEGMENTS]; + int head = 0, tail = 0, found_depth = -1, placed = 0; + + n_past_doors = 0; + if (!ConsoleObject || id < 0 || id >= N_robot_types) + return 0; + // the segments the ship can fly to without opening anything, nearest first; the doors it can open at the + // nearest distance (the "first doors": there can be more than one way on) each get a robot + memset(seen, 0, sizeof(seen)); + queue[tail++] = ConsoleObject->segnum; + seen[ConsoleObject->segnum] = 1; + depth[ConsoleObject->segnum] = 0; + while (head < tail) { + int s = queue[head++], side; + if (found_depth >= 0 && depth[s] > found_depth) + break; + for (side = 0; side < MAX_SIDES_PER_SEGMENT; side++) { + int child = Segments[s].children[side], w = Segments[s].sides[side].wall_num; + if (!IS_CHILD(child) || seen[child]) + continue; + if (w < 0) { + seen[child] = 1; + depth[child] = depth[s] + 1; + queue[tail++] = child; + } else if (Walls[w].type == WALL_DOOR && Walls[w].keys == KEY_NONE && !(Walls[w].flags & WALL_DOOR_LOCKED) && + n_past_doors < PAST_DOOR_MAX) { + seen[child] = 1; // one robot per room past the doors + found_depth = depth[s]; + if (place_robot_past_door(id, s, side) >= 0) { + past_doors[n_past_doors++] = s * 6 + side; + placed++; + } + } + } + } + return placed; +} + +/* Sets a robot's shields to percent of its full strength (damaged robots smoke). */ +EMSCRIPTEN_KEEPALIVE void d2web_test_shields(int objnum, int percent) +{ + if (objnum >= 0 && objnum <= Highest_object_index && Objects[objnum].type == OBJ_ROBOT) + Objects[objnum].shields = Robot_info[Objects[objnum].id].strength * percent / 100; +} + +/* 0 draws the game's own models instead of the loaded high-resolution ones. */ +extern int xmodel_enabled; +EMSCRIPTEN_KEEPALIVE void d2web_test_hires_models(int on) +{ + xmodel_enabled = on; +} + +/* Puts the ship at the far side of segment segnum, looking at the middle of side sidenum. + * Returns 0 if there is no such segment. */ +EMSCRIPTEN_KEEPALIVE int d2web_test_view(int segnum, int sidenum) +{ + vms_vector from, to, center, fvec; + if (!ConsoleObject || segnum < 0 || segnum > Highest_segment_index || sidenum < 0 || sidenum >= MAX_SIDES_PER_SEGMENT) + return 0; + compute_segment_center(¢er, &Segments[segnum]); + compute_center_point_on_side(&to, &Segments[segnum], sidenum); + compute_center_point_on_side(&from, &Segments[segnum], Side_opposite[sidenum]); + vm_vec_avg(&from, &from, ¢er); + vm_vec_sub(&fvec, &to, &from); + vm_vector_2_matrix(&ConsoleObject->orient, &fvec, NULL, NULL); + ConsoleObject->pos = from; + vm_vec_zero(&ConsoleObject->mtype.phys_info.velocity); + vm_vec_zero(&ConsoleObject->mtype.phys_info.rotvel); + obj_relink(ConsoleObject - Objects, segnum); + Players[Player_num].shields = MAX_SHIELDS; // robots there may have been shooting + return 1; +} + +/* The first side at or after seg * 6 + side (counting that way) whose texture gives light, + * as seg * 6 + side, or -1. */ +EMSCRIPTEN_KEEPALIVE int d2web_test_next_light(int from) +{ + int i; + for (i = from < 0 ? 0 : from; i < (Highest_segment_index + 1) * MAX_SIDES_PER_SEGMENT; i++) { + side *s = &Segments[i / MAX_SIDES_PER_SEGMENT].sides[i % MAX_SIDES_PER_SEGMENT]; + if (Segments[i / MAX_SIDES_PER_SEGMENT].children[i % MAX_SIDES_PER_SEGMENT] == -1 && + (TmapInfo[s->tmap_num].lighting > 0 || (s->tmap_num2 && TmapInfo[s->tmap_num2 & 0x3fff].lighting > 0))) + return i; + } + return -1; +} + +/* Switches the view: 0 full cockpit, 2 status bar, 3 full screen (CM_*). */ +#include "playsave.h" +extern void init_cockpit(void); +EMSCRIPTEN_KEEPALIVE void d2web_test_cockpit(int mode) +{ + PlayerCfg.CurrentCockpitMode = mode; + init_cockpit(); +} + +/* Sets player flags (PLAYER_FLAGS_*), e.g. a headlight that is on. */ +#include "player.h" +EMSCRIPTEN_KEEPALIVE void d2web_test_player_flags(int flags) +{ + Players[Player_num].flags |= flags; +} + +/* Like d2web_test_next_light, for sides whose texture has one of the TMI_* flags in mask + * (1 lava, 2 water, 4 force field). */ +EMSCRIPTEN_KEEPALIVE int d2web_test_next_surface(int from, int mask) +{ + int i; + for (i = from < 0 ? 0 : from; i < (Highest_segment_index + 1) * MAX_SIDES_PER_SEGMENT; i++) { + segment *sg = &Segments[i / MAX_SIDES_PER_SEGMENT]; + side *s = &sg->sides[i % MAX_SIDES_PER_SEGMENT]; + if ((sg->children[i % MAX_SIDES_PER_SEGMENT] == -1 || s->wall_num != -1) && + ((TmapInfo[s->tmap_num].flags | (s->tmap_num2 ? TmapInfo[s->tmap_num2 & 0x3fff].flags : 0)) & mask)) + return i; + } + return -1; +} + +/* Blows up a robot as if the ship shot it. */ +#include "collide.h" +EMSCRIPTEN_KEEPALIVE void d2web_test_kill(int objnum) +{ + if (objnum >= 0 && objnum <= Highest_object_index && Objects[objnum].type == OBJ_ROBOT) + apply_damage_to_robot(&Objects[objnum], Objects[objnum].shields + F1_0, ConsoleObject - Objects); +} + +/* 1 stops robots firing (for clean comparison shots). */ +#include "game.h" +EMSCRIPTEN_KEEPALIVE void d2web_test_calm(int on) +{ + cheats.robotfiringsuspended = on; +} + +/* Turns an object to pitch, heading and bank in degrees (for looking at a robot from all sides). */ +EMSCRIPTEN_KEEPALIVE void d2web_test_orient(int objnum, int pitch, int heading, int bank) +{ + vms_angvec a; + if (objnum < 0 || objnum > Highest_object_index) + return; + a.p = pitch * 65536 / 360; + a.h = heading * 65536 / 360; + a.b = bank * 65536 / 360; + vm_angles_2_matrix(&Objects[objnum].orient, &a); + vm_vec_zero(&Objects[objnum].mtype.phys_info.rotvel); +} + +/* Sets the reticle type (2 = none, for clean screenshots). */ +EMSCRIPTEN_KEEPALIVE void d2web_test_reticle(int type) +{ + PlayerCfg.ReticleType = type; +} + +/* Turns an object about its own up axis by heading degrees, then about its right axis by pitch. */ +EMSCRIPTEN_KEEPALIVE void d2web_test_turn(int objnum, int heading, int pitch) +{ + vms_matrix *m; + vms_vector f, r, u; + fix s, c; + if (objnum < 0 || objnum > Highest_object_index) + return; + m = &Objects[objnum].orient; + fix_sincos(heading * 65536 / 360, &s, &c); + vm_vec_copy_scale(&f, &m->fvec, c); + vm_vec_scale_add2(&f, &m->rvec, s); + vm_vec_copy_scale(&r, &m->rvec, c); + vm_vec_scale_add2(&r, &m->fvec, -s); + m->fvec = f; + m->rvec = r; + fix_sincos(pitch * 65536 / 360, &s, &c); + vm_vec_copy_scale(&f, &m->fvec, c); + vm_vec_scale_add2(&f, &m->uvec, -s); + vm_vec_copy_scale(&u, &m->uvec, c); + vm_vec_scale_add2(&u, &m->fvec, s); + m->fvec = f; + m->uvec = u; + vm_vec_zero(&Objects[objnum].mtype.phys_info.rotvel); +} + +/* The game model number robot type id uses. */ +EMSCRIPTEN_KEEPALIVE int d2web_test_robot_model(int id) +{ + return id >= 0 && id < N_robot_types ? Robot_info[id].model_num : -1; +} + +/* How many robots of type id the level has now. */ +EMSCRIPTEN_KEEPALIVE int d2web_test_count_robots(int id) +{ + int i, n = 0; + for (i = 0; i <= Highest_object_index; i++) + if (Objects[i].type == OBJ_ROBOT && Objects[i].id == id) + n++; + return n; +} diff --git a/d2/arch/web/web.h b/d2/arch/web/web.h new file mode 100644 index 0000000..b2f9617 --- /dev/null +++ b/d2/arch/web/web.h @@ -0,0 +1,105 @@ +/* Browser (Emscripten) glue for D2X-Redux. Implemented in library_d2web.js. */ +#ifndef _D2WEB_H +#define _D2WEB_H + +#ifdef __EMSCRIPTEN__ +#ifdef __cplusplus +extern "C" { +#endif + +/* Yield to the browser until the next display refresh (requestAnimationFrame). */ +void d2web_frame_wait(void); + +/* CD audio emulation: the page rips the Descent II disc image into per-track audio. */ +int d2web_cd_numtracks(void); +int d2web_cd_play(int first, int last); +void d2web_cd_stop(void); +void d2web_cd_pause(void); +void d2web_cd_resume(void); +int d2web_cd_status(void); /* 0 stopped, 1 playing, 2 paused */ +int d2web_cd_track(void); +void d2web_cd_volume(int volume); /* 0..8 */ + +/* MIDI music: the page plays standard MIDI data through a General MIDI soft synth. */ +int d2web_midi_play(const unsigned char *data, int len, int loop); +void d2web_midi_stop(void); +void d2web_midi_pause(void); +void d2web_midi_resume(void); +void d2web_midi_pause_resume(void); +void d2web_midi_volume(int volume); /* 0..8 */ +/* Converts a Descent .hmp song to MIDI and plays it (web.c). */ +int d2web_play_hmp(const char *filename, int loop); + +/* Music folder (the "jukebox" music type): the player's own music files, stored by the page. + * songnum is a SONG_* number; level music steps through the folder's level playlist. */ +int d2web_music_has(int songnum); /* -1: any music at all; SONG_FIRST_LEVEL_SONG: level music */ +int d2web_music_song(int songnum, int repeat, int then_credits); +int d2web_music_level(int levelsong, int offset); /* levelsong = level number - 1 */ +void d2web_music_stop(void); +void d2web_music_pause(void); +void d2web_music_resume(void); +void d2web_music_pause_resume(void); +void d2web_music_volume(int volume); /* 0..8 */ + +/* Touch controls: the page's on-screen stick, look area and buttons. Fills out[6]: stick + * x, y (-1..1, y down), look x, y (turn time since the last frame), held buttons and the + * buttons tapped since the last frame (reported once per frame). Returns 0 without touch. */ +int d2web_touch_read(float *out); +#define D2WEB_TOUCH_FIRE 1 +#define D2WEB_TOUCH_MISSILE 2 +#define D2WEB_TOUCH_UP 4 +#define D2WEB_TOUCH_DOWN 8 +#define D2WEB_TOUCH_BOOST 16 +#define D2WEB_TOUCH_FLARE 32 +#define D2WEB_TOUCH_BOMB 64 +#define D2WEB_TOUCH_WEAPON 128 +#define D2WEB_TOUCH_SECONDARY 256 +#define D2WEB_TOUCH_MAP 512 + +/* The page's look options (Module.d2options; on unless set false). */ +int d2web_option(int which); +#define D2WEB_OPTION_SHARP 0 /* sharp upscaling of movies and smooth text */ +#define D2WEB_OPTION_EFFECTS 1 /* light halos, smoke and sparks */ +#define D2WEB_OPTION_GLOW 2 /* glow (bloom) and the filmic tone curve */ +#define D2WEB_OPTION_LIGHTING 3 /* per-pixel lights, bumpy and shiny surfaces */ +#define D2WEB_OPTION_AO 4 /* ambient occlusion */ +#define D2WEB_OPTION_HAZE 5 /* light in the air */ +#define D2WEB_OPTION_SURFACES 6 /* flowing lava, rippling water, shimmering force fields */ +#define D2WEB_OPTION_EXPLOSIONS 7 /* fireballs, shockwaves, debris and scorch marks */ +#define D2WEB_OPTION_REFLECTIONS 8 /* reflections on smooth surfaces */ +#define D2WEB_OPTION_ULTRA 9 /* the sharper (4x D2X-XL) texture set, where loaded */ +#define D2WEB_OPTION_INVERT_PITCH 10 /* reverse up/down for every control (mouse, gamepad, keys, touch) */ + +/* A look constant, def unless Module.d2tune[i] overrides it (for tuning while it runs). */ +float d2web_tune(int i, float def); + +/* WebGL version of the context (1 or 2). */ +int d2web_gl_version(void); + +/* Give a shader its GLSL ES 3.00 source unchanged (the GL emulation rewrites GLSL 1.10). */ +void d2web_shader_source(unsigned int shader, const char *src); + +/* True once after a gamepad was connected or removed. */ +int d2web_gamepads_changed(void); + +/* Persist the player/save directory to IndexedDB (debounced). */ +void d2web_sync_saves(void); + +/* The player chose Quit: flush saves and hand control back to the page. */ +void d2web_quit(void); + +/* Around an intro, movie or briefing (they nest): the page shows a Skip button while one is up. + d2web_cutscene_skipping() is true once the button was pressed, until the outermost one ends. */ +void d2web_cutscene(int begin); +int d2web_cutscene_skipping(void); + +/* Puts a robot of type id just past each of the nearest doors the ship can open from where it starts, facing the + door and holding its place (Vertigo Level 1 shows off the remodelled Medium Lifter this way). Returns how many. */ +int d2web_place_robots_past_first_doors(int id); + +#ifdef __cplusplus +} +#endif +#endif + +#endif diff --git a/d2/arch/web/web_config.h b/d2/arch/web/web_config.h new file mode 100644 index 0000000..b33cc74 --- /dev/null +++ b/d2/arch/web/web_config.h @@ -0,0 +1,104 @@ +/* Forced-include config for the browser build. */ +#define SHAREPATH "/usr/share/games/d2x-redux" +#include +#ifndef SDL_arraysize +#define SDL_arraysize(a) (sizeof(a) / sizeof((a)[0])) +#endif +/* SDL 1.2 names missing from Emscripten's SDL 1.3-style headers */ +#define SDL_GL_SWAP_CONTROL 16 +#define SDLK_WORLD_0 0 +#define SDLK_WORLD_1 0 +#define SDLK_WORLD_2 0 +#define SDLK_WORLD_3 0 +#define SDLK_WORLD_4 0 +#define SDLK_WORLD_5 0 +#define SDLK_WORLD_6 0 +#define SDLK_WORLD_7 0 +#define SDLK_WORLD_8 0 +#define SDLK_WORLD_9 0 +#define SDLK_WORLD_10 0 +#define SDLK_WORLD_11 0 +#define SDLK_WORLD_12 0 +#define SDLK_WORLD_13 0 +#define SDLK_WORLD_14 0 +#define SDLK_WORLD_15 0 +#define SDLK_WORLD_16 0 +#define SDLK_WORLD_17 0 +#define SDLK_WORLD_18 0 +#define SDLK_WORLD_19 0 +#define SDLK_WORLD_20 0 +#define SDLK_WORLD_21 0 +#define SDLK_WORLD_22 0 +#define SDLK_WORLD_23 0 +#define SDLK_WORLD_24 0 +#define SDLK_WORLD_25 0 +#define SDLK_WORLD_26 0 +#define SDLK_WORLD_27 0 +#define SDLK_WORLD_28 0 +#define SDLK_WORLD_29 0 +#define SDLK_WORLD_30 0 +#define SDLK_WORLD_31 0 +#define SDLK_WORLD_32 0 +#define SDLK_WORLD_33 0 +#define SDLK_WORLD_34 0 +#define SDLK_WORLD_35 0 +#define SDLK_WORLD_36 0 +#define SDLK_WORLD_37 0 +#define SDLK_WORLD_38 0 +#define SDLK_WORLD_39 0 +#define SDLK_WORLD_40 0 +#define SDLK_WORLD_41 0 +#define SDLK_WORLD_42 0 +#define SDLK_WORLD_43 0 +#define SDLK_WORLD_44 0 +#define SDLK_WORLD_45 0 +#define SDLK_WORLD_46 0 +#define SDLK_WORLD_47 0 +#define SDLK_WORLD_48 0 +#define SDLK_WORLD_49 0 +#define SDLK_WORLD_50 0 +#define SDLK_WORLD_51 0 +#define SDLK_WORLD_52 0 +#define SDLK_WORLD_53 0 +#define SDLK_WORLD_54 0 +#define SDLK_WORLD_55 0 +#define SDLK_WORLD_56 0 +#define SDLK_WORLD_57 0 +#define SDLK_WORLD_58 0 +#define SDLK_WORLD_59 0 +#define SDLK_WORLD_60 0 +#define SDLK_WORLD_61 0 +#define SDLK_WORLD_62 0 +#define SDLK_WORLD_63 0 +#define SDLK_WORLD_64 0 +#define SDLK_WORLD_65 0 +#define SDLK_WORLD_66 0 +#define SDLK_WORLD_67 0 +#define SDLK_WORLD_68 0 +#define SDLK_WORLD_69 0 +#define SDLK_WORLD_70 0 +#define SDLK_WORLD_71 0 +#define SDLK_WORLD_72 0 +#define SDLK_WORLD_73 0 +#define SDLK_WORLD_74 0 +#define SDLK_WORLD_75 0 +#define SDLK_WORLD_76 0 +#define SDLK_WORLD_77 0 +#define SDLK_WORLD_78 0 +#define SDLK_WORLD_79 0 +#define SDLK_WORLD_80 0 +#define SDLK_WORLD_81 0 +#define SDLK_WORLD_82 0 +#define SDLK_WORLD_83 0 +#define SDLK_WORLD_84 0 +#define SDLK_WORLD_85 0 +#define SDLK_WORLD_86 0 +#define SDLK_WORLD_87 0 +#define SDLK_WORLD_88 0 +#define SDLK_WORLD_89 0 +#define SDLK_WORLD_90 0 +#define SDLK_WORLD_91 0 +#define SDLK_WORLD_92 0 +#define SDLK_WORLD_93 0 +#define SDLK_WORLD_94 0 +#define SDLK_WORLD_95 0 diff --git a/d2/include/args.h b/d2/include/args.h index 8983f5c..83d4b78 100644 --- a/d2/include/args.h +++ b/d2/include/args.h @@ -50,6 +50,7 @@ typedef struct Arg int SysNoBorders; int SysAutoDemo; int SysNoMovies; + int SysNoTitles; int CtlNoCursor; int CtlNoMouse; int CtlNoJoystick; diff --git a/d2/include/ogl_init.h b/d2/include/ogl_init.h index af0b258..99b034b 100644 --- a/d2/include/ogl_init.h +++ b/d2/include/ogl_init.h @@ -11,7 +11,13 @@ #include #endif +#ifndef __EMSCRIPTEN__ #include +#else +#define GL_GLEXT_PROTOTYPES +#include +#include +#endif #ifdef _WIN32 #include "loadgl.h" int ogl_init_load_library(void); @@ -64,6 +70,7 @@ typedef struct _ogl_texture { int wrapstate; unsigned long numrend; int is_png; + GLuint nmap, gmap, emap; // material maps beside it, for the per-pixel walls (0: none) } ogl_texture; extern ogl_texture* ogl_get_free_texture(); @@ -79,6 +86,25 @@ extern int gl_initialized; extern int active_texture_unit; extern GLfloat ogl_maxanisotropy; +// a bitmap's palette indices, RLE decoded (into a buffer shared with the next call) +unsigned char *ogl_bitmap_indices(grs_bitmap *bm); + +// ogl_shader.c: sharp upscaling of movies and smooth-edged font glyphs +int ogl_sharp_enabled(void); +int ogl_upscale_begin(ogl_texture *tex, float u1, float v1, float u2, float v2, float scale, int movie); +int ogl_glyph_begin(float scale); +void ogl_shader_end(void); +unsigned int ogl_program3(const char *vs, const char *defines, const char *fs); +int ogl_sprite_begin(ogl_texture *tex, float brightness, int additive); // ogl_shader_end() after +extern float ogl_sprite_glow; // render_object: > 0 draws the next sprites soft-edged, this bright + +// post-processing of the 3D view (ogl_post.c) +int ogl_post_begin(void); +void ogl_post_end(void); +int ogl_post_active(void); +void ogl_post_origin(int *x, int *y); +int ogl_post_history(unsigned *color, unsigned *depth, float *reproj, float *scale); + void ogl_setActiveTexture(int t); int ogl_init_window(int x, int y);//create a window/switch modes/etc diff --git a/d2/include/pngfile.h b/d2/include/pngfile.h index 3c03242..1acb53b 100644 --- a/d2/include/pngfile.h +++ b/d2/include/pngfile.h @@ -17,6 +17,8 @@ typedef struct _png_data { } png_data; extern int read_png(const char *filename, png_data *pdata); +// a JPEG (or other image stb_image reads) as 8-bit RGBA; alpha is set when the file has it +extern int read_image_stb(const char *filename, png_data *pdata); extern int write_png(const char *filename, png_data *pdata); #endif diff --git a/d2/include/xmodel.h b/d2/include/xmodel.h index 2bc25cf..42c25a4 100644 --- a/d2/include/xmodel.h +++ b/d2/include/xmodel.h @@ -22,6 +22,8 @@ void xmodel_free_all(); void xmodel_load_gl_all(); void xmodel_free_gl_all(); int xmodel_show_if_loaded(enum xmodel_type mt, int modelnum, vms_vector *pos, vms_matrix *orient, int mpcolor, g3s_lrgb *light); +int xmodel_show_polyobj(int modelnum, vms_vector *pos, vms_matrix *orient, vms_angvec *anim_angles, int flags, + int mpcolor, g3s_lrgb *light); int xmodel_exists(enum xmodel_type mt, int modelnum); #ifdef __cplusplus diff --git a/d2/libmve/mveplay.c b/d2/libmve/mveplay.c index bfa69f6..22d5043 100644 --- a/d2/libmve/mveplay.c +++ b/d2/libmve/mveplay.c @@ -19,6 +19,9 @@ #endif // _WIN32 #include +#ifdef __EMSCRIPTEN__ +#include +#endif #ifdef USE_SDLMIXER #include #endif @@ -191,6 +194,40 @@ static void timer_start(void) timer_started=1; } +#ifdef __EMSCRIPTEN__ +// The browser can't block mid-frame (it would show a half-drawn screen), so instead of +// sleeping until the next movie frame is due we report whether it is due yet. +static int timer_frame_due(void) +{ + struct timeval tv; + long long now, expire; + + if (!timer_started) + return 1; + gettimeofday(&tv, NULL); + now = (long long)tv.tv_sec * 1000000 + tv.tv_usec; + expire = (long long)timer_expire.tv_sec * 1000000 + timer_expire.tv_usec; + if (now < expire) + return 0; + if (now - expire > 1000000) // fell far behind (tab was hidden): don't fast-forward + timer_start(); + return 1; +} + +static void timer_advance(void) +{ + int nsec; + + timer_expire.tv_usec += micro_frame_delay; + if (timer_expire.tv_usec > 1000000) + { + nsec = timer_expire.tv_usec / 1000000; + timer_expire.tv_sec += nsec; + timer_expire.tv_usec -= nsec*1000000; + } +} +#endif + static void do_timer_wait(void) { int nsec=0; @@ -216,6 +253,8 @@ static void do_timer_wait(void) Sleep(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); #elif defined(macintosh) Delay(ts.tv_sec * 1000 + ts.tv_nsec / 1000000, NULL); +#elif defined(__EMSCRIPTEN__) + emscripten_sleep(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); #else if (nanosleep(&ts, NULL) == -1 && errno == EINTR) exit(1); @@ -745,6 +784,16 @@ int MVE_rmStepMovie() if (!timer_started) timer_start(); +#ifdef __EMSCRIPTEN__ + if (init_timer && !timer_frame_due()) + { + // next movie frame isn't due: redraw the current one for this display frame + if (g_vBackBuf1 && video_initialized) + mve_showframe(g_vBackBuf1, g_destX, g_destY, g_width, g_height, g_screenWidth, g_screenHeight); + return 0; + } +#endif + while (cont && !g_frameUpdated) // make a "step" be a frame, not a chunk... cont = mve_play_next_chunk(mve); g_frameUpdated = 0; @@ -757,7 +806,12 @@ int MVE_rmStepMovie() init_timer = 1; } +#ifdef __EMSCRIPTEN__ + if (init_timer) + timer_advance(); +#else do_timer_wait(); +#endif return 0; } diff --git a/d2/main/collide.c b/d2/main/collide.c index fdb2e78..4186519 100644 --- a/d2/main/collide.c +++ b/d2/main/collide.c @@ -24,6 +24,7 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "rle.h" #include "inferno.h" #include "game.h" +#include "fx.h" #include "gr.h" #include "stdlib.h" #include "timer.h" @@ -824,6 +825,7 @@ void collide_weapon_and_wall( object * weapon, fix hitspeed, short hitseg, short digi_link_sound_to_pos( Weapon_info[weapon->id].wall_hit_sound,weapon->segnum, 0, &weapon->pos, 0, volume ); if ( Weapon_info[weapon->id].wall_hit_vclip > -1 ) { + fx_impact(weapon, hitseg, hitwall, hitpt); if ( Weapon_info[weapon->id].damage_radius ) explode_badass_weapon(weapon,hitpt); else @@ -1656,6 +1658,7 @@ void collide_robot_and_weapon( object * robot, object * weapon, vms_vector *coll multi_robot_request_change(robot, Objects[weapon->ctype.laser_info.parent_num].id); #endif + fx_hit(weapon, collision_point); if ( Robot_info[robot->id].exp1_vclip_num > -1 ) expl_obj = object_create_explosion( weapon->segnum, collision_point, (robot->size/2*3)/4, Robot_info[robot->id].exp1_vclip_num ); else if ( Weapon_info[weapon->id].robot_hit_vclip > -1 ) diff --git a/d2/main/fireball.c b/d2/main/fireball.c index fe9b0d1..4cbbd67 100644 --- a/d2/main/fireball.c +++ b/d2/main/fireball.c @@ -31,6 +31,7 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "object.h" #include "vclip.h" #include "game.h" +#include "fx.h" #include "polyobj.h" #include "sounds.h" #include "player.h" @@ -1355,6 +1356,7 @@ void do_explosion_sequence(object *obj) expl_obj = object_create_badass_explosion( del_obj, del_obj->segnum, spawn_pos, fixmul(del_obj->size, EXPLOSION_SCALE), vclip_num, F1_0*Robot_info[del_obj->id].badass, i2f(4)*Robot_info[del_obj->id].badass, i2f(35)*Robot_info[del_obj->id].badass, -1 ); else expl_obj = object_create_explosion( del_obj->segnum, spawn_pos, fixmul(del_obj->size, EXPLOSION_SCALE), vclip_num ); + fx_explosion(spawn_pos, del_obj->segnum, fixmul(del_obj->size, EXPLOSION_SCALE)); if ((del_obj->contains_count > 0) && !(Game_mode & GM_MULTI)) { // Multiplayer handled outside of this code!! // If dropping a weapon that the player has, drop energy instead, unless it's vulcan, in which case drop vulcan ammo. diff --git a/d2/main/fx.c b/d2/main/fx.c new file mode 100644 index 0000000..a7d5009 --- /dev/null +++ b/d2/main/fx.c @@ -0,0 +1,1129 @@ +/* + * Light halos, smoke and sparks (browser edition). + * + * Halos glow over the lamps of the mine's light textures, placed where the lamp's bright + * pixels are on each wall the renderer draws, and go out with the light. Missiles leave smoke + * trails, damaged robots smoke harder the closer they are to dying, and shots and explosions + * throw sparks. Purely visual: nothing here feeds back into the game, and it has its own + * random numbers so the game's (and demos') stay as they were. The page's Effects option + * (Module.d2options.effects) turns it off. + */ + +#define GL_GLEXT_PROTOTYPES +#include +#include +#include +#include + +#include "fx.h" +#include "segment.h" +#include "gameseg.h" +#include "game.h" +#include "gameseq.h" +#include "robot.h" +#include "weapon.h" +#include "laser.h" +#include "player.h" +#include "bm.h" +#include "textures.h" +#include "vclip.h" +#include "piggy.h" +#include "palette.h" +#include "render.h" +#include "../3d/globvars.h" +#include "ogl_init.h" +#include "internal.h" +#ifdef __EMSCRIPTEN__ +#include "../arch/web/web.h" +#endif + +#ifdef __EMSCRIPTEN__ +#include +// for tests: lit sides seen, halos drawn, particles, vertices in the last 3D view +static int fx_stats[4]; +EMSCRIPTEN_KEEPALIVE int *d2web_test_fx_stats(void) { return fx_stats; } +#define STAT(i, v) (fx_stats[i] = (v)) +#else +#define STAT(i, v) +#endif + +static int fx_enabled(void) +{ +#ifdef __EMSCRIPTEN__ + return d2web_option(D2WEB_OPTION_EFFECTS); +#else + return 0; +#endif +} + +// fireballs, shockwaves, debris and scorch marks +static int boom_enabled(void) +{ +#ifdef __EMSCRIPTEN__ + return d2web_option(D2WEB_OPTION_EXPLOSIONS); +#else + return 0; +#endif +} + +static unsigned fx_seed = 0x2545f491; +static float frand(void) // 0..1 +{ + fx_seed = fx_seed * 1664525u + 1013904223u; + return (fx_seed >> 8) * (1.0f / 16777216.0f); +} + +static float dot(const float *a, const float *b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } +static float len(const float *a) { return sqrtf(dot(a, a)); } +static void fv(const vms_vector *v, float *o) { o[0] = f2fl(v->x); o[1] = f2fl(v->y); o[2] = f2fl(v->z); } +static void madd(float *o, const float *a, const float *b, float s) { for (int k = 0; k < 3; k++) o[k] = a[k] + b[k] * s; } +static float smooth(float e0, float e1, float x) +{ + float t = (x - e0) / (e1 - e0); + t = t < 0 ? 0 : t > 1 ? 1 : t; + return t * t * (3 - 2 * t); +} + +static void rand_dir(float *d) +{ + float l2; + do { + for (int k = 0; k < 3; k++) + d[k] = frand() * 2 - 1; + l2 = dot(d, d); + } while (l2 > 1 || l2 < 0.01f); + l2 = 1 / sqrtf(l2); + for (int k = 0; k < 3; k++) + d[k] *= l2; +} + +// --------------------------------------------------------------------------------------- +// Particles + +enum { FX_SMOKE, FX_SPARK, FX_GLOW, FX_FIRE, FX_RING, FX_DEBRIS }; + +typedef struct particle { + float pos[3], vel[3]; + float age, life; // seconds + float size, grow; // half size in world units, growth per second + float angle, spin; + float drag; + float rgb[3], alpha; + float acc; // debris: time toward its next smoke puff + unsigned char kind; +} particle; + +#define MAX_PARTICLES 2048 +static particle particles[MAX_PARTICLES]; +static int n_particles; + +static particle *spawn(int kind) +{ + particle *p = n_particles < MAX_PARTICLES ? &particles[n_particles++] : &particles[(int)(frand() * (MAX_PARTICLES - 1))]; + memset(p, 0, sizeof(*p)); + p->kind = kind; + p->alpha = 1; + return p; +} + +// how lit the segment is, for smoke (which the game's lighting doesn't reach) +static float seg_light(int segnum) +{ + float l = segnum >= 0 && segnum <= Highest_segment_index ? f2fl(Segments[segnum].static_light) : 0.6f; + return l < 0.25f ? 0.25f : l > 1 ? 1 : l; +} + +static void smoke(const float *pos, const float *vel, float size, float grow, float life, float grey, float alpha, int segnum) +{ + particle *p = spawn(FX_SMOKE); + float l = grey * (0.45f + 0.55f * seg_light(segnum)); + memcpy(p->pos, pos, sizeof(p->pos)); + memcpy(p->vel, vel, sizeof(p->vel)); + p->size = size; + p->grow = grow; + p->life = life; + p->angle = frand() * 6.283f; + p->spin = (frand() - 0.5f) * 1.2f; + p->drag = 1.2f; + p->rgb[0] = p->rgb[1] = p->rgb[2] = l; + p->rgb[2] *= 1.04f; + p->alpha = alpha; +} + +// sparks fly out of pos, off the surface with this normal when there is one +static void sparks(const float *pos, const float *normal, int n, const float *rgb, float speed, float life) +{ + for (int i = 0; i < n; i++) { + particle *p = spawn(FX_SPARK); + float d[3]; + rand_dir(d); + if (normal) { + float s = dot(d, normal); + if (s < 0) + madd(d, d, normal, -2 * s); + madd(d, d, normal, 0.5f); + s = 1 / len(d); + for (int k = 0; k < 3; k++) + d[k] *= s; + madd(p->pos, pos, normal, 0.15f); + } else + memcpy(p->pos, pos, sizeof(p->pos)); + for (int k = 0; k < 3; k++) + p->vel[k] = d[k] * speed * (0.35f + 0.65f * frand()); + p->life = life * (0.45f + 0.55f * frand()); + p->size = 0.12f + 0.08f * frand(); + p->drag = 2.5f; + memcpy(p->rgb, rgb, sizeof(p->rgb)); + } +} + +static void glow(const float *pos, float size, float life, const float *rgb, float alpha) +{ + particle *p = spawn(FX_GLOW); + memcpy(p->pos, pos, sizeof(p->pos)); + p->size = size; + p->life = life; + memcpy(p->rgb, rgb, sizeof(p->rgb)); + p->alpha = alpha; +} + +// the color a weapon's shots glow in (as the colored dynamic light finds it), made hot +static void weapon_color(object *weapon, float *rgb) +{ + weapon_info *wi = &Weapon_info[weapon->id]; + grs_bitmap *bm = NULL; + float m; + if (wi->render_type == WEAPON_RENDER_LASER || wi->render_type == WEAPON_RENDER_BLOB) + bm = &GameBitmaps[wi->bitmap.index]; + else if (wi->render_type == WEAPON_RENDER_VCLIP && wi->weapon_vclip >= 0) + bm = &GameBitmaps[Vclip[wi->weapon_vclip].frames[0].index]; + rgb[0] = 1, rgb[1] = 0.7f, rgb[2] = 0.35f; // matter: hot metal + if (bm && !wi->matter) { + float c[3] = { (float)bm->avg_color_rgb[0], (float)bm->avg_color_rgb[1], (float)bm->avg_color_rgb[2] }; + m = c[0] > c[1] ? c[0] : c[1]; + m = m > c[2] ? m : c[2]; + if (m > 0) + for (int k = 0; k < 3; k++) + rgb[k] = 0.35f + 0.65f * c[k] / m; // toward white: sparks are hot + } +} + +// --------------------------------------------------------------------------------------- +// Explosions: layered fireballs that cool from white-hot to red, a shockwave, glowing debris +// that trails smoke, and scorch marks that stay on the walls a while + +static void fire_puffs(const float *p, float s, int n, float life) +{ + for (int i = 0; i < n; i++) { + particle *q = spawn(FX_FIRE); + float d[3]; + rand_dir(d); + madd(q->pos, p, d, s * 0.35f * frand()); + for (int k = 0; k < 3; k++) + q->vel[k] = d[k] * s * (0.6f + 0.9f * frand()); + q->drag = 3.0f; + q->size = s * (0.12f + 0.1f * frand()); + q->grow = s * (0.5f + 0.35f * frand()); + q->life = life * (0.65f + 0.5f * frand()); + q->angle = frand() * 6.283f; + q->spin = (frand() - 0.5f) * 2.5f; + } +} + +static void shockwave(const float *p, float s) +{ + particle *q = spawn(FX_RING); + memcpy(q->pos, p, sizeof(q->pos)); + q->size = s * 0.3f; + q->grow = s * 9.0f; + q->life = 0.38f; +} + +static void debris(const float *p, float s, int n) +{ + for (int i = 0; i < n; i++) { + particle *q = spawn(FX_DEBRIS); + float d[3], speed = (s * 4 + 14) * (0.35f + 0.65f * frand()); + rand_dir(d); + memcpy(q->pos, p, sizeof(q->pos)); + for (int k = 0; k < 3; k++) + q->vel[k] = d[k] * speed; + q->drag = 0.7f; + q->size = (0.12f + 0.25f * frand()) * (s < 3 ? 1 : s / 3 > 2.5f ? 2.5f : s / 3); + q->life = 1.4f + frand() * 1.2f; + q->angle = frand() * 6.283f; + q->spin = (frand() - 0.5f) * 14; + } +} + +#define MAX_DECALS 96 +typedef struct decal { + float pos[3], t1[3], t2[3]; // center, half axes along the wall + float age, life, alpha, ember; +} decal; +static decal decals[MAX_DECALS]; +static int n_decals, next_decal; + +static void scorch(int segnum, int sidenum, const float *p, float size, float alpha, float life, float ember) +{ + side *sd = &Segments[segnum].sides[sidenum]; + float n[3], a[3] = { 0, 0, 0 }, t1[3], t2[3], l, c, sn, ang = frand() * 6.283f; + decal *d; + if (sd->wall_num != -1) // doors and such move: the mark would float + return; + fv(&sd->normals[0], n); + a[fabsf(n[0]) < 0.6f ? 0 : 1] = 1; + t1[0] = n[1] * a[2] - n[2] * a[1]; + t1[1] = n[2] * a[0] - n[0] * a[2]; + t1[2] = n[0] * a[1] - n[1] * a[0]; + l = 1 / len(t1); + for (int k = 0; k < 3; k++) + t1[k] *= l; + t2[0] = n[1] * t1[2] - n[2] * t1[1]; + t2[1] = n[2] * t1[0] - n[0] * t1[2]; + t2[2] = n[0] * t1[1] - n[1] * t1[0]; + d = n_decals < MAX_DECALS ? &decals[n_decals++] : &decals[next_decal++ % MAX_DECALS]; + c = cosf(ang) * size; + sn = sinf(ang) * size; + for (int k = 0; k < 3; k++) { + d->t1[k] = t1[k] * c + t2[k] * sn; + d->t2[k] = t2[k] * c - t1[k] * sn; + } + madd(d->pos, p, n, 0.04f); + d->age = 0; + d->life = life; + d->alpha = alpha; + d->ember = ember; +} + +// a blast of size s (the exploding thing's radius) +static void blast(const float *p, float s) +{ + float flash[3] = { 2.2f, 1.7f, 1.1f }; + int n = (int)(4 + s * 0.35f); + fire_puffs(p, s, n > 10 ? 10 : n, 0.75f + s * 0.02f); + shockwave(p, s); + n = (int)(5 + s * 0.6f); + debris(p, s, n > 14 ? 14 : n); + glow(p, s * 1.6f, 0.16f, flash, 0.45f); +} + +void fx_impact(object *weapon, int segnum, int sidenum, vms_vector *pos) +{ + weapon_info *wi = &Weapon_info[weapon->id]; + float p[3], n[3], rgb[3]; + if (boom_enabled()) { + fv(pos, p); + fv(&Segments[segnum].sides[sidenum].normals[0], n); + if (wi->damage_radius) { + float s = f2fl(wi->impact_size), at[3]; + s = s < 2.5f ? 2.5f : s; + madd(at, p, n, s * 0.3f); + blast(at, s); + scorch(segnum, sidenum, p, s * 0.9f, 0.85f, 40, 1); + } else if (wi->matter) + scorch(segnum, sidenum, p, 0.4f, 0.7f, 20, 0); + else + scorch(segnum, sidenum, p, 0.75f, 0.45f, 12, 0.6f); + } + if (!fx_enabled()) + return; + fv(pos, p); + fv(&Segments[segnum].sides[sidenum].normals[0], n); + weapon_color(weapon, rgb); + if (wi->damage_radius) { // missiles + float hot[3] = { 1, 0.75f, 0.4f }, at[3]; + sparks(p, n, 28, hot, 38, 1.0f); + for (int i = 0; i < 4; i++) { + float d[3]; + rand_dir(d); + madd(at, p, n, 1.5f); + madd(d, d, n, 1.2f); + for (int k = 0; k < 3; k++) + d[k] *= 1.5f; + smoke(at, d, 2.2f, 2.4f, 2.4f + frand(), 0.28f, 0.5f, segnum); + } + } else if (wi->matter) // vulcan, gauss: metal sparks + sparks(p, n, 7, rgb, 32, 0.4f); + else { + sparks(p, n, 10, rgb, 26, 0.45f); + glow(p, 1.6f, 0.18f, rgb, 0.5f); + } +} + +void fx_hit(object *weapon, vms_vector *pos) +{ + float p[3], rgb[3]; + fv(pos, p); + if (boom_enabled() && Weapon_info[weapon->id].damage_radius) { + float s = f2fl(Weapon_info[weapon->id].impact_size); + blast(p, s < 2.5f ? 2.5f : s); + } + if (!fx_enabled()) + return; + weapon_color(weapon, rgb); + sparks(p, NULL, Weapon_info[weapon->id].damage_radius ? 16 : 6, rgb, 24, 0.35f); +} + +void fx_explosion(vms_vector *pos, int segnum, fix size) +{ + float p[3], s = f2fl(size), hot[3] = { 1, 0.7f, 0.35f }; + int n = (int)(18 + s * 2.5f); + fv(pos, p); + if (boom_enabled()) + blast(p, s); + if (!fx_enabled()) + return; + sparks(p, NULL, n > 60 ? 60 : n, hot, 28 + s * 3, 1.1f); + n = (int)(3 + s / 3); + for (int i = 0; i < (n > 9 ? 9 : n); i++) { + float d[3], at[3]; + rand_dir(d); + madd(at, p, d, s * 0.25f); + for (int k = 0; k < 3; k++) + d[k] *= s * 0.35f; + smoke(at, d, s * 0.35f, s * 0.3f, 2.6f + frand() * 1.2f, 0.32f, 0.6f, segnum); + } +} + +// trails: puffs every TRAIL_STEP units along each missile's path +#define TRAIL_STEP 1.1f +static int trail_sig[MAX_OBJECTS]; +static float trail_last[MAX_OBJECTS][3], trail_acc[MAX_OBJECTS]; +static float smoke_acc[MAX_OBJECTS]; +static int smoke_sig[MAX_OBJECTS]; + +static int is_missile(object *obj) +{ + weapon_info *wi = &Weapon_info[obj->id]; + if (!wi->matter || wi->render_type != WEAPON_RENDER_POLYMODEL) + return 0; + switch (obj->id) { + case PROXIMITY_ID: case SUPERPROX_ID: case PMINE_ID: case ROBOT_SUPERPROX_ID: + return 0; + } + return 1; +} + +static void missile_trail(object *obj, int objnum) +{ + float tail[3], back[3], d[3], l; + int n = 0; + fv(&obj->pos, tail); + fv(&obj->orient.fvec, back); + madd(tail, tail, back, -f2fl(obj->size) * 0.8f); + if (trail_sig[objnum] != obj->signature) { + trail_sig[objnum] = obj->signature; + memcpy(trail_last[objnum], tail, sizeof(tail)); + trail_acc[objnum] = TRAIL_STEP; + return; + } + for (int k = 0; k < 3; k++) + d[k] = tail[k] - trail_last[objnum][k]; + l = len(d); + for (float at = TRAIL_STEP - trail_acc[objnum]; at <= l && n < 16; at += TRAIL_STEP, n++) { + float p[3], v[3], hot[3] = { 1, 0.6f, 0.25f }; + madd(p, trail_last[objnum], d, at / l); + rand_dir(v); + for (int k = 0; k < 3; k++) + v[k] *= 0.5f; + smoke(p, v, 0.5f, 1.6f, 1.1f + frand() * 0.5f, 0.85f, 0.5f, obj->segnum); + if (!n) + glow(p, 1.0f, 0.12f, hot, 0.6f); + } + trail_acc[objnum] = fmodf(trail_acc[objnum] + l, TRAIL_STEP); + memcpy(trail_last[objnum], tail, sizeof(tail)); +} + +// damaged robots (and other players' ships) smoke, harder the closer they are to dying +static void damage_smoke(object *obj, int objnum, float dt) +{ + fix full = obj->type == OBJ_ROBOT ? Robot_info[obj->id].strength : i2f(100); + float frac, rate, pos[3], vel[3], view[3], s = f2fl(obj->size); + if (full <= 0 || obj->shields <= 0 || obj->shields >= full / 2) + return; + if (obj->type == OBJ_ROBOT ? Robot_info[obj->id].cloak_type : (Players[obj->id].flags & PLAYER_FLAGS_CLOAKED)) + return; + fv(&obj->pos, pos); + fv(&View_position, view); + for (int k = 0; k < 3; k++) + view[k] -= pos[k]; + if (len(view) > 250) + return; + if (smoke_sig[objnum] != obj->signature) { + smoke_sig[objnum] = obj->signature; + smoke_acc[objnum] = 0; + } + frac = f2fl(obj->shields) / f2fl(full); // below 0.5 + rate = 2 + (0.5f - frac) * 10; // puffs per second + smoke_acc[objnum] += dt * rate; + fv(&obj->mtype.phys_info.velocity, vel); + while (smoke_acc[objnum] >= 1) { + float p[3], v[3]; + smoke_acc[objnum] -= 1; + rand_dir(v); + madd(p, pos, v, s * 0.3f); + for (int k = 0; k < 3; k++) + v[k] = v[k] * 0.9f + vel[k] * 0.25f; + smoke(p, v, s * 0.22f, s * 0.35f, 1.4f + frand() * 0.7f, 0.26f, 0.55f, obj->segnum); + } + if (frac < 0.2f && frand() < dt * 1.5f) { + float hot[3] = { 1, 0.7f, 0.35f }; + sparks(pos, NULL, 4, hot, 18, 0.4f); + } +} + +static int fx_level = -1000; +static void level_changed(void); + +void fx_frame(void) +{ + float dt = f2fl(FrameTime); + if (Current_level_num != fx_level) + level_changed(); + if (dt <= 0) + return; + if (dt > 0.1f) + dt = 0.1f; + for (int i = 0; i < n_particles;) { + particle *p = &particles[i]; + float drag; + p->age += dt; + if (p->age >= p->life) { + *p = particles[--n_particles]; + continue; + } + drag = expf(-p->drag * dt); + for (int k = 0; k < 3; k++) { + p->vel[k] *= drag; + p->pos[k] += p->vel[k] * dt; + } + p->size += p->grow * dt; + p->angle += p->spin * dt; + i++; + } + for (int i = 0; i < n_decals;) { + decals[i].age += dt; + if (decals[i].age >= decals[i].life) { + decals[i] = decals[--n_decals]; + continue; + } + i++; + } + if (!fx_enabled() && !boom_enabled()) { + n_particles = n_decals = 0; + return; + } + for (int i = 0, n = n_particles; i < n; i++) { // hot debris trails smoke + particle *p = &particles[i]; + if (p->kind != FX_DEBRIS || p->age > 1.1f) + continue; + for (p->acc += dt; p->acc > 0.045f; p->acc -= 0.045f) { + float v[3]; + for (int k = 0; k < 3; k++) + v[k] = p->vel[k] * 0.08f; + smoke(p->pos, v, 0.22f, 1.1f, 0.7f + frand() * 0.4f, 0.32f, 0.5f * (1 - p->age / 1.1f), -1); + p = &particles[i]; // (spawning can move nothing, but stay safe) + } + } + if (!fx_enabled()) + return; + for (int i = 0; i <= Highest_object_index; i++) { + object *obj = &Objects[i]; + if (obj->type == OBJ_WEAPON && is_missile(obj)) + missile_trail(obj, i); + else if (obj->type == OBJ_ROBOT || (obj->type == OBJ_PLAYER && obj != Viewer && (Game_mode & GM_MULTI))) + damage_smoke(obj, i, dt); + } +} + +// --------------------------------------------------------------------------------------- +// Light halos + +// Where a light texture's lamps are: its bright pixels, one spot per connected patch. +#define MAX_SPOTS 4 +typedef struct light_spots { + signed char n; // -1: not looked at yet + float u[MAX_SPOTS], v[MAX_SPOTS], r[MAX_SPOTS]; // texture units + float rgb[3]; +} light_spots; +static light_spots tex_spots[MAX_TEXTURES]; + +#define MAX_TEX_SIZE 256 +static unsigned char spot_mask[MAX_TEX_SIZE * MAX_TEX_SIZE]; +static unsigned short spot_stack[MAX_TEX_SIZE * MAX_TEX_SIZE]; + +static light_spots *texture_spots(int tmap) +{ + light_spots *ls = &tex_spots[tmap]; + grs_bitmap *bm; + unsigned char *px; + int w, h, maxl = 0, thresh; + double rgb[3] = { 0, 0, 0 }; + int nbright = 0, nopaque = 0; + float area[MAX_SPOTS]; + + if (ls->n >= 0) + return ls; + ls->n = 0; + // lava, water and force fields glow all over: no lamps there + if (TmapInfo[tmap].flags & (TMI_VOLATILE | TMI_WATER | TMI_FORCE_FIELD)) + return ls; + PIGGY_PAGE_IN(Textures[tmap]); + bm = &GameBitmaps[Textures[tmap].index]; + w = bm->bm_w; + h = bm->bm_h; + if (w <= 0 || h <= 0 || w > MAX_TEX_SIZE || h > MAX_TEX_SIZE || !bm->bm_data) + return ls; + px = ogl_bitmap_indices(bm); +#define LUM(c) (gr_palette[(c) * 3] * 30 + gr_palette[(c) * 3 + 1] * 59 + gr_palette[(c) * 3 + 2] * 11) // 0..6300 + for (int i = 0; i < w * h; i++) + if (px[i] < 254 && LUM(px[i]) > maxl) + maxl = LUM(px[i]); + if (maxl < 3800) // no lamp bright enough to glow + return ls; + thresh = maxl * 82 / 100; + for (int i = 0; i < w * h; i++) { + spot_mask[i] = px[i] < 254 && LUM(px[i]) >= thresh; + if (px[i] < 254) + nopaque++; + if (spot_mask[i]) { + for (int k = 0; k < 3; k++) + rgb[k] += gr_palette[px[i] * 3 + k]; + nbright++; + } + } +#undef LUM + if (nbright < 3 || nbright > nopaque * 35 / 100) // a glowing surface, not a lamp + return ls; + // connected patches, biggest kept + for (int start = 0; start < w * h; start++) { + int sp = 0, n = 0; + double sx = 0, sy = 0; + if (spot_mask[start] != 1) + continue; + spot_mask[start] = 2; + spot_stack[sp++] = start; + while (sp) { + int i = spot_stack[--sp], x = i % w, y = i / w; + int nb[4] = { x > 0 ? i - 1 : -1, x < w - 1 ? i + 1 : -1, y > 0 ? i - w : -1, y < h - 1 ? i + w : -1 }; + n++; + sx += x + 0.5; + sy += y + 0.5; + for (int k = 0; k < 4; k++) + if (nb[k] >= 0 && spot_mask[nb[k]] == 1) { + spot_mask[nb[k]] = 2; + spot_stack[sp++] = nb[k]; + } + } + if (n < 4) + continue; + int slot = ls->n < MAX_SPOTS ? ls->n++ : -1; + if (slot < 0) { // replace the smallest if this one is bigger + slot = 0; + for (int k = 1; k < MAX_SPOTS; k++) + if (area[k] < area[slot]) + slot = k; + if (area[slot] >= n) + continue; + } + area[slot] = n; + ls->u[slot] = sx / n / w; + ls->v[slot] = sy / n / h; + ls->r[slot] = sqrtf(n / 3.14159f) / w; + } + { + float m = 0; + for (int k = 0; k < 3; k++) { + ls->rgb[k] = rgb[k] / nbright; + m = ls->rgb[k] > m ? ls->rgb[k] : m; + } + for (int k = 0; k < 3; k++) // the lamp's color, a little toward white + ls->rgb[k] = 0.3f + 0.7f * ls->rgb[k] / m; + } + return ls; +} + +// the sides drawn in this view that may carry a lamp +#define MAX_LIT_SIDES 1024 +static int lit_sides[MAX_LIT_SIDES], n_lit_sides; +static unsigned short side_stamp[MAX_SEGMENTS][MAX_SIDES_PER_SEGMENT], pass = 1; + +void fx_note_face(int segnum, int sidenum) +{ + side *sd = &Segments[segnum].sides[sidenum]; + if (side_stamp[segnum][sidenum] == pass || n_lit_sides >= MAX_LIT_SIDES) + return; + side_stamp[segnum][sidenum] = pass; + if (TmapInfo[sd->tmap_num].lighting > 0 || (sd->tmap_num2 && TmapInfo[sd->tmap_num2 & 0x3fff].lighting > 0)) + lit_sides[n_lit_sides++] = segnum * MAX_SIDES_PER_SEGMENT + sidenum; +} + +static void level_changed(void) +{ + fx_level = Current_level_num; + n_particles = n_decals = 0; + for (int i = 0; i < MAX_TEXTURES; i++) + tex_spots[i].n = -1; + memset(trail_sig, 0, sizeof(trail_sig)); + memset(smoke_sig, 0, sizeof(smoke_sig)); +} + +// --------------------------------------------------------------------------------------- +// Drawing + +typedef struct fxvert { + float pos[3]; + float tex[2]; + float color[4]; +} fxvert; + +#define MAX_HALOS 768 +#define MAX_FX_VERTS ((MAX_PARTICLES + MAX_HALOS) * 6) +static fxvert fx_verts[MAX_FX_VERTS]; +static int n_verts; +static float view_rows[3][3], view_pos[3], cam_right[3], cam_up[3]; +static GLuint glow_tex, smoke_tex, fire_tex, ring_tex, chunk_tex, scorch_tex; + +static void to_view(const float *p, float *o) +{ + float d[3] = { p[0] - view_pos[0], p[1] - view_pos[1], p[2] - view_pos[2] }; + o[0] = dot(view_rows[0], d); + o[1] = dot(view_rows[1], d); + o[2] = -dot(view_rows[2], d); +} + +static void vert(const float *p, float u, float v, const float *rgb, float a) +{ + fxvert *fv = &fx_verts[n_verts++]; + to_view(p, fv->pos); + fv->tex[0] = u; + fv->tex[1] = v; + fv->color[0] = rgb[0]; + fv->color[1] = rgb[1]; + fv->color[2] = rgb[2]; + fv->color[3] = a; +} + +// a quad through the four world points, as two triangles +static void quad(const float *a, const float *b, const float *c, const float *d, const float *rgb, float alpha) +{ + if (n_verts + 6 > MAX_FX_VERTS) + return; + vert(a, 0, 0, rgb, alpha); vert(b, 1, 0, rgb, alpha); vert(c, 1, 1, rgb, alpha); + vert(a, 0, 0, rgb, alpha); vert(c, 1, 1, rgb, alpha); vert(d, 0, 1, rgb, alpha); +} + +// a camera-facing square, turned by angle +static void billboard(const float *p, float size, float angle, const float *rgb, float alpha) +{ + float c = cosf(angle) * size, s = sinf(angle) * size, r[3], u[3], q[4][3]; + for (int k = 0; k < 3; k++) { + r[k] = cam_right[k] * c + cam_up[k] * s; + u[k] = cam_up[k] * c - cam_right[k] * s; + q[0][k] = p[k] - r[k] + u[k]; + q[1][k] = p[k] + r[k] + u[k]; + q[2][k] = p[k] + r[k] - u[k]; + q[3][k] = p[k] - r[k] - u[k]; + } + quad(q[0], q[1], q[2], q[3], rgb, alpha); +} + +// a spark: a glow stretched along its path, facing the camera +static void streak(const float *head, const float *tail, float width, const float *rgb, float alpha) +{ + float d[3], to[3], side[3], q[4][3], l; + for (int k = 0; k < 3; k++) { + d[k] = head[k] - tail[k]; + to[k] = view_pos[k] - head[k]; + } + side[0] = d[1] * to[2] - d[2] * to[1]; + side[1] = d[2] * to[0] - d[0] * to[2]; + side[2] = d[0] * to[1] - d[1] * to[0]; + l = len(side); + if (l < 1e-6f) + return; + l = width / l; + for (int k = 0; k < 3; k++) { + float e = d[k] * 0.3f; // the glow's round ends reach past the path + q[0][k] = head[k] + e + side[k] * l; + q[1][k] = head[k] + e - side[k] * l; + q[2][k] = tail[k] - e - side[k] * l; + q[3][k] = tail[k] - e + side[k] * l; + } + quad(q[0], q[1], q[2], q[3], rgb, alpha); +} + +enum { TEX_GLOW, TEX_SMOKE, TEX_FIRE, TEX_RING, TEX_CHUNK, TEX_SCORCH }; + +static GLuint make_texture(int kind) +{ + static unsigned char img[64 * 64 * 4]; + GLuint t; + for (int y = 0; y < 64; y++) + for (int x = 0; x < 64; x++) { + float dx = (x + 0.5f) / 32 - 1, dy = (y + 0.5f) / 32 - 1, r = sqrtf(dx * dx + dy * dy), a, shade = 1; + float th = atan2f(dy, dx); + if (kind == TEX_FIRE) { + // a turbulent ball of flame, densest in the middle + float n = 0.5f + 0.22f * sinf(dx * 9.3f + 0.7f) * sinf(dy * 8.1f + 2.2f) + + 0.16f * sinf((dx + dy) * 17.9f + 1.1f) * sinf((dx - dy) * 15.3f) + + 0.1f * sinf(th * 7 + r * 9); + a = smooth(1.0f, 0.1f, r + (n - 0.5f) * 0.5f) * (0.6f + 0.5f * n); + } else if (kind == TEX_RING) { + float q = (r - 0.72f) / 0.13f; + a = expf(-q * q) * smooth(1.0f, 0.9f, r) * (0.8f + 0.2f * sinf(th * 11)); + } else if (kind == TEX_CHUNK) { + // a jagged lump of metal, lit from one side + float rr = 0.62f + 0.2f * sinf(th * 3 + 1) + 0.12f * sinf(th * 5 + 2.3f); + a = smooth(rr, rr - 0.1f, r); + shade = 0.55f + 0.45f * (0.5f - 0.35f * (dx + dy) - 0.3f * r); + } else if (kind == TEX_SCORCH) { + // soot, densest in the middle, with a ragged edge and streaks out from the blast + float n = 0.5f + 0.25f * sinf(th * 9 + 0.4f) * sinf(r * 13) + 0.2f * sinf(th * 23 + 1.7f); + a = smooth(1.0f, 0.25f, r + (n - 0.5f) * 0.35f) * (0.75f + 0.25f * n); + } else if (kind == TEX_SMOKE) { + // a soft puff with some billows + float n = 0.5f + 0.25f * sinf(dx * 7.1f + 1.3f) * sinf(dy * 6.3f + 0.4f) + + 0.15f * sinf((dx + dy) * 12.7f) * sinf((dx - dy) * 11.3f + 2.1f); + a = smooth(1.0f, 0.25f, r) * (0.55f + 0.6f * n); + } else + a = expf(-r * r * 5.5f) * smooth(1.0f, 0.7f, r); // a glow that fades to nothing at the edge + a = a < 0 ? 0 : a > 1 ? 1 : a; + shade = shade < 0 ? 0 : shade > 1 ? 1 : shade; + img[(y * 64 + x) * 4] = img[(y * 64 + x) * 4 + 1] = img[(y * 64 + x) * 4 + 2] = (unsigned char)(shade * 255); + img[(y * 64 + x) * 4 + 3] = (unsigned char)(a * 255); + } + glGenTextures(1, &t); + glBindTexture(GL_TEXTURE_2D, t); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, img); + return t; +} + +static int inside(const float *a, const float *b, const float *c, float u, float v, float *w) +{ + float d = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]); + if (fabsf(d) < 1e-6f) + return 0; + w[0] = ((b[1] - c[1]) * (u - c[0]) + (c[0] - b[0]) * (v - c[1])) / d; + w[1] = ((c[1] - a[1]) * (u - c[0]) + (a[0] - c[0]) * (v - c[1])) / d; + w[2] = 1 - w[0] - w[1]; + return w[0] >= -0.02f && w[1] >= -0.02f && w[2] >= -0.02f; +} + +static void halo(const float *at, const float *normal, float radius, const float *rgb) +{ + float to[3], dist, facing, fade, size, pull, p[3], c[3]; + for (int k = 0; k < 3; k++) + to[k] = view_pos[k] - at[k]; + dist = len(to); + if (dist < 0.01f) + return; + for (int k = 0; k < 3; k++) + to[k] /= dist; + facing = dot(normal, to); + size = radius * 5 + 1.5f; + size = size < 2 ? 2 : size > 10 ? 10 : size; + fade = smooth(0.05f, 0.5f, facing) * smooth(size * 0.4f, size * 1.5f, dist) * 0.5f; + if (fade < 0.01f) + return; + // Toward the camera, so its wall seen at an angle doesn't cut it (made smaller to look the + // same size from there). + pull = size * 2.5f < dist * 0.6f ? size * 2.5f : dist * 0.6f; + madd(p, at, to, pull); + for (int k = 0; k < 3; k++) + c[k] = rgb[k] * fade; + billboard(p, size * (dist - pull) / dist, 0, c, 1); +} + +static void side_halos(int segnum, int sidenum) +{ + segment *seg = &Segments[segnum]; + side *sd = &seg->sides[sidenum]; + int t2 = sd->tmap_num2 & 0x3fff, rot = (sd->tmap_num2 >> 14) & 3, count = 0; + float P[4][3], U[4][2], n[3], minu = 1e9f, maxu = -1e9f, minv = 1e9f, maxv = -1e9f, scale, e0, e1; + light_spots *ls; + + if (Light_subtracted[segnum] & (1 << sidenum)) // shot out or switched off + return; + if (sd->tmap_num2 && TmapInfo[t2].lighting > 0) + ls = texture_spots(t2); + else { + ls = texture_spots(sd->tmap_num); + rot = 0; + } + if (ls->n <= 0) + return; + for (int k = 0; k < 4; k++) { + fv(&Vertices[seg->verts[Side_to_verts[sidenum][k]]], P[k]); + U[k][0] = f2fl(sd->uvls[k].u); + U[k][1] = f2fl(sd->uvls[k].v); + minu = U[k][0] < minu ? U[k][0] : minu; + maxu = U[k][0] > maxu ? U[k][0] : maxu; + minv = U[k][1] < minv ? U[k][1] : minv; + maxv = U[k][1] > maxv ? U[k][1] : maxv; + } + fv(&sd->normals[0], n); + { // world units per texture repeat + float d[3], du = U[1][0] - U[0][0], dv = U[1][1] - U[0][1]; + for (int k = 0; k < 3; k++) + d[k] = P[1][k] - P[0][k]; + e0 = sqrtf(du * du + dv * dv) > 1e-4f ? len(d) / sqrtf(du * du + dv * dv) : 0; + du = U[2][0] - U[1][0]; + dv = U[2][1] - U[1][1]; + for (int k = 0; k < 3; k++) + d[k] = P[2][k] - P[1][k]; + e1 = sqrtf(du * du + dv * dv) > 1e-4f ? len(d) / sqrtf(du * du + dv * dv) : 0; + scale = e0 && e1 ? (e0 + e1) / 2 : e0 + e1; + } + for (int s = 0; s < ls->n; s++) { + float u = ls->u[s], v = ls->v[s]; + // the overlay is turned on the wall as the texture merger turns it + switch (rot) { + case 1: u = ls->v[s]; v = 1 - ls->u[s]; break; + case 2: u = 1 - ls->u[s]; v = 1 - ls->v[s]; break; + case 3: u = 1 - ls->v[s]; v = ls->u[s]; break; + } + // every repeat of the texture on this side + for (int i = (int)floorf(minu - u); i <= (int)ceilf(maxu - u) && count < 16; i++) + for (int j = (int)floorf(minv - v); j <= (int)ceilf(maxv - v) && count < 16; j++) { + float w[3], at[3]; + int a = 0, b = 1, c = 2; + if (!inside(U[0], U[1], U[2], u + i, v + j, w)) { + if (!inside(U[0], U[2], U[3], u + i, v + j, w)) + continue; + b = 2; + c = 3; + } + for (int k = 0; k < 3; k++) + at[k] = P[a][k] * w[0] + P[b][k] * w[1] + P[c][k] * w[2]; + halo(at, n, ls->r[s] * scale, ls->rgb); + count++; + } + } +} + +static int smoke_order[MAX_PARTICLES]; +static float smoke_depth[MAX_PARTICLES]; +static int far_first(const void *a, const void *b) +{ + float da = smoke_depth[*(const int *)a], db = smoke_depth[*(const int *)b]; + return da < db ? 1 : da > db ? -1 : 0; +} + +static void draw(GLuint tex, int first, int count) +{ + if (count <= 0) + return; + glBindTexture(GL_TEXTURE_2D, tex); + glDrawArrays(GL_TRIANGLES, first, count); +} + +// fire cools from white-hot through orange to deep red (brighter than white for the glow) +static void fire_color(float t, float *c) +{ + static const float k[4][3] = { { 1.3f, 1.1f, 0.75f }, { 1.05f, 0.5f, 0.17f }, { 0.45f, 0.13f, 0.035f }, { 0.1f, 0.02f, 0.01f } }; + static const float at[4] = { 0, 0.15f, 0.5f, 1 }; + int i = t < at[1] ? 0 : t < at[2] ? 1 : 2; + float f = (t - at[i]) / (at[i + 1] - at[i]), fade = smooth(0, 0.06f, t) * (1 - t); + for (int j = 0; j < 3; j++) + c[j] = (k[i][j] + (k[i + 1][j] - k[i][j]) * f) * fade; +} + +// what fx_render draws, in order: each a texture and a blend over a range of fx_verts +typedef struct batch { + GLuint *tex; + int additive, first; +} batch; +static batch batches[8]; +static int n_batches; + +static void batch_begin(GLuint *tex, int additive) +{ + batches[n_batches].tex = tex; + batches[n_batches].additive = additive; + batches[n_batches].first = n_verts; + n_batches++; +} + +void fx_render(void) +{ + int n_smoke = 0, scissor, boom = boom_enabled(); + pass = pass == 0xffff ? 1 : pass + 1; + if (!fx_enabled() && !boom) { + n_lit_sides = 0; + return; + } + if (Current_level_num != fx_level) + level_changed(); + for (int r = 0; r < 3; r++) { + const vms_vector *row = r == 0 ? &View_matrix.rvec : r == 1 ? &View_matrix.uvec : &View_matrix.fvec; + fv(row, view_rows[r]); + } + fv(&View_position, view_pos); + fv(&Unscaled_matrix.rvec, cam_right); + fv(&Unscaled_matrix.uvec, cam_up); + n_verts = 0; + n_batches = 0; + + // scorch marks darken the walls; fresh ones still glow + batch_begin(&scorch_tex, 0); + for (int i = 0; i < n_decals; i++) { + decal *d = &decals[i]; + float q[4][3], dark[3] = { 0.03f, 0.025f, 0.02f }; + for (int k = 0; k < 3; k++) { + q[0][k] = d->pos[k] - d->t1[k] - d->t2[k]; + q[1][k] = d->pos[k] + d->t1[k] - d->t2[k]; + q[2][k] = d->pos[k] + d->t1[k] + d->t2[k]; + q[3][k] = d->pos[k] - d->t1[k] + d->t2[k]; + } + quad(q[0], q[1], q[2], q[3], dark, d->alpha * (1 - smooth(d->life * 0.7f, d->life, d->age))); + } + batch_begin(&scorch_tex, 1); + for (int i = 0; i < n_decals; i++) { + decal *d = &decals[i]; + float q[4][3], f = 1 - smooth(0, 1.8f, d->age), c[3]; + if (d->ember <= 0 || f <= 0) + continue; + f *= f * d->ember; + c[0] = 2.0f * f, c[1] = 0.55f * f, c[2] = 0.12f * f; + for (int k = 0; k < 3; k++) { + q[0][k] = d->pos[k] - d->t1[k] * 0.7f - d->t2[k] * 0.7f; + q[1][k] = d->pos[k] + d->t1[k] * 0.7f - d->t2[k] * 0.7f; + q[2][k] = d->pos[k] + d->t1[k] * 0.7f + d->t2[k] * 0.7f; + q[3][k] = d->pos[k] - d->t1[k] * 0.7f + d->t2[k] * 0.7f; + } + quad(q[0], q[1], q[2], q[3], c, 1); + } + + // smoke, far to near, blended over what is behind it + batch_begin(&smoke_tex, 0); + for (int i = 0; i < n_particles; i++) + if (particles[i].kind == FX_SMOKE) { + float v[3]; + to_view(particles[i].pos, v); + if (v[2] > -0.5f) // behind the camera + continue; + smoke_depth[i] = -v[2]; + smoke_order[n_smoke++] = i; + } + qsort(smoke_order, n_smoke, sizeof(int), far_first); + for (int i = 0; i < n_smoke; i++) { + particle *p = &particles[smoke_order[i]]; + float t = p->age / p->life; + billboard(p->pos, p->size, p->angle, p->rgb, p->alpha * smooth(0, 0.08f, t) * (1 - t) * sqrtf(1 - t)); + } + + // debris: dark lumps, glowing while still hot + batch_begin(&chunk_tex, 0); + for (int i = 0; i < n_particles; i++) { + particle *p = &particles[i]; + float heat, c[3], t; + if (p->kind != FX_DEBRIS) + continue; + t = p->age / p->life; + heat = 1 - smooth(0, 1.0f, p->age); + c[0] = 0.13f + 1.5f * heat; + c[1] = 0.11f + 0.6f * heat * heat; + c[2] = 0.1f + 0.15f * heat * heat * heat; + billboard(p->pos, p->size, p->angle, c, 1 - smooth(0.85f, 1, t)); + } + + // flames and shockwaves, added to the light + batch_begin(&fire_tex, 1); + for (int i = 0; i < n_particles; i++) { + particle *p = &particles[i]; + float c[3]; + if (p->kind != FX_FIRE) + continue; + fire_color(p->age / p->life, c); + billboard(p->pos, p->size, p->angle, c, 1); + } + batch_begin(&ring_tex, 1); + for (int i = 0; i < n_particles; i++) { + particle *p = &particles[i]; + float t, f, c[3]; + if (p->kind != FX_RING) + continue; + t = p->age / p->life; + f = (1 - t) * (1 - t) * 0.45f; + c[0] = 1.5f * f, c[1] = 1.15f * f, c[2] = 0.75f * f; + billboard(p->pos, p->size, 0, c, 1); + } + batch_begin(&glow_tex, 1); + + // glows: halos, sparks, flashes, added to the light + STAT(0, n_lit_sides); + { + int before = n_verts; + for (int i = 0; i < n_lit_sides && fx_enabled(); i++) + side_halos(lit_sides[i] / MAX_SIDES_PER_SEGMENT, lit_sides[i] % MAX_SIDES_PER_SEGMENT); + STAT(1, (n_verts - before) / 6); + } + n_lit_sides = 0; + for (int i = 0; i < n_particles; i++) { + particle *p = &particles[i]; + float t = p->age / p->life, c[3]; + if (p->kind == FX_SPARK) { + float tail[3], f = (1 - t) * (1 - t); + // cools from white-hot to the weapon's color and red + c[0] = p->rgb[0] * f; + c[1] = p->rgb[1] * f * (1 - 0.45f * t); + c[2] = p->rgb[2] * f * (1 - 0.8f * t); + madd(tail, p->pos, p->vel, -0.06f); + streak(p->pos, tail, p->size, c, 1); + } else if (p->kind == FX_GLOW) { + float f = p->alpha * (1 - t); + for (int k = 0; k < 3; k++) + c[k] = p->rgb[k] * f; + billboard(p->pos, p->size * (1 + t), 0, c, 1); + } else if (p->kind == FX_DEBRIS && p->age < 1.0f) { // its hot glow, along its path + float tail[3], h = 1 - p->age; + h *= h; + c[0] = 1.4f * h, c[1] = 0.55f * h, c[2] = 0.15f * h; + madd(tail, p->pos, p->vel, -0.035f); + streak(p->pos, tail, p->size * 1.3f, c, 1); + } + } + STAT(2, n_particles); + STAT(3, n_verts); + if (!n_verts) + return; + + batches[n_batches].first = n_verts; // the end of the last one + if (!glow_tex) { + glow_tex = make_texture(TEX_GLOW); + smoke_tex = make_texture(TEX_SMOKE); + fire_tex = make_texture(TEX_FIRE); + ring_tex = make_texture(TEX_RING); + chunk_tex = make_texture(TEX_CHUNK); + scorch_tex = make_texture(TEX_SCORCH); + } + scissor = glIsEnabled(GL_SCISSOR_TEST); + glDisable(GL_SCISSOR_TEST); + glDisable(GL_CULL_FACE); + glDepthMask(GL_FALSE); + OGL_ENABLE(TEXTURE_2D); + glVertexPointer(3, GL_FLOAT, sizeof(fxvert), fx_verts[0].pos); + glTexCoordPointer(2, GL_FLOAT, sizeof(fxvert), fx_verts[0].tex); + glColorPointer(4, GL_FLOAT, sizeof(fxvert), fx_verts[0].color); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + for (int i = 0; i < n_batches; i++) { + glBlendFunc(GL_SRC_ALPHA, batches[i].additive ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA); + draw(*batches[i].tex, batches[i].first, batches[i + 1].first - batches[i].first); + } + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + glDepthMask(GL_TRUE); + glEnable(GL_CULL_FACE); + if (scissor) + glEnable(GL_SCISSOR_TEST); +} diff --git a/d2/main/fx.h b/d2/main/fx.h new file mode 100644 index 0000000..a3e0ddd --- /dev/null +++ b/d2/main/fx.h @@ -0,0 +1,18 @@ +/* + * Light halos, smoke and sparks (browser edition). Purely visual: nothing here feeds back + * into the game. + */ + +#ifndef _FX_H +#define _FX_H + +#include "object.h" + +void fx_frame(void); // once per game frame: age particles, emit trails and smoke +void fx_note_face(int segnum, int sidenum); // the renderer draws this side now +void fx_render(void); // draws the effects into the 3D view being rendered +void fx_impact(object *weapon, int segnum, int sidenum, vms_vector *pos); // a shot hits a wall +void fx_hit(object *weapon, vms_vector *pos); // a shot hits a robot +void fx_explosion(vms_vector *pos, int segnum, fix size); // a robot, player or reactor blows up + +#endif diff --git a/d2/main/game.c b/d2/main/game.c index f15d413..4758a33 100644 --- a/d2/main/game.c +++ b/d2/main/game.c @@ -28,6 +28,7 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "gr.h" #include "inferno.h" #include "game.h" +#include "fx.h" #include "key.h" #include "object.h" #include "physics.h" @@ -1481,6 +1482,7 @@ void GameProcessFrame(void) omega_charge_frame(); slide_textures(); flicker_lights(); + fx_frame(); // light halos, smoke and sparks //if the player is taking damage, give up guided missile control if (Players[Player_num].shields != player_shields) diff --git a/d2/main/gameseq.c b/d2/main/gameseq.c index 30de489..9d3cd2f 100644 --- a/d2/main/gameseq.c +++ b/d2/main/gameseq.c @@ -106,6 +106,9 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "segment.h" #include "gameseg.h" #include "multibot.h" +#ifdef __EMSCRIPTEN__ +#include "web.h" +#endif void StartNewLevelSecret(int level_num, int page_in_textures); @@ -828,6 +831,8 @@ void InitPlayerObject() extern void init_seismic_disturbances(void); +static int Skip_level_intro; // -notitles: a new game starts without the opening movie and briefing + //starts a new game on the given level void StartNewGame(int start_level) { @@ -843,10 +848,12 @@ void StartNewGame(int start_level) N_players = 1; + Skip_level_intro = GameArg.SysNoTitles; if (start_level < 0) StartNewLevelSecret(start_level, 0); else StartNewLevel(start_level); + Skip_level_intro = 0; Players[Player_num].starting_level = start_level; // Mark where they started @@ -1663,6 +1670,13 @@ void StartNewLevelSub(int level_num, int page_in_textures, int secret_flag) reset_respawnable_bots(); +#ifdef __EMSCRIPTEN__ + // Vertigo Level 1 shows off the remodelled Medium Lifter (extra-sharp pack): one waits behind each first door + if (!(Game_mode & GM_MULTI) && Newdemo_state != ND_STATE_PLAYBACK && level_num == 1 && + !d_stricmp(Current_mission_filename, "d2x") && d2web_option(D2WEB_OPTION_ULTRA)) + d2web_place_robots_past_first_doors(1); +#endif + set_homing_update_rate(Game_mode & GM_MULTI ? Netgame.HomingUpdateRate : 25); // Say player can use FLASH cheat to mark path to exit. @@ -1743,6 +1757,9 @@ void ShowLevelIntro(int level_num) ubyte save_pal[sizeof(gr_palette)]; memcpy(save_pal,gr_palette,sizeof(gr_palette)); +#ifdef __EMSCRIPTEN__ + d2web_cutscene(1); // the movie and briefing skip as one +#endif if (PLAYING_BUILTIN_MISSION) { @@ -1775,6 +1792,9 @@ void ShowLevelIntro(int level_num) { do_briefing_screens(Briefing_text_filename, level_num); } +#ifdef __EMSCRIPTEN__ + d2web_cutscene(0); +#endif memcpy(gr_palette,save_pal,sizeof(gr_palette)); } @@ -1809,7 +1829,8 @@ void StartNewLevel(int level_num) maybe_set_first_secret_visit(level_num); } - ShowLevelIntro(level_num); + if (!Skip_level_intro) + ShowLevelIntro(level_num); StartNewLevelSub(level_num, 1, 0 ); diff --git a/d2/main/inferno.c b/d2/main/inferno.c index dc6e44a..22c3ee3 100644 --- a/d2/main/inferno.c +++ b/d2/main/inferno.c @@ -25,6 +25,7 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. char copyright[] = "DESCENT II COPYRIGHT (C) 1994-1996 PARALLAX SOFTWARE CORPORATION"; +#include "web.h" #include #include #include @@ -415,7 +416,17 @@ int main(int argc, char *argv[]) con_printf( CON_DEBUG, "Initializing movie libraries...\n" ); init_movies(); //init movie libraries - show_titles(); + if (GameArg.SysNoTitles) // skip the intro movie and logo screens, straight to the title music + songs_play_song(SONG_TITLE, 1); + else { +#ifdef __EMSCRIPTEN__ + d2web_cutscene(1); +#endif + show_titles(); +#ifdef __EMSCRIPTEN__ + d2web_cutscene(0); +#endif + } set_screen_mode(SCREEN_MENU); @@ -519,5 +530,8 @@ int main(int argc, char *argv[]) PHYSFSX_removeArchiveContent(); reset_observatory_stats(); +#ifdef __EMSCRIPTEN__ + d2web_quit(); // save to browser storage and return to the page +#endif return(0); //presumably successful exit } diff --git a/d2/main/kconfig.c b/d2/main/kconfig.c index d9aafbc..a05fbd2 100644 --- a/d2/main/kconfig.c +++ b/d2/main/kconfig.c @@ -97,6 +97,10 @@ fix Cruise_speed=0; #define STATE_BIT3 4 #define STATE_BIT4 8 #define STATE_BIT5 16 +#ifdef __EMSCRIPTEN__ +#include "web.h" +#define TOUCH_BIT 32 // the page's touch controls +#endif #define INFO_Y (188) @@ -1740,6 +1744,41 @@ void kconfig_read_controls(d_event *event, int automap_flag) if (Cruise_speed < 0 ) Cruise_speed = 0; if (Controls.forward_thrust_time==0) Controls.forward_thrust_time = fixmul(Cruise_speed,FrameTime)/100; +#ifdef __EMSCRIPTEN__ + //----------- Touch controls (phones and tablets), from the page + { + float touch[6]; // stick x, y (-1..1); look x, y (turn time); held buttons; buttons tapped this frame + if (d2web_touch_read(touch)) + { + int held = (int)touch[4], taps = (int)touch[5]; +#define TOUCH_STATE(field, bit) Controls.field = (held & (bit)) ? Controls.field | TOUCH_BIT : Controls.field & ~TOUCH_BIT + Controls.forward_thrust_time -= (fix)(touch[1] * FrameTime); + Controls.sideways_thrust_time += (fix)(touch[0] * FrameTime); + Controls.heading_time += fl2f(touch[2]); + Controls.pitch_time += fl2f(touch[3]); + if (held & D2WEB_TOUCH_UP) Controls.vertical_thrust_time += speed_factor*FrameTime; + if (held & D2WEB_TOUCH_DOWN) Controls.vertical_thrust_time -= speed_factor*FrameTime; + TOUCH_STATE(fire_primary_state, D2WEB_TOUCH_FIRE); + TOUCH_STATE(fire_secondary_state, D2WEB_TOUCH_MISSILE); + TOUCH_STATE(afterburner_state, D2WEB_TOUCH_BOOST); + if (taps & D2WEB_TOUCH_FIRE) Controls.fire_primary_count++; + if (taps & D2WEB_TOUCH_MISSILE) Controls.fire_secondary_count++; + if (taps & D2WEB_TOUCH_FLARE) Controls.fire_flare_count++; + if (taps & D2WEB_TOUCH_BOMB) Controls.drop_bomb_count++; + if (taps & D2WEB_TOUCH_WEAPON) Controls.cycle_primary_count++; + if (taps & D2WEB_TOUCH_SECONDARY) Controls.cycle_secondary_count++; + if (taps & D2WEB_TOUCH_MAP) Controls.automap_count++; +#undef TOUCH_STATE + } + } +#endif + +#ifdef __EMSCRIPTEN__ + // the page's Reverse up/down: every control at once, before the overrun (worked out from these values) + if (d2web_option(D2WEB_OPTION_INVERT_PITCH)) + Controls.pitch_time = -Controls.pitch_time; +#endif + //----------- Add overrun values Controls.pitch_time += Controls.pitch_time_overrun; Controls.heading_time += Controls.heading_time_overrun; diff --git a/d2/main/lighting.c b/d2/main/lighting.c index 5e4f613..ccadb0a 100644 --- a/d2/main/lighting.c +++ b/d2/main/lighting.c @@ -45,10 +45,23 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "bm.h" #include "rle.h" #include "wall.h" +#include "plight.h" +#include "../3d/globvars.h" int Do_dynamic_light=1; int use_fcd_lighting = 0; g3s_lrgb Dynamic_light[MAX_VERTICES]; +g3s_lrgb Dynamic_light_pp[MAX_VERTICES]; // the part of Dynamic_light from the lights plight.c draws per pixel +pp_light Pp_lights[PP_MAX_LIGHTS]; +int Pp_num_lights; +object *Pp_headlight; // the viewer's own headlight, drawn per pixel +static int pp_apply; // apply_light: the light being applied is one of those + +#define ADD_LIGHT(v, R, G, B) do { \ + fix r_ = (R), g_ = (G), b_ = (B); \ + Dynamic_light[v].r += r_; Dynamic_light[v].g += g_; Dynamic_light[v].b += b_; \ + if (pp_apply) { Dynamic_light_pp[v].r += r_; Dynamic_light_pp[v].g += g_; Dynamic_light_pp[v].b += b_; } \ +} while (0) #define HEADLIGHT_CONE_DOT (F1_0*9/10) #define HEADLIGHT_SCALE (F1_0*10) @@ -85,9 +98,7 @@ void apply_light(g3s_lrgb obj_light_emission, int obj_seg, vms_vector *obj_pos, if (dist < MIN_LIGHT_DIST) dist = MIN_LIGHT_DIST; - Dynamic_light[vertnum].r += fixdiv(obj_light_emission.r, dist); - Dynamic_light[vertnum].g += fixdiv(obj_light_emission.g, dist); - Dynamic_light[vertnum].b += fixdiv(obj_light_emission.b, dist); + ADD_LIGHT(vertnum, fixdiv(obj_light_emission.r, dist), fixdiv(obj_light_emission.g, dist), fixdiv(obj_light_emission.b, dist)); } } } else { @@ -158,9 +169,7 @@ void apply_light(g3s_lrgb obj_light_emission, int obj_seg, vms_vector *obj_pos, if (dot < F1_0/2) { // Do the normal thing, but darken around headlight. - Dynamic_light[vertnum].r += fixdiv(obj_light_emission.r, fixmul(HEADLIGHT_SCALE, dist)); - Dynamic_light[vertnum].g += fixdiv(obj_light_emission.g, fixmul(HEADLIGHT_SCALE, dist)); - Dynamic_light[vertnum].b += fixdiv(obj_light_emission.b, fixmul(HEADLIGHT_SCALE, dist)); + ADD_LIGHT(vertnum, fixdiv(obj_light_emission.r, fixmul(HEADLIGHT_SCALE, dist)), fixdiv(obj_light_emission.g, fixmul(HEADLIGHT_SCALE, dist)), fixdiv(obj_light_emission.b, fixmul(HEADLIGHT_SCALE, dist))); } else { @@ -168,24 +177,18 @@ void apply_light(g3s_lrgb obj_light_emission, int obj_seg, vms_vector *obj_pos, { if (dist < max_headlight_dist) { - Dynamic_light[vertnum].r += fixmul(fixmul(dot, dot), obj_light_emission.r)/8; - Dynamic_light[vertnum].g += fixmul(fixmul(dot, dot), obj_light_emission.g)/8; - Dynamic_light[vertnum].b += fixmul(fixmul(dot, dot), obj_light_emission.b)/8; + ADD_LIGHT(vertnum, fixmul(fixmul(dot, dot), obj_light_emission.r)/8, fixmul(fixmul(dot, dot), obj_light_emission.g)/8, fixmul(fixmul(dot, dot), obj_light_emission.b)/8); } } else { - Dynamic_light[vertnum].r += fixmul(fixmul(dot, dot), obj_light_emission.r)/8; - Dynamic_light[vertnum].g += fixmul(fixmul(dot, dot), obj_light_emission.g)/8; - Dynamic_light[vertnum].b += fixmul(fixmul(dot, dot), obj_light_emission.b)/8; + ADD_LIGHT(vertnum, fixmul(fixmul(dot, dot), obj_light_emission.r)/8, fixmul(fixmul(dot, dot), obj_light_emission.g)/8, fixmul(fixmul(dot, dot), obj_light_emission.b)/8); } } } else { - Dynamic_light[vertnum].r += fixdiv(obj_light_emission.r, dist); - Dynamic_light[vertnum].g += fixdiv(obj_light_emission.g, dist); - Dynamic_light[vertnum].b += fixdiv(obj_light_emission.b, dist); + ADD_LIGHT(vertnum, fixdiv(obj_light_emission.r, dist), fixdiv(obj_light_emission.g, dist), fixdiv(obj_light_emission.b, dist)); } } } @@ -197,6 +200,28 @@ void apply_light(g3s_lrgb obj_light_emission, int obj_seg, vms_vector *obj_pos, #define FLASH_SCALE (3*F1_0/FLASH_LEN_FIXED_SECONDS) // ---------------------------------------------------------------------------------------------- +// A light for set_dynamic_light to apply +typedef struct light_cand { + g3s_lrgb e; + vms_vector pos; + short seg, objnum; + fix score; + sbyte pp; +} light_cand; + +static light_cand Light_cands[MAX_OBJECTS + MUZZLE_QUEUE_MAX]; +static int N_light_cands; + +static void add_light_cand(g3s_lrgb e, int seg, vms_vector *pos, int objnum) +{ + light_cand *c = &Light_cands[N_light_cands++]; + c->e = e; + c->pos = *pos; + c->seg = seg; + c->objnum = objnum; + c->pp = 0; +} + void cast_muzzle_flash_light(int n_render_vertices, int *render_vertices, int *vert_segnum_list) { fix64 current_time; @@ -214,7 +239,7 @@ void cast_muzzle_flash_light(int n_render_vertices, int *render_vertices, int *v { g3s_lrgb ml; ml.r = ml.g = ml.b = ((FLASH_LEN_FIXED_SECONDS - time_since_flash) * FLASH_SCALE); - apply_light(ml, Muzzle_data[i].segnum, &Muzzle_data[i].pos, n_render_vertices, render_vertices, vert_segnum_list, -1); + add_light_cand(ml, Muzzle_data[i].segnum, &Muzzle_data[i].pos, -1); } else { @@ -224,6 +249,49 @@ void cast_muzzle_flash_light(int n_render_vertices, int *render_vertices, int *v } } +// Picks the lights plight.c draws per pixel: the brightest near the viewer, and the viewer's +// own headlight. Dim lights (which only reach their own segment) and markers stay per vertex. +// With per-pixel lighting off they are still listed, for the light haze. +static void select_pp_lights(void) +{ + int i, j, pp = plight_enabled(); + Pp_num_lights = 0; + Pp_headlight = NULL; + if (!pp && !plight_haze_enabled()) + return; + for (i = 0; i < N_light_cands; i++) { + light_cand *c = &Light_cands[i]; + fix avg = (c->e.r + c->e.g + c->e.b) / 3; + object *o = c->objnum >= 0 ? &Objects[c->objnum] : NULL; + c->score = -1; + if (avg * 64 <= F1_0 * 8 || (o && o->type == OBJ_MARKER)) + continue; + if (o && o->type == OBJ_PLAYER && (Players[o->id].flags & PLAYER_FLAGS_HEADLIGHT_ON)) { + if (o == Viewer && o->id == Player_num) { + Pp_headlight = o; + c->pp = pp; + } + continue; + } + if (o && o == Viewer) // the ship's own glow: right at the eye, it would flood the walls close by + continue; + c->score = fixdiv(avg, max(vm_vec_dist_quick(&c->pos, &View_position), F1_0 * 20)); + } + for (j = 0; j < PP_MAX_LIGHTS; j++) { + int best = -1; + for (i = 0; i < N_light_cands; i++) + if (Light_cands[i].score > 0 && (best < 0 || Light_cands[i].score > Light_cands[best].score)) + best = i; + if (best < 0) + break; + Light_cands[best].pp = pp; + Light_cands[best].score = -1; + Pp_lights[Pp_num_lights].pos = Light_cands[best].pos; + Pp_lights[Pp_num_lights].emission = Light_cands[best].e; + Pp_num_lights++; + } +} + // Translation table to make flares flicker at different rates fix Obj_light_xlate[16] = { 0x1234, 0x3321, 0x2468, 0x1735, 0x0123, 0x19af, 0x3f03, 0x232a, @@ -504,21 +572,30 @@ void set_dynamic_light(void) vertnum = render_vertices[vv]; Assert(vertnum >= 0 && vertnum <= Highest_vertex_index); Dynamic_light[vertnum].r = Dynamic_light[vertnum].g = Dynamic_light[vertnum].b = 0; + Dynamic_light_pp[vertnum].r = Dynamic_light_pp[vertnum].g = Dynamic_light_pp[vertnum].b = 0; } + N_light_cands = 0; cast_muzzle_flash_light(n_render_vertices, render_vertices, vert_segnum_list); for (objnum=0; objnum<=Highest_object_index; objnum++) { object *obj = &Objects[objnum]; - vms_vector *objpos = &obj->pos; g3s_lrgb obj_light_emission; obj_light_emission = compute_light_emission(objnum); if (((obj_light_emission.r+obj_light_emission.g+obj_light_emission.b)/3) > 0) - apply_light(obj_light_emission, obj->segnum, objpos, n_render_vertices, render_vertices, vert_segnum_list, objnum); + add_light_cand(obj_light_emission, obj->segnum, &obj->pos, objnum); + } + + select_pp_lights(); + for (vv = 0; vv < N_light_cands; vv++) { + light_cand *c = &Light_cands[vv]; + pp_apply = c->pp; + apply_light(c->e, c->seg, &c->pos, n_render_vertices, render_vertices, vert_segnum_list, c->objnum); } + pp_apply = 0; } // --------------------------------------------------------- diff --git a/d2/main/lighting.h b/d2/main/lighting.h index 391321f..d4b465f 100644 --- a/d2/main/lighting.h +++ b/d2/main/lighting.h @@ -27,6 +27,18 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. extern fix Beam_brightness; extern g3s_lrgb Dynamic_light[MAX_VERTICES]; +extern g3s_lrgb Dynamic_light_pp[MAX_VERTICES]; + +// The lights plight.c draws per pixel this frame (their part of Dynamic_light is in +// Dynamic_light_pp), and the viewer's headlight if it is on. +#define PP_MAX_LIGHTS 16 +typedef struct pp_light { + vms_vector pos; + g3s_lrgb emission; +} pp_light; +extern pp_light Pp_lights[PP_MAX_LIGHTS]; +extern int Pp_num_lights; +extern struct object *Pp_headlight; extern void set_dynamic_light(void); diff --git a/d2/main/menu.c b/d2/main/menu.c index 8301896..4e5e9f6 100644 --- a/d2/main/menu.c +++ b/d2/main/menu.c @@ -60,6 +60,9 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "jukebox.h" // for jukebox_exts #endif #include "config.h" +#ifdef __EMSCRIPTEN__ +#include "web.h" +#endif #include "movie.h" #include "gamepal.h" #include "gauges.h" @@ -1715,7 +1718,7 @@ int sound_menuset(newmenu *menu, d_event *event, void *userdata) GameCfg.MusicType = MUSIC_TYPE_REDBOOK; replay = 1; } -#ifdef USE_SDLMIXER +#if defined(USE_SDLMIXER) || defined(__EMSCRIPTEN__) else if (citem == opt_sm_mtype3) { GameCfg.MusicType = MUSIC_TYPE_CUSTOM; @@ -1820,7 +1823,9 @@ int sound_menuset(newmenu *menu, d_event *event, void *userdata) #ifdef USE_SDLMIXER #define SOUND_MENU_NITEMS 33 #else -#ifdef _WIN32 +#if defined(__EMSCRIPTEN__) // adds the built-in music choice and, once loaded, the music folder +#define SOUND_MENU_NITEMS 12 +#elif defined(_WIN32) // adds the built-in music choice #define SOUND_MENU_NITEMS 11 #else #define SOUND_MENU_NITEMS 10 @@ -1858,7 +1863,10 @@ void do_sound_menu() opt_sm_mtype0 = nitems; m[nitems].type = NM_TYPE_RADIO; m[nitems].text = "no music"; m[nitems].value = (GameCfg.MusicType == MUSIC_TYPE_NONE); m[nitems].group = 0; nitems++; -#if defined(USE_SDLMIXER) || defined(_WIN32) +#if defined(__EMSCRIPTEN__) + opt_sm_mtype1 = nitems; + m[nitems].type = NM_TYPE_RADIO; m[nitems].text = "original midi music"; m[nitems].value = (GameCfg.MusicType == MUSIC_TYPE_BUILTIN); m[nitems].group = 0; nitems++; +#elif defined(USE_SDLMIXER) || defined(_WIN32) opt_sm_mtype1 = nitems; m[nitems].type = NM_TYPE_RADIO; m[nitems].text = "built-in/addon music"; m[nitems].value = (GameCfg.MusicType == MUSIC_TYPE_BUILTIN); m[nitems].group = 0; nitems++; #endif @@ -1870,6 +1878,13 @@ void do_sound_menu() opt_sm_mtype3 = nitems; m[nitems].type = NM_TYPE_RADIO; m[nitems].text = "jukebox"; m[nitems].value = (GameCfg.MusicType == MUSIC_TYPE_CUSTOM); m[nitems].group = 0; nitems++; +#elif defined(__EMSCRIPTEN__) + opt_sm_mtype3 = -1; + if (d2web_music_has(-1) || GameCfg.MusicType == MUSIC_TYPE_CUSTOM) + { + opt_sm_mtype3 = nitems; + m[nitems].type = NM_TYPE_RADIO; m[nitems].text = "music folder"; m[nitems].value = (GameCfg.MusicType == MUSIC_TYPE_CUSTOM); m[nitems].group = 0; nitems++; + } #endif m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = ""; @@ -1940,7 +1955,11 @@ void do_sound_menu() m[nitems].type = NM_TYPE_INPUT; m[nitems].text = GameCfg.CMMiscMusic[SONG_ENDGAME]; m[nitems++].text_len = NM_MAX_TEXT_LEN-1; #endif +#ifdef __EMSCRIPTEN__ + Assert(nitems <= SOUND_MENU_NITEMS); // the music folder choice shows once one is loaded +#else Assert(nitems == SOUND_MENU_NITEMS); +#endif newmenu_do1( NULL, "Sound Effects & Music", nitems, m, sound_menuset, NULL, 0 ); diff --git a/d2/main/movie.c b/d2/main/movie.c index 33bd8ca..3a8fa33 100644 --- a/d2/main/movie.c +++ b/d2/main/movie.c @@ -53,6 +53,9 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "ogl_init.h" #endif #include "args.h" +#ifdef __EMSCRIPTEN__ +#include "web.h" +#endif extern char CDROM_dir[]; @@ -148,7 +151,13 @@ int PlayMovie(const char *filename, int must_have) // Start sound MVE_sndInit(!GameArg.SndNoSound ? 1 : -1); +#ifdef __EMSCRIPTEN__ + d2web_cutscene(1); +#endif ret = RunMovie(name, GameArg.GfxMovieHires, must_have, -1, -1); +#ifdef __EMSCRIPTEN__ + d2web_cutscene(0); +#endif // MD2211: if using SDL_Mixer, we never reinit the sound system if (!GameArg.SndNoSound diff --git a/d2/main/newdemo.c b/d2/main/newdemo.c index 79cf5fb..e27f272 100644 --- a/d2/main/newdemo.c +++ b/d2/main/newdemo.c @@ -87,7 +87,7 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "editor/editor.h" #endif -extern int init_hoard_data(); +extern void init_hoard_data(); extern void init_seismic_disturbances(void); #define ND_EVENT_EOF 0 // EOF diff --git a/d2/main/object.c b/d2/main/object.c index 602b2d5..9dbdef5 100644 --- a/d2/main/object.c +++ b/d2/main/object.c @@ -67,6 +67,10 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "gameseq.h" #include "playsave.h" #include "timer.h" +#include "ogl_init.h" +#ifdef __EMSCRIPTEN__ +#include "../arch/web/web.h" +#endif #ifdef EDITOR #include "editor/editor.h" #endif @@ -799,14 +803,24 @@ void render_object(object *obj) if ( PlayerCfg.AlphaEffects ) // set nice transparency/blending for certrain objects gr_settransblend( GR_FADE_OFF, GR_BLEND_ADDITIVE_C ); +#ifdef __EMSCRIPTEN__ + if (d2web_option(D2WEB_OPTION_EXPLOSIONS)) // soft-edged, and glowing in the HDR view + ogl_sprite_glow = 1.25f; +#endif draw_fireball(obj); + ogl_sprite_glow = 0; break; case RT_WEAPON_VCLIP: if ( PlayerCfg.AlphaEffects && !is_proximity_bomb_or_smart_mine(obj->id)) // set nice transparency/blending for certain objects gr_settransblend( 7, GR_BLEND_ADDITIVE_A ); +#ifdef __EMSCRIPTEN__ + if (d2web_option(D2WEB_OPTION_GLOW) && !is_proximity_bomb_or_smart_mine(obj->id)) + ogl_sprite_glow = 1.5f; +#endif draw_weapon_vclip(obj); + ogl_sprite_glow = 0; break; case RT_HOSTAGE: @@ -834,7 +848,12 @@ void render_object(object *obj) if ( PlayerCfg.AlphaEffects ) // set nice transparency/blending for certrain objects gr_settransblend( 7, GR_BLEND_ADDITIVE_A ); +#ifdef __EMSCRIPTEN__ + if (d2web_option(D2WEB_OPTION_GLOW)) + ogl_sprite_glow = 1.5f; +#endif Laser_render(obj); + ogl_sprite_glow = 0; break; default: diff --git a/d2/main/playsave.c b/d2/main/playsave.c index 1944a8c..c7d0f7e 100644 --- a/d2/main/playsave.c +++ b/d2/main/playsave.c @@ -50,6 +50,7 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "args.h" #include "vers_id.h" #include "newdemo.h" +#include "kconfig.h" #include "gauges.h" //version 5 -> 6: added new highest level information @@ -87,6 +88,36 @@ int new_player_config() PlayerCfg.ControlType=0; // Assume keyboard memcpy(PlayerCfg.KeySettings, DefaultKeySettings, sizeof(DefaultKeySettings)); memcpy(PlayerCfg.KeySettingsD2X, DefaultKeySettingsD2X, sizeof(DefaultKeySettingsD2X)); +#ifdef __EMSCRIPTEN__ + // Browser players click to capture the mouse and expect it to fly the ship, and the only + // controller layout a browser reports is the standard (Xbox-style) gamepad, so set both up. + PlayerCfg.ControlType = CONTROL_USING_MOUSE | CONTROL_USING_JOYSTICK; + { + static const ubyte pad[][2] = { + { 0, 7 }, // fire primary: right trigger + { 1, 6 }, // fire secondary: left trigger + { 4, 2 }, // fire flare: X + { 8, 0 }, // slide up: A + { 9, 1 }, // slide down: B + { 11, 4 }, // bank left: left bumper + { 12, 5 }, // bank right: right bumper + { 25, 15 }, // rear view: d-pad right + { 26, 3 }, // drop bomb: Y + { 27, 10 }, // afterburner: left stick click + { 28, 12 }, // cycle primary: d-pad up + { 29, 13 }, // cycle secondary: d-pad down + { 30, 14 }, // headlight: d-pad left + { 13, 3 }, // pitch: right stick Y + { 15, 2 }, // turn: right stick X + { 17, 0 }, // slide left/right: left stick X + { 23, 1 }, // throttle: left stick Y + }; + int i; + + for (i = 0; i < sizeof(pad) / sizeof(pad[0]); i++) + PlayerCfg.KeySettings[1][pad[i][0]] = pad[i][1]; + } +#endif kc_set_controls(); PlayerCfg.DefaultDifficulty = 1; @@ -126,8 +157,14 @@ int new_player_config() PlayerCfg.AutomapFreeFlight = 0; PlayerCfg.NoFireAutoselect = 0; PlayerCfg.CycleAutoselectOnly = 0; +#ifdef __EMSCRIPTEN__ + // the browser edition defaults new pilots to the enhanced look + PlayerCfg.AlphaEffects = 1; + PlayerCfg.DynLightColor = 1; +#else PlayerCfg.AlphaEffects = 0; PlayerCfg.DynLightColor = 0; +#endif PlayerCfg.DisableCockpit = 0; /* DisableCockpit */ PlayerCfg.StickyRearview = 0; /* StickyRearview */ PlayerCfg.SelectAfterFire = 1; /* SelectAfterFire */ diff --git a/d2/main/plight.c b/d2/main/plight.c new file mode 100644 index 0000000..1e8f349 --- /dev/null +++ b/d2/main/plight.c @@ -0,0 +1,735 @@ +/* + * Per-pixel lighting of the mine's walls (browser edition, WebGL 2). Walls are drawn with a + * shader that lights each pixel from the nearest moving lights (shots, flares, explosions, + * the ship's glow and its headlight cone) instead of only blending between corners, gives + * the textures relief and highlights from the room's lamps, and makes the lamps' bright parts + * glow. The game's own corner lighting stays the base, so rooms keep their look, and only + * where a room is lit do surfaces shine (no highlights through walls). + */ + +#define GL_GLEXT_PROTOTYPES +#include +#include +#include +#include +#include + +#include "plight.h" +#include "inferno.h" +#include "segment.h" +#include "gameseg.h" +#include "gameseq.h" +#include "game.h" +#include "object.h" +#include "player.h" +#include "lighting.h" +#include "bm.h" +#include "textures.h" +#include "piggy.h" +#include "palette.h" +#include "timer.h" +#include "../3d/globvars.h" +#include "ogl_init.h" +#ifdef __EMSCRIPTEN__ +#include "../arch/web/web.h" +#endif + +#define LAMPS_PER_SEG 4 +#define LAMP_REACH 100.0f // units from a segment's center to lamps that light it +#define HEADLIGHT_EMISSION 10.0f // lighting.c HEADLIGHT_SCALE + +static const char *world_vs = + "in vec4 a_position;\n" + "in vec4 a_texCoord0;\n" + "in vec4 a_color;\n" + "uniform mat4 u_modelView;\n" + "uniform mat4 u_projection;\n" + "out vec2 v_uv;\n" + "out vec4 v_color;\n" + "out vec3 v_pos;\n" + "void main() {\n" + " vec4 p = u_modelView * a_position;\n" + " v_uv = a_texCoord0.xy;\n" + " v_color = a_color;\n" + " v_pos = p.xyz;\n" + " gl_Position = u_projection * p;\n" + "}\n"; + +// Positions are in view space with the view's zoom and aspect undone (unscale), so lengths +// are in mine units. Lights: xyz position, w reach; colors in the game's light units (a light +// gives emission / distance, like lighting.c). The vertex color is the game's own light. +static const char *world_fs = + "#define MAX_LIGHTS 16\n" + "#define MAX_LAMPS 4\n" + "uniform sampler2D tex;\n" + "uniform vec3 unscale;\n" + "uniform vec4 mat;\n" + "uniform float pools;\n" // 1: the lamp pools shade it (0 for moving surfaces alone) // emissive, bump, gloss, kind + "uniform vec2 texsize;\n" + "uniform int nlights;\n" + "uniform vec4 lpos[MAX_LIGHTS];\n" + "uniform vec3 lcol[MAX_LIGHTS];\n" + "uniform vec4 headpos;\n" // xyz, w emission (0: off) + "uniform vec3 headdir;\n" + "uniform int nlamps;\n" + "uniform vec4 lamppos[MAX_LAMPS];\n" // xyz, w strength + "uniform vec3 lampcol[MAX_LAMPS];\n" + "uniform vec4 tune[3];\n" // relief, bump depth, headlight, moving-light shine; lamp shine, glow, light cap, + // moving-light gain; lamp pools: strength, dark away from lamps, bright near, reach + "in vec2 v_uv;\n" + "in vec4 v_color;\n" + "in vec3 v_pos;\n" + "out vec4 o;\n" + "uniform float time;\n" // seconds + "uniform sampler2D hcolor;\n" // last frame, for reflections + "uniform sampler2D hdepth;\n" + "uniform mat4 reproj;\n" // this view's space to last frame's + "uniform vec3 hscale;\n" + "uniform vec2 refl;\n" // strength, on + "uniform sampler2D nmap, gmap, emap;\n" // material maps: normal, gloss (g) and metal (r), glow + "uniform vec3 maps;\n" // which of them this texture has + "float hdist(vec2 uv) {\n" // last frame's distance along its view axis, in units + " float z = texture(hdepth, uv).r * 2.0 - 1.0;\n" + " return 2.0 * 0.1 * 5000.0 / (5000.1 - z * 4999.9) / hscale.z;\n" + "}\n" + "float lum(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }\n" + "float hash2(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }\n" + "float vnoise(vec2 p) {\n" + " vec2 i = floor(p), f = fract(p);\n" + " f = f * f * (3.0 - 2.0 * f);\n" + " return mix(mix(hash2(i), hash2(i + vec2(1.0, 0.0)), f.x), mix(hash2(i + vec2(0.0, 1.0)), hash2(i + vec2(1.0)), f.x), f.y);\n" + "}\n" + // water: the slope of three crossing ripple trains, in texture units + "vec2 ripples(vec2 uv) {\n" + " const float TAU = 6.2832;\n" + " vec2 d1 = vec2(1.0, 0.3), d2 = vec2(-0.4, 1.0), d3 = vec2(0.7, -0.8);\n" + " return d1 * cos(dot(uv, d1) * TAU * 3.0 + time * 1.7) * 3.0 * 0.5\n" + " + d2 * cos(dot(uv, d2) * TAU * 4.0 - time * 2.1) * 4.0 * 0.35\n" + " + d3 * cos(dot(uv, d3) * TAU * 7.0 + time * 2.9) * 7.0 * 0.15;\n" + "}\n" + "void main() {\n" + " int kind = int(mat.w + 0.5);\n" // 1 lava, 2 water, 3 force field + " vec2 uv = v_uv;\n" + " vec2 rip = vec2(0.0);\n" + " if (kind == 1)\n" // lava churns as it flows + " uv += vec2(sin(v_uv.y * 9.4 + time * 0.7) + 0.5 * sin((v_uv.x + v_uv.y) * 12.6 - time * 1.1),\n" + " cos(v_uv.x * 8.2 - time * 0.6) + 0.5 * cos((v_uv.x - v_uv.y) * 15.1 + time * 0.9)) * 0.011;\n" + " else if (kind == 2) {\n" // water bends what is under it + " rip = ripples(v_uv);\n" + " uv += rip * 0.004;\n" + " } else if (kind == 3)\n" + " uv.x += sin(v_uv.y * 18.8 + time * 4.0) * 0.004;\n" + " vec4 c = texture(tex, uv);\n" + " if (c.a < 0.02) discard;\n" + " vec3 P = v_pos * unscale;\n" + " vec3 dpx = dFdx(P), dpy = dFdy(P);\n" + " vec3 N = normalize(cross(dpx, dpy));\n" + " vec3 V = normalize(-P);\n" + " if (dot(N, V) < 0.0) N = -N;\n" + // relief: height from the texture's brightness, through the surface's own uv frame; it + // fades out where texels get smaller than pixels, so distant walls don't shimmer + " vec2 dux = dFdx(v_uv), duy = dFdy(v_uv);\n" + " vec3 sx = cross(dpy, N), sy = cross(N, dpx);\n" + " vec3 T = sx * dux.x + sy * duy.x, B = sx * dux.y + sy * duy.y;\n" + " float ts = inversesqrt(max(max(dot(T, T), dot(B, B)), 1e-12));\n" + " float foot = max(length(dux * texsize), length(duy * texsize));\n" + " float bump = mat.y * (1.0 - smoothstep(0.7, 2.5, foot));\n" + " vec3 Nb = N;\n" + " if (maps.x > 0.5) {\n" // a normal map: the surface's real shape (fading only far off; its mips smooth it) + " vec3 n = texture(nmap, uv).xyz * 2.0 - 1.0;\n" + " vec3 Nm = normalize(N * max(n.z, 0.05) + normalize(T) * n.x + normalize(B) * n.y);\n" + " Nb = normalize(mix(N, Nm, (1.0 - smoothstep(2.0, 8.0, foot)) * tune[0].y / 5.0));\n" + " } else if (bump > 0.001) {\n" + " vec2 tx = vec2(1.0 / texsize.x, 0.0), ty = vec2(0.0, 1.0 / texsize.y);\n" + " vec2 g = vec2(lum(texture(tex, uv + tx).rgb) - lum(texture(tex, uv - tx).rgb),\n" + " lum(texture(tex, uv + ty).rgb) - lum(texture(tex, uv - ty).rgb)) * 0.5;\n" + " Nb = normalize(N - (T * g.x + B * g.y) * ts * bump * tune[0].y);\n" + " }\n" + " if (kind == 2)\n" + " Nb = normalize(Nb - (T * rip.x + B * rip.y) * ts * 0.05);\n" + " float gloss = kind == 2 ? 0.85 : mat.z, metal = 0.0;\n" + " if (maps.y > 0.5 && kind != 2) {\n" + " vec2 gm = texture(gmap, uv).gr;\n" + " gloss = gm.x;\n" + " metal = gm.y;\n" + " }\n" + " float shin = mix(10.0, 48.0, gloss);\n" + " vec3 base = v_color.rgb;\n" + " float lit = min(lum(base) * 2.0, 1.0);\n" + // the room's lamps: the direction the bumps catch light from, and highlights + " vec3 ld = vec3(0.0), spec = vec3(0.0), pool = vec3(0.0);\n" + " float lw = 0.0;\n" + " for (int i = 0; i < MAX_LAMPS; i++) {\n" + " if (i >= nlamps) break;\n" + " vec3 L = lamppos[i].xyz - P;\n" + " float d2 = dot(L, L);\n" + " L *= inversesqrt(d2);\n" + " float f = max(dot(N, L), 0.0) * lamppos[i].w / (1.0 + d2 / 900.0);\n" + " ld += L * f;\n" + " lw += f;\n" + " spec += lampcol[i] * f * pow(max(dot(Nb, normalize(L + V)), 0.0), shin);\n" + " pool += lampcol[i] * max(dot(Nb, L), 0.0) * lamppos[i].w / (1.0 + d2 / (tune[2].w * tune[2].w));\n" + " }\n" + // pools of the lamps' own colored light; away from them the room falls darker + " float pa = lum(pool), amt = pa / (pa + 0.4);\n" + " vec3 tint = pa > 1e-4 ? pool / pa : vec3(1.0);\n" + " vec3 shade = mix(vec3(1.0), mix(vec3(tune[2].y), tint * tune[2].z, amt), tune[2].x * pools);\n" + // a pool lifts dim walls fully but walls the game already lights fully only a little + " shade = 1.0 + (shade - 1.0) * mix(vec3(1.0), vec3(clamp(1.2 - lum(base), 0.15, 1.0)), step(1.0, shade));\n" + " vec3 Ld = lw > 1e-4 ? normalize(ld) : V;\n" + " float relief = clamp(1.0 + (dot(Nb, Ld) - dot(N, Ld)) * tune[0].x, 0.35, 1.7);\n" + " spec *= gloss * lit * tune[1].x;\n" + // moving lights, per pixel + " vec3 dyn = vec3(0.0);\n" + " for (int i = 0; i < MAX_LIGHTS; i++) {\n" + " if (i >= nlights) break;\n" + " vec3 L = lpos[i].xyz - P;\n" + " float d = length(L);\n" + " L /= max(d, 1e-3);\n" + " vec3 e = lcol[i] * (tune[1].w * smoothstep(lpos[i].w, lpos[i].w * 0.7, d) / max(d, 4.0));\n" + " dyn += e * (0.25 + 0.75 * max(dot(Nb, L), 0.0));\n" + " spec += e * pow(max(dot(Nb, normalize(L + V)), 0.0), shin) * gloss * tune[0].w;\n" + " }\n" + " if (headpos.w > 0.0) {\n" + " vec3 L = headpos.xyz - P;\n" + " float d = length(L);\n" + " L /= max(d, 1e-3);\n" + " float cd = dot(-L, headdir);\n" + " float cone = smoothstep(0.5, 0.85, cd) * pow(cd, 4.0) * headpos.w * tune[0].z / (1.0 + d * d / 40000.0);\n" + " float h = max(cone, headpos.w / 10.0 / max(d, 4.0));\n" + " dyn += vec3(h) * (0.25 + 0.75 * max(dot(Nb, L), 0.0));\n" + " spec += vec3(h) * pow(max(dot(Nb, normalize(L + V)), 0.0), shin) * gloss * 0.5;\n" + " }\n" + " vec3 light = min(base * relief * shade + dyn, vec3(tune[1].z));\n" + " vec3 rgb = c.rgb * light * (1.0 - metal * 0.4) + spec * mix(vec3(1.0), c.rgb * 1.6, mix(0.5, 1.0, metal));\n" // metal tints its shine + // a lamp's bright parts give light: they glow (or what its glow map says) + " float m = max(max(c.r, c.g), c.b);\n" + " if (maps.z > 0.5)\n" + " rgb += texture(emap, uv).rgb * tune[1].y * 1.5;\n" + " else\n" + " rgb += c.rgb * smoothstep(0.55, 0.95, m) * mat.x * tune[1].y;\n" + // reflections: march the reflected ray through last frame's view until it passes behind + // what was seen there; shiny surfaces take that color, more at grazing angles + " if (refl.y > 0.5 && gloss > 0.4) {\n" // smooth metal and water, not rock + " vec3 R = reflect(-V, normalize(mix(N, Nb, 0.35)));\n" // the relief only ruffles it + " float fres = 0.04 + 0.96 * pow(1.0 - max(dot(Nb, V), 0.0), 5.0);\n" + " float amt = refl.x * gloss * gloss * mix(0.25, 1.0, fres) * min(lum(base) * 3.0, 1.0);\n" + " if (refl.x > 50.0) rgb = vec3(0.15, 0.0, 0.15);\n" + " vec3 X = P + N * 0.05;\n" + " float st = 0.8;\n" + " for (int i = 0; i < 14; i++) {\n" + " if (amt < 0.01) break;\n" + " X += R * st;\n" + " st *= 1.32;\n" + " vec3 xp = (reproj * vec4(X, 1.0)).xyz;\n" + " if (xp.z > -0.2) break;\n" + " vec3 e = xp * hscale;\n" + " vec2 u = e.xy / -e.z * 0.5 + 0.5;\n" + " if (any(lessThan(u, vec2(0.0))) || any(greaterThan(u, vec2(1.0)))) break;\n" + " float sd = hdist(u), rd = -xp.z;\n" + " if (rd > sd + 0.02) {\n" + " if (rd < sd + st * 1.5 + 0.5) {\n" + " vec2 f = smoothstep(0.0, 0.08, u) * smoothstep(1.0, 0.92, u);\n" + " vec3 hit = texture(hcolor, u).rgb * f.x * f.y * (1.0 - float(i) / 14.0);\n" + " rgb = refl.x > 50.0 ? hit + vec3(0.0, 0.2, 0.0) : rgb * (1.0 - amt * 0.3) + hit * amt;\n" // > 50: test view + " }\n" + " break;\n" + " }\n" + " }\n" + " }\n" + " if (kind == 1)\n" // lava glows, brightest where it is hottest, in slow waves + " rgb += c.rgb * smoothstep(0.2, 0.7, m) * (0.5 + 0.7 * vnoise(uv * 5.0 + vec2(time * 0.2, -time * 0.13))) * 0.9;\n" + " else if (kind == 2)\n" // water: brighter at grazing angles, like a reflection + " rgb += base * c.rgb * pow(1.0 - max(dot(Nb, V), 0.0), 4.0) * 0.6;\n" + " else if (kind == 3)\n" // force fields shimmer with running bands of energy + " rgb += c.rgb * (0.5 + 0.5 * sin(v_uv.y * 37.7 - time * 5.0)) * (0.4 + 0.6 * vnoise(v_uv * 9.0 + time * 1.5)) * 1.1;\n" + " o = vec4(rgb, c.a * v_color.a);\n" + "}\n"; + +static struct { + int tried; + GLuint prog; + GLint pools, time, refl, reproj, hscale, tune, unscale, mat, texsize, nlights, lpos, lcol, headpos, headdir, nlamps, lamppos, lampcol, maps; +} W; + +typedef struct lamp { + float pos[3]; // world, mine units + float col[3]; + float strength; + short seg; + sbyte side; +} lamp; + +static lamp Lamps[MAX_SEGMENTS * MAX_SIDES_PER_SEGMENT]; +static short Seg_lamps[MAX_SEGMENTS][LAMPS_PER_SEG]; +static ubyte Seg_nlamps[MAX_SEGMENTS]; +static int Built_level = -1000, Built_segs = -1; + +typedef struct texmat { + float gloss, bump; + char done; +} texmat; + +static texmat Mats[MAX_TEXTURES]; + +static struct { + int on, lit, seg, side, tmap1, tmap2; // lit: per-pixel lighting (else only a moving surface) +} Face; +static int Frame_dirty, Lamps_seg = -1; + +static int ready(void) +{ + if (!W.tried) { + GLuint p; + W.tried = 1; +#ifdef __EMSCRIPTEN__ + if (d2web_gl_version() < 2) + return 0; +#endif + if (!(p = W.prog = ogl_program3(world_vs, "", world_fs))) + return 0; + glUseProgram(p); + glUniform1i(glGetUniformLocation(p, "tex"), 0); + W.tune = glGetUniformLocation(p, "tune"); + W.time = glGetUniformLocation(p, "time"); + W.pools = glGetUniformLocation(p, "pools"); + W.refl = glGetUniformLocation(p, "refl"); + W.reproj = glGetUniformLocation(p, "reproj"); + W.hscale = glGetUniformLocation(p, "hscale"); + glUniform1i(glGetUniformLocation(p, "hcolor"), 1); + glUniform1i(glGetUniformLocation(p, "hdepth"), 2); + glUniform1i(glGetUniformLocation(p, "nmap"), 3); + glUniform1i(glGetUniformLocation(p, "gmap"), 4); + glUniform1i(glGetUniformLocation(p, "emap"), 5); + W.maps = glGetUniformLocation(p, "maps"); + W.unscale = glGetUniformLocation(p, "unscale"); + W.mat = glGetUniformLocation(p, "mat"); + W.texsize = glGetUniformLocation(p, "texsize"); + W.nlights = glGetUniformLocation(p, "nlights"); + W.lpos = glGetUniformLocation(p, "lpos"); + W.lcol = glGetUniformLocation(p, "lcol"); + W.headpos = glGetUniformLocation(p, "headpos"); + W.headdir = glGetUniformLocation(p, "headdir"); + W.nlamps = glGetUniformLocation(p, "nlamps"); + W.lamppos = glGetUniformLocation(p, "lamppos"); + W.lampcol = glGetUniformLocation(p, "lampcol"); + glUseProgram(0); + } + return W.prog != 0; +} + +int plight_enabled(void) +{ +#ifdef __EMSCRIPTEN__ + return d2web_option(D2WEB_OPTION_LIGHTING) && ready(); +#else + return 0; +#endif +} + +// How shiny and how bumpy a texture looks, from its pixels: grey, smooth metal shines; colorful +// or noisy rock barely does and has deeper relief. +static texmat *material(int tmap) +{ + texmat *m = &Mats[tmap]; + if (!m->done) { + grs_bitmap *bm = &GameBitmaps[Textures[tmap].index]; + unsigned char *px; + float *l, sat = 0, noise = 0, rough; + int w, h, x, y, n = 0; + + m->done = 1; + m->gloss = 0.3f; + m->bump = 0.8f; + PIGGY_PAGE_IN(Textures[tmap]); + w = bm->bm_w; + h = bm->bm_h; + if (w < 4 || h < 4 || !(px = ogl_bitmap_indices(bm)) || !(l = malloc(w * h * sizeof(float)))) + return m; + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + int c = px[y * w + x]; + float r = gr_palette[c * 3] / 63.0f, g = gr_palette[c * 3 + 1] / 63.0f, b = gr_palette[c * 3 + 2] / 63.0f; + float mx = fmaxf(r, fmaxf(g, b)), mn = fminf(r, fminf(g, b)); + l[y * w + x] = 0.299f * r + 0.587f * g + 0.114f * b; + if (c != 255 && mx > 0.05f) { + sat += (mx - mn) / mx; + n++; + } + } + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + float avg = (l[y * w + (x + 1) % w] + l[y * w + (x + w - 1) % w] + l[((y + 1) % h) * w + x] + l[((y + h - 1) % h) * w + x]) / 4; + noise += fabsf(l[y * w + x] - avg); + } + free(l); + sat = n ? sat / n : 0; + noise /= w * h; + rough = fminf(fmaxf((noise - 0.015f) / 0.06f, 0), 1); + m->gloss = fminf(fmaxf(0.75f - sat * 1.6f, 0.08f), 0.7f) * (1 - rough * 0.85f); // rock stays matte + m->bump = 0.55f + rough * 0.6f; + } + return m; +} + +static void bitmap_color(int tmap, float *col) +{ + grs_bitmap *bm = &GameBitmaps[Textures[tmap].index]; + float mx; + PIGGY_PAGE_IN(Textures[tmap]); + col[0] = bm->avg_color_rgb[0]; + col[1] = bm->avg_color_rgb[1]; + col[2] = bm->avg_color_rgb[2]; + mx = fmaxf(col[0], fmaxf(col[1], col[2])); + if (mx <= 0) { + col[0] = col[1] = col[2] = 1; + return; + } + // a lamp's color, as bright as white (the average includes its dark frame) + col[0] = 0.3f + 0.7f * col[0] / mx; + col[1] = 0.3f + 0.7f * col[1] / mx; + col[2] = 0.3f + 0.7f * col[2] / mx; +} + +// The lamps (sides with light-giving textures) of the level and the strongest few that reach +// each segment through its open sides. +static void build_lamps(void) +{ + static int visit[MAX_SEGMENTS], stamp; + static short queue[MAX_SEGMENTS]; + static sbyte depth[MAX_SEGMENTS]; + static int first[MAX_SEGMENTS + 1]; + int seg, sn, n = 0; + + Built_level = Current_level_num; + Built_segs = Highest_segment_index; + memset(Mats, 0, sizeof(Mats)); + for (seg = 0; seg <= Highest_segment_index; seg++) { + first[seg] = n; + for (sn = 0; sn < MAX_SIDES_PER_SEGMENT; sn++) { + side *s = &Segments[seg].sides[sn]; + int t1 = s->tmap_num, t2 = s->tmap_num2 & 0x3fff; + fix light = TmapInfo[t1].lighting + (t2 ? TmapInfo[t2].lighting : 0); + vms_vector c, nrm; + lamp *l; + if (Segments[seg].children[sn] != -1 || light <= 0) + continue; + compute_center_point_on_side(&c, &Segments[seg], sn); + vm_vec_avg(&nrm, &s->normals[0], &s->normals[1]); + vm_vec_normalize_quick(&nrm); + vm_vec_scale_add2(&c, &nrm, F1_0); + l = &Lamps[n++]; + l->pos[0] = f2fl(c.x); + l->pos[1] = f2fl(c.y); + l->pos[2] = f2fl(c.z); + bitmap_color(t2 && TmapInfo[t2].lighting > 0 ? t2 : t1, l->col); + l->strength = f2fl(light); + l->seg = seg; + l->side = sn; + } + } + first[seg] = n; + + for (seg = 0; seg <= Highest_segment_index; seg++) { + float best[LAMPS_PER_SEG], cx, cy, cz; + int head = 0, tail = 0, k, cnt = 0; + vms_vector c; + compute_segment_center(&c, &Segments[seg]); + cx = f2fl(c.x); + cy = f2fl(c.y); + cz = f2fl(c.z); + stamp++; + queue[tail++] = seg; + visit[seg] = stamp; + depth[seg] = 0; + while (head < tail) { + int s = queue[head++], i; + for (i = first[s]; i < first[s + 1]; i++) { + float dx = Lamps[i].pos[0] - cx, dy = Lamps[i].pos[1] - cy, dz = Lamps[i].pos[2] - cz; + float d2 = dx * dx + dy * dy + dz * dz, score; + if (d2 > LAMP_REACH * LAMP_REACH) + continue; + score = Lamps[i].strength / (1 + d2 / 900); + // keep the best few, best first + if (cnt < LAMPS_PER_SEG) + k = cnt++; + else if (score > best[LAMPS_PER_SEG - 1]) + k = LAMPS_PER_SEG - 1; + else + continue; + for (; k > 0 && best[k - 1] < score; k--) { + best[k] = best[k - 1]; + Seg_lamps[seg][k] = Seg_lamps[seg][k - 1]; + } + best[k] = score; + Seg_lamps[seg][k] = i; + } + if (depth[s] < 3) + for (i = 0; i < MAX_SIDES_PER_SEGMENT; i++) { + int ch = Segments[s].children[i]; + if (ch >= 0 && visit[ch] != stamp) { + visit[ch] = stamp; + depth[ch] = depth[s] + 1; + queue[tail++] = ch; + } + } + } + Seg_nlamps[seg] = cnt; + } +} + +static void to_view(const vms_vector *p, float *out) +{ + vms_vector t, r; + vm_vec_sub(&t, p, &View_position); + vm_vec_rotate(&r, &t, &Unscaled_matrix); + out[0] = f2fl(r.x); + out[1] = f2fl(r.y); + out[2] = -f2fl(r.z); +} + +static void dir_to_view(const vms_vector *d, float *out) +{ + vms_vector r; + vm_vec_rotate(&r, d, &Unscaled_matrix); + out[0] = f2fl(r.x); + out[1] = f2fl(r.y); + out[2] = -f2fl(r.z); +} + +void plight_frame(void) +{ + Frame_dirty = 1; + Lamps_seg = -1; + Face.on = 0; +} + +static int surfaces_enabled(void) +{ +#ifdef __EMSCRIPTEN__ + return d2web_option(D2WEB_OPTION_SURFACES) && ready(); +#else + return 0; +#endif +} + +#define SURFACE_FLAGS (TMI_VOLATILE | TMI_WATER | TMI_FORCE_FIELD) + +int plight_side(int segnum, int sidenum, int tmap1, int tmap2) +{ + int lit = plight_enabled(); + Face.on = 0; + if (!lit && !(surfaces_enabled() && ((TmapInfo[tmap1].flags | (tmap2 ? TmapInfo[tmap2 & 0x3fff].flags : 0)) & SURFACE_FLAGS))) + return 0; + if (Built_level != Current_level_num || Built_segs != Highest_segment_index) + build_lamps(); + Face.on = 1; + Face.lit = lit; + Face.seg = segnum; + Face.side = sidenum; + Face.tmap1 = tmap1; + Face.tmap2 = tmap2 & 0x3fff; + return lit; +} + +void plight_side_done(void) +{ + Face.on = 0; +} + +static void upload_frame(void) +{ + float pos[PP_MAX_LIGHTS][4], col[PP_MAX_LIGHTS][3]; + int i; +#ifdef __EMSCRIPTEN__ + glUniform4f(W.tune, d2web_tune(0, 2.6f), d2web_tune(1, 5.0f), d2web_tune(2, 0.1f), d2web_tune(3, 0.9f)); + glUniform4f(W.tune + 1, d2web_tune(4, 0.45f), d2web_tune(5, 0.8f), d2web_tune(6, 1.8f), d2web_tune(24, 1.6f)); + glUniform4f(W.tune + 2, d2web_tune(20, 1.0f), d2web_tune(21, 0.42f), d2web_tune(22, 1.9f), d2web_tune(23, 36.0f)); +#endif + glUniform3f(W.unscale, 1 / f2fl(Matrix_scale.x), 1 / f2fl(Matrix_scale.y), 1 / f2fl(Matrix_scale.z)); + glUniform1f(W.time, (float)(GameTime64 % (F1_0 * 3600LL)) / F1_0); + glUniform2f(W.refl, 0, 0); + if (!plight_enabled()) { // only moving surfaces + glUniform1i(W.nlights, 0); + glUniform4f(W.headpos, 0, 0, 0, 0); + return; + } + { + unsigned hc, hd; + float reproj[16], hs[3]; + if (d2web_option(D2WEB_OPTION_REFLECTIONS) && ogl_post_history(&hc, &hd, reproj, hs)) { + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, hc); + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, hd); + glActiveTexture(GL_TEXTURE0); + glUniformMatrix4fv(W.reproj, 1, GL_FALSE, reproj); + glUniform3f(W.hscale, hs[0], hs[1], hs[2]); + glUniform2f(W.refl, d2web_tune(19, 0.7f), 1); + } + } + for (i = 0; i < Pp_num_lights; i++) { + pp_light *l = &Pp_lights[i]; + to_view(&l->pos, pos[i]); + pos[i][3] = f2fl((l->emission.r + l->emission.g + l->emission.b) / 3) * 64; + col[i][0] = f2fl(l->emission.r); + col[i][1] = f2fl(l->emission.g); + col[i][2] = f2fl(l->emission.b); + } + glUniform1i(W.nlights, Pp_num_lights); + if (Pp_num_lights) { + glUniform4fv(W.lpos, Pp_num_lights, pos[0]); + glUniform3fv(W.lcol, Pp_num_lights, col[0]); + } + if (Pp_headlight) { + float hp[3], hd[3]; + to_view(&Pp_headlight->pos, hp); + dir_to_view(&Pp_headlight->orient.fvec, hd); + glUniform4f(W.headpos, hp[0], hp[1], hp[2], HEADLIGHT_EMISSION); + glUniform3f(W.headdir, hd[0], hd[1], hd[2]); + } else + glUniform4f(W.headpos, 0, 0, 0, 0); +} + +static void upload_lamps(int seg) +{ + float pos[LAMPS_PER_SEG][4], col[LAMPS_PER_SEG][3]; + int i, n = 0; + for (i = 0; i < Seg_nlamps[seg]; i++) { + lamp *l = &Lamps[Seg_lamps[seg][i]]; + vms_vector p; + if (Light_subtracted[l->seg] & (1 << l->side)) + continue; + p.x = fl2f(l->pos[0]); + p.y = fl2f(l->pos[1]); + p.z = fl2f(l->pos[2]); + to_view(&p, pos[n]); + pos[n][3] = l->strength; + memcpy(col[n], l->col, sizeof(col[n])); + n++; + } + glUniform1i(W.nlamps, n); + if (n) { + glUniform4fv(W.lamppos, n, pos[0]); + glUniform3fv(W.lampcol, n, col[0]); + } +} + +int plight_bind(grs_bitmap *bm, int overlay) +{ + int tmap, lit, flags, kind; + texmat *m; + if (!Face.on || !bm->gltexture) + return 0; + tmap = overlay ? Face.tmap2 : Face.tmap1; + glUseProgram(W.prog); + if (Frame_dirty) { + upload_frame(); + Frame_dirty = 0; + } + if (Lamps_seg != Face.seg) { + if (Face.lit) + upload_lamps(Face.seg); + else + glUniform1i(W.nlamps, 0); + Lamps_seg = Face.seg; + } + m = material(tmap); + lit = TmapInfo[tmap].lighting > 0; + if (!overlay && Face.tmap2 && bm != &GameBitmaps[Textures[Face.tmap1].index]) // merged with its overlay + lit |= TmapInfo[Face.tmap2].lighting > 0; + if (Light_subtracted[Face.seg] & (1 << Face.side)) + lit = 0; + flags = surfaces_enabled() ? TmapInfo[tmap].flags : 0; + if (!overlay && Face.tmap2 && bm != &GameBitmaps[Textures[Face.tmap1].index]) + flags |= surfaces_enabled() ? TmapInfo[Face.tmap2].flags : 0; + kind = flags & TMI_VOLATILE ? 1 : flags & TMI_WATER ? 2 : flags & TMI_FORCE_FIELD ? 3 : 0; + if (Face.lit) + glUniform4f(W.mat, lit ? 1.0f : 0.0f, m->bump, m->gloss, kind); + else + glUniform4f(W.mat, 0, 0, 0, kind); + glUniform1f(W.pools, Face.lit ? 1 : 0); + glUniform2f(W.texsize, bm->gltexture->tw, bm->gltexture->th); + { // material maps (merged with its overlay: the base texture's, which share its uvs) + ogl_texture *t = bm->gltexture; + grs_bitmap *base = &GameBitmaps[Textures[Face.tmap1].index]; + if (!overlay && Face.tmap2 && bm != base && base->gltexture) + t = base->gltexture; + glUniform3f(W.maps, t->nmap ? 1 : 0, t->gmap ? 1 : 0, t->emap ? 1 : 0); + if (t->nmap || t->gmap || t->emap) { + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, t->nmap); + glActiveTexture(GL_TEXTURE4); + glBindTexture(GL_TEXTURE_2D, t->gmap); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_2D, t->emap); + glActiveTexture(GL_TEXTURE0); + } + } + return 1; +} + +void plight_unbind(void) +{ + glUseProgram(0); +} + +int plight_haze_enabled(void) +{ +#ifdef __EMSCRIPTEN__ + return d2web_option(D2WEB_OPTION_HAZE) && d2web_gl_version() >= 2; +#else + return 0; +#endif +} + +// The moving lights (not the ship's own glow and muzzle flashes, which would veil the whole +// view) and the lamps that light the viewer's segment. +int plight_haze_lights(float (*pos)[4], float (*col)[3], int max) +{ + int i, n = 0, seg = Viewer ? Viewer->segnum : -1; +#ifdef __EMSCRIPTEN__ + float lamp_gain = d2web_tune(18, 5.0f); +#else + float lamp_gain = 5.0f; +#endif + if (Built_level != Current_level_num || Built_segs != Highest_segment_index) + build_lamps(); + for (i = 0; i < Pp_num_lights && n < max; i++) { + pp_light *l = &Pp_lights[i]; + if (vm_vec_dist_quick(&l->pos, &View_position) < F1_0 * 8) + continue; + to_view(&l->pos, pos[n]); + pos[n][3] = 0; + col[n][0] = f2fl(l->emission.r); + col[n][1] = f2fl(l->emission.g); + col[n][2] = f2fl(l->emission.b); + n++; + } + if (seg >= 0 && seg <= Highest_segment_index) + for (i = 0; i < Seg_nlamps[seg] && n < max; i++) { + lamp *l = &Lamps[Seg_lamps[seg][i]]; + vms_vector p; + if (Light_subtracted[l->seg] & (1 << l->side)) + continue; + p.x = fl2f(l->pos[0]); + p.y = fl2f(l->pos[1]); + p.z = fl2f(l->pos[2]); + to_view(&p, pos[n]); + pos[n][3] = 0; + col[n][0] = l->col[0] * l->strength * lamp_gain; + col[n][1] = l->col[1] * l->strength * lamp_gain; + col[n][2] = l->col[2] * l->strength * lamp_gain; + n++; + } + return n; +} + +int plight_headlight(float *pos, float *dir) +{ + if (!Viewer || Viewer->type != OBJ_PLAYER || !(Players[Viewer->id].flags & PLAYER_FLAGS_HEADLIGHT_ON)) + return 0; + to_view(&Viewer->pos, pos); + dir_to_view(&Viewer->orient.fvec, dir); + return 1; +} diff --git a/d2/main/plight.h b/d2/main/plight.h new file mode 100644 index 0000000..629d5c7 --- /dev/null +++ b/d2/main/plight.h @@ -0,0 +1,22 @@ +/* + * Per-pixel lighting of the mine's walls (browser edition). Purely visual. + */ + +#ifndef _PLIGHT_H +#define _PLIGHT_H + +#include "gr.h" + +int plight_enabled(void); // walls are lit per pixel (option on, WebGL 2) +void plight_frame(void); // a 3D view is about to be drawn +int plight_side(int segnum, int sidenum, int tmap1, int tmap2); // render_face draws this side next (1: per pixel) +void plight_side_done(void); +int plight_bind(grs_bitmap *bm, int overlay); // g3_draw_tmap: draw the bound bitmap per pixel (1: program bound) +void plight_unbind(void); + +// for the light haze (ogl_post.c): lights in view space (xyz, w unused) and their colors +int plight_haze_enabled(void); +int plight_haze_lights(float (*pos)[4], float (*col)[3], int max); +int plight_headlight(float *pos, float *dir); // 1: the viewer's headlight is on + +#endif diff --git a/d2/main/polyobj.c b/d2/main/polyobj.c index 823ccc1..2f8d7d3 100644 --- a/d2/main/polyobj.c +++ b/d2/main/polyobj.c @@ -528,7 +528,7 @@ void draw_polygon_model(vms_vector *pos,vms_matrix *orient,vms_angvec *anim_angl #ifdef OGL if (!(Game_mode & GM_MULTI) || Netgame.AllowCustomModelsTextures) - if (xmodel_show_if_loaded(XM_POLYOBJ, model_num, pos, orient, alt_textures_to_ship_color(alt_textures), &light)) + if (xmodel_show_polyobj(model_num, pos, orient, anim_angles, flags, alt_textures_to_ship_color(alt_textures), &light)) return; #endif diff --git a/d2/main/powerup.c b/d2/main/powerup.c index 650f69e..68d5617 100644 --- a/d2/main/powerup.c +++ b/d2/main/powerup.c @@ -255,7 +255,7 @@ int pick_up_vulcan_ammo(void) extern void invalidate_escort_goal(void); extern char GetKeyValue(char); -extern void check_to_use_primary(int); +extern int check_to_use_primary(int); extern void multi_send_got_flag (char); // returns true if powerup consumed diff --git a/d2/main/render.c b/d2/main/render.c index 517bc8a..03ae248 100644 --- a/d2/main/render.c +++ b/d2/main/render.c @@ -27,6 +27,8 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "bm.h" #include "texmap.h" #include "render.h" +#include "fx.h" +#include "plight.h" #include "game.h" #include "object.h" #include "laser.h" @@ -206,11 +208,12 @@ void render_face(int segnum, int sidenum, int nv, int *vp, int tmap1, int tmap2, g3s_uvl uvl_copy[8]; g3s_lrgb dyn_light[8]; - int i; + int i, pp; const g3s_point *pointlist[8]; Assert(nv <= 8); + fx_note_face(segnum, sidenum); for (i=0; i MAX_LIGHT) uvl_copy[i].l = MAX_LIGHT; @@ -298,9 +308,9 @@ void render_face(int segnum, int sidenum, int nv, int *vp, int tmap1, int tmap2, } // add light color - dyn_light[i].r += Dynamic_light[vp[i]].r; - dyn_light[i].g += Dynamic_light[vp[i]].g; - dyn_light[i].b += Dynamic_light[vp[i]].b; + dyn_light[i].r += dl.r; + dyn_light[i].g += dl.g; + dyn_light[i].b += dl.b; // saturate at max value if (dyn_light[i].r > MAX_LIGHT) dyn_light[i].r = MAX_LIGHT; @@ -333,6 +343,7 @@ void render_face(int segnum, int sidenum, int nv, int *vp, int tmap1, int tmap2, g3_draw_tmap(nv,pointlist,uvl_copy,dyn_light,bm); gr_settransblend(GR_FADE_OFF, GR_BLEND_NORMAL); // revert any transparency/blending setting back to normal + plight_side_done(); #ifndef NDEBUG if (Outline_mode) draw_outline(nv, pointlist); @@ -1605,10 +1616,13 @@ fix Zoom_factor=F1_0; //renders onto current canvas void render_frame(fix eye_offset, int window_num) { - int start_seg_num; + int start_seg_num, post; if (Endlevel_sequence) { + int post = window_num == 0 && ogl_post_begin(); render_endlevel_frame(eye_offset); + if (post) + ogl_post_end(); return; } @@ -1623,7 +1637,9 @@ void render_frame(fix eye_offset, int window_num) //Here: start_lighting_frame(Viewer); //this is for ugly light-smoothing hack - + + post = window_num == 0 && ogl_post_begin(); // main view: drawn off-screen for glow etc. + plight_frame(); g3_start_frame(); Viewer_eye = Viewer->pos; @@ -1678,8 +1694,11 @@ void render_frame(fix eye_offset, int window_num) #endif render_mine(start_seg_num, eye_offset, window_num); + fx_render(); // light halos, smoke and sparks g3_end_frame(); + if (post) + ogl_post_end(); //RenderingType=0; diff --git a/d2/main/songs.c b/d2/main/songs.c index cf9fb7d..76e008b 100644 --- a/d2/main/songs.c +++ b/d2/main/songs.c @@ -31,6 +31,9 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "digi_mixer_music.h" #include "jukebox.h" #endif +#ifdef __EMSCRIPTEN__ +#include "web.h" +#endif #include "config.h" #include "timer.h" #include "args.h" @@ -59,6 +62,10 @@ void songs_set_volume(int volume) #ifdef USE_SDLMIXER mix_set_music_volume(volume); #endif +#ifdef __EMSCRIPTEN__ + d2web_midi_volume(volume); + d2web_music_volume(volume); +#endif } // Set up everything for our music @@ -149,12 +156,14 @@ void songs_init() if (1) #endif { -#ifndef _WIN32 +#if !defined(_WIN32) && !defined(__EMSCRIPTEN__) if (GameCfg.MusicType == MUSIC_TYPE_BUILTIN) GameCfg.MusicType = MUSIC_TYPE_NONE; #endif +#ifndef __EMSCRIPTEN__ // the page plays the music folder itself if (GameCfg.MusicType == MUSIC_TYPE_CUSTOM) GameCfg.MusicType = MUSIC_TYPE_NONE; +#endif } if (GameCfg.MusicType == MUSIC_TYPE_REDBOOK) @@ -188,6 +197,10 @@ void songs_stop_all(void) #ifdef USE_SDLMIXER mix_stop_music(); #endif +#ifdef __EMSCRIPTEN__ + d2web_midi_stop(); + d2web_music_stop(); +#endif Song_playing = -1; } @@ -202,6 +215,10 @@ void songs_pause(void) #ifdef USE_SDLMIXER mix_pause_music(); #endif +#ifdef __EMSCRIPTEN__ + d2web_midi_pause(); + d2web_music_pause(); +#endif } void songs_resume(void) @@ -214,6 +231,10 @@ void songs_resume(void) #ifdef USE_SDLMIXER mix_resume_music(); #endif +#ifdef __EMSCRIPTEN__ + d2web_midi_resume(); + d2web_music_resume(); +#endif } void songs_pause_resume(void) @@ -223,6 +244,10 @@ void songs_pause_resume(void) #ifdef USE_SDLMIXER mix_pause_resume_music(); #endif +#ifdef __EMSCRIPTEN__ + d2web_midi_pause_resume(); + d2web_music_pause_resume(); +#endif } /* @@ -300,6 +325,8 @@ int songs_play_file(char *filename, int repeat, void (*hook_finished_track)()) return digi_win32_play_midi_song( filename, repeat ); #elif defined(USE_SDLMIXER) return mix_play_file( filename, repeat, hook_finished_track ); +#elif defined(__EMSCRIPTEN__) + return d2web_play_hmp( filename, repeat ); #else return 0; #endif @@ -356,6 +383,18 @@ int songs_play_song( int songnum, int repeat ) Song_playing = songnum; } } +#ifdef __EMSCRIPTEN__ + // The CD has no briefing, level-end or game-end tracks: the original game played its + // MIDI songs there, so do the same (a missing song keeps the current music going) + else if (songnum != SONG_TITLE && songnum != SONG_CREDITS && PHYSFSX_exists(BIMSongs[songnum].filename, 1)) + { + if (songs_play_file(BIMSongs[songnum].filename, repeat, NULL)) + { + Redbook_playing = 0; + Song_playing = songnum; + } + } +#endif break; } #ifdef USE_SDLMIXER @@ -373,6 +412,19 @@ int songs_play_song( int songnum, int repeat ) Song_playing = songnum; break; } +#elif defined(__EMSCRIPTEN__) + case MUSIC_TYPE_CUSTOM: + { + // EXCEPTION: If the folder has no SONG_ENDLEVEL, continue playing level song. + if (Song_playing >= SONG_FIRST_LEVEL_SONG && songnum == SONG_ENDLEVEL && !d2web_music_has(songnum)) + return Song_playing; + + songs_stop_all(); + // Play the credits song after the title song if original CD track order was chosen + if (d2web_music_song(songnum, repeat, songnum == SONG_TITLE && GameCfg.OrigTrackOrder)) + Song_playing = songnum; + break; + } #endif default: Song_playing = -1; @@ -489,6 +541,20 @@ int songs_play_level_song( int levelnum, int offset ) break; } +#elif defined(__EMSCRIPTEN__) + case MUSIC_TYPE_CUSTOM: + { + // we have just been told to play the same as we do already -> ignore + if (!offset && Song_playing >= SONG_FIRST_LEVEL_SONG && songnum + SONG_FIRST_LEVEL_SONG == Song_playing) + return Song_playing; + + // The page keeps the folder's level playlist: it picks this level's track (or steps + // through the list by offset) and moves on to the next track when one ends. + songs_stop_all(); + if (d2web_music_level(songnum, offset)) + Song_playing = songnum + SONG_FIRST_LEVEL_SONG; + break; + } #endif default: Song_playing = -1; diff --git a/d2/main/titles.c b/d2/main/titles.c index af6f092..8cf8dbd 100644 --- a/d2/main/titles.c +++ b/d2/main/titles.c @@ -49,6 +49,10 @@ COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. #include "mouse.h" #include "console.h" #include "args.h" +#ifdef __EMSCRIPTEN__ +#include "config.h" +#include "web.h" +#endif #ifdef OGL #include "ogl_init.h" #endif @@ -1412,7 +1416,12 @@ void do_briefing_screens(char *filename, int level_num) return; } - if (EMULATING_D1 || is_SHAREWARE || is_MAC_SHARE || is_D2_OEM || !PLAYING_BUILTIN_MISSION) + if (EMULATING_D1 || is_SHAREWARE || is_MAC_SHARE || is_D2_OEM || !PLAYING_BUILTIN_MISSION +#ifdef __EMSCRIPTEN__ + // a music folder with a briefing song plays it instead of the hum + || (GameCfg.MusicType == MUSIC_TYPE_CUSTOM && d2web_music_has(SONG_BRIEFING)) +#endif + ) { if ((songs_is_playing() != SONG_BRIEFING) && (songs_is_playing() != SONG_ENDGAME)) songs_play_song( SONG_BRIEFING, 1 ); @@ -1433,8 +1442,14 @@ void do_briefing_screens(char *filename, int level_num) // Stay where we are in the stack frame until briefing done // Too complicated otherwise +#ifdef __EMSCRIPTEN__ + d2web_cutscene(1); +#endif while (window_exists(wind)) event_process(); +#ifdef __EMSCRIPTEN__ + d2web_cutscene(0); +#endif } void do_end_briefing_screens(char *filename) diff --git a/d2/misc/args.c b/d2/misc/args.c index cb81385..52a10c8 100644 --- a/d2/misc/args.c +++ b/d2/misc/args.c @@ -143,6 +143,7 @@ void ReadCmdArgs(void) GameArg.SysWindow = FindArg("-window"); GameArg.SysNoBorders = FindArg("-noborders"); GameArg.SysNoMovies = FindArg("-nomovies"); + GameArg.SysNoTitles = FindArg("-notitles"); GameArg.SysAutoDemo = FindArg("-autodemo"); // Control Options @@ -152,9 +153,9 @@ void ReadCmdArgs(void) GameArg.CtlNoJoystick = FindArg("-nojoystick"); GameArg.CtlNoStickyKeys = FindArg("-nostickykeys"); if (GameArg.CtlNoStickyKeys) // Must happen before SDL_Init! - SDL_putenv("SDL_DISABLE_LOCK_KEYS=1"); + putenv("SDL_DISABLE_LOCK_KEYS=1"); else - SDL_putenv("SDL_DISABLE_LOCK_KEYS=0"); + putenv("SDL_DISABLE_LOCK_KEYS=0"); // Sound Options diff --git a/d2/misc/physfsrwops.c b/d2/misc/physfsrwops.c index a6ab6fd..c789b14 100644 --- a/d2/misc/physfsrwops.c +++ b/d2/misc/physfsrwops.c @@ -23,7 +23,15 @@ #include /* used for SEEK_SET, SEEK_CUR, SEEK_END ... */ #include "physfsrwops.h" -static int physfsrwops_seek(SDL_RWops *rw, int offset, int whence) +#ifdef __EMSCRIPTEN__ +typedef long rw_off_t; +typedef size_t rw_size_t; +#else +typedef int rw_off_t; +typedef int rw_size_t; +#endif + +static rw_off_t physfsrwops_seek(SDL_RWops *rw, rw_off_t offset, int whence) { PHYSFS_file *handle = (PHYSFS_file *) rw->hidden.unknown.data1; int pos = 0; @@ -97,7 +105,7 @@ static int physfsrwops_seek(SDL_RWops *rw, int offset, int whence) } /* physfsrwops_seek */ -static int physfsrwops_read(SDL_RWops *rw, void *ptr, int size, int maxnum) +static rw_size_t physfsrwops_read(SDL_RWops *rw, void *ptr, rw_size_t size, rw_size_t maxnum) { PHYSFS_file *handle = (PHYSFS_file *) rw->hidden.unknown.data1; PHYSFS_sint64 rc = PHYSFS_read(handle, ptr, size, maxnum); @@ -107,18 +115,18 @@ static int physfsrwops_read(SDL_RWops *rw, void *ptr, int size, int maxnum) SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError()); } /* if */ - return((int) rc); + return((rw_size_t) rc); } /* physfsrwops_read */ -static int physfsrwops_write(SDL_RWops *rw, const void *ptr, int size, int num) +static rw_size_t physfsrwops_write(SDL_RWops *rw, const void *ptr, rw_size_t size, rw_size_t num) { PHYSFS_file *handle = (PHYSFS_file *) rw->hidden.unknown.data1; PHYSFS_sint64 rc = PHYSFS_write(handle, ptr, size, num); if (rc != num) SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError()); - return((int) rc); + return((rw_size_t) rc); } /* physfsrwops_write */ diff --git a/d2/misc/pngfile.c b/d2/misc/pngfile.c index 9d9dba2..ac67b7d 100644 --- a/d2/misc/pngfile.c +++ b/d2/misc/pngfile.c @@ -4,6 +4,7 @@ #include #include +#include #include "pngfile.h" #include "u_mem.h" #include "pstypes.h" @@ -15,6 +16,42 @@ static void PNGCBAPI png_read_data(png_structp png_ptr, png_bytep data, size_t l png_error(png_ptr, "Read Error"); } +unsigned char *stbi_load_from_memory(const unsigned char *buffer, int len, int *x, int *y, int *comp, int req_comp); + +int read_image_stb(const char *filename, png_data *pdata) +{ + PHYSFS_file *fp; + PHYSFS_sint64 fsize; + unsigned char *buf, *img; + int w, h, n; + + if (!filename || !pdata || (fp = PHYSFS_openRead(filename)) == NULL) + return 0; + if ((fsize = PHYSFS_fileLength(fp)) <= 0 || !(buf = malloc(fsize))) { + PHYSFS_close(fp); + return 0; + } + if (PHYSFS_read(fp, buf, 1, fsize) != fsize) { + free(buf); + PHYSFS_close(fp); + return 0; + } + PHYSFS_close(fp); + img = stbi_load_from_memory(buf, (int)fsize, &w, &h, &n, 4); // stb_image allocates with malloc + free(buf); + if (!img) + return 0; + memset(pdata, 0, sizeof(*pdata)); + pdata->width = w; + pdata->height = h; + pdata->depth = 8; + pdata->channels = 4; + pdata->color = 1; + pdata->alpha = n == 2 || n == 4; + pdata->data = img; + return 1; +} + int read_png(const char *filename, png_data *pdata) { //ubyte header[8]; diff --git a/d2/xmodel/ase.h b/d2/xmodel/ase.h index 11220f8..73625f1 100644 --- a/d2/xmodel/ase.h +++ b/d2/xmodel/ase.h @@ -25,7 +25,7 @@ class CFace { CFloatVector3 m_vNormal; uint16_t m_nVerts [3]; // indices of vertices uint16_t m_nTexCoord [3]; - //int16_t m_nBitmap; + int16_t m_nBitmap; // material id, then bitmap (CModel::ResolveFaceBitmaps) }; class CSubModel { @@ -89,6 +89,8 @@ class CModel { int32_t m_nVerts; int32_t m_nFaces; int32_t m_bCustom; + // per bitmap: -2 a texture; a flat color: N for a material named "colour N", else -1 + int8_t m_nFlat [64]; public: CModel () { Init (); } @@ -110,10 +112,11 @@ class CModel { private: int32_t ReadTexture (CFile& cf, int32_t nBitmap); int32_t ReadOpacity (CFile& cf, int32_t nBitmap); - int32_t ReadMaterial (CFile& cf); + int32_t ReadMaterial (CFile& cf, int32_t& nSubs); int32_t ReadMaterialList (CFile& cf); int32_t FindSubModel (const char *pszName); void LinkSubModels (void); + void ResolveFaceBitmaps (void); int32_t ReadSubModel (CFile& cf); }; diff --git a/d2/xmodel/aseread.cpp b/d2/xmodel/aseread.cpp index 19cad13..a17dc91 100644 --- a/d2/xmodel/aseread.cpp +++ b/d2/xmodel/aseread.cpp @@ -310,14 +310,12 @@ while ((pszToken = ReadLine (cf))) { strtok (NULL, " :\t"); pf->m_nVerts [i] = IntTok (" :\t"); } - #if 0 - do { - pszToken = StrTok (" :\t"); - if (!*pszToken) - return CModel::Error ("unexpected end of file"); - } while (strcmp (pszToken, "*MESH_MTLID")); - pf->m_nBitmap = IntTok (" "); - #endif + pf->m_nBitmap = 0; + while ((pszToken = strtok (NULL, " :\t"))) + if (!strcmp (pszToken, "*MESH_MTLID")) { + pf->m_nBitmap = IntTok (" \t"); + break; + } } } return CModel::Error ("unexpected end of file"); @@ -600,6 +598,7 @@ m_nModel = -1; m_nSubModels = 0; m_nVerts = 0; m_nFaces = 0; +memset (m_nFlat, -2, sizeof (m_nFlat)); } //------------------------------------------------------------------------------ @@ -699,38 +698,98 @@ return CModel::Error ("unexpected end of file"); //------------------------------------------------------------------------------ -int32_t CModel::ReadMaterial (CFile& cf) +// Every material, and every sub-material of a multi/sub-object material, gets a bitmap of its +// own; a face picks its bitmap by its submodel's material and its *MESH_MTLID (ResolveFaceBitmaps). +#define MAX_ASE_BITMAPS 64 +#define MAX_ASE_MATERIALS 64 + +static int32_t nUsedBitmaps; +static int16_t matBase [MAX_ASE_MATERIALS], matCount [MAX_ASE_MATERIALS]; + +// skips a { } block the reader doesn't use; the line that opened it has been read +static int32_t SkipBlock (CFile& cf) { - int32_t i; - CBitmap *pBm; + int32_t nDepth = 1; + +while ((pszToken = ReadLine (cf))) { + if (*pszToken == '}') { + if (!--nDepth) + return 1; + } + else + while ((pszToken = strtok (NULL, " \t"))) + if (*pszToken == '{') + nDepth++; + } +return CModel::Error ("unexpected end of file"); +} -i = IntTok (" \t"); -if ((i < 0) || (i >= m_textures.m_nBitmaps)) - return CModel::Error ("invalid bitmap number"); +// a material without a texture is drawn in its diffuse color: a 1x1 bitmap of that color +static void SetFlatColor (CBitmap *pBm, const float *color) +{ +pBm->SetWidth (1); +pBm->SetHeight (1); +pBm->SetBPP (4); +pBm->CreateBuffer (); +for (int32_t i = 0; i < 3; i++) + pBm->Buffer () [i] = (uint8_t) (color [i] < 0 ? 0 : color [i] > 1 ? 255 : color [i] * 255 + 0.5f); +pBm->Buffer () [3] = 255; +} + +// Reads a material or sub-material block. Returns the bitmap of a plain material, the first +// bitmap of its sub-materials (nSubs of them) or -1 on error. +int32_t CModel::ReadMaterial (CFile& cf, int32_t& nSubs) +{ + int32_t nBitmap = -1, nFirst = -1, nColour = -1; + float color [3] = {1, 1, 1}; + +nSubs = 0; if (CharTok (" \t") != '{') - return CModel::Error ("syntax error"); -pBm = m_textures.m_bitmaps + i; -pBm->SetFlat (1); + return CModel::Error ("syntax error"), -1; while ((pszToken = ReadLine (cf))) { - if (*pszToken == '}') - return 1; - if (!strcmp (pszToken, "*MATERAL_DIFFUSE")) { - //CRGBColor avgRGB; - //avgRGB.Red () = (uint8_t) FRound (FloatTok (" \t") * 255); - //avgRGB.Green () = (uint8_t) FRound (FloatTok (" \t") * 255); - //avgRGB.Blue () = (uint8_t) FRound (FloatTok (" \t") * 255); - //pBm->SetAvgColor (avgRGB); + if (*pszToken == '}') { + if (nSubs) + return nFirst; + if (nBitmap < 0) { + if (nUsedBitmaps >= MAX_ASE_BITMAPS) + return CModel::Error ("too many materials"), -1; + SetFlatColor (m_textures.m_bitmaps + (nBitmap = nUsedBitmaps++), color); + m_nFlat [nBitmap] = nColour; + } + return nBitmap; } - else if (!strcmp (pszToken, "*MAP_DIFFUSE")) { - if (!ReadTexture (cf, i)) - return CModel::Error (NULL); + if (!strcmp (pszToken, "*MATERIAL_NAME")) { // "colour N": the model's Nth flat color (xmodel.cpp) + const char *pszName = StrTok ("\""); + if (!strncmp (pszName, "COLOUR ", 7)) + nColour = atoi (pszName + 7); } - else if (!strcmp (pszToken, "*MAP_OPACITY")) { - if (!ReadOpacity (cf, i)) - return CModel::Error (NULL); + else if (!strcmp (pszToken, "*MATERIAL_DIFFUSE")) { + for (int32_t i = 0; i < 3; i++) + color [i] = FloatTok (" \t"); + } + else if ((!strcmp (pszToken, "*MAP_DIFFUSE") || !strcmp (pszToken, "*MAP_GENERIC")) && (nBitmap < 0)) { + if (nUsedBitmaps >= MAX_ASE_BITMAPS) + return CModel::Error ("too many materials"), -1; + if (!ReadTexture (cf, nBitmap = nUsedBitmaps++)) + return CModel::Error (NULL), -1; } + else if (!strcmp (pszToken, "*SUBMATERIAL")) { + int32_t nSubSubs, i; + IntTok (" \t"); + if ((i = ReadMaterial (cf, nSubSubs)) < 0) + return -1; + if (!nSubs++) + nFirst = i; + } + else + while ((pszToken = strtok (NULL, " \t"))) + if (*pszToken == '{') { + if (!SkipBlock (cf)) + return -1; + break; + } } -return CModel::Error ("unexpected end of file"); +return CModel::Error ("unexpected end of file"), -1; } //------------------------------------------------------------------------------ @@ -743,26 +802,47 @@ if (!(pszToken = ReadLine (cf))) return CModel::Error ("unexpected end of file"); if (strcmp (pszToken, "*MATERIAL_COUNT")) return CModel::Error ("material count missing"); -int32_t nBitmaps = IntTok (" \t"); -if (!nBitmaps) +int32_t nMaterials = IntTok (" \t"); +if ((nMaterials <= 0) || (nMaterials > MAX_ASE_MATERIALS)) return CModel::Error ("no bitmaps specified"); -if (!(m_textures.Create (nBitmaps))) +if (!(m_textures.Create (MAX_ASE_BITMAPS))) return CModel::Error ("out of memory"); +nUsedBitmaps = 0; +memset (matCount, 0, sizeof (matCount)); while ((pszToken = ReadLine (cf))) { if (*pszToken == '}') { - if (!nBitmaps) - return 1; - return CModel::Error ("bitmaps missing"); + m_textures.m_nBitmaps = nUsedBitmaps; + return 1; } if (!strcmp (pszToken, "*MATERIAL")) { - if (!ReadMaterial (cf)) + int32_t i = IntTok (" \t"), nSubs, nBitmap; + if ((i < 0) || (i >= nMaterials)) + return CModel::Error ("invalid material number"); + if ((nBitmap = ReadMaterial (cf, nSubs)) < 0) return CModel::Error (NULL); - nBitmaps--; + matBase [i] = nBitmap; + matCount [i] = nSubs ? nSubs : 1; } } return CModel::Error ("unexpected end of file"); } +// a face's bitmap: its submodel's material, and the sub-material its *MESH_MTLID picks +// (counting around, as 3ds Max does) +void CModel::ResolveFaceBitmaps (void) +{ +for (CSubModel *psm = m_subModels; psm; psm = psm->m_next) { + int32_t m = psm->m_nBitmap; + if ((m < 0) || (m >= MAX_ASE_MATERIALS) || !matCount [m]) + m = 0; + for (int32_t i = 0; i < psm->m_nFaces; i++) { + CFace& f = psm->m_faces [i]; + int32_t n = matCount [m] ? matBase [m] + f.m_nBitmap % matCount [m] : 0; + f.m_nBitmap = ((n >= 0) && (n < m_textures.m_nBitmaps)) ? n : 0; + } + } +} + //------------------------------------------------------------------------------ int32_t CModel::ReadSubModel (CFile& cf) @@ -860,6 +940,7 @@ if (!nResult) Destroy (); else { LinkSubModels (); + ResolveFaceBitmaps (); //gameData.modelData.bHaveHiresModel [uint32_t (this - gameData.modelData.aseModels [bCustom != 0].Buffer ())] = 1; if (bCacheModelData) { //if (IsPlayerShip (nModel)) diff --git a/d2/xmodel/strfunc.h b/d2/xmodel/strfunc.h index 86dbf86..284c6a7 100644 --- a/d2/xmodel/strfunc.h +++ b/d2/xmodel/strfunc.h @@ -79,6 +79,9 @@ static void strupr8(char *s) { #endif #ifndef WIN32 +#ifdef __EMSCRIPTEN__ +#define strlwr xmodel_strlwr +#endif static char *strlwr(char *s) { for (char *p = s, c; (c = *p); p++) if (c >= 'A' && c <= 'Z') diff --git a/d2/xmodel/tga.cpp b/d2/xmodel/tga.cpp index 8865faf..33d3869 100644 --- a/d2/xmodel/tga.cpp +++ b/d2/xmodel/tga.cpp @@ -644,12 +644,98 @@ return 1; #endif +#ifdef HAVE_LIBPNG +extern "C" { +#include "pngfile.h" +} + +#ifdef __EMSCRIPTEN__ +// A big painted texture (the extra-sharp pack's robots) can ship as x.jpg instead of x.png. +static int read_jpeg_beside (const char *pngName, png_data *pdata) +{ + char name [FILENAME_LEN]; + snprintf (name, sizeof (name), "%.*s.jpg", (int) strlen (pngName) - 4, pngName); + return read_image_stb (name, pdata); +} +#endif + +// Model textures named "x.tga" in a model ship as x.png (D2X-XL 2.x); animated ones are +// vertical frame strips (name#0.png, frame k in row k): name#k is its own file or row k of +// the strip. Loads as RGBA. +static int32_t ReadPNG (CBitmap* pBm, const char *pszFile, int32_t alpha) +{ + char szName [FILENAME_LEN], *psz, *pszHash; + png_data pdata; + int32_t nFrame = 0; + +CFile::SplitPath (pszFile, NULL, szName, NULL); +if ((psz = strrchr (szName, '.'))) + *psz = '\0'; +if ((pszHash = strchr (szName, '#'))) + nFrame = atoi (pszHash + 1); +strcat (szName, ".png"); +if (read_png (szName, &pdata)) + nFrame = 0; // a file of its own, or a strip it is the first frame of +#ifdef __EMSCRIPTEN__ +else if (!pszHash && read_jpeg_beside (szName, &pdata)) + nFrame = 0; +#endif +else { + if (!nFrame) + return 0; + strcpy (pszHash, "#0.png"); + if (!read_png (szName, &pdata)) + return 0; + } +int32_t w = pdata.width, h = pdata.height, bpp = pdata.paletted ? 1 : pdata.channels, nOffset = 0; +if (pdata.depth != 8 || (pdata.paletted && !pdata.palette)) { + free (pdata.data); + if (pdata.palette) + free (pdata.palette); + return 0; + } +if (pszHash && h > w && !(h % w)) { + nOffset = (nFrame % (h / w)) * w * w; + h = w; + } +pBm->SetName (pszFile); +pBm->SetWidth (w); +pBm->SetHeight (h); +pBm->SetBPP (4); +pBm->CreateBuffer (); +uint8_t *d = pBm->Buffer (); +for (int32_t i = nOffset; i < nOffset + w * h; i++, d += 4) { + const uint8_t *s = pdata.paletted ? pdata.palette + pdata.data [i] * 3 : pdata.data + i * bpp; + if (bpp >= 3 || pdata.paletted) { + d [0] = s [0]; + d [1] = s [1]; + d [2] = s [2]; + } + else + d [0] = d [1] = d [2] = s [0]; + d [3] = (bpp == 4) ? s [3] : (bpp == 2) ? s [1] : 255; + if ((d [0] == 120) && (d [1] == 88) && (d [2] == 128)) // D2X-XL super transparency + d [3] = 0; + else if (alpha >= 0) + d [3] = alpha; + } +free (pdata.data); +if (pdata.palette) + free (pdata.palette); +return 1; +} +#endif + //--------------------------------------------------------------- int32_t CTGA::Read (const char *pszFile, const char *pszFolder, int32_t alpha, double brightness, int32_t bGrayScale, bool bAutoComplete) { int32_t r; +#ifdef HAVE_LIBPNG +if (ReadPNG (m_pBm, pszFile, alpha)) + return 1; +#endif #if USE_SDL_IMAGE if (ReadImage (pszFile, pszFolder, alpha, brightness, bGrayScale)) diff --git a/d2/xmodel/xdescent.h b/d2/xmodel/xdescent.h index c53598c..97f0161 100644 --- a/d2/xmodel/xdescent.h +++ b/d2/xmodel/xdescent.h @@ -94,7 +94,7 @@ public: inline CBitmap *CurFrame() { return 0; } inline bool CreateBuffer() { if (m_data) - m_data = NULL; + delete[] m_data; m_data = new uint8_t[m_width * m_height * m_bpp]; return true; } diff --git a/d2/xmodel/xmodel.cpp b/d2/xmodel/xmodel.cpp index d75a377..98bb1c4 100644 --- a/d2/xmodel/xmodel.cpp +++ b/d2/xmodel/xmodel.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include "xdescent.h" @@ -10,6 +11,9 @@ #include "xmodel.h" #include "xmodelnames.h" extern "C" { +#ifdef __EMSCRIPTEN__ +#include "../arch/web/web.h" +#endif #include "internal.h" #include "../3d/globvars.h" #undef FILENAME_LEN @@ -17,28 +21,72 @@ extern "C" { #undef FILENAME_LEN #include "polyobj.h" #include "texmap.h" +#include "console.h" +#include "piggy.h" +#include "bm.h" +#include "vclip.h" +#include "effects.h" } struct CGameFolders gameFolders; struct CGameStates gameStates; +// The GL emulation only reads vertex attributes interleaved with one stride struct vert { CFloatVector3 pos; tTexCoord2f tex; + float color[4]; // shading, worked out again for each draw: floats, since the game's + // model light goes above 1 in bright places and the GL emulation keeps it +}; + +// A texture the game animates on the model (a boss's pulsing skin: an effect's +// changing_object_texture): all its frames, shown as the game shows them +struct anim_tex { + int bitmap; // the model bitmap it stands for + int objbm; // the ObjBitmaps entry the game animates + int nframes; + unsigned short game[VCLIP_MAX_FRAMES]; // the game's bitmap for each frame + CBitmap frames[VCLIP_MAX_FRAMES]; + GLuint tex[VCLIP_MAX_FRAMES]; +}; +#define MAX_ANIM_TEX 8 + +// one draw call: the faces of one part that use one texture +struct range { + int sub, bitmap, first, count; }; struct render_model { ASE::CModel m; - int *bmvertofs; - int *bmvertcount; + struct range *ranges; + int nranges; struct vert *verts; + float *normals; // per vertex, for the shading int vertcount; + // Robots are split into $SUBMODEL0..n parts that match the game model's moving parts, + // so they can follow its animation; nsubs is 0 for models drawn in one piece. + int nsubs; + signed char parents[MAX_SUBMODELS]; + int match; // 0 not compared with the game model yet, 1 parts match, -1 they don't GLuint *bmtex; - GLuint vbo; + struct anim_tex *anims; + int nanims; + float gain; // light scale that makes it as bright as the game model (fit_brightness) + float part_gain[MAX_SUBMODELS]; // the same for each part, when the parts match the game model's + // from .light beside the model ("gain 0.7 ceiling 1"), for models whose texture is a full-brightness + // painting with dark areas (an image-to-3D model) that the average-brightness fit would light far too brightly + float fixed_gain; // used instead of fit_brightness when above 0 + float light_ceiling; // the most light any vertex gets (keeping its color) when above 0 int glloaded; }; void *xmodels[NUM_XMODELS]; +void *xrobots[NUM_XROBOTS]; +extern "C" { int xmodel_enabled = 1; } // 0 draws the game's own models (for comparing) +static signed char polyobj_xrobot[MAX_POLYGON_MODELS]; + +static int is_pow2(int n) { return n > 0 && !(n & (n - 1)); } +static void upload_texture(CBitmap& bm, GLuint tex); // return -1 on error int xmodel_load_gl(void *model) { @@ -49,15 +97,32 @@ int xmodel_load_gl(void *model) { glew_loaded = 1; } #endif - render_model& rm = *(render_model *)model; int num_bitmaps = rm.m.m_textures.m_nBitmaps; glGenTextures(num_bitmaps, rm.bmtex); for (int i = 0; i < num_bitmaps; i++) { CBitmap& bm = rm.m.m_textures.m_bitmaps[i]; - if (!bm.Width() || (!rm.bmvertcount[i] && !bm.Team())) + int used = 0; + for (int r = 0; r < rm.nranges; r++) + used |= rm.ranges[r].bitmap == i; + if (!bm.Width() || (!used && !bm.Team())) continue; - glBindTexture(GL_TEXTURE_2D, rm.bmtex[i]); + upload_texture(bm, rm.bmtex[i]); + } + for (int a = 0; a < rm.nanims; a++) { + anim_tex& at = rm.anims[a]; + glGenTextures(at.nframes, at.tex); + for (int k = 0; k < at.nframes; k++) + if (at.frames[k].Width()) + upload_texture(at.frames[k], at.tex[k]); + } + rm.glloaded = 1; + return 0; +} + +static void upload_texture(CBitmap& bm, GLuint tex) { + { + glBindTexture(GL_TEXTURE_2D, tex); if (bm.BPP() == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bm.Width(), bm.Height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, @@ -66,19 +131,17 @@ int xmodel_load_gl(void *model) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, bm.Width(), bm.Height(), 0, GL_RGB, GL_UNSIGNED_BYTE, bm.Buffer()); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + // WebGL 1 can only mipmap and repeat power-of-two textures + if (is_pow2(bm.Width()) && is_pow2(bm.Height())) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glGenerateMipmap(GL_TEXTURE_2D); + } else { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glGenerateMipmap(GL_TEXTURE_2D); } - - glGenBuffers(1, &rm.vbo); - - glBindBuffer(GL_ARRAY_BUFFER, rm.vbo); - glBufferData(GL_ARRAY_BUFFER, rm.vertcount * sizeof(rm.verts[0]), rm.verts, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - rm.glloaded = 1; - return 0; } void xmodel_free_gl(void *model) { @@ -87,8 +150,10 @@ void xmodel_free_gl(void *model) { return; glDeleteTextures(rm.m.m_textures.m_nBitmaps, rm.bmtex); memset(rm.bmtex, 0, rm.m.m_textures.m_nBitmaps * sizeof(rm.bmtex[0])); - glDeleteBuffers(1, &rm.vbo); - rm.vbo = 0; + for (int a = 0; a < rm.nanims; a++) { + glDeleteTextures(rm.anims[a].nframes, rm.anims[a].tex); + memset(rm.anims[a].tex, 0, sizeof(rm.anims[a].tex)); + } rm.glloaded = 0; } @@ -97,12 +162,21 @@ void xmodel_free(void *model) { render_model& rm = *rmp; xmodel_free_gl(model); delete[] rm.verts; - delete[] rm.bmvertcount; - delete[] rm.bmvertofs; + delete[] rm.normals; + delete[] rm.ranges; delete[] rm.bmtex; + delete[] rm.anims; delete rmp; } +// the part number of a $SUBMODELn node, or -1 +static int part_number(ASE::CSubModel *sm) { + if (strncmp(sm->m_szName, "$SUBMODEL", 9)) + return -1; + int n = atoi(sm->m_szName + 9); + return n >= 0 && n < MAX_SUBMODELS ? n : -1; +} + // return NULL on error void *xmodel_load(const char *filename) { render_model* rmp = new render_model(); @@ -114,6 +188,25 @@ void *xmodel_load(const char *filename) { return NULL; } rm.glloaded = 0; + rm.gain = 1; + for (int i = 0; i < MAX_SUBMODELS; i++) + rm.part_gain[i] = 1; + rm.fixed_gain = rm.light_ceiling = 0; + { + char lightname[64], line[128]; + const char *dot = strrchr(filename, '.'); + int base = dot ? (int)(dot - filename) : (int)strlen(filename); + snprintf(lightname, sizeof(lightname), "%.*s.light", base, filename); + CFile cf; + if (cf.Open(lightname, "", "rb", 0)) + while (cf.GetS(line, sizeof(line))) { + float v; + if (sscanf(line, " gain %f", &v) == 1) + rm.fixed_gain = v; + else if (sscanf(line, " ceiling %f", &v) == 1) + rm.light_ceiling = v; + } + } int num_bitmaps = m.m_textures.m_nBitmaps; for (int i = 0; i < num_bitmaps; i++) { CBitmap& bm = m.m_textures.m_bitmaps[i]; @@ -127,94 +220,624 @@ void *xmodel_load(const char *filename) { data[j + 2] = x; } } - int *bmvertcount = rm.bmvertcount = new int[num_bitmaps](); - int i, v; + + // parts: use them only when every node is a $SUBMODELn with a known parent ASE::CSubModel *sm; - for (sm = m.m_subModels, i = 0; sm; sm = sm->m_next, i++) { + int nsubs = 0; + memset(rm.parents, -1, sizeof(rm.parents)); + for (sm = m.m_subModels; sm; sm = sm->m_next) { + int n = part_number(sm); + if (n < 0) { + nsubs = 0; + break; + } + ASE::CSubModel *p; + for (p = m.m_subModels; p && p->m_nSubModel != sm->m_nParent; p = p->m_next) + ; + rm.parents[n] = p ? part_number(p) : -1; + if (n + 1 > nsubs) + nsubs = n + 1; + } + rm.nsubs = nsubs; + rm.match = 0; + + // one range per part and texture + int nkeys = (MAX_SUBMODELS + 1) * num_bitmaps; + int *count = new int[nkeys](); + int v = 0; + for (sm = m.m_subModels; sm; sm = sm->m_next) { if (ExcludeSubModel(sm, 0, -1, 0, 0)) continue; - for (int f = 0; f < sm->m_nFaces; f++) - bmvertcount[sm->/*m_faces[f].*/m_nBitmap]+=3; + int sub = nsubs ? part_number(sm) : 0; + for (int fi = 0; fi < sm->m_nFaces; fi++) + count[sub * num_bitmaps + sm->m_faces[fi].m_nBitmap] += 3; + v += sm->m_nFaces * 3; } - - int *bmvertofs = rm.bmvertofs = new int[num_bitmaps](); + int vertcount = rm.vertcount = v; + int *start = new int[nkeys](); + rm.ranges = new range[nkeys]; + rm.nranges = 0; v = 0; - for (int i = 0; i < num_bitmaps; i++) { - bmvertofs[i] = v; - v += bmvertcount[i]; + for (int k = 0; k < nkeys; k++) { + start[k] = v; + if (!count[k]) + continue; + range& r = rm.ranges[rm.nranges++]; + r.sub = k / num_bitmaps; + r.bitmap = k % num_bitmaps; + r.first = v; + r.count = count[k]; + v += count[k]; } - int vertcount = rm.vertcount = v; - - int *bmvertpos = new int[num_bitmaps](); - memcpy(bmvertpos, rm.bmvertofs, num_bitmaps * sizeof(int)); vert *verts = rm.verts = new vert[vertcount]; + float *normals = rm.normals = new float[vertcount * 3](); + float outward = 0; for (sm = m.m_subModels; sm; sm = sm->m_next) { if (ExcludeSubModel(sm, 0, -1, 0, 0)) continue; int hastex = sm->m_nTexCoord; CFloatVector3 ofs = sm->m_vOffset; + // Vertex normals: a face's corner averages the faces around that vertex that meet it at + // under 50 degrees, so curves shade smoothly and hard edges stay sharp. + int nf = sm->m_nFaces, nv = sm->m_nVerts; + float *fn = new float[nf * 3], *fu = new float[nf * 3]; // area-weighted, unit + int *vstart = new int[nv + 1](), *vfaces = new int[nf * 3]; + for (int fi = 0; fi < nf; fi++) { + ASE::CFace& f = sm->m_faces[fi]; + float *p[3]; + for (int j = 0; j < 3; j++) + p[j] = sm->m_vertices[f.m_nVerts[j]].m_vertex.v.vec; + float a[3], b[3], *n = fn + fi * 3; + for (int j = 0; j < 3; j++) { + a[j] = p[1][j] - p[0][j]; + b[j] = p[2][j] - p[0][j]; + } + n[0] = a[1] * b[2] - a[2] * b[1]; + n[1] = a[2] * b[0] - a[0] * b[2]; + n[2] = a[0] * b[1] - a[1] * b[0]; + float l = sqrtf(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); + for (int j = 0; j < 3; j++) { + fu[fi * 3 + j] = l > 0 ? n[j] / l : 0; + outward += n[j] * (p[0][j] + p[1][j] + p[2][j]); + vstart[f.m_nVerts[j] + 1]++; + } + } + for (int i = 0; i < nv; i++) + vstart[i + 1] += vstart[i]; + int *fill = new int[nv]; + memcpy(fill, vstart, nv * sizeof(int)); + for (int fi = 0; fi < nf; fi++) + for (int j = 0; j < 3; j++) + vfaces[fill[sm->m_faces[fi].m_nVerts[j]]++] = fi; + delete[] fill; + int sub = nsubs ? part_number(sm) : 0; for (int fi = 0; fi < sm->m_nFaces; fi++) { ASE::CFace& f = sm->m_faces[fi]; - int bm = sm->m_nBitmap, v = bmvertpos[bm]; + int key = sub * num_bitmaps + f.m_nBitmap; + int vi = start[key]; for (int j = 0; j < 3; j++) { - verts[v + j].pos = sm->m_vertices[f.m_nVerts[j]].m_vertex + ofs; + verts[vi + j].pos = sm->m_vertices[f.m_nVerts[j]].m_vertex + ofs; if (hastex) - verts[v + j].tex = sm->m_texCoord[f.m_nTexCoord[j]]; + verts[vi + j].tex = sm->m_texCoord[f.m_nTexCoord[j]]; + float n[3] = { 0, 0, 0 }, *u = fu + fi * 3; + int v = f.m_nVerts[j]; + for (int k = vstart[v]; k < vstart[v + 1]; k++) { + int g = vfaces[k]; + if (u[0] * fu[g * 3] + u[1] * fu[g * 3 + 1] + u[2] * fu[g * 3 + 2] > 0.64f) + for (int c = 0; c < 3; c++) + n[c] += fn[g * 3 + c]; + } + float l = sqrtf(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); + for (int k = 0; k < 3; k++) + normals[(vi + j) * 3 + k] = l > 0 ? n[k] / l : u[k]; } - bmvertpos[bm] += 3; + start[key] += 3; } + delete[] fn; + delete[] fu; + delete[] vstart; + delete[] vfaces; } - delete[] bmvertpos; - + // the face winding decides which way the normals point: make them face out of the model + if (outward < 0) + for (int i = 0; i < vertcount * 3; i++) + normals[i] = -normals[i]; + delete[] start; + delete[] count; rm.bmtex = new GLuint[num_bitmaps](); - rm.vbo = 0; - return rmp; } -void xmodel_show(void *model, int mpcolor, g3s_lrgb *light) { - render_model& rm = *(render_model *)model; +extern "C" void ogl_match_bitmap_colors(grs_bitmap *bm, unsigned char *rgba, int w, int h); +extern "C" void ogl_bitmap_average(grs_bitmap *bm, float *rgb); + +// How bright a model looks: its surface's average luminance per unit area, textured faces at +// a typical light, flat ones unlit as the game draws its flat polygons. +#define TYPICAL_LIGHT 0.75f +static float luminance(const float *c) { return 0.3f * c[0] + 0.59f * c[1] + 0.11f * c[2]; } +static float flat_rgb(short c, float *rgb) { + rgb[0] = ((c >> 10) & 31) / 31.0f; + rgb[1] = ((c >> 5) & 31) / 31.0f; + rgb[2] = (c & 31) / 31.0f; + return luminance(rgb); +} + +static double polygon_area(const vms_vector *pts, const unsigned short *idx, int nv) { + double a = 0; + for (int i = 2; i < nv; i++) { + const vms_vector *p0 = &pts[idx[0]], *p1 = &pts[idx[i - 1]], *p2 = &pts[idx[i]]; + double ux = f2fl(p1->x - p0->x), uy = f2fl(p1->y - p0->y), uz = f2fl(p1->z - p0->z); + double vx = f2fl(p2->x - p0->x), vy = f2fl(p2->y - p0->y), vz = f2fl(p2->z - p0->z); + double cx = uy * vz - uz * vy, cy = uz * vx - ux * vz, cz = ux * vy - uy * vx; + a += sqrt(cx * cx + cy * cy + cz * cz) / 2; + } + return a; +} + +#define W(p) (*(short *)(p)) +#define MAX_SURFACE_POINTS 1000 +// subcalls 0 leaves out the parts that hang off this one +static void game_surface(ubyte *p, vms_vector *pts, const float *tex_lum, int ntex, double *sum, double *area, + int subcalls = 1) { + for (;;) + switch (W(p)) { + case 1: { // OP_DEFPOINTS + int n = W(p + 2); + if (n <= MAX_SURFACE_POINTS) + memcpy(pts, p + 4, n * sizeof(vms_vector)); + p += n * sizeof(vms_vector) + 4; + break; + } + case 7: { // OP_DEFP_START + int n = W(p + 2), start = W(p + 4); + if (start >= 0 && start + n <= MAX_SURFACE_POINTS) + memcpy(pts + start, p + 8, n * sizeof(vms_vector)); + p += n * sizeof(vms_vector) + 8; + break; + } + case 2: // OP_FLATPOLY + case 3: { // OP_TMAPPOLY + int nv = W(p + 2), ok = 1; + const unsigned short *idx = (const unsigned short *)(p + 30); + for (int i = 0; i < nv; i++) + ok &= idx[i] < MAX_SURFACE_POINTS; + if (ok) { + double a = polygon_area(pts, idx, nv); + float rgb[3]; + float l = W(p) == 2 ? flat_rgb(W(p + 28), rgb) + : W(p + 28) < ntex ? tex_lum[W(p + 28)] * TYPICAL_LIGHT : 0; + *sum += a * l; + *area += a; + } + p += 30 + ((nv & ~1) + 1) * 2 + (W(p) == 3 ? nv * 12 : 0); + break; + } + case 4: // OP_SORTNORM + game_surface(p + W(p + 28), pts, tex_lum, ntex, sum, area, subcalls); + game_surface(p + W(p + 30), pts, tex_lum, ntex, sum, area, subcalls); + p += 32; + break; + case 5: // OP_RODBM + p += 36; + break; + case 6: // OP_SUBCALL + if (subcalls) + game_surface(p + W(p + 16), pts, tex_lum, ntex, sum, area); + p += 20; + break; + case 8: // OP_GLOW + p += 4; + break; + default: // OP_EOF + return; + } +} +#undef W + +static int parts_match(render_model& rm, polymodel *po); +static float clamp_gain(double g) { return g < 0.7 ? 0.7f : g > 1.8 ? 1.8f : (float)g; } + +// The models often texture with grey metal what the game draws as bright flat polygons +// (Fiddler's claws), so each robot is lit to look as bright overall as its game model, and +// part by part where its parts match the game model's. +static void fit_brightness(render_model& rm, polymodel *po) { + static vms_vector pts[MAX_SURFACE_POINTS]; + if (rm.fixed_gain > 0) { + rm.gain = rm.fixed_gain; + for (int i = 0; i < MAX_SUBMODELS; i++) + rm.part_gain[i] = rm.gain; + return; + } + float tex_lum[MAX_POLYOBJ_TEXTURES] = { 0 }, rgb[3]; + int ntex = po->n_textures < MAX_POLYOBJ_TEXTURES ? po->n_textures : MAX_POLYOBJ_TEXTURES; + for (int t = 0; t < ntex; t++) { + bitmap_index bi = ObjBitmaps[ObjBitmapPtrs[po->first_texture + t]]; + PIGGY_PAGE_IN(bi); + ogl_bitmap_average(&GameBitmaps[bi.index], rgb); + tex_lum[t] = luminance(rgb); + } + double gsum = 0, garea = 0; + game_surface(po->model_data, pts, tex_lum, ntex, &gsum, &garea); + int num_bitmaps = rm.m.m_textures.m_nBitmaps; + float *blum = new float[num_bitmaps](); + for (int i = 0; i < num_bitmaps; i++) { + CBitmap& bm = rm.m.m_textures.m_bitmaps[i]; + double c[3] = { 0, 0, 0 }; + int n = bm.Width() * bm.Height(); + if (bm.BPP() != 4 || !n) + continue; + for (int j = 0; j < n; j++) + for (int k = 0; k < 3; k++) + c[k] += bm.Buffer()[j * 4 + k]; + for (int k = 0; k < 3; k++) + rgb[k] = c[k] / n / 255; + blum[i] = luminance(rgb) * (rm.m.m_nFlat[i] != -2 ? 1 : TYPICAL_LIGHT); + } + double msum = 0, marea = 0, psum[MAX_SUBMODELS] = { 0 }, parea[MAX_SUBMODELS] = { 0 }; + for (int r = 0; r < rm.nranges; r++) + for (int i = rm.ranges[r].first; i + 2 < rm.ranges[r].first + rm.ranges[r].count; i += 3) { + const float *p0 = rm.verts[i].pos.v.vec, *p1 = rm.verts[i + 1].pos.v.vec, *p2 = rm.verts[i + 2].pos.v.vec; + double ux = p1[0] - p0[0], uy = p1[1] - p0[1], uz = p1[2] - p0[2]; + double vx = p2[0] - p0[0], vy = p2[1] - p0[1], vz = p2[2] - p0[2]; + double cx = uy * vz - uz * vy, cy = uz * vx - ux * vz, cz = ux * vy - uy * vx; + double a = sqrt(cx * cx + cy * cy + cz * cz) / 2; + msum += a * blum[rm.ranges[r].bitmap]; + marea += a; + psum[rm.ranges[r].sub] += a * blum[rm.ranges[r].bitmap]; + parea[rm.ranges[r].sub] += a; + } + delete[] blum; + if (gsum > 0 && garea > 0 && msum > 0 && marea > 0) + rm.gain = clamp_gain((gsum / garea) / (msum / marea)); + for (int i = 0; i < MAX_SUBMODELS; i++) + rm.part_gain[i] = rm.gain; + if (!parts_match(rm, po)) + return; + for (int i = 0; i < rm.nsubs; i++) { + double s = 0, a = 0; + game_surface(po->model_data + po->submodel_ptrs[i], pts, tex_lum, ntex, &s, &a, 0); + if (s > 0 && a > 0 && psum[i] > 0 && parea[i] > 0) + rm.part_gain[i] = clamp_gain((s / a) / (psum[i] / parea[i])); + } +} +// The game model's flat-shaded polygon colors (15-bit RGB), each once, in the order the +// interpreter meets them: what the models' "colour N" materials stand for. +#define W(p) (*(short *)(p)) +static void flat_colors(ubyte *p, short *colors, int *n) { + for (;;) + switch (W(p)) { + case 0: // OP_EOF + return; + case 1: // OP_DEFPOINTS + p += W(p + 2) * sizeof(vms_vector) + 4; + break; + case 7: // OP_DEFP_START + p += W(p + 2) * sizeof(vms_vector) + 8; + break; + case 2: { // OP_FLATPOLY + int i; + for (i = 0; i < *n && colors[i] != W(p + 28); i++) + ; + if (i == *n && *n < 16) + colors[(*n)++] = W(p + 28); + p += 30 + ((W(p + 2) & ~1) + 1) * 2; + break; + } + case 3: // OP_TMAPPOLY + p += 30 + ((W(p + 2) & ~1) + 1) * 2 + W(p + 2) * 12; + break; + case 4: // OP_SORTNORM + flat_colors(p + W(p + 28), colors, n); + flat_colors(p + W(p + 30), colors, n); + p += 32; + break; + case 5: // OP_RODBM + p += 36; + break; + case 6: // OP_SUBCALL + flat_colors(p + W(p + 16), colors, n); + p += 20; + break; + case 8: // OP_GLOW + p += 4; + break; + default: + return; + } +} +#undef W + +// The game model's own textures settle the look: a robot's eye color is a frame of an +// animated texture, which the models name as frame 0, and the colors should match the +// game bitmaps (see ogl_fit_png). +static void fit_textures(render_model& rm, polymodel *po) { + int changed = 0, nflat = 0; + short flat[16]; + flat_colors(po->model_data, flat, &nflat); + for (int i = 0; i < rm.m.m_textures.m_nBitmaps; i++) { + CBitmap& bm = rm.m.m_textures.m_bitmaps[i]; + const char *file = rm.m.m_textures.m_names[i].Buffer(); + char name[64]; + int c = rm.m.m_nFlat[i]; + if (c >= 0 && c < nflat && bm.Buffer()) { // as gr_find_closest_color_15bpp reads it + uint8_t *d = bm.Buffer(); + d[0] = ((flat[c] >> 10) & 31) * 255 / 31; + d[1] = ((flat[c] >> 5) & 31) * 255 / 31; + d[2] = (flat[c] & 31) * 255 / 31; + changed = 1; + } + if (!file || bm.BPP() != 4) + continue; + snprintf(name, sizeof(name), "%s", file); + if (char *p = strrchr(name, '.')) + *p = '\0'; + size_t base = strcspn(name, "#"); + int t; + for (t = 0; t < po->n_textures; t++) { + bitmap_index bi = ObjBitmaps[ObjBitmapPtrs[po->first_texture + t]]; + PIGGY_PAGE_IN(bi); + grs_bitmap *gb = &GameBitmaps[bi.index]; + const char *gname = piggy_game_bitmap_name(gb); + if (!gname || strncmp(gname, name, base) || (gname[base] && gname[base] != '#')) + continue; + if (strcmp(gname, name)) { + char gfile[64]; + snprintf(gfile, sizeof(gfile), "%s.png", gname); + CTGA tga(&bm); + if (!tga.ReadModelTexture(gfile, 0)) + break; + } + ogl_match_bitmap_colors(gb, bm.Buffer(), bm.Width(), bm.Height()); + changed = 1; + int objbm = ObjBitmapPtrs[po->first_texture + t]; + for (int e = 0; e < Num_effects; e++) { + vclip& vc = Effects[e].vc; + if (Effects[e].changing_object_texture != objbm || rm.nanims >= MAX_ANIM_TEX || vc.num_frames <= 0) + continue; + if (!rm.anims) + rm.anims = new anim_tex[MAX_ANIM_TEX](); + anim_tex& at = rm.anims[rm.nanims++]; + at.bitmap = i; + at.objbm = objbm; + at.nframes = vc.num_frames < VCLIP_MAX_FRAMES ? vc.num_frames : VCLIP_MAX_FRAMES; + for (int k = 0; k < at.nframes; k++) { + grs_bitmap *fb = &GameBitmaps[at.game[k] = vc.frames[k].index]; + const char *fname = piggy_game_bitmap_name(fb); + char ffile[64]; + if (!fname) + continue; + snprintf(ffile, sizeof(ffile), "%s.png", fname); + CTGA ftga(&at.frames[k]); + if (!ftga.ReadModelTexture(ffile, 0)) + continue; + PIGGY_PAGE_IN(vc.frames[k]); + ogl_match_bitmap_colors(fb, at.frames[k].Buffer(), at.frames[k].Width(), at.frames[k].Height()); + } + break; + } + break; + } + // a texture the game model doesn't use (Vertigo's robots have textures of their own) + // still matches the game bitmap it is named after + if (t == po->n_textures) { + bitmap_index bi = piggy_find_bitmap(name); + if (bi.index > 0) { + PIGGY_PAGE_IN(bi); + ogl_match_bitmap_colors(&GameBitmaps[bi.index], bm.Buffer(), bm.Width(), bm.Height()); + changed = 1; + } + } + } + fit_brightness(rm, po); + if (changed) + xmodel_free_gl(&rm); +} + +// Robot parts must line up with the game model's: same count and the same parent for each. +static int parts_match(render_model& rm, polymodel *po) { + if (!rm.nsubs || rm.nsubs != po->n_models) + return 0; + for (int i = 0; i < rm.nsubs; i++) + if (i ? rm.parents[i] != po->submodel_parents[i] || rm.parents[i] >= i : rm.parents[i] != -1) + return 0; + return 1; +} + +// Where each part is drawn: xf[i] maps the model's rest-pose coordinates of part i to the +// pose the game model has now (column-major 4x4). Follows the interpreter's submodel calls: +// a part rotates by its animation angles about its pivot, offset from its parent. +// root < 0 draws the whole model; else just that part and what hangs off it, centered on +// the part (debris). +static void part_transforms(render_model& rm, polymodel *po, vms_angvec *anim_angles, int root, + float xf[][16], int *draw, float rot[][9]) { + float pivot[MAX_SUBMODELS][3], lin[MAX_SUBMODELS][9], ofs[MAX_SUBMODELS][3]; + for (int i = 0; i < rm.nsubs; i++) { + int p = i ? rm.parents[i] : -1; + float o[3] = { f2fl(po->submodel_offsets[i].x), f2fl(po->submodel_offsets[i].y), f2fl(po->submodel_offsets[i].z) }; + if (p < 0) + for (int k = 0; k < 3; k++) + pivot[i][k] = 0; + else + for (int k = 0; k < 3; k++) + pivot[i][k] = pivot[p][k] + o[k]; + draw[i] = root < 0 || i == root || (p >= 0 && draw[p]); + if (!draw[i]) + continue; + if (i == root || p < 0) { + // the root keeps the model's axes; a debris piece is centered on its own middle + for (int k = 0; k < 9; k++) + lin[i][k] = k % 4 ? 0 : 1; + for (int k = 0; k < 3; k++) + ofs[i][k] = i == root ? -0.5f * (f2fl((&po->submodel_mins[i].x)[k]) + f2fl((&po->submodel_maxs[i].x)[k])) : 0; + } else { + // child -> parent is R^T p + offset, R from the part's animation angles + vms_matrix r; + vms_angvec zero = { 0, 0, 0 }; + vm_angles_2_matrix(&r, anim_angles ? &anim_angles[i] : &zero); + float rt[9] = { // columns: rvec, uvec, fvec + f2fl(r.rvec.x), f2fl(r.rvec.y), f2fl(r.rvec.z), + f2fl(r.uvec.x), f2fl(r.uvec.y), f2fl(r.uvec.z), + f2fl(r.fvec.x), f2fl(r.fvec.y), f2fl(r.fvec.z) }; + for (int c = 0; c < 3; c++) + for (int k = 0; k < 3; k++) + lin[i][c * 3 + k] = lin[p][k] * rt[c * 3] + lin[p][3 + k] * rt[c * 3 + 1] + lin[p][6 + k] * rt[c * 3 + 2]; + for (int k = 0; k < 3; k++) + ofs[i][k] = lin[p][k] * o[0] + lin[p][3 + k] * o[1] + lin[p][6 + k] * o[2] + ofs[p][k]; + } + } + for (int i = 0; i < rm.nsubs; i++) { + if (!draw[i]) + continue; + float *m = xf[i]; + for (int c = 0; c < 3; c++) { + for (int k = 0; k < 3; k++) + m[c * 4 + k] = lin[i][c * 3 + k]; + m[c * 4 + 3] = 0; + } + // rest-pose vertex v is at v - pivot in the part's own coordinates + for (int k = 0; k < 3; k++) + m[12 + k] = ofs[i][k] - (lin[i][k] * pivot[i][0] + lin[i][3 + k] * pivot[i][1] + lin[i][6 + k] * pivot[i][2]); + m[15] = 1; + memcpy(rot[i], lin[i], sizeof(rot[i])); + } +} + +// Shades like the game's own models: a quarter of the light, plus the rest on faces turned +// toward the viewer. view is the view direction in model coordinates. +static void shade(render_model& rm, const float *view, float rot[][9], g3s_lrgb *light, float alpha, int parts) { + float a = alpha; + // with the modern look, metal shines where it faces the light that reaches it from the + // viewer's side (scaled by that light, so it never shines in the dark) + float shine = 0; +#ifdef __EMSCRIPTEN__ + shine = d2web_option(D2WEB_OPTION_LIGHTING) ? 1.0f : 0.0f; +#endif + for (int r = 0; r < rm.nranges; r++) { + range& rg = rm.ranges[r]; + const float *m = rot[rg.sub]; + float gain = parts ? rm.part_gain[rg.sub] : rm.gain; + float lr = f2fl(light->r) * gain, lg = f2fl(light->g) * gain, lb = f2fl(light->b) * gain; + if (rm.m.m_nFlat[rg.bitmap] != -2) { // flat colors: the game draws its flat polygons unlit + for (int i = rg.first; i < rg.first + rg.count; i++) { + float *c = rm.verts[i].color; + c[0] = c[1] = c[2] = 1; + c[3] = a; + } + continue; + } + // the view direction in the part's rest-pose axes + float d[3] = { + m[0] * view[0] + m[1] * view[1] + m[2] * view[2], + m[3] * view[0] + m[4] * view[1] + m[5] * view[2], + m[6] * view[0] + m[7] * view[1] + m[8] * view[2] }; + for (int i = rg.first; i < rg.first + rg.count; i++) { + const float *n = rm.normals + i * 3; + // either side: some parts are modelled with the opposite winding, and faces turned + // away are hidden behind the near ones anyway + float f = fabsf(n[0] * d[0] + n[1] * d[1] + n[2] * d[2]); + float l = 0.25f + 0.75f * f; + float *c = rm.verts[i].color; + if (shine) { // (some models' normals aren't unit length) + float fs = f < 1 ? f : 1, f2 = fs * fs, f4 = f2 * f2, f16 = f4 * f4 * f4 * f4; + l += (f16 * 0.45f + f16 * f16 * f16 * 0.35f) * shine; + } + c[0] = l * lr; + c[1] = l * lg; + c[2] = l * lb; + if (rm.light_ceiling > 0) { // at most this much light, same color + float top = c[0] > c[1] ? (c[0] > c[2] ? c[0] : c[2]) : (c[1] > c[2] ? c[1] : c[2]); + if (top > rm.light_ceiling) + for (int k = 0; k < 3; k++) + c[k] *= rm.light_ceiling / top; + } + c[3] = a; + } + } +} + +static void xmodel_draw(render_model& rm, int mpcolor, g3s_lrgb *light, const float *view, + polymodel *po, vms_angvec *anim_angles, int root) { + int num_bitmaps = rm.m.m_textures.m_nBitmaps; + static float xf[MAX_SUBMODELS][16], rot[MAX_SUBMODELS][9]; + int draw[MAX_SUBMODELS]; + int parts = po && rm.match > 0; + if (parts) + part_transforms(rm, po, anim_angles, root, xf, draw, rot); + else + for (int i = 0; i < MAX_SUBMODELS; i++) { + for (int k = 0; k < 9; k++) + rot[i][k] = k % 4 ? 0 : 1; + draw[i] = 1; + } if (GameCfg.ClassicDepth && !(Game_mode & GM_MULTI)) glEnable(GL_DEPTH_TEST); - float color_alpha; - if (tmap_drawer_ptr == draw_tmap_flat) { // cloaked effect + int cloaked = tmap_drawer_ptr == draw_tmap_flat; + if (cloaked) { // cloaked effect OGL_DISABLE(TEXTURE_2D); - color_alpha = 1.0 - (grd_curcanv->cv_fade_level/(GLfloat)GR_FADE_LEVELS) * 0.9; + color_alpha = 1.0 - (grd_curcanv->cv_fade_level/(GLfloat)NUM_LIGHTING_LEVELS); // as g3_draw_tmap glColor4f(0, 0, 0, color_alpha); } else { OGL_ENABLE(TEXTURE_2D); color_alpha = (grd_curcanv->cv_fade_level >= GR_FADE_OFF)?1.0:(1.0 - (float)grd_curcanv->cv_fade_level / ((float)GR_FADE_LEVELS - 1.0)); - glColor4f(f2fl(light->r), f2fl(light->g), f2fl(light->b), color_alpha); + shade(rm, view, rot, light, color_alpha, parts); + glColorPointer(4, GL_FLOAT, sizeof(vert), rm.verts[0].color); + glEnableClientState(GL_COLOR_ARRAY); } - - glBindBuffer(GL_ARRAY_BUFFER, rm.vbo); - glVertexPointer(3, GL_FLOAT, sizeof(vert), (void *)0); - glTexCoordPointer(2, GL_FLOAT, sizeof(vert), (void *)offsetof(vert, tex)); + glVertexPointer(3, GL_FLOAT, sizeof(vert), &rm.verts[0].pos); + glTexCoordPointer(2, GL_FLOAT, sizeof(vert), &rm.verts[0].tex); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); int team = mpcolor == -1 ? 0 : mpcolor >= 7 ? 1 : mpcolor + 2; - for (int i = 0; i < num_bitmaps; i++) { - if (!rm.bmvertcount[i]) + int cur = -1; + for (int r = 0; r < rm.nranges; r++) { + range& rg = rm.ranges[r]; + int i = rg.bitmap; + if (!draw[rg.sub]) continue; + if (parts && rg.sub != cur) { + if (cur >= 0) + glPopMatrix(); + glPushMatrix(); + glMultMatrixf(xf[rg.sub]); + cur = rg.sub; + } if (rm.m.m_textures.m_bitmaps[i].Team() && team && rm.m.m_textures.m_bitmaps[i].Team() != team) { for (int j = 0; j < num_bitmaps; j++) if (rm.m.m_textures.m_bitmaps[j].Team() == team) glBindTexture(GL_TEXTURE_2D, rm.bmtex[j]); - } else - glBindTexture(GL_TEXTURE_2D, rm.bmtex[i]); - glDrawArrays(GL_TRIANGLES, rm.bmvertofs[i], rm.bmvertcount[i]); + } else { + GLuint tex = rm.bmtex[i]; + for (int a = 0; a < rm.nanims; a++) { + anim_tex& at = rm.anims[a]; + if (at.bitmap != i) + continue; + for (int k = 0; k < at.nframes; k++) + if (at.game[k] == ObjBitmaps[at.objbm].index && at.tex[k]) + tex = at.tex[k]; + } + glBindTexture(GL_TEXTURE_2D, tex); + } + glDrawArrays(GL_TRIANGLES, rg.first, rg.count); } + if (cur >= 0) + glPopMatrix(); + if (!cloaked) + glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); - glBindBuffer(GL_ARRAY_BUFFER, 0); if (GameCfg.ClassicDepth && !(Game_mode & GM_MULTI)) glDisable(GL_DEPTH_TEST); } +void xmodel_show(void *model, int mpcolor, g3s_lrgb *light) { + static const float view[3] = { 0, 0, 1 }; + xmodel_draw(*(render_model *)model, mpcolor, light, view, NULL, NULL, -1); +} + #if 0 #define GLAPIENTRY #define GL_DEBUG_TYPE_ERROR 0x824C @@ -235,18 +858,20 @@ void gl_debug() { } #endif -void xmodel_show_at(void *model, vms_vector *pos, vms_matrix *orient, int mpcolor, g3s_lrgb *light) { - if (!((render_model *)model)->glloaded) +static void xmodel_show_posed(void *model, vms_vector *pos, vms_matrix *orient, int mpcolor, g3s_lrgb *light, + polymodel *po, vms_angvec *anim_angles, int root) { + render_model& rm = *(render_model *)model; + if (!rm.glloaded) xmodel_load_gl(model); vms_vector v,v2,vpos; vms_matrix vmat,m; + vm_vec_sub(&v,&View_position,pos); vm_vec_rotate(&v2,&v,orient); vm_copy_transpose_matrix(&m,orient); vm_matrix_x_matrix(&vmat,&m,&View_matrix); vm_vec_rotate(&vpos,&v2,&vmat); - vpos.z *= -1; // create 4x4 lookat matrix @@ -263,30 +888,55 @@ void xmodel_show_at(void *model, vms_vector *pos, vms_matrix *orient, int mpcolo for (int j = 0; j < 3; j++) fm[3 * 4 + j] = -f2fl(vpos_elem[j]); fm[15] = 1; - // forward vec -> backward vec for (int j = 0; j < 3; j++) fm[2 + j * 4] *= -1; + // the view direction in model coordinates (the forward row of the model's view matrix) + float view[3] = { f2fl(vmat.fvec.x), f2fl(vmat.fvec.y), f2fl(vmat.fvec.z) }; + glPushMatrix(); glLoadMatrixf(fm); - xmodel_show(model, mpcolor, light); + xmodel_draw(rm, mpcolor, light, view, po, anim_angles, root); glPopMatrix(); } +void xmodel_show_at(void *model, vms_vector *pos, vms_matrix *orient, int mpcolor, g3s_lrgb *light) { + xmodel_show_posed(model, pos, orient, mpcolor, light, NULL, NULL, -1); +} + void xmodel_free_all() { for (int i = 0; i < NUM_XMODELS; i++) if (xmodels[i]) { xmodel_free(xmodels[i]); xmodels[i] = NULL; } + for (int i = 0; i < NUM_XROBOTS; i++) + if (xrobots[i]) { + xmodel_free(xrobots[i]); + xrobots[i] = NULL; + } } void xmodel_load_all() { static int free_registered; - for (int i = 0; i < NUM_XMODELS; i++) + int n = 0, nr = 0; + Uint32 t = SDL_GetTicks(); + for (int i = 0; i < NUM_XMODELS; i++) { if (!xmodels[i]) xmodels[i] = xmodel_load(xmodelnames[i]); + n += xmodels[i] != NULL; + } + memset(polyobj_xrobot, -1, sizeof(polyobj_xrobot)); + for (int i = 0; i < NUM_XROBOTS; i++) { + if (!xrobots[i]) + xrobots[i] = xmodel_load(xmodel_robots[i].name); + if (xrobots[i]) + polyobj_xrobot[xmodel_robots[i].model] = i; + nr += xrobots[i] != NULL; + } + if (n || nr) + con_printf(CON_NORMAL, "Loaded %d models and %d robot models in %u ms\n", n, nr, SDL_GetTicks() - t); if (!free_registered) { atexit(xmodel_free_all); free_registered = 1; @@ -297,12 +947,18 @@ void xmodel_load_gl_all() { for (int i = 0; i < NUM_XMODELS; i++) if (xmodels[i]) xmodel_load_gl(xmodels[i]); + for (int i = 0; i < NUM_XROBOTS; i++) + if (xrobots[i]) + xmodel_load_gl(xrobots[i]); } void xmodel_free_gl_all() { for (int i = 0; i < NUM_XMODELS; i++) if (xmodels[i]) xmodel_free_gl(xmodels[i]); + for (int i = 0; i < NUM_XROBOTS; i++) + if (xrobots[i]) + xmodel_free_gl(xrobots[i]); } static int xmodel_xlate(enum xmodel_type mt, int modelnum) { @@ -315,14 +971,48 @@ static int xmodel_xlate(enum xmodel_type mt, int modelnum) { // returns 1 if drawn int xmodel_show_if_loaded(enum xmodel_type mt, int modelnum, vms_vector *pos, vms_matrix *orient, int mpcolor, g3s_lrgb *light) { - int xmodelnum = xmodel_xlate(mt, modelnum); + int xmodelnum = xmodel_enabled ? xmodel_xlate(mt, modelnum) : -1; if (xmodelnum == -1 || !xmodels[xmodelnum]) return 0; xmodel_show_at(xmodels[xmodelnum], pos, orient, xmodelnum == model_pyrogl ? mpcolor : -1, light); return 1; } +// A game model: robots follow its animation (and break into its parts as debris, flags +// being the parts to draw); returns 1 if drawn. +int xmodel_show_polyobj(int modelnum, vms_vector *pos, vms_matrix *orient, vms_angvec *anim_angles, int flags, + int mpcolor, g3s_lrgb *light) { + if (modelnum < 0 || modelnum >= MAX_POLYGON_MODELS || !xmodel_enabled) + return 0; + if (polyobj_xrobot[modelnum] >= 0) { + render_model& rm = *(render_model *)xrobots[(int)polyobj_xrobot[modelnum]]; + polymodel *po = &Polygon_models[modelnum]; + if (!rm.match) { + fit_textures(rm, po); + rm.match = parts_match(rm, po) ? 1 : -1; + if (rm.match < 0) + con_printf(CON_VERBOSE, "%s: parts differ from model %d, drawn without animation\n", + xmodel_robots[(int)polyobj_xrobot[modelnum]].name, modelnum); + } + int root = -1; + if (flags) { + // debris is one part; without matching parts leave it to the game model + if (rm.match < 0) + return 0; + for (root = 0; !(flags & 1); flags >>= 1) + root++; + if (root >= rm.nsubs) + return 0; + } + xmodel_show_posed(&rm, pos, orient, -1, light, po, anim_angles, root); + return 1; + } + if (flags) + return 0; + return xmodel_show_if_loaded(XM_POLYOBJ, modelnum, pos, orient, mpcolor, light); +} + int xmodel_exists(enum xmodel_type mt, int modelnum) { - int xmodelnum = xmodel_xlate(mt, modelnum); + int xmodelnum = xmodel_enabled ? xmodel_xlate(mt, modelnum) : -1; return xmodelnum != -1 && xmodels[xmodelnum]; } diff --git a/d2/xmodel/xmodelnames.h b/d2/xmodel/xmodelnames.h index c9a5a0e..baf8cbf 100644 --- a/d2/xmodel/xmodelnames.h +++ b/d2/xmodel/xmodelnames.h @@ -219,7 +219,7 @@ const char *xmodelnames[] = { "sminepack.ase", "smartmine.ase", "superlaser.ase", - "eshakersub.ase", + "shakrsub.ase", "laser5.ase", "laser6.ase", "shield.ase", @@ -228,6 +228,91 @@ const char *xmodelnames[] = { #define NUM_XMODELS ((int)(sizeof(xmodelnames) / sizeof(xmodelnames[0]))) +// Robot models by game model number, as D2X-XL pairs them (models/hiresmodels.cpp) +struct xmodel_robot { + short model; + const char *name; +}; + +const struct xmodel_robot xmodel_robots[] = { + {0, "smallhulk.ase"}, + {2, "mediumlifter.ase"}, + {4, "spider.ase"}, + {6, "class1drone.ase"}, + {8, "class2drone.ase"}, + {10, "class1driller-cloaked.ase"}, + {14, "class2supervisor.ase"}, + {15, "secondarylifter.ase"}, + {17, "class1heavydriller.ase"}, + {19, "class3gopher.ase"}, + {20, "class1platform.ase"}, + {21, "class2platform.ase"}, + {23, "smallspider.ase"}, + {25, "fusionhulk.ase"}, + {26, "superhulk.ase"}, + {28, "d1boss1.ase"}, + {29, "cloakedlifter.ase"}, + {31, "class1driller.ase"}, + {33, "mediumhulk.ase"}, + {35, "advancedlifter.ase"}, + {37, "ptmcdefense.ase"}, + {39, "d1boss2.ase"}, + {40, "bper.ase"}, + {41, "smelter.ase"}, + {43, "icespider.ase"}, + {44, "bulkdestroyer.ase"}, + {45, "trnracer.ase"}, + {46, "foxattackbot.ase"}, + {47, "sidarm.ase"}, + {49, "redfattyboss.ase"}, + {51, "guidebot.ase"}, + {54, "eviltwin.ase"}, + {55, "itsc.ase"}, + {56, "itdroid.ase"}, + {58, "pest.ase"}, + {60, "pig.ase"}, + {62, "d-claw.ase"}, + {64, "redhornet.ase"}, + {65, "thief.ase"}, + {67, "seeker.ase"}, + {68, "e-bandit.ase"}, + {69, "fireboss.ase"}, + {70, "waterboss.ase"}, + {71, "boarshead.ase"}, + {72, "greenspider.ase"}, + {73, "omegabot.ase"}, + {75, "louguard.ase"}, + {76, "alienboss1.ase"}, + {77, "redfattyjunior.ase"}, + {78, "d-claw-cloaked.ase"}, + {80, "smelter-cloaked.ase"}, + {81, "smelterclone-cloaked.ase"}, + {82, "omegaspawn.ase"}, + {83, "smelterclone.ase"}, + {85, "omegaclone.ase"}, + {86, "bperclone.ase"}, + {87, "spiderclone.ase"}, + {88, "spiderspawn.ase"}, + {89, "iceboss.ase"}, + {90, "spiderspawnclone.ase"}, + {91, "alienboss2.ase"}, + // Vertigo (its robots follow the game's 166 models) + {166, "compactlifter.ase"}, + {167, "fervid99.ase"}, + {168, "fiddler.ase"}, + {169, "class2heavydriller.ase"}, + {170, "smelter2.ase"}, + {171, "max.ase"}, + {172, "sniperng.ase"}, + {173, "logikill.ase"}, + {174, "canary.ase"}, + {175, "vertigoboss.ase"}, + {176, "redguard.ase"}, + {177, "spike.ase"}, +}; + +#define NUM_XROBOTS ((int)(sizeof(xmodel_robots) / sizeof(xmodel_robots[0]))) + short xmodel_polyobj_xlate[] = { model_mediumhulk, model_mediumhulk,