From 53a7b3d47ca12667f3796d05901fe10046a7c494 Mon Sep 17 00:00:00 2001 From: Spoike Date: Tue, 27 Nov 2012 03:23:19 +0000 Subject: [PATCH] added support for external capture plugins - and using avcodec as a plugin.c. The ragdoll API is potentially usable now, but still really limited. Enabled SQL requests by default using sqlite. Note that you'll need the sqlite dll to use this. MySQL should still be usable, but I didn't try. MySQL requires -DUSE_MYSQL to compile it, and a dll and -mysql argument to enable it. Fixed nacl. NPFTE plugin now invokes an exe to run the game rather than running the game within the browser. externvalue builtin now accepts & prefix to return a pointer instead. Fixed vector autocvars. uri_get, bufstr_add, bufstr_free, now functional. QC debugger can now show asm if line numbers are not available. Added support for QC watchpoints. Use the watchpoint command. gl_specular now give specular even without rtlights, thankfully not as blatently, but its there. android will not crash due to supported audio formats, and gles2 can be selected via a cvar (requires full FTEDroidActivity/program restart). git-svn-id: https://svn.code.sf.net/p/fteqw/code/trunk@4152 fc73d0e0-1445-4013-8a0c-d673dee63da5 --- README.txt | 29 + engine/Makefile | 3 + engine/client/cl_cam.c | 2 +- engine/client/cl_demo.c | 28 +- engine/client/cl_ents.c | 10 +- engine/client/cl_main.c | 286 +- engine/client/cl_master.h | 4 +- engine/client/cl_parse.c | 85 +- engine/client/cl_screen.c | 96 +- engine/client/cl_tent.c | 23 +- engine/client/clhl_game.c | 2 +- engine/client/client.h | 23 +- engine/client/console.c | 338 +- engine/client/image.c | 48 +- engine/client/in_win.c | 4 +- engine/client/keys.c | 397 +- engine/client/m_download.c | 170 + engine/client/m_mp3.c | 805 +- engine/client/m_options.c | 10 + engine/client/net_master.c | 54 +- engine/client/p_script.c | 13 +- engine/client/pr_csqc.c | 43 +- engine/client/pr_menu.c | 171 +- engine/client/pr_skelobj.c | 476 +- engine/client/quakedef.h | 4 +- engine/client/r_2d.c | 65 +- engine/client/r_partset.c | 6 +- engine/client/r_surf.c | 357 +- engine/client/render.h | 8 +- engine/client/renderer.c | 35 +- engine/client/renderque.c | 33 + engine/client/renderque.h | 1 + engine/client/sbar.c | 53 +- engine/client/screen.h | 2 +- engine/client/snd_alsa.c | 50 +- engine/client/snd_dma.c | 4 +- engine/client/snd_droid.c | 107 +- engine/client/snd_mem.c | 18 +- engine/client/sys_axfte.cpp | 23 +- engine/client/sys_droid.c | 23 +- engine/client/sys_morphos.c | 2 + engine/client/sys_npfte.c | 35 +- engine/client/sys_plugfte.c | 832 +- engine/client/sys_plugfte.h | 5 +- engine/client/sys_sdl.c | 2 + engine/client/sys_win.c | 419 +- engine/client/textedit.c | 421 +- engine/client/view.c | 17 +- engine/common/bothdefs.h | 11 + engine/common/cmd.c | 59 +- engine/common/cmd.h | 5 +- engine/common/com_mesh.c | 12 +- engine/common/com_phys_ode.c | 197 +- engine/common/common.c | 139 +- engine/common/common.h | 6 +- engine/common/console.h | 12 +- engine/common/fs.c | 162 +- engine/common/fs_stdio.c | 2 +- engine/common/fs_zip.c | 2 + engine/common/gl_q2bsp.c | 3 +- engine/common/mathlib.c | 9 +- engine/common/mathlib.h | 2 +- engine/common/net.h | 2 +- engine/common/net_chan.c | 2 +- engine/common/net_wins.c | 60 +- engine/common/plugin.c | 10 + engine/common/pr_bgcmd.c | 292 +- engine/common/pr_common.h | 40 +- engine/common/protocol.h | 9 +- engine/common/qvm.c | 13 - engine/common/sys.h | 1 + engine/common/world.h | 6 + engine/d3d/d3d11_backend.c | 19 +- engine/d3d/d3d11_image.c | 7 +- engine/d3d/d3d11_shader.c | 12 +- engine/d3d/d3d_backend.c | 58 +- engine/d3d/d3d_shader.c | 18 +- engine/dotnet2005/ftequake.sln | 48 +- engine/dotnet2005/ftequake.vcproj | 337 +- engine/dotnet2005/npfte.vcproj | 26807 +--------------- .../droid/src/com/fteqw/FTEDroidActivity.java | 344 +- .../droid/src/com/fteqw/FTEDroidEngine.java | 1 + engine/gl/gl_alias.c | 4 +- engine/gl/gl_backend.c | 427 +- engine/gl/gl_bloom.c | 2 - engine/gl/gl_draw.c | 30 +- engine/gl/gl_font.c | 44 +- engine/gl/gl_heightmap.c | 145 +- engine/gl/gl_hlmdl.c | 170 - engine/gl/gl_model.c | 22 +- engine/gl/gl_model.h | 3 + engine/gl/gl_rmain.c | 94 +- engine/gl/gl_screen.c | 8 +- engine/gl/gl_shader.c | 298 +- engine/gl/gl_shadow.c | 11 +- engine/gl/gl_vidcommon.c | 31 +- engine/gl/gl_viddroid.c | 11 +- engine/gl/gl_vidnt.c | 35 +- engine/gl/ltface.c | 8 +- engine/gl/r_bishaders.h | 630 +- engine/gl/shader.h | 14 +- engine/http/httpclient.c | 70 +- engine/http/iweb.h | 1 + engine/libs/vorbis/vorbisfile.h | 117 +- engine/nacl/sys_ppapi.c | 44 +- engine/partcfgs/high.cfg | 6 +- engine/qclib/comprout.c | 8 +- engine/qclib/execloop.h | 198 +- engine/qclib/initlib.c | 3 + engine/qclib/pr_comp.h | 9 - engine/qclib/pr_edict.c | 100 +- engine/qclib/pr_exec.c | 320 +- engine/qclib/pr_multi.c | 20 +- engine/qclib/progsint.h | 8 +- engine/qclib/progslib.h | 12 +- engine/qclib/qcc.h | 2 + engine/qclib/qcc_pr_comp.c | 53 +- engine/qclib/qcc_pr_lex.c | 81 +- engine/qclib/qccmain.c | 7 +- engine/server/pr_cmds.c | 297 +- engine/server/progdefs.h | 41 +- engine/server/sqlite3.h | 7097 ++++ engine/server/sv_init.c | 6 +- engine/server/sv_main.c | 14 +- engine/server/sv_mvd.c | 26 +- engine/server/sv_phys.c | 1 - engine/server/sv_send.c | 1 + engine/server/sv_sql.c | 656 +- engine/server/sv_sql.h | 28 +- engine/server/sv_sys_win.c | 58 +- engine/server/sv_user.c | 9 +- engine/server/svhl_game.c | 2 +- engine/server/world.c | 2 +- engine/setup/setup.vdproj | 194 +- engine/shaders/generatebuiltinsl.c | 41 +- engine/shaders/glsl/altwater.glsl | 7 +- engine/shaders/glsl/defaultwall.glsl | 84 +- engine/shaders/hlsl11/default2d.hlsl | 34 + engine/shaders/hlsl11/defaultfill.hlsl | 29 + engine/shaders/hlsl11/defaultskin.hlsl | 57 + engine/shaders/hlsl11/defaultsky.hlsl | 47 + engine/shaders/hlsl11/defaultsprite.hlsl | 36 + engine/shaders/hlsl11/defaultwall.hlsl | 36 + engine/shaders/hlsl11/defaultwarp.hlsl | 41 + engine/shaders/hlsl11/drawflat_wall.hlsl | 39 + engine/shaders/hlsl11/terrain.hlsl | 49 + engine/shaders/hlsl11/terraindebug.hlsl | 36 + engine/shaders/hlsl9/defaultsky.hlsl | 52 + engine/shaders/hlsl9/defaultwarp.hlsl | 36 + engine/shaders/hlsl9/rtlight.hlsl | 62 + plugins/avplug/avdecode.c | 266 + plugins/avplug/avencode.c | 435 + plugins/avplug/readme.txt | 22 + plugins/berkelium/berkelium.vcproj | 6 +- plugins/berkelium/plugapi.cpp | 18 +- plugins/engine.h | 28 +- plugins/plugin.c | 14 + plugins/plugin.h | 1 + specs/console.txt | 67 + 159 files changed, 17179 insertions(+), 30191 deletions(-) create mode 100644 engine/server/sqlite3.h create mode 100644 engine/shaders/hlsl11/default2d.hlsl create mode 100644 engine/shaders/hlsl11/defaultfill.hlsl create mode 100644 engine/shaders/hlsl11/defaultskin.hlsl create mode 100644 engine/shaders/hlsl11/defaultsky.hlsl create mode 100644 engine/shaders/hlsl11/defaultsprite.hlsl create mode 100644 engine/shaders/hlsl11/defaultwall.hlsl create mode 100644 engine/shaders/hlsl11/defaultwarp.hlsl create mode 100644 engine/shaders/hlsl11/drawflat_wall.hlsl create mode 100644 engine/shaders/hlsl11/terrain.hlsl create mode 100644 engine/shaders/hlsl11/terraindebug.hlsl create mode 100644 engine/shaders/hlsl9/defaultsky.hlsl create mode 100644 engine/shaders/hlsl9/defaultwarp.hlsl create mode 100644 engine/shaders/hlsl9/rtlight.hlsl create mode 100644 plugins/avplug/avdecode.c create mode 100644 plugins/avplug/avencode.c create mode 100644 plugins/avplug/readme.txt create mode 100644 specs/console.txt diff --git a/README.txt b/README.txt index 255fba85..4d94a753 100644 --- a/README.txt +++ b/README.txt @@ -28,6 +28,35 @@ Note that there is no way to install the package with a different name at this t +Browser versions of FTE: +The FTE browser plugin is available only in windows. +Compile with 'make npfte-rel FTE_TARGET=win32'. +This will yield an npfte.dll file. +You can 'register' this dll by running 'regsvr32 npfte.dll' at a command prompt (this is the standard way to register an activex control - any setup software should provide some mechanism to do this at install time). This will register both the netscape/firefox/chrome/opera version, and the activex/IE version of the plugin. +Note that the plugin will run the engine in a separate process and thus requires a valid fteqw.exe file in the same directory as the plugin. +If given an 'npfte.txt' file that contains the line 'relexe foo', the plugin will try to run foo.exe instead of fteqw, basedir "foo" can be used to invoke it with a different basedir. You can use this if you'd rather run the mingl or gl-only version, or if you'd like to retarget npfte to invoke a different quake engine intead. Note that different quake engines will need to support the -plugin argument and the stdin/stdout parsing for embedding - at the time of writing, no others do. +The following chunk of html can then be included on a web page to embed it. Yes. Two nested objects. +Plugin failed to load + +Nacl version of FTE: +make gl-rel FTE_TARGET=nacl NACL_SDK_ROOT=SOMEVALIDPATHHERE BITS=32 +make gl-rel FTE_TARGET=nacl NACL_SDK_ROOT=SOMEVALIDPATHHERE BITS=64 +in windows compile with cygwin, not minsys. +This will give you two 'nexe' files. +You can then embed the 'fteqw.nmf' file (its entire contents can be found on the following line) with mime type 'application/x-nacl' on your page. Give it a sane width/height. + { + "program": { + "x86-64": {"url": "fteqw_x86_64.nexe"}, + "x86-32": {"url": "fteqw_x86_32.nexe"} + } +} + +You can object.postMessage("join foo") / qtvplay / map to tell it to switch server/map/stream. +You can read console prints via listener.addEventListener('message', handleMessage, true); +Your users will need to explicitly allow nacl use outside of google play (in about:config or whatever it is), or you will need to submit your port of fte to google play. + + + This stuff has separate directories engine: FTEQW game engine itself. Both client and dedicated server. engine/ftequake: location of old msvc6 project file. Might not work. diff --git a/engine/Makefile b/engine/Makefile index 696487b2..e949d495 100644 --- a/engine/Makefile +++ b/engine/Makefile @@ -537,6 +537,7 @@ SERVER_OBJS = \ sv_ents.o \ sv_send.o \ sv_user.o \ + sv_sql.o \ sv_mvd.o \ sv_ccmds.o \ sv_rankin.o \ @@ -664,6 +665,8 @@ endif #specific targets override those defaults as needed. #google native client ifeq ($(FTE_TARGET),nacl) + OGGVORBISLDFLAGS= + ifeq ($(shell uname -o 2>&1 | grep Cygwin),) CC=$(NACL_SDK_ROOT)/toolchain/linux_x86_newlib/bin/i686-nacl-gcc -DNACL -m$(BITS) STRIP=$(NACL_SDK_ROOT)/toolchain/linux_x86_newlib/bin/i686-nacl-strip diff --git a/engine/client/cl_cam.c b/engine/client/cl_cam.c index f25362fa..5b084b4b 100644 --- a/engine/client/cl_cam.c +++ b/engine/client/cl_cam.c @@ -697,7 +697,7 @@ void Cam_TrackPlayer(int pnum, char *cmdname, char *plrarg) c = plrarg; while (*c) { - if (!isdigit(*c)) + if (*c < '0' || *c > '9') { Con_Printf("Couldn't find nick %s\n", plrarg); return; diff --git a/engine/client/cl_demo.c b/engine/client/cl_demo.c index 08046c41..588559ff 100644 --- a/engine/client/cl_demo.c +++ b/engine/client/cl_demo.c @@ -34,7 +34,7 @@ char lastdemoname[256]; extern cvar_t qtvcl_forceversion1; extern cvar_t qtvcl_eztvextensions; -unsigned char demobuffer[1024*16]; +unsigned char demobuffer[1024*66]; int demobuffersize; int demopreparsedbytes; qboolean disablepreparse; @@ -325,20 +325,19 @@ void CL_DemoJump_f(void) if (!cls.demoplayback) return; - if (*s == '+') + if (*s == '+' || *s == '-') { if (colon) { colon++; - demtime += atoi(colon); - - demtime += atoi(s)*60; + newtime = demtime + atoi(colon) + atoi(s)*60; } else - demtime += atoi(s); + newtime = demtime + atoi(s); } else { + //absolute seek time if (colon) { colon++; @@ -347,16 +346,17 @@ void CL_DemoJump_f(void) } else newtime = atoi(s); + } - if (newtime >= demtime) - demtime = newtime; - else - { - Con_Printf("Rewinding demo\n"); - CL_PlayDemo(lastdemoname); + if (newtime >= demtime) + demtime = newtime; + else + { + Con_Printf("Rewinding demo\n"); + CL_PlayDemo(lastdemoname); - demtime = newtime; - } + //now fastparse it. + demtime = newtime; } } diff --git a/engine/client/cl_ents.c b/engine/client/cl_ents.c index 4b6fa7b4..0c0a0263 100644 --- a/engine/client/cl_ents.c +++ b/engine/client/cl_ents.c @@ -2242,9 +2242,9 @@ void CL_LinkStaticEntities(void *pvs) if ((!r_drawflame.ival) && (clmodel->engineflags & MDLF_FLAME)) continue; + /*pvs test*/ if (pvs && !cl.worldmodel->funcs.EdictInFatPVS(cl.worldmodel, &cl_static_entities[i].pvscache, pvs)) continue; - /*pvs test*/ ent = &cl_visedicts[cl_numvisedicts++]; *ent = *stat; @@ -3255,11 +3255,13 @@ void CL_ParsePlayerinfo (void) TP_ParsePlayerInfo(oldstate, state, info); + + //can't CL_SetStatInt as we don't know if its actually us or not cl.players[num].stats[STAT_WEAPONFRAME] = state->weaponframe; cl.players[num].statsf[STAT_WEAPONFRAME] = state->weaponframe; for (i = 0; i < cl.splitclients; i++) { - if (cl.playernum[i] == num) + if (spec_track[i] == num) { cl.playerview[i].stats[STAT_WEAPONFRAME] = state->weaponframe; cl.playerview[i].statsf[STAT_WEAPONFRAME] = state->weaponframe; @@ -3484,9 +3486,10 @@ guess_pm_type: TP_ParsePlayerInfo(oldstate, state, info); + //can't CL_SetStatInt as we don't know if its actually us or not for (i = 0; i < cl.splitclients; i++) { - if (cl.playernum[i] == num) + if (spec_track[i] == num) { cl.playerview[i].stats[STAT_WEAPONFRAME] = state->weaponframe; cl.playerview[i].statsf[STAT_WEAPONFRAME] = state->weaponframe; @@ -3729,6 +3732,7 @@ void CL_LinkPlayers (void) { vec3_t org; VectorCopy(state->origin, org); + //make the light appear at the predicted position rather than anywhere else. for (pnum = 0; pnum < cl.splitclients; pnum++) if (cl.playernum[pnum] == j) VectorCopy(cl.playerview[pnum].simorg, org); diff --git a/engine/client/cl_main.c b/engine/client/cl_main.c index b7a29b7f..814b6040 100644 --- a/engine/client/cl_main.c +++ b/engine/client/cl_main.c @@ -102,7 +102,7 @@ extern int total_loading_size, current_loading_size, loading_stage; // // info mirrors // -cvar_t password = CVARF("password", "", CVAR_USERINFO | CVAR_NOUNSAFEEXPAND); //this is parhaps slightly dodgy... +cvar_t password = CVARAF("password", "", "pq_password", CVAR_USERINFO | CVAR_NOUNSAFEEXPAND); //this is parhaps slightly dodgy... added pq_password alias because baker seems to be using this for user accounts. cvar_t spectator = CVARF("spectator", "", CVAR_USERINFO); cvar_t name = CVARFC("name", "unnamed", CVAR_ARCHIVE | CVAR_USERINFO, Name_Callback); cvar_t team = CVARF("team", "", CVAR_ARCHIVE | CVAR_USERINFO); @@ -1089,6 +1089,7 @@ void CL_ClearState (void) CL_ClearParseState(); CL_ClearTEnts(); CL_ClearCustomTEnts(); + Surf_ClearLightmaps(); T_FreeInfoStrings(); SCR_ShowPic_Clear(); @@ -1135,6 +1136,7 @@ void CL_ClearState (void) cl.allocated_client_slots = QWMAX_CLIENTS; #ifndef CLIENTONLY + //FIXME: we should just set it to 0 to make sure its set up properly elsewhere. if (sv.state) cl.allocated_client_slots = sv.allocated_client_slots; #endif @@ -3406,6 +3408,8 @@ Writes key bindings and archived cvars to config.cfg void Host_WriteConfiguration (void) { vfsfile_t *f; + char savename[MAX_OSPATH]; + char sysname[MAX_OSPATH]; if (host_initialized && cfg_save_name.string && *cfg_save_name.string) { @@ -3415,7 +3419,9 @@ void Host_WriteConfiguration (void) return; } - f = FS_OpenVFS(va("%s.cfg",cfg_save_name.string), "wb", FS_GAMEONLY); + Q_snprintfz(savename, sizeof(savename), "%s.cfg", cfg_save_name.string); + + f = FS_OpenVFS(savename, "wb", FS_GAMEONLY); if (!f) { Con_TPrintf (TLC_CONFIGCFG_WRITEFAILED); @@ -3426,6 +3432,9 @@ void Host_WriteConfiguration (void) Cvar_WriteVariables (f, false); VFS_CLOSE (f); + + FS_NativePath(savename, FS_GAMEONLY, sysname, sizeof(sysname)); + Con_Printf("Wrote %s\n", savename); } } @@ -3477,7 +3486,7 @@ double Host_Frame (double time) static double time3 = 0; int pass1, pass2, pass3; // float fps; - double realframetime; + double realframetime, newrealtime; static double spare; float maxfps; qboolean maxfpsignoreserver; @@ -3490,7 +3499,13 @@ double Host_Frame (double time) return 0; // something bad happened, or the server disconnected } - realframetime = time = Media_TweekCaptureFrameTime(time); + newrealtime = Media_TweekCaptureFrameTime(realtime, time); + + realframetime = time = newrealtime - realtime; + realtime = newrealtime; + + if (oldrealtime > realtime) + oldrealtime = 0; // if (cls.demoplayback && cl_demospeed.value>0) // realframetime *= cl_demospeed.value; // this probably screws up other timings @@ -3508,11 +3523,6 @@ double Host_Frame (double time) Plug_Tick(); #endif - // decide the simulation time - realtime += realframetime; - if (oldrealtime > realtime) - oldrealtime = 0; - if (cl.paused) cl.gametimemark += time; @@ -3570,7 +3580,7 @@ double Host_Frame (double time) maxfps = 4; } - if (maxfps > 0) + if (maxfps > 0 && Media_Capturing() != 2) { realtime += spare/1000; //don't use it all! spare = CL_FilterTime((realtime - oldrealtime)*1000, maxfps, maxfpsignoreserver); @@ -3779,6 +3789,130 @@ void CL_ReadCDKey(void) //============================================================================ +void CL_StartCinematicOrMenu(void) +{ + //start up the ui now we have a renderer +#ifdef VM_UI + UI_Start(); +#endif + + Con_TPrintf (TLC_QUAKEWORLD_INITED, fs_gamename.string); + + //there might be some console command or somesuch waiting for the renderer to begin (demos or map command or whatever all need model support). + realtime+=1; + Cbuf_Execute (); //server may have been waiting for the renderer + + //and any startup cinematics +#ifndef NOMEDIA + if (!cls.demoinfile && !cls.state && !Media_PlayingFullScreen()) + { + int ol_depth; + int idcin_depth; + int idroq_depth; + + idcin_depth = COM_FDepthFile("video/idlog.cin", true); //q2 + idroq_depth = COM_FDepthFile("video/idlogo.roq", true); //q2 + ol_depth = COM_FDepthFile("video/openinglogos.roq", true); //jk2 + + if (ol_depth != 0x7fffffff && (ol_depth <= idroq_depth || ol_depth <= idcin_depth)) + Media_PlayFilm("video/openinglogos.roq"); + else if (idroq_depth != 0x7fffffff && idroq_depth <= idcin_depth) + Media_PlayFilm("video/idlogo.roq"); + else if (idcin_depth != 0x7fffffff) + Media_PlayFilm("video/idlog.cin"); + } +#endif + + if (!cls.demoinfile && !*cls.servername && !Media_Playing()) + { +#ifndef CLIENTONLY + if (!sv.state) +#endif + { + if (qrenderer > QR_NONE) + M_ToggleMenu_f(); + //Con_ForceActiveNow(); + } + } +} + +//note that this does NOT include commandline. +void CL_ExecInitialConfigs(void) +{ + int qrc, hrc, def, i; + + Cbuf_AddText ("cl_warncmd 0\n", RESTRICT_LOCAL); + + //who should we imitate? + qrc = COM_FDepthFile("quake.rc", true); //q1 + hrc = COM_FDepthFile("hexen.rc", true); //h2 + def = COM_FDepthFile("default.cfg", true); //q2/q3 + + if (qrc <= def && qrc <= hrc && qrc!=0x7fffffff) + Cbuf_AddText ("exec quake.rc\n", RESTRICT_LOCAL); + else if (hrc <= def && hrc!=0x7fffffff) + Cbuf_AddText ("exec hexen.rc\n", RESTRICT_LOCAL); + else + { //they didn't give us an rc file! + Cbuf_AddText ("bind ~ toggleconsole\n", RESTRICT_LOCAL); //we expect default.cfg to not exist. :( + Cbuf_AddText ("exec default.cfg\n", RESTRICT_LOCAL); + if (COM_FCheckExists ("config.cfg")) + Cbuf_AddText ("exec config.cfg\n", RESTRICT_LOCAL); + if (COM_FCheckExists ("q3config.cfg")) + Cbuf_AddText ("exec q3config.cfg\n", RESTRICT_LOCAL); + Cbuf_AddText ("exec autoexec.cfg\n", RESTRICT_LOCAL); + } + Cbuf_AddText ("exec fte.cfg\n", RESTRICT_LOCAL); + + if (COM_FCheckExists ("frontend.cfg")) + Cbuf_AddText ("exec frontend.cfg\n", RESTRICT_LOCAL); + Cbuf_AddText ("cl_warncmd 1\n", RESTRICT_LOCAL); //and then it's allowed to start moaning. + + { + extern cvar_t com_parseutf8; + com_parseutf8.ival = com_parseutf8.value; + } + +// Cbuf_Execute (); //if the server initialisation causes a problem, give it a place to abort to + + + //assuming they didn't use any waits in their config (fools) + //the configs should be fully loaded. + //so convert the backwards compable commandline parameters in cvar sets. + + if (COM_CheckParm ("-window") || COM_CheckParm ("-startwindowed")) + Cvar_Set(Cvar_FindVar("vid_fullscreen"), "0"); + if (COM_CheckParm ("-fullscreen")) + Cvar_Set(Cvar_FindVar("vid_fullscreen"), "1"); + + if ((i = COM_CheckParm ("-width"))) //width on it's own also sets height + { + Cvar_Set(Cvar_FindVar("vid_width"), com_argv[i+1]); + Cvar_SetValue(Cvar_FindVar("vid_height"), (atoi(com_argv[i+1])/4)*3); + } + if ((i = COM_CheckParm ("-height"))) + Cvar_Set(Cvar_FindVar("vid_height"), com_argv[i+1]); + + if ((i = COM_CheckParm ("-conwidth"))) //width on it's own also sets height + { + Cvar_Set(Cvar_FindVar("vid_conwidth"), com_argv[i+1]); + Cvar_SetValue(Cvar_FindVar("vid_conheight"), (atoi(com_argv[i+1])/4)*3); + } + if ((i = COM_CheckParm ("-conheight"))) + Cvar_Set(Cvar_FindVar("vid_conheight"), com_argv[i+1]); + + if ((i = COM_CheckParm ("-bpp"))) + Cvar_Set(Cvar_FindVar("vid_bpp"), com_argv[i+1]); + + if (COM_CheckParm ("-current")) + Cvar_Set(Cvar_FindVar("vid_desktopsettings"), "1"); + Cbuf_Execute (); //if the server initialisation causes a problem, give it a place to abort to +} + + + + + /* ==================== Host_Init @@ -3786,12 +3920,8 @@ Host_Init */ void Host_Init (quakeparms_t *parms) { -#ifndef NPFTE - int i; - int qrc, hrc, def; -#endif extern cvar_t com_parseutf8; - com_parseutf8.ival = 1; + com_parseutf8.ival = 1; //enable utf8 parsing even before cvars are registered. COM_InitArgv (parms->argc, parms->argv); @@ -3875,117 +4005,27 @@ void Host_Init (quakeparms_t *parms) host_initialized = true; -#ifdef NPFTE -} + Sys_SendKeyEvents(); -void Host_FinishInit(void) -{ - int i; - int qrc, hrc, def; -#endif - Cbuf_AddText ("cl_warncmd 0\n", RESTRICT_LOCAL); + //the engine is technically initialised at this point, except for the renderer. now we exec configs and bring up the renderer + //anything that needs models cannot be run yet, but it should be safe to allow console commands etc. + //if we get a map command, we'll just stick it on the end of the console command buffer. - //who should we imitate? - qrc = COM_FDepthFile("quake.rc", true); //q1 - hrc = COM_FDepthFile("hexen.rc", true); //h2 - def = COM_FDepthFile("default.cfg", true); //q2/q3 + Con_History_Load(); - if (qrc <= def && qrc <= hrc && qrc!=0x7fffffff) - Cbuf_AddText ("exec quake.rc\n", RESTRICT_LOCAL); - else if (hrc <= def && hrc!=0x7fffffff) - Cbuf_AddText ("exec hexen.rc\n", RESTRICT_LOCAL); - else - { //they didn't give us an rc file! - Cbuf_AddText ("bind ~ toggleconsole\n", RESTRICT_LOCAL); //we expect default.cfg to not exist. :( - Cbuf_AddText ("exec default.cfg\n", RESTRICT_LOCAL); - if (COM_FCheckExists ("config.cfg")) - Cbuf_AddText ("exec config.cfg\n", RESTRICT_LOCAL); - if (COM_FCheckExists ("q3config.cfg")) - Cbuf_AddText ("exec q3config.cfg\n", RESTRICT_LOCAL); - Cbuf_AddText ("exec autoexec.cfg\n", RESTRICT_LOCAL); - } - Cbuf_AddText ("exec fte.cfg\n", RESTRICT_LOCAL); - - if (COM_FCheckExists ("frontend.cfg")) - Cbuf_AddText ("exec frontend.cfg\n", RESTRICT_LOCAL); - Cbuf_AddText ("cl_warncmd 1\n", RESTRICT_LOCAL); //and then it's allowed to start moaning. + CL_ExecInitialConfigs(); + if (CL_CheckBootDownloads()) { - extern cvar_t com_parseutf8; - com_parseutf8.ival = com_parseutf8.value; + Cmd_StuffCmds(); + Cbuf_Execute (); } - Cbuf_Execute (); //if the server initialisation causes a problem, give it a place to abort to - - - //assuming they didn't use any waits in their config (fools) - //the configs should be fully loaded. - //so convert the backwards compable commandline parameters in cvar sets. - - if (COM_CheckParm ("-window") || COM_CheckParm ("-startwindowed")) - Cvar_Set(Cvar_FindVar("vid_fullscreen"), "0"); - if (COM_CheckParm ("-fullscreen")) - Cvar_Set(Cvar_FindVar("vid_fullscreen"), "1"); - - if ((i = COM_CheckParm ("-width"))) //width on it's own also sets height - { - Cvar_Set(Cvar_FindVar("vid_width"), com_argv[i+1]); - Cvar_SetValue(Cvar_FindVar("vid_height"), (atoi(com_argv[i+1])/4)*3); - } - if ((i = COM_CheckParm ("-height"))) - Cvar_Set(Cvar_FindVar("vid_height"), com_argv[i+1]); - - if ((i = COM_CheckParm ("-conwidth"))) //width on it's own also sets height - { - Cvar_Set(Cvar_FindVar("vid_conwidth"), com_argv[i+1]); - Cvar_SetValue(Cvar_FindVar("vid_conheight"), (atoi(com_argv[i+1])/4)*3); - } - if ((i = COM_CheckParm ("-conheight"))) - Cvar_Set(Cvar_FindVar("vid_conheight"), com_argv[i+1]); - - if ((i = COM_CheckParm ("-bpp"))) - Cvar_Set(Cvar_FindVar("vid_bpp"), com_argv[i+1]); - - if (COM_CheckParm ("-current")) - Cvar_Set(Cvar_FindVar("vid_desktopsettings"), "1"); - - //now exec their commandline - Cmd_StuffCmds(); - Cbuf_Execute (); //if the server initialisation causes a problem, give it a place to abort to - - Renderer_Start(); - -#ifdef VM_UI - UI_Start(); -#endif - -#ifndef NOMEDIA - if (!cls.demoinfile && !cls.state && !Media_PlayingFullScreen()) - { - int ol_depth; - int idcin_depth; - int idroq_depth; - - idcin_depth = COM_FDepthFile("video/idlog.cin", true); //q2 - idroq_depth = COM_FDepthFile("video/idlogo.roq", true); //q2 - ol_depth = COM_FDepthFile("video/openinglogos.roq", true); //jk2 - - if (ol_depth != 0x7fffffff && (ol_depth <= idroq_depth || ol_depth <= idcin_depth)) - Media_PlayFilm("video/openinglogos.roq"); - else if (idroq_depth != 0x7fffffff && idroq_depth <= idcin_depth) - Media_PlayFilm("video/idlogo.roq"); - else if (idcin_depth != 0x7fffffff) - Media_PlayFilm("video/idlog.cin"); - } -#endif - Con_TPrintf (TL_NL); Con_Printf ("%s", version_string()); Con_TPrintf (TL_NL); - Con_TPrintf (TLC_QUAKEWORLD_INITED, fs_gamename.string); - Con_DPrintf("This program is free software; you can redistribute it and/or " "modify it under the terms of the GNU General Public License " "as published by the Free Software Foundation; either version 2 " @@ -3997,20 +4037,9 @@ Con_TPrintf (TL_NL); "\n" "See the GNU General Public License for more details.\n"); - realtime+=1; - Cbuf_Execute (); //server may have been waiting for the renderer + Renderer_Start(); - if (!cls.demoinfile && !*cls.servername && !Media_Playing()) - { -#ifndef CLIENTONLY - if (!sv.state) -#endif - { - if (qrenderer > QR_NONE) - M_ToggleMenu_f(); - //Con_ForceActiveNow(); - } - } + CL_StartCinematicOrMenu(); } /* @@ -4045,6 +4074,9 @@ void Host_Shutdown(void) S_Shutdown(); IN_Shutdown (); R_ShutdownRenderer(); +#ifdef CL_MASTER + MasterInfo_Shutdown(); +#endif CL_FreeDlights(); M_Shutdown(); #ifndef CLIENTONLY diff --git a/engine/client/cl_master.h b/engine/client/cl_master.h index dcc9d080..1c945c71 100644 --- a/engine/client/cl_master.h +++ b/engine/client/cl_master.h @@ -128,7 +128,8 @@ typedef struct serverinfo_s { typedef struct master_s{ struct master_s *next; netadr_t adr; - char *address; //text based address (http servers + char *address; //text based address (http servers) + struct dl_download *dl; int type; int servertype; //filled in for http servers int sends; /*needs to resend?*/ @@ -163,6 +164,7 @@ extern player_t *mplayers; void Master_SetupSockets(void); void CL_QueryServers(void); int Master_CheckPollSockets(void); +void MasterInfo_Shutdown(void); void MasterInfo_Request(master_t *mast, qboolean evenifwedonthavethefiles); serverinfo_t *Master_InfoForServer (netadr_t addr); serverinfo_t *Master_InfoForNum (int num); diff --git a/engine/client/cl_parse.c b/engine/client/cl_parse.c index 7e0fbc5a..72e49522 100644 --- a/engine/client/cl_parse.c +++ b/engine/client/cl_parse.c @@ -233,7 +233,7 @@ char *svc_nqstrings[] = "dpsvc_spawnbaseline2", //55 "dpsvc_spawnstatic2", //56 obsolete "dpsvc_entities", //57 - "NEW PROTOCOL", //58 + "dpsvc_csqcentities", //58 "dpsvc_spawnstaticsound2", //59 "dpsvc_trailparticles", //60 "dpsvc_pointparticles", //61 @@ -360,8 +360,11 @@ qboolean CL_EnqueDownload(char *filename, char *localname, unsigned int flags) char *ext; downloadlist_t *dl; qboolean webdl = false; - if (localname && !strncmp(filename, "http://", 7)) + if (!strncmp(filename, "http://", 7)) { + if (!localname) + return false; + webdl = true; } else @@ -619,6 +622,7 @@ void CL_DownloadFinished(void) CL_CheckModelResources(filename); if (!cl.sendprespawn) { +/* for (i = 0; i < mod_numknown; i++) //go and load this model now. { if (!strcmp(mod_known[i].name, filename)) @@ -627,6 +631,7 @@ void CL_DownloadFinished(void) break; } } +*/ for (i = 0; i < MAX_MODELS; i++) //go and load this model now. { if (!strcmp(cl.model_name[i], filename)) @@ -637,6 +642,14 @@ void CL_DownloadFinished(void) break; } } + for (i = 0; i < MAX_CSQCMODELS; i++) //go and load this model now. + { + if (!strcmp(cl.model_csqcname[i], filename)) + { + cl.model_csqcprecache[i] = Mod_ForName(cl.model_csqcname[i], false); //throw away result. + break; + } + } for (i = 0; i < MAX_VWEP_MODELS; i++) { if (!strcmp(cl.model_name_vwep[i], filename)) @@ -1589,12 +1602,10 @@ downloadlist_t *CL_DownloadFailed(char *name) return failed; } -float downloadstarttime; #ifdef PEXT_CHUNKEDDOWNLOADS #define MAXBLOCKS 512 //must be power of 2 #define DLBLOCKSIZE 1024 int downloadsize; -int receivedbytes; struct { int chunkno; @@ -1605,7 +1616,7 @@ int download_file_number; int CL_DownloadRate(void) { - return receivedbytes/(Sys_DoubleTime() - downloadstarttime); + return cls.downloadedbytes/(Sys_DoubleTime() - cls.downloadstarttime); } void CL_ParseChunkedDownload(void) @@ -1664,7 +1675,7 @@ void CL_ParseChunkedDownload(void) cls.downloadpercent = 0; downloadsize = totalsize; - downloadstarttime = Sys_DoubleTime(); + cls.downloadstarttime = Sys_DoubleTime(); /* strcpy(cls.downloadname, svname); @@ -1696,7 +1707,7 @@ void CL_ParseChunkedDownload(void) download_file_number++; firstblock = 0; - receivedbytes = 0; + cls.downloadedbytes = 0; blockcycle = -1; //so it requests 0 first. :) for (chunknum = 0; chunknum < MAXBLOCKS; chunknum++) dlblock[chunknum].chunkno = ~0u; @@ -1728,7 +1739,7 @@ void CL_ParseChunkedDownload(void) dlblock[ridx].chunkno = ~0; // Con_Printf("usable\n", chunknum); - receivedbytes+=DLBLOCKSIZE; + cls.downloadedbytes+=DLBLOCKSIZE; VFS_SEEK(cls.downloadqw, chunknum*DLBLOCKSIZE); if (downloadsize - chunknum*DLBLOCKSIZE < DLBLOCKSIZE) //final block is actually meant to be smaller than we recieve. @@ -1736,7 +1747,7 @@ void CL_ParseChunkedDownload(void) else VFS_WRITE(cls.downloadqw, data, DLBLOCKSIZE); - cls.downloadpercent = receivedbytes/(float)downloadsize*100; + cls.downloadpercent = cls.downloadedbytes/(float)downloadsize*100; } int CL_CountQueuedDownloads(void) @@ -1781,7 +1792,7 @@ int CL_RequestADownloadChunk(void) CL_SendClientCommand(true, "stopdownload"); CL_DownloadFinished(); - Con_DPrintf("Download took %i seconds (%i more)\n", (int)(Sys_DoubleTime() - downloadstarttime), CL_CountQueuedDownloads()); + Con_DPrintf("Download took %i seconds (%i more)\n", (int)(Sys_DoubleTime() - cls.downloadstarttime), CL_CountQueuedDownloads()); *cls.downloadlocalname = '\0'; *cls.downloadremotename = '\0'; @@ -1896,8 +1907,8 @@ void CL_ParseDownload (void) return; } - downloadstarttime = Sys_DoubleTime(); - receivedbytes = 0; + cls.downloadstarttime = Sys_DoubleTime(); + cls.downloadedbytes = 0; SCR_EndLoadingPlaque(); } #ifdef PEXT_ZLIBDL @@ -1918,9 +1929,9 @@ void CL_ParseDownload (void) msg_readcount += size; } - receivedbytes += size; + cls.downloadedbytes += size; if (cls.downloadpercent != percent) //try and guess the size (its most acurate when the percent value changes) - downloadsize = ((float)receivedbytes*100)/percent; + downloadsize = ((float)cls.downloadedbytes*100)/percent; if (cls.downloadmethod == DL_QWPENDING) cls.downloadmethod = DL_QW; @@ -1949,7 +1960,7 @@ void CL_ParseDownload (void) cls.downloadqw = NULL; cls.downloadpercent = 0; - Con_DPrintf("Download took %i seconds\n", (int)(Sys_DoubleTime() - downloadstarttime)); + Con_DPrintf("Download took %i seconds\n", (int)(Sys_DoubleTime() - cls.downloadstarttime)); // get another file if needed @@ -2002,6 +2013,12 @@ void CLDP_ParseDownloadBegin(char *s) size = (unsigned int)atoi(Cmd_Argv(1)); fname = Cmd_Argv(2); + if (strcmp(fname, cls.downloadlocalname)) + { + Con_Printf("Warning: server started sending a file we did not request. Ignoring.\n"); + return; + } + COM_StripExtension (fname, cls.downloadtempname, sizeof(cls.downloadtempname)-5); strcat (cls.downloadtempname, ".tmp"); @@ -2017,6 +2034,10 @@ void CLDP_ParseDownloadBegin(char *s) cls.downloadqw = FS_OpenVFS (cls.downloadtempname, "wb", FS_GAME); cls.downloadmethod = DL_DARKPLACES; + Q_strncpyz(cls.downloadlocalname, fname, sizeof(cls.downloadlocalname)); + cls.downloadstarttime = Sys_DoubleTime(); + cls.downloadedbytes = 0; + if (cls.downloadqw) { //fill the file with 0 bytes @@ -2032,7 +2053,7 @@ void CLDP_ParseDownloadBegin(char *s) else CL_DownloadFailed(cls.downloadremotename); - downloadstarttime = Sys_DoubleTime(); + cls.downloadstarttime = Sys_DoubleTime(); } void CLDP_ParseDownloadFinished(char *s) @@ -2089,7 +2110,7 @@ void CLDP_ParseDownloadFinished(char *s) cls.downloadqw = NULL; cls.downloadpercent = 0; - Con_DPrintf("Download took %i seconds\n", (int)(Sys_DoubleTime() - downloadstarttime)); + Con_DPrintf("Download took %i seconds\n", (int)(Sys_DoubleTime() - cls.downloadstarttime)); // get another file if needed @@ -2758,8 +2779,15 @@ void CLNQ_ParseServerData(void) //Doesn't change gamedir - use with caution. Q_strncpyz (cl.levelname, str, sizeof(cl.levelname)); // seperate the printfs so the server message can have a color +#if 1 + Con_Printf ("\n\n"); + Con_Printf ("^Ue01d^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01f"); + Con_Printf ("\n\n"); + Con_Printf ("\1%s\n", str); +#else Con_TPrintf (TLC_LINEBREAK_NEWLEVEL); Con_TPrintf (TLC_PC_PS_NL, 2, str); +#endif SCR_BeginLoadingPlaque(); @@ -3545,6 +3573,7 @@ void CL_ParseStatic (int version) ent = &cl_static_entities[i].ent; memset(ent, 0, sizeof(*ent)); + memset(&cl_static_entities[i].pvscache, 0, sizeof(cl_static_entities[i].pvscache)); ent->keynum = es.number; @@ -3591,8 +3620,13 @@ void CL_ParseStatic (int version) /*FIXME: compensate for angle*/ VectorAdd(es.origin, ent->model->mins, mins); VectorAdd(es.origin, ent->model->maxs, maxs); - cl.worldmodel->funcs.FindTouchedLeafs(cl.worldmodel, &cl_static_entities[i].pvscache, mins, maxs); } + else + { + VectorCopy(es.origin, mins); + VectorCopy(es.origin, maxs); + } + cl.worldmodel->funcs.FindTouchedLeafs(cl.worldmodel, &cl_static_entities[i].pvscache, mins, maxs); } /* @@ -3600,7 +3634,7 @@ void CL_ParseStatic (int version) CL_ParseStaticSound =================== */ -void CL_ParseStaticSound (void) +void CL_ParseStaticSound (qboolean large) { extern cvar_t cl_staticsounds; vec3_t org; @@ -3609,7 +3643,10 @@ void CL_ParseStaticSound (void) for (i=0 ; i<3 ; i++) org[i] = MSG_ReadCoord (); - sound_num = MSG_ReadByte (); + if (large) + sound_num = (unsigned short)MSG_ReadShort(); + else + sound_num = MSG_ReadByte (); vol = MSG_ReadByte (); atten = MSG_ReadByte (); @@ -5474,7 +5511,7 @@ void CLQW_ParseServerMessage (void) break; case svc_spawnstaticsound: - CL_ParseStaticSound (); + CL_ParseStaticSound (false); break; case svc_cdtrack: @@ -6157,7 +6194,7 @@ void CLNQ_ParseServerMessage (void) break; case svc_spawnstaticsound: - CL_ParseStaticSound (); + CL_ParseStaticSound (false); break; case svc_spawnstatic: @@ -6386,6 +6423,10 @@ void CLNQ_ParseServerMessage (void) CLDP_ParseDarkPlaces5Entities(); break; + case svcdp_spawnstaticsound2: + CL_ParseStaticSound(true); + break; + #ifdef PEXT_CSQC case svcdp_csqcentities: CSQC_ParseEntities(); diff --git a/engine/client/cl_screen.c b/engine/client/cl_screen.c index 881d0873..2fb324f7 100644 --- a/engine/client/cl_screen.c +++ b/engine/client/cl_screen.c @@ -1872,91 +1872,87 @@ int MipColor(int r, int g, int b) return best; } -qboolean SCR_ScreenShot (char *filename) +qboolean SCR_ScreenShot (char *filename, void *rgb_buffer, int width, int height) { - int truewidth, trueheight; - qbyte *buffer; int i, c, temp; #if defined(AVAIL_PNGLIB) || defined(AVAIL_JPEGLIB) extern cvar_t scr_sshot_compression; #endif -#define MAX_PREPAD 128 char *ext; ext = COM_FileExtension(filename); - buffer = VID_GetRGBInfo(MAX_PREPAD, &truewidth, &trueheight); -#ifdef warningmsg -#pragma warningmsg("Need to ensure that the various image writing routines can cope with ((width|height)&3") -#endif - - if (!buffer) + if (!rgb_buffer) return false; #ifdef AVAIL_PNGLIB if (!strcmp(ext, "png")) { - Image_WritePNG(filename, scr_sshot_compression.value, buffer+MAX_PREPAD, truewidth, trueheight); + Image_WritePNG(filename, scr_sshot_compression.value, rgb_buffer, width, height); } else #endif #ifdef AVAIL_JPEGLIB if (!strcmp(ext, "jpeg") || !strcmp(ext, "jpg")) { - screenshotJPEG(filename, scr_sshot_compression.value, buffer+MAX_PREPAD, truewidth, trueheight); + screenshotJPEG(filename, scr_sshot_compression.value, rgb_buffer, width, height); } else #endif /* if (!strcmp(ext, "bmp")) { - WriteBMPFile(pcxname, buffer+MAX_PREPAD, truewidth, trueheight); + WriteBMPFile(pcxname, rgb_buffer, width, height); } else*/ if (!strcmp(ext, "pcx")) { int y, x; qbyte *src, *dest; - qbyte *newbuf = buffer + MAX_PREPAD; - // convert to eight bit - for (y = 0; y < trueheight; y++) { - src = newbuf + (truewidth * 3 * y); - dest = newbuf + (truewidth * y); + qbyte *newbuf = rgb_buffer; + // convert in-place to eight bit + for (y = 0; y < height; y++) + { + src = newbuf + (width * 3 * y); + dest = newbuf + (width * y); - for (x = 0; x < truewidth; x++) { + for (x = 0; x < width; x++) { *dest++ = MipColor(src[0], src[1], src[2]); src += 3; } } - WritePCXfile (filename, newbuf, truewidth, trueheight, truewidth, host_basepal, false); + WritePCXfile (filename, newbuf, width, height, width, host_basepal, false); } else //tga { - buffer+=MAX_PREPAD-18; - memset (buffer, 0, 18); - buffer[2] = 2; // uncompressed type - buffer[12] = truewidth&255; - buffer[13] = truewidth>>8; - buffer[14] = trueheight&255; - buffer[15] = trueheight>>8; - buffer[16] = 24; // pixel size - - // swap rgb to bgr - c = 18+truewidth*trueheight*3; - for (i=18 ; i>8; + header[14] = height&255; + header[15] = height>>8; + header[16] = 24; // pixel size + VFS_WRITE(vfs, header, sizeof(header)); + + // swap rgb to bgr + c = width*height*3; + for (i=0 ; iorigin); dl->radius = 150 + r_explosionlight.value*200; - dl->die = cl.time + 1; - dl->decay = 300; + dl->die = cl.time + 0.75; + dl->decay = dl->radius*2; dl->color[0] = 4.0; dl->color[1] = 2.0; @@ -2890,7 +2890,7 @@ void CL_UpdateBeams (void) int i, j; beam_t *b; vec3_t dist, org; - float *vieworg; + float *vieworg, *viewang; float d; entity_t *ent; entity_state_t *st; @@ -2937,11 +2937,20 @@ void CL_UpdateBeams (void) float delta, f, len; if (cl.spectator && autocam[j]) - { + { //if we're tracking someone, use their origin explicitly. vieworg = pl->origin; } else vieworg = cl.playerview[j].simorg; + viewang = cl.playerview[j].simangles; + + if (cl_truelightning.ival >= 2 && cls.netchan.outgoing_sequence > cl_truelightning.ival) + { + frame_t *frame = &cl.frames[(cls.netchan.outgoing_sequence-cl_truelightning.ival)&UPDATE_MASK]; + viewang = frame->playerstate[cl.playernum[j]].viewangles; + viewang[0] = (frame->playerstate[cl.playernum[j]].command.angles[0] * 360) / 65336.0; + viewang[1] = (frame->playerstate[cl.playernum[j]].command.angles[1] * 360) / 65336.0; + } VectorCopy (vieworg, b->start); b->start[2] += cl.crouch[j] + bound(-7, v_viewheight.value, 4); @@ -2960,10 +2969,10 @@ void CL_UpdateBeams (void) ang[0] = -ang[0]; if (ang[0] < -180) ang[0] += 360; - ang[0] += (cl.playerview[j].simangles[0] - ang[0]) * f; + ang[0] += (viewang[0] - ang[0]) * f; // lerp yaw - delta = cl.playerview[j].simangles[1] - ang[1]; + delta = viewang[1] - ang[1]; if (delta > 180) delta -= 360; if (delta < -180) @@ -2974,7 +2983,7 @@ void CL_UpdateBeams (void) AngleVectors (ang, fwd, ang, ang); VectorCopy(fwd, ang); VectorScale (fwd, len, fwd); - VectorCopy (cl.playerview[j].simorg, org); + VectorCopy (vieworg, org); org[2] += 16; VectorAdd (org, fwd, b->end); diff --git a/engine/client/clhl_game.c b/engine/client/clhl_game.c index a3b2cf0a..0339402b 100644 --- a/engine/client/clhl_game.c +++ b/engine/client/clhl_game.c @@ -1166,7 +1166,7 @@ void CLHL_LoadClientGame(void) memset(&CLHL_cgamefuncs, 0, sizeof(CLHL_cgamefuncs)); - clg = Sys_LoadLibrary("C:/Incoming/d/Half-Life/sdks/hlsdk-2.3-p3/hlsdk-2.3-p3/multiplayer/cl_dll/Debug/client", funcs); + clg = NULL;//Sys_LoadLibrary("C:/Incoming/d/Half-Life/sdks/hlsdk-2.3-p3/hlsdk-2.3-p3/multiplayer/cl_dll/Debug/client", funcs); if (!clg) { path = NULL; diff --git a/engine/client/client.h b/engine/client/client.h index c6e7e395..54b11e47 100644 --- a/engine/client/client.h +++ b/engine/client/client.h @@ -378,11 +378,13 @@ typedef struct enum {DL_NONE, DL_QW, DL_QWCHUNKS, DL_Q3, DL_DARKPLACES, DL_QWPENDING, DL_HTTP, DL_FTP} downloadmethod; vfsfile_t *downloadqw; // file transfer from server - char downloadtempname[MAX_OSPATH]; - char downloadlocalname[MAX_OSPATH]; - char downloadremotename[MAX_OSPATH]; - int downloadpercent; - int downloadchunknum; + char downloadtempname[MAX_OSPATH]; //file its currently writing to. + char downloadlocalname[MAX_OSPATH]; //file its going to be renamed to. + char downloadremotename[MAX_OSPATH]; //file its coming from. + float downloadpercent; //for progress indicator. + int downloadchunknum; //for QW downloads only. + float downloadstarttime; //for speed info + unsigned int downloadedbytes; //number of bytes downloaded, for progress/speed info // demo loop control int demonum; // -1 = don't play demos @@ -822,6 +824,9 @@ void CL_SetInfo (int pnum, char *key, char *value); void CL_BeginServerConnect(int port); char *CL_TryingToConnect(void); +void CL_ExecInitialConfigs(void); +qboolean CL_CheckBootDownloads(void); + #define MAX_VISEDICTS 2048 extern int cl_numvisedicts; extern entity_t cl_visedicts[]; @@ -1347,6 +1352,14 @@ typedef struct void (VARGS *getsize) (void *ctx, int *width, int *height); void (VARGS *changestream) (void *ctx, char *streamname); } media_decoder_funcs_t; +typedef struct { + void *(VARGS *capture_begin) (char *streamname, int videorate, int width, int height, int *sndkhz, int *sndchannels, int *sndbits); + void (VARGS *capture_video) (void *ctx, void *data, int frame, int width, int height); + void (VARGS *capture_audio) (void *ctx, void *data, int bytes); + void (VARGS *capture_end) (void *ctx); +} media_encoder_funcs_t; extern struct plugin_s *currentplug; qboolean Media_RegisterDecoder(struct plugin_s *plug, media_decoder_funcs_t *funcs); qboolean Media_UnregisterDecoder(struct plugin_s *plug, media_decoder_funcs_t *funcs); +qboolean Media_RegisterEncoder(struct plugin_s *plug, media_encoder_funcs_t *funcs); +qboolean Media_UnregisterEncoder(struct plugin_s *plug, media_encoder_funcs_t *funcs); diff --git a/engine/client/console.c b/engine/client/console.c index 0a1e67d5..ecb219b4 100644 --- a/engine/client/console.c +++ b/engine/client/console.c @@ -24,10 +24,12 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. console_t con_main; console_t *con_current; // points to whatever is the visible console console_t *con_chat; // points to a chat console +conline_t *con_footerline; //temp text at the bottom of the console #define Font_ScreenWidth() (vid.pixelwidth) static int Con_DrawProgress(int left, int right, int y); +static int Con_DrawConsoleLines(conline_t *l, int sx, int ex, int y, int top, qboolean selactive, int selsx, int selex, int selsy, int seley); #ifdef QTERM #include @@ -66,11 +68,6 @@ cvar_t con_separatechat = CVAR("con_separatechat", "0"); #define NUM_CON_TIMES 24 -#define MAXCMDLINE 256 -extern unsigned char key_lines[32][MAXCMDLINE]; -extern int edit_line; -extern int key_linepos; - static conline_t *selstartline, *selendline; static unsigned int selstartoffset, selendoffset; @@ -163,6 +160,14 @@ console_t *Con_Create(char *name, unsigned int flags) void Con_SetActive (console_t *con) { con_current = con; + + if (con_footerline) + { + selstartline = NULL; + selendline = NULL; + Z_Free(con_footerline); + con_footerline = NULL; + } } /*for enumerating consoles*/ qboolean Con_NameForNum(int num, char *buffer, int buffersize) @@ -357,6 +362,55 @@ void Key_ClearTyping (void) key_linepos = 1; } +void Con_History_Load(void) +{ + unsigned char *cr; + vfsfile_t *file = FS_OpenVFS("conhistory.txt", "rb", FS_ROOT); + + for (edit_line=0 ; edit_line<=CON_EDIT_LINES_MASK ; edit_line++) + { + key_lines[edit_line][0] = ']'; + key_lines[edit_line][1] = 0; + } + edit_line = 0; + key_linepos = 1; + + if (file) + { + while (VFS_GETS(file, key_lines[edit_line]+1, sizeof(key_lines[edit_line])-1)) + { + //strip a trailing \r if its from windows. + cr = key_lines[edit_line] + strlen(key_lines[edit_line]); + if (cr > key_lines[edit_line] && cr[-1] == '\r') + cr[-1] = '\0'; + edit_line = (edit_line + 1) & CON_EDIT_LINES_MASK; + } + VFS_CLOSE(file); + } + history_line = edit_line; +} +void Con_History_Save(void) +{ + vfsfile_t *file = FS_OpenVFS("conhistory.txt", "wb", FS_ROOT); + int line; + if (file) + { + line = edit_line - CON_EDIT_LINES_MASK; + if (line < 0) + line = 0; + for(; line < edit_line; line++) + { + VFS_PUTS(file, key_lines[line]+1); +#ifdef _WIN32 //use an \r\n for readability with notepad. + VFS_PUTS(file, "\r\n"); +#else + VFS_PUTS(file, "\n"); +#endif + } + VFS_CLOSE(file); + } +} + /* ================ Con_ToggleConsole_f @@ -539,12 +593,20 @@ void Con_Init (void) void Con_Shutdown(void) { + Con_History_Save(); + while(con_main.next) { Con_Destroy(con_main.next); } con_initialized = false; Con_Destroy(&con_main); + + selstartline = NULL; + selendline = NULL; + if (con_footerline) + Z_Free(con_footerline); + con_footerline = NULL; } void TTS_SayConString(conchar_t *stringtosay); @@ -793,6 +855,47 @@ void VARGS Con_DPrintf (char *fmt, ...) Con_PrintCon(&con_main, msg); } +/*description text at the bottom of the console*/ +void Con_Footerf(qboolean append, char *fmt, ...) +{ + va_list argptr; + char msg[MAXPRINTMSG]; + conchar_t marked[MAXPRINTMSG], *markedend; + int oldlen, newlen; + conline_t *newf; + + va_start (argptr,fmt); + vsnprintf (msg,sizeof(msg)-1, fmt,argptr); + va_end (argptr); + markedend = COM_ParseFunString(COLOR_YELLOW << CON_FGSHIFT, msg, marked, sizeof(marked), false); + + newlen = markedend - marked; + if (append) + oldlen = con_footerline->length; + else + oldlen = 0; + + if (!newlen && !oldlen) + newf = NULL; + else + { + newf = Z_Malloc(sizeof(*newf) + (oldlen + newlen) * sizeof(conchar_t)); + if (con_footerline) + memcpy(newf, con_footerline, sizeof(*con_footerline)+oldlen*sizeof(conchar_t)); + markedend = (void*)(newf+1); + markedend += oldlen; + memcpy(markedend, marked, newlen*sizeof(conchar_t)); + newf->length = oldlen + newlen; + } + + if (selstartline == con_footerline) + selstartline = NULL; + if (selendline == con_footerline) + selendline = NULL; + Z_Free(con_footerline); + con_footerline = newf; +} + /* ============================================================================== @@ -811,7 +914,7 @@ y is the bottom of the input return value is the top of the region ================ */ -int Con_DrawInput (int left, int right, int y) +int Con_DrawInput (int left, int right, int y, qboolean selactive, int selsx, int selex, int selsy, int seley) { #ifdef _WIN32 extern qboolean ActiveApp; @@ -869,7 +972,7 @@ int Con_DrawInput (int left, int right, int y) { int cmdstart; cmdstart = text[1] == '/'?2:1; - fname = Cmd_CompleteCommand(text+cmdstart, true, true, con_commandmatch); + fname = Cmd_CompleteCommand(text+cmdstart, true, true, con_commandmatch, NULL); if (fname) //we can compleate it to: { for (p = min(strlen(fname), key_linepos-cmdstart); fname[p]>' '; p++) @@ -931,43 +1034,9 @@ int Con_DrawInput (int left, int right, int y) } /*if its getting completed to something, show some help about the command that is going to be used*/ - if (!text[1]) - con_commandmatch = 0; - if (con_commandmatch && fname && Cmd_IsCommand(text+(text[1] == '/'?2:1))) + if (con_footerline) { - cvar_t *var; - char *desc = NULL; - if (!desc) - { - var = Cvar_FindVar(fname); - if (var && var->description) - desc = var->description; - } - if (!desc) - { - desc = Cmd_Describe(fname); - } - - if (desc) - { - int lines; - conchar_t *starts[8]; - conchar_t *ends[8]; - conchar_t *end; - end = maskedtext; - - end = COM_ParseFunString((COLOR_YELLOW<0) - { - rhs = left; - y -= Font_CharHeight(); - for (cchar = starts[lines]; cchar < ends[lines]; cchar++) - { - rhs = Font_DrawChar(rhs, y, *cchar); - } - } - } + y = Con_DrawConsoleLines(con_footerline, left, right, y, 0, selactive, selsx, selex, selsy, seley); } /*just above that, we have the tab completion list*/ @@ -984,7 +1053,7 @@ int Con_DrawInput (int left, int right, int y) for (i = 1; ; i++) { - cmd = Cmd_CompleteCommand (text+cmdstart, true, true, i); + cmd = Cmd_CompleteCommand (text+cmdstart, true, true, i, NULL); if (!cmd) break; @@ -1188,20 +1257,13 @@ static int Con_DrawProgress(int left, int right, int y) progresstext = cls.downloadlocalname; progresspercent = cls.downloadpercent; - if ((int)(realtime/2)&1) - sprintf(progresspercenttext, " %02d%% (%ukbps)", (int)progresspercent, CL_DownloadRate()/1000); + CL_GetDownloadSizes(&count, &total, &extra); + + if ((int)(realtime/2)&1 || total == 0) + sprintf(progresspercenttext, " %5.1f%% (%ukbps)", progresspercent, CL_DownloadRate()/1000); else { - CL_GetDownloadSizes(&count, &total, &extra); - if (total == 0) - { - //just show progress - sprintf(progresspercenttext, " %02f%%", progresspercent); - } - else - { - sprintf(progresspercenttext, " %02d%% (%u%skb)", (int)progresspercent, total/1024, extra?"+":""); - } + sprintf(progresspercenttext, " %5.1f%% (%u%skb)", progresspercent, total/1024, extra?"+":""); } } #ifdef RUNTIMELIGHTING @@ -1342,72 +1404,40 @@ int Con_DrawAlternateConsoles(int lines) return y; } -/* -================ -Con_DrawConsole - -Draws the console with the solid background -================ -*/ -void Con_DrawConsole (int lines, qboolean noback) +//draws the conline_t list bottom-up within the width of the screen until the top of the screen is reached. +//if text is selected, the selstartline globals will be updated, so make sure the lines persist or check them. +static int Con_DrawConsoleLines(conline_t *l, int sx, int ex, int y, int top, qboolean selactive, int selsx, int selex, int selsy, int seley) { - extern qboolean scr_con_forcedraw; - int x, y, sx, ex, linecount, linelength; - conline_t *l; - conchar_t *s; - int selsx, selsy, selex, seley, selactive; - int top; + int linecount; + int linelength; conchar_t *starts[64], *ends[sizeof(starts)/sizeof(starts[0])]; + conchar_t *s; int i; - qboolean haveprogress; - int hidelines; + int x; - if (lines <= 0) - return; - -#ifdef QTERM - if (qterms) - QT_Update(); -#endif - -// draw the background - if (!noback) - R2D_ConsoleBackground (0, lines, scr_con_forcedraw); - - con_current->unseentext = false; - - con_current->vislines = lines; - - top = Con_DrawAlternateConsoles(lines); - - x = 8; - y = lines; - - selactive = Key_GetConsoleSelectionBox(&selsx, &selsy, &selex, &seley); - - Font_BeginString(font_conchar, x, y, &x, &y); - Font_BeginString(font_conchar, selsx, selsy, &selsx, &selsy); - Font_BeginString(font_conchar, selex, seley, &selex, &seley); - ex = Font_ScreenWidth(); - sx = x; - ex -= sx; - - y -= Font_CharHeight(); - haveprogress = Con_DrawProgress(x, ex - x, y) != y; - y = Con_DrawInput (x, ex - x, y); + //deactivate the selection if the start and end is outside + if ( + (selsx < sx && selex < sx) || + (selsx > ex && selex > ex) || + (selsy < top && seley < top) || + (selsy > y && seley > y) + ) + selactive = false; if (selactive) { - if (selsx < x) - selsx = x; - if (selex < x) - selex = x; + //clip it + if (selsx < sx) + selsx = sx; + if (selex < sx) + selex = sx; if (selsy > y) selsy = y; if (seley > y) seley = y; + //scale the y coord to be in lines instead of pixels selsy -= y; seley -= y; selsy /= Font_CharHeight(); @@ -1415,6 +1445,7 @@ void Con_DrawConsole (int lines, qboolean noback) selsy--; seley--; + //invert the selections to make sense, text-wise if (selsy == seley) { //single line selected backwards @@ -1441,19 +1472,6 @@ void Con_DrawConsole (int lines, qboolean noback) seley += y; } - if (!con_current->display) - con_current->display = con_current->current; - l = con_current->display; - hidelines = con_current->subline; - - if (l != con_current->current) - { - y -= 8; - // draw arrows to show the buffer is backscrolled - for (x = sx ; xcurrent && l->length == 0) l = l->older; for (; l; l = l->older) @@ -1470,14 +1488,6 @@ void Con_DrawConsole (int lines, qboolean noback) } l->lines = linecount; - if (hidelines > 0) - { - linecount -= hidelines; - if (linecount < 0) - linecount = 0; - hidelines -= linecount; - } - while (linecount-- > 0) { s = starts[linecount]; @@ -1554,6 +1564,74 @@ void Con_DrawConsole (int lines, qboolean noback) if (y < top) break; } + return y; +} + +/* +================ +Con_DrawConsole + +Draws the console with the solid background +================ +*/ +void Con_DrawConsole (int lines, qboolean noback) +{ + extern qboolean scr_con_forcedraw; + int x, y, sx, ex; + conline_t *l; + int selsx, selsy, selex, seley, selactive; + int top; + qboolean haveprogress; + + if (lines <= 0) + return; + +#ifdef QTERM + if (qterms) + QT_Update(); +#endif + +// draw the background + if (!noback) + R2D_ConsoleBackground (0, lines, scr_con_forcedraw); + + con_current->unseentext = false; + + con_current->vislines = lines; + + top = Con_DrawAlternateConsoles(lines); + + x = 8; + y = lines; + + selstartline = NULL; + selendline = NULL; + selactive = Key_GetConsoleSelectionBox(&selsx, &selsy, &selex, &seley); + + Font_BeginString(font_conchar, x, y, &x, &y); + Font_BeginString(font_conchar, selsx, selsy, &selsx, &selsy); + Font_BeginString(font_conchar, selex, seley, &selex, &seley); + ex = Font_ScreenWidth(); + sx = x; + ex -= sx; + + y -= Font_CharHeight(); + haveprogress = Con_DrawProgress(x, ex - x, y) != y; + y = Con_DrawInput (x, ex - x, y, selactive, selsx, selex, selsy, seley); + + if (!con_current->display) + con_current->display = con_current->current; + l = con_current->display; + + if (l != con_current->current) + { + y -= 8; + // draw arrows to show the buffer is backscrolled + for (x = sx ; x @@ -66,9 +73,10 @@ char *ReadGreyTargaFile (qbyte *data, int flen, tgaheader_t *tgahead, int asgrey numPixels = columns * rows; flipped = !((tgahead->attribs & 0x20) >> 5); +#ifndef NPFTE if (r_dodgytgafiles.value) flipped = true; - +#endif if (tgahead->version == 1) { @@ -173,8 +181,10 @@ qbyte *ReadTargaFile(qbyte *buf, int length, int *width, int *height, qboolean * tgaheader.attribs = buf[17]; flipped = !((tgaheader.attribs & 0x20) >> 5); +#ifndef NPFTE if (r_dodgytgafiles.value) flipped = true; +#endif data=buf+18; data += tgaheader.id_len; @@ -872,7 +882,7 @@ error: - +#ifndef NPFTE int Image_WritePNG (char *filename, int compression, qbyte *pixels, int width, int height) { char name[MAX_OSPATH]; @@ -940,6 +950,7 @@ err: fclose(fp); return true; } +#endif #endif @@ -1340,6 +1351,7 @@ badjpeg: } /*end read*/ +#ifndef NPFTE /*begin write*/ #define OUTPUT_BUF_SIZE 4096 typedef struct { @@ -1503,8 +1515,9 @@ void screenshotJPEG(char *filename, int compression, qbyte *screendata, int scre #endif } #endif +#endif - +#ifndef NPFTE /* ============== WritePCXfile @@ -1575,7 +1588,7 @@ void WritePCXfile (const char *filename, qbyte *data, int width, int height, else COM_WriteFile (filename, pcx, length); } - +#endif /* @@ -1622,9 +1635,11 @@ qbyte *ReadPCXFile(qbyte *buf, int length, int *width, int *height) *width = swidth; *height = sheight; +#ifndef NPFTE if (r_dodgypcxfiles.value) palette = host_basepal; else +#endif palette = buf + length-768; data = (char *)(pcx+1); @@ -2054,6 +2069,10 @@ qbyte *ReadBMPFile(qbyte *buf, int length, int *width, int *height) return NULL; }*/ + +#ifndef NPFTE + + // saturate function, stolen from jitspoe void SaturateR8G8B8(qbyte *data, int size, float sat) { @@ -2214,14 +2233,14 @@ texid_tf GL_LoadTextureDDS(char *iname, unsigned char *buffer, int filesize) divsize = 4; blocksize = 8; } - else if (*(int*)&fmtheader.ddpfPixelFormat.dwFourCC == *(int*)"DXT3") + else if (*(int*)&fmtheader.ddpfPixelFormat.dwFourCC == *(int*)"DXT2" || *(int*)&fmtheader.ddpfPixelFormat.dwFourCC == *(int*)"DXT3") { intfmt = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; pad = 8; divsize = 4; blocksize = 16; } - else if (*(int*)&fmtheader.ddpfPixelFormat.dwFourCC == *(int*)"DXT5") + else if (*(int*)&fmtheader.ddpfPixelFormat.dwFourCC == *(int*)"DXT4" || *(int*)&fmtheader.ddpfPixelFormat.dwFourCC == *(int*)"DXT5") { intfmt = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; pad = 8; @@ -2458,6 +2477,20 @@ texid_t R_LoadHiResTexture(char *name, char *subpath, unsigned int flags) return tex; } +#ifdef DDS + snprintf(fname, sizeof(fname)-1, "dds/%s.dds", nicename); /*should be safe if its null*/ + if ((buf = COM_LoadFile (fname, 5))) + { + tex = GL_LoadTextureDDS(name, buf, com_filesize); + if (TEXVALID(tex)) + { + BZ_Free(buf); + return tex; + } + BZ_Free(buf); + } +#endif + if (strchr(name, '/')) //never look in a root dir for the pic i = 0; else @@ -2489,7 +2522,7 @@ texid_t R_LoadHiResTexture(char *name, char *subpath, unsigned int flags) if ((buf = COM_LoadFile (fname, 5))) { #ifdef DDS - tex = GL_LoadTextureDDS(fname, buf, com_filesize); + tex = GL_LoadTextureDDS(name, buf, com_filesize); if (TEXVALID(tex)) { BZ_Free(buf); @@ -2746,3 +2779,4 @@ void AddOcranaLEDsIndexed (qbyte *image, int h, int w) } } } +#endif diff --git a/engine/client/in_win.c b/engine/client/in_win.c index 7ad7aa68..1580b364 100644 --- a/engine/client/in_win.c +++ b/engine/client/in_win.c @@ -403,7 +403,6 @@ static void INS_ActivateMouse (void) ClipCursor (&window_rect); } - Con_Printf("Mouse grabbed\n"); mouseactive = true; } } @@ -465,7 +464,6 @@ static void INS_DeactivateMouse (void) ReleaseCapture (); } - Con_Printf("Mouse released\n"); mouseactive = false; } } @@ -1220,7 +1218,7 @@ void INS_MouseMove (float *movements, int pnum) extern int window_x, window_y; #ifdef AVAIL_DINPUT - if (dinput) + if (dinput && mouseactive) { DIDEVICEOBJECTDATA od; DWORD dwElements; diff --git a/engine/client/keys.c b/engine/client/keys.c index 6b809a35..8b3a8252 100644 --- a/engine/client/keys.c +++ b/engine/client/keys.c @@ -30,7 +30,7 @@ void Editor_Key(int key, int unicode); #define KEY_MODIFIERSTATES 8 #define MAXCMDLINE 256 -unsigned char key_lines[32][MAXCMDLINE]; +unsigned char key_lines[CON_EDIT_LINES_MASK+1][MAXCMDLINE]; int key_linepos; int shift_down=false; int key_lastpress; @@ -245,7 +245,7 @@ qboolean Cmd_IsCommand (char *line) command[i] = s[i]; command[i] = 0; - cmd = Cmd_CompleteCommand (command, true, false, -1); + cmd = Cmd_CompleteCommand (command, true, false, -1, NULL); if (!cmd || strcmp (cmd, command) ) return false; // just a chat message return true; @@ -268,18 +268,19 @@ void CompleteCommand (qboolean force) { int i; char *cmd, *s; + char *desc; s = key_lines[edit_line]+1; if (*s == '\\' || *s == '/') s++; - cmd = Cmd_CompleteCommand (s, true, true, 2); + cmd = Cmd_CompleteCommand (s, true, true, 2, NULL); if (!cmd || force) { if (!force) - cmd = Cmd_CompleteCommand (s, false, true, 1); + cmd = Cmd_CompleteCommand (s, false, true, 1, &desc); else - cmd = Cmd_CompleteCommand (s, true, true, con_commandmatch); + cmd = Cmd_CompleteCommand (s, true, true, con_commandmatch, &desc); if (cmd) { key_lines[edit_line][1] = '/'; @@ -292,7 +293,7 @@ void CompleteCommand (qboolean force) // if (strlen(cmd)>strlen(s)) { - cmd = Cmd_CompleteCommand (s, true, true, 0); + cmd = Cmd_CompleteCommand (s, true, true, 0, NULL); if (cmd && !strcmp(s, cmd)) //also a compleate var { key_lines[edit_line][key_linepos] = ' '; @@ -302,10 +303,13 @@ void CompleteCommand (qboolean force) key_lines[edit_line][key_linepos] = 0; if (!con_commandmatch) con_commandmatch = 1; + + if (desc) + Con_Footerf(false, "%s: %s", cmd, desc); return; } } - cmd = Cmd_CompleteCommand (s, false, true, 0); + cmd = Cmd_CompleteCommand (s, false, true, 0, &desc); if (cmd) { i = key_lines[edit_line][1] == '/'?2:1; @@ -323,13 +327,25 @@ void CompleteCommand (qboolean force) if (!con_commandmatch) con_commandmatch = 1; + + if (desc) + Con_Footerf(false, "%s: %s", cmd, desc); + return; //don't alter con_commandmatch if we compleated a tiny bit more } } con_commandmatch++; - if (!Cmd_CompleteCommand(s, true, true, con_commandmatch)) + if (Cmd_CompleteCommand(s, true, true, con_commandmatch, &desc)) + { + if (desc) + Con_Footerf(false, "%s: %s", cmd, desc); + } + else + { + Con_Footerf(false, ""); con_commandmatch = 1; + } } //lines typed at the main console enter here @@ -338,6 +354,8 @@ void Con_ExecuteLine(console_t *con, char *line) qboolean waschat = false; con_commandmatch=1; + Con_Footerf(false, ""); + if (cls.state >= ca_connected && cl_chatmode.value == 2) { waschat = true; @@ -451,6 +469,192 @@ void Key_ConsoleInsert(char *instext) } } +void Key_DefaultLinkClicked(char *text, char *info) +{ + char *c; + /*the engine supports specific default links*/ + /*we don't support everything. a: there's no point. b: unbindall links are evil.*/ + c = Info_ValueForKey(info, "player"); + if (*c) + { + unsigned int player = atoi(c); + int i; + if (player >= MAX_CLIENTS || !*cl.players[player].name) + return; + + c = Info_ValueForKey(info, "action"); + if (*c) + { + if (!strcmp(c, "mute")) + { + if (!cl.players[player].vignored) + { + cl.players[player].vignored = true; + Con_Printf("^[%s\\player\\%i^] muted\n", cl.players[player].name, player); + } + else + { + cl.players[player].vignored = false; + Con_Printf("^[%s\\player\\%i^] unmuted\n", cl.players[player].name, player); + } + } + else if (!strcmp(c, "ignore")) + { + if (!cl.players[player].ignored) + { + cl.players[player].ignored = true; + cl.players[player].vignored = true; + Con_Printf("^[%s\\player\\%i^] ignored\n", cl.players[player].name, player); + } + else + { + cl.players[player].ignored = false; + cl.players[player].vignored = false; + Con_Printf("^[%s\\player\\%i^] unignored\n", cl.players[player].name, player); + } + } + else if (!strcmp(c, "spec")) + { + Cam_TrackPlayer(0, "spectate", cl.players[player].name); + } + else if (!strcmp(c, "kick")) + { +#ifndef CLIENTONLY + if (sv.active) + { + //use the q3 command, because we can. + Cbuf_AddText(va("\nclientkick %i\n", player), RESTRICT_LOCAL); + } + else +#endif + Cbuf_AddText(va("\nrcon kick %s\n", cl.players[player].name), RESTRICT_LOCAL); + } + else if (!strcmp(c, "ban")) + { +#ifndef CLIENTONLY + if (sv.active) + { + //use the q3 command, because we can. + Cbuf_AddText(va("\nbanname %s QuickBan\n", cl.players[player].name), RESTRICT_LOCAL); + } + else +#endif + Cbuf_AddText(va("\nrcon banname %s QuickBan\n", cl.players[player].name), RESTRICT_LOCAL); + } + return; + } + + Con_Footerf(false, "^m#^m ^[%s\\player\\%i^]: %if %ims", cl.players[player].name, player, cl.players[player].frags, cl.players[player].ping); + + for (i = 0; i < cl.splitclients; i++) + { + if (cl.playernum[i] == player) + break; + } + if (i == cl.splitclients) + { + extern cvar_t rcon_password; + if (cl.spectator || cls.demoplayback) + { + //we're spectating, or an mvd + Con_Footerf(true, " ^[Spectate\\player\\%i\\action\\spec^]", player); + } + else + { + //we're playing. + if (cls.protocol == CP_QUAKEWORLD && strcmp(cl.players[cl.playernum[0]].team, cl.players[player].team)) + Con_Footerf(true, " ^[[Join Team %s]\\cmd\\setinfo team %s^]", cl.players[player].team, cl.players[player].team); + } + Con_Footerf(true, " ^[%sgnore\\player\\%i\\action\\ignore^]", cl.players[player].ignored?"Uni":"I", player); + // if (cl_voip_play.ival) + Con_Footerf(true, " ^[%sute\\player\\%i\\action\\mute^]", cl.players[player].vignored?"Unm":"M", player); + + if (!cls.demoplayback && (*rcon_password.string +#ifndef CLIENTONLY + || (sv.state && svs.clients[player].netchan.remote_address.type != NA_LOOPBACK) +#endif + )) + { + Con_Footerf(true, " ^[Kick\\player\\%i\\action\\kick^]", player); + Con_Footerf(true, " ^[Ban\\player\\%i\\action\\ban^]", player); + } + } + else + { + char cmdprefix[6]; + snprintf(cmdprefix, sizeof(cmdprefix), "%i ", i); + + //hey look! its you! + + if (cl.spectator || cls.demoplayback) + { + //need join option here or something + } + else + { + Con_Footerf(true, " ^[Suicide\\cmd\\kill^]"); + #ifndef CLIENTONLY + if (!sv.state) + Con_Footerf(true, " ^[Disconnect\\cmd\\disconnect^]"); + if (cls.allow_cheats || (sv.state && sv.allocated_client_slots == 1)) + #else + Con_Footerf(true, " ^[Disconnect\\cmd\\disconnect^]"); + if (cls.allow_cheats) + #endif + { + Con_Footerf(true, " ^[Noclip\\cmd\\noclip^]"); + Con_Footerf(true, " ^[Fly\\cmd\\fly^]"); + Con_Footerf(true, " ^[God\\cmd\\god^]"); + Con_Footerf(true, " ^[Give\\impulse\\9^]"); + } + } + } + return; + } + c = Info_ValueForKey(info, "desc"); + if (*c) + { + Con_Footerf(false, "%s", c); + return; + } + c = Info_ValueForKey(info, "connect"); + if (*c && !strchr(c, ';') && !strchr(c, '\n')) + { + Cbuf_AddText(va("\nconnect %s\n", c), RESTRICT_LOCAL); + return; + } + c = Info_ValueForKey(info, "qtv"); + if (*c && !strchr(c, ';') && !strchr(c, '\n')) + { + Cbuf_AddText(va("\nqtvplay %s\n", c), RESTRICT_LOCAL); + return; + } + c = Info_ValueForKey(info, "demo"); + if (*c && !strchr(c, ';') && !strchr(c, '\n')) + { + Cbuf_AddText(va("\nplaydemo %s\n", c), RESTRICT_LOCAL); + return; + } + c = Info_ValueForKey(info, "cmd"); + if (*c && !strchr(c, ';') && !strchr(c, '\n')) + { + Cbuf_AddText(va("\ncmd %s\n", c), RESTRICT_LOCAL); + return; + } + c = Info_ValueForKey(info, "impulse"); + if (*c && !strchr(c, ';') && !strchr(c, '\n')) + { + Cbuf_AddText(va("\nimpulse %s\n", c), RESTRICT_LOCAL); + return; + } + if (!*info && *text == '/') + { + Q_strncpyz(key_lines[edit_line]+1, text, sizeof(key_lines[edit_line])-1); + key_linepos = strlen(key_lines[edit_line]); + return; + } +} + void Key_ConsoleRelease(int key, int unicode) { extern int mousecursor_x, mousecursor_y; @@ -461,6 +665,7 @@ void Key_ConsoleRelease(int key, int unicode) if (abs(con_mousedown[0] - mousecursor_x) < 5 && abs(con_mousedown[1] - mousecursor_y) < 5) { buffer = Con_CopyConsole(false); + Con_Footerf(false, ""); if (!buffer) return; if (keydown[K_SHIFT]) @@ -506,156 +711,13 @@ void Key_ConsoleRelease(int key, int unicode) { if (end[0] == '^' && end[1] == ']') { - char *c; //okay, its a valid link that they clicked *end = 0; #ifdef CSQC_DAT if (!CSQC_ConsoleLink(buffer+2, info)) #endif { - /*the engine supports specific default links*/ - /*we don't support everything. a: there's no point. b: unbindall links are evil.*/ - c = Info_ValueForKey(info, "player"); - if (*c) - { - unsigned int player = atoi(c); - int i; - if (player >= MAX_CLIENTS) - break; - - c = Info_ValueForKey(info, "action"); - if (*c) - { - if (!strcmp(c, "mute")) - { - if (!cl.players[player].vignored) - { - cl.players[player].vignored = true; - Con_Printf("^[%s\\player\\%i^] muted\n", cl.players[player].name, player); - } - else - { - cl.players[player].vignored = false; - Con_Printf("^[%s\\player\\%i^] unmuted\n", cl.players[player].name, player); - } - } - else if (!strcmp(c, "ignore")) - { - if (!cl.players[player].ignored) - { - cl.players[player].ignored = true; - cl.players[player].vignored = true; - Con_Printf("^[%s\\player\\%i^] ignored\n", cl.players[player].name, player); - } - else - { - cl.players[player].ignored = false; - cl.players[player].vignored = false; - Con_Printf("^[%s\\player\\%i^] unignored\n", cl.players[player].name, player); - } - } - else if (!strcmp(c, "kick")) - { -#ifndef CLIENTONLY - if (sv.active) - { - //use the q3 command, because we can. - Cbuf_AddText(va("\nclientkick %i\n", player), RESTRICT_LOCAL); - } - else -#endif - Cbuf_AddText(va("\nrcon kick %s\n", cl.players[player].name), RESTRICT_LOCAL); - } - else if (!strcmp(c, "ban")) - { -#ifndef CLIENTONLY - if (sv.active) - { - //use the q3 command, because we can. - Cbuf_AddText(va("\nbanname %s QuickBan\n", cl.players[player].name), RESTRICT_LOCAL); - } - else -#endif - Cbuf_AddText(va("\nrcon banname %s QuickBan\n", cl.players[player].name), RESTRICT_LOCAL); - } - break; - } - - Con_Printf("^m#^m ^[%s\\player\\%i^]: %if %ims", cl.players[player].name, player, cl.players[player].frags, cl.players[player].ping); - - for (i = 0; i < cl.splitclients; i++) - { - if (cl.playernum[i] == player) - break; - } - if (i == cl.splitclients) - { - extern cvar_t rcon_password; - if (cls.protocol == CP_QUAKEWORLD && strcmp(cl.players[cl.playernum[0]].team, cl.players[player].team)) - Con_Printf(" ^[[Join Team %s]\\cmd\\setinfo team %s^]", cl.players[player].team, cl.players[player].team); - Con_Printf(" ^[%sgnore\\player\\%i\\action\\ignore^]", cl.players[player].ignored?"Uni":"I", player); -// if (cl_voip_play.ival) - Con_Printf(" ^[%sute\\player\\%i\\action\\mute^]", cl.players[player].vignored?"Unm":"M", player); - - if (*rcon_password.string -#ifndef CLIENTONLY - || (sv.state && svs.clients[player].netchan.remote_address.type != NA_LOOPBACK) -#endif - ) - { - Con_Printf(" ^[Kick\\player\\%i\\action\\kick^]", player); - Con_Printf(" ^[Ban\\player\\%i\\action\\ban^]", player); - } - } - else - { - char cmdprefix[6]; - snprintf(cmdprefix, sizeof(cmdprefix), "%i ", i); - - //hey look! its you! - Con_Printf(" ^[Suicide\\cmd\\kill^]"); -#ifndef CLIENTONLY - if (!sv.state) - Con_Printf(" ^[Disconnect\\cmd\\disconnect^]"); - if (cls.allow_cheats || (sv.state && sv.allocated_client_slots == 1)) -#else - Con_Printf(" ^[Disconnect\\cmd\\disconnect^]"); - if (cls.allow_cheats) -#endif - { - Con_Printf(" ^[Noclip\\cmd\\noclip^]"); - Con_Printf(" ^[Fly\\cmd\\fly^]"); - Con_Printf(" ^[God\\cmd\\god^]"); - Con_Printf(" ^[Give\\impulse\\9^]"); - } - } - Con_Printf("\r"); - break; - } - c = Info_ValueForKey(info, "connect"); - if (*c && !strchr(c, ';') && !strchr(c, '\n')) - { - Cbuf_AddText(va("\nconnect %s\n", c), RESTRICT_LOCAL); - break; - } - c = Info_ValueForKey(info, "qtv"); - if (*c && !strchr(c, ';') && !strchr(c, '\n')) - { - Cbuf_AddText(va("\nqtvplay %s\n", c), RESTRICT_LOCAL); - break; - } - c = Info_ValueForKey(info, "cmd"); - if (*c && !strchr(c, ';') && !strchr(c, '\n')) - { - Cbuf_AddText(va("\ncmd %s\n", c), RESTRICT_LOCAL); - break; - } - c = Info_ValueForKey(info, "impulse"); - if (*c && !strchr(c, ';') && !strchr(c, '\n')) - { - Cbuf_AddText(va("\nimpulse %s\n", c), RESTRICT_LOCAL); - break; - } + Key_DefaultLinkClicked(buffer+2, info); } break; @@ -669,6 +731,8 @@ void Key_ConsoleRelease(int key, int unicode) } Z_Free(buffer); } + else + Con_Footerf(false, ""); } if (key == K_MOUSE2 && con_mousedown[2] == 2) { @@ -700,7 +764,7 @@ unsigned char *utf_left(unsigned char *start, unsigned char *cursor) if (*cursor == ']' && cursor > start && cursor[-1] == '^') { //just stepped onto a link - char *linkstart; + unsigned char *linkstart; linkstart = cursor-1; while(linkstart >= start) { @@ -834,7 +898,7 @@ void Key_Console (unsigned int unicode, int key) if (key == K_ENTER) { // backslash text are commands, else chat int oldl = edit_line; - edit_line = (edit_line + 1) & 31; + edit_line = (edit_line + 1) & (CON_EDIT_LINES_MASK); history_line = edit_line; key_lines[edit_line][0] = ']'; key_lines[edit_line][1] = '\0'; @@ -846,9 +910,12 @@ void Key_Console (unsigned int unicode, int key) return; } - if (key == K_SPACE && con_current->commandcompletion) + if (key == K_SPACE && keydown[K_CTRL] && con_current->commandcompletion) { - if (keydown[K_CTRL] && Cmd_CompleteCommand(key_lines[edit_line]+1, true, true, con_current->commandcompletion)) + char *txt = key_lines[edit_line]+1; + if (*txt == '/') + txt++; + if (Cmd_CompleteCommand(txt, true, true, con_current->commandcompletion, NULL)) { CompleteCommand (true); return; @@ -867,7 +934,7 @@ void Key_Console (unsigned int unicode, int key) CompleteCommand (false); return; } - if (key != K_SHIFT && con_commandmatch) + if (key != K_CTRL && key != K_SHIFT && con_commandmatch) con_commandmatch=1; if (key == K_LEFTARROW) @@ -913,11 +980,11 @@ void Key_Console (unsigned int unicode, int key) { do { - history_line = (history_line - 1) & 31; + history_line = (history_line - 1) & CON_EDIT_LINES_MASK; } while (history_line != edit_line && !key_lines[history_line][1]); if (history_line == edit_line) - history_line = (edit_line+1)&31; + history_line = (edit_line+1)&CON_EDIT_LINES_MASK; Q_strcpy(key_lines[edit_line], key_lines[history_line]); key_linepos = Q_strlen(key_lines[edit_line]); @@ -936,7 +1003,7 @@ void Key_Console (unsigned int unicode, int key) } do { - history_line = (history_line + 1) & 31; + history_line = (history_line + 1) & CON_EDIT_LINES_MASK; } while (history_line != edit_line && !key_lines[history_line][1]); @@ -1105,7 +1172,7 @@ void Key_Console (unsigned int unicode, int key) } } - if (keydown[K_ALT]) + if (keydown[K_ALT] && key > 32 && key < 128) key |= 128; // red char } @@ -1524,7 +1591,7 @@ void Key_Init (void) { int i; - for (i=0 ; i<32 ; i++) + for (i=0 ; i<=CON_EDIT_LINES_MASK ; i++) { key_lines[i][0] = ']'; key_lines[i][1] = 0; @@ -1611,9 +1678,9 @@ qboolean Key_MouseShouldBeFree(void) //if true, the input code is expected to return mouse cursor positions rather than deltas extern cvar_t cl_prydoncursor; -// extern int mouseusedforgui; -// if (mouseusedforgui) //I don't like this -// return true; + extern int mouseusedforgui; + if (mouseusedforgui) //I don't like this + return true; // if (!ActiveApp) // return true; diff --git a/engine/client/m_download.c b/engine/client/m_download.c index 6d2a0d31..8910f768 100644 --- a/engine/client/m_download.c +++ b/engine/client/m_download.c @@ -803,3 +803,173 @@ void Menu_DownloadStuff_f (void) #endif +#ifdef AVAIL_ZLIB + +static int numbootdownloads; +#include "fs.h" +extern searchpathfuncs_t zipfilefuncs; +static int CL_BootDownload_Extract(const char *fname, int fsize, void *ptr) +{ + char buffer[512*1024]; + int read; + void *zip = ptr; + flocation_t loc; + int slashes; + const char *s; + vfsfile_t *compressedpak; + vfsfile_t *decompressedpak; + + if (zipfilefuncs.FindFile(zip, &loc, fname, NULL)) + { + compressedpak = zipfilefuncs.OpenVFS(zip, &loc, "rb"); + if (compressedpak) + { + //this extra logic is so we can handle things like nexuiz/data/blah.pk3 + //as well as just data/blah.pk3 + slashes = 0; + for (s = strchr(fname, '/'); s; s = strchr(s+1, '/')) + slashes++; + for (; slashes > 1; slashes--) + fname = strchr(fname, '/')+1; + + if (!slashes) + { + FS_CreatePath(fname, FS_GAMEONLY); + decompressedpak = FS_OpenVFS(fname, "wb", FS_GAMEONLY); + } + else + { + FS_CreatePath(fname, FS_ROOT); + decompressedpak = FS_OpenVFS(fname, "wb", FS_ROOT); + } + if (decompressedpak) + { + for(;;) + { + read = VFS_READ(compressedpak, buffer, sizeof(buffer)); + if (read <= 0) + break; + if (VFS_WRITE(decompressedpak, buffer, read) != read) + { + Con_Printf("write failed writing %s. disk full?\n", fname); + break; + } + } + VFS_CLOSE(decompressedpak); + } + VFS_CLOSE(compressedpak); + } + } + return true; +} +static void CL_BootDownload_Complete(struct dl_download *dl) +{ + void *zip; +/* + int sz; + char *buf; + FILE *f; + sz = VFS_GETLEN(dl->file); + buf = malloc(sz); + VFS_READ(dl->file, buf, sz); + f = fopen("C:/Games/Quake/test/emptybasedir/test.zip", "wb"); + fwrite(buf, 1, sz, f); + fclose(f); + free(buf); +*/ + if (dl->status == DL_FINISHED) + zip = zipfilefuncs.OpenNew(dl->file, dl->url); + else + zip = NULL; + /*the zip code will have eaten the file handle*/ + dl->file = NULL; + if (zip) + { + /*scan it to extract its contents*/ + zipfilefuncs.EnumerateFiles(zip, "*/*.pk3", CL_BootDownload_Extract, zip); + zipfilefuncs.EnumerateFiles(zip, "*/*.pak", CL_BootDownload_Extract, zip); + zipfilefuncs.EnumerateFiles(zip, "*/*/*.pk3", CL_BootDownload_Extract, zip); + zipfilefuncs.EnumerateFiles(zip, "*/*/*.pak", CL_BootDownload_Extract, zip); + + /*close it, delete the temp file from disk, etc*/ + zipfilefuncs.ClosePath(zip); + + /*restart the filesystem so those new files can be found*/ + Cmd_ExecuteString("fs_restart\n", RESTRICT_LOCAL); + } + + if (!--numbootdownloads) + { + CL_ExecInitialConfigs(); + Cmd_StuffCmds(); + Cbuf_Execute (); + Cmd_ExecuteString("vid_restart\n", RESTRICT_LOCAL); + } +} + +qboolean CL_CheckBootDownloads(void) +{ + char *downloads = fs_gamedownload.string; + char token[2048]; + char *c, *s; + vfsfile_t *f; + struct dl_download *dl; + int mirrors; + + while ((downloads = COM_ParseOut(downloads, token, sizeof(token)))) + { + //FIXME: do we want to add some sort of file size indicator? + c = token; + while(*c && *c != ':' && *c != '|') + c++; + if (!*c) //erp? + continue; + *c++ = 0; + f = FS_OpenVFS(token, "rb", FS_ROOT); + if (f) + { + Con_DPrintf("Already have %s\n", token); + VFS_CLOSE(f); + continue; + } + mirrors = 1; + for (s = c; *s; s++) + { + if (*s == '|') + mirrors++; + } + mirrors = rand() % mirrors; + + while(mirrors) + { + mirrors--; + while(*c != '|') + c++; + c++; + } + for (s = c; *s; s++) + { + if (*s == '|') + *s = 0; + } + + Con_Printf("Attempting to download %s\n", c); + + dl = HTTP_CL_Get(c, token, CL_BootDownload_Complete); + if (dl) + { +#ifdef MULTITHREAD + DL_CreateThread(dl, FS_OpenTemp(), CL_BootDownload_Complete); +#endif + numbootdownloads++; + } + } + + return !numbootdownloads; +} +#else +qboolean CL_CheckBootDownloads(void) +{ + return true; +} +#endif diff --git a/engine/client/m_mp3.c b/engine/client/m_mp3.c index 0fe7bb48..6abab3a2 100644 --- a/engine/client/m_mp3.c +++ b/engine/client/m_mp3.c @@ -14,6 +14,9 @@ #ifdef _WIN32 #define WINAMP #endif +#if defined(_WIN32) +#define WINAVI +#endif #ifdef WINAMP @@ -229,11 +232,13 @@ qboolean Media_FakeTrack(int i, qboolean loop) sprintf(trackname, "sound/cdtracks/track%03i.ogg", i); found = COM_FCheckExists(trackname); } +#ifdef WINAVI if (!found) { sprintf(trackname, "sound/cdtracks/track%03i.mp3", i); found = COM_FCheckExists(trackname); } +#endif if (!found) { sprintf(trackname, "sound/cdtracks/track%03i.wav", i); @@ -756,10 +761,6 @@ char *Media_NextTrack(int musicchannelnum) -//Avi files are specific to windows. Bit of a bummer really. -#if defined(_WIN32) -#define WINAVI -#endif @@ -1405,6 +1406,7 @@ static qboolean Media_Plugin_DecodeFrame(cin_t *cin, qboolean nosound) if (cin->outtype != TF_INVALID) return true; + cin->ended = true; return false; } static void Media_Plugin_DoneFrame(cin_t *cin) @@ -2357,33 +2359,26 @@ void Media_PlayFilm_f (void) -#if defined(GLQUAKE) -#if defined(WINAVI) -#define WINAVIRECORDING -PAVIFILE recordavi_file; -#define recordavi_video_stream (recordavi_codec_fourcc?recordavi_compressed_video_stream:recordavi_uncompressed_video_stream) -PAVISTREAM recordavi_uncompressed_video_stream; -PAVISTREAM recordavi_compressed_video_stream; -PAVISTREAM recordavi_uncompressed_audio_stream; -WAVEFORMATEX recordavi_wave_format; -unsigned long recordavi_codec_fourcc; -#endif /* WINAVI */ - soundcardinfo_t *capture_fakesounddevice; +/* int recordavi_video_frame_counter; int recordavi_audio_frame_counter; float recordavi_frametime; //length of a frame in fractional seconds float recordavi_videotime; float recordavi_audiotime; -int capturesize; -int capturewidth; -char *capturevideomem; -vfsfile_t *captureaudiorawfile; +*/ +//int capturesize; +//int capturewidth; +//char *capturevideomem; //short *captureaudiomem; -int captureaudiosamples; +//int captureaudiosamples; +double captureframeinterval; //interval between video frames +double capturelastvideotime; //time of last video frame int captureframe; +qboolean captureframeforce; + qboolean capturepaused; -cvar_t capturerate = SCVAR("capturerate", "15"); +cvar_t capturerate = SCVAR("capturerate", "30"); #if defined(WINAVI) cvar_t capturecodec = SCVAR("capturecodec", "divx"); #else @@ -2394,18 +2389,332 @@ cvar_t capturesoundchannels = SCVAR("capturesoundchannels", "1"); cvar_t capturesoundbits = SCVAR("capturesoundbits", "8"); cvar_t capturemessage = SCVAR("capturemessage", ""); qboolean recordingdemo; -enum { - CT_NONE, - CT_AVI, - CT_SCREENSHOT -} capturetype; -char capturefilenameprefix[MAX_QPATH]; +media_encoder_funcs_t *capturedriver[8]; -qboolean Media_Capturing (void) +media_encoder_funcs_t *currentcapture_funcs; +void *currentcapture_ctx; + + +#if 1 +/*screenshot capture*/ +struct capture_raw_ctx { - if (!capturetype) - return false; - return true; + char videonameprefix[MAX_QPATH]; + vfsfile_t *audio; +}; + +static void *QDECL capture_raw_begin (char *streamname, int videorate, int width, int height, int *sndkhz, int *sndchannels, int *sndbits) +{ + struct capture_raw_ctx *ctx = Z_Malloc(sizeof(*ctx)); + + Q_strncpyz(ctx->videonameprefix, streamname, sizeof(ctx->videonameprefix)); + ctx->audio = NULL; + if (*sndkhz) + { + char filename[MAX_OSPATH]; + if (*sndbits < 8) + *sndbits = 8; + if (*sndbits != 8) + *sndbits = 16; + if (*sndchannels > 6) + *sndchannels = 6; + if (*sndchannels < 1) + *sndchannels = 1; + Q_snprintfz(filename, sizeof(filename), "%s/audio_%ichan_%ikhz_%ib.raw", ctx->videonameprefix, *sndchannels, *sndkhz/1000, *sndbits); + ctx->audio = FS_OpenVFS(filename, "wb", FS_GAMEONLY); + } + if (!ctx->audio) + { + *sndkhz = 0; + *sndchannels = 0; + *sndbits = 0; + } + return ctx; +} +static void QDECL capture_raw_video (void *vctx, void *data, int frame, int width, int height) +{ + struct capture_raw_ctx *ctx = vctx; + char filename[MAX_OSPATH]; + Q_snprintfz(filename, sizeof(filename), "%s/%8.8i.%s", ctx->videonameprefix, frame, capturecodec.string); + SCR_ScreenShot(filename, data, width, height); +} +static void QDECL capture_raw_audio (void *vctx, void *data, int bytes) +{ + struct capture_raw_ctx *ctx = vctx; + + if (ctx->audio) + VFS_WRITE(ctx->audio, data, bytes); +} +static void QDECL capture_raw_end (void *vctx) +{ + struct capture_raw_ctx *ctx = vctx; + Z_Free(ctx); +} +static media_encoder_funcs_t capture_raw = +{ + capture_raw_begin, + capture_raw_video, + capture_raw_audio, + capture_raw_end +}; +#endif +#if defined(WINAVI) + +/*screenshot capture*/ +struct capture_avi_ctx +{ + PAVIFILE file; + #define avi_video_stream(ctx) (ctx->codec_fourcc?ctx->compressed_video_stream:ctx->uncompressed_video_stream) + PAVISTREAM uncompressed_video_stream; + PAVISTREAM compressed_video_stream; + PAVISTREAM uncompressed_audio_stream; + WAVEFORMATEX wave_format; + unsigned long codec_fourcc; + + int audio_frame_counter; +}; + +static void QDECL capture_avi_end(void *vctx) +{ + struct capture_avi_ctx *ctx = vctx; + + if (ctx->uncompressed_video_stream) qAVIStreamRelease(ctx->uncompressed_video_stream); + if (ctx->compressed_video_stream) qAVIStreamRelease(ctx->compressed_video_stream); + if (ctx->uncompressed_audio_stream) qAVIStreamRelease(ctx->uncompressed_audio_stream); + if (ctx->file) qAVIFileRelease(ctx->file); + Z_Free(ctx); +} + +static void *QDECL capture_avi_begin (char *streamname, int videorate, int width, int height, int *sndkhz, int *sndchannels, int *sndbits) +{ + struct capture_avi_ctx *ctx = Z_Malloc(sizeof(*ctx)); + HRESULT hr; + BITMAPINFOHEADER bitmap_info_header; + AVISTREAMINFOA stream_header; + FILE *f; + char aviname[256]; + char nativepath[256]; + + char *fourcc = capturecodec.string; + + if (strlen(fourcc) == 4) + ctx->codec_fourcc = mmioFOURCC(*(fourcc+0), *(fourcc+1), *(fourcc+2), *(fourcc+3)); + else + ctx->codec_fourcc = 0; + + if (!qAVIStartup()) + { + Con_Printf("vfw support not available.\n"); + capture_avi_end(ctx); + return NULL; + } + + /*convert to foo.avi*/ + COM_StripExtension(streamname, aviname, sizeof(aviname)); + COM_DefaultExtension (aviname, ".avi", sizeof(aviname)); + /*find the system location of that*/ + FS_NativePath(aviname, FS_GAMEONLY, nativepath, sizeof(nativepath)); + + //wipe it. + f = fopen(nativepath, "rb"); + if (f) + { + fclose(f); + unlink(nativepath); + } + + hr = qAVIFileOpenA(&ctx->file, nativepath, OF_WRITE | OF_CREATE, NULL); + if (FAILED(hr)) + { + Con_Printf("Failed to open %s\n", nativepath); + capture_avi_end(ctx); + return NULL; + } + + + memset(&bitmap_info_header, 0, sizeof(BITMAPINFOHEADER)); + bitmap_info_header.biSize = 40; + bitmap_info_header.biWidth = vid.pixelwidth; + bitmap_info_header.biHeight = vid.pixelheight; + bitmap_info_header.biPlanes = 1; + bitmap_info_header.biBitCount = 24; + bitmap_info_header.biCompression = BI_RGB; + bitmap_info_header.biSizeImage = vid.pixelwidth*vid.pixelheight * 3; + + + memset(&stream_header, 0, sizeof(stream_header)); + stream_header.fccType = streamtypeVIDEO; + stream_header.fccHandler = ctx->codec_fourcc; + stream_header.dwScale = 100; + stream_header.dwRate = (unsigned long)(0.5 + 100.0/captureframeinterval); + SetRect(&stream_header.rcFrame, 0, 0, vid.pixelwidth, vid.pixelheight); + + hr = qAVIFileCreateStreamA(ctx->file, &ctx->uncompressed_video_stream, &stream_header); + if (FAILED(hr)) + { + Con_Printf("Couldn't initialise the stream, check codec\n"); + capture_avi_end(ctx); + return NULL; + } + + if (ctx->codec_fourcc) + { + AVICOMPRESSOPTIONS opts; + AVICOMPRESSOPTIONS* aopts[1] = { &opts }; + memset(&opts, 0, sizeof(opts)); + opts.fccType = stream_header.fccType; + opts.fccHandler = ctx->codec_fourcc; + // Make the stream according to compression + hr = qAVIMakeCompressedStream(&ctx->compressed_video_stream, ctx->uncompressed_video_stream, &opts, NULL); + if (FAILED(hr)) + { + Con_Printf("Failed to init compressor\n"); + capture_avi_end(ctx); + return NULL; + } + } + + + hr = qAVIStreamSetFormat(avi_video_stream(ctx), 0, &bitmap_info_header, sizeof(BITMAPINFOHEADER)); + if (FAILED(hr)) + { + Con_Printf("Failed to set format\n"); + capture_avi_end(ctx); + return NULL; + } + + if (*sndbits != 8 && *sndbits != 16) + *sndbits = 8; + if (*sndchannels < 1 && *sndchannels > 6) + *sndchannels = 1; + + if (*sndkhz) + { + memset(&ctx->wave_format, 0, sizeof(WAVEFORMATEX)); + ctx->wave_format.wFormatTag = WAVE_FORMAT_PCM; + ctx->wave_format.nChannels = *sndchannels; + ctx->wave_format.nSamplesPerSec = *sndkhz; + ctx->wave_format.wBitsPerSample = *sndbits; + ctx->wave_format.nBlockAlign = ctx->wave_format.wBitsPerSample/8 * ctx->wave_format.nChannels; + ctx->wave_format.nAvgBytesPerSec = ctx->wave_format.nSamplesPerSec * ctx->wave_format.nBlockAlign; + ctx->wave_format.cbSize = 0; + + + memset(&stream_header, 0, sizeof(stream_header)); + stream_header.fccType = streamtypeAUDIO; + stream_header.dwScale = ctx->wave_format.nBlockAlign; + stream_header.dwRate = stream_header.dwScale * (unsigned long)ctx->wave_format.nSamplesPerSec; + stream_header.dwSampleSize = ctx->wave_format.nBlockAlign; + + hr = qAVIFileCreateStreamA(ctx->file, &ctx->uncompressed_audio_stream, &stream_header); + if (FAILED(hr)) + { + capture_avi_end(ctx); + return NULL; + } + + hr = qAVIStreamSetFormat(ctx->uncompressed_audio_stream, 0, &ctx->wave_format, sizeof(WAVEFORMATEX)); + if (FAILED(hr)) + { + capture_avi_end(ctx); + return NULL; + } + } + return ctx; +} + +static void QDECL capture_avi_video(void *vctx, void *vdata, int frame, int width, int height) +{ + struct capture_avi_ctx *ctx = vctx; + qbyte *data = vdata; + int c, i; + qbyte temp; + // swap rgb to bgr + c = width*height*3; + for (i=0 ; iuncompressed_audio_stream) + qAVIStreamWrite(ctx->uncompressed_audio_stream, ctx->audio_frame_counter++, 1, data, bytes, AVIIF_KEYFRAME, NULL, NULL); +} + +static media_encoder_funcs_t capture_avi = +{ + capture_avi_begin, + capture_avi_video, + capture_avi_audio, + capture_avi_end +}; +#else +media_encoder_funcs_t capture_avi = +{ + NULL, + NULL, + NULL, + NULL +}; +#endif + + +static media_encoder_funcs_t *pluginencodersfunc[8]; +static struct plugin_s *pluginencodersplugin[8]; + +qboolean Media_RegisterEncoder(struct plugin_s *plug, media_encoder_funcs_t *funcs) +{ + int i; + for (i = 0; i < sizeof(pluginencodersfunc)/sizeof(pluginencodersfunc[0]); i++) + { + if (pluginencodersfunc[i] == NULL) + { + pluginencodersfunc[i] = funcs; + pluginencodersplugin[i] = plug; + return true; + } + } + return false; +} +void Media_StopRecordFilm_f(void); +/*funcs==null closes ALL decoders from this plugin*/ +qboolean Media_UnregisterEncoder(struct plugin_s *plug, media_encoder_funcs_t *funcs) +{ + qboolean success = true; + int i; + static media_decoder_funcs_t deadfuncs; + + for (i = 0; i < sizeof(pluginencodersfunc)/sizeof(pluginencodersfunc[0]); i++) + { + if (pluginencodersfunc[i] == funcs || (!funcs && pluginencodersplugin[i] == plug)) + { + if (currentcapture_funcs == funcs) + Media_StopRecordFilm_f(); + + plugindecodersfunc[i] = NULL; + plugindecodersplugin[i] = NULL; + if (funcs) + return success; + } + } + return success; +} + +//returns 0 if not capturing. 1 if capturing live. 2 if capturing a demo (where frame timings are forced). +int Media_Capturing (void) +{ + if (!currentcapture_funcs) + return 0; + return captureframeforce?2:1; } void Media_CapturePause_f (void) @@ -2424,20 +2733,42 @@ qboolean Media_PausedDemo (void) return false; } -double Media_TweekCaptureFrameTime(double time) +static qboolean Media_ForceTimeInterval(void) { - if (cls.demoplayback && Media_Capturing() && recordavi_frametime) + return (cls.demoplayback && Media_Capturing() && captureframeinterval>0); +} + +double Media_TweekCaptureFrameTime(double oldtime, double time) +{ + if (Media_ForceTimeInterval()) { - return time = recordavi_frametime; + captureframeforce = true; + //if we're forcing time intervals, then we use fixed time increments and generate a new video frame for every single frame. + return capturelastvideotime; } - return time; + return oldtime + time; } void Media_RecordFrame (void) { - if (!capturetype) + char *buffer; + int truewidth, trueheight; + + if (!currentcapture_funcs) return; +/* if (*capturecutoff.string && captureframe * captureframeinterval > capturecutoff.value*60) + { + currentcapture_funcs->capture_end(currentcapture_ctx); + currentcapture_ctx = currentcapture_funcs->capture_begin(Cmd_Argv(1), capturerate.value, vid.pixelwidth, vid.pixelheight, &sndkhz, &sndchannels, &sndbits); + if (!currentcapture_ctx) + { + currentcapture_funcs = NULL; + return; + } + captureframe = 0; + } +*/ if (Media_PausedDemo()) { int y = vid.height -32-16; @@ -2445,12 +2776,12 @@ void Media_RecordFrame (void) if (y > vid.height-8) y = vid.height-8; Draw_FunString((strlen(capturemessage.string)+1)*8, y, S_COLOR_RED "PAUSED"); + + if (captureframeforce) + capturelastvideotime += captureframeinterval; return; } - if (cls.findtrack) - return; //skip until we're tracking the right player. - //overlay this on the screen, so it appears in the film if (*capturemessage.string) { @@ -2462,55 +2793,33 @@ void Media_RecordFrame (void) } //time for annother frame? - if (recordavi_videotime > realtime+1) - recordavi_videotime = realtime; //urm, wrapped?.. - if (recordavi_videotime > realtime) - goto skipframe; - recordavi_videotime += recordavi_frametime; - //audio is mixed to match the video times - - switch (capturetype) + if (!captureframeforce) { - case CT_AVI: -#if defined(WINAVI) - { - HRESULT hr; - char *framebuffer = capturevideomem; - qbyte temp; - int i, c; - - if (!framebuffer) - { - Con_Printf("framebuffer = NULL with AVI capture type (this shouldn't happen)\n"); - return; - } - //ask gl for it - qglReadPixels (0, 0, vid.pixelwidth, vid.pixelheight, GL_RGB, GL_UNSIGNED_BYTE, framebuffer ); - - // swap rgb to bgr - c = vid.pixelwidth*vid.pixelheight*3; - for (i=0 ; i realtime+1) + capturelastvideotime = realtime; //urm, wrapped?.. + if (capturelastvideotime > realtime) + goto skipframe; } + + if (cls.findtrack) + { + capturelastvideotime += captureframeinterval; + return; //skip until we're tracking the right player. + } + + //submit the current video frame. audio will be mixed to match. + buffer = VID_GetRGBInfo(0, &truewidth, &trueheight); + if (buffer) + { + currentcapture_funcs->capture_video(currentcapture_ctx, buffer, captureframe, truewidth, trueheight); + capturelastvideotime += captureframeinterval; + captureframe++; + BZ_Free (buffer); + } + else + Con_DPrintf("Unable to grab video image\n"); + + captureframeforce = false; //this is drawn to the screen and not the film skipframe: @@ -2539,7 +2848,7 @@ static unsigned int MSD_GetDMAPos(soundcardinfo_t *sc) { int s; - s = captureframe*(snd_speed*recordavi_frametime); + s = captureframe*(snd_speed*captureframeinterval); // s >>= (sc->sn.samplebits/8) - 1; @@ -2559,52 +2868,39 @@ static void MSD_Submit(soundcardinfo_t *sc, int start, int end) int offset; int bytespersample; - lastpos = sc->snd_completed; newpos = sc->paintedtime; - samplestosubmit = newpos - lastpos; - if (samplestosubmit < (snd_speed*recordavi_frametime)) - return; - - bytespersample = sc->sn.numchannels*sc->sn.samplebits/8; - - sc->snd_completed = newpos; - offset = (lastpos % (sc->sn.samples/sc->sn.numchannels)); - - //we could just use a buffer size equal to the number of samples in each frame - //but that isn't as robust when it comes to floating point imprecisions - //namly: that it would loose a sample each frame with most framerates. - - switch (capturetype) + while(1) { - case CT_AVI: -#if defined(WINAVI) + lastpos = sc->snd_completed; + samplestosubmit = newpos - lastpos; + if (samplestosubmit < (snd_speed*captureframeinterval)) + return; + if (samplestosubmit < 1152) + return; + if (samplestosubmit > 1152) + samplestosubmit = 1152; + + bytespersample = sc->sn.numchannels*sc->sn.samplebits/8; + + offset = (lastpos % (sc->sn.samples/sc->sn.numchannels)); + + //we could just use a buffer size equal to the number of samples in each frame + //but that isn't as robust when it comes to floating point imprecisions + //namly: that it would loose a sample each frame with most framerates. + if ((sc->snd_completed % (sc->sn.samples/sc->sn.numchannels)) < offset) { int partialsamplestosubmit; //wraped, two chunks to send partialsamplestosubmit = ((sc->sn.samples/sc->sn.numchannels)) - offset; - qAVIStreamWrite(recordavi_uncompressed_audio_stream, recordavi_audio_frame_counter++, 1, sc->sn.buffer+offset*bytespersample, partialsamplestosubmit*bytespersample, AVIIF_KEYFRAME, NULL, NULL); + currentcapture_funcs->capture_audio(currentcapture_ctx, sc->sn.buffer+offset*bytespersample, partialsamplestosubmit*bytespersample); samplestosubmit -= partialsamplestosubmit; + sc->snd_completed += partialsamplestosubmit; offset = 0; } - qAVIStreamWrite(recordavi_uncompressed_audio_stream, recordavi_audio_frame_counter++, 1, sc->sn.buffer+offset*bytespersample, samplestosubmit*bytespersample, AVIIF_KEYFRAME, NULL, NULL); -#endif /* WINAVI */ - break; - case CT_NONE: - break; - case CT_SCREENSHOT: - if ((sc->snd_completed % (sc->sn.samples/sc->sn.numchannels)) < offset) - { - int partialsamplestosubmit; - //wraped, two chunks to send - partialsamplestosubmit = ((sc->sn.samples/sc->sn.numchannels)) - offset; - VFS_WRITE(captureaudiorawfile, sc->sn.buffer+offset*bytespersample, partialsamplestosubmit*bytespersample); - samplestosubmit -= partialsamplestosubmit; - offset = 0; - } - VFS_WRITE(captureaudiorawfile, sc->sn.buffer+offset*bytespersample, samplestosubmit*bytespersample); - break; + currentcapture_funcs->capture_audio(currentcapture_ctx, sc->sn.buffer+offset*bytespersample, samplestosubmit*bytespersample); + sc->snd_completed += samplestosubmit; } } @@ -2614,25 +2910,30 @@ static void MSD_Shutdown (soundcardinfo_t *sc) capture_fakesounddevice = NULL; } -void Media_InitFakeSoundDevice (int channels, int samplebits) +void Media_InitFakeSoundDevice (int speed, int channels, int samplebits) { soundcardinfo_t *sc; if (capture_fakesounddevice) return; + if (!snd_speed) + snd_speed = speed; + sc = Z_Malloc(sizeof(soundcardinfo_t)); sc->snd_sent = 0; sc->snd_completed = 0; - sc->sn.samples = snd_speed*0.5; - sc->sn.speed = snd_speed; + sc->sn.samples = speed*0.5; + sc->sn.speed = speed; sc->sn.samplebits = samplebits; sc->sn.samplepos = 0; sc->sn.numchannels = channels; sc->inactive_sound = true; + sc->sn.samples -= sc->sn.samples%1152; + sc->sn.buffer = (unsigned char *) BZ_Malloc(sc->sn.samples*sc->sn.numchannels*(sc->sn.samplebits/8)); @@ -2655,40 +2956,22 @@ void Media_InitFakeSoundDevice (int channels, int samplebits) void Media_StopRecordFilm_f (void) { -#if defined(WINAVI) - if (recordavi_uncompressed_video_stream) qAVIStreamRelease(recordavi_uncompressed_video_stream); - if (recordavi_compressed_video_stream) qAVIStreamRelease(recordavi_compressed_video_stream); - if (recordavi_uncompressed_audio_stream) qAVIStreamRelease(recordavi_uncompressed_audio_stream); - if (recordavi_file) qAVIFileRelease(recordavi_file); - - recordavi_uncompressed_video_stream=NULL; - recordavi_compressed_video_stream = NULL; - recordavi_uncompressed_audio_stream=NULL; - recordavi_file = NULL; -#endif /* WINAVI */ - - if (capturevideomem) - BZ_Free(capturevideomem); - capturevideomem = NULL; - if (capture_fakesounddevice) S_ShutdownCard(capture_fakesounddevice); capture_fakesounddevice = NULL; - if (captureaudiorawfile) - VFS_CLOSE(captureaudiorawfile); - captureaudiorawfile = NULL; - - - capturevideomem = NULL; - recordingdemo=false; - capturetype = CT_NONE; + if (currentcapture_funcs) + currentcapture_funcs->capture_end(currentcapture_ctx); + currentcapture_ctx = NULL; + currentcapture_funcs = NULL; } void Media_RecordFilm_f (void) { char *fourcc = capturecodec.string; + int sndkhz, sndchannels, sndbits; + int i; if (Cmd_Argc() != 2) { @@ -2702,18 +2985,16 @@ void Media_RecordFilm_f (void) Media_StopRecordFilm_f(); - recordavi_video_frame_counter = 0; - recordavi_audio_frame_counter = 0; - if (capturerate.value<=0) { Con_Printf("Invalid capturerate\n"); capturerate.value = 15; } - recordavi_frametime = 1/capturerate.value; - if (recordavi_frametime < 0.001) - recordavi_frametime = 0.001; //no more than 1000 images per second. + captureframeinterval = 1/capturerate.value; + if (captureframeinterval < 0.001) + captureframeinterval = 0.001; //no more than 1000 images per second. + capturelastvideotime = realtime = 0; captureframe = 0; if (*fourcc) @@ -2723,209 +3004,70 @@ void Media_RecordFilm_f (void) !strcmp(fourcc, "jpg") || !strcmp(fourcc, "pcx")) { - capturetype = CT_SCREENSHOT; - Q_strncpyz(capturefilenameprefix, Cmd_Argv(1), sizeof(capturefilenameprefix)); + currentcapture_funcs = &capture_raw; } else { - capturetype = CT_AVI; + currentcapture_funcs = &capture_avi; } } else { - capturetype = CT_AVI; //uncompressed avi + currentcapture_funcs = &capture_avi; } - - if (capturetype == CT_NONE) + for (i = 0; i < 8; i++) { - + if (pluginencodersfunc[i]) + currentcapture_funcs = pluginencodersfunc[i]; } - else if (capturetype == CT_SCREENSHOT) + + if (capturesound.ival) { - if (capturesound.value && capturesoundchannels.value >= 1) - { - char filename[MAX_OSPATH]; - int chans = capturesoundchannels.value; - int sbits = capturesoundbits.value; - if (sbits < 8) - sbits = 8; - if (sbits != 8) - sbits = 16; - if (chans > 6) - chans = 6; - Q_snprintfz(filename, sizeof(filename), "%s/audio_%ichan_%ikhz_%ib.raw", capturefilenameprefix, chans, snd_speed/1000, sbits); - captureaudiorawfile = FS_OpenVFS(filename, "wb", FS_GAMEONLY); - - if (captureaudiorawfile) - Media_InitFakeSoundDevice(chans, sbits); - } + sndkhz = snd_speed?snd_speed:48000; + sndchannels = capturesoundchannels.ival; + sndbits = capturesoundbits.ival; } -#if defined(WINAVI) - else if (capturetype == CT_AVI) - { - HRESULT hr; - BITMAPINFOHEADER bitmap_info_header; - AVISTREAMINFOA stream_header; - FILE *f; - char aviname[256]; - char nativepath[256]; - - if (strlen(fourcc) == 4) - recordavi_codec_fourcc = mmioFOURCC(*(fourcc+0), *(fourcc+1), *(fourcc+2), *(fourcc+3)); - else - recordavi_codec_fourcc = 0; - - if (!qAVIStartup()) - { - Con_Printf("vfw support not available.\n"); - return; - } - - /*convert to foo.avi*/ - COM_StripExtension(Cmd_Argv(1), aviname, sizeof(aviname)); - COM_DefaultExtension (aviname, ".avi", sizeof(aviname)); - /*find the system location of that*/ - FS_NativePath(aviname, FS_ROOT, nativepath, sizeof(nativepath)); - - //wipe it. - f = fopen(nativepath, "rb"); - if (f) - { - fclose(f); - unlink(nativepath); - } - - hr = qAVIFileOpenA(&recordavi_file, nativepath, OF_WRITE | OF_CREATE, NULL); - if (FAILED(hr)) - { - Con_Printf("Failed to open %s\n", nativepath); - return; - } - - - memset(&bitmap_info_header, 0, sizeof(BITMAPINFOHEADER)); - bitmap_info_header.biSize = 40; - bitmap_info_header.biWidth = vid.pixelwidth; - bitmap_info_header.biHeight = vid.pixelheight; - bitmap_info_header.biPlanes = 1; - bitmap_info_header.biBitCount = 24; - bitmap_info_header.biCompression = BI_RGB; - bitmap_info_header.biSizeImage = vid.pixelwidth*vid.pixelheight * 3; - - - memset(&stream_header, 0, sizeof(stream_header)); - stream_header.fccType = streamtypeVIDEO; - stream_header.fccHandler = recordavi_codec_fourcc; - stream_header.dwScale = 100; - stream_header.dwRate = (unsigned long)(0.5 + 100.0/recordavi_frametime); - SetRect(&stream_header.rcFrame, 0, 0, vid.pixelwidth, vid.pixelheight); - - hr = qAVIFileCreateStreamA(recordavi_file, &recordavi_uncompressed_video_stream, &stream_header); - if (FAILED(hr)) - { - Con_Printf("Couldn't initialise the stream, check codec\n"); - Media_StopRecordFilm_f(); - return; - } - - if (recordavi_codec_fourcc) - { - AVICOMPRESSOPTIONS opts; - AVICOMPRESSOPTIONS* aopts[1] = { &opts }; - memset(&opts, 0, sizeof(opts)); - opts.fccType = stream_header.fccType; - opts.fccHandler = recordavi_codec_fourcc; - // Make the stream according to compression - hr = qAVIMakeCompressedStream(&recordavi_compressed_video_stream, recordavi_uncompressed_video_stream, &opts, NULL); - if (FAILED(hr)) - { - Con_Printf("Failed to init compressor\n"); - Media_StopRecordFilm_f(); - return; - } - } - - - hr = qAVIStreamSetFormat(recordavi_video_stream, 0, &bitmap_info_header, sizeof(BITMAPINFOHEADER)); - if (FAILED(hr)) - { - Con_Printf("Failed to set format\n"); - Media_StopRecordFilm_f(); - return; - } - - if (capturesoundbits.value != 8 && capturesoundbits.value != 16) - Cvar_Set(&capturesoundbits, "8"); - if (capturesoundchannels.value < 1 && capturesoundchannels.value > 6) - Cvar_Set(&capturesoundchannels, "1"); - - if (capturesound.value) - { - memset(&recordavi_wave_format, 0, sizeof(WAVEFORMATEX)); - recordavi_wave_format.wFormatTag = WAVE_FORMAT_PCM; - recordavi_wave_format.nChannels = capturesoundchannels.value; - recordavi_wave_format.nSamplesPerSec = snd_speed; - recordavi_wave_format.wBitsPerSample = capturesoundbits.value; - recordavi_wave_format.nBlockAlign = recordavi_wave_format.wBitsPerSample/8 * recordavi_wave_format.nChannels; - recordavi_wave_format.nAvgBytesPerSec = recordavi_wave_format.nSamplesPerSec * recordavi_wave_format.nBlockAlign; - recordavi_wave_format.cbSize = 0; - - - memset(&stream_header, 0, sizeof(stream_header)); - stream_header.fccType = streamtypeAUDIO; - stream_header.dwScale = recordavi_wave_format.nBlockAlign; - stream_header.dwRate = stream_header.dwScale * (unsigned long)recordavi_wave_format.nSamplesPerSec; - stream_header.dwSampleSize = recordavi_wave_format.nBlockAlign; - - hr = qAVIFileCreateStreamA(recordavi_file, &recordavi_uncompressed_audio_stream, &stream_header); - if (FAILED(hr)) return; - - hr = qAVIStreamSetFormat(recordavi_uncompressed_audio_stream, 0, &recordavi_wave_format, sizeof(WAVEFORMATEX)); - if (FAILED(hr)) return; - - Media_InitFakeSoundDevice(recordavi_wave_format.nChannels, recordavi_wave_format.wBitsPerSample); - } - - - recordavi_videotime = realtime; - recordavi_audiotime = realtime; - -// if (recordavi_wave_format.nSamplesPerSec) -// captureaudiomem = BZ_Malloc(recordavi_wave_format.nSamplesPerSec*2); - - capturevideomem = BZ_Malloc(vid.pixelwidth*vid.pixelheight*3); - } -#endif /* WINAVI */ else { - Con_Printf("That sort of video capturing is not supported in this build\n"); - capturetype = CT_NONE; + sndkhz = 0; + sndchannels = 0; + sndbits = 0; } + + if (!currentcapture_funcs->capture_begin) + currentcapture_ctx = NULL; + else + currentcapture_ctx = currentcapture_funcs->capture_begin(Cmd_Argv(1), capturerate.value, vid.pixelwidth, vid.pixelheight, &sndkhz, &sndchannels, &sndbits); + if (!currentcapture_ctx) + { + currentcapture_funcs = NULL; + Con_Printf("Unable to initialise capture driver\n"); + } + else if (sndkhz) + Media_InitFakeSoundDevice(sndkhz, sndchannels, sndbits); } void Media_CaptureDemoEnd(void) { if (recordingdemo) Media_StopRecordFilm_f(); } +void CL_PlayDemo(char *demoname); void Media_RecordDemo_f(void) { - CL_PlayDemo_f(); + if (Cmd_Argc() < 2) + return; + CL_PlayDemo(Cmd_Argv(1)); + if (Cmd_Argc() > 2) + Cmd_ShiftArgs(1, false); Media_RecordFilm_f(); scr_con_current=0; key_dest = key_game; - if (capturetype != CT_NONE) + if (currentcapture_funcs) recordingdemo = true; else CL_Stopdemo_f(); //capturing failed for some reason } -#else /* GLQUAKE */ -void Media_CaptureDemoEnd(void){} -void Media_RecordAudioFrame (short *sample_buffer, int samples){} -double Media_TweekCaptureFrameTime(double time) { return time ; } -void Media_RecordFrame (void) {} -qboolean Media_PausedDemo (void) {return false;} //should not return a value -#endif /* GLQUAKE */ #ifdef _WIN32 typedef struct ISpNotifySink ISpNotifySink; @@ -3626,6 +3768,11 @@ void Media_Init(void) Cvar_Register(&tts_mode, "Gimmicks"); #endif +#if defined(WINAVI) + Media_RegisterEncoder(NULL, &capture_avi); +#endif + Media_RegisterEncoder(NULL, &capture_raw); + Cmd_AddCommand("playfilm", Media_PlayFilm_f); Cmd_AddCommand("cinematic", Media_PlayFilm_f); Cmd_AddCommand("music_fforward", Media_FForward_f); @@ -3872,7 +4019,7 @@ void M_Media_Draw (void){} void M_Media_Key (int key) {} qboolean Media_ShowFilm(void){return false;} -double Media_TweekCaptureFrameTime(double time) { return time ; } +double Media_TweekCaptureFrameTime(double oldtime, double time) { return oldtime+time ; } void Media_RecordFrame (void) {} void Media_CaptureDemoEnd(void) {} void Media_RecordDemo_f(void) {} diff --git a/engine/client/m_options.c b/engine/client/m_options.c index d234215a..d851cbb2 100644 --- a/engine/client/m_options.c +++ b/engine/client/m_options.c @@ -435,6 +435,8 @@ const char *presetexec[] = "gl_specular 0;" "r_loadlit 0;" "r_fastsky 1;" + "r_waterstyle 0;" + "r_lavastyle 0;" "r_shadow_realtime_dlight 0;" "r_shadow_realtime_world 0;" "r_glsl_offsetmapping 0;" @@ -444,6 +446,7 @@ const char *presetexec[] = "r_waterwarp 0;" "r_lightstylesmooth 0;" "r_part_density 0.25;" + , // fast options "gl_texturemode ln;" "r_particlesystem classic;" @@ -452,7 +455,10 @@ const char *presetexec[] = "gl_flashblend 1;" "r_loadlit 1;" "r_fastsky 0;" + "r_waterstyle 1;" + "r_lavastyle 1;" "r_nolightdir 0;" + , // normal options #ifdef MINIMAL "r_particlesystem classic;" @@ -467,6 +473,7 @@ const char *presetexec[] = "gl_load24bit 1;" "r_replacemodels \"md3 md2\";" "r_waterwarp 1;" + , // nice options "r_stains 0.75;" "gl_texturemode ll;" @@ -476,14 +483,17 @@ const char *presetexec[] = #endif "gl_specular 1;" "r_loadlit 2;" + "r_waterstyle 2;" // "r_fastsky -1;" "r_shadow_realtime_dlight 1;" "gl_detail 1;" "r_lightstylesmooth 1;" "gl_texture_anisotropic_filtering 4;" + , // realtime options // "r_bloom 1;" "r_particledesc \"spikeset high tsshaft\";" + "r_waterstyle 3;" "r_glsl_offsetmapping 1;" "r_shadow_realtime_world 1;" "gl_texture_anisotropic_filtering 16;" diff --git a/engine/client/net_master.c b/engine/client/net_master.c index 7c10a0ae..a152624e 100644 --- a/engine/client/net_master.c +++ b/engine/client/net_master.c @@ -40,6 +40,7 @@ cvar_t slist_writeserverstxt = SCVAR("slist_writeservers", "0"); void CL_MasterListParse(netadrtype_t adrtype, int type, qboolean slashpad); void CL_QueryServers(void); int CL_ReadServerInfo(char *msg, int servertype, qboolean favorite); +void MasterInfo_RemoveAllPlayers(void); master_t *master; player_t *mplayers; @@ -495,7 +496,7 @@ float Master_ReadKeyFloat(serverinfo_t *server, int keynum) char *Master_ReadKeyString(serverinfo_t *server, int keynum) { - char adr[MAX_ADR_SIZE]; + static char adr[MAX_ADR_SIZE]; if (keynum < SLKEY_CUSTOM) { @@ -631,12 +632,26 @@ void Master_AddMaster (char *address, int type, char *description) void MasterInfo_Shutdown(void) { master_t *mast; + serverinfo_t *sv; + MasterInfo_RemoveAllPlayers(); + while(firstserver) + { + sv = firstserver; + firstserver = sv->next; + Z_Free(sv); + } while(master) { mast = master; master = mast->next; + if (mast->dl) + DL_Close(mast->dl); Z_Free(mast); } + + maxvisibleservers = 0; + numvisibleservers = 0; + Z_Free(visibleservers); } void Master_AddMasterHTTP (char *address, int mastertype, char *description) @@ -1267,6 +1282,8 @@ void MasterInfo_ProcessHTTPJSON(struct dl_download *dl) { int len; char *buf; + master_t *mast = dl->user_ctx; + mast->dl = NULL; if (dl->file) { len = VFS_GETLEN(dl->file); @@ -1285,11 +1302,15 @@ void MasterInfo_ProcessHTTPJSON(struct dl_download *dl) // wrapper functions for the different server types void MasterInfo_ProcessHTTPNQ(struct dl_download *dl) { + master_t *mast = dl->user_ctx; + mast->dl = NULL; MasterInfo_ProcessHTTP(dl->file, SS_NETQUAKE); } void MasterInfo_ProcessHTTPQW(struct dl_download *dl) { + master_t *mast = dl->user_ctx; + mast->dl = NULL; MasterInfo_ProcessHTTP(dl->file, SS_GENERICQUAKEWORLD); } #endif @@ -1368,13 +1389,28 @@ void MasterInfo_Request(master_t *mast, qboolean evenifwedonthavethefiles) #endif #ifdef WEBCLIENT case MT_MASTERHTTPJSON: - HTTP_CL_Get(mast->address, NULL, MasterInfo_ProcessHTTPJSON); + if (!mast->dl) + { + mast->dl = HTTP_CL_Get(mast->address, NULL, MasterInfo_ProcessHTTPJSON); + if (mast->dl) + mast->dl->user_ctx = mast; + } break; case MT_MASTERHTTPNQ: - HTTP_CL_Get(mast->address, NULL, MasterInfo_ProcessHTTPNQ); + if (!mast->dl) + { + mast->dl = HTTP_CL_Get(mast->address, NULL, MasterInfo_ProcessHTTPNQ); + if (mast->dl) + mast->dl->user_ctx = mast; + } break; case MT_MASTERHTTPQW: - HTTP_CL_Get(mast->address, NULL, MasterInfo_ProcessHTTPQW); + if (!mast->dl) + { + mast->dl = HTTP_CL_Get(mast->address, NULL, MasterInfo_ProcessHTTPQW); + if (mast->dl) + mast->dl->user_ctx = mast; + } break; #endif } @@ -1757,6 +1793,16 @@ serverinfo_t *Master_InfoForNum (int num) return NULL; } +void MasterInfo_RemoveAllPlayers(void) +{ + player_t *p; + while(mplayers) + { + p = mplayers; + mplayers = p->next; + Z_Free(p); + } +} void MasterInfo_RemovePlayers(netadr_t adr) { player_t *p, *prev; diff --git a/engine/client/p_script.c b/engine/client/p_script.c index d7029606..4ff900ff 100644 --- a/engine/client/p_script.c +++ b/engine/client/p_script.c @@ -1779,6 +1779,8 @@ static void P_ImportEffectInfo_f(void) args--; } line = COM_StringParse(line, com_token, sizeof(com_token), false, false); + if (!line) + break; Q_strncpyz(arg[args], com_token, sizeof(arg[args])); args++; if (*com_token == '\n') @@ -4655,8 +4657,13 @@ static void GL_DrawParticleBeam(int count, beamseg_t **blist, plooks_t *type) c = b->next; q = c->p; + if (!q) + continue; p = b->p; + q->rgba[3] = 1; + p->rgba[3] = 1; + VectorSubtract(r_refdef.vieworg, q->org, v); VectorNormalize(v); CrossProduct(c->dir, v, cr); @@ -5108,7 +5115,11 @@ static void PScript_DrawParticleTypes (void) { while ((p=type->particles)) { - if (pdraw) + if (scenetri) + { + tdraw(scenetri, p, type->slooks); + } + else if (pdraw) RQ_AddDistReorder(pdraw, p, type->slooks, p->org); // make sure emitter runs at least once diff --git a/engine/client/pr_csqc.c b/engine/client/pr_csqc.c index 95239219..a1406a22 100644 --- a/engine/client/pr_csqc.c +++ b/engine/client/pr_csqc.c @@ -611,6 +611,13 @@ static qboolean CopyCSQCEdictToEntity(csqcedict_t *in, entity_t *out) cs_getframestate(in, rflags, &out->framestate); VectorCopy(in->v->origin, out->origin); + VectorCopy(in->v->oldorigin, out->oldorigin); + if (in->v->enemy) + { + csqcedict_t *ed = (csqcedict_t*)PROG_TO_EDICT(csqcprogs, in->v->enemy); + VectorSubtract(out->oldorigin, ed->v->oldorigin, out->oldorigin); + } + if (rflags & CSQCRF_USEAXIS) { VectorCopy(csqcg.forward, out->axis[0]); @@ -1394,6 +1401,7 @@ static void QCBUILTIN PF_R_SetViewFlag(progfuncs_t *prinst, struct globalvars_s } } +void R2D_PolyBlend (void); static void QCBUILTIN PF_R_RenderScene(progfuncs_t *prinst, struct globalvars_s *pr_globals) { if (cl.worldmodel) @@ -1404,13 +1412,7 @@ static void QCBUILTIN PF_R_RenderScene(progfuncs_t *prinst, struct globalvars_s V_CalcGunPositionAngle(csqc_lplayernum, V_CalcBob(csqc_lplayernum, true)); R_RenderView(); - -#ifdef GLQUAKE - if (qrenderer == QR_OPENGL) - { - GL_Set2D (false); - } -#endif + R2D_PolyBlend (); vid.recalc_refdef = 1; @@ -1686,7 +1688,7 @@ static void csqc_setmodel(progfuncs_t *prinst, csqcedict_t *ent, int modelindex) ent->v->modelindex = modelindex; if (modelindex < 0) { - if (modelindex <= -MAX_MODELS) + if (modelindex <= -MAX_CSQCMODELS) return; ent->v->model = PR_SetString(prinst, cl.model_csqcname[-modelindex]); if (!cl.model_csqcprecache[-modelindex]) @@ -3257,7 +3259,7 @@ static void QCBUILTIN PF_cl_runningserver (progfuncs_t *prinst, struct globalvar #ifdef CLIENTONLY G_FLOAT(OFS_RETURN) = false; #else - G_FLOAT(OFS_RETURN) = !!sv.active; + G_FLOAT(OFS_RETURN) = sv.state != ss_dead; #endif } @@ -4275,7 +4277,6 @@ static struct { // {"bulleten", PF_bulleten, 243}, (removed builtin) {"rotatevectorsbytag", PF_rotatevectorsbytag, 244}, -#ifdef SQL {"sqlconnect", PF_NoCSQC, 250}, // #250 float([string host], [string user], [string pass], [string defaultdb], [string driver]) sqlconnect (FTE_SQL) {"sqldisconnect", PF_NoCSQC, 251}, // #251 void(float serveridx) sqldisconnect (FTE_SQL) {"sqlopenquery", PF_NoCSQC, 252}, // #252 float(float serveridx, void(float serveridx, float queryidx, float rows, float columns, float eof) callback, float querytype, string query) sqlopenquery (FTE_SQL) @@ -4285,7 +4286,6 @@ static struct { {"sqlescape", PF_NoCSQC, 256}, // #256 string(float serveridx, string data) sqlescape (FTE_SQL) {"sqlversion", PF_NoCSQC, 257}, // #257 string(float serveridx) sqlversion (FTE_SQL) {"sqlreadfloat", PF_NoCSQC, 258}, // #258 float(float serveridx, float queryidx, float row, float column) sqlreadfloat (FTE_SQL) -#endif {"stoi", PF_stoi, 259}, {"itos", PF_itos, 260}, @@ -4293,7 +4293,7 @@ static struct { {"htos", PF_htos, 262}, {"skel_create", PF_skel_create, 263},//float(float modlindex) skel_create = #263; // (FTE_CSQC_SKELETONOBJECTS) - {"skel_build", PF_skel_build, 264},//float(float skel, entity ent, float modelindex, float retainfrac, float firstbone, float lastbone) skel_build = #264; // (FTE_CSQC_SKELETONOBJECTS) + {"skel_build", PF_skel_build, 264},//float(float skel, entity ent, float modelindex, float retainfrac, float firstbone, float lastbone, optional float addition) skel_build = #264; // (FTE_CSQC_SKELETONOBJECTS) {"skel_get_numbones", PF_skel_get_numbones, 265},//float(float skel) skel_get_numbones = #265; // (FTE_CSQC_SKELETONOBJECTS) {"skel_get_bonename", PF_skel_get_bonename, 266},//string(float skel, float bonenum) skel_get_bonename = #266; // (FTE_CSQC_SKELETONOBJECTS) (returns tempstring) {"skel_get_boneparent", PF_skel_get_boneparent, 267},//float(float skel, float bonenum) skel_get_boneparent = #267; // (FTE_CSQC_SKELETONOBJECTS) @@ -4623,6 +4623,8 @@ static struct { {"isfunction", PF_isfunction, 607}, {"parseentitydata", PF_parseentitydata, 608}, + {"findkeysforcommand", PF_cl_findkeysforcommand, 610}, + {"sprintf", PF_sprintf, 627}, {"getsurfacenumtriangles",PF_getsurfacenumtriangles,628}, @@ -4831,6 +4833,10 @@ void CSQC_Shutdown(void) memset(&deltafunction, 0, sizeof(deltafunction)); memset(csqcdelta_playerents, 0, sizeof(csqcdelta_playerents)); + Z_Free(csqcent); + csqcent = NULL; + maxcsqcentities = 0; + csqcmapentitydata = NULL; csqcmapentitydataloaded = false; @@ -5084,10 +5090,16 @@ qboolean CSQC_Init (qboolean anycsqc, qboolean csdatenabled, unsigned int checks if (csqc_singlecheats || anycsqc) { - Con_DPrintf("loading csaddon.dat...\n"); if (PR_LoadProgs(csqcprogs, "csaddon.dat", 0, NULL, 0) >= 0) + { + Con_DPrintf("loaded csaddon.dat...\n"); loaded = true; + } + else + Con_DPrintf("unable to find csaddon.dat.\n"); } + else + Con_DPrintf("skipping csaddon.dat due to cheat restrictions\n"); if (!loaded) { @@ -5188,9 +5200,8 @@ void CSQC_WorldLoaded(void) #endif worldent = (csqcedict_t *)EDICT_NUM(csqcprogs, 0); - worldent->v->modelindex = 1; - worldent->v->model = PR_SetString(csqcprogs, cl.model_name[(int)worldent->v->modelindex]); worldent->v->solid = SOLID_BSP; + csqc_setmodel(csqcprogs, worldent, 1); if (csqcg.worldloaded) PR_ExecuteProgram(csqcprogs, csqcg.worldloaded); @@ -5357,7 +5368,7 @@ void CSQC_RegisterCvarsAndThings(void) { Cmd_AddCommand("coredump_csqc", CSQC_CoreDump); Cmd_AddCommand ("extensionlist_csqc", PR_CSExtensionList_f); - Cmd_AddCommand("cl_cmd", CSQC_GameCommand_f); + Cmd_AddCommandD("cl_cmd", CSQC_GameCommand_f, "Calls the csqc's GameCommand function"); Cmd_AddCommand("breakpoint_csqc", CSQC_Breakpoint_f); Cvar_Register(&pr_csqc_memsize, CSQCPROGSGROUP); diff --git a/engine/client/pr_menu.c b/engine/client/pr_menu.c index ca767092..5f1f5939 100644 --- a/engine/client/pr_menu.c +++ b/engine/client/pr_menu.c @@ -393,7 +393,8 @@ void QCBUILTIN PF_CL_drawcolouredstring (progfuncs_t *prinst, struct globalvars_ else if ((*str & CON_CHARMASK) == '\r') px = ipx; else - px = Font_DrawScaleChar(px, py, size[0], size[1], *str++); + px = Font_DrawScaleChar(px, py, size[0], size[1], *str); + str++; } Font_InvalidateColour(); Font_EndString(font_conchar); @@ -411,7 +412,7 @@ void QCBUILTIN PF_CL_stringwidth(progfuncs_t *prinst, struct globalvars_s *pr_gl else fontsize = 8; - if (mp_globs.drawfontscale) + if (mp_globs.drawfontscale && !prinst->parms->user) fontsize *= mp_globs.drawfontscale[1]; end = COM_ParseFunString(CON_WHITEMASK, text, buffer, sizeof(buffer), !usecolours); @@ -421,7 +422,7 @@ void QCBUILTIN PF_CL_stringwidth(progfuncs_t *prinst, struct globalvars_s *pr_gl px = Font_LineWidth(buffer, end); Font_EndString(font_conchar); - if (mp_globs.drawfontscale) + if (mp_globs.drawfontscale && !prinst->parms->user) px *= mp_globs.drawfontscale[1]; G_FLOAT(OFS_RETURN) = px * fontsize; @@ -572,9 +573,13 @@ void QCBUILTIN PF_CL_drawcharacter (progfuncs_t *prinst, struct globalvars_s *pr return; } + //no control chars. use quake ones if so + if (chara < 32 && chara != '\t') + chara |= 0xe000; + Font_BeginScaledString(font_conchar, pos[0], pos[1], &x, &y); Font_ForceColour(rgb[0], rgb[1], rgb[2], alpha); - Font_DrawScaleChar(x, y, size[0], size[1], CON_WHITEMASK | /*0xe000|*/(chara&0xff)); + Font_DrawScaleChar(x, y, size[0], size[1], CON_WHITEMASK | /*0xe000|*/chara); Font_InvalidateColour(); Font_EndString(font_conchar); @@ -590,6 +595,7 @@ void QCBUILTIN PF_CL_drawrawstring (progfuncs_t *prinst, struct globalvars_s *pr float alpha = G_FLOAT(OFS_PARM4); // float flag = G_FLOAT(OFS_PARM5); float x, y; + unsigned int c; if (!text) { @@ -602,7 +608,7 @@ void QCBUILTIN PF_CL_drawrawstring (progfuncs_t *prinst, struct globalvars_s *pr y = pos[1]; Font_ForceColour(rgb[0], rgb[1], rgb[2], alpha); - if (mp_globs.drawfontscale) + if (mp_globs.drawfontscale && !prinst->parms->user) { size[0] *= mp_globs.drawfontscale[0]; size[1] *= mp_globs.drawfontscale[1]; @@ -611,7 +617,12 @@ void QCBUILTIN PF_CL_drawrawstring (progfuncs_t *prinst, struct globalvars_s *pr { //FIXME: which charset is this meant to be using? //quakes? 8859-1? utf8? some weird hacky mixture? - x = Font_DrawScaleChar(x, y, size[0], size[1], CON_WHITEMASK|/*0xe000|*/(*text++&0xff)); + c = *text++&0xff; + if ((c&0x7f) < 32) + c |= 0xe000; //if its a control char, just use the quake range instead. + else if (c & 0x80) + c |= 0xe000; //if its a high char, just use the quake range instead. we could colour it, but why bother + x = Font_DrawScaleChar(x, y, size[0], size[1], CON_WHITEMASK|/*0xe000|*/c); } Font_InvalidateColour(); Font_EndString(font_conchar); @@ -704,6 +715,7 @@ void QCBUILTIN PF_mod (progfuncs_t *prinst, struct globalvars_s *pr_globals) if (b == 0) { Con_Printf("mod by zero\n"); + *prinst->pr_trace = 1; G_FLOAT(OFS_RETURN) = 0; } else @@ -741,16 +753,25 @@ static void QCBUILTIN PF_menu_cvar (progfuncs_t *prinst, struct globalvars_s *pr char *str; str = PR_GetStringOfs(prinst, OFS_PARM0); - str = RemapCvarNameFromDPToFTE(str); - var = Cvar_Get(str, "", 0, "menu cvars"); - if (var) - { - if (var->latched_string) - G_FLOAT(OFS_RETURN) = atof(var->latched_string); else - G_FLOAT(OFS_RETURN) = var->value; - } + + if (!strcmp(str, "vid_conwidth")) + G_FLOAT(OFS_RETURN) = vid.width; + else if (!strcmp(str, "vid_conheight")) + G_FLOAT(OFS_RETURN) = vid.height; else - G_FLOAT(OFS_RETURN) = 0; + { + str = RemapCvarNameFromDPToFTE(str); + var = Cvar_Get(str, "", 0, "menu cvars"); + if (var) + { + if (var->latched_string) + G_FLOAT(OFS_RETURN) = atof(var->latched_string); + else + G_FLOAT(OFS_RETURN) = var->value; + } + else + G_FLOAT(OFS_RETURN) = 0; + } } static void QCBUILTIN PF_menu_cvar_set (progfuncs_t *prinst, struct globalvars_s *pr_globals) { @@ -833,6 +854,10 @@ void QCBUILTIN PF_isserver (progfuncs_t *prinst, struct globalvars_s *pr_globals G_FLOAT(OFS_RETURN) = sv.state != ss_dead; #endif } +void QCBUILTIN PF_isdemo (progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + G_FLOAT(OFS_RETURN) = !!cls.demoplayback; +} //float clientstate(void) = #62; void QCBUILTIN PF_clientstate (progfuncs_t *prinst, struct globalvars_s *pr_globals) @@ -914,12 +939,12 @@ void QCBUILTIN PF_cl_setmousetarget (progfuncs_t *prinst, struct globalvars_s *p extern int mouseusedforgui; switch ((int)G_FLOAT(OFS_PARM0)) { - case 1: - mouseusedforgui = true; - break; - case 2: + case 1: //1 is delta-based. mouseusedforgui = false; break; + case 2: //2 is absolute. + mouseusedforgui = true; + break; default: PR_BIError(prinst, "PF_setmousetarget: not a valid destination\n"); } @@ -929,7 +954,7 @@ void QCBUILTIN PF_cl_setmousetarget (progfuncs_t *prinst, struct globalvars_s *p void QCBUILTIN PF_cl_getmousetarget (progfuncs_t *prinst, struct globalvars_s *pr_globals) { extern int mouseusedforgui; - G_FLOAT(OFS_RETURN) = mouseusedforgui?1:2; + G_FLOAT(OFS_RETURN) = mouseusedforgui?2:1; } //vector getmousepos(void) = #66; @@ -1406,6 +1431,37 @@ void QCBUILTIN PF_altstr_set(progfuncs_t *prinst, struct globalvars_s *pr_global } +//string(string serveraddress) crypto_getkeyfp +void QCBUILTIN PF_crypto_getkeyfp(progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + //not supported. + G_INT(OFS_RETURN) = 0; +} +//string(string serveraddress) crypto_getidfp +void QCBUILTIN PF_crypto_getidfp(progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + //not supported. + G_INT(OFS_RETURN) = 0; +} +//string(string serveraddress) crypto_getencryptlevel +void QCBUILTIN PF_crypto_getencryptlevel(progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + //not supported. + G_INT(OFS_RETURN) = 0; +} +//string(float i) crypto_getmykeyfp +void QCBUILTIN PF_crypto_getmykeyfp(progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + //not supported. + G_INT(OFS_RETURN) = 0; +} +//string(float i) crypto_getmyidfp +void QCBUILTIN PF_crypto_getmyidfp(progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + //not supported. + G_INT(OFS_RETURN) = 0; +} + builtin_t menu_builtins[] = { //0 PF_Fixme, @@ -1527,7 +1583,7 @@ builtin_t menu_builtins[] = { PF_infoadd, // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS) PF_infoget, // #227 string(string info, string key) infoget (FTE_STRINGS) PF_strncmp, // #228 float(string s1, string s2, float len) strncmp (FTE_STRINGS) - PF_strncasecmp, // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS) + PF_strcasecmp, // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS) //230 PF_strncasecmp, // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS) skip1 @@ -1543,7 +1599,21 @@ builtin_t menu_builtins[] = { skip10 skip50 //300 - skip100 + skip10 + skip10 + skip10 + skip10 + skip1 + skip1 + skip1 + skip1 + skip1 + skip1 + skip1 + skip1 + skip1 + PF_isdemo, + skip50 //400 skip10 skip10 @@ -1677,7 +1747,7 @@ builtin_t menu_builtins[] = { PF_M_sethostcachemasknumber, PF_M_resorthostcache, PF_M_sethostcachesort, - PF_M_refreshhostcache, + PF_M_refreshhostcache, //600 PF_M_gethostcachenumber, PF_M_gethostcacheindexforkey, PF_M_addwantedhostcachekey, @@ -1692,16 +1762,14 @@ builtin_t menu_builtins[] = { PF_sprintf, /*sprintf*/ skip1 /*not listed in dp*/ skip1 /*not listed in dp*/ - skip1 /*setkeybind*/ + skip1 /*setkeybind*/ //630 skip1 /*getbindmaps*/ skip1 /*setbindmaps*/ - skip1 /*crypto*/ - skip1 /*crypto*/ - skip1 /*crypto*/ - skip1 /*crypto*/ - skip1 /*crypto #637*/ - - + PF_crypto_getkeyfp, /*crypto*/ + PF_crypto_getidfp, /*crypto*/ + PF_crypto_getencryptlevel, /*crypto*/ + PF_crypto_getmykeyfp, /*crypto*/ + PF_crypto_getmyidfp, /*crypto #637*/ }; int menu_numbuiltins = sizeof(menu_builtins)/sizeof(menu_builtins[0]); @@ -1752,6 +1820,10 @@ void MP_Shutdown (void) PR_fclose_progs(menuprogs); search_close_progs(menuprogs, true); +#ifdef CL_MASTER + Master_ClearMasks(); +#endif + CloseProgs(menuprogs); #ifdef TEXTEDITOR Editor_ProgsKilled(menuprogs); @@ -1762,12 +1834,6 @@ void MP_Shutdown (void) m_state = 0; mouseusedforgui = false; - - if (inmenuprogs) //something in the menu caused the problem, so... - { - inmenuprogs = 0; - longjmp(mp_abort, 1); - } } pbool QC_WriteFile(const char *name, void *data, int len); @@ -1797,6 +1863,12 @@ void VARGS Menu_Abort (char *format, ...) } MP_Shutdown(); + + if (inmenuprogs) //something in the menu caused the problem, so... + { + inmenuprogs = 0; + longjmp(mp_abort, 1); + } } void MP_CvarChanged(cvar_t *var) @@ -1858,13 +1930,14 @@ qboolean MP_Init (void) menuprogparms.sv_num_edicts = &num_menu_edicts; menuprogparms.useeditor = NULL;//sorry... QCEditor;//void (*useeditor) (char *filename, int line, int nump, char **parms); + menuprogparms.useeditor = QCEditor;//void (*useeditor) (char *filename, int line, int nump, char **parms); menutime = Sys_DoubleTime(); if (!menuprogs) { Con_DPrintf("Initializing menu.dat\n"); menuprogs = InitProgs(&menuprogparms); - PR_Configure(menuprogs, -1, 1); + PR_Configure(menuprogs, 64*1024*1024, 1); if (PR_LoadProgs(menuprogs, "menu.dat", 10020, NULL, 0) < 0) //no per-progs builtins. { //failed to load or something @@ -1886,11 +1959,8 @@ qboolean MP_Init (void) if (mp_time) *mp_time = Sys_DoubleTime(); -#ifdef warningmsg -#pragma warningmsg("disabled until csqc gets forked or some such") -#endif - //mp_globs.drawfont = (float*)PR_FindGlobal(menuprogs, "drawfont", 0, NULL); - //mp_globs.drawfontscale = (float*)PR_FindGlobal(menuprogs, "drawfontscale", 0, NULL); + mp_globs.drawfont = (float*)PR_FindGlobal(menuprogs, "drawfont", 0, NULL); + mp_globs.drawfontscale = (float*)PR_FindGlobal(menuprogs, "drawfontscale", 0, NULL); menuentsize = PR_InitEnts(menuprogs, 8192); @@ -1971,6 +2041,12 @@ void MP_Draw(void) void MP_Keydown(int key, int unicode) { extern qboolean keydown[K_MAX]; + +#ifdef TEXTEDITOR + if (editormodal) + return; +#endif + if (setjmp(mp_abort)) return; @@ -2008,6 +2084,11 @@ void MP_Keydown(int key, int unicode) void MP_Keyup(int key, int unicode) { +#ifdef TEXTEDITOR + if (editormodal) + return; +#endif + if (setjmp(mp_abort)) return; @@ -2030,6 +2111,10 @@ qboolean MP_Toggle(void) { if (!menuprogs) return false; +#ifdef TEXTEDITOR + if (editormodal) + return false; +#endif if (setjmp(mp_abort)) return false; diff --git a/engine/client/pr_skelobj.c b/engine/client/pr_skelobj.c index 5cbd26d2..674c1a34 100644 --- a/engine/client/pr_skelobj.c +++ b/engine/client/pr_skelobj.c @@ -21,6 +21,18 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. this file deals with qc builtins to apply custom skeletal blending (skeletal objects extension), as well as the logic required to perform realtime ragdoll, if I ever implement that. */ +/* +skeletal objects are just a set of bone poses. +they are separate from the entity they are attached to, and must be created/destroyed separately. +typically the bones are all stored relative to their parent. +qc must use skel_build to copy animation data from the file format into the skeletal object for rendering, but can build different bones using different animations or can override explicit bones. + +ragdoll file is a description of the joints in the ragdoll. +a skeletal object, built from a doll instead of a model, has a series of physics objects created at key points (ie: not face). +these objects are absolute +qc must build the skeletal object still, which fills the skeletal object from the physics objects instead of animation data, for bones that have solid objects. +*/ + #include "quakedef.h" #if defined(CSQC_DAT) || !defined(CLIENTONLY) @@ -36,21 +48,25 @@ this file deals with qc builtins to apply custom skeletal blending (skeletal obj typedef struct doll_s { char *name; + int uses; model_t *model; struct doll_s *next; int numbodies; int numjoints; + int numbones; struct { + char name[32]; int bone; - char *name; - } body[32]; + } *body; + odejointinfo_t *joint; struct { - int type; - int body[2]; - } joint[32]; + //easy lookup table for bone->body. + //most of these will be -1, which means 'import from animation object' + int bodyidx; + } *bone; } doll_t; enum @@ -60,6 +76,8 @@ enum }; typedef struct { + odebody_t odebody; + int ownerent; /*multiple of 12*/ int flags; @@ -77,8 +95,8 @@ typedef struct skelobject_s world_t *world; /*be it ssqc or csqc*/ enum { - SKOT_RELATIVE, - SKOT_ABSOLUTE + SKOT_RELATIVE, //relative to parent + SKOT_ABSOLUTE //relative to model } type; unsigned int numbones; @@ -88,6 +106,8 @@ typedef struct skelobject_s struct skelobject_s *animsource; unsigned int numbodies; body_t *body; + int numjoints; + odejoint_t *joint; doll_t *doll; #endif } skelobject_t; @@ -177,13 +197,37 @@ static void bonematident_toqcvectors(float vx[3], float vy[3], float vz[3], floa static qboolean pendingkill; /*states that there is a skel waiting to be killed*/ #ifdef RAGDOLL -doll_t *rag_loaddoll(model_t *mod, char *fname) +void rag_uninstanciate(skelobject_t *sko); +int rag_finddollbody(doll_t *d, char *bodyname) +{ + int i; + for (i = 0; i < d->numbodies; i++) + { + if (!strcmp(d->body[i].name, bodyname)) + return i; + } + return -1; +} +int rag_finddolljoint(doll_t *d, char *name) +{ + int i; + for (i = 0; i < d->numjoints; i++) + { + if (!strcmp(d->joint[i].name, name)) + return i; + } + return -1; +} +doll_t *rag_loaddoll(model_t *mod, char *fname, int numbones) { doll_t *d; void *fptr = NULL; char *file; int fsize; - int i, j; + int i; + char *cmd; + galiasbone_t *bones; + int errors = 0; for (d = dolllist; d; d = d->next) { @@ -192,49 +236,180 @@ doll_t *rag_loaddoll(model_t *mod, char *fname) return d; } + bones = Mod_GetBoneInfo(mod); + if (!bones) + { + //model not skeletal. + return NULL; + } + fsize = FS_LoadFile(fname, &fptr); if (!fptr) return NULL; + d = malloc(sizeof(*d)); d->next = dolllist; dolllist = d; d->name = strdup(fname); d->model = mod; d->numbodies = 0; + d->body = NULL; d->numjoints = 0; + d->uses = 0; + d->joint = NULL; + d->numbones = numbones; + d->bone = malloc(sizeof(*d->bone) * d->numbones); + for (i = 0; i < d->numbones; i++) + d->bone[i].bodyidx = -1; file = fptr; - while(file) + while(file && *file) { - file = COM_Parse(file); - if (!strcmp(com_token, "body")) + file = Cmd_TokenizeString(file, false, false); + cmd = Cmd_Argv(0); + + if (!stricmp(cmd, "body")) { - file = COM_Parse(file); - d->body[d->numbodies].name = strdup(com_token); - file = COM_Parse(file); - d->body[d->numbodies].bone = Mod_TagNumForName(d->model, com_token); - d->numbodies++; - } - else if (!strcmp(com_token, "joint")) - { - for (i = 0; i < 2; i++) + int boneidx; + boneidx = Mod_TagNumForName(d->model, Cmd_Argv(2))-1; + if (boneidx >= 0) { - file = COM_Parse(file); - d->joint[d->numjoints].body[i] = 0; - for (j = 0; j < d->numbodies; j++) - { - if (!strcmp(d->body[j].name, com_token)) - { - d->joint[d->numjoints].body[i] = j; - break; - } - } + d->body = realloc(d->body, sizeof(*d->body)*(d->numbodies+1)); + Q_strncpyz(d->body[d->numbodies].name, Cmd_Argv(1), sizeof(d->body[d->numbodies].name)); + d->bone[boneidx].bodyidx = d->numbodies; + d->body[d->numbodies].bone = boneidx; + d->numbodies++; } - d->numjoints++; + else if (!errors++) + Con_Printf("Unable to create body \"%s\" because bone \"%s\" does not exist in \"%s\"\n", Cmd_Argv(1), Cmd_Argv(2), mod->name); + } + else if (!stricmp(cmd, "joint")) + { + odejointinfo_t *joint; + char *name; + d->joint = realloc(d->joint, sizeof(*d->joint)*(d->numjoints+1)); + joint = &d->joint[d->numjoints]; + memset(joint, 0, sizeof(*joint)); + Q_strncpyz(joint->name, Cmd_Argv(1), sizeof(joint->name)); + name = Cmd_Argv(2); + joint->body1 = *name?rag_finddollbody(d, name):-1; + if (*name && joint->body1 < 0 && !errors++) + { + Con_Printf("Joint \"%s\" joints invalid body \"%s\" in \"%s\"\n", joint->name, name, fname); + continue; + } + name = Cmd_Argv(3); + joint->body2 = *name?rag_finddollbody(d, name):-1; + if (*name && (joint->body2 < 0 || joint->body2 == joint->body1) && !errors++) + { + if (joint->body2 == joint->body1) + Con_Printf("Joint \"%s\" joints body \"%s\" to itself in \"%s\"\n", joint->name, name, fname); + else + Con_Printf("Joint \"%s\" joints invalid body \"%s\" in \"%s\"\n", joint->name, name, fname); + continue; + } + joint->orgmatrix[0] = 1; + joint->orgmatrix[4] = 1; + joint->orgmatrix[8] = 1; + joint->bonepivot = d->body[(joint->body2 >= 0)?joint->body2:joint->body1].bone; //default the pivot object to the bone of the second object. + + joint->ERP = 0.4; + joint->ERP2 = 0.4; + joint->CFM = 0.1; + joint->CFM2 = 0.1; + + if (joint->body1 >= 0 || joint->body2 >= 0) + d->numjoints++; + else if (!errors++) + Con_Printf("Joint property \"%s\" not recognised in \"%s\"\n", joint->name, fname); + } + else if (!stricmp(cmd, "setjoint")) + { + int j = rag_finddolljoint(d, Cmd_Argv(1)); + if (j >= 0) + { + odejointinfo_t *joint = &d->joint[j]; + char *prop = Cmd_Argv(2); + char *val = Cmd_Argv(3); + if (!stricmp(prop, "type")) + { + if (!stricmp(val, "fixed")) + joint->type = JOINTTYPE_FIXED; + else if (!stricmp(val, "point")) + joint->type = JOINTTYPE_POINT; + else if (!stricmp(val, "hinge")) + joint->type = JOINTTYPE_HINGE; + else if (!stricmp(val, "slider")) + joint->type = JOINTTYPE_SLIDER; + else if (!stricmp(val, "universal")) + joint->type = JOINTTYPE_UNIVERSAL; + else if (!stricmp(val, "hinge2")) + joint->type = JOINTTYPE_HINGE2; + } + else if (!stricmp(prop, "ERP")) + joint->ERP = atof(val); + else if (!stricmp(prop, "ERP2")) + joint->ERP2 = atof(val); + else if (!stricmp(prop, "CFM")) + joint->CFM = atof(val); + else if (!stricmp(prop, "CFM2")) + joint->CFM2 = atof(val); + else if (!stricmp(prop, "FMax")) + joint->FMax = atof(val); + else if (!stricmp(prop, "FMax2")) + joint->FMax2 = atof(val); + else if (!stricmp(prop, "HiStop")) + joint->HiStop = atof(val); + else if (!stricmp(prop, "HiStop2")) + joint->HiStop2 = atof(val); + else if (!stricmp(prop, "LoStop")) + joint->LoStop = atof(val); + else if (!stricmp(prop, "LoStop2")) + joint->LoStop2 = atof(val); + else if (!stricmp(prop, "origin") || !stricmp(prop, "pivot")) + { + //the origin is specified in base-frame model space + //we need to make it relative to the joint's bodies + float omat[12] = { 1, 0, 0, atoi(Cmd_Argv(3)), + 0, 1, 0, atoi(Cmd_Argv(4)), + 0, 0, 1, atoi(Cmd_Argv(5))}; + char *bone = Cmd_Argv(6); + i = Mod_TagNumForName(d->model, Cmd_Argv(2))-1; + joint->bonepivot = i; + Matrix3x4_Multiply(omat, bones[i].inverse, joint->orgmatrix); + } + else if (!errors++) + Con_Printf("Joint property \"%s\" not recognised in \"%s\"\n", prop, fname); + } + else if (!errors++) + Con_Printf("Joint \"%s\" not yet defined in \"%s\"\n", Cmd_Argv(1), fname); } } FS_FreeFile(fptr); return d; } +void rag_freedoll(doll_t *doll) +{ + free(doll->bone); + free(doll->body); + free(doll->joint); + free(doll); +} + +void rag_flushdolls(void) +{ + doll_t *d, **link; + for (link = &dolllist; *link; ) + { + d = *link; + if (!d->uses) + { + *link = d->next; + rag_freedoll(d); + } + else + link = &(*link)->next; + } +} void skel_integrate(progfuncs_t *prinst, skelobject_t *sko, skelobject_t *skelobjsrc, float ft, float mmat[12]) { @@ -364,6 +539,7 @@ void skel_reset(progfuncs_t *prinst) { if (skelobjects[i].world = prinst->parms->user) { + rag_uninstanciate(&skelobjects[i]); skelobjects[i].numbones = 0; skelobjects[i].inuse = false; skelobjects[i].bonematrix = NULL; @@ -372,6 +548,7 @@ void skel_reset(progfuncs_t *prinst) while (numskelobjectsused && !skelobjects[numskelobjectsused-1].inuse) numskelobjectsused--; + rag_flushdolls(); } /*deletes any skeletons marked for deletion*/ @@ -385,7 +562,10 @@ void skel_dodelete(progfuncs_t *prinst) for (skelidx = 0; skelidx < numskelobjectsused; skelidx++) { if (skelobjects[skelidx].inuse == 2) + { + rag_uninstanciate(&skelobjects[skelidx]); skelobjects[skelidx].inuse = 0; + } } while (numskelobjectsused && !skelobjects[numskelobjectsused-1].inuse) @@ -418,7 +598,7 @@ skelobject_t *skel_get(progfuncs_t *prinst, int skelidx, int bonecount) skelobjects[skelidx].bonematrix = (float*)PR_AddString(prinst, "", sizeof(float)*12*bonecount); } skelobjects[skelidx].world = prinst->parms->user; - if (numskelobjectsused == skelidx) + if (numskelobjectsused <= skelidx) numskelobjectsused = skelidx + 1; skelobjects[skelidx].model = NULL; skelobjects[skelidx].inuse = 1; @@ -459,59 +639,223 @@ void QCBUILTIN PF_skel_mmap(progfuncs_t *prinst, struct globalvars_s *pr_globals if (!sko || sko->world != prinst->parms->user) G_INT(OFS_RETURN) = 0; else - G_INT(OFS_RETURN) = PR_SetString(prinst, (void*)sko->bonematrix); + G_INT(OFS_RETURN) = (char*)sko->bonematrix - prinst->stringtable; } +//may not poke the skeletal object bone data. +void rag_uninstanciate(skelobject_t *sko) +{ + int i; + if (!sko->doll) + return; + + for (i = 0; i < sko->numbodies; i++) + { + World_ODE_RagDestroyBody(sko->world, &sko->body[i].odebody); + } + free(sko->body); + sko->body = NULL; + sko->numbodies = 0; + + for (i = 0; i < sko->numjoints; i++) + { + World_ODE_RagDestroyJoint(sko->world, &sko->joint[i]); + } + free(sko->joint); + sko->joint = NULL; + sko->numjoints = 0; + + sko->doll->uses--; + sko->doll = NULL; +} +qboolean rag_instanciate(skelobject_t *sko, doll_t *doll, float *emat, wedict_t *ent) +{ + int i; + vec3_t org, porg; + float *bmat; + float bodymat[12], worldmat[12]; + vec3_t aaa2[3]; + galiasbone_t *bones = Mod_GetBoneInfo(sko->model); + int bone; + odebody_t *body1, *body2; + odejointinfo_t *j; + sko->numbodies = doll->numbodies; + sko->body = malloc(sizeof(*sko->body) * sko->numbodies); + sko->doll = doll; + doll->uses++; + for (i = 0; i < sko->numbodies; i++) + { + memset(&sko->body[i], 0, sizeof(sko->body[i])); + + bone = doll->body[i].bone; + bmat = sko->bonematrix + bone*12; + R_ConcatTransforms((void*)emat, (void*)bmat, (void*)bodymat); + if (!World_ODE_RagCreateBody(sko->world, &sko->body[i].odebody, bodymat, ent)) + return false; + } + sko->numjoints = doll->numjoints; + sko->joint = malloc(sizeof(*sko->joint) * sko->numjoints); + memset(sko->joint, 0, sizeof(*sko->joint) * sko->numjoints); + for(i = 0; i < sko->numjoints; i++) + { + j = &doll->joint[i]; + body1 = j->body1>=0?&sko->body[j->body1].odebody:NULL; + body2 = j->body2>=0?&sko->body[j->body2].odebody:NULL; + + bone = j->bonepivot; + bmat = sko->bonematrix + bone*12; + + R_ConcatTransforms(bmat, j->orgmatrix, bodymat); + R_ConcatTransforms((void*)emat, (void*)bodymat, (void*)worldmat); + aaa2[0][0] = worldmat[3]; + aaa2[0][1] = worldmat[3+4]; + aaa2[0][2] = worldmat[3+8]; +// P_RunParticleEffectTypeString(aaa2[0], vec3_origin, 1, "te_spike"); + + aaa2[1][0] = 1; + aaa2[1][1] = 0; + aaa2[1][2] = 0; + + aaa2[2][0] = 0; + aaa2[2][1] = 1; + aaa2[2][2] = 0; + +// VectorCopy(j->offset, aaa2[0]); //fixme: transform these vectors into world space, and transform to match the current positions of the bones. +// VectorCopy(j->axis, aaa2[1]); +// VectorCopy(j->axis2, aaa2[2]); + World_ODE_RagCreateJoint(sko->world, &sko->joint[i], j, body1, body2, aaa2); + } + return true; +} +void rag_derive(skelobject_t *sko, skelobject_t *asko, float *emat) +{ + doll_t *doll = sko->doll; + float *bmat = sko->bonematrix; + float *amat = asko?asko->bonematrix:NULL; + galiasbone_t *bones = Mod_GetBoneInfo(sko->model); + int i; + float invemat[12]; + float bodymat[12]; + + Matrix3x4_Invert(emat, invemat); + + for (i = 0; i < doll->numbones; i++) + { + if (doll->bone[i].bodyidx >= 0) + { + World_ODE_RagMatrixFromBody(sko->world, &sko->body[doll->bone[i].bodyidx].odebody, bodymat); + //that body matrix is in world space, so transform to model space for our result + R_ConcatTransforms((void*)invemat, (void*)bodymat, (void*)((float*)bmat+i*12)); + } + else if (amat) + { + //this bone has no joint object, use the anim sko's relative pose info instead + if (bones[i].parent >= 0) + R_ConcatTransforms((void*)(bmat + bones[i].parent*12), (void*)((float*)amat+i*12), (void*)((float*)bmat+i*12)); + else + memcpy((void*)((float*)bmat+i*12), (void*)((float*)amat+i*12), sizeof(float)*12); + } + } +} + +//update a skeletal object to track its ragdoll/apply a ragdoll to a skeletal object. void QCBUILTIN PF_skel_ragedit(progfuncs_t *prinst, struct globalvars_s *pr_globals) { + //do we want to be able to generate a ragdoll object with this function too? #ifdef RAGDOLL - int skelidx = G_FLOAT(OFS_PARM0); - char *skelname = PR_GetStringOfs(prinst, OFS_PARM1); + wedict_t *wed = (wedict_t*)G_EDICT(prinst, OFS_PARM0); + char *ragname = PR_GetStringOfs(prinst, OFS_PARM1); int parentskel = G_FLOAT(OFS_PARM2); - float *entorg = G_VECTOR(OFS_PARM3); - float *forward = G_VECTOR(OFS_PARM4); - float *right = G_VECTOR(OFS_PARM5); - float *up = G_VECTOR(OFS_PARM6); + int skelidx = wed->xv->skeletonindex; skelobject_t *sko, *psko; doll_t *doll; int i; float emat[12]; + extern cvar_t temp1; - bonemat_fromqcvectors(emat, forward, right, up, entorg); + { + vec3_t d[3], a; + //fixme: respond to renderflags&USEAXIS? scale? + a[0] = wed->v->angles[0] * -1; /*mod_alias bug*/ + a[1] = wed->v->angles[1]; + a[2] = wed->v->angles[2]; + AngleVectors(a, d[0], d[1], d[2]); + bonemat_fromqcvectors(emat, d[0], d[1], d[2], wed->v->origin); + skelidx = wed->xv->skeletonindex; + } G_FLOAT(OFS_RETURN) = 0; - sko = skel_get(prinst, skelidx, 0); - if (!sko) + //the parent skeletal object must be relative, if specified. + psko = skel_get(prinst, parentskel, 0); + if (psko && psko->type != SKOT_RELATIVE) return; - if (*skelname) + sko = skel_get(prinst, skelidx, 0); + if (!sko) { - doll = rag_loaddoll(sko->model, skelname); + Con_DPrintf("PF_skel_ragedit: invalid skeletal object\n"); + return; + } + + if (!sko->world->ode.ode) + { + Con_DPrintf("PF_skel_ragedit: ODE not enabled\n"); + return; + } + + if (*ragname) + { + if (sko->doll && !strcmp(sko->doll->name, ragname)) + doll = sko->doll; + else + doll = rag_loaddoll(sko->model, ragname, sko->numbones); if (!doll) + { + Con_DPrintf("PF_skel_ragedit: invalid doll\n"); return; + } } else { /*no doll name makes it revert to a normal skeleton*/ - sko->doll = NULL; + rag_uninstanciate(sko); G_FLOAT(OFS_RETURN) = 1; return; } - if (sko->doll != doll) + if (sko->type != SKOT_ABSOLUTE) { - sko->doll = doll; - free(sko->body); - sko->numbodies = doll->numbodies; - sko->body = malloc(sko->numbodies * sizeof(*sko->body)); - memset(sko->body, 0, sko->numbodies * sizeof(*sko->body)); -// for (i = 0; i < sko->numbodies; i++) -// sko->body[i].jointo = doll->body[i].bone * 12; + float tmp[12]; + float *bmat = sko->bonematrix; + galiasbone_t *bones = Mod_GetBoneInfo(sko->model); + for (i = 0; i < sko->numbones; i++) + { + //bones without parents are technically already absolute + if (bones[i].parent >= 0) + { + //write to a tmp to avoid premature clobbering + R_ConcatTransforms((void*)(bmat + bones[i].parent*12), (void*)((float*)bmat+i*12), (void*)tmp); + memcpy((void*)(bmat+i*12), tmp, sizeof(tmp)); + } + } + sko->type = SKOT_ABSOLUTE; } - psko = skel_get(prinst, parentskel, 0); - skel_integrate(prinst, sko, psko, host_frametime, emat); + if (sko->doll != doll || temp1.ival) + { + rag_uninstanciate(sko); + if (!rag_instanciate(sko, doll, emat, wed)) + { + rag_uninstanciate(sko); + Con_DPrintf("PF_skel_ragedit: unable to instanciate objects\n"); + G_FLOAT(OFS_RETURN) = 0; + return; + } + } + + rag_derive(sko, psko, emat); +// skel_integrate(prinst, sko, psko, host_frametime, emat); G_FLOAT(OFS_RETURN) = 1; #endif @@ -527,6 +871,7 @@ void QCBUILTIN PF_skel_create (progfuncs_t *prinst, struct globalvars_s *pr_glob model_t *model; int midx; int type; + int i; midx = G_FLOAT(OFS_PARM0); type = (*prinst->callargc > 1)?G_FLOAT(OFS_PARM1):SKOT_RELATIVE; @@ -554,6 +899,15 @@ void QCBUILTIN PF_skel_create (progfuncs_t *prinst, struct globalvars_s *pr_glob skelobj->model = model; skelobj->type = type; + /* + for (i = 0; i < numbones; i++) + { + galiasbone_t *bones = Mod_GetBoneInfo(skelobj->model); + Matrix3x4_Invert_Simple(bones[i].inverse, skelobj->bonematrix + i*12); + } + skelobj->type = SKOT_ABSOLUTE; + */ + G_FLOAT(OFS_RETURN) = (skelobj - skelobjects) + 1; } @@ -605,6 +959,16 @@ void QCBUILTIN PF_skel_build(progfuncs_t *prinst, struct globalvars_s *pr_global if (firstbone < 0) firstbone = 0; + if (skelobj->type != SKOT_RELATIVE) + { + if (firstbone > 0 || lastbone < skelobj->numbones || retainfrac) + { + Con_Printf("skel_build on non-relative skeleton\n"); + return; + } + skelobj->type = SKOT_RELATIVE; //entire model will get replaced, convert it. + } + if (retainfrac == 0) { /*replace everything*/ diff --git a/engine/client/quakedef.h b/engine/client/quakedef.h index 1fb4e514..3a71e02c 100644 --- a/engine/client/quakedef.h +++ b/engine/client/quakedef.h @@ -218,7 +218,8 @@ int VARGS linuxlike_vsnprintf(char *buffer, int size, const char *format, va_lis typedef struct quakeparms_s { - char *basedir; + char *basedir; //working directory + char *binarydir; //exe directory int argc; const char **argv; void *membase; @@ -240,6 +241,7 @@ extern qboolean noclip_anglehack; extern quakeparms_t host_parms; extern cvar_t fs_gamename; +extern cvar_t fs_gamedownload; extern cvar_t com_protocolname; extern cvar_t com_modname; extern cvar_t sys_ticrate; diff --git a/engine/client/r_2d.c b/engine/client/r_2d.c index 00ed735d..7bef310b 100644 --- a/engine/client/r_2d.c +++ b/engine/client/r_2d.c @@ -4,6 +4,7 @@ #include "gl_draw.h" texid_t missing_texture; +texid_t missing_texture_gloss; texid_t translate_texture; shader_t *translate_shader; @@ -17,7 +18,9 @@ static mpic_t *draw_backtile; static shader_t *shader_draw_fill, *shader_draw_fill_trans; mpic_t *draw_disc; -shader_t *shader_brighten; +shader_t *shader_contrastup; +shader_t *shader_contrastdown; +shader_t *shader_brightness; shader_t *shader_polyblend; shader_t *shader_menutint; @@ -31,7 +34,7 @@ unsigned int r2d_be_flags; extern cvar_t scr_conalpha; extern cvar_t gl_conback; extern cvar_t gl_font; -extern cvar_t gl_contrast; +extern cvar_t gl_contrast, gl_brightness; extern cvar_t gl_screenangle; extern cvar_t vid_conautoscale; extern cvar_t vid_conheight; @@ -124,6 +127,8 @@ Image loading code must be ready for use at this point. */ void R2D_Init(void) { + unsigned int nogloss[4*4]; + int i; conback = NULL; Shader_Init(); @@ -144,7 +149,10 @@ void R2D_Init(void) #pragma warningmsg("Fixme: move conwidth handling into here") #endif + for (i = 0; i < 4*4; i++) + nogloss[i] = LittleLong(0xff101010); missing_texture = R_LoadTexture8("no_texture", 16, 16, (unsigned char*)r_notexture_mip + r_notexture_mip->offsets[0], IF_NOALPHA|IF_NOGAMMA, 0); + missing_texture_gloss = R_LoadTexture("no_texture_gloss", 4, 4, TF_RGBA32, (unsigned char*)nogloss, IF_NOGAMMA); translate_texture = r_nulltex; ch_int_texture = r_nulltex; @@ -182,10 +190,11 @@ void R2D_Init(void) "blendfunc blend\n" "}\n" "}\n"); - shader_brighten = R_RegisterShader("constrastshader", + shader_contrastup = R_RegisterShader("constrastupshader", "{\n" "program defaultfill\n" "{\n" + "nodepthtest\n" "map $whiteimage\n" "blendfunc gl_dst_color gl_one\n" "rgbgen vertex\n" @@ -193,6 +202,30 @@ void R2D_Init(void) "}\n" "}\n" ); + shader_contrastdown = R_RegisterShader("constrastdownshader", + "{\n" + "program defaultfill\n" + "{\n" + "nodepthtest\n" + "map $whiteimage\n" + "blendfunc gl_dst_color gl_zero\n" + "rgbgen vertex\n" + "alphagen vertex\n" + "}\n" + "}\n" + ); + shader_brightness = R_RegisterShader("brightnessshader", + "{\n" + "program defaultfill\n" + "{\n" + "nodepthtest\n" + "map $whiteimage\n" + "blendfunc gl_one gl_one\n" + "rgbgen vertex\n" + "alphagen vertex\n" + "}\n" + "}\n" + ); shader_polyblend = R_RegisterShader("polyblendshader", "{\n" "program defaultfill\n" @@ -520,7 +553,9 @@ void R2D_ConsoleBackground (int firstline, int lastline, qboolean forceopaque) void R2D_EditorBackground (void) { - R2D_ScalePic(0, 0, vid.width, vid.height, conback); + R2D_ImageColours(0, 0, 0, 1); + R2D_FillBlock(0, 0, vid.width, vid.height); +// R2D_ScalePic(0, 0, vid.width, vid.height, conback); } /* @@ -760,7 +795,7 @@ void R2D_BrightenScreen (void) RSpeedMark(); - if (gl_contrast.value <= 1.0) + if (gl_contrast.value != 1.0 && gl_brightness.value != 0) return; if (r_refdef.flags & Q2RDF_NOWORLDMODEL) @@ -772,11 +807,27 @@ void R2D_BrightenScreen (void) while (f > 1) { if (f >= 2) + { R2D_ImageColours (1, 1, 1, 1); + f *= 0.5; + } else + { R2D_ImageColours (f - 1, f - 1, f - 1, 1); - R2D_ScalePic(0, 0, vid.width, vid.height, shader_brighten); - f *= 0.5; + f = 1; + } + R2D_ScalePic(0, 0, vid.width, vid.height, shader_contrastup); + } + if (f < 1) + { + R2D_ImageColours (f, f, f, 1); + R2D_ScalePic(0, 0, vid.width, vid.height, shader_contrastdown); + } + + if (gl_brightness.value) + { + R2D_ImageColours (gl_brightness.value, gl_brightness.value, gl_brightness.value, 1); + R2D_ScalePic(0, 0, vid.width, vid.height, shader_brightness); } R2D_ImageColours (1, 1, 1, 1); diff --git a/engine/client/r_partset.c b/engine/client/r_partset.c index 28a13ea4..d5e5f231 100644 --- a/engine/client/r_partset.c +++ b/engine/client/r_partset.c @@ -1592,9 +1592,9 @@ char *particle_set_high = "float f;\n" "nst = scoord.xy / scoord.w;\n" "nst = (1.0 + nst)/2.0;\n" -"f = 1 - length(tcoord);\n" -// f = 1 - tcoord*tcoord; -"if (f < 0) discard;\n" +"f = 1.0 - length(tcoord);\n" +// f = 1.0 - tcoord*tcoord; +"if (f < 0.0) discard;\n" "f *= alph;\n" "gl_FragColor = texture2D(s_t0, nst - tcoord*f);\n" "}\n" diff --git a/engine/client/r_surf.c b/engine/client/r_surf.c index 43cdf668..3f6d5cc8 100644 --- a/engine/client/r_surf.c +++ b/engine/client/r_surf.c @@ -1418,6 +1418,14 @@ static qbyte *R_MarkLeafSurfaces_Q1 (void) } #endif +/* +static qbyte *Surf_MaskVis(qbyte *src, qbyte *dest) +{ + int i; + if (cl.worldmodel->leafs[i].ma +} +*/ +qbyte *frustumvis; /* ================ R_RecursiveWorldNode @@ -1456,6 +1464,9 @@ start: { pleaf = (mleaf_t *)node; + c = pleaf - cl.worldmodel->leafs; + frustumvis[c>>3] |= 1<<(c&7); + mark = pleaf->firstmarksurface; c = pleaf->nummarksurfaces; @@ -2019,6 +2030,9 @@ void Surf_SetupFrame(void) case Q1CONTENTS_SKY: r_viewcontents |= FTECONTENTS_SKY; break; + case Q1CONTENTS_SOLID: + r_viewcontents |= FTECONTENTS_SOLID; + break; } } } @@ -2176,7 +2190,9 @@ R_DrawWorld void Surf_DrawWorld (void) { - qbyte *vis; + //surfvis vs entvis - the key difference is that surfvis is surfaces while entvis is volume. though surfvis should be frustum culled also for lighting. entvis doesn't care. + qbyte *surfvis, *entvis; + qbyte frustumvis_[MAX_MAP_LEAFS/8]; RSpeedLocals(); if (r_refdef.flags & Q2RDF_NOWORLDMODEL) @@ -2221,14 +2237,14 @@ void Surf_DrawWorld (void) #ifdef Q3BSPS if (currententity->model->fromgame == fg_quake3) { - vis = R_MarkLeaves_Q3 (); + entvis = surfvis = R_MarkLeaves_Q3 (); Surf_RecursiveQ3WorldNode (cl.worldmodel->nodes, (1<nodes); } @@ -2238,14 +2254,14 @@ void Surf_DrawWorld (void) #ifdef MAP_PROC if (cl.worldmodel->fromgame == fg_doom3) { - vis = D3_CalcVis(cl.worldmodel, r_origin); + entvis = surfvis = D3_CalcVis(cl.worldmodel, r_origin); } else #endif #ifdef MAP_DOOM if (currentmodel->fromgame == fg_doom) { - vis = NULL; + entvis = surfvis = NULL; GLR_DoomWorld(); } else @@ -2253,37 +2269,42 @@ void Surf_DrawWorld (void) #ifdef TERRAIN if (currentmodel->type == mod_heightmap) { - vis = NULL; + entvis = surfvis = NULL; } else #endif { //extern cvar_t temp1; // if (0)//temp1.value) -// vis = R_MarkLeafSurfaces_Q1(); +// entvis = surfvis = R_MarkLeafSurfaces_Q1(); // else { - vis = R_MarkLeaves_Q1 (); + entvis = R_MarkLeaves_Q1 (); if (!(r_novis.ival & 2)) VectorCopy (r_origin, modelorg); + frustumvis = frustumvis_; + memset(frustumvis, 0, (cl.worldmodel->numleafs + 7)>>3); + if (r_refdef.useperspective) Surf_RecursiveWorldNode (cl.worldmodel->nodes, 0x1f); else Surf_OrthoRecursiveWorldNode (cl.worldmodel->nodes, 0x1f); + surfvis = frustumvis; } } if (!(r_refdef.flags & Q2RDF_NOWORLDMODEL)) { - CL_LinkStaticEntities(vis); + // CL_LinkStaticEntities(entvis); TRACE(("dbg: calling R_DrawParticles\n")); - P_DrawParticles (); + if (!r_refdef.recurse) + P_DrawParticles (); } RSpeedEnd(RSPEED_WORLDNODE); TRACE(("dbg: calling BE_DrawWorld\n")); - BE_DrawWorld(true, vis); + BE_DrawWorld(true, surfvis); /*FIXME: move this away*/ if (cl.worldmodel->fromgame == fg_quake || cl.worldmodel->fromgame == fg_halflife) @@ -2486,6 +2507,163 @@ int Surf_NewExternalLightmaps(int count, char *filepattern, qboolean deluxe) return first; } +void Surf_BuildModelLightmaps (model_t *m) +{ + int i, t; + int shift; + msurface_t *surf; + batch_t *batch; + int sortid; + int ptype; + int newfirst; + + if (!lightmap_bytes) + return; + +#ifdef TERRAIN + if (m->terrain) + Terr_PurgeTerrainModel(m, true, false); +#endif + + if (m->type != mod_brush) + return; + + if (!m->lightmaps.count) + return; + if (m->needload) + return; + + currentmodel = m; + shift = Surf_LightmapShift(currentmodel); + + if (*m->name == '*' && m->fromgame == fg_quake3) //FIXME: should be all bsp formats + newfirst = cl.model_precache[1]->lightmaps.first; + else + { + if (!m->lightdata && m->lightmaps.count && m->fromgame == fg_quake3) + { + char pattern[MAX_QPATH]; + COM_StripAllExtensions(m->name, pattern, sizeof(pattern)); + Q_strncatz(pattern, "/lm_%04u.tga", sizeof(pattern)); + newfirst = Surf_NewExternalLightmaps(m->lightmaps.count, pattern, m->lightmaps.deluxemapping); + } + else + newfirst = Surf_NewLightmaps(m->lightmaps.count, m->lightmaps.width, m->lightmaps.height, m->lightmaps.deluxemapping); + } + + //fixup batch lightmaps + for (sortid = 0; sortid < SHADER_SORT_COUNT; sortid++) + for (batch = m->batches[sortid]; batch != NULL; batch = batch->next) + { + for (i = 0; i < MAXLIGHTMAPS; i++) + { + if (batch->lightmap[i] < 0) + continue; + batch->lightmap[i] = batch->lightmap[i] - m->lightmaps.first + newfirst; + } + } + + + /*particle emision based upon texture. this is lazy code*/ + if (m == cl.worldmodel) + { + for (t = m->numtextures-1; t >= 0; t--) + { + ptype = P_FindParticleType(va("tex_%s", m->textures[t]->name)); + + if (ptype != P_INVALID) + { + for (i=0; inummodelsurfaces; i++) + { + surf = m->surfaces + i + m->firstmodelsurface; + if (surf->texinfo->texture == m->textures[t]) + P_EmitSkyEffectTris(m, surf, ptype); + } + } + } + } + + + if (m->fromgame == fg_quake3) + { + int j; + unsigned char *src; + unsigned char *dst; + for (i = 0; i < m->lightmaps.count; i++) + { + if (lightmap[newfirst+i]->external) + continue; + + dst = lightmap[newfirst+i]->lightmaps; + src = m->lightdata + i*m->lightmaps.width*m->lightmaps.height*3; + if (lightmap_bytes == 4 && m->lightdata) + { + if (lightmap_bgra) + { + for (j = 0; j < m->lightmaps.width*m->lightmaps.height; j++, dst += 4, src += 3) + { + dst[0] = src[2]; + dst[1] = src[1]; + dst[2] = src[0]; + dst[3] = 255; + } + } + else + { + for (j = 0; j < m->lightmaps.width*m->lightmaps.height; j++, dst += 4, src += 3) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + dst[3] = 255; + } + } + } + } + } + else + { + int j; + lightmapinfo_t *lm, *dlm; + qbyte *deluxemap; + //fixup surface lightmaps, and paint + for (i=0; inummodelsurfaces; i++) + { + surf = m->surfaces + i + m->firstmodelsurface; + for (j = 0; j < 4; j++) + { + if (surf->lightmaptexturenums[j] < m->lightmaps.first) + { + surf->lightmaptexturenums[j] = -1; + continue; + } + surf->lightmaptexturenums[j] = surf->lightmaptexturenums[0] - m->lightmaps.first + newfirst; + + lm = lightmap[surf->lightmaptexturenums[j]]; + if (lm->hasdeluxe) + { + dlm = lightmap[surf->lightmaptexturenums[j]+1]; + deluxemap = dlm->lightmaps + (surf->light_t[j] * dlm->width + surf->light_s[j]) * lightmap_bytes; + } + else + deluxemap = NULL; + + Surf_BuildLightMap (surf, + lm->lightmaps + (surf->light_t[j] * lm->width + surf->light_s[j]) * lightmap_bytes, + deluxemap, + lm->stainmaps + (surf->light_t[j] * lm->width + surf->light_s[j]) * 3, + shift, r_ambient.value*255); + } + } + } + m->lightmaps.first = newfirst; +} + +void Surf_ClearLightmaps(void) +{ + lightmap_bytes = 0; +} + /* ================== GL_BuildLightmaps @@ -2497,14 +2675,8 @@ Groups surfaces into their respective batches (based on the lightmap number). */ void Surf_BuildLightmaps (void) { - int i, j, t; + int i, j; model_t *m; - int shift; - msurface_t *surf; - batch_t *batch; - int sortid; - int ptype; - int newfirst; r_framecount = 1; // no dlightcache @@ -2522,155 +2694,24 @@ void Surf_BuildLightmaps (void) r_oldviewleaf2 = NULL; r_oldviewcluster = -1; r_oldviewcluster2 = -1; + numlightmaps = 0; if (cl.worldmodel->fromgame == fg_doom) return; //no lightmaps. - numlightmaps = 0; - for (j=1 ; jterrain) - Terr_PurgeTerrainModel(m, true, false); -#endif - - if (m->type != mod_brush) - continue; - - if (!m->lightmaps.count) - continue; - if (m->needload) - continue; - - currentmodel = m; - shift = Surf_LightmapShift(currentmodel); - - if (*m->name == '*' && m->fromgame == fg_quake3) //FIXME: should be all bsp formats - newfirst = cl.model_precache[1]->lightmaps.first; - else - { - if (!m->lightdata && m->lightmaps.count) - { - char pattern[MAX_QPATH]; - COM_StripAllExtensions(m->name, pattern, sizeof(pattern)); - Q_strncatz(pattern, "/lm_%04u.tga", sizeof(pattern)); - newfirst = Surf_NewExternalLightmaps(m->lightmaps.count, pattern, m->lightmaps.deluxemapping); - } - else - newfirst = Surf_NewLightmaps(m->lightmaps.count, m->lightmaps.width, m->lightmaps.height, m->lightmaps.deluxemapping); - } - - //fixup batch lightmaps - for (sortid = 0; sortid < SHADER_SORT_COUNT; sortid++) - for (batch = m->batches[sortid]; batch != NULL; batch = batch->next) - { - for (i = 0; i < MAXLIGHTMAPS; i++) - { - if (batch->lightmap[i] < 0) - continue; - batch->lightmap[i] = batch->lightmap[i] - m->lightmaps.first + newfirst; - } - } - - - /*particle emision based upon texture. this is lazy code*/ - if (m == cl.worldmodel) - { - for (t = m->numtextures-1; t >= 0; t--) - { - ptype = P_FindParticleType(va("tex_%s", m->textures[t]->name)); - - if (ptype != P_INVALID) - { - for (i=0; inummodelsurfaces; i++) - { - surf = m->surfaces + i + m->firstmodelsurface; - if (surf->texinfo->texture == m->textures[t]) - P_EmitSkyEffectTris(m, surf, ptype); - } - } - } - } - - - if (m->fromgame == fg_quake3) - { - int j; - unsigned char *src; - unsigned char *dst; - for (i = 0; i < m->lightmaps.count; i++) - { - if (lightmap[newfirst+i]->external) - continue; - - dst = lightmap[newfirst+i]->lightmaps; - src = m->lightdata + i*m->lightmaps.width*m->lightmaps.height*3; - if (lightmap_bytes == 4 && m->lightdata) - { - if (lightmap_bgra) - { - for (j = 0; j < m->lightmaps.width*m->lightmaps.height; j++, dst += 4, src += 3) - { - dst[0] = src[2]; - dst[1] = src[1]; - dst[2] = src[0]; - dst[3] = 255; - } - } - else - { - for (j = 0; j < m->lightmaps.width*m->lightmaps.height; j++, dst += 4, src += 3) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - dst[3] = 255; - } - } - } - } - } - else - { - int j; - lightmapinfo_t *lm, *dlm; - qbyte *deluxemap; - //fixup surface lightmaps, and paint - for (i=0; inummodelsurfaces; i++) - { - surf = m->surfaces + i + m->firstmodelsurface; - for (j = 0; j < 4; j++) - { - if (surf->lightmaptexturenums[j] < m->lightmaps.first) - { - surf->lightmaptexturenums[j] = -1; - continue; - } - surf->lightmaptexturenums[j] = surf->lightmaptexturenums[0] - m->lightmaps.first + newfirst; - - lm = lightmap[surf->lightmaptexturenums[j]]; - if (lm->hasdeluxe) - { - dlm = lightmap[surf->lightmaptexturenums[j]+1]; - deluxemap = dlm->lightmaps + (surf->light_t[j] * dlm->width + surf->light_s[j]) * lightmap_bytes; - } - else - deluxemap = NULL; - - Surf_BuildLightMap (surf, - lm->lightmaps + (surf->light_t[j] * lm->width + surf->light_s[j]) * lightmap_bytes, - deluxemap, - lm->stainmaps + (surf->light_t[j] * lm->width + surf->light_s[j]) * 3, - shift, r_ambient.value*255); - } - } - } - m->lightmaps.first = newfirst; + Surf_BuildModelLightmaps(m); + } + for (j=1 ; j=rqmingrad; i--) +// for (i = rqmingrad; i<=rqmaxgrad; i++) + { + for (rq = distrque[i]; rq; rq=rq->next) + { + if (!maxslot || rq->render != lr || typeptr != rq->data2) + { + if (maxslot != SLOTS) + lr(SLOTS - maxslot, &slot[maxslot], typeptr); + maxslot = SLOTS; + } + + slot[--maxslot] = rq->data1; + typeptr = rq->data2; + lr = rq->render; + } + } + if (maxslot != SLOTS) + lr(SLOTS - maxslot, &slot[maxslot], typeptr); +} + + void RQ_Shutdown(void) { Z_Free(initialque); diff --git a/engine/client/renderque.h b/engine/client/renderque.h index 83cece1e..51bba10d 100644 --- a/engine/client/renderque.h +++ b/engine/client/renderque.h @@ -5,6 +5,7 @@ void RQ_BeginFrame(void); void RQ_AddDistReorder(void (*render) (int count, void **objects, void *objtype), void *object, void *objtype, float *pos); void RQ_RenderBatchClear(void); +void RQ_RenderBatch(void); typedef struct renderque_s { diff --git a/engine/client/sbar.c b/engine/client/sbar.c index 186728ef..4d211344 100644 --- a/engine/client/sbar.c +++ b/engine/client/sbar.c @@ -2554,6 +2554,19 @@ void Sbar_IntermissionNumber (int x, int y, int num, int digits, int color, qboo } } +#define COL_TEAM_LOWAVGHIGH COLUMN("low/avg/high", 12*8, {sprintf (num, "%3i/%3i/%3i", plow, pavg, phigh); Draw_FunString ( x, y, num); }) +#define COL_TEAM_TEAM COLUMN("team", 4*8, {Draw_FunStringWidth ( x, y, tm->team, 4*8); \ + if (!strncmp(cl.players[cl.playernum[0]].team, tm->team, 16))\ + {\ + Draw_FunString ( x - 1*8, y, "^Ue010");\ + Draw_FunString ( x + 4*8, y, "^Ue011");\ + }\ + }) +#define COL_TEAM_TOTAL COLUMN("total", 5*8, {Draw_FunString ( x, y, va("%5i", tm->frags)); }) +#define COL_TEAM_PLAYERS COLUMN("players", 7*8, {Draw_FunString ( x, y, va("%5i", tm->players)); }) +#define ALL_TEAM_COLUMNS COL_TEAM_LOWAVGHIGH COL_TEAM_TEAM COL_TEAM_TOTAL COL_TEAM_PLAYERS + + /* ================== Sbar_TeamOverlay @@ -2565,10 +2578,9 @@ added by Zoid void Sbar_TeamOverlay (void) { mpic_t *pic; - int i, k, l; - int x, y; + int i, k; + int x, y, l; char num[12]; - char team[5]; team_t *tm; int plow, phigh, pavg; @@ -2592,19 +2604,31 @@ void Sbar_TeamOverlay (void) y += 24; } - x = (vid.width - 320)/2 + 36; - Draw_FunString(x, y, "low/avg/high team total players"); + x = l = (vid.width - 320)/2 + 36; + +#define COLUMN(title, cwidth, code) Draw_FunString(x, y, title), x+=cwidth + 8; + ALL_TEAM_COLUMNS +// if (rank_width+(cwidth)+8 <= vid.width) {showcolumns |= (1<0) {buf[c++] = '^'; buf[c++] = 'U'; buf[c++] = 'e'; buf[c++] = '0'; buf[c++] = '1'; buf[c++] = (c==5?'d':(!t?'f':'e'));} buf[c] = 0; Draw_FunString(x, y, buf); x += cwidth + 8;} + ALL_TEAM_COLUMNS +// Draw_FunString(x, y, "^Ue01d^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01f ^Ue01d^Ue01e^Ue01e^Ue01f ^Ue01d^Ue01e^Ue01e^Ue01e^Ue01f ^Ue01d^Ue01e^Ue01e^Ue01e^Ue01e^Ue01e^Ue01f"); y += 8; +#undef COLUMN + // sort the teams Sbar_SortTeams(); // draw the text - l = scoreboardlines; - for (i=0 ; i < scoreboardteams && y <= vid.height-10 ; i++) { k = teamsort[i]; @@ -2624,6 +2648,13 @@ void Sbar_TeamOverlay (void) if (pavg < 0 || pavg > 999) pavg = 999; + x = l; + +#if 1 +#define COLUMN(title, cwidth, code) code; x+=cwidth + 8; + ALL_TEAM_COLUMNS +#undef COLUMN +#else sprintf (num, "%3i/%3i/%3i", plow, pavg, phigh); Draw_FunString ( x, y, num); @@ -2641,10 +2672,10 @@ void Sbar_TeamOverlay (void) if (!strncmp(cl.players[cl.playernum[0]].team, tm->team, 16)) { - Draw_FunString ( x + 104 - 8, y, "^Ue016"); - Draw_FunString ( x + 104 + 32, y, "^Ue017"); + Draw_FunString ( x + 104 - 8, y, "^Ue010"); + Draw_FunString ( x + 104 + 32, y, "^Ue011"); } - +#endif y += 8; } y += 8; diff --git a/engine/client/screen.h b/engine/client/screen.h index 7a6ebcad..0f3785bf 100644 --- a/engine/client/screen.h +++ b/engine/client/screen.h @@ -81,7 +81,7 @@ void SCR_ShowPic_Clear(void); //a header is better than none... void Draw_TextBox (int x, int y, int width, int lines); -qboolean SCR_ScreenShot (char *filename); +qboolean SCR_ScreenShot (char *filename, void *rgb_buffer, int width, int height); void SCR_DrawTwoDimensional(int uimenu, qboolean nohud); diff --git a/engine/client/snd_alsa.c b/engine/client/snd_alsa.c index 8cff4e93..4c00f76f 100755 --- a/engine/client/snd_alsa.c +++ b/engine/client/snd_alsa.c @@ -122,41 +122,41 @@ static unsigned int ALSA_RW_GetDMAPos (soundcardinfo_t *sc) static void ALSA_RW_Submit (soundcardinfo_t *sc, int start, int end) { int state; - unsigned int frames, offset, ringsize; - unsigned chunk; - int result; + unsigned int frames, offset, ringsize; + unsigned chunk; + int result; int stride = sc->sn.numchannels * (sc->sn.samplebits/8); - /*we can't change the data that was already written*/ - frames = end - sc->snd_sent; - if (!frames) - return; + /*we can't change the data that was already written*/ + frames = end - sc->snd_sent; + if (!frames) + return; state = psnd_pcm_state (sc->handle); - ringsize = sc->sn.samples / sc->sn.numchannels; + ringsize = sc->sn.samples / sc->sn.numchannels; - chunk = frames; - offset = sc->snd_sent % ringsize; + chunk = frames; + offset = sc->snd_sent % ringsize; - if (offset + chunk >= ringsize) - chunk = ringsize - offset; + if (offset + chunk >= ringsize) + chunk = ringsize - offset; result = psnd_pcm_writei(sc->handle, sc->sn.buffer + offset*stride, chunk); - if (result < chunk) - { - if (result >= 0) - sc->snd_sent += result; - return; - } - sc->snd_sent += chunk; + if (result < chunk) + { + if (result >= 0) + sc->snd_sent += result; + return; + } + sc->snd_sent += chunk; - chunk = frames - chunk; - if (chunk) - { + chunk = frames - chunk; + if (chunk) + { result = psnd_pcm_writei(sc->handle, sc->sn.buffer, chunk); - if (result > 0) - sc->snd_sent += result; - } + if (result > 0) + sc->snd_sent += result; + } if (state == SND_PCM_STATE_PREPARED) psnd_pcm_start (sc->handle); diff --git a/engine/client/snd_dma.c b/engine/client/snd_dma.c index 76a52cbe..4b0d6786 100644 --- a/engine/client/snd_dma.c +++ b/engine/client/snd_dma.c @@ -50,7 +50,7 @@ vec3_t listener_up = {0, 0, 1}; vec3_t listener_velocity; vec_t sound_nominal_clip_dist=1000.0; -#define MAX_SFX 512 +#define MAX_SFX 2048 sfx_t *known_sfx; // hunk allocated [MAX_SFX] int num_sfx; @@ -901,7 +901,7 @@ void S_Startup (void) break; } - sound_started = !!sndcardinfo; + sound_started = true;//!!sndcardinfo; S_ClearRaw(); diff --git a/engine/client/snd_droid.c b/engine/client/snd_droid.c index 8a2ff4f8..848f1d29 100644 --- a/engine/client/snd_droid.c +++ b/engine/client/snd_droid.c @@ -6,10 +6,10 @@ java code has a function or two which just periodically calls us to ask us to du #include #include -//static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static soundcardinfo_t *sys_sc = NULL; extern int sys_soundflags; +//called by the java code when it wants to know what sort of AudioTrack format to use. JNIEXPORT jint JNICALL Java_com_fteqw_FTEDroidEngine_audioinfo(JNIEnv *env, jclass this, jint arg) { soundcardinfo_t *sc = sys_sc; @@ -33,55 +33,50 @@ JNIEXPORT jint JNICALL Java_com_fteqw_FTEDroidEngine_paintaudio(JNIEnv *env, jcl int offset = 0; soundcardinfo_t *sc = sys_sc; int framesz; -// if (!pthread_mutex_lock(&mutex)) + + if (sc) { - if (sc) + int buffersize = sc->sn.samples*sc->sn.samplebits/8; + + int curtime = GetSoundtime(sc); + framesz = sc->sn.numchannels * sc->sn.samplebits/8; + + S_PaintChannels (sc, curtime + (len / framesz)); + + if (len > buffersize) { - int buffersize = sc->sn.samples*sc->sn.samplebits/8; - - int curtime = GetSoundtime(sc); - framesz = sc->sn.numchannels * sc->sn.samplebits/8; - - S_PaintChannels (sc, curtime + (len / framesz)); - - if (len > buffersize) - { - len = buffersize; //whoa nellie! - } - - if (len + sc->snd_sent%buffersize > buffersize) - { //buffer will wrap, fill in the rest - (*env)->SetByteArrayRegion(env, stream, offset, buffersize - (sc->snd_sent%buffersize), (char*)sc->sn.buffer + (sc->snd_sent%buffersize)); - offset += buffersize - (sc->snd_sent%buffersize); - sc->snd_sent += buffersize - (sc->snd_sent%buffersize); - len -= buffersize - (sc->snd_sent%buffersize); - if (len < 0) /*this must be impossible, surely?*/ - len = 0; - } - //and finish from the start - (*env)->SetByteArrayRegion(env, stream, offset, len, (char*)sc->sn.buffer + (sc->snd_sent%buffersize)); - offset += len; - sc->snd_sent += len; + len = buffersize; //whoa nellie! } - else - offset = len; /*so the playback thread ends up blocked properly*/ -// pthread_mutex_unlock(&mutex); + + if (len + sc->snd_sent%buffersize > buffersize) + { //buffer will wrap, fill in the rest + (*env)->SetByteArrayRegion(env, stream, offset, buffersize - (sc->snd_sent%buffersize), (char*)sc->sn.buffer + (sc->snd_sent%buffersize)); + offset += buffersize - (sc->snd_sent%buffersize); + sc->snd_sent += buffersize - (sc->snd_sent%buffersize); + len -= buffersize - (sc->snd_sent%buffersize); + if (len < 0) /*this must be impossible, surely?*/ + len = 0; + } + //and finish from the start + (*env)->SetByteArrayRegion(env, stream, offset, len, (char*)sc->sn.buffer + (sc->snd_sent%buffersize)); + offset += len; + sc->snd_sent += len; } + else + offset = len; /*so the playback thread ends up blocked properly*/ return offset; } static void Droid_Shutdown(soundcardinfo_t *sc) { -// pthread_mutex_lock(&mutex); - + //fixme: what if we're currently inside Java_com_fteqw_FTEDroidEngine_paintaudio? sys_sc = NULL; free(sc->sn.buffer); sys_soundflags = 0; - -// pthread_mutex_unlock(&mutex); } +//return the number of samples that have already been submitted to the device. static unsigned int Droid_GetDMAPos(soundcardinfo_t *sc) { sc->sn.samplepos = sc->snd_sent / (sc->sn.samplebits/8); @@ -90,12 +85,10 @@ static unsigned int Droid_GetDMAPos(soundcardinfo_t *sc) static void Droid_UnlockBuffer(soundcardinfo_t *sc, void *buffer) { -// pthread_mutex_unlock(&mutex); } static void *Droid_LockBuffer(soundcardinfo_t *sc, unsigned int *sampidx) { -// pthread_mutex_lock(&mutex); return sc->sn.buffer; } @@ -116,34 +109,28 @@ static int Droid_InitCard (soundcardinfo_t *sc, int cardnum) if (sys_sc) return 2; -// if (!pthread_mutex_lock(&mutex)) - { - sc->selfpainting = true; -// sc->sn.speed = 11025; -// sc->sn.samplebits = 16; -// sc->sn.numchannels = 1; + sc->selfpainting = true; +// sc->sn.speed = 11025; +// sc->sn.samplebits = 16; +// sc->sn.numchannels = 1; - /*internal buffer should have 1 sec audio*/ - sc->sn.samples = sc->sn.speed*sc->sn.numchannels; + /*internal buffer should have 1 sec audio*/ + sc->sn.samples = sc->sn.speed*sc->sn.numchannels; - sc->Lock = Droid_LockBuffer; - sc->Unlock = Droid_UnlockBuffer; - sc->SetWaterDistortion = Droid_SetUnderWater; - sc->Submit = Droid_Submit; - sc->Shutdown = Droid_Shutdown; - sc->GetDMAPos = Droid_GetDMAPos; + sc->Lock = Droid_LockBuffer; + sc->Unlock = Droid_UnlockBuffer; + sc->SetWaterDistortion = Droid_SetUnderWater; + sc->Submit = Droid_Submit; + sc->Shutdown = Droid_Shutdown; + sc->GetDMAPos = Droid_GetDMAPos; - sc->sn.buffer = malloc(sc->sn.samples*sc->sn.samplebits/8); - - sys_sc = sc; + sc->sn.buffer = malloc(sc->sn.samples*sc->sn.samplebits/8); + + sys_sc = sc; - sys_soundflags = 3; - -// pthread_mutex_unlock(&mutex); + sys_soundflags = 3; - return 1; - } - return 0; + return 1; } int (*pDroid_InitCard) (soundcardinfo_t *sc, int cardnum) = &Droid_InitCard; diff --git a/engine/client/snd_mem.c b/engine/client/snd_mem.c index d7faebe6..a7d2c48b 100644 --- a/engine/client/snd_mem.c +++ b/engine/client/snd_mem.c @@ -22,6 +22,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" #include "winquake.h" +#include "fs.h" int cache_full_cycle; @@ -779,7 +780,8 @@ qboolean S_LoadSound (sfx_t *s) if (name[1] == ':' && name[2] == '\\') { - FILE *f; + vfsfile_t *f; + int fsize; #ifndef _WIN32 //convert from windows to a suitable alternative. char unixname[128]; Q_snprintfz(unixname, sizeof(unixname), "/mnt/%c/%s", name[0]-'A'+'a', name+3); @@ -794,16 +796,16 @@ qboolean S_LoadSound (sfx_t *s) #endif - if ((f = fopen(name, "rb"))) + if ((f = VFSOS_Open(name, "rb"))) { - com_filesize = COM_filelength(f); - data = Hunk_TempAlloc (com_filesize); - result = fread(data, 1, com_filesize, f); //do something with result + fsize = VFS_GETLEN(f); + data = Hunk_TempAlloc (fsize); + result = VFS_READ(f, data, fsize); - if (result != com_filesize) - Con_SafePrintf("S_LoadSound() fread: Filename: %s, expected %i, result was %u\n",name,com_filesize,(unsigned int)result); + if (result != fsize) + Con_SafePrintf("S_LoadSound() fread: Filename: %s, expected %i, result was %u\n", name, fsize, (unsigned int)result); - fclose(f); + VFS_CLOSE(f); } else { diff --git a/engine/client/sys_axfte.cpp b/engine/client/sys_axfte.cpp index d7f92a73..6137d335 100644 --- a/engine/client/sys_axfte.cpp +++ b/engine/client/sys_axfte.cpp @@ -64,6 +64,7 @@ public: } static void statuschanged(void *arg) { + //potentially comes from another thread //axfte *fte = (axfte*)arg; InvalidateRect(NULL, NULL, FALSE); } @@ -602,6 +603,7 @@ public: ULONG_PTR dwContinue), /* [in] */ ULONG_PTR dwContinue) { + struct contextpublic *pub = (struct contextpublic*)plug; int width, height; HBITMAP bmp = (HBITMAP)funcs->GetSplashBack(plug, hdcDraw, &width, &height); if (bmp) @@ -620,6 +622,11 @@ public: DeleteDC(memDC); funcs->ReleaseSplashBack(plug, bmp); } + if (*pub->statusmessage) + { + SetBkMode(hdcDraw, TRANSPARENT); + TextOutA(hdcDraw, 0, 0, pub->statusmessage, strlen(pub->statusmessage)); + } return S_OK; } @@ -785,10 +792,6 @@ struct {"Software\\Classes\\CLSID\\{"axfte_iid_str"}\\VersionIndependentProgID\\", "FTE.FTEPlug"}, {"Software\\Classes\\CLSID\\{"axfte_iid_str"}\\ProgID\\", "FTE.FTEPlug.1.0"}, -#ifdef warningmsg -#pragma warningmsg("Hey, moodles, do you want the plugin to register itself as a firefox plugin at the same time as it registers itself for support in IE?") -#endif - /* {"Software\\MozillaPlugins\\@fteqw.com/FTE\\Description", ENGINEWEBSITE}, {"Software\\MozillaPlugins\\@fteqw.com/FTE\\GeckoVersion", "1.00"}, {"Software\\MozillaPlugins\\@fteqw.com/FTE\\Path", "***DLLNAME***"}, @@ -800,7 +803,6 @@ struct {"Software\\MozillaPlugins\\@fteqw.com/FTE\\MimeTypes\\application/x-qtv\\Suffixes", "qtv"}, {"Software\\MozillaPlugins\\@fteqw.com/FTE\\Suffixes\\qtv", ""}, {"Software\\MozillaPlugins\\@fteqw.com/FTE\\Suffixes\\mvd", ""}, - */ {NULL} }; HRESULT WINAPI DllRegisterServer(void) @@ -826,8 +828,15 @@ HRESULT WINAPI DllRegisterServer(void) RegSetValueExA(h, ls, 0, REG_SZ, (BYTE*)binaryname, strlen(binaryname)); else if (!strcmp(regkeys[i].value, "***VERSION***")) { - char *ver = version_string(); - RegSetValueExA(h, ls, 0, REG_SZ, (BYTE*)ver, strlen(ver)); + char s[128]; +#ifdef OFFICIAL_RELEASE + Q_snprintfz(s, sizeof(s), "%s v%i.%02i", DISTRIBUTION, FTE_VER_MAJOR, FTE_VER_MINOR); +#elif defined(SVNREVISION) + Q_snprintfz(s, sizeof(s), "%s SVN %s", DISTRIBUTION, STRINGIFY(SVNREVISION)); +#else + Q_snprintfz(s, sizeof(s), "%s build %s", DISTRIBUTION, __DATE__); +#endif + RegSetValueExA(h, ls, 0, REG_SZ, (BYTE*)s, strlen(s)); } else RegSetValueExA(h, ls, 0, REG_SZ, (BYTE*)regkeys[i].value, strlen(regkeys[i].value)); diff --git a/engine/client/sys_droid.c b/engine/client/sys_droid.c index 4492be6b..24389799 100644 --- a/engine/client/sys_droid.c +++ b/engine/client/sys_droid.c @@ -27,10 +27,11 @@ static unsigned int vibrateduration; static char errormessage[256]; extern jmp_buf host_abort; -cvar_t sys_vibrate = CVAR("sys_vibrate", "1"); +cvar_t sys_vibrate = CVARD("sys_vibrate", "1", "Enables the system vibrator for damage events and such things. The value provided is a duration scaler."); cvar_t sys_osk = CVAR("sys_osk", "0"); //to be toggled -cvar_t sys_keepscreenon = CVAR("sys_keepscreenon", "1"); //to be toggled -cvar_t sys_orientation = CVAR("sys_orientation", "sensor"); +cvar_t sys_keepscreenon = CVARD("sys_keepscreenon", "1", "If set, the screen will never darken. This might cost some extra battery power, but then so will running a 3d engine."); //to be toggled +cvar_t sys_orientation = CVARD("sys_orientation", "landscape", "Specifies what angle to render quake at.\nValid values are: sensor (autodetect), landscape, portrait, reverselandscape, reverseportrait"); +cvar_t sys_glesversion_cvar = CVARD("sys_glesversion", "1", "Specifies which version of gles to use. 1 or 2 are valid values."); extern cvar_t vid_conautoscale; @@ -56,9 +57,15 @@ JNIEXPORT jstring JNICALL Java_com_fteqw_FTEDroidEngine_geterrormessage(JNIEnv * JNIEXPORT jstring JNICALL Java_com_fteqw_FTEDroidEngine_getpreferedorientation(JNIEnv *env, jobject obj) { sys_orientation.modified = false; + sys_glesversion_cvar.modified = false; return (*env)->NewStringUTF(env, sys_orientation.string); } +JNIEXPORT jint JNICALL Java_com_fteqw_FTEDroidEngine_getpreferedglesversion(JNIEnv *env, jobject obj) +{ + return sys_glesversion_cvar.ival; +} + /*the java passes in all input directly via a 'UI' thread. we don't need to poll it at all*/ void INS_Move(float *movements, int pnum) { @@ -96,8 +103,11 @@ JNIEXPORT jint JNICALL Java_com_fteqw_FTEDroidEngine_frame(JNIEnv *env, jobject static vec3_t oac; //if we had an error, don't even run a frame any more. - if (*errormessage) + if (*errormessage || !sys_running) + { + Sys_Printf("Crashed or quit\n"); return 8; + } #ifdef SERVERONLY SV_Frame(); @@ -127,7 +137,7 @@ JNIEXPORT jint JNICALL Java_com_fteqw_FTEDroidEngine_frame(JNIEnv *env, jobject ret |= 4; if (*errormessage) ret |= 8; - if (sys_orientation.modified) + if (sys_orientation.modified || sys_glesversion_cvar.modified) ret |= 16; if (sys_soundflags) { @@ -190,6 +200,7 @@ JNIEXPORT void JNICALL Java_com_fteqw_FTEDroidEngine_init(JNIEnv *env, jobject o Sys_Printf("reinit\n"); if (sys_memheap) free(sys_memheap); + memset(&parms, 0, sizeof(parms)); parms.basedir = NULL; /*filled in later*/ parms.argc = 3; parms.argv = args; @@ -239,6 +250,7 @@ JNIEXPORT void JNICALL Java_com_fteqw_FTEDroidEngine_init(JNIEnv *env, jobject o #endif sys_running = true; sys_lastframe = Sys_Milliseconds(); + sys_orientation.modified = true; } } @@ -407,6 +419,7 @@ void Sys_Init(void) Cvar_Register(&sys_osk, "android stuff"); Cvar_Register(&sys_keepscreenon, "android stuff"); Cvar_Register(&sys_orientation, "android stuff"); + Cvar_Register(&sys_glesversion_cvar, "android stuff"); } qboolean Sys_GetDesktopParameters(int *width, int *height, int *bpp, int *refreshrate) diff --git a/engine/client/sys_morphos.c b/engine/client/sys_morphos.c index cfbeb2f7..ba58b6c0 100755 --- a/engine/client/sys_morphos.c +++ b/engine/client/sys_morphos.c @@ -398,6 +398,8 @@ int main(int argc, char **argv) quakeparms_t parms; int i; + memset(&parms, 0, sizeof(parms)); + COM_InitArgv(argc, argv); TL_InitLanguages(); diff --git a/engine/client/sys_npfte.c b/engine/client/sys_npfte.c index bfd2bc16..25bafd44 100644 --- a/engine/client/sys_npfte.c +++ b/engine/client/sys_npfte.c @@ -67,7 +67,7 @@ qboolean NPFTE_BeginDownload(void *ctx, struct pipetype *ftype, char *url) } void NPFTE_StatusChanged(void *sysctx) -{ +{ //potentially called from another thread NPP instance = sysctx; struct contextpublic *pub = instance->pdata; InvalidateRgn(pub->oldwnd, NULL, FALSE); @@ -128,11 +128,28 @@ LRESULT CALLBACK MyPluginWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPar case WM_ERASEBKGND: return FALSE; case WM_PAINT: - if (pub->downloading) + if (*pub->statusmessage) { HDC hdc; PAINTSTRUCT paint; - char *s; + unsigned int progress; + unsigned int total; + + progress = pub->dldone; + total = pub->dlsize; + + hdc = BeginPaint(hWnd, &paint); + DrawWndBack(ctx, hWnd, hdc, &paint); + SetBkMode(hdc, TRANSPARENT); + TextOutA(hdc, 0, 0, pub->statusmessage, strlen(pub->statusmessage)); + EndPaint(hWnd, &paint); + return TRUE; + } + else if (pub->downloading) + { + HDC hdc; + PAINTSTRUCT paint; + char s[32]; unsigned int progress; unsigned int total; @@ -144,11 +161,11 @@ LRESULT CALLBACK MyPluginWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPar SetBkMode(hdc, TRANSPARENT); TextOutA(hdc, 0, 0, "Downloading Data, please wait", 16); if (!progress && !total) - s = "connecting"; + sprintf(s, "connecting"); else if (total) - s = va("%i bytes (%i%%)", progress, (int)((100.0f*progress)/total)); + sprintf(s, "%i bytes (%i%%)", progress, (int)((100.0f*progress)/total)); else - s = va("%i bytes", progress); + sprintf(s, "%i bytes", progress); TextOutA(hdc, 0, 32, s, strlen(s)); EndPaint(hWnd, &paint); return TRUE; @@ -169,9 +186,9 @@ LRESULT CALLBACK MyPluginWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPar if (pub->availver) { - s = va("Your plugin may be incompatible"); + s = "Your plugin may be incompatible"; TextOutA(hdc, 0, 32, s, strlen(s)); - s = va("Version %3.2f was requested, you are using version %3.2f", pub->availver, (float)version_number()); + s = "A newer version is available. Your version is dated " __DATE__ "."; TextOutA(hdc, 0, 48, s, strlen(s)); } } @@ -183,7 +200,7 @@ LRESULT CALLBACK MyPluginWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPar case WM_LBUTTONDOWN: SetActiveWindow(hWnd); if (!Plug_StartContext(ctx)) - Plug_StopContext(NULL); + Plug_StopContext(NULL, false); break; default: break; diff --git a/engine/client/sys_plugfte.c b/engine/client/sys_plugfte.c index 24a51dea..3d469300 100644 --- a/engine/client/sys_plugfte.c +++ b/engine/client/sys_plugfte.c @@ -6,6 +6,287 @@ static void UnpackAndExtractPakFiles_Complete(struct dl_download *dl); static void pscript_property_splash_sets(struct context *ctx, const char *val); + +#ifdef _MSC_VER +# ifdef _WIN64 +# pragma comment(lib, MSVCLIBSPATH "zlib64.lib") +# else +# pragma comment(lib, MSVCLIBSPATH "zlib.lib") +# endif +#endif + +void BZ_Free(void *ptr) +{ + free(ptr); +} +void *BZF_Malloc(int size) +{ + return malloc(size); +} +//FIXME: we can't use this. +void *BZ_Malloc(int size) +{ + return BZF_Malloc(size); +} + +void QDECL Q_strncpyz(char *d, const char *s, int n) +{ + int i; + n--; + if (n < 0) + return; //this could be an error + + for (i=0; *s; i++) + { + if (i == n) + break; + *d++ = *s++; + } + *d='\0'; +} +char *COM_SkipPath (const char *pathname) +{ + const char *last; + + last = pathname; + while (*pathname) + { + if (*pathname=='/' || *pathname == '\\') + last = pathname+1; + pathname++; + } + return (char *)last; +} +void VARGS Q_vsnprintfz (char *dest, size_t size, const char *fmt, va_list argptr) +{ + vsnprintf (dest, size, fmt, argptr); + dest[size-1] = 0; +} +void VARGS Q_snprintfz (char *dest, size_t size, const char *fmt, ...) +{ + va_list argptr; + + va_start (argptr, fmt); + Q_vsnprintfz(dest, size, fmt, argptr); + va_end (argptr); +} +char *COM_TrimString(char *str) +{ + int i; + static char buffer[256]; + while (*str <= ' ' && *str>'\0') + str++; + + for (i = 0; i < 255; i++) + { + if (*str <= ' ') + break; + buffer[i] = *str++; + } + buffer[i] = '\0'; + return buffer; +} +void VARGS Con_Printf (const char *fmt, ...) +{ + va_list argptr; + char dest[256]; + + va_start (argptr, fmt); + Q_vsnprintfz(dest, sizeof(dest), fmt, argptr); + va_end (argptr); + + OutputDebugString(dest); +} + +#include "netinc.h" +#ifdef _WIN32 +#include +#endif +qboolean NET_StringToSockaddr (const char *s, int defaultport, struct sockaddr_qstorage *sadr, int *addrfamily, int *addrsize) +{ + struct addrinfo *addrinfo = NULL; + struct addrinfo *pos; + struct addrinfo udp6hint; + int error; + char *port; + char dupbase[256]; + int len; + + if (!(*s)) + return false; + + memset (sadr, 0, sizeof(*sadr)); + + + memset(&udp6hint, 0, sizeof(udp6hint)); + udp6hint.ai_family = 0;//Any... we check for AF_INET6 or 4 + udp6hint.ai_socktype = SOCK_DGRAM; + udp6hint.ai_protocol = IPPROTO_UDP; + + //handle parsing of ipv6 literal addresses + if (*s == '[') + { + port = strstr(s, "]"); + if (!port) + error = EAI_NONAME; + else + { + len = port - (s+1); + if (len >= sizeof(dupbase)) + len = sizeof(dupbase)-1; + strncpy(dupbase, s+1, len); + dupbase[len] = '\0'; + error = getaddrinfo(dupbase, (port[1] == ':')?port+2:NULL, &udp6hint, &addrinfo); + } + } + else + { + port = strrchr(s, ':'); + + if (port) + { + len = port - s; + if (len >= sizeof(dupbase)) + len = sizeof(dupbase)-1; + strncpy(dupbase, s, len); + dupbase[len] = '\0'; + error = getaddrinfo(dupbase, port+1, &udp6hint, &addrinfo); + } + else + error = EAI_NONAME; + if (error) //failed, try string with no port. + error = getaddrinfo(s, NULL, &udp6hint, &addrinfo); //remember, this func will return any address family that could be using the udp protocol... (ip4 or ip6) + } + if (error) + { + return false; + } + ((struct sockaddr*)sadr)->sa_family = 0; + for (pos = addrinfo; pos; pos = pos->ai_next) + { + switch(pos->ai_family) + { + default: + //unrecognised address families are ignored. + break; + case AF_INET6: + if (((struct sockaddr_in *)sadr)->sin_family == AF_INET6) + break; //first one should be best... + //fallthrough + case AF_INET: + memcpy(sadr, pos->ai_addr, pos->ai_addrlen); + if (pos->ai_family == AF_INET) + goto dblbreak; //don't try finding any more, this is quake, they probably prefer ip4... + break; + } + } +dblbreak: + freeaddrinfo (addrinfo); + if (!((struct sockaddr*)sadr)->sa_family) //none suitablefound + return false; + + if (addrfamily) + *addrfamily = ((struct sockaddr*)sadr)->sa_family; + if (addrsize) + { + if (((struct sockaddr*)sadr)->sa_family == AF_INET) + *addrsize = sizeof(struct sockaddr_in); + else + *addrsize = sizeof(struct sockaddr_in6); + } + + return true; +} + +char *COM_ParseOut (const char *data, char *out, int outlen) +{ + int c; + int len; + + len = 0; + out[0] = 0; + + if (!data) + return NULL; + +// skip whitespace +skipwhite: + while ( (c = *data) <= ' ') + { + if (c == 0) + return NULL; // end of file; + data++; + } + +// skip // comments + if (c=='/') + { + if (data[1] == '/') + { + while (*data && *data != '\n') + data++; + goto skipwhite; + } + } + +//skip / * comments + if (c == '/' && data[1] == '*') + { + data+=2; + while(*data) + { + if (*data == '*' && data[1] == '/') + { + data+=2; + goto skipwhite; + } + data++; + } + goto skipwhite; + } + +// handle quoted strings specially + if (c == '\"') + { + data++; + while (1) + { + if (len >= outlen-1) + { + out[len] = 0; + return (char*)data; + } + + c = *data++; + if (c=='\"' || !c) + { + out[len] = 0; + return (char*)data; + } + out[len] = c; + len++; + } + } + +// parse a regular word + do + { + if (len >= outlen-1) + { + out[len] = 0; + return (char*)data; + } + + out[len] = c; + data++; + len++; + c = *data; + } while (c>32); + + out[len] = 0; + return (char*)data; +} + typedef struct { vfsfile_t funcs; @@ -33,7 +314,7 @@ unsigned long VFSPIPE_Tell(vfsfile_t *f) } qboolean VFSPIPE_Seek(vfsfile_t *f, unsigned long offset) { - Con_Printf("Seeking is a bad plan, mmkay?"); + OutputDebugStringA("Seeking is a bad plan, mmkay?\n"); return false; } int VFSPIPE_ReadBytes(vfsfile_t *f, void *buffer, int len) @@ -118,6 +399,7 @@ struct context char *onstart; char *onend; char *ondemoend; + char *curserver; //updated by engine void *hostinstance; @@ -136,10 +418,17 @@ struct context void *thread; char resetvideo; qboolean shutdown; + qboolean multiplecontexts; struct context *next; struct browserfuncs bfuncs; + +#ifdef _WIN32 + HANDLE pipetoengine; + HANDLE pipefromengine; + HANDLE engineprocess; +#endif }; #ifdef _WIN32 @@ -148,15 +437,19 @@ extern HWND sys_parentwindow; extern unsigned int sys_parentwidth; extern unsigned int sys_parentheight; HINSTANCE global_hInstance; -static char binaryname[MAX_PATH]; +static char binarypath[MAX_PATH]; BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { + char *bp; switch (fdwReason) { case DLL_PROCESS_ATTACH: global_hInstance = hinstDLL; - GetModuleFileName(global_hInstance, binaryname, sizeof(binaryname)); + GetModuleFileName(global_hInstance, binarypath, sizeof(binarypath)); + bp = COM_SkipPath(binarypath); + if (bp) + *bp = 0; break; default: break; @@ -168,18 +461,67 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) struct context *activecontext; struct context *contextlist; -#define ADDRARG(x) do {if (argc < maxargs) argv[argc++] = strdup(x);} while(0) -#define ADDCARG(x) do {if (argc < maxargs) argv[argc++] = strdup(cleanarg(x));} while(0) +#define ADDRARG(x) do {if (argc < maxargs) argv[argc++] = strdup(x);} while(0) //for strings that are safe +#define ADDCARG(x) do {if (argc < maxargs) argv[argc++] = cleanarg(x);} while(0) //for arguments that we don't trust. char *cleanarg(char *arg) { - //no hacking us, please. - while (*arg == '-' || *arg == '+') - arg++; - while (*arg && *(unsigned char*)arg <= ' ') + unsigned char *c; + //skip over any leading spaces. + while (*arg <= ' ') arg++; + + //reject anything with a leading + or - + if (*arg == '-' || *arg == '+') + return strdup("badarg"); + + //clean up the argument + for (c = (unsigned char *)arg; *c; c++) + { + //remove special chars... we automagically add quotes so any that exist are someone trying to get past us. + if (*c == ';' || *c == '\n' || *c == '\"') + *c = '?'; + //remove other control chars. + //we allow spaces + if (*c < ' ') + *c = '?'; + } + if (*arg) - return arg; - return "badarg"; + { + char *out = malloc(strlen(arg)+3); + strcpy(out+1, arg); + out[0] = '\"'; + strcat(out, "\""); + return out; + } + return strdup("\"\""); +} + +void Plug_GetBinaryName(char *exe, int exelen, + char *basedir, int basedirlen) +{ + char buffer[1024]; + char cmd[64]; + char value[1024]; + FILE *f; + Q_snprintfz(buffer, sizeof(buffer), "%s%s", binarypath, "npfte.txt"); + f = fopen(buffer, "rt"); + if (f) + { + while(fgets(buffer, sizeof(buffer), f)) + { + *cmd = 0; + *value = 0; + COM_ParseOut(COM_ParseOut(buffer, cmd, sizeof(cmd)), value, sizeof(value)); + if (!strcmp(cmd, "relexe")) + Q_snprintfz(buffer, sizeof(buffer), "%s%s", binarypath, value); + else if (!strcmp(cmd, "absexe")) + Q_strncpyz(exe, value, exelen); + else if (!strcmp(cmd, "basedir")) + Q_strncpyz(basedir, value, basedirlen); + } + fclose(f); + } } int Plug_GenCommandline(struct context *ctx, char **argv, int maxargs) @@ -187,10 +529,25 @@ int Plug_GenCommandline(struct context *ctx, char **argv, int maxargs) char *s; int argc; char tok[256]; + char exe[1024]; + char basedir[1024]; - argv[0] = strdup(binaryname); + Q_snprintfz(exe, sizeof(exe), "%s%s", binarypath, "fteqw"); + *basedir = 0; + + Plug_GetBinaryName(exe, sizeof(exe), basedir, sizeof(basedir)); + + argv[0] = strdup(exe); argc = 1; + ADDRARG("-plugin"); + + if (*basedir) + { + ADDRARG("-basedir"); + ADDCARG(basedir); + } + switch(ctx->qtvf.connectiontype) { default: @@ -253,66 +610,117 @@ int Plug_GenCommandline(struct context *ctx, char **argv, int maxargs) } return argc; } +qboolean Plug_GenCommandlineString(struct context *ctx, char *cmdline, int cmdlinelen) +{ + char *argv[64]; + int argc, i; + argc = Plug_GenCommandline(ctx, argv, 64); + for (i = 0; i < argc; i++) + { + //add quotes for any arguments with spaces + if (strchr(argv[i], ' ')) + { + Q_strncatz(cmdline, "\"", cmdlinelen); + Q_strncatz(cmdline, argv[i], cmdlinelen); + Q_strncatz(cmdline, "\"", cmdlinelen); + } + else + Q_strncatz(cmdline, argv[i], cmdlinelen); + Q_strncatz(cmdline, " ", cmdlinelen); + } + return true; +} -#if _MSC_VER >= 1300 -#define CATCHCRASH -#endif +void Plug_ExecuteCommand(struct context *ctx, char *message, ...) +{ + va_list va; -#ifdef CATCHCRASH -#ifdef _DEBUG -#include "dbghelp.h" -DWORD CrashExceptionHandler (DWORD exceptionCode, LPEXCEPTION_POINTERS exceptionInfo); -#endif -#endif + char finalmessage[1024]; + DWORD written = 0; + + va_start (va, message); + vsnprintf (finalmessage, sizeof(finalmessage)-1, message, va); + va_end (va); + + WriteFile(ctx->pipetoengine, finalmessage, strlen(finalmessage), &written, NULL); +} + +void Plug_CreatePluginProcess(struct context *ctx) +{ + char cmdline[8192]; + PROCESS_INFORMATION childinfo; + STARTUPINFO startinfo; + SECURITY_ATTRIBUTES pipesec = {sizeof(pipesec), NULL, TRUE}; + if (!Plug_GenCommandlineString(ctx, cmdline, sizeof(cmdline))) + return; + + memset(&startinfo, 0, sizeof(startinfo)); + startinfo.cb = sizeof(startinfo); + startinfo.hStdInput = NULL; + startinfo.hStdError = NULL; + startinfo.hStdOutput = NULL; + startinfo.dwFlags |= STARTF_USESTDHANDLES; + + //create pipes for the stdin/stdout. + CreatePipe(&ctx->pipefromengine, &startinfo.hStdOutput, &pipesec, 0); + CreatePipe(&startinfo.hStdInput, &ctx->pipetoengine, &pipesec, 0); + + SetHandleInformation(ctx->pipefromengine, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation(ctx->pipetoengine, HANDLE_FLAG_INHERIT, 0); + + Plug_ExecuteCommand(ctx, "vid_recenter %i %i %i %i %#llx\n", ctx->windowleft, ctx->windowtop, ctx->windowwidth, ctx->windowheight, (long long)ctx->windowhnd); + + CreateProcess(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, binarypath, &startinfo, &childinfo); + + //these ends of the pipes were inherited by now, so we can discard them in the caller. + CloseHandle(startinfo.hStdOutput); + CloseHandle(startinfo.hStdInput); +} int Plug_PluginThread(void *ctxptr) { - char *argv[16]; - int argc = 0; + char buffer[1024]; + char *nl; + int bufoffs = 0; struct context *ctx = ctxptr; - struct dl_download *dl; -#ifdef CATCHCRASH - __try -#endif +#if 0 + //I really don't know what to do about multiple active clients downloading at once. + //maybe just depricate this feature. android ports have the same issue with missing files. + //we should probably just have the engine take charge of the downloads. + if (ctx->datadownload) { - argc = Plug_GenCommandline(ctx, argv, sizeof(argv)/sizeof(argv[0])); - NPQTV_Sys_Startup(argc, argv); - - if (ctx->datadownload) + char token[1024]; + struct dl_download *dl; + char *s = ctx->datadownload; + char *c; + vfsfile_t *f; + while ((s = COM_ParseOut(s, token, sizeof(token)))) { - char *s = ctx->datadownload; - char *c; - vfsfile_t *f; - Sys_LockMutex(ctx->mutex); - while ((s = COM_ParseOut(s, com_token, sizeof(com_token)))) + //FIXME: do we want to add some sort of file size indicator? + c = strchr(token, ':'); + if (!c) + continue; + *c++ = 0; + f = VFSSTDIO_Open(va("%s/%s", basedir, token), "rb", NULL); + if (f) { - //FIXME: do we want to add some sort of file size indicator? - c = strchr(com_token, ':'); - if (!c) - continue; - *c++ = 0; - f = FS_OpenVFS(com_token, "rb", FS_ROOT); - if (f) - { - Con_Printf("Already have %s\n", com_token); - VFS_CLOSE(f); - continue; - } - - Con_Printf("Attempting to download %s\n", c); - - dl = DL_Create(c); - dl->user_ctx = ctx; - dl->next = ctx->packagelist; - if (DL_CreateThread(dl, FS_OpenTemp(), UnpackAndExtractPakFiles_Complete)) - ctx->packagelist = dl; + Plug_ExecuteCommand(ctx, "echo " "Already have %s\n", token); + VFS_CLOSE(f); + continue; } - Sys_UnlockMutex(ctx->mutex); + + Plug_ExecuteCommand(ctx, "echo " "Attempting to download %s\n", c); + + dl = DL_Create(c); + dl->user_ctx = ctx; + dl->next = ctx->packagelist; + if (DL_CreateThread(dl, FS_OpenTemp(), UnpackAndExtractPakFiles_Complete)) + ctx->packagelist = dl; } ctx->pub.downloading = true; - while(host_initialized && !ctx->shutdown && ctx->packagelist) + while(!ctx->shutdown && ctx->packagelist) { int total=0, done=0; ctx->resetvideo = false; @@ -342,82 +750,83 @@ int Plug_PluginThread(void *ctxptr) Sleep(10); } ctx->pub.downloading = false; - - if (host_initialized && !ctx->shutdown) - { - Sys_LockMutex(ctx->mutex); - ctx->resetvideo = false; - sys_parentwindow = ctx->windowhnd; - sys_parentleft = ctx->windowleft; - sys_parenttop = ctx->windowtop; - sys_parentwidth = ctx->windowwidth; - sys_parentheight = ctx->windowheight; - Host_FinishInit(); - Sys_UnlockMutex(ctx->mutex); - } - if (ctx->bfuncs.StatusChanged) - ctx->bfuncs.StatusChanged(ctx->hostinstance); - - while(host_initialized) - { - Sys_LockMutex(ctx->mutex); - if (ctx->shutdown) - { - ctx->shutdown = false; - Host_Shutdown(); /*will shut down the host*/ - } - else if (ctx->resetvideo) - { - sys_parentwindow = ctx->windowhnd; - sys_parentleft = ctx->windowleft; - sys_parenttop = ctx->windowtop; - sys_parentwidth = ctx->windowwidth; - sys_parentheight = ctx->windowheight; - if (ctx->resetvideo == 2) - SetParent(mainwindow, sys_parentwindow); - ctx->resetvideo = false; - Cbuf_AddText("vid_recenter\n", RESTRICT_LOCAL); - } - else - NPQTV_Sys_MainLoop(); - Sys_UnlockMutex(ctx->mutex); - } - } -#ifdef CATCHCRASH -#ifdef _DEBUG - __except (CrashExceptionHandler(GetExceptionCode(), GetExceptionInformation())) - { - - } -#else - __except (EXCEPTION_EXECUTE_HANDLER) - { - Host_Shutdown(); - MessageBox(sys_parentwindow, "Sorry, FTE plugin crashed.\nYou probably should restart your browser", "FTE crashed", 0); } -#endif #endif - Sys_LockMutex(ctx->mutex); - while (ctx->packagelist) - { - dl = ctx->packagelist; - ctx->packagelist = dl->next; + Plug_CreatePluginProcess(ctx); - /*don't close while locked*/ - Sys_UnlockMutex(ctx->mutex); - DL_Close(dl); - Sys_LockMutex(ctx->mutex); - } - ctx->pub.running = false; - Sys_UnlockMutex(ctx->mutex); if (ctx->bfuncs.StatusChanged) ctx->bfuncs.StatusChanged(ctx->hostinstance); - while(argc-- > 0) - free(argv[argc]); + while(1) + { + DWORD avail; + //use Peek so we can read exactly how much there is without blocking, so we don't have to read byte-by-byte. + PeekNamedPipe(ctx->pipefromengine, NULL, 0, NULL, &avail, NULL); + if (!avail) + avail = 1; //so we do actually sleep. + if (avail > sizeof(buffer)-1 - bufoffs) + avail = sizeof(buffer)-1 - bufoffs; + if (!ReadFile(ctx->pipefromengine, buffer + bufoffs, avail, &avail, NULL) || !avail) + { + //broken pipe, client died. + break; + } + bufoffs += avail; + while(1) + { + buffer[bufoffs] = 0; + nl = strchr(buffer, '\n'); + if (nl) + { + *nl = 0; + if (!strncmp(buffer, "status ", 7)) + { + //don't just strcpy it, copy by byte, saves locking. + int i = strlen(buffer+7)+1; + if (i > sizeof(ctx->pub.statusmessage)) + i = sizeof(ctx->pub.statusmessage); + ctx->pub.statusmessage[i] = 0; + while (i-->0) + { + ctx->pub.statusmessage[i] = buffer[7+i]; + } - activecontext = NULL; + if (ctx->bfuncs.StatusChanged) + ctx->bfuncs.StatusChanged(ctx->hostinstance); + } + else if (!strcmp(buffer, "status")) + { + *ctx->pub.statusmessage = 0; + if (ctx->bfuncs.StatusChanged) + ctx->bfuncs.StatusChanged(ctx->hostinstance); + } + else if (!strcmp(buffer, "curserver")) + { + Plug_LockPlugin(ctx, true); + free(ctx->curserver); + ctx->curserver = strdup(buffer + 10); + Plug_LockPlugin(ctx, false); + } + else + { + //handle anything else we need to handle here + OutputDebugStringA("Unknown command from engine \""); + OutputDebugStringA(buffer); + OutputDebugStringA("\"\n"); + } + } + else + break; + } + } + ctx->pub.running = false; + *ctx->pub.statusmessage = 0; + if (ctx->bfuncs.StatusChanged) + ctx->bfuncs.StatusChanged(ctx->hostinstance); + + if (ctx == activecontext) + activecontext = NULL; return 0; } @@ -436,25 +845,53 @@ void Plug_LockPlugin(struct context *ctx, qboolean lockstate) //begins the context, fails if one is already active qboolean Plug_StartContext(struct context *ctx) { - if (activecontext) + if (activecontext && !ctx->multiplecontexts) return false; + if (ctx->pub.running) + return true; + + if (ctx->thread) + Plug_StopContext(ctx, true); + ctx->pub.running = true; - activecontext = ctx; - ctx->mutex = Sys_CreateMutex(); + if (!ctx->multiplecontexts) + activecontext = ctx; + if (!ctx->mutex) + ctx->mutex = Sys_CreateMutex(); ctx->thread = Sys_CreateThread(Plug_PluginThread, ctx, THREADP_NORMAL, 0); return true; } //asks a context to stop, is not instant. -void Plug_StopContext(struct context *ctx) +void Plug_StopContext(struct context *ctx, qboolean wait) { + void *thread; if (ctx == NULL) ctx = activecontext; if (!ctx) return; - if (ctx->pub.running == true) - ctx->shutdown = true; + Plug_ExecuteCommand(ctx, "quit force\n"); + + thread = ctx->thread; + if (ctx->thread) + { + if (wait) + { + while (ctx->pub.running && ctx->windowhnd) + { + MSG msg; + while (PeekMessage(&msg, ctx->windowhnd, 0, 0, PM_REMOVE)) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + Sleep(10); + } + Sys_WaitOnThread(ctx->thread); + ctx->thread = NULL; + } + } } //creates a plugin context @@ -507,6 +944,10 @@ qboolean Plug_ChangeWindow(struct context *ctx, void *whnd, int left, int top, i if (ctx->pub.running && !ctx->resetvideo) ctx->resetvideo = true; + + if (ctx->pub.running) + Plug_ExecuteCommand(ctx, "vid_recenter %i %i %i %i %#llx\n", ctx->windowleft, ctx->windowtop, ctx->windowwidth, ctx->windowheight, (long long)ctx->windowhnd); + Plug_LockPlugin(ctx, false); return result; @@ -535,10 +976,10 @@ void Plug_DestroyContext(struct context *ctx) ctx->splashdownload = NULL; } - ctx->shutdown = true; - if (ctx->thread) - Sys_WaitOnThread(ctx->thread); - ctx->thread = NULL; + Plug_StopContext(ctx, true); + + if (ctx->mutex) + Sys_DestroyMutex(ctx->mutex); //actually these ifs are not required, just the frees if (ctx->gamename) @@ -556,6 +997,7 @@ void Plug_DestroyContext(struct context *ctx) //////////////////////////////////////// +#if 0 #include "fs.h" extern searchpathfuncs_t zipfilefuncs; @@ -633,11 +1075,12 @@ static void UnpackAndExtractPakFiles_Complete(struct dl_download *dl) zipfilefuncs.ClosePath(zip); /*restart the filesystem so those new files can be found*/ - Cmd_ExecuteString("fs_restart", RESTRICT_LOCAL); + Plug_ExecuteCommand(dl->user_ctx, "fs_restart\n"); } Plug_LockPlugin(dl->user_ctx, false); } +#endif void LoadSplashImage(struct dl_download *dl) { @@ -650,11 +1093,13 @@ void LoadSplashImage(struct dl_download *dl) char *buffer; unsigned char *image; + Plug_LockPlugin(ctx, true); ctx->splashwidth = 0; ctx->splashheight = 0; image = ctx->splashdata; ctx->splashdata = NULL; free(image); + Plug_LockPlugin(ctx, false); if (!f) { @@ -678,6 +1123,7 @@ void LoadSplashImage(struct dl_download *dl) free(buffer); if (image) { + Plug_LockPlugin(ctx, true); if (ctx->splashdata) free(ctx->splashdata); ctx->splashdata = malloc(width*height*4); @@ -693,12 +1139,13 @@ void LoadSplashImage(struct dl_download *dl) ctx->splashwidth = width; ctx->splashheight = height; BZ_Free(image); - + Plug_LockPlugin(ctx, false); if (ctx->bfuncs.StatusChanged) ctx->bfuncs.StatusChanged(ctx->hostinstance); } } +#if 0 static void ReadQTVFileDescriptor(struct context *ctx, vfsfile_t *f, const char *name) { CL_ParseQTVFile(f, name, &ctx->qtvf); @@ -718,7 +1165,7 @@ static void EndDemo(struct context *ctx, vfsfile_t *f, const char *name) { Cmd_ExecuteString("disconnect", RESTRICT_LOCAL); } - +#endif ///////////////////////////////////// @@ -729,9 +1176,8 @@ static void EndDemo(struct context *ctx, vfsfile_t *f, const char *name) struct pscript_property { char *name; - qboolean onlyifactive; - cvar_t *cvar; + char *cvarname; char *(*getstring)(struct context *ctx); void (*setstring)(struct context *ctx, const char *val); @@ -759,7 +1205,7 @@ void pscript_property_running_setb(struct context *ctx, int i) if (i) Plug_StartContext(ctx); else - Plug_StopContext(ctx); + Plug_StopContext(ctx, false); } char *pscript_property_startserver_gets(struct context *ctx) @@ -780,10 +1226,8 @@ char *pscript_property_curserver_gets(struct context *ctx) if (!pscript_property_running_getb(ctx)) return pscript_property_startserver_gets(ctx); - if (cls.demoplayback) - return strdup(va("demo:%s",lastdemoname)); - else if (cls.state != ca_disconnected) - return strdup(cls.servername); + if (ctx->curserver) + return strdup(ctx->curserver); else return strdup(""); } @@ -798,8 +1242,7 @@ void pscript_property_curserver_sets(struct context *ctx, const char *val) return; } - Q_strncpyz(cls.servername, val, sizeof(cls.servername)); - CL_BeginServerConnect(0); + Plug_ExecuteCommand(ctx, "connect \"%s\"\n", val); } void pscript_property_stream_sets(struct context *ctx, const char *val) @@ -810,8 +1253,7 @@ void pscript_property_stream_sets(struct context *ctx, const char *val) ctx->qtvf.connectiontype = QTVCT_STREAM; Q_strncpyz(ctx->qtvf.server, val, sizeof(ctx->qtvf.server)); - if (pscript_property_running_getb(ctx)) - Cmd_ExecuteString(va("qtvplay \"%s\"\n", val), RESTRICT_INSECURE); + Plug_ExecuteCommand(ctx, "qtvplay \"%s\"\n", val); } void pscript_property_map_sets(struct context *ctx, const char *val) { @@ -820,19 +1262,20 @@ void pscript_property_map_sets(struct context *ctx, const char *val) ctx->qtvf.connectiontype = QTVCT_MAP; Q_strncpyz(ctx->qtvf.server, val, sizeof(ctx->qtvf.server)); - if (pscript_property_running_getb(ctx)) - Cmd_ExecuteString(va("map \"%s\"\n", val), RESTRICT_INSECURE); + Plug_ExecuteCommand(ctx, "map \"%s\"\n", val); } float pscript_property_curver_getf(struct context *ctx) { - return version_number(); + int base = FTE_VER_MAJOR * 10000 + FTE_VER_MINOR * 100; + return base; +// return version_number(); } void pscript_property_availver_setf(struct context *ctx, float val) { ctx->pub.availver = val; - if (ctx->pub.availver <= version_number()) + if (ctx->pub.availver <= pscript_property_curver_getf(ctx)) ctx->pub.availver = 0; } @@ -884,36 +1327,45 @@ char *pscript_property_build_gets(struct context *ctx) ); } -extern cvar_t skin, team, topcolor, bottomcolor, vid_fullscreen, cl_download_mapsrc; +float pscript_property_multi_getf(struct context *ctx) +{ + return ctx->multiplecontexts; +} +void pscript_property_multi_setf(struct context *ctx, float f) +{ + ctx->multiplecontexts = !!f; +} + static struct pscript_property pscript_properties[] = { - {"", false, NULL, pscript_property_curserver_gets, pscript_property_curserver_sets}, - {"server", false, NULL, pscript_property_curserver_gets, pscript_property_curserver_sets}, - {"running", false, NULL, NULL, NULL, pscript_property_running_getb, pscript_property_running_setb}, - {"startserver", false, NULL, pscript_property_startserver_gets, pscript_property_startserver_sets}, - {"join", false, NULL, NULL, pscript_property_curserver_sets}, - {"playername", true, &name}, - {NULL, true, &skin}, - {NULL, true, &team}, - {NULL, true, &topcolor}, - {NULL, true, &bottomcolor}, - {NULL, true, &password}, -// {NULL, true, &spectator}, - {"mapsrc", true, &cl_download_mapsrc}, - {"fullscreen", true, &vid_fullscreen}, + {"", NULL, pscript_property_curserver_gets, pscript_property_curserver_sets}, + {"server", NULL, pscript_property_curserver_gets, pscript_property_curserver_sets}, + {"running", NULL, NULL, NULL, pscript_property_running_getb, pscript_property_running_setb}, + {"startserver", NULL, pscript_property_startserver_gets, pscript_property_startserver_sets}, + {"join", NULL, NULL, pscript_property_curserver_sets}, + {"playername", "name"}, + {NULL, "skin"}, + {NULL, "team"}, + {NULL, "topcolor"}, + {NULL, "bottomcolor"}, + {NULL, "password"}, //cvars are write only, just so you know. +// {NULL, "spectator"}, + {"mapsrc", "cl_download_mapsrc"}, + {"fullscreen", "vid_fullscreen"}, - {"datadownload",false, NULL, NULL, pscript_property_datadownload_sets}, + {"datadownload",NULL, NULL, pscript_property_datadownload_sets}, - {"game", false, NULL, NULL, pscript_property_game_sets}, - {"availver", false, NULL, NULL, NULL, NULL, NULL, NULL, pscript_property_availver_setf}, - {"plugver", false, NULL, NULL, NULL, NULL, NULL, pscript_property_curver_getf}, + {"game", NULL, NULL, pscript_property_game_sets}, + {"availver", NULL, NULL, NULL, NULL, NULL, NULL, pscript_property_availver_setf}, + {"plugver", NULL, NULL, NULL, NULL, NULL, pscript_property_curver_getf}, + {"multiple", NULL, NULL, NULL, NULL, NULL, pscript_property_multi_getf, pscript_property_multi_setf}, - {"splash", false, NULL, NULL, pscript_property_splash_sets}, + {"splash", NULL, NULL, pscript_property_splash_sets}, - {"stream", false, NULL, NULL, pscript_property_stream_sets}, - {"map", false, NULL, NULL, pscript_property_map_sets}, + {"stream", NULL, NULL, pscript_property_stream_sets}, + {"map", NULL, NULL, pscript_property_map_sets}, - {"build", false, NULL, pscript_property_build_gets}, + {"build", NULL, pscript_property_build_gets}, {NULL} }; @@ -921,15 +1373,15 @@ static struct pscript_property pscript_properties[] = int Plug_FindProp(struct context *ctx, const char *field) { struct pscript_property *prop; - for (prop = pscript_properties; prop->name||prop->cvar; prop++) + for (prop = pscript_properties; prop->name||prop->cvarname; prop++) { - if (!stricmp(prop->name?prop->name:prop->cvar->name, field)) + if (!stricmp(prop->name?prop->name:prop->cvarname, field)) { - if (prop->onlyifactive) - { - if (!ctx->pub.running) - return -1; - } +// if (prop->onlyifactive) +// { +// if (!ctx->pub.running) +// return -1; +// } return prop - pscript_properties; } } @@ -959,10 +1411,10 @@ qboolean Plug_SetString(struct context *ctx, int fieldidx, const char *value) field->setfloat(ctx, atof(value)); Plug_LockPlugin(ctx, false); } - else if (field->cvar && ctx->pub.running) + else if (field->cvarname && ctx->pub.running) { Plug_LockPlugin(ctx, true); - Cvar_Set(field->cvar, value); + Plug_ExecuteCommand(ctx, "%s \"%s\"\n", field->cvarname, value); Plug_LockPlugin(ctx, false); } else @@ -992,10 +1444,10 @@ qboolean Plug_SetInteger(struct context *ctx, int fieldidx, int value) field->setfloat(ctx, value); Plug_LockPlugin(ctx, false); } - else if (field->cvar && ctx->pub.running) + else if (field->cvarname && ctx->pub.running) { Plug_LockPlugin(ctx, true); - Cvar_SetValue(field->cvar, value); + Plug_ExecuteCommand(ctx, "%s \"%i\"\n", field->cvarname, value); Plug_LockPlugin(ctx, false); } else @@ -1019,10 +1471,10 @@ qboolean Plug_SetFloat(struct context *ctx, int fieldidx, float value) field->setint(ctx, value); Plug_LockPlugin(ctx, false); } - else if (field->cvar && ctx->pub.running) + else if (field->cvarname && ctx->pub.running) { Plug_LockPlugin(ctx, true); - Cvar_SetValue(field->cvar, value); + Plug_ExecuteCommand(ctx, "%s \"%f\"\n", field->cvarname, value); Plug_LockPlugin(ctx, false); } else diff --git a/engine/client/sys_plugfte.h b/engine/client/sys_plugfte.h index 776edb5a..bd72d4ce 100644 --- a/engine/client/sys_plugfte.h +++ b/engine/client/sys_plugfte.h @@ -17,6 +17,7 @@ struct contextpublic unsigned int dlsize; unsigned int dldone; float availver; /*this is the version of the plugin that is available, if current is better, use 0*/ + char statusmessage[256]; #if defined(_WIN32) && defined(__QUAKEDEF_H__) /*the npapi stuff is lazy and uses this*/ @@ -58,7 +59,7 @@ struct context *Plug_CreateContext(void *sysctx, const struct browserfuncs *func void Plug_DestroyContext(struct context *ctx); void Plug_LockPlugin(struct context *ctx, qboolean lockstate); qboolean Plug_StartContext(struct context *ctx); -void Plug_StopContext(struct context *ctx); +void Plug_StopContext(struct context *ctx, qboolean wait); qboolean Plug_ChangeWindow(struct context *ctx, void *whnd, int left, int top, int width, int height); int Plug_FindProp(struct context *ctx, const char *field); @@ -81,7 +82,7 @@ struct plugfuncs void (*DestroyContext)(struct context *ctx); void (*LockPlugin)(struct context *ctx, qboolean lockstate); qboolean (*StartContext)(struct context *ctx); - void (*StopContext)(struct context *ctx); + void (*StopContext)(struct context *ctx, qboolean wait); qboolean (*ChangeWindow)(struct context *ctx, void *whnd, int left, int top, int width, int height); int (*FindProp)(struct context *ctx, const char *field); diff --git a/engine/client/sys_sdl.c b/engine/client/sys_sdl.c index 44d8151a..10ecb0eb 100644 --- a/engine/client/sys_sdl.c +++ b/engine/client/sys_sdl.c @@ -483,6 +483,8 @@ int QDECL main(int argc, char **argv) int t; int delay = 1; + memset(&parms, 0, sizeof(parms)); + parms.argv = argv; parms.basedir = "."; diff --git a/engine/client/sys_win.c b/engine/client/sys_win.c index 5d404efc..86050048 100644 --- a/engine/client/sys_win.c +++ b/engine/client/sys_win.c @@ -49,6 +49,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #if !defined(CLIENTONLY) && !defined(SERVERONLY) qboolean isDedicated = false; #endif +qboolean isPlugin; qboolean debugout; HWND sys_parentwindow; @@ -87,7 +88,11 @@ qboolean Sys_RandomBytes(qbyte *string, int len) return true; } - +/* +================= +Library loading +================= +*/ void Sys_CloseLibrary(dllhandle_t *lib) { FreeLibrary((HMODULE)lib); @@ -371,19 +376,183 @@ typedef BOOL (WINAPI *MINIDUMPWRITEDUMP) ( #ifdef PRINTGLARRAYS #include "glquake.h" -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_CURRENT_PROGRAM 0x8B8D + +char *DecodeGLEnum(GLenum num) +{ + switch(num) + { + case GL_CW: return "GL_CW"; + case GL_CCW: return "GL_CCW"; + case GL_NEVER: return "GL_NEVER"; + case GL_LESS: return "GL_LESS"; + case GL_EQUAL: return "GL_EQUAL"; + case GL_LEQUAL: return "GL_LEQUAL"; + case GL_GREATER: return "GL_GREATER"; + case GL_NOTEQUAL: return "GL_NOTEQUAL"; + case GL_GEQUAL: return "GL_GEQUAL"; + case GL_ALWAYS: return "GL_ALWAYS"; + case GL_FRONT: return "GL_FRONT"; + case GL_BACK: return "GL_BACK"; + case GL_FRONT_AND_BACK: return "GL_FRONT_AND_BACK"; + case GL_COMBINE_ARB: return "GL_COMBINE"; + case GL_MODULATE: return "GL_MODULATE"; + case GL_REPLACE: return "GL_REPLACE"; + case GL_ZERO: return "GL_ZERO"; + case GL_ONE: return "GL_ONE"; + case GL_SRC_COLOR: return "GL_SRC_COLOR"; + case GL_ONE_MINUS_SRC_COLOR: return "GL_ONE_MINUS_SRC_COLOR"; + case GL_SRC_ALPHA: return "GL_SRC_ALPHA"; + case GL_ONE_MINUS_SRC_ALPHA: return "GL_ONE_MINUS_SRC_ALPHA"; + case GL_DST_ALPHA: return "GL_DST_ALPHA"; + case GL_ONE_MINUS_DST_ALPHA: return "GL_ONE_MINUS_DST_ALPHA"; + case GL_DST_COLOR: return "GL_DST_COLOR"; + case GL_ONE_MINUS_DST_COLOR: return "GL_ONE_MINUS_DST_COLOR"; + case GL_SRC_ALPHA_SATURATE: return "GL_SRC_ALPHA_SATURATE"; + default: return va("0x%x", num); + } +} + +void DumpGLState(void) +{ + int rval; + void *ptr; + int i; + GLint glint; + GLint glint4[4]; + void (APIENTRY *qglGetVertexAttribiv) (GLuint index, GLenum pname, GLint* params); + void (APIENTRY *qglGetVertexAttribPointerv) (GLuint index, GLenum pname, GLvoid** pointer); + qglGetVertexAttribiv = (void*)wglGetProcAddress("glGetVertexAttribiv"); + qglGetVertexAttribPointerv = (void*)wglGetProcAddress("glGetVertexAttribPointerv"); +#pragma comment(lib,"opengl32.lib") + + if (qglGetVertexAttribiv) + { + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &rval); + Sys_Printf("VERTEX_ARRAY_BINDING: %i\n", rval); + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &rval); + Sys_Printf("GL_ARRAY_BUFFER_BINDING: %i\n", rval); + if (glIsEnabled(GL_COLOR_ARRAY)) + { + glGetIntegerv(GL_COLOR_ARRAY_BUFFER_BINDING, &rval); + glGetPointerv(GL_COLOR_ARRAY_POINTER, &ptr); + Sys_Printf("GL_COLOR_ARRAY: %s %i:%p\n", glIsEnabled(GL_COLOR_ARRAY)?"en":"dis", rval, ptr); + } +// if (glIsEnabled(GL_FOG_COORDINATE_ARRAY_EXT)) +// { +// glGetPointerv(GL_FOG_COORD_ARRAY_POINTER, &ptr); +// Sys_Printf("GL_FOG_COORDINATE_ARRAY_EXT: %i (%lx)\n", (int) glIsEnabled(GL_FOG_COORDINATE_ARRAY_EXT), (int) ptr); +// } +// if (glIsEnabled(GL_INDEX_ARRAY)) + { + glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &rval); + glGetPointerv(GL_INDEX_ARRAY_POINTER, &ptr); + Sys_Printf("GL_INDEX_ARRAY: %s %i:%p\n", glIsEnabled(GL_INDEX_ARRAY)?"en":"dis", rval, ptr); + } + if (glIsEnabled(GL_NORMAL_ARRAY)) + { + glGetIntegerv(GL_NORMAL_ARRAY_BUFFER_BINDING, &rval); + glGetPointerv(GL_NORMAL_ARRAY_POINTER, &ptr); + Sys_Printf("GL_NORMAL_ARRAY: %s %i:%p\n", glIsEnabled(GL_NORMAL_ARRAY)?"en":"dis", rval, ptr); + } + // glGetPointerv(GL_SECONDARY_COLOR_ARRAY_POINTER, &ptr); + // Sys_Printf("GL_SECONDARY_COLOR_ARRAY: %i (%lx)\n", (int) glIsEnabled(GL_SECONDARY_COLOR_ARRAY), (int) ptr); + for (i = 0; i < 4; i++) + { + qglClientActiveTextureARB(mtexid0 + i); + if (glIsEnabled(GL_TEXTURE_COORD_ARRAY)) + { + glGetIntegerv(GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING, &rval); + glGetPointerv(GL_TEXTURE_COORD_ARRAY_POINTER, &ptr); + Sys_Printf("GL_TEXTURE_COORD_ARRAY %i: %s %i:%p\n", i, glIsEnabled(GL_TEXTURE_COORD_ARRAY)?"en":"dis", rval, ptr); + } + } + if (glIsEnabled(GL_VERTEX_ARRAY)) + { + glGetIntegerv(GL_VERTEX_ARRAY_BUFFER_BINDING, &rval); + glGetPointerv(GL_VERTEX_ARRAY_POINTER, &ptr); + Sys_Printf("GL_VERTEX_ARRAY: %s %i:%p\n", glIsEnabled(GL_VERTEX_ARRAY)?"en":"dis", rval, ptr); + } + + for (i = 0; i < 16; i++) + { + int en, bo, as, st, ty, no; + + qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &en); + if (!en) + continue; + qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &bo); + qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &as); + qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &st); + qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &ty); + qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &no); + qglGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &ptr); + + Sys_Printf("attrib%i: %s as:%i st:%i ty:%0x %s%i:%p\n", i, en?"en":"dis", as, st,ty,no?"norm ":"", bo, ptr); + } + + glGetIntegerv(GL_CURRENT_PROGRAM, &glint); + Sys_Printf("GL_CURRENT_PROGRAM: %i\n", glint); + + glGetIntegerv(GL_BLEND, &glint); + Sys_Printf("GL_BLEND: %i\n", glint); + glGetIntegerv(GL_BLEND_SRC, &glint); + Sys_Printf("GL_BLEND_SRC: %i\n", DecodeGLEnum(glint)); + glGetIntegerv(GL_BLEND_DST, &glint); + Sys_Printf("GL_BLEND_DST: %i\n", DecodeGLEnum(glint)); + + glGetIntegerv(GL_DEPTH_WRITEMASK, &glint); + Sys_Printf("GL_DEPTH_WRITEMASK: %i\n", glint); + glGetIntegerv(GL_DEPTH_TEST, &glint); + Sys_Printf("GL_DEPTH_TEST: %i\n", glint); + glGetIntegerv(GL_DEPTH_FUNC, &glint); + Sys_Printf("GL_DEPTH_FUNC: %s\n", DecodeGLEnum(glint)); + glGetIntegerv(GL_CULL_FACE, &glint); + Sys_Printf("GL_CULL_FACE: %i\n", glint); + glGetIntegerv(GL_CULL_FACE_MODE, &glint); + Sys_Printf("GL_CULL_FACE_MODE: %s\n", DecodeGLEnum(glint)); + glGetIntegerv(GL_FRONT_FACE, &glint); + Sys_Printf("GL_FRONT_FACE: %s\n", DecodeGLEnum(glint)); + glGetIntegerv(GL_SCISSOR_TEST, &glint); + Sys_Printf("GL_SCISSOR_TEST: %i\n", glint); + glGetIntegerv(GL_STENCIL_TEST, &glint); + Sys_Printf("GL_STENCIL_TEST: %i\n", glint); + glGetIntegerv(GL_COLOR_WRITEMASK, glint4); + Sys_Printf("GL_COLOR_WRITEMASK: %i %i %i %i\n", glint4[0], glint4[1], glint4[2], glint4[3]); + + GL_SelectTexture(0); + glGetIntegerv(GL_TEXTURE_2D, &glint); + Sys_Printf("GL_TEXTURE_2D: %i\n", glint); + glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &glint); + Sys_Printf("GL_TEXTURE_ENV_MODE: %s\n", DecodeGLEnum(glint)); + GL_SelectTexture(1); + glGetIntegerv(GL_TEXTURE_2D, &glint); + Sys_Printf("GL_TEXTURE_2D: %i\n", glint); + glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &glint); + Sys_Printf("GL_TEXTURE_ENV_MODE: %s\n", DecodeGLEnum(glint)); + GL_SelectTexture(2); + glGetIntegerv(GL_TEXTURE_2D, &glint); + Sys_Printf("GL_TEXTURE_2D: %i\n", glint); + glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &glint); + Sys_Printf("GL_TEXTURE_ENV_MODE: %s\n", DecodeGLEnum(glint)); + } +} #endif DWORD CrashExceptionHandler (DWORD exceptionCode, LPEXCEPTION_POINTERS exceptionInfo) @@ -398,56 +567,7 @@ DWORD CrashExceptionHandler (DWORD exceptionCode, LPEXCEPTION_POINTERS exception BOOL (WINAPI *pIsDebuggerPresent)(void); #ifdef PRINTGLARRAYS - int rval; - void *ptr; - int i; - void (APIENTRY *qglGetVertexAttribiv) (GLuint index, GLenum pname, GLint* params); - void (APIENTRY *qglGetVertexAttribPointerv) (GLuint index, GLenum pname, GLvoid** pointer); - qglGetVertexAttribiv = (void*)wglGetProcAddress("glGetVertexAttribiv"); - qglGetVertexAttribPointerv = (void*)wglGetProcAddress("glGetVertexAttribPointerv"); -#pragma comment(lib,"opengl32.lib") - - if (qglGetVertexAttribiv) - { - glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &rval); - Sys_Printf("GL_ARRAY_BUFFER_BINDING: %i\n", rval); - glGetPointerv(GL_COLOR_ARRAY_POINTER, &ptr); - Sys_Printf("GL_COLOR_ARRAY: %s (%lx)\n", glIsEnabled(GL_COLOR_ARRAY)?"en":"dis", (int) ptr); - // glGetPointerv(GL_FOG_COORD_ARRAY_POINTER, &ptr); - // Sys_Printf("GL_FOG_COORDINATE_ARRAY_EXT: %i (%lx)\n", (int) glIsEnabled(GL_FOG_COORDINATE_ARRAY_EXT), (int) ptr); - glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &rval); - glGetPointerv(GL_INDEX_ARRAY_POINTER, &ptr); - Sys_Printf("GL_INDEX_ARRAY: %s %i:%p\n", glIsEnabled(GL_INDEX_ARRAY)?"en":"dis", rval, ptr); - glGetPointerv(GL_NORMAL_ARRAY_POINTER, &ptr); - Sys_Printf("GL_NORMAL_ARRAY: %s (%lx)\n", glIsEnabled(GL_NORMAL_ARRAY)?"en":"dis", (int) ptr); - // glGetPointerv(GL_SECONDARY_COLOR_ARRAY_POINTER, &ptr); - // Sys_Printf("GL_SECONDARY_COLOR_ARRAY: %i (%lx)\n", (int) glIsEnabled(GL_SECONDARY_COLOR_ARRAY), (int) ptr); - for (i = 0; i < 4; i++) - { - qglClientActiveTextureARB(mtexid0 + i); - glGetIntegerv(GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING, &rval); - glGetPointerv(GL_TEXTURE_COORD_ARRAY_POINTER, &ptr); - Sys_Printf("GL_TEXTURE_COORD_ARRAY %i: %s %i:%p\n", i, glIsEnabled(GL_TEXTURE_COORD_ARRAY)?"en":"dis", rval, ptr); - } - glGetIntegerv(GL_VERTEX_ARRAY_BUFFER_BINDING, &rval); - glGetPointerv(GL_VERTEX_ARRAY_POINTER, &ptr); - Sys_Printf("GL_VERTEX_ARRAY: %s %i:%p\n", glIsEnabled(GL_VERTEX_ARRAY)?"en":"dis", rval, ptr); - - for (i = 0; i < 16; i++) - { - int en, bo, as, st, ty, no; - - qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &en); - qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &bo); - qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &as); - qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &st); - qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &ty); - qglGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &no); - qglGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &ptr); - - Sys_Printf("attrib%i: %s as:%i st:%i ty:%0x %s%i:%p\n", i, en?"en":"dis", as, st,ty,no?"norm ":"", bo, ptr); - } - } + DumpGLState(); #endif hKernel = LoadLibrary ("kernel32"); @@ -851,15 +971,7 @@ void VARGS Sys_Error (const char *error, ...) SetHookState(false); #endif -#ifdef NPFTE - { - extern jmp_buf host_abort; - /*jump to start of main loop (which exits the main loop)*/ - longjmp (host_abort, 1); - } -#else exit (1); -#endif } static wchar_t dequake(conchar_t chr) @@ -912,15 +1024,17 @@ void VARGS Sys_Printf (char *fmt, ...) if (debugout) { //msvc debug output - conchar_t msg[1024], *end; - wchar_t wide[1024]; - int i; + conchar_t msg[1024], *end, *in; + wchar_t wide[1024], *out; end = COM_ParseFunString(CON_WHITEMASK, text, msg, sizeof(msg), false); - for (i = 0; msg+i < end; i++) + out = wide; + in = msg; + for (in = msg; in < end; in++) { - wide[i] = dequake(msg[i] & CON_CHARMASK); + if (!(*in & CON_HIDDEN)) + *out++ = dequake(*in & CON_CHARMASK); } - wide[i] = 0; + *out = 0; OutputDebugStringW(wide); } #endif @@ -946,21 +1060,12 @@ void Sys_Quit (void) longjmp(restart_jmpbuf, 1); #endif -#ifdef NPFTE - { - extern jmp_buf host_abort; - /*jump to start of main loop (which exits the main loop)*/ - longjmp (host_abort, 1); - } -#else - #ifdef USE_MSVCRT_DEBUG if (_CrtDumpMemoryLeaks()) OutputDebugStringA("Leaks detected\n"); #endif exit(1); -#endif } @@ -1262,7 +1367,52 @@ void Sys_SendKeyEvents (void) { MSG msg; - if (isDedicated) + if (isPlugin) + { + DWORD avail; + static char text[256], *nl; + static int textpos = 0; + + HANDLE input = GetStdHandle(STD_INPUT_HANDLE); + if (!PeekNamedPipe(input, NULL, 0, NULL, &avail, NULL)) + { + Cmd_ExecuteString("quit force", RESTRICT_LOCAL); + } + else if (avail) + { + if (avail > sizeof(text)-1-avail) + avail = sizeof(text)-1-avail; + if (ReadFile(input, text+textpos, avail, &avail, NULL)) + { + textpos += avail; + while(1) + { + text[textpos] = 0; + nl = strchr(text, '\n'); + if (nl) + { + *nl++ = 0; + if (!qrenderer && !strncmp(text, "vid_recenter ", 13)) + { + Cmd_TokenizeString(text, false, false); + sys_parentleft = strtoul(Cmd_Argv(1), NULL, 0); + sys_parenttop = strtoul(Cmd_Argv(2), NULL, 0); + sys_parentwidth = strtoul(Cmd_Argv(3), NULL, 0); + sys_parentheight = strtoul(Cmd_Argv(4), NULL, 0); + sys_parentwindow = (HWND)strtoul(Cmd_Argv(5), NULL, 16); + } + Cmd_ExecuteString(text, RESTRICT_LOCAL); + memmove(text, nl, textpos - (nl - text)); + textpos -= (nl - text); + } + else + break; + } + } + + } + } + else if (isDedicated) { #ifndef CLIENTONLY SV_GetConsoleCommands (); @@ -1363,76 +1513,6 @@ qboolean Sys_Startup_CheckMem(quakeparms_t *parms) return true; } -#ifdef NPFTE -static quakeparms_t parms; -double lastlooptime; -qboolean NPQTV_Sys_Startup(int argc, char *argv[]) -{ - if (!host_initialized) - { - TL_InitLanguages(); - - parms.argc = argc; - parms.argv = argv; - parms.basedir = argv[0]; - COM_InitArgv (parms.argc, parms.argv); - - if (!Sys_Startup_CheckMem(&parms)) - return false; - - Host_Init (&parms); - } - - lastlooptime = Sys_DoubleTime (); - - return true; -} - -void NPQTV_Sys_MainLoop(void) -{ - double duratrion, newtime; - - if (isDedicated) - { -#ifndef CLIENTONLY - NET_Sleep(50, false); - - // find time passed since last cycle - newtime = Sys_DoubleTime (); - duratrion = newtime - lastlooptime; - lastlooptime = newtime; - - SV_Frame (); -#else - Sys_Error("wut?"); -#endif - } - else - { -#ifndef SERVERONLY - double sleeptime; - - newtime = Sys_DoubleTime (); - duratrion = newtime - lastlooptime; - sleeptime = Host_Frame (duratrion); - lastlooptime = newtime; - - SetHookState(sys_disableWinKeys.ival); - - Sys_Sleep(sleeptime); -// Sleep(0); -#else - Sys_Error("wut?"); -#endif - } -} - -void Sys_RecentServer(char *command, char *target, char *title, char *desc) -{ -} - -#else - /* ================== WinMain @@ -1833,7 +1913,7 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin // MSG msg; quakeparms_t parms; double time, oldtime, newtime; - char cwd[1024]; + char cwd[1024], bindir[1024], *s; const char *qtvfile = NULL; int delay = 0; @@ -1841,6 +1921,8 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin if (hPrevInstance) return 0; + memset(&parms, 0, sizeof(parms)); + #ifndef MINGW #if _MSC_VER > 1200 Win7_Init(); @@ -1937,12 +2019,21 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin setjmp (restart_jmpbuf); #endif - GetModuleFileName(NULL, cwd, sizeof(cwd)-1); - strcpy(exename, COM_SkipPath(cwd)); + GetModuleFileName(NULL, bindir, sizeof(bindir)-1); + s = COM_SkipPath(exename); + strcpy(exename, s); + *s = 0; parms.argv = (const char **)argv; COM_InitArgv (parms.argc, parms.argv); + isPlugin = !!COM_CheckParm("-plugin"); + if (isPlugin) + { + printf("status Starting up!\n"); + fflush(stdout); + } + if (COM_CheckParm("--version") || COM_CheckParm("-v")) { printf("version " DISTRIBUTION " " __TIME__ " " __DATE__ "\n"); @@ -1978,6 +2069,7 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin //tprints are now allowed parms.basedir = cwd; + parms.binarydir = bindir; parms.argc = com_argc; parms.argv = com_argv; @@ -2050,6 +2142,12 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin #endif #endif + if (isPlugin) + { + printf("status Running!\n"); + fflush(stdout); + } + /* main window message loop */ while (1) { @@ -2134,7 +2232,6 @@ int __cdecl main(void) } return WinMain(GetModuleHandle(NULL), NULL, cmdline, SW_NORMAL); } -#endif qboolean Sys_GetDesktopParameters(int *width, int *height, int *bpp, int *refreshrate) { diff --git a/engine/client/textedit.c b/engine/client/textedit.c index 93af4907..2d787ece 100644 --- a/engine/client/textedit.c +++ b/engine/client/textedit.c @@ -16,11 +16,22 @@ F11 will step through. #include "quakedef.h" #ifdef TEXTEDITOR -static cvar_t alloweditor = SCVAR("alloweditor", "1"); //disallow loading editor for stepbystep debugging. -static cvar_t editstripcr = SCVAR("edit_stripcr", "1"); //remove \r from eols (on load). -static cvar_t editaddcr = SCVAR("edit_addcr", "1"); //make sure that each line ends with a \r (on save). -static cvar_t edittabspacing = SCVAR("edit_tabsize", "4"); -cvar_t debugger = SCVAR("debugger", "1"); + +#ifdef _WIN32 +#define editaddcr_default "1" +#else +#define editaddcr_default "0" +#endif +#ifdef ANDROID +#define debugger_default "0" +#else +#define debugger_default "1" +#endif + +static cvar_t editstripcr = CVARD("edit_stripcr", "1", "remove \\r from eols (on load)"); +static cvar_t editaddcr = CVARD("edit_addcr", editaddcr_default, "make sure that each line ends with a \\r (on save)"); +static cvar_t edittabspacing = CVARD("edit_tabsize", "4", "How wide tab alignment is"); +cvar_t debugger = CVARD("debugger", debugger_default, "When enabled, QC errors and debug events will enable step-by-step tracing."); #undef pr_trace @@ -53,6 +64,21 @@ static void E_Free(void *mem) #define GETBLOCK(s, ret) ret = (void *)E_Malloc(sizeof(fileblock_t) + s);ret->allocatedlength = s;ret->data = (char *)ret + sizeof(fileblock_t) +void PR_GenerateStatementString (progfuncs_t *progfuncs, int statementnum, char *out, int outlen); +fileblock_t *GenAsm(int statement) +{ + char linebuf[256]; + fileblock_t *b; + int l; + PR_GenerateStatementString(editprogfuncs, statement, linebuf, sizeof(linebuf)); + l = strlen(linebuf); + b = E_Malloc(sizeof(fileblock_t) + l); + b->allocatedlength = l; + b->datalength = l; + b->data = (char *)b + sizeof(fileblock_t); + memcpy(b->data, linebuf, l); + return b; +} static char OpenEditorFile[256]; @@ -61,8 +87,10 @@ qboolean editoractive; //(export) qboolean editormodal; //doesn't return. (export) static qboolean editorblocking; static qboolean madechanges; +static qboolean editenabled; static qboolean insertkeyhit=true; static qboolean useeval; +static qboolean stepasm; static char evalstring[256]; @@ -161,7 +189,7 @@ static void CloseEditor(void) { fileblock_t *b; - key_dest = key_console; + key_dest = key_game; editoractive = false; editprogfuncs = NULL; @@ -169,11 +197,11 @@ static void CloseEditor(void) return; OpenEditorFile[0] = '\0'; - for (b = firstblock; b;) + while(firstblock) { - firstblock = b; - b=b->next; - E_Free(firstblock); + b = firstblock; + firstblock=firstblock->next; + E_Free(b); } madechanges = false; @@ -227,6 +255,7 @@ static qboolean EditorSaveFile(char *s) //returns true if succesful fclose(F); */ madechanges = false; + editenabled = true; executionlinenum = -1; return true; @@ -236,6 +265,14 @@ static qboolean EditorSaveFile(char *s) //returns true if succesful static void EditorNewFile(void) { + fileblock_t *b; + while(firstblock) + { + b = firstblock; + firstblock=firstblock->next; + E_Free(b); + } + GETBLOCK(64, firstblock); GETBLOCK(64, firstblock->next); firstblock->next->prev = firstblock; @@ -250,9 +287,10 @@ static void EditorNewFile(void) key_dest = key_editor; editoractive = true; + editenabled = true; } -static void EditorOpenFile(char *name) +static void EditorOpenFile(char *name, qboolean readonly) { int i; char line[8192]; @@ -347,14 +385,17 @@ static void EditorOpenFile(char *name) madechanges = false; executionlinenum = -1; + editenabled = !readonly; key_dest = key_editor; editoractive = true; } +extern qboolean keydown[K_MAX]; void Editor_Key(int key, int unicode) { int i; + fileblock_t *nb; if (keybindings[key][0]) if (!strcmp(keybindings[key][0], "toggleconsole")) { @@ -400,7 +441,7 @@ void Editor_Key(int key, int unicode) if (key == K_SHIFT) return; - if (useeval && key != K_F11 && key != K_F5) + if (useeval) { switch(key) { @@ -408,19 +449,19 @@ void Editor_Key(int key, int unicode) if (editprogfuncs) *editprogfuncs->pr_trace = 0; useeval = false; - break; + return; case K_F3: useeval = false; - break; + return; case K_DEL: evalstring[0] = '\0'; - break; + return; case K_BACKSPACE: i = strlen(evalstring); if (i < 1) - break; + return; evalstring[i-1] = '\0'; - break; + return; default: if (unicode) { @@ -428,9 +469,20 @@ void Editor_Key(int key, int unicode) evalstring[i] = unicode; evalstring[i+1] = '\0'; } + return; + case K_F5: + case K_F9: + case K_F11: + case K_MWHEELUP: + case K_UPARROW: + case K_PGUP: + case K_MWHEELDOWN: + case K_DOWNARROW: + case K_PGDN: + case K_LEFTARROW: + case K_RIGHTARROW: break; } - return; } /* if (ctrl_down && (key == 'c' || key == K_INS)) @@ -466,6 +518,14 @@ void Editor_Key(int key, int unicode) cursorblock = cursorblock->prev; cursorlinenum--; } + else if (cursorlinenum>1) + { + cursorlinenum--; + nb = GenAsm(cursorlinenum); + nb->next = cursorblock; + cursorblock->prev = nb; + firstblock = cursorblock = nb; + } } } SetCursorpos(); @@ -490,6 +550,14 @@ void Editor_Key(int key, int unicode) cursorblock = cursorblock->next; cursorlinenum++; } + else + { + cursorlinenum++; + nb = GenAsm(cursorlinenum); + nb->prev = cursorblock; + cursorblock->next = nb; + cursorblock = nb; + } } } SetCursorpos(); @@ -516,7 +584,7 @@ void Editor_Key(int key, int unicode) s++; } if (*file) - EditorOpenFile(file); + EditorOpenFile(file, false); } break; case K_F3: @@ -593,14 +661,39 @@ void Editor_Key(int key, int unicode) case K_LEFTARROW: cursorx--; + if (keydown[K_CTRL]) + { + //skip additional whitespace + while(cursorx > 0 && (cursorblock->data[cursorx-1] == ' ' || cursorblock->data[cursorx-1] <= '\t')) + cursorx--; + //skip over the word, to the start of it + while(cursorx > 0 && ((cursorblock->data[cursorx-1] >= 'a' && cursorblock->data[cursorx-1] <= 'z') || + (cursorblock->data[cursorx-1] >= 'A' && cursorblock->data[cursorx-1] <= 'Z') || + (cursorblock->data[cursorx-1] >= '0' && cursorblock->data[cursorx-1] <= '9'))) + cursorx--; + } if (cursorx < 0) cursorx = 0; break; case K_RIGHTARROW: - cursorx++; - if (cursorx > cursorblock->datalength) - cursorx = cursorblock->datalength; + if (keydown[K_CTRL]) + { + while(cursorx+1 < cursorblock->datalength && ((cursorblock->data[cursorx] >= 'a' && cursorblock->data[cursorx] <= 'z') || + (cursorblock->data[cursorx] >= 'A' && cursorblock->data[cursorx] <= 'Z') || + (cursorblock->data[cursorx] >= '0' && cursorblock->data[cursorx] <= '9'))) + cursorx++; + cursorx++; + while(cursorx+1 < cursorblock->datalength && (cursorblock->data[cursorx] == ' ' || cursorblock->data[cursorx] <= '\t')) + cursorx++; + } + else + { + cursorx++; + if (cursorx > cursorblock->datalength) + cursorx = cursorblock->datalength; + } + break; case K_BACKSPACE: @@ -615,29 +708,38 @@ void Editor_Key(int key, int unicode) break; } - cursorlinenum-=1; - madechanges = true; + if (editenabled) + { + cursorlinenum-=1; + madechanges = true; - cursorblock = b->prev; + cursorblock = b->prev; - MakeNewSize(cursorblock, b->datalength + cursorblock->datalength+5); + MakeNewSize(cursorblock, b->datalength + cursorblock->datalength+5); - cursorx = cursorblock->datalength; - memcpy(cursorblock->data + cursorblock->datalength, b->data, b->datalength); - cursorblock->datalength += b->datalength; + cursorx = cursorblock->datalength; + memcpy(cursorblock->data + cursorblock->datalength, b->data, b->datalength); + cursorblock->datalength += b->datalength; - cursorblock->next = b->next; - if (b->next) - b->next->prev = cursorblock; -// cursorblock->prev->next = cursorblock->next; -// cursorblock->next->prev = cursorblock->prev; + cursorblock->next = b->next; + if (b->next) + b->next->prev = cursorblock; + // cursorblock->prev->next = cursorblock->next; + // cursorblock->next->prev = cursorblock->prev; - E_Free(b); -// cursorblock = b; + E_Free(b); + // cursorblock = b; + } + else + { + cursorblock = cursorblock->prev; + cursorx = cursorblock->datalength; + } break; } case K_DEL: //bksp falls through. + if (editenabled) { int a; fileblock_t *b; @@ -673,6 +775,7 @@ void Editor_Key(int key, int unicode) break; case K_ENTER: + if (editenabled) { fileblock_t *b = cursorblock; @@ -695,14 +798,22 @@ void Editor_Key(int key, int unicode) cursorx = 0; } + else if (cursorblock->next) + { + cursorblock = cursorblock->next; + cursorlinenum++; + cursorx = 0; + } break; case K_INS: insertkeyhit = insertkeyhit?false:true; break; default: + if (!editenabled) + break; if (unicode < ' ' && unicode != '\t') //we deem these as unprintable - break; + break; if (insertkeyhit) //insert a char { @@ -735,58 +846,138 @@ void Editor_Key(int key, int unicode) } } -static void Draw_Line(int x, int y, fileblock_t *b, int cursorx) +static void Draw_Line(int vy, fileblock_t *b, int cursorx) { - int nx = 0, nnx; + int nx = 0; + int y; + char *tooltip = NULL; + int nnx; qbyte *d = b->data; qbyte *c; int i; - - int colour=COLOR_WHITE; + extern int mousecursor_x, mousecursor_y; + int smx = (mousecursor_x * vid.pixelwidth) / vid.width, smy = (mousecursor_y * vid.pixelheight) / vid.height; + unsigned int colour; int ts = edittabspacing.value; + char linebuf[128]; if (cursorx >= 0) c = d + cursorx; else c = NULL; - Font_BeginString(font_conchar, x, y, &x, &y); + Font_BeginString(font_conchar, nx, vy, &nx, &y); if (ts < 1) ts = 4; ts*=8; + //figure out the colour if (b->flags & (FB_BREAK)) - colour = COLOR_RED; //red - - if (executionblock == b) { - if (colour) //break point too - colour = COLOR_GREEN; //green + if (executionblock == b) + colour = COLOR_MAGENTA<= y && smy < y + Font_CharHeight()) + { + int e, s; + nx = -viewportx; + for (i = 0; i < b->datalength; i++) + { + if (d[i] == '\t') + { + nnx=nx+ts; + nnx-=(nnx - -viewportx)%ts; + } + else + nnx = Font_CharEndCoord(font_conchar, nx, (int)d[i] | (colour)); + + if (smx >= nx && smx <= nnx) + { + for(s = i; s > 0; ) + { + if ((d[s-1] >= 'a' && d[s-1] <= 'z') || + (d[s-1] >= 'A' && d[s-1] <= 'Z') || + (d[s-1] >= '0' && d[s-1] <= '9') || + d[s-1] == '.' || d[s-1] == '_') + s--; + else + break; + } + for (e = i; e < b->datalength; ) + { + if ((d[e] >= 'a' && d[e] <= 'z') || + (d[e] >= 'A' && d[e] <= 'Z') || + (d[e] >= '0' && d[e] <= '9') || + /*d[e] == '.' ||*/ d[e] == '_') + e++; + else + break; + } + if (e >= s+sizeof(linebuf)) + e = s+sizeof(linebuf) - 1; + memcpy(linebuf, d+s, e - s); + linebuf[e-s] = 0; + if (*linebuf) + tooltip = editprogfuncs->EvaluateDebugString(editprogfuncs, linebuf); + break; + } + nx = nnx; + } + } + nx = -viewportx; for (i = 0; i < b->datalength; i++) { if (*d == '\t') { if (d == c) - Font_DrawChar(nx, y, (int)11 | (CON_WHITEMASK)); + { + int e = Font_DrawChar(nx, y, (int)11 | (CON_WHITEMASK|CON_BLINKTEXT)); + if (e >= vid.pixelwidth) + viewportx += e - vid.pixelwidth; + if (nx < 0) + { + viewportx -= -nx; + if (viewportx < 0) + viewportx = 0; + } + } nx+=ts; - nx-=(nx - x)%ts; + nx-=(nx - -viewportx)%ts; d++; continue; } - if (nx < (int)vid.pixelwidth) - nnx = Font_DrawChar(nx, y, (int)*d | (colour<=0) + nnx = Font_DrawChar(nx, y, (int)*d | (colour)); else nnx = vid.pixelwidth; if (d == c) - Font_DrawChar(nx, y, (int)11 | (CON_WHITEMASK)); + { + int e = Font_DrawChar(nx, y, (int)11 | (CON_WHITEMASK|CON_BLINKTEXT)); + if (e >= vid.pixelwidth) + viewportx += e - vid.pixelwidth; + if (nx < 0) + { + viewportx -= -nx; + if (viewportx < 0) + viewportx = 0; + } + } nx = nnx; d++; @@ -794,8 +985,32 @@ static void Draw_Line(int x, int y, fileblock_t *b, int cursorx) /*we didn't do the cursor! stick it at the end*/ if (c && c >= d) - Font_DrawChar(nx, y, (int)11 | (CON_WHITEMASK)); + { + int e = Font_DrawChar(nx, y, (int)11 | (CON_WHITEMASK|CON_BLINKTEXT)); + if (e >= vid.pixelwidth) + viewportx += e - vid.pixelwidth; + if (nx < 0) + { + viewportx -= -nx; + if (viewportx < 0) + viewportx = 0; + } + } + if (tooltip) + { + while(*tooltip) + { + if (*tooltip == '\n') + { + smy += Font_CharHeight(); + smx = (mousecursor_x * vid.pixelwidth) / vid.width; + tooltip++; + } + else + smx = Font_DrawChar(smx, smy, (COLOR_CYAN<data[y] == '\0') - break; - else if (cursorblock->data[y] == '\t') - { - x+=32; - x&=~31; - } - else - x+=8; - } - x=-x + vid.width/2; - if (x > 0) - x = 0; - if (madechanges) Draw_FunString (vid.width - 8, 0, "!"); if (!insertkeyhit) Draw_FunString (vid.width - 16, 0, "O"); + if (!editenabled) + Draw_FunString (vid.width - 24, 0, "R"); Draw_FunString(0, 0, va("%6i:%4i:%s", cursorlinenum, cursorx+1, OpenEditorFile)); if (useeval) @@ -915,9 +1114,8 @@ void Editor_Draw(void) { c = -1; if (b == cursorblock) - if ((int)(Sys_DoubleTime()*4.0) & 1) - c = cursorx; - Draw_Line(x, y, b, c); + c = cursorx; + Draw_Line(y, b, c); y+=8; if (y > vid.height) @@ -947,10 +1145,10 @@ void Editor_Draw(void) */ } -int QCLibEditor(progfuncs_t *prfncs, char *filename, int line, int nump, char **parms) +int QCLibEditor(progfuncs_t *prfncs, char *filename, int line, int statement, int nump, char **parms) { char *f1, *f2; - if (editormodal || line < 0 || !debugger.ival) + if (editormodal || (line < 0 && !statement) || !debugger.ival) return line; //whoops if (qrenderer == QR_NONE) @@ -988,38 +1186,82 @@ int QCLibEditor(progfuncs_t *prfncs, char *filename, int line, int nump, char ** f1 += 4; if (!strncmp(f2, "src/", 4)) f2 += 4; - if (!editoractive || strcmp(f1, f2)) - { - if (editoractive) - EditorSaveFile(OpenEditorFile); - EditorOpenFile(filename); + stepasm = line < 0; + + if (stepasm) + { + fileblock_t *nb, *lb; + int i; + EditorNewFile(); + E_Free(firstblock->next); + E_Free(firstblock); + + cursorlinenum = statement; + firstblock = GenAsm(cursorlinenum); + cursorblock = firstblock; + + for (i = cursorlinenum; i > 0 && i > cursorlinenum - 20; i) + { + i--; + firstblock->prev = GenAsm(i); + firstblock->prev->next = firstblock; + firstblock = firstblock->prev; + } + lb = cursorblock; + for (i = cursorlinenum; i < cursorlinenum+20; ) + { + i++; + nb = GenAsm(i); + lb->next = nb; + nb->prev = lb; + lb = nb; + } + } + else + { + if (!editoractive || strcmp(f1, f2)) + { + if (editoractive && madechanges) + EditorSaveFile(OpenEditorFile); + + EditorOpenFile(filename, true); + } + + for (cursorlinenum = 1, cursorblock = firstblock; cursorlinenum < line && cursorblock->next; cursorlinenum++) + cursorblock=cursorblock->next; } - for (cursorlinenum = 1, cursorblock = firstblock; cursorlinenum < line && cursorblock->next; cursorlinenum++) - cursorblock=cursorblock->next; + executionlinenum = cursorlinenum; executionblock = cursorblock; if (!parms) { + double oldrealtime = realtime; editormodal = true; while(editormodal && editoractive && editprogfuncs) { + realtime = Sys_DoubleTime(); // key_dest = key_editor; scr_disabled_for_loading=false; SCR_UpdateScreen(); Sys_SendKeyEvents(); + IN_Commands (); S_ExtraUpdate(); - NET_Sleep(100, false); //any os. + NET_Sleep(20, false); //any os. } + realtime = oldrealtime; editormodal = false; } - return line; + if (stepasm) + return -executionlinenum; + else + return executionlinenum; } void Editor_ProgsKilled(progfuncs_t *dead) @@ -1042,9 +1284,9 @@ static void Editor_f(void) editprogfuncs = NULL; useeval = false; - if (editoractive) + if (editoractive && madechanges) EditorSaveFile(OpenEditorFile); - EditorOpenFile(Cmd_Argv(1)); + EditorOpenFile(Cmd_Argv(1), false); // EditorNewFile(); } @@ -1052,7 +1294,6 @@ void Editor_Init(void) { Cmd_AddCommand("edit", Editor_f); - Cvar_Register(&alloweditor, "Text editor"); Cvar_Register(&editstripcr, "Text editor"); Cvar_Register(&editaddcr, "Text editor"); Cvar_Register(&edittabspacing, "Text editor"); diff --git a/engine/client/view.c b/engine/client/view.c index fcc1bfc6..810d1057 100644 --- a/engine/client/view.c +++ b/engine/client/view.c @@ -142,19 +142,21 @@ V_CalcBob float V_CalcBob (int pnum, qboolean queryold) { static double bobtime[MAX_SPLITS]; + static double cltime[MAX_SPLITS]; static float bob[MAX_SPLITS]; float cycle; if (cl.spectator) return 0; - if (!cl.onground[pnum] || cl.paused || queryold) + if (!cl.onground[pnum] || cl.paused) return bob[pnum]; // just use old value if (cl_bobcycle.value <= 0) return 0; - bobtime[pnum] += host_frametime; + bobtime[pnum] += cl.time - cltime[pnum]; + cltime[pnum] = cl.time; cycle = bobtime[pnum] - (int)(bobtime[pnum]/cl_bobcycle.value)*cl_bobcycle.value; cycle /= cl_bobcycle.value; if (cycle < cl_bobup.value) @@ -568,7 +570,7 @@ void V_SetContentsColor (int contents) cl.cshifts[CSHIFT_CONTENTS].percent *= v_contentblend.value; - if (cl.cshifts[CSHIFT_SERVER].percent) + if (cl.cshifts[CSHIFT_CONTENTS].percent) { //bound contents so it can't go negative if (cl.cshifts[CSHIFT_CONTENTS].percent < 0) cl.cshifts[CSHIFT_CONTENTS].percent = 0; @@ -1292,13 +1294,16 @@ void R_DrawNameTags(void) continue; if (i == cl.playernum[r_refdef.currentplayernum]) continue; // Don't draw tag for the local player + if (cl.players[i].spectator) + continue; + if (i == Cam_TrackNum(r_refdef.currentplayernum)) + continue; if (TP_IsPlayerVisible(nametagorg[i])) { VectorCopy(nametagorg[i], tagcenter); tagcenter[2] += 32; - Matrix4x4_CM_Project(tagcenter, center, r_refdef.viewangles, r_refdef.vieworg, r_refdef.fov_x, r_refdef.fov_y); - if (center[2] > 1) + if (!Matrix4x4_CM_Project(tagcenter, center, r_refdef.viewangles, r_refdef.vieworg, r_refdef.fov_x, r_refdef.fov_y)) continue; len = COM_ParseFunString(CON_WHITEMASK, cl.players[i].name, buffer, sizeof(buffer), false) - buffer; @@ -1307,6 +1312,7 @@ void R_DrawNameTags(void) } } +void R2D_PolyBlend (void); void V_RenderPlayerViews(int plnum) { int oldnuments; @@ -1333,6 +1339,7 @@ void V_RenderPlayerViews(int plnum) Cam_SelfTrack(plnum); R_RenderView (); + R2D_PolyBlend (); R_DrawNameTags(); cl_numvisedicts = oldnuments; diff --git a/engine/common/bothdefs.h b/engine/common/bothdefs.h index 76db8cbe..cc2aac1f 100644 --- a/engine/common/bothdefs.h +++ b/engine/common/bothdefs.h @@ -175,6 +175,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #endif #endif #else + #define USE_SQLITE +// #define USE_MYSQL + #define SIDEVIEWS 4 //enable secondary/reverse views. #define SP2MODELS //quake2 sprite models @@ -260,6 +263,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #undef IRCCONNECT #endif +#ifndef MULTITHREAD + #undef USE_SQLITE + #undef USE_MYSQL +#endif + +#if defined(USE_SQLITE) || defined(USE_MYSQL) + #define SQL +#endif //fix things a little... #ifdef NPQTV diff --git a/engine/common/cmd.c b/engine/common/cmd.c index 0747d18e..056342f6 100644 --- a/engine/common/cmd.c +++ b/engine/common/cmd.c @@ -1336,10 +1336,10 @@ char *Cmd_ExpandStringArguments (char *data, char *dest, int destlen) ============ Cmd_TokenizeString -Parses the given string into command line tokens. +Parses the given string into command line tokens, stopping at the \n ============ */ -void Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize) +char *Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize) { int i; @@ -1365,7 +1365,7 @@ void Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize) } if (!*text) - return; + return text; if (cmd_argc == 1) { @@ -1374,7 +1374,9 @@ void Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize) text = COM_StringParse (text, com_token, sizeof(com_token), expandmacros, qctokenize); if (!text) - return; + return text; + if (!strcmp(com_token, "\n")) + return text; if (cmd_argc < MAX_ARGS) { @@ -1383,6 +1385,7 @@ void Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize) cmd_argc++; } } + return text; } void Cmd_TokenizePunctation (char *text, char *punctuation) @@ -1438,7 +1441,7 @@ Cmd_AddCommand ============ */ -qboolean Cmd_AddCommand (char *cmd_name, xcommand_t function) +qboolean Cmd_AddCommandD (char *cmd_name, xcommand_t function, char *desc) { cmd_function_t *cmd; @@ -1467,6 +1470,7 @@ qboolean Cmd_AddCommand (char *cmd_name, xcommand_t function) cmd = (cmd_function_t*)Z_Malloc (sizeof(cmd_function_t)+strlen(cmd_name)+1); cmd->name = (char*)(cmd+1); + cmd->description = desc; strcpy(cmd->name, cmd_name); cmd->function = function; cmd->next = cmd_functions; @@ -1476,6 +1480,11 @@ qboolean Cmd_AddCommand (char *cmd_name, xcommand_t function) return true; } +qboolean Cmd_AddCommand (char *cmd_name, xcommand_t function) +{ + return Cmd_AddCommandD(cmd_name, function, NULL); +} + void Cmd_RemoveCommand (char *cmd_name) { cmd_function_t *cmd, **back; @@ -1660,8 +1669,9 @@ typedef struct { qboolean allowcutdown; qboolean cutdown; char result[256]; + char *desc; } match_t; -void Cmd_CompleteCheck(char *check, match_t *match) //compare cumulative strings and join the result +void Cmd_CompleteCheck(char *check, match_t *match, char *desc) //compare cumulative strings and join the result { if (*match->result) { @@ -1678,21 +1688,19 @@ void Cmd_CompleteCheck(char *check, match_t *match) //compare cumulative strings else if (match->matchnum > 0) { strcpy(match->result, check); + match->desc = desc; match->matchnum--; } } else { if (match->matchnum > 0) - { - strcpy(match->result, check); match->matchnum--; - } - else - strcpy(match->result, check); + strcpy(match->result, check); + match->desc = desc; } } -char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens, int matchnum) +char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens, int matchnum, char **descptr) { extern cvar_group_t *cvar_groups; cmd_function_t *cmd; @@ -1711,6 +1719,9 @@ char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens else len = Q_strlen(partial); + if (descptr) + *descptr = NULL; + if (!len) return NULL; @@ -1719,6 +1730,7 @@ char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens match.allowcutdown = !fullonly?true:false; match.cutdown = false; + match.desc = NULL; if (matchnum) match.matchnum = matchnum; else @@ -1731,17 +1743,17 @@ char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens { for (cmd=cmd_functions ; cmd ; cmd=cmd->next) if (!Q_strncasecmp (partial,cmd->name, len) && (matchnum == -1 || !partial[len] || strlen(cmd->name) == len)) - Cmd_CompleteCheck(cmd->name, &match); + Cmd_CompleteCheck(cmd->name, &match, cmd->description); for (a=cmd_alias ; a ; a=a->next) if (!Q_strncasecmp (partial, a->name, len) && (matchnum == -1 || !partial[len] || strlen(a->name) == len)) - Cmd_CompleteCheck(a->name, &match); + Cmd_CompleteCheck(a->name, &match, ""); for (grp=cvar_groups ; grp ; grp=grp->next) for (cvar=grp->cvars ; cvar ; cvar=cvar->next) { if (!Q_strncasecmp (partial,cvar->name, len) && (matchnum == -1 || !partial[len] || strlen(cvar->name) == len)) - Cmd_CompleteCheck(cvar->name, &match); + Cmd_CompleteCheck(cvar->name, &match, cvar->description); if (cvar->name2 && !Q_strncasecmp (partial,cvar->name2, len) && (matchnum == -1 || !partial[len] || strlen(cvar->name2) == len)) - Cmd_CompleteCheck(cvar->name2, &match); + Cmd_CompleteCheck(cvar->name2, &match, cvar->description); } } @@ -1749,23 +1761,26 @@ char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens { for (cmd=cmd_functions ; cmd ; cmd=cmd->next) if (!Q_strncmp (partial,cmd->name, len) && (matchnum == -1 || !partial[len] || strlen(cmd->name) == len)) - Cmd_CompleteCheck(cmd->name, &match); + Cmd_CompleteCheck(cmd->name, &match, cmd->description); for (a=cmd_alias ; a ; a=a->next) if (!Q_strncmp (partial, a->name, len) && (matchnum == -1 || !partial[len] || strlen(a->name) == len)) - Cmd_CompleteCheck(a->name, &match); + Cmd_CompleteCheck(a->name, &match, ""); for (grp=cvar_groups ; grp ; grp=grp->next) for (cvar=grp->cvars ; cvar ; cvar=cvar->next) { if (!Q_strncmp (partial,cvar->name, len) && (matchnum == -1 || !partial[len] || strlen(cvar->name) == len)) - Cmd_CompleteCheck(cvar->name, &match); + Cmd_CompleteCheck(cvar->name, &match, cvar->description); if (cvar->name2 && !Q_strncmp (partial,cvar->name2, len) && (matchnum == -1 || !partial[len] || strlen(cvar->name2) == len)) - Cmd_CompleteCheck(cvar->name2, &match); + Cmd_CompleteCheck(cvar->name2, &match, cvar->description); } } if (match.matchnum>0) return NULL; if (!*match.result) return NULL; + + if (descptr) + *descptr = match.desc; return match.result; } @@ -2735,6 +2750,7 @@ void Cmd_WriteConfig_f(void) vfsfile_t *f; char *filename; char fname[MAX_OSPATH]; + char sysname[MAX_OSPATH]; filename = Cmd_Argv(1); if (!*filename) @@ -2779,6 +2795,9 @@ void Cmd_WriteConfig_f(void) VFS_CLOSE(f); Cvar_Saved(); + + FS_NativePath(fname, FS_GAMEONLY, sysname, sizeof(sysname)); + Con_Printf ("Wrote %s\n",sysname); } void Cmd_Reset_f(void) diff --git a/engine/common/cmd.h b/engine/common/cmd.h index 5755a72f..48e17f48 100644 --- a/engine/common/cmd.h +++ b/engine/common/cmd.h @@ -78,6 +78,7 @@ void Cmd_StuffCmds (void); void Cmd_RemoveCommand (char *cmd_name); qboolean Cmd_AddCommand (char *cmd_name, xcommand_t function); +qboolean Cmd_AddCommandD (char *cmd_name, xcommand_t function, char *description); // called by the init functions of other parts of the program to // register commands and functions to call for them. // The cmd_name is referenced later, so it should not be in temp memory @@ -89,7 +90,7 @@ qboolean Cmd_Exists (char *cmd_name); char *Cmd_Describe (char *cmd_name); -char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens, int matchnum); +char *Cmd_CompleteCommand (char *partial, qboolean fullonly, qboolean caseinsens, int matchnum, char **descptr); qboolean Cmd_IsCommand (char *line); // attempts to match a partial command for automatic command line completion // returns NULL if nothing fits @@ -114,7 +115,7 @@ void Alias_WipeStuffedAliaes(void); void Cmd_AddMacro(char *s, char *(*f)(void), int disputableintentions); void Cmd_TokenizePunctation (char *text, char *punctuation); -void Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize); +char *Cmd_TokenizeString (char *text, qboolean expandmacros, qboolean qctokenize); // Takes a null terminated string. Does not need to be /n terminated. // breaks the string up into arg tokens. diff --git a/engine/common/com_mesh.c b/engine/common/com_mesh.c index f029d838..2fc43d29 100644 --- a/engine/common/com_mesh.c +++ b/engine/common/com_mesh.c @@ -1534,8 +1534,9 @@ qboolean Alias_GAliasBuildMesh(mesh_t *mesh, galiasinfo_t *inf, int surfnum, ent #ifdef SKELETALMODELS meshcache.usebonepose = NULL; - if (inf->ofs_skel_xyz && 1)//!inf->ofs_skel_weight) + if (inf->ofs_skel_xyz && !inf->ofs_skel_weight) { + //if we have skeletal xyz info, but no skeletal weights, then its a partial model that cannot possibly be animated. meshcache.usebonepose = NULL; mesh->xyz_array = (vecV_t*)((char*)inf + inf->ofs_skel_xyz); mesh->xyz2_array = NULL; @@ -1548,8 +1549,10 @@ qboolean Alias_GAliasBuildMesh(mesh_t *mesh, galiasinfo_t *inf, int surfnum, ent mesh->xyz2_array = NULL; meshcache.usebonepose = Alias_GetBonePositions(inf, &e->framestate, meshcache.bonepose, MAX_BONES, true); - if (e->fatness || !inf->ofs_skel_idx || !usebones) + if (e->fatness || !inf->ofs_skel_idx || !usebones || inf->numswtransforms) { + //software bone animation + //there are two ways to animate a skeleton, one is to transform Alias_BuildSkeletalMesh(mesh, meshcache.usebonepose, inf); #ifdef PEXT_FATNESS @@ -1575,6 +1578,7 @@ qboolean Alias_GAliasBuildMesh(mesh_t *mesh, galiasinfo_t *inf, int surfnum, ent } else { + //hardware bone animation mesh->xyz_array = (vecV_t*)((char*)inf + inf->ofs_skel_xyz); mesh->normals_array = (vec3_t*)((char*)inf + inf->ofs_skel_norm); mesh->snormals_array = (vec3_t*)((char*)inf + inf->ofs_skel_svect); @@ -5842,7 +5846,7 @@ galiasinfo_t *Mod_ParseIQMMeshModel(model_t *mod, char *buffer) Q_strncpyz(bones[i].name, strings+ijoint[i].name, sizeof(bones[i].name)); bones[i].parent = ijoint[i].parent; - GenMatrixPosQuat3Scale(ijoint[i].translate, ijoint[i].rotate, ijoint[i].scale, &basepose[i*12]); + GenMatrixPosQuat3Scale(ijoint[i].translate, ijoint[i].rotate, ijoint[i].scale, mat); if (ijoint[i].parent >= 0) Matrix3x4_Multiply(mat, &basepose[ijoint[i].parent*12], &basepose[i*12]); @@ -5932,7 +5936,7 @@ galiasinfo_t *Mod_ParseIQMMeshModel(model_t *mod, char *buffer) for (i = 0; i < h->num_anims; i++) { fgroup[i].isheirachical = true; - fgroup[i].loop = LittleLong(anim[i].flags) & IQM_LOOP; + fgroup[i].loop = !!(LittleLong(anim[i].flags) & IQM_LOOP); Q_strncpyz(fgroup[i].name, strings+anim[i].name, sizeof(fgroup[i].name)); fgroup[i].numposes = LittleLong(anim[i].num_frames); fgroup[i].poseofs = (char*)(opose+LittleLong(anim[i].first_frame)*12*h->num_poses) - (char*)&fgroup[i]; diff --git a/engine/common/com_phys_ode.c b/engine/common/com_phys_ode.c index d3c7c920..8670cafe 100644 --- a/engine/common/com_phys_ode.c +++ b/engine/common/com_phys_ode.c @@ -482,7 +482,7 @@ void (ODE_API *dJointSetUniversalParam)(dJointID, int parameter, dRea //void (ODE_API *dJointSetPistonAnchorOffset)(dJointID j, dReal x, dReal y, dReal z, dReal dx, dReal dy, dReal dz); //void (ODE_API *dJointSetPistonParam)(dJointID, int parameter, dReal value); //void (ODE_API *dJointAddPistonForce)(dJointID joint, dReal force); -//void (ODE_API *dJointSetFixed)(dJointID); +void (ODE_API *dJointSetFixed)(dJointID); //void (ODE_API *dJointSetFixedParam)(dJointID, int parameter, dReal value); //void (ODE_API *dJointSetAMotorNumAxes)(dJointID, int num); //void (ODE_API *dJointSetAMotorAxis)(dJointID, int anum, int rel, dReal x, dReal y, dReal z); @@ -947,7 +947,7 @@ static dllfunction_t odefuncs[] = // {"dJointSetPistonAnchorOffset", (void **) &dJointSetPistonAnchorOffset}, // {"dJointSetPistonParam", (void **) &dJointSetPistonParam}, // {"dJointAddPistonForce", (void **) &dJointAddPistonForce}, -// {"dJointSetFixed", (void **) &dJointSetFixed}, + {(void **) &dJointSetFixed, "dJointSetFixed"}, // {"dJointSetFixedParam", (void **) &dJointSetFixedParam}, // {"dJointSetAMotorNumAxes", (void **) &dJointSetAMotorNumAxes}, // {"dJointSetAMotorAxis", (void **) &dJointSetAMotorAxis}, @@ -1177,7 +1177,7 @@ void World_ODE_Init(void) const char* dllname = { # if defined(WIN64) - "libode1_64.dll" + "libode1_64" # elif defined(WIN32) "ode_double" # elif defined(MACOSX) @@ -1664,7 +1664,6 @@ static void World_ODE_Frame_JointFromEntity(world_t *world, wedict_t *ed) break; case 0: default: - Sys_Error("what? but above the joint was valid...\n"); break; } #undef SETPARAMS @@ -1771,11 +1770,169 @@ static qboolean GenerateCollisionMesh(world_t *world, model_t *mod, wedict_t *ed ed->ode.ode_numtriangles = numindexes/3; return true; } -/* -static void World_ODE_BodyFromSkel(world_t *world) + +qboolean World_ODE_RagCreateBody(world_t *world, odebody_t *bodyptr, float *mat, wedict_t *ent) { + dVector3 r[3]; + + if (!world->ode.ode_space) + return false; + bodyptr->ode_geom = dCreateBox(world->ode.ode_space, 3, 3, 3); + bodyptr->ode_body = dBodyCreate(world->ode.ode_world); + dGeomSetBody(bodyptr->ode_geom, bodyptr->ode_body); + dGeomSetData(bodyptr->ode_geom, (void*)ent); + + r[0][0] = mat[0]; + r[0][1] = mat[1]; + r[0][2] = mat[2]; + r[1][0] = mat[4]; + r[1][1] = mat[5]; + r[1][2] = mat[6]; + r[2][0] = mat[8]; + r[2][1] = mat[9]; + r[2][2] = mat[10]; + + dBodySetPosition(bodyptr->ode_body, mat[3], mat[7], mat[11]); + dBodySetRotation(bodyptr->ode_body, r[0]); + dBodySetLinearVel(bodyptr->ode_body, 0, 0, 0); + dBodySetAngularVel(bodyptr->ode_body, 0, 0, 0); + return true; } -*/ + +void World_ODE_RagMatrixFromBody(world_t *world, odebody_t *bodyptr, float *mat) +{ + const dReal *o = dBodyGetPosition(bodyptr->ode_body); + const dReal *r = dBodyGetRotation(bodyptr->ode_body); + mat[0] = r[0]; + mat[1] = r[1]; + mat[2] = r[2]; + mat[3] = o[0]; + + mat[4] = r[4]; + mat[5] = r[5]; + mat[6] = r[6]; + mat[7] = o[1]; + + mat[8] = r[8]; + mat[9] = r[9]; + mat[10] = r[10]; + mat[11] = o[2]; +} + +void World_ODE_RagCreateJoint(world_t *world, odejoint_t *joint, odejointinfo_t *info, odebody_t *body1, odebody_t *body2, vec3_t aaa2[3]) +{ + switch(info->type) + { + case JOINTTYPE_POINT: + joint->ode_joint = dJointCreateBall(world->ode.ode_world, 0); + break; + case JOINTTYPE_HINGE: + joint->ode_joint = dJointCreateHinge(world->ode.ode_world, 0); + break; + case JOINTTYPE_SLIDER: + joint->ode_joint = dJointCreateSlider(world->ode.ode_world, 0); + break; + case JOINTTYPE_UNIVERSAL: + joint->ode_joint = dJointCreateUniversal(world->ode.ode_world, 0); + break; + case JOINTTYPE_HINGE2: + joint->ode_joint = dJointCreateHinge2(world->ode.ode_world, 0); + break; + case JOINTTYPE_FIXED: + joint->ode_joint = dJointCreateFixed(world->ode.ode_world, 0); + break; + default: + joint->ode_joint = NULL; + break; + } + if (joint->ode_joint) + { + //Con_Printf("made new joint %i\n", (int) (ed - prog->edicts)); +// dJointSetData(joint->ode_joint, NULL); + dJointAttach(joint->ode_joint, body1?body1->ode_body:NULL, body2?body2->ode_body:NULL); + + switch(info->type) + { + case JOINTTYPE_POINT: + dJointSetBallAnchor(joint->ode_joint, aaa2[0][0], aaa2[0][1], aaa2[0][2]); + break; + case JOINTTYPE_HINGE: + dJointSetHingeAnchor(joint->ode_joint, aaa2[0][0], aaa2[0][1], aaa2[0][2]); + dJointSetHingeAxis(joint->ode_joint, aaa2[1][0], aaa2[1][1], aaa2[1][2]); + dJointSetHingeParam(joint->ode_joint, dParamFMax, info->FMax); + dJointSetHingeParam(joint->ode_joint, dParamHiStop, info->HiStop); + dJointSetHingeParam(joint->ode_joint, dParamLoStop, info->LoStop); + dJointSetHingeParam(joint->ode_joint, dParamStopCFM, info->CFM); + dJointSetHingeParam(joint->ode_joint, dParamStopERP, info->ERP); + dJointSetHingeParam(joint->ode_joint, dParamVel, info->Vel); + break; + case JOINTTYPE_SLIDER: + dJointSetSliderAxis(joint->ode_joint, aaa2[1][0], aaa2[1][1], aaa2[1][2]); + dJointSetSliderParam(joint->ode_joint, dParamFMax, info->FMax); + dJointSetSliderParam(joint->ode_joint, dParamHiStop, info->HiStop); + dJointSetSliderParam(joint->ode_joint, dParamLoStop, info->LoStop); + dJointSetSliderParam(joint->ode_joint, dParamStopCFM, info->CFM); + dJointSetSliderParam(joint->ode_joint, dParamStopERP, info->ERP); + dJointSetSliderParam(joint->ode_joint, dParamVel, info->Vel); + break; + case JOINTTYPE_UNIVERSAL: + dJointSetUniversalAnchor(joint->ode_joint, aaa2[0][0], aaa2[0][1], aaa2[0][2]); + dJointSetUniversalAxis1(joint->ode_joint, aaa2[1][0], aaa2[1][1], aaa2[1][2]); + dJointSetUniversalAxis2(joint->ode_joint, aaa2[2][0], aaa2[2][1], aaa2[2][2]); + dJointSetUniversalParam(joint->ode_joint, dParamFMax, info->FMax); + dJointSetUniversalParam(joint->ode_joint, dParamHiStop, info->HiStop); + dJointSetUniversalParam(joint->ode_joint, dParamLoStop, info->LoStop); + dJointSetUniversalParam(joint->ode_joint, dParamStopCFM, info->CFM); + dJointSetUniversalParam(joint->ode_joint, dParamStopERP, info->ERP); + dJointSetUniversalParam(joint->ode_joint, dParamVel, info->Vel); + dJointSetUniversalParam(joint->ode_joint, dParamFMax2, info->FMax2); + dJointSetUniversalParam(joint->ode_joint, dParamHiStop2, info->HiStop2); + dJointSetUniversalParam(joint->ode_joint, dParamLoStop2, info->LoStop2); + dJointSetUniversalParam(joint->ode_joint, dParamStopCFM2, info->CFM2); + dJointSetUniversalParam(joint->ode_joint, dParamStopERP2, info->ERP2); + dJointSetUniversalParam(joint->ode_joint, dParamVel2, info->Vel2); + break; + case JOINTTYPE_HINGE2: + dJointSetHinge2Anchor(joint->ode_joint, aaa2[0][0], aaa2[0][1], aaa2[0][2]); + dJointSetHinge2Axis1(joint->ode_joint, aaa2[1][0], aaa2[1][1], aaa2[1][2]); + dJointSetHinge2Axis2(joint->ode_joint, aaa2[2][0], aaa2[2][1], aaa2[2][2]); + dJointSetHinge2Param(joint->ode_joint, dParamFMax, info->FMax); + dJointSetHinge2Param(joint->ode_joint, dParamHiStop, info->HiStop); + dJointSetHinge2Param(joint->ode_joint, dParamLoStop, info->LoStop); + dJointSetHinge2Param(joint->ode_joint, dParamStopCFM, info->CFM); + dJointSetHinge2Param(joint->ode_joint, dParamStopERP, info->ERP); + dJointSetHinge2Param(joint->ode_joint, dParamVel, info->Vel); + dJointSetHinge2Param(joint->ode_joint, dParamFMax2, info->FMax2); + dJointSetHinge2Param(joint->ode_joint, dParamHiStop2, info->HiStop2); + dJointSetHinge2Param(joint->ode_joint, dParamLoStop2, info->LoStop2); + dJointSetHinge2Param(joint->ode_joint, dParamStopCFM2, info->CFM2); + dJointSetHinge2Param(joint->ode_joint, dParamStopERP2, info->ERP2); + dJointSetHinge2Param(joint->ode_joint, dParamVel2, info->Vel2); + break; + case JOINTTYPE_FIXED: + dJointSetFixed(joint->ode_joint); + break; + } + } +} + +void World_ODE_RagDestroyBody(world_t *world, odebody_t *bodyptr) +{ + if (bodyptr->ode_geom) + dGeomDestroy(bodyptr->ode_geom); + bodyptr->ode_geom = NULL; + if (bodyptr->ode_body) + dBodyDestroy(bodyptr->ode_body); + bodyptr->ode_body = NULL; +} + +void World_ODE_RagDestroyJoint(world_t *world, odejoint_t *joint) +{ + if (joint->ode_joint) + dJointDestroy(joint->ode_joint); + joint->ode_joint = NULL; +} + static void World_ODE_Frame_BodyFromEntity(world_t *world, wedict_t *ed) { dBodyID body = (dBodyID)ed->ode.ode_body; @@ -1995,21 +2152,13 @@ static void World_ODE_Frame_BodyFromEntity(world_t *world, wedict_t *ed) } // get current data from entity - VectorClear(origin); - VectorClear(velocity); - //VectorClear(forward); - //VectorClear(left); - //VectorClear(up); - //VectorClear(spinvelocity); - VectorClear(angles); - VectorClear(avelocity); gravity = true; VectorCopy(ed->v->origin, origin); VectorCopy(ed->v->velocity, velocity); - //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.axis_forward);if (val) VectorCopy(val->vector, forward); - //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.axis_left);if (val) VectorCopy(val->vector, left); - //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.axis_up);if (val) VectorCopy(val->vector, up); - //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.spinvelocity);if (val) VectorCopy(val->vector, spinvelocity); + //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.axis_forward);if (val) VectorCopy(val->vector, forward); else VectorClear(forward); + //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.axis_left);if (val) VectorCopy(val->vector, left); else VectorClear(left); + //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.axis_up);if (val) VectorCopy(val->vector, up); else VectorClear(up); + //val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.spinvelocity);if (val) VectorCopy(val->vector, spinvelocity); else VectorClear(spinvelocity); VectorCopy(ed->v->angles, angles); VectorCopy(ed->v->avelocity, avelocity); if (ed == world->edicts || (ed->xv->gravity && ed->xv->gravity <= 0.01)) @@ -2231,11 +2380,11 @@ static void VARGS nearCallback (void *data, dGeomID o1, dGeomID o2) return; ed1 = (wedict_t *) dGeomGetData(o1); - if(ed1 && ed1->isfree) - ed1 = NULL; + if(!ed1 || ed1->isfree) + ed1 = world->edicts; ed2 = (wedict_t *) dGeomGetData(o2); - if(ed2 && ed2->isfree) - ed2 = NULL; + if(!ed2 || ed2->isfree) + ed2 = world->edicts; // generate contact points between the two non-space geoms numcontacts = dCollide(o1, o2, MAX_CONTACTS, &(contact[0].geom), sizeof(contact[0])); @@ -2317,7 +2466,7 @@ static void VARGS nearCallback (void *data, dGeomID o1, dGeomID o2) void World_ODE_Frame(world_t *world, double frametime, double gravity) { - if (world->ode.ode && (world->ode.hasodeents))// || world->ode.hasragdoll)) + if (world->ode.ode && (world->ode.hasodeents || world->ode.hasextraobjs)) { int i; wedict_t *ed; diff --git a/engine/common/common.c b/engine/common/common.c index 7f4aeb18..5fee2d40 100644 --- a/engine/common/common.c +++ b/engine/common/common.c @@ -93,6 +93,7 @@ cvar_t gameversion = CVARFD("gameversion","", CVAR_SERVERINFO, "gamecode version cvar_t gameversion_min = CVARD("gameversion_min","", "gamecode version for server browsers"); cvar_t gameversion_max = CVARD("gameversion_max","", "gamecode version for server browsers"); cvar_t fs_gamename = CVARFD("fs_gamename", "", CVAR_NOSET, "The filesystem is trying to run this game"); +cvar_t fs_gamedownload = CVARFD("fs_gamedownload", "", CVAR_NOSET, "The place that the game can be downloaded from."); cvar_t com_protocolname = CVARD("com_gamename", "", "The game name used for dpmaster queries"); cvar_t com_modname = CVARD("com_modname", "", "dpmaster information"); cvar_t com_parseutf8 = CVARD("com_parseutf8", "0", "Interpret console messages/playernames/etc as UTF-8. Requires special fonts. -1=iso 8859-1. 0=quakeascii(chat uses high chars). 1=utf8, revert to ascii on decode errors. 2=utf8 ignoring errors"); //1 parse. 2 parse, but stop parsing that string if a char was malformed. @@ -188,7 +189,7 @@ void QDECL Q_strncpyz(char *d, const char *s, int n) //windows/linux have inconsistant snprintf //this is an attempt to get them consistant and safe //size is the total size of the buffer -void VARGS Q_vsnprintfz (char *dest, size_t size, char *fmt, va_list argptr) +void VARGS Q_vsnprintfz (char *dest, size_t size, const char *fmt, va_list argptr) { vsnprintf (dest, size, fmt, argptr); dest[size-1] = 0; @@ -197,7 +198,7 @@ void VARGS Q_vsnprintfz (char *dest, size_t size, char *fmt, va_list argptr) //windows/linux have inconsistant snprintf //this is an attempt to get them consistant and safe //size is the total size of the buffer -void VARGS Q_snprintfz (char *dest, size_t size, char *fmt, ...) +void VARGS Q_snprintfz (char *dest, size_t size, const char *fmt, ...) { va_list argptr; @@ -405,7 +406,7 @@ char *Q_strlwr(char *s) int wildcmp(const char *wild, const char *string) { const char *cp=NULL, *mp=NULL; - +/* while ((*string) && (*wild != '*')) { if ((*wild != *string) && (*wild != '?')) @@ -415,30 +416,29 @@ int wildcmp(const char *wild, const char *string) wild++; string++; } - +*/ while (*string) { if (*wild == '*') { - if (!*++wild) //a * at the end of the wild string matches anything the checked string has + if (wild[1] == *string || *string == '/' || *string == '\\') { - string = strchr(string, '/'); - if (string && string[1]) /*don't match it if there's a / with something after it*/ - return 0; - return 1; + //* terminates if we get a match on the char following it, or if its a \ or / char + wild++; + continue; } - mp = wild; - cp = string+1; + string++; } else if ((*wild == *string) || (*wild == '?')) { + //this char matches wild++; string++; } else { - wild = mp; - string = cp++; + //failure + return false; } } @@ -1629,7 +1629,7 @@ char *COM_SkipPath (const char *pathname) last = pathname; while (*pathname) { - if (*pathname=='/') + if (*pathname=='/' || *pathname == '\\') last = pathname+1; pathname++; } @@ -2455,77 +2455,25 @@ conchar_t *COM_ParseFunString(conchar_t defaultflags, const char *str, conchar_t messedup: if (!--outsize) break; + uc = (unsigned char)(*str++); if (utf8) - *out++ = (unsigned char)(*str++) | ext; + *out++ = uc | ext; else { - if (strchr("\n\r\t ", *str)) - *out++ = (unsigned char)(*str++) | (ext&~CON_HIGHCHARSMASK); - else if (*str >= 32 && *str < 127 && !(ext&CON_HIGHCHARSMASK)) - *out++ = (unsigned char)(*str++) | ext; + if (uc == '\n' || uc == '\r' || uc == '\t' || uc == ' ') + *out++ = uc | (ext&~CON_HIGHCHARSMASK); + else if (uc >= 32 && uc < 127 && !(ext&CON_HIGHCHARSMASK)) + *out++ = uc | ext; + else if (uc >= 0x80+32 && uc < 0x80+127) + *out++ = (uc&127) | ext ^ CON_2NDCHARSETTEXT; else - *out++ = (unsigned char)(*str++) | ext | 0xe000; + *out++ = uc | ext | 0xe000; } } *out = 0; return out; } -int COM_FunStringLength(unsigned char *str) -{ - //FIXME: - int len = 0; - - while(*str) - { - //fixme: utf8 - if (*str == '^') - { - str++; - if (*str >= '0' && *str <= '9') - str++; //invisible - else if (*str == '&') // extended code - { - if (isextendedcode(str[1]) && isextendedcode(str[2])) - { - str++;// foreground char - str++; // background char - str++; - continue; - } - // else invalid code - goto messedup; - } - else if (*str == 'a' || *str == 'b' || *str == 'h' || *str == 's' || *str == 'r') - str++; //invisible - else if (*str == '^') - { - len++; //double-code single-output - str++; - } - else - { - len++; //not recognised - len++; - str++; - } - continue; - } - if (*str == '&' && str[1] == 'c' && ishexcode(str[2]) && ishexcode(str[3]) && ishexcode(str[4])) - { - //ezquake colour codes - str += 5; - continue; - } -messedup: - len++; - str++; - } - - return len; -} - - //============================================================================ #define TOKENSIZE sizeof(com_token) @@ -3472,6 +3420,12 @@ void COM_Version_f (void) } #endif +#ifdef MULTITHREAD + Con_Printf("multithreading: enabled\n"); +#else + Con_Printf("multithreading: disabled\n"); +#endif + //print out which libraries are disabled #ifndef AVAIL_ZLIB Con_Printf("zlib disabled\n"); @@ -3493,6 +3447,37 @@ void COM_Version_f (void) #else Con_Printf("libjpeg: %i (%d series)\n", JPEG_LIB_VERSION, ( JPEG_LIB_VERSION / 10 ) ); #endif +#ifdef SPEEX_STATIC + Con_Printf("speex: static\n"); +#elif defined(VOICECHAT) + Con_Printf("speex: dynamic\n"); +#else + Con_Printf("speex: disabled\n"); +#endif +#ifdef ODE_STATIC + Con_Printf("ODE: static\n"); +#elif defined(USEODE) + Con_Printf("ODE: dynamic\n"); +#else + Con_Printf("ODE: disabled\n"); +#endif +#ifndef AVAIL_OGGVORBIS + Con_Printf("Ogg Vorbis: disabled\n"); +#elif defined(LIBVORBISFILE_STATIC) + Con_Printf("Ogg Vorbis: static\n"); +#else + Con_Printf("Ogg Vorbis: dynamic\n"); +#endif +#ifdef USE_MYSQL + Con_Printf("mySQL: dynamic\n"); +#else + Con_Printf("mySQL: disabled\n"); +#endif +#ifdef USE_SQLITE + Con_Printf("sqlite: dynamic\n"); +#else + Con_Printf("sqlite: disabled\n"); +#endif #ifndef AVAIL_OGGVORBIS Con_Printf("libvorbis disabled\n"); #endif @@ -3734,7 +3719,7 @@ void COM_Effectinfo_Reload(void) if (!f) return; buf = f; - while (*f) + while (f && *f) { f = COM_ParseToken(f, NULL); if (strcmp(com_token, "\n")) @@ -3749,7 +3734,7 @@ void COM_Effectinfo_Reload(void) do { f = COM_ParseToken(f, NULL); - } while(*f && strcmp(com_token, "\n")); + } while(f && *f && strcmp(com_token, "\n")); } } FS_FreeFile(buf); diff --git a/engine/common/common.h b/engine/common/common.h index cf76ac64..6e7ed2c0 100644 --- a/engine/common/common.h +++ b/engine/common/common.h @@ -211,8 +211,8 @@ int wildcmp(const char *wild, const char *string); //1 if match #define Q_strcmp(s1, s2) strcmp((s1), (s2)) #define Q_strncmp(s1, s2, n) strncmp((s1), (s2), (n)) -void VARGS Q_snprintfz (char *dest, size_t size, char *fmt, ...) LIKEPRINTF(3); -void VARGS Q_vsnprintfz (char *dest, size_t size, char *fmt, va_list args); +void VARGS Q_snprintfz (char *dest, size_t size, const char *fmt, ...) LIKEPRINTF(3); +void VARGS Q_vsnprintfz (char *dest, size_t size, const char *fmt, va_list args); int VARGS Com_sprintf(char *buffer, int size, const char *format, ...) LIKEPRINTF(3); #define Q_strncpyS(d, s, n) do{const char *____in=(s);char *____out=(d);int ____i; for (____i=0;*(____in); ____i++){if (____i == (n))break;*____out++ = *____in++;}if (____i < (n))*____out='\0';}while(0) //only use this when it should be used. If undiciided, use N @@ -277,7 +277,6 @@ void COM_ParsePlusSets (void); typedef unsigned int conchar_t; char *COM_DeFunString(conchar_t *str, conchar_t *stop, char *out, int outsize, qboolean ignoreflags); conchar_t *COM_ParseFunString(conchar_t defaultflags, const char *str, conchar_t *out, int outsize, qboolean keepmarkup); //ext is usually CON_WHITEMASK, returns its null terminator -int COM_FunStringLength(unsigned char *str); char *COM_SkipPath (const char *pathname); void COM_StripExtension (const char *in, char *out, int outlen); @@ -391,7 +390,6 @@ void FS_ReloadPackFiles(void); char *FSQ3_GenerateClientPacksList(char *buffer, int maxlen, int basechecksum); -FTE_DEPRECATED int COM_filelength (FILE *f); qbyte *COM_LoadStackFile (const char *path, void *buffer, int bufsize); qbyte *COM_LoadTempFile (const char *path); qbyte *COM_LoadTempMoreFile (const char *path); //allocates a little bit more without freeing old temp diff --git a/engine/common/console.h b/engine/common/console.h index ff5e0065..e9617e69 100644 --- a/engine/common/console.h +++ b/engine/common/console.h @@ -117,7 +117,6 @@ typedef struct console_s int x; // offset in current line for next print int cr; conline_t *display; // bottom of console displays this line - int subline; int vislines; // pixel lines int linesprinted; // for notify times qboolean unseentext; @@ -132,6 +131,15 @@ extern console_t con_main; extern console_t *con_current; // point to either con_main or con_chat extern console_t *con_chat; +//shared between console and keys. +//really the console input should be in console.c instead of keys.c I suppose. +#define MAXCMDLINE 256 +#define CON_EDIT_LINES_MASK ((1<<6)-1) +extern unsigned char key_lines[CON_EDIT_LINES_MASK+1][MAXCMDLINE]; +extern int edit_line; +extern int key_linepos; +extern int history_line; + extern int scr_chatmode; //extern int con_totallines; @@ -144,6 +152,7 @@ void Con_CheckResize (void); void Con_ForceActiveNow(void); void Con_Init (void); void Con_Shutdown (void); +void Con_History_Load(void); void Con_DrawConsole (int lines, qboolean noback); char *Con_CopyConsole(qboolean nomarkup); void Con_Print (char *txt); @@ -151,6 +160,7 @@ void VARGS Con_Printf (const char *fmt, ...) LIKEPRINTF(1); void VARGS Con_TPrintf (translation_t text, ...); void VARGS Con_DPrintf (char *fmt, ...) LIKEPRINTF(1); void VARGS Con_SafePrintf (char *fmt, ...) LIKEPRINTF(1); +void Con_Footerf(qboolean append, char *fmt, ...) LIKEPRINTF(2); void Con_Clear_f (void); void Con_DrawNotify (void); void Con_ClearNotify (void); diff --git a/engine/common/fs.c b/engine/common/fs.c index cd1c29ee..af3d1538 100644 --- a/engine/common/fs.c +++ b/engine/common/fs.c @@ -176,40 +176,6 @@ searchpath_t *com_searchpaths; searchpath_t *com_purepaths; searchpath_t *com_base_searchpaths; // without gamedirs -/* -================ -COM_filelength -================ -*/ -int COM_filelength (FILE *f) -{ - int pos; - int end; - - pos = ftell (f); - fseek (f, 0, SEEK_END); - end = ftell (f); - fseek (f, pos, SEEK_SET); - - return end; -} -/* -static int COM_FileOpenRead (char *path, FILE **hndl) -{ - FILE *f; - - f = fopen(path, "rb"); - if (!f) - { - *hndl = NULL; - return -1; - } - *hndl = f; - - return COM_filelength(f); -} -*/ - int COM_FileSize(const char *path) { int len; @@ -1810,8 +1776,8 @@ void COM_Gamedir (const char *dir) /*stuff that makes dp-only mods work a bit better*/ #define DPCOMPAT "set _cl_playermodel \"\"\n set dpcompat_set 1\n set dpcompat_trailparticles 1\nset dpcompat_corruptglobals 1\nset vid_pixelheight 1\n" -/*nexuiz/xonotic has a few quirks...*/ -#define NEXCFG DPCOMPAT "set r_particlesdesc effectinfo\nset sv_maxairspeed \"400\"\nset sv_jumpvelocity 270\nset sv_mintic \"0.01\"\ncl_nolerp 0\n" +/*nexuiz/xonotic has a few quirks/annoyances...*/ +#define NEXCFG DPCOMPAT "set r_particlesdesc effectinfo\nset sv_maxairspeed \"400\"\nset sv_jumpvelocity 270\nset sv_mintic \"0.01\"\ncl_nolerp 0\npr_enable_uriget 0\n" /*some modern non-compat settings*/ #define DMFCFG "set com_parseutf8 1\npm_airstep 1\nsv_demoExtensions 1\n" /*set some stuff so our regular qw client appears more like hexen2*/ @@ -1830,6 +1796,7 @@ typedef struct { const char *dir[4]; const char *poshname; //Full name for the game. + const char *downloadaddr; } gamemode_info_t; const gamemode_info_t gamemode_info[] = { //note that there is no basic 'fte' gamemode, this is because we aim for network compatability. Darkplaces-Quake is the closest we get. @@ -1837,12 +1804,12 @@ const gamemode_info_t gamemode_info[] = { //rogue/hipnotic have no special files - the detection conflicts and stops us from running regular quake //cmdline switch exename protocol name(dpmaster) identifying file exec dir1 dir2 dir3 dir(fte) full name - {"-quake", "q1", "DarkPlaces-Quake", {"id1/pak0.pak" - "id1/quake.rc"}, NULL, {"id1", "qw", "fte"}, "Quake"}, + {"-quake", "q1", "DarkPlaces-Quake", {"id1/pak0.pak", + "id1/quake.rc"}, NULL, {"id1", "qw", "fte"}, "Quake"/*, "id1/pak0.pak|http://quakeservers.nquake.com/qsw106.zip|http://nquake.localghost.net/qsw106.zip|http://qw.quakephil.com/nquake/qsw106.zip|http://fnu.nquake.com/qsw106.zip"*/}, {"-hipnotic", "hipnotic", "Darkplaces-Hipnotic", {NULL}, NULL, {"id1", "qw", "hipnotic", "fte"}, "Quake: Scourge of Armagon"}, {"-rogue", "rogue", "Darkplaces-Rogue", {NULL}, NULL, {"id1", "qw", "rogue", "fte"}, "Quake: Dissolution of Eternity"}, {"-nexuiz", "nexuiz", "Nexuiz", {"nexuiz.exe"}, NEXCFG, {"data", "ftedata"}, "Nexuiz"}, - {"-xonotic", "xonotic", "Xonotic", {"xonotic.exe"}, NEXCFG, {"data", "ftedata"}, "Xonotic"}, + {"-xonotic", "xonotic", "Xonotic", {"xonotic.exe"}, NEXCFG, {"data", "ftedata"}, "Xonotic", "data/xonotic-20120308-data.pk3|http://localhost/xonotic-0.6.0.zip"}, {"-spark", "spark", "Spark", {"base/src/progs.src", "base/qwprogs.dat", "base/pak0.pak"}, DMFCFG, {"base", }, "Spark"}, @@ -2215,7 +2182,8 @@ static qboolean Sys_SteamHasFile(char *basepath, int basepathlen, char *steamdir FILE *f; DWORD resultlen; HKEY key = NULL; - if (!FAILED(RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Valve\\Steam", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + + if (RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Valve\\Steam", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; RegQueryValueEx(key, "SteamPath", NULL, NULL, basepath, &resultlen); @@ -2239,7 +2207,7 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base #endif //first, try and find it in our game paths location - if (!FAILED(RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\" FULLENGINENAME "\\GamePaths", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + if (RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\" FULLENGINENAME "\\GamePaths", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; if (!RegQueryValueEx(key, gamename, NULL, NULL, basepath, &resultlen)) @@ -2284,7 +2252,7 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base HKEY key = NULL; //look for HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Quake2_exe\Path - if (!FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Quake2_exe", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Quake2_exe", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; RegQueryValueEx(key, "Path", NULL, NULL, basepath, &resultlen); @@ -2306,7 +2274,7 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base DWORD resultlen; HKEY key = NULL; //reads HKEY_LOCAL_MACHINE\SOFTWARE\Activision\Wolfenstein - Enemy Territory - if (!FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Activision\\Wolfenstein - Enemy Territory", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Activision\\Wolfenstein - Enemy Territory", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; RegQueryValueEx(key, "InstallPath", NULL, NULL, basepath, &resultlen); @@ -2328,7 +2296,7 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base HKEY key = NULL; //reads HKEY_LOCAL_MACHINE\SOFTWARE\id\Quake III Arena\InstallPath - if (!FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\id\\Quake III Arena", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\id\\Quake III Arena", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; RegQueryValueEx(key, "InstallPath", NULL, NULL, basepath, &resultlen); @@ -2350,7 +2318,7 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base DWORD resultlen; HKEY key = NULL; //reads HKEY_LOCAL_MACHINE\SOFTWARE\World Of Padman\Path - if (!FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\World Of Padman", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\World Of Padman", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; RegQueryValueEx(key, "Path", NULL, NULL, basepath, &resultlen); @@ -2365,7 +2333,7 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base DWORD resultlen; HKEY key = NULL; //reads HKEY_LOCAL_MACHINE\SOFTWARE\id\Doom 3\InstallPath - if (!FAILED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\id\\Doom 3", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key))) + if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\id\\Doom 3", 0, STANDARD_RIGHTS_READ|KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) { resultlen = basepathlen; RegQueryValueEx(key, "InstallPath", NULL, NULL, basepath, &resultlen); @@ -2416,13 +2384,13 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base Q_strncpyz(basepath, resultpath, basepathlen-1); //and save it into the windows registry - if (!FAILED(RegCreateKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\" FULLENGINENAME "\\GamePaths", + if (RegCreateKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\" FULLENGINENAME "\\GamePaths", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &key, - NULL))) + NULL) == ERROR_SUCCESS) { RegSetValueEx(key, gamename, 0, REG_SZ, basepath, strlen(basepath)); @@ -2439,6 +2407,9 @@ qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *base #else qboolean Sys_FindGameData(const char *poshname, const char *gamename, char *basepath, int basepathlen) { +#ifdef __linux__ + // /usr/share/quake +#endif return false; } #endif @@ -2518,6 +2489,7 @@ void FS_StartupWithGame(int gamenum) Cvar_Set(&com_protocolname, gamemode_info[gamenum].protocolname); Cvar_ForceSet(&fs_gamename, gamemode_info[gamenum].poshname); + Cvar_ForceSet(&fs_gamedownload, gamemode_info[gamenum].downloadaddr?gamemode_info[gamenum].downloadaddr:""); i = COM_CheckParm ("-basepack"); while (i && i < com_argc-1) @@ -2596,7 +2568,7 @@ void FS_StartupWithGame(int gamenum) COM_Gamedir(com_argv[i+1]); } -#if 1//def ANDROID +#ifdef ANDROID { vfsfile_t *f; //write a .nomedia file to avoid people from getting random explosion sounds etc intersperced with their music @@ -2679,6 +2651,7 @@ void COM_InitFilesystem (void) Cvar_Register(&fs_gamename, "FS"); + Cvar_Register(&fs_gamedownload, "FS"); Cvar_Register(&com_protocolname, "Server Info"); Cvar_Register(&com_modname, "Server Info"); //identify the game from a telling file @@ -2697,6 +2670,29 @@ void COM_InitFilesystem (void) } } } + if (gamenum == -1 && host_parms.binarydir && *host_parms.binarydir && autobasedir) + { + for (i = 0; gamemode_info[i].argname && gamenum==-1; i++) + { + //look in the directory the exe exists in if we failed to find a valid installation in the working dir + for (j = 0; j < 4; j++) + { + if (gamemode_info[i].auniquefile[j]) + { + f = VFSOS_Open(va("%s%s", host_parms.binarydir, gamemode_info[i].auniquefile[j]), "rb"); + if (f) + { + //apply this as the new -basedir + Q_strncpyz(com_quakedir, host_parms.binarydir, sizeof(com_quakedir)); + gamenum = i; + //we found it, its all okay + VFS_CLOSE(f); + break; + } + } + } + } + } //use the game based on an exe name over the filesystem one (could easily have multiple fs path matches). for (i = 0; gamemode_info[i].argname; i++) { @@ -2711,37 +2707,59 @@ void COM_InitFilesystem (void) { gamenum = i; - for (j = 0; j < 4; j++) + if (autobasedir) { - if (gamemode_info[gamenum].auniquefile[j]) + //try the working directory first + for (j = 0; j < 4; j++) { - f = VFSOS_Open(va("%s%s", com_quakedir, gamemode_info[i].auniquefile[j]), "rb"); - if (f) + if (gamemode_info[gamenum].auniquefile[j]) { - //we found it, its all okay - VFS_CLOSE(f); - break; - } - if (autobasedir) - { -#ifdef _WIN32 - if (Sys_FindGameData(gamemode_info[i].poshname, gamemode_info[i].exename, com_quakedir, sizeof(com_quakedir))) + f = VFSOS_Open(va("%s%s", com_quakedir, gamemode_info[i].auniquefile[j]), "rb"); + if (f) { - if (com_quakedir[strlen(com_quakedir)-1] == '\\') - com_quakedir[strlen(com_quakedir)-1] = '/'; - else if (com_quakedir[strlen(com_quakedir)-1] != '/') + //we found it, its all okay + VFS_CLOSE(f); + break; + } + } + } + //try looking where the exe is + if (j == 4 && host_parms.binarydir && *host_parms.binarydir) + { + for (j = 0; j < 4; j++) + { + if (gamemode_info[gamenum].auniquefile[j]) + { + f = VFSOS_Open(va("%s%s", host_parms.binarydir, gamemode_info[i].auniquefile[j]), "rb"); + if (f) { - com_quakedir[strlen(com_quakedir)+1] = '\0'; - com_quakedir[strlen(com_quakedir)] = '/'; + Q_strncpyz(com_quakedir, host_parms.binarydir, sizeof(com_quakedir)); + //we found it, its all okay + VFS_CLOSE(f); + break; } } - else -#endif + } + } + //scan known locations/windows registry/etc to see if we can find an existing install + if (j == 4) + { + char realpath[MAX_OSPATH-1]; + if (Sys_FindGameData(gamemode_info[i].poshname, gamemode_info[i].exename, realpath, sizeof(realpath))) + { + Q_strncpyz(com_quakedir, realpath, sizeof(com_quakedir)); + if (com_quakedir[strlen(com_quakedir)-1] == '\\') + com_quakedir[strlen(com_quakedir)-1] = '/'; + else if (com_quakedir[strlen(com_quakedir)-1] != '/') { - Con_Printf("Couldn't find the gamedata for this game mode!\n"); + com_quakedir[strlen(com_quakedir)+1] = '\0'; + com_quakedir[strlen(com_quakedir)] = '/'; } } - break; + else + { + Con_Printf("Couldn't find the gamedata for this game mode!\n"); + } } } break; @@ -2760,8 +2778,10 @@ void COM_InitFilesystem (void) if (autobasedir) { - if (Sys_FindGameData(gamemode_info[i].poshname, gamemode_info[i].exename, com_quakedir, sizeof(com_quakedir))) + char realpath[MAX_OSPATH-1]; + if (Sys_FindGameData(gamemode_info[i].poshname, gamemode_info[i].exename, realpath, sizeof(realpath))) { + Q_strncpyz(com_quakedir, realpath, sizeof(com_quakedir)); if (com_quakedir[strlen(com_quakedir)-1] == '\\') com_quakedir[strlen(com_quakedir)-1] = '/'; else if (com_quakedir[strlen(com_quakedir)-1] != '/') diff --git a/engine/common/fs_stdio.c b/engine/common/fs_stdio.c index b3034697..09d51a77 100644 --- a/engine/common/fs_stdio.c +++ b/engine/common/fs_stdio.c @@ -121,7 +121,7 @@ vfsfile_t *FSSTDIO_OpenTemp(void) vfsfile_t *Sys_OpenAsset(const char *fname); #endif -static vfsfile_t *VFSSTDIO_Open(const char *osname, const char *mode, qboolean *needsflush) +vfsfile_t *VFSSTDIO_Open(const char *osname, const char *mode, qboolean *needsflush) { FILE *f; vfsstdiofile_t *file; diff --git a/engine/common/fs_zip.c b/engine/common/fs_zip.c index ed3ea413..b333e92d 100644 --- a/engine/common/fs_zip.c +++ b/engine/common/fs_zip.c @@ -524,6 +524,8 @@ int VFSZIP_ReadBytes (struct vfsfile_s *file, void *buffer, int bytestoread) VFS_SEEK(vfsz->parent->raw, vfsz->pos+vfsz->startpos); vfsz->parent->currentfile = file; } + if (vfsz->pos + bytestoread > vfsz->length) + bytestoread = max(0, vfsz->length - vfsz->pos); read = VFS_READ(vfsz->parent->raw, buffer, bytestoread); } diff --git a/engine/common/gl_q2bsp.c b/engine/common/gl_q2bsp.c index e1e7b98f..62d53bf0 100644 --- a/engine/common/gl_q2bsp.c +++ b/engine/common/gl_q2bsp.c @@ -1969,7 +1969,8 @@ qboolean CModQ3_LoadSubmodels (lump_t *l) bleaf->contents = 0; leafbrush = &map_leafbrushes[numleafbrushes]; - for ( j = 0; j < bleaf->numleafbrushes; j++, leafbrush++ ) { + for ( j = 0; j < bleaf->numleafbrushes; j++, leafbrush++ ) + { *leafbrush = LittleLong ( in->firstbrush ) + j; bleaf->contents |= map_brushes[*leafbrush].contents; } diff --git a/engine/common/mathlib.c b/engine/common/mathlib.c index 6485ff60..4b0e7ee9 100644 --- a/engine/common/mathlib.c +++ b/engine/common/mathlib.c @@ -1685,8 +1685,10 @@ void Matrix4x4_CM_UnProject(const vec3_t in, vec3_t out, const vec3_t viewangles //returns fractions of screen. //uses GL style rotations and translations and stuff. //3d -> screen (fixme: offscreen return values needed) -void Matrix4x4_CM_Project (const vec3_t in, vec3_t out, const vec3_t viewangles, const vec3_t vieworg, float fovx, float fovy) +//returns false if the 2d point is offscreen. +qboolean Matrix4x4_CM_Project (const vec3_t in, vec3_t out, const vec3_t viewangles, const vec3_t vieworg, float fovx, float fovy) { + qboolean result = true; float modelview[16]; float proj[16]; @@ -1705,12 +1707,17 @@ void Matrix4x4_CM_Project (const vec3_t in, vec3_t out, const vec3_t viewangles, v[0] /= v[3]; v[1] /= v[3]; + if (v[2] < 0) + result = false; //too close to the view v[2] /= v[3]; out[0] = (1+v[0])/2; out[1] = (1+v[1])/2; out[2] = (1+v[2])/2; + if (out[2] > 1) + result = false; //beyond far clip plane } + return result; } diff --git a/engine/common/mathlib.h b/engine/common/mathlib.h index 09a4a40d..8199221f 100644 --- a/engine/common/mathlib.h +++ b/engine/common/mathlib.h @@ -155,7 +155,7 @@ void Matrix4x4_CM_ModelViewMatrixFromAxis (float *modelview, const vec3_t pn, c void Matrix4_CreateFromQuakeEntity (float *matrix, float x, float y, float z, float pitch, float yaw, float roll, float scale); void Matrix4_Multiply (const float *a, const float *b, float *out); void Matrix3x4_Multiply(const float *a, const float *b, float *out); -void Matrix4x4_CM_Project (const vec3_t in, vec3_t out, const vec3_t viewangles, const vec3_t vieworg, float fovx, float fovy); +qboolean Matrix4x4_CM_Project (const vec3_t in, vec3_t out, const vec3_t viewangles, const vec3_t vieworg, float fovx, float fovy); void Matrix4x4_CM_Transform3 (const float *matrix, const float *vector, float *product); void Matrix4x4_CM_Transform4 (const float *matrix, const float *vector, float *product); void Matrix4x4_CM_Transform34(const float *matrix, const vec3_t vector, vec4_t product); diff --git a/engine/common/net.h b/engine/common/net.h index 3bc459d9..9f8acb5c 100644 --- a/engine/common/net.h +++ b/engine/common/net.h @@ -96,7 +96,7 @@ qboolean NET_CompareAdr (netadr_t a, netadr_t b); qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b); char *NET_AdrToString (char *s, int len, netadr_t a); char *NET_BaseAdrToString (char *s, int len, netadr_t a); -qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr); +qboolean NET_StringToSockaddr (const char *s, int defaultport, struct sockaddr_qstorage *sadr, int *addrfamily, int *addrsize); qboolean NET_StringToAdr (const char *s, netadr_t *a); qboolean NET_IsClientLegal(netadr_t *adr); diff --git a/engine/common/net_chan.c b/engine/common/net_chan.c index a6aac825..71e9b06c 100644 --- a/engine/common/net_chan.c +++ b/engine/common/net_chan.c @@ -88,7 +88,7 @@ cvar_t net_mtu = CVARD("net_mtu", "1450", "Specifies a maximum udp payload size, cvar_t pext_replacementdeltas = CVAR("debug_pext_replacementdeltas", "0"); /*rename once the extension is finalized*/ -/*returns the bitmask of supported+enabled extensions*/ +/*returns the entire bitmask of supported+enabled extensions*/ unsigned int Net_PextMask(int maskset) { unsigned int mask = 0; diff --git a/engine/common/net_wins.c b/engine/common/net_wins.c index ccb63dbc..0f4aa818 100644 --- a/engine/common/net_wins.c +++ b/engine/common/net_wins.c @@ -662,13 +662,7 @@ idnewt:28000 any form of ipv6, including port number. ============= */ -#define DO(src,dest) \ - copy[0] = s[src]; \ - copy[1] = s[src + 1]; \ - sscanf (copy, "%x", &val); \ - ((struct sockaddr_ipx *)sadr)->dest = val - -qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr) +qboolean NET_StringToSockaddr (const char *s, int defaultport, struct sockaddr_qstorage *sadr, int *addrfamily, int *addrsize) { struct hostent *h; char *colon; @@ -685,6 +679,13 @@ qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr) unsigned int val; ((struct sockaddr_ipx *)sadr)->sa_family = AF_IPX; + +#define DO(src,dest) \ + copy[0] = s[src]; \ + copy[1] = s[src + 1]; \ + sscanf (copy, "%x", &val); \ + ((struct sockaddr_ipx *)sadr)->dest = val + copy[2] = 0; DO(0, sa_netnum[0]); DO(2, sa_netnum[1]); @@ -697,7 +698,14 @@ qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr) DO(17, sa_nodenum[4]); DO(19, sa_nodenum[5]); sscanf (&s[22], "%u", &val); + +#undef DO + ((struct sockaddr_ipx *)sadr)->sa_socket = htons((unsigned short)val); + if (addrfamily) + *addrfamily = AF_IPX; + if (addrsize) + *addrsize = sizeof(struct sockaddr_ipx); } else #endif @@ -719,7 +727,7 @@ qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr) if (*s == '[') { - port = strstr(s, "]:"); + port = strstr(s, "]"); if (!port) error = EAI_NONAME; else @@ -729,7 +737,7 @@ qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr) len = sizeof(dupbase)-1; strncpy(dupbase, s+1, len); dupbase[len] = '\0'; - error = pgetaddrinfo(dupbase, port+2, &udp6hint, &addrinfo); + error = pgetaddrinfo(dupbase, (port[1] == ':')?port+2:NULL, &udp6hint, &addrinfo); } } else @@ -748,7 +756,7 @@ qboolean NET_StringToSockaddr (const char *s, struct sockaddr_qstorage *sadr) else error = EAI_NONAME; if (error) //failed, try string with no port. - error = pgetaddrinfo(s, NULL, &udp6hint, &addrinfo); //remember, this func will return any address family that could be using the udp protocol... (ip4 or ip6) + error = pgetaddrinfo(s, NULL, &udp6hint, &addrinfo); //remember, this func will return any address family that could be using the udp protocol... (ip4 or ip6) } if (error) { @@ -779,6 +787,24 @@ dblbreak: pfreeaddrinfo (addrinfo); if (!((struct sockaddr*)sadr)->sa_family) //none suitablefound return false; + + if (addrfamily) + *addrfamily = ((struct sockaddr*)sadr)->sa_family; + + if (((struct sockaddr*)sadr)->sa_family == AF_INET) + { + if (!((struct sockaddr_in *)sadr)->sin_port) + ((struct sockaddr_in *)sadr)->sin_port = htons(defaultport); + if (addrsize) + *addrsize = sizeof(struct sockaddr_in); + } + else + { + if (!((struct sockaddr_in6 *)sadr)->sin6_port) + ((struct sockaddr_in6 *)sadr)->sin6_port = htons(defaultport); + if (addrsize) + *addrsize = sizeof(struct sockaddr_in6); + } } else #endif @@ -791,6 +817,8 @@ dblbreak: if (strlen(s) >= sizeof(copy)-1) return false; + ((struct sockaddr_in *)sadr)->sin_port = htons(defaultport); + strcpy (copy, s); // strip off a trailing :port if present for (colon = copy ; *colon ; colon++) @@ -812,6 +840,10 @@ dblbreak: return false; *(int *)&((struct sockaddr_in *)sadr)->sin_addr = *(int *)h->h_addr_list[0]; } + if (addrfamily) + *addrfamily = AF_INET; + if (addrsize) + *addrsize = sizeof(struct sockaddr_in); #else return false; #endif @@ -820,8 +852,6 @@ dblbreak: return true; } -#undef DO - /* accepts anything that NET_StringToSockaddr accepts plus certain url schemes including: tcp, irc @@ -868,7 +898,7 @@ qboolean NET_StringToAdr (const char *s, netadr_t *a) { //make sure that the rest of the address is a valid ip address (4 or 6) - if (!NET_StringToSockaddr (s+6, &sadr)) + if (!NET_StringToSockaddr (s+6, 0, &sadr, NULL, NULL)) { a->type = NA_INVALID; return false; @@ -914,7 +944,7 @@ qboolean NET_StringToAdr (const char *s, netadr_t *a) } #endif - if (!NET_StringToSockaddr (s, &sadr)) + if (!NET_StringToSockaddr (s, 0, &sadr, NULL, NULL)) { a->type = NA_INVALID; return false; @@ -4269,7 +4299,7 @@ void NET_GetLocalAddress (int socket, netadr_t *out) if (getsockname (socket, (struct sockaddr *)&address, &namelen) == -1) { notvalid = true; - NET_StringToSockaddr("0.0.0.0", (struct sockaddr_qstorage *)&address); + NET_StringToSockaddr("0.0.0.0", 0, (struct sockaddr_qstorage *)&address, NULL, NULL); // Sys_Error ("NET_Init: getsockname:", strerror(qerrno)); } diff --git a/engine/common/plugin.c b/engine/common/plugin.c index f492b168..ebcb2a4d 100644 --- a/engine/common/plugin.c +++ b/engine/common/plugin.c @@ -477,6 +477,11 @@ static qintptr_t VARGS Plug_ExportNative(void *offset, quintptr_t mask, const qi else if (!strcmp(name, "Media_VideoDecoder")) { Media_RegisterDecoder(currentplug, func); +// currentplug->blockcloses++; + } + else if (!strcmp(name, "Media_VideoEncoder")) + { + Media_RegisterEncoder(currentplug, func); // currentplug->blockcloses++; } #endif @@ -1812,6 +1817,7 @@ void Plug_Close(plugin_t *plug) Con_Printf("Closing plugin %s\n", plug->name); #if defined(PLUGINS) && !defined(NOMEDIA) && !defined(SERVERONLY) Media_UnregisterDecoder(plug, NULL); + Media_UnregisterEncoder(plug, NULL); #endif if (plug->shutdown) VM_Call(plug->vm, plug->shutdown); @@ -1900,6 +1906,10 @@ void Plug_Shutdown(void) BZ_Free(plugbuiltins); plugbuiltins = NULL; + plugincvararraylen = 0; + BZ_Free(plugincvararray); + plugincvararray = NULL; + plugincommandarraylen = 0; BZ_Free(plugincommandarray); plugincommandarray = NULL; diff --git a/engine/common/pr_bgcmd.c b/engine/common/pr_bgcmd.c index 3a030bfa..50dcdb54 100644 --- a/engine/common/pr_bgcmd.c +++ b/engine/common/pr_bgcmd.c @@ -6,16 +6,13 @@ #include -//fixme -#define Z_QC_TAG 2 -#define PRSTR 0xa6ffb3d7 - static char *cvargroup_progs = "Progs variables"; cvar_t pr_brokenfloatconvert = SCVAR("pr_brokenfloatconvert", "0"); cvar_t pr_tempstringcount = SCVAR("pr_tempstringcount", "");//"16"); cvar_t pr_tempstringsize = SCVAR("pr_tempstringsize", "4096"); -cvar_t dpcompat_stats = CVAR("dpcompat_stats", "0"); +cvar_t pr_enable_uriget = SCVAR("pr_enable_uriget", "1"); +int tokenizeqc(char *str, qboolean dpfuckage); static char *strtoupper(char *s) { @@ -50,7 +47,7 @@ void PF_Common_RegisterCvars(void) Cvar_Register (&pr_brokenfloatconvert, cvargroup_progs); Cvar_Register (&pr_tempstringcount, cvargroup_progs); Cvar_Register (&pr_tempstringsize, cvargroup_progs); - Cvar_Register (&dpcompat_stats, cvargroup_progs); + Cvar_Register (&pr_enable_uriget, cvargroup_progs); WPhys_Init(); } @@ -823,9 +820,8 @@ void QCBUILTIN PF_cvar_type (progfuncs_t *prinst, struct globalvars_s *pr_global ret |= 4; // CVAR_TYPE_PRIVATE if(!(v->flags & CVAR_USERCREATED)) ret |= 8; // CVAR_TYPE_ENGINE - - //fte cvars don't support this - // ret |= 16; // CVAR_TYPE_HASDESCRIPTION + if (v->description) + ret |= 16; // CVAR_TYPE_HASDESCRIPTION } G_FLOAT(OFS_RETURN) = ret; } @@ -1204,19 +1200,19 @@ static void PF_fwrite (progfuncs_t *prinst, int fnum, char *msg, int len) { if (fnum < 0 || fnum >= MAX_QC_FILES) { - Con_Printf("PF_fgets: File out of range\n"); + Con_Printf("PF_fwrite: File out of range\n"); return; //out of range } if (!pf_fopen_files[fnum].data) { - Con_Printf("PF_fgets: File is not open\n"); + Con_Printf("PF_fwrite: File is not open\n"); return; //not open } if (pf_fopen_files[fnum].prinst != prinst) { - Con_Printf("PF_fgets: File is from wrong instance\n"); + Con_Printf("PF_fwrite: File is from wrong instance\n"); return; //this just isn't ours. } @@ -1263,6 +1259,7 @@ void PF_fcloseall (progfuncs_t *prinst) Con_Printf("qc file %s was still open\n", pf_fopen_files[i].name); PF_fclose_i(i); } + tokenizeqc("", false); } @@ -2151,7 +2148,7 @@ void QCBUILTIN PF_substring (progfuncs_t *prinst, struct globalvars_s *pr_global slen = strlen(s); if (start < 0) - start = slen-start; + start = slen+start; if (length < 0) length = slen-start+(length+1); if (start < 0) @@ -2279,7 +2276,15 @@ void QCBUILTIN PF_etos (progfuncs_t *prinst, struct globalvars_s *pr_globals) void QCBUILTIN PF_strlennocol (progfuncs_t *prinst, struct globalvars_s *pr_globals) { char *in = PR_GetStringOfs(prinst, OFS_PARM0); - G_FLOAT(OFS_RETURN) = COM_FunStringLength(in); + char result[8192]; + unsigned int flagged[8192]; + unsigned int len = 0; + COM_ParseFunString(CON_WHITEMASK, in, flagged, sizeof(flagged), false); + COM_DeFunString(flagged, NULL, result, sizeof(result), true); + + for (len = 0; result[len]; len++) + ; + G_FLOAT(OFS_RETURN) = len; } //DP_QC_STRINGCOLORFUNCTIONS @@ -2351,7 +2356,7 @@ struct strbuf { int allocated; }; -#define NUMSTRINGBUFS 16 +#define NUMSTRINGBUFS 64 struct strbuf strbuflist[NUMSTRINGBUFS]; void PF_buf_shutdown(progfuncs_t *prinst) @@ -2531,30 +2536,67 @@ void QCBUILTIN PF_bufstr_set (progfuncs_t *prinst, struct globalvars_s *pr_glob void QCBUILTIN PF_bufstr_add (progfuncs_t *prinst, struct globalvars_s *pr_globals) { int bufno = G_FLOAT(OFS_PARM0)-1; - //char *string = PR_GetStringOfs(prinst, OFS_PARM1); - //int order = G_FLOAT(OFS_PARM2); + char *string = PR_GetStringOfs(prinst, OFS_PARM1); + int order = G_FLOAT(OFS_PARM2); + + int index; if ((unsigned int)bufno >= NUMSTRINGBUFS) return; if (strbuflist[bufno].prinst != prinst) return; - Con_Printf("PF_bufstr_add: stub\n"); + if (order) + { + //add on end + index = strbuflist[bufno].used; + } + else + { + //find a hole + for (index = 0; index < strbuflist[bufno].used; index++) + if (!strbuflist[bufno].strings[index]) + break; + } - G_FLOAT(OFS_RETURN) = 0; + //expand it if needed + if (index >= strbuflist[bufno].allocated) + { + int oldcount; + oldcount = strbuflist[bufno].allocated; + strbuflist[bufno].allocated = (index + 256); + strbuflist[bufno].strings = BZ_Realloc(strbuflist[bufno].strings, strbuflist[bufno].allocated*sizeof(char*)); + memset(strbuflist[bufno].strings+oldcount, 0, (strbuflist[bufno].allocated - oldcount) * sizeof(char*)); + } + + //add in the new string. + if (strbuflist[bufno].strings[index]) + Z_Free(strbuflist[bufno].strings[index]); + strbuflist[bufno].strings[index] = Z_Malloc(strlen(string)+1); + strcpy(strbuflist[bufno].strings[index], string); + + if (index >= strbuflist[bufno].used) + strbuflist[bufno].used = index+1; + + G_FLOAT(OFS_RETURN) = index; } // #449 void(float bufhandle, float string_index) bufstr_free (DP_QC_STRINGBUFFERS) void QCBUILTIN PF_bufstr_free (progfuncs_t *prinst, struct globalvars_s *pr_globals) { int bufno = G_FLOAT(OFS_PARM0)-1; - //int index = G_FLOAT(OFS_PARM1); + int index = G_FLOAT(OFS_PARM1); if ((unsigned int)bufno >= NUMSTRINGBUFS) return; if (strbuflist[bufno].prinst != prinst) return; - Con_Printf("PF_bufstr_free: stub\n"); + if (index >= strbuflist[bufno].used) + return; //not valid anyway. + + if (strbuflist[bufno].strings[index]) + Z_Free(strbuflist[bufno].strings[index]); + strbuflist[bufno].strings[index] = NULL; } void QCBUILTIN PF_buf_cvarlist (progfuncs_t *prinst, struct globalvars_s *pr_globals) @@ -2659,14 +2701,74 @@ void QCBUILTIN PF_uri_unescape (progfuncs_t *prinst, struct globalvars_s *pr_gl RETURN_TSTRING(resultbuf); } +#ifdef WEBCLIENT +static void PR_uri_get_callback(struct dl_download *dl) +{ + extern progfuncs_t *menuprogs; + world_t *w = dl->user_ctx; + progfuncs_t *prinst = w?w->progs:menuprogs; + float id = dl->user_num; + func_t func; + + if (!prinst) + return; + + func = PR_FindFunction(prinst, "URI_Get_Callback", PR_ANY); + + if (func) + { + int len; + char *buffer; + struct globalvars_s *pr_globals = PR_globals(prinst, PR_CURRENT); + + G_FLOAT(OFS_PARM0) = id; + G_FLOAT(OFS_PARM1) = (dl->replycode!=200)?dl->replycode:0; //for compat with DP, we change any 200s to 0. + G_INT(OFS_PARM2) = 0; + + if (dl->file) + { + len = VFS_GETLEN(dl->file); + buffer = malloc(len+1); + buffer[len] = 0; + VFS_READ(dl->file, buffer, len); + G_INT(OFS_PARM2) = PR_TempString(prinst, buffer); + free(buffer); + } + + PR_ExecuteProgram(prinst, func); + } +} +#endif + // uri_get() gets content from an URL and calls a callback "uri_get_callback" with it set as string; an unique ID of the transfer is returned // returns 1 on success, and then calls the callback with the ID, 0 or the HTTP status code, and the received data in a string //float(string uril, float id) uri_get = #513; void QCBUILTIN PF_uri_get (progfuncs_t *prinst, struct globalvars_s *pr_globals) { - Con_Printf("PF_uri_get: stub\n"); +#ifdef WEBCLIENT + world_t *w = prinst->parms->user; + unsigned char *url = PR_GetStringOfs(prinst, OFS_PARM0); + float id = G_FLOAT(OFS_PARM1); + struct dl_download *dl; - G_FLOAT(OFS_RETURN) = 0; + if (!pr_enable_uriget.ival) + { + Con_Printf("PF_uri_get(\"%s\",%g): %s disabled\n", url, id, pr_enable_uriget.name); + G_FLOAT(OFS_RETURN) = 0; + return; + } + Con_DPrintf("PF_uri_get(%s,%g)\n", url, id); + + dl = HTTP_CL_Get(url, NULL, PR_uri_get_callback); + if (dl) + { + dl->user_ctx = w; + dl->user_num = id; + G_FLOAT(OFS_RETURN) = 1; + } + else +#endif + G_FLOAT(OFS_RETURN) = 0; } //////////////////////////////////////////////////// @@ -3170,18 +3272,30 @@ void QCBUILTIN PF_externvalue (progfuncs_t *prinst, struct globalvars_s *pr_glob char *varname = PF_VarString(prinst, 1, pr_globals); eval_t *var; - var = prinst->FindGlobal(prinst, varname, n, NULL); - - if (var) + if (*varname == '&') { - G_INT(OFS_RETURN+0) = ((int*)&var->_int)[0]; - G_INT(OFS_RETURN+1) = ((int*)&var->_int)[1]; - G_INT(OFS_RETURN+2) = ((int*)&var->_int)[2]; + //return its address instead of its value, for pointer use. + var = prinst->FindGlobal(prinst, varname+1, n, NULL); + if (var) + G_INT(OFS_RETURN) = (char*)var - prinst->stringtable; + else + G_INT(OFS_RETURN) = 0; } else { - n = prinst->FindFunction(prinst, varname, n); - G_INT(OFS_RETURN) = n; + var = prinst->FindGlobal(prinst, varname, n, NULL); + + if (var) + { + G_INT(OFS_RETURN+0) = ((int*)&var->_int)[0]; + G_INT(OFS_RETURN+1) = ((int*)&var->_int)[1]; + G_INT(OFS_RETURN+2) = ((int*)&var->_int)[2]; + } + else + { + n = prinst->FindFunction(prinst, varname, n); + G_INT(OFS_RETURN) = n; + } } } @@ -3657,7 +3771,8 @@ nolength: default: verbatim: if(o < end - 1) - *o++ = *s++; + *o++ = *s; + s++; break; } } @@ -3667,6 +3782,77 @@ finished: RETURN_TSTRING(outbuf); } +fdef_t *ED_FieldInfo (progfuncs_t *progfuncs, unsigned int *count); +char *PR_UglyValueString (progfuncs_t *progfuncs, etype_t type, eval_t *val); +pbool ED_ParseEval (progfuncs_t *progfuncs, eval_t *eval, int type, char *s); +//float() +void QCBUILTIN PF_numentityfields (progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + unsigned int count = 0; + ED_FieldInfo(prinst, &count); + G_FLOAT(OFS_RETURN) = count; +} +//string(float fieldnum) +void QCBUILTIN PF_entityfieldname (progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + unsigned int fidx = G_FLOAT(OFS_PARM0); + unsigned int count = 0; + fdef_t *fdef; + fdef = ED_FieldInfo(prinst, &count); + if (fidx < count) + { + RETURN_TSTRING(fdef[fidx].name); + } + else + G_INT(OFS_RETURN) = 0; +} +//float(float fieldnum) +void QCBUILTIN PF_entityfieldtype (progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + unsigned int fidx = G_FLOAT(OFS_PARM0); + unsigned int count = 0; + fdef_t *fdef = ED_FieldInfo(prinst, &count); + if (fidx < count) + { + G_FLOAT(OFS_RETURN) = fdef[fidx].type; + } + else + G_FLOAT(OFS_RETURN) = 0; +} +//string(float fieldnum, entity ent) +void QCBUILTIN PF_getentityfieldstring (progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + unsigned int fidx = G_FLOAT(OFS_PARM0); + wedict_t *ent = (wedict_t *)G_EDICT(prinst, OFS_PARM1); + eval_t *eval; + unsigned int count = 0; + fdef_t *fdef = ED_FieldInfo(prinst, &count); + if (fidx < count) + { + eval = (eval_t *)&((float *)ent->v)[fdef[fidx].ofs]; + RETURN_TSTRING(PR_UglyValueString(prinst, fdef[fidx].type, eval)); + } + else + G_INT(OFS_RETURN) = 0; +} +//float(float fieldnum, entity ent, string s) +void QCBUILTIN PF_putentityfieldstring (progfuncs_t *prinst, struct globalvars_s *pr_globals) +{ + unsigned int fidx = G_FLOAT(OFS_PARM0); + wedict_t *ent = (wedict_t *)G_EDICT(prinst, OFS_PARM1); + char *str = PR_GetStringOfs(prinst, OFS_PARM2); + eval_t *eval; + unsigned int count = 0; + fdef_t *fdef = ED_FieldInfo(prinst, &count); + if (fidx < count) + { + eval = (eval_t *)&((float *)ent->v)[fdef[fidx].ofs]; + G_FLOAT(OFS_RETURN) = ED_ParseEval(prinst, eval, fdef[fidx].type, str); + } + else + G_FLOAT(OFS_RETURN) = 0; +} + #define DEF_SAVEGLOBAL (1u<<15) static void PR_AutoCvarApply(progfuncs_t *prinst, eval_t *val, etype_t type, cvar_t *var) { @@ -3690,11 +3876,11 @@ static void PR_AutoCvarApply(progfuncs_t *prinst, eval_t *val, etype_t type, cva char res[128]; char *vs = var->string; vs = COM_ParseOut(vs, res, sizeof(res)); - val->_vector[0] = atof(com_token); + val->_vector[0] = atof(res); vs = COM_ParseOut(vs, res, sizeof(res)); - val->_vector[1] = atof(com_token); + val->_vector[1] = atof(res); vs = COM_ParseOut(vs, res, sizeof(res)); - val->_vector[2] = atof(com_token); + val->_vector[2] = atof(res); } break; } @@ -3726,11 +3912,17 @@ void PR_FoundPrefixedGlobals(progfuncs_t *progfuncs, char *name, eval_t *val, et { cvar_t *var; char *vals; + int nlen; name += 9; //autocvar_ switch(type & ~DEF_SAVEGLOBAL) { case ev_float: + //ignore individual vector componants. let the vector itself do all the work. + nlen = strlen(name); + if(nlen >= 2 && name[nlen-2] == '_' && (name[nlen-1] == 'x' || name[nlen-1] == 'y' || name[nlen-1] == 'z')) + return; + vals = va("%f", val->_float); break; case ev_integer: @@ -3786,7 +3978,7 @@ lh_extension_t QSG_Extensions[] = { {"FTE_PEXT_Q3BSP"}, //quake3 bsp support. dp probably has an equivelent, but this is queryable per client. {"DP_ENT_COLORMOD"}, {NULL}, //splitscreen - not queryable. - {"FTE_HEXEN2"}, //client can use hexen2 maps. server can use hexen2 progs + {"FTE_HEXEN2", 3, NULL, {"particle2", "particle3", "particle4"}}, //client can use hexen2 maps. server can use hexen2 progs {"FTE_PEXT_SPAWNSTATIC"}, //means that static entities can have alpha/scale and anything else the engine supports on normal ents. (Added for >256 models, while still being compatible - previous system failed with -1 skins) {"FTE_PEXT_CUSTOMTENTS", 2, NULL, {"RegisterTempEnt", "CustomTempEnt"}}, {"FTE_PEXT_256PACKETENTITIES"}, //client is able to receive unlimited packet entities (server caps itself to 256 to prevent insanity). @@ -3835,6 +4027,7 @@ lh_extension_t QSG_Extensions[] = { //to an extend {"DP_HALFLIFE_SPRITE"}, {"DP_INPUTBUTTONS"}, {"DP_LITSUPPORT"}, + {"DP_MD3_TAGSINFO", 2, NULL, {"gettagindex", "gettaginfo"}}, {"DP_MONSTERWALK"}, {"DP_MOVETYPEBOUNCEMISSILE"}, //I added the code for hexen2 support. {"DP_MOVETYPEFOLLOW"}, @@ -3854,6 +4047,7 @@ lh_extension_t QSG_Extensions[] = { {"DP_QC_FINDCHAINFLAGS", 1, NULL, {"findchainflags"}}, {"DP_QC_FINDFLOAT", 1, NULL, {"findfloat"}}, {"DP_QC_FS_SEARCH", 4, NULL, {"search_begin", "search_end", "search_getsize", "search_getfilename"}}, + {"DP_QC_GETSURFACE", 6, NULL, {"getsurfacenumpoints", "getsurfacepoint", "getsurfacenormal", "getsurfacetexture", "getsurfacenearpoint", "getsurfaceclippedpoint"}}, {"DP_QC_GETSURFACEPOINTATTRIBUTE", 1, NULL, {"getsurfacepointattribute"}}, {"DP_QC_MINMAXBOUND", 3, NULL, {"min", "max", "bound"}}, {"DP_QC_MULTIPLETEMPSTRINGS"}, @@ -3901,14 +4095,14 @@ lh_extension_t QSG_Extensions[] = { {"DP_SV_WRITEUNTERMINATEDSTRING", 1, NULL, {"WriteUnterminatedString"}}, {"DP_TE_BLOOD", 1, NULL, {"te_blood"}}, {"DP_TE_BLOODSHOWER", 1, NULL, {"te_bloodshower"}}, - {"DP_TE_CUSTOMFLASH", 1, NULL, {"te_customflash"}}, - {"DP_TE_EXPLOSIONRGB"}, - {"DP_TE_FLAMEJET", 1, NULL, {"te_flamejet"}}, + {"_DP_TE_CUSTOMFLASH", 1, NULL, {"te_customflash"}}, + {"DP_TE_EXPLOSIONRGB", 1, NULL, {"te_explosionrgb"}}, + {"_DP_TE_FLAMEJET", 1, NULL, {"te_flamejet"}}, {"DP_TE_PARTICLECUBE", 1, NULL, {"te_particlecube"}}, - //particlerain - //particlesnow - {"DP_TE_PLASMABURN", 1, NULL, {"te_plasmaburn"}}, - {"DP_TE_QUADEFFECTS1"}, + {"_DP_TE_PARTICLERAIN", 1, NULL, {"te_particlerain"}}, + {"_DP_TE_PARTICLESNOW", 1, NULL, {"te_particlesnow"}}, + {"_DP_TE_PLASMABURN", 1, NULL, {"te_plasmaburn"}}, + {"_DP_TE_QUADEFFECTS1", 4, NULL, {"te_gunshotquad", "te_spikequad", "te_superspikequad", "te_explosionquad"}}, {"DP_TE_SMALLFLASH", 1, NULL, {"te_smallflash"}}, {"DP_TE_SPARK", 1, NULL, {"te_spark"}}, {"DP_TE_STANDARDEFFECTBUILTINS", 14, NULL, {"te_gunshot", "te_spike", "te_superspike", "te_explosion", "te_tarexplosion", "te_wizspike", "te_knightspike", "te_lavasplash", "te_teleport", "te_explosion2", "te_lightning1", "te_lightning2", "te_lightning3", "te_beam"}}, @@ -3933,7 +4127,7 @@ lh_extension_t QSG_Extensions[] = { {"FTE_MEDIA_CIN"}, //playfilm command supports q2 cin files. {"FTE_MEDIA_ROQ"}, //playfilm command supports q3 roq files #endif - {"FTE_MULTIPROGS"}, //multiprogs functions are available. + {"FTE_MULTIPROGS", 5, NULL, {"externcall", "addprogs", "externvalue", "externset", "instr"}}, //multiprogs functions are available. {"FTE_MULTITHREADED", 3, NULL, {"sleep", "fork", "abort"}}, #ifdef SERVER_DEMO_PLAYBACK {"FTE_MVD_PLAYBACK"}, @@ -3944,19 +4138,19 @@ lh_extension_t QSG_Extensions[] = { {"FTE_QC_CHECKPVS", 1, NULL, {"checkpvs"}}, {"FTE_QC_MATCHCLIENTNAME", 1, NULL, {"matchclientname"}}, {"FTE_QC_PAUSED"}, - {"FTE_QC_SENDPACKET", 1, NULL, {"sendpacket"}}, + {"FTE_QC_INTCONV", 4, NULL, {"stoi", "itos", "stoh", "htos"}}, + {"FTE_QC_SENDPACKET", 1, NULL, {"sendpacket"}}, //includes the SV_ParseConnectionlessPacket event. {"FTE_QC_TRACETRIGGER"}, {"FTE_SOLID_LADDER"}, //Allows a simple trigger to remove effects of gravity (solid 20). obsolete. will prolly be removed at some point as it is not networked properly. Use FTE_ENT_SKIN_CONTENTS -#ifdef SQL // serverside SQL functions for managing an SQL database connection {"FTE_SQL", 9, NULL, {"sqlconnect","sqldisconnect","sqlopenquery","sqlclosequery","sqlreadfield","sqlerror","sqlescape","sqlversion", "sqlreadfloat"}}, -#endif + //eperimental advanced strings functions. //reuses the FRIK_FILE builtins (with substring extension) - {"FTE_STRINGS", 16, NULL, {"stof", "strlen","strcat","substring","stov","strzone","strunzone", - "strstrofs", "str2chr", "chr2str", "strconv", "infoadd", "infoget", "strncmp", "strcasecmp", "strncasecmp"}}, + {"FTE_STRINGS", 17, NULL, {"stof", "strlen","strcat","substring","stov","strzone","strunzone", + "strstrofs", "str2chr", "chr2str", "strconv", "infoadd", "infoget", "strncmp", "strcasecmp", "strncasecmp", "strpad"}}, {"FTE_SV_REENTER"}, {"FTE_TE_STANDARDEFFECTBUILTINS", 14, NULL, {"te_gunshot", "te_spike", "te_superspike", "te_explosion", "te_tarexplosion", "te_wizspike", "te_knightspike", "te_lavasplash", "te_teleport", "te_lightning1", "te_lightning2", "te_lightning3", "te_lightningblood", "te_bloodqw"}}, diff --git a/engine/common/pr_common.h b/engine/common/pr_common.h index fc4075ab..3c604a11 100644 --- a/engine/common/pr_common.h +++ b/engine/common/pr_common.h @@ -53,11 +53,6 @@ struct wedict_s #define PF_pointsound PF_Fixme #define PF_gecko_mousemove PF_Fixme -#define PF_numentityfields PF_Fixme -#define PF_entityfieldname PF_Fixme -#define PF_entityfieldtype PF_Fixme -#define PF_getentityfieldstring PF_Fixme -#define PF_putentityfieldstring PF_Fixme #define PF_WritePicture PF_Fixme #define PF_ReadPicture PF_Fixme @@ -179,6 +174,11 @@ void PR_fclose_progs (progfuncs_t *prinst); char *PF_VarString (progfuncs_t *prinst, int first, struct globalvars_s *pr_globals); void PR_AutoCvarSetup(progfuncs_t *prinst); void PR_AutoCvar(progfuncs_t *prinst, cvar_t *var); +void QCBUILTIN PF_numentityfields (progfuncs_t *prinst, struct globalvars_s *pr_globals); +void QCBUILTIN PF_entityfieldname (progfuncs_t *prinst, struct globalvars_s *pr_globals); +void QCBUILTIN PF_entityfieldtype (progfuncs_t *prinst, struct globalvars_s *pr_globals); +void QCBUILTIN PF_getentityfieldstring (progfuncs_t *prinst, struct globalvars_s *pr_globals); +void QCBUILTIN PF_putentityfieldstring (progfuncs_t *prinst, struct globalvars_s *pr_globals); void QCBUILTIN PF_getsurfacenumpoints(progfuncs_t *prinst, struct globalvars_s *pr_globals); @@ -315,7 +315,7 @@ void QCBUILTIN PF_calltimeofday (progfuncs_t *prinst, struct globalvars_s *pr_gl void QCBUILTIN PF_whichpack (progfuncs_t *prinst, struct globalvars_s *pr_globals); void PF_fclose_progs (progfuncs_t *prinst); -int QCEditor (progfuncs_t *prinst, char *filename, int line, int nump, char **parms); +int QCEditor (progfuncs_t *prinst, char *filename, int line, int statement, int nump, char **parms); @@ -489,6 +489,34 @@ enum csqc_input_event CSIE_ACCELEROMETER = 4 /*x, y, z*/ }; +enum terrainedit_e +{ + ter_reload, // + ter_save, // + ter_sethole, //vector pos, float radius, floatbool hole + ter_height_set, //vector pos, float radius, float newheight + ter_height_smooth, //vector pos, float radius, float percent + ter_height_spread, //vector pos, float radius, float percent + ter_raise, //vector pos, float radius, float heightchange + ter_lower, //vector pos, float radius, float heightchange + ter_tex_kill, //vector pos, void junk, void junk, string texname + ter_tex_get, //vector pos, void junk, float imagenum + ter_mix_paint, //vector pos, float radius, float percent, string texname + ter_mix_concentrate, //vector pos, float radius, float percent + ter_mix_noise, //vector pos, float radius, float percent + ter_mix_blur, //vector pos, float radius, float percent + ter_water_set, //vector pos, float radius, float newwaterheight + ter_mesh_add, //entity ent + ter_mesh_kill, //vector pos, float radius + ter_tint, //vector pos, float radius, float percent, vector newcol, float newalph + ter_height_flatten, //vector pos, float radius, float percent +// ter_poly_add, //add a poly, woo +// ter_poly_remove, //remove polys + +// ter_autopaint_h, //vector pos, float radius, float percent, string tex1, string tex2 (paint tex1/tex2 +// ter_autopaint_n //vector pos, float radius, float percent, string tex1, string tex2 +}; + enum { GE_MAXENTS = -1, diff --git a/engine/common/protocol.h b/engine/common/protocol.h index 6d5d7235..ed9be53d 100644 --- a/engine/common/protocol.h +++ b/engine/common/protocol.h @@ -52,10 +52,10 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define PEXT_SPAWNSTATIC2 0x00400000 //Sends an entity delta instead of a baseline. #define PEXT_CUSTOMTEMPEFFECTS 0x00800000 //supports custom temp ents. #define PEXT_256PACKETENTITIES 0x01000000 //Client can recieve 256 packet entities. -//#define PEXT_NEVERUSED 0x02000000 +//#define PEXT_NEVERUSED 0x02000000 //reserved for a future multicastmask #define PEXT_SHOWPIC 0x04000000 #define PEXT_SETATTACHMENT 0x08000000 //md3 tags (needs networking, they need to lerp). -//#define PEXT_NEVERUSED 0x10000000 +//#define PEXT_NEVERUSED 0x10000000 //reserved for a future multicastmask #define PEXT_CHUNKEDDOWNLOADS 0x20000000 //alternate file download method. Hopefully it'll give quadroupled download speed, especially on higher pings. #ifdef CSQC_DAT @@ -773,8 +773,9 @@ enum { ========================================================== */ -#define MAX_CLIENTS 32 /*max 255, min 32*/ -#define QWMAX_CLIENTS 32 /*QW's standard max*/ +#define MAX_CLIENTS 32//255 /*max 255, min 32*/ +#define QWMAX_CLIENTS 32 /*QW's standard max. clients might have issues above this value*/ +#define NQMAX_CLIENTS 16 /*NQ's standard max. clients might have issues above this value*/ #define UPDATE_BACKUP 64 // copies of entity_state_t to keep buffered // must be power of two diff --git a/engine/common/qvm.c b/engine/common/qvm.c index c517521d..0143d6d3 100644 --- a/engine/common/qvm.c +++ b/engine/common/qvm.c @@ -33,10 +33,6 @@ Also, can efficiency be improved much? */ -#ifdef __MORPHOS__ -#include -#endif - #include "quakedef.h" #ifdef VM_ANY @@ -70,10 +66,6 @@ struct vm_s { qintptr_t (EXPORT_FN *vmMain)(qintptr_t command, qintptr_t arg0, qintptr_t arg1, qintptr_t arg2, qintptr_t arg3, qintptr_t arg4, qintptr_t arg5, qintptr_t arg6); }; -#if defined(__MORPHOS__) && I_AM_BIGFOOT -#include -#endif - dllhandle_t *QVM_LoadDLL(const char *name, void **vmMain, sys_calldll_t syscall) { void (EXPORT_FN *dllEntry)(sys_calldll_t syscall); @@ -88,11 +80,6 @@ dllhandle_t *QVM_LoadDLL(const char *name, void **vmMain, sys_calldll_t syscall) {NULL, NULL}, }; -#ifdef __MORPHOS__ - if (DynLoadBase == 0) - return 0; -#endif - #ifdef _WIN32 snprintf(dllname_arch, sizeof(dllname_arch), "%sx86.dll", name); snprintf(dllname_anycpu, sizeof(dllname_anycpu), "%s.dll", name); diff --git a/engine/common/sys.h b/engine/common/sys.h index 2ab7ed83..8ea99f8d 100644 --- a/engine/common/sys.h +++ b/engine/common/sys.h @@ -92,6 +92,7 @@ qboolean Sys_GetDesktopParameters(int *width, int *height, int *bpp, int *refres #ifdef MULTITHREAD void *Sys_CreateThread(int (*func)(void *), void *args, int priority, int stacksize); void Sys_WaitOnThread(void *thread); +void Sys_DetachThread(void *thread); #define THREADP_IDLE -5 #define THREADP_NORMAL 0 diff --git a/engine/common/world.h b/engine/common/world.h index fce37636..15459194 100644 --- a/engine/common/world.h +++ b/engine/common/world.h @@ -207,6 +207,12 @@ void World_ODE_Init(void); void World_ODE_Start(world_t *world); void World_ODE_End(world_t *world); void World_ODE_Shutdown(void); + +qboolean World_ODE_RagCreateBody(world_t *world, odebody_t *bodyptr, float *mat, wedict_t *ed); +void World_ODE_RagDestroyBody(world_t *world, odebody_t *bodyptr); +void World_ODE_RagMatrixFromBody(world_t *world, odebody_t *bodyptr, float *mat); +void World_ODE_RagCreateJoint(world_t *world, odejoint_t *joint, odejointinfo_t *info, odebody_t *body1, odebody_t *body2, vec3_t aaa2[3]); +void World_ODE_RagDestroyJoint(world_t *world, odejoint_t *joint); #endif void World_ClearWorld (world_t *w); diff --git a/engine/d3d/d3d11_backend.c b/engine/d3d/d3d11_backend.c index fe988a59..3f66b158 100644 --- a/engine/d3d/d3d11_backend.c +++ b/engine/d3d/d3d11_backend.c @@ -13,7 +13,7 @@ extern ID3D11DeviceContext *d3ddevctx; //#define d3dcheck(foo) foo #define d3dcheck(foo) do{HRESULT err = foo; if (FAILED(err)) Sys_Error("D3D reported error on backend line %i - error 0x%x\n", __LINE__, (unsigned int)err);} while(0) -#define MAX_TMUS 8 +#define MAX_TMUS 16 extern float d3d_trueprojection[16]; @@ -1542,9 +1542,9 @@ static void BE_SubmitMeshChain(int idxfirst) static void BE_ApplyUniforms(program_t *prog, int permu) { //FIXME: how many of these calls can we avoid? - ID3D11DeviceContext_IASetInputLayout(d3ddevctx, prog->handle[permu].hlsl.layout); - ID3D11DeviceContext_VSSetShader(d3ddevctx, prog->handle[permu].hlsl.vert, NULL, 0); - ID3D11DeviceContext_PSSetShader(d3ddevctx, prog->handle[permu].hlsl.frag, NULL, 0); + ID3D11DeviceContext_IASetInputLayout(d3ddevctx, prog->permu[permu].handle.hlsl.layout); + ID3D11DeviceContext_VSSetShader(d3ddevctx, prog->permu[permu].handle.hlsl.vert, NULL, 0); + ID3D11DeviceContext_PSSetShader(d3ddevctx, prog->permu[permu].handle.hlsl.frag, NULL, 0); ID3D11DeviceContext_IASetPrimitiveTopology(d3ddevctx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ID3D11DeviceContext_VSSetConstantBuffers(d3ddevctx, 0, sizeof(shaderstate.cbuffers)/sizeof(shaderstate.cbuffers[0]), shaderstate.cbuffers); @@ -1558,15 +1558,15 @@ static void BE_RenderMeshProgram(shader_t *s, unsigned int vertcount, unsigned i program_t *p = s->prog; - if (TEXVALID(shaderstate.curtexnums->bump) && p->handle[perm|PERMUTATION_BUMPMAP].hlsl.vert) + if (TEXVALID(shaderstate.curtexnums->bump) && p->permu[perm|PERMUTATION_BUMPMAP].handle.hlsl.vert) perm |= PERMUTATION_BUMPMAP; - if (TEXVALID(shaderstate.curtexnums->specular) && p->handle[perm|PERMUTATION_SPECULAR].hlsl.vert) + if (TEXVALID(shaderstate.curtexnums->specular) && p->permu[perm|PERMUTATION_SPECULAR].handle.hlsl.vert) perm |= PERMUTATION_SPECULAR; - if (TEXVALID(shaderstate.curtexnums->fullbright) && p->handle[perm|PERMUTATION_FULLBRIGHT].hlsl.vert) + if (TEXVALID(shaderstate.curtexnums->fullbright) && p->permu[perm|PERMUTATION_FULLBRIGHT].handle.hlsl.vert) perm |= PERMUTATION_FULLBRIGHT; - if (p->handle[perm|PERMUTATION_UPPERLOWER].hlsl.vert && (TEXVALID(shaderstate.curtexnums->upperoverlay) || TEXVALID(shaderstate.curtexnums->loweroverlay))) + if (p->permu[perm|PERMUTATION_UPPERLOWER].handle.hlsl.vert && (TEXVALID(shaderstate.curtexnums->upperoverlay) || TEXVALID(shaderstate.curtexnums->loweroverlay))) perm |= PERMUTATION_UPPERLOWER; - if (r_refdef.gfog_rgbd[3] && p->handle[perm|PERMUTATION_FOG].hlsl.vert) + if (r_refdef.gfog_rgbd[3] && p->permu[perm|PERMUTATION_FOG].handle.hlsl.vert) perm |= PERMUTATION_FOG; // if (r_glsl_offsetmapping.ival && TEXVALID(shaderstate.curtexnums->bump) && p->handle[perm|PERMUTATION_OFFSET.hlsl.vert) // perm |= PERMUTATION_OFFSET; @@ -2449,6 +2449,7 @@ static entity_t *R_NearestPortal(plane_t *plane) int i; entity_t *best = NULL; float dist, bestd = 0; + //for q3-compat, portals on world scan for a visedict to use for their view. for (i = 0; i < cl_numvisedicts; i++) { if (cl_visedicts[i].rtype == RT_PORTALSURFACE) diff --git a/engine/d3d/d3d11_image.c b/engine/d3d/d3d11_image.c index 28c81bc2..521ce811 100644 --- a/engine/d3d/d3d11_image.c +++ b/engine/d3d/d3d11_image.c @@ -125,8 +125,11 @@ static void *D3D11_AllocNewTextureData(void *datargba, int width, int height, un } texid_t D3D11_AllocNewTexture(char *ident, int width, int height, unsigned int flags) { + d3d11texture_t *t; void *img = D3D11_AllocNewTextureData(NULL, width, height, flags); - d3d11texture_t *t = d3d_lookup_texture(""); + if (!img) + return r_nulltex; + t = d3d_lookup_texture(""); t->tex2d = img; return ToTexID(t); @@ -207,6 +210,8 @@ static void Upload_Texture_32(ID3D11Texture2D *tex, unsigned int *data, int widt // D3D11_MAPPED_SUBRESOURCE lock; D3D11_TEXTURE2D_DESC desc; + if (!tex) + return; ID3D11Texture2D_GetDesc(tex, &desc); if (width == desc.Width && height == desc.Height) diff --git a/engine/d3d/d3d11_shader.c b/engine/d3d/d3d11_shader.c index 684e9dd0..844e99ca 100644 --- a/engine/d3d/d3d11_shader.c +++ b/engine/d3d/d3d11_shader.c @@ -138,9 +138,9 @@ qboolean D3D11Shader_CreateProgram (program_t *prog, const char *name, int permu ID3DBlob *vcode = NULL, *fcode = NULL, *errors = NULL; qboolean success = false; - prog->handle[permu].hlsl.vert = NULL; - prog->handle[permu].hlsl.frag = NULL; - prog->handle[permu].hlsl.layout = NULL; + prog->permu[permu].handle.hlsl.vert = NULL; + prog->permu[permu].handle.hlsl.frag = NULL; + prog->permu[permu].handle.hlsl.layout = NULL; if (pD3DCompile) { @@ -176,7 +176,7 @@ qboolean D3D11Shader_CreateProgram (program_t *prog, const char *name, int permu success = false; else { - if (FAILED(ID3D11Device_CreateVertexShader(pD3DDev11, vcode->lpVtbl->GetBufferPointer(vcode), vcode->lpVtbl->GetBufferSize(vcode), NULL, (ID3D11VertexShader**)&prog->handle[permu].hlsl.vert))) + if (FAILED(ID3D11Device_CreateVertexShader(pD3DDev11, vcode->lpVtbl->GetBufferPointer(vcode), vcode->lpVtbl->GetBufferSize(vcode), NULL, (ID3D11VertexShader**)&prog->permu[permu].handle.hlsl.vert))) success = false; } if (errors) @@ -191,7 +191,7 @@ qboolean D3D11Shader_CreateProgram (program_t *prog, const char *name, int permu success = false; else { - if (FAILED(ID3D11Device_CreatePixelShader(pD3DDev11, fcode->lpVtbl->GetBufferPointer(fcode), fcode->lpVtbl->GetBufferSize(fcode), NULL, (ID3D11PixelShader**)&prog->handle[permu].hlsl.frag))) + if (FAILED(ID3D11Device_CreatePixelShader(pD3DDev11, fcode->lpVtbl->GetBufferPointer(fcode), fcode->lpVtbl->GetBufferSize(fcode), NULL, (ID3D11PixelShader**)&prog->permu[permu].handle.hlsl.frag))) success = false; } if (errors) @@ -291,7 +291,7 @@ qboolean D3D11Shader_CreateProgram (program_t *prog, const char *name, int permu decl[elements].InstanceDataStepRate = 0; elements++; */ - if (FAILED(ID3D11Device_CreateInputLayout(pD3DDev11, decl, elements, vcode->lpVtbl->GetBufferPointer(vcode), vcode->lpVtbl->GetBufferSize(vcode), (ID3D11InputLayout**)&prog->handle[permu].hlsl.layout))) + if (FAILED(ID3D11Device_CreateInputLayout(pD3DDev11, decl, elements, vcode->lpVtbl->GetBufferPointer(vcode), vcode->lpVtbl->GetBufferSize(vcode), (ID3D11InputLayout**)&prog->permu[permu].handle.hlsl.layout))) { Con_Printf("HLSL Shader %s requires unsupported inputs\n", name); success = false; diff --git a/engine/d3d/d3d_backend.c b/engine/d3d/d3d_backend.c index ed651fdc..eaefdebf 100644 --- a/engine/d3d/d3d_backend.c +++ b/engine/d3d/d3d_backend.c @@ -33,7 +33,11 @@ Things to improve: +#define FORCESTATE +#ifdef FORCESTATE +#pragma warningmsg("D3D9 FORCESTATE is active") +#endif extern LPDIRECT3DDEVICE9 pD3DDev9; @@ -41,7 +45,9 @@ extern LPDIRECT3DDEVICE9 pD3DDev9; //#define d3dcheck(foo) foo #define d3dcheck(foo) do{HRESULT err = foo; if (FAILED(err)) Sys_Error("D3D reported error on backend line %i - error 0x%x\n", __LINE__, (unsigned int)err);} while(0) -#define MAX_TMUS 4 +#define MAX_TMUS 16 + +#define MAX_TC_TMUS 4 extern float d3d_trueprojection[16]; @@ -179,8 +185,8 @@ typedef struct unsigned int dynxyz_offs; unsigned int dynxyz_size; - IDirect3DVertexBuffer9 *dynst_buff[MAX_TMUS]; - unsigned int dynst_offs[MAX_TMUS]; + IDirect3DVertexBuffer9 *dynst_buff[MAX_TC_TMUS]; + unsigned int dynst_offs[MAX_TC_TMUS]; unsigned int dynst_size; IDirect3DVertexBuffer9 *dyncol_buff; @@ -304,7 +310,11 @@ static void BE_ApplyShaderBits(unsigned int bits) } } +#ifdef FORCESTATE + delta = ~0; +#else delta = bits ^ shaderstate.shaderbits; +#endif if (!delta) return; shaderstate.shaderbits = bits; @@ -433,7 +443,7 @@ void D3D9BE_Reset(qboolean before) if (shaderstate.dynxyz_buff) IDirect3DVertexBuffer9_Release(shaderstate.dynxyz_buff); shaderstate.dynxyz_buff = NULL; - for (tmu = 0; tmu < MAX_TMUS; tmu++) + for (tmu = 0; tmu < MAX_TC_TMUS; tmu++) { if (shaderstate.dynst_buff[tmu]) IDirect3DVertexBuffer9_Release(shaderstate.dynst_buff[tmu]); @@ -507,7 +517,7 @@ void D3D9BE_Reset(qboolean before) elements++; } - for (tmu = 0; tmu < MAX_TMUS; tmu++) + for (tmu = 0; tmu < MAX_TC_TMUS; tmu++) { if (i & (D3D_VDEC_ST0<handle[permu].hlsl.vert); - IDirect3DDevice9_SetPixelShader(pD3DDev9, prog->handle[permu].hlsl.frag); + IDirect3DDevice9_SetVertexShader(pD3DDev9, prog->permu[permu].handle.hlsl.vert); + IDirect3DDevice9_SetPixelShader(pD3DDev9, prog->permu[permu].handle.hlsl.frag); for (i = 0; i < prog->numparams; i++) { + h = prog->permu[permu].parm[i]; switch (prog->parm[i].type) { case SP_M_PROJECTION: - IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], d3d_trueprojection, 4); + IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, h, d3d_trueprojection, 4); break; case SP_M_VIEW: - IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], r_refdef.m_view, 4); + IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, h, r_refdef.m_view, 4); break; // case SP_M_MODEL: -// IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], r_refdef.m_view, 4); +// IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, h, r_refdef.m_view, 4); // break; case SP_V_EYEPOS: - IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], r_origin, 1); + IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, h, r_origin, 1); break; case SP_E_EYEPOS: { @@ -1681,13 +1693,13 @@ static void BE_ApplyUniforms(program_t *prog, int permu) float m16[16]; Matrix4x4_CM_ModelMatrixFromAxis(m16, shaderstate.curentity->axis[0], shaderstate.curentity->axis[1], shaderstate.curentity->axis[2], shaderstate.curentity->origin); Matrix4x4_CM_Transform3(m16, r_origin, t2); - IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], t2, 1); + IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, h, t2, 1); } break; case SP_E_TIME: { vec4_t t1 = {shaderstate.curtime}; - IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], t1, 1); + IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, h, t1, 1); } break; case SP_M_MODELVIEWPROJECTION: @@ -1695,7 +1707,7 @@ static void BE_ApplyUniforms(program_t *prog, int permu) float mv[16], mvp[16]; Matrix4_Multiply(r_refdef.m_view, shaderstate.m_model, mv); Matrix4_Multiply(d3d_trueprojection, mv, mvp); - IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], mvp, 4); + IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, h, mvp, 4); } break; @@ -1708,15 +1720,15 @@ static void BE_ApplyUniforms(program_t *prog, int permu) Matrix4_Invert(shaderstate.m_model, inv); Matrix4x4_CM_Transform3(inv, shaderstate.curdlight->origin, t2); - IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], t2, 3); + IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, h, t2, 3); break; } case SP_LIGHTRADIUS: - IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], &shaderstate.curdlight->radius, 1); + IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, h, &shaderstate.curdlight->radius, 1); break; case SP_LIGHTCOLOUR: - IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, prog->parm[i].handle[permu], shaderstate.curdlight_colours, 3); + IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, h, shaderstate.curdlight_colours, 3); break; case SP_E_COLOURS: @@ -1754,15 +1766,15 @@ static void BE_RenderMeshProgram(shader_t *s, unsigned int vertcount, unsigned i program_t *p = s->prog; - if (TEXVALID(shaderstate.curtexnums->bump) && p->handle[perm|PERMUTATION_BUMPMAP].hlsl.vert) + if (TEXVALID(shaderstate.curtexnums->bump) && p->permu[perm|PERMUTATION_BUMPMAP].handle.hlsl.vert) perm |= PERMUTATION_BUMPMAP; - if (TEXVALID(shaderstate.curtexnums->specular) && p->handle[perm|PERMUTATION_SPECULAR].hlsl.vert) + if (TEXVALID(shaderstate.curtexnums->specular) && p->permu[perm|PERMUTATION_SPECULAR].handle.hlsl.vert) perm |= PERMUTATION_SPECULAR; - if (TEXVALID(shaderstate.curtexnums->fullbright) && p->handle[perm|PERMUTATION_FULLBRIGHT].hlsl.vert) + if (TEXVALID(shaderstate.curtexnums->fullbright) && p->permu[perm|PERMUTATION_FULLBRIGHT].handle.hlsl.vert) perm |= PERMUTATION_FULLBRIGHT; - if (p->handle[perm|PERMUTATION_UPPERLOWER].hlsl.vert && (TEXVALID(shaderstate.curtexnums->upperoverlay) || TEXVALID(shaderstate.curtexnums->loweroverlay))) + if (p->permu[perm|PERMUTATION_UPPERLOWER].handle.hlsl.vert && (TEXVALID(shaderstate.curtexnums->upperoverlay) || TEXVALID(shaderstate.curtexnums->loweroverlay))) perm |= PERMUTATION_UPPERLOWER; - if (r_refdef.gfog_rgbd[3] && p->handle[perm|PERMUTATION_FOG].hlsl.vert) + if (r_refdef.gfog_rgbd[3] && p->permu[perm|PERMUTATION_FOG].handle.hlsl.vert) perm |= PERMUTATION_FOG; // if (r_glsl_offsetmapping.ival && TEXVALID(shaderstate.curtexnums->bump) && p->handle[perm|PERMUTATION_OFFSET.hlsl.vert) // perm |= PERMUTATION_OFFSET; diff --git a/engine/d3d/d3d_shader.c b/engine/d3d/d3d_shader.c index bdcdee6d..d5d14146 100644 --- a/engine/d3d/d3d_shader.c +++ b/engine/d3d/d3d_shader.c @@ -155,14 +155,14 @@ void D3D9Shader_Init(void) return; } -qboolean D3D9Shader_CreateProgram (program_t *prog, int permu, char **precompilerconstants, char *vert, char *frag) +qboolean D3D9Shader_CreateProgram (program_t *prog, char *sname, int permu, char **precompilerconstants, char *vert, char *frag) { D3DXMACRO defines[64]; LPD3DXBUFFER code = NULL, errors = NULL; qboolean success = false; - prog->handle[permu].hlsl.vert = NULL; - prog->handle[permu].hlsl.frag = NULL; + prog->permu[permu].handle.hlsl.vert = NULL; + prog->permu[permu].handle.hlsl.frag = NULL; if (pD3DXCompileShader) { @@ -194,32 +194,32 @@ qboolean D3D9Shader_CreateProgram (program_t *prog, int permu, char **precompile success = true; defines[0].Name = "VERTEX_SHADER"; - if (FAILED(pD3DXCompileShader(vert, strlen(vert), defines, NULL, "main", "vs_2_0", 0, &code, &errors, (LPD3DXCONSTANTTABLE*)&prog->handle[permu].hlsl.ctabv))) + if (FAILED(pD3DXCompileShader(vert, strlen(vert), defines, NULL, "main", "vs_2_0", 0, &code, &errors, (LPD3DXCONSTANTTABLE*)&prog->permu[permu].handle.hlsl.ctabv))) success = false; else { - IDirect3DDevice9_CreateVertexShader(pD3DDev9, code->lpVtbl->GetBufferPointer(code), (IDirect3DVertexShader9**)&prog->handle[permu].hlsl.vert); + IDirect3DDevice9_CreateVertexShader(pD3DDev9, code->lpVtbl->GetBufferPointer(code), (IDirect3DVertexShader9**)&prog->permu[permu].handle.hlsl.vert); code->lpVtbl->Release(code); } if (errors) { char *messages = errors->lpVtbl->GetBufferPointer(errors); - Con_Printf("%s", messages); + Con_Printf("Error compiling vertex shader %s:\n%s", sname, messages); errors->lpVtbl->Release(errors); } defines[0].Name = "FRAGMENT_SHADER"; - if (FAILED(pD3DXCompileShader(frag, strlen(frag), defines, NULL, "main", "ps_2_0", 0, &code, &errors, (LPD3DXCONSTANTTABLE*)&prog->handle[permu].hlsl.ctabf))) + if (FAILED(pD3DXCompileShader(frag, strlen(frag), defines, NULL, "main", "ps_2_0", 0, &code, &errors, (LPD3DXCONSTANTTABLE*)&prog->permu[permu].handle.hlsl.ctabf))) success = false; else { - IDirect3DDevice9_CreatePixelShader(pD3DDev9, code->lpVtbl->GetBufferPointer(code), (IDirect3DPixelShader9**)&prog->handle[permu].hlsl.frag); + IDirect3DDevice9_CreatePixelShader(pD3DDev9, code->lpVtbl->GetBufferPointer(code), (IDirect3DPixelShader9**)&prog->permu[permu].handle.hlsl.frag); code->lpVtbl->Release(code); } if (errors) { char *messages = errors->lpVtbl->GetBufferPointer(errors); - Con_Printf("%s", messages); + Con_Printf("Error compiling pixel shader %s:\n%s", sname, messages); errors->lpVtbl->Release(errors); } } diff --git a/engine/dotnet2005/ftequake.sln b/engine/dotnet2005/ftequake.sln index a04b039c..8743c1da 100644 --- a/engine/dotnet2005/ftequake.sln +++ b/engine/dotnet2005/ftequake.sln @@ -2,6 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ftequake", "ftequake.vcproj", "{88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}" ProjectSection(ProjectDependencies) = postProject + {32B12987-DF8C-4E40-B07C-B18586A4CA65} = {32B12987-DF8C-4E40-B07C-B18586A4CA65} {0018E098-B12A-4E4D-9B22-6772DA287080} = {0018E098-B12A-4E4D-9B22-6772DA287080} EndProjectSection EndProject @@ -26,7 +27,9 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "nacl", "..\nacl\nacl.vcproj EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xsv", "..\..\plugins\xsv\xsv.vcproj", "{873CCE24-3549-49D4-A4B4-653F91B1532A}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "berkelium", "..\..\plugins\berkelium\berkelium.vcproj", "{4877586B-E85B-4DF8-BCCE-59D31514D240}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "berkplug", "..\..\plugins\berkelium\berkelium.vcproj", "{4877586B-E85B-4DF8-BCCE-59D31514D240}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "avplug", "..\..\plugins\avplug\avplug.vcproj", "{32B12987-DF8C-4E40-B07C-B18586A4CA65}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -56,8 +59,8 @@ Global Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DDebug|Win32.ActiveCfg = D3DRelease|Win32 - {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DDebug|Win32.Build.0 = D3DRelease|Win32 + {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DDebug|Win32.ActiveCfg = D3DDebug|Win32 + {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DDebug|Win32.Build.0 = D3DDebug|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DDebug|x64.ActiveCfg = D3DDebug|x64 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DDebug|x64.Build.0 = D3DDebug|x64 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.D3DRelease|Win32.ActiveCfg = D3DRelease|Win32 @@ -76,6 +79,7 @@ Global {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.GLDebug|x64.ActiveCfg = GLDebug|x64 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.GLDebug|x64.Build.0 = GLDebug|x64 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.GLRelease|Win32.ActiveCfg = GLRelease|Win32 + {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.GLRelease|Win32.Build.0 = GLRelease|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.GLRelease|x64.ActiveCfg = GLRelease|x64 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.GLRelease|x64.Build.0 = GLRelease|x64 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1364}.MDebug|Win32.ActiveCfg = MDebug|Win32 @@ -144,6 +148,7 @@ Global {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.Debug|Win32.Build.0 = GLDebug|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.Debug|x64.ActiveCfg = GLDebug|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.GLDebug|Win32.ActiveCfg = GLDebug|Win32 + {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.GLDebug|Win32.Build.0 = GLDebug|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.GLDebug|x64.ActiveCfg = GLDebug|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.GLRelease|Win32.ActiveCfg = GLRelease|Win32 {88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}.GLRelease|x64.ActiveCfg = GLRelease|Win32 @@ -349,7 +354,6 @@ Global {873CCE24-3549-49D4-A4B4-653F91B1532A}.Debug|Win32.Build.0 = Debug|Win32 {873CCE24-3549-49D4-A4B4-653F91B1532A}.Debug|x64.ActiveCfg = Debug|Win32 {873CCE24-3549-49D4-A4B4-653F91B1532A}.GLDebug|Win32.ActiveCfg = Debug|Win32 - {873CCE24-3549-49D4-A4B4-653F91B1532A}.GLDebug|Win32.Build.0 = Debug|Win32 {873CCE24-3549-49D4-A4B4-653F91B1532A}.GLDebug|x64.ActiveCfg = Debug|Win32 {873CCE24-3549-49D4-A4B4-653F91B1532A}.GLRelease|Win32.ActiveCfg = Release|Win32 {873CCE24-3549-49D4-A4B4-653F91B1532A}.GLRelease|x64.ActiveCfg = Release|Win32 @@ -383,7 +387,6 @@ Global {4877586B-E85B-4DF8-BCCE-59D31514D240}.Debug|Win32.Build.0 = Debug|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.Debug|x64.ActiveCfg = Debug|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.GLDebug|Win32.ActiveCfg = Debug|Win32 - {4877586B-E85B-4DF8-BCCE-59D31514D240}.GLDebug|Win32.Build.0 = Debug|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.GLDebug|x64.ActiveCfg = Debug|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.GLRelease|Win32.ActiveCfg = Release|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.GLRelease|x64.ActiveCfg = Release|Win32 @@ -405,6 +408,41 @@ Global {4877586B-E85B-4DF8-BCCE-59D31514D240}.Release|Win32.ActiveCfg = Release|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.Release|Win32.Build.0 = Release|Win32 {4877586B-E85B-4DF8-BCCE-59D31514D240}.Release|x64.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.D3DDebug|Win32.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.D3DDebug|Win32.Build.0 = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.D3DDebug|x64.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.D3DRelease|Win32.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.D3DRelease|Win32.Build.0 = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.D3DRelease|x64.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Debug Dedicated Server|Win32.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Debug Dedicated Server|Win32.Build.0 = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Debug Dedicated Server|x64.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Debug|Win32.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Debug|Win32.Build.0 = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Debug|x64.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.GLDebug|Win32.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.GLDebug|x64.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.GLRelease|Win32.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.GLRelease|Win32.Build.0 = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.GLRelease|x64.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MDebug|Win32.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MDebug|Win32.Build.0 = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MDebug|x64.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MinGLDebug|Win32.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MinGLDebug|Win32.Build.0 = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MinGLDebug|x64.ActiveCfg = Debug|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MinGLRelease|Win32.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MinGLRelease|Win32.Build.0 = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MinGLRelease|x64.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MRelease|Win32.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MRelease|Win32.Build.0 = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.MRelease|x64.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Release Dedicated Server|Win32.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Release Dedicated Server|Win32.Build.0 = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Release Dedicated Server|x64.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Release|Win32.ActiveCfg = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Release|Win32.Build.0 = Release|Win32 + {32B12987-DF8C-4E40-B07C-B18586A4CA65}.Release|x64.ActiveCfg = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/engine/dotnet2005/ftequake.vcproj b/engine/dotnet2005/ftequake.vcproj index 3a7df4cd..740abbee 100644 --- a/engine/dotnet2005/ftequake.vcproj +++ b/engine/dotnet2005/ftequake.vcproj @@ -249,7 +249,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../libs/speex;..\client;../libs/freetype2/include;../common;../server;../gl;../sw;../qclib;../libs;../d3d9;../libs/dxsdk9/include;../libs/dxsdk7/include" - PreprocessorDefinitions="_DEBUG;D3D9QUAKE;WIN32;_WINDOWS" + PreprocessorDefinitions="_DEBUG;D3D9QUAKE;D3D11QUAKE;WIN32;_WINDOWS" RuntimeLibrary="1" FloatingPointModel="2" UsePrecompiledHeader="2" @@ -4944,6 +4944,169 @@ /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -9659,6 +9822,14 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/engine/dotnet2005/npfte.vcproj b/engine/dotnet2005/npfte.vcproj index ca2d9d3a..c129cf6b 100644 --- a/engine/dotnet2005/npfte.vcproj +++ b/engine/dotnet2005/npfte.vcproj @@ -57,7 +57,6 @@ PreprocessorDefinitions="_DEBUG;GLQUAKE;WIN32;_WINDOWS;NPQTV;MULTITHREAD" RuntimeLibrary="1" FloatingPointModel="2" - UsePrecompiledHeader="2" PrecompiledHeaderThrough="quakedef.h" BrowseInformation="1" WarningLevel="3" @@ -268,7 +267,6 @@ RuntimeLibrary="0" BufferSecurityCheck="false" FloatingPointModel="2" - UsePrecompiledHeader="2" PrecompiledHeaderThrough="quakedef.h" BrowseInformation="1" WarningLevel="3" @@ -441,6 +439,377 @@ Name="Source Files" Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -481,26463 +850,37 @@ RelativePath="..\client\sys_plugfte.h" > + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - =2?4:1)/*egl.EGL_OPENGL_ES2_BIT*/, +// egl.EGL_SURFACE_TYPE, egl.EGL_WINDOW_BIT, + egl.EGL_BLUE_SIZE, 5, + egl.EGL_GREEN_SIZE, 6, + egl.EGL_RED_SIZE, 5, + egl.EGL_DEPTH_SIZE, 16, +// egl.EGL_STENCIL_SIZE, 8, + egl.EGL_NONE, egl.EGL_NONE + }; + + if (!egl.eglChooseConfig(display, attribs, cfg, 64, num_configs)) + throw new IllegalArgumentException("eglChooseConfig failed"); + + if (num_configs[0] == 0) + { + attribs[1] = 1; //egl.EGL_RENDERABLE_TYPE, 1/*egl.EGL_OPENGL_ES_BIT*/, + if (!egl.eglChooseConfig(display, attribs, cfg, 64, num_configs)) + throw new IllegalArgumentException("eglChooseConfig failed"); + + if (num_configs[0] == 0) + { + throw new IllegalArgumentException("eglChooseConfig didn't report any valid configs"); + } + } + + android.util.Log.i("FTEDroid", "Found " + num_configs[0] + " EGL configs."); + + //try to find a gles2 context instead. + for (i = 0; i < num_configs[0]; i++) + { + android.util.Log.i("FTEDroid", "Config " + i + ":"); + egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_RED_SIZE, value); + android.util.Log.i("FTEDroid", "EGL_RED_SIZE " + value[0]); + egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_GREEN_SIZE, value); + android.util.Log.i("FTEDroid", "EGL_GREEN_SIZE " + value[0]); + egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_BLUE_SIZE, value); + android.util.Log.i("FTEDroid", "EGL_BLUE_SIZE " + value[0]); + egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_DEPTH_SIZE, value); + android.util.Log.i("FTEDroid", "EGL_DEPTH_SIZE " + value[0]); + egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_STENCIL_SIZE, value); + android.util.Log.i("FTEDroid", "EGL_STENCIL_SIZE " + value[0]); + + egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_RENDERABLE_TYPE, value); + android.util.Log.i("FTEDroid", "EGL_RENDERABLE_TYPE " + value[0]); + + if ((value[0] & 4) == 4) + { + android.util.Log.i("FTEDroid", "Found a GLES2 context!"); + return cfg[i]; + } + } + return cfg[0]; + } + } private class FTERenderer implements GLSurfaceView.Renderer { private boolean inited; public int glesversion; - private String basedir, userdir; FTEDroidActivity act; FTEView theview; + FTEEGLConfig cfgchooser; int notifiedflags; + void updateGLESVersion() + { + if (FTEDroidEngine.getpreferedglesversion() < 2) + { + android.util.Log.i("FTEDroid", "Using GLES1"); + this.glesversion = 1; + } + else if (android.os.Build.VERSION.SDK_INT >= 8) //could be 5 with setEGLContextFactory instead of setEGLContextClientVersion + { + if (cfgchooser.CheckGLES2Support()) + { + android.util.Log.i("FTEDroid", "Support for GLES2 detected"); + this.glesversion = 2; + cfgchooser.setversion(theview, this.glesversion); + } + else + { + android.util.Log.i("FTEDroid", "GLES2 not supported. Using GLES1."); + this.glesversion = 1; + } + } + else + { + android.util.Log.i("FTEDroid", "GLES2 requires android 2.2+"); + this.glesversion = 1; + } + } + FTERenderer(FTEView view, FTEDroidActivity parent) { act = parent; theview = view; - try - { - android.content.pm.PackageInfo info = parent.getPackageManager().getPackageInfo("com.fteqw", 0); - basedir = info.applicationInfo.sourceDir; - } - catch(android.content.pm.PackageManager.NameNotFoundException e) - { - /*oh well, can just use the homedir instead*/ - } -// try -// { - userdir = Environment.getExternalStorageDirectory().getPath() + "/fte"; -// } -// catch(foo) -// { -// } - android.util.Log.i("FTEDroid", "Base dir is \"" + basedir + "\"."); - android.util.Log.i("FTEDroid", "User dir is \"" + userdir + "\"."); + FTEDroidEngine.init(0, 0, 0, basedir, userdir); + inited = true; + + cfgchooser = new FTEEGLConfig(); +// theview.setEGLConfigChooser(cfgchooser); + updateGLESVersion(); } @Override @@ -140,7 +250,17 @@ public class FTEDroidActivity extends Activity act.runOnUiThread(r); } if (((flags ^ notifiedflags) & 8) != 0) - { + { + final String errormsg = FTEDroidEngine.geterrormessage(); + + inited = false; + + if (errormsg == "") + { + finish(); + System.exit(0); + } + //8 means sys error Runnable r = new Runnable() { @@ -149,7 +269,7 @@ public class FTEDroidActivity extends Activity theview.setVisibility(theview.GONE); AlertDialog ad = new AlertDialog.Builder(act).create(); ad.setTitle("FTE ERROR"); - ad.setMessage(FTEDroidEngine.geterrormessage()); + ad.setMessage(errormsg); ad.setCancelable(false); ad.setButton("Ok", new DialogInterface.OnClickListener() { @@ -166,7 +286,8 @@ public class FTEDroidActivity extends Activity act.runOnUiThread(r); } if (((flags ^ notifiedflags) & 16) != 0) - { + { + //16 means orientation cvar change Runnable r = new Runnable() { public void run() @@ -231,93 +352,6 @@ public class FTEDroidActivity extends Activity } } - private class FTEEGLConfig implements GLSurfaceView.EGLConfigChooser - { - public void setversion(FTEView view, int version) - { - view.setEGLContextClientVersion(version); - } - public boolean CheckGLES2Support() - { - EGL10 egl = (EGL10) EGLContext.getEGL(); - EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); - EGLConfig cfg; - - int[] version = new int[2]; - egl.eglInitialize(display, version); - - cfg = chooseConfig(egl, display); - - int[] value = {0}; - egl.eglGetConfigAttrib(display, cfg, EGL10.EGL_RENDERABLE_TYPE, value); - egl.eglTerminate(display); - return ((value[0] & 4) == 4); - } - - @Override - public EGLConfig chooseConfig (EGL10 egl, EGLDisplay display) - { - int EGL_CONTEXT_CLIENT_VERSION = 0x3098; - EGLConfig[] cfg = new EGLConfig[64]; - int[] num_configs = {0}; - int[] value = {0}; - int i; - int[] attribs = - { - egl.EGL_RENDERABLE_TYPE, 4/*egl.EGL_OPENGL_ES2_BIT*/, -// egl.EGL_SURFACE_TYPE, egl.EGL_WINDOW_BIT, - egl.EGL_BLUE_SIZE, 5, - egl.EGL_GREEN_SIZE, 6, - egl.EGL_RED_SIZE, 5, - egl.EGL_DEPTH_SIZE, 16, -// egl.EGL_STENCIL_SIZE, 8, - egl.EGL_NONE, egl.EGL_NONE - }; - - if (!egl.eglChooseConfig(display, attribs, cfg, 64, num_configs)) - throw new IllegalArgumentException("eglChooseConfig failed"); - - if (num_configs[0] == 0) - { - attribs[1] = 1; //egl.EGL_RENDERABLE_TYPE, 1/*egl.EGL_OPENGL_ES_BIT*/, - if (!egl.eglChooseConfig(display, attribs, cfg, 64, num_configs)) - throw new IllegalArgumentException("eglChooseConfig failed"); - - if (num_configs[0] == 0) - { - throw new IllegalArgumentException("eglChooseConfig didn't report any valid configs"); - } - } - - android.util.Log.i("FTEDroid", "Found " + num_configs[0] + " EGL configs."); - - for (i = 0; i < num_configs[0]; i++) - { - android.util.Log.i("FTEDroid", "Config " + i + ":"); - egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_RED_SIZE, value); - android.util.Log.i("FTEDroid", "EGL_RED_SIZE " + value[0]); - egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_GREEN_SIZE, value); - android.util.Log.i("FTEDroid", "EGL_GREEN_SIZE " + value[0]); - egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_BLUE_SIZE, value); - android.util.Log.i("FTEDroid", "EGL_BLUE_SIZE " + value[0]); - egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_DEPTH_SIZE, value); - android.util.Log.i("FTEDroid", "EGL_DEPTH_SIZE " + value[0]); - egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_STENCIL_SIZE, value); - android.util.Log.i("FTEDroid", "EGL_STENCIL_SIZE " + value[0]); - - egl.eglGetConfigAttrib(display, cfg[i], egl.EGL_RENDERABLE_TYPE, value); - android.util.Log.i("FTEDroid", "EGL_RENDERABLE_TYPE " + value[0]); - - if ((value[0] & 4) == 4) - { - android.util.Log.i("FTEDroid", "Found a GLES2 context!"); - return cfg[i]; - } - } - return cfg[0]; - } - } - private class FTEView extends GLSurfaceView implements SensorEventListener { private final FTERenderer rndr; @@ -334,26 +368,35 @@ public class FTEDroidActivity extends Activity { byte[] audbuf = new byte[2048]; int avail; + AudioTrack at; int chans; - if (schannels >= 8) //the OUT enumeration allows specific speaker control. but also api level 5+ - chans = AudioFormat.CHANNEL_OUT_7POINT1; - else if (schannels >= 6) - chans = AudioFormat.CHANNEL_OUT_5POINT1; - else if (schannels >= 4) - chans = AudioFormat.CHANNEL_OUT_QUAD; - else if (schannels >= 2) - chans = AudioFormat.CHANNEL_CONFIGURATION_STEREO; - else - chans = AudioFormat.CHANNEL_CONFIGURATION_MONO; - int enc = (sbits == 8)?AudioFormat.ENCODING_PCM_8BIT:AudioFormat.ENCODING_PCM_16BIT; - - int sz = 2*AudioTrack.getMinBufferSize(sspeed, chans, enc); + try + { + if (schannels >= 8) //the OUT enumeration allows specific speaker control. but also api level 5+ + chans = AudioFormat.CHANNEL_OUT_7POINT1; + else if (schannels >= 6) + chans = AudioFormat.CHANNEL_OUT_5POINT1; + else if (schannels >= 4) + chans = AudioFormat.CHANNEL_OUT_QUAD; + else if (schannels >= 2) + chans = AudioFormat.CHANNEL_CONFIGURATION_STEREO; + else + chans = AudioFormat.CHANNEL_CONFIGURATION_MONO; + int enc = (sbits == 8)?AudioFormat.ENCODING_PCM_8BIT:AudioFormat.ENCODING_PCM_16BIT; + + int sz = 2*AudioTrack.getMinBufferSize(sspeed, chans, enc); -// if (sz < sspeed * 0.05) -// sz = sspeed * 0.05; + // if (sz < sspeed * 0.05) + // sz = sspeed * 0.05; - AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, sspeed, chans, enc, sz, AudioTrack.MODE_STREAM); + at = new AudioTrack(AudioManager.STREAM_MUSIC, sspeed, chans, enc, sz, AudioTrack.MODE_STREAM); + } + catch(IllegalArgumentException e) + { + //fixme: tell the engine that its bad and that it should configure some different audio attributes, instead of simply muting. + return; + } at.setStereoVolume(1, 1); at.play(); @@ -494,35 +537,6 @@ public class FTEDroidActivity extends Activity inputevent = new FTELegacyInputEvent(); rndr = new FTERenderer(this, context); - - if (USE_GLES_VERSION < 2) - { - android.util.Log.i("FTEDroid", "GLES2 disabled at game compile time"); - rndr.glesversion = 1; - } - else if (android.os.Build.VERSION.SDK_INT >= 8) //could be 5 with setEGLContextFactory instead of setEGLContextClientVersion - { - FTEEGLConfig cfgchooser = new FTEEGLConfig(); - setEGLConfigChooser(cfgchooser); - - if (cfgchooser.CheckGLES2Support()) - { - android.util.Log.i("FTEDroid", "Support for GLES2 detected"); - rndr.glesversion = 2; - cfgchooser.setversion(this, rndr.glesversion); - } - else - { - android.util.Log.i("FTEDroid", "GLES2 not supported. Using GLES1."); - rndr.glesversion = 1; - } - } - else - { - android.util.Log.i("FTEDroid", "GLES2 requires android 2.2+"); - rndr.glesversion = 1; - } - setRenderer(rndr); setFocusable(true); setFocusableInTouchMode(true); @@ -632,6 +646,28 @@ public class FTEDroidActivity extends Activity public void onCreate(Bundle savedInstanceState) { android.util.Log.i("FTEDroid", "onCreate"); + + try + { + String packagename = this.getComponentName().getPackageName(); //"com.fteqw", but not hardcoded. + android.util.Log.i("FTEDroid", "Installed in package \"" + packagename + "\"."); + android.content.pm.PackageInfo info = this.getPackageManager().getPackageInfo(packagename, 0); + basedir = info.applicationInfo.sourceDir; + } + catch(android.content.pm.PackageManager.NameNotFoundException e) + { + /*oh well, can just use the homedir instead*/ + } +// try +// { + userdir = Environment.getExternalStorageDirectory().getPath() + "/fte"; +// } +// catch(foo) +// { +// } + android.util.Log.i("FTEDroid", "Base dir is \"" + basedir + "\"."); + android.util.Log.i("FTEDroid", "User dir is \"" + userdir + "\"."); + //go full-screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); diff --git a/engine/droid/src/com/fteqw/FTEDroidEngine.java b/engine/droid/src/com/fteqw/FTEDroidEngine.java index c46cba1c..1dce57fa 100644 --- a/engine/droid/src/com/fteqw/FTEDroidEngine.java +++ b/engine/droid/src/com/fteqw/FTEDroidEngine.java @@ -11,6 +11,7 @@ public class FTEDroidEngine public static native int audioinfo(int arg); public static native String geterrormessage(); public static native String getpreferedorientation(); + public static native int getpreferedglesversion(); public static native void newglcontext(); static diff --git a/engine/gl/gl_alias.c b/engine/gl/gl_alias.c index 9b8cc2e9..1d3a9d91 100644 --- a/engine/gl/gl_alias.c +++ b/engine/gl/gl_alias.c @@ -938,7 +938,7 @@ void R_GAlias_DrawBatch(batch_t *batch) { if (batch->surf_first == surfnum) { - needrecolour = Alias_GAliasBuildMesh(&mesh, inf, surfnum, e, true); + needrecolour = Alias_GAliasBuildMesh(&mesh, inf, surfnum, e, batch->shader->prog && batch->shader->prog->permu[PERMUTATION_SKELETAL].handle.glsl); batch->mesh = &meshl; return; } @@ -976,7 +976,7 @@ void R_GAlias_GenerateBatches(entity_t *e, batch_t **batches) clmodel = e->model; - if (!(e->flags & Q2RF_WEAPONMODEL)) + if (!(e->flags & Q2RF_WEAPONMODEL) && !e->framestate.bonestate) { if (R_CullEntityBox (e, clmodel->mins, clmodel->maxs)) return; diff --git a/engine/gl/gl_backend.c b/engine/gl/gl_backend.c index 508ef5b6..7ebd5737 100644 --- a/engine/gl/gl_backend.c +++ b/engine/gl/gl_backend.c @@ -2,9 +2,11 @@ //#define FORCESTATE +void DumpGLState(void); + #ifdef GLQUAKE -#define r_refract_fboival 1 +#define r_refract_fboival 0 #include "glquake.h" #include "shader.h" @@ -144,10 +146,10 @@ struct { qboolean force2d; int currenttmu; - int blendmode[SHADER_PASS_MAX]; - int texenvmode[SHADER_PASS_MAX]; - int currenttextures[SHADER_PASS_MAX]; - GLenum curtexturetype[SHADER_PASS_MAX]; + int blendmode[SHADER_TMU_MAX]; + int texenvmode[SHADER_TMU_MAX]; + int currenttextures[SHADER_TMU_MAX]; + GLenum curtexturetype[SHADER_TMU_MAX]; polyoffset_t curpolyoffset; unsigned int curcull; @@ -182,6 +184,10 @@ struct { int curvertexvbo; void *curvertexpointer; + int pendingtexcoordparts[SHADER_TMU_MAX]; + int pendingtexcoordvbo[SHADER_TMU_MAX]; + void *pendingtexcoordpointer[SHADER_TMU_MAX]; + float identitylighting; //set to how bright lightmaps should be (reduced for overbright or realtime_world_lightmaps) texid_t temptexture; //$current @@ -395,8 +401,6 @@ void GL_DeselectVAO(void) void GL_SelectEBO(int vbo) { //EBO is part of the current VAO, so keep things matching that - GL_DeselectVAO(); - #ifndef FORCESTATE if (shaderstate.currentebo != vbo) #endif @@ -506,12 +510,21 @@ static void BE_ApplyAttributes(unsigned int bitstochange, unsigned int bitstoend } //legacy tmus - if (bitstoendisable >= (1u<= (1u<= (1u<= (1u<texcoord.gl.addr); break; case VATTR_LMCOORD: - GL_SelectVBO(shaderstate.sourcevbo->lmcoord[0].gl.vbo); - qglVertexAttribPointer(VATTR_LMCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vec2_t), shaderstate.sourcevbo->lmcoord[0].gl.addr); + if (!shaderstate.sourcevbo->lmcoord[0].gl.vbo && !shaderstate.sourcevbo->lmcoord[0].gl.addr) + { + GL_SelectVBO(shaderstate.sourcevbo->texcoord.gl.vbo); + qglVertexAttribPointer(VATTR_LMCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vec2_t), shaderstate.sourcevbo->texcoord.gl.addr); + } + else + { + GL_SelectVBO(shaderstate.sourcevbo->lmcoord[0].gl.vbo); + qglVertexAttribPointer(VATTR_LMCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(vec2_t), shaderstate.sourcevbo->lmcoord[0].gl.addr); + } break; case VATTR_LMCOORD2: GL_SelectVBO(shaderstate.sourcevbo->lmcoord[1].gl.vbo); @@ -644,10 +665,16 @@ static void BE_ApplyAttributes(unsigned int bitstochange, unsigned int bitstoend } } -static void BE_EnableShaderAttributes(unsigned int progattrmask) +static void BE_EnableShaderAttributes(unsigned int progattrmask, int usevao) { unsigned int bitstochange, bitstoendisable; + if (shaderstate.currentvao != usevao) + { + shaderstate.currentvao = usevao; + qglBindVertexArray(usevao); + } + if (shaderstate.currentvao) { bitstochange = shaderstate.sourcevbo->vaodynamic&progattrmask; @@ -719,6 +746,8 @@ void GLBE_SetupVAO(vbo_t *vbo, unsigned vaodynamic) } else { + GL_DeselectVAO(); + /*always select the coord vbo and indicies ebo, for easy bufferdata*/ GL_SelectEBO(vbo->indicies.gl.vbo); GL_SelectVBO(vbo->coord.gl.vbo); @@ -755,13 +784,15 @@ void GLBE_RenderShadowBuffer(unsigned int numverts, int vbo, vecV_t *verts, unsi { GL_SelectProgram(shaderstate.allblackshader); - BE_EnableShaderAttributes(gl_config.nofixedfunc?(1u<0) { @@ -970,6 +1000,7 @@ static void T_Gen_CurrentRender(int tmu) static void Shader_BindTextureForPass(int tmu, const shaderpass_t *pass) { extern texid_t missing_texture; + extern texid_t missing_texture_gloss; extern texid_t scenepp_postproc_cube; extern texid_t r_whiteimage; @@ -1008,7 +1039,10 @@ static void Shader_BindTextureForPass(int tmu, const shaderpass_t *pass) t = shaderstate.curtexnums?shaderstate.curtexnums->bump:r_nulltex; /*FIXME: nulltex is not correct*/ break; case T_GEN_SPECULAR: - t = shaderstate.curtexnums->specular; + if (TEXVALID(shaderstate.curtexnums->specular)) + t = shaderstate.curtexnums->specular; + else + t = missing_texture_gloss; break; case T_GEN_UPPEROVERLAY: t = shaderstate.curtexnums->upperoverlay; @@ -1490,9 +1524,10 @@ static void GenerateTCFog(int passnum, mfog_t *fog) mesh = shaderstate.meshes[m]; tcgen_fog(texcoordarray[passnum]+mesh->vbofirstvert*2, mesh->numvertexes, (float*)mesh->xyz_array, fog); } - GL_SelectVBO(0); - qglClientActiveTextureARB(mtexid0 + passnum); - qglTexCoordPointer(2, GL_FLOAT, 0, texcoordarray[passnum]); + + shaderstate.pendingtexcoordparts[passnum] = 2; + shaderstate.pendingtexcoordvbo[passnum] = 0; + shaderstate.pendingtexcoordpointer[passnum] = texcoordarray[passnum]; } static void GenerateTCMods(const shaderpass_t *pass, int passnum) { @@ -1521,9 +1556,11 @@ static void GenerateTCMods(const shaderpass_t *pass, int passnum) memcpy(texcoordarray[passnum]+mesh->vbofirstvert*2, src, 8*mesh->numvertexes); } } - GL_SelectVBO(0); - qglTexCoordPointer(2, GL_FLOAT, 0, texcoordarray[passnum]); + shaderstate.pendingtexcoordparts[passnum] = 2; + shaderstate.pendingtexcoordvbo[passnum] = 0; + shaderstate.pendingtexcoordpointer[passnum] = texcoordarray[passnum]; #else + GL_DeselectVAO(); if (!shaderstate.vbo_texcoords[passnum]) { qglGenBuffersARB(1, &shaderstate.vbo_texcoords[passnum]); @@ -1550,7 +1587,10 @@ static void GenerateTCMods(const shaderpass_t *pass, int passnum) qglBufferSubDataARB(GL_ARRAY_BUFFER_ARB, meshlist->vbofirstvert*8, meshlist->numvertexes*8, src); } } - qglTexCoordPointer(2, GL_FLOAT, 0, NULL); + + shaderstate.pendingtexcoordparts[passnum] = 2; + shaderstate.pendingtexcoordvbo[passnum] = shaderstate.vbo_texcoords[passnum]; + shaderstate.pendingtexcoordpointer[passnum] = NULL; #endif } @@ -2199,42 +2239,47 @@ static void GenerateColourMods(const shaderpass_t *pass) static void BE_GeneratePassTC(const shaderpass_t *pass, int tmu) { - qglClientActiveTextureARB(mtexid0 + tmu); if (!pass->numtcmods) { //if there are no tcmods, pass through here as fast as possible if (pass->tcgen == TC_GEN_BASE) { - GL_SelectVBO(shaderstate.sourcevbo->texcoord.gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->texcoord.gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 2; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->texcoord.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->texcoord.gl.addr; } else if (pass->tcgen == TC_GEN_LIGHTMAP) { if (!shaderstate.sourcevbo->lmcoord[0].gl.addr) { - GL_SelectVBO(shaderstate.sourcevbo->texcoord.gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->texcoord.gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 2; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->texcoord.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->texcoord.gl.addr; } else { - GL_SelectVBO(shaderstate.sourcevbo->lmcoord[0].gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->lmcoord[0].gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 2; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->lmcoord[0].gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->lmcoord[0].gl.addr; } } else if (pass->tcgen == TC_GEN_NORMAL) { - GL_SelectVBO(shaderstate.sourcevbo->normals.gl.vbo); - qglTexCoordPointer(3, GL_FLOAT, 0, shaderstate.sourcevbo->normals.gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 3; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->normals.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->normals.gl.addr; } else if (pass->tcgen == TC_GEN_SVECTOR) { - GL_SelectVBO(shaderstate.sourcevbo->svector.gl.vbo); - qglTexCoordPointer(3, GL_FLOAT, 0, shaderstate.sourcevbo->svector.gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 3; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->svector.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->svector.gl.addr; } else if (pass->tcgen == TC_GEN_TVECTOR) { - GL_SelectVBO(shaderstate.sourcevbo->tvector.gl.vbo); - qglTexCoordPointer(3, GL_FLOAT, 0, shaderstate.sourcevbo->tvector.gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 3; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->tvector.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->tvector.gl.addr; } else { @@ -2569,7 +2614,7 @@ static void DrawPass(const shaderpass_t *pass) shaderstate.lastpasstmus = tmu; /*push it*/ - BE_EnableShaderAttributes(attr); + BE_EnableShaderAttributes(attr, 0); BE_SubmitMeshChain(); tmu = 0; @@ -2586,9 +2631,9 @@ static void DrawPass(const shaderpass_t *pass) shaderstate.pendingcolourflat[3] = 1; /*pick the correct st coords for this lightmap pass*/ - qglClientActiveTextureARB(mtexid0 + tmu); - GL_SelectVBO(shaderstate.sourcevbo->lmcoord[j].gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->lmcoord[j].gl.addr); + shaderstate.pendingtexcoordparts[tmu] = 2; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->lmcoord[j].gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->lmcoord[j].gl.addr; BE_SetPassBlendMode(tmu, PBM_ADD); BE_SendPassBlendDepthMask((pass[0].shaderbits & ~SBITS_BLEND_BITS) | SBITS_SRCBLEND_ONE | SBITS_DSTBLEND_ONE); @@ -2607,7 +2652,7 @@ static void DrawPass(const shaderpass_t *pass) GL_LazyBind(k, 0, r_nulltex); } shaderstate.lastpasstmus = tmu; - BE_EnableShaderAttributes(attr); + BE_EnableShaderAttributes(attr, 0); BE_SubmitMeshChain(); tmu = 0; @@ -2626,7 +2671,7 @@ static void DrawPass(const shaderpass_t *pass) GL_LazyBind(i, 0, r_nulltex); } shaderstate.lastpasstmus = tmu; - BE_EnableShaderAttributes(attr); + BE_EnableShaderAttributes(attr, 0); BE_SubmitMeshChain(); } @@ -2636,6 +2681,7 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, vec3_t param3; int r, g, b; int i; + unsigned int ph; const shaderprogparm_t *p; /*don't bother setting it if the ent properties are unchanged (but do if the mesh changed)*/ @@ -2645,25 +2691,26 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, for (i = 0; i < prog->numparams; i++) { p = &prog->parm[i]; - if (p->handle[perm] == -1) + ph = prog->permu[perm].parm[i]; + if (ph == -1) continue; /*not in this permutation*/ switch(p->type) { case SP_M_VIEW: - qglUniformMatrix4fvARB(p->handle[perm], 1, false, r_refdef.m_view); + qglUniformMatrix4fvARB(ph, 1, false, r_refdef.m_view); break; case SP_M_PROJECTION: - qglUniformMatrix4fvARB(p->handle[perm], 1, false, r_refdef.m_projection); + qglUniformMatrix4fvARB(ph, 1, false, r_refdef.m_projection); break; case SP_M_MODELVIEW: - qglUniformMatrix4fvARB(p->handle[perm], 1, false, shaderstate.modelviewmatrix); + qglUniformMatrix4fvARB(ph, 1, false, shaderstate.modelviewmatrix); break; case SP_M_MODELVIEWPROJECTION: { float m16[16]; Matrix4_Multiply(r_refdef.m_projection, shaderstate.modelviewmatrix, m16); - qglUniformMatrix4fvARB(p->handle[perm], 1, false, m16); + qglUniformMatrix4fvARB(ph, 1, false, m16); } break; case SP_M_INVMODELVIEWPROJECTION: @@ -2671,15 +2718,15 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, float m16[16], inv[16]; Matrix4_Multiply(r_refdef.m_projection, shaderstate.modelviewmatrix, m16); Matrix4_Invert(m16, inv); - qglUniformMatrix4fvARB(p->handle[perm], 1, false, inv); + qglUniformMatrix4fvARB(ph, 1, false, inv); } break; case SP_M_MODEL: - qglUniformMatrix4fvARB(p->handle[perm], 1, false, shaderstate.modelmatrix); + qglUniformMatrix4fvARB(ph, 1, false, shaderstate.modelmatrix); break; case SP_M_ENTBONES: { - qglUniformMatrix3x4fv(p->handle[perm], shaderstate.sourcevbo->numbones, false, shaderstate.sourcevbo->bones); + qglUniformMatrix3x4fv(ph, shaderstate.sourcevbo->numbones, false, shaderstate.sourcevbo->bones); } break; case SP_M_INVVIEWPROJECTION: @@ -2687,12 +2734,12 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, float m16[16], inv[16]; Matrix4_Multiply(r_refdef.m_projection, r_refdef.m_view, m16); Matrix4_Invert(m16, inv); - qglUniformMatrix4fvARB(p->handle[perm], 1, false, inv); + qglUniformMatrix4fvARB(ph, 1, false, inv); } break; case SP_E_VBLEND: - qglUniform2fvARB(p->handle[perm], 1, shaderstate.meshes[0]->xyz_blendw); + qglUniform2fvARB(ph, 1, shaderstate.meshes[0]->xyz_blendw); break; case SP_E_LMSCALE: @@ -2728,7 +2775,7 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, VectorScale(colscale[j], d_lightstylevalue[s]/256.0f, colscale[j]); } - qglUniform4fvARB(p->handle[perm], j, (GLfloat*)colscale); + qglUniform4fvARB(ph, j, (GLfloat*)colscale); shaderstate.lastuniform = 0; } else @@ -2745,38 +2792,38 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, } colscale[0][3] = 1; - qglUniform4fvARB(p->handle[perm], 1, (GLfloat*)colscale); + qglUniform4fvARB(ph, 1, (GLfloat*)colscale); } break; case SP_E_GLOWMOD: - qglUniform3fvARB(p->handle[perm], 1, (GLfloat*)shaderstate.curentity->glowmod); + qglUniform3fvARB(ph, 1, (GLfloat*)shaderstate.curentity->glowmod); break; case SP_E_ORIGIN: - qglUniform3fvARB(p->handle[perm], 1, (GLfloat*)shaderstate.curentity->origin); + qglUniform3fvARB(ph, 1, (GLfloat*)shaderstate.curentity->origin); break; case SP_E_COLOURS: - qglUniform4fvARB(p->handle[perm], 1, (GLfloat*)shaderstate.curentity->shaderRGBAf); + qglUniform4fvARB(ph, 1, (GLfloat*)shaderstate.curentity->shaderRGBAf); break; case SP_E_COLOURSIDENT: if (shaderstate.flags & BEF_FORCECOLOURMOD) - qglUniform4fvARB(p->handle[perm], 1, (GLfloat*)shaderstate.curentity->shaderRGBAf); + qglUniform4fvARB(ph, 1, (GLfloat*)shaderstate.curentity->shaderRGBAf); else - qglUniform4fARB(p->handle[perm], 1, 1, 1, shaderstate.curentity->shaderRGBAf[3]); + qglUniform4fARB(ph, 1, 1, 1, shaderstate.curentity->shaderRGBAf[3]); break; case SP_E_TOPCOLOURS: R_FetchTopColour(&r, &g, &b); param3[0] = r/255.0f; param3[1] = g/255.0f; param3[2] = b/255.0f; - qglUniform3fvARB(p->handle[perm], 1, param3); + qglUniform3fvARB(ph, 1, param3); break; case SP_E_BOTTOMCOLOURS: R_FetchBottomColour(&r, &g, &b); param3[0] = r/255.0f; param3[1] = g/255.0f; param3[2] = b/255.0f; - qglUniform3fvARB(p->handle[perm], 1, param3); + qglUniform3fvARB(ph, 1, param3); break; case SP_RENDERTEXTURESCALE: @@ -2797,7 +2844,7 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, param3[1] = vid.pixelheight/(float)g; } param3[2] = 1; - qglUniform3fvARB(p->handle[perm], 1, param3); + qglUniform3fvARB(ph, 1, param3); break; case SP_LIGHTSCREEN: @@ -2817,27 +2864,27 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, v[1] = (v[1]/v[3]) + 0.5; v[2] = (v[2]/v[3]) + 0.5; - qglUniform3fvARB(p->handle[perm], 1, v); + qglUniform3fvARB(ph, 1, v); } break; case SP_LIGHTRADIUS: - qglUniform1fARB(p->handle[perm], shaderstate.lightradius); + qglUniform1fARB(ph, shaderstate.lightradius); break; case SP_LIGHTCOLOUR: - qglUniform3fvARB(p->handle[perm], 1, shaderstate.lightcolours); + qglUniform3fvARB(ph, 1, shaderstate.lightcolours); break; case SP_W_FOG: - qglUniform4fvARB(p->handle[perm], 1, r_refdef.gfog_rgbd); + qglUniform4fvARB(ph, 1, r_refdef.gfog_rgbd); break; case SP_V_EYEPOS: - qglUniform3fvARB(p->handle[perm], 1, r_origin); + qglUniform3fvARB(ph, 1, r_origin); break; case SP_E_EYEPOS: { /*eye position in model space*/ vec3_t t2; Matrix4x4_CM_Transform3(shaderstate.modelmatrixinv, r_origin, t2); - qglUniform3fvARB(p->handle[perm], 1, t2); + qglUniform3fvARB(ph, 1, t2); } break; case SP_LIGHTPOSITION: @@ -2845,17 +2892,17 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, /*light position in model space*/ vec3_t t2; Matrix4x4_CM_Transform3(shaderstate.modelmatrixinv, shaderstate.lightorg, t2); - qglUniform3fvARB(p->handle[perm], 1, t2); + qglUniform3fvARB(ph, 1, t2); } break; case SP_LIGHTCOLOURSCALE: - qglUniform3fvARB(p->handle[perm], 1, shaderstate.lightcolourscale); + qglUniform3fvARB(ph, 1, shaderstate.lightcolourscale); break; case SP_LIGHTPROJMATRIX: { float t[16]; Matrix4x4_CM_Projection_Far(t, 90, 90, 4, 3000); - qglUniformMatrix4fvARB(p->handle[perm], 1, false, t); + qglUniformMatrix4fvARB(ph, 1, false, t); } break; case SP_LIGHTCUBEMATRIX: @@ -2863,36 +2910,36 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, { float t[16]; Matrix4_Multiply(shaderstate.modelmatrix, shaderstate.lightprojmatrix, t); - qglUniformMatrix4fvARB(p->handle[perm], 1, false, t); + qglUniformMatrix4fvARB(ph, 1, false, t); } break; /*static lighting info*/ case SP_E_L_DIR: - qglUniform3fvARB(p->handle[perm], 1, (float*)shaderstate.curentity->light_dir); + qglUniform3fvARB(ph, 1, (float*)shaderstate.curentity->light_dir); break; case SP_E_L_MUL: - qglUniform3fvARB(p->handle[perm], 1, (float*)shaderstate.curentity->light_range); + qglUniform3fvARB(ph, 1, (float*)shaderstate.curentity->light_range); break; case SP_E_L_AMBIENT: - qglUniform3fvARB(p->handle[perm], 1, (float*)shaderstate.curentity->light_avg); + qglUniform3fvARB(ph, 1, (float*)shaderstate.curentity->light_avg); break; case SP_E_TIME: - qglUniform1fARB(p->handle[perm], shaderstate.curtime); + qglUniform1fARB(ph, shaderstate.curtime); break; case SP_CONSTI: case SP_TEXTURE: - qglUniform1iARB(p->handle[perm], p->ival); + qglUniform1iARB(ph, p->ival); break; case SP_CONSTF: - qglUniform1fARB(p->handle[perm], p->fval); + qglUniform1fARB(ph, p->fval); break; case SP_CVARI: - qglUniform1iARB(p->handle[perm], ((cvar_t*)p->pval)->ival); + qglUniform1iARB(ph, ((cvar_t*)p->pval)->ival); break; case SP_CVARF: - qglUniform1fARB(p->handle[perm], ((cvar_t*)p->pval)->value); + qglUniform1fARB(ph, ((cvar_t*)p->pval)->value); break; case SP_CVAR3F: { @@ -2904,7 +2951,7 @@ static void BE_Program_Set_Attributes(const program_t *prog, unsigned int perm, param3[1] = atof(com_token); vs = COM_Parse(vs); param3[2] = atof(com_token); - qglUniform3fvARB(p->handle[perm], 1, param3); + qglUniform3fvARB(ph, 1, param3); } break; @@ -2925,45 +2972,42 @@ static void BE_RenderMeshProgram(const shader_t *shader, const shaderpass_t *pas perm = 0; if (shaderstate.sourcevbo->numbones) { - if (p->handle[perm|PERMUTATION_SKELETAL].glsl) + if (p->permu[perm|PERMUTATION_SKELETAL].handle.glsl) perm |= PERMUTATION_SKELETAL; else return; } - if (p->handle[perm|PERMUTATION_FRAMEBLEND].glsl && shaderstate.sourcevbo->coord2.gl.addr) + if (p->permu[perm|PERMUTATION_FRAMEBLEND].handle.glsl && shaderstate.sourcevbo->coord2.gl.addr) perm |= PERMUTATION_FRAMEBLEND; - if (TEXVALID(shaderstate.curtexnums->bump) && p->handle[perm|PERMUTATION_BUMPMAP].glsl) + if (TEXVALID(shaderstate.curtexnums->bump) && p->permu[perm|PERMUTATION_BUMPMAP].handle.glsl) perm |= PERMUTATION_BUMPMAP; - if (TEXVALID(shaderstate.curtexnums->specular) && p->handle[perm|PERMUTATION_SPECULAR].glsl) + if (/*TEXVALID(shaderstate.curtexnums->specular) &&*/ p->permu[perm|PERMUTATION_SPECULAR].handle.glsl) perm |= PERMUTATION_SPECULAR; - if (TEXVALID(shaderstate.curtexnums->fullbright) && p->handle[perm|PERMUTATION_FULLBRIGHT].glsl) + if (TEXVALID(shaderstate.curtexnums->fullbright) && p->permu[perm|PERMUTATION_FULLBRIGHT].handle.glsl) perm |= PERMUTATION_FULLBRIGHT; - if ((TEXVALID(shaderstate.curtexnums->loweroverlay) || TEXVALID(shaderstate.curtexnums->upperoverlay)) && p->handle[perm|PERMUTATION_UPPERLOWER].glsl) + if ((TEXVALID(shaderstate.curtexnums->loweroverlay) || TEXVALID(shaderstate.curtexnums->upperoverlay)) && p->permu[perm|PERMUTATION_UPPERLOWER].handle.glsl) perm |= PERMUTATION_UPPERLOWER; - if (r_refdef.gfog_rgbd[3] && p->handle[perm|PERMUTATION_FOG].glsl) + if (r_refdef.gfog_rgbd[3] && p->permu[perm|PERMUTATION_FOG].handle.glsl) perm |= PERMUTATION_FOG; - if (p->handle[perm|PERMUTATION_DELUXE].glsl && TEXVALID(shaderstate.curtexnums->bump) && shaderstate.curbatch->lightmap[0] >= 0 && lightmap[shaderstate.curbatch->lightmap[0]]->hasdeluxe) + if (p->permu[perm|PERMUTATION_DELUXE].handle.glsl && TEXVALID(shaderstate.curtexnums->bump) && shaderstate.curbatch->lightmap[0] >= 0 && lightmap[shaderstate.curbatch->lightmap[0]]->hasdeluxe) perm |= PERMUTATION_DELUXE; - if (shaderstate.curbatch->lightmap[1] >= 0 && p->handle[perm|PERMUTATION_LIGHTSTYLES].glsl) + if (shaderstate.curbatch->lightmap[1] >= 0 && p->permu[perm|PERMUTATION_LIGHTSTYLES].handle.glsl) perm |= PERMUTATION_LIGHTSTYLES; - if (shaderstate.currentvao != shaderstate.sourcevbo->vao) - { - shaderstate.currentvao = shaderstate.sourcevbo->vao; - qglBindVertexArray(shaderstate.sourcevbo->vao); - } - GL_SelectProgram(p->handle[perm].glsl); - if (shaderstate.lastuniform == p->handle[perm].glsl) + GL_SelectProgram(p->permu[perm].handle.glsl); +#ifndef FORCESTATE + if (shaderstate.lastuniform == p->permu[perm].handle.glsl) i = true; else +#endif { i = false; - shaderstate.lastuniform = p->handle[perm].glsl; + shaderstate.lastuniform = p->permu[perm].handle.glsl; } BE_Program_Set_Attributes(p, perm, i); BE_SendPassBlendDepthMask(pass->shaderbits); - BE_EnableShaderAttributes(p->attrmask[perm]); + BE_EnableShaderAttributes(p->permu[perm].attrmask, shaderstate.sourcevbo->vao); if (p->nofixedcompat) { for (i = 0; i < pass->numMergedPasses; i++) @@ -3186,6 +3230,7 @@ void GLBE_SelectDLight(dlight_t *dl, vec3_t colour) { float view[16], proj[16]; int lmode; + extern cvar_t gl_specular; /*generate light projection information*/ float nearplane = 4; @@ -3205,6 +3250,7 @@ void GLBE_SelectDLight(dlight_t *dl, vec3_t colour) shaderstate.lightradius = dl->radius; VectorCopy(dl->origin, shaderstate.lightorg); VectorCopy(dl->lightcolourscales, shaderstate.lightcolourscale); + shaderstate.lightcolourscale[2] *= gl_specular.value; VectorCopy(colour, shaderstate.lightcolours); #ifdef RTLIGHTS shaderstate.lightcubemap = dl->cubetexture; @@ -3268,6 +3314,7 @@ static void BE_LegacyLighting(void) int i, m; mesh_t *mesh; unsigned int attr = (1u<bump.num && gl_config.arb_texture_cube_map && gl_config.arb_texture_env_dot3 && gl_config.arb_texture_env_combine && be_maxpasses >= 4) { //we could get this down to 2 tmus by arranging for the dot3 result to be written the alpha buffer. But then we'd need to have an alpha buffer too. - attr |= (1u<<(VATTR_LEG_TMU0)) | (1u<<(VATTR_LEG_TMU0+1)) | (1u<<(VATTR_LEG_TMU0+2)); if (!shaderstate.normalisationcubemap.num) shaderstate.normalisationcubemap = GenerateNormalisationCubeMap(); //tmu0: normalmap+replace+regular tex coords - GL_LazyBind(0, GL_TEXTURE_2D, shaderstate.curtexnums->bump); - BE_SetPassBlendMode(0, PBM_REPLACE); - qglClientActiveTextureARB(mtexid0 + 0); - GL_SelectVBO(shaderstate.sourcevbo->texcoord.gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->texcoord.gl.addr); + GL_LazyBind(tmu, GL_TEXTURE_2D, shaderstate.curtexnums->bump); + BE_SetPassBlendMode(tmu, PBM_REPLACE); + shaderstate.pendingtexcoordparts[tmu] = 2; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->texcoord.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->texcoord.gl.addr; + attr |= (1u<<(VATTR_LEG_TMU0+tmu)); + tmu++; //tmu1: normalizationcubemap+dot3+lightdir - GL_LazyBind(1, GL_TEXTURE_CUBE_MAP_ARB, shaderstate.normalisationcubemap); - BE_SetPassBlendMode(1, PBM_DOTPRODUCT); - qglClientActiveTextureARB(mtexid0 + 1); - GL_SelectVBO(0); - qglTexCoordPointer(3, GL_FLOAT, 0, texcoordarray[0]); + GL_LazyBind(tmu, GL_TEXTURE_CUBE_MAP_ARB, shaderstate.normalisationcubemap); + BE_SetPassBlendMode(tmu, PBM_DOTPRODUCT); + shaderstate.pendingtexcoordparts[tmu] = 3; + shaderstate.pendingtexcoordvbo[tmu] = 0; + shaderstate.pendingtexcoordpointer[tmu] = texcoordarray[0]; + attr |= (1u<<(VATTR_LEG_TMU0+tmu)); + tmu++; //tmu2: $diffuse+multiply+regular tex coords - GL_LazyBind(2, GL_TEXTURE_2D, shaderstate.curtexnums->base); //texture not used, its just to make sure the code leaves it enabled. - BE_SetPassBlendMode(2, PBM_MODULATE); - qglClientActiveTextureARB(mtexid0 + 2); - GL_SelectVBO(shaderstate.sourcevbo->texcoord.gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->texcoord.gl.addr); + GL_LazyBind(tmu, GL_TEXTURE_2D, shaderstate.curtexnums->base); //texture not used, its just to make sure the code leaves it enabled. + BE_SetPassBlendMode(tmu, PBM_MODULATE); + shaderstate.pendingtexcoordparts[tmu] = 2; + shaderstate.pendingtexcoordvbo[tmu] = shaderstate.sourcevbo->texcoord.gl.vbo; + shaderstate.pendingtexcoordpointer[tmu] = shaderstate.sourcevbo->texcoord.gl.addr; + attr |= (1u<<(VATTR_LEG_TMU0+tmu)); + tmu++; //tmu3: $any+multiply-by-colour+notc - GL_LazyBind(3, GL_TEXTURE_2D, shaderstate.curtexnums->bump); //texture not used, its just to make sure the code leaves it enabled. - BE_SetPassBlendMode(3, PBM_MODULATE_PREV_COLOUR); + GL_LazyBind(tmu, GL_TEXTURE_2D, shaderstate.curtexnums->bump); //texture not used, its just to make sure the code leaves it enabled. + BE_SetPassBlendMode(tmu, PBM_MODULATE_PREV_COLOUR); + shaderstate.pendingtexcoordparts[tmu] = 0; + shaderstate.pendingtexcoordvbo[tmu] = 0; + shaderstate.pendingtexcoordpointer[tmu] = NULL; + tmu++; //note we need 4 combiners in the first because we can't use the colour argument in the first without breaking the normals. - for (i = 4; i < shaderstate.lastpasstmus; i++) + for (i = tmu; i < shaderstate.lastpasstmus; i++) { - GL_LazyBind(i, GL_TEXTURE_2D, r_nulltex); + GL_LazyBind(i, 0, r_nulltex); } - shaderstate.lastpasstmus = 4; + shaderstate.lastpasstmus = tmu; } else { @@ -3341,13 +3397,12 @@ static void BE_LegacyLighting(void) //multiplies by vertex colours GL_LazyBind(0, GL_TEXTURE_2D, shaderstate.curtexnums->base); //texture not used, its just to make sure the code leaves it enabled. BE_SetPassBlendMode(0, PBM_MODULATE); - qglClientActiveTextureARB(mtexid0 + 0); - GL_SelectVBO(shaderstate.sourcevbo->texcoord.gl.vbo); - qglTexCoordPointer(2, GL_FLOAT, 0, shaderstate.sourcevbo->texcoord.gl.addr); + shaderstate.pendingtexcoordvbo[0] = shaderstate.sourcevbo->texcoord.gl.vbo; + shaderstate.pendingtexcoordpointer[0] = shaderstate.sourcevbo->texcoord.gl.addr; for (i = 1; i < shaderstate.lastpasstmus; i++) { - GL_LazyBind(i, GL_TEXTURE_2D, r_nulltex); + GL_LazyBind(i, 0, r_nulltex); } shaderstate.lastpasstmus = 1; } @@ -3356,15 +3411,14 @@ static void BE_LegacyLighting(void) shaderstate.pendingcolourvbo = 0; shaderstate.pendingcolourpointer = coloursarray; - GL_DeselectVAO(); GL_DeSelectProgram(); - BE_EnableShaderAttributes(attr); + BE_EnableShaderAttributes(attr, 0); BE_SubmitMeshChain(); - GL_LazyBind(1, GL_TEXTURE_2D, r_nulltex); - GL_LazyBind(2, GL_TEXTURE_2D, r_nulltex); - GL_LazyBind(3, GL_TEXTURE_2D, r_nulltex); + GL_LazyBind(1, 0, r_nulltex); + GL_LazyBind(2, 0, r_nulltex); + GL_LazyBind(3, 0, r_nulltex); } #endif @@ -3455,8 +3509,11 @@ static void DrawMeshes(void) break; } - if (!shaderstate.shader_light[shaderstate.lightmode]) + if (!shaderstate.shader_light[shaderstate.lightmode] || !shaderstate.shader_light[shaderstate.lightmode]->prog) + { + shaderstate.shader_light[shaderstate.lightmode] = NULL; break; + } } else { @@ -3478,27 +3535,24 @@ static void DrawMeshes(void) BE_RenderMeshProgram(shaderstate.crepopaqueshader, shaderstate.crepopaqueshader->passes); break; case BEM_DEPTHONLY: - GL_DeselectVAO(); GL_DeSelectProgram(); #ifdef warningmsg #pragma warningmsg("fixme: support alpha test") #endif - BE_EnableShaderAttributes((1u<passes[0].shaderbits | SBITS_MISC_NODEPTHTEST); - BE_EnableShaderAttributes((1u<flags & SHADER_HASLIGHTMAP) && !TEXVALID(shaderstate.curtexnums->fullbright) && !gl_config.nofixedfunc) { - //FIXME: do this with a shader instead? its not urgent as we can draw the shader normally anyway, just faster. - GL_DeselectVAO(); - GL_DeSelectProgram(); - shaderstate.pendingcolourvbo = 0; - shaderstate.pendingcolourpointer = NULL; - Vector4Set(shaderstate.pendingcolourflat, 0, 0, 0, 1); - while(shaderstate.lastpasstmus>0) + if (gl_config.arb_shader_objects) { - GL_LazyBind(--shaderstate.lastpasstmus, 0, r_nulltex); - } - BE_SetPassBlendMode(0, PBM_REPLACE); - BE_SendPassBlendDepthMask(shaderstate.curshader->passes[0].shaderbits); + char *defs[] = {NULL}; + if (!shaderstate.allblackshader) + shaderstate.allblackshader = GLSlang_CreateProgram("allblackprogram", gl_config.gles?100:110, defs, "#include \"sys/skeletal.h\"\nvoid main(){gl_Position = skeletaltransform();}", "void main(){gl_FragColor=vec4(0.0,0.0,0.0,1.0);}", false); - BE_EnableShaderAttributes((1u<passes[0].shaderbits); + BE_EnableShaderAttributes(1u<0) + { + GL_LazyBind(--shaderstate.lastpasstmus, 0, r_nulltex); + } + + BE_SetPassBlendMode(0, PBM_REPLACE); + BE_SendPassBlendDepthMask(shaderstate.curshader->passes[0].shaderbits); + + BE_EnableShaderAttributes((1u<numpasses) { @@ -3558,7 +3632,6 @@ static void DrawMeshes(void) } if (shaderstate.curbatch->fog) { - GL_DeselectVAO(); GL_DeSelectProgram(); GenerateFogTexture(&shaderstate.fogtexture, shaderstate.curbatch->fog->shader->fog_dist, 2048); @@ -3578,7 +3651,7 @@ static void DrawMeshes(void) BE_SendPassBlendDepthMask(SBITS_SRCBLEND_SRC_ALPHA | SBITS_DSTBLEND_ONE_MINUS_SRC_ALPHA | SBITS_MISC_DEPTHEQUALONLY); GenerateTCFog(0, shaderstate.curbatch->fog); - BE_EnableShaderAttributes((1u<name)); if (shaderstate.curentity != &r_worldentity) { - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); } shaderstate.curtexnums = texnums; @@ -3640,7 +3713,7 @@ void GLBE_DrawMesh_List(shader_t *shader, int nummeshes, mesh_t **meshlist, vbo_ shaderstate.flags = beflags; if (shaderstate.curentity != &r_worldentity) { - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); } shaderstate.curtexnums = texnums; @@ -3697,7 +3770,7 @@ void GLBE_SubmitBatch(batch_t *batch) shaderstate.flags = batch->flags; if (shaderstate.curentity != batch->ent) { - BE_SelectEntity(batch->ent); + GLBE_SelectEntity(batch->ent); } if (batch->skin) shaderstate.curtexnums = batch->skin; @@ -3829,6 +3902,7 @@ static void GLBE_SubmitMeshesSortList(batch_t *sortlist) if (batch->shader->flags & SHADER_HASREFLECT) { + vrect_t orect = r_refdef.vrect; if (!shaderstate.tex_reflection.num) { shaderstate.tex_reflection = GL_AllocNewTexture("***tex_reflection***", vid.pixelwidth/2, vid.pixelheight/2, 0); @@ -3842,17 +3916,23 @@ static void GLBE_SubmitMeshesSortList(batch_t *sortlist) GL_ForceDepthWritable(); GLBE_RenderToTexture(r_nulltex, r_nulltex, shaderstate.tex_reflection, true); qglViewport (0, 0, vid.pixelwidth/2, vid.pixelheight/2); + r_refdef.vrect.x = 0; + r_refdef.vrect.y = 0; + r_refdef.vrect.width = vid.pixelwidth/2; + r_refdef.vrect.height = vid.pixelheight/2; GL_ForceDepthWritable(); qglClearColor(0, 0, 0, 0); qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLR_DrawPortal(batch, cl.worldmodel->batches, 1); GLBE_RenderToTexture(r_nulltex, r_nulltex, r_nulltex, false); qglViewport (0, 0, vid.pixelwidth, vid.pixelheight); + r_refdef.vrect = orect; } if (batch->shader->flags & SHADER_HASREFRACT) { if (r_refract_fboival) { + vrect_t orect; if (!shaderstate.tex_refraction.num) { shaderstate.tex_refraction = GL_AllocNewTexture("***tex_refraction***", vid.pixelwidth/2, vid.pixelheight/2, 0); @@ -3865,7 +3945,14 @@ static void GLBE_SubmitMeshesSortList(batch_t *sortlist) } GL_ForceDepthWritable(); GLBE_RenderToTexture(r_nulltex, r_nulltex, shaderstate.tex_refraction, true); + qglViewport (0, 0, vid.pixelwidth/2, vid.pixelheight/2); + orect = r_refdef.vrect; + r_refdef.vrect.x = 0; + r_refdef.vrect.y = 0; + r_refdef.vrect.width = vid.pixelwidth/2; + r_refdef.vrect.height = vid.pixelheight/2; + GL_ForceDepthWritable(); qglClearColor(0, 0, 0, 0); qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -3873,12 +3960,14 @@ static void GLBE_SubmitMeshesSortList(batch_t *sortlist) GLBE_RenderToTexture(r_nulltex, r_nulltex, r_nulltex, false); qglViewport (0, 0, vid.pixelwidth, vid.pixelheight); + r_refdef.vrect = orect; } else GLR_DrawPortal(batch, cl.worldmodel->batches, 2); } if (batch->shader->flags & SHADER_HASRIPPLEMAP) { + vrect_t orect; if (!shaderstate.tex_ripplemap.num) { shaderstate.tex_ripplemap = GL_AllocNewTexture("***tex_ripplemap***", vid.pixelwidth/2, vid.pixelheight/2, 0); @@ -3891,6 +3980,12 @@ static void GLBE_SubmitMeshesSortList(batch_t *sortlist) } GLBE_RenderToTexture(r_nulltex, r_nulltex, shaderstate.tex_ripplemap, false); qglViewport (0, 0, vid.pixelwidth/2, vid.pixelheight/2); + orect = r_refdef.vrect; + r_refdef.vrect.x = 0; + r_refdef.vrect.y = 0; + r_refdef.vrect.width = vid.pixelwidth/2; + r_refdef.vrect.height = vid.pixelheight/2; + qglClearColor(0, 0, 0, 0); qglClear(GL_COLOR_BUFFER_BIT); @@ -3902,6 +3997,7 @@ static void GLBE_SubmitMeshesSortList(batch_t *sortlist) GLBE_RenderToTexture(r_nulltex, r_nulltex, r_nulltex, false); qglViewport (0, 0, vid.pixelwidth, vid.pixelheight); + r_refdef.vrect = orect; } BE_SelectMode(oldbem); } @@ -4003,7 +4099,7 @@ void GLBE_BaseEntTextures(void) shaderstate.mbatches = batches; BE_GenModelBatches(batches); GLBE_SubmitMeshes(false, SHADER_SORT_PORTAL, SHADER_SORT_DECAL); - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); shaderstate.mbatches = ob; } #endif @@ -4157,7 +4253,7 @@ void GLBE_DrawLightPrePass(qbyte *vis) qglClearColor (0,0,0,0); qglClear(GL_COLOR_BUFFER_BIT); - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); /*now draw the prelights*/ GLBE_SubmitMeshes(true, SHADER_SORT_PRELIGHT, SHADER_SORT_PRELIGHT); @@ -4167,12 +4263,12 @@ void GLBE_DrawLightPrePass(qbyte *vis) qglDrawBuffer(GL_BACK); /*now draw the postlight passes (this includes blended stuff which will NOT be lit)*/ - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); GLBE_SubmitMeshes(true, SHADER_SORT_SKY, SHADER_SORT_NEAREST); #ifdef RTLIGHTS /*regular lighting now*/ - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); Sh_DrawLights(vis); #endif @@ -4190,12 +4286,11 @@ void GLBE_DrawWorld (qboolean drawworld, qbyte *vis) RSpeedLocals(); shaderstate.mbatches = batches; - GL_DoSwap(); - TRACE(("GLBE_DrawWorld: %i %p\n", drawworld, vis)); if (!r_refdef.recurse) { + GL_DoSwap(); if (shaderstate.wbatch + 50 > shaderstate.maxwbatches) { int newm = shaderstate.wbatch + 100; @@ -4247,7 +4342,7 @@ void GLBE_DrawWorld (qboolean drawworld, qbyte *vis) else shaderstate.updatetime = cl.servertime; - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); BE_UpdateLightmaps(); if (drawworld) @@ -4259,7 +4354,7 @@ void GLBE_DrawWorld (qboolean drawworld, qbyte *vis) if (gl_overbright.ival > 2) gl_overbright.ival = 2; - for (i = 0; i < SHADER_PASS_MAX; i++) + for (i = 0; i < SHADER_TMU_MAX; i++) shaderstate.blendmode[i] = -1; } @@ -4294,7 +4389,7 @@ void GLBE_DrawWorld (qboolean drawworld, qbyte *vis) { RSpeedRemark(); TRACE(("GLBE_DrawWorld: drawing lights\n")); - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); Sh_DrawLights(vis); RSpeedEnd(RSPEED_STENCILSHADOWS); TRACE(("GLBE_DrawWorld: lights drawn\n")); @@ -4340,7 +4435,7 @@ void GLBE_DrawWorld (qboolean drawworld, qbyte *vis) #endif } - BE_SelectEntity(&r_worldentity); + GLBE_SelectEntity(&r_worldentity); shaderstate.curtime = shaderstate.updatetime = realtime; shaderstate.identitylighting = 1; diff --git a/engine/gl/gl_bloom.c b/engine/gl/gl_bloom.c index 9cbcd8d5..341fd13d 100644 --- a/engine/gl/gl_bloom.c +++ b/engine/gl/gl_bloom.c @@ -186,8 +186,6 @@ void R_BloomBlend (void) if (!r_refdef.pxrect.width || !r_refdef.pxrect.height) return; - GL_Set2D(false); - /*update textures if we need to resize them*/ R_SetupBloomTextures(r_refdef.pxrect.width, r_refdef.pxrect.height); diff --git a/engine/gl/gl_draw.c b/engine/gl/gl_draw.c index bd2af7da..d23f9c5d 100644 --- a/engine/gl/gl_draw.c +++ b/engine/gl/gl_draw.c @@ -380,13 +380,15 @@ void GL_Texturemode2d_Callback (struct cvar_s *var, char *oldvalue) void GLDraw_ImageList_f(void) { int count = 0; + unsigned int mem = 0; gltexture_t *glt; for (glt=gltextures ; glt ; glt=glt->next) { count++; + mem += glt->width * glt->height * 4; Con_Printf("%s (%i*%i, seq=%i)\n", glt->identifier, glt->width, glt->height, glt->com.regsequence); } - Con_Printf("%i images\n", count); + Con_Printf("%i images, %i bytes\n", count, mem); } void GLDraw_FlushOldTextures(void) @@ -493,7 +495,7 @@ TRACE(("dbg: GLDraw_ReInit: Allocating upload buffers\n")); TRACE(("dbg: GLDraw_ReInit: PPL_LoadSpecularFragmentProgram\n")); GL_InitSceneProcessingShaders(); - Cmd_AddCommand ("r_imagelist", GLDraw_ImageList_f); + Cmd_AddCommandD ("r_imagelist", GLDraw_ImageList_f, "Debug command. Reveals current list of loaded images."); } void GLDraw_DeInit (void) @@ -1393,15 +1395,9 @@ void GL_Upload24BGR (char *name, qbyte *framedata, int inwidth, int inheight, un dest = uploadmemorybufferintermediate; //change from bgr bottomup to rgba topdown - for (outwidth = 1; outwidth < inwidth; outwidth*=2) - ; - for (outheight = 1; outheight < inheight; outheight*=2) - ; - - if (outwidth > 512) - outwidth = 512; - if (outheight > 512) - outheight = 512; + outwidth = inwidth; + outheight = inheight; + GL_RoundDimensions(&outwidth, &outheight, !(flags&IF_NOMIPMAP)); if (outwidth*outheight > sizeofuploadmemorybufferintermediate/4) Sys_Error("GL_Upload24BGR: image too big (%i*%i)", inwidth, inheight); @@ -1466,15 +1462,9 @@ void GL_Upload24BGR_Flip (char *name, qbyte *framedata, int inwidth, int inheigh dest = uploadmemorybufferintermediate; //change from bgr bottomup to rgba topdown - for (outwidth = 1; outwidth < inwidth; outwidth*=2) - ; - for (outheight = 1; outheight < inheight; outheight*=2) - ; - - if (outwidth > 512) - outwidth = 512; - if (outheight > 512) - outheight = 512; + outwidth = inwidth; + outheight = inheight; + GL_RoundDimensions(&outwidth, &outheight, !(flags&IF_NOMIPMAP)); if (outwidth*outheight > sizeofuploadmemorybufferintermediate/4) Sys_Error("GL_Upload24BGR_Flip: image too big (%i*%i)", inwidth, inheight); diff --git a/engine/gl/gl_font.c b/engine/gl/gl_font.c index 24d6b2a0..454b9527 100644 --- a/engine/gl/gl_font.c +++ b/engine/gl/gl_font.c @@ -950,7 +950,7 @@ struct font_s *Font_LoadFont(int height, char *fontfilename) for (i = '!'; i <= '_'; i++) { dp = NULL; - FS_LoadFile(va("wad/stcfn%.3d", i), &dp); + FS_LoadFile(va("wad/stcfn%.3d", i), (void**)&dp); if (!dp) break; @@ -1128,6 +1128,12 @@ struct font_s *Font_LoadFont(int height, char *fontfilename) void Font_Free(struct font_s *f) { struct charcache_s **link; + + if (f->alt) + { + Font_Free(f->alt); + f->alt = NULL; + } for (link = &fontplanes.oldestchar; *link; ) { if (*link >= f->chars && *link <= f->chars + FONTCHARS) @@ -1195,8 +1201,13 @@ int Font_CharEndCoord(struct font_s *font, int x, unsigned int charcode) if ((charcode&CON_CHARMASK) == '\t') return x + ((TABWIDTH - (x % TABWIDTH)) % TABWIDTH); - if ((charcode & CON_2NDCHARSETTEXT) && font->alt) - font = font->alt; + if (charcode & CON_2NDCHARSETTEXT) + { + if (font->alt) + font = font->alt; + else if ((charcode & CON_CHARMASK) >= 0x20 && (charcode&CON_CHARMASK) < 0x80) + charcode |= 0xe000; + } c = Font_GetChar(font, (CHARIDXTYPE)(charcode&CON_CHARMASK)); if (!c) @@ -1216,8 +1227,13 @@ int Font_CharWidth(unsigned int charcode) struct font_s *font = curfont; if (charcode&CON_HIDDEN) return 0; - if ((charcode & CON_2NDCHARSETTEXT) && font->alt) - font = font->alt; + if (charcode & CON_2NDCHARSETTEXT) + { + if (font->alt) + font = font->alt; + else if ((charcode & CON_CHARMASK) >= 0x20 && (charcode&CON_CHARMASK) < 0x80) + charcode |= 0xe000; + } c = Font_GetChar(curfont, (CHARIDXTYPE)(charcode&CON_CHARMASK)); if (!c) @@ -1340,8 +1356,13 @@ int Font_DrawChar(int px, int py, unsigned int charcode) if (charcode & CON_HIDDEN) return px; - if ((charcode & CON_2NDCHARSETTEXT) && font->alt) - font = font->alt; + if (charcode & CON_2NDCHARSETTEXT) + { + if (font->alt) + font = font->alt; + else if ((charcode & CON_CHARMASK) >= 0x20 && (charcode&CON_CHARMASK) < 0x80) + charcode |= 0xe000; + } //crash if there is no current font. c = Font_GetChar(font, (CHARIDXTYPE)(charcode&CON_CHARMASK)); @@ -1464,8 +1485,13 @@ float Font_DrawScaleChar(float px, float py, float cw, float ch, unsigned int ch int col; int v; struct font_s *font = curfont; - if ((charcode & CON_2NDCHARSETTEXT) && font->alt) - font = font->alt; + if (charcode & CON_2NDCHARSETTEXT) + { + if (font->alt) + font = font->alt; + else if ((charcode & CON_CHARMASK) >= 0x20 && (charcode&CON_CHARMASK) < 0x80) + charcode |= 0xe000; + } cw /= font->charheight; ch /= font->charheight; diff --git a/engine/gl/gl_heightmap.c b/engine/gl/gl_heightmap.c index 8b61a751..9b794db3 100644 --- a/engine/gl/gl_heightmap.c +++ b/engine/gl/gl_heightmap.c @@ -10,6 +10,17 @@ #define TERRAINTHICKNESS 16 #define TERRAINACTIVESECTIONS 1000 +/* +a note on networking: +By default terrain is NOT networked. This means content is loaded without networking delays. +If you wish to edit the terrain collaboratively, you can enable the mod_terrain_networked cvar. +When set, changes on the server will notify clients that a section has changed, and the client will reload it as needed. +Changes on the client WILL NOT notify the server, and will get clobbered if the change is also made on the server. +This means for editing purposes, you MUST funnel it via ssqc with your own permission checks. +It also means for explosions and local stuff, the server will merely restate changes from impacts if you do them early. BUT DO NOT CALL THE EDIT FUNCTION IF THE SERVER HAS ALREADY APPLIED THE CHANGE. +*/ +cvar_t mod_terrain_networked = CVARD("mod_terrain_networked", "0", "Terrain edits are networked. Clients will download sections on demand, and servers will notify clients of changes."); + //heightmaps work thusly: //there is one raw heightmap file //the file is split to 4*4 sections. @@ -258,6 +269,15 @@ static char *Terr_DiskSectionName(heightmap_t *hm, int sx, int sy) sy &= CHUNKLIMIT-1; return va("maps/%s/sect_%03x_%03x.hms", hm->path, sx, sy); } +static char *Terr_TempDiskSectionName(heightmap_t *hm, int sx, int sy) +{ + sx -= CHUNKBIAS; + sy -= CHUNKBIAS; + //wrap cleanly + sx &= CHUNKLIMIT-1; + sy &= CHUNKLIMIT-1; + return va("temp/%s/sect_%03x_%03x.hms", hm->path, sx, sy); +} static hmsection_t *Terr_LoadSection(heightmap_t *hm, hmsection_t *s, int sx, int sy) { dsection_t *ds = NULL; @@ -269,6 +289,14 @@ static hmsection_t *Terr_LoadSection(heightmap_t *hm, hmsection_t *s, int sx, in #endif void *ptr; + if (mod_terrain_networked.ival) + { +#ifndef CLIENTONLY + if (hm != sv.world.worldmodel->terrain) +#endif + return NULL; + } + /*queue the file for download if we don't have it yet*/ if (FS_LoadFile(Terr_DiskSectionName(hm, sx, sy), (void**)&ds) < 0 #ifndef CLIENTONLY @@ -544,12 +572,12 @@ static hmsection_t *Terr_LoadSection(heightmap_t *hm, hmsection_t *s, int sx, in return s; } -static qboolean Terr_SaveSection(heightmap_t *hm, hmsection_t *s, int sx, int sy) +//doesn't clear edited/dirty flags or anything +static qboolean Terr_SaveSection(heightmap_t *hm, hmsection_t *s, int sx, int sy, char *fname) { #ifndef SERVERONLY dsection_t ds; dsmesh_t dm; - char *fname; unsigned char *lm; vfsfile_t *f; int nothing = 0; @@ -608,7 +636,6 @@ static qboolean Terr_SaveSection(heightmap_t *hm, hmsection_t *s, int sx, int sy ds.maxh = s->maxh; ds.ents_num = s->numents; - fname = Terr_DiskSectionName(hm, sx, sy); FS_CreatePath(fname, FS_GAMEONLY); f = FS_OpenVFS(fname, "wb", FS_GAMEONLY); @@ -683,7 +710,7 @@ static hmsection_t *Terr_GetSection(heightmap_t *hm, int x, int y, qboolean dolo } /*save all currently loaded sections*/ -int HeightMap_Save(heightmap_t *hm) +int Heightmap_Save(heightmap_t *hm) { hmsection_t *s; int x, y; @@ -697,7 +724,7 @@ int HeightMap_Save(heightmap_t *hm) continue; if (s->flags & TSF_EDITED) { - if (Terr_SaveSection(hm, s, x, y)) + if (Terr_SaveSection(hm, s, x, y, Terr_DiskSectionName(hm, x, y))) { s->flags &= ~TSF_EDITED; sectionssaved++; @@ -709,6 +736,68 @@ int HeightMap_Save(heightmap_t *hm) return sectionssaved; } +#ifndef CLIENTONLY +static int dehex(int i) +{ + if (i >= '0' && i <= '9') + return (i-'0'); + else if (i >= 'A' && i <= 'F') + return (i-'A'+10); + else + return (i-'a'+10); +} + +//on servers, we can get requests to download current map sections. if so, give them it. +qboolean Terrain_LocateSection(char *name, flocation_t *loc) +{ + heightmap_t *hm; + hmsection_t *s; + int x, y; + int nlen = strlen(name); + + //reject if its not in maps + if (strncmp(name, "maps/", 5)) + return false; + //or too short + if (nlen < 17+5) + return false; + //reject if its not a section... + if (strncmp(name+nlen - 17, "/sect_", 6) || strcmp(name+nlen - 4, ".hms")) + return false; + + //FIXME: find the right map instead + hm = sv.world.worldmodel->terrain; + + if (!hm) //its not terrain. + return false; + + x = dehex(name[nlen-17+ 6])<<8; + x|= dehex(name[nlen-17+ 7])<<4; + x|= dehex(name[nlen-17+ 8])<<0; + + y = dehex(name[nlen-17+10])<<8; + y|= dehex(name[nlen-17+11])<<4; + y|= dehex(name[nlen-17+12])<<0; + + x += CHUNKBIAS; + y += CHUNKBIAS; + + //verify that its valid + if (strcmp(name, Terr_DiskSectionName(hm, x, y))) + return false; + + s = Terr_GetSection(hm, x, y, false); + if (!s || !(s->flags & TSF_EDITED)) + return false; //its not been edited, might as well just use the regular file + + name = Terr_TempDiskSectionName(hm, x, y); + if (!Terr_SaveSection(hm, s, x, y, name)) + return false; + + return FS_FLocateFile(name, FSLFRT_IFFOUND, loc); +} +#endif + void Terr_DestroySection(heightmap_t *hm, hmsection_t *s, qboolean lightmapreusable) { RemoveLink(&s->recycle); @@ -729,7 +818,7 @@ void Terr_DestroySection(heightmap_t *hm, hmsection_t *s, qboolean lightmapreusa hm->relight = NULL; #ifdef GLQUAKE - if (qrenderer == QR_OPENGL) + if (qrenderer == QR_OPENGL && qglDeleteBuffersARB) { qglDeleteBuffersARB(1, &s->vbo.coord.gl.vbo); qglDeleteBuffersARB(1, &s->vbo.indicies.gl.vbo); @@ -2491,35 +2580,6 @@ static void ted_itterate(heightmap_t *hm, int distribution, float *pos, float ra } } -//Heightmap_NativeBoxContents -enum -{ - ter_reload, // - ter_save, // - ter_sethole, //vector pos, float radius, floatbool hole - ter_height_set, //vector pos, float radius, float newheight - ter_height_smooth, //vector pos, float radius, float percent - ter_height_spread, //vector pos, float radius, float percent - ter_raise, //vector pos, float radius, float heightchange - ter_lower, //vector pos, float radius, float heightchange - ter_tex_kill, //vector pos, void junk, void junk, string texname - ter_tex_get, //vector pos, void junk, float imagenum - ter_mixpaint, //vector pos, float radius, float percent, string texname - ter_mixconcentrate, //vector pos, float radius, float percent - ter_mixnoise, //vector pos, float radius, float percent - ter_mixblur, //vector pos, float radius, float percent - ter_water_set, //vector pos, float radius, float newwaterheight - ter_mesh_add, //entity ent - ter_mesh_kill, //vector pos, float radius - ter_tint, //vector pos, float radius, float percent, vector newcol, float newalph - ter_height_flatten, //vector pos, float radius, float percent -// ter_poly_add, //add a poly, woo -// ter_poly_remove, //remove polys - -// ter_autopaint_h, //vector pos, float radius, float percent, string tex1, string tex2 (paint tex1/tex2 -// ter_autopaint_n //vector pos, float radius, float percent, string tex1, string tex2 -}; - void QCBUILTIN PF_terrain_edit(progfuncs_t *prinst, struct globalvars_s *pr_globals) { world_t *vmw = prinst->parms->user; @@ -2548,7 +2608,7 @@ void QCBUILTIN PF_terrain_edit(progfuncs_t *prinst, struct globalvars_s *pr_glob Terr_PurgeTerrainModel(mod, false, true); break; case ter_save: - Con_Printf("%i sections saved\n", HeightMap_Save(hm)); + Con_Printf("%i sections saved\n", Heightmap_Save(hm)); break; case ter_sethole: /* { @@ -2623,16 +2683,16 @@ void QCBUILTIN PF_terrain_edit(progfuncs_t *prinst, struct globalvars_s *pr_glob // case ter_mixset: // ted_itterate(hm, tid_exponential, pos, radius, 1, SECTTEXSIZE, ted_mixset, G_VECTOR(OFS_PARM4)); // break; - case ter_mixpaint: + case ter_mix_paint: ted_itterate(hm, tid_exponential, pos, radius, quant/10, SECTTEXSIZE, ted_mixpaint, PR_GetStringOfs(prinst, OFS_PARM4)); break; - case ter_mixconcentrate: + case ter_mix_concentrate: ted_itterate(hm, tid_exponential, pos, radius, 1, SECTTEXSIZE, ted_mixconcentrate, NULL); break; - case ter_mixnoise: + case ter_mix_noise: ted_itterate(hm, tid_exponential, pos, radius, 1, SECTTEXSIZE, ted_mixnoise, NULL); break; - case ter_mixblur: + case ter_mix_blur: Vector4Set(tally, 0, 0, 0, 0); ted_itterate(hm, tid_exponential, pos, radius, 1, SECTTEXSIZE, ted_mixtally, &tally); VectorScale(tally, 1/(tally[3]*255), tally); @@ -3007,4 +3067,9 @@ void *Mod_LoadTerrainInfo(model_t *mod, char *loadname) return hm; } + +void Terr_Init(void) +{ + Cvar_Register(&mod_terrain_networked, "Terrain"); +} #endif diff --git a/engine/gl/gl_hlmdl.c b/engine/gl/gl_hlmdl.c index 2388a7b0..81054be9 100644 --- a/engine/gl/gl_hlmdl.c +++ b/engine/gl/gl_hlmdl.c @@ -556,176 +556,6 @@ void HL_SetupBones(hlmodel_t *model, int seqnum, int firstbone, int lastbone, fl } } - -#if 0 -/* - ======================================================================================================================= - R_Draw_HL_AliasModel - main drawing function - ======================================================================================================================= - */ -void R_DrawHLModel(entity_t *curent) -{ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - hlmodelcache_t *modelc = Mod_Extradata(curent->model); - hlmodel_t model; - int b, m, v; - short *skins; - int bgroup, cbone, lastbone; - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - //general model - model.header = (hlmdl_header_t *) ((char *)modelc + modelc->header); - model.texheader = (hlmdl_header_t *) ((char *)modelc + modelc->texheader); - model.textures = (hlmdl_tex_t *) ((char *)modelc + modelc->textures); - model.bones = (hlmdl_bone_t *) ((char *)modelc + modelc->bones); - model.bonectls = (hlmdl_bonecontroller_t *) ((char *)modelc + modelc->bonectls); - model.shaders = (shader_t **) ((char *)modelc + modelc->shaders); - - skins = (short *) ((qbyte *) model.texheader + model.texheader->skins); - - if (!model.texheader->numtextures) - { - Con_DPrintf("model with no textures: %s\n", curent->model->name); - return; - } - - for (b = 0; b < MAX_BONE_CONTROLLERS; b++) - model.controller[b] = curent->framestate.bonecontrols[b]; - -// Con_Printf("%s %i\n", sequence->name, sequence->unknown1[0]); - - - - cbone = 0; - for (bgroup = 0; bgroup < FS_COUNT; bgroup++) - { - lastbone = curent->framestate.g[bgroup].endbone; - if (bgroup == FS_COUNT-1) - lastbone = model.header->numbones; - if (cbone >= lastbone) - continue; - HL_SetupBones(&model, curent->framestate.g[bgroup].frame[0], cbone, lastbone, (curent->framestate.g[bgroup].subblendfrac+1)*0.5, curent->framestate.g[bgroup].frametime[0]); /* Setup the bones */ - cbone = lastbone; - } - - /* Manipulate each mesh directly */ - for(b = 0; b < model.header->numbodyparts; b++) - { - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - hlmdl_bodypart_t *bodypart = (hlmdl_bodypart_t *) ((qbyte *) model.header + model.header->bodypartindex) + - b; - int bodyindex = (0 / bodypart->base) % bodypart->nummodels; - hlmdl_model_t *amodel = (hlmdl_model_t *) ((qbyte *) model.header + bodypart->modelindex) + bodyindex; - qbyte *bone = ((qbyte *) model.header + amodel->vertinfoindex); - vec3_t *verts = (vec3_t *) ((qbyte *) model.header + amodel->vertindex); - vec3_t transformed[2048]; - -// vec3_t *norms = (vec3_t *) ((qbyte *) model.header + amodel->unknown3[2]); -// vec3_t transformednorms[2048]; - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - - for(v = 0; v < amodel->numverts; v++) // Transform per the matrix - { - VectorTransform(verts[v], (void *)transform_matrix[bone[v]], transformed[v]); -// glVertex3fv(verts[v]); -// glVertex3f( verts[v][0]+10*verts[v][0], -// verts[v][1]+10*verts[v][1], -// verts[v][2]+10*verts[v][2]); - } - - //Need to work out what we have! - //raw data appears to be unit vectors - //transformed gives some points on the skeleton. - //what's also weird is that the meshes use these up! -/* glDisable(GL_TEXTURE_2D); - glBegin(GL_LINES); - for(v = 0; v < amodel->unknown3[0]; v++) // Transform per the matrix - { - VectorTransform(norms[v], transform_matrix[bone[v]], transformednorms[v]); - glVertex3fv(transformednorms[v]); - glVertex3f( transformednorms[v][0]+10*transformednorms[v][0], - transformednorms[v][1]+10*transformednorms[v][1], - transformednorms[v][2]+10*transformednorms[v][2]); - } - glEnd(); - glEnable(GL_TEXTURE_2D); -*/ - - - /* Draw each mesh */ - for(m = 0; m < amodel->nummesh; m++) - { - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - hlmdl_mesh_t *mesh = (hlmdl_mesh_t *) ((qbyte *) model.header + amodel->meshindex) + m; - float tex_w; - float tex_h; - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - { - tex_w = 1.0f / model.textures[skins[mesh->skinindex]].w; - tex_h = 1.0f / model.textures[skins[mesh->skinindex]].h; -// GL_LazyBind(0, GL_TEXTURE_2D, model.shaders[skins[mesh->skinindex]]->defaulttextures.base); - } - - GL_Draw_HL_AliasFrame((short *) ((qbyte *) model.header + mesh->index), transformed, tex_w, tex_h); - } - } -} - -/* - ======================================================================================================================= - GL_Draw_HL_AliasFrame - clip and draw all triangles - ======================================================================================================================= - */ -void GL_Draw_HL_AliasFrame(short *order, vec3_t *transformed, float tex_w, float tex_h) -{ - /*~~~~~~~~~~*/ - int count = 0; - /*~~~~~~~~~~*/ - -// int c_tris=0; -// int c_verts=0; -// int c_chains=0; - - for(;;) - { - count = *order++; /* get the vertex count and primitive type */ - if(!count) break; /* done */ - - if(count < 0) - { - count = -count; - qglBegin(GL_TRIANGLE_FAN); - } - else - { - qglBegin(GL_TRIANGLE_STRIP); - } -// c_tris += count-2; -// c_chains++; - - do - { - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - float *verts = transformed[order[0]]; - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - //FIXME: what's order[1]? - - /* texture coordinates come from the draw list */ - qglTexCoord2f(order[2] * tex_w, order[3] * tex_h); - order += 4; - - qglVertex3fv(verts); -// c_verts++; - } while(--count); - - qglEnd(); - } -} -#endif - void R_HL_BuildFrame(hlmodel_t *model, hlmdl_model_t *amodel, entity_t *curent, short *order, float tex_s, float tex_t, mesh_t *mesh) { static vecV_t xyz[2048]; diff --git a/engine/gl/gl_model.c b/engine/gl/gl_model.c index 49a4c907..40d3778d 100644 --- a/engine/gl/gl_model.c +++ b/engine/gl/gl_model.c @@ -314,7 +314,7 @@ void RMod_Think (void) { COM_StripExtension(lightmodel->name, filename, sizeof(filename)); COM_DefaultExtension(filename, ".lux", sizeof(filename)); - f = FS_OpenVFS(filename, "wb", FS_GAMEONLY); + f = FS_OpenVFS(filename, "wb", FS_GAME); if (f) { VFS_WRITE(f, "QLIT\1\0\0\0", 8); @@ -329,7 +329,8 @@ void RMod_Think (void) { COM_StripExtension(lightmodel->name, filename, sizeof(filename)); COM_DefaultExtension(filename, ".lit", sizeof(filename)); - f = FS_OpenVFS(filename, "wb", FS_GAMEONLY); + + f = FS_OpenVFS(filename, "wb", FS_GAME); if (f) { VFS_WRITE(f, "QLIT\1\0\0\0", 8); @@ -429,6 +430,10 @@ void RMod_Init (void) Cmd_AddCommand("mod_batchlist", RMod_BatchList_f); Cmd_AddCommand("mod_texturelist", RMod_TextureList_f); Cmd_AddCommand("mod_usetexture", RMod_BlockTextureColour_f); + +#ifdef TERRAIN + Terr_Init(); +#endif } void RMod_Shutdown (void) @@ -734,6 +739,7 @@ model_t *RMod_LoadModel (model_t *mod, qboolean crash) TRACE(("RMod_LoadModel: md3\n")); if (!Mod_LoadQ3Model (mod, buf)) continue; + Surf_BuildModelLightmaps(mod); break; #endif @@ -801,6 +807,7 @@ model_t *RMod_LoadModel (model_t *mod, qboolean crash) TRACE(("RMod_LoadModel: q2/q3/raven/fusion bsp\n")); if (!Mod_LoadQ2BrushModel (mod, buf)) continue; + Surf_BuildModelLightmaps(mod); break; #endif #ifdef MAP_DOOM @@ -820,6 +827,7 @@ model_t *RMod_LoadModel (model_t *mod, qboolean crash) TRACE(("RMod_LoadModel: hl/q1 bsp\n")); if (!RMod_LoadBrushModel (mod, buf)) continue; + Surf_BuildModelLightmaps(mod); break; //Text based misc types. @@ -861,7 +869,7 @@ model_t *RMod_LoadModel (model_t *mod, qboolean crash) } #endif - Con_Printf(CON_WARNING "Unrecognised model format %i\n", LittleLong(*(unsigned *)buf)); + Con_Printf(CON_WARNING "Unrecognised model format 0x%x (%c%c%c%c)\n", LittleLong(*(unsigned *)buf), ((char*)buf)[0], ((char*)buf)[1], ((char*)buf)[2], ((char*)buf)[3]); continue; } @@ -1236,7 +1244,7 @@ void RMod_LoadMiptex(texture_t *tx, miptex_t *mt, texnums_t *tn, int maps) snprintf(altname, sizeof(altname)-1, "%s_bump", mt->name); } - if (!TEXVALID(tn->bump) && loadmodel->fromgame != fg_halflife)// && gl_bump_fallbacks.ival) + if (!TEXVALID(tn->bump) && loadmodel->fromgame != fg_halflife && r_loadbumpmapping)// && gl_bump_fallbacks.ival) { //no mip levels here, would be absurd. base = (qbyte *)(mt+1); //convert to greyscale. @@ -1794,9 +1802,9 @@ void RMod_LoadLighting (lump_t *l) luxdata = Hunk_AllocName(samples*3, "lux data"); for (i = 0; i < samples; i++) { - litdata[i*3+0] = 0.5f*255; - litdata[i*3+0] = 0.5f*255; - litdata[i*3+0] = 255; + luxdata[i*3+0] = 0.5f*255; + luxdata[i*3+1] = 0.5f*255; + luxdata[i*3+2] = 255; } } #endif diff --git a/engine/gl/gl_model.h b/engine/gl/gl_model.h index 5ac8b226..079c8a1e 100644 --- a/engine/gl/gl_model.h +++ b/engine/gl/gl_model.h @@ -305,6 +305,7 @@ typedef struct vbo_s } vbo_t; void GL_SelectVBO(int vbo); void GL_SelectEBO(int vbo); +void GL_DeselectVAO(void); typedef struct texture_s { @@ -1019,10 +1020,12 @@ qbyte *Mod_LeafPVS (mleaf_t *leaf, model_t *model); // gl_heightmap.c // #ifdef TERRAIN +void Terr_Init(void); void Terr_DrawTerrainModel (batch_t **batch, entity_t *e); qboolean Terr_LoadTerrainModel (model_t *mod, void *buffer); void Terr_PurgeTerrainModel(model_t *mod, qboolean lightmapsonly, qboolean lightmapreusable); void *Mod_LoadTerrainInfo(model_t *mod, char *loadname); //call this after loading a bsp +qboolean Terrain_LocateSection(char *name, flocation_t *loc); //used on servers to generate sections for download. qboolean Heightmap_Trace(model_t *model, int forcehullnum, int frame, vec3_t axis[3], vec3_t start, vec3_t end, vec3_t mins, vec3_t maxs, unsigned int contentmask, struct trace_s *trace); unsigned int Heightmap_PointContents(model_t *model, vec3_t axis[3], vec3_t org); struct fragmentdecal_s; diff --git a/engine/gl/gl_rmain.c b/engine/gl/gl_rmain.c index 119dfc98..72d05933 100644 --- a/engine/gl/gl_rmain.c +++ b/engine/gl/gl_rmain.c @@ -102,6 +102,7 @@ texid_t scenepp_texture_warp; texid_t scenepp_texture_edge; texid_t scenepp_postproc_cube; +int scenepp_postproc_cube_size; // KrimZon - init post processing - called in GL_CheckExtensions, when they're called // I put it here so that only this file need be changed when messing with the post @@ -581,7 +582,10 @@ void R_RenderScene (void) TRACE(("dbg: calling R_RenderDlights\n")); R_RenderDlights (); - RQ_RenderBatchClear(); + if (r_refdef.recurse) + RQ_RenderBatch(); + else + RQ_RenderBatchClear(); cl_numvisedicts = tmpvisents; } @@ -677,6 +681,7 @@ static entity_t *R_NearestPortal(plane_t *plane) int i; entity_t *best = NULL; float dist, bestd = 0; + //for q3-compat, portals on world scan for a visedict to use for their view. for (i = 0; i < cl_numvisedicts; i++) { if (cl_visedicts[i].rtype == RT_PORTALSURFACE) @@ -826,6 +831,15 @@ void GLR_DrawPortal(batch_t *batch, batch_t **blist, int portaltype) // memset(newvis, 0xff, pvsbytes); } } + else if (batch->ent != &r_worldentity) + { + float d; + view = batch->ent; + d = DotProduct(r_refdef.vieworg, plane.normal) - plane.dist; + d-= 0.1; //nudge it past. + VectorAdd(r_refdef.vieworg, view->oldorigin, r_refdef.vieworg); //trivial offset for the warpzone. + VectorMA(r_refdef.vieworg, -d, plane.normal, r_refdef.pvsorigin); //clip the pvs origin to the plane. + } else if (!(view = R_NearestPortal(&plane)) || VectorCompare(view->origin, view->oldorigin)) { r_refdef.flipcull ^= true; @@ -1011,14 +1025,15 @@ void GLR_SetupFog (void) } #endif +void GLBE_RenderToTexture(texid_t sourcecol, texid_t sourcedepth, texid_t destcol, qboolean usedepth); static void R_RenderMotionBlur(void) { int vwidth = 1, vheight = 1; float vs, vt, cs, ct; -#ifdef warningmsg -#pragma warningmsg("backend fixme") -#endif + shader_t *shader; + #if !defined(ANDROID) && !defined(NACL) + //figure out the size of our texture. if (gl_config.arb_texture_non_power_of_two) { //we can use any size, supposedly vwidth = vid.pixelwidth; @@ -1032,21 +1047,6 @@ static void R_RenderMotionBlur(void) vheight *= 2; } - qglViewport (0, 0, vid.pixelwidth, vid.pixelheight); - - PPL_RevertToKnownState(); - - GL_LazyBind(0, GL_TEXTURE_2D, sceneblur_texture); - - // go 2d - qglMatrixMode(GL_PROJECTION); - qglPushMatrix(); - qglLoadIdentity (); - qglOrtho (0, vid.pixelwidth, 0, vid.pixelheight, -99999, 99999); - qglMatrixMode(GL_MODELVIEW); - qglPushMatrix(); - qglLoadIdentity (); - //blend the last frame onto the scene //the maths is because our texture is over-sized (must be power of two) cs = vs = (float)vid.pixelwidth / vwidth * 0.5; @@ -1054,34 +1054,28 @@ static void R_RenderMotionBlur(void) vs *= gl_motionblurscale.value; vt *= gl_motionblurscale.value; - qglDisable (GL_DEPTH_TEST); - GL_CullFace(0); - qglDisable (GL_ALPHA_TEST); - qglEnable(GL_BLEND); - qglColor4f(1, 1, 1, gl_motionblur.value); - qglBegin(GL_QUADS); - qglTexCoord2f(cs-vs, ct-vt); - qglVertex2f(0, 0); - qglTexCoord2f(cs+vs, ct-vt); - qglVertex2f(vid.pixelwidth, 0); - qglTexCoord2f(cs+vs, ct+vt); - qglVertex2f(vid.pixelwidth, vid.pixelheight); - qglTexCoord2f(cs-vs, ct+vt); - qglVertex2f(0, vid.pixelheight); - qglEnd(); - - qglMatrixMode(GL_PROJECTION); - qglPopMatrix(); - qglMatrixMode(GL_MODELVIEW); - qglPopMatrix(); - + //render using our texture + shader = R_RegisterShader("postproc_motionblur", + "{\n" + "program default2d\n" + "{\n" + "map $sourcecolour\n" + "blendfunc blend\n" + "}\n" + "}\n" + ); + GLBE_RenderToTexture(sceneblur_texture, r_nulltex, r_nulltex, false); + R2D_ImageColours(1, 1, 1, gl_motionblur.value); + R2D_Image(0, 0, vid.width, vid.height, cs-vs, ct+vt, cs+vs, ct-vt, shader); + GLBE_RenderToTexture(r_nulltex, r_nulltex, r_nulltex, false); + //grab the current image so we can feed that back into the next frame. + GL_MTBind(0, GL_TEXTURE_2D, sceneblur_texture); //copy the image into the texture so that we can play with it next frame too! qglCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, vwidth, vheight, 0); qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); qglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #endif - PPL_RevertToKnownState(); } /*FIXME: we could use geometry shaders to draw to all 6 faces at once*/ @@ -1174,8 +1168,10 @@ qboolean R_RenderScene_Cubemap(void) VectorCopy(r_refdef.viewangles, saveang); saveang[2] = 0; - if (!TEXVALID(scenepp_postproc_cube)) + if (!TEXVALID(scenepp_postproc_cube) || cmapsize != scenepp_postproc_cube_size) { + if (TEXVALID(scenepp_postproc_cube)) + GL_DestroyTexture(scenepp_postproc_cube); scenepp_postproc_cube = GL_AllocNewTexture("***fish***", cmapsize, cmapsize, 0); GL_MTBind(0, GL_TEXTURE_CUBE_MAP_ARB, scenepp_postproc_cube); @@ -1185,10 +1181,14 @@ qboolean R_RenderScene_Cubemap(void) qglTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); qglTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); qglTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + + scenepp_postproc_cube_size = cmapsize; } - r_refdef.vrect.width = cmapsize; - r_refdef.vrect.height = cmapsize; + vrect = r_refdef.vrect; //save off the old vrect + + r_refdef.vrect.width = (cmapsize * vid.width) / vid.pixelwidth; + r_refdef.vrect.height = (cmapsize * vid.height) / vid.pixelheight; r_refdef.vrect.x = 0; r_refdef.vrect.y = prect.y; @@ -1223,6 +1223,8 @@ qboolean R_RenderScene_Cubemap(void) qglCopyTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + i, 0, 0, 0, 0, vid.pixelheight - (prect.y + cmapsize), cmapsize, cmapsize); } + r_refdef.vrect = vrect; + qglViewport (prect.x, vid.pixelheight - (prect.y+prect.height), prect.width, prect.height); // go 2d @@ -1339,6 +1341,8 @@ void GLR_RenderView (void) if (r_refdef.flags & Q2RDF_NOWORLDMODEL) return; + GL_Set2D (false); + if (r_bloom.value) R_BloomBlend(); @@ -1348,7 +1352,6 @@ void GLR_RenderView (void) { if (scenepp_waterwarp) { - GL_Set2D(false); R2D_ScalePic(0, 0, vid.width, vid.height, scenepp_waterwarp); } } @@ -1363,7 +1366,6 @@ void GLR_RenderView (void) shader_t *postproc = R_RegisterCustom(r_postprocshader.string, NULL, NULL); if (postproc) { - GL_Set2D(false); R2D_ScalePic(0, 0, vid.width, vid.height, postproc); } } diff --git a/engine/gl/gl_screen.c b/engine/gl/gl_screen.c index 69fbe539..5e010327 100644 --- a/engine/gl/gl_screen.c +++ b/engine/gl/gl_screen.c @@ -178,12 +178,6 @@ void GLSCR_UpdateScreen (void) GL_Set2D (false); - if (!noworld) - { - R2D_PolyBlend (); - R2D_BrightenScreen(); - } - scr_con_forcedraw = false; if (noworld) { @@ -208,6 +202,8 @@ void GLSCR_UpdateScreen (void) SCR_DrawCursor(0); V_UpdatePalette (false); + R2D_BrightenScreen(); + #if defined(_WIN32) && defined(GLQUAKE) Media_RecordFrame(); #endif diff --git a/engine/gl/gl_shader.c b/engine/gl/gl_shader.c index b97a1b41..f1a2a887 100644 --- a/engine/gl/gl_shader.c +++ b/engine/gl/gl_shader.c @@ -936,8 +936,6 @@ static qboolean Shader_LoadPermutations(char *name, program_t *prog, char *scrip break; }; - memset(prog->handle, 0, sizeof(*prog->handle)*PERMUTATIONS); - nummodifiers = 0; for (end = strchr(name, '#'); end && *end; ) { @@ -965,6 +963,7 @@ static qboolean Shader_LoadPermutations(char *name, program_t *prog, char *scrip for (p = 0; p < PERMUTATIONS; p++) { + memset(&prog->permu[p].handle, 0, sizeof(prog->permu[p].handle)); if (nopermutation & p) { continue; @@ -992,19 +991,19 @@ static qboolean Shader_LoadPermutations(char *name, program_t *prog, char *scrip #ifdef GLQUAKE else if (qrenderer == QR_OPENGL) { - if (prog->handle[p].glsl) - qglDeleteProgramObject_(prog->handle[p].glsl); - prog->handle[p].glsl = GLSlang_CreateProgram(name, (((p & PERMUTATION_SKELETAL) && ver < 120)?120:ver), permutationdefines, script, script, onefailed); - if (!prog->handle[p].glsl) + if (prog->permu[p].handle.glsl) + qglDeleteProgramObject_(prog->permu[p].handle.glsl); + prog->permu[p].handle.glsl = GLSlang_CreateProgram(name, (((p & PERMUTATION_SKELETAL) && ver < 120)?120:ver), permutationdefines, script, script, onefailed); + if (!prog->permu[p].handle.glsl) onefailed = true; - if (!p && !prog->handle[p].glsl) + if (!p && !prog->permu[p].handle.glsl) break; } #endif #ifdef D3D9QUAKE else if (qrenderer == QR_DIRECT3D9) { - if (!D3D9Shader_CreateProgram(prog, p, permutationdefines, script, script)) + if (!D3D9Shader_CreateProgram(prog, name, p, permutationdefines, script, script)) break; } #endif @@ -1041,7 +1040,7 @@ struct sbuiltin_s char *body; } sbuiltins[] = { -#ifdef GLQUAKE +#if 0//def GLQUAKE /*a quick note on glsl versions: gl versioning started with 110 gles versioning started at 100 and only had a single one defined @@ -1293,162 +1292,6 @@ struct sbuiltin_s "#endif\n" }, #endif -#ifdef D3D9QUAKE - {QR_DIRECT3D9, 9, "rtlight", - /* - texture units: - s0=diffuse, s1=normal, s2=specular, s3=shadowmap - custom modifiers: - PCF(shadowmap) - CUBE(projected cubemap) - */ - "!!permu BUMP\n" - "!!permu SPECULAR\n" - "!!permu OFFSETMAPPING\n" - "!!permu SKELETAL\n" - "!!permu FOG\n" - - - "struct a2v {\n" - "float4 pos: POSITION;\n" - "float3 tc: TEXCOORD0;\n" - "float3 n: NORMAL0;\n" - "float3 s: TANGENT0;\n" - "float3 t: BINORMAL0;\n" - "};\n" - "struct v2f {\n" - "#ifndef FRAGMENT_SHADER\n" - "float4 pos: POSITION;\n" - "#endif\n" - "float3 tc: TEXCOORD0;\n" - "float3 lpos: TEXCOORD1;\n" - "};\n" - - "#ifdef VERTEX_SHADER\n" - "float4x4 m_modelviewprojection;\n" - "float3 l_lightposition;\n" - "v2f main (a2v inp)\n" - "{\n" - " v2f outp;\n" - " outp.pos = mul(m_modelviewprojection, inp.pos);\n" - " outp.tc = inp.tc;\n" - - "float3 lightminusvertex = l_lightposition - inp.pos.xyz;\n" - "outp.lpos.x = dot(lightminusvertex, inp.s.xyz);\n" - "outp.lpos.y = dot(lightminusvertex, inp.t.xyz);\n" - "outp.lpos.z = dot(lightminusvertex, inp.n.xyz);\n" - " return outp;\n" - "}\n" - "#endif\n" - - "#ifdef FRAGMENT_SHADER\n" - "sampler s_t0;\n" - "sampler s_t1;\n" - "float l_lightradius;\n" - "float3 l_lightcolour;\n" - "float4 main (v2f inp) : COLOR0\n" - "{\n" - " float3 col = l_lightcolour;\n" - " col *= max(1.0 - dot(inp.lpos, inp.lpos)/(l_lightradius*l_lightradius), 0.0);\n" - " float3 diff = tex2D(s_t0, inp.tc);\n" - " return float4(diff * col, 1);" - "}\n" - "#endif\n" - }, - - {QR_DIRECT3D9, 9, "defaultsky", - - "struct a2v {\n" - "float4 pos: POSITION;\n" - "};\n" - "struct v2f {\n" - "#ifndef FRAGMENT_SHADER\n" - "float4 pos: POSITION;\n" - "#endif\n" - "float3 vpos: TEXCOORD0;\n" - "};\n" - - "#ifdef VERTEX_SHADER\n" - "float4x4 m_modelviewprojection;\n" - "v2f main (a2v inp)\n" - "{\n" - " v2f outp;\n" - " outp.pos = mul(m_modelviewprojection, inp.pos);\n" - " outp.vpos = inp.pos;\n" - " return outp;\n" - "}\n" - "#endif\n" - - "#ifdef FRAGMENT_SHADER\n" - "float e_time;\n" - "float3 e_eyepos;\n" - - "float l_lightradius;\n" - "float3 l_lightcolour;\n" - "float3 l_lightposition;\n" - - "sampler s_t0;\n" /*diffuse*/ - "sampler s_t1;\n" /*normal*/ - "sampler s_t2;\n" /*specular*/ - "float4 main (v2f inp) : COLOR0\n" - "{\n" - " float2 tccoord;\n" - - " float3 dir = inp.vpos - e_eyepos;\n" - - " dir.z *= 3.0;\n" - " dir.xy /= 0.5*length(dir);\n" - - " tccoord = (dir.xy + e_time*0.03125);\n" - " float4 solid = tex2D(s_t0, tccoord);\n" - - " tccoord = (dir.xy + e_time*0.0625);\n" - " float4 clouds = tex2D(s_t1, tccoord);\n" - - " return float4((solid.rgb*(1.0-clouds.a)) + (clouds.a*clouds.rgb), 1);\n" - "}\n" - "#endif\n" - }, - - {QR_DIRECT3D9, 9, "defaultwarp", - "!!cvarf r_wateralpha\n" - "struct a2v {\n" - "float4 pos: POSITION;\n" - "float2 tc: TEXCOORD0;\n" - "};\n" - "struct v2f {\n" - "#ifndef FRAGMENT_SHADER\n" - "float4 pos: POSITION;\n" - "#endif\n" - "float2 tc: TEXCOORD0;\n" - "};\n" - "#ifdef VERTEX_SHADER\n" - "float4x4 m_modelviewprojection;\n" - "v2f main (a2v inp)\n" - "{\n" - " v2f outp;\n" - " outp.pos = mul(m_modelviewprojection, inp.pos);\n" - " outp.tc = inp.tc;\n" - " return outp;\n" - "}\n" - "#endif\n" - - "#ifdef FRAGMENT_SHADER\n" - "float cvar_r_wateralpha;\n" - "float e_time;\n" - "sampler s_t0;\n" - "float4 main (v2f inp) : COLOR0\n" - "{\n" - " float2 ntc;\n" - " ntc.x = inp.tc.x + sin(inp.tc.y+e_time)*0.125;\n" - " ntc.y = inp.tc.y + sin(inp.tc.x+e_time)*0.125;\n" - " float3 ts = tex2D(s_t0, ntc).xyz;\n" - - " return float4(ts, cvar_r_wateralpha);\n" - "}\n" - "#endif\n" - }, -#endif #include "r_bishaders.h" {QR_NONE} }; @@ -1460,8 +1303,8 @@ void Shader_UnloadProg(program_t *prog) int p; for (p = 0; p < PERMUTATIONS; p++) { - if (prog->handle[p].glsl) - qglDeleteProgramObject_(prog->handle[p].glsl); + if (prog->permu[p].handle.glsl) + qglDeleteProgramObject_(prog->permu[p].handle.glsl); } } #endif @@ -1728,18 +1571,18 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty //figure out visible attributes for (p = 0; p < PERMUTATIONS; p++) { - if (!prog->handle[p].glsl) + if (!prog->permu[p].handle.glsl) continue; - GLSlang_UseProgram(prog->handle[p].glsl); + GLSlang_UseProgram(prog->permu[p].handle.glsl); for (i = 0; shader_attr_names[i].name; i++) { - uniformloc = qglGetAttribLocationARB(prog->handle[p].glsl, shader_attr_names[i].name); + uniformloc = qglGetAttribLocationARB(prog->permu[p].handle.glsl, shader_attr_names[i].name); if (uniformloc != -1) { if (shader_attr_names[i].ptype != uniformloc) Con_Printf("Bad attribute\n"); else - prog->attrmask[p] |= 1u<permu[p].attrmask |= 1u<handle[p].glsl) + if (!prog->permu[p].handle.glsl) continue; - GLSlang_UseProgram(prog->handle[p].glsl); + GLSlang_UseProgram(prog->permu[p].handle.glsl); - uniformloc = qglGetUniformLocationARB(prog->handle[p].glsl, shader_unif_names[i].name); + uniformloc = qglGetUniformLocationARB(prog->permu[p].handle.glsl, shader_unif_names[i].name); if (uniformloc != -1) found = true; @@ -1764,7 +1607,7 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty break; } else - prog->parm[prog->numparams].handle[p] = uniformloc; + prog->permu[p].parm[prog->numparams] = uniformloc; } if (found) { @@ -1797,16 +1640,16 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty found = false; for (p = 0; p < PERMUTATIONS; p++) { - if (!prog->handle[p].glsl) + if (!prog->permu[p].handle.glsl) continue; - GL_SelectProgram(prog->handle[p].glsl); - uniformloc = qglGetUniformLocationARB(prog->handle[p].glsl, va("cvar_%s", tmpname)); + GL_SelectProgram(prog->permu[p].handle.glsl); + uniformloc = qglGetUniformLocationARB(prog->permu[p].handle.glsl, va("cvar_%s", tmpname)); if (uniformloc != -1) { qglUniform1fARB(uniformloc, cvar->value); found = true; } - prog->parm[prog->numparams].handle[p] = uniformloc; + prog->permu[p].parm[prog->numparams] = uniformloc; } if (found) prog->numparams++; @@ -1814,14 +1657,14 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty /*set texture uniforms*/ for (p = 0; p < PERMUTATIONS; p++) { - if (!prog->handle[p].glsl) + if (!prog->permu[p].handle.glsl) continue; - if (!(prog->attrmask[p] & (1u<attrmask[p] |= (1u<handle[p].glsl); + if (!(prog->permu[p].attrmask & (1u<permu[p].attrmask |= (1u<permu[p].handle.glsl); for (i = 0; i < 8; i++) { - uniformloc = qglGetUniformLocationARB(prog->handle[p].glsl, va("s_t%i", i)); + uniformloc = qglGetUniformLocationARB(prog->permu[p].handle.glsl, va("s_t%i", i)); if (uniformloc != -1) qglUniform1iARB(uniformloc, i); } @@ -1846,20 +1689,20 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty cvar->flags |= CVAR_SHADERSYSTEM; for (p = 0; p < PERMUTATIONS; p++) { - if (!prog->handle[p].glsl) + if (!prog->permu[p].handle.hlsl.vert || !prog->permu[p].handle.hlsl.frag) continue; - uniformloc = D3D9Shader_FindUniform(&prog->handle[p], 1, va("cvar_%s", tmpname)); + uniformloc = D3D9Shader_FindUniform(&prog->permu[p].handle, 1, va("cvar_%s", tmpname)); if (uniformloc != -1) { vec4_t v = {cvar->value, 0, 0, 0}; - IDirect3DDevice9_SetVertexShader(pD3DDev9, prog->handle[0].hlsl.vert); + IDirect3DDevice9_SetVertexShader(pD3DDev9, prog->permu[p].handle.hlsl.vert); IDirect3DDevice9_SetVertexShaderConstantF(pD3DDev9, 0, v, 1); } - uniformloc = D3D9Shader_FindUniform(&prog->handle[p], 2, va("cvar_%s", tmpname)); + uniformloc = D3D9Shader_FindUniform(&prog->permu[p].handle, 2, va("cvar_%s", tmpname)); if (uniformloc != -1) { vec4_t v = {cvar->value, 0, 0, 0}; - IDirect3DDevice9_SetPixelShader(pD3DDev9, prog->handle[0].hlsl.vert); + IDirect3DDevice9_SetPixelShader(pD3DDev9, prog->permu[p].handle.hlsl.frag); IDirect3DDevice9_SetPixelShaderConstantF(pD3DDev9, 0, v, 1); } } @@ -1869,10 +1712,10 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty found = false; for (p = 0; p < PERMUTATIONS; p++) { - uniformloc = D3D9Shader_FindUniform(&prog->handle[p], 0, shader_unif_names[i].name); + uniformloc = D3D9Shader_FindUniform(&prog->permu[p].handle, 0, shader_unif_names[i].name); if (uniformloc != -1) found = true; - prog->parm[prog->numparams].handle[p] = uniformloc; + prog->permu[p].parm[prog->numparams] = uniformloc; } if (found) { @@ -1885,11 +1728,11 @@ static void Shader_ProgAutoFields(program_t *prog, char **cvarnames, int *cvarty { for (i = 0; i < 8; i++) { - uniformloc = D3D9Shader_FindUniform(&prog->handle[p], 2, va("s_t%i", i)); + uniformloc = D3D9Shader_FindUniform(&prog->permu[p].handle, 2, va("s_t%i", i)); if (uniformloc != -1) { int v[4] = {i}; - IDirect3DDevice9_SetPixelShader(pD3DDev9, prog->handle[0].hlsl.vert); + IDirect3DDevice9_SetPixelShader(pD3DDev9, prog->permu[p].handle.hlsl.frag); IDirect3DDevice9_SetPixelShaderConstantI(pD3DDev9, 0, v, 1); } } @@ -2087,12 +1930,12 @@ static void Shader_ProgramParam ( shader_t *shader, shaderpass_t *pass, char **p prog->parm[prog->numparams].type = parmtype; for (p = 0; p < PERMUTATIONS; p++) { - if (!prog->handle[p].glsl) + if (!prog->permu[p].handle.glsl) continue; - GLSlang_UseProgram(prog->handle[p].glsl); + GLSlang_UseProgram(prog->permu[p].handle.glsl); - uniformloc = qglGetUniformLocationARB(prog->handle[p].glsl, token); - prog->parm[prog->numparams].handle[p] = uniformloc; + uniformloc = qglGetUniformLocationARB(prog->permu[p].handle.glsl, token); + prog->permu[p].parm[prog->numparams] = uniformloc; if (uniformloc != -1) { @@ -2223,6 +2066,7 @@ static qboolean Shaderpass_MapGen (shader_t *shader, shaderpass_t *pass, char *t { pass->texgen = T_GEN_SPECULAR; pass->tcgen = TC_GEN_BASE; + shader->flags |= SHADER_HASGLOSS; } else if (!Q_stricmp (tname, "$fullbright")) { @@ -4010,7 +3854,15 @@ void R_BuildDefaultTexnums(texnums_t *tn, shader_t *shader) } if (!TEXVALID(shader->defaulttextures.specular)) + { + extern cvar_t gl_specular; + if ((shader->flags & SHADER_HASGLOSS) && gl_specular.value && gl_load24bit.value) + { + if (!TEXVALID(tn->specular)) + tn->specular = R_LoadHiResTexture(va("%s_gloss", shader->name), NULL, 0); + } TEXASSIGN(shader->defaulttextures.specular, tn->specular); + } if (!TEXVALID(shader->defaulttextures.fullbright)) TEXASSIGN(shader->defaulttextures.fullbright, tn->fullbright); } @@ -4070,10 +3922,49 @@ void Shader_DefaultBSPLM(char *shortname, shader_t *s, const void *args) "{\n" "map $fullbright\n" "}\n" + "{\n" + "map $specular\n" + "}\n" "}\n" ); } #endif + +#if 0//def D3D9QUAKE + if (qrenderer == QR_DIRECT3D9) + { + if (!builtin) + builtin = ( + "{\n" + "program defaultwall\n" + /*"param texture 0 tex_diffuse\n" + "param texture 1 tex_lightmap\n" + "param texture 2 tex_normalmap\n" + "param texture 3 tex_deluxmap\n" + "param texture 4 tex_fullbright\n"*/ + "{\n" + "map $diffuse\n" + "}\n" + "{\n" + "map $lightmap\n" + "}\n" + "{\n" + "map $normalmap\n" + "}\n" + "{\n" + "map $deluxmap\n" + "}\n" + "{\n" + "map $fullbright\n" + "}\n" + "{\n" + "map $specular\n" + "}\n" + "}\n" + ); + } +#endif + #ifdef GLQUAKE if (qrenderer == QR_OPENGL) { @@ -4128,6 +4019,9 @@ void Shader_DefaultBSPLM(char *shortname, shader_t *s, const void *args) "{\n" "map $fullbright\n" "}\n" + "{\n" + "map $specular\n" + "}\n" "}\n" ); } @@ -4214,8 +4108,10 @@ char *Shader_DefaultBSPWater(char *shortname) else if (r_fastturb.ival) wstyle = 0; #ifdef GLQUAKE - else if (qrenderer == QR_OPENGL && gl_config.arb_shader_objects && r_waterstyle.ival>0 && !r_fastturb.ival && strncmp(shortname, "*lava", 5)) - wstyle = r_waterstyle.ival; //r_waterstyle does not apply to lava, and requires glsl and stuff + else if (qrenderer == QR_OPENGL && gl_config.arb_shader_objects && !strncmp(shortname, "*lava", 5)) + wstyle = r_lavastyle.ival; + else if (qrenderer == QR_OPENGL && gl_config.arb_shader_objects && strncmp(shortname, "*lava", 5)) + wstyle = r_waterstyle.ival<1?1:r_waterstyle.ival; #endif else wstyle = 1; @@ -4263,6 +4159,7 @@ char *Shader_DefaultBSPWater(char *shortname) case 2: //refraction of the underwater surface, with a fresnel return ( "{\n" + "sort blend\n" /*make sure it always has the same sort order, so switching on/off wateralpha doesn't break stuff*/ "surfaceparm nodlight\n" "{\n" "map $refraction\n" @@ -4279,6 +4176,7 @@ char *Shader_DefaultBSPWater(char *shortname) case 3: //reflections return ( "{\n" + "sort blend\n" /*make sure it always has the same sort order, so switching on/off wateralpha doesn't break stuff*/ "surfaceparm nodlight\n" "{\n" "map $refraction\n" @@ -4295,6 +4193,7 @@ char *Shader_DefaultBSPWater(char *shortname) case 4: //ripples return ( "{\n" + "sort blend\n" /*make sure it always has the same sort order, so switching on/off wateralpha doesn't break stuff*/ "surfaceparm nodlight\n" "{\n" "map $refraction\n" @@ -4314,6 +4213,7 @@ char *Shader_DefaultBSPWater(char *shortname) case 5: //ripples+reflections return ( "{\n" + "sort blend\n" /*make sure it always has the same sort order, so switching on/off wateralpha doesn't break stuff*/ "surfaceparm nodlight\n" "{\n" "map $refraction\n" diff --git a/engine/gl/gl_shadow.c b/engine/gl/gl_shadow.c index fa666337..7e60200e 100644 --- a/engine/gl/gl_shadow.c +++ b/engine/gl/gl_shadow.c @@ -429,6 +429,7 @@ static struct shadowmesh_s *SHM_FinishShadowMesh(dlight_t *dl) case QR_OPENGL: qglGenBuffersARB(2, sh_shmesh->vebo); + GL_DeselectVAO(); GL_SelectVBO(sh_shmesh->vebo[0]); qglBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(*sh_shmesh->verts) * sh_shmesh->numverts, sh_shmesh->verts, GL_STATIC_DRAW_ARB); @@ -1382,6 +1383,9 @@ static qboolean Sh_VisOverlaps(qbyte *v1, qbyte *v2) return false; } +#if 1 +#define Sh_LeafInView Sh_VisOverlaps +#else static qboolean Sh_LeafInView(qbyte *lightvis, qbyte *vvis) { int i; @@ -1409,6 +1413,7 @@ static qboolean Sh_LeafInView(qbyte *lightvis, qbyte *vvis) return false; } +#endif typedef struct { @@ -2181,7 +2186,7 @@ static void Sh_DrawShadowMapLight(dlight_t *l, vec3_t colour, qbyte *vvis) else lvis = NULL; - qglDisable(GL_SCISSOR_TEST); + Sh_ScissorOff(); Sh_GenShadowMap(l, lvis); @@ -2297,6 +2302,7 @@ static void Sh_DrawBrushModelShadow(dlight_t *dl, entity_t *e) BE_SelectEntity(e); + GL_DeselectVAO(); GL_SelectVBO(0); GL_SelectEBO(0); qglEnableClientState(GL_VERTEX_ARRAY); @@ -2534,7 +2540,6 @@ static qboolean Sh_DrawStencilLight(dlight_t *dl, vec3_t colour, qbyte *vvis) { int sfrontfail; int sbackfail; - qglEnable(GL_SCISSOR_TEST); qglEnable(GL_STENCIL_TEST); //FIXME: is it practical to test to see if scissors allow not clearing the stencil buffer? @@ -2650,7 +2655,7 @@ static qboolean Sh_DrawStencilLight(dlight_t *dl, vec3_t colour, qbyte *vvis) //end stencil writing. /*stencil writing probably changed the vertex pointer, and our backend caches it*/ - PPL_RevertToKnownState(); +// PPL_RevertToKnownState(); #if 0 //draw the stencil stuff to the red channel qglMatrixMode(GL_PROJECTION); diff --git a/engine/gl/gl_vidcommon.c b/engine/gl/gl_vidcommon.c index c7e04f96..30860256 100644 --- a/engine/gl/gl_vidcommon.c +++ b/engine/gl/gl_vidcommon.c @@ -319,6 +319,8 @@ extern cvar_t gl_workaround_ati_shadersource; qboolean GL_CheckExtension(char *extname) { int i; + int len; + const char *foo; cvar_t *v = Cvar_Get(va("gl_ext_%s", extname), "1", 0, "GL Extensions"); if (v && !v->ival) { @@ -339,8 +341,18 @@ qboolean GL_CheckExtension(char *extname) if (!gl_extensions) return false; - //note that this is not actually correct... - return !!strstr(gl_extensions, extname); + //the list is space delimited. we cannot just strstr lest we find leading/trailing _FOO_. + len = strlen(extname); + for (foo = gl_extensions; *foo; ) + { + if (!strncmp(foo, extname, len) && (foo[len] == ' ' || !foo[len])) + return true; + while(*foo && *foo != ' ') + foo++; + if (*foo == ' ') + foo++; + } + return false; } void APIENTRY GL_DrawRangeElementsEmul(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices) @@ -355,6 +367,10 @@ void APIENTRY GL_ClientStateStub(GLenum array) { } +void APIENTRY GL_ClientActiveTextureStub(GLenum texid) +{ +} + #define getglcore getglfunction #define getglext(name) getglfunction(name) void GL_CheckExtensions (void *(*getglfunction) (char *name)) @@ -388,7 +404,8 @@ void GL_CheckExtensions (void *(*getglfunction) (char *name)) s++; gl_minor_version = atoi(s); } - gl_config.glversion = gl_major_version + (gl_minor_version/10.f); + //yes, I know, this can't cope with minor versions of 10+... I don't care yet. + gl_config.glversion += gl_major_version + (gl_minor_version/10.f); /*gl3 adds glGetStringi instead, as core, with the old form require GL_ARB_compatibility*/ if (gl_major_version >= 3 && qglGetStringi) /*warning: wine fails to export qglGetStringi*/ @@ -578,6 +595,7 @@ void GL_CheckExtensions (void *(*getglfunction) (char *name)) } } + /* else if (GL_CheckExtension("GL_SGIS_multitexture") && !COM_CheckParm("-nomtex")) { //SGIS multitexture, limited in many ways but basic functionality is identical to ARB Con_SafePrintf("Multitexture extensions found.\n"); @@ -587,10 +605,17 @@ void GL_CheckExtensions (void *(*getglfunction) (char *name)) mtexid0 = GL_TEXTURE0_SGIS; } + */ + if (!qglClientActiveTextureARB) + { + qglClientActiveTextureARB = GL_ClientActiveTextureStub; + } if ((gl_config.gles && gl_config.glversion >= 2) || GL_CheckExtension("GL_EXT_stencil_wrap")) gl_config.ext_stencil_wrap = true; + qglStencilOpSeparateATI = NULL; + qglActiveStencilFaceEXT = NULL; if (gl_config.gles && gl_config.glversion >= 2) qglStencilOpSeparateATI = (void *) getglext("glStencilOpSeparate"); else if (GL_CheckExtension("GL_ATI_separate_stencil")) diff --git a/engine/gl/gl_viddroid.c b/engine/gl/gl_viddroid.c index d12febd1..4e80c607 100644 --- a/engine/gl/gl_viddroid.c +++ b/engine/gl/gl_viddroid.c @@ -20,7 +20,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "quakedef.h" #include "glquake.h" -extern qboolean sys_glesversion; +extern int sys_glesversion; static dllhandle_t *sys_gl_module = NULL; @@ -85,6 +85,9 @@ qboolean GLVID_Init (rendererstate_t *info, unsigned char *palette) Cons: GL_EndRendering call will not swap buffers. Buffers will be swapped on return to java. */ + if (!sys_glesversion) + return false; + if (sys_glesversion >= 2) Sys_Printf("Loading GLES2 driver\n"); else @@ -114,12 +117,12 @@ void GLVID_DeInit(void) { if (sys_display != EGL_NO_DISPLAY) { - eglMakeCurrent(sys_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + eglMakeCurrent(sys_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (sys_context != EGL_NO_CONTEXT) eglDestroyContext(sys_display, sys_context); if (sys_surface != EGL_NO_SURFACE) eglDestroySurface(sys_display, sys_surface); - eglTerminate(sys_display); + eglTerminate(sys_display); sys_context = EGL_NO_CONTEXT; sys_surface = EGL_NO_SURFACE; sys_display = EGL_NO_DISPLAY; @@ -189,7 +192,7 @@ qboolean GLVID_Init (rendererstate_t *info, unsigned char *palette) vid.pixelwidth = w; vid.pixelheight = h; - GLVID_SetPalette (palette); + GLVID_SetPalette (palette); GL_Init(GLES_GetSymbol); vid.recalc_refdef = 1; return true; diff --git a/engine/gl/gl_vidnt.c b/engine/gl/gl_vidnt.c index 2f5c8c8a..7314d05f 100644 --- a/engine/gl/gl_vidnt.c +++ b/engine/gl/gl_vidnt.c @@ -1303,6 +1303,26 @@ void GLVID_Recenter_f(void) //int nx = 0; //int ny = 0; +#ifdef _MSC_VER +#define strtoull _strtoui64 +#endif + + if (Cmd_Argc() > 1) + sys_parentleft = atoi(Cmd_Argv(1)); + if (Cmd_Argc() > 2) + sys_parenttop = atoi(Cmd_Argv(2)); + if (Cmd_Argc() > 3) + sys_parentwidth = atoi(Cmd_Argv(3)); + if (Cmd_Argc() > 4) + sys_parentheight = atoi(Cmd_Argv(4)); + if (Cmd_Argc() > 5) + { + HWND newparent = (HWND)strtoull(Cmd_Argv(5), NULL, 16); + if (newparent != sys_parentwindow && mainwindow && modestate==MS_WINDOWED) + SetParent(mainwindow, sys_parentwindow); + sys_parentwindow = newparent; + } + if (sys_parentwindow && modestate==MS_WINDOWED) { WindowRect = centerrect(sys_parentleft, sys_parenttop, sys_parentwidth, sys_parentheight, vid_width.value, vid_height.value); @@ -1673,6 +1693,11 @@ BOOL bSetupPixelFormat(HDC hDC, rendererstate_t *info) qDescribePixelFormat(hDC, pixelformat, sizeof(pfd), &pfd); FixPaletteInDescriptor(hDC, &pfd); gl_stencilbits = pfd.cStencilBits; + + if ((pfd.dwFlags & PFD_GENERIC_FORMAT) && !(pfd.dwFlags & PFD_GENERIC_ACCELERATED)) + { + Con_Printf(CON_WARNING "WARNING: software-rendered opengl context\nPlease install appropriate graphics drivers, or try d3d rendering instead\n"); + } return TRUE; } } @@ -1694,6 +1719,11 @@ BOOL bSetupPixelFormat(HDC hDC, rendererstate_t *info) return FALSE; } + if ((pfd.dwFlags & PFD_GENERIC_FORMAT) && !(pfd.dwFlags & PFD_GENERIC_ACCELERATED)) + { + Con_Printf(CON_WARNING "WARNING: software-rendered opengl context\nPlease install appropriate graphics drivers, or try d3d rendering instead\n"); + } + FixPaletteInDescriptor(hDC, &pfd); return TRUE; } @@ -1883,9 +1913,8 @@ LONG WINAPI GLMainWndProc ( if (wParam & MK_LBUTTON) { temp |= 1; -#ifdef NPFTE - SetFocus(hWnd); -#endif + if (sys_parentwindow && modestate == MS_WINDOWED) + SetFocus(hWnd); } if (wParam & MK_RBUTTON) diff --git a/engine/gl/ltface.c b/engine/gl/ltface.c index 18885b64..274019b9 100644 --- a/engine/gl/ltface.c +++ b/engine/gl/ltface.c @@ -939,9 +939,11 @@ void LightFace (int surfnum) temp[1] = DotProduct(wnorm, tvector); temp[2] = DotProduct(wnorm, l.facenormal); VectorNormalize(temp); - *dulout++ = -(temp[0]+1)*128 + 128; - *dulout++ = (temp[1]+1)*128 + 128; - *dulout++ = (temp[2]+1)*128 + 128; + temp[2] += 0.5; + VectorNormalize(temp); + *dulout++ = (-temp[0]+1)*128; + *dulout++ = (-temp[1]+1)*128; + *dulout++ = (-temp[2]+1)*128; } } } diff --git a/engine/gl/r_bishaders.h b/engine/gl/r_bishaders.h index 89ff9d76..49448fd6 100644 --- a/engine/gl/r_bishaders.h +++ b/engine/gl/r_bishaders.h @@ -5,6 +5,7 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND #ifdef GLQUAKE {QR_OPENGL, 110, "altwater", +"!!cvarf r_glsl_turbscale\n" //modifier: REFLECT (s_t2 is a reflection instead of diffusemap) //modifier: STRENGTH (0.1 = fairly gentle, 0.2 = big waves) //modifier: FRESNEL (5=water) @@ -12,6 +13,8 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND //modifier: RIPPLEMAP (s_t3 contains a ripplemap //modifier: TINT (some colour value) +"uniform float cvar_r_glsl_turbscale;\n" + "#ifndef FRESNEL\n" "#define FRESNEL 5.0\n" "#endif\n" @@ -74,9 +77,9 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND //the fresnel term decides how transparent the water should be "f = pow(1.0-abs(dot(normalize(n), normalize(eye))), float(FRESNEL));\n" -"refr = texture2D(s_t0, stc + n.st*STRENGTH).rgb * TINT;\n" +"refr = texture2D(s_t0, stc + n.st*STRENGTH*cvar_r_glsl_turbscale).rgb * TINT;\n" "#ifdef REFLECT\n" -"refl = texture2D(s_t2, stc - n.st*STRENGTH).rgb;\n" +"refl = texture2D(s_t2, stc - n.st*STRENGTH*cvar_r_glsl_turbscale).rgb;\n" "#else\n" "refl = texture2D(s_t2, ntc).xyz;\n" "#endif\n" @@ -334,6 +337,44 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "default2d", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float4 vcol: COLOR0;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float4 vcol: COLOR0;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_projection, inp.pos);\n" +"outp.tc = inp.tc;\n" +"outp.vcol = inp.vcol;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture;\n" +"SamplerState SampleType;\n" +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"return shaderTexture.Sample(SampleType, inp.tc) * inp.vcol;\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "defaultadditivesprite", "!!permu FOG\n" @@ -431,6 +472,67 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "defaultskin", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float4 tc: TEXCOORD0;\n" +"float3 normal: NORMAL;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float3 light: TEXCOORD1;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +//attribute vec2 v_texcoord; +//uniform vec3 e_light_dir; +//uniform vec3 e_light_mul; +//uniform vec3 e_light_ambient; +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.light = e_light_ambient + (dot(inp.normal,e_light_dir)*e_light_mul);\n" +"outp.tc = inp.tc.xy;\n" +"return outp;\n" +"}\n" +"#endif\n" +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture[4]; //diffuse, lower, upper, fullbright\n" +"SamplerState SampleType;\n" + +//uniform vec4 e_colourident; +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"float4 col;\n" +"col = shaderTexture[0].Sample(SampleType, inp.tc);\n" +"#ifdef UPPER\n" +"float4 uc = shaderTexture[2].Sample(SampleType, inp.tc);\n" +"col.rgb = mix(col.rgb, uc.rgb*e_uppercolour, uc.a);\n" +"#endif\n" +"#ifdef LOWER\n" +"float4 lc = shaderTexture[1].Sample(SampleType, inp.tc);\n" +"col.rgb = mix(col.rgb, lc.rgb*e_lowercolour, lc.a);\n" +"#endif\n" +"col.rgb *= inp.light;\n" +"#ifdef FULLBRIGHT\n" +"float4 fb = shaderTexture[3].Sample(SampleType, inp.tc);\n" +"col.rgb = mix(col.rgb, fb.rgb, fb.a);\n" +"#endif\n" +"return col;\n" +// return fog4(col * e_colourident); +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "defaultsky", //regular sky shader for scrolling q1 skies @@ -465,6 +567,113 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D9QUAKE +{QR_DIRECT3D9, 9, "defaultsky", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"};\n" +"struct v2f\n" +"{\n" +"#ifndef FRAGMENT_SHADER\n" +"float4 pos: POSITION;\n" +"#endif\n" +"float3 vpos: TEXCOORD0;\n" +"};\n" + +"#ifdef VERTEX_SHADER\n" +"float4x4 m_modelviewprojection;\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_modelviewprojection, inp.pos);\n" +"outp.vpos = inp.pos;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"float e_time;\n" +"float3 e_eyepos;\n" + +"float l_lightradius;\n" +"float3 l_lightcolour;\n" +"float3 l_lightposition;\n" + +"sampler s_t0; /*diffuse*/\n" +"sampler s_t1; /*normal*/\n" +"sampler s_t2; /*specular*/\n" +"float4 main (v2f inp) : COLOR0\n" +"{\n" +"float2 tccoord;\n" + +"float3 dir = inp.vpos - e_eyepos;\n" + +"dir.z *= 3.0;\n" +"dir.xy /= 0.5*length(dir);\n" + +"tccoord = (dir.xy + e_time*0.03125);\n" +"float4 solid = tex2D(s_t0, tccoord);\n" + +"tccoord = (dir.xy + e_time*0.0625);\n" +"float4 clouds = tex2D(s_t1, tccoord);\n" + +"return float4((solid.rgb*(1.0-clouds.a)) + (clouds.a*clouds.rgb), 1);\n" +"}\n" +"#endif\n" +}, +#endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "defaultsky", +//regular sky shader for scrolling q1 skies +//the sky surfaces are thrown through this as-is. + +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float3 mpos: TEXCOORD1;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.mpos = outp.pos.xyz;\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.tc = inp.tc;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture[2];\n" +"SamplerState SampleType;\n" + +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"float2 tccoord;\n" +"float3 dir = inp.mpos - v_eyepos;\n" +"dir.z *= 3.0;\n" +"dir.xy /= 0.5*length(dir);\n" +"tccoord = (dir.xy + e_time*0.03125);\n" +"float4 solid = shaderTexture[0].Sample(SampleType, tccoord);\n" +"tccoord = (dir.xy + e_time*0.0625);\n" +"float4 clouds = shaderTexture[1].Sample(SampleType, tccoord);\n" +"return (solid*(1.0-clouds.a)) + (clouds.a*clouds);\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "defaultsprite", "!!permu FOG\n" @@ -496,6 +705,46 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "defaultsprite", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float4 tc: TEXCOORD0;\n" +"float4 vcol: COLOR0;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float4 vcol: COLOR0;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.tc = inp.tc.xy;\n" +"outp.vcol = inp.vcol;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture;\n" +"SamplerState SampleType;\n" +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"return shaderTexture.Sample(SampleType, inp.tc) * inp.vcol;\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "defaultwall", "!!permu DELUXE\n" @@ -503,13 +752,15 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "!!permu FOG\n" "!!permu LIGHTSTYLED\n" "!!permu BUMP\n" +"!!permu SPECULAR\n" "!!cvarf r_glsl_offsetmapping_scale\n" +"!!cvarf gl_specular\n" //this is what normally draws all of your walls, even with rtlights disabled //note that the '286' preset uses drawflat_walls instead. "#include \"sys/fog.h\"\n" -"#if defined(OFFSETMAPPING)\n" +"#if defined(OFFSETMAPPING) || defined(SPECULAR)\n" "varying vec3 eyevector;\n" "#endif\n" @@ -530,7 +781,7 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "attribute vec2 v_lmcoord3;\n" "attribute vec2 v_lmcoord4;\n" "#endif\n" -"#if defined(OFFSETMAPPING)\n" +"#if defined(OFFSETMAPPING) || defined(SPECULAR)\n" "uniform vec3 e_eyepos;\n" "attribute vec3 v_normal;\n" "attribute vec3 v_svector;\n" @@ -538,7 +789,7 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" "void main ()\n" "{\n" -"#if defined(OFFSETMAPPING)\n" +"#if defined(OFFSETMAPPING) || defined(SPECULAR)\n" "vec3 eyeminusvertex = e_eyepos - v_position.xyz;\n" "eyevector.x = -dot(eyeminusvertex, v_svector.xyz);\n" "eyevector.y = dot(eyeminusvertex, v_tvector.xyz);\n" @@ -560,20 +811,23 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND //samplers "uniform sampler2D s_t0; //diffuse\n" "uniform sampler2D s_t1; //lightmap0\n" -"#if defined(OFFSETMAPPING) || defined(DELUXE)\n" -"uniform sampler2D s_t2; //normal\n" +"#if defined(BUMP) && (defined(OFFSETMAPPING) || defined(DELUXE) || defined(SPECULAR))\n" +"uniform sampler2D s_t2; //normal.rgb+height.a\n" "#endif\n" "uniform sampler2D s_t3; //deluxe0\n" "#ifdef FULLBRIGHT\n" "uniform sampler2D s_t4; //fullbright\n" "#endif\n" +"#ifdef SPECULAR\n" +"uniform sampler2D s_t5; //specular\n" +"#endif\n" "#ifdef LIGHTSTYLED\n" -"uniform sampler2D s_t5; //lightmap1\n" -"uniform sampler2D s_t6; //lightmap2\n" -"uniform sampler2D s_t7; //lightmap3\n" -"uniform sampler2D s_t8; //deluxe1\n" -"uniform sampler2D s_t9; //deluxe2\n" -"uniform sampler2D s_t10; //deluxe3\n" +"uniform sampler2D s_t6; //lightmap1\n" +"uniform sampler2D s_t7; //lightmap2\n" +"uniform sampler2D s_t8; //lightmap3\n" +"uniform sampler2D s_t9; //deluxe1\n" +"uniform sampler2D s_t10; //deluxe2\n" +"uniform sampler2D s_t11; //deluxe3\n" "#endif\n" "#ifdef LIGHTSTYLED\n" @@ -582,6 +836,9 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "uniform vec4 e_lmscale;\n" "#endif\n" "uniform vec4 e_colourident;\n" +"#ifdef SPECULAR\n" +"uniform float cvar_gl_specular;\n" +"#endif\n" "#ifdef OFFSETMAPPING\n" "#include \"sys/offsetmapping.h\"\n" "#endif\n" @@ -596,31 +853,53 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND //yay, regular texture! "gl_FragColor = texture2D(s_t0, tc);\n" +"#if defined(BUMP) && (defined(DELUXE) || defined(SPECULAR))\n" +"vec3 norm = normalize(texture2D(s_t2, tc).rgb - 0.5);\n" +"#elif defined(SPECULAR) || defined(DELUXE)\n" +"vec3 norm = vec3(0, 0, 1); //specular lighting expects this to exist.\n" +"#endif\n" + //modulate that by the lightmap(s) including deluxemap(s) "#ifdef LIGHTSTYLED\n" -"vec4 lightmaps;\n" +"vec3 lightmaps;\n" "#ifdef DELUXE\n" -"vec3 norm = texture2D(s_t2, tc).rgb;\n" -"lightmaps = texture2D(s_t1, lm ) * e_lmscale[0] * dot(norm, texture2D(s_t3, lm ).rgb);\n" -"lightmaps += texture2D(s_t5, lm2) * e_lmscale[1] * dot(norm, texture2D(s_t8, lm2).rgb);\n" -"lightmaps += texture2D(s_t6, lm3) * e_lmscale[2] * dot(norm, texture2D(s_t9, lm3).rgb);\n" -"lightmaps += texture2D(s_t7, lm4) * e_lmscale[3] * dot(norm, texture2D(s_t10,lm4).rgb);\n" +"lightmaps = texture2D(s_t1, lm ).rgb * e_lmscale[0].rgb * dot(norm, texture2D(s_t3, lm ).rgb);\n" +"lightmaps += texture2D(s_t6, lm2).rgb * e_lmscale[1].rgb * dot(norm, texture2D(s_t9, lm2).rgb);\n" +"lightmaps += texture2D(s_t7, lm3).rgb * e_lmscale[2].rgb * dot(norm, texture2D(s_t10, lm3).rgb);\n" +"lightmaps += texture2D(s_t8, lm4).rgb * e_lmscale[3].rgb * dot(norm, texture2D(s_t11,lm4).rgb);\n" "#else\n" -"lightmaps = texture2D(s_t1, lm ) * e_lmscale[0];\n" -"lightmaps += texture2D(s_t5, lm2) * e_lmscale[1];\n" -"lightmaps += texture2D(s_t6, lm3) * e_lmscale[2];\n" -"lightmaps += texture2D(s_t7, lm4) * e_lmscale[3];\n" +"lightmaps = texture2D(s_t1, lm ).rgb * e_lmscale[0].rgb;\n" +"lightmaps += texture2D(s_t6, lm2).rgb * e_lmscale[1].rgb;\n" +"lightmaps += texture2D(s_t7, lm3).rgb * e_lmscale[2].rgb;\n" +"lightmaps += texture2D(s_t8, lm4).rgb * e_lmscale[3].rgb;\n" "#endif\n" +"#else\n" +"vec3 lightmaps = (texture2D(s_t1, lm) * e_lmscale).rgb;\n" +//modulate by the bumpmap dot light +"#ifdef DELUXE\n" +"lightmaps *= dot(norm, 2.0*(texture2D(s_t3, lm).rgb-0.5));\n" +"#endif\n" +"#endif\n" + +"#ifdef SPECULAR\n" +"vec4 specs = texture2D(s_t5, tc);\n" +"#ifdef DELUXE\n" +//not lightstyled... +"vec3 halfdir = normalize(normalize(eyevector) + 2.0*(texture2D(s_t3, lm).rgb-0.5)); //this norm should be the deluxemap info instead\n" +"#else\n" +"vec3 halfdir = normalize(normalize(eyevector) + vec3(0.0, 0.0, 1.0)); //this norm should be the deluxemap info instead\n" +"#endif\n" +"float spec = pow(max(dot(halfdir, norm), 0.0), 32.0 * specs.a);\n" +"spec *= cvar_gl_specular;\n" +//NOTE: rtlights tend to have a *4 scaler here to over-emphasise the effect because it looks cool. +//As not all maps will have deluxemapping, and the double-cos from the light util makes everything far too dark anyway, +//we default to something that is not garish when the light value is directly infront of every single pixel. +//we can justify this difference due to the rtlight editor etc showing the *4. +"gl_FragColor.rgb += spec * specs.rgb;\n" +"#endif\n" + +//now we have our diffuse+specular terms, modulate by lightmap values. "gl_FragColor.rgb *= lightmaps.rgb;\n" -"#else\n" -"#ifdef DELUXE\n" -//gl_FragColor.rgb = dot(normalize(texture2D(s_t2, tc).rgb - 0.5), normalize(texture2D(s_t3, lm).rgb - 0.5)); -//gl_FragColor.rgb = texture2D(s_t3, lm).rgb; -"gl_FragColor.rgb *= (texture2D(s_t1, lm) * e_lmscale).rgb * dot(normalize(texture2D(s_t2, tc).rgb-0.5), 2.0*(texture2D(s_t3, lm).rgb-0.5));\n" -"#else\n" -"gl_FragColor.rgb *= (texture2D(s_t1, lm) * e_lmscale).rgb;\n" -"#endif\n" -"#endif\n" //add on the fullbright "#ifdef FULLBRIGHT\n" @@ -638,6 +917,46 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "defaultwall", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float4 tc: TEXCOORD0;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float2 lmtc: TEXCOORD1;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.tc = inp.tc.xy;\n" +"outp.lmtc = inp.tc.zw;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture[2];\n" +"SamplerState SampleType[2];\n" + +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"return shaderTexture[0].Sample(SampleType[0], inp.tc) * shaderTexture[1].Sample(SampleType[1], inp.lmtc).bgra;\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "defaultwarp", "!!cvarf r_wateralpha\n" @@ -671,6 +990,91 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D9QUAKE +{QR_DIRECT3D9, 9, "defaultwarp", +"!!cvarf r_wateralpha\n" +"struct a2v {\n" +"float4 pos: POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"};\n" +"struct v2f {\n" +"#ifndef FRAGMENT_SHADER\n" +"float4 pos: POSITION;\n" +"#endif\n" +"float2 tc: TEXCOORD0;\n" +"};\n" +"#ifdef VERTEX_SHADER\n" +"float4x4 m_modelviewprojection;\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_modelviewprojection, inp.pos);\n" +"outp.tc = inp.tc;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"float cvar_r_wateralpha;\n" +"float e_time;\n" +"sampler s_t0;\n" +"float4 main (v2f inp) : COLOR0\n" +"{\n" +"float2 ntc;\n" +"ntc.x = inp.tc.x + sin(inp.tc.y+e_time)*0.125;\n" +"ntc.y = inp.tc.y + sin(inp.tc.x+e_time)*0.125;\n" +"float3 ts = tex2D(s_t0, ntc).xyz;\n" + +"return float4(ts, cvar_r_wateralpha);\n" +"}\n" +"#endif\n" +}, +#endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "defaultwarp", +"!!cvarf r_wateralpha\n" + +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.tc = inp.tc;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +// float cvar_r_wateralpha; +// float e_time; +// sampler s_t0; +"Texture2D shaderTexture;\n" +"SamplerState SampleType;\n" +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"float2 ntc;\n" +"ntc.x = inp.tc.x + sin(inp.tc.y+e_time)*0.125;\n" +"ntc.y = inp.tc.y + sin(inp.tc.x+e_time)*0.125;\n" +"return shaderTexture.Sample(SampleType, ntc);\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "drawflat_wall", "!!cvarv r_floorcolor\n" @@ -705,6 +1109,49 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "drawflat_wall", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float4 tc: TEXCOORD0;\n" +"float3 norm: NORMAL;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float2 lmtc: TEXCOORD1;\n" +"float4 col: TEXCOORD2;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.tc = inp.tc.xy;\n" +"outp.lmtc = inp.tc.zw;\n" +"outp.col = ((inp.norm.z<0.73)?float4(0.5, 0.5, 0.5, 1):float4(0.25, 0.25, 0.5, 1));\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture;\n" +"SamplerState SampleType;\n" + +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"return inp.col * shaderTexture.Sample(SampleType, inp.lmtc);\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "lpp_depthnorm", "!!permu BUMP\n" @@ -1174,6 +1621,72 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D9QUAKE +{QR_DIRECT3D9, 9, "rtlight", +"!!permu BUMP\n" +"!!permu SPECULAR\n" +"!!permu OFFSETMAPPING\n" +"!!permu SKELETAL\n" +"!!permu FOG\n" + + +// texture units: +// s0=diffuse, s1=normal, s2=specular, s3=shadowmap +// custom modifiers: +// PCF(shadowmap) +// CUBE(projected cubemap) + + + +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float3 tc: TEXCOORD0;\n" +"float3 n: NORMAL0;\n" +"float3 s: TANGENT0;\n" +"float3 t: BINORMAL0;\n" +"};\n" +"struct v2f\n" +"{\n" +"#ifndef FRAGMENT_SHADER\n" +"float4 pos: POSITION;\n" +"#endif\n" +"float3 tc: TEXCOORD0;\n" +"float3 lpos: TEXCOORD1;\n" +"};\n" + +"#ifdef VERTEX_SHADER\n" +"float4x4 m_modelviewprojection;\n" +"float3 l_lightposition;\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_modelviewprojection, inp.pos);\n" +"outp.tc = inp.tc;\n" + +"float3 lightminusvertex = l_lightposition - inp.pos.xyz;\n" +"outp.lpos.x = dot(lightminusvertex, inp.s.xyz);\n" +"outp.lpos.y = dot(lightminusvertex, inp.t.xyz);\n" +"outp.lpos.z = dot(lightminusvertex, inp.n.xyz);\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"sampler s_t0;\n" +"sampler s_t1;\n" +"float l_lightradius;\n" +"float3 l_lightcolour;\n" +"float4 main (v2f inp) : COLOR0\n" +"{\n" +"float3 col = l_lightcolour;\n" +"col *= max(1.0 - dot(inp.lpos, inp.lpos)/(l_lightradius*l_lightradius), 0.0);\n" +"float3 diff = tex2D(s_t0, inp.tc);\n" +"return float4(diff * col, 1);\n" +"}\n" +"#endif\n" +}, +#endif #ifdef GLQUAKE {QR_OPENGL, 110, "underwaterwarp", "!!cvarf r_waterwarp\n" @@ -1272,3 +1785,56 @@ YOU SHOULD NOT EDIT THIS FILE BY HAND "#endif\n" }, #endif +#ifdef D3D11QUAKE +{QR_DIRECT3D11, 11, "terrain", +"struct a2v\n" +"{\n" +"float4 pos: POSITION;\n" +"float4 tc: TEXCOORD0;\n" +"float4 vcol: COLOR0;\n" +"};\n" +"struct v2f\n" +"{\n" +"float4 pos: SV_POSITION;\n" +"float2 tc: TEXCOORD0;\n" +"float2 lmtc: TEXCOORD1;\n" +"float4 vcol: COLOR0;\n" +"};\n" + +"#include \n" + +"#ifdef VERTEX_SHADER\n" +"v2f main (a2v inp)\n" +"{\n" +"v2f outp;\n" +"outp.pos = mul(m_model, inp.pos);\n" +"outp.pos = mul(m_view, outp.pos);\n" +"outp.pos = mul(m_projection, outp.pos);\n" +"outp.tc = inp.tc.xy;\n" +"outp.lmtc = inp.tc.zw;\n" +"outp.vcol = inp.vcol;\n" +"return outp;\n" +"}\n" +"#endif\n" + +"#ifdef FRAGMENT_SHADER\n" +"Texture2D shaderTexture[5];\n" +"SamplerState SampleType;\n" + +"float4 main (v2f inp) : SV_TARGET\n" +"{\n" +"return float4(1,1,1,1);\n" + +// float4 m = shaderTexture[4].Sample(SampleType, inp.tc) ; + +// return inp.vcol*float4(m.aaa,1.0)*( +// shaderTexture[0].Sample(SampleType, inp.tc)*m.r +// + shaderTexture[1].Sample(SampleType, inp.tc)*m.g +// + shaderTexture[2].Sample(SampleType, inp.tc)*m.b +// + shaderTexture[3].Sample(SampleType, inp.tc)*1.0 - (m.r + m.g + m.b)) +// ; + +"}\n" +"#endif\n" +}, +#endif diff --git a/engine/gl/shader.h b/engine/gl/shader.h index 32a4b3bd..1a5005b9 100644 --- a/engine/gl/shader.h +++ b/engine/gl/shader.h @@ -2,6 +2,7 @@ #define SHADER_H typedef void (shader_gen_t)(char *name, shader_t*, const void *args); +#define SHADER_TMU_MAX 16 #define SHADER_PASS_MAX 8 #define SHADER_MAX_TC_MODS 8 #define SHADER_DEFORM_MAX 8 @@ -347,7 +348,6 @@ typedef struct { SP_CVAR3F, SP_TEXTURE } type; - unsigned int handle[PERMUTATIONS]; union { int ival; @@ -375,10 +375,13 @@ typedef struct programshared_s { int refs; qboolean nofixedcompat; - union programhandle_u handle[PERMUTATIONS]; - unsigned int attrmask[PERMUTATIONS]; int numparams; shaderprogparm_t parm[SHADER_PROGPARMS_MAX]; + struct { + union programhandle_u handle; + unsigned int attrmask; + unsigned int parm[SHADER_PROGPARMS_MAX]; + } permu[PERMUTATIONS]; } program_t; typedef struct { @@ -417,7 +420,7 @@ struct shader_s SHADER_NOIMAGE = 1 << 8, SHADER_ENTITY_MERGABLE = 1 << 9, SHADER_VIDEOMAP = 1 << 10, - SHADER_DEPTHWRITE = 1 << 11, + SHADER_DEPTHWRITE = 1 << 11, //some pass already wrote depth. not used by the renderer. SHADER_AGEN_PORTAL = 1 << 12, SHADER_BLEND = 1 << 13, //blend or alphatest (not 100% opaque). SHADER_NODRAW = 1 << 14, //parsed only to pee off developers when they forget it on no-pass shaders. @@ -430,6 +433,7 @@ struct shader_s SHADER_HASREFRACT = 1 << 20, //says that we need to generate a refraction image first SHADER_HASNORMALMAP = 1 << 21, //says that we need to load a normalmap texture SHADER_HASRIPPLEMAP = 1 << 22, //water surface disturbances for water splashes + SHADER_HASGLOSS = 1 << 23, // } flags; program_t *prog; @@ -523,7 +527,7 @@ qboolean D3D9BE_LightCullModel(vec3_t org, model_t *model); void D3D9BE_SelectEntity(entity_t *ent); void D3D9BE_SelectDLight(dlight_t *dl, vec3_t colour); -qboolean D3D9Shader_CreateProgram (program_t *prog, int permu, char **precompilerconstants, char *vert, char *frag); +qboolean D3D9Shader_CreateProgram (program_t *prog, char *sname, int permu, char **precompilerconstants, char *vert, char *frag); int D3D9Shader_FindUniform(union programhandle_u *h, int type, char *name); void D3D9Shader_Init(void); void D3D9BE_Reset(qboolean before); diff --git a/engine/http/httpclient.c b/engine/http/httpclient.c index 8d6f20c7..d2d130c2 100644 --- a/engine/http/httpclient.c +++ b/engine/http/httpclient.c @@ -46,6 +46,7 @@ void HTTP_Cleanup(struct dl_download *dl) free(con->buffer); free(con); + dl->abort = NULL; dl->status = DL_PENDING; dl->completed = 0; dl->totalsize = 0; @@ -112,6 +113,7 @@ static qboolean HTTP_DL_Work(struct dl_download *dl) con->state = HC_GETTING; dl->status = DL_ACTIVE; con->contentlength = -1; //meaning end of stream. + dl->replycode = 0; } else { @@ -160,6 +162,9 @@ static qboolean HTTP_DL_Work(struct dl_download *dl) msg = COM_ParseOut(con->buffer, buffer, sizeof(buffer)); msg = COM_ParseOut(msg, buffer, sizeof(buffer)); + + dl->replycode = atoi(buffer); + if (!stricmp(buffer, "100")) { //http/1.1 servers can give this. We ignore it. @@ -222,6 +227,7 @@ static qboolean HTTP_DL_Work(struct dl_download *dl) if (!dl->file) { +#ifndef NPFTE if (*dl->localname) { FS_CreatePath(dl->localname, FS_GAME); @@ -229,6 +235,7 @@ static qboolean HTTP_DL_Work(struct dl_download *dl) } else dl->file = FS_OpenTemp(); +#endif if (!dl->file) { Con_Printf("HTTP: Couldn't open file \"%s\"\n", dl->localname); @@ -350,8 +357,10 @@ static qboolean HTTP_DL_Work(struct dl_download *dl) void HTTPDL_Establish(struct dl_download *dl) { unsigned long _true = true; - struct sockaddr_qstorage from; + struct sockaddr_qstorage serveraddr; struct http_dl_ctx_s *con; + int addressfamily; + int addresssize; char server[128]; char uri[MAX_OSPATH]; @@ -379,30 +388,28 @@ void HTTPDL_Establish(struct dl_download *dl) con = malloc(sizeof(*con)); memset(con, 0, sizeof(*con)); dl->ctx = con; + dl->abort = HTTP_Cleanup; - if ((con->sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) + dl->status = DL_RESOLVING; + + if (!NET_StringToSockaddr(server, 80, &serveraddr, &addressfamily, &addresssize)) { dl->status = DL_FAILED; return; } - dl->status = DL_RESOLVING; - {//quake routines using dns and stuff (Really, I wanna keep quake and ftp fairly seperate) - netadr_t qaddy; - if (!NET_StringToAdr (server, &qaddy)) - { - dl->status = DL_FAILED; - return; - } - if (!qaddy.port) - qaddy.port = htons(80); - NetadrToSockadr(&qaddy, &from); - }//end of quake. - dl->status = DL_QUERY; + if ((con->sock = socket (addressfamily, SOCK_STREAM, IPPROTO_TCP)) == -1) + { + dl->status = DL_FAILED; + return; + } + + //don't bother binding. its optional. + //not yet blocking. - if (connect(con->sock, (struct sockaddr *)&from, sizeof(struct sockaddr_in)) == -1) + if (connect(con->sock, (struct sockaddr *)&serveraddr, addresssize) == -1) { dl->status = DL_FAILED; return; @@ -414,7 +421,7 @@ void HTTPDL_Establish(struct dl_download *dl) return; } - ExpandBuffer(con, 2048); + ExpandBuffer(con, 512*1024); sprintf(con->buffer, "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n" "User-Agent: "FULLENGINENAME"\r\n" "\r\n", uri, server); con->bufferused = strlen(con->buffer); con->contentlength = -1; @@ -480,10 +487,16 @@ static int DL_Thread_Work(void *arg) { if (!dl->poll(dl)) { +#ifdef NPFTE + //the plugin doesn't have a download loop if (dl->notify) dl->notify(dl); if (dl->file) VFS_CLOSE(dl->file); +#else + if (dl->status != DL_FAILED && dl->status != DL_FINISHED) + dl->status = DL_FAILED; +#endif break; } } @@ -540,8 +553,12 @@ void DL_Close(struct dl_download *dl) } +/*updates pending downloads*/ +#ifndef NPFTE + static struct dl_download *activedownloads; static struct dl_download *showndownload; +unsigned int shownbytestart; /*create a download context and add it to the list, for lazy people*/ struct dl_download *HTTP_CL_Get(const char *url, const char *localfile, void (*NotifyFunction)(struct dl_download *dl)) { @@ -555,10 +572,10 @@ struct dl_download *HTTP_CL_Get(const char *url, const char *localfile, void (*N newdl->next = activedownloads; activedownloads = newdl; + return newdl; } -/*updates pending downloads*/ void HTTP_CL_Think(void) { struct dl_download *con = activedownloads; @@ -568,6 +585,18 @@ void HTTP_CL_Think(void) while (*link) { con = *link; +#ifdef MULTITHREAD + if (con->threadctx) + { + if (con->status == DL_FINISHED || con->status == DL_FAILED) + { + Sys_WaitOnThread(con->threadctx); + con->threadctx = NULL; + continue; + } + } + else +#endif if (!con->poll(con)) { if (con->file) @@ -595,6 +624,9 @@ void HTTP_CL_Think(void) showndownload = con; strcpy(cls.downloadlocalname, con->localname); strcpy(cls.downloadremotename, con->url); + cls.downloadstarttime = Sys_DoubleTime(); + cls.downloadedbytes = 0; + shownbytestart = con->completed; } if (cls.downloadmethod == DL_HTTP) { @@ -608,8 +640,10 @@ void HTTP_CL_Think(void) cls.downloadpercent = 50; else cls.downloadpercent = con->completed*100.0f/con->totalsize; + cls.downloadedbytes = con->completed; } } } } +#endif #endif /*WEBCLIENT*/ diff --git a/engine/http/iweb.h b/engine/http/iweb.h index 322ef8a2..2ebfaa65 100644 --- a/engine/http/iweb.h +++ b/engine/http/iweb.h @@ -128,6 +128,7 @@ struct dl_download DL_ACTIVE, /*receiving data*/ DL_FINISHED /*its complete*/ } status; + unsigned int replycode; unsigned int totalsize; /*max size (can be 0 for unknown)*/ unsigned int completed; /*ammount correctly received so far*/ diff --git a/engine/libs/vorbis/vorbisfile.h b/engine/libs/vorbis/vorbisfile.h index de540cf7..ba2078f1 100644 --- a/engine/libs/vorbis/vorbisfile.h +++ b/engine/libs/vorbis/vorbisfile.h @@ -26,6 +26,11 @@ extern "C" #include #include "codec.h" +/*Spike: libvorbis internally uses cdecl. fte uses whatever the project settings are, so make sure this header is explicit so that everything still works.*/ +#ifndef VARGS +#define VARGS +#endif + /* The function prototypes for the callbacks are basically the same as for * the stdio functions fread, fseek, fclose, ftell. * The one difference is that the FILE * arguments have been replaced with @@ -37,10 +42,10 @@ extern "C" * unseekable */ typedef struct { - size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource); - int (*seek_func) (void *datasource, ogg_int64_t offset, int whence); - int (*close_func) (void *datasource); - long (*tell_func) (void *datasource); + size_t (VARGS *read_func) (void *ptr, size_t size, size_t nmemb, void *datasource); + int (VARGS *seek_func) (void *datasource, ogg_int64_t offset, int whence); + int (VARGS *close_func) (void *datasource); + long (VARGS *tell_func) (void *datasource); } ov_callbacks; #ifndef OV_EXCLUDE_STATIC_CALLBACKS @@ -73,31 +78,31 @@ static int _ov_header_fseek_wrap(FILE *f,ogg_int64_t off,int whence){ */ static ov_callbacks OV_CALLBACKS_DEFAULT = { - (size_t (*)(void *, size_t, size_t, void *)) fread, - (int (*)(void *, ogg_int64_t, int)) _ov_header_fseek_wrap, - (int (*)(void *)) fclose, - (long (*)(void *)) ftell + (size_t (VARGS *)(void *, size_t, size_t, void *)) fread, + (int (VARGS *)(void *, ogg_int64_t, int)) _ov_header_fseek_wrap, + (int (VARGS *)(void *)) fclose, + (long (VARGS *)(void *)) ftell }; static ov_callbacks OV_CALLBACKS_NOCLOSE = { - (size_t (*)(void *, size_t, size_t, void *)) fread, - (int (*)(void *, ogg_int64_t, int)) _ov_header_fseek_wrap, - (int (*)(void *)) NULL, - (long (*)(void *)) ftell + (size_t (VARGS *)(void *, size_t, size_t, void *)) fread, + (int (VARGS *)(void *, ogg_int64_t, int)) _ov_header_fseek_wrap, + (int (VARGS *)(void *)) NULL, + (long (VARGS *)(void *)) ftell }; static ov_callbacks OV_CALLBACKS_STREAMONLY = { - (size_t (*)(void *, size_t, size_t, void *)) fread, - (int (*)(void *, ogg_int64_t, int)) NULL, - (int (*)(void *)) fclose, - (long (*)(void *)) NULL + (size_t (VARGS *)(void *, size_t, size_t, void *)) fread, + (int (VARGS *)(void *, ogg_int64_t, int)) NULL, + (int (VARGS *)(void *)) fclose, + (long (VARGS *)(void *)) NULL }; static ov_callbacks OV_CALLBACKS_STREAMONLY_NOCLOSE = { - (size_t (*)(void *, size_t, size_t, void *)) fread, - (int (*)(void *, ogg_int64_t, int)) NULL, - (int (*)(void *)) NULL, - (long (*)(void *)) NULL + (size_t (VARGS *)(void *, size_t, size_t, void *)) fread, + (int (VARGS *)(void *, ogg_int64_t, int)) NULL, + (int (VARGS *)(void *)) NULL, + (long (VARGS *)(void *)) NULL }; #endif @@ -146,57 +151,57 @@ typedef struct OggVorbis_File { } OggVorbis_File; -extern int ov_clear(OggVorbis_File *vf); -extern int ov_fopen(const char *path,OggVorbis_File *vf); -extern int ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes); -extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf, +extern int VARGS ov_clear(OggVorbis_File *vf); +extern int VARGS ov_fopen(const char *path,OggVorbis_File *vf); +extern int VARGS ov_open(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes); +extern int VARGS ov_open_callbacks(void *datasource, OggVorbis_File *vf, const char *initial, long ibytes, ov_callbacks callbacks); -extern int ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes); -extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf, +extern int VARGS ov_test(FILE *f,OggVorbis_File *vf,const char *initial,long ibytes); +extern int VARGS ov_test_callbacks(void *datasource, OggVorbis_File *vf, const char *initial, long ibytes, ov_callbacks callbacks); -extern int ov_test_open(OggVorbis_File *vf); +extern int VARGS ov_test_open(OggVorbis_File *vf); -extern long ov_bitrate(OggVorbis_File *vf,int i); -extern long ov_bitrate_instant(OggVorbis_File *vf); -extern long ov_streams(OggVorbis_File *vf); -extern long ov_seekable(OggVorbis_File *vf); -extern long ov_serialnumber(OggVorbis_File *vf,int i); +extern long VARGS ov_bitrate(OggVorbis_File *vf,int i); +extern long VARGS ov_bitrate_instant(OggVorbis_File *vf); +extern long VARGS ov_streams(OggVorbis_File *vf); +extern long VARGS ov_seekable(OggVorbis_File *vf); +extern long VARGS ov_serialnumber(OggVorbis_File *vf,int i); -extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i); -extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i); -extern double ov_time_total(OggVorbis_File *vf,int i); +extern ogg_int64_t VARGS ov_raw_total(OggVorbis_File *vf,int i); +extern ogg_int64_t VARGS ov_pcm_total(OggVorbis_File *vf,int i); +extern double VARGS ov_time_total(OggVorbis_File *vf,int i); -extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos); -extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos); -extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos); -extern int ov_time_seek(OggVorbis_File *vf,double pos); -extern int ov_time_seek_page(OggVorbis_File *vf,double pos); +extern int VARGS ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos); +extern int VARGS ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos); +extern int VARGS ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos); +extern int VARGS ov_time_seek(OggVorbis_File *vf,double pos); +extern int VARGS ov_time_seek_page(OggVorbis_File *vf,double pos); -extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos); -extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos); -extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos); -extern int ov_time_seek_lap(OggVorbis_File *vf,double pos); -extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos); +extern int VARGS ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos); +extern int VARGS ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos); +extern int VARGS ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos); +extern int VARGS ov_time_seek_lap(OggVorbis_File *vf,double pos); +extern int VARGS ov_time_seek_page_lap(OggVorbis_File *vf,double pos); -extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf); -extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf); -extern double ov_time_tell(OggVorbis_File *vf); +extern ogg_int64_t VARGS ov_raw_tell(OggVorbis_File *vf); +extern ogg_int64_t VARGS ov_pcm_tell(OggVorbis_File *vf); +extern double VARGS ov_time_tell(OggVorbis_File *vf); -extern vorbis_info *ov_info(OggVorbis_File *vf,int link); -extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link); +extern vorbis_info *VARGS ov_info(OggVorbis_File *vf,int link); +extern vorbis_comment *VARGS ov_comment(OggVorbis_File *vf,int link); -extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples, +extern long VARGS ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples, int *bitstream); -extern long ov_read_filter(OggVorbis_File *vf,char *buffer,int length, +extern long VARGS ov_read_filter(OggVorbis_File *vf,char *buffer,int length, int bigendianp,int word,int sgned,int *bitstream, void (*filter)(float **pcm,long channels,long samples,void *filter_param),void *filter_param); -extern long ov_read(OggVorbis_File *vf,char *buffer,int length, +extern long VARGS ov_read(OggVorbis_File *vf,char *buffer,int length, int bigendianp,int word,int sgned,int *bitstream); -extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2); +extern int VARGS ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2); -extern int ov_halfrate(OggVorbis_File *vf,int flag); -extern int ov_halfrate_p(OggVorbis_File *vf); +extern int VARGS ov_halfrate(OggVorbis_File *vf,int flag); +extern int VARGS ov_halfrate_p(OggVorbis_File *vf); #ifdef __cplusplus } diff --git a/engine/nacl/sys_ppapi.c b/engine/nacl/sys_ppapi.c index 3460122f..29ba3ff2 100644 --- a/engine/nacl/sys_ppapi.c +++ b/engine/nacl/sys_ppapi.c @@ -160,6 +160,23 @@ void Sys_Shutdown(void) { } +//this is already done using the ppapi event callback. can't poll any of this stuff. +void INS_Move(float *movements, int pnum) +{ +} +void INS_Commands(void) +{ +} +void INS_Init(void) +{ +} +void INS_ReInit(void) +{ +} +void INS_Shutdown(void) +{ +} + //nacl supposedly has no way to implement this (other than us writing a listfile in each directory) int Sys_EnumerateFiles (const char *gpath, const char *match, int (*func)(const char *, int, void *), void *parm) { @@ -307,6 +324,7 @@ void startquake(void) "" }; quakeparms_t parms; + memset(&parms, 0, sizeof(parms)); parms.basedir = ""; /*filled in later*/ parms.argc = 1; parms.argv = args; @@ -406,9 +424,6 @@ unsigned int domkeytoquake(unsigned int code) return tab[code]; } -void IN_QueueKey(int down, int keycode, int unicode); -void IN_QueueMouse(int act, int ptrid, float x, float y, int button); -void IN_AmmendUnicode(int unicode); PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) { extern cvar_t vid_fullscreen; @@ -433,10 +448,10 @@ PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) return PP_TRUE; } } - IN_QueueMouse(1, 0, 0, 0, ppb_mouseinputevent_interface->GetButton(resource)); + IN_KeyEvent(0, true, K_MOUSE1 + ppb_mouseinputevent_interface->GetButton(resource), 0); return PP_TRUE; case PP_INPUTEVENT_TYPE_MOUSEUP: - IN_QueueMouse(2, 0, 0, 0, ppb_mouseinputevent_interface->GetButton(resource)); + IN_KeyEvent(0, false, K_MOUSE1 + ppb_mouseinputevent_interface->GetButton(resource), 0); return PP_TRUE; case PP_INPUTEVENT_TYPE_MOUSEMOVE: { @@ -444,12 +459,12 @@ PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) if (mouselocked) { p = ppb_mouseinputevent_interface->GetMovement(resource); - IN_QueueMouse(3, 0, p.x, p.y, 0); + IN_MouseMove(0, false, p.x, p.y, 0, 0); } else { p = ppb_mouseinputevent_interface->GetPosition(resource); - IN_QueueMouse(0, 0, p.x, p.y, 0); + IN_MouseMove(0, true, p.x, p.y, 0, 0); } } return PP_TRUE; @@ -468,14 +483,14 @@ PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) //BUG: the value is fractional. while (p.x >= 1) { - IN_QueueKey(1, K_MWHEELUP, 0); - IN_QueueKey(0, K_MWHEELUP, 0); + IN_KeyEvent(0, 1, K_MWHEELUP, 0); + IN_KeyEvent(0, 0, K_MWHEELUP, 0); p.x--; } while (p.x <= -1) { - IN_QueueKey(1, K_MWHEELDOWN, 0); - IN_QueueKey(0, K_MWHEELDOWN, 0); + IN_KeyEvent(0, 1, K_MWHEELDOWN, 0); + IN_KeyEvent(0, 0, K_MWHEELDOWN, 0); p.x++; } } @@ -484,10 +499,10 @@ PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) // Con_Printf("rawkeydown\n"); return PP_FALSE; case PP_INPUTEVENT_TYPE_KEYDOWN: - IN_QueueKey(1, domkeytoquake(ppb_keyboardinputevent_interface->GetKeyCode(resource)), 0); + IN_KeyEvent(0, 1, domkeytoquake(ppb_keyboardinputevent_interface->GetKeyCode(resource)), 0); return PP_FALSE; case PP_INPUTEVENT_TYPE_KEYUP: - IN_QueueKey(0, domkeytoquake(ppb_keyboardinputevent_interface->GetKeyCode(resource)), 0); + IN_KeyEvent(0, 0, domkeytoquake(ppb_keyboardinputevent_interface->GetKeyCode(resource)), 0); return PP_TRUE; case PP_INPUTEVENT_TYPE_CHAR: { @@ -540,7 +555,8 @@ PP_Bool InputEvent_HandleEvent(PP_Instance pp_instance, PP_Resource resource) len--; } - IN_AmmendUnicode(c); + IN_KeyEvent(0, true, 0, c); + IN_KeyEvent(0, false, 0, c); } } return PP_TRUE; diff --git a/engine/partcfgs/high.cfg b/engine/partcfgs/high.cfg index 53ca8b2d..b42b476e 100644 --- a/engine/partcfgs/high.cfg +++ b/engine/partcfgs/high.cfg @@ -295,9 +295,9 @@ r_part te_teleport float f; nst = scoord.xy / scoord.w; nst = (1.0 + nst)/2.0; - f = 1 - length(tcoord); -// f = 1 - tcoord*tcoord; - if (f < 0) discard; + f = 1.0 - length(tcoord); +// f = 1.0 - tcoord*tcoord; + if (f < 0.0) discard; f *= alph; gl_FragColor = texture2D(s_t0, nst - tcoord*f); } diff --git a/engine/qclib/comprout.c b/engine/qclib/comprout.c index a2a7a3bd..6a46203b 100644 --- a/engine/qclib/comprout.c +++ b/engine/qclib/comprout.c @@ -92,7 +92,7 @@ pbool CompileParams(progfuncs_t *progfuncs, int doall, int nump, char **parms) if (!externs->useeditor) printf("Error in %s on line %i\n", errorfile, errorline); else - externs->useeditor(progfuncs, errorfile, errorline, nump, parms); + externs->useeditor(progfuncs, errorfile, errorline, 0, nump, parms); } return false; } @@ -118,7 +118,7 @@ int Comp_Begin(progfuncs_t *progfuncs, int nump, char **parms) { PostCompile(); if (*errorfile) - externs->useeditor(progfuncs, errorfile, errorline, nump, parms); + externs->useeditor(progfuncs, errorfile, errorline, 0, nump, parms); return false; } @@ -135,7 +135,7 @@ int Comp_Continue(progfuncs_t *progfuncs) { PostCompile(); if (*errorfile && externs->useeditor) - externs->useeditor(progfuncs, errorfile, errorline, comp_nump, comp_parms); + externs->useeditor(progfuncs, errorfile, errorline, 0, comp_nump, comp_parms); return false; } @@ -146,7 +146,7 @@ int Comp_Continue(progfuncs_t *progfuncs) PostCompile(); if (*errorfile && externs->useeditor) - externs->useeditor(progfuncs, errorfile, errorline, comp_nump, comp_parms); + externs->useeditor(progfuncs, errorfile, errorline, 0 , comp_nump, comp_parms); return false; } diff --git a/engine/qclib/execloop.h b/engine/qclib/execloop.h index 208a79b3..970465dd 100644 --- a/engine/qclib/execloop.h +++ b/engine/qclib/execloop.h @@ -36,7 +36,7 @@ #endif #ifdef DEBUGABLE -#define OPCODE (st->op & ~0x8000) +#define OPCODE (pr_trace?(st->op & ~0x8000):st->op) #else #define OPCODE (st->op) #endif @@ -48,10 +48,35 @@ //rely upon just st { #ifdef DEBUGABLE -cont: //last statement may have been a breakpoint +cont: //last statement may have been a breakpoint s = st-pr_statements; s+=1; - s=ShowStep(progfuncs, s); + + if (prinst->watch_ptr && prinst->watch_ptr->_int != prinst->watch_old._int) + { + //this will fire on the next instruction after the variable got changed. + pr_xstatement = s; + switch(prinst->watch_type) + { + case ev_float: + printf("Watch point hit in %s, \"%s\" changed from %g to %g.\n", PR_StringToNative(progfuncs, pr_xfunction->s_name), prinst->watch_name, prinst->watch_old._float, prinst->watch_ptr->_float); + break; + default: + printf("Watch point hit in %s, \"%s\" changed from %i to %i.\n", PR_StringToNative(progfuncs, pr_xfunction->s_name), prinst->watch_name, prinst->watch_old._int, prinst->watch_ptr->_int); + break; + case ev_function: + case ev_string: + printf("Watch point hit in %s, \"%s\" now set to %s.\n", PR_StringToNative(progfuncs, pr_xfunction->s_name), prinst->watch_name, PR_ValueString(progfuncs, prinst->watch_type, prinst->watch_ptr)); + break; + } + prinst->watch_old = *prinst->watch_ptr; +// prinst->watch_ptr = NULL; + if (pr_trace<1) + pr_trace=1; //this is what it's for + } + + if (pr_trace) + s=ShowStep(progfuncs, s); st = pr_statements + s; reeval: @@ -313,14 +338,6 @@ reeval: break; case OP_STOREP_I: case OP_GSTOREP_I: - if ((unsigned int)OPB->_int >= prinst->addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", PR_StringToNative(progfuncs, pr_xfunction->s_name)); - } - ptr = QCPOINTER(OPB); - ptr->_int = OPA->_int; - break; case OP_STOREP_F: case OP_GSTOREP_F: case OP_STOREP_ENT: @@ -486,7 +503,7 @@ reeval: #ifndef DEBUGABLE //boot it over to the debugger pr_trace++; - printf("assignment to read-only entity in %s", PR_StringToNative(progfuncs, pr_xfunction->s_name)); + printf("assignment to read-only entity in %s\n", PR_StringToNative(progfuncs, pr_xfunction->s_name)); st--; goto cont; #else @@ -606,88 +623,91 @@ reeval: case OP_CALL2: case OP_CALL1: case OP_CALL0: - RUNAWAYCHECK(); - pr_xstatement = st-pr_statements; - - if (OPCODE > OP_CALL8) - pr_argc = OPCODE - (OP_CALL1H-1); - else - pr_argc = OPCODE - OP_CALL0; - fnum = OPA->function; - if ((fnum & ~0xff000000)==0) { - PR_RunError(progfuncs, "NULL function from qc (%s).\n", PR_StringToNative(progfuncs, pr_xfunction->s_name)); -#ifndef DEBUGABLE - goto cont; -#endif - break; - } -/* -{ - static char buffer[1024*1024*8]; - int size = sizeof buffer; - progfuncs->save_ents(progfuncs, buffer, &size, 0); -}*/ + int callerprogs; + int newpr; + unsigned int fnum; + RUNAWAYCHECK(); + pr_xstatement = st-pr_statements; - { - int callerprogs=pr_typecurrent; -//about to switch. needs caching. - - //if it's an external call, switch now (before any function pointers are used) - PR_MoveParms(progfuncs, (fnum & 0xff000000)>>24, callerprogs); - PR_SwitchProgs(progfuncs, (fnum & 0xff000000)>>24); - - newf = &pr_functions[fnum & ~0xff000000]; - - if (newf->first_statement < 0) - { // negative statements are built in functions - /*calling a builtin in another progs may affect that other progs' globals instead, is the theory anyway, so args and stuff need to move over*/ - if (pr_typecurrent != 0) - { - PR_MoveParms(progfuncs, 0, pr_typecurrent); - PR_SwitchProgs(progfuncs, 0); - } - i = -newf->first_statement; -// p = pr_typecurrent; - progfuncs->lastcalledbuiltinnumber = i; - if (i < externs->numglobalbuiltins) - { - prinst->numtempstringsstack = prinst->numtempstrings; - (*externs->globalbuiltins[i]) (progfuncs, (struct globalvars_s *)current_progstate->globals); - if (prinst->continuestatement!=-1) - { - st=&pr_statements[prinst->continuestatement]; - prinst->continuestatement=-1; - break; - } - } + if (OPCODE > OP_CALL8) + pr_argc = OPCODE - (OP_CALL1H-1); else + pr_argc = OPCODE - OP_CALL0; + fnum = OPA->function; + + callerprogs=pr_typecurrent; //so we can revert to the right caller. + newpr = (fnum & 0xff000000)>>24; //this is the progs index of the callee + fnum &= ~0xff000000; //the callee's function index. + + //if it's an external call, switch now (before any function pointers are used) + if (!PR_SwitchProgsParms(progfuncs, newpr) || !fnum || fnum > pr_progs->numfunctions) { - i -= externs->numglobalbuiltins; - if (i >= current_progstate->numbuiltins) + char *msg = fnum?"OP_CALL references invalid function in %s\n":"NULL function from qc (%s).\n"; + PR_SwitchProgsParms(progfuncs, callerprogs); + + //break/skip the instruction. + printf(msg, PR_StringToNative(progfuncs, pr_xfunction->s_name)); +#ifndef DEBUGABLE + pr_trace++; + st--; + goto cont; +#else + pr_globals[OFS_RETURN] = 0; + pr_globals[OFS_RETURN+1] = 0; + pr_globals[OFS_RETURN+2] = 0; + break; +#endif + } + + newf = &pr_functions[fnum & ~0xff000000]; + + if (newf->first_statement < 0) + { // negative statements are built in functions + /*calling a builtin in another progs may affect that other progs' globals instead, is the theory anyway, so args and stuff need to move over*/ + if (pr_typecurrent != 0) { -// if (newf->first_statement == -0x7fffffff) -// ((builtin_t)newf->profile) (progfuncs, (struct globalvars_s *)current_progstate->globals); -// else - PR_RunError (progfuncs, "Bad builtin call number - %i", -newf->first_statement); + PR_SwitchProgsParms(progfuncs, 0); + } + i = -newf->first_statement; + // p = pr_typecurrent; + progfuncs->lastcalledbuiltinnumber = i; + if (i < externs->numglobalbuiltins) + { + prinst->numtempstringsstack = prinst->numtempstrings; + (*externs->globalbuiltins[i]) (progfuncs, (struct globalvars_s *)current_progstate->globals); + if (prinst->continuestatement!=-1) + { + st=&pr_statements[prinst->continuestatement]; + prinst->continuestatement=-1; + break; + } } else - current_progstate->builtins [i] (progfuncs, (struct globalvars_s *)current_progstate->globals); - } - PR_MoveParms(progfuncs, callerprogs, pr_typecurrent); -// memcpy(&pr_progstate[p].globals[OFS_RETURN], ¤t_progstate->globals[OFS_RETURN], sizeof(vec3_t)); - PR_SwitchProgs(progfuncs, (progsnum_t)callerprogs); + { + i -= externs->numglobalbuiltins; + if (i >= current_progstate->numbuiltins) + { + // if (newf->first_statement == -0x7fffffff) + // ((builtin_t)newf->profile) (progfuncs, (struct globalvars_s *)current_progstate->globals); + // else + PR_RunError (progfuncs, "Bad builtin call number - %i", -newf->first_statement); + } + else + current_progstate->builtins [i] (progfuncs, (struct globalvars_s *)current_progstate->globals); + } + // memcpy(&pr_progstate[p].globals[OFS_RETURN], ¤t_progstate->globals[OFS_RETURN], sizeof(vec3_t)); + PR_SwitchProgsParms(progfuncs, (progsnum_t)callerprogs); -//#ifndef DEBUGABLE //decide weather non debugger wants to start debugging. - s = st-pr_statements; - goto restart; -//#endif -// break; - } -// PR_MoveParms((OPA->function & 0xff000000)>>24, pr_typecurrent); -// PR_SwitchProgs((OPA->function & 0xff000000)>>24); - s = PR_EnterFunction (progfuncs, newf, callerprogs); - st = &pr_statements[s]; + //#ifndef DEBUGABLE //decide weather non debugger wants to start debugging. + s = st-pr_statements; + goto restart; + //#endif + // break; + } + // PR_SwitchProgsParms((OPA->function & 0xff000000)>>24); + s = PR_EnterFunction (progfuncs, newf, callerprogs); + st = &pr_statements[s]; } goto restart; @@ -898,11 +918,11 @@ reeval: break; case OP_CSTATE: - externs->cstateop(progfuncs, OPA->_float, OPB->_float, fnum); + externs->cstateop(progfuncs, OPA->_float, OPB->_float, pr_xfunction - pr_functions); break; case OP_CWSTATE: - externs->cwstateop(progfuncs, OPA->_float, OPB->_float, fnum); + externs->cwstateop(progfuncs, OPA->_float, OPB->_float, pr_xfunction - pr_functions); break; case OP_THINKTIME: @@ -1127,7 +1147,7 @@ reeval: OPC->_int = (OPA->_float != OPB->_int); break; - case OP_GADDRESS: + case OP_GADDRESS: //return glob[aint+bfloat] case OP_GLOAD_I: case OP_GLOAD_F: case OP_GLOAD_FLD: diff --git a/engine/qclib/initlib.c b/engine/qclib/initlib.c index 0192bcc3..31266e6b 100644 --- a/engine/qclib/initlib.c +++ b/engine/qclib/initlib.c @@ -1057,6 +1057,7 @@ progfuncs_t deffuncs = { PR_memalloc, PR_AllocTempStringLen, PR_memfree, + PR_SetWatchPoint, }; #undef printf @@ -1154,6 +1155,8 @@ void CloseProgs(progfuncs_t *inst) f(inst->inst->tempstrings); inst->inst->tempstrings = NULL; + free(inst->inst->watch_name); + /* while(inst->prinst->extensionbuiltin) diff --git a/engine/qclib/pr_comp.h b/engine/qclib/pr_comp.h index 35590863..f508c089 100644 --- a/engine/qclib/pr_comp.h +++ b/engine/qclib/pr_comp.h @@ -434,15 +434,6 @@ typedef struct ddef32_s string_t s_name; } ddef32_t; -typedef struct fdef_s -{ - unsigned int type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - unsigned int ofs; - unsigned int progsofs; //used at loading time, so maching field offsets (unions/members) are positioned at the same runtime offset. - char * name; -} fdef_t; - typedef void *ddefXX_t; #else typedef struct QCC_ddef16_s diff --git a/engine/qclib/pr_edict.c b/engine/qclib/pr_edict.c index 9a750dcb..2bd7028e 100644 --- a/engine/qclib/pr_edict.c +++ b/engine/qclib/pr_edict.c @@ -224,6 +224,11 @@ fdef_t *ED_FieldAtOfs (progfuncs_t *progfuncs, unsigned int ofs) } return NULL; } +fdef_t *ED_FieldInfo (progfuncs_t *progfuncs, unsigned int *count) +{ + *count = numfields; + return field; +} /* ============ ED_FindField @@ -493,7 +498,7 @@ char *PR_ValueString (progfuncs_t *progfuncs, etype_t type, eval_t *val) else { if ((val->function & 0xff000000)>>24 >= (unsigned)maxprogs || !pr_progstate[(val->function & 0xff000000)>>24].functions) - sprintf (line, "Bad function"); + sprintf (line, "Bad function %i:%i", (val->function & 0xff000000)>>24, val->function & ~0xff000000); else { if ((val->function &~0xff000000) >= pr_progs->numfunctions) @@ -1028,6 +1033,88 @@ Can parse either fields or globals returns false if error ============= */ +pbool ED_ParseEval (progfuncs_t *progfuncs, eval_t *eval, int type, char *s) +{ + int i; + char string[128]; + fdef_t *def; + char *v, *w; + string_t st; + dfunction_t *func; + + switch (type & ~DEF_SAVEGLOBAL) + { + case ev_string: + st = PR_StringToProgs(progfuncs, ED_NewString (progfuncs, s, 0)); + eval->string = st; + break; + + case ev_float: + eval->_float = (float)atof (s); + break; + + case ev_integer: + eval->_int = atoi (s); + break; + + case ev_vector: + strncpy (string, s, sizeof(string)); + string[sizeof(string)-1] = 0; + v = string; + w = string; + for (i=0 ; i<3 ; i++) + { + while (*v && *v != ' ') + v++; + if (!*v) + { + eval->_vector[i] = (float)atof (w); + w = v; + } + else + { + *v = 0; + eval->_vector[i] = (float)atof (w); + w = v = v+1; + } + } + break; + + case ev_entity: + eval->edict = atoi (s); + break; + + case ev_field: + def = ED_FindField (progfuncs, s); + if (!def) + { + printf ("Can't find field %s\n", s); + return false; + } + eval->_int = def->ofs; + break; + + case ev_function: + if (s[1]==':'&&s[2]=='\0') + { + eval->function = 0; + return true; + } + func = ED_FindFunction (progfuncs, s, &i, -1); + if (!func) + { + printf ("Can't find function %s\n", s); + return false; + } + eval->function = (func - pr_progstate[i].functions) | (i<<24); + break; + + default: + return false; + } + return true; +} + pbool ED_ParseEpair (progfuncs_t *progfuncs, int qcptr, unsigned int fldofs, int fldtype, char *s) { int i; @@ -1810,6 +1897,8 @@ int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) free(oldglobals); oldglobals = NULL; } + + PR_SwitchProgs(progfuncs, 0); } else if (!strcmp(qcc_token, "globals")) { @@ -1855,8 +1944,8 @@ int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) case PST_KKQWSV: if (!(d16 = ED_FindGlobal16(progfuncs, qcc_token))) { + printf("global value %s not found\n", qcc_token); file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); } else { @@ -1868,8 +1957,8 @@ int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) case PST_FTE32: if (!(d32 = ED_FindGlobal32(progfuncs, qcc_token))) { + printf("global value %s not found\n", qcc_token); file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); } else { @@ -1881,6 +1970,7 @@ int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) Sys_Error("Bad struct type in LoadEnts"); } } + PR_SwitchProgs(progfuncs, 0); // file = QCC_COM_Parse(file); // if (com_token[0] != '}') @@ -1969,8 +2059,8 @@ int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) case PST_KKQWSV: if (!(d16 = ED_FindGlobal16(progfuncs, qcc_token))) { + printf("global value %s not found\n", qcc_token); file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); } else { @@ -1982,8 +2072,8 @@ int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) case PST_FTE32: if (!(d32 = ED_FindGlobal32(progfuncs, qcc_token))) { + printf("global value %s not found\n", qcc_token); file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); } else { diff --git a/engine/qclib/pr_exec.c b/engine/qclib/pr_exec.c index fb82d5d6..29e08230 100644 --- a/engine/qclib/pr_exec.c +++ b/engine/qclib/pr_exec.c @@ -65,7 +65,7 @@ static void PR_PrintStatement (progfuncs_t *progfuncs, int statementnum) } else #endif - printf ("op%3i "); + printf ("op%3i ", op); if (op == OP_IF_F || op == OP_IFNOT_F) printf ("%sbranch %i",PR_GlobalString(progfuncs, arg[0]),arg[1]); @@ -90,6 +90,135 @@ static void PR_PrintStatement (progfuncs_t *progfuncs, int statementnum) printf ("\n"); } +#ifdef _WIN32 +static void VARGS QC_snprintfz (char *dest, size_t size, const char *fmt, ...) +{ + va_list args; + va_start (args, fmt); + vsnprintf (dest, size-1, fmt, args); + va_end (args); + //make sure its terminated. + dest[size-1] = 0; +} +#else +#define QC_snprintfz snprintf +#endif + +void PR_GenerateStatementString (progfuncs_t *progfuncs, int statementnum, char *out, int outlen) +{ + int i; + unsigned int op; + unsigned int arg[3]; + + *out = 0; + outlen--; + + switch(current_progstate->structtype) + { + case PST_DEFAULT: + case PST_QTEST: + op = ((dstatement16_t*)current_progstate->statements + statementnum)->op; + arg[0] = ((dstatement16_t*)current_progstate->statements + statementnum)->a; + arg[1] = ((dstatement16_t*)current_progstate->statements + statementnum)->b; + arg[2] = ((dstatement16_t*)current_progstate->statements + statementnum)->c; + break; + case PST_KKQWSV: + case PST_FTE32: + op = ((dstatement32_t*)current_progstate->statements + statementnum)->op; + arg[0] = ((dstatement32_t*)current_progstate->statements + statementnum)->a; + arg[1] = ((dstatement32_t*)current_progstate->statements + statementnum)->b; + arg[2] = ((dstatement32_t*)current_progstate->statements + statementnum)->c; + break; + } + + if (current_progstate->linenums) + { + QC_snprintfz (out, outlen, "%3i: ", current_progstate->linenums[statementnum]); + outlen -= strlen(out); + out += strlen(out); + } + else + { + QC_snprintfz (out, outlen, "%3i: ", statementnum); + outlen -= strlen(out); + out += strlen(out); + } + +#ifndef MINIMAL + if ( (unsigned)op < OP_NUMOPS) + { + QC_snprintfz (out, outlen, "%s", pr_opcodes[op].name); + outlen -= strlen(out); + out += strlen(out); + QC_snprintfz (out, outlen, " "); + outlen -= 1; + out += 1; + + QC_snprintfz (out, outlen, "%s ", pr_opcodes[op].name); + i = strlen(pr_opcodes[op].name); + for ( ; i<10 ; i++) + { + QC_snprintfz (out, outlen, " "); + outlen -= 1; + out += 1; + } + } + else +#endif + { + QC_snprintfz (out, outlen, "op%3i ", op); + outlen -= strlen(out); + out += strlen(out); + } + + if (op == OP_IF_F || op == OP_IFNOT_F) + { + QC_snprintfz (out, outlen, "%sbranch %i",PR_GlobalString(progfuncs, arg[0]),arg[1]); + outlen -= strlen(out); + out += strlen(out); + } + else if (op == OP_GOTO) + { + QC_snprintfz (out, outlen, "branch %i",arg[0]); + outlen -= strlen(out); + out += strlen(out); + } + else if ( (unsigned)(op - OP_STORE_F) < 6) + { + QC_snprintfz (out, outlen, "%s",PR_GlobalString(progfuncs, arg[0])); + outlen -= strlen(out); + out += strlen(out); + QC_snprintfz (out, outlen, "%s", PR_GlobalStringNoContents(progfuncs, arg[1])); + outlen -= strlen(out); + out += strlen(out); + } + else + { + if (arg[0]) + { + QC_snprintfz (out, outlen, "%s",PR_GlobalString(progfuncs, arg[0])); + outlen -= strlen(out); + out += strlen(out); + } + if (arg[1]) + { + QC_snprintfz (out, outlen, "%s",PR_GlobalString(progfuncs, arg[1])); + outlen -= strlen(out); + out += strlen(out); + } + if (arg[2]) + { + QC_snprintfz (out, outlen, "%s", PR_GlobalStringNoContents(progfuncs, arg[2])); + outlen -= strlen(out); + out += strlen(out); + } + } + QC_snprintfz (out, outlen, "\n"); + outlen -= 1; + out += 1; +} + + /* ============ PR_StackTrace @@ -351,8 +480,7 @@ int ASMCALL PR_LeaveFunction (progfuncs_t *progfuncs) // up stack pr_depth--; - PR_MoveParms(progfuncs, pr_stack[pr_depth].progsnum, pr_typecurrent); - PR_SwitchProgs(progfuncs, pr_stack[pr_depth].progsnum); + PR_SwitchProgsParms(progfuncs, pr_stack[pr_depth].progsnum); pr_xfunction = pr_stack[pr_depth].f; pr_spushed = pr_stack[pr_depth].pushed; @@ -376,7 +504,7 @@ ddef32_t *ED_FindLocalOrGlobal(progfuncs_t *progfuncs, char *name, eval_t **val) case PST_KKQWSV: //this gets parms fine, but not locals if (pr_xfunction) - for (i = 0; i < pr_xfunction->numparms; i++) + for (i = 0; i < pr_xfunction->locals; i++) { def16 = ED_GlobalAtOfs16(progfuncs, pr_xfunction->parm_start+i); if (!def16) @@ -449,23 +577,132 @@ char *COM_TrimString(char *str) return buffer; } +pbool LocateDebugTerm(progfuncs_t *progfuncs, char *key, eval_t **result, etype_t *rettype, eval_t *store) +{ + ddef32_t *def; + fdef_t *fdef; + eval_t *val = NULL; + char *c, *c2; + etype_t type = ev_void; + struct edictrun_s *ed; + + c = strchr(key, '.'); + if (c) *c = '\0'; + def = ED_FindLocalOrGlobal(progfuncs, key, &val); + if (!def) + { + if (*key == '\'') + { + type = ev_vector; + val = store; + val->_vector[0] = 0; + val->_vector[1] = 0; + val->_vector[2] = 0; + } + else if (*key == '\"') + { + type = ev_string; + val = store; + val->string = 0; + } + else if (atoi(key)) + { + type = ev_entity; + val = store; + val->edict = atoi(key); + } + } + else + type = def->type; + + if (c) *c = '.'; + if (!val) + { + return false; + } + + //go through ent vars + c = strchr(key, '.'); + while(c) + { + c2 = c+1; + c = strchr(c2, '.'); + type = type &~DEF_SAVEGLOBAL; + if (current_progstate && current_progstate->types) + type = current_progstate->types[type].type; + if (type != ev_entity) + return false; + if (c)*c = '\0'; + fdef = ED_FindField(progfuncs, COM_TrimString(c2)); + if (c)*c = '.'; + if (!fdef) + return false; + ed = PROG_TO_EDICT(progfuncs, val->_int); + if (!ed) + return false; + val = (eval_t *) (((char *)ed->fields) + fdef->ofs*4); + type = fdef->type; + } + *rettype = type; + *result = val; + return true; +} + +pbool PR_SetWatchPoint(progfuncs_t *progfuncs, char *key) +{ + eval_t *val; + eval_t fakeval; + etype_t type; + + if (!key) + { + free(prinst->watch_name); + prinst->watch_name = NULL; + prinst->watch_ptr = NULL; + prinst->watch_type = ev_void; + return false; + } + if (!LocateDebugTerm(progfuncs, key, &val, &type, &fakeval)) + { + printf("Unable to evaluate watch term \"%s\"\n", key); + return false; + } + if (val == &fakeval) + { + printf("Do you like watching paint dry?\n"); + return false; + } + if (type == ev_vector) + { + printf("Unable to watch vectors. Watching the x field instead.\n"); + type = ev_float; + } + + free(prinst->watch_name); + prinst->watch_name = strdup(key); + prinst->watch_ptr = val; + prinst->watch_old = *prinst->watch_ptr; + prinst->watch_type = type; + return true; +} + char *EvaluateDebugString(progfuncs_t *progfuncs, char *key) { static char buf[256]; - char *c, *c2; - ddef32_t *def; fdef_t *fdef; eval_t *val; char *assignment; - int type; - ddef32_t fakedef; + etype_t type; eval_t fakeval; - edictrun_t *ed; assignment = strchr(key, '='); if (assignment) *assignment = '\0'; + if (!LocateDebugTerm(progfuncs, key, &val, &type, &fakeval)) + return "(unable to evaluate)"; + + /* c = strchr(key, '.'); if (c) *c = '\0'; def = ED_FindLocalOrGlobal(progfuncs, key, &val); @@ -509,7 +746,7 @@ char *EvaluateDebugString(progfuncs_t *progfuncs, char *key) val = (eval_t *) (((char *)ed->fields) + fdef->ofs*4); type = fdef->type; } - +*/ if (assignment) { assignment++; @@ -835,15 +1072,24 @@ static char *lastfile = 0; return statement; } - if (f && pr_progstate[pn].linenums && externs->useeditor) + if (f && externs->useeditor) { - if (lastline == pr_progstate[pn].linenums[statement] && lastfile == f->s_file+progfuncs->stringtable) - return statement; //no info/same line as last time + if (pr_progstate[pn].linenums) + { + if (lastline == pr_progstate[pn].linenums[statement] && lastfile == f->s_file+progfuncs->stringtable) + return statement; //no info/same line as last time - lastline = pr_progstate[pn].linenums[statement]; + lastline = pr_progstate[pn].linenums[statement]; + } + else + lastline = -1; lastfile = f->s_file+progfuncs->stringtable; - lastline = externs->useeditor(progfuncs, lastfile, lastline, 0, NULL); + lastline = externs->useeditor(progfuncs, lastfile, lastline, statement, 0, NULL); + if (lastline < 0) + return -lastline; + if (!pr_progstate[pn].linenums) + return statement; if (pr_progstate[pn].linenums[statement] != lastline) { @@ -864,7 +1110,7 @@ static char *lastfile = 0; { if (*(f->s_file+progfuncs->stringtable)) //if we can't get the filename, then it was stripped, and debugging it like this is useless if (externs->useeditor) - externs->useeditor(progfuncs, f->s_file+progfuncs->stringtable, -1, 0, NULL); + externs->useeditor(progfuncs, f->s_file+progfuncs->stringtable, -1, 0, 0, NULL); return statement; } @@ -895,6 +1141,29 @@ void PR_ExecuteCode (progfuncs_t *progfuncs, int s) int fnum; + if (prinst->watch_ptr && prinst->watch_ptr->_int != prinst->watch_old._int) + { + switch(prinst->watch_type) + { + case ev_float: + printf("Watch point \"%s\" changed by engine from %g to %g.\n", prinst->watch_name, prinst->watch_old._float, prinst->watch_ptr->_float); + break; + default: + printf("Watch point \"%s\" changed by engine from %i to %i.\n", prinst->watch_name, prinst->watch_old._int, prinst->watch_ptr->_int); + break; + case ev_function: + case ev_string: + printf("Watch point \"%s\" set by engine to %s.\n", prinst->watch_name, PR_ValueString(progfuncs, prinst->watch_type, prinst->watch_ptr)); + break; + } + prinst->watch_old = *prinst->watch_ptr; + + //we can't dump stack or anything, as we don't really know the stack frame that it happened in. + + //stop watching + prinst->watch_ptr = NULL; + } + prinst->continuestatement = -1; #ifdef QCJIT if (current_progstate->jit) @@ -932,7 +1201,7 @@ restart: //jumped to when the progs might have changed. case PST_QTEST: #define INTSIZE 16 st16 = &pr_statements16[s]; - while (pr_trace) + while (pr_trace || prinst->watch_ptr) { #define DEBUGABLE #ifdef SEPARATEINCLUDES @@ -954,7 +1223,7 @@ restart: //jumped to when the progs might have changed. case PST_FTE32: #define INTSIZE 32 st32 = &pr_statements32[s]; - while (pr_trace) + while (pr_trace || prinst->watch_ptr) { #define DEBUGABLE #ifdef SEPARATEINCLUDES @@ -1003,8 +1272,7 @@ void PR_ExecuteProgram (progfuncs_t *progfuncs, func_t fnum) printf("PR_ExecuteProgram: tried branching into invalid progs\n"); return; } - PR_MoveParms(progfuncs, newprogs, pr_typecurrent); - PR_SwitchProgs(progfuncs, newprogs); + PR_SwitchProgsParms(progfuncs, newprogs); } if (!(fnum & ~0xff000000) || (signed)(fnum & ~0xff000000) >= pr_progs->numfunctions) @@ -1041,8 +1309,7 @@ void PR_ExecuteProgram (progfuncs_t *progfuncs, func_t fnum) } current_progstate->builtins [i] (progfuncs, (struct globalvars_s *)current_progstate->globals); } - PR_MoveParms(progfuncs, initial_progs, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); + PR_SwitchProgsParms(progfuncs, initial_progs); return; } @@ -1059,8 +1326,7 @@ void PR_ExecuteProgram (progfuncs_t *progfuncs, func_t fnum) PR_ExecuteCode(progfuncs, s); - PR_MoveParms(progfuncs, initial_progs, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); + PR_SwitchProgsParms(progfuncs, initial_progs); PR_FreeTemps(progfuncs, tempdepth); prinst->numtempstringsstack = tempdepth; @@ -1179,8 +1445,7 @@ void PR_ResumeThread (progfuncs_t *progfuncs, struct qcthread_s *thread) //do progs switching stuff as appropriate. (fteqw only) initial_progs = pr_typecurrent; - PR_MoveParms(progfuncs, prnum, pr_typecurrent); - PR_SwitchProgs(progfuncs, prnum); + PR_SwitchProgsParms(progfuncs, prnum); oldexitdepth = prinst->exitdepth; @@ -1242,8 +1507,7 @@ void PR_ResumeThread (progfuncs_t *progfuncs, struct qcthread_s *thread) PR_ExecuteCode(progfuncs, s); - PR_MoveParms(progfuncs, initial_progs, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); + PR_SwitchProgsParms(progfuncs, initial_progs); PR_FreeTemps(progfuncs, tempdepth); prinst->numtempstringsstack = tempdepth; diff --git a/engine/qclib/pr_multi.c b/engine/qclib/pr_multi.c index 334536ec..13055312 100644 --- a/engine/qclib/pr_multi.c +++ b/engine/qclib/pr_multi.c @@ -16,6 +16,7 @@ sharedvar_t *shares; //shared globals, not including parms int maxshares; */ +//switches progs without preserving parms/ret/shared pbool PR_SwitchProgs(progfuncs_t *progfuncs, progsnum_t type) { if ((unsigned)type >= maxprogs) @@ -40,22 +41,30 @@ pbool PR_SwitchProgs(progfuncs_t *progfuncs, progsnum_t type) return true; } -void PR_MoveParms(progfuncs_t *progfuncs, progsnum_t newpr, progsnum_t oldpr) //from 2 to 1 +//switch to new progs, preserving all arguments. oldpr should be 'pr_typecurrent' +pbool PR_SwitchProgsParms(progfuncs_t *progfuncs, progsnum_t newpr) //from 2 to 1 { unsigned int a; progstate_t *np; progstate_t *op; + int oldpr = pr_typecurrent; if (newpr == oldpr) - return; //don't bother coping variables to themselves... + { + //don't bother coping variables to themselves... + return true; + } np = &pr_progstate[(int)newpr]; op = &pr_progstate[(int)oldpr]; if ((unsigned)newpr >= maxprogs || !np->globals) - PR_RunError(progfuncs, "QCLIB: Bad prog type - %i", newpr); - if ((unsigned)oldpr >= maxprogs || !op->globals) - return; + { + printf("QCLIB: Bad prog type - %i", newpr); + return false; + } + if ((unsigned)oldpr >= maxprogs || !op->globals) //startup? + return PR_SwitchProgs(progfuncs, newpr); //copy parms. for (a = 0; a < MAX_PARMS;a++) @@ -81,6 +90,7 @@ void PR_MoveParms(progfuncs_t *progfuncs, progsnum_t newpr, progsnum_t oldpr) // } */ } + return PR_SwitchProgs(progfuncs, newpr); } progsnum_t PR_LoadProgs(progfuncs_t *progfuncs, char *s, int headercrc, builtin_t *builtins, int numbuiltins) diff --git a/engine/qclib/progsint.h b/engine/qclib/progsint.h index 060d1e84..0f0f6075 100644 --- a/engine/qclib/progsint.h +++ b/engine/qclib/progsint.h @@ -150,6 +150,7 @@ typedef struct edictrun_s int Comp_Begin(progfuncs_t *progfuncs, int nump, char **parms); int Comp_Continue(progfuncs_t *progfuncs); +pbool PR_SetWatchPoint(progfuncs_t *progfuncs, char *key); char *EvaluateDebugString(progfuncs_t *progfuncs, char *key); char *SaveEnts(progfuncs_t *progfuncs, char *mem, int *size, int mode); int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags); @@ -303,7 +304,7 @@ void ED_PrintNum (progfuncs_t *progfuncs, int ent); pbool PR_SwitchProgs(progfuncs_t *progfuncs, progsnum_t type); -void PR_MoveParms(progfuncs_t *progfuncs, progsnum_t progs1, progsnum_t progs2); +pbool PR_SwitchProgsParms(progfuncs_t *progfuncs, progsnum_t newprogs); @@ -366,6 +367,11 @@ var(unsigned int, maxprogs); var(progstate_t *,current_progstate); #define current_progstate prinst->current_progstate +var(char *, watch_name); +var(eval_t *, watch_ptr); +var(eval_t, watch_old); +var(etype_t, watch_type); + var(unsigned int, numshares); #define numshares prinst->numshares var(sharedvar_t *,shares); //shared globals, not including parms diff --git a/engine/qclib/progslib.h b/engine/qclib/progslib.h index 543f64ab..32277df8 100644 --- a/engine/qclib/progslib.h +++ b/engine/qclib/progslib.h @@ -43,6 +43,15 @@ typedef struct { #define sizeofevalc sizeof(evalc_t) typedef enum {ev_void, ev_string, ev_float, ev_vector, ev_entity, ev_field, ev_function, ev_pointer, ev_integer, ev_variant, ev_struct, ev_union} etype_t; +typedef struct fdef_s +{ + unsigned int type; // if DEF_SAVEGLOBAL bit is set + // the variable needs to be saved in savegames + unsigned int ofs; + unsigned int progsofs; //used at loading time, so maching field offsets (unions/members) are positioned at the same runtime offset. + char * name; +} fdef_t; + //the number of pointers to variables (as opposed to functions - those are fine) in these structures is excessive. //Many of the functions are also obsolete. struct progfuncs_s { @@ -143,6 +152,7 @@ struct progfuncs_s { string_t (*AllocTempString) (progfuncs_t *prinst, char **str, unsigned int len); void (*AddressableFree) (progfuncs_t *progfuncs, void *mem); /*frees a block of addressable memory*/ + pbool (*SetWatchPoint) (progfuncs_t *prinst, char *key); }; typedef struct progexterns_s { @@ -183,7 +193,7 @@ typedef struct progexterns_s { struct edict_s **sv_edicts; //pointer to the engine's reference to world. unsigned int *sv_num_edicts; //pointer to the engine's edict count. - int (*useeditor) (progfuncs_t *prinst, char *filename, int line, int nump, char **parms); //called on syntax errors or step-by-step debugging. + int (*useeditor) (progfuncs_t *prinst, char *filename, int line, int statement, int nump, char **parms); //called on syntax errors or step-by-step debugging. void (*addressablerelocated) (progfuncs_t *progfuncs, char *oldb, char *newb, int oldlen); //called when the progs memory was resized. you must fix up all pointers to globals, strings, fields, addressable blocks. void *user; /*contains the owner's world reference in FTE*/ diff --git a/engine/qclib/qcc.h b/engine/qclib/qcc.h index 1ee2ac62..e60d358e 100644 --- a/engine/qclib/qcc.h +++ b/engine/qclib/qcc.h @@ -436,6 +436,8 @@ tt_immediate, // string, float, vector extern char pr_token[8192]; extern token_type_t pr_token_type; +extern int pr_token_line; +extern int pr_token_line_last; extern QCC_type_t *pr_immediate_type; extern QCC_eval_t pr_immediate; diff --git a/engine/qclib/qcc_pr_comp.c b/engine/qclib/qcc_pr_comp.c index e7ce47a3..fdbbd047 100644 --- a/engine/qclib/qcc_pr_comp.c +++ b/engine/qclib/qcc_pr_comp.c @@ -2412,7 +2412,7 @@ QCC_def_t *QCC_PR_Statement (QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_ statement->c = statements[st].c; /*convert old one to an OP_LOAD*/ - statement_linenums[st] = pr_source_line; + statement_linenums[st] = pr_token_line_last; statements[st].op = ((*op->type_c)->type==ev_vector)?OP_LOAD_V:OP_LOAD_F; statements[st].a = statements[st].a; statements[st].b = statements[st].b; @@ -2423,7 +2423,7 @@ QCC_def_t *QCC_PR_Statement (QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_ statement = &statements[numstatements]; numstatements++; - statement_linenums[statement-statements] = pr_source_line; + statement_linenums[statement-statements] = pr_token_line_last; switch(op - pr_opcodes) { case OP_SUBSTOREP_V: @@ -2497,7 +2497,7 @@ QCC_def_t *QCC_PR_Statement (QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_ statement = &statements[numstatements]; numstatements++; - statement_linenums[statement-statements] = pr_source_line; + statement_linenums[statement-statements] = pr_token_line_last; statement->op = OP_SUB_F; //t = c & i @@ -2544,7 +2544,7 @@ QCC_def_t *QCC_PR_Statement (QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_ if (outstatement) *outstatement = statement; - statement_linenums[statement-statements] = pr_source_line; + statement_linenums[statement-statements] = pr_token_line_last; statement->op = op - pr_opcodes; statement->a = var_a ? var_a->ofs : 0; statement->b = var_b ? var_b->ofs : 0; @@ -2602,7 +2602,7 @@ QCC_dstatement_t *QCC_PR_SimpleStatement( int op, int var_a, int var_b, int var_ QCC_PR_ParseError(ERR_BADEXTENSION, "Opcode \"%s|%s\" not valid for target\n", pr_opcodes[op].name, pr_opcodes[op].opname); } - statement_linenums[numstatements] = pr_source_line; + statement_linenums[numstatements] = pr_token_line_last; statement = &statements[numstatements]; numstatements++; @@ -2627,7 +2627,7 @@ void QCC_PR_Statement3 ( QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_b, Q statement = &statements[numstatements]; numstatements++; - statement_linenums[statement-statements] = pr_source_line; + statement_linenums[statement-statements] = pr_token_line_last; statement->op = op - pr_opcodes; statement->a = var_a ? var_a->ofs : 0; statement->b = var_b ? var_b->ofs : 0; @@ -3771,7 +3771,7 @@ QCC_def_t *QCC_PR_ParseFunctionCall (QCC_def_t *func) //warning, the func could e = QCC_PR_Statement(pr_opcodes+OP_CONV_ITOF, e, NULL, NULL); else if ((p->type == ev_function && p->type == ev_string) && e->type->type == ev_integer && e->constant && !((int*)qcc_pr_globals)[e->ofs]) { //you're allowed to use int 0 to pass a null function pointer - //this is basically because __NULL__ is defined as ~0 (int 0) + //this is basically because __NULL__ is defined as 0i (int 0) } else if (p->type != ev_variant && e->type->type != ev_variant) //can cast to variant whatever happens { @@ -4494,7 +4494,7 @@ QCC_def_t *QCC_PR_ParseArrayPointer (QCC_def_t *d, pbool allowarrayassign) tmp = (void *)qccHunkAlloc (sizeof(QCC_def_t)); memcpy (tmp, d, sizeof(QCC_def_t)); tmp->arraysize = 0; - tmp->ofs = d->ofs + (cidx * type_size[d->type->type]); + tmp->ofs = d->ofs + cidx; d = tmp; //d can be assigned to freely @@ -4535,7 +4535,8 @@ QCC_def_t *QCC_PR_ParseArrayPointer (QCC_def_t *d, pbool allowarrayassign) // st->a = d->ofs; break; case ev_vector: - d = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_V], d, QCC_SupplyConversion(idx, ev_float, true), &st); //get pointer to precise def. + idx = QCC_PR_Statement(&pr_opcodes[OP_DIV_F], QCC_SupplyConversion(idx, ev_float, true), QCC_MakeFloatConst(3), NULL); + d = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_V], d, idx, &st); //get pointer to precise def. // st->a = d->ofs; break; case ev_string: @@ -4571,7 +4572,7 @@ QCC_def_t *QCC_PR_ParseArrayPointer (QCC_def_t *d, pbool allowarrayassign) def_parms[0].type = type_vector; funcretr = QCC_PR_GetDef(type_function, qcva("ArrayGet*%s", d->name), NULL, true, 0, false); - args[0] = QCC_SupplyConversion(idx, ev_float, true); + args[0] = QCC_PR_Statement(&pr_opcodes[OP_DIV_F], QCC_SupplyConversion(idx, ev_float, true), QCC_MakeFloatConst(3), NULL); d = QCC_PR_GenerateFunctionCall(funcretr, args, 1); d->type = t; } @@ -7357,19 +7358,28 @@ void QCC_WriteAsmFunction(QCC_def_t *sc, unsigned int firststatement, gofs_t fir if (strlen(pr_opcodes[statements[i].op].opname)<6) fprintf(asmfile, "\t"); if (pr_opcodes[statements[i].op].type_a) + { fprintf(asmfile, "\t%s", QCC_VarAtOffset(statements[i].a, (*pr_opcodes[statements[i].op].type_a)->size)); + fprintf(asmfile, "/*%i*/", statements[i].a); + } else fprintf(asmfile, "\t%i", statements[i].a); if (pr_opcodes[statements[i].op].type_b != &type_void) { if (pr_opcodes[statements[i].op].type_b) + { fprintf(asmfile, ",\t%s", QCC_VarAtOffset(statements[i].b, (*pr_opcodes[statements[i].op].type_b)->size)); + fprintf(asmfile, "/*%i*/", statements[i].b); + } else fprintf(asmfile, ",\t%i", statements[i].b); if (pr_opcodes[statements[i].op].type_c != &type_void && pr_opcodes[statements[i].op].associative==ASSOC_LEFT) { if (pr_opcodes[statements[i].op].type_c) + { fprintf(asmfile, ",\t%s", QCC_VarAtOffset(statements[i].c, (*pr_opcodes[statements[i].op].type_c)->size)); + fprintf(asmfile, "/*%i*/", statements[i].c); + } else fprintf(asmfile, ",\t%i", statements[i].c); } @@ -7379,7 +7389,10 @@ void QCC_WriteAsmFunction(QCC_def_t *sc, unsigned int firststatement, gofs_t fir if (pr_opcodes[statements[i].op].type_c != &type_void) { if (pr_opcodes[statements[i].op].type_c) + { fprintf(asmfile, ",\t%s", QCC_VarAtOffset(statements[i].c, (*pr_opcodes[statements[i].op].type_c)->size)); + fprintf(asmfile, "/*%i*/", statements[i].c); + } else fprintf(asmfile, ",\t%i", statements[i].c); } @@ -8264,7 +8277,15 @@ QCC_def_t *QCC_PR_GetDef (QCC_type_t *type, char *name, QCC_def_t *scope, pbool if (type && typecmp(def->type, type)) { if (!pr_scope) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHREDEC, def, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); + { + if (typecmp_lax(def->type, type)) + { + //unequal even when we're lax + QCC_PR_ParseError (ERR_TYPEMISMATCHREDEC, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); + } + else + QCC_PR_ParseWarning (WARN_LAXCAST, "Optional arguments differ on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); + } } if (def->arraysize != arraysize && arraysize>=0) QCC_PR_ParseErrorPrintDef(ERR_TYPEMISMATCHARRAYSIZE, def, "Array sizes for redecleration of %s do not match",name); @@ -8334,7 +8355,15 @@ QCC_def_t *QCC_PR_GetDef (QCC_type_t *type, char *name, QCC_def_t *scope, pbool if (type && typecmp(def->type, type)) { if (!pr_scope) - QCC_PR_ParseError (ERR_TYPEMISMATCHREDEC, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); + { + if (typecmp_lax(def->type, type)) + { + //unequal even when we're lax + QCC_PR_ParseError (ERR_TYPEMISMATCHREDEC, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); + } + else + QCC_PR_ParseWarning (WARN_LAXCAST, "Optional arguments differ on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); + } } if (def->arraysize != arraysize && arraysize>=0) QCC_PR_ParseError (ERR_TYPEMISMATCHARRAYSIZE, "Array sizes for redecleration of %s do not match",name); diff --git a/engine/qclib/qcc_pr_lex.c b/engine/qclib/qcc_pr_lex.c index 7a4319ba..f7590755 100644 --- a/engine/qclib/qcc_pr_lex.c +++ b/engine/qclib/qcc_pr_lex.c @@ -22,7 +22,7 @@ void QCC_PR_ConditionCompilation(void); pbool QCC_PR_UndefineName(char *name); -char *QCC_PR_CheakCompConstString(char *def); +char *QCC_PR_CheckCompConstString(char *def); CompilerConstant_t *QCC_PR_CheckCompConstDefined(char *def); pbool QCC_Include(char *filename); @@ -37,6 +37,8 @@ int pr_bracelevel; char pr_token[8192]; token_type_t pr_token_type; +int pr_token_line; +int pr_token_line_last; QCC_type_t *pr_immediate_type; QCC_eval_t pr_immediate; @@ -180,9 +182,10 @@ void QCC_FindBestInclude(char *newfile, char *currentfile, char *rootpath) doubledots++; } +#if 0 currentfile += strlen(rootpath); //could this be bad? - strcpy(fullname, rootpath); + end = fullname+strlen(end); if (*fullname && end[-1] != '/') { @@ -191,6 +194,10 @@ void QCC_FindBestInclude(char *newfile, char *currentfile, char *rootpath) } strcpy(end, currentfile); end = end+strlen(end); +#else + strcpy(fullname, currentfile); + end = fullname+strlen(fullname); +#endif while (end > fullname) { @@ -1313,7 +1320,7 @@ void QCC_PR_LexString (void) c = *end; *end = '\0'; - cnst = QCC_PR_CheakCompConstString(pr_file_p); + cnst = QCC_PR_CheckCompConstString(pr_file_p); if (cnst==pr_file_p) cnst=NULL; *end = c; @@ -2177,7 +2184,7 @@ static void QCC_PR_ExpandStrCat(char **buffer, int *bufferlen, int *buffermax, /*no null terminator, remember to cat one if required*/ } -int QCC_PR_CheakCompConst(void) +int QCC_PR_CheckCompConst(void) { char *oldpr_file_p = pr_file_p; int whitestart; @@ -2470,7 +2477,7 @@ int QCC_PR_CheakCompConst(void) return false; } -char *QCC_PR_CheakCompConstString(char *def) +char *QCC_PR_CheckCompConstString(char *def) { char *s; @@ -2480,7 +2487,7 @@ char *QCC_PR_CheakCompConstString(char *def) if (c) { - s = QCC_PR_CheakCompConstString(c->value); + s = QCC_PR_CheckCompConstString(c->value); return s; } return def; @@ -2520,6 +2527,9 @@ void QCC_PR_Lex (void) QCC_PR_LexWhitespace (); + pr_token_line_last = pr_token_line; + pr_token_line = pr_source_line; + if (!pr_file_p) { if (QCC_PR_UnInclude()) @@ -2585,7 +2595,7 @@ void QCC_PR_Lex (void) if (c == '#' && !(pr_file_p[1]=='-' || (pr_file_p[1]>='0' && pr_file_p[1] <='9'))) //hash and not number { pr_file_p++; - if (!QCC_PR_CheakCompConst()) + if (!QCC_PR_CheckCompConst()) { if (!QCC_PR_SimpleGetToken()) strcpy(pr_token, "unknown"); @@ -2600,7 +2610,7 @@ void QCC_PR_Lex (void) if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' ) { - if (flag_hashonly || !QCC_PR_CheakCompConst()) //look for a macro. + if (flag_hashonly || !QCC_PR_CheckCompConst()) //look for a macro. QCC_PR_LexName (); else if (pr_token_type == tt_eof) @@ -2965,6 +2975,59 @@ int typecmp(QCC_type_t *a, QCC_type_t *b) return 0; } +//compares the types, but doesn't complain if there are optional arguments which differ +int typecmp_lax(QCC_type_t *a, QCC_type_t *b) +{ + int numargs = 0; + int t; + if (a == b) + return 0; + if (!a || !b) + return 1; //different (^ and not both null) + + if (a->type != b->type) + { + if (a->type != ev_variant && b->type != ev_variant) + return 1; + } + else if (a->size != b->size) + return 1; + + t = a->num_parms; + if (t < 0) + t = (t * -1) - 1; + numargs = t; + t = b->num_parms; + if (t < 0) + t = (t * -1) - 1; + if (numargs > t) + numargs = t; + +// if (STRCMP(a->name, b->name)) //This isn't 100% clean. +// return 1; + + if (typecmp_lax(a->aux_type, b->aux_type)) + return 1; + + if (numargs) + { + a = a->param; + b = b->param; + + while(numargs-->0 || (a&&b)) + { + if (typecmp_lax(a, b)) + return 1; + + a=a->next; + b=b->next; + } + } + + return 0; +} + + QCC_type_t *QCC_PR_DuplicateType(QCC_type_t *in) { QCC_type_t *out, *op, *ip; @@ -3392,7 +3455,7 @@ QCC_type_t *QCC_PR_ParseType (int newtype, pbool silentfail) return QCC_PR_FindType (newt); } - name = QCC_PR_CheakCompConstString(pr_token); + name = QCC_PR_CheckCompConstString(pr_token); if (QCC_PR_CheckKeyword (keyword_class, "class")) { diff --git a/engine/qclib/qccmain.c b/engine/qclib/qccmain.c index e19b9430..b88bc62c 100644 --- a/engine/qclib/qccmain.c +++ b/engine/qclib/qccmain.c @@ -2013,6 +2013,7 @@ unsigned short QCC_PR_WriteProgdefs (char *filename) } ADD("} entvars_t;\n\n"); +/* ///temp ADD2("//with this the crc isn't needed for fields.\n#ifdef FIELDSSTRUCT\nstruct fieldvars_s {\n\tint ofs;\n\tint type;\n\tchar *name;\n} fieldvars[] = {\n"); f=0; @@ -2030,6 +2031,7 @@ unsigned short QCC_PR_WriteProgdefs (char *filename) } ADD2("\n};\n#endif\n\n"); //end temp +*/ ADD2(qcva("#define PROGHEADER_CRC %i\n", crc)); @@ -3307,7 +3309,10 @@ void QCC_ContinueCompile(void) if (newstylesource) { - new_QCC_ContinueCompile(); + do + { + new_QCC_ContinueCompile(); + } while(currentchunk); //while parsing through preprocessor, make sure nothing gets hurt. return; } diff --git a/engine/server/pr_cmds.c b/engine/server/pr_cmds.c index 194e66f7..29d2e04b 100644 --- a/engine/server/pr_cmds.c +++ b/engine/server/pr_cmds.c @@ -24,6 +24,18 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "sv_sql.h" #endif +#ifndef SQL +#define PF_sqlconnect PF_Fixme +#define PF_sqldisconnect PF_Fixme +#define PF_sqlopenquery PF_Fixme +#define PF_sqlclosequery PF_Fixme +#define PF_sqlreadfield PF_Fixme +#define PF_sqlerror PF_Fixme +#define PF_sqlescape PF_Fixme +#define PF_sqlversion PF_Fixme +#define PF_sqlreadfloat PF_Fixme +#endif + #define Z_QC_TAG 2 #ifndef CLIENTONLY @@ -400,14 +412,14 @@ void QC_Clear(void); builtin_t pr_builtin[]; extern int pr_numbuiltins; -int QCLibEditor(progfuncs_t *prinst, char *filename, int line, int nump, char **parms); -int QCEditor (progfuncs_t *prinst, char *filename, int line, int nump, char **parms) +int QCLibEditor(progfuncs_t *prinst, char *filename, int line, int statement, int nump, char **parms); +int QCEditor (progfuncs_t *prinst, char *filename, int line, int statement, int nump, char **parms) { #ifdef TEXTEDITOR static char oldfuncname[64]; if (!parms) - return QCLibEditor(prinst, filename, line, nump, parms); + return QCLibEditor(prinst, filename, line, statement, nump, parms); else { if (!nump && !strncmp(oldfuncname, *parms, sizeof(oldfuncname))) @@ -627,6 +639,7 @@ void PR_LoadGlabalStruct(void) //static vec3_t vecwriteonly; // 523:16: warning: unused variable ‘vecwriteonly’ static float input_buttons_default; static float input_timelength_default; + static float input_impulse_default; static vec3_t input_angles_default; static vec3_t input_movevalues_default; int i; @@ -686,6 +699,7 @@ void PR_LoadGlabalStruct(void) globalfloat (false, clientcommandframe); globalfloat (false, input_timelength); + globalfloat (false, input_impulse); globalvec (false, input_angles); globalvec (false, input_movevalues); globalfloat (false, input_buttons); @@ -704,6 +718,7 @@ void PR_LoadGlabalStruct(void) ensureglobal(trace_surfaceflags, writeonly); ensureglobal(input_timelength, input_timelength_default); + ensureglobal(input_impulse, input_impulse_default); ensureglobal(input_angles, input_angles_default); ensureglobal(input_movevalues, input_movevalues_default); ensureglobal(input_buttons, input_buttons_default); @@ -751,13 +766,16 @@ void PR_LoadGlabalStruct(void) ensureglobal(trace_inwater, writeonly); ensureglobal(physics_mode, svphysicsmode); - pr_global_struct->dimension_send = 255; + //this can be a map start or a loadgame. don't hurt stuff. + if (!pr_global_struct->dimension_send) + pr_global_struct->dimension_send = 255; +/* pr_global_struct->dimension_send = 255; pr_global_struct->serverflags = 0; pr_global_struct->total_secrets = 0; pr_global_struct->total_monsters = 0; pr_global_struct->found_secrets = 0; pr_global_struct->killed_monsters = 0; - +*/ pr_teamfield = 0; SpectatorConnect = PR_FindFunction(svprogfuncs, "SpectatorConnect", PR_ANY); @@ -1121,6 +1139,41 @@ void PR_BreakPoint_f(void) Con_Printf("Breakpoint has been cleared\n"); } +void PR_WatchPoint_f(void) +{ + char *variable = Cmd_Argv(1); + int oldself; + if (!*variable) + variable = NULL; + + if (!svprogfuncs) + { + Con_Printf("Start the server first\n"); + return; + } + oldself = pr_global_struct->self; + if (oldself == 0) + { //if self is world, set it to something sensible. + int i; + for (i = 0; i < sv.allocated_client_slots; i++) + { + if (svs.clients[i].state && svs.clients[i].netchan.remote_address.type == NA_LOOPBACK) + { + //always use first local client, if available. + pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, svs.clients[i].edict); + break; + } + //failing that, just use the first client. + if (svs.clients[i].state == cs_spawned && !pr_global_struct->self) + pr_global_struct->self = EDICT_TO_PROG(svprogfuncs, svs.clients[i].edict); + } + } + if (svprogfuncs->SetWatchPoint(svprogfuncs, variable)) + Con_Printf("Watchpoint set\n"); + else + Con_Printf("Watchpoint cleared\n"); + pr_global_struct->self = oldself; +} void PR_SSCoreDump_f(void) { @@ -1162,6 +1215,7 @@ void PR_Init(void) int i; Cmd_AddCommand ("breakpoint", PR_BreakPoint_f); + Cmd_AddCommand ("watchpoint", PR_WatchPoint_f); Cmd_AddCommand ("decompile", PR_Decompile_f); Cmd_AddCommand ("compile", PR_Compile_f); Cmd_AddCommand ("applycompile", PR_ApplyCompilation_f); @@ -1593,6 +1647,9 @@ void Q_InitProgs(void) } } +// svprogfuncs->ToggleBreak(svprogfuncs, "", 0, 2); +// svprogfuncs->SetWatchPoint(svprogfuncs, ""); + sv.world.max_edicts = pr_maxedicts.value; if (sv.world.max_edicts > MAX_EDICTS) sv.world.max_edicts = MAX_EDICTS; @@ -3699,7 +3756,7 @@ static void QCBUILTIN PF_h2precache_puzzle_model (progfuncs_t *prinst, struct gl static void QCBUILTIN PF_getmodelindex (progfuncs_t *prinst, struct globalvars_s *pr_globals) { char *s = PR_GetStringOfs(prinst, OFS_PARM0); - qboolean queryonly = G_FLOAT(OFS_PARM1); + qboolean queryonly = (*svprogfuncs->callargc >= 2)?G_FLOAT(OFS_PARM1):false; G_FLOAT(OFS_RETURN) = PF_precache_model_Internal(prinst, s, queryonly); } @@ -5100,7 +5157,6 @@ char *PF_infokey_Internal (int entnum, char *key) { char *value; static char ov[256]; - char adr[MAX_ADR_SIZE]; if (entnum == 0) { @@ -5116,7 +5172,7 @@ char *PF_infokey_Internal (int entnum, char *key) { value = ov; if (!strcmp(key, "ip") || !strcmp(key, "realip")) //note: FTE doesn't support mvdsv's realip stuff, so pretend that we do if the mod asks - value = strcpy(ov, NET_BaseAdrToString (adr, sizeof(adr), svs.clients[entnum-1].netchan.remote_address)); + NET_BaseAdrToString (ov, sizeof(ov), svs.clients[entnum-1].netchan.remote_address); else if (!strcmp(key, "ping")) sprintf(ov, "%d", SV_CalcPing (&svs.clients[entnum-1], false)); else if (!strcmp(key, "svping")) @@ -5333,7 +5389,7 @@ void PF_sqlconnect (progfuncs_t *prinst, struct globalvars_s *pr_globals) paramstr[3] = sql_defaultdb.string; // verify/switch driver choice - if (*svprogfuncs->callargc > (SQL_CONNECT_PARAMS + 1)) + if (*svprogfuncs->callargc >= (SQL_CONNECT_PARAMS + 1)) driver = PR_GetStringOfs(prinst, OFS_PARM0 + SQL_CONNECT_PARAMS * 3); else driver = ""; @@ -5893,24 +5949,17 @@ FIXME: check for null pointers first? static void QCBUILTIN PF_MVDSV_strcpy (progfuncs_t *prinst, struct globalvars_s *pr_globals) { + int dst = G_INT(OFS_PARM0); char *src = PR_GetStringOfs(prinst, OFS_PARM1); - char *dest = PR_GetStringOfs(prinst, OFS_PARM0); - int *ident; - ident = (int *)(dest-8); + int size = strlen(src)+1; -/* - if (*ident != PRSTR) + if (dst < 0 || dst+size >= prinst->stringtablesize) { - Con_Printf("PF_strcpy: not an allocated string\n"); + PR_BIError(prinst, "PF_strcpy: invalid dest\n"); return; } - if (ident[1] < strlen(src)+1) - { - Con_Printf("PF_strcpy: allocated string is not big enough.\n"); - return; - } -*/ - strcpy(dest, src); + + strcpy(prinst->stringtable+dst, src); } /* @@ -5924,7 +5973,17 @@ FIXME: check for null pointers first? static void QCBUILTIN PF_MVDSV_strncpy (progfuncs_t *prinst, struct globalvars_s *pr_globals) { - strncpy(PR_GetStringOfs(prinst, OFS_PARM0), PR_GetStringOfs(prinst, OFS_PARM1), (int) G_FLOAT(OFS_PARM2)); + int dst = G_INT(OFS_PARM0); + char *src = PR_GetStringOfs(prinst, OFS_PARM1); + int size = G_FLOAT(OFS_PARM2); + + if (dst < 0 || dst+size >= prinst->stringtablesize) + { + PR_BIError(prinst, "PF_strncpy: invalid dest\n"); + return; + } + + strncpy(prinst->stringtable+dst, src, size); } @@ -7957,10 +8016,12 @@ void QCBUILTIN PF_ForceInfoKey(progfuncs_t *prinst, struct globalvars_s *pr_glob else if (e1 <= sv.allocated_client_slots) { //woo. we found a client. Info_SetValueForStarKey(svs.clients[e1-1].userinfo, key, value, sizeof(svs.clients[e1-1].userinfo)); - - + SV_ExtractFromUserinfo (&svs.clients[e1-1]); + if (SV_UserInfoIsBasic(key)) + Info_SetValueForKey (svs.clients[e1-1].userinfobasic, key, value, sizeof(svs.clients[e1-1].userinfobasic)); + MSG_WriteByte (&sv.reliable_datagram, svc_setinfo); MSG_WriteByte (&sv.reliable_datagram, e1-1); MSG_WriteString (&sv.reliable_datagram, key); @@ -8470,6 +8531,7 @@ qboolean SV_RunFullQCMovement(client_t *client, usercmd_t *ucmd) pr_global_struct->input_timelength = ucmd->msec/1000.0f; + pr_global_struct->input_impulse = ucmd->impulse; //precision inaccuracies. :( #define ANGLE2SHORT(x) (x) * (65536/360.0) if (sv_player->v->fixangle) @@ -8560,15 +8622,15 @@ static void QCBUILTIN PF_SendPacket(progfuncs_t *prinst, struct globalvars_s *pr #define STUB ,true -#ifdef DEBUG -#define NYI ,false +#if defined(DEBUG) || defined(_DEBUG) +#define NYI #else #define NYI ,true #endif BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"fixme", PF_Fixme, 0, 0, 0, 0, "void()"}, {"ignore", PF_Ignore, 0, 0, 0, 0, "void()"}, - {"makevectors", PF_makevectors, 1, 1, 1, 0, "void(vector)"}, + {"makevectors", PF_makevectors, 1, 1, 1, 0, "void(vector vang)"}, {"setorigin", PF_setorigin, 2, 2, 2, 0, "void(entity e, vector o)"}, {"setmodel", PF_setmodel, 3, 3, 3, 0, "void(entity e, string m)"}, {"setsize", PF_setsize, 4, 4, 4, 0, "void(entity e, vector min, vector max)"}, @@ -8691,14 +8753,14 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"precache_file2", PF_precache_file, 77, 77, 0, 0, "void(string str)"}, //77 {"setspawnparms", PF_setspawnparms, 78, 78, 78, 0, "void()"}, //78 - {"plaque_draw", PF_h2plaque_draw, 0, 0, 79, 0, ""}, //79 + {"plaque_draw", PF_h2plaque_draw, 0, 0, 79, 0, "void(entity targ, float stringno)"}, //79 {"logfrag", PF_logfrag, 0, 79, 0, 79, "void(entity killer, entity killee)"}, //79 // Tomaz - QuakeC String Manipulation Begin - {"tq_zone", PF_dupstring, 0, 0, 0, 79, "", true}, //79 - {"tq_unzone", PF_forgetstring, 0, 0, 0, 80, "", true}, //80 - {"tq_stof", PF_stof, 0, 0, 0, 81, "", true}, //81 - {"tq_strcat", PF_strcat, 0, 0, 0, 82, "", true}, //82 + {"tq_zone", PF_dupstring, 0, 0, 0, 79, "string(string s)", true}, //79 + {"tq_unzone", PF_forgetstring, 0, 0, 0, 80, "void(string s)", true}, //80 + {"tq_stof", PF_stof, 0, 0, 0, 81, "float(string s)", true}, //81 + {"tq_strcat", PF_strcat, 0, 0, 0, 82, "string(string s1, optional string s2, optional string s3, optional string s4, optional string s5, optional string s6, optional string s7, optional string s8)", true}, //82 {"tq_substring", PF_substring, 0, 0, 0, 83, "string(string str, float start, float len)", true}, //83 {"tq_stof", PF_stof, 0, 0, 0, 84, "float(string s)", true}, //84 {"tq_stov", PF_stov, 0, 0, 0, 85, "vector(string s)", true}, //85 @@ -8729,23 +8791,23 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs //some of these are a little iffy. //we support them for mvdsv compatability but some of them look very hacky. //these ones are not honoured with numbers, but can be used via the proper means. - {"teamfield", PF_teamfield, 0, 0, 0, 87, "", true}, - {"substr", PF_substr, 0, 0, 0, 88, "", true}, - {"mvdstrcat", PF_strcat, 0, 0, 0, 89, "", true}, - {"mvdstrlen", PF_strlen, 0, 0, 0, 90, "", true}, - {"str2byte", PF_str2byte, 0, 0, 0, 91, "", true}, - {"str2short", PF_str2short, 0, 0, 0, 92, "", true}, - {"mvdnewstr", PF_newstring, 0, 0, 0, 93, "", true}, - {"mvdfreestr", PF_forgetstring, 0, 0, 0, 94, "", true}, - {"conprint", PF_conprint, 0, 0, 0, 95, "", true}, - {"readcmd", PF_readcmd, 0, 0, 0, 96, "", true}, - {"mvdstrcpy", PF_MVDSV_strcpy, 0, 0, 0, 97, "", true}, - {"strstr", PF_strstr, 0, 0, 0, 98, "", true}, - {"mvdstrncpy", PF_MVDSV_strncpy, 0, 0, 0, 99, "", true}, - {"log", PF_log, 0, 0, 0, 100, "", true}, -// {"redirectcmd", PF_redirectcmd, 0, 0, 0, 101, "", true}, - {"mvdcalltimeofday",PF_calltimeofday, 0, 0, 0, 102, "", true}, - {"forcedemoframe", PF_forcedemoframe, 0, 0, 0, 103, "", true}, + {"teamfield", PF_teamfield, 0, 0, 0, 87, "void(.string teamfield)", true}, + {"substr", PF_substr, 0, 0, 0, 88, "string(string str, float start, float len)", true}, + {"mvdstrcat", PF_strcat, 0, 0, 0, 89, "string(string s1, optional string s2, optional string s3, optional string s4, optional string s5, optional string s6, optional string s7, optional string s8)", true}, + {"mvdstrlen", PF_strlen, 0, 0, 0, 90, "float(string s)", true}, + {"str2byte", PF_str2byte, 0, 0, 0, 91, "float(string str)", true}, + {"str2short", PF_str2short, 0, 0, 0, 92, "float(string str)", true}, + {"mvdnewstr", PF_newstring, 0, 0, 0, 93, "string(string s, optional float bufsize)", true}, + {"mvdfreestr", PF_forgetstring, 0, 0, 0, 94, "void(string s)", true}, + {"conprint", PF_conprint, 0, 0, 0, 95, "void(string s, ...)", true}, + {"readcmd", PF_readcmd, 0, 0, 0, 96, "string(string str)", true}, + {"mvdstrcpy", PF_MVDSV_strcpy, 0, 0, 0, 97, "void(string dst, string src)", true}, + {"strstr", PF_strstr, 0, 0, 0, 98, "string(string str, string sub)", true}, + {"mvdstrncpy", PF_MVDSV_strncpy, 0, 0, 0, 99, "void(string dst, string src, float count)", true}, + {"log", PF_log, 0, 0, 0, 100, "void(string name, float console, string text)", true}, +// {"redirectcmd", PF_redirectcmd, 0, 0, 0, 101, "void(entity to, string str)", true}, + {"mvdcalltimeofday",PF_calltimeofday, 0, 0, 0, 102, "void()", true}, + {"forcedemoframe", PF_forcedemoframe, 0, 0, 0, 103, "void(float now)", true}, //end of mvdsv {"setpuzzlemodel", PF_h2set_puzzle_model,0, 0, 87, 0}, @@ -8789,7 +8851,7 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"checkextension", PF_checkextension, 99, 99, 0, 99, "float(string extname)"}, // #99 //darkplaces system - query a string to see if the mod supports X Y and Z. {"builtin_find", PF_builtinsupported,100, 100, 0, 100, "float(string builtinname)"}, // #100 //per builtin system. {"anglemod", PF_anglemod, 0, 0, 0, 102, "float(float value)"}, - {"qsg_cvar_string", PF_cvar_string, 0, 0, 0, 103, "", true}, + {"qsg_cvar_string", PF_cvar_string, 0, 0, 0, 103, "string(string cvarname)", true}, //TEI_SHOWLMP2 {"showpic", PF_ShowPic, 0, 0, 0, 104, "void(string slot, string picname, float x, float y, float zone, optional entity player)"}, @@ -8798,15 +8860,15 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"changepic", PF_ChangePic, 0, 0, 0, 107, "void(string slot, string picname, optional entity player)"}, {"showpicent", PF_ShowPic, 0, 0, 0, 108, "void(string slot, entity player)", true}, {"hidepicent", PF_HidePic, 0, 0, 0, 109, "void(string slot, entity player)", true}, -// {"movepicent", PF_ShowPic, 0, 0, 0, 110, "", true}, -// {"changepicent", PF_HidePic, 0, 0, 0, 111, "", true}, +// {"movepicent", PF_ShowPic, 0, 0, 0, 110, "void(string slot, float x, float y, float zone, entity player)", true}, +// {"changepicent", PF_HidePic, 0, 0, 0, 111, "void(string slot, string picname, entity player)", true}, //End TEU_SHOWLMP2 //frik file {"fopen", PF_fopen, 0, 0, 0, 110, "float(string filename, float mode, optional float mmapminsize)"}, // (FRIK_FILE) {"fclose", PF_fclose, 0, 0, 0, 111, "void(float fhandle)"}, // (FRIK_FILE) {"fgets", PF_fgets, 0, 0, 0, 112, "string(float fhandle)"}, // (FRIK_FILE) - {"fputs", PF_fputs, 0, 0, 0, 113, "void(float fhandle, string s)"}, // (FRIK_FILE) + {"fputs", PF_fputs, 0, 0, 0, 113, "void(float fhandle, string s, optional string s2, optional string s3, optional string s4, optional string s5, optional string s6, optional string s7)"}, // (FRIK_FILE) {"strlen", PF_strlen, 0, 0, 0, 114, "float(string s)"}, // (FRIK_FILE) {"strcat", PF_strcat, 0, 0, 0, 115, "string(string s1, optional string s2, ...)"}, // (FRIK_FILE) {"substring", PF_substring, 0, 0, 0, 116, "string(string s, float start, float length)"}, // (FRIK_FILE) @@ -8889,17 +8951,16 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"rotatevectorsbytag", PF_Fixme, 0, 0, 0, 244, "vector(entity ent, float tagnum)"}, // #234 -#ifdef SQL - {"sqlconnect", PF_sqlconnect, 0, 0, 0, 250, "float(optional string host, optional string user, optional string pass, optional string defaultdb, optional string driver)"} // sqlconnect (FTE_SQL) - {"sqldisconnect", PF_sqldisconnect, 0, 0, 0, 251, "void(float serveridx)"} // sqldisconnect (FTE_SQL) - {"sqlopenquery", PF_sqlopenquery, 0, 0, 0, 252, "float(float serveridx, void(float serveridx, float queryidx, float rows, float columns, float eof) callback, float querytype, string query)"} // sqlopenquery (FTE_SQL) - {"sqlclosequery", PF_sqlclosequery, 0, 0, 0, 253, "void(float serveridx, float queryidx)"} // sqlclosequery (FTE_SQL) - {"sqlreadfield", PF_sqlreadfield, 0, 0, 0, 254, "string(float serveridx, float queryidx, float row, float column)"} // sqlreadfield (FTE_SQL) - {"sqlerror", PF_sqlerror, 0, 0, 0, 255, "string(float serveridx, optional float queryidx)"} // sqlerror (FTE_SQL) - {"sqlescape", PF_sqlescape, 0, 0, 0, 256, "string(float serveridx, string data)"} // sqlescape (FTE_SQL) - {"sqlversion", PF_sqlversion, 0, 0, 0, 257, "string(float serveridx)"} // sqlversion (FTE_SQL) - {"sqlreadfloat", PF_sqlreadfloat, 0, 0, 0, 258, "float(float serveridx, float queryidx, float row, float column)"} // sqlreadfloat (FTE_SQL) -#endif + {"sqlconnect", PF_sqlconnect, 0, 0, 0, 250, "float(optional string host, optional string user, optional string pass, optional string defaultdb, optional string driver)"}, // sqlconnect (FTE_SQL) + {"sqldisconnect", PF_sqldisconnect, 0, 0, 0, 251, "void(float serveridx)"}, // sqldisconnect (FTE_SQL) + {"sqlopenquery", PF_sqlopenquery, 0, 0, 0, 252, "float(float serveridx, void(float serveridx, float queryidx, float rows, float columns, float eof) callback, float querytype, string query)"}, // sqlopenquery (FTE_SQL) + {"sqlclosequery", PF_sqlclosequery, 0, 0, 0, 253, "void(float serveridx, float queryidx)"}, // sqlclosequery (FTE_SQL) + {"sqlreadfield", PF_sqlreadfield, 0, 0, 0, 254, "string(float serveridx, float queryidx, float row, float column)"}, // sqlreadfield (FTE_SQL) + {"sqlerror", PF_sqlerror, 0, 0, 0, 255, "string(float serveridx, optional float queryidx)"}, // sqlerror (FTE_SQL) + {"sqlescape", PF_sqlescape, 0, 0, 0, 256, "string(float serveridx, string data)"}, // sqlescape (FTE_SQL) + {"sqlversion", PF_sqlversion, 0, 0, 0, 257, "string(float serveridx)"}, // sqlversion (FTE_SQL) + {"sqlreadfloat", PF_sqlreadfloat, 0, 0, 0, 258, "float(float serveridx, float queryidx, float row, float column)"}, // sqlreadfloat (FTE_SQL) + {"stoi", PF_stoi, 0, 0, 0, 259, "int(string)"}, {"itos", PF_itos, 0, 0, 0, 260, "string(int)"}, {"stoh", PF_stoh, 0, 0, 0, 261, "int(string)"}, @@ -8918,13 +8979,13 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"skel_mul_bones", PF_skel_mul_bones, 0, 0, 0, 273, "void(float skel, float startbone, float endbone, vector org, optional vector fwd, optional vector right, optional vector up)"}, // (FTE_CSQC_SKELETONOBJECTS) (reads v_forward etc) {"skel_copybones", PF_skel_copybones, 0, 0, 0, 274, "void(float skeldst, float skelsrc, float startbone, float entbone)"}, // (FTE_CSQC_SKELETONOBJECTS) {"skel_delete", PF_skel_delete, 0, 0, 0, 275, "void(float skel)"}, // (FTE_CSQC_SKELETONOBJECTS) - {"frameforname", PF_frameforname, 0, 0, 0, 276, "void(float modidx, string framename)"},// (FTE_CSQC_SKELETONOBJECTS) + {"frameforname", PF_frameforname, 0, 0, 0, 276, "float(float modidx, string framename)"},// (FTE_CSQC_SKELETONOBJECTS) {"frameduration", PF_frameduration, 0, 0, 0, 277, "float(float modidx, float framenum)"},// (FTE_CSQC_SKELETONOBJECTS) {"terrain_edit", PF_terrain_edit, 0, 0, 0, 278, "void(float action, vector pos, float radius, float quant)"},// (??FTE_TERRAIN_EDIT?? {"touchtriggers", PF_touchtriggers, 0, 0, 0, 279, "void()"},// {"writefloat", PF_WriteFloat, 0, 0, 0, 280, "void(float buf, float fl)"},// - {"skel_ragupdate", PF_skel_ragedit, 0, 0, 0, 281, "float(float skel, string dollname, float parentskel, vector trans, vector fwd, vector rt, vector up)" NYI}, // (FTE_CSQC_RAGDOLL) + {"skel_ragupdate", PF_skel_ragedit, 0, 0, 0, 281, "float(entity skelent, string dollname, float parentskel)" NYI}, // (FTE_CSQC_RAGDOLL) {"skel_mmap", PF_skel_mmap, 0, 0, 0, 282, "float*(float skel)"},// (FTE_QC_RAGDOLL) {"skel_set_bone_world",PF_skel_set_bone_world,0,0, 0, 283, "void(entity ent, float bonenum, vector org, optional vector angorfwd, optional vector right, optional vector up)"}, {"frametoname", PF_frametoname, 0, 0, 0, 284, "string(float modidx, float framenum)"}, @@ -9044,9 +9105,9 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs //DP_SV_SETCOLOR {"setcolors", PF_setcolors, 0, 0, 0, 401, "void(entity from, entity to)"},// //DP_QC_FINDCHAIN - {"findchain", PF_sv_findchain, 0, 0, 0, 402, "entity(string field, string match)"},// (DP_QC_FINDCHAIN) + {"findchain", PF_sv_findchain, 0, 0, 0, 402, "entity(.string field, string match)"},// (DP_QC_FINDCHAIN) //DP_QC_FINDCHAINFLOAT - {"findchainfloat", PF_sv_findchainfloat,0, 0, 0, 403, "entity(float fld, float match)"},// (DP_QC_FINDCHAINFLOAT) + {"findchainfloat", PF_sv_findchainfloat,0, 0, 0, 403, "entity(.float fld, float match)"},// (DP_QC_FINDCHAINFLOAT) //DP_SV_EFFECT {"effect", PF_effect, 0, 0, 0, 404, "void(vector org, string modelname, float startframe, float endframe, float framerate)"},// (DP_SV_EFFECT) //DP_TE_BLOOD @@ -9074,7 +9135,7 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"te_customflash", PF_te_customflash, 0, 0, 0, 417, "void(vector org, float radius, float lifetime, vector color)"},// (DP_TE_CUSTOMFLASH) //DP_TE_STANDARDEFFECTBUILTINS - {"te_gunshot", PF_te_gunshot, 0, 0, 0, 418, "void(vector org)"},// #418 te_gunshot + {"te_gunshot", PF_te_gunshot, 0, 0, 0, 418, "void(vector org, optional float count)"},// #418 te_gunshot {"te_spike", PF_te_spike, 0, 0, 0, 419, "void(vector org)"},// #419 te_spike {"te_superspike", PF_te_superspike, 0, 0, 0, 420, "void(vector org)"},// #420 te_superspike {"te_explosion", PF_te_explosion, 0, 0, 0, 421, "void(vector org)"},// #421 te_explosion @@ -9116,7 +9177,7 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs {"cvar_string", PF_cvar_string, 0, 0, 0, 448, "string(string cvarname)"},// //DP_QC_FINDFLAGS - {"findflags", PF_FindFlags, 0, 0, 0, 449, "entity(entity start, .entity fld, float match)"},// + {"findflags", PF_FindFlags, 0, 0, 0, 449, "entity(entity start, .float fld, float match)"},// //DP_QC_FINDCHAINFLAGS {"findchainflags", PF_sv_findchainflags,0, 0, 0, 450, "entity(.float fld, float match)"},// //DP_MD3_TAGSINFO @@ -9231,7 +9292,7 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs //DP_QC_URI_GET {"uri_get", PF_uri_get, 0, 0, 0, 513, "float(string uril, float id)" STUB},// - {"tokenize_console",PF_tokenize_console,0, 0, 0, 514, "void(string str)"}, + {"tokenize_console",PF_tokenize_console,0, 0, 0, 514, "float(string str)"}, {"argv_start_index",PF_argv_start_index,0, 0, 0, 515, "float(float idx)"}, {"argv_end_index", PF_argv_end_index, 0, 0, 0, 516, "float(float idx)"}, {"buf_cvarlist", PF_buf_cvarlist, 0, 0, 0, 517, "void(float strbuf)" STUB}, @@ -9261,7 +9322,7 @@ BuiltinList_t BuiltinList[] = { //nq qw h2 ebfs //VM_SV_getextresponse, // #624 string getextresponse(void) - {"sprintf", PF_sprintf, 0, 0, 0, 627, "string(...)"}, + {"sprintf", PF_sprintf, 0, 0, 0, 627, "string(string fmt, ...)"}, {"getsurfacenumtriangles",PF_getsurfacenumtriangles,0,0, 0, 628, "float(entity e, float s)"}, {"getsurfacetriangle",PF_getsurfacetriangle,0,0, 0, 629, "vector(entity e, float s, float n)"}, @@ -9606,7 +9667,7 @@ void PR_DumpPlatform_f(void) int idx; int i, j; - int d = 0, nd; + int d = 0, nd, k; vfsfile_t *f; char *fname = ""; char dbgfname[MAX_OSPATH]; @@ -10006,6 +10067,25 @@ void PR_DumpPlatform_f(void) {"LFLAG_SHADOWMAP", "const float", CS, LFLAG_SHADOWMAP}, {"LFLAG_CREPUSCULAR", "const float", CS, LFLAG_CREPUSCULAR}, + {"TEREDIT_RELOAD", "const float", CS, ter_reload}, + {"TEREDIT_SAVE", "const float", CS, ter_save}, + {"TEREDIT_SETHOLE", "const float", CS, ter_sethole}, + {"TEREDIT_HEIGHT_SET", "const float", CS, ter_height_set}, + {"TEREDIT_HEIGHT_SMOOTH","const float",CS, ter_height_smooth}, + {"TEREDIT_HEIGHT_SPREAD","const float",CS, ter_height_spread}, + {"TEREDIT_HEIGHT_RAISE","const float", CS, ter_raise}, + {"TEREDIT_HEIGHT_FLATTEN","const float", CS, ter_height_flatten}, + {"TEREDIT_HEIGHT_LOWER","const float", CS, ter_lower}, + {"TEREDIT_TEX_KILL", "const float", CS, ter_tex_kill}, + {"TEREDIT_TEX_GET", "const float", CS, ter_tex_get}, + {"TEREDIT_MIX_PAINT", "const float", CS, ter_mix_paint}, + {"TEREDIT_MIX_UNIFY", "const float", CS, ter_mix_concentrate}, + {"TEREDIT_MIX_NOISE", "const float", CS, ter_mix_noise}, + {"TEREDIT_MIX_BLUR", "const float", CS, ter_mix_blur}, + {"TEREDIT_WATER_SET", "const float", CS, ter_water_set}, + {"TEREDIT_MESH_ADD", "const float", CS, ter_mesh_add}, + {"TEREDIT_MESH_KILL", "const float", CS, ter_mesh_kill}, + {"TEREDIT_TINT", "const float", CS, ter_tint}, NULL }; @@ -10138,7 +10218,7 @@ void PR_DumpPlatform_f(void) if (d != ALL) VFS_PRINTF(f, "#endif\n"); - d = 0; + d = ALL; for (i = 0; BuiltinList[i].name; i++) { if (BuiltinList[i].obsolete) @@ -10154,9 +10234,9 @@ void PR_DumpPlatform_f(void) if (PR_CSQC_BuiltinValid(BuiltinList[i].name, idx)) { if (BuiltinList[i].bifunc == PF_Fixme || BuiltinList[i].bifunc == PF_Ignore) - nd = 2; /*csqc only*/ + nd = CS; /*csqc only*/ else - nd = 0; /*both*/ + nd = NQ|QW|CS; /*both*/ } else { @@ -10167,23 +10247,70 @@ void PR_DumpPlatform_f(void) nd = d; /*don't switch ifdefs*/ } else - nd = 1; /*ssqc only*/ + nd = NQ|QW; /*ssqc only*/ } if (nd != d) { - if (d) + if (!(nd & targ)) + continue; + + if (d != ALL) VFS_PRINTF(f, "#endif\n"); - if (nd == 1) - VFS_PRINTF(f, "#ifdef SSQC\n"); - if (nd == 2) - VFS_PRINTF(f, "#ifdef CSQC\n"); d = nd; + + switch(d) + { + case 0: + continue; + case QW: + VFS_PRINTF(f, "#if defined(SSQC) && !defined(NETQUAKE)\n"); + break; + case NQ: + VFS_PRINTF(f, "#if defined(SSQC) && defined(NETQUAKE)\n"); + break; + case QW|NQ: + VFS_PRINTF(f, "#ifdef SSQC\n"); + break; + case CS: + VFS_PRINTF(f, "#ifdef CSQC\n"); + break; + case QW|CS: + VFS_PRINTF(f, "#if defined(CSQC) || (defined(SSQC) && !defined(NETQUAKE))\n"); + break; + case NQ|CS: + VFS_PRINTF(f, "#if defined(CSQC) || (defined(SSQC) && defined(NETQUAKE))\n"); + break; + case ALL: + break; + } } - VFS_PRINTF(f, "%s%s %s = #%u;\n", BuiltinList[i].obsolete?"//":"", BuiltinList[i].prototype, BuiltinList[i].name, idx); + VFS_PRINTF(f, "%s%s %s = #%u;", BuiltinList[i].obsolete?"//":"", BuiltinList[i].prototype, BuiltinList[i].name, idx); + nd = 0; + for (j = 0; j < QSG_Extensions_count; j++) + { + for (k = 0; k < QSG_Extensions[j].numbuiltins; k++) + { + if (!strcmp(QSG_Extensions[j].builtinnames[k], BuiltinList[i].name)) + { + if (!nd) + VFS_PRINTF(f, " /* Part of "); + else + VFS_PRINTF(f, ", "); + nd++; + VFS_PRINTF(f, "%s", QSG_Extensions[j].name); + } + } + } + if (nd) + VFS_PRINTF(f, "*/\n"); + else + VFS_PRINTF(f, "\n"); } } - if (d) + if (d != ALL) VFS_PRINTF(f, "#endif\n"); + + VFS_PRINTF(f, "#pragma noref 0\n"); VFS_CLOSE(f); diff --git a/engine/server/progdefs.h b/engine/server/progdefs.h index 90d36c92..4b9035fc 100644 --- a/engine/server/progdefs.h +++ b/engine/server/progdefs.h @@ -85,6 +85,7 @@ typedef struct nqglobalvars_s float *physics_mode; float *clientcommandframe; float *input_timelength; + float *input_impulse; vec3_t *input_angles; vec3_t *input_movevalues; float *input_buttons; @@ -362,15 +363,46 @@ comextqcfields #endif - #if defined(CSQC_DAT) || !defined(CLIENTONLY) - #if defined(ODE_STATIC) || defined(ODE_DYNAMIC) - #define USEODE 1 + #define USEODE 1 + #if !(defined(ODE_STATIC) || defined(ODE_DYNAMIC)) + #undef USEODE #endif #endif #ifdef USEODE -typedef struct { +typedef struct +{ + void *ode_body; + void *ode_geom; +} odebody_t; + +typedef struct +{ + void *ode_joint; +} odejoint_t; +typedef struct +{ + char name[32]; + int type; + int body1; //handled by the ragdoll code, rather than the physics library. + int body2; //handled by the ragdoll code. + int bonepivot; //pivot is specified relative to this bone. + + float FMax, FMax2; + float HiStop, HiStop2; + float LoStop, LoStop2; + float CFM, CFM2; + float ERP, ERP2; + float Vel, Vel2; + vec3_t offset, offset2; + vec3_t axis, axis2; + + float orgmatrix[12]; +} odejointinfo_t; + +typedef struct +{ // physics parameters qboolean ode_physics; void *ode_body; @@ -417,6 +449,7 @@ typedef struct // for ODE physics engine qboolean ode; // if true then ode is activated qboolean hasodeents; // if true then we have some ode body somewhere, and we consume more cycles processing full physics, instead of trying to skip as much as we can + qboolean hasextraobjs; void *ode_world; void *ode_space; void *ode_contactgroup; diff --git a/engine/server/sqlite3.h b/engine/server/sqlite3.h new file mode 100644 index 00000000..5a1f9d46 --- /dev/null +++ b/engine/server/sqlite3.h @@ -0,0 +1,7097 @@ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve the right to make minor changes +** if experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +#ifndef SQLITE_API +# define SQLITE_API +#endif + + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.7.14.1" +#define SQLITE_VERSION_NUMBER 3007014 +#define SQLITE_SOURCE_ID "2012-10-04 19:37:12 091570e46d04e84b67228e0bdbcd6e1fb60c6bdb" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API SQLITE_EXTERN const char sqlite3_version[]; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled with mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** and [sqlite3_close_v2()] are its destructors. There are many other +** interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors +** for the [sqlite3] object. +** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if +** the [sqlite3] object is successfully destroyed and all associated +** resources are deallocated. +** +** ^If the database connection is associated with unfinalized prepared +** statements or unfinished sqlite3_backup objects then sqlite3_close() +** will leave the database connection open and return [SQLITE_BUSY]. +** ^If sqlite3_close_v2() is called with unfinalized prepared statements +** and unfinished sqlite3_backups, then the database connection becomes +** an unusable "zombie" which will automatically be deallocated when the +** last prepared statement is finalized or the last sqlite3_backup is +** finished. The sqlite3_close_v2() interface is intended for use with +** host languages that are garbage collected, and where the order in which +** destructors are called is arbitrary. +** +** Applications should [sqlite3_finalize | finalize] all [prepared statements], +** [sqlite3_blob_close | close] all [BLOB handles], and +** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated +** with the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close() is called on a [database connection] that still has +** outstanding [prepared statements], [BLOB handles], and/or +** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation +** of resources is deferred until all [prepared statements], [BLOB handles], +** and [sqlite3_backup] objects are also destroyed. +** +** ^If an [sqlite3] object is destroyed while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] +** must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer +** argument is a harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3*); +SQLITE_API int sqlite3_close_v2(sqlite3*); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicate success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes], +** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) +#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) +#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) +#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) +#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) +#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) +#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the [sqlite3_vfs.xOpen] method. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* Reserved: 0x00F00000 */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that +** after reboot following a crash or power loss, the only bytes in a +** file that were written at the application level might have changed +** and that adjacent bytes, even bytes within the same sector are +** guaranteed to be unchanged. +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs.xOpen] method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The +** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] +** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element +** to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +**
    +**
  • [[SQLITE_FCNTL_SIZE_HINT]] +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +**
  • [[SQLITE_FCNTL_CHUNK_SIZE]] +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +**
  • [[SQLITE_FCNTL_FILE_POINTER]] +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +**
  • [[SQLITE_FCNTL_SYNC_OMITTED]] +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specialized VFSes +** that do require it. +** +**
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] +** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic +** retry counts and intervals for certain disk I/O operations for the +** windows [VFS] in order to provide robustness in the presence of +** anti-virus programs. By default, the windows VFS will retry file read, +** file write, and file delete operations up to 10 times, with a delay +** of 25 milliseconds before the first retry and with the delay increasing +** by an additional 25 milliseconds with each subsequent retry. This +** opcode allows these two values (10 retries and 25 milliseconds of delay) +** to be adjusted. The values are changed for all database connections +** within the same process. The argument is a pointer to an array of two +** integers where the first integer i the new retry count and the second +** integer is the delay. If either integer is negative, then the setting +** is not changed but instead the prior value of that setting is written +** into the array entry, allowing the current retry settings to be +** interrogated. The zDbName parameter is ignored. +** +**
  • [[SQLITE_FCNTL_PERSIST_WAL]] +** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the +** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary +** write ahead log and shared memory files used for transaction control +** are automatically deleted when the latest connection to the database +** closes. Setting persistent WAL mode causes those files to persist after +** close. Persisting the files is useful when other processes that do not +** have write permission on the directory containing the database file want +** to read the database file, as the WAL and shared memory files must exist +** in order for the database to be readable. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable persistent WAL mode or 1 to enable persistent +** WAL mode. If the integer is -1, then it is overwritten with the current +** WAL persistence setting. +** +**
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the +** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the +** xDeviceCharacteristics methods. The fourth parameter to +** [sqlite3_file_control()] for this opcode should be a pointer to an integer. +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage +** mode. If the integer is -1, then it is overwritten with the current +** zero-damage mode setting. +** +**
  • [[SQLITE_FCNTL_OVERWRITE]] +** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening +** a write transaction to indicate that, unless it is rolled back for some +** reason, the entire database file will be overwritten by the current +** transaction. This is used by VACUUM operations. +** +**
  • [[SQLITE_FCNTL_VFSNAME]] +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of +** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** final bottom-level VFS are written into memory obtained from +** [sqlite3_malloc()] and the result is stored in the char* variable +** that the fourth parameter of [sqlite3_file_control()] points to. +** The caller is responsible for freeing the memory when done. As with +** all file-control actions, there is no guarantee that this will actually +** do anything. Callers should initialize the char* variable to a NULL +** pointer in case this file-control is not implemented. This file-control +** is intended for diagnostic use only. +** +**
  • [[SQLITE_FCNTL_PRAGMA]] +** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] +** file control is sent to the open [sqlite3_file] object corresponding +** to the database file to which the pragma statement refers. ^The argument +** to the [SQLITE_FCNTL_PRAGMA] file control is an array of +** pointers to strings (char**) in which the second element of the array +** is the name of the pragma and the third element is the argument to the +** pragma or NULL if the pragma has no argument. ^The handler for an +** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element +** of the char** argument point to a string obtained from [sqlite3_mprintf()] +** or the equivalent and that string will become the result of the pragma or +** the error message if the pragma fails. ^If the +** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal +** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] +** file control returns [SQLITE_OK], then the parser assumes that the +** VFS has handled the PRAGMA itself and the parser generates a no-op +** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns +** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means +** that the VFS encountered an error while handling the [PRAGMA] and the +** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] +** file control occurs at the beginning of pragma statement analysis and so +** it is able to override built-in [PRAGMA] statements. +**
+*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 +#define SQLITE_FCNTL_WIN32_AV_RETRY 9 +#define SQLITE_FCNTL_PERSIST_WAL 10 +#define SQLITE_FCNTL_OVERWRITE 11 +#define SQLITE_FCNTL_VFSNAME 12 +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 +#define SQLITE_FCNTL_PRAGMA 14 + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". See +** the [VFS | VFS documentation] for further information. +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** [[sqlite3_vfs.xOpen]] +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 11 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_MASTER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** [[sqlite3_vfs.xAccess]] +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multiplied by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +** +** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** are not used by the SQLite core. These optional interfaces are provided +** by some VFSes to facilitate testing of the VFS code. By overriding +** system calls with functions under its control, a test program can +** simulate faults and error conditions that would otherwise be difficult +** or impossible to induce. The set of system calls that can be overridden +** varies from one VFS to another, and from one version of the same VFS to the +** next. Applications that use these interfaces must be prepared for any +** or all of these interfaces to be NULL or for their behavior to change +** from one release to the next. Applications must not attempt to access +** any of these methods if the iVersion of the VFS is less than 3. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +typedef void (*sqlite3_syscall_ptr)(void); +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 3) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** Those below are for version 3 and greater. + */ + int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); + sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); + const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); + /* + ** The methods above are in versions 1 through 3 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). +** +** The second argument to sqlite3_db_config(D,V,...) is the +** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code +** that indicates what aspect of the [database connection] is being configured. +** Subsequent arguments vary depending on the configuration verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc, xRealloc, and xFree methods must work like the +** malloc(), realloc() and free() functions from the standard C library. +** ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** KEYWORDS: {configuration option} +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
+**
^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
+**
^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scratch allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
+** +** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
+**
^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implementation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
+** +** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
+**
^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined. +** The minimum allocation size is capped at 2**12. Reasonable values +** for the minimum allocation size are 2**5 through 2**8.
+** +** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
+**
^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
+** +** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
+**
^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods2] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
+** +** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
+**
^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods2] object. SQLite copies of the current +** page cache implementation into that object.)^
+** +** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
+**
^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI +**
This option takes a single argument of type int. If non-zero, then +** URI handling is globally enabled. If the parameter is zero, then URI handling +** is globally disabled. If URI handling is globally enabled, all filenames +** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or +** specified as part of [ATTACH] commands are interpreted as URIs, regardless +** of whether or not the [SQLITE_OPEN_URI] flag is set when the database +** connection is opened. If it is globally disabled, filenames are +** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the +** database connection is opened. By default, URI handling is globally +** disabled. The default value may be changed by compiling with the +** [SQLITE_USE_URI] symbol defined. +** +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] +**
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE +**
These options are obsolete and should not be used by new code. +** They are retained for backwards compatibility but are now no-ops. +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* no-op */ +#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ +#define SQLITE_CONFIG_URI 17 /* int */ +#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ +#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_DBCONFIG_LOOKASIDE
+**
^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to a memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
+** +**
SQLITE_DBCONFIG_ENABLE_FKEY
+**
^This option is used to enable or disable the enforcement of +** [foreign key constraints]. There should be two additional arguments. +** The first argument is an integer which is 0 to disable FK enforcement, +** positive to enable FK enforcement or negative to leave FK enforcement +** unchanged. The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether FK enforcement is off or on +** following this call. The second parameter may be a NULL pointer, in +** which case the FK enforcement setting is not reported back.
+** +**
SQLITE_DBCONFIG_ENABLE_TRIGGER
+**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. +** There should be two additional arguments. +** The first argument is an integer which is 0 to disable triggers, +** positive to enable triggers or negative to leave the setting unchanged. +** The second parameter is a pointer to an integer into which +** is written 0 or 1 to indicate whether triggers are disabled or enabled +** following this call. The second parameter may be a NULL pointer, in +** which case the trigger setting is not reported back.
+** +**
+*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ +#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^As of SQLite version 3.7.7, this routines +** records the last insert rowid of both ordinary tables and [virtual tables]. +** ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger or within a [virtual table] +** method, then this routine will return the [rowid] of the inserted +** row as long as the trigger or virtual table method is running. +** But once the trigger or virtual table method ends, the value returned +** by this routine reverts to what it was before the trigger or virtual +** table method began.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a nul-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
+**  char *zText = "It's a happy day!";
+** 
+** +** One can use this text in an SQL statement as follows: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
+**  INSERT INTO table1 VALUES('It''s a happy day!')
+** 
+** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
+**  INSERT INTO table1 VALUES('It's a happy day!');
+** 
+** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** Prior to SQLite version 3.7.10, the Windows OS interface layer called +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors were detected, but +** they were reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers an authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +** +** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] +** from the [sqlite3_vtab_on_conflict()] interface. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file as specified by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above optionally combined with other +** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** [[URI filenames in sqlite3_open()]]

URI Filenames

+** +** ^If [URI filename] interpretation is enabled, and the filename argument +** begins with "file:", then the filename is interpreted as a URI. ^URI +** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is +** set in the fourth argument to sqlite3_open_v2(), or if it has +** been enabled globally using the [SQLITE_CONFIG_URI] option with the +** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. +** As of SQLite version 3.7.7, URI filename interpretation is turned off +** by default, but future releases of SQLite might enable URI filename +** interpretation by default. See "[URI filenames]" for additional +** information. +** +** URI filenames are parsed according to RFC 3986. ^If the URI contains an +** authority, then it must be either an empty string or the string +** "localhost". ^If the authority is not an empty string or "localhost", an +** error is returned to the caller. ^The fragment component of a URI, if +** present, is ignored. +** +** ^SQLite uses the path component of the URI as the name of the disk file +** which contains the database. ^If the path begins with a '/' character, +** then it is interpreted as an absolute path. ^If the path does not begin +** with a '/' (meaning that the authority section is omitted from the URI) +** then the path is interpreted as a relative path. +** ^On windows, the first component of an absolute path +** is a drive specification (e.g. "C:"). +** +** [[core URI query parameters]] +** The query component of a URI may contain parameters that are interpreted +** either by SQLite itself, or by a [VFS | custom VFS implementation]. +** SQLite interprets the following three query parameters: +** +**
    +**
  • vfs: ^The "vfs" parameter may be used to specify the name of +** a VFS object that provides the operating system interface that should +** be used to access the database file on disk. ^If this option is set to +** an empty string the default VFS object is used. ^Specifying an unknown +** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is +** present, then the VFS specified by the option takes precedence over +** the value passed as the fourth parameter to sqlite3_open_v2(). +** +**
  • mode: ^(The mode parameter may be set to either "ro", "rw", +** "rwc", or "memory". Attempting to set it to any other value is +** an error)^. +** ^If "ro" is specified, then the database is opened for read-only +** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the +** third argument to sqlite3_prepare_v2(). ^If the mode option is set to +** "rw", then the database is opened for read-write (but not create) +** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had +** been set. ^Value "rwc" is equivalent to setting both +** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is +** set to "memory" then a pure [in-memory database] that never reads +** or writes from disk is used. ^It is an error to specify a value for +** the mode parameter that is less restrictive than that specified by +** the flags passed in the third parameter to sqlite3_open_v2(). +** +**
  • cache: ^The cache parameter may be set to either "shared" or +** "private". ^Setting it to "shared" is equivalent to setting the +** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to +** sqlite3_open_v2(). ^Setting the cache parameter to "private" is +** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. +** ^If sqlite3_open_v2() is used and the "cache" parameter is present in +** a URI filename, its value overrides any behaviour requested by setting +** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. +**
+** +** ^Specifying an unknown parameter in the query component of a URI is not an +** error. Future versions of SQLite might understand additional query +** parameters. See "[query parameters with special meaning to SQLite]" for +** additional information. +** +** [[URI filename examples]]

URI filename examples

+** +** +**
URI filenames Results +**
file:data.db +** Open the file "data.db" in the current directory. +**
file:/home/fred/data.db
+** file:///home/fred/data.db
+** file://localhost/home/fred/data.db
+** Open the database file "/home/fred/data.db". +**
file://darkstar/home/fred/data.db +** An error. "darkstar" is not a recognized authority. +**
+** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db +** Windows only: Open the file "data.db" on fred's desktop on drive +** C:. Note that the %20 escaping in this example is not strictly +** necessary - space characters can be used literally +** in URI filenames. +**
file:data.db?mode=ro&cache=private +** Open file "data.db" in the current directory for read-only access. +** Regardless of whether or not shared-cache mode is enabled by +** default, use a private cache. +**
file:/home/fred/data.db?vfs=unix-nolock +** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". +**
file:data.db?mode=readonly +** An error. "readonly" is not a valid option for the "mode" parameter. +**
+** +** ^URI hexadecimal escape sequences (%HH) are supported within the path and +** query components of a URI. A hexadecimal escape sequence consists of a +** percent sign - "%" - followed by exactly two hexadecimal digits +** specifying an octet value. ^Before the path or query components of a +** URI filename are interpreted, they are encoded using UTF-8 and all +** hexadecimal escape sequences replaced by a single byte containing the +** corresponding octet. If this process generates an invalid UTF-8 encoding, +** the results are undefined. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various +** features that require the use of temporary files may fail. +** +** See also: [sqlite3_temp_directory] +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Obtain Values For URI Parameters +** +** These are utility routines, useful to VFS implementations, that check +** to see if a database file was a URI that contained a specific query +** parameter, and if so obtains the value of that query parameter. +** +** If F is the database filename pointer passed into the xOpen() method of +** a VFS implementation when the flags parameter to xOpen() has one or +** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and +** P is the name of the query parameter, then +** sqlite3_uri_parameter(F,P) returns the value of the P +** parameter if it exists or a NULL pointer if P does not appear as a +** query parameter on F. If P is a query parameter of F +** has no explicit value, then sqlite3_uri_parameter(F,P) returns +** a pointer to an empty string. +** +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean +** parameter and returns true (1) or false (0) according to the value +** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the +** value of query parameter P is one of "yes", "true", or "on" in any +** case or if the value begins with a non-zero number. The +** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of +** query parameter P is one of "no", "false", or "off" in any case or +** if the value begins with a numeric zero. If P is not a query +** parameter on F or if the value of P is does not match any of the +** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). +** +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a +** 64-bit signed integer and returns that integer, or D if P does not +** exist. If the value of P is something other than an integer, then +** zero is returned. +** +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and +** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and +** is not a database file pathname pointer that SQLite passed into the xOpen +** VFS method, then the behavior of this routine is undefined and probably +** undesirable. +*/ +SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); +SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); +SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); + + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
    +**
  1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
  2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** [[SQLITE_LIMIT_LENGTH]] ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** [[SQLITE_LIMIT_COLUMN]] ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** [[SQLITE_LIMIT_VDBE_OP]] ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
)^ +** +** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** [[SQLITE_LIMIT_ATTACHED]] ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** [[SQLITE_LIMIT_VARIABLE_NUMBER]] +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes as this saves SQLite from having to +** make a copy of the input string. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. +** the +**
  6. +**
+*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If A Prepared Statement Has Been Reset +** +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the +** [prepared statement] S has been stepped at least once using +** [sqlite3_step(S)] but has not run to completion and/or has not +** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) +** interface returns false if S is a NULL pointer. If S is not a +** NULL pointer and is not a pointer to a valid [prepared statement] +** object, then the behavior is undefined and probably undesirable. +** +** This interface can be used in combination [sqlite3_next_stmt()] +** to locate all prepared statements associated with a database +** connection that are in need of being reset. This can be used, +** for example, in diagnostic routines to search for prepared +** statements that are holding a transaction open. +*/ +SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. An internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() +** is negative, then the length of the string is +** the number of bytes up to the first zero terminator. +** If the fourth parameter to sqlite3_bind_blob() is negative, then +** the behavior is undefined. +** If a non-negative fourth parameter is provided to sqlite3_bind_text() +** or sqlite3_bind_text16() then that parameter must be the byte offset +** where the NUL terminator would occur assuming the string were NUL +** terminated. If any NUL characters occur at byte offsets less than +** the value of the fourth parameter then the resulting string value will +** contain embedded NULs. The result of expressions involving strings +** with embedded NULs is undefined. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the statement is automatically +** reprepared by the first call to [sqlite3_step()] for a particular run +** or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within an +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** ^The sqlite3_data_count(P) routine returns 0 if the previous call to +** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) +** will return non-zero if previous call to [sqlite3_step](P) returned +** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] +** where it always returns zero since each step of that multi-step +** pragma returns 0 columns of data. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero-terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is NULL pointer +**
NULL BLOB Result is NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER Convert from float to integer +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB Same as FLOAT->TEXT +**
TEXT INTEGER Use atoi() +**
TEXT FLOAT Use atof() +**
TEXT BLOB No change +**
BLOB INTEGER Convert to TEXT then use atoi() +**
BLOB FLOAT Convert to TEXT then use atof() +**
BLOB TEXT Add a zero terminator if needed +**
+**
)^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL pointers for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is +** less than or equal to zero or if a memory allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** The following two functions may be used by scalar SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** metadata associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If no metadata has been ever +** been set for the Nth argument of the function, or if the corresponding +** function parameter has changed since the meta-data was set, +** then sqlite3_get_auxdata() returns a NULL pointer. +** +** ^The sqlite3_set_auxdata() interface saves the metadata +** pointed to by its 3rd parameter as the metadata for the N-th +** argument of the application-defined function. Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** ^If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the metadata when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. +** +** SQLite is free to call the destructor and drop metadata on any +** parameter of any function at any time. ^The only guarantee is that +** the destructor will be called before the metadata is dropped. +** +** ^(In practice, metadata is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and [parameters].)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an +** error indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an +** error indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. If the 3rd parameter is non-negative, then it +** must be the byte offset into the string where the NUL terminator would +** appear if the string where NUL terminated. If any NUL characters occur +** in the string at a byte offset that is less than the value of the 3rd +** parameter, then the resulting string will contain embedded NULs and the +** result of expressions operating on strings with embedded NULs is undefined. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is an application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must always return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +SQLITE_API void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +** +** Note to Windows Runtime users: The temporary directory must be set +** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various +** features that require the use of temporary files may fail. Here is an +** example of how to do this using C++ with the Windows Runtime: +** +**
+** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
+**       TemporaryFolder->Path->Data();
+** char zPathBuf[MAX_PATH + 1];
+** memset(zPathBuf, 0, sizeof(zPathBuf));
+** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
+**       NULL, NULL);
+** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
+** 
+*/ +SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Name Of The Folder Holding Database Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all database files +** specified with a relative pathname and created or accessed by +** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed +** to be relative to that directory.)^ ^If this variable is a NULL +** pointer, then SQLite assumes that all database files specified +** with a relative pathname are relative to the current directory +** for the process. Only the windows VFS makes use of this global +** variable; it is ignored by the unix VFS. +** +** Changing the value of this variable while a database connection is +** open can result in a corrupt database. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [data_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [data_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [data_store_directory pragma] should be avoided. +*/ +SQLITE_API SQLITE_EXTERN char *sqlite3_data_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Return The Filename For A Database Connection +** +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename +** associated with database N of connection D. ^The main database file +** has the name "main". If there is no attached database N on the database +** connection D, or if database N is a temporary or in-memory database, then +** a NULL pointer is returned. +** +** ^The filename returned by this function is the output of the +** xFullPathname method of the [VFS]. ^In other words, the filename +** will be an absolute pathname, even if the filename used +** to open the database originally was a URI or relative pathname. +*/ +SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Determine if a database is read-only +** +** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N +** of connection D is read-only, 0 if it is read/write, or -1 if N is not +** the name of a database on connection D. +*/ +SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The commit and rollback hook callbacks are not reentrant. +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that running any other SQL statements, including SELECT statements, +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify +** the database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** See also: [sqlite3_db_release_memory()] +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Free Memory Used By A Database Connection +** +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap +** memory as possible from database connection D. Unlike the +** [sqlite3_release_memory()] interface, this interface is effect even +** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is +** omitted. +** +** See also: [sqlite3_release_memory()] +*/ +SQLITE_API int sqlite3_db_release_memory(sqlite3*); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call, or negative in the case of an +** error. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The soft heap limit is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specified using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** SQLite extension library contained in the file zFile. +** +** ^The entry point is zProc. +** ^zProc may be 0, in which case the name of the entry point +** defaults to "sqlite3_extension_init". +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. See ticket #1863. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked SQLite extension +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()]. +*/ +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); + /* The methods above are in version 1 of the sqlite_module object. Those + ** below are for version 2 and greater. */ + int (*xSavepoint)(sqlite3_vtab *pVTab, int); + int (*xRelease)(sqlite3_vtab *pVTab, int); + int (*xRollbackTo)(sqlite3_vtab *pVTab, int); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_PTHREADS +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
)^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and +** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix +** and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_LRU2 +**
)^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provide versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 +#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 +#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 +#define SQLITE_TESTCTRL_LAST 19 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [status parameters | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** KEYWORDS: {status parameters} +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_SCRATCH_USED]] ^(
SQLITE_STATUS_SCRATCH_USED
+**
This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
)^ +** +** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
)^ +** +** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
SQLITE_STATUS_SCRATCH_SIZE
+**
This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
+**
This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS options], that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS options] is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** KEYWORDS: {SQLITE_DBSTATUS options} +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero.)^ +** +** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
+**
This parameter returns the number of pager cache hits that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
+**
This parameter returns the number of pager cache misses that have +** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS +** is always 0. +**
+** +** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
+**
This parameter returns the number of dirty cache entries that have +** been written to disk. Specifically, the number of pages written to the +** wal file in wal mode databases, or the number of pages written to the +** database file in rollback mode databases. Any pages written as part of +** transaction rollback or database recovery operations are not included. +** If an IO or other error occurs while writing a page to disk, the effect +** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The +** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_CACHE_HIT 7 +#define SQLITE_DBSTATUS_CACHE_MISS 8 +#define SQLITE_DBSTATUS_CACHE_WRITE 9 +#define SQLITE_DBSTATUS_MAX 9 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache_page object represents a single page in the +** page cache. The page cache will allocate instances of this +** object. Various methods of the page cache use pointers to instances +** of this object as parameters or as their return value. +** +** See [sqlite3_pcache_methods2] for additional information. +*/ +typedef struct sqlite3_pcache_page sqlite3_pcache_page; +struct sqlite3_pcache_page { + void *pBuf; /* The content of the page */ + void *pExtra; /* Extra information associated with the page */ +}; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods2 structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** [[the xInit() page cache method]] +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** [[the xShutdown() page cache method]] +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** [[the xCreate() page cache methods]] +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will always a power of two. ^The +** second parameter szExtra is a number of bytes of extra storage +** associated with each page cache entry. ^The szExtra parameter will +** a number less than 250. SQLite will use the +** extra szExtra bytes on each page to store metadata about the underlying +** database page on disk. The value passed into szExtra depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^The third argument to xCreate(), bPurgeable, is true if the cache being +** created will be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** [[the xCachesize() page cache method]] +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** [[the xPagecount() page cache methods]] +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** [[the xFetch() page cache methods]] +** The xFetch() method locates a page in the cache and returns a pointer to +** an sqlite3_pcache_page object associated with that page, or a NULL pointer. +** The pBuf element of the returned sqlite3_pcache_page object will be a +** pointer to a buffer of szPage bytes used to store the content of a +** single database page. The pExtra element of sqlite3_pcache_page will be +** a pointer to the szExtra bytes of extra storage that SQLite has requested +** for each entry in the page cache. +** +** The page to be fetched is determined by the key. ^The minimum key value +** is 1. After it has been retrieved using xFetch, the page is considered +** to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behaviour when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** [[the xUnpin() page cache method]] +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** [[the xRekey() page cache methods]] +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** [[the xDestroy() page cache method]] +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods2 +** functions. +** +** [[the xShrink() page cache method]] +** ^SQLite invokes the xShrink() method when it wants the page cache to +** free up as much of heap memory as possible. The page cache implementation +** is not obligated to free any memory, but well-behaved implementations should +** do their best. +*/ +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; +struct sqlite3_pcache_methods2 { + int iVersion; + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); + void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, + unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); + void (*xShrink)(sqlite3_pcache*); +}; + +/* +** This is the obsolete pcache_methods object that has now been replaced +** by sqlite3_pcache_methods2. This object is not used by SQLite. It is +** retained in the header file for backwards compatibility only. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** [[sqlite3_backup_init()]] sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** [[sqlite3_backup_step()]] sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** [[sqlite3_backup_finish()]] sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] +** sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications +** and extensions to compare the contents of two buffers containing UTF-8 +** strings in a case-independent fashion, using the same definition of "case +** independence" that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_stricmp(const char *, const char *); +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the error log +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +** +** See also: [sqlite3_wal_checkpoint_v2()] +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** CAPI3REF: Checkpoint a database +** +** Run a checkpoint operation on WAL database zDb attached to database +** handle db. The specific operation is determined by the value of the +** eMode parameter: +** +**
+**
SQLITE_CHECKPOINT_PASSIVE
+** Checkpoint as many frames as possible without waiting for any database +** readers or writers to finish. Sync the db file if all frames in the log +** are checkpointed. This mode is the same as calling +** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. +** +**
SQLITE_CHECKPOINT_FULL
+** This mode blocks (calls the busy-handler callback) until there is no +** database writer and all readers are reading from the most recent database +** snapshot. It then checkpoints all frames in the log file and syncs the +** database file. This call blocks database writers while it is running, +** but not database readers. +** +**
SQLITE_CHECKPOINT_RESTART
+** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after +** checkpointing the log file it blocks (calls the busy-handler callback) +** until all readers are reading from the database file only. This ensures +** that the next client to write to the database file restarts the log file +** from the beginning. This call blocks database writers while it is running, +** but not database readers. +**
+** +** If pnLog is not NULL, then *pnLog is set to the total number of frames in +** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to +** the total number of checkpointed frames (including any that were already +** checkpointed when this function is called). *pnLog and *pnCkpt may be +** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. +** If no values are available because of an error, they are both set to -1 +** before returning to communicate this to the caller. +** +** All calls obtain an exclusive "checkpoint" lock on the database file. If +** any other process is running a checkpoint operation at the same time, the +** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a +** busy-handler configured, it will not be invoked in this case. +** +** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive +** "writer" lock on the database file. If the writer lock cannot be obtained +** immediately, and a busy-handler is configured, it is invoked and the writer +** lock retried until either the busy-handler returns 0 or the lock is +** successfully obtained. The busy-handler is also invoked while waiting for +** database readers as described above. If the busy-handler returns 0 before +** the writer lock is obtained or while waiting for database readers, the +** checkpoint operation proceeds from that point in the same way as +** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible +** without blocking any further. SQLITE_BUSY is returned in this case. +** +** If parameter zDb is NULL or points to a zero length string, then the +** specified operation is attempted on all WAL databases. In this case the +** values written to output parameters *pnLog and *pnCkpt are undefined. If +** an SQLITE_BUSY error is encountered when processing one or more of the +** attached WAL databases, the operation is still attempted on any remaining +** attached databases and SQLITE_BUSY is returned to the caller. If any other +** error occurs while processing an attached database, processing is abandoned +** and the error code returned to the caller immediately. If no error +** (SQLITE_BUSY or otherwise) is encountered while processing the attached +** databases, SQLITE_OK is returned. +** +** If database zDb is the name of an attached database that is not in WAL +** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If +** zDb is not NULL (or a zero length string) and is not the name of any +** attached database, SQLITE_ERROR is returned to the caller. +*/ +SQLITE_API int sqlite3_wal_checkpoint_v2( + sqlite3 *db, /* Database handle */ + const char *zDb, /* Name of attached database (or NULL) */ + int eMode, /* SQLITE_CHECKPOINT_* value */ + int *pnLog, /* OUT: Size of WAL log in frames */ + int *pnCkpt /* OUT: Total number of frames checkpointed */ +); + +/* +** CAPI3REF: Checkpoint operation parameters +** +** These constants can be used as the 3rd parameter to +** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] +** documentation for additional information about the meaning and use of +** each of these values. +*/ +#define SQLITE_CHECKPOINT_PASSIVE 0 +#define SQLITE_CHECKPOINT_FULL 1 +#define SQLITE_CHECKPOINT_RESTART 2 + +/* +** CAPI3REF: Virtual Table Interface Configuration +** +** This function may be called by either the [xConnect] or [xCreate] method +** of a [virtual table] implementation to configure +** various facets of the virtual table interface. +** +** If this interface is invoked outside the context of an xConnect or +** xCreate virtual table method then the behavior is undefined. +** +** At present, there is only one option that may be configured using +** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options +** may be added in the future. +*/ +SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Virtual Table Configuration Options +** +** These macros define the various options to the +** [sqlite3_vtab_config()] interface that [virtual table] implementations +** can use to customize and optimize their behavior. +** +**
+**
SQLITE_VTAB_CONSTRAINT_SUPPORT +**
Calls of the form +** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, +** where X is an integer. If X is zero, then the [virtual table] whose +** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not +** support constraints. In this configuration (which is the default) if +** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire +** statement is rolled back as if [ON CONFLICT | OR ABORT] had been +** specified as part of the users SQL statement, regardless of the actual +** ON CONFLICT mode specified. +** +** If X is non-zero, then the virtual table implementation guarantees +** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before +** any modifications to internal or persistent data structures have been made. +** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite +** is able to roll back a statement or database transaction, and abandon +** or continue processing the current SQL statement as appropriate. +** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns +** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode +** had been ABORT. +** +** Virtual table implementations that are required to handle OR REPLACE +** must do so within the [xUpdate] method. If a call to the +** [sqlite3_vtab_on_conflict()] function indicates that the current ON +** CONFLICT policy is REPLACE, the virtual table implementation should +** silently replace the appropriate rows within the xUpdate callback and +** return SQLITE_OK. Or, if this is not possible, it may return +** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT +** constraint handling. +**
+*/ +#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 + +/* +** CAPI3REF: Determine The Virtual Table Conflict Policy +** +** This function may only be called from within a call to the [xUpdate] method +** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The +** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], +** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode +** of the SQL statement that triggered the call to the [xUpdate] method of the +** [virtual table]. +*/ +SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); + +/* +** CAPI3REF: Conflict resolution modes +** +** These constants are returned by [sqlite3_vtab_on_conflict()] to +** inform a [virtual table] implementation what the [ON CONFLICT] mode +** is for the SQL statement being evaluated. +** +** Note that the [SQLITE_IGNORE] constant is also used as a potential +** return value from the [sqlite3_set_authorizer()] callback and that +** [SQLITE_ABORT] is also a [result code]. +*/ +#define SQLITE_ROLLBACK 1 +/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ +#define SQLITE_FAIL 3 +/* #define SQLITE_ABORT 4 // Also an error code */ +#define SQLITE_REPLACE 5 + + + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#ifdef __cplusplus +} /* End of the 'extern "C"' block */ +#endif +#endif + +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, +#ifdef SQLITE_RTREE_INT_ONLY + int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes), +#else + int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes), +#endif + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + diff --git a/engine/server/sv_init.c b/engine/server/sv_init.c index 7be9c08e..43955664 100644 --- a/engine/server/sv_init.c +++ b/engine/server/sv_init.c @@ -42,6 +42,7 @@ extern cvar_t sv_gamespeed; extern cvar_t sv_csqcdebug; extern cvar_t sv_csqc_progname; extern cvar_t sv_calcphs; +extern cvar_t sv_playerslots; /* ================ @@ -1042,7 +1043,10 @@ void SV_SpawnServer (char *server, char *startspot, qboolean noents, qboolean us if (!isDedicated && !deathmatch.value && !coop.value) sv.allocated_client_slots = 1; else - sv.allocated_client_slots = MAX_CLIENTS; + sv.allocated_client_slots = QWMAX_CLIENTS; + if (sv_playerslots.ival > 0) + sv.allocated_client_slots = sv_playerslots.ival; + sv.allocated_client_slots = bound(1, sv.allocated_client_slots, MAX_CLIENTS); //bound it // leave slots at start for clients only for (i=0 ; i 4) + if (numssclients<1 || numssclients > MAX_SPLITS) { SV_RejectMessage (SCP_BAD, "Server is %s.\n", version_string()); Con_Printf ("* rejected connect from broken client\n"); @@ -4150,6 +4159,7 @@ void SV_InitLocal (void) Cvar_Register (&pm_walljump, cvargroup_serverphysics); Cvar_Register (&sv_compatiblehulls, cvargroup_serverphysics); + Cvar_Register (&dpcompat_stats, "Darkplaces compatibility"); for (i = 0; i < sizeof(sv_motd)/sizeof(sv_motd[0]); i++) Cvar_Register(&sv_motd[i], cvargroup_serverinfo); diff --git a/engine/server/sv_mvd.c b/engine/server/sv_mvd.c index 409fdaae..a0089b3e 100644 --- a/engine/server/sv_mvd.c +++ b/engine/server/sv_mvd.c @@ -2035,38 +2035,26 @@ void SV_MVD_QTVReverse_f (void) char *data; int sock; - struct sockaddr_in local; struct sockaddr_qstorage remote; // int fromlen; + int adrfam; + int adrsz; unsigned int nonblocking = true; - if (!NET_StringToSockaddr(ip, &remote)) + if (!NET_StringToSockaddr(ip, 0, &remote, &adrfam, &adrsz)) { Con_Printf ("qtvreverse: failed to resolve address\n"); return; } - - local.sin_family = AF_INET; - local.sin_addr.s_addr = INADDR_ANY; - local.sin_port = 0; - - if ((sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) + if ((sock = socket (adrfam, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { Con_Printf ("qtvreverse: socket: %s\n", strerror(qerrno)); return; } - - if( bind (sock, (void *)&local, sizeof(local)) == INVALID_SOCKET) - { - closesocket(sock); - Con_Printf ("qtvreverse: bind: %s\n", strerror(qerrno)); - return; - } - - if (connect(sock, (void*)&remote, sizeof(remote)) == INVALID_SOCKET) + if (connect(sock, (void*)&remote, adrsz) == INVALID_SOCKET) { closesocket(sock); Con_Printf ("qtvreverse: connect: %s\n", strerror(qerrno)); @@ -2467,10 +2455,10 @@ void SV_MVDList_f (void) for (d = demo.dest; d; d = d->nextdest) { if (!strcmp(list->name, d->name)) - Con_Printf("*%d: %s %dk\n", i, list->name, d->totalsize/1024); + Con_Printf("*%d: ^[^7%s\\demo\\%s/%s^] %dk\n", i, list->name, sv_demoDir.string, list->name, d->totalsize/1024); } if (!d) - Con_Printf("%d: %s %dk\n", i, list->name, list->size/1024); + Con_Printf("%d: ^[^7%s\\demo\\%s/%s^] %dk\n", i, list->name, sv_demoDir.string, list->name, list->size/1024); } } diff --git a/engine/server/sv_phys.c b/engine/server/sv_phys.c index e969f818..93041bd9 100644 --- a/engine/server/sv_phys.c +++ b/engine/server/sv_phys.c @@ -1832,7 +1832,6 @@ void WPhys_RunEntity (world_t *w, wedict_t *ent) host_client = &svs.clients[ent->entnum-1]; SV_ClientThink(); - if (progstype == PROG_QW) //detect if the mod should do a jump if (svent->v->button2) if ((int)svent->v->flags & FL_JUMPRELEASED) diff --git a/engine/server/sv_send.c b/engine/server/sv_send.c index 48db7bc6..ada08ec2 100644 --- a/engine/server/sv_send.c +++ b/engine/server/sv_send.c @@ -30,6 +30,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #define CHAN_BODY 4 extern cvar_t sv_gravity, sv_friction, sv_waterfriction, sv_gamespeed, sv_stopspeed, sv_spectatormaxspeed, sv_accelerate, sv_airaccelerate, sv_wateraccelerate, sv_edgefriction; +extern cvar_t dpcompat_stats; /* ============================================================================= diff --git a/engine/server/sv_sql.c b/engine/server/sv_sql.c index d99835d0..ee6b3d95 100644 --- a/engine/server/sv_sql.c +++ b/engine/server/sv_sql.c @@ -1,8 +1,12 @@ #include "quakedef.h" +//SQLITE: +//should probably be compiled with -DSQLITE_OMIT_ATTACH -DSQLITE_OMIT_LOAD_EXTENSION which would mean we don't need to override authorisation. + #ifdef SQL #include "sv_sql.h" +#ifdef USE_MYSQL static void (VARGS *qmysql_library_end)(void); static int (VARGS *qmysql_library_init)(int argc, char **argv, char **groups); @@ -55,6 +59,41 @@ static dllfunction_t mysqlfuncs[] = {(void*)&qmysql_thread_safe, "mysql_thread_safe"}, {NULL} }; +#endif + +#ifdef USE_SQLITE +SQLITE_API int (QDECL *qsqlite3_open)(const char *zFilename, sqlite3 **ppDb); +SQLITE_API const char *(QDECL *qsqlite3_libversion)(void); +SQLITE_API int (QDECL *qsqlite3_set_authorizer)(sqlite3*, int (QDECL *xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData); +SQLITE_API int (QDECL *qsqlite3_enable_load_extension)(sqlite3 *db, int onoff); +SQLITE_API const char *(QDECL *qsqlite3_errmsg)(sqlite3 *db); +SQLITE_API int (QDECL *qsqlite3_close)(sqlite3 *db); + +SQLITE_API int (QDECL *qsqlite3_prepare)(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail); +SQLITE_API int (QDECL *qsqlite3_column_count)(sqlite3_stmt *pStmt); +SQLITE_API const char *(QDECL *qsqlite3_column_name)(sqlite3_stmt *pStmt, int N); +SQLITE_API int (QDECL *qsqlite3_step)(sqlite3_stmt *pStmt); +SQLITE_API const unsigned char *(QDECL *qsqlite3_column_text)(sqlite3_stmt *pStmt, int i); +SQLITE_API int (QDECL *qsqlite3_finalize)(sqlite3_stmt *pStmt); + +static dllfunction_t sqlitefuncs[] = +{ + {(void*)&qsqlite3_open, "sqlite3_open"}, /* written as a define alias in mysql.h */ + {(void*)&qsqlite3_libversion, "sqlite3_libversion"}, /* written as a define alias in mysql.h */ + {(void*)&qsqlite3_set_authorizer, "sqlite3_set_authorizer"}, + {(void*)&qsqlite3_enable_load_extension, "sqlite3_enable_load_extension"}, + {(void*)&qsqlite3_errmsg, "sqlite3_errmsg"}, + {(void*)&qsqlite3_close, "sqlite3_close"}, + + {(void*)&qsqlite3_prepare, "sqlite3_prepare"}, + {(void*)&qsqlite3_column_count, "sqlite3_column_count"}, + {(void*)&qsqlite3_column_name, "sqlite3_column_name"}, + {(void*)&qsqlite3_step, "sqlite3_step"}, + {(void*)&qsqlite3_column_text, "sqlite3_column_text"}, + {(void*)&qsqlite3_finalize, "sqlite3_finalize"}, + {NULL} +}; +#endif cvar_t sql_driver = SCVARF("sv_sql_driver", "mysql", CVAR_NOUNSAFEEXPAND); cvar_t sql_host = SCVARF("sv_sql_host", "127.0.0.1", CVAR_NOUNSAFEEXPAND); @@ -119,46 +158,87 @@ queryrequest_t *SQL_PullRequest(sqlserver_t *server, qboolean lock) sqlserver_t **sqlservers; int sqlservercount; -qboolean sqlavailable; +int sqlavailable; + +#ifdef USE_SQLITE +//this is to try to sandbox sqlite so it can only edit the file its originally opened with. +int QDECL mysqlite_authorizer(void *ctx, int action, const char *detail0, const char *detail1, const char *detail2, const char *detail3) +{ + if (action == SQLITE_PRAGMA) + { + Sys_Printf("SQL: Rejecting pragma \"%s\"\n", detail0); + return SQLITE_DENY; + } + if (action == SQLITE_ATTACH) + { + Sys_Printf("SQL: Rejecting attach to \"%s\"\n", detail0); + return SQLITE_DENY; + } + return SQLITE_OK; +} +#endif int sql_serverworker(void *sref) { sqlserver_t *server = (sqlserver_t *)sref; - char *error = NULL; - my_bool reconnect = 1; - int tinit, i; + const char *error = NULL; + int tinit = -1, i; qboolean needlock = false; - if (tinit = qmysql_thread_init()) - error = "MYSQL thread init failed"; - else if (!(server->mysql = qmysql_init(NULL))) - error = "MYSQL init failed"; - else if (qmysql_options(server->mysql, MYSQL_OPT_RECONNECT, &reconnect)) - error = "MYSQL reconnect options set failed"; - else - { - int port = 0; - char *colon; - - colon = strchr(server->connectparams[0], ':'); - if (colon) + switch(server->driver) + { +#ifdef USE_MYSQL + case SQLDRV_MYSQL: { - *colon = '\0'; - port = atoi(colon + 1); + my_bool reconnect = 1; + if (!qmysql_thread_init) + error = "MYSQL library not available"; + else if (tinit = qmysql_thread_init()) + error = "MYSQL thread init failed"; + else if (!(server->mysql = qmysql_init(NULL))) + error = "MYSQL init failed"; + else if (qmysql_options(server->mysql, MYSQL_OPT_RECONNECT, &reconnect)) + error = "MYSQL reconnect options set failed"; + else + { + int port = 0; + char *colon; + + colon = strchr(server->connectparams[0], ':'); + if (colon) + { + *colon = '\0'; + port = atoi(colon + 1); + } + + if (!(server->mysql = qmysql_real_connect(server->mysql, server->connectparams[0], server->connectparams[1], server->connectparams[2], server->connectparams[3], port, 0, 0))) + error = "MYSQL initial connect attempt failed"; + + if (colon) + *colon = ':'; + } } - - if (!(server->mysql = qmysql_real_connect(server->mysql, server->connectparams[0], server->connectparams[1], server->connectparams[2], server->connectparams[3], port, 0, 0))) - error = "MYSQL initial connect attempt failed"; - - if (colon) - *colon = ':'; + break; +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + if (qsqlite3_open(server->connectparams[3], &server->sqlite)) + { + error = qsqlite3_errmsg(server->sqlite); + } + else + { + //disable extension loading, set up an authorizer hook. + qsqlite3_enable_load_extension(server->sqlite, false); + qsqlite3_set_authorizer(server->sqlite, mysqlite_authorizer, server); + } + break; +#endif + default: + error = "That driver is not enabled in this build."; + break; } - for (i = SQL_CONNECT_STRUCTPARAMS; i < SQL_CONNECT_PARAMS; i++) - Z_Free(server->connectparams[i]); - - BZ_Realloc(server->connectparams, sizeof(char *) * SQL_CONNECT_STRUCTPARAMS); - if (error) server->active = false; @@ -174,10 +254,10 @@ int sql_serverworker(void *sref) queryrequest_t *qreq = NULL; queryresult_t *qres; const char *qerror = NULL; - MYSQL_RES *mysqlres = NULL; int rows = -1; int columns = -1; int qesize = 0; + void *res = NULL; if (!(qreq = SQL_PullRequest(server, needlock))) break; @@ -186,55 +266,177 @@ int sql_serverworker(void *sref) // a lock next round needlock = true; - // perform the query and fill out the result structure - if (qmysql_query(server->mysql, qreq->query)) - qerror = qmysql_error(server->mysql); - else // query succeeded + switch(server->driver) { - mysqlres = qmysql_store_result(server->mysql); - if (mysqlres) // result set returned - { - rows = qmysql_num_rows(mysqlres); - columns = qmysql_num_fields(mysqlres); - } - else if (qmysql_field_count(server->mysql) == 0) // no result set - { - rows = qmysql_affected_rows(server->mysql); - if (rows < 0) - rows = 0; - columns = 0; - } - else // error +#ifdef USE_MYSQL + case SQLDRV_MYSQL: + // perform the query and fill out the result structure + if (qmysql_query(server->mysql, qreq->query)) qerror = qmysql_error(server->mysql); - } + else // query succeeded + { + res = qmysql_store_result(server->mysql); + if (res) // result set returned + { + rows = qmysql_num_rows(res); + columns = qmysql_num_fields(res); + } + else if (qmysql_field_count(server->mysql) == 0) // no result set + { + rows = qmysql_affected_rows(server->mysql); + if (rows < 0) + rows = 0; + columns = 0; + } + else // error + qerror = qmysql_error(server->mysql); + + } - if (qerror) - qesize = Q_strlen(qerror); - qres = (queryresult_t *)ZF_Malloc(sizeof(queryresult_t) + qesize); - if (qres) - { if (qerror) - Q_strncpy(qres->error, qerror, qesize); - qres->result = mysqlres; - qres->rows = rows; - qres->columns = columns; - qres->request = qreq; - qres->eof = true; // store result has no more rows to read afterwards - qreq->next = NULL; + qesize = Q_strlen(qerror); + qres = (queryresult_t *)ZF_Malloc(sizeof(queryresult_t) + qesize); + if (qres) + { + if (qerror) + Q_strncpy(qres->error, qerror, qesize); + qres->result = res; + qres->rows = rows; + qres->columns = columns; + qres->request = qreq; + qres->eof = true; // store result has no more rows to read afterwards + qreq->next = NULL; - SQL_PushResult(server, qres); - } - else // we're screwed here so bomb out - { - server->active = false; - error = "MALLOC ERROR! Unable to allocate query result!"; + SQL_PushResult(server, qres); + } + else // we're screwed here so bomb out + { + server->active = false; + error = "MALLOC ERROR! Unable to allocate query result!"; + break; + } break; +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + { + int rc; + sqlite3_stmt *pStmt; + const char *trailingstring; + char *statementstring = qreq->query; + char **mat; + int matsize; + int rowspace; + qboolean keeplooping = true; + +// qsqlite3_mutex_enter(server->sqlite->mutex); +// while(*statementstring) +// { + if (qsqlite3_prepare(server->sqlite, statementstring, -1, &pStmt, &trailingstring) == SQLITE_OK) + { //sql statement is valid, apparently. + columns = qsqlite3_column_count(pStmt); + + rc = qsqlite3_step(pStmt); + while(keeplooping) + { + rowspace = 65; + + matsize = columns * sizeof(char*); + + qres = (queryresult_t *)ZF_Malloc(sizeof(queryresult_t) + columns * sizeof(char*) * rowspace); + mat = (char**)(qres + 1); + if (qres) + { + qres->result = mat; + qres->rows = 0; + qres->columns = columns; + qres->request = qreq; + qres->eof = false; + qreq->next = NULL; + + //headers technically take a row. + for (i = 0; i < columns; i++) + { + mat[i] = strdup(qsqlite3_column_name(pStmt, i)); + } + rowspace--; + mat += columns; + + while(1) + { + if (rc == SQLITE_ROW) + { + if (!rowspace) + break; + + //generate the row info + for (i = 0; i < columns; i++) + mat[i] = strdup(qsqlite3_column_text(pStmt, i)); + qres->rows++; + rowspace--; + mat += columns; + } + else if (rc == SQLITE_DONE) + { + //no more data to get. + keeplooping = false; + qres->eof = true; //this one was the ender. + break; + } + + rc = qsqlite3_step(pStmt); + } + } + else + keeplooping = false; + + SQL_PushResult(server, qres); + } + qsqlite3_finalize(pStmt); + } + else + { + char *queryerror = va("Bad SQL statement %s", statementstring); + qres = (queryresult_t *)ZF_Malloc(sizeof(queryresult_t) + strlen(queryerror)); + if (qres) + { + strcpy(qres->error, queryerror); + qres->result = NULL; + qres->rows = 0; + qres->columns = -1; + qres->request = qreq; + qres->eof = true; + qreq->next = NULL; + + SQL_PushResult(server, qres); + } + break; + } +// statementstring = trailingstring; +// } +// qsqlite3_mutex_leave(server->sqlite->mutex); + } + break; +#endif } } } - if (server->mysql) - qmysql_close(server->mysql); + switch(server->driver) + { +#ifdef USE_MYSQL + case SQLDRV_MYSQL: + if (server->mysql) + qmysql_close(server->mysql); + break; +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + qsqlite3_close(server->sqlite); + server->sqlite = NULL; + break; +#endif + } // if we have a server error we still need to put it on the queue if (error) @@ -250,9 +452,12 @@ int sql_serverworker(void *sref) } } +#ifdef USE_MYSQL if (!tinit) qmysql_thread_end(); +#endif + server->terminated = true; return 0; } @@ -260,6 +465,8 @@ sqlserver_t *SQL_GetServer (int serveridx, qboolean inactives) { if (serveridx < 0 || serveridx >= sqlservercount) return NULL; + if (!sqlservers[serveridx]) + return NULL; if (!inactives && sqlservers[serveridx]->active == false) return NULL; return sqlservers[serveridx]; @@ -280,11 +487,29 @@ queryresult_t *SQL_GetQueryResult (sqlserver_t *server, int queryidx) return NULL; } -void SQL_DeallocResult(queryresult_t *qres) +static void SQL_DeallocResult(sqlserver_t *server, queryresult_t *qres) { // deallocate current result - if (qres->result) - qmysql_free_result(qres->result); + switch(server->driver) + { +#ifdef USE_MYSQL + case SQLDRV_MYSQL: + if (qres->result) + qmysql_free_result(qres->result); + break; +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + if (qres->result) + { + char **mat = qres->result; + int i; + for (i = 0; i < qres->columns * (qres->rows+1); i++) + free(mat[i]); + } + break; +#endif + } if (qres->request) Z_Free(qres->request); @@ -299,7 +524,7 @@ void SQL_ClosePersistantResult(sqlserver_t *server, queryresult_t *qres) if (prev == qres) { server->persistresults = prev->next; - SQL_DeallocResult(prev); + SQL_DeallocResult(server, prev); return; } @@ -308,7 +533,7 @@ void SQL_ClosePersistantResult(sqlserver_t *server, queryresult_t *qres) if (cur == qres) { prev = cur->next; - SQL_DeallocResult(cur); + SQL_DeallocResult(server, cur); return; } } @@ -320,7 +545,7 @@ void SQL_CloseResult(sqlserver_t *server, queryresult_t *qres) return; if (qres == server->currentresult) { - SQL_DeallocResult(server->currentresult); + SQL_DeallocResult(server, server->currentresult); server->currentresult = NULL; return; } @@ -338,12 +563,12 @@ void SQL_CloseAllResults(sqlserver_t *server) { oldqres = qres; qres = qres->next; - SQL_DeallocResult(oldqres); + SQL_DeallocResult(server, oldqres); } // close current if (server->currentresult) { - SQL_DeallocResult(server->currentresult); + SQL_DeallocResult(server, server->currentresult); server->currentresult = NULL; } // close persistant results @@ -352,13 +577,13 @@ void SQL_CloseAllResults(sqlserver_t *server) { oldqres = qres; qres = qres->next; - SQL_DeallocResult(oldqres); + SQL_DeallocResult(server, oldqres); } server->persistresults = NULL; // close server result if (server->serverresult) { - SQL_DeallocResult(server->serverresult); + SQL_DeallocResult(server, server->serverresult); server->serverresult = NULL; } } @@ -376,50 +601,141 @@ char *SQL_ReadField (sqlserver_t *server, queryresult_t *qres, int row, int col, { // fetch field name if (fields) // but only if we asked for them { - MYSQL_FIELD *field; + switch(server->driver) + { +#ifdef USE_MYSQL + case SQLDRV_MYSQL: + { + MYSQL_FIELD *field = qmysql_fetch_field_direct(qres->result, col); - field = qmysql_fetch_field_direct(qres->result, col); - - if (!field) + if (!field) + return NULL; + else + return field->name; + } +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + { + char **mat = qres->result; + if (mat) + return mat[col]; + } return NULL; - else - return field->name; +#endif + default: + return NULL; + } } else return NULL; } else { // fetch data - MYSQL_ROW sqlrow; + switch(server->driver) + { +#ifdef USE_MYSQL + case SQLDRV_MYSQL: + { + MYSQL_ROW sqlrow; - qmysql_data_seek(qres->result, row); - sqlrow = qmysql_fetch_row(qres->result); - if (!sqlrow || !sqlrow[col]) + qmysql_data_seek(qres->result, row); + sqlrow = qmysql_fetch_row(qres->result); + if (!sqlrow || !sqlrow[col]) + return NULL; + else + return sqlrow[col]; + } +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + { + char **mat = qres->result; + col += qres->columns * (row+1); + if (mat) + return mat[col]; + } + return NULL; +#endif + default: return NULL; - else - return sqlrow[col]; + } } } } +void SQL_CleanupServer(sqlserver_t *server) +{ + int i; + queryrequest_t *qreq, *oldqreq; + + server->active = false; // set thread to kill itself + if (server->requestcondv) + Sys_ConditionBroadcast(server->requestcondv); // force condition check + if (server->thread) + Sys_WaitOnThread(server->thread); // wait on thread to die + + // server resource deallocation (TODO: should this be done in the thread itself?) + if (server->requestcondv) + Sys_DestroyConditional(server->requestcondv); + if (server->resultlock) + Sys_DestroyMutex(server->resultlock); + + // close orphaned requests + qreq = server->requests; + while (qreq) + { + oldqreq = qreq; + qreq = qreq->next; + Z_Free(oldqreq); + } + + SQL_CloseAllResults(server); + + for (i = SQL_CONNECT_STRUCTPARAMS; i < SQL_CONNECT_PARAMS; i++) + Z_Free(server->connectparams[i]); + if (server->connectparams) + BZ_Free(server->connectparams); + + Z_Free(server); +} + int SQL_NewServer(char *driver, char **paramstr) { sqlserver_t *server; int serverref; int drvchoice; int paramsize[SQL_CONNECT_PARAMS]; + char nativepath[MAX_OSPATH]; int i, tsize; - for (i = 0; i < SQL_CONNECT_PARAMS; i++) - paramsize[i] = Q_strlen(paramstr[i]); - if (Q_strcasecmp(driver, "mysql") == 0) drvchoice = SQLDRV_MYSQL; else if (Q_strcasecmp(driver, "sqlite") == 0) - return -1; // drvchoice = SQLDRV_SQLITE; + drvchoice = SQLDRV_SQLITE; else // invalid driver choice so we bomb out return -1; + if (!(sqlavailable & (1u<driver) { +#ifdef USE_MYSQL case SQLDRV_MYSQL: - srclen = strlen(dst); - if (srclen > (dstlen / 2 - 1)) - dst[0] = '\0'; - qmysql_real_escape_string(server->mysql, dst, src, srclen); + { + int srclen = strlen(dst); + if (srclen > (dstlen / 2 - 1)) + dst[0] = '\0'; + else + qmysql_real_escape_string(server->mysql, dst, src, srclen); + } break; +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + { + dstlen--; + while (dstlen > 2 && *src) + { + if (*src == '\'') + { + *dst++ = *src; + dstlen--; + } + *dst++ = *src++; + dstlen--; + } + *dst = '\0'; + } + break; +#endif default: dst[0] = '\0'; } } -char *SQL_Info(sqlserver_t *server) +const char *SQL_Info(sqlserver_t *server) { switch (server->driver) { +#ifdef USE_MYSQL case SQLDRV_MYSQL: - return va("mysql: %s", qmysql_get_client_info()); + if (qmysql_get_client_info) + return va("mysql: %s", qmysql_get_client_info()); + else + return "ERROR: mysql library not loaded"; break; +#endif +#ifdef USE_SQLITE + case SQLDRV_SQLITE: + if (qsqlite3_libversion) + return va("sqlite: %s", qsqlite3_libversion()); + else + return "ERROR: sqlite library not loaded"; +#endif default: return "unknown"; } @@ -560,7 +909,7 @@ char *SQL_Info(sqlserver_t *server) qboolean SQL_Available(void) { - return sqlavailable; + return !!sqlavailable; } /* SQL related commands */ @@ -568,7 +917,10 @@ void SQL_Status_f(void) { int i; - Con_Printf("%i connections\n", sqlservercount); + if (!SQL_Available()) + Con_Printf("No SQL library available.\n"); + else + Con_Printf("%i connections\n", sqlservercount); for (i = 0; i < sqlservercount; i++) { int reqnum = 0; @@ -578,6 +930,9 @@ void SQL_Status_f(void) sqlserver_t *server = sqlservers[i]; + if (!server) + continue; + Sys_LockMutex(server->resultlock); Sys_LockConditional(server->requestcondv); for (qreq = server->requests; qreq; qreq = qreq->next) @@ -585,11 +940,22 @@ void SQL_Status_f(void) for (qres = server->results; qres; qres = qres->next) resnum++; - Con_Printf("#%i %s@%s: %s\n", - i, - server->connectparams[1], - server->connectparams[0], - server->active ? "active" : "inactive"); + switch(server->driver) + { + case SQLDRV_MYSQL: + Con_Printf("#%i %s@%s: %s\n", + i, + server->connectparams[1], + server->connectparams[0], + server->active ? "active" : "inactive"); + break; + case SQLDRV_SQLITE: + Con_Printf("#%i %s: %s\n", + i, + server->connectparams[3], + server->active ? "active" : "inactive"); + break; + } if (reqnum) { @@ -661,6 +1027,16 @@ void SQL_ServerCycle (progfuncs_t *prinst, struct globalvars_s *pr_globals) sqlserver_t *server = sqlservers[i]; queryresult_t *qres; + if (!server) + continue; + + if (server->terminated) + { + sqlservers[i] = NULL; + SQL_CleanupServer(server); + continue; + } + while (qres = SQL_PullResult(server)) { qres->next = NULL; @@ -719,6 +1095,7 @@ void SQL_ServerCycle (progfuncs_t *prinst, struct globalvars_s *pr_globals) } } +#ifdef USE_MYSQL void SQL_MYSQLInit(void) { if (!(mysqlhandle = Sys_LoadLibrary("libmysql", mysqlfuncs))) @@ -732,7 +1109,7 @@ void SQL_MYSQLInit(void) if (!qmysql_library_init(0, NULL, NULL)) { Con_Printf("MYSQL backend loaded\n"); - sqlavailable = true; + sqlavailable |= 1u<active = false; // set thread to kill itself - Sys_ConditionBroadcast(server->requestcondv); // force condition check - Sys_WaitOnThread(server->thread); // wait on thread to die - - // server resource deallocation (TODO: should this be done in the thread itself?) - Sys_DestroyConditional(server->requestcondv); - Sys_DestroyMutex(server->resultlock); - - // close orphaned requests - qreq = server->requests; - while (qreq) - { - oldqreq = qreq; - qreq = qreq->next; - Z_Free(oldqreq); - } - - SQL_CloseAllResults(server); - - // the alloc'ed connect params should get deallocated by the thread - if (server->connectparams) - BZ_Free(server->connectparams); - - Z_Free(server); + sqlservers[i] = NULL; + if (!server) + continue; + SQL_CleanupServer(server); } if (sqlservers) Z_Free(sqlservers); @@ -805,9 +1174,12 @@ void SQL_DeInit(void) SQL_KillServers(); - qmysql_library_end(); +#ifdef USE_MYSQL + if (qmysql_library_end) + qmysql_library_end(); Sys_CloseLibrary(mysqlhandle); +#endif } #endif diff --git a/engine/server/sv_sql.h b/engine/server/sv_sql.h index d6c8a04b..b1c9f2a5 100644 --- a/engine/server/sv_sql.h +++ b/engine/server/sv_sql.h @@ -1,6 +1,16 @@ -#ifndef MYSQLDLL_H -#define MYSQLDLL_H -#include +#ifndef SV_SQL_H +#define SV_SQL_H + +#ifdef USE_MYSQL + #ifdef _WIN32 + #include + #endif + #include +#endif + +#ifdef USE_SQLITE + #include "sqlite3.h" +#endif dllhandle_t *mysqlhandle; @@ -34,7 +44,7 @@ typedef struct queryresult_s int rows; /* rows contained in single result set */ int columns; /* fields */ qboolean eof; /* end of query reached */ - MYSQL_RES *result; /* result set from mysql */ + void *result; /* result set from mysql */ #if 0 char **resultset; /* stored result set from partial fetch */ #endif @@ -45,8 +55,14 @@ typedef struct sqlserver_s { void *thread; /* worker thread for server */ sqldrv_t driver; /* driver type */ +#ifdef USE_MYSQL MYSQL *mysql; /* mysql server */ +#endif +#ifdef USE_SQLITE + sqlite3 *sqlite; +#endif volatile qboolean active; /* set to false to kill thread */ + volatile qboolean terminated; /* set by the worker to say that it won't block (for long) and can be joined */ void *requestcondv; /* lock and conditional variable for queue read/write */ void *resultlock; /* mutex for queue read/write */ int querynum; /* next reference number for queries */ @@ -67,7 +83,7 @@ void SQL_DeInit(void); sqlserver_t *SQL_GetServer (int serveridx, qboolean inactives); queryresult_t *SQL_GetQueryResult (sqlserver_t *server, int queryidx); -void SQL_DeallocResult(queryresult_t *qres); +//void SQL_DeallocResult(sqlserver_t *server, queryresult_t *qres); void SQL_ClosePersistantResult(sqlserver_t *server, queryresult_t *qres); void SQL_CloseResult(sqlserver_t *server, queryresult_t *qres); void SQL_CloseAllResults(sqlserver_t *server); @@ -76,7 +92,7 @@ int SQL_NewServer(char *driver, char **paramstr); int SQL_NewQuery(sqlserver_t *server, int callfunc, int type, int self, float selfid, int other, float otherid, char *str); void SQL_Disconnect(sqlserver_t *server); void SQL_Escape(sqlserver_t *server, char *src, char *dst, int dstlen); -char *SQL_Info(sqlserver_t *server); +const char *SQL_Info(sqlserver_t *server); qboolean SQL_Available(void); void SQL_ServerCycle (progfuncs_t *prinst, struct globalvars_s *pr_globals); diff --git a/engine/server/sv_sys_win.c b/engine/server/sv_sys_win.c index 8c6cbbfc..4fda6e8e 100644 --- a/engine/server/sv_sys_win.c +++ b/engine/server/sv_sys_win.c @@ -650,7 +650,7 @@ char *Sys_ConsoleInput (void) if (c == '\t') { int i; - char *s = Cmd_CompleteCommand(coninput_text, true, true, 0); + char *s = Cmd_CompleteCommand(coninput_text, true, true, 0, NULL); if(s) { for (i = 0; i < coninput_len; i++) @@ -724,6 +724,8 @@ void ApplyColour(unsigned int chr) void Sys_PrintColouredChar(unsigned int chr) { + if (chr & CON_HIDDEN) + return; ApplyColour(chr); printf("%c", chr & CON_CHARMASK); @@ -765,29 +767,16 @@ void Sys_Printf (char *fmt, ...) putch('\b'); } - - for (t = (unsigned char*)msg; *t; t++) - { - if (*t >= 146 && *t < 156) - *t = *t - 146 + '0'; - if (*t >= 0x12 && *t <= 0x1b) - *t = *t - 0x12 + '0'; - if (*t == 143) - *t = '.'; - if (*t == 157 || *t == 158 || *t == 159) - *t = '-'; - if (*t >= 128) - *t -= 128; - if (*t == 16) - *t = '['; - if (*t == 17) - *t = ']'; - if (*t == 0x1c) - *t = 249; - } - if (sys_colorconsole.value && hconsoleout) { +#if 1 + conchar_t out[MAXPRINTMSG], *c, *end; + end = COM_ParseFunString(CON_WHITEMASK, msg, out, sizeof(out), false); + + for (c = out; c < end; c++) + Sys_PrintColouredChar (*c); +#else + int ext = CON_WHITEMASK; int extstack[4]; int extstackdepth = 0; @@ -880,11 +869,32 @@ void Sys_Printf (char *fmt, ...) } Sys_PrintColouredChar ((*str++) | ext); } - +#endif ApplyColour(CON_WHITEMASK); } else + { + for (t = (unsigned char*)msg; *t; t++) + { + if (*t >= 146 && *t < 156) + *t = *t - 146 + '0'; + if (*t >= 0x12 && *t <= 0x1b) + *t = *t - 0x12 + '0'; + if (*t == 143) + *t = '.'; + if (*t == 157 || *t == 158 || *t == 159) + *t = '-'; + if (*t >= 128) + *t -= 128; + if (*t == 16) + *t = '['; + if (*t == 17) + *t = ']'; + if (*t == 0x1c) + *t = 249; + } printf("%s", msg); + } if (coninput_len) @@ -1107,6 +1117,8 @@ void StartQuakeServer(void) //static char cwd[1024]; //unused variable int t; + memset(&parms, 0, sizeof(parms)); + TL_InitLanguages(); parms.argc = com_argc; diff --git a/engine/server/sv_user.c b/engine/server/sv_user.c index 080fdf12..43d2f833 100644 --- a/engine/server/sv_user.c +++ b/engine/server/sv_user.c @@ -298,7 +298,7 @@ void SV_New_f (void) splitnum = 0; for (split = host_client, splitnum = 0; split; split = split->controlled) splitnum++; - ClientReliableWrite_Byte (host_client, (split->spectator?128:0) | splitnum); + ClientReliableWrite_Byte (host_client, (host_client->spectator?128:0) | splitnum); //read each player's userinfo to see if its a spectator or not. this hint is merely a cheat. for (split = host_client; split; split = split->controlled) { playernum = NUM_FOR_EDICT(svprogfuncs, split->edict)-1; @@ -2675,6 +2675,10 @@ static int SV_LocateDownload(char *name, flocation_t *loc, char **replacementnam else return -1; //not found/unable to open } + else if (Terrain_LocateSection(name, loc)) + { + found = true; + } else found = FS_FLocateFile(name, FSLFRT_IFFOUND, loc); @@ -2783,6 +2787,9 @@ void SV_DownloadSize_f(void) ClientReliableWrite_Begin (host_client, svc_stufftext, 2+strlen(name)); ClientReliableWrite_String (host_client, name); break; + case -6: /*heightmap section*/ + //don't reply. + break; } } diff --git a/engine/server/svhl_game.c b/engine/server/svhl_game.c index a0a57459..df671817 100644 --- a/engine/server/svhl_game.c +++ b/engine/server/svhl_game.c @@ -1262,7 +1262,7 @@ int SVHL_InitGame(void) return 1; } - hlgamecode = Sys_LoadLibrary("C:/Incoming/d/Half-Life/sdks/hlsdk-2.3-p3/hlsdk-2.3-p3/multiplayer/dlls/debugmp/mp.dll", hlgamefuncs); + hlgamecode = NULL;//Sys_LoadLibrary("C:/Incoming/d/Half-Life/sdks/hlsdk-2.3-p3/hlsdk-2.3-p3/multiplayer/dlls/debugmp/mp.dll", hlgamefuncs); if (!hlgamecode) { gamedll = Info_ValueForKey(svs.info, "*gamedll"); diff --git a/engine/server/world.c b/engine/server/world.c index 5bf8756c..ecd6bba4 100644 --- a/engine/server/world.c +++ b/engine/server/world.c @@ -920,7 +920,7 @@ qboolean TransformedTrace (struct model_s *model, int hulloverride, int frame, v } // don't rotate non bsp ents. Too small to bother. - if (model) + if (model && !model->needload) { VectorSubtract (start, origin, start_l); VectorSubtract (end, origin, end_l); diff --git a/engine/setup/setup.vdproj b/engine/setup/setup.vdproj index f454e8c8..6e179e56 100644 --- a/engine/setup/setup.vdproj +++ b/engine/setup/setup.vdproj @@ -70,12 +70,6 @@ "Entry" { "MsmKey" = "8:_71CBEB9164DF59638557E9DDA2701375" - "OwnerKey" = "8:_59B5273419A741098C2F6C4D3D48B5F9" - "MsmSig" = "8:_UNDEFINED" - } - "Entry" - { - "MsmKey" = "8:_71CBEB9164DF59638557E9DDA2701375" "OwnerKey" = "8:_3D8125FEDA5B43DFAE7E3CF1642F05A8" "MsmSig" = "8:_UNDEFINED" } @@ -111,7 +105,7 @@ "InstallerBootstrapper" = "3:2" "BootstrapperCfg:{63ACBE69-63AA-4F98-B2B6-99F9E24495F2}" { - "Enabled" = "11:TRUE" + "Enabled" = "11:FALSE" "PromptEnabled" = "11:TRUE" "PrerequisitesLocation" = "2:1" "Url" = "8:" @@ -138,7 +132,7 @@ "InstallerBootstrapper" = "3:2" "BootstrapperCfg:{63ACBE69-63AA-4F98-B2B6-99F9E24495F2}" { - "Enabled" = "11:TRUE" + "Enabled" = "11:FALSE" "PromptEnabled" = "11:TRUE" "PrerequisitesLocation" = "2:1" "Url" = "8:" @@ -147,7 +141,7 @@ { "{EDC2488A-8267-493A-A98E-7D9C3B36CDF3}:Microsoft.Net.Framework.2.0" { - "Name" = "8:Microsoft .NET Framework 2.0" + "Name" = "8:.NET Framework 2.0" "ProductCode" = "8:Microsoft.Net.Framework.2.0" } } @@ -443,7 +437,7 @@ "Name" = "8:Microsoft Visual Studio" "ProductName" = "8:FTEQuake" "ProductCode" = "8:{1E2732CA-B825-4859-B5F7-41749C2BCBA3}" - "PackageCode" = "8:{C7794AE3-06F3-4BEB-BEDD-18434AE7855A}" + "PackageCode" = "8:{309367B2-B756-448D-B49E-90522718F916}" "UpgradeCode" = "8:{ED40A57B-C477-465A-8F0E-02E662BD739A}" "RestartWWWService" = "11:FALSE" "RemovePreviousVersions" = "11:TRUE" @@ -498,184 +492,6 @@ { "Keys" { - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_BA542D4D6D7B4A64B364F1C78F8F20F8" - { - "Name" = "8:Software" - "Condition" = "8:NPFTE" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:FALSE" - "Transitive" = "11:FALSE" - "Keys" - { - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_052DC401864F43D09A342786A17CB17E" - { - "Name" = "8:MozillaPlugins" - "Condition" = "8:" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:FALSE" - "Transitive" = "11:FALSE" - "Keys" - { - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_72A4CA00A74F46E28190454DE108A80B" - { - "Name" = "8:@fteqw.com/npFTE" - "Condition" = "8:" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:TRUE" - "Transitive" = "11:FALSE" - "Keys" - { - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_AE4CF76690644064A9ADBBA9BD1B9208" - { - "Name" = "8:MimeTypes" - "Condition" = "8:" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:TRUE" - "Transitive" = "11:FALSE" - "Keys" - { - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_1FC1AEDF2D3545408D04E544FE23192F" - { - "Name" = "8:application/x-fteplugin" - "Condition" = "8:" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:TRUE" - "Transitive" = "11:FALSE" - "Keys" - { - } - "Values" - { - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_E5D107AFC3D8450BA2B340C074E9ECEB" - { - "Name" = "8:Description" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:FTE Browser Plugin" - } - } - } - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_7A99D87EEBBC442EB22A23CFE1C3EAED" - { - "Name" = "8:application/x-qtv" - "Condition" = "8:" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:TRUE" - "Transitive" = "11:FALSE" - "Keys" - { - } - "Values" - { - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_0438CD1948E5418BA70012A58633CE71" - { - "Name" = "8:Suffixes" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:qtv" - } - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_D33B30BC77DE456AB625E7823EE719E2" - { - "Name" = "8:Description" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:QuakeTV Stream Information File" - } - } - } - } - "Values" - { - } - } - "{60EA8692-D2D5-43EB-80DC-7906BF13D6EF}:_C70BEC3C971B4FEC8C0D09248A984B97" - { - "Name" = "8:Suffixes" - "Condition" = "8:" - "AlwaysCreate" = "11:FALSE" - "DeleteAtUninstall" = "11:TRUE" - "Transitive" = "11:FALSE" - "Keys" - { - } - "Values" - { - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_D68A43CA0F284FE8A0EA2686803DB13E" - { - "Name" = "8:qtv" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:" - } - } - } - } - "Values" - { - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_15F93F3E68C74AB9B3E588FEF9847B36" - { - "Name" = "8:GeckoVersion" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:1.0" - } - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_408FC05728EA4929BA76659C4F8FDABE" - { - "Name" = "8:Vendor" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:[Manufacturer]" - } - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_7144D64EBC1F4693BC6AD2AF33D9852A" - { - "Name" = "8:Description" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:Quake in a Browser" - } - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_AFCDA966380243C4BFD1982226E8E47E" - { - "Name" = "8:Version" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:[Version]" - } - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_D5FB5B18F26746D9BA0457E8F038FAA8" - { - "Name" = "8:ProductName" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:FTE Quake Plugin" - } - "{ADCFDA98-8FDD-45E4-90BC-E3D20B029870}:_F040BDD5ACDA41BA9C2050923C944C11" - { - "Name" = "8:Path" - "Condition" = "8:" - "Transitive" = "11:FALSE" - "ValueTypes" = "3:1" - "Value" = "8:[TARGETDIR]npfte.dll" - } - } - } - } - "Values" - { - } - } - } - "Values" - { - } - } } } } @@ -1288,7 +1104,7 @@ "Exclude" = "11:FALSE" "IsDependency" = "11:FALSE" "IsolateTo" = "8:" - "ProjectOutputGroupRegister" = "3:1" + "ProjectOutputGroupRegister" = "3:4" "OutputConfiguration" = "8:GLRelease|Win32" "OutputGroupCanonicalName" = "8:Built" "OutputProjectGuid" = "8:{88BFEE0E-7BC0-43AD-9CCC-6B1A6E4C1365}" diff --git a/engine/shaders/generatebuiltinsl.c b/engine/shaders/generatebuiltinsl.c index e1281561..873a5eef 100644 --- a/engine/shaders/generatebuiltinsl.c +++ b/engine/shaders/generatebuiltinsl.c @@ -67,6 +67,21 @@ void dumpprogstring(FILE *out, FILE *src) } +struct shadertype_s +{ + char *filepattern; + char *preprocessor; + char *rendererapi; + int apiversion; +} shadertype[] = +{ + {"glsl/%s.glsl", "GLQUAKE", "QR_OPENGL", 110}, //gl2+ + {"gles/%s.glsl", "GLQUAKE", "QR_OPENGL", 100}, //gles + {"hlsl9/%s.hlsl", "D3D9QUAKE", "QR_DIRECT3D9", 9}, //d3d9 + {"hlsl11/%s.hlsl", "D3D11QUAKE", "QR_DIRECT3D11", 11}, //d3d11 +}; +//tbh we should precompile the d3d shaders. + int main(void) { FILE *c, *s; @@ -84,35 +99,17 @@ int main(void) for (i = 0; *shaders[i]; i++) { - for (a = 0; a < 3; a++) + for (a = 0; a < sizeof(shadertype)/sizeof(shadertype[0]); a++) { - if (a == 0) - sprintf(line, "glsl/%s.glsl", shaders[i]); - else if (a == 1) - sprintf(line, "gles/%s.glsl", shaders[i]); - else - sprintf(line, "hlsl/%s.hlsl", shaders[i]); + sprintf(line, shadertype[a].filepattern, shaders[i]); s = fopen(line, "rt"); if (!s) { printf("unable to open %s\n", line); continue; } - if (a == 0) - { - fprintf(c, "#ifdef GLQUAKE\n"); - fprintf(c, "{QR_OPENGL, 110, \"%s\",\n", shaders[i]); - } - else if (a == 1) - { - fprintf(c, "#ifdef GLQUAKE\n"); - fprintf(c, "{QR_OPENGL, 100, \"%s\",\n", shaders[i]); - } - else - { - fprintf(c, "#ifdef D3DQUAKE\n"); - fprintf(c, "{QR_DIRECT3D, 9, \"%s\",\n", shaders[i]); - } + fprintf(c, "#ifdef %s\n", shadertype[a].preprocessor); + fprintf(c, "{%s, %i, \"%s\",\n", shadertype[a].rendererapi, shadertype[a].apiversion, shaders[i]); while(fgets(line, sizeof(line), s)) { diff --git a/engine/shaders/glsl/altwater.glsl b/engine/shaders/glsl/altwater.glsl index 629e53af..02e3f609 100644 --- a/engine/shaders/glsl/altwater.glsl +++ b/engine/shaders/glsl/altwater.glsl @@ -1,3 +1,4 @@ +!!cvarf r_glsl_turbscale //modifier: REFLECT (s_t2 is a reflection instead of diffusemap) //modifier: STRENGTH (0.1 = fairly gentle, 0.2 = big waves) //modifier: FRESNEL (5=water) @@ -5,6 +6,8 @@ //modifier: RIPPLEMAP (s_t3 contains a ripplemap //modifier: TINT (some colour value) +uniform float cvar_r_glsl_turbscale; + #ifndef FRESNEL #define FRESNEL 5.0 #endif @@ -67,9 +70,9 @@ void main (void) //the fresnel term decides how transparent the water should be f = pow(1.0-abs(dot(normalize(n), normalize(eye))), float(FRESNEL)); - refr = texture2D(s_t0, stc + n.st*STRENGTH).rgb * TINT; + refr = texture2D(s_t0, stc + n.st*STRENGTH*cvar_r_glsl_turbscale).rgb * TINT; #ifdef REFLECT - refl = texture2D(s_t2, stc - n.st*STRENGTH).rgb; + refl = texture2D(s_t2, stc - n.st*STRENGTH*cvar_r_glsl_turbscale).rgb; #else refl = texture2D(s_t2, ntc).xyz; #endif diff --git a/engine/shaders/glsl/defaultwall.glsl b/engine/shaders/glsl/defaultwall.glsl index 805ec972..7b49994d 100644 --- a/engine/shaders/glsl/defaultwall.glsl +++ b/engine/shaders/glsl/defaultwall.glsl @@ -3,13 +3,15 @@ !!permu FOG !!permu LIGHTSTYLED !!permu BUMP +!!permu SPECULAR !!cvarf r_glsl_offsetmapping_scale +!!cvarf gl_specular //this is what normally draws all of your walls, even with rtlights disabled //note that the '286' preset uses drawflat_walls instead. #include "sys/fog.h" -#if defined(OFFSETMAPPING) +#if defined(OFFSETMAPPING) || defined(SPECULAR) varying vec3 eyevector; #endif @@ -30,7 +32,7 @@ attribute vec2 v_lmcoord2; attribute vec2 v_lmcoord3; attribute vec2 v_lmcoord4; #endif -#if defined(OFFSETMAPPING) +#if defined(OFFSETMAPPING) || defined(SPECULAR) uniform vec3 e_eyepos; attribute vec3 v_normal; attribute vec3 v_svector; @@ -38,7 +40,7 @@ attribute vec3 v_tvector; #endif void main () { -#if defined(OFFSETMAPPING) +#if defined(OFFSETMAPPING) || defined(SPECULAR) vec3 eyeminusvertex = e_eyepos - v_position.xyz; eyevector.x = -dot(eyeminusvertex, v_svector.xyz); eyevector.y = dot(eyeminusvertex, v_tvector.xyz); @@ -60,20 +62,23 @@ void main () //samplers uniform sampler2D s_t0; //diffuse uniform sampler2D s_t1; //lightmap0 -#if defined(OFFSETMAPPING) || defined(DELUXE) -uniform sampler2D s_t2; //normal +#if defined(BUMP) && (defined(OFFSETMAPPING) || defined(DELUXE) || defined(SPECULAR)) +uniform sampler2D s_t2; //normal.rgb+height.a #endif uniform sampler2D s_t3; //deluxe0 #ifdef FULLBRIGHT uniform sampler2D s_t4; //fullbright #endif +#ifdef SPECULAR +uniform sampler2D s_t5; //specular +#endif #ifdef LIGHTSTYLED -uniform sampler2D s_t5; //lightmap1 -uniform sampler2D s_t6; //lightmap2 -uniform sampler2D s_t7; //lightmap3 -uniform sampler2D s_t8; //deluxe1 -uniform sampler2D s_t9; //deluxe2 -uniform sampler2D s_t10; //deluxe3 +uniform sampler2D s_t6; //lightmap1 +uniform sampler2D s_t7; //lightmap2 +uniform sampler2D s_t8; //lightmap3 +uniform sampler2D s_t9; //deluxe1 +uniform sampler2D s_t10; //deluxe2 +uniform sampler2D s_t11; //deluxe3 #endif #ifdef LIGHTSTYLED @@ -82,6 +87,9 @@ uniform vec4 e_lmscale[4]; uniform vec4 e_lmscale; #endif uniform vec4 e_colourident; +#ifdef SPECULAR +uniform float cvar_gl_specular; +#endif #ifdef OFFSETMAPPING #include "sys/offsetmapping.h" #endif @@ -96,32 +104,54 @@ void main () //yay, regular texture! gl_FragColor = texture2D(s_t0, tc); +#if defined(BUMP) && (defined(DELUXE) || defined(SPECULAR)) + vec3 norm = normalize(texture2D(s_t2, tc).rgb - 0.5); +#elif defined(SPECULAR) || defined(DELUXE) + vec3 norm = vec3(0, 0, 1); //specular lighting expects this to exist. +#endif + //modulate that by the lightmap(s) including deluxemap(s) #ifdef LIGHTSTYLED - vec4 lightmaps; + vec3 lightmaps; #ifdef DELUXE - vec3 norm = texture2D(s_t2, tc).rgb; - lightmaps = texture2D(s_t1, lm ) * e_lmscale[0] * dot(norm, texture2D(s_t3, lm ).rgb); - lightmaps += texture2D(s_t5, lm2) * e_lmscale[1] * dot(norm, texture2D(s_t8, lm2).rgb); - lightmaps += texture2D(s_t6, lm3) * e_lmscale[2] * dot(norm, texture2D(s_t9, lm3).rgb); - lightmaps += texture2D(s_t7, lm4) * e_lmscale[3] * dot(norm, texture2D(s_t10,lm4).rgb); + lightmaps = texture2D(s_t1, lm ).rgb * e_lmscale[0].rgb * dot(norm, texture2D(s_t3, lm ).rgb); + lightmaps += texture2D(s_t6, lm2).rgb * e_lmscale[1].rgb * dot(norm, texture2D(s_t9, lm2).rgb); + lightmaps += texture2D(s_t7, lm3).rgb * e_lmscale[2].rgb * dot(norm, texture2D(s_t10, lm3).rgb); + lightmaps += texture2D(s_t8, lm4).rgb * e_lmscale[3].rgb * dot(norm, texture2D(s_t11,lm4).rgb); #else - lightmaps = texture2D(s_t1, lm ) * e_lmscale[0]; - lightmaps += texture2D(s_t5, lm2) * e_lmscale[1]; - lightmaps += texture2D(s_t6, lm3) * e_lmscale[2]; - lightmaps += texture2D(s_t7, lm4) * e_lmscale[3]; + lightmaps = texture2D(s_t1, lm ).rgb * e_lmscale[0].rgb; + lightmaps += texture2D(s_t6, lm2).rgb * e_lmscale[1].rgb; + lightmaps += texture2D(s_t7, lm3).rgb * e_lmscale[2].rgb; + lightmaps += texture2D(s_t8, lm4).rgb * e_lmscale[3].rgb; #endif - gl_FragColor.rgb *= lightmaps.rgb; #else + vec3 lightmaps = (texture2D(s_t1, lm) * e_lmscale).rgb; + //modulate by the bumpmap dot light #ifdef DELUXE -//gl_FragColor.rgb = dot(normalize(texture2D(s_t2, tc).rgb - 0.5), normalize(texture2D(s_t3, lm).rgb - 0.5)); -//gl_FragColor.rgb = texture2D(s_t3, lm).rgb; - gl_FragColor.rgb *= (texture2D(s_t1, lm) * e_lmscale).rgb * dot(normalize(texture2D(s_t2, tc).rgb-0.5), 2.0*(texture2D(s_t3, lm).rgb-0.5)); - #else - gl_FragColor.rgb *= (texture2D(s_t1, lm) * e_lmscale).rgb; + lightmaps *= dot(norm, 2.0*(texture2D(s_t3, lm).rgb-0.5)); #endif #endif +#ifdef SPECULAR + vec4 specs = texture2D(s_t5, tc); + #ifdef DELUXE +//not lightstyled... + vec3 halfdir = normalize(normalize(eyevector) + 2.0*(texture2D(s_t3, lm).rgb-0.5)); //this norm should be the deluxemap info instead + #else + vec3 halfdir = normalize(normalize(eyevector) + vec3(0.0, 0.0, 1.0)); //this norm should be the deluxemap info instead + #endif + float spec = pow(max(dot(halfdir, norm), 0.0), 32.0 * specs.a); + spec *= cvar_gl_specular; +//NOTE: rtlights tend to have a *4 scaler here to over-emphasise the effect because it looks cool. +//As not all maps will have deluxemapping, and the double-cos from the light util makes everything far too dark anyway, +//we default to something that is not garish when the light value is directly infront of every single pixel. +//we can justify this difference due to the rtlight editor etc showing the *4. + gl_FragColor.rgb += spec * specs.rgb; +#endif + + //now we have our diffuse+specular terms, modulate by lightmap values. + gl_FragColor.rgb *= lightmaps.rgb; + //add on the fullbright #ifdef FULLBRIGHT gl_FragColor.rgb += texture2D(s_t4, tc).rgb; diff --git a/engine/shaders/hlsl11/default2d.hlsl b/engine/shaders/hlsl11/default2d.hlsl new file mode 100644 index 00000000..4754a923 --- /dev/null +++ b/engine/shaders/hlsl11/default2d.hlsl @@ -0,0 +1,34 @@ +struct a2v +{ + float4 pos: POSITION; + float2 tc: TEXCOORD0; + float4 vcol: COLOR0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float4 vcol: COLOR0; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_projection, inp.pos); + outp.tc = inp.tc; + outp.vcol = inp.vcol; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture; + SamplerState SampleType; + float4 main (v2f inp) : SV_TARGET + { + return shaderTexture.Sample(SampleType, inp.tc) * inp.vcol; + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/defaultfill.hlsl b/engine/shaders/hlsl11/defaultfill.hlsl new file mode 100644 index 00000000..f09650e7 --- /dev/null +++ b/engine/shaders/hlsl11/defaultfill.hlsl @@ -0,0 +1,29 @@ +struct a2v +{ + float4 pos: POSITION; + float4 vcol: COLOR0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float4 vcol: COLOR0; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_projection, inp.pos); + outp.vcol = inp.vcol; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + float4 main (v2f inp) : SV_TARGET + { + return inp.vcol; + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/defaultskin.hlsl b/engine/shaders/hlsl11/defaultskin.hlsl new file mode 100644 index 00000000..894a9bb2 --- /dev/null +++ b/engine/shaders/hlsl11/defaultskin.hlsl @@ -0,0 +1,57 @@ +struct a2v +{ + float4 pos: POSITION; + float4 tc: TEXCOORD0; + float3 normal: NORMAL; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float3 light: TEXCOORD1; +}; + +#include + +#ifdef VERTEX_SHADER +//attribute vec2 v_texcoord; +//uniform vec3 e_light_dir; +//uniform vec3 e_light_mul; +//uniform vec3 e_light_ambient; + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.light = e_light_ambient + (dot(inp.normal,e_light_dir)*e_light_mul); + outp.tc = inp.tc.xy; + return outp; + } +#endif +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture[4]; //diffuse, lower, upper, fullbright + SamplerState SampleType; + +//uniform vec4 e_colourident; + float4 main (v2f inp) : SV_TARGET + { + float4 col; + col = shaderTexture[0].Sample(SampleType, inp.tc); +#ifdef UPPER + float4 uc = shaderTexture[2].Sample(SampleType, inp.tc); + col.rgb = mix(col.rgb, uc.rgb*e_uppercolour, uc.a); +#endif +#ifdef LOWER + float4 lc = shaderTexture[1].Sample(SampleType, inp.tc); + col.rgb = mix(col.rgb, lc.rgb*e_lowercolour, lc.a); +#endif + col.rgb *= inp.light; +#ifdef FULLBRIGHT + float4 fb = shaderTexture[3].Sample(SampleType, inp.tc); + col.rgb = mix(col.rgb, fb.rgb, fb.a); +#endif + return col; +// return fog4(col * e_colourident); + } +#endif diff --git a/engine/shaders/hlsl11/defaultsky.hlsl b/engine/shaders/hlsl11/defaultsky.hlsl new file mode 100644 index 00000000..fb8a29e7 --- /dev/null +++ b/engine/shaders/hlsl11/defaultsky.hlsl @@ -0,0 +1,47 @@ +//regular sky shader for scrolling q1 skies +//the sky surfaces are thrown through this as-is. + +struct a2v +{ + float4 pos: POSITION; + float2 tc: TEXCOORD0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float3 mpos: TEXCOORD1; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.mpos = outp.pos.xyz; + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture[2]; + SamplerState SampleType; + + float4 main (v2f inp) : SV_TARGET + { + float2 tccoord; + float3 dir = inp.mpos - v_eyepos; + dir.z *= 3.0; + dir.xy /= 0.5*length(dir); + tccoord = (dir.xy + e_time*0.03125); + float4 solid = shaderTexture[0].Sample(SampleType, tccoord); + tccoord = (dir.xy + e_time*0.0625); + float4 clouds = shaderTexture[1].Sample(SampleType, tccoord); + return (solid*(1.0-clouds.a)) + (clouds.a*clouds); + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/defaultsprite.hlsl b/engine/shaders/hlsl11/defaultsprite.hlsl new file mode 100644 index 00000000..e7c6ef11 --- /dev/null +++ b/engine/shaders/hlsl11/defaultsprite.hlsl @@ -0,0 +1,36 @@ +struct a2v +{ + float4 pos: POSITION; + float4 tc: TEXCOORD0; + float4 vcol: COLOR0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float4 vcol: COLOR0; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc.xy; + outp.vcol = inp.vcol; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture; + SamplerState SampleType; + float4 main (v2f inp) : SV_TARGET + { + return shaderTexture.Sample(SampleType, inp.tc) * inp.vcol; + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/defaultwall.hlsl b/engine/shaders/hlsl11/defaultwall.hlsl new file mode 100644 index 00000000..55207b29 --- /dev/null +++ b/engine/shaders/hlsl11/defaultwall.hlsl @@ -0,0 +1,36 @@ +struct a2v +{ + float4 pos: POSITION; + float4 tc: TEXCOORD0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float2 lmtc: TEXCOORD1; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc.xy; + outp.lmtc = inp.tc.zw; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture[2]; + SamplerState SampleType[2]; + + float4 main (v2f inp) : SV_TARGET + { + return shaderTexture[0].Sample(SampleType[0], inp.tc) * shaderTexture[1].Sample(SampleType[1], inp.lmtc).bgra; + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/defaultwarp.hlsl b/engine/shaders/hlsl11/defaultwarp.hlsl new file mode 100644 index 00000000..90e95129 --- /dev/null +++ b/engine/shaders/hlsl11/defaultwarp.hlsl @@ -0,0 +1,41 @@ +!!cvarf r_wateralpha + +struct a2v +{ + float4 pos: POSITION; + float2 tc: TEXCOORD0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER +// float cvar_r_wateralpha; +// float e_time; +// sampler s_t0; + Texture2D shaderTexture; + SamplerState SampleType; + float4 main (v2f inp) : SV_TARGET + { + float2 ntc; + ntc.x = inp.tc.x + sin(inp.tc.y+e_time)*0.125; + ntc.y = inp.tc.y + sin(inp.tc.x+e_time)*0.125; + return shaderTexture.Sample(SampleType, ntc); + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/drawflat_wall.hlsl b/engine/shaders/hlsl11/drawflat_wall.hlsl new file mode 100644 index 00000000..7a0839d5 --- /dev/null +++ b/engine/shaders/hlsl11/drawflat_wall.hlsl @@ -0,0 +1,39 @@ +struct a2v +{ + float4 pos: POSITION; + float4 tc: TEXCOORD0; + float3 norm: NORMAL; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float2 lmtc: TEXCOORD1; + float4 col: TEXCOORD2; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc.xy; + outp.lmtc = inp.tc.zw; + outp.col = ((inp.norm.z<0.73)?float4(0.5, 0.5, 0.5, 1):float4(0.25, 0.25, 0.5, 1)); + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture; + SamplerState SampleType; + + float4 main (v2f inp) : SV_TARGET + { + return inp.col * shaderTexture.Sample(SampleType, inp.lmtc); + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/terrain.hlsl b/engine/shaders/hlsl11/terrain.hlsl new file mode 100644 index 00000000..487dead4 --- /dev/null +++ b/engine/shaders/hlsl11/terrain.hlsl @@ -0,0 +1,49 @@ +struct a2v +{ + float4 pos: POSITION; + float4 tc: TEXCOORD0; + float4 vcol: COLOR0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float2 lmtc: TEXCOORD1; + float4 vcol: COLOR0; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc.xy; + outp.lmtc = inp.tc.zw; + outp.vcol = inp.vcol; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + Texture2D shaderTexture[5]; + SamplerState SampleType; + + float4 main (v2f inp) : SV_TARGET + { +return float4(1,1,1,1); + +// float4 m = shaderTexture[4].Sample(SampleType, inp.tc) ; + +// return inp.vcol*float4(m.aaa,1.0)*( +// shaderTexture[0].Sample(SampleType, inp.tc)*m.r +// + shaderTexture[1].Sample(SampleType, inp.tc)*m.g +// + shaderTexture[2].Sample(SampleType, inp.tc)*m.b +// + shaderTexture[3].Sample(SampleType, inp.tc)*1.0 - (m.r + m.g + m.b)) +// ; + + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl11/terraindebug.hlsl b/engine/shaders/hlsl11/terraindebug.hlsl new file mode 100644 index 00000000..c6f38ef9 --- /dev/null +++ b/engine/shaders/hlsl11/terraindebug.hlsl @@ -0,0 +1,36 @@ +struct a2v +{ + float4 pos: POSITION; + float4 tc: TEXCOORD0; +}; +struct v2f +{ + float4 pos: SV_POSITION; + float2 tc: TEXCOORD0; + float2 lmtc: TEXCOORD1; +}; + +#include + +#ifdef VERTEX_SHADER + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_model, inp.pos); + outp.pos = mul(m_view, outp.pos); + outp.pos = mul(m_projection, outp.pos); + outp.tc = inp.tc.xy; + outp.lmtc = inp.tc.zw; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER +// Texture2D shaderTexture[5]; +// SamplerState SampleType; + + float4 main (v2f inp) : SV_TARGET + { + return float4(1,1,1,1);//shaderTexture[4].Sample(SampleType, inp.lmtc).bgr, 1.0); + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl9/defaultsky.hlsl b/engine/shaders/hlsl9/defaultsky.hlsl new file mode 100644 index 00000000..5e2292a1 --- /dev/null +++ b/engine/shaders/hlsl9/defaultsky.hlsl @@ -0,0 +1,52 @@ + struct a2v + { + float4 pos: POSITION; + }; + struct v2f + { +#ifndef FRAGMENT_SHADER + float4 pos: POSITION; +#endif + float3 vpos: TEXCOORD0; + }; + +#ifdef VERTEX_SHADER + float4x4 m_modelviewprojection; + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_modelviewprojection, inp.pos); + outp.vpos = inp.pos; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + float e_time; + float3 e_eyepos; + + float l_lightradius; + float3 l_lightcolour; + float3 l_lightposition; + + sampler s_t0; /*diffuse*/ + sampler s_t1; /*normal*/ + sampler s_t2; /*specular*/ + float4 main (v2f inp) : COLOR0 + { + float2 tccoord; + + float3 dir = inp.vpos - e_eyepos; + + dir.z *= 3.0; + dir.xy /= 0.5*length(dir); + + tccoord = (dir.xy + e_time*0.03125); + float4 solid = tex2D(s_t0, tccoord); + + tccoord = (dir.xy + e_time*0.0625); + float4 clouds = tex2D(s_t1, tccoord); + + return float4((solid.rgb*(1.0-clouds.a)) + (clouds.a*clouds.rgb), 1); + } +#endif \ No newline at end of file diff --git a/engine/shaders/hlsl9/defaultwarp.hlsl b/engine/shaders/hlsl9/defaultwarp.hlsl new file mode 100644 index 00000000..63b65487 --- /dev/null +++ b/engine/shaders/hlsl9/defaultwarp.hlsl @@ -0,0 +1,36 @@ +!!cvarf r_wateralpha +struct a2v { + float4 pos: POSITION; + float2 tc: TEXCOORD0; +}; +struct v2f { + #ifndef FRAGMENT_SHADER + float4 pos: POSITION; + #endif + float2 tc: TEXCOORD0; +}; +#ifdef VERTEX_SHADER + float4x4 m_modelviewprojection; + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_modelviewprojection, inp.pos); + outp.tc = inp.tc; + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + float cvar_r_wateralpha; + float e_time; + sampler s_t0; + float4 main (v2f inp) : COLOR0 + { + float2 ntc; + ntc.x = inp.tc.x + sin(inp.tc.y+e_time)*0.125; + ntc.y = inp.tc.y + sin(inp.tc.x+e_time)*0.125; + float3 ts = tex2D(s_t0, ntc).xyz; + + return float4(ts, cvar_r_wateralpha); + } +#endif diff --git a/engine/shaders/hlsl9/rtlight.hlsl b/engine/shaders/hlsl9/rtlight.hlsl new file mode 100644 index 00000000..22243bb9 --- /dev/null +++ b/engine/shaders/hlsl9/rtlight.hlsl @@ -0,0 +1,62 @@ +!!permu BUMP +!!permu SPECULAR +!!permu OFFSETMAPPING +!!permu SKELETAL +!!permu FOG + + +// texture units: +// s0=diffuse, s1=normal, s2=specular, s3=shadowmap +// custom modifiers: +// PCF(shadowmap) +// CUBE(projected cubemap) + + + + struct a2v + { + float4 pos: POSITION; + float3 tc: TEXCOORD0; + float3 n: NORMAL0; + float3 s: TANGENT0; + float3 t: BINORMAL0; + }; + struct v2f + { + #ifndef FRAGMENT_SHADER + float4 pos: POSITION; + #endif + float3 tc: TEXCOORD0; + float3 lpos: TEXCOORD1; + }; + +#ifdef VERTEX_SHADER + float4x4 m_modelviewprojection; + float3 l_lightposition; + v2f main (a2v inp) + { + v2f outp; + outp.pos = mul(m_modelviewprojection, inp.pos); + outp.tc = inp.tc; + + float3 lightminusvertex = l_lightposition - inp.pos.xyz; + outp.lpos.x = dot(lightminusvertex, inp.s.xyz); + outp.lpos.y = dot(lightminusvertex, inp.t.xyz); + outp.lpos.z = dot(lightminusvertex, inp.n.xyz); + return outp; + } +#endif + +#ifdef FRAGMENT_SHADER + sampler s_t0; + sampler s_t1; + float l_lightradius; + float3 l_lightcolour; + float4 main (v2f inp) : COLOR0 + { + float3 col = l_lightcolour; + col *= max(1.0 - dot(inp.lpos, inp.lpos)/(l_lightradius*l_lightradius), 0.0); + float3 diff = tex2D(s_t0, inp.tc); + return float4(diff * col, 1); + } +#endif \ No newline at end of file diff --git a/plugins/avplug/avdecode.c b/plugins/avplug/avdecode.c new file mode 100644 index 00000000..f7ba43cf --- /dev/null +++ b/plugins/avplug/avdecode.c @@ -0,0 +1,266 @@ +#include "../plugin.h" +#include "../engine.h" + +#include +#include +#include +#include + +/*should probably try threading this*/ +/*timing is based upon the start time. this means overflow issues with rtsp etc*/ + +struct decctx +{ + unsigned int width, height; + + AVFormatContext *pFormatCtx; + int videoStream; + AVCodecContext *pCodecCtx; + AVFrame *pFrame; + int64_t num, denum; + + AVPicture pFrameRGB; + struct SwsContext *pScaleCtx; + + unsigned int starttime; + unsigned int lastframe; +}; + +static qboolean AVDec_SetSize (void *vctx, int width, int height) +{ + struct decctx *ctx = (struct decctx*)vctx; + AVPicture newscaled; + + //colourspace conversions will be fastest if we +// if (width > ctx->pCodecCtx->width) + width = ctx->pCodecCtx->width; +// if (height > ctx->pCodecCtx->height) + height = ctx->pCodecCtx->height; + + //is this a no-op? + if (width == ctx->width && height == ctx->height && ctx->pScaleCtx) + return true; + + if (avpicture_alloc(&newscaled, AV_PIX_FMT_BGRA, width, height) >= 0) + { + //update the scale context as required + //clear the old stuff out + avpicture_free(&ctx->pFrameRGB); + + ctx->width = width; + ctx->height = height; + ctx->pFrameRGB = newscaled; + return qtrue; + } + return qfalse; //unsupported +} + +static void *AVDec_Create(char *medianame) +{ + struct decctx *ctx; + + unsigned int i; + AVCodec *pCodec; + + /*only respond to av: media prefixes*/ + if (!strncmp(medianame, "av:", 3)) + medianame = medianame + 3; + else + return NULL; + + ctx = malloc(sizeof(*ctx)); + memset(ctx, 0, sizeof(*ctx)); + + //so we always decode the first frame instantly. + + ctx->starttime = timeGetTime(); + + // Open video file + if(avformat_open_input(&ctx->pFormatCtx, medianame, NULL, NULL)==0) + { + // Retrieve stream information + if(av_find_stream_info(ctx->pFormatCtx)>=0) + { + // Find the first video stream + ctx->videoStream=-1; + for(i=0; ipFormatCtx->nb_streams; i++) + if(ctx->pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) + { + ctx->videoStream=i; + break; + } + + if(ctx->videoStream!=-1) + { + // Get a pointer to the codec context for the video stream + ctx->pCodecCtx=ctx->pFormatCtx->streams[ctx->videoStream]->codec; + ctx->num = ctx->pFormatCtx->streams[ctx->videoStream]->time_base.num; + ctx->denum = ctx->pFormatCtx->streams[ctx->videoStream]->time_base.den; + + // Find the decoder for the video stream + pCodec=avcodec_find_decoder(ctx->pCodecCtx->codec_id); + + // Open codec + if(pCodec!=NULL && avcodec_open(ctx->pCodecCtx, pCodec) >= 0) + { + // Allocate video frame + ctx->pFrame=avcodec_alloc_frame(); + if(ctx->pFrame!=NULL) + { + if (AVDec_SetSize(ctx, ctx->pCodecCtx->width, ctx->pCodecCtx->height)) + { + return ctx; + } + av_free(ctx->pFrame); + } + avcodec_close(ctx->pCodecCtx); + } + } + } + av_close_input_file(ctx->pFormatCtx); + } + free(ctx); + return NULL; +} + +static void *AVDec_DisplayFrame(void *vctx, qboolean nosound, enum uploadfmt_e *fmt, int *width, int *height) +{ + struct decctx *ctx = (struct decctx*)vctx; + AVPacket packet; + int frameFinished; + qboolean repainted = false; + int64_t curtime, lasttime; + + curtime = ((timeGetTime() - ctx->starttime) * ctx->denum); + curtime /= (ctx->num * 1000); + + *fmt = TF_BGRA32; + while (1) + { + lasttime = av_frame_get_best_effort_timestamp(ctx->pFrame); + + if (lasttime > curtime) + break; + + // We're ahead of the previous frame. try and read the next. + if (av_read_frame(ctx->pFormatCtx, &packet) < 0) + { + *fmt = TF_INVALID; + break; + } + + // Is this a packet from the video stream? + if(packet.stream_index==ctx->videoStream) + { + // Decode video frame + avcodec_decode_video2(ctx->pCodecCtx, ctx->pFrame, &frameFinished, &packet); + + // Did we get a video frame? + if(frameFinished) + { + ctx->pScaleCtx = sws_getCachedContext(ctx->pScaleCtx, ctx->pCodecCtx->width, ctx->pCodecCtx->height, ctx->pCodecCtx->pix_fmt, ctx->width, ctx->height, AV_PIX_FMT_BGRA, SWS_POINT, 0, 0, 0); + + // Convert the image from its native format to RGB + sws_scale(ctx->pScaleCtx, ctx->pFrame->data, ctx->pFrame->linesize, 0, ctx->pCodecCtx->height, ctx->pFrameRGB.data, ctx->pFrameRGB.linesize); + + repainted = true; + } + } + + // Free the packet that was allocated by av_read_frame + av_free_packet(&packet); + } + + *width = ctx->width; + *height = ctx->height; + if (!repainted) + return NULL; + return ctx->pFrameRGB.data[0]; +} +static void AVDec_Destroy(void *vctx) +{ + struct decctx *ctx = (struct decctx*)vctx; + + // Free the RGB image + avpicture_free(&ctx->pFrameRGB); + + // Free the YUV frame + av_free(ctx->pFrame); + + // Close the codec + avcodec_close(ctx->pCodecCtx); + + // Close the video file + av_close_input_file(ctx->pFormatCtx); + + free(ctx); +} +static void AVDec_GetSize (void *vctx, int *width, int *height) +{ + struct decctx *ctx = (struct decctx*)vctx; + *width = ctx->width; + *height = ctx->height; +} + +static void AVDec_CursorMove (void *vctx, float posx, float posy) +{ + //its a video, dumbass +} +static void AVDec_Key (void *vctx, int code, int unicode, int isup) +{ + //its a video, dumbass +} +static void AVDec_ChangeStream(void *vctx, char *newstream) +{ +} +static void AVDec_Rewind(void *ctx) +{ +} + +/* +//avcodec has no way to shut down properly. +static qintptr_t AVDec_Shutdown(qintptr_t *args) +{ + return 0; +} +*/ + +static media_decoder_funcs_t decoderfuncs = +{ + AVDec_Create, + AVDec_DisplayFrame, + NULL,//doneframe + AVDec_Destroy, + AVDec_Rewind, + + NULL,//AVDec_CursorMove, + NULL,//AVDec_Key, + NULL,//AVDec_SetSize, + AVDec_GetSize, + NULL,//AVDec_ChangeStream +}; + +static qboolean AVDec_Init(void) +{ + if (!Plug_ExportNative("Media_VideoDecoder", &decoderfuncs)) + { + Con_Printf("avplug: Engine doesn't support media decoder plugins\n"); + return false; + } + + return true; +} + +//get the encoder/decoders to register themselves with the engine, then make sure avformat/avcodec have registered all they have to give. +qboolean AVEnc_Init(void); +qintptr_t Plug_Init(qintptr_t *args) +{ + qboolean okay = false; + + okay |= AVDec_Init(); + okay |= AVEnc_Init(); + if (okay) + av_register_all(); + return okay; +} + diff --git a/plugins/avplug/avencode.c b/plugins/avplug/avencode.c new file mode 100644 index 00000000..22a9bab6 --- /dev/null +++ b/plugins/avplug/avencode.c @@ -0,0 +1,435 @@ +#include "../plugin.h" +#include "../engine.h" + +#include "avformat.h" +#include "avio.h" +#include "avcodec.h" +#include "swscale.h" + +/* +Most of the logic in here came from here: +http://svn.gnumonks.org/tags/21c3-video/upstream/ffmpeg-0.4.9-pre1/output_example.c +*/ + +struct encctx +{ + AVFormatContext *fc; + qboolean doneheaders; + + AVStream *video_st; + struct SwsContext *scale_ctx; + AVFrame *picture; + uint8_t *video_outbuf; + int video_outbuf_size; + + AVStream *audio_st; + AVFrame *audio; +}; + +static void AVEnc_End (void *ctx); + +static AVFrame *alloc_frame(enum PixelFormat pix_fmt, int width, int height) +{ + AVFrame *picture; + uint8_t *picture_buf; + int size; + + picture = avcodec_alloc_frame(); + if(!picture) + return NULL; + size = avpicture_get_size(pix_fmt, width, height); + picture_buf = (uint8_t*)(av_malloc(size)); + if (!picture_buf) + { + av_free(picture); + return NULL; + } + avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, width, height); + picture->width = width; + picture->height = height; + return picture; +} +AVStream *add_video_stream(struct encctx *ctx, AVCodec *codec, int fps, int width, int height) +{ + AVCodecContext *c; + AVStream *st; + char prof[128]; + int bitrate = (int)Cvar_GetFloat("avplug_videobitrate"); + int forcewidth = (int)Cvar_GetFloat("avplug_videoforcewidth"); + int forceheight = (int)Cvar_GetFloat("avplug_videoforceheight"); + + st = avformat_new_stream(ctx->fc, codec); + if (!st) + { + fprintf(stderr, "Could not alloc stream\n"); + exit(1); + } + + c = st->codec; + c->codec_id = codec->id; + c->codec_type = codec->type; + + /* put sample parameters */ + c->bit_rate = bitrate; + /* resolution must be a multiple of two */ + c->width = forcewidth?forcewidth:width; + c->height = forceheight?forceheight:height; + /* frames per second */ + c->time_base.num = 1; + c->time_base.den = fps; + c->gop_size = 12; /* emit one intra frame every twelve frames at most */ + c->pix_fmt = PIX_FMT_YUV420P; + if (c->codec_id == CODEC_ID_MPEG2VIDEO) + { + /* just for testing, we also add B frames */ + c->max_b_frames = 2; + } + if (c->codec_id == CODEC_ID_MPEG1VIDEO) + { + /* needed to avoid using macroblocks in which some coeffs overflow + this doesnt happen with normal video, it just happens here as the + motion of the chroma plane doesnt match the luma plane */ +// c->mb_decision=2; + } + // some formats want stream headers to be seperate + if (ctx->fc->oformat->flags & AVFMT_GLOBALHEADER) + c->flags |= CODEC_FLAG_GLOBAL_HEADER; + + *prof = 0; + Cvar_GetString("avplug_format", prof, sizeof(prof)); +// av_opt_set(c->priv_data, "profile", prof, AV_OPT_SEARCH_CHILDREN); + + return st; +} +void close_video(struct encctx *ctx) +{ + if (!ctx->video_st) + return; + + avcodec_close(ctx->video_st->codec); + if (ctx->picture) + { + av_free(ctx->picture->data[0]); + av_free(ctx->picture); + } + av_free(ctx->video_outbuf); +} +static void AVEnc_Video (void *vctx, void *data, int frame, int width, int height) +{ + struct encctx *ctx = vctx; + //weird maths to flip it. + uint8_t *srcslices[2] = {(uint8_t*)data + (height-1)*width*3, NULL}; + int srcstride[2] = {-width*3, 0}; + int success; + AVPacket pkt; + + if (!ctx->video_st) + return; + + //convert RGB to whatever the codec needs (ie: yuv...). + ctx->scale_ctx = sws_getCachedContext(ctx->scale_ctx, width, height, AV_PIX_FMT_RGB24, ctx->picture->width, ctx->picture->height, ctx->video_st->codec->pix_fmt, SWS_POINT, 0, 0, 0); + sws_scale(ctx->scale_ctx, srcslices, srcstride, 0, height, ctx->picture->data, ctx->picture->linesize); + + av_init_packet(&pkt); + ctx->picture->pts = av_rescale_q(frame, ctx->video_st->codec->time_base, ctx->video_st->time_base); + success = 0; + pkt.data = ctx->video_outbuf; + pkt.size = ctx->video_outbuf_size; + if (avcodec_encode_video2(ctx->video_st->codec, &pkt, ctx->picture, &success) == 0 && success) + { + pkt.pts = ctx->video_st->codec->coded_frame->pts; + if(ctx->video_st->codec->coded_frame->key_frame) + pkt.flags |= AV_PKT_FLAG_KEY; + pkt.stream_index = ctx->video_st->index; + pkt.data = ctx->video_outbuf; +// pkt.size = psize; + + av_write_frame(ctx->fc, &pkt); + } +} + +AVStream *add_audio_stream(struct encctx *ctx, AVCodec *codec, int samplerate, int bits, int channels) +{ + AVCodecContext *c; + AVStream *st; + int bitrate = (int)Cvar_GetFloat("avplug_audiobitrate"); + + st = avformat_new_stream(ctx->fc, codec); + if (!st) + { + fprintf(stderr, "Could not alloc stream\n"); + exit(1); + } + + c = st->codec; + c->codec_id = codec->id; + c->codec_type = codec->type; + + /* put sample parameters */ + c->bit_rate = bitrate; + /* frames per second */ + c->sample_fmt = ((bits==16)?AV_SAMPLE_FMT_S16:AV_SAMPLE_FMT_U8); + c->sample_rate = samplerate; + c->channels = channels; + switch(channels) + { + case 1: + c->channel_layout = AV_CH_FRONT_CENTER; + break; + case 2: + c->channel_layout = AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT; + break; + default: + break; + } + + // some formats want stream headers to be seperate + if (ctx->fc->oformat->flags & AVFMT_GLOBALHEADER) + c->flags |= CODEC_FLAG_GLOBAL_HEADER; + + return st; +} +void close_audio(struct encctx *ctx) +{ + if (!ctx->audio_st) + return; + + avcodec_close(ctx->audio_st->codec); +} +static void AVEnc_Audio (void *vctx, void *data, int bytes) +{ + struct encctx *ctx = vctx; + int success; + AVPacket pkt; + + ctx->audio->nb_samples = ctx->audio_st->codec->frame_size; + if (avcodec_fill_audio_frame(ctx->audio, ctx->audio_st->codec->channels, ctx->audio_st->codec->sample_fmt, data, bytes, 0) < 0) + return; + + av_init_packet(&pkt); + pkt.data = NULL; + pkt.size = 0; + success = 0; + if (avcodec_encode_audio2(ctx->audio_st->codec, &pkt, ctx->audio, &success) == 0 && success) + { + pkt.pts = ctx->audio_st->codec->coded_frame->pts; + if(ctx->audio_st->codec->coded_frame->key_frame) + pkt.flags |= AV_PKT_FLAG_KEY; + pkt.stream_index = ctx->audio_st->index; +// pkt.data = ctx->video_outbuf; +// pkt.size = psize; + + av_write_frame(ctx->fc, &pkt); + } +} + +static void *AVEnc_Begin (char *streamname, int videorate, int width, int height, int *sndkhz, int *sndchannels, int *sndbits) +{ + struct encctx *ctx; + AVOutputFormat *fmt = NULL; + AVCodec *videocodec = NULL; + AVCodec *audiocodec = NULL; + char formatname[64]; + formatname[0] = 0; + Cvar_GetString("avplug_format", formatname, sizeof(formatname)); + + if (*formatname) + { + fmt = av_guess_format(formatname, NULL, NULL); + if (!fmt) + { + Con_Printf("Unknown format specified.\n"); + return NULL; + } + } + if (!fmt) + fmt = av_guess_format(NULL, streamname, NULL); + if (!fmt) + { + Con_DPrintf("Could not deduce output format from file extension: using MPEG.\n"); + fmt = av_guess_format("mpeg", NULL, NULL); + } + if (!fmt) + { + Con_Printf("Format not known\n"); + return NULL; + } + + if (videorate) + { + char codecname[64]; + codecname[0] = 0; + Cvar_GetString("avplug_videocodec", codecname, sizeof(codecname)); + + if (strcmp(codecname, "none")) + { + if (codecname[0]) + { + videocodec = avcodec_find_encoder_by_name(codecname); + if (!videocodec) + { + Con_Printf("Unsupported avplug_codec \"%s\"\n", codecname); + return NULL; + } + } + if (!videocodec && fmt->video_codec != AV_CODEC_ID_NONE) + videocodec = avcodec_find_encoder(fmt->video_codec); + } + } + if (*sndkhz) + { + char codecname[64]; + codecname[0] = 0; + Cvar_GetString("avplug_audiocodec", codecname, sizeof(codecname)); + + if (strcmp(codecname, "none")) + { + if (codecname[0]) + { + audiocodec = avcodec_find_encoder_by_name(codecname); + if (!audiocodec) + { + Con_Printf("Unsupported avplug_codec \"%s\"\n", codecname); + return NULL; + } + } + if (!audiocodec && fmt->audio_codec != AV_CODEC_ID_NONE) + audiocodec = avcodec_find_encoder(fmt->audio_codec); + } + } + + Con_DPrintf("Using format \"%s\"\n", fmt->name); + if (videocodec) + Con_DPrintf("Using Video Codec \"%s\"\n", videocodec->name); + else + Con_DPrintf("Not encoding video\n"); + if (audiocodec) + Con_DPrintf("Using Audio Codec \"%s\"\n", audiocodec->name); + else + Con_DPrintf("Not encoding audio\n"); + + if (!videocodec && !audiocodec) + { + Con_DPrintf("Nothing to encode!\n"); + return NULL; + } + + if (!audiocodec) + *sndkhz = 0; + + ctx = malloc(sizeof(*ctx)); + if (!ctx) + return NULL; + memset(ctx, 0, sizeof(*ctx)); + + ctx->fc = avformat_alloc_context(); + ctx->fc->oformat = fmt; + snprintf(ctx->fc->filename, sizeof(ctx->fc->filename), "%s", streamname); + + + //pick default codecs + ctx->video_st = NULL; + if (videocodec) + { + ctx->video_st = add_video_stream(ctx, videocodec, videorate, width, height); + + if (ctx->video_st) + { + AVCodecContext *c = ctx->video_st->codec; + if (avcodec_open2(c, videocodec, NULL) < 0) + { + Con_Printf("Could not init codec instance \"%s\". Maybe try a different framerate/resolution/bitrate\n", videocodec->name); + AVEnc_End(ctx); + return NULL; + } + + ctx->picture = alloc_frame(c->pix_fmt, c->width, c->height); + + ctx->video_outbuf_size = 200000; + ctx->video_outbuf = av_malloc(ctx->video_outbuf_size); + if (!ctx->video_outbuf) + ctx->video_outbuf_size = 0; + } + } + if (audiocodec) + { + ctx->audio_st = add_audio_stream(ctx, audiocodec, *sndkhz, *sndbits, *sndchannels); + if (ctx->audio_st) + { + AVCodecContext *c = ctx->audio_st->codec; + if (avcodec_open2(c, audiocodec, NULL) < 0) + { + Con_Printf("Could not init codec instance \"%s\".\n", audiocodec->name); + AVEnc_End(ctx); + return NULL; + } + + ctx->audio = avcodec_alloc_frame(); + } + } + + av_dump_format(ctx->fc, 0, streamname, 1); + + if (!(fmt->flags & AVFMT_NOFILE)) + { + if (avio_open(&ctx->fc->pb, streamname, AVIO_FLAG_WRITE) < 0) + { + Con_Printf("Could not open '%s'\n", streamname); + AVEnc_End(ctx); + return NULL; + } + } + + //nearly complete, can make the file dirty now. + avformat_write_header(ctx->fc, NULL); + ctx->doneheaders = true; + return ctx; +} +static void AVEnc_End (void *vctx) +{ + struct encctx *ctx = vctx; + unsigned int i; + + close_video(ctx); + + //don't write trailers if this is an error case and we never even wrote the headers. + if (ctx->doneheaders) + av_write_trailer(ctx->fc); + + for(i = 0; i < ctx->fc->nb_streams; i++) + av_freep(&ctx->fc->streams[i]); +// if (!(fmt->flags & AVFMT_NOFILE)) + avio_close(ctx->fc->pb); + av_free(ctx->fc); + free(ctx); +} +static media_encoder_funcs_t encoderfuncs = +{ + AVEnc_Begin, + AVEnc_Video, + AVEnc_Audio, + AVEnc_End +}; + + + +qboolean AVEnc_Init(void) +{ + Cvar_Register("avplug_format", "", 0, "avplug"); + + Cvar_Register("avplug_videocodec", "", 0, "avplug"); + Cvar_Register("avplug_videocodecprofile", "", 0, "avplug"); + Cvar_Register("avplug_videobitrate", "4000000", 0, "avplug"); + Cvar_Register("avplug_videoforcewidth", "", 0, "avplug"); + Cvar_Register("avplug_videoforceheight", "", 0, "avplug"); + Cvar_Register("avplug_audiocodec", "", 0, "avplug"); + Cvar_Register("avplug_audiobitrate", "64000", 0, "avplug"); + + if (!Plug_ExportNative("Media_VideoEncoder", &encoderfuncs)) + { + Con_Printf("avplug: Engine doesn't support media encoder plugins\n"); + return false; + } + + return true; +} diff --git a/plugins/avplug/readme.txt b/plugins/avplug/readme.txt new file mode 100644 index 00000000..7c056b57 --- /dev/null +++ b/plugins/avplug/readme.txt @@ -0,0 +1,22 @@ +video encoder/decoder using the ffmpeg avformat/avcodec libraries. + +The video decoder plugs into the media decoder functionality on media with an 'av:' prefix, specifically: +The console command 'playfilm av:c:\foo.mpg' will start playing back c:\foo.mpg fullscreen. +The shader term 'videomap av:c:\foo.mpg' will play the video upon the shader. This can be used with csqc+drawpic, csqc+beginpolygon, or placed upon walls. +It theoretically supports any file that the avformat/avcodec libraries support, but has no ability to pass arguments, thus playback is likely limited only to files which require no explicit overrides. + +The video encoder plugs into the existing capture command. Or something. I don't know. Its all basically junk. +The container type is guessed by the file name used. +avplug_format says which container format to use. If empty, will be guessed based upon file extension. See ffmpeg docs for more info. +avplug_videocodec says which video codec to use. If empty, will be guessed based upon the container type ('libx264' for h264 compression). See ffmpeg docs for a full list. +avplug_videobitrate says what bitrate to encode at. Default 400000. +At the time of writing, audio is not implemented. + +To check if the plugin is loaded, use the plug_list command. + +For streaming, you can try this: +avplug_format mpegts +avplug_videocodec mpeg4 +capture udp://PLAYERIP:1234 +You can then run VLC or some such app and tell it to listen on port 1234. +You might be able to find some other protocol/codec that works better for you. Consult the ffmpeg documentation for that, if you can find something that's actually readable. diff --git a/plugins/berkelium/berkelium.vcproj b/plugins/berkelium/berkelium.vcproj index 7c97f7df..0069b2d5 100644 --- a/plugins/berkelium/berkelium.vcproj +++ b/plugins/berkelium/berkelium.vcproj @@ -2,8 +2,9 @@ +qboolean inited; + class decctx { public: @@ -188,6 +190,13 @@ static void *Dec_Create(char *medianame) else return NULL; + if (!inited) + { + //linux lags behind and apparently returns void, so don't bother checking return values on windows, cos I'm lazy. + Berkelium::init(Berkelium::FileString::empty()); + inited = qtrue; + } + decctx *ctx = new decctx(); Berkelium::Context* context = Berkelium::Context::create(); @@ -366,22 +375,23 @@ static void Dec_ChangeStream(void *vctx, char *newstream) static bool Dec_Init(void) { - //linux lags behind and apparently returns void. - Berkelium::init(Berkelium::FileString::empty()); return true; } static qintptr_t Dec_Tick(qintptr_t *args) { //need to keep it ticking over, if any work is to be done. - Berkelium::update(); + if (inited) + Berkelium::update(); return 0; } static qintptr_t Dec_Shutdown(qintptr_t *args) { //force-kill all. - Berkelium::destroy(); + if (inited) + Berkelium::destroy(); + inited = qfalse; return 0; } diff --git a/plugins/engine.h b/plugins/engine.h index fac72f2f..3f980c3f 100644 --- a/plugins/engine.h +++ b/plugins/engine.h @@ -9,16 +9,24 @@ typedef enum uploadfmt_e typedef struct { - void *(*createdecoder)(char *name); //needed - void *(*decodeframe)(void *ctx, qboolean nosound, enum uploadfmt_e *fmt, int *width, int *height); //needed - void (*doneframe)(void *ctx, void *img); //basically a free() - void (*shutdown)(void *ctx); //probably needed... - void (*rewind)(void *ctx); + void *(QDECL *createdecoder)(char *name); //needed + void *(QDECL *decodeframe)(void *ctx, qboolean nosound, enum uploadfmt_e *fmt, int *width, int *height); //needed + void (QDECL *doneframe)(void *ctx, void *img); //basically a free() + void (QDECL *shutdown)(void *ctx); //probably needed... + void (QDECL *rewind)(void *ctx); //these are any interactivity functions you might want... - void (*cursormove) (void *ctx, float posx, float posy); //pos is 0-1 - void (*key) (void *ctx, int code, int unicode, int event); //key event! event=1=down - qboolean (*setsize) (void *ctx, int width, int height); //updates the desired screen-space size - void (*getsize) (void *ctx, int *width, int *height); //retrieves the screen-space size - void (*changestream) (void *ctx, char *streamname); //can be used to accept commands from qc + void (QDECL *cursormove) (void *ctx, float posx, float posy); //pos is 0-1 + void (QDECL *key) (void *ctx, int code, int unicode, int event); //key event! event=1=down + qboolean (QDECL *setsize) (void *ctx, int width, int height); //updates the desired screen-space size + void (QDECL *getsize) (void *ctx, int *width, int *height); //retrieves the screen-space size + void (QDECL *changestream) (void *ctx, char *streamname); //can be used to accept commands from qc } media_decoder_funcs_t; + +typedef struct +{ + void *(QDECL *capture_begin) (char *streamname, int videorate, int width, int height, int *sndkhz, int *sndchannels, int *sndbits); + void (QDECL *capture_video) (void *ctx, void *data, int frame, int width, int height); + void (QDECL *capture_audio) (void *ctx, void *data, int bytes); + void (QDECL *capture_end) (void *ctx); +} media_encoder_funcs_t; diff --git a/plugins/plugin.c b/plugins/plugin.c index 076eeaee..f78817dc 100644 --- a/plugins/plugin.c +++ b/plugins/plugin.c @@ -265,6 +265,20 @@ void Con_Printf(const char *format, ...) Con_Print(string); } +void Con_DPrintf(const char *format, ...) +{ + va_list argptr; + static char string[1024]; + + if (!Cvar_GetFloat("developer")) + return; + + va_start (argptr, format); + vsnprintf (string, sizeof(string), format,argptr); + va_end (argptr); + + Con_Print(string); +} void Sys_Errorf(const char *format, ...) { va_list argptr; diff --git a/plugins/plugin.h b/plugins/plugin.h index 765f488e..aca81aef 100644 --- a/plugins/plugin.h +++ b/plugins/plugin.h @@ -225,6 +225,7 @@ char *va(char *format, ...); qintptr_t Plug_Init(qintptr_t *args); qboolean Plug_Export(const char *name, export_t func); void Con_Printf(const char *format, ...); +void Con_DPrintf(const char *format, ...); //not a particuarly efficient implementation, so beware. void Sys_Errorf(const char *format, ...); typedef unsigned char qbyte; void Q_strncpyz(char *d, const char *s, int n); diff --git a/specs/console.txt b/specs/console.txt new file mode 100644 index 00000000..36d0d7f9 --- /dev/null +++ b/specs/console.txt @@ -0,0 +1,67 @@ +Autocompletion: + FTE will not randomly complete commands. The ctrl+space key combo is directly equivelent to tab in vanilla engines. + Some commands/cvars have descriptions. These will be shown if the command is entered. + +Chat: + Lines typed in may be interpreted as either chat or commands, depending on the value of cl_chatmode. + Lines starting with a / are always commands. + Lines where the first word is automatically coloured yellow will be executed as commands. + Lines where the first word is automatically coloured white will be broadcast to other players as chat. + Tab completion will always insert a leading / to designate the line as a command rather than chat. + + cl_chatmode 0 - Acts like NQ where the console ONLY accepts commands. + cl_chatmode 1 - Acts like Q3 where the input is assumed to be chat. Commands require a leading / (which is also inserted by tab, by the way). + cl_chatmode 2 - Acts like QW where the input is assumed to be chat if its not a valid command. + +Keys: + tab: attempt to complete the command. If there's multiple, will complete only as far as the commonality goes. + ctrl+space: completes the current line using the highlighted suggestion + ctrl+tab: cycles consoles. + mouse1+drag: scroll console up/down. + mouse1+click: 'use' link underneath the cursor. + shift+mouse1: insert word/link/ip under the cursor to the input line. + mouse2: select+copy text to the clipboard. + ctrl+c/ctrl+ins: copy the entire input line to the clipboard. + ctrl+v/shift+ins: insert the clipboard contents onto the input line. newlines are replaced with semi-colons. + left/right: move cursor left/right. + del: remove input-line character under the cursor. if at the end of line removes just before the cursor. + backspace: removes char to the left of the cursor. + up/down: scroll through command history. + pgup/pgdn/mwheel: scroll console up/down. + home: go to top of console (oldest). + end: go to bottom of console (most recent). + alt: make text red + ctrl+: 0123456789[]gryb(=)a<->,.BC ctrl with one of the prior chars give various special chars. yellow numbers, LEDs, separators. + +Links: + Basic format: + ^[^2VISIBLE TEXT\key1\value1\key2\value2^] + Colour markup for the link must be contained within, and will be reset at the end of it. + + CSQC: + If CSQC is running at the time, clicking on a link will result in this call: + float(string linktext, string linkinfo) CSQC_ConsoleLink; + If the CSQC returns false, the engine will examine the link for default fields, so if you handle it yourself you must return true to prevent both csqc and engine trying to do the same thing. + The 'linktext' field is the visible text from the link (ie: what the user saw). However, any colour modifiers may have been converted/mangled. + The 'linkinfo' is the first \ and everything up to the closing ^]. Again, colours should be avoided. + For easy parsing/generation of the linkinfo field, you can use the infoget/infoadd builtins from the FTE_STRINGS extension. + Note that links can be sent from other players also. The behaviour of the link is also hidden from the user. + Thus you should either require the user to confirm the action, or provide links that are merely informative. + The builtin field names are somewhat generic. You can use them as a fallback for if the player disconnects. + + Built in link fields: + player: the link is associated with a player slot. The value should be entnum(playerentity)-1. + action: if this field is also set, then when clicked the engine shall carry out the action named in the value upon that player slot. + kick: kicks the player (requires rcon). + ban: bans the player's ip (requires rcon). + mute: mutes the player's voicechat feature. + ignore: any 'say' commands received from the player are ignored. also mutes. + desc: displays the value as text. The use of this field is somewhat limited by length. + connect: the client will attempt to 'connect $value', so the value must be an acceptable hostname or ip:port. You should probably always include the port. + qtv: the client will attempt to 'qtvplay $value', so the value must be an acceptable qtv stream identifier. + demo: the client will attempt to 'playdemo $value', so this value must include any subdirectory for the named demo. + cmd: the client will attempt to 'cmd $value'. A mod can see the results of this using KRIMZON_SV_PARSECLIENTCOMMAND. + impulse: the client will attempt to 'impulse $value'. A mod can thus snoop on this by checking self.impulse on the player. Must naturally be between 0 and 255. + leading forward-slash: Links with no info and a leading forward slash will be inserted into the input line when clicked. The user must still press enter to issue the given command. Use semi-colons if you wish to include multiple cvars/commands in a single link. + This list is subject to change. + \ No newline at end of file