From 54e2a4d9d35092d6b33a40c171f28a3ee6e65468 Mon Sep 17 00:00:00 2001 From: Jeff Teunissen Date: Fri, 8 Dec 2000 06:51:37 +0000 Subject: [PATCH] Okay, the big whitespace reformat. There is some silliness (case statements, variable declarations), but all in all it's not bad. --- include/context_x11.h | 2 +- source/buildnum.c | 38 +- source/cd_audio.c | 530 ++++---- source/cd_linux.c | 280 ++-- source/cd_null.c | 23 +- source/cd_sdl.c | 252 ++-- source/cd_win.c | 390 +++--- source/checksum.c | 135 +- source/cl_cam.c | 470 +++---- source/cl_cmd.c | 62 +- source/cl_cvar.c | 10 +- source/cl_demo.c | 469 ++++--- source/cl_ents.c | 817 ++++++------ source/cl_input.c | 580 ++++++--- source/cl_main.c | 1113 ++++++++-------- source/cl_misc.c | 16 +- source/cl_parse.c | 1206 ++++++++--------- source/cl_pred.c | 126 +- source/cl_slist.c | 306 +++-- source/cl_sys_sdl.c | 146 ++- source/cl_sys_unix.c | 174 +-- source/cl_sys_win.c | 376 +++--- source/cl_tent.c | 476 ++++--- source/cl_trans.c | 41 +- source/cmd.c | 532 ++++---- source/com.c | 59 +- source/console.c | 406 +++--- source/context_x11.c | 163 ++- source/crc.c | 84 +- source/cvar.c | 254 ++-- source/d_edge.c | 235 ++-- source/d_fill.c | 51 +- source/d_init.c | 77 +- source/d_modech.c | 45 +- source/d_part.c | 229 ++-- source/d_polyse.c | 616 +++++---- source/d_scan.c | 355 ++--- source/d_sky.c | 83 +- source/d_sprite.c | 249 ++-- source/d_surf.c | 197 ++- source/d_vars.c | 25 +- source/d_zpoint.c | 19 +- source/dga_check.c | 35 +- source/dirent.c | 336 +++-- source/draw.c | 627 ++++----- source/fnmatch.c | 277 ++-- source/fractalnoise.c | 64 +- source/gl_draw.c | 873 +++++++------ source/gl_dyn_fires.c | 119 +- source/gl_dyn_part.c | 594 ++++----- source/gl_dyn_textures.c | 94 +- source/gl_mesh.c | 251 ++-- source/gl_model_alias.c | 217 ++-- source/gl_model_brush.c | 81 +- source/gl_model_fullbright.c | 29 +- source/gl_model_sprite.c | 29 +- source/gl_ngraph.c | 127 +- source/gl_refrag.c | 173 ++- source/gl_rlight.c | 354 ++--- source/gl_rmain.c | 610 ++++----- source/gl_rmisc.c | 378 +++--- source/gl_rsurf.c | 918 ++++++------- source/gl_screen.c | 14 +- source/gl_sky_clip.c | 361 +++--- source/gl_trans.c | 9 +- source/gl_view.c | 91 +- source/gl_warp.c | 137 +- source/in_null.c | 21 +- source/in_sdl.c | 453 ++++--- source/in_svgalib.c | 342 ++--- source/in_win.c | 1012 +++++++-------- source/in_x11.c | 328 +++-- source/info.c | 156 +-- source/joy_linux.c | 101 +- source/joy_null.c | 22 +- source/keys.c | 503 ++++---- source/link.c | 16 +- source/locs.c | 102 +- source/mathlib.c | 517 ++++---- source/mdfour.c | 210 +-- source/menu.c | 1711 ++++++++++++------------ source/model.c | 165 +-- source/model_alias.c | 140 +- source/model_brush.c | 757 ++++++----- source/model_sprite.c | 105 +- source/msg.c | 274 ++-- source/net_chan.c | 263 ++-- source/net_com.c | 17 +- source/net_udp.c | 263 ++-- source/nonintel.c | 14 +- source/pcx.c | 30 +- source/pmove.c | 590 ++++----- source/pmovetst.c | 270 ++-- source/pr_cmds.c | 1598 ++++++++++++----------- source/pr_edict.c | 1157 +++++++++-------- source/pr_exec.c | 23 +- source/pr_offs.c | 34 +- source/qargs.c | 74 +- source/qendian.c | 28 +- source/qfgl_ext.c | 40 +- source/quakefs.c | 640 +++++---- source/quakeio.c | 198 +-- source/r_aclip.c | 278 ++-- source/r_alias.c | 488 ++++--- source/r_bsp.c | 454 +++---- source/r_draw.c | 548 ++++---- source/r_edge.c | 458 +++---- source/r_efrag.c | 185 ++- source/r_light.c | 178 ++- source/r_main.c | 979 +++++++------- source/r_misc.c | 344 +++-- source/r_part.c | 514 ++++---- source/r_sky.c | 218 ++-- source/r_sprite.c | 269 ++-- source/r_surf.c | 447 +++---- source/r_vars.c | 7 +- source/r_view.c | 493 +++---- source/sbar.c | 933 +++++++------ source/screen.c | 26 +- source/sizebuf.c | 51 +- source/skin.c | 160 ++- source/snd_alsa_0_5.c | 356 ++--- source/snd_alsa_0_6.c | 328 ++--- source/snd_disk.c | 59 +- source/snd_dma.c | 731 +++++------ source/snd_mem.c | 263 ++-- source/snd_mix.c | 388 +++--- source/snd_null.c | 24 +- source/snd_oss.c | 144 ++- source/snd_sdl.c | 62 +- source/snd_sun.c | 119 +- source/snd_win.c | 532 ++++---- source/sv_ccmds.c | 560 ++++---- source/sv_cvar.c | 33 +- source/sv_ents.c | 409 +++--- source/sv_init.c | 266 ++-- source/sv_main.c | 139 +- source/sv_misc.c | 6 +- source/sv_model.c | 18 +- source/sv_move.c | 308 +++-- source/sv_nchan.c | 129 +- source/sv_phys.c | 627 +++++---- source/sv_send.c | 530 ++++---- source/sv_sys_unix.c | 103 +- source/sv_sys_win.c | 154 ++- source/sv_user.c | 1077 +++++++-------- source/sw_model_alias.c | 224 ++-- source/sw_model_brush.c | 22 +- source/sw_model_sprite.c | 48 +- source/sw_view.c | 55 +- source/sys_null.c | 89 +- source/sys_unix.c | 123 +- source/sys_win.c | 97 +- source/teamplay.c | 219 ++-- source/tga.c | 232 ++-- source/va.c | 16 +- source/ver_check.c | 34 +- source/vid.c | 32 +- source/vid_3dfxsvga.c | 122 +- source/vid_common_gl.c | 124 +- source/vid_ggi.c | 1003 +++++++------- source/vid_glx.c | 33 +- source/vid_mgl.c | 2370 ++++++++++++++++------------------ source/vid_null.c | 47 +- source/vid_sdl.c | 209 +-- source/vid_sgl.c | 89 +- source/vid_svgalib.c | 460 ++++--- source/vid_wgl.c | 1413 ++++++++++---------- source/vid_x11.c | 301 ++--- source/wad.c | 122 +- source/world.c | 585 +++++---- source/zone.c | 436 +++---- 172 files changed, 26949 insertions(+), 26640 deletions(-) diff --git a/include/context_x11.h b/include/context_x11.h index b0f697f..576691f 100644 --- a/include/context_x11.h +++ b/include/context_x11.h @@ -57,7 +57,7 @@ void x11_process_events (void); void x11_open_display (void); void x11_close_display (void); void x11_create_null_cursor (void); -void x11_set_vidmode (int, int); +void x11_update_vidmode (int, int); void x11_restore_vidmode (void); void x11_create_window (int, int); void x11_grab_keyboard (void); diff --git a/source/buildnum.c b/source/buildnum.c index 568b7c8..0251340 100644 --- a/source/buildnum.c +++ b/source/buildnum.c @@ -37,43 +37,41 @@ #endif //char *date = "Dec 21 1999"; -static char *date = __DATE__ ; -static char *mon[12] = -{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; -static char mond[12] = -{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; +static char *date = __DATE__; +static char *mon[12] = + { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", + "Nov", "Dec" }; +static char mond[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // returns days since Dec 21 1999 -int build_number( void ) +int +build_number (void) { - int m = 0; - int d = 0; - int y = 0; - static int b = 0; + int m = 0; + int d = 0; + int y = 0; + static int b = 0; if (b != 0) return b; - for (m = 0; m < 11; m++) - { - if (strncasecmp( &date[0], mon[m], 3 ) == 0) + for (m = 0; m < 11; m++) { + if (strncasecmp (&date[0], mon[m], 3) == 0) break; d += mond[m]; } - d += atoi( &date[4] ) - 1; + d += atoi (&date[4]) - 1; - y = atoi( &date[7] ) - 1900; + y = atoi (&date[7]) - 1900; - b = d + (int)((y - 1) * 365.25); + b = d + (int) ((y - 1) * 365.25); - if (((y % 4) == 0) && m > 1) - { + if (((y % 4) == 0) && m > 1) { b += 1; } - b -= 36148; // Dec 21 1999 + b -= 36148; // Dec 21 1999 return b; } - diff --git a/source/cd_audio.c b/source/cd_audio.c index 8478987..9f00e28 100644 --- a/source/cd_audio.c +++ b/source/cd_audio.c @@ -27,12 +27,12 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include "dosisms.h" -extern cvar_t *bgmvolume; +extern cvar_t *bgmvolume; #define ADDRESS_MODE_HSG 0 #define ADDRESS_MODE_RED_BOOK 1 @@ -102,159 +102,145 @@ extern cvar_t *bgmvolume; #pragma pack(1) -struct playAudioRequest -{ - char addressingMode; - int startLocation; - int sectors; +struct playAudioRequest { + char addressingMode; + int startLocation; + int sectors; }; -struct readRequest -{ - char mediaDescriptor; - short bufferOffset; - short bufferSegment; - short length; - short startSector; - int volumeID; +struct readRequest { + char mediaDescriptor; + short bufferOffset; + short bufferSegment; + short length; + short startSector; + int volumeID; }; -struct writeRequest -{ - char mediaDescriptor; - short bufferOffset; - short bufferSegment; - short length; - short startSector; - int volumeID; +struct writeRequest { + char mediaDescriptor; + short bufferOffset; + short bufferSegment; + short length; + short startSector; + int volumeID; }; -struct cd_request -{ - char headerLength; - char unit; - char command; - short status; - char reserved[8]; - union - { - struct playAudioRequest playAudio; - struct readRequest read; - struct writeRequest write; +struct cd_request { + char headerLength; + char unit; + char command; + short status; + char reserved[8]; + union { + struct playAudioRequest playAudio; + struct readRequest read; + struct writeRequest write; } x; }; -struct audioChannelInfo_s -{ - char code; - char channel0input; - char channel0volume; - char channel1input; - char channel1volume; - char channel2input; - char channel2volume; - char channel3input; - char channel3volume; +struct audioChannelInfo_s { + char code; + char channel0input; + char channel0volume; + char channel1input; + char channel1volume; + char channel2input; + char channel2volume; + char channel3input; + char channel3volume; }; -struct deviceStatus_s -{ - char code; - int status; +struct deviceStatus_s { + char code; + int status; }; -struct mediaChange_s -{ - char code; - char status; +struct mediaChange_s { + char code; + char status; }; -struct audioDiskInfo_s -{ - char code; - char lowTrack; - char highTrack; - int leadOutStart; +struct audioDiskInfo_s { + char code; + char lowTrack; + char highTrack; + int leadOutStart; }; -struct audioTrackInfo_s -{ - char code; - char track; - int start; - char control; +struct audioTrackInfo_s { + char code; + char track; + int start; + char control; }; -struct audioStatus_s -{ - char code; - short status; - int PRstartLocation; - int PRendLocation; +struct audioStatus_s { + char code; + short status; + int PRstartLocation; + int PRendLocation; }; -struct reset_s -{ - char code; +struct reset_s { + char code; }; -union readInfo_u -{ - struct audioChannelInfo_s audioChannelInfo; - struct deviceStatus_s deviceStatus; - struct mediaChange_s mediaChange; - struct audioDiskInfo_s audioDiskInfo; - struct audioTrackInfo_s audioTrackInfo; - struct audioStatus_s audioStatus; - struct reset_s reset; +union readInfo_u { + struct audioChannelInfo_s audioChannelInfo; + struct deviceStatus_s deviceStatus; + struct mediaChange_s mediaChange; + struct audioDiskInfo_s audioDiskInfo; + struct audioTrackInfo_s audioTrackInfo; + struct audioStatus_s audioStatus; + struct reset_s reset; }; #pragma pack() #define MAXIMUM_TRACKS 32 -typedef struct -{ - int start; - int length; - qboolean isData; +typedef struct { + int start; + int length; + qboolean isData; } track_info; -typedef struct -{ - qboolean valid; - int leadOutAddress; - track_info track[MAXIMUM_TRACKS]; - byte lowTrack; - byte highTrack; +typedef struct { + qboolean valid; + int leadOutAddress; + track_info track[MAXIMUM_TRACKS]; + byte lowTrack; + byte highTrack; } cd_info; -static struct cd_request *cdRequest; -static union readInfo_u *readInfo; -static cd_info cd; +static struct cd_request *cdRequest; +static union readInfo_u *readInfo; +static cd_info cd; -static qboolean playing = false; -static qboolean wasPlaying = false; -static qboolean mediaCheck = false; -static qboolean initialized = false; -static qboolean enabled = true; +static qboolean playing = false; +static qboolean wasPlaying = false; +static qboolean mediaCheck = false; +static qboolean initialized = false; +static qboolean enabled = true; static qboolean playLooping = false; -static short cdRequestSegment; -static short cdRequestOffset; -static short readInfoSegment; -static short readInfoOffset; -static byte remap[256]; -static byte cdrom; -static byte playTrack; -static byte cdvolume; +static short cdRequestSegment; +static short cdRequestOffset; +static short readInfoSegment; +static short readInfoOffset; +static byte remap[256]; +static byte cdrom; +static byte playTrack; +static byte cdvolume; -static int RedBookToSector(int rb) +static int +RedBookToSector (int rb) { - byte minute; - byte second; - byte frame; + byte minute; + byte second; + byte frame; minute = (rb >> 16) & 0xff; second = (rb >> 8) & 0xff; @@ -263,7 +249,8 @@ static int RedBookToSector(int rb) } -static void CDAudio_Reset(void) +static void +CDAudio_Reset (void) { cdRequest->headerLength = 13; cdRequest->unit = 0; @@ -273,7 +260,8 @@ static void CDAudio_Reset(void) cdRequest->x.write.mediaDescriptor = 0; cdRequest->x.write.bufferOffset = readInfoOffset; cdRequest->x.write.bufferSegment = readInfoSegment; - cdRequest->x.write.length = sizeof(struct reset_s); + cdRequest->x.write.length = sizeof (struct reset_s); + cdRequest->x.write.startSector = 0; cdRequest->x.write.volumeID = 0; @@ -287,7 +275,8 @@ static void CDAudio_Reset(void) } -static void CDAudio_Eject(void) +static void +CDAudio_Eject (void) { cdRequest->headerLength = 13; cdRequest->unit = 0; @@ -297,7 +286,8 @@ static void CDAudio_Eject(void) cdRequest->x.write.mediaDescriptor = 0; cdRequest->x.write.bufferOffset = readInfoOffset; cdRequest->x.write.bufferSegment = readInfoSegment; - cdRequest->x.write.length = sizeof(struct reset_s); + cdRequest->x.write.length = sizeof (struct reset_s); + cdRequest->x.write.startSector = 0; cdRequest->x.write.volumeID = 0; @@ -311,9 +301,10 @@ static void CDAudio_Eject(void) } -static int CDAudio_GetAudioTrackInfo(byte track, int *start) +static int +CDAudio_GetAudioTrackInfo (byte track, int *start) { - byte control; + byte control; cdRequest->headerLength = 13; cdRequest->unit = 0; @@ -323,7 +314,8 @@ static int CDAudio_GetAudioTrackInfo(byte track, int *start) cdRequest->x.read.mediaDescriptor = 0; cdRequest->x.read.bufferOffset = readInfoOffset; cdRequest->x.read.bufferSegment = readInfoSegment; - cdRequest->x.read.length = sizeof(struct audioTrackInfo_s); + cdRequest->x.read.length = sizeof (struct audioTrackInfo_s); + cdRequest->x.read.startSector = 0; cdRequest->x.read.volumeID = 0; @@ -336,9 +328,9 @@ static int CDAudio_GetAudioTrackInfo(byte track, int *start) regs.x.bx = cdRequestOffset; dos_int86 (0x2f); - if (cdRequest->status & STATUS_ERROR_BIT) - { - Con_DPrintf("CDAudio_GetAudioTrackInfo %04x\n", cdRequest->status & 0xffff); + if (cdRequest->status & STATUS_ERROR_BIT) { + Con_DPrintf ("CDAudio_GetAudioTrackInfo %04x\n", + cdRequest->status & 0xffff); return -1; } @@ -348,9 +340,10 @@ static int CDAudio_GetAudioTrackInfo(byte track, int *start) } -static int CDAudio_GetAudioDiskInfo(void) +static int +CDAudio_GetAudioDiskInfo (void) { - int n; + int n; cdRequest->headerLength = 13; cdRequest->unit = 0; @@ -360,7 +353,8 @@ static int CDAudio_GetAudioDiskInfo(void) cdRequest->x.read.mediaDescriptor = 0; cdRequest->x.read.bufferOffset = readInfoOffset; cdRequest->x.read.bufferSegment = readInfoSegment; - cdRequest->x.read.length = sizeof(struct audioDiskInfo_s); + cdRequest->x.read.length = sizeof (struct audioDiskInfo_s); + cdRequest->x.read.startSector = 0; cdRequest->x.read.volumeID = 0; @@ -372,9 +366,9 @@ static int CDAudio_GetAudioDiskInfo(void) regs.x.bx = cdRequestOffset; dos_int86 (0x2f); - if (cdRequest->status & STATUS_ERROR_BIT) - { - Con_DPrintf("CDAudio_GetAudioDiskInfo %04x\n", cdRequest->status & 0xffff); + if (cdRequest->status & STATUS_ERROR_BIT) { + Con_DPrintf ("CDAudio_GetAudioDiskInfo %04x\n", + cdRequest->status & 0xffff); return -1; } @@ -383,14 +377,16 @@ static int CDAudio_GetAudioDiskInfo(void) cd.highTrack = readInfo->audioDiskInfo.highTrack; cd.leadOutAddress = readInfo->audioDiskInfo.leadOutStart; - for (n = cd.lowTrack; n <= cd.highTrack; n++) - { + for (n = cd.lowTrack; n <= cd.highTrack; n++) { cd.track[n].isData = CDAudio_GetAudioTrackInfo (n, &cd.track[n].start); - if (n > cd.lowTrack) - { - cd.track[n-1].length = RedBookToSector(cd.track[n].start) - RedBookToSector(cd.track[n-1].start); + if (n > cd.lowTrack) { + cd.track[n - 1].length = + RedBookToSector (cd.track[n].start) - + RedBookToSector (cd.track[n - 1].start); if (n == cd.highTrack) - cd.track[n].length = RedBookToSector(cd.leadOutAddress) - RedBookToSector(cd.track[n].start); + cd.track[n].length = + RedBookToSector (cd.leadOutAddress) - + RedBookToSector (cd.track[n].start); } } @@ -398,7 +394,8 @@ static int CDAudio_GetAudioDiskInfo(void) } -static int CDAudio_GetAudioStatus(void) +static int +CDAudio_GetAudioStatus (void) { cdRequest->headerLength = 13; cdRequest->unit = 0; @@ -408,7 +405,8 @@ static int CDAudio_GetAudioStatus(void) cdRequest->x.read.mediaDescriptor = 0; cdRequest->x.read.bufferOffset = readInfoOffset; cdRequest->x.read.bufferSegment = readInfoSegment; - cdRequest->x.read.length = sizeof(struct audioStatus_s); + cdRequest->x.read.length = sizeof (struct audioStatus_s); + cdRequest->x.read.startSector = 0; cdRequest->x.read.volumeID = 0; @@ -426,7 +424,8 @@ static int CDAudio_GetAudioStatus(void) } -static int CDAudio_MediaChange(void) +static int +CDAudio_MediaChange (void) { cdRequest->headerLength = 13; cdRequest->unit = 0; @@ -436,7 +435,8 @@ static int CDAudio_MediaChange(void) cdRequest->x.read.mediaDescriptor = 0; cdRequest->x.read.bufferOffset = readInfoOffset; cdRequest->x.read.bufferSegment = readInfoSegment; - cdRequest->x.read.length = sizeof(struct mediaChange_s); + cdRequest->x.read.length = sizeof (struct mediaChange_s); + cdRequest->x.read.startSector = 0; cdRequest->x.read.volumeID = 0; @@ -452,7 +452,8 @@ static int CDAudio_MediaChange(void) } -byte CDAudio_GetVolume (void) +byte +CDAudio_GetVolume (void) { return cdvolume; } @@ -460,7 +461,8 @@ byte CDAudio_GetVolume (void) // we set the volume to 0 first and then to the desired volume // some cd-rom drivers seem to need it done this way -void CDAudio_SetVolume (byte volume) +void +CDAudio_SetVolume (byte volume) { if (!initialized || !enabled) return; @@ -473,7 +475,8 @@ void CDAudio_SetVolume (byte volume) cdRequest->x.read.mediaDescriptor = 0; cdRequest->x.read.bufferOffset = readInfoOffset; cdRequest->x.read.bufferSegment = readInfoSegment; - cdRequest->x.read.length = sizeof(struct audioChannelInfo_s); + cdRequest->x.read.length = sizeof (struct audioChannelInfo_s); + cdRequest->x.read.startSector = 0; cdRequest->x.read.volumeID = 0; @@ -506,36 +509,34 @@ void CDAudio_SetVolume (byte volume) } -void CDAudio_Play(byte track, qboolean looping) +void +CDAudio_Play (byte track, qboolean looping) { if (!initialized || !enabled) return; - + if (!cd.valid) return; track = remap[track]; - if (playing) - { + if (playing) { if (playTrack == track) return; - CDAudio_Stop(); + CDAudio_Stop (); } playLooping = looping; - if (track < cd.lowTrack || track > cd.highTrack) - { - Con_DPrintf("CDAudio_Play: Bad track number %u.\n", track); + if (track < cd.lowTrack || track > cd.highTrack) { + Con_DPrintf ("CDAudio_Play: Bad track number %u.\n", track); return; } playTrack = track; - if (cd.track[track].isData) - { - Con_DPrintf("CDAudio_Play: Can not play data.\n"); + if (cd.track[track].isData) { + Con_DPrintf ("CDAudio_Play: Can not play data.\n"); return; } @@ -554,9 +555,8 @@ void CDAudio_Play(byte track, qboolean looping) regs.x.bx = cdRequestOffset; dos_int86 (0x2f); - if (cdRequest->status & STATUS_ERROR_BIT) - { - Con_DPrintf("CDAudio_Play: track %u failed\n", track); + if (cdRequest->status & STATUS_ERROR_BIT) { + Con_DPrintf ("CDAudio_Play: track %u failed\n", track); cd.valid = false; playing = false; return; @@ -566,11 +566,12 @@ void CDAudio_Play(byte track, qboolean looping) } -void CDAudio_Stop(void) +void +CDAudio_Stop (void) { if (!initialized || !enabled) return; - + cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_STOP_AUDIO; @@ -587,17 +588,18 @@ void CDAudio_Stop(void) } -void CDAudio_Resume(void) +void +CDAudio_Resume (void) { if (!initialized || !enabled) return; - + if (!cd.valid) return; if (!wasPlaying) return; - + cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_RESUME_AUDIO; @@ -613,121 +615,113 @@ void CDAudio_Resume(void) } -static void CD_f (void) +static void +CD_f (void) { - char *command; - int ret; - int n; - int startAddress; + char *command; + int ret; + int n; + int startAddress; - if (Cmd_Argc() < 2) + if (Cmd_Argc () < 2) return; command = Cmd_Argv (1); - if (Q_strcasecmp(command, "on") == 0) - { + if (Q_strcasecmp (command, "on") == 0) { enabled = true; return; } - if (Q_strcasecmp(command, "off") == 0) - { + if (Q_strcasecmp (command, "off") == 0) { if (playing) - CDAudio_Stop(); + CDAudio_Stop (); enabled = false; return; } - if (Q_strcasecmp(command, "reset") == 0) - { + if (Q_strcasecmp (command, "reset") == 0) { enabled = true; if (playing) - CDAudio_Stop(); + CDAudio_Stop (); for (n = 0; n < 256; n++) remap[n] = n; - CDAudio_Reset(); - CDAudio_GetAudioDiskInfo(); + CDAudio_Reset (); + CDAudio_GetAudioDiskInfo (); return; } - if (Q_strcasecmp(command, "remap") == 0) - { - ret = Cmd_Argc() - 2; - if (ret <= 0) - { + if (Q_strcasecmp (command, "remap") == 0) { + ret = Cmd_Argc () - 2; + if (ret <= 0) { for (n = 1; n < 256; n++) if (remap[n] != n) - Con_Printf(" %u -> %u\n", n, remap[n]); + Con_Printf (" %u -> %u\n", n, remap[n]); return; } for (n = 1; n <= ret; n++) - remap[n] = Q_atoi(Cmd_Argv (n+1)); + remap[n] = Q_atoi (Cmd_Argv (n + 1)); return; } - if (!cd.valid) - { - Con_Printf("No CD in player.\n"); + if (!cd.valid) { + Con_Printf ("No CD in player.\n"); return; } - if (Q_strcasecmp(command, "play") == 0) - { - CDAudio_Play(Q_atoi(Cmd_Argv (2)), false); + if (Q_strcasecmp (command, "play") == 0) { + CDAudio_Play (Q_atoi (Cmd_Argv (2)), false); return; } - if (Q_strcasecmp(command, "loop") == 0) - { - CDAudio_Play(Q_atoi(Cmd_Argv (2)), true); + if (Q_strcasecmp (command, "loop") == 0) { + CDAudio_Play (Q_atoi (Cmd_Argv (2)), true); return; } - if (Q_strcasecmp(command, "stop") == 0) - { - CDAudio_Stop(); + if (Q_strcasecmp (command, "stop") == 0) { + CDAudio_Stop (); return; } - if (Q_strcasecmp(command, "resume") == 0) - { - CDAudio_Resume(); + if (Q_strcasecmp (command, "resume") == 0) { + CDAudio_Resume (); return; } - if (Q_strcasecmp(command, "eject") == 0) - { + if (Q_strcasecmp (command, "eject") == 0) { if (playing) - CDAudio_Stop(); - CDAudio_Eject(); + CDAudio_Stop (); + CDAudio_Eject (); cd.valid = false; return; } - if (Q_strcasecmp(command, "info") == 0) - { - Con_Printf("%u tracks\n", cd.highTrack - cd.lowTrack + 1); - for (n = cd.lowTrack; n <= cd.highTrack; n++) - { + if (Q_strcasecmp (command, "info") == 0) { + Con_Printf ("%u tracks\n", cd.highTrack - cd.lowTrack + 1); + for (n = cd.lowTrack; n <= cd.highTrack; n++) { ret = CDAudio_GetAudioTrackInfo (n, &startAddress); - Con_Printf("Track %2u: %s at %2u:%02u\n", n, ret ? "data " : "music", (startAddress >> 16) & 0xff, (startAddress >> 8) & 0xff); + Con_Printf ("Track %2u: %s at %2u:%02u\n", n, + ret ? "data " : "music", (startAddress >> 16) & 0xff, + (startAddress >> 8) & 0xff); } if (playing) - Con_Printf("Currently %s track %u\n", playLooping ? "looping" : "playing", playTrack); - Con_Printf("Volume is %u\n", cdvolume); - CDAudio_MediaChange(); - Con_Printf("Status %04x\n", cdRequest->status & 0xffff); + Con_Printf ("Currently %s track %u\n", + playLooping ? "looping" : "playing", playTrack); + Con_Printf ("Volume is %u\n", cdvolume); + CDAudio_MediaChange (); + Con_Printf ("Status %04x\n", cdRequest->status & 0xffff); return; } } -void CDAudio_Update(void) +void +CDAudio_Update (void) { - int ret; - int newVolume; - static double lastUpdate; + int ret; + int newVolume; + static double lastUpdate; if (!initialized || !enabled) return; @@ -736,132 +730,128 @@ void CDAudio_Update(void) return; lastUpdate = realtime; - if (mediaCheck) - { - static double lastCheck; + if (mediaCheck) { + static double lastCheck; if ((realtime - lastCheck) < 5.0) return; lastCheck = realtime; - ret = CDAudio_MediaChange(); - if (ret == MEDIA_CHANGED) - { - Con_DPrintf("CDAudio: media changed\n"); + ret = CDAudio_MediaChange (); + if (ret == MEDIA_CHANGED) { + Con_DPrintf ("CDAudio: media changed\n"); playing = false; wasPlaying = false; cd.valid = false; - CDAudio_GetAudioDiskInfo(); + CDAudio_GetAudioDiskInfo (); return; } } - newVolume = (int)(bgmvolume->value * 255.0); - if (newVolume < 0) - { + newVolume = (int) (bgmvolume->value * 255.0); + if (newVolume < 0) { Cvar_SetValue (bgmvolume, 0.0); newVolume = 0; - } - else if (newVolume > 255) - { + } else if (newVolume > 255) { Cvar_SetValue (bgmvolume, 1.0); newVolume = 255; } if (cdvolume != newVolume) CDAudio_SetVolume (newVolume); - if (playing) - { - CDAudio_GetAudioStatus(); - if ((cdRequest->status & STATUS_BUSY_BIT) == 0) - { + if (playing) { + CDAudio_GetAudioStatus (); + if ((cdRequest->status & STATUS_BUSY_BIT) == 0) { playing = false; if (playLooping) - CDAudio_Play(playTrack, true); + CDAudio_Play (playTrack, true); } } } -qboolean CDAudio_Playing(void) +qboolean +CDAudio_Playing (void) { return playing; } -int CDAudio_Init(void) +int +CDAudio_Init (void) { - char *memory; - int n; + char *memory; + int n; if (cls.state == ca_dedicated) return -1; - if (COM_CheckParm("-nocdaudio")) + if (COM_CheckParm ("-nocdaudio")) return -1; - if (COM_CheckParm("-cdmediacheck")) + if (COM_CheckParm ("-cdmediacheck")) mediaCheck = true; regs.x.ax = 0x1500; regs.x.bx = 0; dos_int86 (0x2f); - if (regs.x.bx == 0) - { - Con_Printf ("MSCDEX not loaded, music is disabled. Use \"-nocdaudio\" if you wish to avoid this message in the future. See README.TXT for help.\n"); + if (regs.x.bx == 0) { + Con_Printf + ("MSCDEX not loaded, music is disabled. Use \"-nocdaudio\" if you wish to avoid this message in the future. See README.TXT for help.\n"); return -1; } if (regs.x.bx > 1) - Con_DPrintf("CDAudio_Init: First CD-ROM drive will be used\n"); + Con_DPrintf ("CDAudio_Init: First CD-ROM drive will be used\n"); cdrom = regs.x.cx; regs.x.ax = 0x150c; regs.x.bx = 0; dos_int86 (0x2f); - if (regs.x.bx == 0) - { - Con_Printf ("MSCDEX version 2.00 or later required for music. See README.TXT for help.\n"); + if (regs.x.bx == 0) { + Con_Printf + ("MSCDEX version 2.00 or later required for music. See README.TXT for help.\n"); return -1; } - memory = dos_getmemory(sizeof(struct cd_request -) + sizeof(union readInfo_u)); - if (memory == NULL) - { - Con_DPrintf("CDAudio_Init: Unable to allocate low memory.\n"); + memory = + + dos_getmemory (sizeof (struct cd_request) + sizeof (union readInfo_u)); + if (memory == NULL) { + Con_DPrintf ("CDAudio_Init: Unable to allocate low memory.\n"); return -1; } - cdRequest = (struct cd_request *)memory; - cdRequestSegment = ptr2real(cdRequest) >> 4; - cdRequestOffset = ptr2real(cdRequest) & 0xf; + cdRequest = (struct cd_request *) memory; + cdRequestSegment = ptr2real (cdRequest) >> 4; + cdRequestOffset = ptr2real (cdRequest) & 0xf; - readInfo = (union readInfo_u *)(memory + sizeof(struct cd_request)); - readInfoSegment = ptr2real(readInfo) >> 4; - readInfoOffset = ptr2real(readInfo) & 0xf; + readInfo = (union readInfo_u *) (memory + sizeof (struct cd_request)); + + readInfoSegment = ptr2real (readInfo) >> 4; + readInfoOffset = ptr2real (readInfo) & 0xf; for (n = 0; n < 256; n++) remap[n] = n; initialized = true; CDAudio_SetVolume (255); - if (CDAudio_GetAudioDiskInfo()) - { - Con_Printf("CDAudio_Init: No CD in player.\n"); + if (CDAudio_GetAudioDiskInfo ()) { + Con_Printf ("CDAudio_Init: No CD in player.\n"); enabled = false; } Cmd_AddCommand ("cd", CD_f); - Con_Printf("CD Audio Initialized\n"); + Con_Printf ("CD Audio Initialized\n"); return 0; } -void CDAudio_Shutdown(void) +void +CDAudio_Shutdown (void) { if (!initialized) return; - CDAudio_Stop(); + CDAudio_Stop (); } diff --git a/source/cd_linux.c b/source/cd_linux.c index a51e558..6b2d573 100644 --- a/source/cd_linux.c +++ b/source/cd_linux.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -49,53 +49,54 @@ #include "sound.h" static qboolean cdValid = false; -static qboolean playing = false; -static qboolean wasPlaying = false; -static qboolean initialized = false; -static qboolean enabled = true; +static qboolean playing = false; +static qboolean wasPlaying = false; +static qboolean initialized = false; +static qboolean enabled = true; static qboolean playLooping = false; -static float cdvolume; -static byte remap[100]; -static byte playTrack; -static byte maxTrack; +static float cdvolume; +static byte remap[100]; +static byte playTrack; +static byte maxTrack; -static int cdfile = -1; +static int cdfile = -1; static char cd_dev[64] = "/dev/cdrom"; -static void CDAudio_Eject(void) +static void +CDAudio_Eject (void) { if (cdfile == -1 || !enabled) - return; // no cd init'd + return; // no cd init'd - if (ioctl (cdfile, CDROMEJECT) == -1 ) + if (ioctl (cdfile, CDROMEJECT) == -1) Con_DPrintf ("CDAudio: ioctl cdromeject failed\n"); } -static void CDAudio_CloseDoor(void) +static void +CDAudio_CloseDoor (void) { if (cdfile == -1 || !enabled) - return; // no cd init'd + return; // no cd init'd - if ( ioctl(cdfile, CDROMCLOSETRAY) == -1 ) - Con_DPrintf("CDAudio: ioctl cdromclosetray failed\n"); + if (ioctl (cdfile, CDROMCLOSETRAY) == -1) + Con_DPrintf ("CDAudio: ioctl cdromclosetray failed\n"); } -static int CDAudio_GetAudioDiskInfo(void) +static int +CDAudio_GetAudioDiskInfo (void) { struct cdrom_tochdr tochdr; cdValid = false; - if ( ioctl(cdfile, CDROMREADTOCHDR, &tochdr) == -1 ) - { - Con_DPrintf("CDAudio: ioctl cdromreadtochdr failed\n"); - return -1; - } + if (ioctl (cdfile, CDROMREADTOCHDR, &tochdr) == -1) { + Con_DPrintf ("CDAudio: ioctl cdromreadtochdr failed\n"); + return -1; + } - if (tochdr.cdth_trk0 < 1) - { - Con_DPrintf("CDAudio: no music tracks\n"); + if (tochdr.cdth_trk0 < 1) { + Con_DPrintf ("CDAudio: no music tracks\n"); return -1; } @@ -106,7 +107,8 @@ static int CDAudio_GetAudioDiskInfo(void) } -void CDAudio_Play(byte track, qboolean looping) +void +CDAudio_Play (byte track, qboolean looping) { struct cdrom_tocentry entry0; struct cdrom_tocentry entry1; @@ -114,27 +116,24 @@ void CDAudio_Play(byte track, qboolean looping) if (cdfile == -1 || !enabled) return; - - if (!cdValid) - { - CDAudio_GetAudioDiskInfo(); + + if (!cdValid) { + CDAudio_GetAudioDiskInfo (); if (!cdValid) return; } track = remap[track]; - if (track < 1 || track > maxTrack) - { - Con_DPrintf("CDAudio: Bad track number %u.\n", track); + if (track < 1 || track > maxTrack) { + Con_DPrintf ("CDAudio: Bad track number %u.\n", track); return; } - // don't try to play a non-audio track entry0.cdte_track = track; entry0.cdte_format = CDROM_MSF; - if ( ioctl(cdfile, CDROMREADTOCENTRY, &entry0) == -1 ) { - Con_DPrintf("CDAudio: ioctl cdromreadtocentry failed\n"); + if (ioctl (cdfile, CDROMREADTOCENTRY, &entry0) == -1) { + Con_DPrintf ("CDAudio: ioctl cdromreadtocentry failed\n"); return; } entry1.cdte_track = track + 1; @@ -142,21 +141,19 @@ void CDAudio_Play(byte track, qboolean looping) if (entry1.cdte_track > maxTrack) { entry1.cdte_track = CDROM_LEADOUT; } - if ( ioctl(cdfile, CDROMREADTOCENTRY, &entry1) == -1 ) { - Con_DPrintf("CDAudio: ioctl cdromreadtocentry failed\n"); + if (ioctl (cdfile, CDROMREADTOCENTRY, &entry1) == -1) { + Con_DPrintf ("CDAudio: ioctl cdromreadtocentry failed\n"); return; } - if (entry0.cdte_ctrl == CDROM_DATA_TRACK) - { - Con_Printf("track %i is not audio\n", track); + if (entry0.cdte_ctrl == CDROM_DATA_TRACK) { + Con_Printf ("track %i is not audio\n", track); return; } - if (playing) - { + if (playing) { if (playTrack == track) return; - CDAudio_Stop(); + CDAudio_Stop (); } msf.cdmsf_min0 = entry0.cdte_addr.msf.minute; @@ -168,21 +165,18 @@ void CDAudio_Play(byte track, qboolean looping) msf.cdmsf_frame1 = entry1.cdte_addr.msf.frame; Con_DPrintf ("%2d:%02d:%02d %2d:%02d:%02d\n", - msf.cdmsf_min0, - msf.cdmsf_sec0, - msf.cdmsf_frame0, - msf.cdmsf_min1, - msf.cdmsf_sec1, - msf.cdmsf_frame1); + msf.cdmsf_min0, + msf.cdmsf_sec0, + msf.cdmsf_frame0, + msf.cdmsf_min1, msf.cdmsf_sec1, msf.cdmsf_frame1); - if ( ioctl(cdfile, CDROMPLAYMSF, &msf) == -1 ) - { - Con_DPrintf("CDAudio: ioctl cdromplaytrkind failed (%s)\n", strerror(errno)); + if (ioctl (cdfile, CDROMPLAYMSF, &msf) == -1) { + Con_DPrintf ("CDAudio: ioctl cdromplaytrkind failed (%s)\n", + strerror (errno)); return; - } - - //if ( ioctl(cdfile, CDROMRESUME) == -1 ) - // Con_DPrintf("CDAudio: ioctl cdromresume failed\n"); + } + // if ( ioctl(cdfile, CDROMRESUME) == -1 ) + // Con_DPrintf("CDAudio: ioctl cdromresume failed\n"); playLooping = looping; playTrack = track; @@ -193,22 +187,24 @@ void CDAudio_Play(byte track, qboolean looping) } -void CDAudio_Stop(void) +void +CDAudio_Stop (void) { if (cdfile == -1 || !enabled) return; - + if (!playing) return; - if ( ioctl(cdfile, CDROMSTOP) == -1 ) - Con_DPrintf("CDAudio: ioctl cdromstop failed (%d)\n", errno); + if (ioctl (cdfile, CDROMSTOP) == -1) + Con_DPrintf ("CDAudio: ioctl cdromstop failed (%d)\n", errno); wasPlaying = false; playing = false; } -void CDAudio_Pause(void) +void +CDAudio_Pause (void) { if (cdfile == -1 || !enabled) return; @@ -216,149 +212,139 @@ void CDAudio_Pause(void) if (!playing) return; - if ( ioctl(cdfile, CDROMPAUSE) == -1 ) - Con_DPrintf("CDAudio: ioctl cdrompause failed\n"); + if (ioctl (cdfile, CDROMPAUSE) == -1) + Con_DPrintf ("CDAudio: ioctl cdrompause failed\n"); wasPlaying = playing; playing = false; } -void CDAudio_Resume(void) +void +CDAudio_Resume (void) { if (cdfile == -1 || !enabled) return; - + if (!cdValid) return; if (!wasPlaying) return; - - if ( ioctl(cdfile, CDROMRESUME) == -1 ) - Con_DPrintf("CDAudio: ioctl cdromresume failed\n"); + + if (ioctl (cdfile, CDROMRESUME) == -1) + Con_DPrintf ("CDAudio: ioctl cdromresume failed\n"); playing = true; } -static void CD_f (void) +static void +CD_f (void) { - char *command; - int ret; - int n; + char *command; + int ret; + int n; - if (Cmd_Argc() < 2) + if (Cmd_Argc () < 2) return; command = Cmd_Argv (1); - if (strcasecmp(command, "on") == 0) - { + if (strcasecmp (command, "on") == 0) { enabled = true; return; } - if (strcasecmp(command, "off") == 0) - { + if (strcasecmp (command, "off") == 0) { if (playing) - CDAudio_Stop(); + CDAudio_Stop (); enabled = false; return; } - if (strcasecmp(command, "reset") == 0) - { + if (strcasecmp (command, "reset") == 0) { enabled = true; if (playing) - CDAudio_Stop(); + CDAudio_Stop (); for (n = 0; n < 100; n++) remap[n] = n; - CDAudio_GetAudioDiskInfo(); + CDAudio_GetAudioDiskInfo (); return; } - if (strcasecmp(command, "remap") == 0) - { - ret = Cmd_Argc() - 2; - if (ret <= 0) - { + if (strcasecmp (command, "remap") == 0) { + ret = Cmd_Argc () - 2; + if (ret <= 0) { for (n = 1; n < 100; n++) if (remap[n] != n) - Con_Printf(" %u -> %u\n", n, remap[n]); + Con_Printf (" %u -> %u\n", n, remap[n]); return; } for (n = 1; n <= ret; n++) - remap[n] = atoi(Cmd_Argv (n+1)); + remap[n] = atoi (Cmd_Argv (n + 1)); return; } - if (strcasecmp(command, "close") == 0) - { - CDAudio_CloseDoor(); + if (strcasecmp (command, "close") == 0) { + CDAudio_CloseDoor (); return; } - if (!cdValid) - { - CDAudio_GetAudioDiskInfo(); - if (!cdValid) - { - Con_Printf("No CD in player.\n"); + if (!cdValid) { + CDAudio_GetAudioDiskInfo (); + if (!cdValid) { + Con_Printf ("No CD in player.\n"); return; } } - if (strcasecmp(command, "play") == 0) - { - CDAudio_Play((byte)atoi(Cmd_Argv (2)), false); + if (strcasecmp (command, "play") == 0) { + CDAudio_Play ((byte) atoi (Cmd_Argv (2)), false); return; } - if (strcasecmp(command, "loop") == 0) - { - CDAudio_Play((byte)atoi(Cmd_Argv (2)), true); + if (strcasecmp (command, "loop") == 0) { + CDAudio_Play ((byte) atoi (Cmd_Argv (2)), true); return; } - if (strcasecmp(command, "stop") == 0) - { - CDAudio_Stop(); + if (strcasecmp (command, "stop") == 0) { + CDAudio_Stop (); return; } - if (strcasecmp(command, "pause") == 0) - { - CDAudio_Pause(); + if (strcasecmp (command, "pause") == 0) { + CDAudio_Pause (); return; } - if (strcasecmp(command, "resume") == 0) - { - CDAudio_Resume(); + if (strcasecmp (command, "resume") == 0) { + CDAudio_Resume (); return; } - if (strcasecmp(command, "eject") == 0) - { + if (strcasecmp (command, "eject") == 0) { if (playing) - CDAudio_Stop(); - CDAudio_Eject(); + CDAudio_Stop (); + CDAudio_Eject (); cdValid = false; return; } - if (strcasecmp(command, "info") == 0) - { - Con_Printf("%u tracks\n", maxTrack); + if (strcasecmp (command, "info") == 0) { + Con_Printf ("%u tracks\n", maxTrack); if (playing) - Con_Printf("Currently %s track %u\n", playLooping ? "looping" : "playing", playTrack); + Con_Printf ("Currently %s track %u\n", + playLooping ? "looping" : "playing", playTrack); else if (wasPlaying) - Con_Printf("Paused %s track %u\n", playLooping ? "looping" : "playing", playTrack); - Con_Printf("Volume is %g\n", cdvolume); + Con_Printf ("Paused %s track %u\n", + playLooping ? "looping" : "playing", playTrack); + Con_Printf ("Volume is %g\n", cdvolume); return; } } -void CDAudio_Update(void) +void +CDAudio_Update (void) { struct cdrom_subchnl subchnl; static time_t lastchk; @@ -378,11 +364,11 @@ void CDAudio_Update(void) } } - if (playing && lastchk < time(NULL)) { - lastchk = time(NULL) + 2; //two seconds between chks + if (playing && lastchk < time (NULL)) { + lastchk = time (NULL) + 2; // two seconds between chks subchnl.cdsc_format = CDROM_MSF; - if (ioctl(cdfile, CDROMSUBCHNL, &subchnl) == -1 ) { - Con_DPrintf("CDAudio: ioctl cdromsubchnl failed\n"); + if (ioctl (cdfile, CDROMSUBCHNL, &subchnl) == -1) { + Con_DPrintf ("CDAudio: ioctl cdromsubchnl failed\n"); playing = false; return; } @@ -390,30 +376,32 @@ void CDAudio_Update(void) subchnl.cdsc_audiostatus != CDROM_AUDIO_PAUSED) { playing = false; if (playLooping) - CDAudio_Play(playTrack, true); + CDAudio_Play (playTrack, true); } } } -int CDAudio_Init(void) +int +CDAudio_Init (void) { - int i; + int i; #if 0 if (cls.state == ca_dedicated) return -1; #endif - if (COM_CheckParm("-nocdaudio")) + if (COM_CheckParm ("-nocdaudio")) return -1; - if ((i = COM_CheckParm("-cddev")) != 0 && i < com_argc - 1) { - strncpy(cd_dev, com_argv[i + 1], sizeof(cd_dev)); - cd_dev[sizeof(cd_dev) - 1] = 0; + if ((i = COM_CheckParm ("-cddev")) != 0 && i < com_argc - 1) { + strncpy (cd_dev, com_argv[i + 1], sizeof (cd_dev)); + cd_dev[sizeof (cd_dev) - 1] = 0; } - if ((cdfile = open(cd_dev, O_RDONLY | O_NONBLOCK)) == -1) { - Con_Printf("CDAudio_Init: open of \"%s\" failed (%i)\n", cd_dev, errno); + if ((cdfile = open (cd_dev, O_RDONLY | O_NONBLOCK)) == -1) { + Con_Printf ("CDAudio_Init: open of \"%s\" failed (%i)\n", cd_dev, + errno); cdfile = -1; return -1; } @@ -423,25 +411,25 @@ int CDAudio_Init(void) initialized = true; enabled = true; - if (CDAudio_GetAudioDiskInfo()) - { - Con_Printf("CDAudio_Init: No CD in player.\n"); + if (CDAudio_GetAudioDiskInfo ()) { + Con_Printf ("CDAudio_Init: No CD in player.\n"); cdValid = false; } Cmd_AddCommand ("cd", CD_f); - Con_Printf("CD Audio Initialized\n"); + Con_Printf ("CD Audio Initialized\n"); return 0; } -void CDAudio_Shutdown(void) +void +CDAudio_Shutdown (void) { if (!initialized) return; - CDAudio_Stop(); - close(cdfile); + CDAudio_Stop (); + close (cdfile); cdfile = -1; } diff --git a/source/cd_null.c b/source/cd_null.c index 36be29d..c8d26a3 100644 --- a/source/cd_null.c +++ b/source/cd_null.c @@ -27,40 +27,47 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif -void CDAudio_Play(byte track, qboolean looping) +void +CDAudio_Play (byte track, qboolean looping) { } -void CDAudio_Stop(void) +void +CDAudio_Stop (void) { } -void CDAudio_Pause(void) +void +CDAudio_Pause (void) { } -void CDAudio_Resume(void) +void +CDAudio_Resume (void) { } -void CDAudio_Update(void) +void +CDAudio_Update (void) { } -int CDAudio_Init(void) +int +CDAudio_Init (void) { return 0; } -void CDAudio_Shutdown(void) +void +CDAudio_Shutdown (void) { } diff --git a/source/cd_sdl.c b/source/cd_sdl.c index 236cfc0..a9a45e6 100644 --- a/source/cd_sdl.c +++ b/source/cd_sdl.c @@ -38,7 +38,7 @@ #include "cmd.h" #include "host.h" -extern cvar_t *bgmvolume; +extern cvar_t *bgmvolume; static qboolean cdValid = false; static qboolean initialized = false; @@ -47,119 +47,135 @@ static qboolean playLooping = false; static SDL_CD *cd_id; static float cdvolume = 1.0; -static void CD_f(); +static void CD_f (); -static void CDAudio_Eject() +static void +CDAudio_Eject () { - if(!cd_id || !enabled) return; + if (!cd_id || !enabled) + return; - if(SDL_CDEject(cd_id)) - Con_DPrintf("Unable to eject CD-ROM tray.\n"); + if (SDL_CDEject (cd_id)) + Con_DPrintf ("Unable to eject CD-ROM tray.\n"); } -void CDAudio_Play(byte track, qboolean looping) +void +CDAudio_Play (byte track, qboolean looping) { - /* Initialize cd_stat to avoid warning */ - /* XXX - Does this default value make sense? */ - CDstatus cd_stat = CD_ERROR; - if(!cd_id || !enabled) return; + /* Initialize cd_stat to avoid warning */ + /* XXX - Does this default value make sense? */ + CDstatus cd_stat = CD_ERROR; - if(!cdValid) - { - if(!CD_INDRIVE(cd_stat=SDL_CDStatus(cd_id)) ||(!cd_id->numtracks)) return; + if (!cd_id || !enabled) + return; + + if (!cdValid) { + if (!CD_INDRIVE (cd_stat = SDL_CDStatus (cd_id)) || (!cd_id->numtracks)) + return; cdValid = true; } - if((track < 1) || (track >= cd_id->numtracks)) - { - Con_DPrintf("CDAudio: Bad track number: %d\n",track); + if ((track < 1) || (track >= cd_id->numtracks)) { + Con_DPrintf ("CDAudio: Bad track number: %d\n", track); return; } - track--; /* Convert track from person to SDL value */ - if(cd_stat == CD_PLAYING) - { - if(cd_id->cur_track == track) return; - CDAudio_Stop(); + track--; /* Convert track from person to SDL + value */ + if (cd_stat == CD_PLAYING) { + if (cd_id->cur_track == track) + return; + CDAudio_Stop (); } - if(SDL_CDPlay(cd_id,cd_id->track[track].offset, - cd_id->track[track].length)) - { - Con_DPrintf("CDAudio_Play: Unable to play track: %d\n",track+1); + if (SDL_CDPlay (cd_id, cd_id->track[track].offset, + cd_id->track[track].length)) { + Con_DPrintf ("CDAudio_Play: Unable to play track: %d\n", track + 1); return; } playLooping = looping; } -void CDAudio_Stop() +void +CDAudio_Stop () { - int cdstate; - if(!cd_id || !enabled) return; - cdstate = SDL_CDStatus(cd_id); - if((cdstate != CD_PLAYING) && (cdstate != CD_PAUSED)) return; + int cdstate; - if(SDL_CDStop(cd_id)) - Con_DPrintf("CDAudio_Stop: Failed to stop track.\n"); + if (!cd_id || !enabled) + return; + cdstate = SDL_CDStatus (cd_id); + if ((cdstate != CD_PLAYING) && (cdstate != CD_PAUSED)) + return; + + if (SDL_CDStop (cd_id)) + Con_DPrintf ("CDAudio_Stop: Failed to stop track.\n"); } -void CDAudio_Pause() +void +CDAudio_Pause () { - if(!cd_id || !enabled) return; - if(SDL_CDStatus(cd_id) != CD_PLAYING) return; + if (!cd_id || !enabled) + return; + if (SDL_CDStatus (cd_id) != CD_PLAYING) + return; - if(SDL_CDPause(cd_id)) - Con_DPrintf("CDAudio_Pause: Failed to pause track.\n"); + if (SDL_CDPause (cd_id)) + Con_DPrintf ("CDAudio_Pause: Failed to pause track.\n"); } -void CDAudio_Resume() +void +CDAudio_Resume () { - if(!cd_id || !enabled) return; - if(SDL_CDStatus(cd_id) != CD_PAUSED) return; + if (!cd_id || !enabled) + return; + if (SDL_CDStatus (cd_id) != CD_PAUSED) + return; - if(SDL_CDResume(cd_id)) - Con_DPrintf("CDAudio_Resume: Failed tp resume track.\n"); + if (SDL_CDResume (cd_id)) + Con_DPrintf ("CDAudio_Resume: Failed tp resume track.\n"); } -void CDAudio_Update() +void +CDAudio_Update () { - if(!cd_id || !enabled) return; - if(bgmvolume->value != cdvolume) { - if(cdvolume) { + if (!cd_id || !enabled) + return; + if (bgmvolume->value != cdvolume) { + if (cdvolume) { Cvar_SetValue (bgmvolume, 0.0); - CDAudio_Pause(); + CDAudio_Pause (); } else { Cvar_SetValue (bgmvolume, 1.0); - CDAudio_Resume(); + CDAudio_Resume (); } cdvolume = bgmvolume->value; return; } - if(playLooping && (SDL_CDStatus(cd_id) != CD_PLAYING) - && (SDL_CDStatus(cd_id) != CD_PAUSED)) - CDAudio_Play(cd_id->cur_track+1,true); + if (playLooping && (SDL_CDStatus (cd_id) != CD_PLAYING) + && (SDL_CDStatus (cd_id) != CD_PAUSED)) + CDAudio_Play (cd_id->cur_track + 1, true); } -int CDAudio_Init() +int +CDAudio_Init () { #ifdef UQUAKE if (cls.state == ca_dedicated) return -1; #endif - if (COM_CheckParm("-nocdaudio")) + if (COM_CheckParm ("-nocdaudio")) return -1; - if ( SDL_Init(SDL_INIT_CDROM) < 0 ) { - Con_Printf("Couldn't initialize SDL CD-AUDIO: %s\n",SDL_GetError()); - return -1; - } - cd_id = SDL_CDOpen(0); - if(!cd_id) - { - Con_Printf("CDAudio_Init: Unable to open default CD-ROM drive: %s\n", - SDL_GetError()); + if (SDL_Init (SDL_INIT_CDROM) < 0) { + Con_Printf ("Couldn't initialize SDL CD-AUDIO: %s\n", SDL_GetError ()); + return -1; + } + cd_id = SDL_CDOpen (0); + if (!cd_id) { + Con_Printf ("CDAudio_Init: Unable to open default CD-ROM drive: %s\n", + SDL_GetError ()); return -1; } @@ -167,97 +183,91 @@ int CDAudio_Init() enabled = true; cdValid = true; - if(!CD_INDRIVE(SDL_CDStatus(cd_id))) - { - Con_Printf("CDAudio_Init: No CD in drive.\n"); + if (!CD_INDRIVE (SDL_CDStatus (cd_id))) { + Con_Printf ("CDAudio_Init: No CD in drive.\n"); cdValid = false; } - if(!cd_id->numtracks) - { - Con_Printf("CDAudio_Init: CD contains no audio tracks.\n"); + if (!cd_id->numtracks) { + Con_Printf ("CDAudio_Init: CD contains no audio tracks.\n"); cdValid = false; } - Cmd_AddCommand("cd",CD_f); - Con_Printf("CD Audio Initialized.\n"); + Cmd_AddCommand ("cd", CD_f); + Con_Printf ("CD Audio Initialized.\n"); return 0; } -void CDAudio_Shutdown() +void +CDAudio_Shutdown () { - if(!cd_id) return; - CDAudio_Stop(); - SDL_CDClose(cd_id); + if (!cd_id) + return; + CDAudio_Stop (); + SDL_CDClose (cd_id); cd_id = NULL; } #define CD_f_DEFINED -static void CD_f() +static void +CD_f () { - char *command; - int cdstate; - if(Cmd_Argc() < 2) return; + char *command; + int cdstate; - command = Cmd_Argv(1); - if(!strcasecmp(command,"on")) - { + if (Cmd_Argc () < 2) + return; + + command = Cmd_Argv (1); + if (!strcasecmp (command, "on")) { enabled = true; } - if(!strcasecmp(command,"off")) - { - if(!cd_id) return; - cdstate = SDL_CDStatus(cd_id); - if((cdstate == CD_PLAYING) || (cdstate == CD_PAUSED)) - CDAudio_Stop(); + if (!strcasecmp (command, "off")) { + if (!cd_id) + return; + cdstate = SDL_CDStatus (cd_id); + if ((cdstate == CD_PLAYING) || (cdstate == CD_PAUSED)) + CDAudio_Stop (); enabled = false; return; } - if(!strcasecmp(command,"play")) - { - CDAudio_Play(atoi(Cmd_Argv(2)),false); + if (!strcasecmp (command, "play")) { + CDAudio_Play (atoi (Cmd_Argv (2)), false); return; } - if(!strcasecmp(command,"loop")) - { - CDAudio_Play(atoi(Cmd_Argv(2)),true); + if (!strcasecmp (command, "loop")) { + CDAudio_Play (atoi (Cmd_Argv (2)), true); return; } - if(!strcasecmp(command,"stop")) - { - CDAudio_Stop(); + if (!strcasecmp (command, "stop")) { + CDAudio_Stop (); return; } - if(!strcasecmp(command,"pause")) - { - CDAudio_Pause(); + if (!strcasecmp (command, "pause")) { + CDAudio_Pause (); return; } - if(!strcasecmp(command,"resume")) - { - CDAudio_Resume(); + if (!strcasecmp (command, "resume")) { + CDAudio_Resume (); return; } - if(!strcasecmp(command,"eject")) - { - CDAudio_Eject(); + if (!strcasecmp (command, "eject")) { + CDAudio_Eject (); return; } - if(!strcasecmp(command,"info")) - { - if(!cd_id) return; - cdstate = SDL_CDStatus(cd_id); - Con_Printf("%d tracks\n",cd_id->numtracks); - if(cdstate == CD_PLAYING) - Con_Printf("Currently %s track %d\n", - playLooping ? "looping" : "playing", - cd_id->cur_track+1); - else - if(cdstate == CD_PAUSED) - Con_Printf("Paused %s track %d\n", - playLooping ? "looping" : "playing", - cd_id->cur_track+1); + if (!strcasecmp (command, "info")) { + if (!cd_id) + return; + cdstate = SDL_CDStatus (cd_id); + Con_Printf ("%d tracks\n", cd_id->numtracks); + if (cdstate == CD_PLAYING) + Con_Printf ("Currently %s track %d\n", + playLooping ? "looping" : "playing", + cd_id->cur_track + 1); + else if (cdstate == CD_PAUSED) + Con_Printf ("Paused %s track %d\n", + playLooping ? "looping" : "playing", + cd_id->cur_track + 1); return; } } - diff --git a/source/cd_win.c b/source/cd_win.c index 4db14b8..9d8142d 100644 --- a/source/cd_win.c +++ b/source/cd_win.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include "qargs.h" @@ -35,77 +35,81 @@ #include "cdaudio.h" #include "cmd.h" #include "host.h" -extern HWND mainwindow; -extern cvar_t *bgmvolume; +extern HWND mainwindow; +extern cvar_t *bgmvolume; static qboolean cdValid = false; -static qboolean playing = false; -static qboolean wasPlaying = false; -static qboolean initialized = false; -static qboolean enabled = false; +static qboolean playing = false; +static qboolean wasPlaying = false; +static qboolean initialized = false; +static qboolean enabled = false; static qboolean playLooping = false; -static float cdvolume; -static byte remap[100]; -static byte playTrack; -static byte maxTrack; +static float cdvolume; +static byte remap[100]; +static byte playTrack; +static byte maxTrack; -UINT wDeviceID; +UINT wDeviceID; -static void CDAudio_Eject(void) +static void +CDAudio_Eject (void) { - DWORD dwReturn; + DWORD dwReturn; - dwReturn = mciSendCommand(wDeviceID, MCI_SET, MCI_SET_DOOR_OPEN, - (DWORD)NULL); - if (dwReturn) { - Con_DPrintf("MCI_SET_DOOR_OPEN failed (%i)\n", dwReturn); + dwReturn = mciSendCommand (wDeviceID, MCI_SET, MCI_SET_DOOR_OPEN, + (DWORD) NULL); + if (dwReturn) { + Con_DPrintf ("MCI_SET_DOOR_OPEN failed (%i)\n", dwReturn); } } -static void CDAudio_CloseDoor(void) +static void +CDAudio_CloseDoor (void) { - DWORD dwReturn; + DWORD dwReturn; - dwReturn = mciSendCommand(wDeviceID, MCI_SET, MCI_SET_DOOR_CLOSED, (DWORD)NULL); - if (dwReturn) { - Con_DPrintf("MCI_SET_DOOR_CLOSED failed (%i)\n", dwReturn); + dwReturn = + mciSendCommand (wDeviceID, MCI_SET, MCI_SET_DOOR_CLOSED, (DWORD) NULL); + if (dwReturn) { + Con_DPrintf ("MCI_SET_DOOR_CLOSED failed (%i)\n", dwReturn); } } -static int CDAudio_GetAudioDiskInfo(void) +static int +CDAudio_GetAudioDiskInfo (void) { - DWORD dwReturn; - MCI_STATUS_PARMS mciStatusParms; + DWORD dwReturn; + MCI_STATUS_PARMS mciStatusParms; cdValid = false; mciStatusParms.dwItem = MCI_STATUS_READY; - dwReturn = mciSendCommand(wDeviceID, MCI_STATUS, MCI_STATUS_ITEM | MCI_WAIT, (DWORD) (LPVOID) &mciStatusParms); - if (dwReturn) - { - Con_DPrintf("CDAudio: drive ready test - get status failed\n"); + dwReturn = + mciSendCommand (wDeviceID, MCI_STATUS, MCI_STATUS_ITEM | MCI_WAIT, + (DWORD) (LPVOID) & mciStatusParms); + if (dwReturn) { + Con_DPrintf ("CDAudio: drive ready test - get status failed\n"); return -1; } - if (!mciStatusParms.dwReturn) - { - Con_DPrintf("CDAudio: drive not ready\n"); + if (!mciStatusParms.dwReturn) { + Con_DPrintf ("CDAudio: drive not ready\n"); return -1; } mciStatusParms.dwItem = MCI_STATUS_NUMBER_OF_TRACKS; - dwReturn = mciSendCommand(wDeviceID, MCI_STATUS, MCI_STATUS_ITEM | MCI_WAIT, (DWORD) (LPVOID) &mciStatusParms); - if (dwReturn) - { - Con_DPrintf("CDAudio: get tracks - status failed\n"); + dwReturn = + mciSendCommand (wDeviceID, MCI_STATUS, MCI_STATUS_ITEM | MCI_WAIT, + (DWORD) (LPVOID) & mciStatusParms); + if (dwReturn) { + Con_DPrintf ("CDAudio: get tracks - status failed\n"); return -1; } - if (mciStatusParms.dwReturn < 1) - { - Con_DPrintf("CDAudio: no music tracks\n"); + if (mciStatusParms.dwReturn < 1) { + Con_DPrintf ("CDAudio: no music tracks\n"); return -1; } @@ -116,69 +120,69 @@ static int CDAudio_GetAudioDiskInfo(void) } -void CDAudio_Play(byte track, qboolean looping) +void +CDAudio_Play (byte track, qboolean looping) { - DWORD dwReturn; - MCI_PLAY_PARMS mciPlayParms; - MCI_STATUS_PARMS mciStatusParms; + DWORD dwReturn; + MCI_PLAY_PARMS mciPlayParms; + MCI_STATUS_PARMS mciStatusParms; if (!enabled) return; - - if (!cdValid) - { - CDAudio_GetAudioDiskInfo(); + + if (!cdValid) { + CDAudio_GetAudioDiskInfo (); if (!cdValid) return; } track = remap[track]; - if (track < 1 || track > maxTrack) - { - Con_DPrintf("CDAudio: Bad track number %u.\n", track); + if (track < 1 || track > maxTrack) { + Con_DPrintf ("CDAudio: Bad track number %u.\n", track); return; } - // don't try to play a non-audio track mciStatusParms.dwItem = MCI_CDA_STATUS_TYPE_TRACK; mciStatusParms.dwTrack = track; - dwReturn = mciSendCommand(wDeviceID, MCI_STATUS, MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT, (DWORD) (LPVOID) &mciStatusParms); - if (dwReturn) - { - Con_DPrintf("MCI_STATUS failed (%i)\n", dwReturn); + dwReturn = + mciSendCommand (wDeviceID, MCI_STATUS, + MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT, + (DWORD) (LPVOID) & mciStatusParms); + if (dwReturn) { + Con_DPrintf ("MCI_STATUS failed (%i)\n", dwReturn); return; } - if (mciStatusParms.dwReturn != MCI_CDA_TRACK_AUDIO) - { - Con_Printf("CDAudio: track %i is not audio\n", track); + if (mciStatusParms.dwReturn != MCI_CDA_TRACK_AUDIO) { + Con_Printf ("CDAudio: track %i is not audio\n", track); return; } - // get the length of the track to be played mciStatusParms.dwItem = MCI_STATUS_LENGTH; mciStatusParms.dwTrack = track; - dwReturn = mciSendCommand(wDeviceID, MCI_STATUS, MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT, (DWORD) (LPVOID) &mciStatusParms); - if (dwReturn) - { - Con_DPrintf("MCI_STATUS failed (%i)\n", dwReturn); + dwReturn = + mciSendCommand (wDeviceID, MCI_STATUS, + MCI_STATUS_ITEM | MCI_TRACK | MCI_WAIT, + (DWORD) (LPVOID) & mciStatusParms); + if (dwReturn) { + Con_DPrintf ("MCI_STATUS failed (%i)\n", dwReturn); return; } - if (playing) - { + if (playing) { if (playTrack == track) return; - CDAudio_Stop(); + CDAudio_Stop (); } - mciPlayParms.dwFrom = MCI_MAKE_TMSF(track, 0, 0, 0); + mciPlayParms.dwFrom = MCI_MAKE_TMSF (track, 0, 0, 0); mciPlayParms.dwTo = (mciStatusParms.dwReturn << 8) | track; - mciPlayParms.dwCallback = (DWORD)mainwindow; - dwReturn = mciSendCommand(wDeviceID, MCI_PLAY, MCI_NOTIFY | MCI_FROM | MCI_TO, (DWORD)(LPVOID) &mciPlayParms); - if (dwReturn) - { - Con_DPrintf("CDAudio: MCI_PLAY failed (%i)\n", dwReturn); + mciPlayParms.dwCallback = (DWORD) mainwindow; + dwReturn = + mciSendCommand (wDeviceID, MCI_PLAY, MCI_NOTIFY | MCI_FROM | MCI_TO, + (DWORD) (LPVOID) & mciPlayParms); + if (dwReturn) { + Con_DPrintf ("CDAudio: MCI_PLAY failed (%i)\n", dwReturn); return; } @@ -191,19 +195,20 @@ void CDAudio_Play(byte track, qboolean looping) } -void CDAudio_Stop(void) +void +CDAudio_Stop (void) { - DWORD dwReturn; + DWORD dwReturn; if (!enabled) return; - + if (!playing) return; - dwReturn = mciSendCommand(wDeviceID, MCI_STOP, 0, (DWORD)NULL); - if (dwReturn) { - Con_DPrintf("MCI_STOP failed (%i)", dwReturn); + dwReturn = mciSendCommand (wDeviceID, MCI_STOP, 0, (DWORD) NULL); + if (dwReturn) { + Con_DPrintf ("MCI_STOP failed (%i)", dwReturn); } wasPlaying = false; @@ -211,10 +216,11 @@ void CDAudio_Stop(void) } -void CDAudio_Pause(void) +void +CDAudio_Pause (void) { - DWORD dwReturn; - MCI_GENERIC_PARMS mciGenericParms; + DWORD dwReturn; + MCI_GENERIC_PARMS mciGenericParms; if (!enabled) return; @@ -222,10 +228,12 @@ void CDAudio_Pause(void) if (!playing) return; - mciGenericParms.dwCallback = (DWORD)mainwindow; - dwReturn = mciSendCommand(wDeviceID, MCI_PAUSE, 0, (DWORD)(LPVOID) &mciGenericParms); - if (dwReturn) { - Con_DPrintf("MCI_PAUSE failed (%i)", dwReturn); + mciGenericParms.dwCallback = (DWORD) mainwindow; + dwReturn = + mciSendCommand (wDeviceID, MCI_PAUSE, 0, + (DWORD) (LPVOID) & mciGenericParms); + if (dwReturn) { + Con_DPrintf ("MCI_PAUSE failed (%i)", dwReturn); } wasPlaying = playing; @@ -233,166 +241,156 @@ void CDAudio_Pause(void) } -void CDAudio_Resume(void) +void +CDAudio_Resume (void) { - DWORD dwReturn; - MCI_PLAY_PARMS mciPlayParms; + DWORD dwReturn; + MCI_PLAY_PARMS mciPlayParms; if (!enabled) return; - + if (!cdValid) return; if (!wasPlaying) return; - - mciPlayParms.dwFrom = MCI_MAKE_TMSF(playTrack, 0, 0, 0); - mciPlayParms.dwTo = MCI_MAKE_TMSF(playTrack + 1, 0, 0, 0); - mciPlayParms.dwCallback = (DWORD)mainwindow; - dwReturn = mciSendCommand(wDeviceID, MCI_PLAY, MCI_TO | MCI_NOTIFY, (DWORD)(LPVOID) &mciPlayParms); - if (dwReturn) - { - Con_DPrintf("CDAudio: MCI_PLAY failed (%i)\n", dwReturn); + + mciPlayParms.dwFrom = MCI_MAKE_TMSF (playTrack, 0, 0, 0); + mciPlayParms.dwTo = MCI_MAKE_TMSF (playTrack + 1, 0, 0, 0); + mciPlayParms.dwCallback = (DWORD) mainwindow; + dwReturn = + mciSendCommand (wDeviceID, MCI_PLAY, MCI_TO | MCI_NOTIFY, + (DWORD) (LPVOID) & mciPlayParms); + if (dwReturn) { + Con_DPrintf ("CDAudio: MCI_PLAY failed (%i)\n", dwReturn); return; } playing = true; } -static void CD_f (void) +static void +CD_f (void) { - char *command; - int ret; - int n; -// int startAddress; + char *command; + int ret; + int n; - if (Cmd_Argc() < 2) +// int startAddress; + + if (Cmd_Argc () < 2) return; command = Cmd_Argv (1); - if (strcasecmp(command, "on") == 0) - { + if (strcasecmp (command, "on") == 0) { enabled = true; return; } - if (strcasecmp(command, "off") == 0) - { + if (strcasecmp (command, "off") == 0) { if (playing) - CDAudio_Stop(); + CDAudio_Stop (); enabled = false; return; } - if (strcasecmp(command, "reset") == 0) - { + if (strcasecmp (command, "reset") == 0) { enabled = true; if (playing) - CDAudio_Stop(); + CDAudio_Stop (); for (n = 0; n < 100; n++) remap[n] = n; - CDAudio_GetAudioDiskInfo(); + CDAudio_GetAudioDiskInfo (); return; } - if (strcasecmp(command, "remap") == 0) - { - ret = Cmd_Argc() - 2; - if (ret <= 0) - { + if (strcasecmp (command, "remap") == 0) { + ret = Cmd_Argc () - 2; + if (ret <= 0) { for (n = 1; n < 100; n++) if (remap[n] != n) - Con_Printf(" %u -> %u\n", n, remap[n]); + Con_Printf (" %u -> %u\n", n, remap[n]); return; } for (n = 1; n <= ret; n++) - remap[n] = atoi(Cmd_Argv (n+1)); + remap[n] = atoi (Cmd_Argv (n + 1)); return; } - if (strcasecmp(command, "close") == 0) - { - CDAudio_CloseDoor(); + if (strcasecmp (command, "close") == 0) { + CDAudio_CloseDoor (); return; } - if (!cdValid) - { - CDAudio_GetAudioDiskInfo(); - if (!cdValid) - { - Con_Printf("No CD in player.\n"); + if (!cdValid) { + CDAudio_GetAudioDiskInfo (); + if (!cdValid) { + Con_Printf ("No CD in player.\n"); return; } } - if (strcasecmp(command, "play") == 0) - { - CDAudio_Play((byte)atoi(Cmd_Argv (2)), false); + if (strcasecmp (command, "play") == 0) { + CDAudio_Play ((byte) atoi (Cmd_Argv (2)), false); return; } - if (strcasecmp(command, "loop") == 0) - { - CDAudio_Play((byte)atoi(Cmd_Argv (2)), true); + if (strcasecmp (command, "loop") == 0) { + CDAudio_Play ((byte) atoi (Cmd_Argv (2)), true); return; } - if (strcasecmp(command, "stop") == 0) - { - CDAudio_Stop(); + if (strcasecmp (command, "stop") == 0) { + CDAudio_Stop (); return; } - if (strcasecmp(command, "pause") == 0) - { - CDAudio_Pause(); + if (strcasecmp (command, "pause") == 0) { + CDAudio_Pause (); return; } - if (strcasecmp(command, "resume") == 0) - { - CDAudio_Resume(); + if (strcasecmp (command, "resume") == 0) { + CDAudio_Resume (); return; } - if (strcasecmp(command, "eject") == 0) - { + if (strcasecmp (command, "eject") == 0) { if (playing) - CDAudio_Stop(); - CDAudio_Eject(); + CDAudio_Stop (); + CDAudio_Eject (); cdValid = false; return; } - if (strcasecmp(command, "info") == 0) - { - Con_Printf("%u tracks\n", maxTrack); + if (strcasecmp (command, "info") == 0) { + Con_Printf ("%u tracks\n", maxTrack); if (playing) - Con_Printf("Currently %s track %u\n", playLooping ? "looping" : "playing", playTrack); + Con_Printf ("Currently %s track %u\n", + playLooping ? "looping" : "playing", playTrack); else if (wasPlaying) - Con_Printf("Paused %s track %u\n", playLooping ? "looping" : "playing", playTrack); - Con_Printf("Volume is %f\n", cdvolume); + Con_Printf ("Paused %s track %u\n", + playLooping ? "looping" : "playing", playTrack); + Con_Printf ("Volume is %f\n", cdvolume); return; } } -LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +LONG +CDAudio_MessageHandler (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (lParam != wDeviceID) return 1; - switch (wParam) - { + switch (wParam) { case MCI_NOTIFY_SUCCESSFUL: - if (playing) - { + if (playing) { playing = false; if (playLooping) - CDAudio_Play(playTrack, true); + CDAudio_Play (playTrack, true); } break; @@ -401,13 +399,13 @@ LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) break; case MCI_NOTIFY_FAILURE: - Con_DPrintf("MCI_NOTIFY_FAILURE\n"); + Con_DPrintf ("MCI_NOTIFY_FAILURE\n"); CDAudio_Stop (); cdValid = false; break; default: - Con_DPrintf("Unexpected MM_MCINOTIFY type (%i)\n", wParam); + Con_DPrintf ("Unexpected MM_MCINOTIFY type (%i)\n", wParam); return 1; } @@ -415,21 +413,18 @@ LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) } -void CDAudio_Update(void) +void +CDAudio_Update (void) { if (!enabled) return; - if (bgmvolume->value != cdvolume) - { - if (cdvolume) - { + if (bgmvolume->value != cdvolume) { + if (cdvolume) { Cvar_SetValue (bgmvolume, 0.0); cdvolume = bgmvolume->value; CDAudio_Pause (); - } - else - { + } else { Cvar_SetValue (bgmvolume, 1.0); cdvolume = bgmvolume->value; CDAudio_Resume (); @@ -438,62 +433,67 @@ void CDAudio_Update(void) } -int CDAudio_Init(void) +int +CDAudio_Init (void) { - DWORD dwReturn; - MCI_OPEN_PARMS mciOpenParms; - MCI_SET_PARMS mciSetParms; - int n; + DWORD dwReturn; + MCI_OPEN_PARMS mciOpenParms; + MCI_SET_PARMS mciSetParms; + int n; -#if 0 // QW +#if 0 // QW if (cls.state == ca_dedicated) return -1; #endif - if (COM_CheckParm("-nocdaudio")) + if (COM_CheckParm ("-nocdaudio")) return -1; mciOpenParms.lpstrDeviceType = "cdaudio"; - dwReturn = mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_SHAREABLE, (DWORD) (LPVOID) &mciOpenParms); - if (dwReturn) { - Con_Printf("CDAudio_Init: MCI_OPEN failed (%i)\n", dwReturn); + dwReturn = + mciSendCommand (0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_SHAREABLE, + (DWORD) (LPVOID) & mciOpenParms); + if (dwReturn) { + Con_Printf ("CDAudio_Init: MCI_OPEN failed (%i)\n", dwReturn); return -1; } wDeviceID = mciOpenParms.wDeviceID; - // Set the time format to track/minute/second/frame (TMSF). - mciSetParms.dwTimeFormat = MCI_FORMAT_TMSF; - dwReturn = mciSendCommand(wDeviceID, MCI_SET, MCI_SET_TIME_FORMAT, (DWORD)(LPVOID) &mciSetParms); - if (dwReturn) { - Con_Printf("MCI_SET_TIME_FORMAT failed (%i)\n", dwReturn); - mciSendCommand(wDeviceID, MCI_CLOSE, 0, (DWORD)NULL); + // Set the time format to track/minute/second/frame (TMSF). + mciSetParms.dwTimeFormat = MCI_FORMAT_TMSF; + dwReturn = + mciSendCommand (wDeviceID, MCI_SET, MCI_SET_TIME_FORMAT, + (DWORD) (LPVOID) & mciSetParms); + if (dwReturn) { + Con_Printf ("MCI_SET_TIME_FORMAT failed (%i)\n", dwReturn); + mciSendCommand (wDeviceID, MCI_CLOSE, 0, (DWORD) NULL); return -1; - } + } for (n = 0; n < 100; n++) remap[n] = n; initialized = true; enabled = true; - if (CDAudio_GetAudioDiskInfo()) - { - Con_Printf("CDAudio_Init: No CD in player.\n"); + if (CDAudio_GetAudioDiskInfo ()) { + Con_Printf ("CDAudio_Init: No CD in player.\n"); cdValid = false; enabled = false; } Cmd_AddCommand ("cd", CD_f); -// Con_Printf("CD Audio Initialized\n"); +// Con_Printf("CD Audio Initialized\n"); return 0; } -void CDAudio_Shutdown(void) +void +CDAudio_Shutdown (void) { if (!initialized) return; - CDAudio_Stop(); - if (mciSendCommand(wDeviceID, MCI_CLOSE, MCI_WAIT, (DWORD)NULL)) - Con_DPrintf("CDAudio_Shutdown: MCI_CLOSE failed\n"); + CDAudio_Stop (); + if (mciSendCommand (wDeviceID, MCI_CLOSE, MCI_WAIT, (DWORD) NULL)) + Con_DPrintf ("CDAudio_Shutdown: MCI_CLOSE failed\n"); } diff --git a/source/checksum.c b/source/checksum.c index ce7d6e1..2208452 100644 --- a/source/checksum.c +++ b/source/checksum.c @@ -39,41 +39,73 @@ #include "crc.h" static byte chktbl[1024 + 4] = { -0x78,0xd2,0x94,0xe3,0x41,0xec,0xd6,0xd5,0xcb,0xfc,0xdb,0x8a,0x4b,0xcc,0x85,0x01, -0x23,0xd2,0xe5,0xf2,0x29,0xa7,0x45,0x94,0x4a,0x62,0xe3,0xa5,0x6f,0x3f,0xe1,0x7a, -0x64,0xed,0x5c,0x99,0x29,0x87,0xa8,0x78,0x59,0x0d,0xaa,0x0f,0x25,0x0a,0x5c,0x58, -0xfb,0x00,0xa7,0xa8,0x8a,0x1d,0x86,0x80,0xc5,0x1f,0xd2,0x28,0x69,0x71,0x58,0xc3, -0x51,0x90,0xe1,0xf8,0x6a,0xf3,0x8f,0xb0,0x68,0xdf,0x95,0x40,0x5c,0xe4,0x24,0x6b, -0x29,0x19,0x71,0x3f,0x42,0x63,0x6c,0x48,0xe7,0xad,0xa8,0x4b,0x91,0x8f,0x42,0x36, -0x34,0xe7,0x32,0x55,0x59,0x2d,0x36,0x38,0x38,0x59,0x9b,0x08,0x16,0x4d,0x8d,0xf8, -0x0a,0xa4,0x52,0x01,0xbb,0x52,0xa9,0xfd,0x40,0x18,0x97,0x37,0xff,0xc9,0x82,0x27, -0xb2,0x64,0x60,0xce,0x00,0xd9,0x04,0xf0,0x9e,0x99,0xbd,0xce,0x8f,0x90,0x4a,0xdd, -0xe1,0xec,0x19,0x14,0xb1,0xfb,0xca,0x1e,0x98,0x0f,0xd4,0xcb,0x80,0xd6,0x05,0x63, -0xfd,0xa0,0x74,0xa6,0x86,0xf6,0x19,0x98,0x76,0x27,0x68,0xf7,0xe9,0x09,0x9a,0xf2, -0x2e,0x42,0xe1,0xbe,0x64,0x48,0x2a,0x74,0x30,0xbb,0x07,0xcc,0x1f,0xd4,0x91,0x9d, -0xac,0x55,0x53,0x25,0xb9,0x64,0xf7,0x58,0x4c,0x34,0x16,0xbc,0xf6,0x12,0x2b,0x65, -0x68,0x25,0x2e,0x29,0x1f,0xbb,0xb9,0xee,0x6d,0x0c,0x8e,0xbb,0xd2,0x5f,0x1d,0x8f, -0xc1,0x39,0xf9,0x8d,0xc0,0x39,0x75,0xcf,0x25,0x17,0xbe,0x96,0xaf,0x98,0x9f,0x5f, -0x65,0x15,0xc4,0x62,0xf8,0x55,0xfc,0xab,0x54,0xcf,0xdc,0x14,0x06,0xc8,0xfc,0x42, -0xd3,0xf0,0xad,0x10,0x08,0xcd,0xd4,0x11,0xbb,0xca,0x67,0xc6,0x48,0x5f,0x9d,0x59, -0xe3,0xe8,0x53,0x67,0x27,0x2d,0x34,0x9e,0x9e,0x24,0x29,0xdb,0x69,0x99,0x86,0xf9, -0x20,0xb5,0xbb,0x5b,0xb0,0xf9,0xc3,0x67,0xad,0x1c,0x9c,0xf7,0xcc,0xef,0xce,0x69, -0xe0,0x26,0x8f,0x79,0xbd,0xca,0x10,0x17,0xda,0xa9,0x88,0x57,0x9b,0x15,0x24,0xba, -0x84,0xd0,0xeb,0x4d,0x14,0xf5,0xfc,0xe6,0x51,0x6c,0x6f,0x64,0x6b,0x73,0xec,0x85, -0xf1,0x6f,0xe1,0x67,0x25,0x10,0x77,0x32,0x9e,0x85,0x6e,0x69,0xb1,0x83,0x00,0xe4, -0x13,0xa4,0x45,0x34,0x3b,0x40,0xff,0x41,0x82,0x89,0x79,0x57,0xfd,0xd2,0x8e,0xe8, -0xfc,0x1d,0x19,0x21,0x12,0x00,0xd7,0x66,0xe5,0xc7,0x10,0x1d,0xcb,0x75,0xe8,0xfa, -0xb6,0xee,0x7b,0x2f,0x1a,0x25,0x24,0xb9,0x9f,0x1d,0x78,0xfb,0x84,0xd0,0x17,0x05, -0x71,0xb3,0xc8,0x18,0xff,0x62,0xee,0xed,0x53,0xab,0x78,0xd3,0x65,0x2d,0xbb,0xc7, -0xc1,0xe7,0x70,0xa2,0x43,0x2c,0x7c,0xc7,0x16,0x04,0xd2,0x45,0xd5,0x6b,0x6c,0x7a, -0x5e,0xa1,0x50,0x2e,0x31,0x5b,0xcc,0xe8,0x65,0x8b,0x16,0x85,0xbf,0x82,0x83,0xfb, -0xde,0x9f,0x36,0x48,0x32,0x79,0xd6,0x9b,0xfb,0x52,0x45,0xbf,0x43,0xf7,0x0b,0x0b, -0x19,0x19,0x31,0xc3,0x85,0xec,0x1d,0x8c,0x20,0xf0,0x3a,0xfa,0x80,0x4d,0x2c,0x7d, -0xac,0x60,0x09,0xc0,0x40,0xee,0xb9,0xeb,0x13,0x5b,0xe8,0x2b,0xb1,0x20,0xf0,0xce, -0x4c,0xbd,0xc6,0x04,0x86,0x70,0xc6,0x33,0xc3,0x15,0x0f,0x65,0x19,0xfd,0xc2,0xd3, + 0x78, 0xd2, 0x94, 0xe3, 0x41, 0xec, 0xd6, 0xd5, 0xcb, 0xfc, 0xdb, 0x8a, + 0x4b, 0xcc, 0x85, 0x01, + 0x23, 0xd2, 0xe5, 0xf2, 0x29, 0xa7, 0x45, 0x94, 0x4a, 0x62, 0xe3, 0xa5, + 0x6f, 0x3f, 0xe1, 0x7a, + 0x64, 0xed, 0x5c, 0x99, 0x29, 0x87, 0xa8, 0x78, 0x59, 0x0d, 0xaa, 0x0f, + 0x25, 0x0a, 0x5c, 0x58, + 0xfb, 0x00, 0xa7, 0xa8, 0x8a, 0x1d, 0x86, 0x80, 0xc5, 0x1f, 0xd2, 0x28, + 0x69, 0x71, 0x58, 0xc3, + 0x51, 0x90, 0xe1, 0xf8, 0x6a, 0xf3, 0x8f, 0xb0, 0x68, 0xdf, 0x95, 0x40, + 0x5c, 0xe4, 0x24, 0x6b, + 0x29, 0x19, 0x71, 0x3f, 0x42, 0x63, 0x6c, 0x48, 0xe7, 0xad, 0xa8, 0x4b, + 0x91, 0x8f, 0x42, 0x36, + 0x34, 0xe7, 0x32, 0x55, 0x59, 0x2d, 0x36, 0x38, 0x38, 0x59, 0x9b, 0x08, + 0x16, 0x4d, 0x8d, 0xf8, + 0x0a, 0xa4, 0x52, 0x01, 0xbb, 0x52, 0xa9, 0xfd, 0x40, 0x18, 0x97, 0x37, + 0xff, 0xc9, 0x82, 0x27, + 0xb2, 0x64, 0x60, 0xce, 0x00, 0xd9, 0x04, 0xf0, 0x9e, 0x99, 0xbd, 0xce, + 0x8f, 0x90, 0x4a, 0xdd, + 0xe1, 0xec, 0x19, 0x14, 0xb1, 0xfb, 0xca, 0x1e, 0x98, 0x0f, 0xd4, 0xcb, + 0x80, 0xd6, 0x05, 0x63, + 0xfd, 0xa0, 0x74, 0xa6, 0x86, 0xf6, 0x19, 0x98, 0x76, 0x27, 0x68, 0xf7, + 0xe9, 0x09, 0x9a, 0xf2, + 0x2e, 0x42, 0xe1, 0xbe, 0x64, 0x48, 0x2a, 0x74, 0x30, 0xbb, 0x07, 0xcc, + 0x1f, 0xd4, 0x91, 0x9d, + 0xac, 0x55, 0x53, 0x25, 0xb9, 0x64, 0xf7, 0x58, 0x4c, 0x34, 0x16, 0xbc, + 0xf6, 0x12, 0x2b, 0x65, + 0x68, 0x25, 0x2e, 0x29, 0x1f, 0xbb, 0xb9, 0xee, 0x6d, 0x0c, 0x8e, 0xbb, + 0xd2, 0x5f, 0x1d, 0x8f, + 0xc1, 0x39, 0xf9, 0x8d, 0xc0, 0x39, 0x75, 0xcf, 0x25, 0x17, 0xbe, 0x96, + 0xaf, 0x98, 0x9f, 0x5f, + 0x65, 0x15, 0xc4, 0x62, 0xf8, 0x55, 0xfc, 0xab, 0x54, 0xcf, 0xdc, 0x14, + 0x06, 0xc8, 0xfc, 0x42, + 0xd3, 0xf0, 0xad, 0x10, 0x08, 0xcd, 0xd4, 0x11, 0xbb, 0xca, 0x67, 0xc6, + 0x48, 0x5f, 0x9d, 0x59, + 0xe3, 0xe8, 0x53, 0x67, 0x27, 0x2d, 0x34, 0x9e, 0x9e, 0x24, 0x29, 0xdb, + 0x69, 0x99, 0x86, 0xf9, + 0x20, 0xb5, 0xbb, 0x5b, 0xb0, 0xf9, 0xc3, 0x67, 0xad, 0x1c, 0x9c, 0xf7, + 0xcc, 0xef, 0xce, 0x69, + 0xe0, 0x26, 0x8f, 0x79, 0xbd, 0xca, 0x10, 0x17, 0xda, 0xa9, 0x88, 0x57, + 0x9b, 0x15, 0x24, 0xba, + 0x84, 0xd0, 0xeb, 0x4d, 0x14, 0xf5, 0xfc, 0xe6, 0x51, 0x6c, 0x6f, 0x64, + 0x6b, 0x73, 0xec, 0x85, + 0xf1, 0x6f, 0xe1, 0x67, 0x25, 0x10, 0x77, 0x32, 0x9e, 0x85, 0x6e, 0x69, + 0xb1, 0x83, 0x00, 0xe4, + 0x13, 0xa4, 0x45, 0x34, 0x3b, 0x40, 0xff, 0x41, 0x82, 0x89, 0x79, 0x57, + 0xfd, 0xd2, 0x8e, 0xe8, + 0xfc, 0x1d, 0x19, 0x21, 0x12, 0x00, 0xd7, 0x66, 0xe5, 0xc7, 0x10, 0x1d, + 0xcb, 0x75, 0xe8, 0xfa, + 0xb6, 0xee, 0x7b, 0x2f, 0x1a, 0x25, 0x24, 0xb9, 0x9f, 0x1d, 0x78, 0xfb, + 0x84, 0xd0, 0x17, 0x05, + 0x71, 0xb3, 0xc8, 0x18, 0xff, 0x62, 0xee, 0xed, 0x53, 0xab, 0x78, 0xd3, + 0x65, 0x2d, 0xbb, 0xc7, + 0xc1, 0xe7, 0x70, 0xa2, 0x43, 0x2c, 0x7c, 0xc7, 0x16, 0x04, 0xd2, 0x45, + 0xd5, 0x6b, 0x6c, 0x7a, + 0x5e, 0xa1, 0x50, 0x2e, 0x31, 0x5b, 0xcc, 0xe8, 0x65, 0x8b, 0x16, 0x85, + 0xbf, 0x82, 0x83, 0xfb, + 0xde, 0x9f, 0x36, 0x48, 0x32, 0x79, 0xd6, 0x9b, 0xfb, 0x52, 0x45, 0xbf, + 0x43, 0xf7, 0x0b, 0x0b, + 0x19, 0x19, 0x31, 0xc3, 0x85, 0xec, 0x1d, 0x8c, 0x20, 0xf0, 0x3a, 0xfa, + 0x80, 0x4d, 0x2c, 0x7d, + 0xac, 0x60, 0x09, 0xc0, 0x40, 0xee, 0xb9, 0xeb, 0x13, 0x5b, 0xe8, 0x2b, + 0xb1, 0x20, 0xf0, 0xce, + 0x4c, 0xbd, 0xc6, 0x04, 0x86, 0x70, 0xc6, 0x33, 0xc3, 0x15, 0x0f, 0x65, + 0x19, 0xfd, 0xc2, 0xd3, // map checksum goes here -0x00,0x00,0x00,0x00 + 0x00, 0x00, 0x00, 0x00 }; #if 0 @@ -84,10 +116,12 @@ COM_BlockSequenceCheckByte For proxy protecting ==================== */ -byte COM_BlockSequenceCheckByte (byte *base, int length, int sequence, unsigned mapchecksum) +byte +COM_BlockSequenceCheckByte (byte * base, int length, int sequence, + unsigned mapchecksum) { - int checksum; - byte *p; + int checksum; + byte *p; if (last_mapchecksum != mapchecksum) { last_mapchecksum = mapchecksum; @@ -96,10 +130,10 @@ byte COM_BlockSequenceCheckByte (byte *base, int length, int sequence, unsigned chktbl[1026] = (mapchecksum & 0x0000ff00) >> 8; chktbl[1027] = (mapchecksum & 0x000000ff); - Com_BlockFullChecksum (chktbl, sizeof(chktbl), chkbuf); + Com_BlockFullChecksum (chktbl, sizeof (chktbl), chkbuf); } - p = chktbl + (sequence % (sizeof(chktbl) - 8)); + p = chktbl + (sequence % (sizeof (chktbl) - 8)); if (length > 60) length = 60; @@ -108,13 +142,13 @@ byte COM_BlockSequenceCheckByte (byte *base, int length, int sequence, unsigned length += 16; chkbuf[length] = (sequence & 0xff) ^ p[0]; - chkbuf[length+1] = p[1]; - chkbuf[length+2] = ((sequence>>8) & 0xff) ^ p[2]; - chkbuf[length+3] = p[3]; + chkbuf[length + 1] = p[1]; + chkbuf[length + 2] = ((sequence >> 8) & 0xff) ^ p[2]; + chkbuf[length + 3] = p[3]; length += 4; - checksum = LittleLong(Com_BlockChecksum (chkbuf, length)); + checksum = LittleLong (Com_BlockChecksum (chkbuf, length)); checksum &= 0xff; @@ -129,26 +163,27 @@ COM_BlockSequenceCRCByte For proxy protecting ==================== */ -byte COM_BlockSequenceCRCByte (byte *base, int length, int sequence) +byte +COM_BlockSequenceCRCByte (byte * base, int length, int sequence) { unsigned short crc; - byte *p; - byte chkb[60 + 4]; + byte *p; + byte chkb[60 + 4]; - p = chktbl + (sequence % (sizeof(chktbl) - 8)); + p = chktbl + (sequence % (sizeof (chktbl) - 8)); if (length > 60) length = 60; memcpy (chkb, base, length); chkb[length] = (sequence & 0xff) ^ p[0]; - chkb[length+1] = p[1]; - chkb[length+2] = ((sequence>>8) & 0xff) ^ p[2]; - chkb[length+3] = p[3]; + chkb[length + 1] = p[1]; + chkb[length + 2] = ((sequence >> 8) & 0xff) ^ p[2]; + chkb[length + 3] = p[3]; length += 4; - crc = CRC_Block(chkb, length); + crc = CRC_Block (chkb, length); crc &= 0xff; diff --git a/source/cl_cam.c b/source/cl_cam.c index c858811..21f67ec 100644 --- a/source/cl_cam.c +++ b/source/cl_cam.c @@ -32,7 +32,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -59,46 +59,44 @@ #define BUTTON_ATTACK 1 #define MAX_ANGLE_TURN 10 -static vec3_t desired_position; // where the camera wants to be +static vec3_t desired_position; // where the camera wants to be static qboolean locked = false; -static int oldbuttons; +static int oldbuttons; // track high fragger -cvar_t *cl_hightrack; +cvar_t *cl_hightrack; -cvar_t *cl_chasecam; +cvar_t *cl_chasecam; -cvar_t *cl_camera_maxpitch; -cvar_t *cl_camera_maxyaw; +cvar_t *cl_camera_maxpitch; +cvar_t *cl_camera_maxyaw; -qboolean cam_forceview; -vec3_t cam_viewangles; -double cam_lastviewtime; +qboolean cam_forceview; +vec3_t cam_viewangles; +double cam_lastviewtime; -int spec_track = 0; // player# of who we are tracking -int autocam = CAM_NONE; +int spec_track = 0; // player# of who we are tracking +int autocam = CAM_NONE; -static void vectoangles(vec3_t vec, vec3_t ang) +static void +vectoangles (vec3_t vec, vec3_t ang) { - float forward; - float yaw, pitch; - - if (vec[1] == 0 && vec[0] == 0) - { + float forward; + float yaw, pitch; + + if (vec[1] == 0 && vec[0] == 0) { yaw = 0; if (vec[2] > 0) pitch = 90; else pitch = 270; - } - else - { - yaw = (int) (atan2(vec[1], vec[0]) * 180 / M_PI); + } else { + yaw = (int) (atan2 (vec[1], vec[0]) * 180 / M_PI); if (yaw < 0) yaw += 360; - forward = sqrt (vec[0]*vec[0] + vec[1]*vec[1]); - pitch = (int) (atan2(vec[2], forward) * 180 / M_PI); + forward = sqrt (vec[0] * vec[0] + vec[1] * vec[1]); + pitch = (int) (atan2 (vec[2], forward) * 180 / M_PI); if (pitch < 0) pitch += 360; } @@ -108,13 +106,15 @@ static void vectoangles(vec3_t vec, vec3_t ang) ang[2] = 0; } -static float vlen(vec3_t v) +static float +vlen (vec3_t v) { - return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); + return sqrt (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); } // returns true if weapon model should be drawn in camera mode -qboolean Cam_DrawViewModel(void) +qboolean +Cam_DrawViewModel (void) { if (!cl.spectator) return true; @@ -125,42 +125,46 @@ qboolean Cam_DrawViewModel(void) } // returns true if we should draw this player, we don't if we are chase camming -qboolean Cam_DrawPlayer(int playernum) +qboolean +Cam_DrawPlayer (int playernum) { - if (cl.spectator && autocam && locked && cl_chasecam->int_val && + if (cl.spectator && autocam && locked && cl_chasecam->int_val && spec_track == playernum) return false; return true; } -void Cam_Unlock(void) +void +Cam_Unlock (void) { if (autocam) { MSG_WriteByte (&cls.netchan.message, clc_stringcmd); MSG_WriteString (&cls.netchan.message, "ptrack"); autocam = CAM_NONE; locked = false; - Sbar_Changed(); + Sbar_Changed (); } } -void Cam_Lock(int playernum) +void +Cam_Lock (int playernum) { - char st[40]; + char st[40]; - snprintf(st, sizeof(st), "ptrack %i", playernum); + snprintf (st, sizeof (st), "ptrack %i", playernum); MSG_WriteByte (&cls.netchan.message, clc_stringcmd); MSG_WriteString (&cls.netchan.message, st); spec_track = playernum; cam_forceview = true; locked = false; - Sbar_Changed(); + Sbar_Changed (); } -pmtrace_t Cam_DoTrace(vec3_t vec1, vec3_t vec2) +pmtrace_t +Cam_DoTrace (vec3_t vec1, vec3_t vec2) { #if 0 - memset(&pmove, 0, sizeof(pmove)); + memset (&pmove, 0, sizeof (pmove)); pmove.numphysent = 1; VectorCopy (vec3_origin, pmove.physents[0].origin); @@ -168,36 +172,38 @@ pmtrace_t Cam_DoTrace(vec3_t vec1, vec3_t vec2) #endif VectorCopy (vec1, pmove.origin); - return PM_PlayerMove(pmove.origin, vec2); + return PM_PlayerMove (pmove.origin, vec2); } - -// Returns distance or 9999 if invalid for some reason -static float Cam_TryFlyby(player_state_t *self, player_state_t *player, vec3_t vec, qboolean checkvis) -{ - vec3_t v; - pmtrace_t trace; - float len; - vectoangles(vec, v); -// v[0] = -v[0]; +// Returns distance or 9999 if invalid for some reason +static float +Cam_TryFlyby (player_state_t * self, player_state_t * player, vec3_t vec, + qboolean checkvis) +{ + vec3_t v; + pmtrace_t trace; + float len; + + vectoangles (vec, v); +// v[0] = -v[0]; VectorCopy (v, pmove.angles); - VectorNormalize(vec); - VectorMA(player->origin, 800, vec, v); + VectorNormalize (vec); + VectorMA (player->origin, 800, vec, v); // v is endpos // fake a player move - trace = Cam_DoTrace(player->origin, v); - if (/*trace.inopen ||*/ trace.inwater) + trace = Cam_DoTrace (player->origin, v); + if ( /* trace.inopen || */ trace.inwater) return 9999; - VectorCopy(trace.endpos, vec); - VectorSubtract(trace.endpos, player->origin, v); - len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); + VectorCopy (trace.endpos, vec); + VectorSubtract (trace.endpos, player->origin, v); + len = sqrt (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); if (len < 32 || len > 800) return 9999; if (checkvis) { - VectorSubtract(trace.endpos, self->origin, v); - len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); + VectorSubtract (trace.endpos, self->origin, v); + len = sqrt (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); - trace = Cam_DoTrace(self->origin, vec); + trace = Cam_DoTrace (self->origin, vec); if (trace.fraction != 1 || trace.inwater) return 9999; } @@ -205,117 +211,119 @@ static float Cam_TryFlyby(player_state_t *self, player_state_t *player, vec3_t v } // Is player visible? -static qboolean Cam_IsVisible(player_state_t *player, vec3_t vec) +static qboolean +Cam_IsVisible (player_state_t * player, vec3_t vec) { - pmtrace_t trace; - vec3_t v; - float d; + pmtrace_t trace; + vec3_t v; + float d; - trace = Cam_DoTrace(player->origin, vec); - if (trace.fraction != 1 || /*trace.inopen ||*/ trace.inwater) + trace = Cam_DoTrace (player->origin, vec); + if (trace.fraction != 1 || /* trace.inopen || */ trace.inwater) return false; // check distance, don't let the player get too far away or too close - VectorSubtract(player->origin, vec, v); - d = vlen(v); + VectorSubtract (player->origin, vec, v); + d = vlen (v); if (d < 16) return false; return true; } -static qboolean InitFlyby(player_state_t *self, player_state_t *player, int checkvis) +static qboolean +InitFlyby (player_state_t * self, player_state_t * player, int checkvis) { - float f, max; - vec3_t vec, vec2; - vec3_t forward, right, up; + float f, max; + vec3_t vec, vec2; + vec3_t forward, right, up; - VectorCopy(player->viewangles, vec); - vec[0] = 0; + VectorCopy (player->viewangles, vec); + vec[0] = 0; AngleVectors (vec, forward, right, up); -// for (i = 0; i < 3; i++) -// forward[i] *= 3; +// for (i = 0; i < 3; i++) +// forward[i] *= 3; - max = 1000; - VectorAdd(forward, up, vec2); - VectorAdd(vec2, right, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorAdd(forward, up, vec2); - VectorSubtract(vec2, right, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorAdd(forward, right, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorSubtract(forward, right, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorAdd(forward, up, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorSubtract(forward, up, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorAdd(up, right, vec2); - VectorSubtract(vec2, forward, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorSubtract(up, right, vec2); - VectorSubtract(vec2, forward, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } + max = 1000; + VectorAdd (forward, up, vec2); + VectorAdd (vec2, right, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorAdd (forward, up, vec2); + VectorSubtract (vec2, right, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorAdd (forward, right, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorSubtract (forward, right, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorAdd (forward, up, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorSubtract (forward, up, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorAdd (up, right, vec2); + VectorSubtract (vec2, forward, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorSubtract (up, right, vec2); + VectorSubtract (vec2, forward, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } // invert - VectorSubtract(vec3_origin, forward, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorCopy(forward, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } + VectorSubtract (vec3_origin, forward, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorCopy (forward, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } // invert - VectorSubtract(vec3_origin, right, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - VectorCopy(right, vec2); - if ((f = Cam_TryFlyby(self, player, vec2, checkvis)) < max) { - max = f; - VectorCopy(vec2, vec); - } - + VectorSubtract (vec3_origin, right, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } + VectorCopy (right, vec2); + if ((f = Cam_TryFlyby (self, player, vec2, checkvis)) < max) { + max = f; + VectorCopy (vec2, vec); + } // ack, can't find him - if (max >= 1000) { -// Cam_Unlock(); + if (max >= 1000) { +// Cam_Unlock(); return false; } locked = true; - VectorCopy(vec, desired_position); + VectorCopy (vec, desired_position); return true; } -static void Cam_CheckHighTarget(void) +static void +Cam_CheckHighTarget (void) { - int i, j, max; - player_info_t *s; + int i, j, max; + player_info_t *s; j = -1; for (i = 0, max = -9999; i < MAX_CLIENTS; i++) { @@ -327,37 +335,40 @@ static void Cam_CheckHighTarget(void) } if (j >= 0) { if (!locked || cl.players[j].frags > cl.players[spec_track].frags) - Cam_Lock(j); + Cam_Lock (j); } else - Cam_Unlock(); + Cam_Unlock (); } - + // ZOID // // Take over the user controls and track a player. // We find a nice position to watch the player and move there -void Cam_Track(usercmd_t *cmd) +void +Cam_Track (usercmd_t *cmd) { player_state_t *player, *self; - frame_t *frame; - vec3_t vec; - float len; + frame_t *frame; + vec3_t vec; + float len; if (!cl.spectator) return; - + if (cl_hightrack->int_val && !locked) - Cam_CheckHighTarget(); + Cam_CheckHighTarget (); if (!autocam || cls.state != ca_active) return; - if (locked && (!cl.players[spec_track].name[0] || cl.players[spec_track].spectator)) { + if (locked + && (!cl.players[spec_track].name[0] + || cl.players[spec_track].spectator)) { locked = false; if (cl_hightrack->int_val) - Cam_CheckHighTarget(); + Cam_CheckHighTarget (); else - Cam_Unlock(); + Cam_Unlock (); return; } @@ -365,15 +376,15 @@ void Cam_Track(usercmd_t *cmd) player = frame->playerstate + spec_track; self = frame->playerstate + cl.playernum; - if (!locked || !Cam_IsVisible(player, desired_position)) { + if (!locked || !Cam_IsVisible (player, desired_position)) { if (!locked || realtime - cam_lastviewtime > 0.1) { - if (!InitFlyby(self, player, true)) - InitFlyby(self, player, false); + if (!InitFlyby (self, player, true)) + InitFlyby (self, player, false); cam_lastviewtime = realtime; } } else cam_lastviewtime = realtime; - + // couldn't track for some reason if (!locked || !autocam) return; @@ -381,69 +392,64 @@ void Cam_Track(usercmd_t *cmd) if (cl_chasecam->int_val) { cmd->forwardmove = cmd->sidemove = cmd->upmove = 0; - VectorCopy(player->viewangles, cl.viewangles); - VectorCopy(player->origin, desired_position); - if (memcmp(&desired_position, &self->origin, sizeof(desired_position)) != 0) { + VectorCopy (player->viewangles, cl.viewangles); + VectorCopy (player->origin, desired_position); + if (memcmp (&desired_position, &self->origin, sizeof (desired_position)) + != 0) { MSG_WriteByte (&cls.netchan.message, clc_tmove); MSG_WriteCoord (&cls.netchan.message, desired_position[0]); MSG_WriteCoord (&cls.netchan.message, desired_position[1]); MSG_WriteCoord (&cls.netchan.message, desired_position[2]); // move there locally immediately - VectorCopy(desired_position, self->origin); + VectorCopy (desired_position, self->origin); } self->weaponframe = player->weaponframe; } else { // Ok, move to our desired position and set our angles to view // the player - VectorSubtract(desired_position, self->origin, vec); - len = vlen(vec); + VectorSubtract (desired_position, self->origin, vec); + len = vlen (vec); cmd->forwardmove = cmd->sidemove = cmd->upmove = 0; - if (len > 16) { // close enough? + if (len > 16) { // close enough? MSG_WriteByte (&cls.netchan.message, clc_tmove); MSG_WriteCoord (&cls.netchan.message, desired_position[0]); MSG_WriteCoord (&cls.netchan.message, desired_position[1]); MSG_WriteCoord (&cls.netchan.message, desired_position[2]); } - // move there locally immediately - VectorCopy(desired_position, self->origin); - - VectorSubtract(player->origin, desired_position, vec); - vectoangles(vec, cl.viewangles); + VectorCopy (desired_position, self->origin); + + VectorSubtract (player->origin, desired_position, vec); + vectoangles (vec, cl.viewangles); cl.viewangles[0] = -cl.viewangles[0]; } } #if 0 -static float adjustang(float current, float ideal, float speed) +static float +adjustang (float current, float ideal, float speed) { - float move; + float move; - current = anglemod(current); - ideal = anglemod(ideal); + current = anglemod (current); + ideal = anglemod (ideal); if (current == ideal) return current; move = ideal - current; - if (ideal > current) - { + if (ideal > current) { if (move >= 180) move = move - 360; - } - else - { + } else { if (move <= -180) move = move + 360; } - if (move > 0) - { + if (move > 0) { if (move > speed) move = speed; - } - else - { + } else { if (move < -speed) move = -speed; } @@ -454,48 +460,52 @@ static float adjustang(float current, float ideal, float speed) #endif #if 0 -void Cam_SetView(void) +void +Cam_SetView (void) { return; player_state_t *player, *self; - frame_t *frame; - vec3_t vec, vec2; + frame_t *frame; + vec3_t vec, vec2; - if (cls.state != ca_active || !cl.spectator || - !autocam || !locked) + if (cls.state != ca_active || !cl.spectator || !autocam || !locked) return; frame = &cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK]; player = frame->playerstate + spec_track; self = frame->playerstate + cl.playernum; - VectorSubtract(player->origin, cl.simorg, vec); + VectorSubtract (player->origin, cl.simorg, vec); if (cam_forceview) { cam_forceview = false; - vectoangles(vec, cam_viewangles); + vectoangles (vec, cam_viewangles); cam_viewangles[0] = -cam_viewangles[0]; } else { - vectoangles(vec, vec2); + vectoangles (vec, vec2); vec2[PITCH] = -vec2[PITCH]; - cam_viewangles[PITCH] = adjustang(cam_viewangles[PITCH], vec2[PITCH], cl_camera_maxpitch->value); - cam_viewangles[YAW] = adjustang(cam_viewangles[YAW], vec2[YAW], cl_camera_maxyaw->value); + cam_viewangles[PITCH] = + adjustang (cam_viewangles[PITCH], vec2[PITCH], + cl_camera_maxpitch->value); + cam_viewangles[YAW] = + adjustang (cam_viewangles[YAW], vec2[YAW], cl_camera_maxyaw->value); } - VectorCopy(cam_viewangles, cl.viewangles); - VectorCopy(cl.viewangles, cl.simangles); + VectorCopy (cam_viewangles, cl.viewangles); + VectorCopy (cl.viewangles, cl.simangles); } #endif -void Cam_FinishMove(usercmd_t *cmd) +void +Cam_FinishMove (usercmd_t *cmd) { - int i; - player_info_t *s; - int end; + int i; + player_info_t *s; + int end; if (cls.state != ca_active) return; - if (!cl.spectator) // only in spectator mode + if (!cl.spectator) // only in spectator mode return; #if 0 @@ -504,19 +514,23 @@ void Cam_FinishMove(usercmd_t *cmd) player = frame->playerstate + spec_track; self = frame->playerstate + cl.playernum; - VectorSubtract(player->origin, self->origin, vec); + VectorSubtract (player->origin, self->origin, vec); if (cam_forceview) { cam_forceview = false; - vectoangles(vec, cam_viewangles); + vectoangles (vec, cam_viewangles); cam_viewangles[0] = -cam_viewangles[0]; } else { - vectoangles(vec, vec2); + vectoangles (vec, vec2); vec2[PITCH] = -vec2[PITCH]; - cam_viewangles[PITCH] = adjustang(cam_viewangles[PITCH], vec2[PITCH], cl_camera_maxpitch->value); - cam_viewangles[YAW] = adjustang(cam_viewangles[YAW], vec2[YAW], cl_camera_maxyaw->value); + cam_viewangles[PITCH] = + adjustang (cam_viewangles[PITCH], vec2[PITCH], + cl_camera_maxpitch->value); + cam_viewangles[YAW] = + adjustang (cam_viewangles[YAW], vec2[YAW], + cl_camera_maxyaw->value); } - VectorCopy(cam_viewangles, cl.viewangles); + VectorCopy (cam_viewangles, cl.viewangles); } #endif @@ -527,8 +541,8 @@ void Cam_FinishMove(usercmd_t *cmd) autocam++; if (autocam > CAM_TRACK) { - Cam_Unlock(); - VectorCopy(cl.viewangles, cmd->angles); + Cam_Unlock (); + VectorCopy (cl.viewangles, cmd->angles); return; } } else @@ -540,22 +554,21 @@ void Cam_FinishMove(usercmd_t *cmd) } if (autocam && cl_hightrack->int_val) { - Cam_CheckHighTarget(); + Cam_CheckHighTarget (); return; } if (locked) { if ((cmd->buttons & BUTTON_JUMP) && (oldbuttons & BUTTON_JUMP)) - return; // don't pogo stick + return; // don't pogo stick if (!(cmd->buttons & BUTTON_JUMP)) { oldbuttons &= ~BUTTON_JUMP; return; } - oldbuttons |= BUTTON_JUMP; // don't jump again until released + oldbuttons |= BUTTON_JUMP; // don't jump again until released } - -// Con_Printf("Selecting track target...\n"); +// Con_Printf("Selecting track target...\n"); if (locked && autocam) end = (spec_track + 1) % MAX_CLIENTS; @@ -565,7 +578,7 @@ void Cam_FinishMove(usercmd_t *cmd) do { s = &cl.players[i]; if (s->name[0] && !s->spectator) { - Cam_Lock(i); + Cam_Lock (i); return; } i = (i + 1) % MAX_CLIENTS; @@ -574,25 +587,26 @@ void Cam_FinishMove(usercmd_t *cmd) i = spec_track; s = &cl.players[i]; if (s->name[0] && !s->spectator) { - Cam_Lock(i); + Cam_Lock (i); return; } - Con_Printf("No target found ...\n"); + Con_Printf ("No target found ...\n"); autocam = locked = false; } -void Cam_Reset(void) +void +Cam_Reset (void) { autocam = CAM_NONE; spec_track = 0; } -void CL_Cam_Init_Cvars(void) +void +CL_Cam_Init_Cvars (void) { - cl_hightrack = Cvar_Get("cl_hightrack", "0", CVAR_NONE, "None"); - cl_chasecam = Cvar_Get("cl_chasecam", "0", CVAR_NONE, "None"); - cl_camera_maxpitch = Cvar_Get("cl_camera_maxpitch", "10", CVAR_NONE, "None"); - cl_camera_maxyaw = Cvar_Get("cl_camera_maxyaw", "30", CVAR_NONE, "None"); + cl_hightrack = Cvar_Get ("cl_hightrack", "0", CVAR_NONE, "None"); + cl_chasecam = Cvar_Get ("cl_chasecam", "0", CVAR_NONE, "None"); + cl_camera_maxpitch = + Cvar_Get ("cl_camera_maxpitch", "10", CVAR_NONE, "None"); + cl_camera_maxyaw = Cvar_Get ("cl_camera_maxyaw", "30", CVAR_NONE, "None"); } - - diff --git a/source/cl_cmd.c b/source/cl_cmd.c index 14c3e45..bd19e79 100644 --- a/source/cl_cmd.c +++ b/source/cl_cmd.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "client.h" #include "console.h" @@ -49,67 +49,63 @@ things like godmode, noclip, etc, are commands directed to the server, so when they are typed in at the console, they will need to be forwarded. =================== */ -void Cmd_ForwardToServer (void) +void +Cmd_ForwardToServer (void) { - if (cls.state == ca_disconnected) - { - Con_Printf ("Can't \"%s\", not connected\n", Cmd_Argv(0)); + if (cls.state == ca_disconnected) { + Con_Printf ("Can't \"%s\", not connected\n", Cmd_Argv (0)); return; } - + if (cls.demoplayback) - return; // not really connected + return; // not really connected MSG_WriteByte (&cls.netchan.message, clc_stringcmd); - SZ_Print (&cls.netchan.message, Cmd_Argv(0)); - if (Cmd_Argc() > 1) - { + SZ_Print (&cls.netchan.message, Cmd_Argv (0)); + if (Cmd_Argc () > 1) { SZ_Print (&cls.netchan.message, " "); - if (!strcasecmp(Cmd_Argv(0), "say") || - !strcasecmp(Cmd_Argv(0), "say_team")) - { - char *s; - s = Team_ParseSay(Cmd_Args()); - if (*s && *s < 32 && *s != 10) - { + if (!strcasecmp (Cmd_Argv (0), "say") || + !strcasecmp (Cmd_Argv (0), "say_team")) { + char *s; + + s = Team_ParseSay (Cmd_Args ()); + if (*s && *s < 32 && *s != 10) { // otherwise the server would eat leading characters // less than 32 or greater than 127 SZ_Print (&cls.netchan.message, "\""); SZ_Print (&cls.netchan.message, s); SZ_Print (&cls.netchan.message, "\""); - } - else + } else SZ_Print (&cls.netchan.message, s); return; } - SZ_Print (&cls.netchan.message, Cmd_Args()); + SZ_Print (&cls.netchan.message, Cmd_Args ()); } } // don't forward the first argument -void Cmd_ForwardToServer_f (void) +void +Cmd_ForwardToServer_f (void) { - if (cls.state == ca_disconnected) - { - Con_Printf ("Can't \"%s\", not connected\n", Cmd_Argv(0)); + if (cls.state == ca_disconnected) { + Con_Printf ("Can't \"%s\", not connected\n", Cmd_Argv (0)); return; } - if (strcasecmp(Cmd_Argv(1), "snap") == 0) { + if (strcasecmp (Cmd_Argv (1), "snap") == 0) { Cbuf_InsertText ("snap\n"); return; } - - if (cls.demoplayback) - return; // not really connected - if (Cmd_Argc() > 1) - { + if (cls.demoplayback) + return; // not really connected + + if (Cmd_Argc () > 1) { MSG_WriteByte (&cls.netchan.message, clc_stringcmd); - SZ_Print (&cls.netchan.message, Cmd_Args()); + SZ_Print (&cls.netchan.message, Cmd_Args ()); } } @@ -118,11 +114,11 @@ void Cmd_ForwardToServer_f (void) Cmd_Init ============ */ -void cl_Cmd_Init (void) +void +cl_Cmd_Init (void) { // // register our commands // Cmd_AddCommand ("cmd", Cmd_ForwardToServer_f); } - diff --git a/source/cl_cvar.c b/source/cl_cvar.c index 3aa2619..6448cd4 100644 --- a/source/cl_cvar.c +++ b/source/cl_cvar.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "cvar.h" #include "sizebuf.h" @@ -37,13 +37,15 @@ #include "va.h" void -Cvar_Info(cvar_t *var) +Cvar_Info (cvar_t *var) { if (var->flags & CVAR_USERINFO) { - Info_SetValueForKey (cls.userinfo, var->name, var->string, MAX_INFO_STRING); + Info_SetValueForKey (cls.userinfo, var->name, var->string, + MAX_INFO_STRING); if (cls.state >= ca_connected) { MSG_WriteByte (&cls.netchan.message, clc_stringcmd); - SZ_Print (&cls.netchan.message, va("setinfo \"%s\" \"%s\"\n", var->name, var->string)); + SZ_Print (&cls.netchan.message, + va ("setinfo \"%s\" \"%s\"\n", var->name, var->string)); } } } diff --git a/source/cl_demo.c b/source/cl_demo.c index a9dfb53..e9285e3 100644 --- a/source/cl_demo.c +++ b/source/cl_demo.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -45,7 +45,7 @@ #include "pmove.h" #include "cl_main.h" -void CL_FinishTimeDemo (void); +void CL_FinishTimeDemo (void); /* ============================================================================== @@ -67,7 +67,8 @@ CL_StopPlayback Called when a demo file runs out, or the user starts a game ============== */ -void CL_StopPlayback (void) +void +CL_StopPlayback (void) { if (!cls.demoplayback) return; @@ -92,34 +93,34 @@ CL_WriteDemoCmd Writes the current user cmd ==================== */ -void CL_WriteDemoCmd (usercmd_t *pcmd) +void +CL_WriteDemoCmd (usercmd_t *pcmd) { - int i; - float fl; - byte c; - usercmd_t cmd; + int i; + float fl; + byte c; + usercmd_t cmd; //Con_Printf("write: %ld bytes, %4.4f\n", msg->cursize, realtime); - fl = LittleFloat((float)realtime); - Qwrite (cls.demofile, &fl, sizeof(fl)); + fl = LittleFloat ((float) realtime); + Qwrite (cls.demofile, &fl, sizeof (fl)); c = dem_cmd; - Qwrite (cls.demofile, &c, sizeof(c)); + Qwrite (cls.demofile, &c, sizeof (c)); // correct for byte order, bytes don't matter cmd = *pcmd; for (i = 0; i < 3; i++) - cmd.angles[i] = LittleFloat(cmd.angles[i]); - cmd.forwardmove = LittleShort(cmd.forwardmove); - cmd.sidemove = LittleShort(cmd.sidemove); - cmd.upmove = LittleShort(cmd.upmove); + cmd.angles[i] = LittleFloat (cmd.angles[i]); + cmd.forwardmove = LittleShort (cmd.forwardmove); + cmd.sidemove = LittleShort (cmd.sidemove); + cmd.upmove = LittleShort (cmd.upmove); - Qwrite(cls.demofile, &cmd, sizeof(cmd)); + Qwrite (cls.demofile, &cmd, sizeof (cmd)); - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { fl = LittleFloat (cl.viewangles[i]); Qwrite (cls.demofile, &fl, 4); } @@ -134,22 +135,23 @@ CL_WriteDemoMessage Dumps the current net message, prefixed by the length and view angles ==================== */ -void CL_WriteDemoMessage (sizebuf_t *msg) +void +CL_WriteDemoMessage (sizebuf_t *msg) { - int len; - float fl; - byte c; + int len; + float fl; + byte c; //Con_Printf("write: %ld bytes, %4.4f\n", msg->cursize, realtime); if (!cls.demorecording) return; - fl = LittleFloat((float)realtime); - Qwrite (cls.demofile, &fl, sizeof(fl)); + fl = LittleFloat ((float) realtime); + Qwrite (cls.demofile, &fl, sizeof (fl)); c = dem_read; - Qwrite (cls.demofile, &c, sizeof(c)); + Qwrite (cls.demofile, &c, sizeof (c)); len = LittleLong (msg->cursize); Qwrite (cls.demofile, &len, 4); @@ -165,111 +167,111 @@ CL_GetDemoMessage FIXME... ==================== */ -qboolean CL_GetDemoMessage (void) +qboolean +CL_GetDemoMessage (void) { - int r, i, j; - float f; - float demotime; - byte c; - usercmd_t *pcmd; + int r, i, j; + float f; + float demotime; + byte c; + usercmd_t *pcmd; // read the time from the packet - Qread(cls.demofile, &demotime, sizeof(demotime)); - demotime = LittleFloat(demotime); + Qread (cls.demofile, &demotime, sizeof (demotime)); + demotime = LittleFloat (demotime); -// decide if it is time to grab the next message +// decide if it is time to grab the next message if (cls.timedemo) { if (cls.td_lastframe < 0) cls.td_lastframe = demotime; else if (demotime > cls.td_lastframe) { cls.td_lastframe = demotime; // rewind back to time - Qseek(cls.demofile, Qtell(cls.demofile) - sizeof(demotime), - SEEK_SET); - return 0; // allready read this frame's message + Qseek (cls.demofile, Qtell (cls.demofile) - sizeof (demotime), + SEEK_SET); + return 0; // allready read this frame's message } if (!cls.td_starttime && cls.state == ca_active) { - cls.td_starttime = Sys_DoubleTime(); + cls.td_starttime = Sys_DoubleTime (); cls.td_startframe = host_framecount; } - realtime = demotime; // warp - } else if (!cl.paused && cls.state >= ca_onserver) { // allways grab until fully connected + realtime = demotime; // warp + } else if (!cl.paused && cls.state >= ca_onserver) { // allways grab + // until fully + // connected if (realtime + 1.0 < demotime) { // too far back realtime = demotime - 1.0; // rewind back to time - Qseek(cls.demofile, Qtell(cls.demofile) - sizeof(demotime), - SEEK_SET); + Qseek (cls.demofile, Qtell (cls.demofile) - sizeof (demotime), + SEEK_SET); return 0; } else if (realtime < demotime) { // rewind back to time - Qseek(cls.demofile, Qtell(cls.demofile) - sizeof(demotime), - SEEK_SET); - return 0; // don't need another message yet + Qseek (cls.demofile, Qtell (cls.demofile) - sizeof (demotime), + SEEK_SET); + return 0; // don't need another message yet } } else - realtime = demotime; // we're warping + realtime = demotime; // we're warping if (cls.state < ca_demostart) Host_Error ("CL_GetDemoMessage: cls.state != ca_active"); - + // get the msg type - Qread (cls.demofile, &c, sizeof(c)); - + Qread (cls.demofile, &c, sizeof (c)); + switch (c) { - case dem_cmd : - // user sent input - i = cls.netchan.outgoing_sequence & UPDATE_MASK; - pcmd = &cl.frames[i].cmd; - r = Qread (cls.demofile, pcmd, sizeof(*pcmd)); - if (r != sizeof(*pcmd)) - { + case dem_cmd: + // user sent input + i = cls.netchan.outgoing_sequence & UPDATE_MASK; + pcmd = &cl.frames[i].cmd; + r = Qread (cls.demofile, pcmd, sizeof (*pcmd)); + if (r != sizeof (*pcmd)) { + CL_StopPlayback (); + return 0; + } + // byte order stuff + for (j = 0; j < 3; j++) + pcmd->angles[j] = LittleFloat (pcmd->angles[j]); + pcmd->forwardmove = LittleShort (pcmd->forwardmove); + pcmd->sidemove = LittleShort (pcmd->sidemove); + pcmd->upmove = LittleShort (pcmd->upmove); + cl.frames[i].senttime = demotime; + cl.frames[i].receivedtime = -1; // we haven't gotten a reply yet + cls.netchan.outgoing_sequence++; + for (i = 0; i < 3; i++) { + Qread (cls.demofile, &f, 4); + cl.viewangles[i] = LittleFloat (f); + } + break; + + case dem_read: + // get the next message + Qread (cls.demofile, &net_message.cursize, 4); + net_message.cursize = LittleLong (net_message.cursize); + // Con_Printf("read: %ld bytes\n", net_message.cursize); + if (net_message.cursize > MAX_MSGLEN) +// Sys_Error ("Demo message > MAX_MSGLEN"); + Host_EndGame ("Demo message > MAX_MSGLEN"); + r = Qread (cls.demofile, net_message.data, net_message.cursize); + if (r != net_message.cursize) { + CL_StopPlayback (); + return 0; + } + break; + + case dem_set: + Qread (cls.demofile, &i, 4); + cls.netchan.outgoing_sequence = LittleLong (i); + Qread (cls.demofile, &i, 4); + cls.netchan.incoming_sequence = LittleLong (i); + break; + + default: + Con_Printf ("Corrupted demo.\n"); CL_StopPlayback (); return 0; - } - // byte order stuff - for (j = 0; j < 3; j++) - pcmd->angles[j] = LittleFloat(pcmd->angles[j]); - pcmd->forwardmove = LittleShort(pcmd->forwardmove); - pcmd->sidemove = LittleShort(pcmd->sidemove); - pcmd->upmove = LittleShort(pcmd->upmove); - cl.frames[i].senttime = demotime; - cl.frames[i].receivedtime = -1; // we haven't gotten a reply yet - cls.netchan.outgoing_sequence++; - for (i=0 ; i<3 ; i++) - { - Qread (cls.demofile, &f, 4); - cl.viewangles[i] = LittleFloat (f); - } - break; - - case dem_read: - // get the next message - Qread (cls.demofile, &net_message.cursize, 4); - net_message.cursize = LittleLong (net_message.cursize); - //Con_Printf("read: %ld bytes\n", net_message.cursize); - if (net_message.cursize > MAX_MSGLEN) -// Sys_Error ("Demo message > MAX_MSGLEN"); - Host_EndGame ("Demo message > MAX_MSGLEN"); - r = Qread (cls.demofile, net_message.data, net_message.cursize); - if (r != net_message.cursize) - { - CL_StopPlayback (); - return 0; - } - break; - - case dem_set : - Qread (cls.demofile, &i, 4); - cls.netchan.outgoing_sequence = LittleLong(i); - Qread (cls.demofile, &i, 4); - cls.netchan.incoming_sequence = LittleLong(i); - break; - - default : - Con_Printf("Corrupted demo.\n"); - CL_StopPlayback (); - return 0; } return 1; @@ -282,16 +284,17 @@ CL_GetMessage Handles recording and playback of demos, on top of NET_ code ==================== */ -qboolean CL_GetMessage (void) +qboolean +CL_GetMessage (void) { - if (cls.demoplayback) + if (cls.demoplayback) return CL_GetDemoMessage (); if (!NET_GetPacket ()) return false; CL_WriteDemoMessage (&net_message); - + return true; } @@ -303,14 +306,13 @@ CL_Stop_f stop recording a demo ==================== */ -void CL_Stop_f (void) +void +CL_Stop_f (void) { - if (!cls.demorecording) - { + if (!cls.demorecording) { Con_Printf ("Not recording a demo.\n"); return; } - // write a disconnect message to the demo file SZ_Clear (&net_message); MSG_WriteLong (&net_message, -1); // -1 sequence means out of band @@ -333,28 +335,29 @@ CL_WriteDemoMessage Dumps the current net message, prefixed by the length and view angles ==================== */ -void CL_WriteRecordDemoMessage (sizebuf_t *msg, int seq) +void +CL_WriteRecordDemoMessage (sizebuf_t *msg, int seq) { - int len; - int i; - float fl; - byte c; + int len; + int i; + float fl; + byte c; //Con_Printf("write: %ld bytes, %4.4f\n", msg->cursize, realtime); if (!cls.demorecording) return; - fl = LittleFloat((float)realtime); - Qwrite (cls.demofile, &fl, sizeof(fl)); + fl = LittleFloat ((float) realtime); + Qwrite (cls.demofile, &fl, sizeof (fl)); c = dem_read; - Qwrite (cls.demofile, &c, sizeof(c)); + Qwrite (cls.demofile, &c, sizeof (c)); len = LittleLong (msg->cursize + 8); Qwrite (cls.demofile, &len, 4); - i = LittleLong(seq); + i = LittleLong (seq); Qwrite (cls.demofile, &i, 4); Qwrite (cls.demofile, &i, 4); @@ -364,26 +367,27 @@ void CL_WriteRecordDemoMessage (sizebuf_t *msg, int seq) } -void CL_WriteSetDemoMessage (void) +void +CL_WriteSetDemoMessage (void) { - int len; - float fl; - byte c; + int len; + float fl; + byte c; //Con_Printf("write: %ld bytes, %4.4f\n", msg->cursize, realtime); if (!cls.demorecording) return; - fl = LittleFloat((float)realtime); - Qwrite (cls.demofile, &fl, sizeof(fl)); + fl = LittleFloat ((float) realtime); + Qwrite (cls.demofile, &fl, sizeof (fl)); c = dem_set; - Qwrite (cls.demofile, &c, sizeof(c)); + Qwrite (cls.demofile, &c, sizeof (c)); - len = LittleLong(cls.netchan.outgoing_sequence); + len = LittleLong (cls.netchan.outgoing_sequence); Qwrite (cls.demofile, &len, 4); - len = LittleLong(cls.netchan.incoming_sequence); + len = LittleLong (cls.netchan.incoming_sequence); Qwrite (cls.demofile, &len, 4); Qflush (cls.demofile); @@ -399,23 +403,23 @@ CL_Record_f record ==================== */ -void CL_Record_f (void) +void +CL_Record_f (void) { - int c; - char name[MAX_OSPATH]; - sizebuf_t buf; - char buf_data[MAX_MSGLEN]; - int n, i, j; - char *s; - entity_t *ent; + int c; + char name[MAX_OSPATH]; + sizebuf_t buf; + char buf_data[MAX_MSGLEN]; + int n, i, j; + char *s; + entity_t *ent; entity_state_t *es, blankes; player_info_t *player; - extern char gamedirfile[]; - int seq = 1; + extern char gamedirfile[]; + int seq = 1; - c = Cmd_Argc(); - if (c != 2) - { + c = Cmd_Argc (); + if (c != 2) { Con_Printf ("record \n"); return; } @@ -426,9 +430,9 @@ void CL_Record_f (void) } if (cls.demorecording) - CL_Stop_f(); - - snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + CL_Stop_f (); + + snprintf (name, sizeof (name), "%s/%s", com_gamedir, Cmd_Argv (1)); // // open the demo file @@ -436,8 +440,7 @@ void CL_Record_f (void) COM_DefaultExtension (name, ".qwd"); cls.demofile = Qopen (name, "wb"); - if (!cls.demofile) - { + if (!cls.demofile) { Con_Printf ("ERROR: couldn't open.\n"); return; } @@ -449,9 +452,9 @@ void CL_Record_f (void) // serverdata // send the info about the new client to all connected clients - memset(&buf, 0, sizeof(buf)); + memset (&buf, 0, sizeof (buf)); buf.data = buf_data; - buf.maxsize = sizeof(buf_data); + buf.maxsize = sizeof (buf_data); // send the serverdata MSG_WriteByte (&buf, svc_serverdata); @@ -468,81 +471,79 @@ void CL_Record_f (void) MSG_WriteString (&buf, cl.levelname); // send the movevars - MSG_WriteFloat(&buf, movevars.gravity); - MSG_WriteFloat(&buf, movevars.stopspeed); - MSG_WriteFloat(&buf, movevars.maxspeed); - MSG_WriteFloat(&buf, movevars.spectatormaxspeed); - MSG_WriteFloat(&buf, movevars.accelerate); - MSG_WriteFloat(&buf, movevars.airaccelerate); - MSG_WriteFloat(&buf, movevars.wateraccelerate); - MSG_WriteFloat(&buf, movevars.friction); - MSG_WriteFloat(&buf, movevars.waterfriction); - MSG_WriteFloat(&buf, movevars.entgravity); + MSG_WriteFloat (&buf, movevars.gravity); + MSG_WriteFloat (&buf, movevars.stopspeed); + MSG_WriteFloat (&buf, movevars.maxspeed); + MSG_WriteFloat (&buf, movevars.spectatormaxspeed); + MSG_WriteFloat (&buf, movevars.accelerate); + MSG_WriteFloat (&buf, movevars.airaccelerate); + MSG_WriteFloat (&buf, movevars.wateraccelerate); + MSG_WriteFloat (&buf, movevars.friction); + MSG_WriteFloat (&buf, movevars.waterfriction); + MSG_WriteFloat (&buf, movevars.entgravity); // send music MSG_WriteByte (&buf, svc_cdtrack); - MSG_WriteByte (&buf, 0); // none in demos + MSG_WriteByte (&buf, 0); // none in demos // send server info string MSG_WriteByte (&buf, svc_stufftext); - MSG_WriteString (&buf, va("fullserverinfo \"%s\"\n", cl.serverinfo) ); + MSG_WriteString (&buf, va ("fullserverinfo \"%s\"\n", cl.serverinfo)); // flush packet CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); // soundlist MSG_WriteByte (&buf, svc_soundlist); MSG_WriteByte (&buf, 0); n = 0; - s = cl.sound_name[n+1]; + s = cl.sound_name[n + 1]; while (*s) { MSG_WriteString (&buf, s); - if (buf.cursize > MAX_MSGLEN/2) { + if (buf.cursize > MAX_MSGLEN / 2) { MSG_WriteByte (&buf, 0); MSG_WriteByte (&buf, n); CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); MSG_WriteByte (&buf, svc_soundlist); MSG_WriteByte (&buf, n + 1); } n++; - s = cl.sound_name[n+1]; + s = cl.sound_name[n + 1]; } if (buf.cursize) { MSG_WriteByte (&buf, 0); MSG_WriteByte (&buf, 0); CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } - // modellist MSG_WriteByte (&buf, svc_modellist); MSG_WriteByte (&buf, 0); n = 0; - s = cl.model_name[n+1]; + s = cl.model_name[n + 1]; while (*s) { MSG_WriteString (&buf, s); - if (buf.cursize > MAX_MSGLEN/2) { + if (buf.cursize > MAX_MSGLEN / 2) { MSG_WriteByte (&buf, 0); MSG_WriteByte (&buf, n); CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); MSG_WriteByte (&buf, svc_modellist); MSG_WriteByte (&buf, n + 1); } n++; - s = cl.model_name[n+1]; + s = cl.model_name[n + 1]; } if (buf.cursize) { MSG_WriteByte (&buf, 0); MSG_WriteByte (&buf, 0); CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } - // spawnstatic for (i = 0; i < cl.num_statics; i++) { @@ -561,15 +562,14 @@ void CL_Record_f (void) MSG_WriteByte (&buf, ent->frame); MSG_WriteByte (&buf, 0); MSG_WriteByte (&buf, ent->skinnum); - for (j=0 ; j<3 ; j++) - { + for (j = 0; j < 3; j++) { MSG_WriteCoord (&buf, ent->origin[j]); MSG_WriteAngle (&buf, ent->angles[j]); } - if (buf.cursize > MAX_MSGLEN/2) { + if (buf.cursize > MAX_MSGLEN / 2) { CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } } @@ -578,39 +578,37 @@ void CL_Record_f (void) // baselines - memset(&blankes, 0, sizeof(blankes)); + memset (&blankes, 0, sizeof (blankes)); for (i = 0; i < MAX_EDICTS; i++) { es = cl_baselines + i; - if (memcmp(es, &blankes, sizeof(blankes))) { - MSG_WriteByte (&buf,svc_spawnbaseline); + if (memcmp (es, &blankes, sizeof (blankes))) { + MSG_WriteByte (&buf, svc_spawnbaseline); MSG_WriteShort (&buf, i); MSG_WriteByte (&buf, es->modelindex); MSG_WriteByte (&buf, es->frame); MSG_WriteByte (&buf, es->colormap); MSG_WriteByte (&buf, es->skinnum); - for (j=0 ; j<3 ; j++) - { - MSG_WriteCoord(&buf, es->origin[j]); - MSG_WriteAngle(&buf, es->angles[j]); + for (j = 0; j < 3; j++) { + MSG_WriteCoord (&buf, es->origin[j]); + MSG_WriteAngle (&buf, es->angles[j]); } - if (buf.cursize > MAX_MSGLEN/2) { + if (buf.cursize > MAX_MSGLEN / 2) { CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } } } MSG_WriteByte (&buf, svc_stufftext); - MSG_WriteString (&buf, va("cmd spawn %i 0\n", cl.servercount) ); + MSG_WriteString (&buf, va ("cmd spawn %i 0\n", cl.servercount)); if (buf.cursize) { CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } - // send current status of all other players for (i = 0; i < MAX_CLIENTS; i++) { @@ -619,15 +617,15 @@ void CL_Record_f (void) MSG_WriteByte (&buf, svc_updatefrags); MSG_WriteByte (&buf, i); MSG_WriteShort (&buf, player->frags); - + MSG_WriteByte (&buf, svc_updateping); MSG_WriteByte (&buf, i); MSG_WriteShort (&buf, player->ping); - + MSG_WriteByte (&buf, svc_updatepl); MSG_WriteByte (&buf, i); MSG_WriteByte (&buf, player->pl); - + MSG_WriteByte (&buf, svc_updateentertime); MSG_WriteByte (&buf, i); MSG_WriteFloat (&buf, player->entertime); @@ -637,17 +635,16 @@ void CL_Record_f (void) MSG_WriteLong (&buf, player->userid); MSG_WriteString (&buf, player->userinfo); - if (buf.cursize > MAX_MSGLEN/2) { + if (buf.cursize > MAX_MSGLEN / 2) { CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } } - + // send all current light styles - for (i=0 ; i MAX_MSGLEN/2) { + if (buf.cursize > MAX_MSGLEN / 2) { CL_WriteRecordDemoMessage (&buf, seq++); - SZ_Clear (&buf); + SZ_Clear (&buf); } } @@ -678,11 +675,11 @@ void CL_Record_f (void) // get the client to check and download skins // when that is completed, a begin command will be issued MSG_WriteByte (&buf, svc_stufftext); - MSG_WriteString (&buf, va("skins\n") ); + MSG_WriteString (&buf, va ("skins\n")); CL_WriteRecordDemoMessage (&buf, seq++); - CL_WriteSetDemoMessage(); + CL_WriteSetDemoMessage (); // done } @@ -694,27 +691,27 @@ CL_ReRecord_f record ==================== */ -void CL_ReRecord_f (void) +void +CL_ReRecord_f (void) { - int c; - char name[MAX_OSPATH]; + int c; + char name[MAX_OSPATH]; - c = Cmd_Argc(); - if (c != 2) - { + c = Cmd_Argc (); + if (c != 2) { Con_Printf ("rerecord \n"); return; } if (!*cls.servername) { - Con_Printf("No server to reconnect to...\n"); + Con_Printf ("No server to reconnect to...\n"); return; } if (cls.demorecording) - CL_Stop_f(); - - snprintf (name, sizeof(name), "%s/%s", com_gamedir, Cmd_Argv(1)); + CL_Stop_f (); + + snprintf (name, sizeof (name), "%s/%s", com_gamedir, Cmd_Argv (1)); // // open the demo file @@ -722,8 +719,7 @@ void CL_ReRecord_f (void) COM_DefaultExtension (name, ".qwd"); cls.demofile = Qopen (name, "wb"); - if (!cls.demofile) - { + if (!cls.demofile) { Con_Printf ("ERROR: couldn't open.\n"); return; } @@ -731,8 +727,8 @@ void CL_ReRecord_f (void) Con_Printf ("recording to %s.\n", name); cls.demorecording = true; - CL_Disconnect(); - CL_BeginServerConnect(); + CL_Disconnect (); + CL_BeginServerConnect (); } @@ -743,33 +739,31 @@ CL_PlayDemo_f play [demoname] ==================== */ -void CL_PlayDemo_f (void) +void +CL_PlayDemo_f (void) { - char name[MAX_OSPATH]; + char name[MAX_OSPATH]; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("play : plays a demo\n"); return; } - // // disconnect from server // CL_Disconnect (); - + // // open the demo file // - strcpy (name, Cmd_Argv(1)); + strcpy (name, Cmd_Argv (1)); COM_DefaultExtension (name, ".qwd"); Con_Printf ("Playing demo from %s.\n", name); COM_FOpenFile (name, &cls.demofile); - if (!cls.demofile) - { + if (!cls.demofile) { Con_Printf ("ERROR: couldn't open.\n"); - cls.demonum = -1; // stop demo loop + cls.demonum = -1; // stop demo loop return; } @@ -785,19 +779,21 @@ CL_FinishTimeDemo ==================== */ -void CL_FinishTimeDemo (void) +void +CL_FinishTimeDemo (void) { - int frames; - float time; - + int frames; + float time; + cls.timedemo = false; - + // the first frame didn't count frames = (host_framecount - cls.td_startframe) - 1; - time = Sys_DoubleTime() - cls.td_starttime; + time = Sys_DoubleTime () - cls.td_starttime; if (!time) time = 1; - Con_Printf ("%i frames %5.1f seconds %5.1f fps\n", frames, time, frames/time); + Con_Printf ("%i frames %5.1f seconds %5.1f fps\n", frames, time, + frames / time); } /* @@ -807,25 +803,24 @@ CL_TimeDemo_f timedemo [demoname] ==================== */ -void CL_TimeDemo_f (void) +void +CL_TimeDemo_f (void) { - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("timedemo : gets demo speeds\n"); return; } CL_PlayDemo_f (); - + if (cls.state != ca_demostart) return; // cls.td_starttime will be grabbed at the second frame of the demo, so // all the loading time doesn't get counted - + cls.timedemo = true; cls.td_starttime = 0; cls.td_startframe = host_framecount; - cls.td_lastframe = -1; // get a new message this frame + cls.td_lastframe = -1; // get a new message this frame } - diff --git a/source/cl_ents.c b/source/cl_ents.c index 07a4f37..dc62e2d 100644 --- a/source/cl_ents.c +++ b/source/cl_ents.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -52,16 +52,16 @@ #include "cl_ents.h" #include "cl_input.h" -extern cvar_t *cl_predict_players; -extern cvar_t *cl_predict_players2; -extern cvar_t *cl_solid_players; +extern cvar_t *cl_predict_players; +extern cvar_t *cl_predict_players2; +extern cvar_t *cl_solid_players; -extern cvar_t *gl_flashblend; +extern cvar_t *gl_flashblend; static struct predicted_player { - int flags; - qboolean active; - vec3_t origin; // predicted origin + int flags; + qboolean active; + vec3_t origin; // predicted origin } predicted_players[MAX_CLIENTS]; //============================================================ @@ -72,34 +72,29 @@ CL_AllocDlight =============== */ -dlight_t *CL_AllocDlight (int key) +dlight_t * +CL_AllocDlight (int key) { - int i; - dlight_t *dl; + int i; + dlight_t *dl; // first look for an exact key match - if (key) - { + if (key) { dl = cl_dlights; - for (i=0 ; ikey == key) - { - memset (dl, 0, sizeof(*dl)); + for (i = 0; i < MAX_DLIGHTS; i++, dl++) { + if (dl->key == key) { + memset (dl, 0, sizeof (*dl)); dl->key = key; dl->color = dl->_color; return dl; } } } - // then look for anything else dl = cl_dlights; - for (i=0 ; idie < cl.time) - { - memset (dl, 0, sizeof(*dl)); + for (i = 0; i < MAX_DLIGHTS; i++, dl++) { + if (dl->die < cl.time) { + memset (dl, 0, sizeof (*dl)); dl->key = key; dl->color = dl->_color; return dl; @@ -107,7 +102,7 @@ dlight_t *CL_AllocDlight (int key) } dl = &cl_dlights[0]; - memset (dl, 0, sizeof(*dl)); + memset (dl, 0, sizeof (*dl)); dl->key = key; dl->color = dl->_color; return dl; @@ -118,10 +113,11 @@ dlight_t *CL_AllocDlight (int key) CL_NewDlight =============== */ -void CL_NewDlight (int key, float x, float y, float z, float radius, float time, - int type) +void +CL_NewDlight (int key, float x, float y, float z, float radius, float time, + int type) { - dlight_t *dl; + dlight_t *dl; dl = CL_AllocDlight (key); dl->origin[0] = x; @@ -129,25 +125,24 @@ void CL_NewDlight (int key, float x, float y, float z, float radius, float time, dl->origin[2] = z; dl->radius = radius; dl->die = cl.time + time; - switch (type) - { + switch (type) { default: case 0: dl->color[0] = 0.4; dl->color[1] = 0.2; dl->color[2] = 0.05; break; - case 1: // blue + case 1: // blue dl->color[0] = 0.05; dl->color[1] = 0.05; dl->color[2] = 0.5; break; - case 2: // red + case 2: // red dl->color[0] = 0.5; dl->color[1] = 0.05; dl->color[2] = 0.05; break; - case 3: // purple + case 3: // purple dl->color[0] = 0.5; dl->color[1] = 0.05; dl->color[2] = 0.5; @@ -162,18 +157,18 @@ CL_DecayLights =============== */ -void CL_DecayLights (void) +void +CL_DecayLights (void) { - int i; - dlight_t *dl; + int i; + dlight_t *dl; dl = cl_dlights; - for (i=0 ; idie < cl.time || !dl->radius) continue; - - dl->radius -= host_frametime*dl->decay; + + dl->radius -= host_frametime * dl->decay; if (dl->radius < 0) dl->radius = 0; } @@ -195,10 +190,11 @@ CL_ParseDelta Can go from either a baseline or a previous packet_entity ================== */ -int bitcounts[32]; /// just for protocol profiling -void CL_ParseDelta (entity_state_t *from, entity_state_t *to, int bits) +int bitcounts[32]; // / just for protocol profiling +void +CL_ParseDelta (entity_state_t *from, entity_state_t *to, int bits) { - int i; + int i; // set everything to the state we are delta'ing from *to = *from; @@ -206,96 +202,89 @@ void CL_ParseDelta (entity_state_t *from, entity_state_t *to, int bits) to->number = bits & 511; bits &= ~511; - if (bits & U_MOREBITS) - { // read in the low order bits + if (bits & U_MOREBITS) { // read in the low order bits i = MSG_ReadByte (); bits |= i; } - // count the bits for net profiling // for (i=0 ; i<16 ; i++) // if (bits&(1<flags = bits; - + if (bits & U_MODEL) to->modelindex = MSG_ReadByte (); - + if (bits & U_FRAME) to->frame = MSG_ReadByte (); if (bits & U_COLORMAP) - to->colormap = MSG_ReadByte(); + to->colormap = MSG_ReadByte (); if (bits & U_SKIN) - to->skinnum = MSG_ReadByte(); + to->skinnum = MSG_ReadByte (); if (bits & U_EFFECTS) - to->effects = MSG_ReadByte(); + to->effects = MSG_ReadByte (); if (bits & U_ORIGIN1) to->origin[0] = MSG_ReadCoord (); - + if (bits & U_ANGLE1) - to->angles[0] = MSG_ReadAngle(); + to->angles[0] = MSG_ReadAngle (); if (bits & U_ORIGIN2) to->origin[1] = MSG_ReadCoord (); - + if (bits & U_ANGLE2) - to->angles[1] = MSG_ReadAngle(); + to->angles[1] = MSG_ReadAngle (); if (bits & U_ORIGIN3) to->origin[2] = MSG_ReadCoord (); - - if (bits & U_ANGLE3) - to->angles[2] = MSG_ReadAngle(); - // LordHavoc: Endy neglected to mark this as being part of the QSG version 2 stuff... - // rearranged it and implemented missing effects + if (bits & U_ANGLE3) + to->angles[2] = MSG_ReadAngle (); + + // LordHavoc: Endy neglected to mark this as being part of the QSG + // version 2 stuff... + // rearranged it and implemented missing effects // Ender (QSG - Begin) if (bits & U_ALPHA) - to->alpha = MSG_ReadByte(); + to->alpha = MSG_ReadByte (); if (bits & U_SCALE) - to->scale = MSG_ReadByte(); + to->scale = MSG_ReadByte (); if (bits & U_EFFECTS2) - to->effects = (to->effects & 0xFF) | (MSG_ReadByte() << 8); + to->effects = (to->effects & 0xFF) | (MSG_ReadByte () << 8); if (bits & U_GLOWSIZE) - to->glowsize = MSG_ReadByte(); + to->glowsize = MSG_ReadByte (); if (bits & U_GLOWCOLOR) - to->glowcolor = MSG_ReadByte(); + to->glowcolor = MSG_ReadByte (); if (bits & U_COLORMOD) - to->colormod = MSG_ReadByte(); + to->colormod = MSG_ReadByte (); if (bits & U_FRAME2) - to->frame = (to->frame & 0xFF) | (MSG_ReadByte() << 8); + to->frame = (to->frame & 0xFF) | (MSG_ReadByte () << 8); // Ender (QSG - End) - if (bits & U_SOLID) - { + if (bits & U_SOLID) { // FIXME } - /* - if ((!to->alpha) || (!to->colormod)) - Con_Printf("fa: %d, fc: %d, ta: %d, tc: %d\n", - from->alpha, from->colormod, to->alpha, to->colormod); - */ - /* - if ((!ent->alpha) || (!ent->colormod[0]) || (!ent->colormod[1]) || - (!ent->colormod[2])) { - Con_Printf("ea: %f, ec0: %f, ec1: %f ec2: %f, sa: %d, sc: %d\n", - ent->alpha, ent->colormod[0], ent->colormod[1], - ent->colormod[2], s1->alpha, s1->colormod); - } - */ + /* + if ((!to->alpha) || (!to->colormod)) Con_Printf("fa: %d, fc: %d, ta: + %d, tc: %d\n", from->alpha, from->colormod, to->alpha, to->colormod); */ + /* + if ((!ent->alpha) || (!ent->colormod[0]) || (!ent->colormod[1]) || + (!ent->colormod[2])) { Con_Printf("ea: %f, ec0: %f, ec1: %f ec2: %f, + sa: %d, sc: %d\n", ent->alpha, ent->colormod[0], ent->colormod[1], + ent->colormod[2], s1->alpha, s1->colormod); } */ } @@ -304,30 +293,29 @@ void CL_ParseDelta (entity_state_t *from, entity_state_t *to, int bits) FlushEntityPacket ================= */ -void FlushEntityPacket (void) +void +FlushEntityPacket (void) { - int word; - entity_state_t olde, newe; + int word; + entity_state_t olde, newe; Con_DPrintf ("FlushEntityPacket\n"); - memset (&olde, 0, sizeof(olde)); + memset (&olde, 0, sizeof (olde)); - cl.validsequence = 0; // can't render a frame - cl.frames[cls.netchan.incoming_sequence&UPDATE_MASK].invalid = true; + cl.validsequence = 0; // can't render a frame + cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK].invalid = true; // read it all, but ignore it - while (1) - { - word = (unsigned short)MSG_ReadShort (); - if (msg_badread) - { // something didn't parse right... + while (1) { + word = (unsigned short) MSG_ReadShort (); + if (msg_badread) { // something didn't parse right... Host_EndGame ("msg_badread in packetentities"); return; } if (!word) - break; // done + break; // done CL_ParseDelta (&olde, &newe, word); } @@ -341,44 +329,47 @@ An svc_packetentities has just been parsed, deal with the rest of the data stream. ================== */ -void CL_ParsePacketEntities (qboolean delta) +void +CL_ParsePacketEntities (qboolean delta) { - int oldpacket, newpacket; - packet_entities_t *oldp, *newp, dummy; - int oldindex, newindex; - int word, newnum, oldnum; - qboolean full; - byte from; + int oldpacket, newpacket; + packet_entities_t *oldp, *newp, dummy; + int oldindex, newindex; + int word, newnum, oldnum; + qboolean full; + byte from; - newpacket = cls.netchan.incoming_sequence&UPDATE_MASK; + newpacket = cls.netchan.incoming_sequence & UPDATE_MASK; newp = &cl.frames[newpacket].packet_entities; cl.frames[newpacket].invalid = false; - if (delta) - { + if (delta) { from = MSG_ReadByte (); oldpacket = cl.frames[newpacket].delta_sequence; - if ( (from&UPDATE_MASK) != (oldpacket&UPDATE_MASK) ) + if ((from & UPDATE_MASK) != (oldpacket & UPDATE_MASK)) Con_DPrintf ("WARNING: from mismatch\n"); - } - else + } else oldpacket = -1; full = false; - if (oldpacket != -1) - { - if (cls.netchan.outgoing_sequence - oldpacket >= UPDATE_BACKUP-1) - { // we can't use this, it is too old + if (oldpacket != -1) { + if (cls.netchan.outgoing_sequence - oldpacket >= UPDATE_BACKUP - 1) { // we + // can't + // use + // this, + // it + // is + // too + // old FlushEntityPacket (); return; } cl.validsequence = cls.netchan.incoming_sequence; - oldp = &cl.frames[oldpacket&UPDATE_MASK].packet_entities; - } - else - { // this is a full update that we can start delta compressing from now + oldp = &cl.frames[oldpacket & UPDATE_MASK].packet_entities; + } else { // this is a full update that we can + // start delta compressing from now oldp = &dummy; dummy.num_entities = 0; cl.validsequence = cls.netchan.incoming_sequence; @@ -389,57 +380,55 @@ void CL_ParsePacketEntities (qboolean delta) newindex = 0; newp->num_entities = 0; - while (1) - { - word = (unsigned short)MSG_ReadShort (); - if (msg_badread) - { // something didn't parse right... + while (1) { + word = (unsigned short) MSG_ReadShort (); + if (msg_badread) { // something didn't parse right... Host_EndGame ("msg_badread in packetentities"); return; } - if (!word) - { - while (oldindex < oldp->num_entities) - { // copy all the rest of the entities from the old packet + if (!word) { + while (oldindex < oldp->num_entities) { // copy all the rest of + // the entities from the + // old packet //Con_Printf ("copy %i\n", oldp->entities[oldindex].number); if (newindex >= MAX_PACKET_ENTITIES) - Host_EndGame ("CL_ParsePacketEntities: newindex == MAX_PACKET_ENTITIES"); + Host_EndGame + ("CL_ParsePacketEntities: newindex == MAX_PACKET_ENTITIES"); newp->entities[newindex] = oldp->entities[oldindex]; newindex++; oldindex++; } break; } - newnum = word&511; - oldnum = oldindex >= oldp->num_entities ? 9999 : oldp->entities[oldindex].number; + newnum = word & 511; + oldnum = + oldindex >= + oldp->num_entities ? 9999 : oldp->entities[oldindex].number; - while (newnum > oldnum) - { - if (full) - { + while (newnum > oldnum) { + if (full) { Con_Printf ("WARNING: oldcopy on full update"); FlushEntityPacket (); return; } - //Con_Printf ("copy %i\n", oldnum); // copy one of the old entities over to the new packet unchanged if (newindex >= MAX_PACKET_ENTITIES) - Host_EndGame ("CL_ParsePacketEntities: newindex == MAX_PACKET_ENTITIES"); + Host_EndGame + ("CL_ParsePacketEntities: newindex == MAX_PACKET_ENTITIES"); newp->entities[newindex] = oldp->entities[oldindex]; newindex++; oldindex++; - oldnum = oldindex >= oldp->num_entities ? 9999 : oldp->entities[oldindex].number; + oldnum = + oldindex >= + oldp->num_entities ? 9999 : oldp->entities[oldindex].number; } - if (newnum < oldnum) - { // new from baseline + if (newnum < oldnum) { // new from baseline //Con_Printf ("baseline %i\n", newnum); - if (word & U_REMOVE) - { - if (full) - { + if (word & U_REMOVE) { + if (full) { cl.validsequence = 0; Con_Printf ("WARNING: U_REMOVE on full update\n"); FlushEntityPacket (); @@ -448,26 +437,26 @@ void CL_ParsePacketEntities (qboolean delta) continue; } if (newindex >= MAX_PACKET_ENTITIES) - Host_EndGame ("CL_ParsePacketEntities: newindex == MAX_PACKET_ENTITIES"); - CL_ParseDelta (&cl_baselines[newnum], &newp->entities[newindex], word); + Host_EndGame + ("CL_ParsePacketEntities: newindex == MAX_PACKET_ENTITIES"); + CL_ParseDelta (&cl_baselines[newnum], &newp->entities[newindex], + word); newindex++; continue; } - if (newnum == oldnum) - { // delta from previous - if (full) - { + if (newnum == oldnum) { // delta from previous + if (full) { cl.validsequence = 0; Con_Printf ("WARNING: delta on full update"); } - if (word & U_REMOVE) - { + if (word & U_REMOVE) { oldindex++; continue; } //Con_Printf ("delta %i\n",newnum); - CL_ParseDelta (&oldp->entities[oldindex], &newp->entities[newindex], word); + CL_ParseDelta (&oldp->entities[oldindex], &newp->entities[newindex], + word); newindex++; oldindex++; } @@ -484,43 +473,49 @@ CL_LinkPacketEntities =============== */ -void CL_LinkPacketEntities (void) +void +CL_LinkPacketEntities (void) { - entity_t *ent; - packet_entities_t *pack; - entity_state_t *s1, *s2; - float f; - model_t *model; - vec3_t old_origin; - float autorotate; - int i; - int pnum; - dlight_t *dl; - extern int cl_playerindex; - extern int cl_h_playerindex, cl_gib1index, cl_gib2index, cl_gib3index; + entity_t *ent; + packet_entities_t *pack; + entity_state_t *s1, *s2; + float f; + model_t *model; + vec3_t old_origin; + float autorotate; + int i; + int pnum; + dlight_t *dl; + extern int cl_playerindex; + extern int cl_h_playerindex, cl_gib1index, cl_gib2index, cl_gib3index; - pack = &cl.frames[cls.netchan.incoming_sequence&UPDATE_MASK].packet_entities; + pack = + &cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK].packet_entities; - autorotate = anglemod(100*cl.time); + autorotate = anglemod (100 * cl.time); - f = 0; // FIXME: no interpolation right now + f = 0; // FIXME: no interpolation right now - for (pnum=0 ; pnumnum_entities ; pnum++) - { + for (pnum = 0; pnum < pack->num_entities; pnum++) { s1 = &pack->entities[pnum]; - s2 = s1; // FIXME: no interpolation right now + s2 = s1; // FIXME: no interpolation right now // spawn light flashes, even ones coming from invisible objects if ((s1->effects & (EF_BLUE | EF_RED)) == (EF_BLUE | EF_RED)) - CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], s1->origin[2], 200 + (rand()&31), 0.1, 3); + CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], + s1->origin[2], 200 + (rand () & 31), 0.1, 3); else if (s1->effects & EF_BLUE) - CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], s1->origin[2], 200 + (rand()&31), 0.1, 1); + CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], + s1->origin[2], 200 + (rand () & 31), 0.1, 1); else if (s1->effects & EF_RED) - CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], s1->origin[2], 200 + (rand()&31), 0.1, 2); + CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], + s1->origin[2], 200 + (rand () & 31), 0.1, 2); else if (s1->effects & EF_BRIGHTLIGHT) - CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], s1->origin[2] + 16, 400 + (rand()&31), 0.1, 0); + CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], + s1->origin[2] + 16, 400 + (rand () & 31), 0.1, 0); else if (s1->effects & EF_DIMLIGHT) - CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], s1->origin[2], 200 + (rand()&31), 0.1, 0); + CL_NewDlight (s1->number, s1->origin[0], s1->origin[1], + s1->origin[2], 200 + (rand () & 31), 0.1, 0); // if set to invisible, skip if (!s1->modelindex) @@ -528,32 +523,31 @@ void CL_LinkPacketEntities (void) // Hack hack hack if (cl_deadbodyfilter->int_val && s1->modelindex == cl_playerindex - && ( (i=s1->frame)==49 || i==60 || i==69 || i==84 || i==93 || i==102) ) + && ((i = s1->frame) == 49 || i == 60 || i == 69 || i == 84 + || i == 93 || i == 102)) continue; if (cl_gibfilter->int_val && - (s1->modelindex == cl_h_playerindex || s1->modelindex == cl_gib1index - || s1->modelindex == cl_gib2index || s1->modelindex == cl_gib3index)) + (s1->modelindex == cl_h_playerindex + || s1->modelindex == cl_gib1index || s1->modelindex == cl_gib2index + || s1->modelindex == cl_gib3index)) continue; // create a new entity if (cl_numvisedicts == MAX_VISEDICTS) - break; // object list is full + break; // object list is full ent = &cl_visedicts[cl_numvisedicts]; cl_numvisedicts++; ent->keynum = s1->number; ent->model = model = cl.model_precache[s1->modelindex]; - + // set colormap - if (s1->colormap && (s1->colormap < MAX_CLIENTS) - && !strcmp(ent->model->name,"progs/player.mdl") ) - { - ent->colormap = cl.players[s1->colormap-1].translations; - ent->scoreboard = &cl.players[s1->colormap-1]; - } - else - { + if (s1->colormap && (s1->colormap < MAX_CLIENTS) + && !strcmp (ent->model->name, "progs/player.mdl")) { + ent->colormap = cl.players[s1->colormap - 1].translations; + ent->scoreboard = &cl.players[s1->colormap - 1]; + } else { ent->colormap = vid.colormap; ent->scoreboard = NULL; } @@ -561,53 +555,50 @@ void CL_LinkPacketEntities (void) // LordHavoc: cleaned up Endy's coding style, and fixed Endy's bugs // Ender: Extend (Colormod) [QSG - Begin] - // N.B: All messy code below is the sole fault of LordHavoc and - // his futile attempts to save bandwidth. :) - // - ent->glowsize = s1->glowsize < 128 ? s1->glowsize * 8.0 : (s1->glowsize - 256) * 8.0; -// if (s1->glowsize != 0) -// Con_Printf("glowsize: %d\n", s1->glowsize); - ent->glowcolor = s1->glowcolor; -// if (s1->glowcolor != 254) -// Con_Printf("glowcolor: %d\n", s1->glowcolor); - ent->alpha = s1->alpha / 255.0; -// if (s1->alpha != 255) -// Con_Printf("alpha: %d\n", s1->alpha); - ent->scale = s1->scale / 16.0; -// if (s1->scale != 16) -// Con_Printf("scale: %d\n", s1->scale); + // N.B: All messy code below is the sole fault of LordHavoc and + // his futile attempts to save bandwidth. :) + // + ent->glowsize = + s1->glowsize < + 128 ? s1->glowsize * 8.0 : (s1->glowsize - 256) * 8.0; +// if (s1->glowsize != 0) +// Con_Printf("glowsize: %d\n", s1->glowsize); + ent->glowcolor = s1->glowcolor; +// if (s1->glowcolor != 254) +// Con_Printf("glowcolor: %d\n", s1->glowcolor); + ent->alpha = s1->alpha / 255.0; +// if (s1->alpha != 255) +// Con_Printf("alpha: %d\n", s1->alpha); + ent->scale = s1->scale / 16.0; +// if (s1->scale != 16) +// Con_Printf("scale: %d\n", s1->scale); if (s1->colormod == 255) ent->colormod[0] = ent->colormod[1] = ent->colormod[2] = 1; - else - { -// Con_Printf("colormod: %d\n", s1->colormod); + else { +// Con_Printf("colormod: %d\n", s1->colormod); ent->colormod[0] = (float) ((s1->colormod >> 5) & 7) * (1.0 / 7.0); ent->colormod[1] = (float) ((s1->colormod >> 2) & 7) * (1.0 / 7.0); ent->colormod[2] = (float) (s1->colormod & 3) * (1.0 / 3.0); } - // + // // Ender: Extend (Colormod) [QSG - End] - // set skin + // set skin ent->skinnum = s1->skinnum; - + // set frame ent->frame = s1->frame; // rotate binary objects locally - if (model->flags & EF_ROTATE) - { + if (model->flags & EF_ROTATE) { ent->angles[0] = 0; ent->angles[1] = autorotate; ent->angles[2] = 0; - } - else - { - float a1, a2; + } else { + float a1, a2; - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { a1 = s1->angles[i]; a2 = s2->angles[i]; if (a1 - a2 > 180) @@ -619,41 +610,37 @@ void CL_LinkPacketEntities (void) } // calculate origin - for (i=0 ; i<3 ; i++) - ent->origin[i] = s2->origin[i] + - f * (s1->origin[i] - s2->origin[i]); + for (i = 0; i < 3; i++) + ent->origin[i] = s2->origin[i] + + f * (s1->origin[i] - s2->origin[i]); // add automatic particle trails if (!model->flags) continue; // scan the old entity display list for a matching - for (i=0 ; ikeynum) - { + for (i = 0; i < cl_oldnumvisedicts; i++) { + if (cl_oldvisedicts[i].keynum == ent->keynum) { VectorCopy (cl_oldvisedicts[i].origin, old_origin); break; } } if (i == cl_oldnumvisedicts) - continue; // not in last message + continue; // not in last message - for (i=0 ; i<3 ; i++) - if ( abs(old_origin[i] - ent->origin[i]) > 128) - { // no trail if too far + for (i = 0; i < 3; i++) + if (abs (old_origin[i] - ent->origin[i]) > 128) { // no trail + // if too far VectorCopy (ent->origin, old_origin); break; } - if (model->flags & EF_ROCKET) - { + if (model->flags & EF_ROCKET) { R_RocketTrail (old_origin, ent->origin, 0, ent); dl = CL_AllocDlight (s1->number); VectorCopy (ent->origin, dl->origin); dl->radius = 200; dl->die = cl.time + 0.1; - } - else if (model->flags & EF_GRENADE) + } else if (model->flags & EF_GRENADE) R_RocketTrail (old_origin, ent->origin, 1, ent); else if (model->flags & EF_GIB) R_RocketTrail (old_origin, ent->origin, 2, ent); @@ -677,20 +664,20 @@ PROJECTILE PARSING / LINKING ========================================================================= */ -typedef struct -{ - int modelindex; - vec3_t origin; - vec3_t angles; +typedef struct { + int modelindex; + vec3_t origin; + vec3_t angles; } projectile_t; #define MAX_PROJECTILES 32 -projectile_t cl_projectiles[MAX_PROJECTILES]; -int cl_num_projectiles; +projectile_t cl_projectiles[MAX_PROJECTILES]; +int cl_num_projectiles; -extern int cl_spikeindex; +extern int cl_spikeindex; -void CL_ClearProjectiles (void) +void +CL_ClearProjectiles (void) { cl_num_projectiles = 0; } @@ -702,16 +689,16 @@ CL_ParseProjectiles Nails are passed as efficient temporary entities ===================== */ -void CL_ParseProjectiles (void) +void +CL_ParseProjectiles (void) { - int i, c, j; - byte bits[6]; - projectile_t *pr; + int i, c, j; + byte bits[6]; + projectile_t *pr; c = MSG_ReadByte (); - for (i=0 ; imodelindex = cl_spikeindex; - pr->origin[0] = ( ( bits[0] + ((bits[1]&15)<<8) ) <<1) - 4096; - pr->origin[1] = ( ( (bits[1]>>4) + (bits[2]<<4) ) <<1) - 4096; - pr->origin[2] = ( ( bits[3] + ((bits[4]&15)<<8) ) <<1) - 4096; - pr->angles[0] = 360*(bits[4]>>4)/16; - pr->angles[1] = 360*bits[5]/256; + pr->origin[0] = ((bits[0] + ((bits[1] & 15) << 8)) << 1) - 4096; + pr->origin[1] = (((bits[1] >> 4) + (bits[2] << 4)) << 1) - 4096; + pr->origin[2] = ((bits[3] + ((bits[4] & 15) << 8)) << 1) - 4096; + pr->angles[0] = 360 * (bits[4] >> 4) / 16; + pr->angles[1] = 360 * bits[5] / 256; } } @@ -735,20 +722,20 @@ CL_LinkProjectiles ============= */ -void CL_LinkProjectiles (void) +void +CL_LinkProjectiles (void) { - int i; - projectile_t *pr; - entity_t *ent; + int i; + projectile_t *pr; + entity_t *ent; - for (i=0, pr=cl_projectiles ; imodelindex < 1) continue; // grab an entity to fill in if (cl_numvisedicts == MAX_VISEDICTS) - break; // object list is full + break; // object list is full ent = &cl_visedicts[cl_numvisedicts]; cl_numvisedicts++; ent->keynum = 0; @@ -759,40 +746,42 @@ void CL_LinkProjectiles (void) ent->scoreboard = NULL; VectorCopy (pr->origin, ent->origin); VectorCopy (pr->angles, ent->angles); - // LordHavoc: Endy had neglected to do this as part of the QSG VERSION 2 stuff - ent->glowsize = 0; - ent->glowcolor = 254; - ent->alpha = 1; - ent->scale = 1; - ent->colormod[0] = ent->colormod[1] = ent->colormod[2] = 1; + // LordHavoc: Endy had neglected to do this as part of the QSG + // VERSION 2 stuff + ent->glowsize = 0; + ent->glowcolor = 254; + ent->alpha = 1; + ent->scale = 1; + ent->colormod[0] = ent->colormod[1] = ent->colormod[2] = 1; } } //======================================== -extern int cl_spikeindex, cl_playerindex, cl_flagindex; +extern int cl_spikeindex, cl_playerindex, cl_flagindex; -entity_t *CL_NewTempEntity (void); +entity_t *CL_NewTempEntity (void); /* =================== CL_ParsePlayerinfo =================== */ -extern int parsecountmod; +extern int parsecountmod; extern double parsecounttime; -void CL_ParsePlayerinfo (void) +void +CL_ParsePlayerinfo (void) { - int msec; - int flags; - player_info_t *info; - player_state_t *state; - int num; - int i; + int msec; + int flags; + player_info_t *info; + player_state_t *state; + int num; + int i; num = MSG_ReadByte (); if (num > MAX_CLIENTS) -// Sys_Error ("CL_ParsePlayerinfo: bad num"); +// Sys_Error ("CL_ParsePlayerinfo: bad num"); Host_EndGame ("CL_ParsePlayerinfo: bad num"); info = &cl.players[num]; @@ -811,21 +800,18 @@ void CL_ParsePlayerinfo (void) // the other player's last move was likely some time // before the packet was sent out, so accurately track // the exact time it was valid at - if (flags & PF_MSEC) - { + if (flags & PF_MSEC) { msec = MSG_ReadByte (); - state->state_time = parsecounttime - msec*0.001; - } - else + state->state_time = parsecounttime - msec * 0.001; + } else state->state_time = parsecounttime; if (flags & PF_COMMAND) MSG_ReadDeltaUsercmd (&nullcmd, &state->command); - for (i=0 ; i<3 ; i++) - { - if (flags & (PF_VELOCITY1<velocity[i] = MSG_ReadShort(); + for (i = 0; i < 3; i++) { + if (flags & (PF_VELOCITY1 << i)) + state->velocity[i] = MSG_ReadShort (); else state->velocity[i] = 0; } @@ -860,38 +846,55 @@ CL_AddFlagModels Called when the CTF flags are set ================ */ -void CL_AddFlagModels (entity_t *ent, int team) +void +CL_AddFlagModels (entity_t *ent, int team) { - int i; - float f; - vec3_t v_forward, v_right, v_up; - entity_t *newent; + int i; + float f; + vec3_t v_forward, v_right, v_up; + entity_t *newent; if (cl_flagindex == -1) return; f = 14; if (ent->frame >= 29 && ent->frame <= 40) { - if (ent->frame >= 29 && ent->frame <= 34) { //axpain - if (ent->frame == 29) f = f + 2; - else if (ent->frame == 30) f = f + 8; - else if (ent->frame == 31) f = f + 12; - else if (ent->frame == 32) f = f + 11; - else if (ent->frame == 33) f = f + 10; - else if (ent->frame == 34) f = f + 4; - } else if (ent->frame >= 35 && ent->frame <= 40) { // pain - if (ent->frame == 35) f = f + 2; - else if (ent->frame == 36) f = f + 10; - else if (ent->frame == 37) f = f + 10; - else if (ent->frame == 38) f = f + 8; - else if (ent->frame == 39) f = f + 4; - else if (ent->frame == 40) f = f + 2; + if (ent->frame >= 29 && ent->frame <= 34) { // axpain + if (ent->frame == 29) + f = f + 2; + else if (ent->frame == 30) + f = f + 8; + else if (ent->frame == 31) + f = f + 12; + else if (ent->frame == 32) + f = f + 11; + else if (ent->frame == 33) + f = f + 10; + else if (ent->frame == 34) + f = f + 4; + } else if (ent->frame >= 35 && ent->frame <= 40) { // pain + if (ent->frame == 35) + f = f + 2; + else if (ent->frame == 36) + f = f + 10; + else if (ent->frame == 37) + f = f + 10; + else if (ent->frame == 38) + f = f + 8; + else if (ent->frame == 39) + f = f + 4; + else if (ent->frame == 40) + f = f + 2; } } else if (ent->frame >= 103 && ent->frame <= 118) { - if (ent->frame >= 103 && ent->frame <= 104) f = f + 6; //nailattack - else if (ent->frame >= 105 && ent->frame <= 106) f = f + 6; //light - else if (ent->frame >= 107 && ent->frame <= 112) f = f + 7; //rocketattack - else if (ent->frame >= 112 && ent->frame <= 118) f = f + 7; //shotattack + if (ent->frame >= 103 && ent->frame <= 104) + f = f + 6; // nailattack + else if (ent->frame >= 105 && ent->frame <= 106) + f = f + 6; // light + else if (ent->frame >= 107 && ent->frame <= 112) + f = f + 7; // rocketattack + else if (ent->frame >= 112 && ent->frame <= 118) + f = f + 7; // shotattack } newent = CL_NewTempEntity (); @@ -899,13 +902,13 @@ void CL_AddFlagModels (entity_t *ent, int team) newent->skinnum = team; AngleVectors (ent->angles, v_forward, v_right, v_up); - v_forward[2] = -v_forward[2]; // reverse z component - for (i=0 ; i<3 ; i++) - newent->origin[i] = ent->origin[i] - f*v_forward[i] + 22*v_right[i]; + v_forward[2] = -v_forward[2]; // reverse z component + for (i = 0; i < 3; i++) + newent->origin[i] = ent->origin[i] - f * v_forward[i] + 22 * v_right[i]; newent->origin[2] -= 16; VectorCopy (ent->angles, newent->angles) - newent->angles[2] -= 45; + newent->angles[2] -= 45; } /* @@ -916,30 +919,30 @@ Create visible entities in the correct position for all current players ============= */ -void CL_LinkPlayers (void) +void +CL_LinkPlayers (void) { - int i, j; - player_info_t *info; - player_state_t *state; - player_state_t exact; - double playertime; - entity_t *ent; - int msec; - frame_t *frame; - int oldphysent; - vec3_t org; + int i, j; + player_info_t *info; + player_state_t *state; + player_state_t exact; + double playertime; + entity_t *ent; + int msec; + frame_t *frame; + int oldphysent; + vec3_t org; playertime = realtime - cls.latency + 0.02; if (playertime > realtime) playertime = realtime; - frame = &cl.frames[cl.parsecount&UPDATE_MASK]; + frame = &cl.frames[cl.parsecount & UPDATE_MASK]; - for (j=0, info=cl.players, state=frame->playerstate ; j < MAX_CLIENTS - ; j++, info++, state++) - { + for (j = 0, info = cl.players, state = frame->playerstate; j < MAX_CLIENTS; + j++, info++, state++) { if (state->messagenum != cl.parsecount) - continue; // not present this frame + continue; // not present this frame // FIXME: Use a findvar or something for gl_flashblend --KB // spawn light flashes, even ones coming from invisible objects @@ -951,17 +954,21 @@ void CL_LinkPlayers (void) VectorCopy (state->origin, org); if ((state->effects & (EF_BLUE | EF_RED)) == (EF_BLUE | EF_RED)) - CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand()&31), 0.1, 3); + CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand () & 31), + 0.1, 3); else if (state->effects & EF_BLUE) - CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand()&31), 0.1, 1); + CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand () & 31), + 0.1, 1); else if (state->effects & EF_RED) - CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand()&31), 0.1, 2); + CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand () & 31), + 0.1, 2); else if (state->effects & EF_BRIGHTLIGHT) - CL_NewDlight (j, org[0], org[1], org[2] + 16, 400 + (rand()&31), 0.1, 0); + CL_NewDlight (j, org[0], org[1], org[2] + 16, + 400 + (rand () & 31), 0.1, 0); else if (state->effects & EF_DIMLIGHT) - CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand()&31), 0.1, 0); + CL_NewDlight (j, org[0], org[1], org[2], 200 + (rand () & 31), + 0.1, 0); } - // the player object never gets added if (j == cl.playernum) continue; @@ -971,15 +978,16 @@ void CL_LinkPlayers (void) // Hack hack hack if (cl_deadbodyfilter->int_val && state->modelindex == cl_playerindex - && ( (i=state->frame)==49 || i==60 || i==69 || i==84 || i==93 || i==102) ) + && ((i = state->frame) == 49 || i == 60 || i == 69 || i == 84 + || i == 93 || i == 102)) continue; - if (!Cam_DrawPlayer(j)) + if (!Cam_DrawPlayer (j)) continue; // grab an entity to fill in if (cl_numvisedicts == MAX_VISEDICTS) - break; // object list is full + break; // object list is full ent = &cl_visedicts[cl_numvisedicts]; cl_numvisedicts++; ent->keynum = 0; @@ -993,30 +1001,30 @@ void CL_LinkPlayers (void) else ent->scoreboard = NULL; - // LordHavoc: more QSG VERSION 2 stuff, FIXME: players don't have extend stuff - ent->glowsize = 0; - ent->glowcolor = 254; - ent->alpha = 1; - ent->scale = 1; + // LordHavoc: more QSG VERSION 2 stuff, FIXME: players don't have + // extend stuff + ent->glowsize = 0; + ent->glowcolor = 254; + ent->alpha = 1; + ent->scale = 1; ent->colormod[0] = ent->colormod[1] = ent->colormod[2] = 1; - // + // // angles - // - ent->angles[PITCH] = -state->viewangles[PITCH]/3; + // + ent->angles[PITCH] = -state->viewangles[PITCH] / 3; ent->angles[YAW] = state->viewangles[YAW]; ent->angles[ROLL] = 0; - ent->angles[ROLL] = V_CalcRoll (ent->angles, state->velocity)*4; + ent->angles[ROLL] = V_CalcRoll (ent->angles, state->velocity) * 4; // only predict half the move to minimize overruns - msec = 500*(playertime - state->state_time); - if (msec <= 0 || (!cl_predict_players->int_val && !cl_predict_players2->int_val)) - { + msec = 500 * (playertime - state->state_time); + if (msec <= 0 + || (!cl_predict_players->int_val + && !cl_predict_players2->int_val)) { VectorCopy (state->origin, ent->origin); //Con_DPrintf ("nopredict\n"); - } - else - { + } else { // predict players movement if (msec > 255) msec = 255; @@ -1047,12 +1055,13 @@ CL_SetSolid Builds all the pmove physents for the current frame =============== */ -void CL_SetSolidEntities (void) +void +CL_SetSolidEntities (void) { - int i; - frame_t *frame; - packet_entities_t *pak; - entity_state_t *state; + int i; + frame_t *frame; + packet_entities_t *pak; + entity_state_t *state; pmove.physents[0].model = cl.worldmodel; VectorCopy (vec3_origin, pmove.physents[0].origin); @@ -1062,18 +1071,17 @@ void CL_SetSolidEntities (void) frame = &cl.frames[parsecountmod]; pak = &frame->packet_entities; - for (i=0 ; inum_entities ; i++) - { + for (i = 0; i < pak->num_entities; i++) { state = &pak->entities[i]; if (!state->modelindex) continue; if (!cl.model_precache[state->modelindex]) continue; - if ( cl.model_precache[state->modelindex]->hulls[1].firstclipnode - || cl.model_precache[state->modelindex]->clipbox ) - { - pmove.physents[pmove.numphysent].model = cl.model_precache[state->modelindex]; + if (cl.model_precache[state->modelindex]->hulls[1].firstclipnode + || cl.model_precache[state->modelindex]->clipbox) { + pmove.physents[pmove.numphysent].model = + cl.model_precache[state->modelindex]; VectorCopy (state->origin, pmove.physents[pmove.numphysent].origin); pmove.numphysent++; } @@ -1091,30 +1099,30 @@ then with clipping against them. This sets up the first phase. === */ -void CL_SetUpPlayerPrediction(qboolean dopred) +void +CL_SetUpPlayerPrediction (qboolean dopred) { - int j; - player_state_t *state; - player_state_t exact; - double playertime; - int msec; - frame_t *frame; + int j; + player_state_t *state; + player_state_t exact; + double playertime; + int msec; + frame_t *frame; struct predicted_player *pplayer; playertime = realtime - cls.latency + 0.02; if (playertime > realtime) playertime = realtime; - frame = &cl.frames[cl.parsecount&UPDATE_MASK]; + frame = &cl.frames[cl.parsecount & UPDATE_MASK]; - for (j=0, pplayer = predicted_players, state=frame->playerstate; - j < MAX_CLIENTS; - j++, pplayer++, state++) { + for (j = 0, pplayer = predicted_players, state = frame->playerstate; + j < MAX_CLIENTS; j++, pplayer++, state++) { pplayer->active = false; if (state->messagenum != cl.parsecount) - continue; // not present this frame + continue; // not present this frame if (!state->modelindex) continue; @@ -1125,25 +1133,22 @@ void CL_SetUpPlayerPrediction(qboolean dopred) // note that the local player is special, since he moves locally // we use his last predicted postition if (j == cl.playernum) { - VectorCopy(cl.frames[cls.netchan.outgoing_sequence&UPDATE_MASK].playerstate[cl.playernum].origin, - pplayer->origin); + VectorCopy (cl.frames[cls.netchan.outgoing_sequence & UPDATE_MASK]. + playerstate[cl.playernum].origin, pplayer->origin); } else { // only predict half the move to minimize overruns - msec = 500*(playertime - state->state_time); + msec = 500 * (playertime - state->state_time); if (msec <= 0 || - (!cl_predict_players->int_val && !cl_predict_players2->int_val) || - !dopred) - { + (!cl_predict_players->int_val && !cl_predict_players2->int_val) + || !dopred) { VectorCopy (state->origin, pplayer->origin); - //Con_DPrintf ("nopredict\n"); - } - else - { + // Con_DPrintf ("nopredict\n"); + } else { // predict players movement if (msec > 255) msec = 255; state->command.msec = msec; - //Con_DPrintf ("predict: %i\n", msec); + // Con_DPrintf ("predict: %i\n", msec); CL_PredictUsercmd (state, &exact, &state->command, false); VectorCopy (exact.origin, pplayer->origin); @@ -1162,35 +1167,36 @@ pmove must be setup with world and solid entity hulls before calling (via CL_PredictMove) =============== */ -void CL_SetSolidPlayers (int playernum) +void +CL_SetSolidPlayers (int playernum) { - int j; - extern vec3_t player_mins; - extern vec3_t player_maxs; + int j; + extern vec3_t player_mins; + extern vec3_t player_maxs; struct predicted_player *pplayer; - physent_t *pent; + physent_t *pent; if (!cl_solid_players->int_val) return; pent = pmove.physents + pmove.numphysent; - for (j=0, pplayer = predicted_players; j < MAX_CLIENTS; j++, pplayer++) { + for (j = 0, pplayer = predicted_players; j < MAX_CLIENTS; j++, pplayer++) { if (!pplayer->active) - continue; // not present this frame + continue; // not present this frame // the player object never gets added if (j == playernum) continue; if (pplayer->flags & PF_DEAD) - continue; // dead players aren't solid + continue; // dead players aren't solid pent->model = 0; - VectorCopy(pplayer->origin, pent->origin); - VectorCopy(player_mins, pent->mins); - VectorCopy(player_maxs, pent->maxs); + VectorCopy (pplayer->origin, pent->origin); + VectorCopy (player_mins, pent->mins); + VectorCopy (player_maxs, pent->maxs); pmove.numphysent++; pent++; } @@ -1206,7 +1212,8 @@ Builds the visedicts array for cl.time Made up of: clients, packet_entities, nails, and tents =============== */ -void CL_EmitEntities (void) +void +CL_EmitEntities (void) { if (cls.state != ca_active) return; @@ -1214,8 +1221,9 @@ void CL_EmitEntities (void) return; cl_oldnumvisedicts = cl_numvisedicts; - cl_oldvisedicts = cl_visedicts_list[(cls.netchan.incoming_sequence-1)&1]; - cl_visedicts = cl_visedicts_list[cls.netchan.incoming_sequence&1]; + cl_oldvisedicts = + cl_visedicts_list[(cls.netchan.incoming_sequence - 1) & 1]; + cl_visedicts = cl_visedicts_list[cls.netchan.incoming_sequence & 1]; cl_numvisedicts = 0; @@ -1224,4 +1232,3 @@ void CL_EmitEntities (void) CL_LinkProjectiles (); CL_UpdateTEnts (); } - diff --git a/source/cl_input.c b/source/cl_input.c index 7766a9e..599d5ac 100644 --- a/source/cl_input.c +++ b/source/cl_input.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -53,7 +53,7 @@ #include "cl_parse.h" #include "cl_input.h" -cvar_t *cl_nodelta; +cvar_t *cl_nodelta; /* =============================================================================== @@ -77,56 +77,59 @@ state bit 2 is edge triggered on the down to up transition */ -kbutton_t in_mlook, in_klook; -kbutton_t in_left, in_right, in_forward, in_back; -kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; -kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; -kbutton_t in_up, in_down; +kbutton_t in_mlook, in_klook; +kbutton_t in_left, in_right, in_forward, in_back; +kbutton_t in_lookup, in_lookdown, in_moveleft, in_moveright; +kbutton_t in_strafe, in_speed, in_use, in_jump, in_attack; +kbutton_t in_up, in_down; -int in_impulse; +int in_impulse; -void KeyDown (kbutton_t *b) +void +KeyDown (kbutton_t *b) { - int k; - char *c; - - c = Cmd_Argv(1); + int k; + char *c; + + c = Cmd_Argv (1); if (c[0]) - k = atoi(c); + k = atoi (c); else - k = -1; // typed manually at the console for continuous down + k = -1; // typed manually at the console for + // continuous down if (k == b->down[0] || k == b->down[1]) - return; // repeating key - + return; // repeating key + if (!b->down[0]) b->down[0] = k; else if (!b->down[1]) b->down[1] = k; - else - { + else { Con_Printf ("Three keys down for a button!\n"); return; } - + if (b->state & 1) - return; // still down - b->state |= 1 + 2; // down + impulse down + return; // still down + b->state |= 1 + 2; // down + impulse down } -void KeyUp (kbutton_t *b) +void +KeyUp (kbutton_t *b) { - int k; - char *c; - - c = Cmd_Argv(1); + int k; + char *c; + + c = Cmd_Argv (1); if (c[0]) - k = atoi(c); - else - { // typed manually at the console, assume for unsticking, so clear all + k = atoi (c); + else { // typed manually at the console, + // assume for unsticking, so clear + // all b->down[0] = b->down[1] = 0; - b->state = 4; // impulse up + b->state = 4; // impulse up return; } @@ -135,65 +138,232 @@ void KeyUp (kbutton_t *b) else if (b->down[1] == k) b->down[1] = 0; else - return; // key up without coresponding down (menu pass through) + return; // key up without coresponding down + // (menu pass through) if (b->down[0] || b->down[1]) - return; // some other key is still holding it down + return; // some other key is still holding it + // down if (!(b->state & 1)) - return; // still up (this should not happen) - b->state &= ~1; // now up - b->state |= 4; // impulse up + return; // still up (this should not happen) + b->state &= ~1; // now up + b->state |= 4; // impulse up } -void IN_KLookDown (void) {KeyDown(&in_klook);} -void IN_KLookUp (void) {KeyUp(&in_klook);} -void IN_MLookDown (void) {KeyDown(&in_mlook);} -void IN_MLookUp (void) { -KeyUp(&in_mlook); -if ( !freelook && lookspring->int_val) - V_StartPitchDrift(); -} -void IN_UpDown(void) {KeyDown(&in_up);} -void IN_UpUp(void) {KeyUp(&in_up);} -void IN_DownDown(void) {KeyDown(&in_down);} -void IN_DownUp(void) {KeyUp(&in_down);} -void IN_LeftDown(void) {KeyDown(&in_left);} -void IN_LeftUp(void) {KeyUp(&in_left);} -void IN_RightDown(void) {KeyDown(&in_right);} -void IN_RightUp(void) {KeyUp(&in_right);} -void IN_ForwardDown(void) {KeyDown(&in_forward);} -void IN_ForwardUp(void) {KeyUp(&in_forward);} -void IN_BackDown(void) {KeyDown(&in_back);} -void IN_BackUp(void) {KeyUp(&in_back);} -void IN_LookupDown(void) {KeyDown(&in_lookup);} -void IN_LookupUp(void) {KeyUp(&in_lookup);} -void IN_LookdownDown(void) {KeyDown(&in_lookdown);} -void IN_LookdownUp(void) {KeyUp(&in_lookdown);} -void IN_MoveleftDown(void) {KeyDown(&in_moveleft);} -void IN_MoveleftUp(void) {KeyUp(&in_moveleft);} -void IN_MoverightDown(void) {KeyDown(&in_moveright);} -void IN_MoverightUp(void) {KeyUp(&in_moveright);} - -void IN_SpeedDown(void) {KeyDown(&in_speed);} -void IN_SpeedUp(void) {KeyUp(&in_speed);} -void IN_StrafeDown(void) {KeyDown(&in_strafe);} -void IN_StrafeUp(void) {KeyUp(&in_strafe);} - -void IN_AttackDown(void) {KeyDown(&in_attack);} -void IN_AttackUp(void) {KeyUp(&in_attack);} - -void IN_UseDown (void) {KeyDown(&in_use);} -void IN_UseUp (void) {KeyUp(&in_use);} -void IN_JumpDown (void) {KeyDown(&in_jump);} -void IN_JumpUp (void) {KeyUp(&in_jump);} - -void IN_Impulse (void) +void +IN_KLookDown (void) { - in_impulse= atoi(Cmd_Argv(1)); - if (Cmd_Argc() <= 2) + KeyDown (&in_klook); +} + +void +IN_KLookUp (void) +{ + KeyUp (&in_klook); +} + +void +IN_MLookDown (void) +{ + KeyDown (&in_mlook); +} + +void +IN_MLookUp (void) +{ + KeyUp (&in_mlook); + if (!freelook && lookspring->int_val) + V_StartPitchDrift (); +} + +void +IN_UpDown (void) +{ + KeyDown (&in_up); +} + +void +IN_UpUp (void) +{ + KeyUp (&in_up); +} + +void +IN_DownDown (void) +{ + KeyDown (&in_down); +} + +void +IN_DownUp (void) +{ + KeyUp (&in_down); +} + +void +IN_LeftDown (void) +{ + KeyDown (&in_left); +} + +void +IN_LeftUp (void) +{ + KeyUp (&in_left); +} + +void +IN_RightDown (void) +{ + KeyDown (&in_right); +} + +void +IN_RightUp (void) +{ + KeyUp (&in_right); +} + +void +IN_ForwardDown (void) +{ + KeyDown (&in_forward); +} + +void +IN_ForwardUp (void) +{ + KeyUp (&in_forward); +} + +void +IN_BackDown (void) +{ + KeyDown (&in_back); +} + +void +IN_BackUp (void) +{ + KeyUp (&in_back); +} + +void +IN_LookupDown (void) +{ + KeyDown (&in_lookup); +} + +void +IN_LookupUp (void) +{ + KeyUp (&in_lookup); +} + +void +IN_LookdownDown (void) +{ + KeyDown (&in_lookdown); +} + +void +IN_LookdownUp (void) +{ + KeyUp (&in_lookdown); +} + +void +IN_MoveleftDown (void) +{ + KeyDown (&in_moveleft); +} + +void +IN_MoveleftUp (void) +{ + KeyUp (&in_moveleft); +} + +void +IN_MoverightDown (void) +{ + KeyDown (&in_moveright); +} + +void +IN_MoverightUp (void) +{ + KeyUp (&in_moveright); +} + +void +IN_SpeedDown (void) +{ + KeyDown (&in_speed); +} + +void +IN_SpeedUp (void) +{ + KeyUp (&in_speed); +} + +void +IN_StrafeDown (void) +{ + KeyDown (&in_strafe); +} + +void +IN_StrafeUp (void) +{ + KeyUp (&in_strafe); +} + +void +IN_AttackDown (void) +{ + KeyDown (&in_attack); +} + +void +IN_AttackUp (void) +{ + KeyUp (&in_attack); +} + +void +IN_UseDown (void) +{ + KeyDown (&in_use); +} + +void +IN_UseUp (void) +{ + KeyUp (&in_use); +} + +void +IN_JumpDown (void) +{ + KeyDown (&in_jump); +} + +void +IN_JumpUp (void) +{ + KeyUp (&in_jump); +} + +void +IN_Impulse (void) +{ + in_impulse = atoi (Cmd_Argv (1)); + if (Cmd_Argc () <= 2) return; - Team_BestWeaponImpulse(); // HACK HACK HACK + Team_BestWeaponImpulse (); // HACK HACK HACK } /* @@ -206,43 +376,44 @@ Returns 0.25 if a key was pressed and released during the frame, 1.0 if held for the entire time =============== */ -float CL_KeyState (kbutton_t *key) +float +CL_KeyState (kbutton_t *key) { - float val; - qboolean impulsedown, impulseup, down; - + float val; + qboolean impulsedown, impulseup, down; + impulsedown = key->state & 2; impulseup = key->state & 4; down = key->state & 1; val = 0; - + if (impulsedown && !impulseup) { if (down) - val = 0.5; // pressed and held this frame + val = 0.5; // pressed and held this frame else - val = 0; // I_Error (); + val = 0; // I_Error (); } if (impulseup && !impulsedown) { if (down) - val = 0; // I_Error (); + val = 0; // I_Error (); else - val = 0; // released this frame + val = 0; // released this frame } if (!impulsedown && !impulseup) { if (down) - val = 1.0; // held the entire frame + val = 1.0; // held the entire frame else - val = 0; // up the entire frame + val = 0; // up the entire frame } if (impulsedown && impulseup) { if (down) - val = 0.75; // released and re-pressed this frame + val = 0.75; // released and re-pressed this frame else - val = 0.25; // pressed and released this frame + val = 0.25; // pressed and released this frame } - key->state &= 1; // clear impulses - + key->state &= 1; // clear impulses + return val; } @@ -251,17 +422,17 @@ float CL_KeyState (kbutton_t *key) //========================================================================== -cvar_t *cl_upspeed; -cvar_t *cl_forwardspeed; -cvar_t *cl_backspeed; -cvar_t *cl_sidespeed; +cvar_t *cl_upspeed; +cvar_t *cl_forwardspeed; +cvar_t *cl_backspeed; +cvar_t *cl_sidespeed; -cvar_t *cl_movespeedkey; +cvar_t *cl_movespeedkey; -cvar_t *cl_yawspeed; -cvar_t *cl_pitchspeed; +cvar_t *cl_yawspeed; +cvar_t *cl_pitchspeed; -cvar_t *cl_anglespeedkey; +cvar_t *cl_anglespeedkey; /* @@ -271,38 +442,41 @@ CL_AdjustAngles Moves the local angle positions ================ */ -void CL_AdjustAngles (void) +void +CL_AdjustAngles (void) { - float speed; - float up, down; - + float speed; + float up, down; + if (in_speed.state & 1) speed = host_frametime * cl_anglespeedkey->value; else speed = host_frametime; - if (!(in_strafe.state & 1)) - { - cl.viewangles[YAW] -= speed*cl_yawspeed->value*CL_KeyState (&in_right); - cl.viewangles[YAW] += speed*cl_yawspeed->value*CL_KeyState (&in_left); - cl.viewangles[YAW] = anglemod(cl.viewangles[YAW]); + if (!(in_strafe.state & 1)) { + cl.viewangles[YAW] -= + speed * cl_yawspeed->value * CL_KeyState (&in_right); + cl.viewangles[YAW] += + speed * cl_yawspeed->value * CL_KeyState (&in_left); + cl.viewangles[YAW] = anglemod (cl.viewangles[YAW]); } - if (in_klook.state & 1) - { + if (in_klook.state & 1) { V_StopPitchDrift (); - cl.viewangles[PITCH] -= speed*cl_pitchspeed->value * CL_KeyState (&in_forward); - cl.viewangles[PITCH] += speed*cl_pitchspeed->value * CL_KeyState (&in_back); + cl.viewangles[PITCH] -= + speed * cl_pitchspeed->value * CL_KeyState (&in_forward); + cl.viewangles[PITCH] += + speed * cl_pitchspeed->value * CL_KeyState (&in_back); } - + up = CL_KeyState (&in_lookup); - down = CL_KeyState(&in_lookdown); - - cl.viewangles[PITCH] -= speed*cl_pitchspeed->value * up; - cl.viewangles[PITCH] += speed*cl_pitchspeed->value * down; + down = CL_KeyState (&in_lookdown); + + cl.viewangles[PITCH] -= speed * cl_pitchspeed->value * up; + cl.viewangles[PITCH] += speed * cl_pitchspeed->value * down; if (up || down) V_StopPitchDrift (); - + if (cl.viewangles[PITCH] > 80) cl.viewangles[PITCH] = 80; if (cl.viewangles[PITCH] < -70) @@ -312,7 +486,7 @@ void CL_AdjustAngles (void) cl.viewangles[ROLL] = 50; if (cl.viewangles[ROLL] < -50) cl.viewangles[ROLL] = -50; - + } /* @@ -322,15 +496,15 @@ CL_BaseMove Send the intended movement message to the server ================ */ -void CL_BaseMove (usercmd_t *cmd) -{ +void +CL_BaseMove (usercmd_t *cmd) +{ CL_AdjustAngles (); - - memset (cmd, 0, sizeof(*cmd)); - + + memset (cmd, 0, sizeof (*cmd)); + VectorCopy (cl.viewangles, cmd->angles); - if (in_strafe.state & 1) - { + if (in_strafe.state & 1) { cmd->sidemove += cl_sidespeed->value * CL_KeyState (&in_right); cmd->sidemove -= cl_sidespeed->value * CL_KeyState (&in_left); } @@ -341,30 +515,28 @@ void CL_BaseMove (usercmd_t *cmd) cmd->upmove += cl_upspeed->value * CL_KeyState (&in_up); cmd->upmove -= cl_upspeed->value * CL_KeyState (&in_down); - if (! (in_klook.state & 1) ) - { + if (!(in_klook.state & 1)) { cmd->forwardmove += cl_forwardspeed->value * CL_KeyState (&in_forward); cmd->forwardmove -= cl_backspeed->value * CL_KeyState (&in_back); - } - + } // // adjust for speed key // - if (in_speed.state & 1) - { + if (in_speed.state & 1) { cmd->forwardmove *= cl_movespeedkey->value; cmd->sidemove *= cl_movespeedkey->value; cmd->upmove *= cl_movespeedkey->value; - } + } } -int MakeChar (int i) +int +MakeChar (int i) { i &= ~3; - if (i < -127*4) - i = -127*4; - if (i > 127*4) - i = 127*4; + if (i < -127 * 4) + i = -127 * 4; + if (i > 127 * 4) + i = 127 * 4; return i; } @@ -373,10 +545,11 @@ int MakeChar (int i) CL_FinishMove ============== */ -void CL_FinishMove (usercmd_t *cmd) +void +CL_FinishMove (usercmd_t *cmd) { - int i; - int ms; + int i; + int ms; // // allways dump the first two message, because it may contain leftover inputs @@ -386,8 +559,8 @@ void CL_FinishMove (usercmd_t *cmd) return; // // figure button bits -// - if ( in_attack.state & 3 ) +// + if (in_attack.state & 3) cmd->buttons |= 1; in_attack.state &= ~2; @@ -404,7 +577,7 @@ void CL_FinishMove (usercmd_t *cmd) // send milliseconds of time to apply the move ms = host_frametime * 1000; if (ms > 250) - ms = 100; // time was unreasonable + ms = 100; // time was unreasonable cmd->msec = ms; VectorCopy (cl.viewangles, cmd->angles); @@ -420,8 +593,10 @@ void CL_FinishMove (usercmd_t *cmd) cmd->sidemove = MakeChar (cmd->sidemove); cmd->upmove = MakeChar (cmd->upmove); - for (i=0 ; i<3 ; i++) - cmd->angles[i] = ((int)(cmd->angles[i]*65536.0/360)&65535) * (360.0/65536.0); + for (i = 0; i < 3; i++) + cmd->angles[i] = + ((int) (cmd->angles[i] * 65536.0 / 360) & 65535) * (360.0 / + 65536.0); } /* @@ -429,18 +604,19 @@ void CL_FinishMove (usercmd_t *cmd) CL_SendCmd ================= */ -void CL_SendCmd (void) +void +CL_SendCmd (void) { - sizebuf_t buf; - byte data[128]; - int i; - usercmd_t *cmd, *oldcmd; - int checksumIndex; - int lost; - int seq_hash; + sizebuf_t buf; + byte data[128]; + int i; + usercmd_t *cmd, *oldcmd; + int checksumIndex; + int lost; + int seq_hash; if (cls.demoplayback) - return; // sendcmds come from the demo + return; // sendcmds come from the demo // save this command off for prediction i = cls.netchan.outgoing_sequence & UPDATE_MASK; @@ -448,7 +624,7 @@ void CL_SendCmd (void) cl.frames[i].senttime = realtime; cl.frames[i].receivedtime = -1; // we haven't gotten a reply yet -// seq_hash = (cls.netchan.outgoing_sequence & 0xffff) ; // ^ QW_CHECK_HASH; +// seq_hash = (cls.netchan.outgoing_sequence & 0xffff) ; // ^ QW_CHECK_HASH; seq_hash = cls.netchan.outgoing_sequence; // get basic movement from keyboard @@ -459,11 +635,11 @@ void CL_SendCmd (void) // if we are spectator, try autocam if (cl.spectator) - Cam_Track(cmd); + Cam_Track (cmd); - CL_FinishMove(cmd); + CL_FinishMove (cmd); - Cam_FinishMove(cmd); + Cam_FinishMove (cmd); // send this and the previous cmds in the message, so // if the last packet was dropped, it can be recovered @@ -478,15 +654,15 @@ void CL_SendCmd (void) MSG_WriteByte (&buf, 0); // write our lossage percentage - lost = CL_CalcNet(); - MSG_WriteByte (&buf, (byte)lost); + lost = CL_CalcNet (); + MSG_WriteByte (&buf, (byte) lost); - i = (cls.netchan.outgoing_sequence-2) & UPDATE_MASK; + i = (cls.netchan.outgoing_sequence - 2) & UPDATE_MASK; cmd = &cl.frames[i].cmd; MSG_WriteDeltaUsercmd (&buf, &nullcmd, cmd); oldcmd = cmd; - i = (cls.netchan.outgoing_sequence-1) & UPDATE_MASK; + i = (cls.netchan.outgoing_sequence - 1) & UPDATE_MASK; cmd = &cl.frames[i].cmd; MSG_WriteDeltaUsercmd (&buf, oldcmd, cmd); oldcmd = cmd; @@ -496,31 +672,31 @@ void CL_SendCmd (void) MSG_WriteDeltaUsercmd (&buf, oldcmd, cmd); // calculate a checksum over the move commands - buf.data[checksumIndex] = COM_BlockSequenceCRCByte( - buf.data + checksumIndex + 1, buf.cursize - checksumIndex - 1, - seq_hash); + buf.data[checksumIndex] = + COM_BlockSequenceCRCByte (buf.data + checksumIndex + 1, + buf.cursize - checksumIndex - 1, seq_hash); // request delta compression of entities - if (cls.netchan.outgoing_sequence - cl.validsequence >= UPDATE_BACKUP-1) + if (cls.netchan.outgoing_sequence - cl.validsequence >= UPDATE_BACKUP - 1) cl.validsequence = 0; if (cl.validsequence && !cl_nodelta->int_val && cls.state == ca_active && - !cls.demorecording) - { - cl.frames[cls.netchan.outgoing_sequence&UPDATE_MASK].delta_sequence = cl.validsequence; + !cls.demorecording) { + cl.frames[cls.netchan.outgoing_sequence & UPDATE_MASK].delta_sequence = + cl.validsequence; MSG_WriteByte (&buf, clc_delta); - MSG_WriteByte (&buf, cl.validsequence&255); - } - else - cl.frames[cls.netchan.outgoing_sequence&UPDATE_MASK].delta_sequence = -1; + MSG_WriteByte (&buf, cl.validsequence & 255); + } else + cl.frames[cls.netchan.outgoing_sequence & UPDATE_MASK].delta_sequence = + -1; if (cls.demorecording) - CL_WriteDemoCmd(cmd); + CL_WriteDemoCmd (cmd); // // deliver the message // - Netchan_Transmit (&cls.netchan, buf.cursize, buf.data); + Netchan_Transmit (&cls.netchan, buf.cursize, buf.data); } @@ -530,20 +706,21 @@ void CL_SendCmd (void) CL_InitInput ============ */ -void CL_Input_Init (void) +void +CL_Input_Init (void) { - Cmd_AddCommand ("+moveup",IN_UpDown); - Cmd_AddCommand ("-moveup",IN_UpUp); - Cmd_AddCommand ("+movedown",IN_DownDown); - Cmd_AddCommand ("-movedown",IN_DownUp); - Cmd_AddCommand ("+left",IN_LeftDown); - Cmd_AddCommand ("-left",IN_LeftUp); - Cmd_AddCommand ("+right",IN_RightDown); - Cmd_AddCommand ("-right",IN_RightUp); - Cmd_AddCommand ("+forward",IN_ForwardDown); - Cmd_AddCommand ("-forward",IN_ForwardUp); - Cmd_AddCommand ("+back",IN_BackDown); - Cmd_AddCommand ("-back",IN_BackUp); + Cmd_AddCommand ("+moveup", IN_UpDown); + Cmd_AddCommand ("-moveup", IN_UpUp); + Cmd_AddCommand ("+movedown", IN_DownDown); + Cmd_AddCommand ("-movedown", IN_DownUp); + Cmd_AddCommand ("+left", IN_LeftDown); + Cmd_AddCommand ("-left", IN_LeftUp); + Cmd_AddCommand ("+right", IN_RightDown); + Cmd_AddCommand ("-right", IN_RightUp); + Cmd_AddCommand ("+forward", IN_ForwardDown); + Cmd_AddCommand ("-forward", IN_ForwardUp); + Cmd_AddCommand ("+back", IN_BackDown); + Cmd_AddCommand ("-back", IN_BackUp); Cmd_AddCommand ("+lookup", IN_LookupDown); Cmd_AddCommand ("-lookup", IN_LookupUp); Cmd_AddCommand ("+lookdown", IN_LookdownDown); @@ -569,9 +746,10 @@ void CL_Input_Init (void) Cmd_AddCommand ("-mlook", IN_MLookUp); } -void CL_Input_Init_Cvars (void) +void +CL_Input_Init_Cvars (void) { - cl_nodelta = Cvar_Get("cl_nodelta", "0", CVAR_NONE, "None"); + cl_nodelta = Cvar_Get ("cl_nodelta", "0", CVAR_NONE, "None"); } @@ -583,13 +761,13 @@ CL_ClearStates ============ Generate key up event for each key that is down */ -void CL_ClearStates (void) +void +CL_ClearStates (void) { - int i; + int i; // send an up event for each key, to make sure the server clears them all - for (i=0 ; i<256 ; i++) - { + for (i = 0; i < 256; i++) { if (keydown[i]) Key_Event (i, 0, false); } diff --git a/source/cl_main.c b/source/cl_main.c index 38ae855..10dc960 100644 --- a/source/cl_main.c +++ b/source/cl_main.c @@ -93,124 +93,126 @@ #include #endif -void CL_RemoveQFInfoKeys (); +void CL_RemoveQFInfoKeys (); // we need to declare some mouse variables here, because the menu system // references them even when on a unix system. -qboolean noclip_anglehack; // remnant from old quake +qboolean noclip_anglehack; // remnant from old quake -cvar_t *fs_globalcfg; -cvar_t *rcon_password; +cvar_t *fs_globalcfg; +cvar_t *rcon_password; -cvar_t *rcon_address; +cvar_t *rcon_address; -cvar_t *cl_timeout; +cvar_t *cl_timeout; -cvar_t *cl_shownet; // can be 0, 1, or 2 -cvar_t *cl_autoexec; -cvar_t *cl_sbar; -cvar_t *cl_sbar_separator; -cvar_t *cl_hudswap; -cvar_t *cl_maxfps; +cvar_t *cl_shownet; // can be 0, 1, or 2 +cvar_t *cl_autoexec; +cvar_t *cl_sbar; +cvar_t *cl_sbar_separator; +cvar_t *cl_hudswap; +cvar_t *cl_maxfps; -cvar_t *lookspring; -cvar_t *lookstrafe; -cvar_t *sensitivity; -cvar_t *cl_freelook; +cvar_t *lookspring; +cvar_t *lookstrafe; +cvar_t *sensitivity; +cvar_t *cl_freelook; -cvar_t *m_pitch; -cvar_t *m_yaw; -cvar_t *m_forward; -cvar_t *m_side; +cvar_t *m_pitch; +cvar_t *m_yaw; +cvar_t *m_forward; +cvar_t *m_side; -cvar_t *cl_predict_players; -cvar_t *cl_predict_players2; -cvar_t *cl_solid_players; +cvar_t *cl_predict_players; +cvar_t *cl_predict_players2; +cvar_t *cl_solid_players; -cvar_t *localid; +cvar_t *localid; static qboolean allowremotecmd = true; // // info mirrors // -cvar_t *password; -cvar_t *spectator; -cvar_t *name; -cvar_t *team; -cvar_t *skin; -cvar_t *topcolor; -cvar_t *bottomcolor; -cvar_t *rate; -cvar_t *noaim; -cvar_t *msg; +cvar_t *password; +cvar_t *spectator; +cvar_t *name; +cvar_t *team; +cvar_t *skin; +cvar_t *topcolor; +cvar_t *bottomcolor; +cvar_t *rate; +cvar_t *noaim; +cvar_t *msg; extern cvar_t *cl_hightrack; -client_static_t cls; -client_state_t cl; +client_static_t cls; +client_state_t cl; -entity_state_t cl_baselines[MAX_EDICTS]; -efrag_t cl_efrags[MAX_EFRAGS]; -entity_t cl_static_entities[MAX_STATIC_ENTITIES]; -lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; -dlight_t cl_dlights[MAX_DLIGHTS]; +entity_state_t cl_baselines[MAX_EDICTS]; +efrag_t cl_efrags[MAX_EFRAGS]; +entity_t cl_static_entities[MAX_STATIC_ENTITIES]; +lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; +dlight_t cl_dlights[MAX_DLIGHTS]; // refresh list // this is double buffered so the last frame // can be scanned for oldorigins of trailing objects -int cl_numvisedicts, cl_oldnumvisedicts; -entity_t *cl_visedicts, *cl_oldvisedicts; -entity_t cl_visedicts_list[2][MAX_VISEDICTS]; +int cl_numvisedicts, cl_oldnumvisedicts; +entity_t *cl_visedicts, *cl_oldvisedicts; +entity_t cl_visedicts_list[2][MAX_VISEDICTS]; -double connect_time = -1; // for connection retransmits +double connect_time = -1; // for connection retransmits quakeparms_t host_parms; -qboolean host_initialized; // true if into command execution -qboolean nomaster; +qboolean host_initialized; // true if into command execution +qboolean nomaster; -double host_frametime; -double realtime; // without any filtering or bounding -double oldrealtime; // last frame run -int host_framecount; +double host_frametime; +double realtime; // without any filtering or bounding +double oldrealtime; // last frame run +int host_framecount; -int host_hunklevel; +int host_hunklevel; -byte *host_basepal; -byte *host_colormap; +byte *host_basepal; +byte *host_colormap; -cvar_t *host_speeds; // set for running times -cvar_t *show_fps; // set for running times -cvar_t *show_time; -cvar_t *developer; +cvar_t *host_speeds; // set for running times +cvar_t *show_fps; // set for running times +cvar_t *show_time; +cvar_t *developer; -int fps_count; +int fps_count; -jmp_buf host_abort; +jmp_buf host_abort; -void Master_Connect_f (void); +void Master_Connect_f (void); -char *server_version = NULL; // version of server we connected to +char *server_version = NULL; // version of server we connected to -char emodel_name[] = "emodel"; -char pmodel_name[] = "pmodel"; -char prespawn_name[] = "prespawn %i 0 %i"; -char modellist_name[] = "modellist %i %i"; -char soundlist_name[] = "soundlist %i %i"; +char emodel_name[] = "emodel"; +char pmodel_name[] = "pmodel"; +char prespawn_name[] = "prespawn %i 0 %i"; +char modellist_name[] = "modellist %i %i"; +char soundlist_name[] = "soundlist %i %i"; -cvar_t *confirm_quit; +cvar_t *confirm_quit; /* ================== CL_Quit_f ================== */ -void CL_Quit_f (void) +void +CL_Quit_f (void) { - if (confirm_quit->int_val /* key_dest != key_console */ /* && cls.state != ca_dedicated */) - { + if (confirm_quit-> + int_val /* key_dest != key_console *//* && cls.state != ca_dedicated */ + ) { M_Menu_Quit_f (); return; } @@ -223,10 +225,11 @@ void CL_Quit_f (void) CL_Version_f ====================== */ -void CL_Version_f (void) +void +CL_Version_f (void) { Con_Printf ("%s Version %s\n", PROGRAM, VERSION); - Con_Printf ("Binary: "__TIME__" "__DATE__"\n"); + Con_Printf ("Binary: " __TIME__ " " __DATE__ "\n"); } @@ -237,29 +240,29 @@ CL_SendConnectPacket called by CL_Connect_f and CL_CheckResend ====================== */ -void CL_SendConnectPacket (void) +void +CL_SendConnectPacket (void) { - netadr_t adr; - char data[2048]; - double t1, t2; + netadr_t adr; + char data[2048]; + double t1, t2; + // JACK: Fixed bug where DNS lookups would cause two connects real fast // Now, adds lookup time to the connect time. -// Should I add it to realtime instead?!?! +// Should I add it to realtime instead?!?! if (cls.state != ca_disconnected) return; t1 = Sys_DoubleTime (); - if (!NET_StringToAdr (cls.servername, &adr)) - { + if (!NET_StringToAdr (cls.servername, &adr)) { Con_Printf ("Bad server address\n"); connect_time = -1; return; } - if (!NET_IsClientLegal(&adr)) - { + if (!NET_IsClientLegal (&adr)) { Con_Printf ("Illegal server address\n"); connect_time = -1; return; @@ -269,20 +272,22 @@ void CL_SendConnectPacket (void) adr.port = BigShort (27500); t2 = Sys_DoubleTime (); - connect_time = realtime+t2-t1; // for retransmit requests + connect_time = realtime + t2 - t1; // for retransmit requests - cls.qport = Cvar_VariableValue("qport"); + cls.qport = Cvar_VariableValue ("qport"); // Arrgh, this was not in the old binary only release, and eats up // far too much of the 196 chars in the userinfo space, leaving nothing // for player use, thus, its commented out for the moment.. - // - //Info_SetValueForStarKey (cls.userinfo, "*ip", NET_AdrToString(adr), MAX_INFO_STRING); + // + // Info_SetValueForStarKey (cls.userinfo, "*ip", NET_AdrToString(adr), + // MAX_INFO_STRING); -// Con_Printf ("Connecting to %s...\n", cls.servername); - snprintf (data, sizeof(data), "%c%c%c%cconnect %i %i %i \"%s\"\n", - 255, 255, 255, 255, PROTOCOL_VERSION, cls.qport, cls.challenge, cls.userinfo); - NET_SendPacket (strlen(data), data, adr); +// Con_Printf ("Connecting to %s...\n", cls.servername); + snprintf (data, sizeof (data), "%c%c%c%cconnect %i %i %i \"%s\"\n", + 255, 255, 255, 255, PROTOCOL_VERSION, cls.qport, cls.challenge, + cls.userinfo); + NET_SendPacket (strlen (data), data, adr); } /* @@ -293,11 +298,12 @@ Resend a connect message if the last one has timed out ================= */ -void CL_CheckForResend (void) +void +CL_CheckForResend (void) { - netadr_t adr; - char data[2048]; - double t1, t2; + netadr_t adr; + char data[2048]; + double t1, t2; if (connect_time == -1) return; @@ -307,14 +313,12 @@ void CL_CheckForResend (void) return; t1 = Sys_DoubleTime (); - if (!NET_StringToAdr (cls.servername, &adr)) - { + if (!NET_StringToAdr (cls.servername, &adr)) { Con_Printf ("Bad server address\n"); connect_time = -1; return; } - if (!NET_IsClientLegal(&adr)) - { + if (!NET_IsClientLegal (&adr)) { Con_Printf ("Illegal server address\n"); connect_time = -1; return; @@ -324,18 +328,20 @@ void CL_CheckForResend (void) adr.port = BigShort (27500); t2 = Sys_DoubleTime (); - connect_time = realtime+t2-t1; // for retransmit requests + connect_time = realtime + t2 - t1; // for retransmit requests VID_SetCaption (va ("Connecting to %s", cls.servername)); Con_Printf ("Connecting to %s...\n", cls.servername); - snprintf (data, sizeof(data), "%c%c%c%cgetchallenge\n", 255, 255, 255, 255); - NET_SendPacket (strlen(data), data, adr); + snprintf (data, sizeof (data), "%c%c%c%cgetchallenge\n", 255, 255, 255, + 255); + NET_SendPacket (strlen (data), data, adr); } -void CL_BeginServerConnect(void) +void +CL_BeginServerConnect (void) { connect_time = 0; - CL_CheckForResend(); + CL_CheckForResend (); } /* @@ -344,22 +350,22 @@ CL_Connect_f ================ */ -void CL_Connect_f (void) +void +CL_Connect_f (void) { - char *server; + char *server; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("usage: connect \n"); - return; + return; } - + server = Cmd_Argv (1); CL_Disconnect (); - strncpy (cls.servername, server, sizeof(cls.servername)-1); - CL_BeginServerConnect(); + strncpy (cls.servername, server, sizeof (cls.servername) - 1); + CL_BeginServerConnect (); } @@ -371,30 +377,29 @@ CL_Rcon_f an unconnected command. ===================== */ -void CL_Rcon_f (void) +void +CL_Rcon_f (void) { - char message[1024]; - int i; - netadr_t to; - int len; + char message[1024]; + int i; + netadr_t to; + int len; snprintf (message, sizeof (message), "\377\377\377\377rcon %s ", rcon_password->string); len = strlen (message); - for (i=1 ; i= ca_connected) to = cls.netchan.remote_address; - else - { - if (!strlen(rcon_address->string)) - { + else { + if (!strlen (rcon_address->string)) { Con_Printf ("You must either be connected,\n" "or set the 'rcon_address' cvar\n" "to issue rcon commands\n"); @@ -403,9 +408,8 @@ void CL_Rcon_f (void) } NET_StringToAdr (rcon_address->string, &to); } - - NET_SendPacket (strlen(message)+1, message - , to); + + NET_SendPacket (strlen (message) + 1, message, to); } @@ -415,36 +419,37 @@ CL_ClearState ===================== */ -void CL_ClearState (void) +void +CL_ClearState (void) { - int i; + int i; S_StopAllSounds (true); Con_DPrintf ("Clearing memory\n"); D_FlushCaches (); Mod_ClearAll (); - if (host_hunklevel) // FIXME: check this... + if (host_hunklevel) // FIXME: check this... Hunk_FreeToLowMark (host_hunklevel); CL_ClearTEnts (); // wipe the entire cl structure - memset (&cl, 0, sizeof(cl)); + memset (&cl, 0, sizeof (cl)); SZ_Clear (&cls.netchan.message); -// clear other arrays - memset (cl_efrags, 0, sizeof(cl_efrags)); - memset (cl_dlights, 0, sizeof(cl_dlights)); - memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); +// clear other arrays + memset (cl_efrags, 0, sizeof (cl_efrags)); + memset (cl_dlights, 0, sizeof (cl_dlights)); + memset (cl_lightstyle, 0, sizeof (cl_lightstyle)); // // allocate the efrags and chain together into a free list // cl.free_efrags = cl_efrags; - for (i=0 ; i Dump userdata / masterdata for a user ==================== */ -void CL_User_f (void) +void +CL_User_f (void) { - int uid; - int i; + int uid; + int i; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("Usage: user \n"); return; } - uid = atoi(Cmd_Argv(1)); + uid = atoi (Cmd_Argv (1)); - for (i=0 ; i [0-13]\n"); return; } - if (Cmd_Argc() == 2) - top = bottom = atoi(Cmd_Argv(1)); - else - { - top = atoi(Cmd_Argv(1)); - bottom = atoi(Cmd_Argv(2)); + if (Cmd_Argc () == 2) + top = bottom = atoi (Cmd_Argv (1)); + else { + top = atoi (Cmd_Argv (1)); + bottom = atoi (Cmd_Argv (2)); } - + top &= 15; if (top > 13) top = 13; bottom &= 15; if (bottom > 13) bottom = 13; - - snprintf (num, sizeof(num), "%i", top); + + snprintf (num, sizeof (num), "%i", top); Cvar_Set (topcolor, num); - snprintf (num, sizeof(num), "%i", bottom); + snprintf (num, sizeof (num), "%i", bottom); Cvar_Set (bottomcolor, num); } @@ -609,43 +612,38 @@ CL_FullServerinfo_f Sent by server when serverinfo changes ================== */ -void CL_FullServerinfo_f (void) +void +CL_FullServerinfo_f (void) { - char *p; + char *p; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("usage: fullserverinfo \n"); return; } - Con_DPrintf("Cmd_Argv(1): '%s'\n", Cmd_Argv(1)); - strcpy (cl.serverinfo, Cmd_Argv(1)); - Con_DPrintf("cl.serverinfo: '%s'\n", cl.serverinfo); + Con_DPrintf ("Cmd_Argv(1): '%s'\n", Cmd_Argv (1)); + strcpy (cl.serverinfo, Cmd_Argv (1)); + Con_DPrintf ("cl.serverinfo: '%s'\n", cl.serverinfo); - if ((p = Info_ValueForKey(cl.serverinfo, "*qf_version")) && *p) - { + if ((p = Info_ValueForKey (cl.serverinfo, "*qf_version")) && *p) { if (server_version == NULL) - Con_Printf("QuakeForge Version %s Server\n", p); - server_version = strdup(p); - } else if ((p = Info_ValueForKey(cl.serverinfo, "*version")) && *p) - { + Con_Printf ("QuakeForge Version %s Server\n", p); + server_version = strdup (p); + } else if ((p = Info_ValueForKey (cl.serverinfo, "*version")) && *p) { if (server_version == NULL) - Con_Printf("Version %s Server\n", p); - server_version = strdup(p); + Con_Printf ("Version %s Server\n", p); + server_version = strdup (p); } - if ((p = Info_ValueForKey(cl.serverinfo, "*qsg_version")) && *p) - { + if ((p = Info_ValueForKey (cl.serverinfo, "*qsg_version")) && *p) { if ((cl.stdver = atoi (p))) - Con_Printf("QSG Standard version %i\n", cl.stdver); + Con_Printf ("QSG Standard version %i\n", cl.stdver); else - Con_Printf("Invalid standards version: %s", p); + Con_Printf ("Invalid standards version: %s", p); } - if ((p = Info_ValueForKey(cl.serverinfo, "skybox")) && *p) - { - if (stricmp (p, "none") == 0) - { + if ((p = Info_ValueForKey (cl.serverinfo, "skybox")) && *p) { + if (stricmp (p, "none") == 0) { allowskybox = false; } else { allowskybox = true; @@ -664,24 +662,27 @@ void CL_FullServerinfo_f (void) void CL_AddQFInfoKeys () { - char cap[100] = ""; // max of 98 or so flags + char cap[100] = ""; // max of 98 or so flags + // set the capabilities info. single char flags (possibly with // modifiefs) // defined capabilities (* = not implemented): - // z client can accept gzipped files. - // h * http transfers - // f * ftp transfers - // a * audio channel (voice chat) - // i * irc - // p pogo stick control - // t team messages + // z client can accept gzipped files. + // h * http transfers + // f * ftp transfers + // a * audio channel (voice chat) + // i * irc + // p pogo stick control + // t team messages strncpy (cap, "pt", sizeof (cap)); #ifdef HAVE_ZLIB strncat (cap, "z", sizeof (cap) - strlen (cap) - 1); #endif Info_SetValueForStarKey (cls.userinfo, "*cap", cap, MAX_INFO_STRING); - Info_SetValueForStarKey (cls.userinfo, "*qf_version", VERSION, MAX_INFO_STRING); - Info_SetValueForStarKey (cls.userinfo, "*qsg_version", QSG_VERSION, MAX_INFO_STRING); + Info_SetValueForStarKey (cls.userinfo, "*qf_version", VERSION, + MAX_INFO_STRING); + Info_SetValueForStarKey (cls.userinfo, "*qsg_version", QSG_VERSION, + MAX_INFO_STRING); Con_Printf ("QuakeForge server detected\n"); } @@ -706,31 +707,29 @@ Allow clients to change userinfo ================== Casey was here :) */ -void CL_FullInfo_f (void) +void +CL_FullInfo_f (void) { - char key[512]; - char value[512]; - char *o; - char *s; + char key[512]; + char value[512]; + char *o; + char *s; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("fullinfo \n"); return; } - s = Cmd_Argv(1); + s = Cmd_Argv (1); if (*s == '\\') s++; - while (*s) - { + while (*s) { o = key; while (*s && *s != '\\') *o++ = *s++; *o = 0; - if (!*s) - { + if (!*s) { Con_Printf ("MISSING VALUE\n"); return; } @@ -744,7 +743,7 @@ void CL_FullInfo_f (void) if (*s) s++; - if (!stricmp(key, pmodel_name) || !stricmp(key, emodel_name)) + if (!stricmp (key, pmodel_name) || !stricmp (key, emodel_name)) continue; Info_SetValueForKey (cls.userinfo, key, value, MAX_INFO_STRING); @@ -758,22 +757,22 @@ CL_SetInfo_f Allow clients to change userinfo ================== */ -void CL_SetInfo_f (void) +void +CL_SetInfo_f (void) { - if (Cmd_Argc() == 1) - { + if (Cmd_Argc () == 1) { Info_Print (cls.userinfo); return; } - if (Cmd_Argc() != 3) - { + if (Cmd_Argc () != 3) { Con_Printf ("usage: setinfo [ ]\n"); return; } - if (!stricmp(Cmd_Argv(1), pmodel_name) || !strcmp(Cmd_Argv(1), emodel_name)) - return; + if (!stricmp (Cmd_Argv (1), pmodel_name) + || !strcmp (Cmd_Argv (1), emodel_name)) return; - Info_SetValueForKey (cls.userinfo, Cmd_Argv(1), Cmd_Argv(2), MAX_INFO_STRING); + Info_SetValueForKey (cls.userinfo, Cmd_Argv (1), Cmd_Argv (2), + MAX_INFO_STRING); if (cls.state >= ca_connected) Cmd_ForwardToServer (); } @@ -787,43 +786,39 @@ packet Contents allows \n escape character ==================== */ -void CL_Packet_f (void) +void +CL_Packet_f (void) { - char send[2048]; - int i, l; - char *in, *out; - netadr_t adr; + char send[2048]; + int i, l; + char *in, *out; + netadr_t adr; - if (Cmd_Argc() != 3) - { + if (Cmd_Argc () != 3) { Con_Printf ("packet \n"); return; } - if (!NET_StringToAdr (Cmd_Argv(1), &adr)) - { + if (!NET_StringToAdr (Cmd_Argv (1), &adr)) { Con_Printf ("Bad address\n"); return; } - in = Cmd_Argv(2); - out = send+4; + in = Cmd_Argv (2); + out = send + 4; send[0] = send[1] = send[2] = send[3] = 0xff; l = strlen (in); - for (i=0 ; i= ca_connected) - { + if (cls.state >= ca_connected) { if (!cls.demoplayback) Con_Printf ("Dup connect received. Ignored.\n"); return; } Netchan_Setup (&cls.netchan, net_from, cls.qport); MSG_WriteChar (&cls.netchan.message, clc_stringcmd); - MSG_WriteString (&cls.netchan.message, "new"); + MSG_WriteString (&cls.netchan.message, "new"); cls.state = ca_connected; Con_Printf ("Connected.\n"); - allowremotecmd = false; // localid required now for remote cmds + allowremotecmd = false; // localid required now for remote + // cmds return; } // remote command from gui front end - if (c == A2C_CLIENT_COMMAND) - { - char cmdtext[2048]; + if (c == A2C_CLIENT_COMMAND) { + char cmdtext[2048]; Con_Printf ("client command\n"); - if ((*(unsigned int *)net_from.ip != *(unsigned int *)net_local_adr.ip - && *(unsigned int *)net_from.ip != htonl(INADDR_LOOPBACK)) ) - { + if ((*(unsigned int *) net_from.ip != *(unsigned int *) net_local_adr.ip + && *(unsigned int *) net_from.ip != htonl (INADDR_LOOPBACK))) { Con_Printf ("Command packet from remote host. Ignored.\n"); return; } @@ -964,32 +959,34 @@ void CL_ConnectionlessPacket (void) #endif s = MSG_ReadString (); - strncpy(cmdtext, s, sizeof(cmdtext) - 1); - cmdtext[sizeof(cmdtext) - 1] = 0; + strncpy (cmdtext, s, sizeof (cmdtext) - 1); + cmdtext[sizeof (cmdtext) - 1] = 0; s = MSG_ReadString (); - while (*s && isspace((int)*s)) + while (*s && isspace ((int) *s)) s++; - while (*s && isspace((int)(s[strlen(s) - 1]))) - s[strlen(s) - 1] = 0; + while (*s && isspace ((int) (s[strlen (s) - 1]))) + s[strlen (s) - 1] = 0; - if (!allowremotecmd && (!*localid->string || strcmp(localid->string, s))) { + if (!allowremotecmd + && (!*localid->string || strcmp (localid->string, s))) { if (!*localid->string) { - Con_Printf("===========================\n"); - Con_Printf("Command packet received from local host, but no " - "localid has been set. You may need to upgrade your server " - "browser.\n"); - Con_Printf("===========================\n"); + Con_Printf ("===========================\n"); + Con_Printf ("Command packet received from local host, but no " + "localid has been set. You may need to upgrade your server " + "browser.\n"); + Con_Printf ("===========================\n"); return; } - Con_Printf("===========================\n"); - Con_Printf("Invalid localid on command packet received from local host. " - "\n|%s| != |%s|\n" - "You may need to reload your server browser and %s.\n", - s, localid->string, PROGRAM); - Con_Printf("===========================\n"); - Cvar_Set(localid, ""); + Con_Printf ("===========================\n"); + Con_Printf + ("Invalid localid on command packet received from local host. " + "\n|%s| != |%s|\n" + "You may need to reload your server browser and %s.\n", s, + localid->string, PROGRAM); + Con_Printf ("===========================\n"); + Cvar_Set (localid, ""); return; } @@ -998,19 +995,16 @@ void CL_ConnectionlessPacket (void) return; } // print command from somewhere - if (c == A2C_PRINT) - { + if (c == A2C_PRINT) { Con_Printf ("print\n"); s = MSG_ReadString (); Con_Print (s); return; } - // ping from somewhere - if (c == A2A_PING) - { - char data[6]; + if (c == A2A_PING) { + char data[6]; Con_Printf ("ping\n"); @@ -1020,7 +1014,7 @@ void CL_ConnectionlessPacket (void) data[3] = 0xff; data[4] = A2A_ACK; data[5] = 0; - + NET_SendPacket (6, &data, net_from); return; } @@ -1029,7 +1023,7 @@ void CL_ConnectionlessPacket (void) Con_Printf ("challenge\n"); s = MSG_ReadString (); - cls.challenge = atoi(s); + cls.challenge = atoi (s); if (strstr (s, "QF")) CL_AddQFInfoKeys (); CL_SendConnectPacket (); @@ -1041,7 +1035,7 @@ void CL_ConnectionlessPacket (void) Host_EndGame ("End of demo"); else Con_Printf ("svc_disconnect\n"); -// Host_EndGame ("Server disconnected"); +// Host_EndGame ("Server disconnected"); return; } @@ -1054,55 +1048,50 @@ void CL_ConnectionlessPacket (void) CL_ReadPackets ================= */ -void CL_ReadPackets (void) +void +CL_ReadPackets (void) { -// while (NET_GetPacket ()) - while (CL_GetMessage()) - { - // +// while (NET_GetPacket ()) + while (CL_GetMessage ()) { + // // remote command packet - // - if (*(int *)net_message.data == -1) - { + // + if (*(int *) net_message.data == -1) { CL_ConnectionlessPacket (); continue; } - if (net_message.cursize < 8) - { - Con_Printf ("%s: Runt packet\n",NET_AdrToString(net_from)); + if (net_message.cursize < 8) { + Con_Printf ("%s: Runt packet\n", NET_AdrToString (net_from)); continue; } - - // + // // packet from server - // - if (!cls.demoplayback && - !NET_CompareAdr (net_from, cls.netchan.remote_address)) - { - Con_DPrintf ("%s:sequenced packet without connection\n" - ,NET_AdrToString(net_from)); + // + if (!cls.demoplayback && + !NET_CompareAdr (net_from, cls.netchan.remote_address)) { + Con_DPrintf ("%s:sequenced packet without connection\n", + NET_AdrToString (net_from)); continue; } - if (!Netchan_Process(&cls.netchan)) - continue; // wasn't accepted for some reason + if (!Netchan_Process (&cls.netchan)) + continue; // wasn't accepted for some reason CL_ParseServerMessage (); -// if (cls.demoplayback && cls.state >= ca_active && !CL_DemoBehind()) -// return; +// if (cls.demoplayback && cls.state >= ca_active && !CL_DemoBehind()) +// return; } - // + // // check timeout - // + // if (cls.state >= ca_connected - && realtime - cls.netchan.last_received > cl_timeout->value) - { + && realtime - cls.netchan.last_received > cl_timeout->value) { Con_Printf ("\nServer connection timed out.\n"); CL_Disconnect (); return; } - + } //============================================================================= @@ -1112,30 +1101,31 @@ void CL_ReadPackets (void) CL_Download_f ===================== */ -void CL_Download_f (void) +void +CL_Download_f (void) { - if (cls.state == ca_disconnected) - { + if (cls.state == ca_disconnected) { Con_Printf ("Must be connected.\n"); return; } - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("Usage: download \n"); return; } - snprintf (cls.downloadname, sizeof(cls.downloadname), "%s/%s", com_gamedir, Cmd_Argv(1)); + snprintf (cls.downloadname, sizeof (cls.downloadname), "%s/%s", com_gamedir, + Cmd_Argv (1)); COM_CreatePath (cls.downloadname); - strncpy (cls.downloadtempname, cls.downloadname, sizeof(cls.downloadtempname)); + strncpy (cls.downloadtempname, cls.downloadname, + sizeof (cls.downloadtempname)); cls.download = Qopen (cls.downloadname, "wb"); cls.downloadtype = dl_single; MSG_WriteByte (&cls.netchan.message, clc_stringcmd); - SZ_Print (&cls.netchan.message, va("download %s\n",Cmd_Argv(1))); + SZ_Print (&cls.netchan.message, va ("download %s\n", Cmd_Argv (1))); } #ifdef _WIN32 @@ -1145,11 +1135,13 @@ void CL_Download_f (void) CL_Minimize_f ================= */ -void CL_Windows_f (void) { -// if (modestate == MS_WINDOWED) -// ShowWindow(mainwindow, SW_MINIMIZE); -// else - SendMessage(mainwindow, WM_SYSKEYUP, VK_TAB, 1 | (0x0F << 16) | (1<<29)); +void +CL_Windows_f (void) +{ +// if (modestate == MS_WINDOWED) +// ShowWindow(mainwindow, SW_MINIMIZE); +// else + SendMessage (mainwindow, WM_SYSKEYUP, VK_TAB, 1 | (0x0F << 16) | (1 << 29)); } #endif @@ -1158,11 +1150,12 @@ void CL_Windows_f (void) { CL_Init ================= */ -void CL_Init (void) +void +CL_Init (void) { - QFile *servlist; - char st[80]; - char e_path[MAX_OSPATH]; + QFile *servlist; + char st[80]; + char e_path[MAX_OSPATH]; cls.state = ca_disconnected; @@ -1171,21 +1164,21 @@ void CL_Init (void) Info_SetValueForKey (cls.userinfo, "bottomcolor", "0", MAX_INFO_STRING); Info_SetValueForKey (cls.userinfo, "rate", "2500", MAX_INFO_STRING); Info_SetValueForKey (cls.userinfo, "msg", "1", MAX_INFO_STRING); -// snprintf (st, sizeof(st), "%s-%04d", QW_VERSION, build_number()); - snprintf (st, sizeof(st), "%s", QW_VERSION); +// snprintf (st, sizeof(st), "%s-%04d", QW_VERSION, build_number()); + snprintf (st, sizeof (st), "%s", QW_VERSION); Info_SetValueForStarKey (cls.userinfo, "*ver", st, MAX_INFO_STRING); - Info_SetValueForStarKey (cls.userinfo, "stdver", QSG_VERSION, MAX_INFO_STRING); + Info_SetValueForStarKey (cls.userinfo, "stdver", QSG_VERSION, + MAX_INFO_STRING); CL_Input_Init (); CL_TEnts_Init (); Pmove_Init (); - - Qexpand_squiggle(fs_userpath->string, e_path); - if ((servlist = Qopen(va("%s/servers.txt", e_path), "r"))) { - slist = SL_LoadF(servlist,slist); - Qclose(servlist); + + Qexpand_squiggle (fs_userpath->string, e_path); + if ((servlist = Qopen (va ("%s/servers.txt", e_path), "r"))) { + slist = SL_LoadF (servlist, slist); + Qclose (servlist); } - // // register our commands @@ -1244,120 +1237,117 @@ void CL_Init (void) } -void CL_Init_Cvars (void) +void +CL_Init_Cvars (void) { - extern cvar_t *baseskin; - extern cvar_t *noskins; + extern cvar_t *baseskin; + extern cvar_t *noskins; // LordHavoc: some people like it asking on quit, others don't... - confirm_quit = Cvar_Get("confirm_quit", "1", CVAR_ARCHIVE, "confirm quit command"); + confirm_quit = + Cvar_Get ("confirm_quit", "1", CVAR_ARCHIVE, "confirm quit command"); - show_fps = Cvar_Get("show_fps", "0", CVAR_NONE, - "display realtime frames per second"); + show_fps = Cvar_Get ("show_fps", "0", CVAR_NONE, + "display realtime frames per second"); // Misty: I like to be able to see the time when I play - show_time = Cvar_Get("show_time", "0", CVAR_NONE, - "display the current time"); - host_speeds = Cvar_Get("host_speeds", "0", CVAR_NONE, - "display host processing times"); - developer = Cvar_Get("developer", "0", CVAR_NONE, - "show info interesting to developers"); + show_time = Cvar_Get ("show_time", "0", CVAR_NONE, + "display the current time"); + host_speeds = Cvar_Get ("host_speeds", "0", CVAR_NONE, + "display host processing times"); + developer = Cvar_Get ("developer", "0", CVAR_NONE, + "show info interesting to developers"); - cl_autoexec = Cvar_Get ("cl_autoexec","0",CVAR_ROM, - "exec autoexec.cfg on gamedir change"); - cl_warncmd = Cvar_Get("cl_warncmd", "0", CVAR_NONE, - "inform when execing a command"); - cl_upspeed = Cvar_Get("cl_upspeed", "200", CVAR_NONE, - "swim/fly up/down speed"); - cl_forwardspeed = Cvar_Get("cl_forwardspeed", "200", CVAR_ARCHIVE, - "forward speed"); - cl_backspeed = Cvar_Get("cl_backspeed", "200", CVAR_ARCHIVE, - "backward speed"); - cl_sidespeed = Cvar_Get("cl_sidespeed", "350", CVAR_NONE, - "strafe speed"); - cl_movespeedkey = Cvar_Get("cl_movespeedkey", "2.0", CVAR_NONE, - "move `run' speed multiplier"); - cl_yawspeed = Cvar_Get("cl_yawspeed", "140", CVAR_NONE, - "turning speed"); - cl_pitchspeed = Cvar_Get("cl_pitchspeed", "150", CVAR_NONE, - "look up/down speed"); - cl_anglespeedkey = Cvar_Get("cl_anglespeedkey", "1.5", CVAR_NONE, - "turn `run' speed multiplier"); - cl_shownet = Cvar_Get("cl_shownet", "0", CVAR_NONE, - "show network packets. 0=off, 1=basic, 2=verbose"); - cl_sbar = Cvar_Get("cl_sbar", "0", CVAR_ARCHIVE, - "status bar mode"); - cl_sbar_separator = Cvar_Get("cl_sbar_separator", "0", CVAR_ARCHIVE, - "turns on status bar separator"); - cl_hudswap = Cvar_Get("cl_hudswap", "0", CVAR_ARCHIVE, - "new HUD on left side?"); - cl_maxfps = Cvar_Get("cl_maxfps", "0", CVAR_ARCHIVE, - "maximum frames rendered in one second. 0 == 32"); - cl_timeout = Cvar_Get("cl_timeout", "60", CVAR_ARCHIVE, - "server connection timeout (since last packet received)"); - lookspring = Cvar_Get("lookspring", "0", CVAR_ARCHIVE, - "Snap view to center when moving and no mlook/klook"); - lookstrafe = Cvar_Get("lookstrafe", "0", CVAR_ARCHIVE, - "when mlook/klook on player will strafe"); - sensitivity = Cvar_Get("sensitivity", "3", CVAR_ARCHIVE, - "mouse sensitivity multiplier"); - cl_freelook = Cvar_Get("freelook", "0", CVAR_ARCHIVE, - "force +mlook"); + cl_autoexec = Cvar_Get ("cl_autoexec", "0", CVAR_ROM, + "exec autoexec.cfg on gamedir change"); + cl_warncmd = Cvar_Get ("cl_warncmd", "0", CVAR_NONE, + "inform when execing a command"); + cl_upspeed = Cvar_Get ("cl_upspeed", "200", CVAR_NONE, + "swim/fly up/down speed"); + cl_forwardspeed = Cvar_Get ("cl_forwardspeed", "200", CVAR_ARCHIVE, + "forward speed"); + cl_backspeed = Cvar_Get ("cl_backspeed", "200", CVAR_ARCHIVE, + "backward speed"); + cl_sidespeed = Cvar_Get ("cl_sidespeed", "350", CVAR_NONE, "strafe speed"); + cl_movespeedkey = Cvar_Get ("cl_movespeedkey", "2.0", CVAR_NONE, + "move `run' speed multiplier"); + cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_NONE, "turning speed"); + cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "150", CVAR_NONE, + "look up/down speed"); + cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", CVAR_NONE, + "turn `run' speed multiplier"); + cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_NONE, + "show network packets. 0=off, 1=basic, 2=verbose"); + cl_sbar = Cvar_Get ("cl_sbar", "0", CVAR_ARCHIVE, "status bar mode"); + cl_sbar_separator = Cvar_Get ("cl_sbar_separator", "0", CVAR_ARCHIVE, + "turns on status bar separator"); + cl_hudswap = Cvar_Get ("cl_hudswap", "0", CVAR_ARCHIVE, + "new HUD on left side?"); + cl_maxfps = Cvar_Get ("cl_maxfps", "0", CVAR_ARCHIVE, + "maximum frames rendered in one second. 0 == 32"); + cl_timeout = Cvar_Get ("cl_timeout", "60", CVAR_ARCHIVE, + "server connection timeout (since last packet received)"); + lookspring = Cvar_Get ("lookspring", "0", CVAR_ARCHIVE, + "Snap view to center when moving and no mlook/klook"); + lookstrafe = Cvar_Get ("lookstrafe", "0", CVAR_ARCHIVE, + "when mlook/klook on player will strafe"); + sensitivity = Cvar_Get ("sensitivity", "3", CVAR_ARCHIVE, + "mouse sensitivity multiplier"); + cl_freelook = Cvar_Get ("freelook", "0", CVAR_ARCHIVE, "force +mlook"); - m_pitch = Cvar_Get("m_pitch", "0.022", CVAR_ARCHIVE, - "mouse pitch (up/down) multipier"); - m_yaw = Cvar_Get("m_yaw", "0.022", CVAR_NONE, - "mouse yaw (left/right) multipiler"); - m_forward = Cvar_Get("m_forward", "1", CVAR_NONE, - "mouse forward/back speed"); - m_side = Cvar_Get("m_side", "0.8", CVAR_NONE, - "mouse strafe speed"); + m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE, + "mouse pitch (up/down) multipier"); + m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_NONE, + "mouse yaw (left/right) multipiler"); + m_forward = Cvar_Get ("m_forward", "1", CVAR_NONE, + "mouse forward/back speed"); + m_side = Cvar_Get ("m_side", "0.8", CVAR_NONE, "mouse strafe speed"); - rcon_password = Cvar_Get("rcon_password", "", CVAR_NONE, - "remote control password"); - rcon_address = Cvar_Get("rcon_address", "", CVAR_NONE, - "server IP address when client not connected - for sending rcon commands"); + rcon_password = Cvar_Get ("rcon_password", "", CVAR_NONE, + "remote control password"); + rcon_address = Cvar_Get ("rcon_address", "", CVAR_NONE, + "server IP address when client not connected - for sending rcon commands"); - cl_predict_players2 = Cvar_Get("cl_predict_players2", "1", CVAR_NONE, - "If this and cl_predict_players is 0, no player prediction is done"); - cl_predict_players = Cvar_Get("cl_predict_players", "1", CVAR_NONE, - "If this and cl_predict_players2 is 0, no player prediction is done"); - cl_solid_players = Cvar_Get("cl_solid_players", "1", CVAR_NONE, - "Are players solid? If off, you can walk through them with difficulty"); + cl_predict_players2 = Cvar_Get ("cl_predict_players2", "1", CVAR_NONE, + "If this and cl_predict_players is 0, no player prediction is done"); + cl_predict_players = Cvar_Get ("cl_predict_players", "1", CVAR_NONE, + "If this and cl_predict_players2 is 0, no player prediction is done"); + cl_solid_players = Cvar_Get ("cl_solid_players", "1", CVAR_NONE, + "Are players solid? If off, you can walk through them with difficulty"); - /* Misty: FIXME: Nobody knows exactly what this does. Someone has to find out, proboably me. */ - localid = Cvar_Get("localid", "", CVAR_NONE, - "FIXME: nobody knows what this does."); + /* Misty: FIXME: Nobody knows exactly what this does. Someone has to find + out, proboably me. */ + localid = Cvar_Get ("localid", "", CVAR_NONE, + "FIXME: nobody knows what this does."); - baseskin = Cvar_Get("baseskin", "base", CVAR_NONE, - "default base skin name"); - noskins = Cvar_Get("noskins", "0", CVAR_NONE, - "set to 1 to not download new skins"); + baseskin = Cvar_Get ("baseskin", "base", CVAR_NONE, + "default base skin name"); + noskins = Cvar_Get ("noskins", "0", CVAR_NONE, + "set to 1 to not download new skins"); - // + // // info mirrors - // - name = Cvar_Get("name", "unnamed", CVAR_ARCHIVE|CVAR_USERINFO, - "Player name"); - password = Cvar_Get("password", "", CVAR_USERINFO, - "Server password"); - spectator = Cvar_Get("spectator", "", CVAR_USERINFO, - "Set to 1 before connecting to become a spectator"); - skin = Cvar_Get("skin", "", CVAR_ARCHIVE|CVAR_USERINFO, - "Players skin"); - team = Cvar_Get("team", "", CVAR_ARCHIVE|CVAR_USERINFO, - "Team player is on."); - topcolor = Cvar_Get("topcolor", "0", CVAR_ARCHIVE|CVAR_USERINFO, - "Players color on top"); - bottomcolor = Cvar_Get("bottomcolor", "0", CVAR_ARCHIVE|CVAR_USERINFO, - "Players color on bottom"); - /* Misty: FIXME: Nobody seems to know exactly what this rate *IS* - bytes/packets/what?? */ - rate = Cvar_Get("rate", "2500", CVAR_ARCHIVE|CVAR_USERINFO, - "download rate"); - /* Misty: FIXME: We need to find out exactly *what* it does suppress/allow */ - msg = Cvar_Get("msg", "1", CVAR_ARCHIVE|CVAR_USERINFO, - "Message level"); - noaim = Cvar_Get("noaim", "0", CVAR_ARCHIVE|CVAR_USERINFO, - "Auto aim off switch. Set to 1 to turn off."); + // + name = Cvar_Get ("name", "unnamed", CVAR_ARCHIVE | CVAR_USERINFO, + "Player name"); + password = Cvar_Get ("password", "", CVAR_USERINFO, "Server password"); + spectator = Cvar_Get ("spectator", "", CVAR_USERINFO, + "Set to 1 before connecting to become a spectator"); + skin = Cvar_Get ("skin", "", CVAR_ARCHIVE | CVAR_USERINFO, "Players skin"); + team = Cvar_Get ("team", "", CVAR_ARCHIVE | CVAR_USERINFO, + "Team player is on."); + topcolor = Cvar_Get ("topcolor", "0", CVAR_ARCHIVE | CVAR_USERINFO, + "Players color on top"); + bottomcolor = Cvar_Get ("bottomcolor", "0", CVAR_ARCHIVE | CVAR_USERINFO, + "Players color on bottom"); + /* Misty: FIXME: Nobody seems to know exactly what this rate *IS* - + bytes/packets/what?? */ + rate = Cvar_Get ("rate", "2500", CVAR_ARCHIVE | CVAR_USERINFO, + "download rate"); + /* Misty: FIXME: We need to find out exactly *what* it does + suppress/allow */ + msg = Cvar_Get ("msg", "1", CVAR_ARCHIVE | CVAR_USERINFO, "Message level"); + noaim = Cvar_Get ("noaim", "0", CVAR_ARCHIVE | CVAR_USERINFO, + "Auto aim off switch. Set to 1 to turn off."); } /* @@ -1367,18 +1357,19 @@ Host_EndGame Call this to drop to a console without exiting the qwcl ================ */ -void Host_EndGame (char *message, ...) +void +Host_EndGame (char *message, ...) { - va_list argptr; - char string[1024]; - + va_list argptr; + char string[1024]; + va_start (argptr, message); - vsnprintf (string, sizeof(string), message, argptr); + vsnprintf (string, sizeof (string), message, argptr); va_end (argptr); Con_Printf ("\n===========================\n"); - Con_Printf ("Host_EndGame: %s\n",string); + Con_Printf ("Host_EndGame: %s\n", string); Con_Printf ("===========================\n\n"); - + CL_Disconnect (); longjmp (host_abort, 1); @@ -1391,28 +1382,29 @@ Host_Error This shuts down the client and exits qwcl ================ */ -void Host_Error (char *error, ...) +void +Host_Error (char *error, ...) { - va_list argptr; - char string[1024]; - static qboolean inerror = false; - + va_list argptr; + char string[1024]; + static qboolean inerror = false; + if (inerror) Sys_Error ("Host_Error: recursively entered"); inerror = true; - - va_start (argptr,error); - vsnprintf (string, sizeof(string), error, argptr); + + va_start (argptr, error); + vsnprintf (string, sizeof (string), error, argptr); va_end (argptr); - Con_Printf ("Host_Error: %s\n",string); - + Con_Printf ("Host_Error: %s\n", string); + CL_Disconnect (); cls.demonum = -1; inerror = false; // FIXME - Sys_Error ("Host_Error: %s\n",string); + Sys_Error ("Host_Error: %s\n", string); } @@ -1423,21 +1415,21 @@ Host_WriteConfiguration Writes key bindings and archived cvars to config.cfg =============== */ -void Host_WriteConfiguration (void) +void +Host_WriteConfiguration (void) { - QFile *f; + QFile *f; + + if (host_initialized) { + char *path = va ("%s/config.cfg", com_gamedir); - if (host_initialized) - { - char *path = va("%s/config.cfg",com_gamedir); COM_CreatePath (path); f = Qopen (path, "w"); - if (!f) - { + if (!f) { Con_Printf ("Couldn't write config.cfg.\n"); return; } - + Key_WriteBindings (f); Cvar_WriteVariables (f); @@ -1456,20 +1448,21 @@ Host_SimulationTime This determines if enough time has passed to run a simulation frame ================== */ -qboolean Host_SimulationTime(float time) +qboolean +Host_SimulationTime (float time) { - float fps; + float fps; if (oldrealtime > realtime) oldrealtime = 0; if (cl_maxfps->int_val) - fps = max(30.0, min(cl_maxfps->value, 72.0)); + fps = max (30.0, min (cl_maxfps->value, 72.0)); else - fps = max(30.0, min(rate->value/80.0, 72.0)); + fps = max (30.0, min (rate->value / 80.0, 72.0)); - if (!cls.timedemo && (realtime + time) - oldrealtime < 1.0/fps) - return false; // framerate is too high + if (!cls.timedemo && (realtime + time) - oldrealtime < 1.0 / fps) + return false; // framerate is too high return true; } #endif @@ -1482,16 +1475,19 @@ Host_Frame Runs all active servers ================== */ -int nopacketcount; -void Host_Frame (float time) +int nopacketcount; +void +Host_Frame (float time) { - static double time1 = 0; - static double time2 = 0; - static double time3 = 0; - int pass1, pass2, pass3; - float fps; - if (setjmp (host_abort) ) - return; // something bad happened, or the server disconnected + static double time1 = 0; + static double time2 = 0; + static double time3 = 0; + int pass1, pass2, pass3; + float fps; + + if (setjmp (host_abort)) + return; // something bad happened, or the + // server disconnected // decide the simulation time realtime += time; @@ -1499,18 +1495,18 @@ void Host_Frame (float time) oldrealtime = 0; if (cl_maxfps->value) - fps = max(30.0, min(cl_maxfps->value, 72.0)); + fps = max (30.0, min (cl_maxfps->value, 72.0)); else - fps = max(30.0, min(rate->value/80.0, 72.0)); + fps = max (30.0, min (rate->value / 80.0, 72.0)); - if (!cls.timedemo && realtime - oldrealtime < 1.0/fps) - return; // framerate is too high + if (!cls.timedemo && realtime - oldrealtime < 1.0 / fps) + return; // framerate is too high host_frametime = realtime - oldrealtime; oldrealtime = realtime; if (host_frametime > 0.2) host_frametime = 0.2; - + // get new key events IN_SendKeyEvents (); @@ -1523,7 +1519,7 @@ void Host_Frame (float time) // fetch results from server CL_ReadPackets (); - if (atoi(Info_ValueForKey(cl.serverinfo, "no_pogo_stick"))) + if (atoi (Info_ValueForKey (cl.serverinfo, "no_pogo_stick"))) Cvar_Set (no_pogo_stick, "1"); // send intentions now @@ -1534,13 +1530,13 @@ void Host_Frame (float time) CL_SendCmd (); // Set up prediction for other players - CL_SetUpPlayerPrediction(false); + CL_SetUpPlayerPrediction (false); // do client side motion prediction CL_PredictMove (); // Set up prediction for other players - CL_SetUpPlayerPrediction(true); + CL_SetUpPlayerPrediction (true); // build a refresh entity list CL_EmitEntities (); @@ -1553,26 +1549,23 @@ void Host_Frame (float time) if (host_speeds->int_val) time2 = Sys_DoubleTime (); - + // update audio - if (cls.state == ca_active) - { + if (cls.state == ca_active) { S_Update (r_origin, vpn, vright, vup); CL_DecayLights (); - } - else + } else S_Update (vec3_origin, vec3_origin, vec3_origin, vec3_origin); - - CDAudio_Update(); - if (host_speeds->int_val) - { - pass1 = (time1 - time3)*1000; + CDAudio_Update (); + + if (host_speeds->int_val) { + pass1 = (time1 - time3) * 1000; time3 = Sys_DoubleTime (); - pass2 = (time2 - time1)*1000; - pass3 = (time3 - time2)*1000; + pass2 = (time2 - time1) * 1000; + pass3 = (time3 - time2) * 1000; Con_Printf ("%3i tot %3i server %3i gfx %3i snd\n", - pass1+pass2+pass3, pass1, pass2, pass3); + pass1 + pass2 + pass3, pass1, pass2, pass3); } host_framecount++; @@ -1586,19 +1579,20 @@ void Host_Frame (float time) Host_Init ==================== */ -void Host_Init (void) +void +Host_Init (void) { if (COM_CheckParm ("-minmemory")) host_parms.memsize = MINIMUM_MEMORY; if (host_parms.memsize < MINIMUM_MEMORY) Sys_Error ("Only %4.1f megs of memory reported, can't execute game", - host_parms.memsize / (float)0x100000); + host_parms.memsize / (float) 0x100000); Memory_Init (host_parms.membase, host_parms.memsize); Cvar_Init (); Sys_Init_Cvars (); - Sys_Init(); + Sys_Init (); Cbuf_Init (); Cmd_Init (); @@ -1612,8 +1606,8 @@ void Host_Init (void) // would have been nice if Cmd_Exec_f could have been used, but it // only reads from within the quake file system, and changing that is // probably Not A Good Thing (tm). - fs_globalcfg = Cvar_Get("fs_globalcfg", FS_GLOBALCFG, - CVAR_ROM, "global configuration file"); + fs_globalcfg = Cvar_Get ("fs_globalcfg", FS_GLOBALCFG, + CVAR_ROM, "global configuration file"); Cmd_Exec_File (fs_globalcfg->string); Cbuf_Execute_Sets (); @@ -1655,19 +1649,19 @@ void Host_Init (void) W_LoadWadFile ("gfx.wad"); Key_Init (); - Con_Init (); - M_Init (); + Con_Init (); + M_Init (); Mod_Init (); - -// Con_Printf ("Exe: "__TIME__" "__DATE__"\n"); - Con_Printf ("%4.1f megs RAM used.\n",host_parms.memsize/ (1024*1024.0)); - + +// Con_Printf ("Exe: "__TIME__" "__DATE__"\n"); + Con_Printf ("%4.1f megs RAM used.\n", host_parms.memsize / (1024 * 1024.0)); + R_Textures_Init (); - - host_basepal = (byte *)COM_LoadHunkFile ("gfx/palette.lmp"); + + host_basepal = (byte *) COM_LoadHunkFile ("gfx/palette.lmp"); if (!host_basepal) Sys_Error ("Couldn't load gfx/palette.lmp"); - host_colormap = (byte *)COM_LoadHunkFile ("gfx/colormap.lmp"); + host_colormap = (byte *) COM_LoadHunkFile ("gfx/colormap.lmp"); if (!host_colormap) Sys_Error ("Couldn't load gfx/colormap.lmp"); #ifdef __linux__ @@ -1679,7 +1673,7 @@ void Host_Init (void) R_Init (); S_Init (); - + cls.state = ca_disconnected; Sbar_Init (); CL_Init (); @@ -1699,7 +1693,8 @@ void Host_Init (void) #endif Cbuf_InsertText ("exec quake.rc\n"); - Cbuf_AddText ("echo Type connect or use GameSpy to connect to a game.\n"); + Cbuf_AddText + ("echo Type connect or use GameSpy to connect to a game.\n"); Cbuf_AddText ("cl_warncmd 1\n"); Hunk_AllocName (0, "-HOST_HUNKLEVEL-"); @@ -1707,7 +1702,8 @@ void Host_Init (void) host_initialized = true; - Con_Printf ("\nClient version %s (build %04d)\n\n", VERSION, build_number ()); + Con_Printf ("\nClient version %s (build %04d)\n\n", VERSION, + build_number ()); Con_Printf ("€‚ %s initialized €‚\n", PROGRAM); } @@ -1721,12 +1717,12 @@ FIXME: this is a callback from Sys_Quit and Sys_Error. It would be better to run quit through here before the final handoff to the sys code. =============== */ -void Host_Shutdown(void) +void +Host_Shutdown (void) { static qboolean isdown = false; - - if (isdown) - { + + if (isdown) { printf ("recursive shutdown\n"); return; } @@ -1734,13 +1730,12 @@ void Host_Shutdown(void) SL_Shutdown (slist); - Host_WriteConfiguration (); - + Host_WriteConfiguration (); + CDAudio_Shutdown (); NET_Shutdown (); - S_Shutdown(); + S_Shutdown (); IN_Shutdown (); if (host_basepal) - VID_Shutdown(); + VID_Shutdown (); } - diff --git a/source/cl_misc.c b/source/cl_misc.c index 0014226..e2b9ea2 100644 --- a/source/cl_misc.c +++ b/source/cl_misc.c @@ -27,25 +27,27 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" #include "sys.h" -qboolean ServerPaused (void) +qboolean +ServerPaused (void) { return false; } -void SV_Error (char *error, ...) +void +SV_Error (char *error, ...) { - va_list argptr; - static char string[1024]; + va_list argptr; + static char string[1024]; va_start (argptr, error); - vsnprintf (string, sizeof(string), error, argptr); + vsnprintf (string, sizeof (string), error, argptr); va_end (argptr); - Sys_Error ("%s\n",string); + Sys_Error ("%s\n", string); } diff --git a/source/cl_parse.c b/source/cl_parse.c index c0a8899..b788f5e 100644 --- a/source/cl_parse.c +++ b/source/cl_parse.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -60,39 +60,41 @@ #include #endif -extern cvar_t *gl_flashblend; -extern cvar_t *cl_autoexec; +extern cvar_t *gl_flashblend; +extern cvar_t *cl_autoexec; -char *svc_strings[] = -{ +char *svc_strings[] = { "svc_bad", "svc_nop", "svc_disconnect", "svc_updatestat", - "svc_version", // [long] server version - "svc_setview", // [short] entity number - "svc_sound", // - "svc_time", // [float] server time - "svc_print", // [string] null terminated string - "svc_stufftext", // [string] stuffed into client's console buffer - // the string should be \n terminated - "svc_setangle", // [vec3] set the view angle to this absolute value - - "svc_serverdata", // [long] version ... - "svc_lightstyle", // [byte] [string] - "svc_updatename", // [byte] [string] - "svc_updatefrags", // [byte] [short] - "svc_clientdata", // - "svc_stopsound", // - "svc_updatecolors", // [byte] [byte] - "svc_particle", // [vec3] - "svc_damage", // [byte] impact [byte] blood [vec3] from - + "svc_version", // [long] server version + "svc_setview", // [short] entity number + "svc_sound", // + "svc_time", // [float] server time + "svc_print", // [string] null terminated string + "svc_stufftext", // [string] stuffed into client's + // console buffer + // the string should be \n terminated + "svc_setangle", // [vec3] set the view angle to this + // absolute value + + "svc_serverdata", // [long] version ... + "svc_lightstyle", // [byte] [string] + "svc_updatename", // [byte] [string] + "svc_updatefrags", // [byte] [short] + "svc_clientdata", // + "svc_stopsound", // + "svc_updatecolors", // [byte] [byte] + "svc_particle", // [vec3] + "svc_damage", // [byte] impact [byte] blood [vec3] + // from + "svc_spawnstatic", "OBSOLETE svc_spawnbinary", "svc_spawnbaseline", - - "svc_temp_entity", // + + "svc_temp_entity", // "svc_setpause", "svc_signonnum", "svc_centerprint", @@ -121,7 +123,7 @@ char *svc_strings[] = "svc_modellist", "svc_soundlist", "svc_packetentities", - "svc_deltapacketentities", + "svc_deltapacketentities", "svc_maxspeed", "svc_entgravity", @@ -143,42 +145,41 @@ char *svc_strings[] = "NEW PROTOCOL" }; -int oldparsecountmod; -int parsecountmod; -double parsecounttime; +int oldparsecountmod; +int parsecountmod; +double parsecounttime; -int cl_spikeindex, cl_playerindex, cl_flagindex; -int cl_h_playerindex, cl_gib1index, cl_gib2index, cl_gib3index; +int cl_spikeindex, cl_playerindex, cl_flagindex; +int cl_h_playerindex, cl_gib1index, cl_gib2index, cl_gib3index; //============================================================================= -int packet_latency[NET_TIMINGS]; +int packet_latency[NET_TIMINGS]; -int CL_CalcNet (void) +int +CL_CalcNet (void) { - int a, i; - frame_t *frame; - int lost; + int a, i; + frame_t *frame; + int lost; - for (i=cls.netchan.outgoing_sequence-UPDATE_BACKUP+1 - ; i <= cls.netchan.outgoing_sequence - ; i++) - { - frame = &cl.frames[i&UPDATE_MASK]; + for (i = cls.netchan.outgoing_sequence - UPDATE_BACKUP + 1; + i <= cls.netchan.outgoing_sequence; i++) { + frame = &cl.frames[i & UPDATE_MASK]; if (frame->receivedtime == -1) - packet_latency[i&NET_TIMINGSMASK] = 9999; // dropped + packet_latency[i & NET_TIMINGSMASK] = 9999; // dropped else if (frame->receivedtime == -2) - packet_latency[i&NET_TIMINGSMASK] = 10000; // choked + packet_latency[i & NET_TIMINGSMASK] = 10000; // choked else if (frame->invalid) - packet_latency[i&NET_TIMINGSMASK] = 9998; // invalid delta + packet_latency[i & NET_TIMINGSMASK] = 9998; // invalid delta else - packet_latency[i&NET_TIMINGSMASK] = (frame->receivedtime - frame->senttime)*20; + packet_latency[i & NET_TIMINGSMASK] = + (frame->receivedtime - frame->senttime) * 20; } lost = 0; - for (a=0 ; achecksum2)); - MSG_WriteString (&cls.netchan.message, va(prespawn_name, cl.servercount, cl.worldmodel->checksum2)); +// MSG_WriteString (&cls.netchan.message, va("prespawn %i 0 %i", cl.servercount, cl.worldmodel->checksum2)); + MSG_WriteString (&cls.netchan.message, + va (prespawn_name, cl.servercount, + cl.worldmodel->checksum2)); } /* @@ -306,44 +309,42 @@ void Model_NextDownload (void) Sound_NextDownload ================= */ -void Sound_NextDownload (void) +void +Sound_NextDownload (void) { - char *s; - int i; + char *s; + int i; - if (cls.downloadnumber == 0) - { + if (cls.downloadnumber == 0) { Con_Printf ("Checking sounds...\n"); cls.downloadnumber = 1; } cls.downloadtype = dl_sound; - for ( - ; cl.sound_name[cls.downloadnumber][0] - ; cls.downloadnumber++) - { + for (; cl.sound_name[cls.downloadnumber][0]; + cls.downloadnumber++) { s = cl.sound_name[cls.downloadnumber]; - if (!CL_CheckOrDownloadFile(va("sound/%s",s))) - return; // started a download + if (!CL_CheckOrDownloadFile (va ("sound/%s", s))) + return; // started a download } - for (i=1 ; i 0) msg_readcount += size; - return; // not in demo playback + return; // not in demo playback } if (size == -1) { @@ -409,11 +411,13 @@ void CL_ParseDownload (void) } if (size == -2) { - char *newname = MSG_ReadString(); - if (strncmp (newname, cls.downloadname, strlen(cls.downloadname)) - || strstr(newname+strlen(cls.downloadname), "/")) { - Con_Printf ("WARNING: server tried to give a strange new name: %s\n", - newname); + char *newname = MSG_ReadString (); + + if (strncmp (newname, cls.downloadname, strlen (cls.downloadname)) + || strstr (newname + strlen (cls.downloadname), "/")) { + Con_Printf + ("WARNING: server tried to give a strange new name: %s\n", + newname); CL_RequestNextDownload (); return; } @@ -425,13 +429,14 @@ void CL_ParseDownload (void) Con_Printf ("downloading to %s\n", cls.downloadname); return; } - // open the file if not opened yet if (!cls.download) { - if (strncmp(cls.downloadtempname,"skins/",6)) - snprintf (name, sizeof(name), "%s/%s", com_gamedir, cls.downloadtempname); + if (strncmp (cls.downloadtempname, "skins/", 6)) + snprintf (name, sizeof (name), "%s/%s", com_gamedir, + cls.downloadtempname); else - snprintf (name, sizeof(name), "%s/qw/%s", fs_userpath->string, cls.downloadtempname); + snprintf (name, sizeof (name), "%s/qw/%s", fs_userpath->string, + cls.downloadtempname); COM_CreatePath (name); @@ -452,20 +457,21 @@ void CL_ParseDownload (void) // request next block #if 0 Con_Printf ("."); - if (10*(percent/10) != cls.downloadpercent) { - cls.downloadpercent = 10*(percent/10); + if (10 * (percent / 10) != cls.downloadpercent) { + cls.downloadpercent = 10 * (percent / 10); Con_Printf ("%i%%", cls.downloadpercent); } #endif if (percent != cls.downloadpercent) - VID_SetCaption (va ("Downloading %s %d%%", cls.downloadname, percent)); + VID_SetCaption (va + ("Downloading %s %d%%", cls.downloadname, percent)); cls.downloadpercent = percent; MSG_WriteByte (&cls.netchan.message, clc_stringcmd); SZ_Print (&cls.netchan.message, "nextdl"); } else { - char oldn[MAX_OSPATH]; - char newn[MAX_OSPATH]; + char oldn[MAX_OSPATH]; + char newn[MAX_OSPATH]; #if 0 Con_Printf ("100%%\n"); @@ -475,17 +481,21 @@ void CL_ParseDownload (void) VID_SetCaption (va ("Connecting to %s", cls.servername)); // rename the temp file to it's final name - if (strcmp(cls.downloadtempname, cls.downloadname)) { - if (strncmp(cls.downloadtempname,"skins/",6)) { - snprintf (oldn, sizeof(oldn), "%s/%s", com_gamedir, cls.downloadtempname); - snprintf (newn, sizeof(newn), "%s/%s", com_gamedir, cls.downloadname); + if (strcmp (cls.downloadtempname, cls.downloadname)) { + if (strncmp (cls.downloadtempname, "skins/", 6)) { + snprintf (oldn, sizeof (oldn), "%s/%s", com_gamedir, + cls.downloadtempname); + snprintf (newn, sizeof (newn), "%s/%s", com_gamedir, + cls.downloadname); } else { - snprintf (oldn, sizeof(oldn), "%s/qw/%s", fs_userpath->string, cls.downloadtempname); - snprintf (newn, sizeof(newn), "%s/qw/%s", fs_userpath->string, cls.downloadname); + snprintf (oldn, sizeof (oldn), "%s/qw/%s", fs_userpath->string, + cls.downloadtempname); + snprintf (newn, sizeof (newn), "%s/qw/%s", fs_userpath->string, + cls.downloadname); } r = Qrename (oldn, newn); if (r) - Con_Printf ("failed to rename, %s.\n", strerror(errno)); + Con_Printf ("failed to rename, %s.\n", strerror (errno)); } cls.download = NULL; @@ -498,15 +508,16 @@ void CL_ParseDownload (void) } static byte *upload_data; -static int upload_pos; -static int upload_size; +static int upload_pos; +static int upload_size; -void CL_NextUpload(void) +void +CL_NextUpload (void) { - byte buffer[1024]; - int r; - int percent; - int size; + byte buffer[1024]; + int r; + int percent; + int size; if (!upload_data) return; @@ -514,7 +525,7 @@ void CL_NextUpload(void) r = upload_size - upload_pos; if (r > 768) r = 768; - memcpy(buffer, upload_data + upload_pos, r); + memcpy (buffer, upload_data + upload_pos, r); MSG_WriteByte (&cls.netchan.message, clc_upload); MSG_WriteShort (&cls.netchan.message, r); @@ -522,52 +533,55 @@ void CL_NextUpload(void) size = upload_size; if (!size) size = 1; - percent = upload_pos*100/size; + percent = upload_pos * 100 / size; MSG_WriteByte (&cls.netchan.message, percent); SZ_Write (&cls.netchan.message, buffer, r); -Con_DPrintf ("UPLOAD: %6d: %d written\n", upload_pos - r, r); + Con_DPrintf ("UPLOAD: %6d: %d written\n", upload_pos - r, r); if (upload_pos != upload_size) return; Con_Printf ("Upload completed\n"); - free(upload_data); + free (upload_data); upload_data = 0; upload_pos = upload_size = 0; } -void CL_StartUpload (byte *data, int size) +void +CL_StartUpload (byte * data, int size) { if (cls.state < ca_onserver) - return; // gotta be connected + return; // gotta be connected // override if (upload_data) - free(upload_data); + free (upload_data); -Con_DPrintf("Upload starting of %d...\n", size); + Con_DPrintf ("Upload starting of %d...\n", size); - upload_data = malloc(size); - memcpy(upload_data, data, size); + upload_data = malloc (size); + memcpy (upload_data, data, size); upload_size = size; upload_pos = 0; - CL_NextUpload(); -} + CL_NextUpload (); +} -qboolean CL_IsUploading(void) +qboolean +CL_IsUploading (void) { if (upload_data) return true; return false; } -void CL_StopUpload(void) +void +CL_StopUpload (void) { if (upload_data) - free(upload_data); + free (upload_data); upload_data = NULL; } @@ -579,22 +593,24 @@ void CL_StopUpload(void) ===================================================================== */ -void Draw_ClearCache (void); +void Draw_ClearCache (void); + +void CL_ClearBaselines (); // LordHavoc: BIG BUG-FIX! -void CL_ClearBaselines(); // LordHavoc: BIG BUG-FIX! /* ================== CL_ParseServerData ================== */ -void CL_ParseServerData (void) +void +CL_ParseServerData (void) { - char *str; - char fn[MAX_OSPATH]; - qboolean cflag = false; - extern char gamedirfile[MAX_OSPATH]; - int protover; - + char *str; + char fn[MAX_OSPATH]; + qboolean cflag = false; + extern char gamedirfile[MAX_OSPATH]; + int protover; + Con_DPrintf ("Serverdata packet received.\n"); // // wipe the client_state_t struct @@ -604,85 +620,91 @@ void CL_ParseServerData (void) // parse protocol version number // allow 2.2 and 2.29 demos to play protover = MSG_ReadLong (); - if (protover != PROTOCOL_VERSION && - !(cls.demoplayback && (protover == 26 || protover == 27 || protover == 28))) - Host_EndGame ("Server returned version %i, not %i\nYou probably need to upgrade.\nCheck http://www.quakeworld.net/", protover, PROTOCOL_VERSION); + if (protover != PROTOCOL_VERSION && + !(cls.demoplayback + && (protover == 26 || protover == 27 + || protover == + 28))) + Host_EndGame + ("Server returned version %i, not %i\nYou probably need to upgrade.\nCheck http://www.quakeworld.net/", + protover, PROTOCOL_VERSION); cl.servercount = MSG_ReadLong (); // game directory str = MSG_ReadString (); - if (stricmp(gamedirfile, str)) { + if (stricmp (gamedirfile, str)) { // save current config - Host_WriteConfiguration (); + Host_WriteConfiguration (); cflag = true; Draw_ClearCache (); } - COM_Gamedir(str); + COM_Gamedir (str); - //ZOID--run the autoexec.cfg in the gamedir - //if it exists + // ZOID--run the autoexec.cfg in the gamedir + // if it exists if (cflag) { - int cl_warncmd_val = cl_warncmd->int_val; + int cl_warncmd_val = cl_warncmd->int_val; + Cbuf_AddText ("cl_warncmd 0\n"); Cbuf_AddText ("exec config.cfg\n"); Cbuf_AddText ("exec frontend.cfg\n"); if (cl_autoexec->int_val) { Cbuf_AddText ("exec autoexec.cfg\n"); } - snprintf(fn,sizeof(fn), "cl_warncmd %d\n", cl_warncmd_val); - Cbuf_AddText(fn); + snprintf (fn, sizeof (fn), "cl_warncmd %d\n", cl_warncmd_val); + Cbuf_AddText (fn); } - // parse player slot, high bit means spectator cl.playernum = MSG_ReadByte (); - if (cl.playernum & 128) - { + if (cl.playernum & 128) { cl.spectator = true; cl.playernum &= ~128; } - // get the full level name str = MSG_ReadString (); - strncpy (cl.levelname, str, sizeof(cl.levelname)-1); + strncpy (cl.levelname, str, sizeof (cl.levelname) - 1); // get the movevars - movevars.gravity = MSG_ReadFloat(); - movevars.stopspeed = MSG_ReadFloat(); - movevars.maxspeed = MSG_ReadFloat(); - movevars.spectatormaxspeed = MSG_ReadFloat(); - movevars.accelerate = MSG_ReadFloat(); - movevars.airaccelerate = MSG_ReadFloat(); - movevars.wateraccelerate = MSG_ReadFloat(); - movevars.friction = MSG_ReadFloat(); - movevars.waterfriction = MSG_ReadFloat(); - movevars.entgravity = MSG_ReadFloat(); + movevars.gravity = MSG_ReadFloat (); + movevars.stopspeed = MSG_ReadFloat (); + movevars.maxspeed = MSG_ReadFloat (); + movevars.spectatormaxspeed = MSG_ReadFloat (); + movevars.accelerate = MSG_ReadFloat (); + movevars.airaccelerate = MSG_ReadFloat (); + movevars.wateraccelerate = MSG_ReadFloat (); + movevars.friction = MSG_ReadFloat (); + movevars.waterfriction = MSG_ReadFloat (); + movevars.entgravity = MSG_ReadFloat (); // seperate the printfs so the server message can have a color - Con_Printf("\n\n\35\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\37\n\n"); + Con_Printf + ("\n\n\35\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\36\37\n\n"); Con_Printf ("%c%s\n", 2, str); // ask for the sound list next - memset(cl.sound_name, 0, sizeof(cl.sound_name)); + memset (cl.sound_name, 0, sizeof (cl.sound_name)); MSG_WriteByte (&cls.netchan.message, clc_stringcmd); -// MSG_WriteString (&cls.netchan.message, va("soundlist %i 0", cl.servercount)); - MSG_WriteString (&cls.netchan.message, va(soundlist_name, cl.servercount, 0)); +// MSG_WriteString (&cls.netchan.message, va("soundlist %i 0", cl.servercount)); + MSG_WriteString (&cls.netchan.message, + va (soundlist_name, cl.servercount, 0)); // now waiting for downloads, etc cls.state = ca_onserver; - CL_ClearBaselines(); + CL_ClearBaselines (); } // LordHavoc: BIG BUG-FIX! Clear baselines each time it connects... -void CL_ClearBaselines() +void +CL_ClearBaselines () { - int i; - memset(cl_baselines, 0, sizeof(cl_baselines)); - for (i = 0;i < MAX_EDICTS;i++) - { + int i; + + memset (cl_baselines, 0, sizeof (cl_baselines)); + for (i = 0; i < MAX_EDICTS; i++) { cl_baselines[i].alpha = 255; cl_baselines[i].scale = 16; cl_baselines[i].glowcolor = 254; @@ -696,16 +718,17 @@ void CL_ClearBaselines() CL_ParseSoundlist ================== */ -void CL_ParseSoundlist (void) +void +CL_ParseSoundlist (void) { - int numsounds; - char *str; - int n; + int numsounds; + char *str; + int n; // precache sounds -// memset (cl.sound_precache, 0, sizeof(cl.sound_precache)); +// memset (cl.sound_precache, 0, sizeof(cl.sound_precache)); - numsounds = MSG_ReadByte(); + numsounds = MSG_ReadByte (); for (;;) { str = MSG_ReadString (); @@ -717,12 +740,13 @@ void CL_ParseSoundlist (void) strcpy (cl.sound_name[numsounds], str); } - n = MSG_ReadByte(); + n = MSG_ReadByte (); if (n) { MSG_WriteByte (&cls.netchan.message, clc_stringcmd); -// MSG_WriteString (&cls.netchan.message, va("soundlist %i %i", cl.servercount, n)); - MSG_WriteString (&cls.netchan.message, va(soundlist_name, cl.servercount, n)); +// MSG_WriteString (&cls.netchan.message, va("soundlist %i %i", cl.servercount, n)); + MSG_WriteString (&cls.netchan.message, + va (soundlist_name, cl.servercount, n)); return; } @@ -736,48 +760,49 @@ void CL_ParseSoundlist (void) CL_ParseModellist ================== */ -void CL_ParseModellist (void) +void +CL_ParseModellist (void) { - int nummodels; - char *str; - int n; + int nummodels; + char *str; + int n; // precache models and note certain default indexes - nummodels = MSG_ReadByte(); + nummodels = MSG_ReadByte (); - for (;;) - { + for (;;) { str = MSG_ReadString (); if (!str[0]) break; nummodels++; - if (nummodels==MAX_MODELS) + if (nummodels == MAX_MODELS) Host_EndGame ("Server sent too many model_precache"); strcpy (cl.model_name[nummodels], str); - if (!strcmp(cl.model_name[nummodels],"progs/spike.mdl")) + if (!strcmp (cl.model_name[nummodels], "progs/spike.mdl")) cl_spikeindex = nummodels; - else if (!strcmp(cl.model_name[nummodels],"progs/player.mdl")) + else if (!strcmp (cl.model_name[nummodels], "progs/player.mdl")) cl_playerindex = nummodels; - else if (!strcmp(cl.model_name[nummodels],"progs/flag.mdl")) + else if (!strcmp (cl.model_name[nummodels], "progs/flag.mdl")) cl_flagindex = nummodels; // for deadbodyfilter &gibfilter - else if (!strcmp(cl.model_name[nummodels],"progs/h_player.mdl")) + else if (!strcmp (cl.model_name[nummodels], "progs/h_player.mdl")) cl_h_playerindex = nummodels; - else if (!strcmp(cl.model_name[nummodels],"progs/gib1.mdl")) + else if (!strcmp (cl.model_name[nummodels], "progs/gib1.mdl")) cl_gib1index = nummodels; - else if (!strcmp(cl.model_name[nummodels],"progs/gib2.mdl")) + else if (!strcmp (cl.model_name[nummodels], "progs/gib2.mdl")) cl_gib2index = nummodels; - else if (!strcmp(cl.model_name[nummodels],"progs/gib3.mdl")) + else if (!strcmp (cl.model_name[nummodels], "progs/gib3.mdl")) cl_gib3index = nummodels; } - n = MSG_ReadByte(); + n = MSG_ReadByte (); if (n) { MSG_WriteByte (&cls.netchan.message, clc_stringcmd); -// MSG_WriteString (&cls.netchan.message, va("modellist %i %i", cl.servercount, n)); - MSG_WriteString (&cls.netchan.message, va(modellist_name, cl.servercount, n)); +// MSG_WriteString (&cls.netchan.message, va("modellist %i %i", cl.servercount, n)); + MSG_WriteString (&cls.netchan.message, + va (modellist_name, cl.servercount, n)); return; } @@ -791,20 +816,21 @@ void CL_ParseModellist (void) CL_ParseBaseline ================== */ -void CL_ParseBaseline (entity_state_t *es) +void +CL_ParseBaseline (entity_state_t *es) { - int i; - + int i; + es->modelindex = MSG_ReadByte (); es->frame = MSG_ReadByte (); - es->colormap = MSG_ReadByte(); - es->skinnum = MSG_ReadByte(); - for (i=0 ; i<3 ; i++) - { + es->colormap = MSG_ReadByte (); + es->skinnum = MSG_ReadByte (); + for (i = 0; i < 3; i++) { es->origin[i] = MSG_ReadCoord (); es->angles[i] = MSG_ReadAngle (); } - // LordHavoc: set up the baseline to account for new effects (alpha, colormod, etc) + // LordHavoc: set up the baseline to account for new effects (alpha, + // colormod, etc) es->alpha = 255; es->scale = 16; es->glowcolor = 254; @@ -822,14 +848,15 @@ Static entities are non-interactive world objects like torches ===================== */ -void CL_ParseStatic (void) +void +CL_ParseStatic (void) { - entity_t *ent; - int i; - entity_state_t es; + entity_t *ent; + int i; + entity_state_t es; CL_ParseBaseline (&es); - + i = cl.num_statics; if (i >= MAX_STATIC_ENTITIES) Host_EndGame ("Too many static entities"); @@ -851,7 +878,7 @@ void CL_ParseStatic (void) ent->glowsize = 0; ent->glowcolor = 254; ent->colormod[0] = ent->colormod[1] = ent->colormod[2] = 1; - + R_AddEfrags (ent); } @@ -860,18 +887,19 @@ void CL_ParseStatic (void) CL_ParseStaticSound =================== */ -void CL_ParseStaticSound (void) +void +CL_ParseStaticSound (void) { - vec3_t org; - int sound_num, vol, atten; - int i; - - for (i=0 ; i<3 ; i++) + vec3_t org; + int sound_num, vol, atten; + int i; + + for (i = 0; i < 3; i++) org[i] = MSG_ReadCoord (); sound_num = MSG_ReadByte (); vol = MSG_ReadByte (); atten = MSG_ReadByte (); - + S_StaticSound (cl.sound_precache[sound_num], org, vol, atten); } @@ -890,40 +918,42 @@ ACTION MESSAGES CL_ParseStartSoundPacket ================== */ -void CL_ParseStartSoundPacket(void) +void +CL_ParseStartSoundPacket (void) { - vec3_t pos; - int channel, ent; - int sound_num; - int volume; - float attenuation; - int i; - - channel = MSG_ReadShort(); + vec3_t pos; + int channel, ent; + int sound_num; + int volume; + float attenuation; + int i; - if (channel & SND_VOLUME) + channel = MSG_ReadShort (); + + if (channel & SND_VOLUME) volume = MSG_ReadByte (); else volume = DEFAULT_SOUND_PACKET_VOLUME; - - if (channel & SND_ATTENUATION) + + if (channel & SND_ATTENUATION) attenuation = MSG_ReadByte () / 64.0; else attenuation = DEFAULT_SOUND_PACKET_ATTENUATION; - + sound_num = MSG_ReadByte (); - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) pos[i] = MSG_ReadCoord (); - - ent = (channel>>3)&1023; + + ent = (channel >> 3) & 1023; channel &= 7; if (ent > MAX_EDICTS) Host_EndGame ("CL_ParseStartSoundPacket: ent = %i", ent); - - S_StartSound (ent, channel, cl.sound_precache[sound_num], pos, volume/255.0, attenuation); -} + + S_StartSound (ent, channel, cl.sound_precache[sound_num], pos, + volume / 255.0, attenuation); +} /* @@ -933,11 +963,12 @@ CL_ParseClientdata Server information pertaining to this client only, sent every frame ================== */ -void CL_ParseClientdata (void) +void +CL_ParseClientdata (void) { - int i; - float latency; - frame_t *frame; + int i; + float latency; + frame_t *frame; // calculate simulated time of message oldparsecountmod = parsecountmod; @@ -954,18 +985,15 @@ void CL_ParseClientdata (void) // calculate latency latency = frame->receivedtime - frame->senttime; - if (latency < 0 || latency > 1.0) - { -// Con_Printf ("Odd latency: %5.2f\n", latency); - } - else - { - // drift the average latency towards the observed latency + if (latency < 0 || latency > 1.0) { +// Con_Printf ("Odd latency: %5.2f\n", latency); + } else { + // drift the average latency towards the observed latency if (latency < cls.latency) cls.latency = latency; else - cls.latency += 0.001; // drift up, so correction are needed - } + cls.latency += 0.001; // drift up, so correction are needed + } } /* @@ -973,11 +1001,14 @@ void CL_ParseClientdata (void) CL_UpdateUserinfo ============== */ -void CL_ProcessUserInfo (int slot, player_info_t *player) +void +CL_ProcessUserInfo (int slot, player_info_t *player) { - strncpy (player->name, Info_ValueForKey (player->userinfo, "name"), sizeof(player->name)-1); - player->topcolor = atoi(Info_ValueForKey (player->userinfo, "topcolor")); - player->bottomcolor = atoi(Info_ValueForKey (player->userinfo, "bottomcolor")); + strncpy (player->name, Info_ValueForKey (player->userinfo, "name"), + sizeof (player->name) - 1); + player->topcolor = atoi (Info_ValueForKey (player->userinfo, "topcolor")); + player->bottomcolor = + atoi (Info_ValueForKey (player->userinfo, "bottomcolor")); if (Info_ValueForKey (player->userinfo, "*spectator")[0]) player->spectator = true; else @@ -995,18 +1026,21 @@ void CL_ProcessUserInfo (int slot, player_info_t *player) CL_UpdateUserinfo ============== */ -void CL_UpdateUserinfo (void) +void +CL_UpdateUserinfo (void) { - int slot; - player_info_t *player; + int slot; + player_info_t *player; slot = MSG_ReadByte (); if (slot >= MAX_CLIENTS) - Host_EndGame ("CL_ParseServerMessage: svc_updateuserinfo > MAX_SCOREBOARD"); + Host_EndGame + ("CL_ParseServerMessage: svc_updateuserinfo > MAX_SCOREBOARD"); player = &cl.players[slot]; player->userid = MSG_ReadLong (); - strncpy (player->userinfo, MSG_ReadString(), sizeof(player->userinfo)-1); + strncpy (player->userinfo, MSG_ReadString (), + sizeof (player->userinfo) - 1); CL_ProcessUserInfo (slot, player); } @@ -1016,12 +1050,13 @@ void CL_UpdateUserinfo (void) CL_SetInfo ============== */ -void CL_SetInfo (void) +void +CL_SetInfo (void) { - int slot; - player_info_t *player; - char key[MAX_MSGLEN]; - char value[MAX_MSGLEN]; + int slot; + player_info_t *player; + char key[MAX_MSGLEN]; + char value[MAX_MSGLEN]; slot = MSG_ReadByte (); if (slot >= MAX_CLIENTS) @@ -1029,12 +1064,12 @@ void CL_SetInfo (void) player = &cl.players[slot]; - strncpy (key, MSG_ReadString(), sizeof(key) - 1); - key[sizeof(key) - 1] = 0; - strncpy (value, MSG_ReadString(), sizeof(value) - 1); - key[sizeof(value) - 1] = 0; + strncpy (key, MSG_ReadString (), sizeof (key) - 1); + key[sizeof (key) - 1] = 0; + strncpy (value, MSG_ReadString (), sizeof (value) - 1); + key[sizeof (value) - 1] = 0; - Con_DPrintf("SETINFO %s: %s=%s\n", player->name, key, value); + Con_DPrintf ("SETINFO %s: %s=%s\n", player->name, key, value); Info_SetValueForKey (player->userinfo, key, value, MAX_INFO_STRING); @@ -1046,17 +1081,18 @@ void CL_SetInfo (void) CL_ServerInfo ============== */ -void CL_ServerInfo (void) +void +CL_ServerInfo (void) { - char key[MAX_MSGLEN]; - char value[MAX_MSGLEN]; + char key[MAX_MSGLEN]; + char value[MAX_MSGLEN]; - strncpy (key, MSG_ReadString(), sizeof(key) - 1); - key[sizeof(key) - 1] = 0; - strncpy (value, MSG_ReadString(), sizeof(value) - 1); - key[sizeof(value) - 1] = 0; + strncpy (key, MSG_ReadString (), sizeof (key) - 1); + key[sizeof (key) - 1] = 0; + strncpy (value, MSG_ReadString (), sizeof (value) - 1); + key[sizeof (value) - 1] = 0; - Con_DPrintf("SERVERINFO: %s=%s\n", key, value); + Con_DPrintf ("SERVERINFO: %s=%s\n", key, value); Info_SetValueForKey (cl.serverinfo, key, value, MAX_SERVERINFO_STRING); } @@ -1066,25 +1102,27 @@ void CL_ServerInfo (void) CL_SetStat ===================== */ -void CL_SetStat (int stat, int value) +void +CL_SetStat (int stat, int value) { - int j; + int j; + if (stat < 0 || stat >= MAX_CL_STATS) -// Sys_Error ("CL_SetStat: %i is invalid", stat); +// Sys_Error ("CL_SetStat: %i is invalid", stat); Host_EndGame ("CL_SetStat: %i is invalid", stat); Sbar_Changed (); - + switch (stat) { - case STAT_ITEMS: // set flash times + case STAT_ITEMS: // set flash times Sbar_Changed (); - for (j=0 ; j<32 ; j++) - if ( (value & (1<= MAX_CLIENTS) + if ((unsigned int) (i - 1) >= MAX_CLIENTS) return; // don't draw our own muzzle flash in gl if flashblending - if (i-1 == cl.playernum && gl_flashblend->int_val) + if (i - 1 == cl.playernum && gl_flashblend->int_val) return; - pl = &cl.frames[parsecountmod].playerstate[i-1]; + pl = &cl.frames[parsecountmod].playerstate[i - 1]; dl = CL_AllocDlight (i); - VectorCopy (pl->origin, dl->origin); + VectorCopy (pl->origin, dl->origin); AngleVectors (pl->viewangles, fv, rv, uv); - + VectorMA (dl->origin, 18, fv, dl->origin); - dl->radius = 200 + (rand()&31); + dl->radius = 200 + (rand () & 31); dl->minlight = 32; dl->die = cl.time + 0.1; dl->color[0] = 0.2; @@ -1134,12 +1173,13 @@ void CL_MuzzleFlash (void) CL_ParseServerMessage ===================== */ -int received_framecount; -void CL_ParseServerMessage (void) +int received_framecount; +void +CL_ParseServerMessage (void) { - int cmd; - char *s; - int i, j; + int cmd; + char *s; + int i, j; received_framecount = host_framecount; cl.last_servermessage = realtime; @@ -1149,7 +1189,7 @@ void CL_ParseServerMessage (void) // if recording demos, copy the message out // if (cl_shownet->int_val == 1) - Con_Printf ("%i ",net_message.cursize); + Con_Printf ("%i ", net_message.cursize); else if (cl_shownet->int_val == 2) Con_Printf ("------------------\n"); @@ -1159,285 +1199,287 @@ void CL_ParseServerMessage (void) // // parse the message // - while (1) - { - if (msg_badread) - { + while (1) { + if (msg_badread) { Host_EndGame ("CL_ParseServerMessage: Bad server message"); break; } cmd = MSG_ReadByte (); - if (cmd == -1) - { - msg_readcount++; // so the EOM showner has the right value - SHOWNET("END OF MESSAGE"); + if (cmd == -1) { + msg_readcount++; // so the EOM showner has the right + // value + SHOWNET ("END OF MESSAGE"); break; } - SHOWNET(svc_strings[cmd]); - - // other commands - switch (cmd) - { - default: - Host_EndGame ("CL_ParseServerMessage: Illegible server message"); - break; - - case svc_nop: -// Con_Printf ("svc_nop\n"); - break; - - case svc_disconnect: - if (cls.state == ca_connected) - Host_EndGame ("Server disconnected\n" - "Server version may not be compatible"); - else - Host_EndGame ("Server disconnected"); - break; + SHOWNET (svc_strings[cmd]); - case svc_print: - i = MSG_ReadByte (); - s = MSG_ReadString (); - if (i == PRINT_CHAT) - { - // TODO: cl_nofake 2 -- accept fake messages from teammates - char *p; - if (cl_nofake->int_val) { - for (p = s; *p; p++) - if (*p == 13) - *p = '#'; + // other commands + switch (cmd) { + default: + Host_EndGame + ("CL_ParseServerMessage: Illegible server message"); + break; + + case svc_nop: +// Con_Printf ("svc_nop\n"); + break; + + case svc_disconnect: + if (cls.state == ca_connected) + Host_EndGame ("Server disconnected\n" + "Server version may not be compatible"); + else + Host_EndGame ("Server disconnected"); + break; + + case svc_print: + i = MSG_ReadByte (); + s = MSG_ReadString (); + if (i == PRINT_CHAT) { + // TODO: cl_nofake 2 -- accept fake messages from + // teammates + char *p; + + if (cl_nofake->int_val) { + for (p = s; *p; p++) + if (*p == 13) + *p = '#'; + } + con_ormask = 128; + S_LocalSound ("misc/talk.wav"); } - con_ormask = 128; - S_LocalSound ("misc/talk.wav"); - } - Con_Printf ("%s", s); - con_ormask = 0; - break; - - case svc_centerprint: - SCR_CenterPrint (MSG_ReadString ()); - break; - - case svc_stufftext: - s = MSG_ReadString (); - Con_DPrintf ("stufftext: %s\n", s); - Cbuf_AddText (s); - break; - - case svc_damage: - V_ParseDamage (); - break; - - case svc_serverdata: - Cbuf_Execute (); // make sure any stuffed commands are done - CL_ParseServerData (); - vid.recalc_refdef = true; // leave full screen intermission - break; - - case svc_setangle: - for (i=0 ; i<3 ; i++) - cl.viewangles[i] = MSG_ReadAngle (); -// cl.viewangles[PITCH] = cl.viewangles[ROLL] = 0; - break; - - case svc_lightstyle: - i = MSG_ReadByte (); - if (i >= MAX_LIGHTSTYLES) -// Sys_Error ("svc_lightstyle > MAX_LIGHTSTYLES"); - Host_EndGame ("svc_lightstyle > MAX_LIGHTSTYLES"); - strcpy (cl_lightstyle[i].map, MSG_ReadString()); - cl_lightstyle[i].length = strlen(cl_lightstyle[i].map); - break; - - case svc_sound: - CL_ParseStartSoundPacket(); - break; - - case svc_stopsound: - i = MSG_ReadShort(); - S_StopSound(i>>3, i&7); - break; - - case svc_updatefrags: - Sbar_Changed (); - i = MSG_ReadByte (); - if (i >= MAX_CLIENTS) - Host_EndGame ("CL_ParseServerMessage: svc_updatefrags > MAX_SCOREBOARD"); - cl.players[i].frags = MSG_ReadShort (); - break; + Con_Printf ("%s", s); + con_ormask = 0; + break; - case svc_updateping: - i = MSG_ReadByte (); - if (i >= MAX_CLIENTS) - Host_EndGame ("CL_ParseServerMessage: svc_updateping > MAX_SCOREBOARD"); - cl.players[i].ping = MSG_ReadShort (); - break; - - case svc_updatepl: - i = MSG_ReadByte (); - if (i >= MAX_CLIENTS) - Host_EndGame ("CL_ParseServerMessage: svc_updatepl > MAX_SCOREBOARD"); - cl.players[i].pl = MSG_ReadByte (); - break; - - case svc_updateentertime: - // time is sent over as seconds ago - i = MSG_ReadByte (); - if (i >= MAX_CLIENTS) - Host_EndGame ("CL_ParseServerMessage: svc_updateentertime > MAX_SCOREBOARD"); - cl.players[i].entertime = realtime - MSG_ReadFloat (); - break; - - case svc_spawnbaseline: - i = MSG_ReadShort (); - CL_ParseBaseline (&cl_baselines[i]); - break; - case svc_spawnstatic: - CL_ParseStatic (); - break; - case svc_temp_entity: - CL_ParseTEnt (); - break; + case svc_centerprint: + SCR_CenterPrint (MSG_ReadString ()); + break; - case svc_killedmonster: - cl.stats[STAT_MONSTERS]++; - break; + case svc_stufftext: + s = MSG_ReadString (); + Con_DPrintf ("stufftext: %s\n", s); + Cbuf_AddText (s); + break; - case svc_foundsecret: - cl.stats[STAT_SECRETS]++; - break; + case svc_damage: + V_ParseDamage (); + break; - case svc_updatestat: - i = MSG_ReadByte (); - j = MSG_ReadByte (); - CL_SetStat (i, j); - break; - case svc_updatestatlong: - i = MSG_ReadByte (); - j = MSG_ReadLong (); - CL_SetStat (i, j); - break; - - case svc_spawnstaticsound: - CL_ParseStaticSound (); - break; + case svc_serverdata: + Cbuf_Execute (); // make sure any stuffed commands are + // done + CL_ParseServerData (); + vid.recalc_refdef = true; // leave full screen intermission + break; - case svc_cdtrack: - cl.cdtrack = MSG_ReadByte (); - CDAudio_Play ((byte)cl.cdtrack, true); - break; + case svc_setangle: + for (i = 0; i < 3; i++) + cl.viewangles[i] = MSG_ReadAngle (); +// cl.viewangles[PITCH] = cl.viewangles[ROLL] = 0; + break; - case svc_intermission: - Con_DPrintf ("svc_intermission\n"); - cl.intermission = 1; - cl.completed_time = realtime; - vid.recalc_refdef = true; // go to full screen - Con_DPrintf ("intermission simorg: "); - for (i=0 ; i<3 ; i++) - { - cl.simorg[i] = MSG_ReadCoord (); - Con_DPrintf ("%f ", cl.simorg[i]); - } - Con_DPrintf ("\nintermission simangles: "); - for (i=0 ; i<3 ; i++) - { - cl.simangles[i] = MSG_ReadAngle (); - Con_DPrintf ("%f ", cl.simangles[i]); - } - Con_DPrintf ("\n"); - VectorCopy (vec3_origin, cl.simvel); - break; + case svc_lightstyle: + i = MSG_ReadByte (); + if (i >= MAX_LIGHTSTYLES) +// Sys_Error ("svc_lightstyle > MAX_LIGHTSTYLES"); + Host_EndGame ("svc_lightstyle > MAX_LIGHTSTYLES"); + strcpy (cl_lightstyle[i].map, MSG_ReadString ()); + cl_lightstyle[i].length = strlen (cl_lightstyle[i].map); + break; - case svc_finale: - cl.intermission = 2; - cl.completed_time = realtime; - vid.recalc_refdef = true; // go to full screen - SCR_CenterPrint (MSG_ReadString ()); - break; - - case svc_sellscreen: - Cmd_ExecuteString ("help"); - break; + case svc_sound: + CL_ParseStartSoundPacket (); + break; - case svc_smallkick: - cl.punchangle = -2; - break; - case svc_bigkick: - cl.punchangle = -4; - break; + case svc_stopsound: + i = MSG_ReadShort (); + S_StopSound (i >> 3, i & 7); + break; - case svc_muzzleflash: - CL_MuzzleFlash (); - break; + case svc_updatefrags: + Sbar_Changed (); + i = MSG_ReadByte (); + if (i >= MAX_CLIENTS) + Host_EndGame + ("CL_ParseServerMessage: svc_updatefrags > MAX_SCOREBOARD"); + cl.players[i].frags = MSG_ReadShort (); + break; - case svc_updateuserinfo: - CL_UpdateUserinfo (); - break; + case svc_updateping: + i = MSG_ReadByte (); + if (i >= MAX_CLIENTS) + Host_EndGame + ("CL_ParseServerMessage: svc_updateping > MAX_SCOREBOARD"); + cl.players[i].ping = MSG_ReadShort (); + break; - case svc_setinfo: - CL_SetInfo (); - break; + case svc_updatepl: + i = MSG_ReadByte (); + if (i >= MAX_CLIENTS) + Host_EndGame + ("CL_ParseServerMessage: svc_updatepl > MAX_SCOREBOARD"); + cl.players[i].pl = MSG_ReadByte (); + break; - case svc_serverinfo: - CL_ServerInfo (); - break; + case svc_updateentertime: + // time is sent over as seconds ago + i = MSG_ReadByte (); + if (i >= MAX_CLIENTS) + Host_EndGame + ("CL_ParseServerMessage: svc_updateentertime > MAX_SCOREBOARD"); + cl.players[i].entertime = realtime - MSG_ReadFloat (); + break; - case svc_download: - CL_ParseDownload (); - break; + case svc_spawnbaseline: + i = MSG_ReadShort (); + CL_ParseBaseline (&cl_baselines[i]); + break; + case svc_spawnstatic: + CL_ParseStatic (); + break; + case svc_temp_entity: + CL_ParseTEnt (); + break; - case svc_playerinfo: - CL_ParsePlayerinfo (); - break; + case svc_killedmonster: + cl.stats[STAT_MONSTERS]++; + break; - case svc_nails: - CL_ParseProjectiles (); - break; + case svc_foundsecret: + cl.stats[STAT_SECRETS]++; + break; - case svc_chokecount: // some preceding packets were choked - i = MSG_ReadByte (); - for (j=0 ; j -cvar_t *cl_nopred; -cvar_t *cl_pushlatency; +cvar_t *cl_nopred; +cvar_t *cl_pushlatency; -extern frame_t *view_frame; +extern frame_t *view_frame; /* ================= @@ -57,23 +57,24 @@ try nudging slightly on all axis to allow for the cut precision of the net coordinates ================= */ -void CL_NudgePosition (void) +void +CL_NudgePosition (void) { - vec3_t base; - int x, y; + vec3_t base; + int x, y; - if (PM_HullPointContents (&cl.model_precache[1]->hulls[1], 0, pmove.origin) == CONTENTS_EMPTY) + if (PM_HullPointContents (&cl.model_precache[1]->hulls[1], 0, pmove.origin) + == CONTENTS_EMPTY) return; VectorCopy (pmove.origin, base); - for (x=-1 ; x<=1 ; x++) - { - for (y=-1 ; y<=1 ; y++) - { - pmove.origin[0] = base[0] + x * 1.0/8; - pmove.origin[1] = base[1] + y * 1.0/8; - if (PM_HullPointContents (&cl.model_precache[1]->hulls[1], 0, pmove.origin) == CONTENTS_EMPTY) - return; + for (x = -1; x <= 1; x++) { + for (y = -1; y <= 1; y++) { + pmove.origin[0] = base[0] + x * 1.0 / 8; + pmove.origin[1] = base[1] + y * 1.0 / 8; + if (PM_HullPointContents + (&cl.model_precache[1]->hulls[1], 0, + pmove.origin) == CONTENTS_EMPTY) return; } } Con_DPrintf ("CL_NudgePosition: stuck\n"); @@ -84,13 +85,14 @@ void CL_NudgePosition (void) CL_PredictUsercmd ============== */ -void CL_PredictUsercmd (player_state_t *from, player_state_t *to, usercmd_t *u, qboolean spectator) +void +CL_PredictUsercmd (player_state_t * from, player_state_t * to, usercmd_t *u, + qboolean spectator) { // split up very long moves - if (u->msec > 50) - { - player_state_t temp; - usercmd_t split; + if (u->msec > 50) { + player_state_t temp; + usercmd_t split; split = *u; split.msec /= 2; @@ -101,7 +103,7 @@ void CL_PredictUsercmd (player_state_t *from, player_state_t *to, usercmd_t *u, } VectorCopy (from->origin, pmove.origin); -// VectorCopy (from->viewangles, pmove.angles); +// VectorCopy (from->viewangles, pmove.angles); VectorCopy (u->angles, pmove.angles); VectorCopy (from->velocity, pmove.velocity); @@ -118,7 +120,7 @@ void CL_PredictUsercmd (player_state_t *from, player_state_t *to, usercmd_t *u, //pmove.origin[i] = ((int)(pmove.origin[i]*8))*0.125; to->waterjumptime = pmove.waterjumptime; to->oldbuttons = pmove.oldbuttons; // Tonik -// to->oldbuttons = pmove.cmd.buttons; +// to->oldbuttons = pmove.cmd.buttons; VectorCopy (pmove.origin, to->origin); VectorCopy (pmove.angles, to->viewangles); VectorCopy (pmove.velocity, to->velocity); @@ -134,12 +136,13 @@ void CL_PredictUsercmd (player_state_t *from, player_state_t *to, usercmd_t *u, CL_PredictMove ============== */ -void CL_PredictMove (void) +void +CL_PredictMove (void) { - int i; - float f; - frame_t *from, *to = NULL; - int oldphysent; + int i; + float f; + frame_t *from, *to = NULL; + int oldphysent; if (cl_pushlatency->value > 0) Cvar_Set (cl_pushlatency, "0"); @@ -147,7 +150,7 @@ void CL_PredictMove (void) if (cl.paused) return; - cl.time = realtime - cls.latency - cl_pushlatency->value*0.001; + cl.time = realtime - cls.latency - cl_pushlatency->value * 0.001; if (cl.time > realtime) cl.time = realtime; @@ -157,7 +160,8 @@ void CL_PredictMove (void) if (!cl.validsequence) return; - if (cls.netchan.outgoing_sequence - cls.netchan.incoming_sequence >= UPDATE_BACKUP-1) + if (cls.netchan.outgoing_sequence - cls.netchan.incoming_sequence >= + UPDATE_BACKUP - 1) return; VectorCopy (cl.viewangles, cl.simangles); @@ -166,31 +170,29 @@ void CL_PredictMove (void) from = &cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK]; // we can now render a frame - if (cls.state == ca_onserver) - { // first update is the final signon stage - VID_SetCaption(cls.servername); + if (cls.state == ca_onserver) { // first update is the final signon + // stage + VID_SetCaption (cls.servername); cls.state = ca_active; } - if (cl_nopred->int_val) - { + if (cl_nopred->int_val) { VectorCopy (from->playerstate[cl.playernum].velocity, cl.simvel); VectorCopy (from->playerstate[cl.playernum].origin, cl.simorg); return; } - // predict forward until cl.time <= to->senttime oldphysent = pmove.numphysent; CL_SetSolidPlayers (cl.playernum); -// to = &cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK]; +// to = &cl.frames[cls.netchan.incoming_sequence & UPDATE_MASK]; - for (i=1 ; iplayerstate[cl.playernum] - , &to->playerstate[cl.playernum], &to->cmd, cl.spectator); + , &to->playerstate[cl.playernum], &to->cmd, + cl.spectator); if (to->senttime >= cl.time) break; from = to; @@ -198,14 +200,14 @@ void CL_PredictMove (void) pmove.numphysent = oldphysent; - if (i == UPDATE_BACKUP-1 || !to) - return; // net hasn't deliver packets in a long time... + if (i == UPDATE_BACKUP - 1 || !to) + return; // net hasn't deliver packets in a + // long time... // now interpolate some fraction of the final frame if (to->senttime == from->senttime) f = 0; - else - { + else { f = (cl.time - from->senttime) / (to->senttime - from->senttime); if (f < 0) @@ -214,21 +216,25 @@ void CL_PredictMove (void) f = 1; } - for (i=0 ; i<3 ; i++) - if ( fabs(from->playerstate[cl.playernum].origin[i] - to->playerstate[cl.playernum].origin[i]) > 128) - { // teleported, so don't lerp + for (i = 0; i < 3; i++) + if (fabs + (from->playerstate[cl.playernum].origin[i] - + to->playerstate[cl.playernum].origin[i]) > 128) { // teleported, + // so don't + // lerp VectorCopy (to->playerstate[cl.playernum].velocity, cl.simvel); VectorCopy (to->playerstate[cl.playernum].origin, cl.simorg); return; } - - for (i=0 ; i<3 ; i++) - { - cl.simorg[i] = from->playerstate[cl.playernum].origin[i] - + f*(to->playerstate[cl.playernum].origin[i] - from->playerstate[cl.playernum].origin[i]); - cl.simvel[i] = from->playerstate[cl.playernum].velocity[i] - + f*(to->playerstate[cl.playernum].velocity[i] - from->playerstate[cl.playernum].velocity[i]); - } + + for (i = 0; i < 3; i++) { + cl.simorg[i] = from->playerstate[cl.playernum].origin[i] + + f * (to->playerstate[cl.playernum].origin[i] - + from->playerstate[cl.playernum].origin[i]); + cl.simvel[i] = from->playerstate[cl.playernum].velocity[i] + + f * (to->playerstate[cl.playernum].velocity[i] - + from->playerstate[cl.playernum].velocity[i]); + } } @@ -237,9 +243,9 @@ void CL_PredictMove (void) CL_Prediction_Init_Cvars ============== */ -void CL_Prediction_Init_Cvars (void) +void +CL_Prediction_Init_Cvars (void) { - cl_pushlatency = Cvar_Get("pushlatency", "-999", CVAR_NONE, "None"); - cl_nopred = Cvar_Get("cl_nopred", "0", CVAR_NONE, "None"); + cl_pushlatency = Cvar_Get ("pushlatency", "-999", CVAR_NONE, "None"); + cl_nopred = Cvar_Get ("cl_nopred", "0", CVAR_NONE, "None"); } - diff --git a/source/cl_slist.c b/source/cl_slist.c index c41565f..8e20f2b 100644 --- a/source/cl_slist.c +++ b/source/cl_slist.c @@ -30,7 +30,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -42,189 +42,223 @@ #include "quakefs.h" #include "va.h" -server_entry_t *slist; - -server_entry_t *SL_Add (server_entry_t *start, char *ip, char *desc) { +server_entry_t *slist; + +server_entry_t * +SL_Add (server_entry_t *start, char *ip, char *desc) +{ server_entry_t *p; + p = start; - if (!start) { //Nothing at beginning of list, create it - start = calloc(1, sizeof(server_entry_t)); + if (!start) { // Nothing at beginning of list, + // create it + start = calloc (1, sizeof (server_entry_t)); + start->prev = 0; start->next = 0; - start->server = malloc(strlen(ip) + 1); - start->desc = malloc(strlen(desc) + 1); - strcpy(start->server,ip); - strcpy(start->desc,desc); + start->server = malloc (strlen (ip) + 1); + start->desc = malloc (strlen (desc) + 1); + strcpy (start->server, ip); + strcpy (start->desc, desc); return (start); } - for(p=start;p->next;p=p->next); //Get to end of list + for (p = start; p->next; p = p->next); // Get to end of list + + p->next = calloc (1, sizeof (server_entry_t)); - p->next = calloc(1, sizeof(server_entry_t)); p->next->prev = p; - p->next->server = malloc(strlen(ip) + 1); - p->next->desc = malloc(strlen(desc) + 1); + p->next->server = malloc (strlen (ip) + 1); + p->next->desc = malloc (strlen (desc) + 1); - strcpy(p->next->server,ip); - strcpy(p->next->desc,desc); + strcpy (p->next->server, ip); + strcpy (p->next->desc, desc); p->next->next = 0; return (start); - } +} -server_entry_t *SL_Del(server_entry_t *start, server_entry_t *del) { +server_entry_t * +SL_Del (server_entry_t *start, server_entry_t *del) +{ server_entry_t *n; + if (del == start) { - free(start->server); - free(start->desc); + free (start->server); + free (start->desc); n = start->next; if (n) n->prev = 0; - free(start); + free (start); return (n); } - - free(del->server); - free(del->desc); + + free (del->server); + free (del->desc); if (del->prev) del->prev->next = del->next; if (del->next) del->next->prev = del->prev; - free(del); + free (del); return (start); } -server_entry_t *SL_InsB (server_entry_t *start, server_entry_t *place, char *ip, char *desc) { - server_entry_t *new; - server_entry_t *other; - - new = calloc(1, sizeof(server_entry_t)); - new->server = malloc(strlen(ip) + 1); - new->desc = malloc(strlen(desc) + 1); - strcpy(new->server,ip); - strcpy(new->desc,desc); - other = place->prev; - if (other) - other->next = new; - place->prev = new; - new->next = place; - new->prev = other; - if (!other) - return new; - return start; +server_entry_t * +SL_InsB (server_entry_t *start, server_entry_t *place, char *ip, char *desc) +{ + server_entry_t *new; + server_entry_t *other; + + new = calloc (1, sizeof (server_entry_t)); + + new->server = malloc (strlen (ip) + 1); + new->desc = malloc (strlen (desc) + 1); + strcpy (new->server, ip); + strcpy (new->desc, desc); + other = place->prev; + if (other) + other->next = new; + place->prev = new; + new->next = place; + new->prev = other; + if (!other) + return new; + return start; } -void SL_Swap (server_entry_t *swap1, server_entry_t *swap2) { - char *p; - p = swap1->server; - swap1->server = swap2->server; - swap2->server = p; - p = swap1->desc; - swap1->desc = swap2->desc; - swap2->desc = p; +void +SL_Swap (server_entry_t *swap1, server_entry_t *swap2) +{ + char *p; + + p = swap1->server; + swap1->server = swap2->server; + swap2->server = p; + p = swap1->desc; + swap1->desc = swap2->desc; + swap2->desc = p; } - -server_entry_t *SL_Get_By_Num (server_entry_t *start, int n) { - int i; - for (i=0;i < n;i++) + +server_entry_t * +SL_Get_By_Num (server_entry_t *start, int n) +{ + int i; + + for (i = 0; i < n; i++) start = start->next; if (!start) return (0); return (start); } - -int SL_Len (server_entry_t *start) { - int i; - for (i=0;start;i++) - start=start->next; + +int +SL_Len (server_entry_t *start) +{ + int i; + + for (i = 0; start; i++) + start = start->next; return i; - } - -server_entry_t *SL_LoadF (QFile *f,server_entry_t *start) { // This could get messy - char line[256]; /* Long lines get truncated. */ - int c = ' '; /* int so it can be compared to EOF properly*/ - int len; - int i; - char *st; - char *addr; - - while (1) { - //First, get a line +} + +server_entry_t * +SL_LoadF (QFile *f, server_entry_t *start) +{ // This could get messy + char line[256]; /* Long lines get truncated. */ + int c = ' '; /* int so it can be compared to EOF + + properly */ + int len; + int i; + char *st; + char *addr; + + while (1) { + // First, get a line i = 0; c = ' '; while (c != '\n' && c != EOF) { - c = Qgetc(f); + c = Qgetc (f); if (i < 255) { line[i] = c; i++; } } - line[i - 1] = '\0'; // Now we can parse it - if ((st = gettokstart(line,1,' ')) != NULL) { - len = gettoklen(line,1,' '); - addr = malloc(len + 1); - strncpy(addr,&line[0],len); - addr[len] = '\0'; - if ((st = gettokstart(line,2,' '))) { - start = SL_Add(start,addr,st); - } - else { - start = SL_Add(start,addr,"Unknown"); - } - } - if (c == EOF) // We're done - return start; - } + line[i - 1] = '\0'; // Now we can parse it + if ((st = gettokstart (line, 1, ' ')) != NULL) { + len = gettoklen (line, 1, ' '); + addr = malloc (len + 1); + strncpy (addr, &line[0], len); + addr[len] = '\0'; + if ((st = gettokstart (line, 2, ' '))) { + start = SL_Add (start, addr, st); + } else { + start = SL_Add (start, addr, "Unknown"); + } + } + if (c == EOF) // We're done + return start; + } } - void SL_SaveF (QFile *f,server_entry_t *start) { - do { - Qprintf(f,"%s %s\n",start->server,start->desc); - start = start->next; - - } while (start); - } - - void SL_Shutdown (server_entry_t *start) { - QFile *f; - char e_path[MAX_OSPATH]; - - if (start) { - Qexpand_squiggle(fs_userpath->string, e_path); - if ((f = Qopen(va("%s/servers.txt", e_path),"w"))) { - SL_SaveF(f,start); - Qclose(f); - } - SL_Del_All (start); - } - } - - void SL_Del_All (server_entry_t *start) { - server_entry_t *n; - while (start) { - n = start->next; - free(start->server); - free(start->desc); - free(start); - start = n; - } - } - +void +SL_SaveF (QFile *f, server_entry_t *start) +{ + do { + Qprintf (f, "%s %s\n", start->server, start->desc); + start = start->next; + + } while (start); +} + +void +SL_Shutdown (server_entry_t *start) +{ + QFile *f; + char e_path[MAX_OSPATH]; + + if (start) { + Qexpand_squiggle (fs_userpath->string, e_path); + if ((f = Qopen (va ("%s/servers.txt", e_path), "w"))) { + SL_SaveF (f, start); + Qclose (f); + } + SL_Del_All (start); + } +} + +void +SL_Del_All (server_entry_t *start) +{ + server_entry_t *n; + + while (start) { + n = start->next; + free (start->server); + free (start->desc); + free (start); + start = n; + } +} -char *gettokstart (char *str, int req, char delim) { - char *start = str; - - int tok = 1; + +char * +gettokstart (char *str, int req, char delim) +{ + char *start = str; + + int tok = 1; while (*start == delim) { start++; } if (*start == '\0') return '\0'; - while (tok < req) { //Stop when we get to the requested token - if (*++start == delim) { //Increment pointer and test - while (*start == delim) { //Get to next token + while (tok < req) { // Stop when we get to the requested + // token + if (*++start == delim) { // Increment pointer and test + while (*start == delim) { // Get to next token start++; } tok++; @@ -236,12 +270,14 @@ char *gettokstart (char *str, int req, char delim) { return start; } -int gettoklen (char *str, int req, char delim) { - char *start = 0; - - int len = 0; - - start = gettokstart(str,req,delim); +int +gettoklen (char *str, int req, char delim) +{ + char *start = 0; + + int len = 0; + + start = gettokstart (str, req, delim); if (start == '\0') { return 0; } diff --git a/source/cl_sys_sdl.c b/source/cl_sys_sdl.c index bd5a982..124272e 100644 --- a/source/cl_sys_sdl.c +++ b/source/cl_sys_sdl.c @@ -62,30 +62,31 @@ #include "client.h" #include "host.h" -qboolean is_server = false; +qboolean is_server = false; -int starttime; +int starttime; #ifdef _WIN32 # include "winquake.h" - // fixme: minimized is not currently supported under SDL -qboolean Minimized=false; -void MaskExceptions (void); + // fixme: minimized is not currently supported under + // SDL +qboolean Minimized = false; +void MaskExceptions (void); #endif void Sys_DebugLog (char *file, char *fmt, ...) { - int fd; - static char data[1024]; // why static ? - va_list argptr; + int fd; + static char data[1024]; // why static ? + va_list argptr; - va_start (argptr, fmt); - vsnprintf (data, sizeof (data), fmt, argptr); - va_end (argptr); - fd = open (file, O_WRONLY | O_CREAT | O_APPEND, 0666); - write (fd, data, strlen (data)); - close (fd); + va_start (argptr, fmt); + vsnprintf (data, sizeof (data), fmt, argptr); + va_end (argptr); + fd = open (file, O_WRONLY | O_CREAT | O_APPEND, 0666); + write (fd, data, strlen (data)); + close (fd); }; /* @@ -99,13 +100,13 @@ FILE IO int Sys_FileTime (char *path) { - QFile *f; - int t, retval; + QFile *f; + int t, retval; f = Qopen (path, "rb"); if (f) { - Qclose(f); + Qclose (f); retval = 1; } else { retval = -1; @@ -133,25 +134,26 @@ Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) { #ifdef _WIN32 - DWORD flOldProtect; + DWORD flOldProtect; // copy on write or just read-write? - if (!VirtualProtect ((LPVOID) startaddr, length, PAGE_READWRITE, &flOldProtect)) - Sys_Error ("Protection change failed\n"); + if (!VirtualProtect + ((LPVOID) startaddr, length, PAGE_READWRITE, + &flOldProtect)) Sys_Error ("Protection change failed\n"); #else - int r; - unsigned long addr; - int psize = getpagesize (); + int r; + unsigned long addr; + int psize = getpagesize (); - addr = (startaddr & ~(psize-1)) - psize; + addr = (startaddr & ~(psize - 1)) - psize; -// fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr, -// addr, startaddr+length, length); +// fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr, +// addr, startaddr+length, length); - r = mprotect((char *) addr, length + startaddr - addr + psize, 7); + r = mprotect ((char *) addr, length + startaddr - addr + psize, 7); if (r < 0) - Sys_Error ("Protection change failed\n"); + Sys_Error ("Protection change failed\n"); #endif } @@ -166,7 +168,7 @@ Sys_Init (void) { #ifdef WIN32 - OSVERSIONINFO vinfo; + OSVERSIONINFO vinfo; #endif #ifdef USE_INTEL_ASM @@ -181,13 +183,15 @@ Sys_Init (void) // NT gets 18ms resolution timeBeginPeriod (1); - vinfo.dwOSVersionInfoSize = sizeof(vinfo); + vinfo.dwOSVersionInfoSize = sizeof (vinfo); if (!GetVersionEx (&vinfo)) Sys_Error ("Couldn't get OS info"); - if ((vinfo.dwMajorVersion < 4) || (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) { - Sys_Error ("This version of " PROGRAM " requires at least Win95 or NT 4.0"); + if ((vinfo.dwMajorVersion < 4) + || (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) { + Sys_Error ("This version of " PROGRAM + " requires at least Win95 or NT 4.0"); } #endif } @@ -196,47 +200,51 @@ Sys_Init (void) void Sys_Error (char *error, ...) { - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; #ifndef _WIN32 - fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK); + fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK); #endif va_start (argptr, error); - vsnprintf (text, sizeof(text), error, argptr); + vsnprintf (text, sizeof (text), error, argptr); va_end (argptr); #ifdef WIN32 MessageBox (NULL, text, "Error", 0 /* MB_OK */ ); #endif - fprintf (stderr, "Error: %s\n", text); + fprintf (stderr, "Error: %s\n", text); - Host_Shutdown (); + Host_Shutdown (); exit (1); } -void Sys_Printf (char *fmt, ...) +void +Sys_Printf (char *fmt, ...) { - va_list argptr; + va_list argptr; - va_start (argptr,fmt); + va_start (argptr, fmt); vprintf (fmt, argptr); va_end (argptr); } -void Sys_Quit (void) +void +Sys_Quit (void) { - Host_Shutdown(); + Host_Shutdown (); exit (0); } -char *Sys_ConsoleInput (void) +char * +Sys_ConsoleInput (void) { return NULL; } -void Sys_Sleep (void) +void +Sys_Sleep (void) { } @@ -244,60 +252,58 @@ void Sys_Sleep (void) void Sys_Init_Cvars (void) { - sys_nostdout = Cvar_Get("sys_nostdout", "0", CVAR_NONE, "None"); - if (COM_CheckParm("-nostdout")) - Cvar_Set(sys_nostdout, "1"); + sys_nostdout = Cvar_Get ("sys_nostdout", "0", CVAR_NONE, "None"); + if (COM_CheckParm ("-nostdout")) + Cvar_Set (sys_nostdout, "1"); } -C_LINKAGE int SDL_main(int c, char **v) +C_LINKAGE int +SDL_main (int c, char **v) { - double time, oldtime, newtime; - int j; + double time, oldtime, newtime; + int j; - static char cwd[1024]; - int t; + static char cwd[1024]; + int t; #ifndef WIN32 - signal(SIGFPE, SIG_IGN); + signal (SIGFPE, SIG_IGN); #endif - memset(&host_parms, 0, sizeof(host_parms)); + memset (&host_parms, 0, sizeof (host_parms)); - COM_InitArgv(c, v); + COM_InitArgv (c, v); host_parms.argc = com_argc; host_parms.argv = com_argv; - host_parms.memsize = 16*1024*1024; + host_parms.memsize = 16 * 1024 * 1024; - j = COM_CheckParm("-mem"); + j = COM_CheckParm ("-mem"); if (j) - host_parms.memsize = (int) (atof(com_argv[j+1]) * 1024 * 1024); + host_parms.memsize = (int) (atof (com_argv[j + 1]) * 1024 * 1024); host_parms.membase = malloc (host_parms.memsize); if (!host_parms.membase) { - printf("Can't allocate memory for zone.\n"); + printf ("Can't allocate memory for zone.\n"); return 1; } - #ifndef WIN32 - noconinput = COM_CheckParm("-noconinput"); + noconinput = COM_CheckParm ("-noconinput"); if (!noconinput) - fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK); + fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK); #endif - Host_Init(); + Host_Init (); oldtime = Sys_DoubleTime (); - while (1) - { + while (1) { // find time spent rendering last frame - newtime = Sys_DoubleTime (); - time = newtime - oldtime; + newtime = Sys_DoubleTime (); + time = newtime - oldtime; - Host_Frame(time); + Host_Frame (time); oldtime = newtime; } } - diff --git a/source/cl_sys_unix.c b/source/cl_sys_unix.c index 13bf478..0938107 100644 --- a/source/cl_sys_unix.c +++ b/source/cl_sys_unix.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -48,8 +48,8 @@ #include "qargs.h" #include "sys.h" -int noconinput = 0; -qboolean is_server = false; +int noconinput = 0; +qboolean is_server = false; #define BASEDIR "." @@ -116,86 +116,93 @@ void Sys_Printf (char *fmt, ...) void Sys_Quit (void) { - Host_Shutdown(); - fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK); - exit(0); + Host_Shutdown (); + fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK); + exit (0); } void Sys_Init_Cvars (void) { - sys_nostdout = Cvar_Get("sys_nostdout", "0", CVAR_NONE, "None"); - if (COM_CheckParm("-nostdout")) Cvar_Set(sys_nostdout, "1"); + sys_nostdout = Cvar_Get ("sys_nostdout", "0", CVAR_NONE, "None"); + if (COM_CheckParm ("-nostdout")) + Cvar_Set (sys_nostdout, "1"); } -void Sys_Init(void) +void +Sys_Init (void) { #ifdef USE_INTEL_ASM - Sys_SetFPCW(); + Sys_SetFPCW (); #endif } -void Sys_Error (char *error, ...) -{ - va_list argptr; - char string[1024]; +void +Sys_Error (char *error, ...) +{ + va_list argptr; + char string[1024]; // change stdin to non blocking - fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK); - - va_start (argptr, error); - vsnprintf (string, sizeof(string), error, argptr); - va_end (argptr); - fprintf(stderr, "Error: %s\n", string); + fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~O_NONBLOCK); + + va_start (argptr, error); + vsnprintf (string, sizeof (string), error, argptr); + va_end (argptr); + fprintf (stderr, "Error: %s\n", string); Host_Shutdown (); exit (1); -} +} -void Sys_Warn (char *warning, ...) -{ - va_list argptr; - char string[1024]; - - va_start (argptr, warning); - vsnprintf (string, sizeof(string), warning,argptr); - va_end (argptr); - fprintf(stderr, "Warning: %s", string); -} - -void Sys_DebugLog(char *file, char *fmt, ...) +void +Sys_Warn (char *warning, ...) { - va_list argptr; - static char data[1024]; // why static ? - int fd; + va_list argptr; + char string[1024]; - va_start (argptr, fmt); - vsnprintf (data, sizeof(data), fmt, argptr); - va_end(argptr); + va_start (argptr, warning); + vsnprintf (string, sizeof (string), warning, argptr); + va_end (argptr); + fprintf (stderr, "Warning: %s", string); +} + +void +Sys_DebugLog (char *file, char *fmt, ...) +{ + va_list argptr; + static char data[1024]; // why static ? + int fd; + + va_start (argptr, fmt); + vsnprintf (data, sizeof (data), fmt, argptr); + va_end (argptr); // fd = open(file, O_WRONLY | O_BINARY | O_CREAT | O_APPEND, 0666); - fd = open(file, O_WRONLY | O_CREAT | O_APPEND, 0666); - write(fd, data, strlen(data)); - close(fd); + fd = open (file, O_WRONLY | O_CREAT | O_APPEND, 0666); + write (fd, data, strlen (data)); + close (fd); } -void floating_point_exception_handler(int whatever) +void +floating_point_exception_handler (int whatever) { -// Sys_Warn("floating point exception\n"); - signal(SIGFPE, floating_point_exception_handler); +// Sys_Warn("floating point exception\n"); + signal (SIGFPE, floating_point_exception_handler); } -char *Sys_ConsoleInput(void) +char * +Sys_ConsoleInput (void) { #if 0 - static char text[256]; - int len; + static char text[256]; + int len; if (cls.state == ca_dedicated) { - len = read (0, text, sizeof(text)); + len = read (0, text, sizeof (text)); if (len < 1) return NULL; - text[len-1] = 0; // rip off the /n and terminate + text[len - 1] = 0; // rip off the /n and terminate return text; } @@ -204,61 +211,63 @@ char *Sys_ConsoleInput(void) } #ifndef USE_INTEL_ASM -void Sys_HighFPPrecision (void) +void +Sys_HighFPPrecision (void) { } -void Sys_LowFPPrecision (void) +void +Sys_LowFPPrecision (void) { } #endif -int skipframes; +int skipframes; -int main (int c, char **v) +int +main (int c, char **v) { - double time, oldtime, newtime; - int j; + double time, oldtime, newtime; + int j; -// static char cwd[1024]; +// static char cwd[1024]; -// signal(SIGFPE, floating_point_exception_handler); - signal(SIGFPE, SIG_IGN); +// signal(SIGFPE, floating_point_exception_handler); + signal (SIGFPE, SIG_IGN); - memset(&host_parms, 0, sizeof(host_parms)); + memset (&host_parms, 0, sizeof (host_parms)); - COM_InitArgv(c, v); + COM_InitArgv (c, v); host_parms.argc = com_argc; host_parms.argv = com_argv; host_parms.memsize = 8 * 1024 * 1024; // 8MB default heap - j = COM_CheckParm("-mem"); + j = COM_CheckParm ("-mem"); if (j) - host_parms.memsize = (int) (atof(com_argv[j+1]) * 1024 * 1024); + host_parms.memsize = (int) (atof (com_argv[j + 1]) * 1024 * 1024); host_parms.membase = malloc (host_parms.memsize); if (!host_parms.membase) { - printf("Can't allocate memory for zone.\n"); + printf ("Can't allocate memory for zone.\n"); return 1; } - noconinput = COM_CheckParm("-noconinput"); + noconinput = COM_CheckParm ("-noconinput"); if (!noconinput) - fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK); + fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) | O_NONBLOCK); - Host_Init(); + Host_Init (); - oldtime = Sys_DoubleTime (); - while (1) - { + oldtime = Sys_DoubleTime (); + while (1) { // find time spent rendering last frame - newtime = Sys_DoubleTime (); - time = newtime - oldtime; + newtime = Sys_DoubleTime (); + time = newtime - oldtime; - Host_Frame(time); + Host_Frame (time); oldtime = newtime; - } + } } @@ -268,21 +277,22 @@ int main (int c, char **v) Sys_MakeCodeWriteable ================ */ -void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) +void +Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) { - int r; + int r; unsigned long addr; - int psize = getpagesize(); + int psize = getpagesize (); - addr = (startaddr & ~(psize-1)) - psize; + addr = (startaddr & ~(psize - 1)) - psize; -// fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr, -// addr, startaddr+length, length); +// fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr, +// addr, startaddr+length, length); - r = mprotect((char*)addr, length + startaddr - addr + psize, 7); + r = mprotect ((char *) addr, length + startaddr - addr + psize, 7); if (r < 0) - Sys_Error("Protection change failed\n"); + Sys_Error ("Protection change failed\n"); } diff --git a/source/cl_sys_win.c b/source/cl_sys_win.c index 2b5bc22..8185f8e 100644 --- a/source/cl_sys_win.c +++ b/source/cl_sys_win.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -45,46 +45,48 @@ #include "client.h" #include "console.h" -qboolean is_server = false; +qboolean is_server = false; #define MINIMUM_WIN_MEMORY 0x0c00000 #define MAXIMUM_WIN_MEMORY 0x1000000 -#define PAUSE_SLEEP 50 // sleep time on pause or minimization +#define PAUSE_SLEEP 50 // sleep time on pause or + // minimization #define NOT_FOCUS_SLEEP 20 // sleep time when not focus -int starttime; -qboolean ActiveApp, Minimized; -qboolean WinNT; +int starttime; +qboolean ActiveApp, Minimized; +qboolean WinNT; -HWND hwnd_dialog; // startup dialog box +HWND hwnd_dialog; // startup dialog box -static HANDLE hinput, houtput; +static HANDLE hinput, houtput; -HANDLE qwclsemaphore; +HANDLE qwclsemaphore; -static HANDLE tevent; +static HANDLE tevent; -extern cvar_t *sys_nostdout; +extern cvar_t *sys_nostdout; -void Sys_InitFloatTime (void); +void Sys_InitFloatTime (void); -void MaskExceptions (void); -void Sys_PopFPCW (void); -void Sys_PushFPCW_SetHigh (void); +void MaskExceptions (void); +void Sys_PopFPCW (void); +void Sys_PushFPCW_SetHigh (void); -void Sys_DebugLog(char *file, char *fmt, ...) +void +Sys_DebugLog (char *file, char *fmt, ...) { - va_list argptr; - static char data[1024]; - int fd; - - va_start (argptr, fmt); - vsnprintf (data, sizeof(data), fmt, argptr); - va_end (argptr); - fd = open (file, O_WRONLY | O_CREAT | O_APPEND, 0666); - write (fd, data, strlen(data)); - close (fd); + va_list argptr; + static char data[1024]; + int fd; + + va_start (argptr, fmt); + vsnprintf (data, sizeof (data), fmt, argptr); + va_end (argptr); + fd = open (file, O_WRONLY | O_CREAT | O_APPEND, 0666); + write (fd, data, strlen (data)); + close (fd); }; /* @@ -100,10 +102,11 @@ FILE IO wfilelength ================ */ -int wfilelength (QFile *f) +int +wfilelength (QFile *f) { - int pos; - int end; + int pos; + int end; pos = Qtell (f); Qseek (f, 0, SEEK_END); @@ -114,25 +117,23 @@ int wfilelength (QFile *f) } -int Sys_FileTime (char *path) +int +Sys_FileTime (char *path) { - QFile *f; - int t, retval; + QFile *f; + int t, retval; t = VID_ForceUnlockedAndReturnState (); - - f = Qopen(path, "rb"); - if (f) - { - Qclose(f); + f = Qopen (path, "rb"); + + if (f) { + Qclose (f); retval = 1; - } - else - { + } else { retval = -1; } - + VID_ForceLockState (t); return retval; } @@ -151,13 +152,15 @@ SYSTEM IO Sys_MakeCodeWriteable ================ */ -void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) +void +Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) { - DWORD flOldProtect; + DWORD flOldProtect; //@@@ copy on write or just read-write? - if (!VirtualProtect((LPVOID)startaddr, length, PAGE_READWRITE, &flOldProtect)) - Sys_Error("Protection change failed\n"); + if (!VirtualProtect + ((LPVOID) startaddr, length, PAGE_READWRITE, + &flOldProtect)) Sys_Error ("Protection change failed\n"); } @@ -170,30 +173,29 @@ Sys_Init void Sys_Init_Cvars (void) { - sys_nostdout = Cvar_Get("sys_nostdout", "1", CVAR_NONE, "None"); + sys_nostdout = Cvar_Get ("sys_nostdout", "1", CVAR_NONE, "None"); } -void Sys_Init (void) +void +Sys_Init (void) { - OSVERSIONINFO vinfo; + OSVERSIONINFO vinfo; // allocate a named semaphore on the client so the // front end can tell if it is alive // mutex will fail if semephore allready exists - qwclsemaphore = CreateMutex( - NULL, /* Security attributes */ - 0, /* owner */ - "qwcl"); /* Semaphore name */ + qwclsemaphore = CreateMutex (NULL, /* Security attributes */ + 0, /* owner */ + "qwcl"); /* Semaphore name */ if (!qwclsemaphore) Sys_Error ("QWCL is already running on this system"); CloseHandle (qwclsemaphore); - qwclsemaphore = CreateSemaphore( - NULL, /* Security attributes */ - 0, /* Initial count */ - 1, /* Maximum count */ - "qwcl"); /* Semaphore name */ + qwclsemaphore = CreateSemaphore (NULL, /* Security attributes */ + 0, /* Initial count */ + 1, /* Maximum count */ + "qwcl"); /* Semaphore name */ #ifdef USE_INTEL_ASM MaskExceptions (); @@ -202,17 +204,17 @@ void Sys_Init (void) // make sure the timer is high precision, otherwise // NT gets 18ms resolution - timeBeginPeriod( 1 ); + timeBeginPeriod (1); - vinfo.dwOSVersionInfoSize = sizeof(vinfo); + vinfo.dwOSVersionInfoSize = sizeof (vinfo); if (!GetVersionEx (&vinfo)) Sys_Error ("Couldn't get OS info"); if ((vinfo.dwMajorVersion < 4) || - (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) - { - Sys_Error ("This version of " PROGRAM " requires a full Win32 implementation."); + (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) { + Sys_Error ("This version of " PROGRAM + " requires a full Win32 implementation."); } if (vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) @@ -222,30 +224,33 @@ void Sys_Init (void) } -void Sys_Error (char *error, ...) +void +Sys_Error (char *error, ...) { - va_list argptr; - char text[1024];//, text2[1024]; -// DWORD dummy; + va_list argptr; + char text[1024]; // , text2[1024]; + +// DWORD dummy; Host_Shutdown (); va_start (argptr, error); - vsnprintf (text, sizeof(text), error, argptr); + vsnprintf (text, sizeof (text), error, argptr); va_end (argptr); - MessageBox(NULL, text, "Error", 0 /* MB_OK */ ); + MessageBox (NULL, text, "Error", 0 /* MB_OK */ ); CloseHandle (qwclsemaphore); exit (1); } -void Sys_Quit (void) +void +Sys_Quit (void) { VID_ForceUnlockedAndReturnState (); - Host_Shutdown(); + Host_Shutdown (); if (tevent) CloseHandle (tevent); @@ -258,45 +263,42 @@ void Sys_Quit (void) -char *Sys_ConsoleInput (void) +char * +Sys_ConsoleInput (void) { - static char text[256]; - static int len; - INPUT_RECORD recs[1024]; -// int count; - int i; - int ch; - DWORD numread, numevents, dummy; - HANDLE th; - char *clipText, *textCopied; + static char text[256]; + static int len; + INPUT_RECORD recs[1024]; - for ( ;; ) - { +// int count; + int i; + int ch; + DWORD numread, numevents, dummy; + HANDLE th; + char *clipText, *textCopied; + + for (;;) { if (!GetNumberOfConsoleInputEvents (hinput, &numevents)) Sys_Error ("Error getting # of console events"); if (numevents <= 0) break; - if (!ReadConsoleInput(hinput, recs, 1, &numread)) + if (!ReadConsoleInput (hinput, recs, 1, &numread)) Sys_Error ("Error reading console input"); if (numread != 1) Sys_Error ("Couldn't read console input"); - if (recs[0].EventType == KEY_EVENT) - { - if (!recs[0].Event.KeyEvent.bKeyDown) - { + if (recs[0].EventType == KEY_EVENT) { + if (!recs[0].Event.KeyEvent.bKeyDown) { ch = recs[0].Event.KeyEvent.uChar.AsciiChar; - switch (ch) - { + switch (ch) { case '\r': - WriteFile(houtput, "\r\n", 2, &dummy, NULL); + WriteFile (houtput, "\r\n", 2, &dummy, NULL); - if (len) - { + if (len) { text[len] = 0; len = 0; return text; @@ -304,47 +306,58 @@ char *Sys_ConsoleInput (void) break; case '\b': - WriteFile(houtput, "\b \b", 3, &dummy, NULL); - if (len) - { + WriteFile (houtput, "\b \b", 3, &dummy, NULL); + if (len) { len--; - putch('\b'); + putch ('\b'); } break; default: - Con_Printf("Stupid: %d\n", recs[0].Event.KeyEvent.dwControlKeyState); - if (((ch=='V' || ch=='v') && (recs[0].Event.KeyEvent.dwControlKeyState & - (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))) || ((recs[0].Event.KeyEvent.dwControlKeyState - & SHIFT_PRESSED) && (recs[0].Event.KeyEvent.wVirtualKeyCode - ==VK_INSERT))) { - if (OpenClipboard(NULL)) { - th = GetClipboardData(CF_TEXT); + Con_Printf ("Stupid: %d\n", + recs[0].Event.KeyEvent.dwControlKeyState); + if ( + ((ch == 'V' || ch == 'v') + && (recs[0].Event.KeyEvent. + dwControlKeyState & (LEFT_CTRL_PRESSED | + RIGHT_CTRL_PRESSED))) + || + ((recs + [0].Event.KeyEvent. + dwControlKeyState & SHIFT_PRESSED) + && (recs[0].Event.KeyEvent.wVirtualKeyCode == + VK_INSERT))) { + if (OpenClipboard (NULL)) { + th = GetClipboardData (CF_TEXT); if (th) { - clipText = GlobalLock(th); + clipText = GlobalLock (th); if (clipText) { - textCopied = malloc(GlobalSize(th)+1); - strcpy(textCopied, clipText); -/* Substitutes a NULL for every token */strtok(textCopied, "\n\r\b"); - i = strlen(textCopied); - if (i+len>=256) - i=256-len; - if (i>0) { - textCopied[i]=0; - text[len]=0; - strncat (text, textCopied, sizeof(text) - strlen (text)); - len+=dummy; - WriteFile(houtput, textCopied, i, &dummy, NULL); + textCopied = + malloc (GlobalSize (th) + 1); + strcpy (textCopied, clipText); +/* Substitutes a NULL for every token */ + strtok (textCopied, "\n\r\b"); + i = strlen (textCopied); + if (i + len >= 256) + i = 256 - len; + if (i > 0) { + textCopied[i] = 0; + text[len] = 0; + strncat (text, textCopied, + sizeof (text) - + strlen (text)); + len += dummy; + WriteFile (houtput, textCopied, i, + &dummy, NULL); } - free(textCopied); + free (textCopied); } - GlobalUnlock(th); + GlobalUnlock (th); } - CloseClipboard(); + CloseClipboard (); } - } else if (ch >= ' ') - { - WriteFile(houtput, &ch, 1, &dummy, NULL); + } else if (ch >= ' ') { + WriteFile (houtput, &ch, 1, &dummy, NULL); text[len] = ch; len = (len + 1) & 0xff; } @@ -359,24 +372,25 @@ char *Sys_ConsoleInput (void) return NULL; } -void Sys_Sleep (void) +void +Sys_Sleep (void) { } -void IN_SendKeyEvents (void) +void +IN_SendKeyEvents (void) { - MSG msg; + MSG msg; - while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) - { - // we always update if there are any event, even if we're paused + while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) { + // we always update if there are any event, even if we're paused scr_skipupdate = 0; if (!GetMessage (&msg, NULL, 0, 0)) Sys_Quit (); - TranslateMessage (&msg); - DispatchMessage (&msg); + TranslateMessage (&msg); + DispatchMessage (&msg); } } @@ -395,10 +409,11 @@ void IN_SendKeyEvents (void) WinMain ================== */ -void SleepUntilInput (int time) +void +SleepUntilInput (int time) { - MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT); + MsgWaitForMultipleObjects (1, &tevent, FALSE, time, QS_ALLINPUT); } @@ -408,56 +423,55 @@ void SleepUntilInput (int time) WinMain ================== */ -HINSTANCE global_hInstance; -int global_nCmdShow; -char *argv[MAX_NUM_ARGVS]; -static char *empty_string = ""; -HWND hwnd_dialog; +HINSTANCE global_hInstance; +int global_nCmdShow; +char *argv[MAX_NUM_ARGVS]; +static char *empty_string = ""; +HWND hwnd_dialog; -int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) +int WINAPI +WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, + int nCmdShow) { -// MSG msg; - double time, oldtime, newtime; - MEMORYSTATUS lpBuffer; - static char cwd[1024]; - int t; - RECT rect; +// MSG msg; + double time, oldtime, newtime; + MEMORYSTATUS lpBuffer; + static char cwd[1024]; + int t; + RECT rect; - /* previous instances do not exist in Win32 */ - if (hPrevInstance) - return 0; + /* previous instances do not exist in Win32 */ + if (hPrevInstance) + return 0; global_hInstance = hInstance; global_nCmdShow = nCmdShow; - lpBuffer.dwLength = sizeof(MEMORYSTATUS); + lpBuffer.dwLength = sizeof (MEMORYSTATUS); GlobalMemoryStatus (&lpBuffer); - if (!GetCurrentDirectory (sizeof(cwd), cwd)) + if (!GetCurrentDirectory (sizeof (cwd), cwd)) Sys_Error ("Couldn't determine current directory"); - if (cwd[strlen(cwd)-1] == '/') - cwd[strlen(cwd)-1] = 0; + if (cwd[strlen (cwd) - 1] == '/') + cwd[strlen (cwd) - 1] = 0; host_parms.argc = 1; argv[0] = empty_string; - while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS)) - { + while (*lpCmdLine && (host_parms.argc < MAX_NUM_ARGVS)) { while (*lpCmdLine && ((*lpCmdLine <= 32) || (*lpCmdLine > 126))) lpCmdLine++; - if (*lpCmdLine) - { + if (*lpCmdLine) { argv[host_parms.argc] = lpCmdLine; host_parms.argc++; while (*lpCmdLine && ((*lpCmdLine > 32) && (*lpCmdLine <= 126))) lpCmdLine++; - if (*lpCmdLine) - { + if (*lpCmdLine) { *lpCmdLine = 0; lpCmdLine++; } @@ -472,18 +486,15 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin host_parms.argc = com_argc; host_parms.argv = com_argv; - hwnd_dialog = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, NULL); + hwnd_dialog = + CreateDialog (hInstance, MAKEINTRESOURCE (IDD_DIALOG1), NULL, NULL); - if (hwnd_dialog) - { - if (GetWindowRect (hwnd_dialog, &rect)) - { - if (rect.left > (rect.top * 2)) - { + if (hwnd_dialog) { + if (GetWindowRect (hwnd_dialog, &rect)) { + if (rect.left > (rect.top * 2)) { SetWindowPos (hwnd_dialog, 0, - (rect.left / 2) - ((rect.right - rect.left) / 2), - rect.top, 0, 0, - SWP_NOZORDER | SWP_NOSIZE); + (rect.left / 2) - ((rect.right - rect.left) / 2), + rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } } @@ -491,7 +502,6 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin UpdateWindow (hwnd_dialog); SetForegroundWindow (hwnd_dialog); } - // take the greater of all the available memory or half the total memory, // but at least 8 Mb and no more than 16 Mb, unless they explicitly // request otherwise @@ -506,9 +516,8 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin if (host_parms.memsize > MAXIMUM_WIN_MEMORY) host_parms.memsize = MAXIMUM_WIN_MEMORY; - if (COM_CheckParm ("-heapsize")) - { - t = COM_CheckParm("-heapsize") + 1; + if (COM_CheckParm ("-heapsize")) { + t = COM_CheckParm ("-heapsize") + 1; if (t < com_argc) host_parms.memsize = atoi (com_argv[t]) * 1024; @@ -519,7 +528,7 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin if (!host_parms.membase) Sys_Error ("Not enough memory free; check disk space\n"); - tevent = CreateEvent(NULL, FALSE, FALSE, NULL); + tevent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!tevent) Sys_Error ("Couldn't create event"); @@ -532,17 +541,15 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin oldtime = Sys_DoubleTime (); - /* main window message loop */ - while (1) - { - // yield the CPU for a little while when paused, minimized, or not the focus - if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized || block_drawing) - { + /* main window message loop */ + while (1) { + // yield the CPU for a little while when paused, minimized, or not + // the focus + if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized + || block_drawing) { SleepUntilInput (PAUSE_SLEEP); - scr_skipupdate = 1; // no point in bothering to draw - } - else if (!ActiveApp && !DDActive) - { + scr_skipupdate = 1; // no point in bothering to draw + } else if (!ActiveApp && !DDActive) { SleepUntilInput (NOT_FOCUS_SLEEP); } @@ -552,7 +559,6 @@ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLin oldtime = newtime; } - /* return success of application */ - return TRUE; + /* return success of application */ + return TRUE; } - diff --git a/source/cl_tent.c b/source/cl_tent.c index 8c4ada6..92760f2 100644 --- a/source/cl_tent.c +++ b/source/cl_tent.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -48,41 +48,40 @@ #endif #define MAX_BEAMS 8 -typedef struct -{ - int entity; - struct model_s *model; - float endtime; - vec3_t start, end; +typedef struct { + int entity; + struct model_s *model; + float endtime; + vec3_t start, end; } beam_t; -beam_t cl_beams[MAX_BEAMS]; +beam_t cl_beams[MAX_BEAMS]; #define MAX_EXPLOSIONS 8 -typedef struct -{ - vec3_t origin; - float start; - model_t *model; +typedef struct { + vec3_t origin; + float start; + model_t *model; } explosion_t; -explosion_t cl_explosions[MAX_EXPLOSIONS]; +explosion_t cl_explosions[MAX_EXPLOSIONS]; -sfx_t *cl_sfx_wizhit; -sfx_t *cl_sfx_knighthit; -sfx_t *cl_sfx_tink1; -sfx_t *cl_sfx_ric1; -sfx_t *cl_sfx_ric2; -sfx_t *cl_sfx_ric3; -sfx_t *cl_sfx_r_exp3; +sfx_t *cl_sfx_wizhit; +sfx_t *cl_sfx_knighthit; +sfx_t *cl_sfx_tink1; +sfx_t *cl_sfx_ric1; +sfx_t *cl_sfx_ric2; +sfx_t *cl_sfx_ric3; +sfx_t *cl_sfx_r_exp3; /* ================= CL_ParseTEnts ================= */ -void CL_TEnts_Init (void) +void +CL_TEnts_Init (void) { cl_sfx_wizhit = S_PrecacheSound ("wizard/hit.wav"); cl_sfx_knighthit = S_PrecacheSound ("hknight/hit.wav"); @@ -98,10 +97,11 @@ void CL_TEnts_Init (void) CL_ClearTEnts ================= */ -void CL_ClearTEnts (void) +void +CL_ClearTEnts (void) { - memset (&cl_beams, 0, sizeof(cl_beams)); - memset (&cl_explosions, 0, sizeof(cl_explosions)); + memset (&cl_beams, 0, sizeof (cl_beams)); + memset (&cl_explosions, 0, sizeof (cl_explosions)); } /* @@ -109,22 +109,22 @@ void CL_ClearTEnts (void) CL_AllocExplosion ================= */ -explosion_t *CL_AllocExplosion (void) +explosion_t * +CL_AllocExplosion (void) { - int i; - float time; - int index; - - for (i=0 ; ientity == ent) - { + for (i = 0, b = cl_beams; i < MAX_BEAMS; i++, b++) + if (b->entity == ent) { b->entity = ent; b->model = m; b->endtime = cl.time + 0.2; @@ -164,12 +164,9 @@ void CL_ParseBeam (model_t *m) VectorCopy (end, b->end); return; } - // find a free beam - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) - { - if (!b->model || b->endtime < cl.time) - { + for (i = 0, b = cl_beams; i < MAX_BEAMS; i++, b++) { + if (!b->model || b->endtime < cl.time) { b->entity = ent; b->model = m; b->endtime = cl.time + 0.2; @@ -178,7 +175,7 @@ void CL_ParseBeam (model_t *m) return; } } - Con_Printf ("beam list overflow!\n"); + Con_Printf ("beam list overflow!\n"); } /* @@ -186,153 +183,151 @@ void CL_ParseBeam (model_t *m) CL_ParseTEnt ================= */ -void CL_ParseTEnt (void) +void +CL_ParseTEnt (void) { - byte type; - vec3_t pos; - dlight_t *dl; - int rnd; - explosion_t *ex; - int cnt = -1; + byte type; + vec3_t pos; + dlight_t *dl; + int rnd; + explosion_t *ex; + int cnt = -1; type = MSG_ReadByte (); - switch (type) - { - case TE_WIZSPIKE: // spike hitting wall - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_RunSpikeEffect (pos, type); - //R_RunParticleEffect (pos, 20, 30); - S_StartSound (-1, 0, cl_sfx_wizhit, pos, 1, 1); - break; - - case TE_KNIGHTSPIKE: // spike hitting wall - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_RunSpikeEffect (pos, type); - //R_RunParticleEffect (pos, 226, 20); - S_StartSound (-1, 0, cl_sfx_knighthit, pos, 1, 1); - break; - - case TE_SPIKE: // spike hitting wall - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_RunSpikeEffect (pos, type); - //R_RunParticleEffect (pos, 0, 10); + switch (type) { + case TE_WIZSPIKE: // spike hitting wall + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_RunSpikeEffect (pos, type); + // R_RunParticleEffect (pos, 20, 30); + S_StartSound (-1, 0, cl_sfx_wizhit, pos, 1, 1); + break; - if ( rand() % 5 ) - S_StartSound (-1, 0, cl_sfx_tink1, pos, 1, 1); - else - { - rnd = rand() & 3; - if (rnd == 1) - S_StartSound (-1, 0, cl_sfx_ric1, pos, 1, 1); - else if (rnd == 2) - S_StartSound (-1, 0, cl_sfx_ric2, pos, 1, 1); - else - S_StartSound (-1, 0, cl_sfx_ric3, pos, 1, 1); - } - break; - case TE_SUPERSPIKE: // super spike hitting wall - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_RunSpikeEffect (pos, type); - //R_RunParticleEffect (pos, 0, 20); + case TE_KNIGHTSPIKE: // spike hitting wall + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_RunSpikeEffect (pos, type); + // R_RunParticleEffect (pos, 226, 20); + S_StartSound (-1, 0, cl_sfx_knighthit, pos, 1, 1); + break; - if ( rand() % 5 ) - S_StartSound (-1, 0, cl_sfx_tink1, pos, 1, 1); - else - { - rnd = rand() & 3; - if (rnd == 1) - S_StartSound (-1, 0, cl_sfx_ric1, pos, 1, 1); - else if (rnd == 2) - S_StartSound (-1, 0, cl_sfx_ric2, pos, 1, 1); - else - S_StartSound (-1, 0, cl_sfx_ric3, pos, 1, 1); - } - break; - - case TE_EXPLOSION: // rocket explosion - // particles - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_ParticleExplosion (pos); - - // light - dl = CL_AllocDlight (0); - VectorCopy (pos, dl->origin); - dl->radius = 350; - dl->die = cl.time + 0.5; - dl->decay = 300; - dl->color[0] = 0.86; - dl->color[1] = 0.31; - dl->color[2] = 0.24; - - // sound - S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); - - // sprite - ex = CL_AllocExplosion (); - VectorCopy (pos, ex->origin); - ex->start = cl.time; - ex->model = Mod_ForName ("progs/s_explod.spr", true); - break; - - case TE_TAREXPLOSION: // tarbaby explosion - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_BlobExplosion (pos); + case TE_SPIKE: // spike hitting wall + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_RunSpikeEffect (pos, type); + // R_RunParticleEffect (pos, 0, 10); - S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); - break; + if (rand () % 5) + S_StartSound (-1, 0, cl_sfx_tink1, pos, 1, 1); + else { + rnd = rand () & 3; + if (rnd == 1) + S_StartSound (-1, 0, cl_sfx_ric1, pos, 1, 1); + else if (rnd == 2) + S_StartSound (-1, 0, cl_sfx_ric2, pos, 1, 1); + else + S_StartSound (-1, 0, cl_sfx_ric3, pos, 1, 1); + } + break; + case TE_SUPERSPIKE: // super spike hitting wall + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_RunSpikeEffect (pos, type); + // R_RunParticleEffect (pos, 0, 20); - case TE_LIGHTNING1: // lightning bolts - CL_ParseBeam (Mod_ForName("progs/bolt.mdl", true)); - break; - - case TE_LIGHTNING2: // lightning bolts - CL_ParseBeam (Mod_ForName("progs/bolt2.mdl", true)); - break; - - case TE_LIGHTNING3: // lightning bolts - CL_ParseBeam (Mod_ForName("progs/bolt3.mdl", true)); - break; - - case TE_LAVASPLASH: - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_LavaSplash (pos); - break; - - case TE_TELEPORT: - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_TeleportSplash (pos); - break; + if (rand () % 5) + S_StartSound (-1, 0, cl_sfx_tink1, pos, 1, 1); + else { + rnd = rand () & 3; + if (rnd == 1) + S_StartSound (-1, 0, cl_sfx_ric1, pos, 1, 1); + else if (rnd == 2) + S_StartSound (-1, 0, cl_sfx_ric2, pos, 1, 1); + else + S_StartSound (-1, 0, cl_sfx_ric3, pos, 1, 1); + } + break; - case TE_GUNSHOT: // bullet hitting wall - case TE_BLOOD: // bullets hitting body - cnt = MSG_ReadByte (); - case TE_LIGHTNINGBLOOD: // lightning hitting body - pos[0] = MSG_ReadCoord (); - pos[1] = MSG_ReadCoord (); - pos[2] = MSG_ReadCoord (); - R_RunPuffEffect (pos, type, cnt); - //R_RunParticleEffect (pos, 0, 20*cnt); - break; - - default: -// Sys_Error ("CL_ParseTEnt: bad type"); - Host_EndGame ("CL_ParseTEnt: bad type"); + case TE_EXPLOSION: // rocket explosion + // particles + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_ParticleExplosion (pos); + + // light + dl = CL_AllocDlight (0); + VectorCopy (pos, dl->origin); + dl->radius = 350; + dl->die = cl.time + 0.5; + dl->decay = 300; + dl->color[0] = 0.86; + dl->color[1] = 0.31; + dl->color[2] = 0.24; + + // sound + S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); + + // sprite + ex = CL_AllocExplosion (); + VectorCopy (pos, ex->origin); + ex->start = cl.time; + ex->model = Mod_ForName ("progs/s_explod.spr", true); + break; + + case TE_TAREXPLOSION: // tarbaby explosion + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_BlobExplosion (pos); + + S_StartSound (-1, 0, cl_sfx_r_exp3, pos, 1, 1); + break; + + case TE_LIGHTNING1: // lightning bolts + CL_ParseBeam (Mod_ForName ("progs/bolt.mdl", true)); + break; + + case TE_LIGHTNING2: // lightning bolts + CL_ParseBeam (Mod_ForName ("progs/bolt2.mdl", true)); + break; + + case TE_LIGHTNING3: // lightning bolts + CL_ParseBeam (Mod_ForName ("progs/bolt3.mdl", true)); + break; + + case TE_LAVASPLASH: + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_LavaSplash (pos); + break; + + case TE_TELEPORT: + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_TeleportSplash (pos); + break; + + case TE_GUNSHOT: // bullet hitting wall + case TE_BLOOD: // bullets hitting body + cnt = MSG_ReadByte (); + case TE_LIGHTNINGBLOOD: // lightning hitting body + pos[0] = MSG_ReadCoord (); + pos[1] = MSG_ReadCoord (); + pos[2] = MSG_ReadCoord (); + R_RunPuffEffect (pos, type, cnt); + // R_RunParticleEffect (pos, 0, 20*cnt); + break; + + default: +// Sys_Error ("CL_ParseTEnt: bad type"); + Host_EndGame ("CL_ParseTEnt: bad type"); } } @@ -342,24 +337,26 @@ void CL_ParseTEnt (void) CL_NewTempEntity ================= */ -entity_t *CL_NewTempEntity (void) +entity_t * +CL_NewTempEntity (void) { - entity_t *ent; + entity_t *ent; if (cl_numvisedicts == MAX_VISEDICTS) return NULL; ent = &cl_visedicts[cl_numvisedicts]; cl_numvisedicts++; ent->keynum = 0; - - memset (ent, 0, sizeof(*ent)); + + memset (ent, 0, sizeof (*ent)); ent->colormap = vid.colormap; - // LordHavoc: Endy had neglected to do this as part of the QSG VERSION 2 stuff - ent->glowsize = 0; - ent->glowcolor = 254; - ent->alpha = 1; - ent->scale = 1; + // LordHavoc: Endy had neglected to do this as part of the QSG VERSION 2 + // stuff + ent->glowsize = 0; + ent->glowcolor = 254; + ent->alpha = 1; + ent->scale = 1; ent->colormod[0] = ent->colormod[1] = ent->colormod[2] = 1; return ent; } @@ -370,57 +367,52 @@ entity_t *CL_NewTempEntity (void) CL_UpdateBeams ================= */ -void CL_UpdateBeams (void) +void +CL_UpdateBeams (void) { - int i,j; - beam_t *b; - vec3_t dist, org; - float d; - entity_t *ent; - float yaw, pitch; - float forward; + int i, j; + beam_t *b; + vec3_t dist, org; + float d; + entity_t *ent; + float yaw, pitch; + float forward; // update lightning - for (i=0, b=cl_beams ; i< MAX_BEAMS ; i++, b++) - { + for (i = 0, b = cl_beams; i < MAX_BEAMS; i++, b++) { if (!b->model || b->endtime < cl.time) continue; - // if coming from the player, update the start position - if (b->entity == cl.playernum+1) // entity 0 is the world + // if coming from the player, update the start position + if (b->entity == cl.playernum + 1) // entity 0 is the world { VectorCopy (cl.simorg, b->start); -// b->start[2] -= 22; // adjust for view height +// b->start[2] -= 22; // adjust for view height } - - // calculate pitch and yaw + // calculate pitch and yaw VectorSubtract (b->end, b->start, dist); - if (dist[1] == 0 && dist[0] == 0) - { + if (dist[1] == 0 && dist[0] == 0) { yaw = 0; if (dist[2] > 0) pitch = 90; else pitch = 270; - } - else - { - yaw = (int) (atan2(dist[1], dist[0]) * 180 / M_PI); + } else { + yaw = (int) (atan2 (dist[1], dist[0]) * 180 / M_PI); if (yaw < 0) yaw += 360; - - forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]); - pitch = (int) (atan2(dist[2], forward) * 180 / M_PI); + + forward = sqrt (dist[0] * dist[0] + dist[1] * dist[1]); + pitch = (int) (atan2 (dist[2], forward) * 180 / M_PI); if (pitch < 0) pitch += 360; } - // add new entities for the lightning + // add new entities for the lightning VectorCopy (b->start, org); - d = VectorNormalize(dist); - while (d > 0) - { + d = VectorNormalize (dist); + while (d > 0) { ent = CL_NewTempEntity (); if (!ent) return; @@ -428,14 +420,14 @@ void CL_UpdateBeams (void) ent->model = b->model; ent->angles[0] = pitch; ent->angles[1] = yaw; - ent->angles[2] = rand()%360; + ent->angles[2] = rand () % 360; - for (j=0 ; j<3 ; j++) - org[j] += dist[j]*30; + for (j = 0; j < 3; j++) + org[j] += dist[j] * 30; d -= 30; } } - + } /* @@ -443,20 +435,19 @@ void CL_UpdateBeams (void) CL_UpdateExplosions ================= */ -void CL_UpdateExplosions (void) +void +CL_UpdateExplosions (void) { - int i; - int f; - explosion_t *ex; - entity_t *ent; + int i; + int f; + explosion_t *ex; + entity_t *ent; - for (i=0, ex=cl_explosions ; i< MAX_EXPLOSIONS ; i++, ex++) - { + for (i = 0, ex = cl_explosions; i < MAX_EXPLOSIONS; i++, ex++) { if (!ex->model) continue; - f = 10*(cl.time - ex->start); - if (f >= ex->model->numframes) - { + f = 10 * (cl.time - ex->start); + if (f >= ex->model->numframes) { ex->model = NULL; continue; } @@ -475,7 +466,8 @@ void CL_UpdateExplosions (void) CL_UpdateTEnts ================= */ -void CL_UpdateTEnts (void) +void +CL_UpdateTEnts (void) { CL_UpdateBeams (); CL_UpdateExplosions (); diff --git a/source/cl_trans.c b/source/cl_trans.c index b0710d2..e197ba3 100644 --- a/source/cl_trans.c +++ b/source/cl_trans.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -45,23 +45,24 @@ CL_NewTranslation ===================== */ -void CL_NewTranslation (int slot) +void +CL_NewTranslation (int slot) { - int i, j; - int top, bottom; - byte *dest, *source; - player_info_t *player; - char s[512]; + int i, j; + int top, bottom; + byte *dest, *source; + player_info_t *player; + char s[512]; if (slot > MAX_CLIENTS) -// Sys_Error ("CL_NewTranslation: slot > MAX_CLIENTS"); +// Sys_Error ("CL_NewTranslation: slot > MAX_CLIENTS"); Host_EndGame ("CL_NewTranslation: slot > MAX_CLIENTS"); player = &cl.players[slot]; - strcpy(s, Info_ValueForKey(player->userinfo, "skin")); - COM_StripExtension(s, s); - if (player->skin && !stricmp(s, player->skin->name)) + strcpy (s, Info_ValueForKey (player->userinfo, "skin")); + COM_StripExtension (s, s); + if (player->skin && !stricmp (s, player->skin->name)) player->skin = NULL; if (player->_topcolor != player->topcolor || @@ -71,7 +72,7 @@ void CL_NewTranslation (int slot) dest = player->translations; source = vid.colormap; - memcpy (dest, vid.colormap, sizeof(player->translations)); + memcpy (dest, vid.colormap, sizeof (player->translations)); top = player->topcolor; if (top > 13 || top < 0) top = 13; @@ -81,19 +82,19 @@ void CL_NewTranslation (int slot) bottom = 13; bottom *= 16; - for (i=0 ; i= cmd_text.maxsize) - { + if (cmd_text.cursize + l >= cmd_text.maxsize) { Con_Printf ("Cbuf_AddText: overflow\n"); return; } @@ -132,52 +134,48 @@ Adds a \n to the text FIXME: actually change the command buffer to do less copying ============ */ -#if 0 // Tonik -void Cbuf_InsertText (char *text) +#if 0 // Tonik +void +Cbuf_InsertText (char *text) { - char *temp; - int templen; + char *temp; + int templen; // copy off any commands still remaining in the exec buffer templen = cmd_text.cursize; - if (templen) - { + if (templen) { temp = malloc (templen); memcpy (temp, cmd_text.data, templen); SZ_Clear (&cmd_text); - } - else - temp = NULL; // shut up compiler + } else + temp = NULL; // shut up compiler // add the entire text of the file Cbuf_AddText (text); SZ_Write (&cmd_text, "\n", 1); // add the copied off data - if (templen) - { + if (templen) { SZ_Write (&cmd_text, temp, templen); free (temp); } } #else -void Cbuf_InsertText (char *text) +void +Cbuf_InsertText (char *text) { - int textlen; + int textlen; - textlen = strlen(text); - if (cmd_text.cursize + 1 + textlen >= cmd_text.maxsize) - { + textlen = strlen (text); + if (cmd_text.cursize + 1 + textlen >= cmd_text.maxsize) { Con_Printf ("Cbuf_InsertText: overflow\n"); return; } - if (!cmd_text.cursize) - { + if (!cmd_text.cursize) { memcpy (cmd_text.data, text, textlen); cmd_text.cursize = textlen; return; } - // Move up to make room for inserted text memmove (cmd_text.data + textlen + 1, cmd_text.data, cmd_text.cursize); cmd_text.cursize += textlen + 1; @@ -190,28 +188,31 @@ void Cbuf_InsertText (char *text) static void -extract_line(char *line) +extract_line (char *line) { - int i; - char *text; - int quotes; + int i; + char *text; + int quotes; // find a \n or ; line break - text = (char *)cmd_text.data; + text = (char *) cmd_text.data; quotes = 0; - for (i=0 ; i< cmd_text.cursize ; i++) { + for (i = 0; i < cmd_text.cursize; i++) { if (text[i] == '"') quotes++; - if ( !(quotes&1) && text[i] == ';') - break; // don't break if inside a quoted string + if (!(quotes & 1) && text[i] == ';') + break; // don't break if inside a quoted + // string if (text[i] == '\n' || text[i] == '\r') break; } memcpy (line, text, i); line[i] = '\0'; - // delete the text from the command buffer and move remaining commands down - // this is necessary because commands (exec, alias) can insert data at the + // delete the text from the command buffer and move remaining commands + // down + // this is necessary because commands (exec, alias) can insert data at + // the // beginning of the text buffer if (i == cmd_text.cursize) @@ -219,7 +220,7 @@ extract_line(char *line) else { i++; cmd_text.cursize -= i; - memcpy (text, text+i, cmd_text.cursize); + memcpy (text, text + i, cmd_text.cursize); } } @@ -231,22 +232,23 @@ extract_line(char *line) void Cbuf_Execute (void) { - char line[1024] = {0}; + char line[1024] = { 0 }; while (cmd_text.cursize) { extract_line (line); // execute the command line - //Con_DPrintf("+%s\n",line), + // Con_DPrintf("+%s\n",line), Cmd_ExecuteString (line); - if (cmd_wait) - { // skip out while text still remains in buffer, leaving it + if (cmd_wait) { // skip out while text still remains + // in buffer, leaving it // for next frame cmd_wait = false; break; } } } + /* Cbuf_Execute @@ -255,17 +257,17 @@ Cbuf_Execute (void) void Cbuf_Execute_Sets (void) { - char line[1024] = {0}; + char line[1024] = { 0 }; while (cmd_text.cursize) { extract_line (line); // execute the command line - if (strnequal(line, "set", 3) && isspace((int) line[3])) { - //Con_DPrintf ("+%s\n",line); + if (strnequal (line, "set", 3) && isspace ((int) line[3])) { + // Con_DPrintf ("+%s\n",line); Cmd_ExecuteString (line); } - if (strnequal(line, "setrom", 6) && isspace((int) line[6])) { - //Con_DPrintf ("+%s\n",line); + if (strnequal (line, "setrom", 6) && isspace ((int) line[6])) { + // Con_DPrintf ("+%s\n",line); Cmd_ExecuteString (line); } } @@ -289,42 +291,40 @@ quake +prog jctest.qp +cmd amlev1 quake -nosound +cmd amlev1 =============== */ -void Cmd_StuffCmds_f (void) +void +Cmd_StuffCmds_f (void) { - int i, j; - int s; - char *build, c; + int i, j; + int s; + char *build, c; s = strlen (com_cmdline); if (!s) return; // pull out the commands - build = malloc (s+1); + build = malloc (s + 1); build[0] = 0; - for (i=0 ; i : execute a script file\n"); return; } - // FIXME: is this safe freeing the hunk here? mark = Hunk_LowMark (); - f = (char *)COM_LoadHunkFile (Cmd_Argv(1)); - if (!f) - { - Con_Printf ("couldn't exec %s\n",Cmd_Argv(1)); + f = (char *) COM_LoadHunkFile (Cmd_Argv (1)); + if (!f) { + Con_Printf ("couldn't exec %s\n", Cmd_Argv (1)); return; } if (!Cvar_Command () && ((cl_warncmd && cl_warncmd->int_val) - || (developer && developer->int_val))) - Con_Printf ("execing %s\n",Cmd_Argv(1)); + || (developer && developer->int_val))) + Con_Printf ("execing %s\n", Cmd_Argv (1)); Cbuf_InsertText (f); Hunk_FreeToLowMark (mark); @@ -402,12 +400,13 @@ Cmd_Echo_f Just prints the rest of the line to the console =============== */ -void Cmd_Echo_f (void) +void +Cmd_Echo_f (void) { - int i; + int i; - for (i=1 ; inext) + for (a = cmd_alias; a; a = a->next) Con_Printf ("%s : %s\n", a->name, a->value); return; } - s = Cmd_Argv(1); - if (strlen(s) >= MAX_ALIAS_NAME) - { + s = Cmd_Argv (1); + if (strlen (s) >= MAX_ALIAS_NAME) { Con_Printf ("Alias name is too long\n"); return; } - // if the alias allready exists, reuse it - for (a = cmd_alias ; a ; a=a->next) - { - if (!strcmp(s, a->name)) - { + for (a = cmd_alias; a; a = a->next) { + if (!strcmp (s, a->name)) { free (a->value); break; } } - if (!a) - { - a = calloc (1, sizeof(cmdalias_t)); + if (!a) { + a = calloc (1, sizeof (cmdalias_t)); a->next = cmd_alias; cmd_alias = a; } strcpy (a->name, s); // copy the rest of the command line - cmd[0] = 0; // start out with a null string - c = Cmd_Argc(); - for (i=2 ; i< c ; i++) - { - strncat (cmd, Cmd_Argv(i), sizeof(cmd) - strlen (cmd)); + cmd[0] = 0; // start out with a null string + c = Cmd_Argc (); + for (i = 2; i < c; i++) { + strncat (cmd, Cmd_Argv (i), sizeof (cmd) - strlen (cmd)); if (i != c) - strncat (cmd, " ", sizeof(cmd) - strlen (cmd)); + strncat (cmd, " ", sizeof (cmd) - strlen (cmd)); } - strncat (cmd, "\n", sizeof(cmd) - strlen (cmd)); + strncat (cmd, "\n", sizeof (cmd) - strlen (cmd)); a->value = CopyString (cmd); } -void Cmd_UnAlias_f (void) +void +Cmd_UnAlias_f (void) { - cmdalias_t *a, *prev; - char *s; + cmdalias_t *a, *prev; + char *s; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("unalias : erase an existing alias\n"); return; } - s = Cmd_Argv(1); - if (strlen(s) >= MAX_ALIAS_NAME) - { + s = Cmd_Argv (1); + if (strlen (s) >= MAX_ALIAS_NAME) { Con_Printf ("Alias name is too long\n"); return; } prev = cmd_alias; - for (a = cmd_alias ; a ; a = a->next) - { - if (!strcmp(s, a->name)) - { + for (a = cmd_alias; a; a = a->next) { + if (!strcmp (s, a->name)) { free (a->value); prev->next = a->next; if (a == cmd_alias) @@ -525,31 +516,31 @@ void Cmd_UnAlias_f (void) ============================================================================= */ -typedef struct cmd_function_s -{ - struct cmd_function_s *next; - char *name; - xcommand_t function; +typedef struct cmd_function_s { + struct cmd_function_s *next; + char *name; + xcommand_t function; } cmd_function_t; #define MAX_ARGS 80 -static int cmd_argc; -static char *cmd_argv[MAX_ARGS]; -static char *cmd_null_string = ""; -static char *cmd_args = NULL; +static int cmd_argc; +static char *cmd_argv[MAX_ARGS]; +static char *cmd_null_string = ""; +static char *cmd_args = NULL; -static cmd_function_t *cmd_functions; // possible commands to execute +static cmd_function_t *cmd_functions; // possible commands to execute /* ============ Cmd_Argc ============ */ -int Cmd_Argc (void) +int +Cmd_Argc (void) { return cmd_argc; } @@ -559,9 +550,10 @@ int Cmd_Argc (void) Cmd_Argv ============ */ -char *Cmd_Argv (int arg) +char * +Cmd_Argv (int arg) { - if ( arg >= cmd_argc ) + if (arg >= cmd_argc) return cmd_null_string; return cmd_argv[arg]; } @@ -573,7 +565,8 @@ Cmd_Args Returns a single string containing argv(1) to argv(argc()-1) ============ */ -char *Cmd_Args (void) +char * +Cmd_Args (void) { if (!cmd_args) return ""; @@ -588,26 +581,25 @@ Cmd_TokenizeString Parses the given string into command line tokens. ============ */ -void Cmd_TokenizeString (char *text) +void +Cmd_TokenizeString (char *text) { - static char argv_buf[1024]; - int argv_idx; + static char argv_buf[1024]; + int argv_idx; argv_idx = 0; cmd_argc = 0; cmd_args = NULL; - while (1) - { + while (1) { // skip whitespace up to a /n - while (*text && *(unsigned char*)text <= ' ' && *text != '\n') - { + while (*text && *(unsigned char *) text <= ' ' && *text != '\n') { text++; } - if (*text == '\n') - { // a newline seperates commands in the buffer + if (*text == '\n') { // a newline seperates commands in + // the buffer text++; break; } @@ -616,22 +608,20 @@ void Cmd_TokenizeString (char *text) return; if (cmd_argc == 1) - cmd_args = text; + cmd_args = text; text = COM_Parse (text); if (!text) return; - if (cmd_argc < MAX_ARGS) - { - if (argv_idx + strlen(com_token) + 1 > 1024) - { + if (cmd_argc < MAX_ARGS) { + if (argv_idx + strlen (com_token) + 1 > 1024) { Con_Printf ("Cmd_TokenizeString: overflow\n"); return; } cmd_argv[cmd_argc] = argv_buf + argv_idx; strcpy (cmd_argv[cmd_argc], com_token); - argv_idx += strlen(com_token) + 1; + argv_idx += strlen (com_token) + 1; cmd_argc++; } @@ -645,31 +635,29 @@ void Cmd_TokenizeString (char *text) Cmd_AddCommand ============ */ -void Cmd_AddCommand (char *cmd_name, xcommand_t function) +void +Cmd_AddCommand (char *cmd_name, xcommand_t function) { - cmd_function_t *cmd; + cmd_function_t *cmd; - if (host_initialized) // because hunk allocation would get stomped + if (host_initialized) // because hunk allocation would get + // stomped Sys_Error ("Cmd_AddCommand after host_initialized"); // fail if the command is a variable name - if (Cvar_VariableString(cmd_name)[0]) - { + if (Cvar_VariableString (cmd_name)[0]) { Con_Printf ("Cmd_AddCommand: %s already defined as a var\n", cmd_name); return; } - // fail if the command already exists - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (!strcmp (cmd_name, cmd->name)) - { + for (cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!strcmp (cmd_name, cmd->name)) { Con_Printf ("Cmd_AddCommand: %s already defined\n", cmd_name); return; } } - cmd = Hunk_Alloc (sizeof(cmd_function_t)); + cmd = Hunk_Alloc (sizeof (cmd_function_t)); cmd->name = cmd_name; cmd->function = function; cmd->next = cmd_functions; @@ -681,13 +669,13 @@ void Cmd_AddCommand (char *cmd_name, xcommand_t function) Cmd_Exists ============ */ -qboolean Cmd_Exists (char *cmd_name) +qboolean +Cmd_Exists (char *cmd_name) { - cmd_function_t *cmd; + cmd_function_t *cmd; - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (!strcmp (cmd_name,cmd->name)) + for (cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!strcmp (cmd_name, cmd->name)) return true; } @@ -701,30 +689,31 @@ qboolean Cmd_Exists (char *cmd_name) Cmd_CompleteCommand ============ */ -char *Cmd_CompleteCommand (char *partial) +char * +Cmd_CompleteCommand (char *partial) { - cmd_function_t *cmd; - int len; - cmdalias_t *a; + cmd_function_t *cmd; + int len; + cmdalias_t *a; - len = strlen(partial); + len = strlen (partial); if (!len) return NULL; // check for exact match - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) + for (cmd = cmd_functions; cmd; cmd = cmd->next) if (!strcasecmp (partial, cmd->name)) return cmd->name; - for (a=cmd_alias ; a ; a=a->next) + for (a = cmd_alias; a; a = a->next) if (!strcasecmp (partial, a->name)) return a->name; // check for partial match - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) + for (cmd = cmd_functions; cmd; cmd = cmd->next) if (!strncasecmp (partial, cmd->name, len)) return cmd->name; - for (a=cmd_alias ; a ; a=a->next) + for (a = cmd_alias; a; a = a->next) if (!strncasecmp (partial, a->name, len)) return a->name; @@ -740,70 +729,63 @@ FIXME: better handling of buffer overflows? ============ */ // dest must point to a 1024-byte buffer -void Cmd_ExpandVariables (char *data, char *dest) +void +Cmd_ExpandVariables (char *data, char *dest) { - unsigned int c; - char buf[1024]; - int i, len; - cvar_t *var, *bestvar; - int quotes = 0; + unsigned int c; + char buf[1024]; + int i, len; + cvar_t *var, *bestvar; + int quotes = 0; len = 0; // parse a regular word - while ( (c = *data) != 0) - { + while ((c = *data) != 0) { if (c == '"') quotes++; - if (c == '$' && !(quotes&1)) - { + if (c == '$' && !(quotes & 1)) { data++; // Copy the text after '$' to a temp buffer i = 0; buf[0] = 0; bestvar = NULL; - while ((c = *data) > 32) - { + while ((c = *data) > 32) { if (c == '$') break; data++; buf[i++] = c; buf[i] = 0; - if ((var = Cvar_FindVar(buf)) != 0) + if ((var = Cvar_FindVar (buf)) != 0) bestvar = var; - if (i >= sizeof(buf)-1) + if (i >= sizeof (buf) - 1) break; } - if (bestvar) - { + if (bestvar) { // check buffer size - if (len + strlen(bestvar->string) >= 1024-1) + if (len + strlen (bestvar->string) >= 1024 - 1) break; - strcpy(&dest[len], bestvar->string); - len += strlen(bestvar->string); - i = strlen(bestvar->name); + strcpy (&dest[len], bestvar->string); + len += strlen (bestvar->string); + i = strlen (bestvar->name); while (buf[i]) dest[len++] = buf[i++]; - } - else - { + } else { // no matching cvar name was found dest[len++] = '$'; - if (len + strlen(buf) >= 1024-1) + if (len + strlen (buf) >= 1024 - 1) break; strcpy (&dest[len], buf); - len += strlen(buf); + len += strlen (buf); } - } - else - { + } else { dest[len] = c; data++; len++; - if (len >= 1024-1) + if (len >= 1024 - 1) break; } }; @@ -819,11 +801,12 @@ A complete command line has been parsed, so try to execute it FIXME: lookupnoadd the token to speed search? ============ */ -void Cmd_ExecuteString (char *text) +void +Cmd_ExecuteString (char *text) { - cmd_function_t *cmd; - cmdalias_t *a; - char buf[1024]; + cmd_function_t *cmd; + cmdalias_t *a; + char buf[1024]; #if 0 Cmd_TokenizeString (text); @@ -833,14 +816,12 @@ void Cmd_ExecuteString (char *text) #endif // execute the command line - if (!Cmd_Argc()) - return; // no tokens + if (!Cmd_Argc ()) + return; // no tokens // check functions - for (cmd=cmd_functions ; cmd ; cmd=cmd->next) - { - if (!strcasecmp (cmd_argv[0],cmd->name)) - { + for (cmd = cmd_functions; cmd; cmd = cmd->next) { + if (!strcasecmp (cmd_argv[0], cmd->name)) { if (!cmd->function) Cmd_ForwardToServer (); else @@ -850,21 +831,19 @@ void Cmd_ExecuteString (char *text) } // Tonik: check cvars - if (Cvar_Command()) + if (Cvar_Command ()) return; // check alias - for (a=cmd_alias ; a ; a=a->next) - { - if (!strcasecmp (cmd_argv[0], a->name)) - { + for (a = cmd_alias; a; a = a->next) { + if (!strcasecmp (cmd_argv[0], a->name)) { Cbuf_InsertText (a->value); return; } } - + if (cl_warncmd->int_val || developer->int_val) - Con_Printf ("Unknown command \"%s\"\n", Cmd_Argv(0)); + Con_Printf ("Unknown command \"%s\"\n", Cmd_Argv (0)); } @@ -878,28 +857,29 @@ Returns the position (1 to argc-1) in the command's argument list where the given parameter apears, or 0 if not present ================ */ -int Cmd_CheckParm (char *parm) +int +Cmd_CheckParm (char *parm) { - int i; + int i; if (!parm) Sys_Error ("Cmd_CheckParm: NULL"); for (i = 1; i < Cmd_Argc (); i++) - if (! strcasecmp (parm, Cmd_Argv (i))) + if (!strcasecmp (parm, Cmd_Argv (i))) return i; return 0; } -void Cmd_CmdList_f (void) +void +Cmd_CmdList_f (void) { - cmd_function_t *cmd; - int i; + cmd_function_t *cmd; + int i; - for (cmd=cmd_functions, i=0 ; cmd ; cmd=cmd->next, i++) - { - Con_Printf("%s\n", cmd->name); + for (cmd = cmd_functions, i = 0; cmd; cmd = cmd->next, i++) { + Con_Printf ("%s\n", cmd->name); } Con_Printf ("------------\n%d commands\n", i); @@ -910,22 +890,23 @@ void Cmd_CmdList_f (void) Cmd_Init ============ */ -void Cmd_Init (void) +void +Cmd_Init (void) { // // register our commands // - Cmd_AddCommand ("stuffcmds",Cmd_StuffCmds_f); - Cmd_AddCommand ("exec",Cmd_Exec_f); - Cmd_AddCommand ("echo",Cmd_Echo_f); - Cmd_AddCommand ("alias",Cmd_Alias_f); - Cmd_AddCommand ("unalias",Cmd_UnAlias_f); + Cmd_AddCommand ("stuffcmds", Cmd_StuffCmds_f); + Cmd_AddCommand ("exec", Cmd_Exec_f); + Cmd_AddCommand ("echo", Cmd_Echo_f); + Cmd_AddCommand ("alias", Cmd_Alias_f); + Cmd_AddCommand ("unalias", Cmd_UnAlias_f); Cmd_AddCommand ("wait", Cmd_Wait_f); Cmd_AddCommand ("cmdlist", Cmd_CmdList_f); } -char com_token[MAX_COM_TOKEN]; +char com_token[MAX_COM_TOKEN]; /* ============== @@ -934,44 +915,39 @@ COM_Parse Parse a token out of a string ============== */ -char *COM_Parse (char *data) +char * +COM_Parse (char *data) { - unsigned int c; - int len; - + unsigned int c; + int len; + len = 0; com_token[0] = 0; - + if (!data) return NULL; - + // skip whitespace -skipwhite: - while ( (c = *data) <= ' ') - { + skipwhite: + while ((c = *data) <= ' ') { if (c == 0) - return NULL; // end of file; + return NULL; // end of file; data++; } - + // skip // comments - if (c=='/' && data[1] == '/') - { + if (c == '/' && data[1] == '/') { while (*data && *data != '\n') data++; goto skipwhite; } - // handle quoted strings specially - if (c == '\"') - { + if (c == '\"') { data++; - while (1) - { + while (1) { c = *data++; - if (c=='\"' || !c) - { + if (c == '\"' || !c) { com_token[len] = 0; return data; } @@ -979,19 +955,17 @@ skipwhite: len++; } } - // parse a regular word - do - { + do { com_token[len] = c; data++; len++; - if (len >= MAX_COM_TOKEN-1) + if (len >= MAX_COM_TOKEN - 1) break; c = *data; - } while (c>32); - + } while (c > 32); + com_token[len] = 0; return data; } diff --git a/source/com.c b/source/com.c index 7a0e868..7cebb2c 100644 --- a/source/com.c +++ b/source/com.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "cvar.h" @@ -38,15 +38,15 @@ #include -cvar_t *registered; +cvar_t *registered; -qboolean com_modified; // set true if using non-id files +qboolean com_modified; // set true if using non-id files -int static_registered = 1; // only for startup check, then set +int static_registered = 1; // only for startup check, then set -qboolean msg_suppress_1 = 0; +qboolean msg_suppress_1 = 0; -void COM_Path_f (void); +void COM_Path_f (void); /* @@ -59,17 +59,18 @@ Immediately exits out if an alternate game was attempted to be started without being registered. ================ */ -void COM_CheckRegistered (void) +void +COM_CheckRegistered (void) { - QFile *h; - unsigned short check[128]; + QFile *h; + unsigned short check[128]; - COM_FOpenFile("gfx/pop.lmp", &h); + COM_FOpenFile ("gfx/pop.lmp", &h); static_registered = 0; if (h) { static_registered = 1; - Qread (h, check, sizeof(check)); + Qread (h, check, sizeof (check)); Qclose (h); } @@ -85,24 +86,25 @@ void COM_CheckRegistered (void) COM_Init ================ */ -void COM_Init (void) +void +COM_Init (void) { #ifndef WORDS_BIGENDIAN - bigendien = false; - BigShort = ShortSwap; - LittleShort = ShortNoSwap; - BigLong = LongSwap; - LittleLong = LongNoSwap; - BigFloat = FloatSwap; - LittleFloat = FloatNoSwap; + bigendien = false; + BigShort = ShortSwap; + LittleShort = ShortNoSwap; + BigLong = LongSwap; + LittleLong = LongNoSwap; + BigFloat = FloatSwap; + LittleFloat = FloatNoSwap; #else - bigendien = true; - BigShort = ShortNoSwap; - LittleShort = ShortSwap; - BigLong = LongNoSwap; - LittleLong = LongSwap; - BigFloat = FloatNoSwap; - LittleFloat = FloatSwap; + bigendien = true; + BigShort = ShortNoSwap; + LittleShort = ShortSwap; + BigLong = LongNoSwap; + LittleLong = LongSwap; + BigFloat = FloatNoSwap; + LittleFloat = FloatSwap; #endif Cmd_AddCommand ("path", COM_Path_f); @@ -111,7 +113,8 @@ void COM_Init (void) COM_CheckRegistered (); } -void COM_Init_Cvars (void) +void +COM_Init_Cvars (void) { - registered = Cvar_Get("registered", "0", CVAR_NONE, "None"); + registered = Cvar_Get ("registered", "0", CVAR_NONE, "None"); } diff --git a/source/console.c b/source/console.c index 11cf67a..dcb12be 100644 --- a/source/console.c +++ b/source/console.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -45,40 +45,47 @@ #include "va.h" #include "screen.h" -int con_ormask; -console_t con_main; -console_t con_chat; -console_t *con; // point to either con_main or con_chat +int con_ormask; +console_t con_main; +console_t con_chat; +console_t *con; // point to either con_main or -int con_linewidth; // characters across screen -int con_totallines; // total lines in console scrollback + // con_chat -float con_cursorspeed = 4; +int con_linewidth; // characters across screen +int con_totallines; // total lines in console scrollback + +float con_cursorspeed = 4; -cvar_t *con_notifytime; //seconds +cvar_t *con_notifytime; // seconds #define NUM_CON_TIMES 4 -float con_times[NUM_CON_TIMES]; // realtime time the line was generated +float con_times[NUM_CON_TIMES]; // realtime time the line was + + // generated // for transparent notify lines -int con_vislines; -int con_notifylines; // scan lines to clear for notify lines +int con_vislines; +int con_notifylines; // scan lines to clear for notify -qboolean con_debuglog; + // lines + +qboolean con_debuglog; #define MAXCMDLINE 256 -extern char key_lines[32][MAXCMDLINE]; -extern int edit_line; -extern int key_linepos; - - -qboolean con_initialized; +extern char key_lines[32][MAXCMDLINE]; +extern int edit_line; +extern int key_linepos; -void Key_ClearTyping (void) +qboolean con_initialized; + + +void +Key_ClearTyping (void) { - key_lines[edit_line][1] = 0; // clear any typing + key_lines[edit_line][1] = 0; // clear any typing key_linepos = 1; } @@ -87,18 +94,17 @@ void Key_ClearTyping (void) Con_ToggleConsole_f ================ */ -void Con_ToggleConsole_f (void) +void +Con_ToggleConsole_f (void) { Key_ClearTyping (); - if (key_dest == key_console) - { + if (key_dest == key_console) { if (cls.state == ca_active) key_dest = key_game; - } - else + } else key_dest = key_console; - + Con_ClearNotify (); } @@ -107,18 +113,17 @@ void Con_ToggleConsole_f (void) Con_ToggleChat_f ================ */ -void Con_ToggleChat_f (void) +void +Con_ToggleChat_f (void) { Key_ClearTyping (); - if (key_dest == key_console) - { + if (key_dest == key_console) { if (cls.state == ca_active) key_dest = key_game; - } - else + } else key_dest = key_console; - + Con_ClearNotify (); } @@ -127,7 +132,8 @@ void Con_ToggleChat_f (void) Con_Clear_f ================ */ -void Con_Clear_f (void) +void +Con_Clear_f (void) { con_main.numlines = 0; con_chat.numlines = 0; @@ -136,27 +142,29 @@ void Con_Clear_f (void) con_main.display = con_main.current; } - + /* ================ Con_ClearNotify ================ */ -void Con_ClearNotify (void) +void +Con_ClearNotify (void) { - int i; - - for (i=0 ; i> 3) - 2; if (width == con_linewidth) return; - if (width < 1) // video hasn't been initialized yet + if (width < 1) // video hasn't been initialized yet { width = 38; con_linewidth = width; con_totallines = CON_TEXTSIZE / con_linewidth; memset (con->text, ' ', CON_TEXTSIZE); - } - else - { + } else { oldwidth = con_linewidth; con_linewidth = width; oldtotallines = con_totallines; @@ -212,20 +220,18 @@ void Con_Resize (console_t *con) numlines = con_totallines; numchars = oldwidth; - + if (con_linewidth < numchars) numchars = con_linewidth; memcpy (tbuf, con->text, CON_TEXTSIZE); memset (con->text, ' ', CON_TEXTSIZE); - for (i=0 ; itext[(con_totallines - 1 - i) * con_linewidth + j] = - tbuf[((con->current - i + oldtotallines) % - oldtotallines) * oldwidth + j]; + tbuf[((con->current - i + oldtotallines) % + oldtotallines) * oldwidth + j]; } } @@ -236,7 +242,7 @@ void Con_Resize (console_t *con) con->display = con->current; } - + /* ================ Con_CheckResize @@ -244,7 +250,8 @@ Con_CheckResize If the line width has changed, reformat the buffer. ================ */ -void Con_CheckResize (void) +void +Con_CheckResize (void) { Con_Resize (&con_main); Con_Resize (&con_chat); @@ -256,14 +263,15 @@ void Con_CheckResize (void) Con_Init ================ */ -void Con_Init (void) +void +Con_Init (void) { - con_debuglog = COM_CheckParm("-condebug"); + con_debuglog = COM_CheckParm ("-condebug"); con = &con_main; con_linewidth = -1; Con_CheckResize (); - + Con_Printf ("Console initialized.\n"); // @@ -277,9 +285,10 @@ void Con_Init (void) con_initialized = true; } -void Con_Init_Cvars (void) +void +Con_Init_Cvars (void) { - con_notifytime = Cvar_Get("con_notifytime", "3", CVAR_NONE, "None"); + con_notifytime = Cvar_Get ("con_notifytime", "3", CVAR_NONE, "None"); } @@ -288,7 +297,8 @@ void Con_Init_Cvars (void) Con_Linefeed =============== */ -void Con_Linefeed (void) +void +Con_Linefeed (void) { con->x = 0; if (con->display == con->current) @@ -296,8 +306,8 @@ void Con_Linefeed (void) con->current++; if (con->numlines < con_totallines) con->numlines++; - memset (&con->text[(con->current%con_totallines)*con_linewidth] - , ' ', con_linewidth); + memset (&con->text[(con->current % con_totallines) * con_linewidth] + , ' ', con_linewidth); } /* @@ -309,70 +319,65 @@ All console printing must go through this in order to be logged to disk If no console is visible, the notify window will pop up. ================ */ -void Con_Print (char *txt) +void +Con_Print (char *txt) { - int y; - int c, l; - static int cr; - int mask; + int y; + int c, l; + static int cr; + int mask; - if (txt[0] == 1 || txt[0] == 2) - { - mask = 128; // go to colored text + if (txt[0] == 1 || txt[0] == 2) { + mask = 128; // go to colored text txt++; - } - else + } else mask = 0; - while ( (c = *txt) ) - { - // count word length - for (l=0 ; l< con_linewidth ; l++) - if ( txt[l] <= ' ') + while ((c = *txt)) { + // count word length + for (l = 0; l < con_linewidth; l++) + if (txt[l] <= ' ') break; - // word wrap - if (l != con_linewidth && (con->x + l > con_linewidth) ) + // word wrap + if (l != con_linewidth && (con->x + l > con_linewidth)) con->x = 0; txt++; - if (cr) - { + if (cr) { con->current--; cr = false; } - - if (!con->x) - { + + if (!con->x) { Con_Linefeed (); - // mark time for transparent overlay + // mark time for transparent overlay if (con->current >= 0) con_times[con->current % NUM_CON_TIMES] = realtime; } - switch (c) - { - case '\n': - con->x = 0; - break; - - case '\r': - con->x = 0; - cr = 1; - break; - - default: // display character and advance - y = con->current % con_totallines; - con->text[y*con_linewidth+con->x] = c | mask | con_ormask; - con->x++; - if (con->x >= con_linewidth) + switch (c) { + case '\n': con->x = 0; - break; + break; + + case '\r': + con->x = 0; + cr = 1; + break; + + default: // display character and advance + y = con->current % con_totallines; + con->text[y * con_linewidth + con->x] = c | mask | con_ormask; + con->x++; + if (con->x >= con_linewidth) + con->x = 0; + break; } - + } } @@ -386,25 +391,26 @@ Handles cursor positioning, line wrapping, etc */ #define MAXPRINTMSG 4096 -void Con_Printf (char *fmt, ...) +void +Con_Printf (char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; - + va_list argptr; + char msg[MAXPRINTMSG]; + va_start (argptr, fmt); - vsnprintf (msg, sizeof(msg), fmt, argptr); + vsnprintf (msg, sizeof (msg), fmt, argptr); va_end (argptr); // also echo to debugging console - Sys_Printf ("%s", msg); // also echo to debugging console + Sys_Printf ("%s", msg); // also echo to debugging console // log all messages to file if (con_debuglog) Sys_DebugLog (va ("%s/qconsole.log", com_gamedir), "%s", msg); - + if (!con_initialized) return; - + // write it to the scrollable buffer Con_Print (msg); } @@ -416,18 +422,20 @@ Con_DPrintf A Con_Printf that only shows up if the "developer" cvar is set ================ */ -void Con_DPrintf (char *fmt, ...) +void +Con_DPrintf (char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; - + va_list argptr; + char msg[MAXPRINTMSG]; + if (!developer->int_val) - return; // don't confuse non-developers with techie stuff... + return; // don't confuse non-developers with + // techie stuff... va_start (argptr, fmt); - vsnprintf (msg, sizeof(msg), fmt, argptr); + vsnprintf (msg, sizeof (msg), fmt, argptr); va_end (argptr); - + Con_Printf ("%s", msg); } @@ -447,35 +455,37 @@ Con_DrawInput The input line scrolls horizontally if typing goes beyond the right edge ================ */ -void Con_DrawInput (void) +void +Con_DrawInput (void) { - int y; - int i; - char *text; - char temp[MAXCMDLINE]; + int y; + int i; + char *text; + char temp[MAXCMDLINE]; if (key_dest != key_console && cls.state == ca_active) - return; // don't draw anything (allways draw if not active) + return; // don't draw anything (allways draw + // if not active) text = strcpy (temp, key_lines[edit_line]); // fill out remainder with spaces - for (i=strlen(text) ; i < MAXCMDLINE ; i++) + for (i = strlen (text); i < MAXCMDLINE; i++) text[i] = ' '; // add the cursor frame - if ( (int)(realtime*con_cursorspeed) & 1 ) + if ((int) (realtime * con_cursorspeed) & 1) text[key_linepos] = 11; -// prestep if horizontally scrolling +// prestep if horizontally scrolling if (key_linepos >= con_linewidth) text += 1 + key_linepos - con_linewidth; // draw it - y = con_vislines-22; + y = con_vislines - 22; - for (i=0 ; icurrent-NUM_CON_TIMES+1 ; i<=con->current ; i++) - { + for (i = con->current - NUM_CON_TIMES + 1; i <= con->current; i++) { if (i < 0) continue; time = con_times[i % NUM_CON_TIMES]; @@ -506,47 +516,43 @@ void Con_DrawNotify (void) time = realtime - time; if (time > con_notifytime->value) continue; - text = con->text + (i % con_totallines)*con_linewidth; - + text = con->text + (i % con_totallines) * con_linewidth; + clearnotify = 0; scr_copytop = 1; - for (x = 0 ; x < con_linewidth ; x++) - Draw_Character8 ( (x+1)<<3, v, text[x]); + for (x = 0; x < con_linewidth; x++) + Draw_Character8 ((x + 1) << 3, v, text[x]); v += 8; } - if (key_dest == key_message) - { + if (key_dest == key_message) { clearnotify = 0; scr_copytop = 1; - - if (chat_team) - { + + if (chat_team) { Draw_String8 (8, v, "say_team:"); skip = 11; - } - else - { + } else { Draw_String8 (8, v, "say:"); skip = 5; } s = chat_buffer; - if (chat_bufferlen > (vid.width>>3)-(skip+1)) - s += chat_bufferlen - ((vid.width>>3)-(skip+1)); + if (chat_bufferlen > (vid.width >> 3) - (skip + 1)) + s += chat_bufferlen - ((vid.width >> 3) - (skip + 1)); x = 0; - while(s[x]) - { - Draw_Character8 ( (x+skip)<<3, v, s[x]); + while (s[x]) { + Draw_Character8 ((x + skip) << 3, v, s[x]); x++; } - Draw_Character8 ( (x+skip)<<3, v, 10+((int)(realtime*con_cursorspeed)&1)); + Draw_Character8 ((x + skip) << 3, v, + 10 + ((int) (realtime * con_cursorspeed) & 1)); v += 8; } - + if (v > con_notifylines) con_notifylines = v; } @@ -558,14 +564,15 @@ Con_DrawConsole Draws the console with the solid background ================ */ -void Con_DrawConsole (int lines) +void +Con_DrawConsole (int lines) { - int i, j, x, y, n; - int rows; - char *text; - int row; - char dlbar[1024]; - + int i, j, x, y, n; + int rows; + char *text; + int row; + char dlbar[1024]; + if (lines <= 0) return; @@ -574,64 +581,62 @@ void Con_DrawConsole (int lines) // draw the text con_vislines = lines; - + // changed to line things up better - rows = (lines-22)>>3; // rows of text to draw + rows = (lines - 22) >> 3; // rows of text to draw y = lines - 30; // draw from the bottom up - if (con->display != con->current) - { - // draw arrows to show the buffer is backscrolled - for (x=0 ; xdisplay != con->current) { + // draw arrows to show the buffer is backscrolled + for (x = 0; x < con_linewidth; x += 4) + Draw_Character8 ((x + 1) << 3, y, '^'); + y -= 8; rows--; } - + row = con->display; - for (i=0 ; icurrent - row >= con_totallines) - break; // past scrollback wrap point - - text = con->text + (row % con_totallines)*con_linewidth; + break; // past scrollback wrap point - for (x=0 ; xtext + (row % con_totallines) * con_linewidth; + + for (x = 0; x < con_linewidth; x++) + Draw_Character8 ((x + 1) << 3, y, text[x]); } // draw the download bar // figure out width if (cls.download) { - if ((text = strrchr(cls.downloadname, '/')) != NULL) + if ((text = strrchr (cls.downloadname, '/')) != NULL) text++; else text = cls.downloadname; x = con_linewidth - ((con_linewidth * 7) / 40); - y = x - strlen(text) - 8; - i = con_linewidth/3; - if (strlen(text) > i) { + y = x - strlen (text) - 8; + i = con_linewidth / 3; + if (strlen (text) > i) { y = x - i - 11; - strncpy(dlbar, text, i); + strncpy (dlbar, text, i); dlbar[i] = 0; - strncat (dlbar, "...", sizeof(dlbar) - strlen (dlbar)); + strncat (dlbar, "...", sizeof (dlbar) - strlen (dlbar)); } else - strncpy(dlbar, text, sizeof (dlbar)); - strncat (dlbar, ": ", sizeof(dlbar) - strlen (dlbar)); - i = strlen(dlbar); + strncpy (dlbar, text, sizeof (dlbar)); + strncat (dlbar, ": ", sizeof (dlbar) - strlen (dlbar)); + i = strlen (dlbar); dlbar[i++] = '\x80'; // where's the dot go? if (cls.downloadpercent == 0) n = 0; else n = y * cls.downloadpercent / 100; - + for (j = 0; j < y; j++) if (j == n) dlbar[i++] = '\x83'; @@ -640,16 +645,15 @@ void Con_DrawConsole (int lines) dlbar[i++] = '\x82'; dlbar[i] = 0; - snprintf(dlbar + strlen(dlbar), sizeof (dlbar) - strlen (dlbar), - " %02d%%", cls.downloadpercent); + snprintf (dlbar + strlen (dlbar), sizeof (dlbar) - strlen (dlbar), + " %02d%%", cls.downloadpercent); // draw it - y = con_vislines-22 + 8; - for (i = 0; i < strlen(dlbar); i++) - Draw_Character8 ( (i+1)<<3, y, dlbar[i]); + y = con_vislines - 22 + 8; + for (i = 0; i < strlen (dlbar); i++) + Draw_Character8 ((i + 1) << 3, y, dlbar[i]); } - // draw the input prompt, user text, and cursor if desired Con_DrawInput (); } diff --git a/source/context_x11.c b/source/context_x11.c index edc8b17..aa82708 100644 --- a/source/context_x11.c +++ b/source/context_x11.c @@ -29,7 +29,7 @@ $Id$ */ -#include +# include "config.h" #include #include @@ -68,19 +68,19 @@ #include "cvar.h" #include "input.h" -static void (*event_handlers[LASTEvent]) (XEvent *); -qboolean oktodraw = false; -int x_shmeventtype; +static void (*event_handlers[LASTEvent]) (XEvent *); +qboolean oktodraw = false; +int x_shmeventtype; -static int x_disp_ref_count = 0; +static int x_disp_ref_count = 0; -Display *x_disp = NULL; -int x_screen; -Window x_root = None; -XVisualInfo *x_visinfo; -Visual *x_vis; -Window x_win; -Cursor nullcursor = None; +Display *x_disp = NULL; +int x_screen; +Window x_root = None; +XVisualInfo *x_visinfo; +Visual *x_vis; +Window x_win; +Cursor nullcursor = None; static Atom aWMDelete = 0; #define X_MASK (VisibilityChangeMask | StructureNotifyMask | ExposureMask) @@ -89,21 +89,21 @@ static Atom aWMDelete = 0; static XF86VidModeModeInfo **vidmodes; static int nummodes; #endif -static int hasvidmode = 0; +static int hasvidmode = 0; -cvar_t *vid_fullscreen; -qboolean vid_fullscreen_active; +cvar_t *vid_fullscreen; +qboolean vid_fullscreen_active; -static int xss_timeout; -static int xss_interval; -static int xss_blanking; -static int xss_exposures; +static int xss_timeout; +static int xss_interval; +static int xss_blanking; +static int xss_exposures; qboolean x11_add_event (int event, void (*event_handler) (XEvent *)) { if (event >= LASTEvent) { - printf("event: %d, LASTEvent: %d\n", event, LASTEvent); + printf ("event: %d, LASTEvent: %d\n", event, LASTEvent); return false; } if (event_handlers[event] != NULL) @@ -128,10 +128,10 @@ x11_del_event (int event, void (*event_handler) (XEvent *)) void x11_process_event (void) { - XEvent x_event; + XEvent x_event; - XNextEvent(x_disp, &x_event); - if ( x_event.type >= LASTEvent ) { + XNextEvent (x_disp, &x_event); + if (x_event.type >= LASTEvent) { // FIXME: KLUGE!!!!!! if (x_event.type == x_shmeventtype) oktodraw = 1; @@ -160,39 +160,40 @@ TragicDeath (int sig) printf ("Received signal %d, exiting...\n", sig); Sys_Quit (); exit (sig); - //XCloseDisplay(x_disp); - //VID_Shutdown(); - //Sys_Error("This death brought to you by the number %d\n", signal_num); + // XCloseDisplay(x_disp); + // VID_Shutdown(); + // Sys_Error("This death brought to you by the number %d\n", signal_num); } void x11_open_display (void) { - if ( !x_disp ) { + if (!x_disp) { x_disp = XOpenDisplay (NULL); - if ( !x_disp ) { - Sys_Error ("x11_open_display: Could not open display [%s]\n", XDisplayName( NULL )); + if (!x_disp) { + Sys_Error ("x11_open_display: Could not open display [%s]\n", + XDisplayName (NULL)); } x_screen = DefaultScreen (x_disp); x_root = RootWindow (x_disp, x_screen); // catch signals - signal(SIGHUP, TragicDeath); - signal(SIGINT, TragicDeath); - signal(SIGQUIT, TragicDeath); - signal(SIGILL, TragicDeath); - signal(SIGTRAP, TragicDeath); - signal(SIGIOT, TragicDeath); - signal(SIGBUS, TragicDeath); - /* signal(SIGFPE, TragicDeath); */ - signal(SIGSEGV, TragicDeath); - signal(SIGTERM, TragicDeath); + signal (SIGHUP, TragicDeath); + signal (SIGINT, TragicDeath); + signal (SIGQUIT, TragicDeath); + signal (SIGILL, TragicDeath); + signal (SIGTRAP, TragicDeath); + signal (SIGIOT, TragicDeath); + signal (SIGBUS, TragicDeath); + /* signal(SIGFPE, TragicDeath); */ + signal (SIGSEGV, TragicDeath); + signal (SIGTERM, TragicDeath); // for debugging only - XSynchronize( x_disp, True ); + XSynchronize (x_disp, True); - x_disp_ref_count=1; + x_disp_ref_count = 1; } else { x_disp_ref_count++; } @@ -220,37 +221,38 @@ x11_close_display (void) void x11_create_null_cursor (void) { - Pixmap cursormask; - XGCValues xgc; - GC gc; - XColor dummycolour; + Pixmap cursormask; + XGCValues xgc; + GC gc; + XColor dummycolour; if (nullcursor != None) return; cursormask = XCreatePixmap (x_disp, x_root, 1, 1, 1); xgc.function = GXclear; - - gc = XCreateGC (x_disp, cursormask, GCFunction, &xgc); - + + gc = XCreateGC (x_disp, cursormask, GCFunction, &xgc); + XFillRectangle (x_disp, cursormask, gc, 0, 0, 1, 1); - + dummycolour.pixel = 0; dummycolour.red = 0; dummycolour.flags = 04; nullcursor = XCreatePixmapCursor (x_disp, cursormask, cursormask, - &dummycolour,&dummycolour, 0, 0); - XFreePixmap (x_disp,cursormask); - XFreeGC (x_disp,gc); + &dummycolour, &dummycolour, 0, 0); + XFreePixmap (x_disp, cursormask); + XFreeGC (x_disp, gc); XDefineCursor (x_disp, x_win, nullcursor); } void x11_set_vidmode (int width, int height) { - const char *str = getenv("MESA_GLX_FX"); + const char *str = getenv ("MESA_GLX_FX"); + if (str && *str != 'd') { - if (tolower(*str) == 'w') { + if (tolower (*str) == 'w') { Cvar_Set (vid_fullscreen, "0"); } else { Cvar_Set (vid_fullscreen, "1"); @@ -258,33 +260,32 @@ x11_set_vidmode (int width, int height) } XGetScreenSaver (x_disp, &xss_timeout, &xss_interval, &xss_blanking, - &xss_exposures); - XSetScreenSaver (x_disp, 0, xss_interval, xss_blanking, - xss_exposures); + &xss_exposures); + XSetScreenSaver (x_disp, 0, xss_interval, xss_blanking, xss_exposures); #ifdef HAVE_VIDMODE - if (!(hasvidmode = VID_CheckVMode(x_disp, NULL, NULL))) { + if (!(hasvidmode = VID_CheckVMode (x_disp, NULL, NULL))) { Cvar_Set (vid_fullscreen, "0"); return; } - XF86VidModeGetAllModeLines(x_disp, x_screen, &nummodes, &vidmodes); + XF86VidModeGetAllModeLines (x_disp, x_screen, &nummodes, &vidmodes); if (vid_fullscreen->int_val) { - int i; - int best_mode = 0, best_x = INT_MAX, best_y = INT_MAX; + int i; + int best_mode = 0, best_x = INT_MAX, best_y = INT_MAX; for (i = 0; i < nummodes; i++) { - if ((best_x > vidmodes[i]->hdisplay) || - (best_y > vidmodes[i]->vdisplay)) { - if ((vidmodes[i]->hdisplay >= width) && - (vidmodes[i]->vdisplay >= height)) { + if ((best_x > vidmodes[i]->hdisplay) || + (best_y > vidmodes[i]->vdisplay)) { + if ((vidmodes[i]->hdisplay >= width) && + (vidmodes[i]->vdisplay >= height)) { best_mode = i; best_x = vidmodes[i]->hdisplay; best_y = vidmodes[i]->vdisplay; } } - printf("%dx%d\n", vidmodes[i]->hdisplay, vidmodes[i]->vdisplay); + printf ("%dx%d\n", vidmodes[i]->hdisplay, vidmodes[i]->vdisplay); } XF86VidModeSwitchToMode (x_disp, x_screen, vidmodes[best_mode]); x11_force_view_port (); @@ -303,26 +304,26 @@ void x11_create_window (int width, int height) { XSetWindowAttributes attr; - XClassHint *ClassHint; - XSizeHints *SizeHints; - char *resname; - unsigned long mask; + XClassHint *ClassHint; + XSizeHints *SizeHints; + char *resname; + unsigned long mask; /* window attributes */ attr.background_pixel = 0; attr.border_pixel = 0; - attr.colormap = XCreateColormap(x_disp, x_root, x_vis, AllocNone); + attr.colormap = XCreateColormap (x_disp, x_root, x_vis, AllocNone); attr.event_mask = X_MASK; mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; if (hasvidmode && vid_fullscreen->int_val) { - attr.override_redirect=1; - mask|=CWOverrideRedirect; + attr.override_redirect = 1; + mask |= CWOverrideRedirect; } x_win = XCreateWindow (x_disp, x_root, 0, 0, width, height, - 0, x_visinfo->depth, InputOutput, - x_vis, mask, &attr); + 0, x_visinfo->depth, InputOutput, + x_vis, mask, &attr); // Set window size hints SizeHints = XAllocSizeHints (); @@ -336,7 +337,6 @@ x11_create_window (int width, int height) XFree (SizeHints); } - // Set window title x11_set_caption (va ("%s %s", PROGRAM, VERSION)); @@ -353,15 +353,14 @@ x11_create_window (int width, int height) XSetClassHint (x_disp, x_win, ClassHint); XFree (ClassHint); } - // Make window respond to Delete events aWMDelete = XInternAtom (x_disp, "WM_DELETE_WINDOW", False); XSetWMProtocols (x_disp, x_win, &aWMDelete, 1); - + if (vid_fullscreen->int_val) { XMoveWindow (x_disp, x_win, 0, 0); XWarpPointer (x_disp, None, x_win, 0, 0, 0, 0, - vid.width+2, vid.height+2); + vid.width + 2, vid.height + 2); x11_force_view_port (); } @@ -373,7 +372,7 @@ void x11_restore_vidmode (void) { XSetScreenSaver (x_disp, xss_timeout, xss_interval, xss_blanking, - xss_exposures); + xss_exposures); #ifdef HAVE_VIDMODE if (hasvidmode) { @@ -389,7 +388,7 @@ x11_grab_keyboard (void) #ifdef HAVE_VIDMODE if (hasvidmode && vid_fullscreen->int_val) { XGrabKeyboard (x_disp, x_win, 1, GrabModeAsync, GrabModeAsync, - CurrentTime); + CurrentTime); } #endif } @@ -405,7 +404,7 @@ void x11_force_view_port (void) { #ifdef HAVE_VIDMODE - int x, y; + int x, y; if (vid_fullscreen->int_val) { do { diff --git a/source/crc.c b/source/crc.c index d9a8431..978faa9 100644 --- a/source/crc.c +++ b/source/crc.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "crc.h" @@ -38,60 +38,63 @@ #define CRC_INIT_VALUE 0xffff #define CRC_XOR_VALUE 0x0000 -static unsigned short crctable[256] = -{ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 +static unsigned short crctable[256] = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; -void CRC_Init(unsigned short *crcvalue) +void +CRC_Init (unsigned short *crcvalue) { *crcvalue = CRC_INIT_VALUE; } -void CRC_ProcessByte(unsigned short *crcvalue, byte data) +void +CRC_ProcessByte (unsigned short *crcvalue, byte data) { *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data]; } -unsigned short CRC_Value(unsigned short crcvalue) +unsigned short +CRC_Value (unsigned short crcvalue) { return crcvalue ^ CRC_XOR_VALUE; } -unsigned short CRC_Block (byte *start, int count) +unsigned short +CRC_Block (byte * start, int count) { - unsigned short crc; + unsigned short crc; CRC_Init (&crc); while (count--) @@ -99,4 +102,3 @@ unsigned short CRC_Block (byte *start, int count) return crc; } - diff --git a/source/cvar.c b/source/cvar.c index 7d5fb0a..98e8533 100644 --- a/source/cvar.c +++ b/source/cvar.c @@ -30,7 +30,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "commdef.h" @@ -47,9 +47,9 @@ #include #endif -cvar_t *cvar_vars; -char *cvar_null_string = ""; -extern cvar_t *developer; +cvar_t *cvar_vars; +char *cvar_null_string = ""; +extern cvar_t *developer; cvar_alias_t *calias_vars; /* @@ -57,49 +57,50 @@ cvar_alias_t *calias_vars; Cvar_FindVar ============ */ -cvar_t *Cvar_FindVar (char *var_name) +cvar_t * +Cvar_FindVar (char *var_name) { - cvar_t *var; + cvar_t *var; - for (var=cvar_vars ; var ; var=var->next) + for (var = cvar_vars; var; var = var->next) if (!strcmp (var_name, var->name)) return var; return NULL; } -cvar_t *Cvar_FindAlias (char *alias_name) +cvar_t * +Cvar_FindAlias (char *alias_name) { - cvar_alias_t *alias; + cvar_alias_t *alias; - for (alias = calias_vars ; alias ; alias=alias->next) + for (alias = calias_vars; alias; alias = alias->next) if (!strcmp (alias_name, alias->name)) return alias->cvar; return NULL; } -void Cvar_Alias_Get (char *name, cvar_t *cvar) +void +Cvar_Alias_Get (char *name, cvar_t *cvar) { - cvar_alias_t *alias; - cvar_t *var; + cvar_alias_t *alias; + cvar_t *var; - if (Cmd_Exists (name)) - { + if (Cmd_Exists (name)) { Con_Printf ("CAlias_Get: %s is a command\n", name); return; } - if (Cvar_FindVar(name)) - { - Con_Printf ("CAlias_Get: tried to alias used cvar name %s\n",name); + if (Cvar_FindVar (name)) { + Con_Printf ("CAlias_Get: tried to alias used cvar name %s\n", name); return; } - var = Cvar_FindAlias(name); - if (!var) - { - alias = (cvar_alias_t *) calloc(1, sizeof(cvar_alias_t)); + var = Cvar_FindAlias (name); + if (!var) { + alias = (cvar_alias_t *) calloc (1, sizeof (cvar_alias_t)); + alias->next = calias_vars; calias_vars = alias; - alias->name = strdup(name); + alias->name = strdup (name); alias->cvar = cvar; } } @@ -109,13 +110,14 @@ void Cvar_Alias_Get (char *name, cvar_t *cvar) Cvar_VariableValue ============ */ -float Cvar_VariableValue (char *var_name) +float +Cvar_VariableValue (char *var_name) { - cvar_t *var; + cvar_t *var; var = Cvar_FindVar (var_name); if (!var) - var = Cvar_FindAlias(var_name); + var = Cvar_FindAlias (var_name); if (!var) return 0; return atof (var->string); @@ -127,13 +129,14 @@ float Cvar_VariableValue (char *var_name) Cvar_VariableString ============ */ -char *Cvar_VariableString (char *var_name) +char * +Cvar_VariableString (char *var_name) { - cvar_t *var; + cvar_t *var; var = Cvar_FindVar (var_name); if (!var) - var = Cvar_FindAlias(var_name); + var = Cvar_FindAlias (var_name); if (!var) return cvar_null_string; return var->string; @@ -145,34 +148,35 @@ char *Cvar_VariableString (char *var_name) Cvar_CompleteVariable ============ */ -char *Cvar_CompleteVariable (char *partial) +char * +Cvar_CompleteVariable (char *partial) { - cvar_t *cvar; - cvar_alias_t *alias; - int len; + cvar_t *cvar; + cvar_alias_t *alias; + int len; - len = strlen(partial); + len = strlen (partial); if (!len) return NULL; // check exact match - for (cvar=cvar_vars ; cvar ; cvar=cvar->next) - if (!strcasecmp (partial,cvar->name)) + for (cvar = cvar_vars; cvar; cvar = cvar->next) + if (!strcasecmp (partial, cvar->name)) return cvar->name; - + // check aliases too :) - for (alias=calias_vars ; alias ; alias=alias->next) + for (alias = calias_vars; alias; alias = alias->next) if (!strcasecmp (partial, alias->name)) return alias->name; // check partial match - for (cvar=cvar_vars ; cvar ; cvar=cvar->next) - if (!strncasecmp (partial,cvar->name, len)) + for (cvar = cvar_vars; cvar; cvar = cvar->next) + if (!strncasecmp (partial, cvar->name, len)) return cvar->name; // check aliases too :) - for (alias=calias_vars ; alias ; alias=alias->next) + for (alias = calias_vars; alias; alias = alias->next) if (!strncasecmp (partial, alias->name, len)) return alias->name; @@ -180,7 +184,7 @@ char *Cvar_CompleteVariable (char *partial) } -void Cvar_Info (cvar_t *var); +void Cvar_Info (cvar_t *var); /* ============ @@ -193,12 +197,12 @@ Cvar_Set (cvar_t *var, char *value) if (!var) return; - if(var->flags & CVAR_ROM) { + if (var->flags & CVAR_ROM) { Con_DPrintf ("Cvar \"%s\" is read-only, cannot modify\n", var->name); return; } - free (var->string); // free the old value string + free (var->string); // free the old value string var->string = malloc (strlen (value) + 1); strcpy (var->string, value); @@ -220,14 +224,14 @@ Cvar_SetROM (cvar_t *var, char *value) if (!var) return; - free (var->string); // free the old value string + free (var->string); // free the old value string - var->string = malloc (strlen(value)+1); + var->string = malloc (strlen (value) + 1); strcpy (var->string, value); var->value = atof (var->string); var->int_val = atoi (var->string); - Cvar_Info(var); + Cvar_Info (var); } /* @@ -236,14 +240,14 @@ Cvar_SetValue ============ */ // 1999-09-07 weird cvar zeros fix by Maddes -void Cvar_SetValue (cvar_t *var, float value) +void +Cvar_SetValue (cvar_t *var, float value) { - char val[32]; - int i; + char val[32]; + int i; - snprintf (val, sizeof(val), "%f", value); - for (i=strlen(val)-1 ; i>0 && val[i]=='0' && val[i-1]!='.' ; i--) - { + snprintf (val, sizeof (val), "%f", value); + for (i = strlen (val) - 1; i > 0 && val[i] == '0' && val[i - 1] != '.'; i--) { val[i] = 0; } Cvar_Set (var, val); @@ -259,22 +263,22 @@ Handles variable inspection and changing from the console qboolean Cvar_Command (void) { - cvar_t *v; + cvar_t *v; // check variables - v = Cvar_FindVar (Cmd_Argv(0)); + v = Cvar_FindVar (Cmd_Argv (0)); if (!v) - v = Cvar_FindAlias (Cmd_Argv(0)); + v = Cvar_FindAlias (Cmd_Argv (0)); if (!v) return false; // perform a variable print or set - if (Cmd_Argc() == 1) { + if (Cmd_Argc () == 1) { Con_Printf ("\"%s\" is \"%s\"\n", v->name, v->string); return true; } - Cvar_Set (v, Cmd_Argv(1)); + Cvar_Set (v, Cmd_Argv (1)); return true; } @@ -287,23 +291,24 @@ Writes lines containing "set variable value" for all variables with the archive flag set to true. ============ */ -void Cvar_WriteVariables (QFile *f) +void +Cvar_WriteVariables (QFile *f) { - cvar_t *var; + cvar_t *var; - for (var = cvar_vars ; var ; var = var->next) - if (var->flags&CVAR_ARCHIVE) + for (var = cvar_vars; var; var = var->next) + if (var->flags & CVAR_ARCHIVE) Qprintf (f, "%s \"%s\"\n", var->name, var->string); } void Cvar_Set_f (void) { - cvar_t *var; - char *value; - char *var_name; + cvar_t *var; + char *value; + char *var_name; - if (Cmd_Argc() != 3) { + if (Cmd_Argc () != 3) { Con_Printf ("usage: set \n"); return; } @@ -322,18 +327,18 @@ Cvar_Set_f (void) } } else { var = Cvar_Get (var_name, value, CVAR_USER_CREATED, - "User-created cvar"); + "User-created cvar"); } } void Cvar_Setrom_f (void) { - cvar_t *var; - char *value; - char *var_name; + cvar_t *var; + char *value; + char *var_name; - if (Cmd_Argc() != 3) { + if (Cmd_Argc () != 3) { Con_Printf ("usage: setrom \n"); return; } @@ -351,40 +356,39 @@ Cvar_Setrom_f (void) Cvar_Set (var, value); } } else { - var = Cvar_Get (var_name, value, CVAR_USER_CREATED|CVAR_ROM, - "User-created READ-ONLY Cvar"); + var = Cvar_Get (var_name, value, CVAR_USER_CREATED | CVAR_ROM, + "User-created READ-ONLY Cvar"); } } -void Cvar_Toggle_f (void) +void +Cvar_Toggle_f (void) { - cvar_t *var; + cvar_t *var; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("toggle : toggle a cvar on/off\n"); return; } - var = Cvar_FindVar (Cmd_Argv(1)); + var = Cvar_FindVar (Cmd_Argv (1)); if (!var) - var = Cvar_FindAlias(Cmd_Argv(1)); - if (!var) - { - Con_Printf ("Unknown variable \"%s\"\n", Cmd_Argv(1)); + var = Cvar_FindAlias (Cmd_Argv (1)); + if (!var) { + Con_Printf ("Unknown variable \"%s\"\n", Cmd_Argv (1)); return; } Cvar_Set (var, var->int_val ? "0" : "1"); } -void Cvar_Help_f (void) +void +Cvar_Help_f (void) { - char *var_name; - cvar_t *var; + char *var_name; + cvar_t *var; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("usage: help \n"); return; } @@ -393,87 +397,86 @@ void Cvar_Help_f (void) var = Cvar_FindVar (var_name); if (!var) var = Cvar_FindAlias (var_name); - if (var) - { - Con_Printf ("%s\n",var->description); + if (var) { + Con_Printf ("%s\n", var->description); return; } Con_Printf ("variable not found\n"); } -void Cvar_CvarList_f (void) +void +Cvar_CvarList_f (void) { - cvar_t *var; - int i; + cvar_t *var; + int i; - for (var=cvar_vars, i=0 ; var ; var=var->next, i++) - Con_Printf("%c%c%c %s\n", - var->flags & CVAR_ARCHIVE ? '*' : ' ', - var->flags & CVAR_USERINFO ? 'u' : ' ', - var->flags & CVAR_SERVERINFO ? 's' : ' ', - var->name); + for (var = cvar_vars, i = 0; var; var = var->next, i++) + Con_Printf ("%c%c%c %s\n", + var->flags & CVAR_ARCHIVE ? '*' : ' ', + var->flags & CVAR_USERINFO ? 'u' : ' ', + var->flags & CVAR_SERVERINFO ? 's' : ' ', var->name); Con_Printf ("------------\n%d variables\n", i); } -void Cvar_Init() +void +Cvar_Init () { developer = Cvar_Get ("developer", "0", 0, "None"); Cmd_AddCommand ("set", Cvar_Set_f); Cmd_AddCommand ("setrom", Cvar_Setrom_f); Cmd_AddCommand ("toggle", Cvar_Toggle_f); - Cmd_AddCommand ("help",Cvar_Help_f); - Cmd_AddCommand ("cvarlist",Cvar_CvarList_f); + Cmd_AddCommand ("help", Cvar_Help_f); + Cmd_AddCommand ("cvarlist", Cvar_CvarList_f); } -void Cvar_Shutdown (void) +void +Cvar_Shutdown (void) { - cvar_t *var,*next; - cvar_alias_t *alias,*nextalias; + cvar_t *var, *next; + cvar_alias_t *alias, *nextalias; // Free cvars var = cvar_vars; - while(var) - { + while (var) { next = var->next; - free(var->string); - free(var->name); - free(var); + free (var->string); + free (var->name); + free (var); var = next; } // Free aliases alias = calias_vars; - while(alias) - { + while (alias) { nextalias = alias->next; - free(alias->name); - free(alias); + free (alias->name); + free (alias); alias = nextalias; } } -cvar_t *Cvar_Get(char *name, char *string, int cvarflags, char *description) +cvar_t * +Cvar_Get (char *name, char *string, int cvarflags, char *description) { - cvar_t *v; + cvar_t *v; - if (Cmd_Exists (name)) - { - Con_Printf ("Cvar_Get: %s is a command\n",name); + if (Cmd_Exists (name)) { + Con_Printf ("Cvar_Get: %s is a command\n", name); return NULL; } - v = Cvar_FindVar(name); - if (!v) - { - v = (cvar_t *) calloc(1, sizeof(cvar_t)); + v = Cvar_FindVar (name); + if (!v) { + v = (cvar_t *) calloc (1, sizeof (cvar_t)); + // Cvar doesn't exist, so we create it v->next = cvar_vars; cvar_vars = v; - v->name = strdup(name); - v->string = malloc (strlen(string)+1); + v->name = strdup (name); + v->string = malloc (strlen (string) + 1); strcpy (v->string, string); v->flags = cvarflags; v->description = description; @@ -502,4 +505,3 @@ Cvar_SetFlags (cvar_t *var, int cvarflags) var->flags = cvarflags; } - diff --git a/source/d_edge.c b/source/d_edge.c index 7159824..b2b9668 100644 --- a/source/d_edge.c +++ b/source/d_edge.c @@ -27,22 +27,22 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "d_local.h" -static int miplevel; +static int miplevel; -float scale_for_mip; -extern int screenwidth; -int ubasestep, errorterm, erroradjustup, erroradjustdown; -int vstartscan; +float scale_for_mip; +extern int screenwidth; +int ubasestep, errorterm, erroradjustup, erroradjustdown; +int vstartscan; // FIXME: should go away -extern void R_RotateBmodel (void); -extern void R_TransformFrustum (void); +extern void R_RotateBmodel (void); +extern void R_TransformFrustum (void); -vec3_t transformed_modelorg; +vec3_t transformed_modelorg; /* ============== @@ -50,7 +50,8 @@ D_DrawPoly ============== */ -void D_DrawPoly (void) +void +D_DrawPoly (void) { // this driver takes spans, not polygons } @@ -61,15 +62,16 @@ void D_DrawPoly (void) D_MipLevelForScale ============= */ -int D_MipLevelForScale (float scale) +int +D_MipLevelForScale (float scale) { - int lmiplevel; + int lmiplevel; - if (scale >= d_scalemip[0] ) + if (scale >= d_scalemip[0]) lmiplevel = 0; - else if (scale >= d_scalemip[1] ) + else if (scale >= d_scalemip[1]) lmiplevel = 1; - else if (scale >= d_scalemip[2] ) + else if (scale >= d_scalemip[2]) lmiplevel = 2; else lmiplevel = 3; @@ -89,36 +91,33 @@ D_DrawSolidSurface // FIXME: clean this up -void D_DrawSolidSurface (surf_t *surf, int color) +void +D_DrawSolidSurface (surf_t *surf, int color) { - espan_t *span; - byte *pdest; - int u, u2, pix; - - pix = (color<<24) | (color<<16) | (color<<8) | color; - for (span=surf->spans ; span ; span=span->pnext) - { - pdest = (byte *)d_viewbuffer + screenwidth*span->v; + espan_t *span; + byte *pdest; + int u, u2, pix; + + pix = (color << 24) | (color << 16) | (color << 8) | color; + for (span = surf->spans; span; span = span->pnext) { + pdest = (byte *) d_viewbuffer + screenwidth * span->v; u = span->u; u2 = span->u + span->count - 1; - ((byte *)pdest)[u] = pix; + ((byte *) pdest)[u] = pix; - if (u2 - u < 8) - { - for (u++ ; u <= u2 ; u++) - ((byte *)pdest)[u] = pix; - } - else - { - for (u++ ; u & 3 ; u++) - ((byte *)pdest)[u] = pix; + if (u2 - u < 8) { + for (u++; u <= u2; u++) + ((byte *) pdest)[u] = pix; + } else { + for (u++; u & 3; u++) + ((byte *) pdest)[u] = pix; u2 -= 4; - for ( ; u <= u2 ; u+=4) - *(int *)((byte *)pdest + u) = pix; + for (; u <= u2; u += 4) + *(int *) ((byte *) pdest + u) = pix; u2 += 4; - for ( ; u <= u2 ; u++) - ((byte *)pdest)[u] = pix; + for (; u <= u2; u++) + ((byte *) pdest)[u] = pix; } } } @@ -129,17 +128,18 @@ void D_DrawSolidSurface (surf_t *surf, int color) D_CalcGradients ============== */ -void D_CalcGradients (msurface_t *pface) +void +D_CalcGradients (msurface_t *pface) { - mplane_t *pplane; - float mipscale; - vec3_t p_temp1; - vec3_t p_saxis, p_taxis; - float t; + mplane_t *pplane; + float mipscale; + vec3_t p_temp1; + vec3_t p_saxis, p_taxis; + float t; pplane = pface->plane; - mipscale = 1.0 / (float)(1 << miplevel); + mipscale = 1.0 / (float) (1 << miplevel); TransformVector (pface->texinfo->vecs[0], p_saxis); TransformVector (pface->texinfo->vecs[1], p_taxis); @@ -153,19 +153,19 @@ void D_CalcGradients (msurface_t *pface) d_tdivzstepv = -p_taxis[1] * t; d_sdivzorigin = p_saxis[2] * mipscale - xcenter * d_sdivzstepu - - ycenter * d_sdivzstepv; + ycenter * d_sdivzstepv; d_tdivzorigin = p_taxis[2] * mipscale - xcenter * d_tdivzstepu - - ycenter * d_tdivzstepv; + ycenter * d_tdivzstepv; VectorScale (transformed_modelorg, mipscale, p_temp1); - t = 0x10000*mipscale; - sadjust = ((fixed16_t)(DotProduct (p_temp1, p_saxis) * 0x10000 + 0.5)) - - ((pface->texturemins[0] << 16) >> miplevel) - + pface->texinfo->vecs[0][3]*t; - tadjust = ((fixed16_t)(DotProduct (p_temp1, p_taxis) * 0x10000 + 0.5)) - - ((pface->texturemins[1] << 16) >> miplevel) - + pface->texinfo->vecs[1][3]*t; + t = 0x10000 * mipscale; + sadjust = ((fixed16_t) (DotProduct (p_temp1, p_saxis) * 0x10000 + 0.5)) - + ((pface->texturemins[0] << 16) >> miplevel) + + pface->texinfo->vecs[0][3] * t; + tadjust = ((fixed16_t) (DotProduct (p_temp1, p_taxis) * 0x10000 + 0.5)) - + ((pface->texturemins[1] << 16) >> miplevel) + + pface->texinfo->vecs[1][3] * t; // // -1 (-epsilon) so we never wander off the edge of the texture @@ -180,23 +180,22 @@ void D_CalcGradients (msurface_t *pface) D_DrawSurfaces ============== */ -void D_DrawSurfaces (void) +void +D_DrawSurfaces (void) { - surf_t *s; - msurface_t *pface; - surfcache_t *pcurrentcache; - vec3_t world_transformed_modelorg; - vec3_t local_modelorg; + surf_t *s; + msurface_t *pface; + surfcache_t *pcurrentcache; + vec3_t world_transformed_modelorg; + vec3_t local_modelorg; currententity = &r_worldentity; TransformVector (modelorg, transformed_modelorg); VectorCopy (transformed_modelorg, world_transformed_modelorg); // TODO: could preset a lot of this at mode set time - if (r_drawflat->int_val) - { - for (s = &surfaces[1] ; sint_val) { + for (s = &surfaces[1]; s < surface_p; s++) { if (!s->spans) continue; @@ -204,14 +203,11 @@ void D_DrawSurfaces (void) d_zistepv = s->d_zistepv; d_ziorigin = s->d_ziorigin; - D_DrawSolidSurface (s, (int)((long)s->data & 0xFF)); + D_DrawSolidSurface (s, (int) ((long) s->data & 0xFF)); D_DrawZSpans (s->spans); } - } - else - { - for (s = &surfaces[1] ; sspans) continue; @@ -221,48 +217,44 @@ void D_DrawSurfaces (void) d_zistepv = s->d_zistepv; d_ziorigin = s->d_ziorigin; - if (s->flags & SURF_DRAWSKY) - { - if (!r_skymade) - { + if (s->flags & SURF_DRAWSKY) { + if (!r_skymade) { R_MakeSky (); } D_DrawSkyScans8 (s->spans); D_DrawZSpans (s->spans); - } - else if (s->flags & SURF_DRAWBACKGROUND) - { - // set up a gradient for the background surface that places it - // effectively at infinity distance from the viewpoint + } else if (s->flags & SURF_DRAWBACKGROUND) { + // set up a gradient for the background surface that places + // it + // effectively at infinity distance from the viewpoint d_zistepu = 0; d_zistepv = 0; d_ziorigin = -0.9; D_DrawSolidSurface (s, r_clearcolor->int_val & 0xFF); D_DrawZSpans (s->spans); - } - else if (s->flags & SURF_DRAWTURB) - { + } else if (s->flags & SURF_DRAWTURB) { pface = s->data; miplevel = 0; cacheblock = (pixel_t *) - ((byte *)pface->texinfo->texture + - pface->texinfo->texture->offsets[0]); + ((byte *) pface->texinfo->texture + + pface->texinfo->texture->offsets[0]); cachewidth = 64; - if (s->insubmodel) - { - // FIXME: we don't want to do all this for every polygon! - // TODO: store once at start of frame - currententity = s->entity; //FIXME: make this passed in to - // R_RotateBmodel () + if (s->insubmodel) { + // FIXME: we don't want to do all this for every polygon! + // TODO: store once at start of frame + currententity = s->entity; // FIXME: make this passed in + // to + // R_RotateBmodel () VectorSubtract (r_origin, currententity->origin, - local_modelorg); + local_modelorg); TransformVector (local_modelorg, transformed_modelorg); - R_RotateBmodel (); // FIXME: don't mess with the frustum, - // make entity passed in + R_RotateBmodel (); // FIXME: don't mess with the + // frustum, + // make entity passed in } D_CalcGradients (pface); @@ -270,13 +262,12 @@ void D_DrawSurfaces (void) Turbulent8 (s->spans); D_DrawZSpans (s->spans); - if (s->insubmodel) - { - // - // restore the old drawing state - // FIXME: we don't want to do this every time! - // TODO: speed up - // + if (s->insubmodel) { + // + // restore the old drawing state + // FIXME: we don't want to do this every time! + // TODO: speed up + // currententity = &r_worldentity; VectorCopy (world_transformed_modelorg, transformed_modelorg); @@ -286,30 +277,30 @@ void D_DrawSurfaces (void) VectorCopy (base_modelorg, modelorg); R_TransformFrustum (); } - } - else - { - if (s->insubmodel) - { - // FIXME: we don't want to do all this for every polygon! - // TODO: store once at start of frame - currententity = s->entity; //FIXME: make this passed in to - // R_RotateBmodel () - VectorSubtract (r_origin, currententity->origin, local_modelorg); + } else { + if (s->insubmodel) { + // FIXME: we don't want to do all this for every polygon! + // TODO: store once at start of frame + currententity = s->entity; // FIXME: make this passed in + // to + // R_RotateBmodel () + VectorSubtract (r_origin, currententity->origin, + local_modelorg); TransformVector (local_modelorg, transformed_modelorg); - R_RotateBmodel (); // FIXME: don't mess with the frustum, - // make entity passed in + R_RotateBmodel (); // FIXME: don't mess with the + // frustum, + // make entity passed in } pface = s->data; miplevel = D_MipLevelForScale (s->nearzi * scale_for_mip - * pface->texinfo->mipadjust); + * pface->texinfo->mipadjust); - // FIXME: make this passed in to D_CacheSurface + // FIXME: make this passed in to D_CacheSurface pcurrentcache = D_CacheSurface (pface, miplevel); - cacheblock = (pixel_t *)pcurrentcache->data; + cacheblock = (pixel_t *) pcurrentcache->data; cachewidth = pcurrentcache->width; D_CalcGradients (pface); @@ -318,13 +309,12 @@ void D_DrawSurfaces (void) D_DrawZSpans (s->spans); - if (s->insubmodel) - { - // - // restore the old drawing state - // FIXME: we don't want to do this every time! - // TODO: speed up - // + if (s->insubmodel) { + // + // restore the old drawing state + // FIXME: we don't want to do this every time! + // TODO: speed up + // VectorCopy (world_transformed_modelorg, transformed_modelorg); VectorCopy (base_vpn, vpn); @@ -338,4 +328,3 @@ void D_DrawSurfaces (void) } } } - diff --git a/source/d_fill.c b/source/d_fill.c index cc1e69c..5d34dd8 100644 --- a/source/d_fill.c +++ b/source/d_fill.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "d_iface.h" @@ -37,62 +37,55 @@ D_FillRect ================ */ -void D_FillRect (vrect_t *rect, int color) +void +D_FillRect (vrect_t *rect, int color) { - int rx, ry, rwidth, rheight; - unsigned char *dest; - unsigned int *ldest; + int rx, ry, rwidth, rheight; + unsigned char *dest; + unsigned int *ldest; rx = rect->x; ry = rect->y; rwidth = rect->width; rheight = rect->height; - if (rx < 0) - { + if (rx < 0) { rwidth += rx; rx = 0; } - if (ry < 0) - { + if (ry < 0) { rheight += ry; ry = 0; } - if (rx+rwidth > vid.width) + if (rx + rwidth > vid.width) rwidth = vid.width - rx; - if (ry+rheight > vid.height) + if (ry + rheight > vid.height) rheight = vid.height - rx; - + if (rwidth < 1 || rheight < 1) return; - dest = ((byte *)vid.buffer + ry*vid.rowbytes + rx); + dest = ((byte *) vid.buffer + ry * vid.rowbytes + rx); - if (((rwidth & 0x03) == 0) && (((long)dest & 0x03) == 0)) - { - // faster aligned dword clear - ldest = (unsigned int *)dest; + if (((rwidth & 0x03) == 0) && (((long) dest & 0x03) == 0)) { + // faster aligned dword clear + ldest = (unsigned int *) dest; color += color << 16; rwidth >>= 2; color += color << 8; - for (ry=0 ; ry +# include "config.h" #endif #include "bothdefs.h" #include "d_local.h" #define NUM_MIPS 4 -cvar_t *d_subdiv16; -cvar_t *d_mipcap; -cvar_t *d_mipscale; +cvar_t *d_subdiv16; +cvar_t *d_mipcap; +cvar_t *d_mipscale; -surfcache_t *d_initial_rover; -qboolean d_roverwrapped; -int d_minmip; -float d_scalemip[NUM_MIPS-1]; +surfcache_t *d_initial_rover; +qboolean d_roverwrapped; +int d_minmip; +float d_scalemip[NUM_MIPS - 1]; -static float basemip[NUM_MIPS-1] = {1.0, 0.5*0.8, 0.25*0.8}; +static float basemip[NUM_MIPS - 1] = { 1.0, 0.5 * 0.8, 0.25 * 0.8 }; -extern int d_aflatcolor; +extern int d_aflatcolor; -void (*d_drawspans) (espan_t *pspan); +void (*d_drawspans) (espan_t *pspan); /* @@ -55,7 +55,8 @@ void (*d_drawspans) (espan_t *pspan); D_Init =============== */ -void D_Init (void) +void +D_Init (void) { r_skydirect = 1; @@ -66,11 +67,12 @@ void D_Init (void) r_aliasuvscale = 1.0; } -void D_Init_Cvars (void) +void +D_Init_Cvars (void) { - d_subdiv16 = Cvar_Get("d_subdiv16", "1", CVAR_NONE, "None"); - d_mipcap = Cvar_Get("d_mipcap", "0", CVAR_NONE, "None"); - d_mipscale = Cvar_Get("d_mipscale", "1", CVAR_NONE, "None"); + d_subdiv16 = Cvar_Get ("d_subdiv16", "1", CVAR_NONE, "None"); + d_mipcap = Cvar_Get ("d_mipcap", "0", CVAR_NONE, "None"); + d_mipscale = Cvar_Get ("d_mipscale", "1", CVAR_NONE, "None"); } /* @@ -78,7 +80,8 @@ void D_Init_Cvars (void) D_CopyRects =============== */ -void D_CopyRects (vrect_t *prects, int transparent) +void +D_CopyRects (vrect_t *prects, int transparent) { // this function is only required if the CPU doesn't have direct access to the @@ -87,8 +90,8 @@ void D_CopyRects (vrect_t *prects, int transparent) // console); Quake will then draw into wherever the driver points vid.buffer // and will call this function before swapping buffers - UNUSED(prects); - UNUSED(transparent); + UNUSED (prects); + UNUSED (transparent); } @@ -97,7 +100,8 @@ void D_CopyRects (vrect_t *prects, int transparent) D_EnableBackBufferAccess =============== */ -void D_EnableBackBufferAccess (void) +void +D_EnableBackBufferAccess (void) { VID_LockBuffer (); @@ -109,7 +113,8 @@ void D_EnableBackBufferAccess (void) D_TurnZOn =============== */ -void D_TurnZOn (void) +void +D_TurnZOn (void) { // not needed for software version } @@ -120,7 +125,8 @@ void D_TurnZOn (void) D_DisableBackBufferAccess =============== */ -void D_DisableBackBufferAccess (void) +void +D_DisableBackBufferAccess (void) { VID_UnlockBuffer (); } @@ -131,14 +137,15 @@ void D_DisableBackBufferAccess (void) D_SetupFrame =============== */ -void D_SetupFrame (void) +void +D_SetupFrame (void) { - int i; + int i; if (r_dowarp) d_viewbuffer = r_warpbuffer; else - d_viewbuffer = (void *)(byte *)vid.buffer; + d_viewbuffer = (void *) (byte *) vid.buffer; if (r_dowarp) screenwidth = WARP_WIDTH; @@ -148,18 +155,18 @@ void D_SetupFrame (void) d_roverwrapped = false; d_initial_rover = sc_rover; - d_minmip = bound(0, d_mipcap->value, 3); + d_minmip = bound (0, d_mipcap->value, 3); - for (i=0 ; i<(NUM_MIPS-1) ; i++) + for (i = 0; i < (NUM_MIPS - 1); i++) d_scalemip[i] = basemip[i] * d_mipscale->value; #ifdef USE_INTEL_ASM - if (d_subdiv16->int_val) - d_drawspans = D_DrawSpans16; - else - d_drawspans = D_DrawSpans8; + if (d_subdiv16->int_val) + d_drawspans = D_DrawSpans16; + else + d_drawspans = D_DrawSpans8; #else - d_drawspans = D_DrawSpans8; + d_drawspans = D_DrawSpans8; #endif d_aflatcolor = 0; @@ -171,11 +178,11 @@ void D_SetupFrame (void) D_UpdateRects =============== */ -void D_UpdateRects (vrect_t *prect) +void +D_UpdateRects (vrect_t *prect) { // the software driver draws these directly to the vid buffer - UNUSED(prect); + UNUSED (prect); } - diff --git a/source/d_modech.c b/source/d_modech.c index 4c69f13..c6d30ad 100644 --- a/source/d_modech.c +++ b/source/d_modech.c @@ -27,37 +27,37 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "d_local.h" -int d_vrectx, d_vrecty, d_vrectright_particle, d_vrectbottom_particle; +int d_vrectx, d_vrecty, d_vrectright_particle, d_vrectbottom_particle; -int d_y_aspect_shift, d_pix_min, d_pix_max, d_pix_shift; +int d_y_aspect_shift, d_pix_min, d_pix_max, d_pix_shift; -int d_scantable[MAXHEIGHT]; -short *zspantable[MAXHEIGHT]; +int d_scantable[MAXHEIGHT]; +short *zspantable[MAXHEIGHT]; /* ================ D_Patch ================ */ -void D_Patch (void) +void +D_Patch (void) { #ifdef USE_INTEL_ASM static qboolean protectset8 = false; - if (!protectset8) - { - Sys_MakeCodeWriteable ((int)D_PolysetAff8Start, - (int)D_PolysetAff8End - (int)D_PolysetAff8Start); + if (!protectset8) { + Sys_MakeCodeWriteable ((int) D_PolysetAff8Start, + (int) D_PolysetAff8End - + (int) D_PolysetAff8Start); protectset8 = true; } - -#endif // USE_INTEL_ASM +#endif // USE_INTEL_ASM } @@ -66,9 +66,10 @@ void D_Patch (void) D_ViewChanged ================ */ -void D_ViewChanged (void) +void +D_ViewChanged (void) { - int rowbytes; + int rowbytes; if (r_dowarp) rowbytes = WARP_WIDTH; @@ -86,8 +87,8 @@ void D_ViewChanged (void) if (d_pix_min < 1) d_pix_min = 1; - d_pix_max = (int)((float)r_refdef.vrect.width / (320.0 / 4.0) + 0.5); - d_pix_shift = 8 - (int)((float)r_refdef.vrect.width / 320.0 + 0.5); + d_pix_max = (int) ((float) r_refdef.vrect.width / (320.0 / 4.0) + 0.5); + d_pix_shift = 8 - (int) ((float) r_refdef.vrect.width / 320.0 + 0.5); if (d_pix_max < 1) d_pix_max = 1; @@ -100,18 +101,16 @@ void D_ViewChanged (void) d_vrecty = r_refdef.vrect.y; d_vrectright_particle = r_refdef.vrectright - d_pix_max; d_vrectbottom_particle = - r_refdef.vrectbottom - (d_pix_max << d_y_aspect_shift); + r_refdef.vrectbottom - (d_pix_max << d_y_aspect_shift); { - int i; + int i; - for (i=0 ; i +# include "config.h" #endif #include "d_local.h" @@ -37,7 +37,8 @@ D_EndParticles ============== */ -void D_EndParticles (void) +void +D_EndParticles (void) { // not used by software driver } @@ -48,7 +49,8 @@ void D_EndParticles (void) D_StartParticles ============== */ -void D_StartParticles (void) +void +D_StartParticles (void) { // not used by software driver } @@ -61,20 +63,21 @@ void D_StartParticles (void) D_DrawParticle ============== */ -void D_DrawParticle (particle_t *pparticle) +void +D_DrawParticle (particle_t *pparticle) { - vec3_t local, transformed; - float zi; - byte *pdest; - short *pz; - int i, izi, pix, count, u, v; + vec3_t local, transformed; + float zi; + byte *pdest; + short *pz; + int i, izi, pix, count, u, v; // transform point VectorSubtract (pparticle->org, r_origin, local); - transformed[0] = DotProduct(local, r_pright); - transformed[1] = DotProduct(local, r_pup); - transformed[2] = DotProduct(local, r_ppn); + transformed[0] = DotProduct (local, r_pright); + transformed[1] = DotProduct (local, r_pup); + transformed[2] = DotProduct (local, r_ppn); if (transformed[2] < PARTICLE_Z_CLIP) return; @@ -82,20 +85,17 @@ void D_DrawParticle (particle_t *pparticle) // project the point // FIXME: preadjust xcenter and ycenter zi = 1.0 / transformed[2]; - u = (int)(xcenter + zi * transformed[0] + 0.5); - v = (int)(ycenter - zi * transformed[1] + 0.5); + u = (int) (xcenter + zi * transformed[0] + 0.5); + v = (int) (ycenter - zi * transformed[1] + 0.5); - if ((v > d_vrectbottom_particle) || - (u > d_vrectright_particle) || - (v < d_vrecty) || - (u < d_vrectx)) - { + if ((v > d_vrectbottom_particle) || + (u > d_vrectright_particle) || (v < d_vrecty) || (u < d_vrectx)) { return; } pz = d_pzbuffer + (d_zwidth * v) + u; pdest = d_viewbuffer + d_scantable[v] + u; - izi = (int)(zi * 0x8000); + izi = (int) (zi * 0x8000); pix = izi >> d_pix_shift; @@ -104,113 +104,94 @@ void D_DrawParticle (particle_t *pparticle) else if (pix > d_pix_max) pix = d_pix_max; - switch (pix) - { - case 1: - count = 1 << d_y_aspect_shift; + switch (pix) { + case 1: + count = 1 << d_y_aspect_shift; - for ( ; count ; count--, pz += d_zwidth, pdest += screenwidth) - { - if (pz[0] <= izi) - { - pz[0] = izi; - pdest[0] = pparticle->color; - } - } - break; - - case 2: - count = 2 << d_y_aspect_shift; - - for ( ; count ; count--, pz += d_zwidth, pdest += screenwidth) - { - if (pz[0] <= izi) - { - pz[0] = izi; - pdest[0] = pparticle->color; - } - - if (pz[1] <= izi) - { - pz[1] = izi; - pdest[1] = pparticle->color; - } - } - break; - - case 3: - count = 3 << d_y_aspect_shift; - - for ( ; count ; count--, pz += d_zwidth, pdest += screenwidth) - { - if (pz[0] <= izi) - { - pz[0] = izi; - pdest[0] = pparticle->color; - } - - if (pz[1] <= izi) - { - pz[1] = izi; - pdest[1] = pparticle->color; - } - - if (pz[2] <= izi) - { - pz[2] = izi; - pdest[2] = pparticle->color; - } - } - break; - - case 4: - count = 4 << d_y_aspect_shift; - - for ( ; count ; count--, pz += d_zwidth, pdest += screenwidth) - { - if (pz[0] <= izi) - { - pz[0] = izi; - pdest[0] = pparticle->color; - } - - if (pz[1] <= izi) - { - pz[1] = izi; - pdest[1] = pparticle->color; - } - - if (pz[2] <= izi) - { - pz[2] = izi; - pdest[2] = pparticle->color; - } - - if (pz[3] <= izi) - { - pz[3] = izi; - pdest[3] = pparticle->color; - } - } - break; - - default: - count = pix << d_y_aspect_shift; - - for ( ; count ; count--, pz += d_zwidth, pdest += screenwidth) - { - for (i=0 ; icolor; + for (; count; count--, pz += d_zwidth, pdest += screenwidth) { + if (pz[0] <= izi) { + pz[0] = izi; + pdest[0] = pparticle->color; } } - } - break; + break; + + case 2: + count = 2 << d_y_aspect_shift; + + for (; count; count--, pz += d_zwidth, pdest += screenwidth) { + if (pz[0] <= izi) { + pz[0] = izi; + pdest[0] = pparticle->color; + } + + if (pz[1] <= izi) { + pz[1] = izi; + pdest[1] = pparticle->color; + } + } + break; + + case 3: + count = 3 << d_y_aspect_shift; + + for (; count; count--, pz += d_zwidth, pdest += screenwidth) { + if (pz[0] <= izi) { + pz[0] = izi; + pdest[0] = pparticle->color; + } + + if (pz[1] <= izi) { + pz[1] = izi; + pdest[1] = pparticle->color; + } + + if (pz[2] <= izi) { + pz[2] = izi; + pdest[2] = pparticle->color; + } + } + break; + + case 4: + count = 4 << d_y_aspect_shift; + + for (; count; count--, pz += d_zwidth, pdest += screenwidth) { + if (pz[0] <= izi) { + pz[0] = izi; + pdest[0] = pparticle->color; + } + + if (pz[1] <= izi) { + pz[1] = izi; + pdest[1] = pparticle->color; + } + + if (pz[2] <= izi) { + pz[2] = izi; + pdest[2] = pparticle->color; + } + + if (pz[3] <= izi) { + pz[3] = izi; + pdest[3] = pparticle->color; + } + } + break; + + default: + count = pix << d_y_aspect_shift; + + for (; count; count--, pz += d_zwidth, pdest += screenwidth) { + for (i = 0; i < pix; i++) { + if (pz[i] <= izi) { + pz[i] = izi; + pdest[i] = pparticle->color; + } + } + } + break; } } -#endif // !USE_INTEL_ASM - +#endif // !USE_INTEL_ASM diff --git a/source/d_polyse.c b/source/d_polyse.c index c1800ec..89f6999 100644 --- a/source/d_polyse.c +++ b/source/d_polyse.c @@ -28,55 +28,55 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" #include "d_local.h" #include "bothdefs.h" // TODO: put in span spilling to shrink list size // !!! if this is changed, it must be changed in d_polysa.s too !!! -#define DPS_MAXSPANS MAXHEIGHT+1 +#define DPS_MAXSPANS MAXHEIGHT+1 // 1 extra for spanpackage that marks end // !!! if this is changed, it must be changed in asm_draw.h too !!! typedef struct { - void *pdest; - short *pz; - int count; - byte *ptex; - int sfrac, tfrac, light, zi; + void *pdest; + short *pz; + int count; + byte *ptex; + int sfrac, tfrac, light, zi; } spanpackage_t; typedef struct { - int isflattop; - int numleftedges; - int *pleftedgevert0; - int *pleftedgevert1; - int *pleftedgevert2; - int numrightedges; - int *prightedgevert0; - int *prightedgevert1; - int *prightedgevert2; + int isflattop; + int numleftedges; + int *pleftedgevert0; + int *pleftedgevert1; + int *pleftedgevert2; + int numrightedges; + int *prightedgevert0; + int *prightedgevert1; + int *prightedgevert2; } edgetable; -int r_p0[6], r_p1[6], r_p2[6]; +int r_p0[6], r_p1[6], r_p2[6]; -byte *d_pcolormap; +byte *d_pcolormap; -int d_aflatcolor; -int d_xdenom; +int d_aflatcolor; +int d_xdenom; -edgetable *pedgetable; +edgetable *pedgetable; -edgetable edgetables[12] = { - {0, 1, r_p0, r_p2, NULL, 2, r_p0, r_p1, r_p2 }, - {0, 2, r_p1, r_p0, r_p2, 1, r_p1, r_p2, NULL}, +edgetable edgetables[12] = { + {0, 1, r_p0, r_p2, NULL, 2, r_p0, r_p1, r_p2}, + {0, 2, r_p1, r_p0, r_p2, 1, r_p1, r_p2, NULL}, {1, 1, r_p0, r_p2, NULL, 1, r_p1, r_p2, NULL}, - {0, 1, r_p1, r_p0, NULL, 2, r_p1, r_p2, r_p0 }, - {0, 2, r_p0, r_p2, r_p1, 1, r_p0, r_p1, NULL}, + {0, 1, r_p1, r_p0, NULL, 2, r_p1, r_p2, r_p0}, + {0, 2, r_p0, r_p2, r_p1, 1, r_p0, r_p1, NULL}, {0, 1, r_p2, r_p1, NULL, 1, r_p2, r_p0, NULL}, - {0, 1, r_p2, r_p1, NULL, 2, r_p2, r_p0, r_p1 }, - {0, 2, r_p2, r_p1, r_p0, 1, r_p2, r_p0, NULL}, + {0, 1, r_p2, r_p1, NULL, 2, r_p2, r_p0, r_p1}, + {0, 2, r_p2, r_p1, r_p0, 1, r_p2, r_p0, NULL}, {0, 1, r_p1, r_p0, NULL, 1, r_p1, r_p2, NULL}, {1, 1, r_p2, r_p1, NULL, 1, r_p0, r_p1, NULL}, {1, 1, r_p1, r_p0, NULL, 1, r_p2, r_p0, NULL}, @@ -84,45 +84,45 @@ edgetable edgetables[12] = { }; // FIXME: some of these can become statics -int a_sstepxfrac, a_tstepxfrac, r_lstepx, a_ststepxwhole; -int r_sstepx, r_tstepx, r_lstepy, r_sstepy, r_tstepy; -int r_zistepx, r_zistepy; -int d_aspancount, d_countextrastep; +int a_sstepxfrac, a_tstepxfrac, r_lstepx, a_ststepxwhole; +int r_sstepx, r_tstepx, r_lstepy, r_sstepy, r_tstepy; +int r_zistepx, r_zistepy; +int d_aspancount, d_countextrastep; -spanpackage_t *a_spans; -spanpackage_t *d_pedgespanpackage; -static int ystart; -byte *d_pdest, *d_ptex; -short *d_pz; -int d_sfrac, d_tfrac, d_light, d_zi; -int d_ptexextrastep, d_sfracextrastep; -int d_tfracextrastep, d_lightextrastep, d_pdestextrastep; -int d_lightbasestep, d_pdestbasestep, d_ptexbasestep; -int d_sfracbasestep, d_tfracbasestep; -int d_ziextrastep, d_zibasestep; -int d_pzextrastep, d_pzbasestep; +spanpackage_t *a_spans; +spanpackage_t *d_pedgespanpackage; +static int ystart; +byte *d_pdest, *d_ptex; +short *d_pz; +int d_sfrac, d_tfrac, d_light, d_zi; +int d_ptexextrastep, d_sfracextrastep; +int d_tfracextrastep, d_lightextrastep, d_pdestextrastep; +int d_lightbasestep, d_pdestbasestep, d_ptexbasestep; +int d_sfracbasestep, d_tfracbasestep; +int d_ziextrastep, d_zibasestep; +int d_pzextrastep, d_pzbasestep; typedef struct { - int quotient; - int remainder; + int quotient; + int remainder; } adivtab_t; -static adivtab_t adivtab[32*32] = { +static adivtab_t adivtab[32 * 32] = { #include "adivtab.h" }; -byte *skintable[MAX_LBM_HEIGHT]; -int skinwidth; -byte *skinstart; +byte *skintable[MAX_LBM_HEIGHT]; +int skinwidth; +byte *skinstart; -void D_PolysetDrawSpans8 (spanpackage_t *pspanpackage); -void D_PolysetCalcGradients (int skinwidth); -void D_DrawSubdiv (void); -void D_DrawNonSubdiv (void); -void D_PolysetRecursiveTriangle (int *p1, int *p2, int *p3); -void D_PolysetSetEdgeTable (void); -void D_RasterizeAliasPolySmooth (void); -void D_PolysetScanLeftEdge (int height); +void D_PolysetDrawSpans8 (spanpackage_t * pspanpackage); +void D_PolysetCalcGradients (int skinwidth); +void D_DrawSubdiv (void); +void D_DrawNonSubdiv (void); +void D_PolysetRecursiveTriangle (int *p1, int *p2, int *p3); +void D_PolysetSetEdgeTable (void); +void D_RasterizeAliasPolySmooth (void); +void D_PolysetScanLeftEdge (int height); #ifndef USE_INTEL_ASM @@ -131,21 +131,20 @@ void D_PolysetScanLeftEdge (int height); D_PolysetDraw ================ */ -void D_PolysetDraw (void) +void +D_PolysetDraw (void) { - spanpackage_t spans[DPS_MAXSPANS + 1 + - ((CACHE_SIZE - 1) / sizeof(spanpackage_t)) + 1]; - // one extra because of cache line pretouching + spanpackage_t spans[DPS_MAXSPANS + 1 + + ((CACHE_SIZE - 1) / sizeof (spanpackage_t)) + 1]; + + // one extra because of cache line pretouching a_spans = (spanpackage_t *) - (((long)&spans[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); + (((long) &spans[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); - if (r_affinetridesc.drawtype) - { + if (r_affinetridesc.drawtype) { D_DrawSubdiv (); - } - else - { + } else { D_DrawNonSubdiv (); } } @@ -156,27 +155,25 @@ void D_PolysetDraw (void) D_PolysetDrawFinalVerts ================ */ -void D_PolysetDrawFinalVerts (finalvert_t *fv, int numverts) +void +D_PolysetDrawFinalVerts (finalvert_t *fv, int numverts) { - int i, z; - short *zbuf; + int i, z; + short *zbuf; - for (i=0 ; iv[0] < r_refdef.vrectright) && - (fv->v[1] < r_refdef.vrectbottom)) - { - z = fv->v[5]>>16; + (fv->v[1] < r_refdef.vrectbottom)) { + z = fv->v[5] >> 16; zbuf = zspantable[fv->v[1]] + fv->v[0]; - if (z >= *zbuf) - { - int pix; - + if (z >= *zbuf) { + int pix; + *zbuf = z; - pix = skintable[fv->v[3]>>16][fv->v[2]>>16]; - pix = ((byte *)acolormap)[pix + (fv->v[4] & 0xFF00) ]; + pix = skintable[fv->v[3] >> 16][fv->v[2] >> 16]; + pix = ((byte *) acolormap)[pix + (fv->v[4] & 0xFF00)]; d_viewbuffer[d_scantable[fv->v[1]] + fv->v[0]] = pix; } } @@ -189,40 +186,36 @@ void D_PolysetDrawFinalVerts (finalvert_t *fv, int numverts) D_DrawSubdiv ================ */ -void D_DrawSubdiv (void) +void +D_DrawSubdiv (void) { - mtriangle_t *ptri; - finalvert_t *pfv, *index0, *index1, *index2; - int i; - int lnumtriangles; + mtriangle_t *ptri; + finalvert_t *pfv, *index0, *index1, *index2; + int i; + int lnumtriangles; pfv = r_affinetridesc.pfinalverts; ptri = r_affinetridesc.ptriangles; lnumtriangles = r_affinetridesc.numtriangles; - for (i=0 ; iv[1]-index1->v[1]) * - (index0->v[0]-index2->v[0]) - - (index0->v[0]-index1->v[0]) * - (index0->v[1]-index2->v[1])) >= 0) - { + if (((index0->v[1] - index1->v[1]) * + (index0->v[0] - index2->v[0]) - + (index0->v[0] - index1->v[0]) * + (index0->v[1] - index2->v[1])) >= 0) { continue; } - d_pcolormap = &((byte *)acolormap)[index0->v[4] & 0xFF00]; + d_pcolormap = &((byte *) acolormap)[index0->v[4] & 0xFF00]; - if (ptri[i].facesfront) - { - D_PolysetRecursiveTriangle(index0->v, index1->v, index2->v); - } - else - { - int s0, s1, s2; + if (ptri[i].facesfront) { + D_PolysetRecursiveTriangle (index0->v, index1->v, index2->v); + } else { + int s0, s1, s2; s0 = index0->v[2]; s1 = index1->v[2]; @@ -235,7 +228,7 @@ void D_DrawSubdiv (void) if (index2->flags & ALIAS_ONSEAM) index2->v[2] += r_affinetridesc.seamfixupX16; - D_PolysetRecursiveTriangle(index0->v, index1->v, index2->v); + D_PolysetRecursiveTriangle (index0->v, index1->v, index2->v); index0->v[2] = s0; index1->v[2] = s1; @@ -250,38 +243,37 @@ void D_DrawSubdiv (void) D_DrawNonSubdiv ================ */ -void D_DrawNonSubdiv (void) +void +D_DrawNonSubdiv (void) { - mtriangle_t *ptri; - finalvert_t *pfv, *index0, *index1, *index2; - int i; - int lnumtriangles; + mtriangle_t *ptri; + finalvert_t *pfv, *index0, *index1, *index2; + int i; + int lnumtriangles; pfv = r_affinetridesc.pfinalverts; ptri = r_affinetridesc.ptriangles; lnumtriangles = r_affinetridesc.numtriangles; - for (i=0 ; ivertindex[0]; index1 = pfv + ptri->vertindex[1]; index2 = pfv + ptri->vertindex[2]; - d_xdenom = (index0->v[1]-index1->v[1]) * - (index0->v[0]-index2->v[0]) - - (index0->v[0]-index1->v[0])*(index0->v[1]-index2->v[1]); + d_xdenom = (index0->v[1] - index1->v[1]) * + (index0->v[0] - index2->v[0]) - + (index0->v[0] - index1->v[0]) * (index0->v[1] - index2->v[1]); - if (d_xdenom >= 0) - { + if (d_xdenom >= 0) { continue; } - r_p0[0] = index0->v[0]; // u - r_p0[1] = index0->v[1]; // v - r_p0[2] = index0->v[2]; // s - r_p0[3] = index0->v[3]; // t - r_p0[4] = index0->v[4]; // light - r_p0[5] = index0->v[5]; // iz + r_p0[0] = index0->v[0]; // u + r_p0[1] = index0->v[1]; // v + r_p0[2] = index0->v[2]; // s + r_p0[3] = index0->v[3]; // t + r_p0[4] = index0->v[4]; // light + r_p0[5] = index0->v[5]; // iz r_p1[0] = index1->v[0]; r_p1[1] = index1->v[1]; @@ -297,8 +289,7 @@ void D_DrawNonSubdiv (void) r_p2[4] = index2->v[4]; r_p2[5] = index2->v[5]; - if (!ptri->facesfront) - { + if (!ptri->facesfront) { if (index0->flags & ALIAS_ONSEAM) r_p0[2] += r_affinetridesc.seamfixupX16; if (index1->flags & ALIAS_ONSEAM) @@ -318,13 +309,14 @@ void D_DrawNonSubdiv (void) D_PolysetRecursiveTriangle ================ */ -void D_PolysetRecursiveTriangle (int *lp1, int *lp2, int *lp3) +void +D_PolysetRecursiveTriangle (int *lp1, int *lp2, int *lp3) { - int *temp; - int d; - int new[6]; - int z; - short *zbuf; + int *temp; + int d; + int new[6]; + int z; + short *zbuf; d = lp2[0] - lp1[0]; if (d < -1 || d > 1) @@ -344,9 +336,8 @@ void D_PolysetRecursiveTriangle (int *lp1, int *lp2, int *lp3) if (d < -1 || d > 1) goto split3; d = lp1[1] - lp3[1]; - if (d < -1 || d > 1) - { -split3: + if (d < -1 || d > 1) { + split3: temp = lp1; lp1 = lp3; lp3 = lp2; @@ -355,15 +346,15 @@ split3: goto split; } - return; // entire tri is filled + return; // entire tri is filled -split2: + split2: temp = lp1; lp1 = lp2; lp2 = lp3; lp3 = temp; -split: + split: // split this edge new[0] = (lp1[0] + lp2[0]) >> 1; new[1] = (lp1[1] + lp2[1]) >> 1; @@ -378,24 +369,23 @@ split: goto nodraw; - z = new[5]>>16; + z = new[5] >> 16; zbuf = zspantable[new[1]] + new[0]; - if (z >= *zbuf) - { - int pix; - + if (z >= *zbuf) { + int pix; + *zbuf = z; - pix = d_pcolormap[skintable[new[3]>>16][new[2]>>16]]; + pix = d_pcolormap[skintable[new[3] >> 16][new[2] >> 16]]; d_viewbuffer[d_scantable[new[1]] + new[0]] = pix; } -nodraw: + nodraw: // recursively continue D_PolysetRecursiveTriangle (lp3, lp1, new); D_PolysetRecursiveTriangle (lp3, new, lp2); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -403,18 +393,18 @@ nodraw: D_PolysetUpdateTables ================ */ -void D_PolysetUpdateTables (void) +void +D_PolysetUpdateTables (void) { - int i; - byte *s; - + int i; + byte *s; + if (r_affinetridesc.skinwidth != skinwidth || - r_affinetridesc.pskin != skinstart) - { + r_affinetridesc.pskin != skinstart) { skinwidth = r_affinetridesc.skinwidth; skinstart = r_affinetridesc.pskin; s = skinstart; - for (i=0 ; ipdest = d_pdest; d_pedgespanpackage->pz = d_pz; d_pedgespanpackage->count = d_aspancount; @@ -440,15 +430,14 @@ void D_PolysetScanLeftEdge (int height) d_pedgespanpackage->sfrac = d_sfrac; d_pedgespanpackage->tfrac = d_tfrac; - // FIXME: need to clamp l, s, t, at both ends? + // FIXME: need to clamp l, s, t, at both ends? d_pedgespanpackage->light = d_light; d_pedgespanpackage->zi = d_zi; d_pedgespanpackage++; errorterm += erroradjustup; - if (errorterm >= 0) - { + if (errorterm >= 0) { d_pdest += d_pdestextrastep; d_pz += d_pzextrastep; d_aspancount += d_countextrastep; @@ -458,17 +447,14 @@ void D_PolysetScanLeftEdge (int height) d_sfrac &= 0xFFFF; d_tfrac += d_tfracextrastep; - if (d_tfrac & 0x10000) - { + if (d_tfrac & 0x10000) { d_ptex += r_affinetridesc.skinwidth; d_tfrac &= 0xFFFF; } d_light += d_lightextrastep; d_zi += d_ziextrastep; errorterm -= erroradjustdown; - } - else - { + } else { d_pdest += d_pdestbasestep; d_pz += d_pzbasestep; d_aspancount += ubasestep; @@ -477,8 +463,7 @@ void D_PolysetScanLeftEdge (int height) d_ptex += d_sfrac >> 16; d_sfrac &= 0xFFFF; d_tfrac += d_tfracbasestep; - if (d_tfrac & 0x10000) - { + if (d_tfrac & 0x10000) { d_ptex += r_affinetridesc.skinwidth; d_tfrac &= 0xFFFF; } @@ -488,7 +473,7 @@ void D_PolysetScanLeftEdge (int height) } while (--height); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -496,12 +481,13 @@ void D_PolysetScanLeftEdge (int height) D_PolysetSetUpForLineScan ==================== */ -void D_PolysetSetUpForLineScan(fixed8_t startvertu, fixed8_t startvertv, - fixed8_t endvertu, fixed8_t endvertv) +void +D_PolysetSetUpForLineScan (fixed8_t startvertu, fixed8_t startvertv, + fixed8_t endvertu, fixed8_t endvertv) { - double dm, dn; - int tm, tn; - adivtab_t *ptemp; + double dm, dn; + int tm, tn; + adivtab_t *ptemp; // TODO: implement x86 version @@ -510,18 +496,14 @@ void D_PolysetSetUpForLineScan(fixed8_t startvertu, fixed8_t startvertv, tm = endvertu - startvertu; tn = endvertv - startvertv; - if (((tm <= 16) && (tm >= -15)) && - ((tn <= 16) && (tn >= -15))) - { - ptemp = &adivtab[((tm+15) << 5) + (tn+15)]; + if (((tm <= 16) && (tm >= -15)) && ((tn <= 16) && (tn >= -15))) { + ptemp = &adivtab[((tm + 15) << 5) + (tn + 15)]; ubasestep = ptemp->quotient; erroradjustup = ptemp->remainder; erroradjustdown = tn; - } - else - { - dm = (double)tm; - dn = (double)tn; + } else { + dm = (double) tm; + dn = (double) tn; FloorDivMod (dm, dn, &ubasestep, &erroradjustup); @@ -537,17 +519,18 @@ void D_PolysetSetUpForLineScan(fixed8_t startvertu, fixed8_t startvertv, D_PolysetCalcGradients ================ */ -void D_PolysetCalcGradients (int skinwidth) +void +D_PolysetCalcGradients (int skinwidth) { - float xstepdenominv, ystepdenominv, t0, t1; - float p01_minus_p21, p11_minus_p21, p00_minus_p20, p10_minus_p20; + float xstepdenominv, ystepdenominv, t0, t1; + float p01_minus_p21, p11_minus_p21, p00_minus_p20, p10_minus_p20; p00_minus_p20 = r_p0[0] - r_p2[0]; p01_minus_p21 = r_p0[1] - r_p2[1]; p10_minus_p20 = r_p1[0] - r_p2[0]; p11_minus_p21 = r_p1[1] - r_p2[1]; - xstepdenominv = 1.0 / (float)d_xdenom; + xstepdenominv = 1.0 / (float) d_xdenom; ystepdenominv = -xstepdenominv; @@ -557,30 +540,30 @@ void D_PolysetCalcGradients (int skinwidth) t0 = r_p0[4] - r_p2[4]; t1 = r_p1[4] - r_p2[4]; r_lstepx = (int) - ceil((t1 * p01_minus_p21 - t0 * p11_minus_p21) * xstepdenominv); + ceil ((t1 * p01_minus_p21 - t0 * p11_minus_p21) * xstepdenominv); r_lstepy = (int) - ceil((t1 * p00_minus_p20 - t0 * p10_minus_p20) * ystepdenominv); + ceil ((t1 * p00_minus_p20 - t0 * p10_minus_p20) * ystepdenominv); t0 = r_p0[2] - r_p2[2]; t1 = r_p1[2] - r_p2[2]; - r_sstepx = (int)((t1 * p01_minus_p21 - t0 * p11_minus_p21) * - xstepdenominv); - r_sstepy = (int)((t1 * p00_minus_p20 - t0* p10_minus_p20) * - ystepdenominv); + r_sstepx = (int) ((t1 * p01_minus_p21 - t0 * p11_minus_p21) * + xstepdenominv); + r_sstepy = (int) ((t1 * p00_minus_p20 - t0 * p10_minus_p20) * + ystepdenominv); t0 = r_p0[3] - r_p2[3]; t1 = r_p1[3] - r_p2[3]; - r_tstepx = (int)((t1 * p01_minus_p21 - t0 * p11_minus_p21) * - xstepdenominv); - r_tstepy = (int)((t1 * p00_minus_p20 - t0 * p10_minus_p20) * - ystepdenominv); + r_tstepx = (int) ((t1 * p01_minus_p21 - t0 * p11_minus_p21) * + xstepdenominv); + r_tstepy = (int) ((t1 * p00_minus_p20 - t0 * p10_minus_p20) * + ystepdenominv); t0 = r_p0[5] - r_p2[5]; t1 = r_p1[5] - r_p2[5]; - r_zistepx = (int)((t1 * p01_minus_p21 - t0 * p11_minus_p21) * - xstepdenominv); - r_zistepy = (int)((t1 * p00_minus_p20 - t0 * p10_minus_p20) * - ystepdenominv); + r_zistepx = (int) ((t1 * p01_minus_p21 - t0 * p11_minus_p21) * + xstepdenominv); + r_zistepy = (int) ((t1 * p00_minus_p20 - t0 * p10_minus_p20) * + ystepdenominv); #ifdef USE_INTEL_ASM a_sstepxfrac = r_sstepx << 16; @@ -593,19 +576,21 @@ void D_PolysetCalcGradients (int skinwidth) a_ststepxwhole = skinwidth * (r_tstepx >> 16) + (r_sstepx >> 16); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM -byte gelmap[256]; -void InitGel (byte *palette) +byte gelmap[256]; +void +InitGel (byte * palette) { - int i; - int r; + int i; + int r; - for (i=0 ; i<256 ; i++) - { -// r = (palette[i*3]>>4); - r = (palette[i*3] + palette[i*3+1] + palette[i*3+2])/(16*3); + for (i = 0; i < 256; i++) { +// r = (palette[i*3]>>4); + r = + (palette[i * 3] + palette[i * 3 + 1] + + palette[i * 3 + 2]) / (16 * 3); gelmap[i] = /* 64 */ 0 + r; } } @@ -618,33 +603,29 @@ void InitGel (byte *palette) D_PolysetDrawSpans8 ================ */ -void D_PolysetDrawSpans8 (spanpackage_t *pspanpackage) +void +D_PolysetDrawSpans8 (spanpackage_t * pspanpackage) { - int lcount; - byte *lpdest; - byte *lptex; - int lsfrac, ltfrac; - int llight; - int lzi; - short *lpz; + int lcount; + byte *lpdest; + byte *lptex; + int lsfrac, ltfrac; + int llight; + int lzi; + short *lpz; - do - { + do { lcount = d_aspancount - pspanpackage->count; errorterm += erroradjustup; - if (errorterm >= 0) - { + if (errorterm >= 0) { d_aspancount += d_countextrastep; errorterm -= erroradjustdown; - } - else - { + } else { d_aspancount += ubasestep; } - if (lcount) - { + if (lcount) { lpdest = pspanpackage->pdest; lptex = pspanpackage->ptex; lpz = pspanpackage->pz; @@ -653,12 +634,10 @@ void D_PolysetDrawSpans8 (spanpackage_t *pspanpackage) llight = pspanpackage->light; lzi = pspanpackage->zi; - do - { - if ((lzi >> 16) >= *lpz) - { - *lpdest = ((byte *)acolormap)[*lptex + (llight & 0xFF00)]; -// gel mapping *lpdest = gelmap[*lpdest]; + do { + if ((lzi >> 16) >= *lpz) { + *lpdest = ((byte *) acolormap)[*lptex + (llight & 0xFF00)]; +// gel mapping *lpdest = gelmap[*lpdest]; *lpz = lzi >> 16; } lpdest++; @@ -670,8 +649,7 @@ void D_PolysetDrawSpans8 (spanpackage_t *pspanpackage) lptex += lsfrac >> 16; lsfrac &= 0xFFFF; ltfrac += a_tstepxfrac; - if (ltfrac & 0x10000) - { + if (ltfrac & 0x10000) { lptex += r_affinetridesc.skinwidth; ltfrac &= 0xFFFF; } @@ -681,7 +659,7 @@ void D_PolysetDrawSpans8 (spanpackage_t *pspanpackage) pspanpackage++; } while (pspanpackage->count != -999999); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -689,30 +667,28 @@ void D_PolysetDrawSpans8 (spanpackage_t *pspanpackage) D_PolysetFillSpans8 ================ */ -void D_PolysetFillSpans8 (spanpackage_t *pspanpackage) +void +D_PolysetFillSpans8 (spanpackage_t * pspanpackage) { - int color; + int color; // FIXME: do z buffering color = d_aflatcolor++; - while (1) - { - int lcount; - byte *lpdest; + while (1) { + int lcount; + byte *lpdest; lcount = pspanpackage->count; if (lcount == -1) return; - if (lcount) - { + if (lcount) { lpdest = pspanpackage->pdest; - do - { + do { *lpdest++ = color; } while (--lcount); } @@ -726,11 +702,12 @@ void D_PolysetFillSpans8 (spanpackage_t *pspanpackage) D_RasterizeAliasPolySmooth ================ */ -void D_RasterizeAliasPolySmooth (void) +void +D_RasterizeAliasPolySmooth (void) { - int initialleftheight, initialrightheight; - int *plefttop, *prighttop, *pleftbottom, *prightbottom; - int working_lstepx, originalcount; + int initialleftheight, initialrightheight; + int *plefttop, *prighttop, *pleftbottom, *prightbottom; + int working_lstepx, originalcount; plefttop = pedgetable->pleftedgevert0; prighttop = pedgetable->prightedgevert0; @@ -754,16 +731,16 @@ void D_RasterizeAliasPolySmooth (void) // // scan out the top (and possibly only) part of the left edge // - D_PolysetSetUpForLineScan(plefttop[0], plefttop[1], - pleftbottom[0], pleftbottom[1]); + D_PolysetSetUpForLineScan (plefttop[0], plefttop[1], + pleftbottom[0], pleftbottom[1]); d_pedgespanpackage = a_spans; ystart = plefttop[1]; d_aspancount = plefttop[0] - prighttop[0]; - d_ptex = (byte *)r_affinetridesc.pskin + (plefttop[2] >> 16) + - (plefttop[3] >> 16) * r_affinetridesc.skinwidth; + d_ptex = (byte *) r_affinetridesc.pskin + (plefttop[2] >> 16) + + (plefttop[3] >> 16) * r_affinetridesc.skinwidth; #ifdef USE_INTEL_ASM d_sfrac = (plefttop[2] & 0xFFFF) << 16; d_tfrac = (plefttop[3] & 0xFFFF) << 16; @@ -780,8 +757,7 @@ void D_RasterizeAliasPolySmooth (void) d_pdestbasestep = screenwidth + ubasestep; d_pdestextrastep = d_pdestbasestep + 1; - d_pdest = (byte *)d_viewbuffer + - ystart * screenwidth + plefttop[0]; + d_pdest = (byte *) d_viewbuffer + ystart * screenwidth + plefttop[0]; d_pz = d_pzbuffer + ystart * d_zwidth + plefttop[0]; // TODO: can reuse partial expressions here @@ -796,8 +772,7 @@ void D_RasterizeAliasPolySmooth (void) d_countextrastep = ubasestep + 1; d_ptexbasestep = ((r_sstepy + r_sstepx * ubasestep) >> 16) + - ((r_tstepy + r_tstepx * ubasestep) >> 16) * - r_affinetridesc.skinwidth; + ((r_tstepy + r_tstepx * ubasestep) >> 16) * r_affinetridesc.skinwidth; #ifdef USE_INTEL_ASM d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) << 16; d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) << 16; @@ -809,14 +784,14 @@ void D_RasterizeAliasPolySmooth (void) d_zibasestep = r_zistepy + r_zistepx * ubasestep; d_ptexextrastep = ((r_sstepy + r_sstepx * d_countextrastep) >> 16) + - ((r_tstepy + r_tstepx * d_countextrastep) >> 16) * - r_affinetridesc.skinwidth; + ((r_tstepy + r_tstepx * d_countextrastep) >> 16) * + r_affinetridesc.skinwidth; #ifdef USE_INTEL_ASM - d_sfracextrastep = (r_sstepy + r_sstepx*d_countextrastep) << 16; - d_tfracextrastep = (r_tstepy + r_tstepx*d_countextrastep) << 16; + d_sfracextrastep = (r_sstepy + r_sstepx * d_countextrastep) << 16; + d_tfracextrastep = (r_tstepy + r_tstepx * d_countextrastep) << 16; #else - d_sfracextrastep = (r_sstepy + r_sstepx*d_countextrastep) & 0xFFFF; - d_tfracextrastep = (r_tstepy + r_tstepx*d_countextrastep) & 0xFFFF; + d_sfracextrastep = (r_sstepy + r_sstepx * d_countextrastep) & 0xFFFF; + d_tfracextrastep = (r_tstepy + r_tstepx * d_countextrastep) & 0xFFFF; #endif d_lightextrastep = d_lightbasestep + working_lstepx; d_ziextrastep = d_zibasestep + r_zistepx; @@ -826,15 +801,14 @@ void D_RasterizeAliasPolySmooth (void) // // scan out the bottom part of the left edge, if it exists // - if (pedgetable->numleftedges == 2) - { - int height; + if (pedgetable->numleftedges == 2) { + int height; plefttop = pleftbottom; pleftbottom = pedgetable->pleftedgevert2; - D_PolysetSetUpForLineScan(plefttop[0], plefttop[1], - pleftbottom[0], pleftbottom[1]); + D_PolysetSetUpForLineScan (plefttop[0], plefttop[1], + pleftbottom[0], pleftbottom[1]); height = pleftbottom[1] - plefttop[1]; @@ -842,8 +816,8 @@ void D_RasterizeAliasPolySmooth (void) ystart = plefttop[1]; d_aspancount = plefttop[0] - prighttop[0]; - d_ptex = (byte *)r_affinetridesc.pskin + (plefttop[2] >> 16) + - (plefttop[3] >> 16) * r_affinetridesc.skinwidth; + d_ptex = (byte *) r_affinetridesc.pskin + (plefttop[2] >> 16) + + (plefttop[3] >> 16) * r_affinetridesc.skinwidth; d_sfrac = 0; d_tfrac = 0; d_light = plefttop[4]; @@ -851,7 +825,7 @@ void D_RasterizeAliasPolySmooth (void) d_pdestbasestep = screenwidth + ubasestep; d_pdestextrastep = d_pdestbasestep + 1; - d_pdest = (byte *)d_viewbuffer + ystart * screenwidth + plefttop[0]; + d_pdest = (byte *) d_viewbuffer + ystart * screenwidth + plefttop[0]; #ifdef USE_INTEL_ASM d_pzbasestep = (d_zwidth + ubasestep) << 1; d_pzextrastep = d_pzbasestep + 2; @@ -868,8 +842,8 @@ void D_RasterizeAliasPolySmooth (void) d_countextrastep = ubasestep + 1; d_ptexbasestep = ((r_sstepy + r_sstepx * ubasestep) >> 16) + - ((r_tstepy + r_tstepx * ubasestep) >> 16) * - r_affinetridesc.skinwidth; + ((r_tstepy + r_tstepx * ubasestep) >> 16) * + r_affinetridesc.skinwidth; #ifdef USE_INTEL_ASM d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) << 16; d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) << 16; @@ -881,38 +855,39 @@ void D_RasterizeAliasPolySmooth (void) d_zibasestep = r_zistepy + r_zistepx * ubasestep; d_ptexextrastep = ((r_sstepy + r_sstepx * d_countextrastep) >> 16) + - ((r_tstepy + r_tstepx * d_countextrastep) >> 16) * - r_affinetridesc.skinwidth; + ((r_tstepy + r_tstepx * d_countextrastep) >> 16) * + r_affinetridesc.skinwidth; #ifdef USE_INTEL_ASM - d_sfracextrastep = ((r_sstepy+r_sstepx*d_countextrastep) & 0xFFFF)<<16; - d_tfracextrastep = ((r_tstepy+r_tstepx*d_countextrastep) & 0xFFFF)<<16; + d_sfracextrastep = + ((r_sstepy + r_sstepx * d_countextrastep) & 0xFFFF) << 16; + d_tfracextrastep = + ((r_tstepy + r_tstepx * d_countextrastep) & 0xFFFF) << 16; #else - d_sfracextrastep = (r_sstepy+r_sstepx*d_countextrastep) & 0xFFFF; - d_tfracextrastep = (r_tstepy+r_tstepx*d_countextrastep) & 0xFFFF; + d_sfracextrastep = (r_sstepy + r_sstepx * d_countextrastep) & 0xFFFF; + d_tfracextrastep = (r_tstepy + r_tstepx * d_countextrastep) & 0xFFFF; #endif d_lightextrastep = d_lightbasestep + working_lstepx; d_ziextrastep = d_zibasestep + r_zistepx; D_PolysetScanLeftEdge (height); } - // scan out the top (and possibly only) part of the right edge, updating the // count field d_pedgespanpackage = a_spans; - D_PolysetSetUpForLineScan(prighttop[0], prighttop[1], - prightbottom[0], prightbottom[1]); + D_PolysetSetUpForLineScan (prighttop[0], prighttop[1], + prightbottom[0], prightbottom[1]); d_aspancount = 0; d_countextrastep = ubasestep + 1; originalcount = a_spans[initialrightheight].count; - a_spans[initialrightheight].count = -999999; // mark end of the spanpackages + a_spans[initialrightheight].count = -999999; // mark end of the + // spanpackages D_PolysetDrawSpans8 (a_spans); // scan out the bottom part of the right edge, if it exists - if (pedgetable->numrightedges == 2) - { - int height; - spanpackage_t *pstart; + if (pedgetable->numrightedges == 2) { + int height; + spanpackage_t *pstart; pstart = a_spans + initialrightheight; pstart->count = originalcount; @@ -924,12 +899,12 @@ void D_RasterizeAliasPolySmooth (void) height = prightbottom[1] - prighttop[1]; - D_PolysetSetUpForLineScan(prighttop[0], prighttop[1], - prightbottom[0], prightbottom[1]); + D_PolysetSetUpForLineScan (prighttop[0], prighttop[1], + prightbottom[0], prightbottom[1]); d_countextrastep = ubasestep + 1; a_spans[initialrightheight + height].count = -999999; - // mark end of the spanpackages + // mark end of the spanpackages D_PolysetDrawSpans8 (pstart); } } @@ -940,45 +915,39 @@ void D_RasterizeAliasPolySmooth (void) D_PolysetSetEdgeTable ================ */ -void D_PolysetSetEdgeTable (void) +void +D_PolysetSetEdgeTable (void) { - int edgetableindex; + int edgetableindex; - edgetableindex = 0; // assume the vertices are already in - // top to bottom order + edgetableindex = 0; // assume the vertices are already in + // top to bottom order // // determine which edges are right & left, and the order in which // to rasterize them // - if (r_p0[1] >= r_p1[1]) - { - if (r_p0[1] == r_p1[1]) - { + if (r_p0[1] >= r_p1[1]) { + if (r_p0[1] == r_p1[1]) { if (r_p0[1] < r_p2[1]) pedgetable = &edgetables[2]; else pedgetable = &edgetables[5]; return; - } - else - { + } else { edgetableindex = 1; } } - if (r_p0[1] == r_p2[1]) - { + if (r_p0[1] == r_p2[1]) { if (edgetableindex) pedgetable = &edgetables[8]; else pedgetable = &edgetables[9]; return; - } - else if (r_p1[1] == r_p2[1]) - { + } else if (r_p1[1] == r_p2[1]) { if (edgetableindex) pedgetable = &edgetables[10]; else @@ -999,12 +968,13 @@ void D_PolysetSetEdgeTable (void) #if 0 -void D_PolysetRecursiveDrawLine (int *lp1, int *lp2) +void +D_PolysetRecursiveDrawLine (int *lp1, int *lp2) { - int d; - int new[6]; - int ofs; - + int d; + int new[6]; + int ofs; + d = lp2[0] - lp1[0]; if (d < -1 || d > 1) goto split; @@ -1012,9 +982,9 @@ void D_PolysetRecursiveDrawLine (int *lp1, int *lp2) if (d < -1 || d > 1) goto split; - return; // line is completed + return; // line is completed -split: + split: // split this edge new[0] = (lp1[0] + lp2[0]) >> 1; new[1] = (lp1[1] + lp2[1]) >> 1; @@ -1025,26 +995,25 @@ split: // draw the point ofs = d_scantable[new[1]] + new[0]; - if (new[5] > d_pzbuffer[ofs]) - { - int pix; - + if (new[5] > d_pzbuffer[ofs]) { + int pix; + d_pzbuffer[ofs] = new[5]; - pix = skintable[new[3]>>16][new[2]>>16]; -// pix = ((byte *)acolormap)[pix + (new[4] & 0xFF00)]; + pix = skintable[new[3] >> 16][new[2] >> 16]; +// pix = ((byte *)acolormap)[pix + (new[4] & 0xFF00)]; d_viewbuffer[ofs] = pix; } - // recursively continue D_PolysetRecursiveDrawLine (lp1, new); D_PolysetRecursiveDrawLine (new, lp2); } -void D_PolysetRecursiveTriangle2 (int *lp1, int *lp2, int *lp3) +void +D_PolysetRecursiveTriangle2 (int *lp1, int *lp2, int *lp3) { - int d; - int new[4]; - + int d; + int new[4]; + d = lp2[0] - lp1[0]; if (d < -1 || d > 1) goto split; @@ -1053,7 +1022,7 @@ void D_PolysetRecursiveTriangle2 (int *lp1, int *lp2, int *lp3) goto split; return; -split: + split: // split this edge new[0] = (lp1[0] + lp2[0]) >> 1; new[1] = (lp1[1] + lp2[1]) >> 1; @@ -1070,4 +1039,3 @@ split: } #endif - diff --git a/source/d_scan.c b/source/d_scan.c index 1af03f4..5b1e493 100644 --- a/source/d_scan.c +++ b/source/d_scan.c @@ -27,17 +27,17 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" #include "d_local.h" -unsigned char *r_turb_pbase, *r_turb_pdest; -fixed16_t r_turb_s, r_turb_t, r_turb_sstep, r_turb_tstep; -int *r_turb_turb; -int r_turb_spancount; +unsigned char *r_turb_pbase, *r_turb_pdest; +fixed16_t r_turb_s, r_turb_t, r_turb_sstep, r_turb_tstep; +int *r_turb_turb; +int r_turb_spancount; -void D_DrawTurbulent8Span (void); +void D_DrawTurbulent8Span (void); /* @@ -48,49 +48,46 @@ D_WarpScreen // the sine warp, to keep the edges from wrapping ============= */ -void D_WarpScreen (void) +void +D_WarpScreen (void) { - int w, h; - int u,v; - byte *dest; - int *turb; - int *col; - byte **row; - byte *rowptr[1024]; - int column[1280]; - float wratio, hratio; + int w, h; + int u, v; + byte *dest; + int *turb; + int *col; + byte **row; + byte *rowptr[1024]; + int column[1280]; + float wratio, hratio; w = r_refdef.vrect.width; h = r_refdef.vrect.height; - wratio = w / (float)scr_vrect.width; - hratio = h / (float)scr_vrect.height; + wratio = w / (float) scr_vrect.width; + hratio = h / (float) scr_vrect.height; - for (v=0 ; v>16)&(CYCLE-1)])>>16)&63; - tturb = ((r_turb_t + r_turb_turb[(r_turb_s>>16)&(CYCLE-1)])>>16)&63; - *r_turb_pdest++ = *(r_turb_pbase + (tturb<<6) + sturb); + do { + sturb = + ((r_turb_s + r_turb_turb[(r_turb_t >> 16) & (CYCLE - 1)]) >> 16) & + 63; + tturb = + ((r_turb_t + r_turb_turb[(r_turb_s >> 16) & (CYCLE - 1)]) >> 16) & + 63; + *r_turb_pdest++ = *(r_turb_pbase + (tturb << 6) + sturb); r_turb_s += r_turb_sstep; r_turb_t += r_turb_tstep; } while (--r_turb_spancount > 0); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* ============= Turbulent8 ============= */ -void Turbulent8 (espan_t *pspan) +void +Turbulent8 (espan_t *pspan) { - int count; - fixed16_t snext, tnext; - float sdivz, tdivz, zi, z, du, dv, spancountminus1; - float sdivz16stepu, tdivz16stepu, zi16stepu; - - r_turb_turb = sintable + ((int)(cl.time*SPEED)&(CYCLE-1)); + int count; + fixed16_t snext, tnext; + float sdivz, tdivz, zi, z, du, dv, spancountminus1; + float sdivz16stepu, tdivz16stepu, zi16stepu; - r_turb_sstep = 0; // keep compiler happy - r_turb_tstep = 0; // ditto + r_turb_turb = sintable + ((int) (cl.time * SPEED) & (CYCLE - 1)); - r_turb_pbase = (unsigned char *)cacheblock; + r_turb_sstep = 0; // keep compiler happy + r_turb_tstep = 0; // ditto + + r_turb_pbase = (unsigned char *) cacheblock; sdivz16stepu = d_sdivzstepu * 16; tdivz16stepu = d_tdivzstepu * 16; zi16stepu = d_zistepu * 16; - do - { - r_turb_pdest = (unsigned char *)((byte *)d_viewbuffer + - (screenwidth * pspan->v) + pspan->u); + do { + r_turb_pdest = (unsigned char *) ((byte *) d_viewbuffer + + (screenwidth * pspan->v) + pspan->u); count = pspan->count; - // calculate the initial s/z, t/z, 1/z, s, and t and clamp - du = (float)pspan->u; - dv = (float)pspan->v; + // calculate the initial s/z, t/z, 1/z, s, and t and clamp + du = (float) pspan->u; + dv = (float) pspan->v; - sdivz = d_sdivzorigin + dv*d_sdivzstepv + du*d_sdivzstepu; - tdivz = d_tdivzorigin + dv*d_tdivzstepv + du*d_tdivzstepu; - zi = d_ziorigin + dv*d_zistepv + du*d_zistepu; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point + sdivz = d_sdivzorigin + dv * d_sdivzstepv + du * d_sdivzstepu; + tdivz = d_tdivzorigin + dv * d_tdivzstepv + du * d_tdivzstepu; + zi = d_ziorigin + dv * d_zistepv + du * d_zistepu; + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point - r_turb_s = (int)(sdivz * z) + sadjust; + r_turb_s = (int) (sdivz * z) + sadjust; if (r_turb_s > bbextents) r_turb_s = bbextents; else if (r_turb_s < 0) r_turb_s = 0; - r_turb_t = (int)(tdivz * z) + tadjust; + r_turb_t = (int) (tdivz * z) + tadjust; if (r_turb_t > bbextentt) r_turb_t = bbextentt; else if (r_turb_t < 0) r_turb_t = 0; - do - { - // calculate s and t at the far end of the span + do { + // calculate s and t at the far end of the span if (count >= 16) r_turb_spancount = 16; else @@ -180,66 +180,69 @@ void Turbulent8 (espan_t *pspan) count -= r_turb_spancount; - if (count) - { - // calculate s/z, t/z, zi->fixed s and t at far end of span, - // calculate s and t steps across span by shifting + if (count) { + // calculate s/z, t/z, zi->fixed s and t at far end of span, + // calculate s and t steps across span by shifting sdivz += sdivz16stepu; tdivz += tdivz16stepu; zi += zi16stepu; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point - snext = (int)(sdivz * z) + sadjust; + snext = (int) (sdivz * z) + sadjust; if (snext > bbextents) snext = bbextents; else if (snext < 16) - snext = 16; // prevent round-off error on <0 steps from - // from causing overstepping & running off the - // edge of the texture + snext = 16; // prevent round-off error on <0 + // steps from + // from causing overstepping & running off the + // edge of the texture - tnext = (int)(tdivz * z) + tadjust; + tnext = (int) (tdivz * z) + tadjust; if (tnext > bbextentt) tnext = bbextentt; else if (tnext < 16) - tnext = 16; // guard against round-off error on <0 steps + tnext = 16; // guard against round-off error on + // <0 steps r_turb_sstep = (snext - r_turb_s) >> 4; r_turb_tstep = (tnext - r_turb_t) >> 4; - } - else - { - // calculate s/z, t/z, zi->fixed s and t at last pixel in span (so - // can't step off polygon), clamp, calculate s and t steps across - // span by division, biasing steps low so we don't run off the - // texture - spancountminus1 = (float)(r_turb_spancount - 1); + } else { + // calculate s/z, t/z, zi->fixed s and t at last pixel in + // span (so + // can't step off polygon), clamp, calculate s and t steps + // across + // span by division, biasing steps low so we don't run off + // the + // texture + spancountminus1 = (float) (r_turb_spancount - 1); sdivz += d_sdivzstepu * spancountminus1; tdivz += d_tdivzstepu * spancountminus1; zi += d_zistepu * spancountminus1; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point - snext = (int)(sdivz * z) + sadjust; + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point + snext = (int) (sdivz * z) + sadjust; if (snext > bbextents) snext = bbextents; else if (snext < 16) - snext = 16; // prevent round-off error on <0 steps from - // from causing overstepping & running off the - // edge of the texture + snext = 16; // prevent round-off error on <0 + // steps from + // from causing overstepping & running off the + // edge of the texture - tnext = (int)(tdivz * z) + tadjust; + tnext = (int) (tdivz * z) + tadjust; if (tnext > bbextentt) tnext = bbextentt; else if (tnext < 16) - tnext = 16; // guard against round-off error on <0 steps + tnext = 16; // guard against round-off error on + // <0 steps - if (r_turb_spancount > 1) - { + if (r_turb_spancount > 1) { r_turb_sstep = (snext - r_turb_s) / (r_turb_spancount - 1); r_turb_tstep = (tnext - r_turb_t) / (r_turb_spancount - 1); } } - r_turb_s = r_turb_s & ((CYCLE<<16)-1); - r_turb_t = r_turb_t & ((CYCLE<<16)-1); + r_turb_s = r_turb_s & ((CYCLE << 16) - 1); + r_turb_t = r_turb_t & ((CYCLE << 16) - 1); D_DrawTurbulent8Span (); @@ -259,54 +262,53 @@ void Turbulent8 (espan_t *pspan) D_DrawSpans8 ============= */ -void D_DrawSpans8 (espan_t *pspan) +void +D_DrawSpans8 (espan_t *pspan) { - int count, spancount; - unsigned char *pbase, *pdest; - fixed16_t s, t, snext, tnext, sstep, tstep; - float sdivz, tdivz, zi, z, du, dv, spancountminus1; - float sdivz8stepu, tdivz8stepu, zi8stepu; + int count, spancount; + unsigned char *pbase, *pdest; + fixed16_t s, t, snext, tnext, sstep, tstep; + float sdivz, tdivz, zi, z, du, dv, spancountminus1; + float sdivz8stepu, tdivz8stepu, zi8stepu; - sstep = 0; // keep compiler happy - tstep = 0; // ditto + sstep = 0; // keep compiler happy + tstep = 0; // ditto - pbase = (unsigned char *)cacheblock; + pbase = (unsigned char *) cacheblock; sdivz8stepu = d_sdivzstepu * 8; tdivz8stepu = d_tdivzstepu * 8; zi8stepu = d_zistepu * 8; - do - { - pdest = (unsigned char *)((byte *)d_viewbuffer + - (screenwidth * pspan->v) + pspan->u); + do { + pdest = (unsigned char *) ((byte *) d_viewbuffer + + (screenwidth * pspan->v) + pspan->u); count = pspan->count; - // calculate the initial s/z, t/z, 1/z, s, and t and clamp - du = (float)pspan->u; - dv = (float)pspan->v; + // calculate the initial s/z, t/z, 1/z, s, and t and clamp + du = (float) pspan->u; + dv = (float) pspan->v; - sdivz = d_sdivzorigin + dv*d_sdivzstepv + du*d_sdivzstepu; - tdivz = d_tdivzorigin + dv*d_tdivzstepv + du*d_tdivzstepu; - zi = d_ziorigin + dv*d_zistepv + du*d_zistepu; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point + sdivz = d_sdivzorigin + dv * d_sdivzstepv + du * d_sdivzstepu; + tdivz = d_tdivzorigin + dv * d_tdivzstepv + du * d_tdivzstepu; + zi = d_ziorigin + dv * d_zistepv + du * d_zistepu; + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point - s = (int)(sdivz * z) + sadjust; + s = (int) (sdivz * z) + sadjust; if (s > bbextents) s = bbextents; else if (s < 0) s = 0; - t = (int)(tdivz * z) + tadjust; + t = (int) (tdivz * z) + tadjust; if (t > bbextentt) t = bbextentt; else if (t < 0) t = 0; - do - { - // calculate s and t at the far end of the span + do { + // calculate s and t at the far end of the span if (count >= 8) spancount = 8; else @@ -314,66 +316,68 @@ void D_DrawSpans8 (espan_t *pspan) count -= spancount; - if (count) - { - // calculate s/z, t/z, zi->fixed s and t at far end of span, - // calculate s and t steps across span by shifting + if (count) { + // calculate s/z, t/z, zi->fixed s and t at far end of span, + // calculate s and t steps across span by shifting sdivz += sdivz8stepu; tdivz += tdivz8stepu; zi += zi8stepu; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point - snext = (int)(sdivz * z) + sadjust; + snext = (int) (sdivz * z) + sadjust; if (snext > bbextents) snext = bbextents; else if (snext < 8) - snext = 8; // prevent round-off error on <0 steps from - // from causing overstepping & running off the - // edge of the texture + snext = 8; // prevent round-off error on <0 + // steps from + // from causing overstepping & running off the + // edge of the texture - tnext = (int)(tdivz * z) + tadjust; + tnext = (int) (tdivz * z) + tadjust; if (tnext > bbextentt) tnext = bbextentt; else if (tnext < 8) - tnext = 8; // guard against round-off error on <0 steps + tnext = 8; // guard against round-off error on + // <0 steps sstep = (snext - s) >> 3; tstep = (tnext - t) >> 3; - } - else - { - // calculate s/z, t/z, zi->fixed s and t at last pixel in span (so - // can't step off polygon), clamp, calculate s and t steps across - // span by division, biasing steps low so we don't run off the - // texture - spancountminus1 = (float)(spancount - 1); + } else { + // calculate s/z, t/z, zi->fixed s and t at last pixel in + // span (so + // can't step off polygon), clamp, calculate s and t steps + // across + // span by division, biasing steps low so we don't run off + // the + // texture + spancountminus1 = (float) (spancount - 1); sdivz += d_sdivzstepu * spancountminus1; tdivz += d_tdivzstepu * spancountminus1; zi += d_zistepu * spancountminus1; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point - snext = (int)(sdivz * z) + sadjust; + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point + snext = (int) (sdivz * z) + sadjust; if (snext > bbextents) snext = bbextents; else if (snext < 8) - snext = 8; // prevent round-off error on <0 steps from - // from causing overstepping & running off the - // edge of the texture + snext = 8; // prevent round-off error on <0 + // steps from + // from causing overstepping & running off the + // edge of the texture - tnext = (int)(tdivz * z) + tadjust; + tnext = (int) (tdivz * z) + tadjust; if (tnext > bbextentt) tnext = bbextentt; else if (tnext < 8) - tnext = 8; // guard against round-off error on <0 steps + tnext = 8; // guard against round-off error on + // <0 steps - if (spancount > 1) - { + if (spancount > 1) { sstep = (snext - s) / (spancount - 1); tstep = (tnext - t) / (spancount - 1); } } - do - { + do { *pdest++ = *(pbase + (s >> 16) + (t >> 16) * cachewidth); s += sstep; t += tstep; @@ -397,55 +401,52 @@ void D_DrawSpans8 (espan_t *pspan) D_DrawZSpans ============= */ -void D_DrawZSpans (espan_t *pspan) +void +D_DrawZSpans (espan_t *pspan) { - int count, doublecount, izistep; - int izi; - short *pdest; - unsigned int ltemp; - double zi; - float du, dv; + int count, doublecount, izistep; + int izi; + short *pdest; + unsigned int ltemp; + double zi; + float du, dv; // FIXME: check for clamping/range problems // we count on FP exceptions being turned off to avoid range problems - izistep = (int)(d_zistepu * 0x8000 * 0x10000); + izistep = (int) (d_zistepu * 0x8000 * 0x10000); - do - { + do { pdest = d_pzbuffer + (d_zwidth * pspan->v) + pspan->u; count = pspan->count; - // calculate the initial 1/z - du = (float)pspan->u; - dv = (float)pspan->v; + // calculate the initial 1/z + du = (float) pspan->u; + dv = (float) pspan->v; - zi = d_ziorigin + dv*d_zistepv + du*d_zistepu; - // we count on FP exceptions being turned off to avoid range problems - izi = (int)(zi * 0x8000 * 0x10000); + zi = d_ziorigin + dv * d_zistepv + du * d_zistepu; + // we count on FP exceptions being turned off to avoid range problems + izi = (int) (zi * 0x8000 * 0x10000); - if ((long)pdest & 0x02) - { - *pdest++ = (short)(izi >> 16); + if ((long) pdest & 0x02) { + *pdest++ = (short) (izi >> 16); izi += izistep; count--; } - if ((doublecount = count >> 1) > 0) - { - do - { + if ((doublecount = count >> 1) > 0) { + do { ltemp = izi >> 16; izi += izistep; ltemp |= izi & 0xFFFF0000; izi += izistep; - *(int *)pdest = ltemp; + *(int *) pdest = ltemp; pdest += 2; } while (--doublecount > 0); } if (count & 1) - *pdest = (short)(izi >> 16); + *pdest = (short) (izi >> 16); } while ((pspan = pspan->pnext) != NULL); } diff --git a/source/d_sky.c b/source/d_sky.c index 53b7762..96b02f2 100644 --- a/source/d_sky.c +++ b/source/d_sky.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" #include "d_local.h" @@ -41,28 +41,30 @@ D_Sky_uv_To_st ================= */ -void D_Sky_uv_To_st (int u, int v, fixed16_t *s, fixed16_t *t) +void +D_Sky_uv_To_st (int u, int v, fixed16_t *s, fixed16_t *t) { - float wu, wv, temp; - vec3_t end; + float wu, wv, temp; + vec3_t end; if (r_refdef.vrect.width >= r_refdef.vrect.height) - temp = (float)r_refdef.vrect.width; + temp = (float) r_refdef.vrect.width; else - temp = (float)r_refdef.vrect.height; + temp = (float) r_refdef.vrect.height; - wu = 8192.0 * (float)(u-((int)vid.width>>1)) / temp; - wv = 8192.0 * (float)(((int)vid.height>>1)-v) / temp; + wu = 8192.0 * (float) (u - ((int) vid.width >> 1)) / temp; + wv = 8192.0 * (float) (((int) vid.height >> 1) - v) / temp; - end[0] = 4096*vpn[0] + wu*vright[0] + wv*vup[0]; - end[1] = 4096*vpn[1] + wu*vright[1] + wv*vup[1]; - end[2] = 4096*vpn[2] + wu*vright[2] + wv*vup[2]; + end[0] = 4096 * vpn[0] + wu * vright[0] + wv * vup[0]; + end[1] = 4096 * vpn[1] + wu * vright[1] + wv * vup[1]; + end[2] = 4096 * vpn[2] + wu * vright[2] + wv * vup[2]; end[2] *= 3; VectorNormalize (end); - temp = skytime*skyspeed; // TODO: add D_SetupFrame & set this there - *s = (int)((temp + 6*(SKYSIZE/2-1)*end[0]) * 0x10000); - *t = (int)((temp + 6*(SKYSIZE/2-1)*end[1]) * 0x10000); + temp = skytime * skyspeed; // TODO: add D_SetupFrame & set this + // there + *s = (int) ((temp + 6 * (SKYSIZE / 2 - 1) * end[0]) * 0x10000); + *t = (int) ((temp + 6 * (SKYSIZE / 2 - 1) * end[1]) * 0x10000); } @@ -71,30 +73,29 @@ void D_Sky_uv_To_st (int u, int v, fixed16_t *s, fixed16_t *t) D_DrawSkyScans8 ================= */ -void D_DrawSkyScans8 (espan_t *pspan) +void +D_DrawSkyScans8 (espan_t *pspan) { - int count, spancount, u, v; - unsigned char *pdest; - fixed16_t s, t, snext, tnext, sstep, tstep; - int spancountminus1; + int count, spancount, u, v; + unsigned char *pdest; + fixed16_t s, t, snext, tnext, sstep, tstep; + int spancountminus1; - sstep = 0; // keep compiler happy - tstep = 0; // ditto + sstep = 0; // keep compiler happy + tstep = 0; // ditto - do - { - pdest = (unsigned char *)((byte *)d_viewbuffer + - (screenwidth * pspan->v) + pspan->u); + do { + pdest = (unsigned char *) ((byte *) d_viewbuffer + + (screenwidth * pspan->v) + pspan->u); count = pspan->count; - // calculate the initial s & t + // calculate the initial s & t u = pspan->u; v = pspan->v; D_Sky_uv_To_st (u, v, &s, &t); - do - { + do { if (count >= SKY_SPAN_MAX) spancount = SKY_SPAN_MAX; else @@ -102,25 +103,21 @@ void D_DrawSkyScans8 (espan_t *pspan) count -= spancount; - if (count) - { + if (count) { u += spancount; - // calculate s and t at far end of span, - // calculate s and t steps across span by shifting + // calculate s and t at far end of span, + // calculate s and t steps across span by shifting D_Sky_uv_To_st (u, v, &snext, &tnext); sstep = (snext - s) >> SKY_SPAN_SHIFT; tstep = (tnext - t) >> SKY_SPAN_SHIFT; - } - else - { - // calculate s and t at last pixel in span, - // calculate s and t steps across span by division - spancountminus1 = (float)(spancount - 1); + } else { + // calculate s and t at last pixel in span, + // calculate s and t steps across span by division + spancountminus1 = (float) (spancount - 1); - if (spancountminus1 > 0) - { + if (spancountminus1 > 0) { u += spancountminus1; D_Sky_uv_To_st (u, v, &snext, &tnext); @@ -129,10 +126,9 @@ void D_DrawSkyScans8 (espan_t *pspan) } } - do - { + do { *pdest++ = r_skysource[((t & R_SKY_TMASK) >> 8) + - ((s & R_SKY_SMASK) >> 16)]; + ((s & R_SKY_SMASK) >> 16)]; s += sstep; t += tstep; } while (--spancount > 0); @@ -144,4 +140,3 @@ void D_DrawSkyScans8 (espan_t *pspan) } while ((pspan = pspan->pnext) != NULL); } - diff --git a/source/d_sprite.c b/source/d_sprite.c index 2207bc0..fb65caf 100644 --- a/source/d_sprite.c +++ b/source/d_sprite.c @@ -27,13 +27,13 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "d_local.h" -static int sprite_height; -static int minindex, maxindex; -static sspan_t *sprite_spans; +static int sprite_height; +static int minindex, maxindex; +static sspan_t *sprite_spans; #ifndef USE_INTEL_ASM @@ -42,19 +42,20 @@ static sspan_t *sprite_spans; D_SpriteDrawSpans ===================== */ -void D_SpriteDrawSpans (sspan_t *pspan) +void +D_SpriteDrawSpans (sspan_t *pspan) { - int count, spancount, izistep; - int izi; - byte *pbase, *pdest; - fixed16_t s, t, snext, tnext, sstep, tstep; - float sdivz, tdivz, zi, z, du, dv, spancountminus1; - float sdivz8stepu, tdivz8stepu, zi8stepu; - byte btemp; - short *pz; + int count, spancount, izistep; + int izi; + byte *pbase, *pdest; + fixed16_t s, t, snext, tnext, sstep, tstep; + float sdivz, tdivz, zi, z, du, dv, spancountminus1; + float sdivz8stepu, tdivz8stepu, zi8stepu; + byte btemp; + short *pz; - sstep = 0; // keep compiler happy - tstep = 0; // ditto + sstep = 0; // keep compiler happy + tstep = 0; // ditto pbase = cacheblock; @@ -63,11 +64,10 @@ void D_SpriteDrawSpans (sspan_t *pspan) zi8stepu = d_zistepu * 8; // we count on FP exceptions being turned off to avoid range problems - izistep = (int)(d_zistepu * 0x8000 * 0x10000); + izistep = (int) (d_zistepu * 0x8000 * 0x10000); - do - { - pdest = (byte *)d_viewbuffer + (screenwidth * pspan->v) + pspan->u; + do { + pdest = (byte *) d_viewbuffer + (screenwidth * pspan->v) + pspan->u; pz = d_pzbuffer + (d_zwidth * pspan->v) + pspan->u; count = pspan->count; @@ -75,32 +75,31 @@ void D_SpriteDrawSpans (sspan_t *pspan) if (count <= 0) goto NextSpan; - // calculate the initial s/z, t/z, 1/z, s, and t and clamp - du = (float)pspan->u; - dv = (float)pspan->v; + // calculate the initial s/z, t/z, 1/z, s, and t and clamp + du = (float) pspan->u; + dv = (float) pspan->v; - sdivz = d_sdivzorigin + dv*d_sdivzstepv + du*d_sdivzstepu; - tdivz = d_tdivzorigin + dv*d_tdivzstepv + du*d_tdivzstepu; - zi = d_ziorigin + dv*d_zistepv + du*d_zistepu; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point - // we count on FP exceptions being turned off to avoid range problems - izi = (int)(zi * 0x8000 * 0x10000); + sdivz = d_sdivzorigin + dv * d_sdivzstepv + du * d_sdivzstepu; + tdivz = d_tdivzorigin + dv * d_tdivzstepv + du * d_tdivzstepu; + zi = d_ziorigin + dv * d_zistepv + du * d_zistepu; + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point + // we count on FP exceptions being turned off to avoid range problems + izi = (int) (zi * 0x8000 * 0x10000); - s = (int)(sdivz * z) + sadjust; + s = (int) (sdivz * z) + sadjust; if (s > bbextents) s = bbextents; else if (s < 0) s = 0; - t = (int)(tdivz * z) + tadjust; + t = (int) (tdivz * z) + tadjust; if (t > bbextentt) t = bbextentt; else if (t < 0) t = 0; - do - { - // calculate s and t at the far end of the span + do { + // calculate s and t at the far end of the span if (count >= 8) spancount = 8; else @@ -108,71 +107,71 @@ void D_SpriteDrawSpans (sspan_t *pspan) count -= spancount; - if (count) - { - // calculate s/z, t/z, zi->fixed s and t at far end of span, - // calculate s and t steps across span by shifting + if (count) { + // calculate s/z, t/z, zi->fixed s and t at far end of span, + // calculate s and t steps across span by shifting sdivz += sdivz8stepu; tdivz += tdivz8stepu; zi += zi8stepu; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point - snext = (int)(sdivz * z) + sadjust; + snext = (int) (sdivz * z) + sadjust; if (snext > bbextents) snext = bbextents; else if (snext < 8) - snext = 8; // prevent round-off error on <0 steps from - // from causing overstepping & running off the - // edge of the texture + snext = 8; // prevent round-off error on <0 + // steps from + // from causing overstepping & running off the + // edge of the texture - tnext = (int)(tdivz * z) + tadjust; + tnext = (int) (tdivz * z) + tadjust; if (tnext > bbextentt) tnext = bbextentt; else if (tnext < 8) - tnext = 8; // guard against round-off error on <0 steps + tnext = 8; // guard against round-off error on + // <0 steps sstep = (snext - s) >> 3; tstep = (tnext - t) >> 3; - } - else - { - // calculate s/z, t/z, zi->fixed s and t at last pixel in span (so - // can't step off polygon), clamp, calculate s and t steps across - // span by division, biasing steps low so we don't run off the - // texture - spancountminus1 = (float)(spancount - 1); + } else { + // calculate s/z, t/z, zi->fixed s and t at last pixel in + // span (so + // can't step off polygon), clamp, calculate s and t steps + // across + // span by division, biasing steps low so we don't run off + // the + // texture + spancountminus1 = (float) (spancount - 1); sdivz += d_sdivzstepu * spancountminus1; tdivz += d_tdivzstepu * spancountminus1; zi += d_zistepu * spancountminus1; - z = (float)0x10000 / zi; // prescale to 16.16 fixed-point - snext = (int)(sdivz * z) + sadjust; + z = (float) 0x10000 / zi; // prescale to 16.16 fixed-point + snext = (int) (sdivz * z) + sadjust; if (snext > bbextents) snext = bbextents; else if (snext < 8) - snext = 8; // prevent round-off error on <0 steps from - // from causing overstepping & running off the - // edge of the texture + snext = 8; // prevent round-off error on <0 + // steps from + // from causing overstepping & running off the + // edge of the texture - tnext = (int)(tdivz * z) + tadjust; + tnext = (int) (tdivz * z) + tadjust; if (tnext > bbextentt) tnext = bbextentt; else if (tnext < 8) - tnext = 8; // guard against round-off error on <0 steps + tnext = 8; // guard against round-off error on + // <0 steps - if (spancount > 1) - { + if (spancount > 1) { sstep = (snext - s) / (spancount - 1); tstep = (tnext - t) / (spancount - 1); } } - do - { + do { btemp = *(pbase + (s >> 16) + (t >> 16) * cachewidth); - if (btemp != 255) - { - if (*pz <= (izi >> 16)) - { + if (btemp != 255) { + if (*pz <= (izi >> 16)) { *pz = izi >> 16; *pdest = btemp; } @@ -190,7 +189,7 @@ void D_SpriteDrawSpans (sspan_t *pspan) } while (count > 0); -NextSpan: + NextSpan: pspan++; } while (pspan->count != DS_SPAN_LIST_END); @@ -204,13 +203,14 @@ NextSpan: D_SpriteScanLeftEdge ===================== */ -void D_SpriteScanLeftEdge (void) +void +D_SpriteScanLeftEdge (void) { - int i, v, itop, ibottom, lmaxindex; - emitpoint_t *pvert, *pnext; - sspan_t *pspan; - float du, dv, vtop, vbottom, slope; - fixed16_t u, u_step; + int i, v, itop, ibottom, lmaxindex; + emitpoint_t *pvert, *pnext; + sspan_t *pspan; + float du, dv, vtop, vbottom, slope; + fixed16_t u, u_step; pspan = sprite_spans; i = minindex; @@ -223,27 +223,24 @@ void D_SpriteScanLeftEdge (void) vtop = ceil (r_spritedesc.pverts[i].v); - do - { + do { pvert = &r_spritedesc.pverts[i]; pnext = pvert - 1; vbottom = ceil (pnext->v); - if (vtop < vbottom) - { + if (vtop < vbottom) { du = pnext->u - pvert->u; dv = pnext->v - pvert->v; slope = du / dv; - u_step = (int)(slope * 0x10000); - // adjust u to ceil the integer portion - u = (int)((pvert->u + (slope * (vtop - pvert->v))) * 0x10000) + - (0x10000 - 1); - itop = (int)vtop; - ibottom = (int)vbottom; + u_step = (int) (slope * 0x10000); + // adjust u to ceil the integer portion + u = (int) ((pvert->u + (slope * (vtop - pvert->v))) * 0x10000) + + (0x10000 - 1); + itop = (int) vtop; + ibottom = (int) vbottom; - for (v=itop ; vu = u >> 16; pspan->v = v; u += u_step; @@ -266,13 +263,14 @@ void D_SpriteScanLeftEdge (void) D_SpriteScanRightEdge ===================== */ -void D_SpriteScanRightEdge (void) +void +D_SpriteScanRightEdge (void) { - int i, v, itop, ibottom; - emitpoint_t *pvert, *pnext; - sspan_t *pspan; - float du, dv, vtop, vbottom, slope, uvert, unext, vvert, vnext; - fixed16_t u, u_step; + int i, v, itop, ibottom; + emitpoint_t *pvert, *pnext; + sspan_t *pspan; + float du, dv, vtop, vbottom, slope, uvert, unext, vvert, vnext; + fixed16_t u, u_step; pspan = sprite_spans; i = minindex; @@ -285,8 +283,7 @@ void D_SpriteScanRightEdge (void) vtop = ceil (vvert); - do - { + do { pvert = &r_spritedesc.pverts[i]; pnext = pvert + 1; @@ -298,8 +295,7 @@ void D_SpriteScanRightEdge (void) vbottom = ceil (vnext); - if (vtop < vbottom) - { + if (vtop < vbottom) { uvert = pvert->u; if (uvert < r_refdef.fvrectx_adj) uvert = r_refdef.fvrectx_adj; @@ -315,15 +311,14 @@ void D_SpriteScanRightEdge (void) du = unext - uvert; dv = vnext - vvert; slope = du / dv; - u_step = (int)(slope * 0x10000); - // adjust u to ceil the integer portion - u = (int)((uvert + (slope * (vtop - vvert))) * 0x10000) + - (0x10000 - 1); - itop = (int)vtop; - ibottom = (int)vbottom; + u_step = (int) (slope * 0x10000); + // adjust u to ceil the integer portion + u = (int) ((uvert + (slope * (vtop - vvert))) * 0x10000) + + (0x10000 - 1); + itop = (int) vtop; + ibottom = (int) vbottom; - for (v=itop ; vcount = (u >> 16) - pspan->u; u += u_step; pspan++; @@ -348,10 +343,11 @@ void D_SpriteScanRightEdge (void) D_SpriteCalculateGradients ===================== */ -void D_SpriteCalculateGradients (void) +void +D_SpriteCalculateGradients (void) { - vec3_t p_normal, p_saxis, p_taxis, p_temp1; - float distinv; + vec3_t p_normal, p_saxis, p_taxis, p_temp1; + float distinv; TransformVector (r_spritedesc.vpn, p_normal); TransformVector (r_spritedesc.vright, p_saxis); @@ -370,18 +366,18 @@ void D_SpriteCalculateGradients (void) d_zistepv = -p_normal[1] * yscaleinv * distinv; d_sdivzorigin = p_saxis[2] - xcenter * d_sdivzstepu - - ycenter * d_sdivzstepv; + ycenter * d_sdivzstepv; d_tdivzorigin = p_taxis[2] - xcenter * d_tdivzstepu - - ycenter * d_tdivzstepv; + ycenter * d_tdivzstepv; d_ziorigin = p_normal[2] * distinv - xcenter * d_zistepu - - ycenter * d_zistepv; + ycenter * d_zistepv; TransformVector (modelorg, p_temp1); - sadjust = ((fixed16_t)(DotProduct (p_temp1, p_saxis) * 0x10000 + 0.5)) - - (-(cachewidth >> 1) << 16); - tadjust = ((fixed16_t)(DotProduct (p_temp1, p_taxis) * 0x10000 + 0.5)) - - (-(sprite_height >> 1) << 16); + sadjust = ((fixed16_t) (DotProduct (p_temp1, p_saxis) * 0x10000 + 0.5)) - + (-(cachewidth >> 1) << 16); + tadjust = ((fixed16_t) (DotProduct (p_temp1, p_taxis) * 0x10000 + 0.5)) - + (-(sprite_height >> 1) << 16); // -1 (-epsilon) so we never wander off the edge of the texture bbextents = (cachewidth << 16) - 1; @@ -394,12 +390,13 @@ void D_SpriteCalculateGradients (void) D_DrawSprite ===================== */ -void D_DrawSprite (void) +void +D_DrawSprite (void) { - int i, nump; - float ymin, ymax; - emitpoint_t *pverts; - sspan_t spans[MAXHEIGHT+1]; + int i, nump; + float ymin, ymax; + emitpoint_t *pverts; + sspan_t spans[MAXHEIGHT + 1]; sprite_spans = spans; @@ -409,16 +406,13 @@ void D_DrawSprite (void) ymax = -999999.9; pverts = r_spritedesc.pverts; - for (i=0 ; iv < ymin) - { + for (i = 0; i < r_spritedesc.nump; i++) { + if (pverts->v < ymin) { ymin = pverts->v; minindex = i; } - if (pverts->v > ymax) - { + if (pverts->v > ymax) { ymax = pverts->v; maxindex = i; } @@ -430,11 +424,11 @@ void D_DrawSprite (void) ymax = ceil (ymax); if (ymin >= ymax) - return; // doesn't cross any scans at all + return; // doesn't cross any scans at all cachewidth = r_spritedesc.pspriteframe->width; sprite_height = r_spritedesc.pspriteframe->height; - cacheblock = (byte *)&r_spritedesc.pspriteframe->pixels[0]; + cacheblock = (byte *) & r_spritedesc.pspriteframe->pixels[0]; // copy the first vertex to the last vertex, so we don't have to deal with // wrapping @@ -447,4 +441,3 @@ void D_DrawSprite (void) D_SpriteScanRightEdge (); D_SpriteDrawSpans (sprite_spans); } - diff --git a/source/d_surf.c b/source/d_surf.c index d89e6c6..1218752 100644 --- a/source/d_surf.c +++ b/source/d_surf.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "qargs.h" @@ -36,15 +36,15 @@ #include -float surfscale; -qboolean r_cache_thrash; // set if surface cache is thrashing +float surfscale; +qboolean r_cache_thrash; // set if surface cache is thrashing -int sc_size; -surfcache_t *sc_rover, *sc_base; +int sc_size; +surfcache_t *sc_rover, *sc_base; #define GUARDSIZE 4 -void * +void * D_SurfaceCacheAddress (void) { return sc_base; @@ -53,43 +53,44 @@ D_SurfaceCacheAddress (void) int D_SurfaceCacheForRes (int width, int height) { - int size, pix; + int size, pix; - if (COM_CheckParm ("-surfcachesize")) - { - size = atoi(com_argv[COM_CheckParm("-surfcachesize")+1]) * 1024; + if (COM_CheckParm ("-surfcachesize")) { + size = atoi (com_argv[COM_CheckParm ("-surfcachesize") + 1]) * 1024; return size; } - + size = SURFCACHE_SIZE_AT_320X200; - pix = width*height; + pix = width * height; if (pix > 64000) - size += (pix-64000)*3; - + size += (pix - 64000) * 3; + return size; } -void D_CheckCacheGuard (void) +void +D_CheckCacheGuard (void) { - byte *s; - int i; + byte *s; + int i; - s = (byte *)sc_base + sc_size; - for (i=0 ; inext = NULL; sc_base->owner = NULL; sc_base->size = sc_size; - + D_ClearCacheGuard (); } @@ -121,19 +123,19 @@ void D_InitCaches (void *buffer, int size) D_FlushCaches ================== */ -void D_FlushCaches (void) +void +D_FlushCaches (void) { - surfcache_t *c; - + surfcache_t *c; + if (!sc_base) return; - for (c = sc_base ; c ; c = c->next) - { + for (c = sc_base; c; c = c->next) { if (c->owner) *c->owner = NULL; } - + sc_rover = sc_base; sc_base->next = NULL; sc_base->owner = NULL; @@ -145,89 +147,82 @@ void D_FlushCaches (void) D_SCAlloc ================= */ -surfcache_t *D_SCAlloc (int width, int size) +surfcache_t * +D_SCAlloc (int width, int size) { - surfcache_t *new; - qboolean wrapped_this_time; + surfcache_t *new; + qboolean wrapped_this_time; if ((width < 0) || (width > 256)) Sys_Error ("D_SCAlloc: bad cache width %d\n", width); if ((size <= 0) || (size > 0x10000)) Sys_Error ("D_SCAlloc: bad cache size %d\n", size); - + /* This adds the offset of data[0] in the surfcache_t struct. */ - size += (int)((surfcache_t *)0)->data; + size += (int) ((surfcache_t *) 0)->data; #define SIZE_ALIGN (sizeof(surfcache_t*)-1) size = (size + SIZE_ALIGN) & ~SIZE_ALIGN; #undef SIZE_ALIGN size = (size + 3) & ~3; if (size > sc_size) - Sys_Error ("D_SCAlloc: %i > cache size",size); + Sys_Error ("D_SCAlloc: %i > cache size", size); // if there is not size bytes after the rover, reset to the start wrapped_this_time = false; - if ( !sc_rover || (byte *)sc_rover - (byte *)sc_base > sc_size - size) - { - if (sc_rover) - { + if (!sc_rover || (byte *) sc_rover - (byte *) sc_base > sc_size - size) { + if (sc_rover) { wrapped_this_time = true; } sc_rover = sc_base; } - // colect and free surfcache_t blocks until the rover block is large enough new = sc_rover; if (sc_rover->owner) *sc_rover->owner = NULL; - - while (new->size < size) - { - // free another + + while (new->size < size) { + // free another sc_rover = sc_rover->next; if (!sc_rover) Sys_Error ("D_SCAlloc: hit the end of memory"); if (sc_rover->owner) *sc_rover->owner = NULL; - + new->size += sc_rover->size; new->next = sc_rover->next; } // create a fragment out of any leftovers - if (new->size - size > 256) - { - sc_rover = (surfcache_t *)( (byte *)new + size); + if (new->size - size > 256) { + sc_rover = (surfcache_t *) ((byte *) new + size); sc_rover->size = new->size - size; sc_rover->next = new->next; sc_rover->width = 0; sc_rover->owner = NULL; new->next = sc_rover; new->size = size; - } - else + } else sc_rover = new->next; - + new->width = width; // DEBUG if (width > 0) - new->height = (size - sizeof(*new) + sizeof(new->data)) / width; + new->height = (size - sizeof (*new) + sizeof (new->data)) / width; - new->owner = NULL; // should be set properly after return + new->owner = NULL; // should be set properly after + // return - if (d_roverwrapped) - { + if (d_roverwrapped) { if (wrapped_this_time || (sc_rover >= d_initial_rover)) r_cache_thrash = true; - } - else if (wrapped_this_time) - { + } else if (wrapped_this_time) { d_roverwrapped = true; } -D_CheckCacheGuard (); // DEBUG + D_CheckCacheGuard (); // DEBUG return new; } @@ -237,15 +232,15 @@ D_CheckCacheGuard (); // DEBUG D_SCDump ================= */ -void D_SCDump (void) +void +D_SCDump (void) { - surfcache_t *test; + surfcache_t *test; - for (test = sc_base ; test ; test = test->next) - { + for (test = sc_base; test; test = test->next) { if (test == sc_rover) Sys_Printf ("ROVER:\n"); - printf ("%p : %i bytes %i width\n",test, test->size, test->width); + printf ("%p : %i bytes %i width\n", test, test->size, test->width); } } @@ -253,26 +248,28 @@ void D_SCDump (void) // if the num is not a power of 2, assume it will not repeat -int MaskForNum (int num) +int +MaskForNum (int num) { - if (num==128) + if (num == 128) return 127; - if (num==64) + if (num == 64) return 63; - if (num==32) + if (num == 32) return 31; - if (num==16) + if (num == 16) return 15; return 255; } -int D_log2 (int num) +int +D_log2 (int num) { - int c; - + int c; + c = 0; - - while (num>>=1) + + while (num >>= 1) c++; return c; } @@ -284,9 +281,10 @@ int D_log2 (int num) D_CacheSurface ================ */ -surfcache_t *D_CacheSurface (msurface_t *surface, int miplevel) +surfcache_t * +D_CacheSurface (msurface_t *surface, int miplevel) { - surfcache_t *cache; + surfcache_t *cache; // // if the surface is animating or flashing, flush the cache @@ -296,33 +294,34 @@ surfcache_t *D_CacheSurface (msurface_t *surface, int miplevel) r_drawsurf.lightadj[1] = d_lightstylevalue[surface->styles[1]]; r_drawsurf.lightadj[2] = d_lightstylevalue[surface->styles[2]]; r_drawsurf.lightadj[3] = d_lightstylevalue[surface->styles[3]]; - + // // see if the cache holds apropriate data // cache = surface->cachespots[miplevel]; if (cache && !cache->dlight && surface->dlightframe != r_framecount - && cache->texture == r_drawsurf.texture - && cache->lightadj[0] == r_drawsurf.lightadj[0] - && cache->lightadj[1] == r_drawsurf.lightadj[1] - && cache->lightadj[2] == r_drawsurf.lightadj[2] - && cache->lightadj[3] == r_drawsurf.lightadj[3] ) + && cache->texture == r_drawsurf.texture + && cache->lightadj[0] == r_drawsurf.lightadj[0] + && cache->lightadj[1] == r_drawsurf.lightadj[1] + && cache->lightadj[2] == r_drawsurf.lightadj[2] + && cache->lightadj[3] == r_drawsurf.lightadj[3]) return cache; // // determine shape of surface // - surfscale = 1.0 / (1<extents[0] >> miplevel; r_drawsurf.rowbytes = r_drawsurf.surfwidth; r_drawsurf.surfheight = surface->extents[1] >> miplevel; - + // // allocate memory if needed // - if (!cache) // if a texture just animated, don't reallocate it + if (!cache) // if a texture just animated, don't + // reallocate it { cache = D_SCAlloc (r_drawsurf.surfwidth, r_drawsurf.surfwidth * r_drawsurf.surfheight); @@ -330,14 +329,14 @@ surfcache_t *D_CacheSurface (msurface_t *surface, int miplevel) cache->owner = &surface->cachespots[miplevel]; cache->mipscale = surfscale; } - + if (surface->dlightframe == r_framecount) cache->dlight = 1; else cache->dlight = 0; - r_drawsurf.surfdat = (pixel_t *)cache->data; - + r_drawsurf.surfdat = (pixel_t *) cache->data; + cache->texture = r_drawsurf.texture; cache->lightadj[0] = r_drawsurf.lightadj[0]; cache->lightadj[1] = r_drawsurf.lightadj[1]; @@ -354,5 +353,3 @@ surfcache_t *D_CacheSurface (msurface_t *surface, int miplevel) return surface->cachespots[miplevel]; } - - diff --git a/source/d_vars.c b/source/d_vars.c index dac7bed..6e99b3e 100644 --- a/source/d_vars.c +++ b/source/d_vars.c @@ -29,7 +29,7 @@ #ifndef USE_INTEL_ASM #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -44,18 +44,17 @@ // FIXME: make into one big structure, like cl or sv // FIXME: do separately for refresh engine and driver -float d_sdivzstepu, d_tdivzstepu, d_zistepu; -float d_sdivzstepv, d_tdivzstepv, d_zistepv; -float d_sdivzorigin, d_tdivzorigin, d_ziorigin; +float d_sdivzstepu, d_tdivzstepu, d_zistepu; +float d_sdivzstepv, d_tdivzstepv, d_zistepv; +float d_sdivzorigin, d_tdivzorigin, d_ziorigin; -fixed16_t sadjust, tadjust, bbextents, bbextentt; +fixed16_t sadjust, tadjust, bbextents, bbextentt; -pixel_t *cacheblock; -int cachewidth; -pixel_t *d_viewbuffer; -short *d_pzbuffer; -unsigned int d_zrowbytes; -unsigned int d_zwidth; - -#endif // !USE_INTEL_ASM +pixel_t *cacheblock; +int cachewidth; +pixel_t *d_viewbuffer; +short *d_pzbuffer; +unsigned int d_zrowbytes; +unsigned int d_zwidth; +#endif // !USE_INTEL_ASM diff --git a/source/d_zpoint.c b/source/d_zpoint.c index a34611c..b8308d6 100644 --- a/source/d_zpoint.c +++ b/source/d_zpoint.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "d_local.h" @@ -37,20 +37,19 @@ D_DrawZPoint ===================== */ -void D_DrawZPoint (void) +void +D_DrawZPoint (void) { - byte *pdest; - short *pz; - int izi; - + byte *pdest; + short *pz; + int izi; + pz = d_pzbuffer + (d_zwidth * r_zpointdesc.v) + r_zpointdesc.u; pdest = d_viewbuffer + d_scantable[r_zpointdesc.v] + r_zpointdesc.u; - izi = (int)(r_zpointdesc.zi * 0x8000); + izi = (int) (r_zpointdesc.zi * 0x8000); - if (*pz <= izi) - { + if (*pz <= izi) { *pz = izi; *pdest = r_zpointdesc.color; } } - diff --git a/source/dga_check.c b/source/dga_check.c index 2ff83ff..b238430 100644 --- a/source/dga_check.c +++ b/source/dga_check.c @@ -29,7 +29,7 @@ */ #ifdef HAVE_CONFIG_H -#include "config.h" +# include "config.h" #endif #include @@ -51,23 +51,26 @@ Check for the presence of the XFree86-DGA X server extension */ qboolean -VID_CheckDGA (Display *dpy, int *maj_ver, int *min_ver, int *hasvideo) +VID_CheckDGA (Display * dpy, int *maj_ver, int *min_ver, int *hasvideo) { #ifdef HAVE_DGA - int event_base, error_base, dgafeat, dummy; + int event_base, error_base, dgafeat, dummy; if (!XF86DGAQueryExtension (dpy, &event_base, &error_base)) { return false; } - if (!maj_ver) maj_ver = &dummy; - if (!min_ver) min_ver = &dummy; + if (!maj_ver) + maj_ver = &dummy; + if (!min_ver) + min_ver = &dummy; if (!XF86DGAQueryVersion (dpy, maj_ver, min_ver)) { return false; } - if (!hasvideo) hasvideo = &dummy; + if (!hasvideo) + hasvideo = &dummy; if (!XF86DGAQueryDirectVideo (dpy, DefaultScreen (dpy), &dgafeat)) { *hasvideo = 0; @@ -78,7 +81,7 @@ VID_CheckDGA (Display *dpy, int *maj_ver, int *min_ver, int *hasvideo) return true; #else return false; -#endif // HAVE_DGA +#endif // HAVE_DGA } @@ -88,25 +91,27 @@ VID_CheckDGA (Display *dpy, int *maj_ver, int *min_ver, int *hasvideo) Check for the presence of the XFree86-VidMode X server extension */ qboolean -VID_CheckVMode (Display *dpy, int *maj_ver, int *min_ver) +VID_CheckVMode (Display * dpy, int *maj_ver, int *min_ver) { #if defined(HAVE_VIDMODE) - int event_base, error_base; - int dummy; + int event_base, error_base; + int dummy; - if (! XF86VidModeQueryExtension(dpy, &event_base, &error_base)) { + if (!XF86VidModeQueryExtension (dpy, &event_base, &error_base)) { return false; } - if (maj_ver == NULL) maj_ver = &dummy; - if (min_ver == NULL) min_ver = &dummy; + if (maj_ver == NULL) + maj_ver = &dummy; + if (min_ver == NULL) + min_ver = &dummy; - if (! XF86VidModeQueryVersion(dpy, maj_ver, min_ver)) { + if (!XF86VidModeQueryVersion (dpy, maj_ver, min_ver)) { return false; } return true; #else return false; -#endif // HAVE_VIDMODE +#endif // HAVE_VIDMODE } diff --git a/source/dirent.c b/source/dirent.c index edd9a9e..b8109a7 100644 --- a/source/dirent.c +++ b/source/dirent.c @@ -33,82 +33,76 @@ * Returns a pointer to a DIR structure appropriately filled in to begin * searching a directory. */ -DIR * +DIR * opendir (const char *szPath) { - DIR *nd; - struct _stat statDir; + DIR *nd; + struct _stat statDir; - errno = 0; + errno = 0; - if (!szPath) - { - errno = EFAULT; - return (DIR *) 0; - } + if (!szPath) { + errno = EFAULT; + return (DIR *) 0; + } - if (szPath[0] == '\0') - { - errno = ENOTDIR; - return (DIR *) 0; - } + if (szPath[0] == '\0') { + errno = ENOTDIR; + return (DIR *) 0; + } - /* Attempt to determine if the given path really is a directory. */ - if (_stat (szPath, &statDir)) - { - /* Error, stat should have set an error value. */ - return (DIR *) 0; - } + /* Attempt to determine if the given path really is a directory. */ + if (_stat (szPath, &statDir)) { + /* Error, stat should have set an error value. */ + return (DIR *) 0; + } - if (!S_ISDIR (statDir.st_mode)) - { - /* Error, stat reports not a directory. */ - errno = ENOTDIR; - return (DIR *) 0; - } + if (!S_ISDIR (statDir.st_mode)) { + /* Error, stat reports not a directory. */ + errno = ENOTDIR; + return (DIR *) 0; + } - /* Allocate enough space to store DIR structure and the complete - * directory path given. */ - nd = (DIR *) calloc (1, sizeof (DIR) + strlen (szPath) + strlen (SLASH) + - strlen (SUFFIX)); + /* Allocate enough space to store DIR structure and the complete * + directory path given. */ + nd = (DIR *) calloc (1, sizeof (DIR) + strlen (szPath) + strlen (SLASH) + + strlen (SUFFIX)); - if (!nd) - { - /* Error, out of memory. */ - errno = ENOMEM; - return (DIR *) 0; - } + if (!nd) { + /* Error, out of memory. */ + errno = ENOMEM; + return (DIR *) 0; + } - /* Create the search expression. */ - strcpy (nd->dd_name, szPath); + /* Create the search expression. */ + strcpy (nd->dd_name, szPath); - /* Add on a slash if the path does not end with one. */ - if (nd->dd_name[0] != '\0' && - nd->dd_name[strlen (nd->dd_name) - 1] != '/' && - nd->dd_name[strlen (nd->dd_name) - 1] != '\\') - { - strcat (nd->dd_name, SLASH); - } + /* Add on a slash if the path does not end with one. */ + if (nd->dd_name[0] != '\0' && + nd->dd_name[strlen (nd->dd_name) - 1] != '/' && + nd->dd_name[strlen (nd->dd_name) - 1] != '\\') { + strcat (nd->dd_name, SLASH); + } - /* Add on the search pattern */ - strcat (nd->dd_name, SUFFIX); + /* Add on the search pattern */ + strcat (nd->dd_name, SUFFIX); - /* Initialize handle to -1 so that a premature closedir doesn't try - * to call _findclose on it. */ - nd->dd_handle = -1; + /* Initialize handle to -1 so that a premature closedir doesn't try * to + call _findclose on it. */ + nd->dd_handle = -1; - /* Initialize the status. */ - nd->dd_stat = 0; + /* Initialize the status. */ + nd->dd_stat = 0; - /* Initialize the dirent structure. ino and reclen are invalid under - * Win32, and name simply points at the appropriate part of the - * findfirst_t structure. */ - nd->dd_dir.d_ino = 0; - nd->dd_dir.d_reclen = 0; - nd->dd_dir.d_namlen = 0; - nd->dd_dir.d_name = nd->dd_dta.name; + /* Initialize the dirent structure. ino and reclen are invalid under * + Win32, and name simply points at the appropriate part of the * + findfirst_t structure. */ + nd->dd_dir.d_ino = 0; + nd->dd_dir.d_reclen = 0; + nd->dd_dir.d_namlen = 0; + nd->dd_dir.d_name = nd->dd_dta.name; - return nd; + return nd; } @@ -121,73 +115,56 @@ opendir (const char *szPath) struct dirent * readdir (DIR * dirp) { - errno = 0; + errno = 0; - /* Check for valid DIR struct. */ - if (!dirp) - { - errno = EFAULT; - return (struct dirent *) 0; - } - - if (dirp->dd_dir.d_name != dirp->dd_dta.name) - { - /* The structure does not seem to be set up correctly. */ - errno = EINVAL; - return (struct dirent *) 0; - } - - if (dirp->dd_stat < 0) - { - /* We have already returned all files in the directory - * (or the structure has an invalid dd_stat). */ - return (struct dirent *) 0; - } - else if (dirp->dd_stat == 0) - { - /* We haven't started the search yet. */ - /* Start the search */ - dirp->dd_handle = _findfirst (dirp->dd_name, &(dirp->dd_dta)); - - if (dirp->dd_handle == -1) - { - /* Whoops! Seems there are no files in that - * directory. */ - dirp->dd_stat = -1; + /* Check for valid DIR struct. */ + if (!dirp) { + errno = EFAULT; + return (struct dirent *) 0; } - else - { - dirp->dd_stat = 1; - } - } - else - { - /* Get the next search entry. */ - if (_findnext (dirp->dd_handle, &(dirp->dd_dta))) - { - /* We are off the end or otherwise error. */ - _findclose (dirp->dd_handle); - dirp->dd_handle = -1; - dirp->dd_stat = -1; - } - else - { - /* Update the status to indicate the correct - * number. */ - dirp->dd_stat++; - } - } - if (dirp->dd_stat > 0) - { - /* Successfully got an entry. Everything about the file is - * already appropriately filled in except the length of the - * file name. */ - dirp->dd_dir.d_namlen = strlen (dirp->dd_dir.d_name); - return &dirp->dd_dir; - } + if (dirp->dd_dir.d_name != dirp->dd_dta.name) { + /* The structure does not seem to be set up correctly. */ + errno = EINVAL; + return (struct dirent *) 0; + } - return (struct dirent *) 0; + if (dirp->dd_stat < 0) { + /* We have already returned all files in the directory * (or the + structure has an invalid dd_stat). */ + return (struct dirent *) 0; + } else if (dirp->dd_stat == 0) { + /* We haven't started the search yet. */ + /* Start the search */ + dirp->dd_handle = _findfirst (dirp->dd_name, &(dirp->dd_dta)); + + if (dirp->dd_handle == -1) { + /* Whoops! Seems there are no files in that * directory. */ + dirp->dd_stat = -1; + } else { + dirp->dd_stat = 1; + } + } else { + /* Get the next search entry. */ + if (_findnext (dirp->dd_handle, &(dirp->dd_dta))) { + /* We are off the end or otherwise error. */ + _findclose (dirp->dd_handle); + dirp->dd_handle = -1; + dirp->dd_stat = -1; + } else { + /* Update the status to indicate the correct * number. */ + dirp->dd_stat++; + } + } + + if (dirp->dd_stat > 0) { + /* Successfully got an entry. Everything about the file is * already + appropriately filled in except the length of the * file name. */ + dirp->dd_dir.d_namlen = strlen (dirp->dd_dir.d_name); + return &dirp->dd_dir; + } + + return (struct dirent *) 0; } @@ -199,26 +176,24 @@ readdir (DIR * dirp) int closedir (DIR * dirp) { - int rc; + int rc; - errno = 0; - rc = 0; + errno = 0; + rc = 0; - if (!dirp) - { - errno = EFAULT; - return -1; - } + if (!dirp) { + errno = EFAULT; + return -1; + } - if (dirp->dd_handle != -1) - { - rc = _findclose (dirp->dd_handle); - } + if (dirp->dd_handle != -1) { + rc = _findclose (dirp->dd_handle); + } - /* Delete the dir structure. */ - free (dirp); + /* Delete the dir structure. */ + free (dirp); - return rc; + return rc; } /* @@ -230,21 +205,19 @@ closedir (DIR * dirp) void rewinddir (DIR * dirp) { - errno = 0; + errno = 0; - if (!dirp) - { - errno = EFAULT; - return; - } + if (!dirp) { + errno = EFAULT; + return; + } - if (dirp->dd_handle != -1) - { - _findclose (dirp->dd_handle); - } + if (dirp->dd_handle != -1) { + _findclose (dirp->dd_handle); + } - dirp->dd_handle = -1; - dirp->dd_stat = 0; + dirp->dd_handle = -1; + dirp->dd_stat = 0; } /* @@ -256,14 +229,13 @@ rewinddir (DIR * dirp) long telldir (DIR * dirp) { - errno = 0; + errno = 0; - if (!dirp) - { - errno = EFAULT; - return -1; - } - return dirp->dd_stat; + if (!dirp) { + errno = EFAULT; + return -1; + } + return dirp->dd_stat; } /* @@ -278,36 +250,28 @@ telldir (DIR * dirp) void seekdir (DIR * dirp, long lPos) { - errno = 0; + errno = 0; - if (!dirp) - { - errno = EFAULT; - return; - } - - if (lPos < -1) - { - /* Seeking to an invalid position. */ - errno = EINVAL; - return; - } - else if (lPos == -1) - { - /* Seek past end. */ - if (dirp->dd_handle != -1) - { - _findclose (dirp->dd_handle); + if (!dirp) { + errno = EFAULT; + return; } - dirp->dd_handle = -1; - dirp->dd_stat = -1; - } - else - { - /* Rewind and read forward to the appropriate index. */ - rewinddir (dirp); - while ((dirp->dd_stat < lPos) && readdir (dirp)) - ; - } + if (lPos < -1) { + /* Seeking to an invalid position. */ + errno = EINVAL; + return; + } else if (lPos == -1) { + /* Seek past end. */ + if (dirp->dd_handle != -1) { + _findclose (dirp->dd_handle); + } + dirp->dd_handle = -1; + dirp->dd_stat = -1; + } else { + /* Rewind and read forward to the appropriate index. */ + rewinddir (dirp); + + while ((dirp->dd_stat < lPos) && readdir (dirp)); + } } diff --git a/source/draw.c b/source/draw.c index 115f131..305cd45 100644 --- a/source/draw.c +++ b/source/draw.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "draw.h" @@ -41,36 +41,36 @@ #include typedef struct { - vrect_t rect; - int width; - int height; - byte *ptexbytes; - int rowbytes; + vrect_t rect; + int width; + int height; + byte *ptexbytes; + int rowbytes; } rectdesc_t; -static rectdesc_t r_rectdesc; +static rectdesc_t r_rectdesc; -byte *draw_chars; // 8*8 graphic characters -qpic_t *draw_disc; -qpic_t *draw_backtile; +byte *draw_chars; // 8*8 graphic characters +qpic_t *draw_disc; +qpic_t *draw_backtile; -cvar_t *cl_verstring; +cvar_t *cl_verstring; //============================================================================= /* Support Routines */ -typedef struct cachepic_s -{ - char name[MAX_QPATH]; - cache_user_t cache; +typedef struct cachepic_s { + char name[MAX_QPATH]; + cache_user_t cache; } cachepic_t; #define MAX_CACHED_PICS 128 -cachepic_t menu_cachepics[MAX_CACHED_PICS]; -int menu_numcachepics; +cachepic_t menu_cachepics[MAX_CACHED_PICS]; +int menu_numcachepics; -qpic_t *Draw_PicFromWad (char *name) +qpic_t * +Draw_PicFromWad (char *name) { return W_GetLumpName (name); } @@ -90,18 +90,18 @@ Draw_ClearCache (void) Draw_CachePic ================ */ -qpic_t *Draw_CachePic (char *path) +qpic_t * +Draw_CachePic (char *path) { - cachepic_t *pic; - int i; - qpic_t *dat; - - for (pic=menu_cachepics, i=0 ; iname)) break; - if (i == menu_numcachepics) - { + if (i == menu_numcachepics) { if (menu_numcachepics == MAX_CACHED_PICS) Sys_Error ("menu_numcachepics == MAX_CACHED_PICS"); menu_numcachepics++; @@ -117,10 +117,9 @@ qpic_t *Draw_CachePic (char *path) // load the pic from disk // COM_LoadCacheFile (path, &pic->cache); - - dat = (qpic_t *)pic->cache.data; - if (!dat) - { + + dat = (qpic_t *) pic->cache.data; + if (!dat) { Sys_Error ("Draw_CachePic: failed to load %s", path); } @@ -136,7 +135,8 @@ qpic_t *Draw_CachePic (char *path) Draw_Init =============== */ -void Draw_Init (void) +void +Draw_Init (void) { draw_chars = W_GetLumpName ("conchars"); draw_disc = W_GetLumpName ("disc"); @@ -147,10 +147,12 @@ void Draw_Init (void) r_rectdesc.ptexbytes = draw_backtile->data; r_rectdesc.rowbytes = draw_backtile->width; - cl_verstring = Cvar_Get("cl_verstring", PROGRAM " " VERSION, CVAR_NONE, "None"); + cl_verstring = + Cvar_Get ("cl_verstring", PROGRAM " " VERSION, CVAR_NONE, "None"); } -void Draw_Init_Cvars (void) +void +Draw_Init_Cvars (void) { } @@ -164,44 +166,41 @@ It can be clipped to the top of the screen to allow the console to be smoothly scrolled off. ================ */ -void Draw_Character8 (int x, int y, int num) +void +Draw_Character8 (int x, int y, int num) { - byte *dest; - byte *source; - unsigned short *pusdest; - int drawline; - int row, col; + byte *dest; + byte *source; + unsigned short *pusdest; + int drawline; + int row, col; num &= 255; - + if (y <= -8) - return; // totally off screen + return; // totally off screen if (y > vid.height - 8 || x < 0 || x > vid.width - 8) return; if (num < 0 || num > 255) return; - row = num>>4; - col = num&15; - source = draw_chars + (row<<10) + (col<<3); + row = num >> 4; + col = num & 15; + source = draw_chars + (row << 10) + (col << 3); - if (y < 0) - { // clipped + if (y < 0) { // clipped drawline = 8 + y; - source -= 128*y; + source -= 128 * y; y = 0; - } - else + } else drawline = 8; - if (r_pixbytes == 1) - { - dest = vid.conbuffer + y*vid.conrowbytes + x; - - while (drawline--) - { + if (r_pixbytes == 1) { + dest = vid.conbuffer + y * vid.conrowbytes + x; + + while (drawline--) { if (source[0]) dest[0] = source[0]; if (source[1]) @@ -221,15 +220,12 @@ void Draw_Character8 (int x, int y, int num) source += 128; dest += vid.conrowbytes; } - } - else - { - // FIXME: pre-expand to native format? + } else { + // FIXME: pre-expand to native format? pusdest = (unsigned short *) - ((byte *)vid.conbuffer + y*vid.conrowbytes + (x<<1)); + ((byte *) vid.conbuffer + y * vid.conrowbytes + (x << 1)); - while (drawline--) - { + while (drawline--) { if (source[0]) pusdest[0] = d_8to16table[source[0]]; if (source[1]) @@ -258,10 +254,10 @@ void Draw_Character8 (int x, int y, int num) Draw_String8 ================ */ -void Draw_String8 (int x, int y, char *str) +void +Draw_String8 (int x, int y, char *str) { - while (*str) - { + while (*str) { Draw_Character8 (x, y, *str); str++; x += 8; @@ -273,58 +269,57 @@ void Draw_String8 (int x, int y, char *str) Draw_AltString8 ================ */ -void Draw_AltString8 (int x, int y, char *str) +void +Draw_AltString8 (int x, int y, char *str) { - while (*str) - { + while (*str) { Draw_Character8 (x, y, (*str) | 0x80); str++; x += 8; } } -void Draw_Pixel(int x, int y, byte color) +void +Draw_Pixel (int x, int y, byte color) { - byte *dest; - unsigned short *pusdest; + byte *dest; + unsigned short *pusdest; - if (r_pixbytes == 1) - { - dest = vid.conbuffer + y*vid.conrowbytes + x; + if (r_pixbytes == 1) { + dest = vid.conbuffer + y * vid.conrowbytes + x; *dest = color; - } - else - { - // FIXME: pre-expand to native format? + } else { + // FIXME: pre-expand to native format? pusdest = (unsigned short *) - ((byte *)vid.conbuffer + y*vid.conrowbytes + (x<<1)); + ((byte *) vid.conbuffer + y * vid.conrowbytes + (x << 1)); *pusdest = d_8to16table[color]; } } -void Draw_Crosshair(void) +void +Draw_Crosshair (void) { - int x, y; + int x, y; extern cvar_t *crosshair, *cl_crossx, *cl_crossy, *crosshaircolor; - extern vrect_t scr_vrect; - byte c = crosshaircolor->int_val; + extern vrect_t scr_vrect; + byte c = crosshaircolor->int_val; if (crosshair->int_val == 2) { - x = scr_vrect.x + scr_vrect.width/2 + cl_crossx->int_val; - y = scr_vrect.y + scr_vrect.height/2 + cl_crossy->int_val; - Draw_Pixel(x - 1, y, c); - Draw_Pixel(x - 3, y, c); - Draw_Pixel(x + 1, y, c); - Draw_Pixel(x + 3, y, c); - Draw_Pixel(x, y - 1, c); - Draw_Pixel(x, y - 3, c); - Draw_Pixel(x, y + 1, c); - Draw_Pixel(x, y + 3, c); + x = scr_vrect.x + scr_vrect.width / 2 + cl_crossx->int_val; + y = scr_vrect.y + scr_vrect.height / 2 + cl_crossy->int_val; + Draw_Pixel (x - 1, y, c); + Draw_Pixel (x - 3, y, c); + Draw_Pixel (x + 1, y, c); + Draw_Pixel (x + 3, y, c); + Draw_Pixel (x, y - 1, c); + Draw_Pixel (x, y - 3, c); + Draw_Pixel (x, y + 1, c); + Draw_Pixel (x, y + 3, c); } else if (crosshair->int_val) - Draw_Character8 ( - scr_vrect.x + scr_vrect.width/2-4 + cl_crossx->int_val, - scr_vrect.y + scr_vrect.height/2-4 + cl_crossy->int_val, - '+'); + Draw_Character8 (scr_vrect.x + scr_vrect.width / 2 - 4 + + cl_crossx->int_val, + scr_vrect.y + scr_vrect.height / 2 - 4 + + cl_crossy->int_val, '+'); } /* @@ -332,77 +327,65 @@ void Draw_Crosshair(void) Draw_Pic ============= */ -void Draw_Pic (int x, int y, qpic_t *pic) +void +Draw_Pic (int x, int y, qpic_t *pic) { - byte *dest, *source, tbyte; - unsigned short *pusdest; - int v, u; + byte *dest, *source, tbyte; + unsigned short *pusdest; + int v, u; - if (x < 0 || (unsigned int)(x + pic->width) > vid.width || y < 0 || - (unsigned int)(y + pic->height) > vid.height) - { + if (x < 0 || (unsigned int) (x + pic->width) > vid.width || y < 0 || + (unsigned int) (y + pic->height) > vid.height) { Sys_Error ("Draw_Pic: bad coordinates"); } source = pic->data; - if (r_pixbytes == 1) - { + if (r_pixbytes == 1) { dest = vid.buffer + y * vid.rowbytes + x; - if (pic->width & 7) - { // general - for (v=0 ; vheight ; v++) - { - for (u=0 ; uwidth ; u++) - if ( (tbyte=source[u]) != TRANSPARENT_COLOR) + if (pic->width & 7) { // general + for (v = 0; v < pic->height; v++) { + for (u = 0; u < pic->width; u++) + if ((tbyte = source[u]) != TRANSPARENT_COLOR) dest[u] = tbyte; - + dest += vid.rowbytes; source += pic->width; } - } - else - { // unwound - for (v=0 ; vheight ; v++) - { - for (u=0 ; uwidth ; u+=8) - { - if ( (tbyte=source[u]) != TRANSPARENT_COLOR) + } else { // unwound + for (v = 0; v < pic->height; v++) { + for (u = 0; u < pic->width; u += 8) { + if ((tbyte = source[u]) != TRANSPARENT_COLOR) dest[u] = tbyte; - if ( (tbyte=source[u+1]) != TRANSPARENT_COLOR) - dest[u+1] = tbyte; - if ( (tbyte=source[u+2]) != TRANSPARENT_COLOR) - dest[u+2] = tbyte; - if ( (tbyte=source[u+3]) != TRANSPARENT_COLOR) - dest[u+3] = tbyte; - if ( (tbyte=source[u+4]) != TRANSPARENT_COLOR) - dest[u+4] = tbyte; - if ( (tbyte=source[u+5]) != TRANSPARENT_COLOR) - dest[u+5] = tbyte; - if ( (tbyte=source[u+6]) != TRANSPARENT_COLOR) - dest[u+6] = tbyte; - if ( (tbyte=source[u+7]) != TRANSPARENT_COLOR) - dest[u+7] = tbyte; + if ((tbyte = source[u + 1]) != TRANSPARENT_COLOR) + dest[u + 1] = tbyte; + if ((tbyte = source[u + 2]) != TRANSPARENT_COLOR) + dest[u + 2] = tbyte; + if ((tbyte = source[u + 3]) != TRANSPARENT_COLOR) + dest[u + 3] = tbyte; + if ((tbyte = source[u + 4]) != TRANSPARENT_COLOR) + dest[u + 4] = tbyte; + if ((tbyte = source[u + 5]) != TRANSPARENT_COLOR) + dest[u + 5] = tbyte; + if ((tbyte = source[u + 6]) != TRANSPARENT_COLOR) + dest[u + 6] = tbyte; + if ((tbyte = source[u + 7]) != TRANSPARENT_COLOR) + dest[u + 7] = tbyte; } dest += vid.rowbytes; source += pic->width; } } - } - else - { - // FIXME: pretranslate at load time? - pusdest = (unsigned short *)vid.buffer + y * (vid.rowbytes >> 1) + x; + } else { + // FIXME: pretranslate at load time? + pusdest = (unsigned short *) vid.buffer + y * (vid.rowbytes >> 1) + x; - for (v=0 ; vheight ; v++) - { - for (u=0 ; uwidth ; u++) - { + for (v = 0; v < pic->height; v++) { + for (u = 0; u < pic->width; u++) { tbyte = source[u]; - if (tbyte != TRANSPARENT_COLOR) - { + if (tbyte != TRANSPARENT_COLOR) { pusdest[u] = d_8to16table[tbyte]; } } @@ -419,42 +402,35 @@ void Draw_Pic (int x, int y, qpic_t *pic) Draw_SubPic ============= */ -void Draw_SubPic(int x, int y, qpic_t *pic, int srcx, int srcy, int width, int height) +void +Draw_SubPic (int x, int y, qpic_t *pic, int srcx, int srcy, int width, + int height) { - byte *dest, *source; - unsigned short *pusdest; - int v, u; + byte *dest, *source; + unsigned short *pusdest; + int v, u; if ((x < 0) || - (x + width > vid.width) || - (y < 0) || - (y + height > vid.height)) - { + (x + width > vid.width) || (y < 0) || (y + height > vid.height)) { Sys_Error ("Draw_Pic: bad coordinates"); } source = pic->data + srcy * pic->width + srcx; - if (r_pixbytes == 1) - { + if (r_pixbytes == 1) { dest = vid.buffer + y * vid.rowbytes + x; - for (v=0 ; vwidth; } - } - else - { - // FIXME: pretranslate at load time? - pusdest = (unsigned short *)vid.buffer + y * (vid.rowbytes >> 1) + x; + } else { + // FIXME: pretranslate at load time? + pusdest = (unsigned short *) vid.buffer + y * (vid.rowbytes >> 1) + x; - for (v=0 ; vwidth) > vid.width || y < 0 || - (unsigned int)(y + pic->height) > vid.height) - { + if (x < 0 || (unsigned int) (x + pic->width) > vid.width || y < 0 || + (unsigned int) (y + pic->height) > vid.height) { Sys_Error ("Draw_TransPic: bad coordinates"); } - + source = pic->data; - if (r_pixbytes == 1) - { + if (r_pixbytes == 1) { dest = vid.buffer + y * vid.rowbytes + x; - if (pic->width & 7) - { // general - for (v=0 ; vheight ; v++) - { - for (u=0 ; uwidth ; u++) - if ( (tbyte=source[u]) != TRANSPARENT_COLOR) + if (pic->width & 7) { // general + for (v = 0; v < pic->height; v++) { + for (u = 0; u < pic->width; u++) + if ((tbyte = source[u]) != TRANSPARENT_COLOR) dest[u] = translation[tbyte]; dest += vid.rowbytes; source += pic->width; } - } - else - { // unwound - for (v=0 ; vheight ; v++) - { - for (u=0 ; uwidth ; u+=8) - { - if ( (tbyte=source[u]) != TRANSPARENT_COLOR) + } else { // unwound + for (v = 0; v < pic->height; v++) { + for (u = 0; u < pic->width; u += 8) { + if ((tbyte = source[u]) != TRANSPARENT_COLOR) dest[u] = translation[tbyte]; - if ( (tbyte=source[u+1]) != TRANSPARENT_COLOR) - dest[u+1] = translation[tbyte]; - if ( (tbyte=source[u+2]) != TRANSPARENT_COLOR) - dest[u+2] = translation[tbyte]; - if ( (tbyte=source[u+3]) != TRANSPARENT_COLOR) - dest[u+3] = translation[tbyte]; - if ( (tbyte=source[u+4]) != TRANSPARENT_COLOR) - dest[u+4] = translation[tbyte]; - if ( (tbyte=source[u+5]) != TRANSPARENT_COLOR) - dest[u+5] = translation[tbyte]; - if ( (tbyte=source[u+6]) != TRANSPARENT_COLOR) - dest[u+6] = translation[tbyte]; - if ( (tbyte=source[u+7]) != TRANSPARENT_COLOR) - dest[u+7] = translation[tbyte]; + if ((tbyte = source[u + 1]) != TRANSPARENT_COLOR) + dest[u + 1] = translation[tbyte]; + if ((tbyte = source[u + 2]) != TRANSPARENT_COLOR) + dest[u + 2] = translation[tbyte]; + if ((tbyte = source[u + 3]) != TRANSPARENT_COLOR) + dest[u + 3] = translation[tbyte]; + if ((tbyte = source[u + 4]) != TRANSPARENT_COLOR) + dest[u + 4] = translation[tbyte]; + if ((tbyte = source[u + 5]) != TRANSPARENT_COLOR) + dest[u + 5] = translation[tbyte]; + if ((tbyte = source[u + 6]) != TRANSPARENT_COLOR) + dest[u + 6] = translation[tbyte]; + if ((tbyte = source[u + 7]) != TRANSPARENT_COLOR) + dest[u + 7] = translation[tbyte]; } dest += vid.rowbytes; source += pic->width; } } - } - else - { - // FIXME: pretranslate at load time? - pusdest = (unsigned short *)vid.buffer + y * (vid.rowbytes >> 1) + x; + } else { + // FIXME: pretranslate at load time? + pusdest = (unsigned short *) vid.buffer + y * (vid.rowbytes >> 1) + x; - for (v=0 ; vheight ; v++) - { - for (u=0 ; uwidth ; u++) - { + for (v = 0; v < pic->height; v++) { + for (u = 0; u < pic->width; u++) { tbyte = source[u]; - if (tbyte != TRANSPARENT_COLOR) - { + if (tbyte != TRANSPARENT_COLOR) { pusdest[u] = d_8to16table[tbyte]; } } @@ -557,75 +521,68 @@ Draw_ConsoleBackground ================ */ -void Draw_ConsoleBackground (int lines) +void +Draw_ConsoleBackground (int lines) { - int x, y, v; - byte *src, *dest; - unsigned short *pusdest; - int f, fstep; - qpic_t *conback; + int x, y, v; + byte *src, *dest; + unsigned short *pusdest; + int f, fstep; + qpic_t *conback; conback = Draw_CachePic ("gfx/conback.lmp"); // draw the pic - if (r_pixbytes == 1) - { + if (r_pixbytes == 1) { dest = vid.conbuffer; - for (y=0 ; ydata + v*320; + for (y = 0; y < lines; y++, dest += vid.conrowbytes) { + v = (vid.conheight - lines + y) * 200 / vid.conheight; + src = conback->data + v * 320; if (vid.conwidth == 320) memcpy (dest, src, vid.conwidth); - else - { + else { f = 0; - fstep = 320*0x10000/vid.conwidth; - for (x=0 ; x>16]; + fstep = 320 * 0x10000 / vid.conwidth; + for (x = 0; x < vid.conwidth; x += 4) { + dest[x] = src[f >> 16]; f += fstep; - dest[x+1] = src[f>>16]; + dest[x + 1] = src[f >> 16]; f += fstep; - dest[x+2] = src[f>>16]; + dest[x + 2] = src[f >> 16]; f += fstep; - dest[x+3] = src[f>>16]; + dest[x + 3] = src[f >> 16]; f += fstep; } } } - } - else - { - pusdest = (unsigned short *)vid.conbuffer; + } else { + pusdest = (unsigned short *) vid.conbuffer; - for (y=0 ; y> 1)) - { - // FIXME: pre-expand to native format? - // FIXME: does the endian switching go away in production? - v = (vid.conheight - lines + y)*200/vid.conheight; - src = conback->data + v*320; + for (y = 0; y < lines; y++, pusdest += (vid.conrowbytes >> 1)) { + // FIXME: pre-expand to native format? + // FIXME: does the endian switching go away in production? + v = (vid.conheight - lines + y) * 200 / vid.conheight; + src = conback->data + v * 320; f = 0; - fstep = 320*0x10000/vid.conwidth; - for (x=0 ; x>16]]; + fstep = 320 * 0x10000 / vid.conwidth; + for (x = 0; x < vid.conwidth; x += 4) { + pusdest[x] = d_8to16table[src[f >> 16]]; f += fstep; - pusdest[x+1] = d_8to16table[src[f>>16]]; + pusdest[x + 1] = d_8to16table[src[f >> 16]]; f += fstep; - pusdest[x+2] = d_8to16table[src[f>>16]]; + pusdest[x + 2] = d_8to16table[src[f >> 16]]; f += fstep; - pusdest[x+3] = d_8to16table[src[f>>16]]; + pusdest[x + 3] = d_8to16table[src[f >> 16]]; f += fstep; } } } if (!cls.download) - Draw_AltString8 (vid.conwidth - strlen(cl_verstring->string) - * 8 - 11, lines-14, cl_verstring->string); - + Draw_AltString8 (vid.conwidth - strlen (cl_verstring->string) + * 8 - 11, lines - 14, cl_verstring->string); + } @@ -634,27 +591,23 @@ void Draw_ConsoleBackground (int lines) R_DrawRect8 ============== */ -void R_DrawRect8 (vrect_t *prect, int rowbytes, byte *psrc, - int transparent) +void +R_DrawRect8 (vrect_t *prect, int rowbytes, byte * psrc, int transparent) { - byte t; - int i, j, srcdelta, destdelta; - byte *pdest; + byte t; + int i, j, srcdelta, destdelta; + byte *pdest; pdest = vid.buffer + (prect->y * vid.rowbytes) + prect->x; srcdelta = rowbytes - prect->width; destdelta = vid.rowbytes - prect->width; - if (transparent) - { - for (i=0 ; iheight ; i++) - { - for (j=0 ; jwidth ; j++) - { + if (transparent) { + for (i = 0; i < prect->height; i++) { + for (j = 0; j < prect->width; j++) { t = *psrc; - if (t != TRANSPARENT_COLOR) - { + if (t != TRANSPARENT_COLOR) { *pdest = t; } @@ -665,11 +618,8 @@ void R_DrawRect8 (vrect_t *prect, int rowbytes, byte *psrc, psrc += srcdelta; pdest += destdelta; } - } - else - { - for (i=0 ; iheight ; i++) - { + } else { + for (i = 0; i < prect->height; i++) { memcpy (pdest, psrc, prect->width); psrc += rowbytes; pdest += vid.rowbytes; @@ -683,30 +633,26 @@ void R_DrawRect8 (vrect_t *prect, int rowbytes, byte *psrc, R_DrawRect16 ============== */ -void R_DrawRect16 (vrect_t *prect, int rowbytes, byte *psrc, - int transparent) +void +R_DrawRect16 (vrect_t *prect, int rowbytes, byte * psrc, int transparent) { - byte t; - int i, j, srcdelta, destdelta; - unsigned short *pdest; + byte t; + int i, j, srcdelta, destdelta; + unsigned short *pdest; // FIXME: would it be better to pre-expand native-format versions? - pdest = (unsigned short *)vid.buffer + - (prect->y * (vid.rowbytes >> 1)) + prect->x; + pdest = (unsigned short *) vid.buffer + + (prect->y * (vid.rowbytes >> 1)) + prect->x; srcdelta = rowbytes - prect->width; destdelta = (vid.rowbytes >> 1) - prect->width; - if (transparent) - { - for (i=0 ; iheight ; i++) - { - for (j=0 ; jwidth ; j++) - { + if (transparent) { + for (i = 0; i < prect->height; i++) { + for (j = 0; j < prect->width; j++) { t = *psrc; - if (t != TRANSPARENT_COLOR) - { + if (t != TRANSPARENT_COLOR) { *pdest = d_8to16table[t]; } @@ -717,13 +663,9 @@ void R_DrawRect16 (vrect_t *prect, int rowbytes, byte *psrc, psrc += srcdelta; pdest += destdelta; } - } - else - { - for (i=0 ; iheight ; i++) - { - for (j=0 ; jwidth ; j++) - { + } else { + for (i = 0; i < prect->height; i++) { + for (j = 0; j < prect->width; j++) { *pdest = d_8to16table[*psrc]; psrc++; pdest++; @@ -744,11 +686,12 @@ This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ -void Draw_TileClear (int x, int y, int w, int h) +void +Draw_TileClear (int x, int y, int w, int h) { - int width, height, tileoffsetx, tileoffsety; - byte *psrc; - vrect_t vr; + int width, height, tileoffsetx, tileoffsety; + byte *psrc; + vrect_t vr; r_rectdesc.rect.x = x; r_rectdesc.rect.y = y; @@ -760,8 +703,7 @@ void Draw_TileClear (int x, int y, int w, int h) tileoffsety = vr.y % r_rectdesc.height; - while (height > 0) - { + while (height > 0) { vr.x = r_rectdesc.rect.x; width = r_rectdesc.rect.width; @@ -775,8 +717,7 @@ void Draw_TileClear (int x, int y, int w, int h) tileoffsetx = vr.x % r_rectdesc.width; - while (width > 0) - { + while (width > 0) { if (tileoffsetx != 0) vr.width = r_rectdesc.width - tileoffsetx; else @@ -786,25 +727,24 @@ void Draw_TileClear (int x, int y, int w, int h) vr.width = width; psrc = r_rectdesc.ptexbytes + - (tileoffsety * r_rectdesc.rowbytes) + tileoffsetx; + (tileoffsety * r_rectdesc.rowbytes) + tileoffsetx; - if (r_pixbytes == 1) - { + if (r_pixbytes == 1) { R_DrawRect8 (&vr, r_rectdesc.rowbytes, psrc, 0); - } - else - { + } else { R_DrawRect16 (&vr, r_rectdesc.rowbytes, psrc, 0); } vr.x += vr.width; width -= vr.width; - tileoffsetx = 0; // only the left tile can be left-clipped + tileoffsetx = 0; // only the left tile can be + // left-clipped } vr.y += vr.height; height -= vr.height; - tileoffsety = 0; // only the top tile can be top-clipped + tileoffsety = 0; // only the top tile can be + // top-clipped } } @@ -816,37 +756,34 @@ Draw_Fill Fills a box of pixels with a single color ============= */ -void Draw_Fill (int x, int y, int w, int h, int c) +void +Draw_Fill (int x, int y, int w, int h, int c) { - byte *dest; - unsigned short *pusdest; - unsigned int uc; - int u, v; + byte *dest; + unsigned short *pusdest; + unsigned int uc; + int u, v; - if (x < 0 || x + w > vid.width || - y < 0 || y + h > vid.height) { - Con_Printf("Bad Draw_Fill(%d, %d, %d, %d, %c)\n", - x, y, w, h, c); + if (x < 0 || x + w > vid.width || y < 0 || y + h > vid.height) { + Con_Printf ("Bad Draw_Fill(%d, %d, %d, %d, %c)\n", x, y, w, h, c); return; } - if (r_pixbytes == 1) - { - dest = vid.buffer + y*vid.rowbytes + x; - for (v=0 ; v> 1) + x; - for (v=0 ; v> 1)) - for (u=0 ; u> 1) + x; + for (v = 0; v < h; v++, pusdest += (vid.rowbytes >> 1)) + for (u = 0; u < w; u++) pusdest[u] = uc; } } + //============================================================================= /* @@ -855,24 +792,23 @@ Draw_FadeScreen ================ */ -void Draw_FadeScreen (void) +void +Draw_FadeScreen (void) { - int x,y; - byte *pbuf; + int x, y; + byte *pbuf; VID_UnlockBuffer (); S_ExtraUpdate (); VID_LockBuffer (); - for (y=0 ; ydata, 24, 24); @@ -908,9 +845,9 @@ Erases the disc icon. Call after completing any disc IO ================ */ -void Draw_EndDisc (void) +void +Draw_EndDisc (void) { D_EndDirectRect (vid.width - 24, 0, 24, 24); } - diff --git a/source/fnmatch.c b/source/fnmatch.c index da2c6a5..7a8fbb3 100644 --- a/source/fnmatch.c +++ b/source/fnmatch.c @@ -26,7 +26,7 @@ $Id$ */ -#include "config.h" +# include "config.h" #ifndef _GNU_SOURCE #define _GNU_SOURCE @@ -50,19 +50,19 @@ #if !defined(__GNU_LIBRARY__) && !defined(STDC_HEADERS) -extern int errno; +extern int errno; #endif /* Match STRING against the filename pattern PATTERN, returning zero if it matches, nonzero if not. */ int fnmatch (pattern, string, flags) - const char *pattern; - const char *string; - int flags; +const char *pattern; +const char *string; +int flags; { - register const char *p = pattern, *n = string; - register unsigned char c; + register const char *p = pattern, *n = string; + register unsigned char c; /* Note that this evalutes C many times. */ #define FOLD(c) ((flags & FNM_CASEFOLD) && isupper (c) ? tolower (c) : (c)) @@ -71,150 +71,149 @@ fnmatch (pattern, string, flags) flags |= FNM_CASEFOLD; #endif - while ((c = *p++) != '\0') - { - c = FOLD (c); - - switch (c) - { - case '?': - if (*n == '\0') - return FNM_NOMATCH; - else if ((flags & FNM_FILE_NAME) && *n == '/') - return FNM_NOMATCH; - else if ((flags & FNM_PERIOD) && *n == '.' && - (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) - return FNM_NOMATCH; - break; - - case '\\': - if (!(flags & FNM_NOESCAPE)) - { - c = *p++; - c = FOLD (c); - } - if (FOLD ((unsigned char)*n) != c) - return FNM_NOMATCH; - break; - - case '*': - if ((flags & FNM_PERIOD) && *n == '.' && - (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) - return FNM_NOMATCH; - - for (c = *p++; c == '?' || c == '*'; c = *p++, ++n) - if (((flags & FNM_FILE_NAME) && *n == '/') || - (c == '?' && *n == '\0')) - return FNM_NOMATCH; - - if (c == '\0') - return 0; - - { - unsigned char c1 = (!(flags & FNM_NOESCAPE) && c == '\\') ? *p : c; - c1 = FOLD (c1); - for (--p; *n != '\0'; ++n) - if ((c == '[' || FOLD ((unsigned char)*n) == c1) && - fnmatch (p, n, flags & ~FNM_PERIOD) == 0) - return 0; - return FNM_NOMATCH; - } - - case '[': - { - /* Nonzero if the sense of the character class is inverted. */ - register int not; - - if (*n == '\0') - return FNM_NOMATCH; - - if ((flags & FNM_PERIOD) && *n == '.' && - (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) - return FNM_NOMATCH; - - not = (*p == '!' || *p == '^'); - if (not) - ++p; - - c = *p++; - for (;;) - { - register unsigned char cstart = c, cend = c; - - if (!(flags & FNM_NOESCAPE) && c == '\\') - cstart = cend = *p++; - - cstart = cend = FOLD (cstart); - - if (c == '\0') - /* [ (unterminated) loses. */ - return FNM_NOMATCH; - - c = *p++; + while ((c = *p++) != '\0') { c = FOLD (c); - if ((flags & FNM_FILE_NAME) && c == '/') - /* [/] can never match. */ - return FNM_NOMATCH; + switch (c) { + case '?': + if (*n == '\0') + return FNM_NOMATCH; + else if ((flags & FNM_FILE_NAME) && *n == '/') + return FNM_NOMATCH; + else if ((flags & FNM_PERIOD) && *n == '.' && + (n == string + || ((flags & FNM_FILE_NAME) + && n[-1] == '/'))) return FNM_NOMATCH; + break; - if (c == '-' && *p != ']') - { - cend = *p++; - if (!(flags & FNM_NOESCAPE) && cend == '\\') - cend = *p++; - if (cend == '\0') - return FNM_NOMATCH; - cend = FOLD (cend); + case '\\': + if (!(flags & FNM_NOESCAPE)) { + c = *p++; + c = FOLD (c); + } + if (FOLD ((unsigned char) *n) != c) + return FNM_NOMATCH; + break; - c = *p++; - } + case '*': + if ((flags & FNM_PERIOD) && *n == '.' && + (n == string || ((flags & FNM_FILE_NAME) && n[-1] == '/'))) + return FNM_NOMATCH; - if (FOLD ((unsigned char)*n) >= cstart - && FOLD ((unsigned char)*n) <= cend) - goto matched; + for (c = *p++; c == '?' || c == '*'; c = *p++, ++n) + if (((flags & FNM_FILE_NAME) && *n == '/') || + (c == '?' && *n == '\0')) + return FNM_NOMATCH; - if (c == ']') - break; - } - if (!not) - return FNM_NOMATCH; - break; + if (c == '\0') + return 0; - matched:; - /* Skip the rest of the [...] that already matched. */ - while (c != ']') - { - if (c == '\0') - /* [... (unterminated) loses. */ - return FNM_NOMATCH; + { + unsigned char c1 = (!(flags & FNM_NOESCAPE) + && c == '\\') ? *p : c; - c = *p++; - if (!(flags & FNM_NOESCAPE) && c == '\\') - /* XXX 1003.2d11 is unclear if this is right. */ - ++p; - } - if (not) - return FNM_NOMATCH; - } - break; + c1 = FOLD (c1); + for (--p; *n != '\0'; ++n) + if ((c == '[' || FOLD ((unsigned char) *n) == c1) && + fnmatch (p, n, flags & ~FNM_PERIOD) == 0) + return 0; + return FNM_NOMATCH; + } - default: - if (c != FOLD ((unsigned char)*n)) - return FNM_NOMATCH; + case '[': + { + /* Nonzero if the sense of the character class is + inverted. */ + register int not; + + if (*n == '\0') + return FNM_NOMATCH; + + if ((flags & FNM_PERIOD) && *n == '.' && + (n == string + || ((flags & FNM_FILE_NAME) + && n[-1] == '/'))) return FNM_NOMATCH; + + not = (*p == '!' || *p == '^'); + if (not) + ++p; + + c = *p++; + for (;;) { + register unsigned char cstart = c, cend = c; + + if (!(flags & FNM_NOESCAPE) && c == '\\') + cstart = cend = *p++; + + cstart = cend = FOLD (cstart); + + if (c == '\0') + /* [ (unterminated) loses. */ + return FNM_NOMATCH; + + c = *p++; + c = FOLD (c); + + if ((flags & FNM_FILE_NAME) && c == '/') + /* [/] can never match. */ + return FNM_NOMATCH; + + if (c == '-' && *p != ']') { + cend = *p++; + if (!(flags & FNM_NOESCAPE) && cend == '\\') + cend = *p++; + if (cend == '\0') + return FNM_NOMATCH; + cend = FOLD (cend); + + c = *p++; + } + + if (FOLD ((unsigned char) *n) >= cstart + && FOLD ((unsigned char) *n) <= cend) + goto matched; + + if (c == ']') + break; + } + if (!not) + return FNM_NOMATCH; + break; + + matched:; + /* Skip the rest of the [...] that already matched. */ + while (c != ']') { + if (c == '\0') + /* [... (unterminated) loses. */ + return FNM_NOMATCH; + + c = *p++; + if (!(flags & FNM_NOESCAPE) && c == '\\') + /* XXX 1003.2d11 is unclear if this is right. */ + ++p; + } + if (not) + return FNM_NOMATCH; + } + break; + + default: + if (c != FOLD ((unsigned char) *n)) + return FNM_NOMATCH; + } + + ++n; } - ++n; - } + if (*n == '\0') + return 0; - if (*n == '\0') - return 0; + if ((flags & FNM_LEADING_DIR) && *n == '/') + /* The FNM_LEADING_DIR flag says that "foo*" matches + "foobar/frobozz". */ + return 0; - if ((flags & FNM_LEADING_DIR) && *n == '/') - /* The FNM_LEADING_DIR flag says that "foo*" matches "foobar/frobozz". */ - return 0; - - return FNM_NOMATCH; + return FNM_NOMATCH; } -#endif /* _LIBC or not __GNU_LIBRARY__. */ - +#endif /* _LIBC or not __GNU_LIBRARY__. */ diff --git a/source/fractalnoise.c b/source/fractalnoise.c index e245b85..67b250b 100644 --- a/source/fractalnoise.c +++ b/source/fractalnoise.c @@ -28,49 +28,57 @@ #include -void fractalnoise(unsigned char *noise, int size) +void +fractalnoise (unsigned char *noise, int size) { - int x, y, g, g2, amplitude, min, max, size1 = size - 1; - int *noisebuf; + int x, y, g, g2, amplitude, min, max, size1 = size - 1; + int *noisebuf; + #define n(x,y) noisebuf[((y)&size1)*size+((x)&size1)] - noisebuf = calloc(size*size, sizeof(int)); + noisebuf = calloc (size * size, sizeof (int)); amplitude = 32767; g2 = size; - n(0,0) = 0; - for (;(g = g2 >> 1) >= 1;g2 >>= 1) - { - // subdivide, diamond-square algorythm (really this has little to do with squares) + n (0, 0) = 0; + for (; (g = g2 >> 1) >= 1; g2 >>= 1) { + // subdivide, diamond-square algorythm (really this has little to do + // with squares) // diamond - for (y = 0;y < size;y += g2) - for (x = 0;x < size;x += g2) - n(x+g,y+g) = (n(x,y) + n(x+g2,y) + n(x,y+g2) + n(x+g2,y+g2)) >> 2; + for (y = 0; y < size; y += g2) + for (x = 0; x < size; x += g2) + n (x + g, y + g) = + (n (x, y) + n (x + g2, y) + n (x, y + g2) + + n (x + g2, y + g2)) >> 2; // square - for (y = 0;y < size;y += g2) - for (x = 0;x < size;x += g2) - { - n(x+g,y) = (n(x,y) + n(x+g2,y) + n(x+g,y-g) + n(x+g,y+g)) >> 2; - n(x,y+g) = (n(x,y) + n(x,y+g2) + n(x-g,y+g) + n(x+g,y+g)) >> 2; + for (y = 0; y < size; y += g2) + for (x = 0; x < size; x += g2) { + n (x + g, y) = + (n (x, y) + n (x + g2, y) + n (x + g, y - g) + + n (x + g, y + g)) >> 2; + n (x, y + g) = + (n (x, y) + n (x, y + g2) + n (x - g, y + g) + + n (x + g, y + g)) >> 2; } // brownian motion theory amplitude >>= 1; - for (y = 0;y < size;y += g) - for (x = 0;x < size;x += g) - n(x,y) += (rand()&litude); + for (y = 0; y < size; y += g) + for (x = 0; x < size; x += g) + n (x, y) += (rand () & amplitude); } // find range of noise values min = max = 0; - for (y = 0;y < size;y++) - for (x = 0;x < size;x++) - { - if (n(x,y) < min) min = n(x,y); - if (n(x,y) > max) max = n(x,y); + for (y = 0; y < size; y++) + for (x = 0; x < size; x++) { + if (n (x, y) < min) + min = n (x, y); + if (n (x, y) > max) + max = n (x, y); } max -= min; // normalize noise and copy to output - for (y = 0;y < size;y++) - for (x = 0;x < size;x++) - *noise++ = (n(x,y) - min) * 255 / max; - free(noisebuf); + for (y = 0; y < size; y++) + for (x = 0; x < size; x++) + *noise++ = (n (x, y) - min) * 255 / max; + free (noisebuf); #undef n } diff --git a/source/gl_draw.c b/source/gl_draw.c index 8fef992..e5d8cd1 100644 --- a/source/gl_draw.c +++ b/source/gl_draw.c @@ -36,49 +36,55 @@ #include #endif -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h -#include "crc.h" // LordHavoc: for texture update validation -#include "bspfile.h" // needed by: glquake.h +#include "crc.h" // LordHavoc: for texture update + // validation +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" -static int GL_LoadPicTexture (qpic_t *pic); +static int GL_LoadPicTexture (qpic_t *pic); -extern byte *host_basepal; +extern byte *host_basepal; extern unsigned char d_15to8table[65536]; -extern cvar_t *crosshair, *cl_crossx, *cl_crossy, *crosshaircolor, *gl_colorlights; +extern cvar_t *crosshair, *cl_crossx, *cl_crossy, *crosshaircolor, -cvar_t *gl_max_size; -cvar_t *gl_picmip; + *gl_colorlights; -cvar_t *gl_constretch; -cvar_t *gl_conalpha; -cvar_t *gl_conspin; -cvar_t *cl_verstring; -cvar_t *gl_lightmode; // LordHavoc: lighting mode +cvar_t *gl_max_size; +cvar_t *gl_picmip; -extern byte *draw_chars; // 8*8 graphic characters -qpic_t *draw_disc; -qpic_t *draw_backtile; +cvar_t *gl_constretch; +cvar_t *gl_conalpha; +cvar_t *gl_conspin; +cvar_t *cl_verstring; +cvar_t *gl_lightmode; // LordHavoc: lighting mode -static int translate_texture; -static int char_texture; -static int cs_texture; // crosshair texturea +extern byte *draw_chars; // 8*8 graphic characters +qpic_t *draw_disc; +qpic_t *draw_backtile; + +static int translate_texture; +static int char_texture; +static int cs_texture; // crosshair texturea static byte cs_data[64] = { 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, @@ -92,33 +98,32 @@ static byte cs_data[64] = { }; -typedef struct -{ - int texnum; - int bytesperpixel; - float sl, tl, sh, th; +typedef struct { + int texnum; + int bytesperpixel; + float sl, tl, sh, th; } glpic_t; -int gl_lightmap_format = 4; -int gl_solid_format = 3; -int gl_alpha_format = 4; +int gl_lightmap_format = 4; +int gl_solid_format = 3; +int gl_alpha_format = 4; -static int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; -static int gl_filter_max = GL_LINEAR; +static int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; +static int gl_filter_max = GL_LINEAR; -typedef struct -{ - int texnum; - char identifier[64]; - int width, height; - int bytesperpixel; - qboolean mipmap; - unsigned short crc; // LordHavoc: CRC for texture validation +typedef struct { + int texnum; + char identifier[64]; + int width, height; + int bytesperpixel; + qboolean mipmap; + unsigned short crc; // LordHavoc: CRC for texture + // validation } gltexture_t; -static gltexture_t gltextures[MAX_GLTEXTURES]; -static int numgltextures = 0; +static gltexture_t gltextures[MAX_GLTEXTURES]; +static int numgltextures = 0; /* ============================================================================= @@ -142,31 +147,32 @@ static int numgltextures = 0; #define BLOCK_WIDTH 256 #define BLOCK_HEIGHT 256 -static int scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH]; -static byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH*BLOCK_HEIGHT*4]; -static qboolean scrap_dirty; -static int scrap_texnum; +static int scrap_allocated[MAX_SCRAPS][BLOCK_WIDTH]; +static byte scrap_texels[MAX_SCRAPS][BLOCK_WIDTH * BLOCK_HEIGHT * 4]; +static qboolean scrap_dirty; +static int scrap_texnum; // returns a texture number and the position inside it -static int Scrap_AllocBlock (int w, int h, int *x, int *y) +static int +Scrap_AllocBlock (int w, int h, int *x, int *y) { - int i, j; - int best, best2; - int texnum; + int i, j; + int best, best2; + int texnum; - for (texnum=0 ; texnum= best) + for (j = 0; j < w; j++) { + if (scrap_allocated[texnum][i + j] >= best) break; - if (scrap_allocated[texnum][i+j] > best2) - best2 = scrap_allocated[texnum][i+j]; + if (scrap_allocated[texnum][i + j] > best2) + best2 = scrap_allocated[texnum][i + j]; } - if (j == w) { // this is a valid spot + if (j == w) { // this is a valid spot *x = i; *y = best = best2; } @@ -175,7 +181,7 @@ static int Scrap_AllocBlock (int w, int h, int *x, int *y) if (best + h > BLOCK_HEIGHT) continue; - for (i=0 ; idata; + gl = (glpic_t *) p->data; #ifdef gl_draw_scraps // load little ones into the scrap if (p->width < 64 && p->height < 64) { - int x, y; - int i, j, k; - int texnum; + int x, y; + int i, j, k; + int texnum; texnum = Scrap_AllocBlock (p->width, p->height, &x, &y); k = 0; - for (i=0 ; iheight ; i++) - for (j=0 ; jwidth ; j++, k++) - scrap_texels[texnum][(y+i)*BLOCK_WIDTH + x + j] = p->data[k]; + for (i = 0; i < p->height; i++) + for (j = 0; j < p->width; j++, k++) + scrap_texels[texnum][(y + i) * BLOCK_WIDTH + x + j] = + p->data[k]; texnum += scrap_texnum; gl->texnum = texnum; - gl->sl = (x+0.01)/(float)BLOCK_WIDTH; - gl->sh = (x+p->width-0.01)/(float)BLOCK_WIDTH; - gl->tl = (y+0.01)/(float)BLOCK_WIDTH; - gl->th = (y+p->height-0.01)/(float)BLOCK_WIDTH; - } - else + gl->sl = (x + 0.01) / (float) BLOCK_WIDTH; + gl->sh = (x + p->width - 0.01) / (float) BLOCK_WIDTH; + gl->tl = (y + 0.01) / (float) BLOCK_WIDTH; + gl->th = (y + p->height - 0.01) / (float) BLOCK_WIDTH; + } else #endif { gl->texnum = GL_LoadPicTexture (p); @@ -255,10 +262,10 @@ qpic_t *Draw_PicFromWad (char *name) void Draw_ClearCache (void) { - cachepic_t *pic; - int i; + cachepic_t *pic; + int i; - for (pic=cachepics, i=0 ; idirty = true; } @@ -267,15 +274,16 @@ Draw_ClearCache (void) Draw_CachePic ================ */ -qpic_t *Draw_CachePic (char *path) +qpic_t * +Draw_CachePic (char *path) { - cachepic_t *pic; - int i; - qpic_t *dat; - glpic_t *gl; + cachepic_t *pic; + int i; + qpic_t *dat; + glpic_t *gl; // First, check and see if its cached.. - for (pic=cachepics, i=0 ; iname)) && !pic->dirty) return &pic->pic; @@ -284,7 +292,7 @@ qpic_t *Draw_CachePic (char *path) Sys_Error ("menu_numcachepics == MAX_CACHED_PICS"); // Load the picture.. - dat = (qpic_t *)COM_LoadTempFile (path); + dat = (qpic_t *) COM_LoadTempFile (path); if (!dat) Sys_Error ("Draw_CachePic: failed to load %s", path); @@ -294,18 +302,21 @@ qpic_t *Draw_CachePic (char *path) // Ok, the image is here, lets load it up into the cache.. // First the image name.. - strncpy (pic->name, path, sizeof(pic->name)); + strncpy (pic->name, path, sizeof (pic->name)); // Now the width and height. pic->pic.width = dat->width; pic->pic.height = dat->height; // Now feed it to the GL stuff and get a texture number.. - gl = (glpic_t *)pic->pic.data; + gl = (glpic_t *) pic->pic.data; gl->texnum = GL_LoadPicTexture (dat); // Alignment stuff.. - gl->sl = 0; gl->sh = 1; gl->tl = 0; gl->th = 1; + gl->sl = 0; + gl->sh = 1; + gl->tl = 0; + gl->th = 1; // Now lets mark this cache entry as used.. pic->dirty = false; @@ -318,17 +329,16 @@ qpic_t *Draw_CachePic (char *path) // Some days I really dislike legacy support.. if (!strcmp (path, "gfx/menuplyr.lmp")) - memcpy (menuplyr_pixels, dat->data, dat->width*dat->height); + memcpy (menuplyr_pixels, dat->data, dat->width * dat->height); // And now we are done, return what was asked for.. return &pic->pic; } -typedef struct -{ - char *name; - int minimize, maximize; +typedef struct { + char *name; + int minimize, maximize; } glmode_t; static glmode_t modes[] = { @@ -345,16 +355,15 @@ static glmode_t modes[] = { Draw_TextureMode_f =============== */ -static void Draw_TextureMode_f (void) +static void +Draw_TextureMode_f (void) { - int i; - gltexture_t *glt; + int i; + gltexture_t *glt; - if (Cmd_Argc() == 1) - { - for (i=0 ; i< 6 ; i++) - if (gl_filter_min == modes[i].minimize) - { + if (Cmd_Argc () == 1) { + for (i = 0; i < 6; i++) + if (gl_filter_min == modes[i].minimize) { Con_Printf ("%s\n", modes[i].name); return; } @@ -362,13 +371,11 @@ static void Draw_TextureMode_f (void) return; } - for (i=0 ; i< 6 ; i++) - { - if (!stricmp (modes[i].name, Cmd_Argv(1) ) ) + for (i = 0; i < 6; i++) { + if (!stricmp (modes[i].name, Cmd_Argv (1))) break; } - if (i == 6) - { + if (i == 6) { Con_Printf ("bad filter name\n"); return; } @@ -377,37 +384,41 @@ static void Draw_TextureMode_f (void) gl_filter_max = modes[i].maximize; // change all the existing mipmap texture objects - for (i=0, glt=gltextures ; imipmap) - { + for (i = 0, glt = gltextures; i < numgltextures; i++, glt++) { + if (glt->mipmap) { glBindTexture (GL_TEXTURE_2D, glt->texnum); - glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); - glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, + gl_filter_min); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, + gl_filter_max); } } } -extern void glrmain_init(); -extern void glrsurf_init(); +extern void glrmain_init (); +extern void glrsurf_init (); + /* =============== Draw_Init =============== */ -void Draw_Init (void) +void +Draw_Init (void) { - int i; + int i; // 3dfx can only handle 256 wide textures - if (!strncasecmp ((char *)gl_renderer, "3dfx",4) || - !strncasecmp ((char *)gl_renderer, "Mesa",4)) + if (!strncasecmp ((char *) gl_renderer, "3dfx", 4) || + !strncasecmp ((char *) gl_renderer, "Mesa", 4)) Cvar_Set (gl_max_size, "256"); - // LordHavoc: 3DFX's dithering has terrible artifacting when using lightmode 1 - if (!strncasecmp ((char *)gl_renderer, "3dfx",4)) + // LordHavoc: 3DFX's dithering has terrible artifacting when using + // lightmode 1 + if (!strncasecmp ((char *) gl_renderer, "3dfx", 4)) Cvar_Set (gl_lightmode, "0"); - lighthalf = gl_lightmode->int_val != 0; // to avoid re-rendering all lightmaps on first frame + lighthalf = gl_lightmode->int_val != 0; // to avoid re-rendering all + // lightmaps on first frame if (lighthalf) { lighthalf_v[0] = lighthalf_v[1] = lighthalf_v[2] = 128; } else { @@ -421,17 +432,22 @@ void Draw_Init (void) // string into the background before turning // it into a texture draw_chars = W_GetLumpName ("conchars"); - for (i=0 ; i<256*64 ; i++) + for (i = 0; i < 256 * 64; i++) if (draw_chars[i] == 0) - draw_chars[i] = 255; // proper transparent color + draw_chars[i] = 255; // proper transparent color // now turn them into textures - char_texture = GL_LoadTexture ("charset", 128, 128, draw_chars, false, true, 1); // 1999-12-27 Conwidth/height charset fix by TcT + char_texture = GL_LoadTexture ("charset", 128, 128, draw_chars, false, true, 1); // 1999-12-27 + // Conwidth/height + // charset + // fix + // by + // TcT cs_texture = GL_LoadTexture ("crosshair", 8, 8, cs_data, false, true, 1); -// char_texture = GL_LoadTexture ("charset", 128, 128, draw_chars, false, true, 1); // 1999-12-27 Conwidth/height charset fix by TcT +// char_texture = GL_LoadTexture ("charset", 128, 128, draw_chars, false, true, 1); // 1999-12-27 Conwidth/height charset fix by TcT - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // save a texture slot for translated picture translate_texture = texture_extension_number++; @@ -442,39 +458,44 @@ void Draw_Init (void) texture_extension_number += MAX_SCRAPS; #endif - // + // // get the other pics we need - // + // draw_disc = Draw_PicFromWad ("disc"); draw_backtile = Draw_PicFromWad ("backtile"); // LordHavoc: call init code for other GL renderer modules; - glrmain_init(); - glrsurf_init(); + glrmain_init (); + glrsurf_init (); } -void Draw_Init_Cvars (void) +void +Draw_Init_Cvars (void) { // LordHavoc: lighting mode - gl_lightmode = Cvar_Get("gl_lightmode", "1", CVAR_ARCHIVE, - "Lighting mode (0 = GLQuake style, 1 = new style)"); - gl_max_size = Cvar_Get("gl_max_size", "1024", CVAR_NONE, - "None"); // CVAR_FIXME - set a description - gl_picmip = Cvar_Get("gl_picmip", "0", CVAR_NONE, - "None"); // CVAR_FIXME - set a description + gl_lightmode = Cvar_Get ("gl_lightmode", "1", CVAR_ARCHIVE, + "Lighting mode (0 = GLQuake style, 1 = new style)"); + gl_max_size = Cvar_Get ("gl_max_size", "1024", CVAR_NONE, "None"); // CVAR_FIXME + // - + // set + // a + // description + gl_picmip = Cvar_Get ("gl_picmip", "0", CVAR_NONE, "None"); // CVAR_FIXME + // - set a + // description gl_colorlights = Cvar_Get ("gl_colorlights", "1", CVAR_ROM, - "Whether to use RGB lightmaps or not"); + "Whether to use RGB lightmaps or not"); // Console effects --KB gl_constretch = Cvar_Get ("gl_constretch", "0", CVAR_ARCHIVE, - "whether slide the console or stretch it"); + "whether slide the console or stretch it"); gl_conalpha = Cvar_Get ("gl_conalpha", "0.6", CVAR_ARCHIVE, - "alpha value for the console background"); + "alpha value for the console background"); gl_conspin = Cvar_Get ("gl_conspin", "0", CVAR_ARCHIVE, - "speed at which the console spins"); + "speed at which the console spins"); - cl_verstring = Cvar_Get("cl_verstring", PROGRAM " " VERSION, CVAR_NONE, - "client version string"); + cl_verstring = Cvar_Get ("cl_verstring", PROGRAM " " VERSION, CVAR_NONE, + "client version string"); } @@ -488,24 +509,25 @@ It can be clipped to the top of the screen to allow the console to be smoothly scrolled off. ================ */ -void Draw_Character8 (int x, int y, int num) +void +Draw_Character8 (int x, int y, int num) { - int row, col; - float frow, fcol, size; + int row, col; + float frow, fcol, size; if (num == 32) - return; // space + return; // space num &= 255; - + if (y <= -8) - return; // totally off screen + return; // totally off screen - row = num>>4; - col = num&15; + row = num >> 4; + col = num & 15; - frow = row*0.0625; - fcol = col*0.0625; + frow = row * 0.0625; + fcol = col * 0.0625; size = 0.0625; glBindTexture (GL_TEXTURE_2D, char_texture); @@ -514,11 +536,11 @@ void Draw_Character8 (int x, int y, int num) glTexCoord2f (fcol, frow); glVertex2f (x, y); glTexCoord2f (fcol + size, frow); - glVertex2f (x+8, y); + glVertex2f (x + 8, y); glTexCoord2f (fcol + size, frow + size); - glVertex2f (x+8, y+8); + glVertex2f (x + 8, y + 8); glTexCoord2f (fcol, frow + size); - glVertex2f (x, y+8); + glVertex2f (x, y + 8); glEnd (); } @@ -527,10 +549,10 @@ void Draw_Character8 (int x, int y, int num) Draw_String8 ================ */ -void Draw_String8 (int x, int y, char *str) +void +Draw_String8 (int x, int y, char *str) { - while (*str) - { + while (*str) { Draw_Character8 (x, y, *str); str++; x += 8; @@ -542,20 +564,21 @@ void Draw_String8 (int x, int y, char *str) Draw_AltString8 ================ */ -void Draw_AltString8 (int x, int y, char *str) +void +Draw_AltString8 (int x, int y, char *str) { - while (*str) - { + while (*str) { Draw_Character8 (x, y, (*str) | 0x80); str++; x += 8; } } -void Draw_Crosshair(void) +void +Draw_Crosshair (void) { - int x, y; - extern vrect_t scr_vrect; + int x, y; + extern vrect_t scr_vrect; unsigned char *pColor; switch (crosshair->int_val) { @@ -563,32 +586,35 @@ void Draw_Crosshair(void) break; case 1: default: - Draw_Character8 ( - scr_vrect.x + scr_vrect.width/2-4 + cl_crossx->int_val, - scr_vrect.y + scr_vrect.height/2-4 + cl_crossy->int_val, '+'); + Draw_Character8 (scr_vrect.x + scr_vrect.width / 2 - 4 + + cl_crossx->int_val, + scr_vrect.y + scr_vrect.height / 2 - 4 + + cl_crossy->int_val, '+'); break; case 2: - x = scr_vrect.x + scr_vrect.width/2 - 3 + cl_crossx->int_val; - y = scr_vrect.y + scr_vrect.height/2 - 3 + cl_crossy->int_val; + x = scr_vrect.x + scr_vrect.width / 2 - 3 + cl_crossx->int_val; + y = scr_vrect.y + scr_vrect.height / 2 - 3 + cl_crossy->int_val; pColor = (unsigned char *) &d_8to24table[crosshaircolor->int_val]; if (lighthalf) - glColor4ub((byte) ((int) pColor[0] >> 1),(byte) ((int) pColor[1] >> 1), (byte) ((int) pColor[2] >> 1), pColor[3]); + glColor4ub ((byte) ((int) pColor[0] >> 1), + (byte) ((int) pColor[1] >> 1), + (byte) ((int) pColor[2] >> 1), pColor[3]); else - glColor4ubv(pColor); + glColor4ubv (pColor); glBindTexture (GL_TEXTURE_2D, cs_texture); glBegin (GL_QUADS); glTexCoord2f (0, 0); glVertex2f (x - 4, y - 4); glTexCoord2f (1, 0); - glVertex2f (x+12, y-4); + glVertex2f (x + 12, y - 4); glTexCoord2f (1, 1); - glVertex2f (x+12, y+12); + glVertex2f (x + 12, y + 12); glTexCoord2f (0, 1); - glVertex2f (x - 4, y+12); + glVertex2f (x - 4, y + 12); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); break; } } @@ -598,70 +624,73 @@ void Draw_Crosshair(void) Draw_Pic ============= */ -void Draw_Pic (int x, int y, qpic_t *pic) +void +Draw_Pic (int x, int y, qpic_t *pic) { - glpic_t *gl; + glpic_t *gl; #ifdef gl_draw_scraps if (scrap_dirty) Scrap_Upload (); #endif - gl = (glpic_t *)pic->data; + gl = (glpic_t *) pic->data; if (lighthalf) - glColor3f(0.4,0.4,0.4); + glColor3f (0.4, 0.4, 0.4); else - glColor3f(0.8,0.8,0.8); + glColor3f (0.8, 0.8, 0.8); glBindTexture (GL_TEXTURE_2D, gl->texnum); glBegin (GL_QUADS); glTexCoord2f (gl->sl, gl->tl); glVertex2f (x, y); glTexCoord2f (gl->sh, gl->tl); - glVertex2f (x+pic->width, y); + glVertex2f (x + pic->width, y); glTexCoord2f (gl->sh, gl->th); - glVertex2f (x+pic->width, y+pic->height); + glVertex2f (x + pic->width, y + pic->height); glTexCoord2f (gl->sl, gl->th); - glVertex2f (x, y+pic->height); + glVertex2f (x, y + pic->height); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } -void Draw_SubPic(int x, int y, qpic_t *pic, int srcx, int srcy, int width, int height) +void +Draw_SubPic (int x, int y, qpic_t *pic, int srcx, int srcy, int width, + int height) { - glpic_t *gl; - float newsl, newtl, newsh, newth; - float oldglwidth, oldglheight; + glpic_t *gl; + float newsl, newtl, newsh, newth; + float oldglwidth, oldglheight; #ifdef gl_draw_scraps if (scrap_dirty) Scrap_Upload (); #endif - gl = (glpic_t *)pic->data; - + gl = (glpic_t *) pic->data; + oldglwidth = gl->sh - gl->sl; oldglheight = gl->th - gl->tl; - newsl = gl->sl + (srcx*oldglwidth)/pic->width; - newsh = newsl + (width*oldglwidth)/pic->width; + newsl = gl->sl + (srcx * oldglwidth) / pic->width; + newsh = newsl + (width * oldglwidth) / pic->width; + + newtl = gl->tl + (srcy * oldglheight) / pic->height; + newth = newtl + (height * oldglheight) / pic->height; - newtl = gl->tl + (srcy*oldglheight)/pic->height; - newth = newtl + (height*oldglheight)/pic->height; - if (lighthalf) - glColor3f(0.4,0.4,0.4); + glColor3f (0.4, 0.4, 0.4); else - glColor3f(0.8,0.8,0.8); + glColor3f (0.8, 0.8, 0.8); glBindTexture (GL_TEXTURE_2D, gl->texnum); glBegin (GL_QUADS); glTexCoord2f (newsl, newtl); glVertex2f (x, y); glTexCoord2f (newsh, newtl); - glVertex2f (x+width, y); + glVertex2f (x + width, y); glTexCoord2f (newsh, newth); - glVertex2f (x+width, y+height); + glVertex2f (x + width, y + height); glTexCoord2f (newsl, newth); - glVertex2f (x, y+height); + glVertex2f (x, y + height); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } /* @@ -671,51 +700,51 @@ Draw_TransPicTranslate Only used for the player color selection menu ============= */ -void Draw_TransPicTranslate (int x, int y, qpic_t *pic, byte *translation) +void +Draw_TransPicTranslate (int x, int y, qpic_t *pic, byte * translation) { - int v, u, c; - unsigned int trans[64*64], *dest; - byte *src; - int p; + int v, u, c; + unsigned int trans[64 * 64], *dest; + byte *src; + int p; glBindTexture (GL_TEXTURE_2D, translate_texture); c = pic->width * pic->height; dest = trans; - for (v=0 ; v<64 ; v++, dest += 64) - { - src = &menuplyr_pixels[ ((v*pic->height)>>6) *pic->width]; - for (u=0 ; u<64 ; u++) - { - p = src[(u*pic->width)>>6]; + for (v = 0; v < 64; v++, dest += 64) { + src = &menuplyr_pixels[((v * pic->height) >> 6) * pic->width]; + for (u = 0; u < 64; u++) { + p = src[(u * pic->width) >> 6]; if (p == 255) dest[u] = p; else - dest[u] = d_8to24table[translation[p]]; + dest[u] = d_8to24table[translation[p]]; } } - glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, trans); + glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 64, 64, 0, GL_RGBA, + GL_UNSIGNED_BYTE, trans); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (lighthalf) - glColor3f(0.4,0.4,0.4); + glColor3f (0.4, 0.4, 0.4); else - glColor3f(0.8,0.8,0.8); + glColor3f (0.8, 0.8, 0.8); glBegin (GL_QUADS); glTexCoord2f (0, 0); glVertex2f (x, y); glTexCoord2f (1, 0); - glVertex2f (x+pic->width, y); + glVertex2f (x + pic->width, y); glTexCoord2f (1, 1); - glVertex2f (x+pic->width, y+pic->height); + glVertex2f (x + pic->width, y + pic->height); glTexCoord2f (0, 1); - glVertex2f (x, y+pic->height); + glVertex2f (x, y + pic->height); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } @@ -725,26 +754,25 @@ void Draw_TransPicTranslate (int x, int y, qpic_t *pic, byte *translation) Draws console background (obviously!) Completely rewritten to use several simple yet very cool GL effects. --KB */ -void -Draw_ConsoleBackground ( int lines ) +void +Draw_ConsoleBackground (int lines) { - int y; - qpic_t *conback; - glpic_t *gl; - float ofs; - float alpha; + int y; + qpic_t *conback; + glpic_t *gl; + float ofs; + float alpha; // This can be a CachePic now, just like in software conback = Draw_CachePic ("gfx/conback.lmp"); - gl = (glpic_t *)conback->data; + gl = (glpic_t *) conback->data; // spin the console? - effect described in a QER tutorial - if (gl_conspin->value) - { + if (gl_conspin->value) { static float xangle = 0; static float xfactor = .3f; static float xstep = .005f; - + glPushMatrix (); glMatrixMode (GL_TEXTURE); glPushMatrix (); @@ -756,26 +784,24 @@ Draw_ConsoleBackground ( int lines ) glRotatef (xangle, 0, 0, 1); glScalef (xfactor, xfactor, xfactor); } - // slide console up/down or stretch it? if (gl_constretch->int_val) ofs = 0; else - ofs = (vid.conheight - lines)/(float)vid.conheight; + ofs = (vid.conheight - lines) / (float) vid.conheight; y = vid.height >> 1; - if (lines > y) - { + if (lines > y) { alpha = 1.0; } else { // set up to draw alpha console - alpha = (float)(gl_conalpha->value * lines)/y; + alpha = (float) (gl_conalpha->value * lines) / y; } if (lighthalf) - glColor4f(0.4,0.4,0.4,alpha); + glColor4f (0.4, 0.4, 0.4, alpha); else - glColor4f(0.8,0.8,0.8,alpha); + glColor4f (0.8, 0.8, 0.8, alpha); // draw the console texture glBindTexture (GL_TEXTURE_2D, gl->texnum); @@ -791,26 +817,23 @@ Draw_ConsoleBackground ( int lines ) glEnd (); // turn off alpha blending - if (alpha < 1.0) - { + if (alpha < 1.0) { if (lighthalf) - glColor3f(0.4,0.4,0.4); + glColor3f (0.4, 0.4, 0.4); else - glColor3f(0.8,0.8,0.8); + glColor3f (0.8, 0.8, 0.8); } - if (gl_conspin->value) - { + if (gl_conspin->value) { glPopMatrix (); glMatrixMode (GL_MODELVIEW); glPopMatrix (); } - // draw version string if not downloading if (!cls.download) - Draw_AltString8 (vid.conwidth - strlen(cl_verstring->string)*8 - 11, - lines-14, cl_verstring->string); - glColor3ubv(lighthalf_v); + Draw_AltString8 (vid.conwidth - strlen (cl_verstring->string) * 8 - 11, + lines - 14, cl_verstring->string); + glColor3ubv (lighthalf_v); } @@ -822,24 +845,25 @@ This repeats a 64*64 tile graphic to fill the screen around a sized down refresh window. ============= */ -void Draw_TileClear (int x, int y, int w, int h) +void +Draw_TileClear (int x, int y, int w, int h) { if (lighthalf) - glColor3f(0.4,0.4,0.4); + glColor3f (0.4, 0.4, 0.4); else - glColor3f(0.8,0.8,0.8); - glBindTexture (GL_TEXTURE_2D, *(int *)draw_backtile->data); + glColor3f (0.8, 0.8, 0.8); + glBindTexture (GL_TEXTURE_2D, *(int *) draw_backtile->data); glBegin (GL_QUADS); - glTexCoord2f (x/64.0, y/64.0); + glTexCoord2f (x / 64.0, y / 64.0); glVertex2f (x, y); - glTexCoord2f ( (x+w)/64.0, y/64.0); - glVertex2f (x+w, y); - glTexCoord2f ( (x+w)/64.0, (y+h)/64.0); - glVertex2f (x+w, y+h); - glTexCoord2f ( x/64.0, (y+h)/64.0 ); - glVertex2f (x, y+h); + glTexCoord2f ((x + w) / 64.0, y / 64.0); + glVertex2f (x + w, y); + glTexCoord2f ((x + w) / 64.0, (y + h) / 64.0); + glVertex2f (x + w, y + h); + glTexCoord2f (x / 64.0, (y + h) / 64.0); + glVertex2f (x, y + h); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } @@ -850,25 +874,29 @@ Draw_Fill Fills a box of pixels with a single color ============= */ -void Draw_Fill (int x, int y, int w, int h, int c) +void +Draw_Fill (int x, int y, int w, int h, int c) { glDisable (GL_TEXTURE_2D); if (lighthalf) - glColor3f (host_basepal[c*3]/510.0, host_basepal[c*3+1]/510.0, host_basepal[c*3+2]/510.0); + glColor3f (host_basepal[c * 3] / 510.0, host_basepal[c * 3 + 1] / 510.0, + host_basepal[c * 3 + 2] / 510.0); else - glColor3f (host_basepal[c*3]/255.0, host_basepal[c*3+1]/255.0, host_basepal[c*3+2]/255.0); + glColor3f (host_basepal[c * 3] / 255.0, host_basepal[c * 3 + 1] / 255.0, + host_basepal[c * 3 + 2] / 255.0); glBegin (GL_QUADS); - glVertex2f (x,y); - glVertex2f (x+w, y); - glVertex2f (x+w, y+h); - glVertex2f (x, y+h); + glVertex2f (x, y); + glVertex2f (x + w, y); + glVertex2f (x + w, y + h); + glVertex2f (x, y + h); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); glEnable (GL_TEXTURE_2D); } + //============================================================================= /* @@ -877,22 +905,23 @@ Draw_FadeScreen ================ */ -void Draw_FadeScreen (void) +void +Draw_FadeScreen (void) { glDisable (GL_TEXTURE_2D); glColor4f (0, 0, 0, 0.7); glBegin (GL_QUADS); - glVertex2f (0,0); + glVertex2f (0, 0); glVertex2f (vid.width, 0); glVertex2f (vid.width, vid.height); glVertex2f (0, vid.height); glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); glEnable (GL_TEXTURE_2D); - Sbar_Changed(); + Sbar_Changed (); } //============================================================================= @@ -905,7 +934,8 @@ Draws the little blue disc in the corner of the screen. Call before beginning any disc IO. ================ */ -void Draw_BeginDisc (void) +void +Draw_BeginDisc (void) { } @@ -918,7 +948,8 @@ Erases the disc icon. Call after completing any disc IO ================ */ -void Draw_EndDisc (void) +void +Draw_EndDisc (void) { } @@ -929,21 +960,22 @@ GL_Set2D Setup as if the screen was 320*200 ================ */ -void GL_Set2D (void) +void +GL_Set2D (void) { glViewport (glx, gly, glwidth, glheight); - glMatrixMode(GL_PROJECTION); + glMatrixMode (GL_PROJECTION); glLoadIdentity (); - glOrtho (0, vid.width, vid.height, 0, -99999, 99999); + glOrtho (0, vid.width, vid.height, 0, -99999, 99999); - glMatrixMode(GL_MODELVIEW); + glMatrixMode (GL_MODELVIEW); glLoadIdentity (); glDisable (GL_DEPTH_TEST); glDisable (GL_CULL_FACE); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } //==================================================================== @@ -953,26 +985,26 @@ void GL_Set2D (void) GL_ResampleTexture ================ */ -static void GL_ResampleTexture (unsigned int *in, int inwidth, int inheight, unsigned int *out, int outwidth, int outheight) +static void +GL_ResampleTexture (unsigned int *in, int inwidth, int inheight, + unsigned int *out, int outwidth, int outheight) { - int i, j; - unsigned int *inrow; - unsigned int frac, fracstep; + int i, j; + unsigned int *inrow; + unsigned int frac, fracstep; - fracstep = inwidth*0x10000/outwidth; - for (i=0 ; i> 1; - for (j=0 ; j>16]; + for (j = 0; j < outwidth; j += 4) { + out[j] = inrow[frac >> 16]; frac += fracstep; - out[j+1] = inrow[frac>>16]; + out[j + 1] = inrow[frac >> 16]; frac += fracstep; - out[j+2] = inrow[frac>>16]; + out[j + 2] = inrow[frac >> 16]; frac += fracstep; - out[j+3] = inrow[frac>>16]; + out[j + 3] = inrow[frac >> 16]; frac += fracstep; } } @@ -984,26 +1016,26 @@ GL_Resample8BitTexture -- JACK ================ */ #if defined(GL_SHARED_TEXTURE_PALETTE_EXT) && defined(HAVE_GL_COLOR_INDEX8_EXT) -static void GL_Resample8BitTexture (unsigned char *in, int inwidth, int inheight, unsigned char *out, int outwidth, int outheight) +static void +GL_Resample8BitTexture (unsigned char *in, int inwidth, int inheight, + unsigned char *out, int outwidth, int outheight) { - int i, j; - unsigned char *inrow; - unsigned int frac, fracstep; + int i, j; + unsigned char *inrow; + unsigned int frac, fracstep; - fracstep = inwidth*0x10000/outwidth; - for (i=0 ; i> 1; - for (j=0 ; j>16]; + for (j = 0; j < outwidth; j += 4) { + out[j] = inrow[frac >> 16]; frac += fracstep; - out[j+1] = inrow[frac>>16]; + out[j + 1] = inrow[frac >> 16]; frac += fracstep; - out[j+2] = inrow[frac>>16]; + out[j + 2] = inrow[frac >> 16]; frac += fracstep; - out[j+3] = inrow[frac>>16]; + out[j + 3] = inrow[frac >> 16]; frac += fracstep; } } @@ -1017,22 +1049,21 @@ GL_MipMap Operates in place, quartering the size of the texture ================ */ -static void GL_MipMap (byte *in, int width, int height) +static void +GL_MipMap (byte * in, int width, int height) { - int i, j; - byte *out; + int i, j; + byte *out; - width <<=2; + width <<= 2; height >>= 1; out = in; - for (i=0 ; i>2; - out[1] = (in[1] + in[5] + in[width+1] + in[width+5])>>2; - out[2] = (in[2] + in[6] + in[width+2] + in[width+6])>>2; - out[3] = (in[3] + in[7] + in[width+3] + in[width+7])>>2; + for (i = 0; i < height; i++, in += width) { + for (j = 0; j < width; j += 8, out += 4, in += 8) { + out[0] = (in[0] + in[4] + in[width + 0] + in[width + 4]) >> 2; + out[1] = (in[1] + in[5] + in[width + 1] + in[width + 5]) >> 2; + out[2] = (in[2] + in[6] + in[width + 2] + in[width + 6]) >> 2; + out[3] = (in[3] + in[7] + in[width + 3] + in[width + 7]) >> 2; } } } @@ -1045,28 +1076,31 @@ Mipping for 8 bit textures ================ */ #if defined(GL_SHARED_TEXTURE_PALETTE_EXT) && defined(HAVE_GL_COLOR_INDEX8_EXT) -static void GL_MipMap8Bit (byte *in, int width, int height) +static void +GL_MipMap8Bit (byte * in, int width, int height) { - int i, j; - byte *out; - unsigned short r,g,b; - byte *at1, *at2, *at3, *at4; + int i, j; + byte *out; + unsigned short r, g, b; + byte *at1, *at2, *at3, *at4; height >>= 1; out = in; - for (i=0 ; i>=5; - g = (at1[1]+at2[1]+at3[1]+at4[1]); g>>=5; - b = (at1[2]+at2[2]+at3[2]+at4[2]); b>>=5; + r = (at1[0] + at2[0] + at3[0] + at4[0]); + r >>= 5; + g = (at1[1] + at2[1] + at3[1] + at4[1]); + g >>= 5; + b = (at1[2] + at2[2] + at3[2] + at4[2]); + b >>= 5; - out[0] = d_15to8table[(r<<0) + (g<<5) + (b<<10)]; + out[0] = d_15to8table[(r << 0) + (g << 5) + (b << 10)]; } } #endif @@ -1076,60 +1110,67 @@ static void GL_MipMap8Bit (byte *in, int width, int height) GL_Upload32 =============== */ -static void GL_Upload32 (unsigned int *data, int width, int height, qboolean mipmap, qboolean alpha) +static void +GL_Upload32 (unsigned int *data, int width, int height, qboolean mipmap, + qboolean alpha) { - unsigned int *scaled; - int scaled_width, scaled_height, samples; + unsigned int *scaled; + int scaled_width, scaled_height, samples; // Snap the height and width to a power of 2. - for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1) ; - for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1) ; + for (scaled_width = 1; scaled_width < width; scaled_width <<= 1); + for (scaled_height = 1; scaled_height < height; scaled_height <<= 1); scaled_width >>= gl_picmip->int_val; scaled_height >>= gl_picmip->int_val; - scaled_width = min(scaled_width, gl_max_size->int_val); - scaled_height = min(scaled_height, gl_max_size->int_val); + scaled_width = min (scaled_width, gl_max_size->int_val); + scaled_height = min (scaled_height, gl_max_size->int_val); - if (!(scaled = malloc(scaled_width * scaled_height * 4 * sizeof(unsigned int)))) - Sys_Error ("GL_LoadTexture: too big"); + if (! + (scaled = + malloc (scaled_width * scaled_height * 4 * + sizeof (unsigned int)))) Sys_Error ("GL_LoadTexture: too big"); samples = alpha ? gl_alpha_format : gl_solid_format; // If the real width/height and the 'scaled' width/height then we // rescale it. if (scaled_width == width && scaled_height == height) { - memcpy (scaled, data, width*height*4); + memcpy (scaled, data, width * height * 4); } else { - GL_ResampleTexture (data, width, height, scaled, scaled_width, scaled_height); + GL_ResampleTexture (data, width, height, scaled, scaled_width, + scaled_height); } - glTexImage2D (GL_TEXTURE_2D, 0, samples, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, scaled); + glTexImage2D (GL_TEXTURE_2D, 0, samples, scaled_width, scaled_height, 0, + GL_RGBA, GL_UNSIGNED_BYTE, scaled); if (mipmap) { - int miplevel; + int miplevel; miplevel = 0; while (scaled_width > 1 || scaled_height > 1) { - GL_MipMap ((byte *)scaled, scaled_width, scaled_height); + GL_MipMap ((byte *) scaled, scaled_width, scaled_height); scaled_width >>= 1; scaled_height >>= 1; scaled_width = max (scaled_width, 1); scaled_height = max (scaled_height, 1); miplevel++; - glTexImage2D (GL_TEXTURE_2D, miplevel, samples, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, scaled); + glTexImage2D (GL_TEXTURE_2D, miplevel, samples, scaled_width, + scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, scaled); } } if (mipmap) { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); } else { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); } - free(scaled); + free (scaled); } /* @@ -1139,64 +1180,69 @@ static void GL_Upload32 (unsigned int *data, int width, int height, qboolean mip this function does nothing. */ void -GL_Upload8_EXT (byte *data, int width, int height, qboolean mipmap, qboolean alpha) +GL_Upload8_EXT (byte * data, int width, int height, qboolean mipmap, + qboolean alpha) { #if defined(GL_SHARED_TEXTURE_PALETTE_EXT) && defined(HAVE_GL_COLOR_INDEX8_EXT) - byte *scaled; - int scaled_width, scaled_height; + byte *scaled; + int scaled_width, scaled_height; // Snap the height and width to a power of 2. - for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1) ; - for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1) ; + for (scaled_width = 1; scaled_width < width; scaled_width <<= 1); + for (scaled_height = 1; scaled_height < height; scaled_height <<= 1); scaled_width >>= gl_picmip->int_val; scaled_height >>= gl_picmip->int_val; - scaled_width = min(scaled_width, gl_max_size->int_val); - scaled_height = min(scaled_height, gl_max_size->int_val); + scaled_width = min (scaled_width, gl_max_size->int_val); + scaled_height = min (scaled_height, gl_max_size->int_val); - if (!(scaled = malloc(scaled_width * scaled_height))) + if (!(scaled = malloc (scaled_width * scaled_height))) Sys_Error ("GL_LoadTexture: too big"); // If the real width/height and the 'scaled' width/height then we // rescale it. if (scaled_width == width && scaled_height == height) { - memcpy (scaled, data, width*height); + memcpy (scaled, data, width * height); } else { - GL_Resample8BitTexture (data, width, height, scaled, scaled_width, scaled_height); + GL_Resample8BitTexture (data, width, height, scaled, scaled_width, + scaled_height); } - glTexImage2D (GL_TEXTURE_2D, 0, GL_COLOR_INDEX8_EXT, scaled_width, scaled_height, 0, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, scaled); + glTexImage2D (GL_TEXTURE_2D, 0, GL_COLOR_INDEX8_EXT, scaled_width, + scaled_height, 0, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, scaled); if (mipmap) { - int miplevel; + int miplevel; miplevel = 0; while (scaled_width > 1 || scaled_height > 1) { - GL_MipMap8Bit ((byte *)scaled, scaled_width, scaled_height); + GL_MipMap8Bit ((byte *) scaled, scaled_width, scaled_height); scaled_width >>= 1; scaled_height >>= 1; scaled_width = max (scaled_width, 1); scaled_height = max (scaled_height, 1); miplevel++; - glTexImage2D (GL_TEXTURE_2D, miplevel, GL_COLOR_INDEX8_EXT, scaled_width, scaled_height, 0, GL_COLOR_INDEX, GL_UNSIGNED_BYTE, scaled); + glTexImage2D (GL_TEXTURE_2D, miplevel, GL_COLOR_INDEX8_EXT, + scaled_width, scaled_height, 0, GL_COLOR_INDEX, + GL_UNSIGNED_BYTE, scaled); } } if (mipmap) { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); } else { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_max); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); } free (scaled); #endif } -extern qboolean VID_Is8bit(); +extern qboolean VID_Is8bit (); /* =============== @@ -1204,13 +1250,14 @@ GL_Upload8 =============== */ void -GL_Upload8 (byte *data, int width, int height, qboolean mipmap, qboolean alpha) +GL_Upload8 (byte * data, int width, int height, qboolean mipmap, qboolean alpha) { - unsigned int *trans = NULL; - int i, s, p; + unsigned int *trans = NULL; + int i, s, p; - s = width*height; + s = width * height; trans = malloc (s * sizeof (unsigned int)); + // if there are no transparent pixels, make it a 3 component // texture even if it was specified as otherwise if (alpha) { @@ -1226,18 +1273,18 @@ GL_Upload8 (byte *data, int width, int height, qboolean mipmap, qboolean alpha) Sys_Error ("GL_Upload8: width*height divisible by 3"); for (i = 0; i < s; i += 4) { trans[i] = d_8to24table[data[i]]; - trans[i+1] = d_8to24table[data[i+1]]; - trans[i+2] = d_8to24table[data[i+2]]; - trans[i+3] = d_8to24table[data[i+3]]; + trans[i + 1] = d_8to24table[data[i + 1]]; + trans[i + 2] = d_8to24table[data[i + 2]]; + trans[i + 3] = d_8to24table[data[i + 3]]; } } #if defined(GL_SHARED_TEXTURE_PALETTE_EXT) && defined(HAVE_GL_COLOR_INDEX8_EXT) # ifdef gl_draw_scraps - if (VID_Is8bit() && !alpha && (data != scrap_texels[0])) { + if (VID_Is8bit () && !alpha && (data != scrap_texels[0])) { # else - if (VID_Is8bit() && !alpha) { + if (VID_Is8bit () && !alpha) { # endif GL_Upload8_EXT (data, width, height, mipmap, alpha); } else { @@ -1247,7 +1294,7 @@ GL_Upload8 (byte *data, int width, int height, qboolean mipmap, qboolean alpha) GL_Upload32 (trans, width, height, mipmap, alpha); } - free(trans); + free (trans); } /* @@ -1256,23 +1303,23 @@ GL_LoadTexture ================ */ int -GL_LoadTexture (char *identifier, int width, int height, byte *data, qboolean mipmap, qboolean alpha, int bytesperpixel) +GL_LoadTexture (char *identifier, int width, int height, byte * data, + qboolean mipmap, qboolean alpha, int bytesperpixel) { gltexture_t *glt; - int i, crc; + int i, crc; // LordHavoc: now just using a standard CRC for texture validation crc = CRC_Block (data, width * height * bytesperpixel); // see if the texture is already present if (identifier[0]) { - for (i=0, glt = gltextures; i < numgltextures; i++, glt++) { + for (i = 0, glt = gltextures; i < numgltextures; i++, glt++) { if (strequal (identifier, glt->identifier)) { if (crc != glt->crc - || width != glt->width - || height != glt->height - || bytesperpixel != glt->bytesperpixel) - goto SetupTexture; + || width != glt->width + || height != glt->height + || bytesperpixel != glt->bytesperpixel) goto SetupTexture; else return gltextures[i].texnum; } @@ -1291,7 +1338,7 @@ GL_LoadTexture (char *identifier, int width, int height, byte *data, qboolean mi glt->texnum = texture_extension_number; texture_extension_number++; -SetupTexture: + SetupTexture: glt->crc = crc; glt->width = width; glt->height = height; @@ -1309,7 +1356,7 @@ SetupTexture: break; default: Sys_Error ("SetupTexture: unknown bytesperpixel %i", - glt->bytesperpixel); + glt->bytesperpixel); } return glt->texnum; @@ -1321,7 +1368,9 @@ SetupTexture: GL_LoadPicTexture ================ */ -static int GL_LoadPicTexture (qpic_t *pic) +static int +GL_LoadPicTexture (qpic_t *pic) { - return GL_LoadTexture ("", pic->width, pic->height, pic->data, false, true, 1); + return GL_LoadTexture ("", pic->width, pic->height, pic->data, false, true, + 1); } diff --git a/source/gl_dyn_fires.c b/source/gl_dyn_fires.c index 56cf14b..e063ae8 100644 --- a/source/gl_dyn_fires.c +++ b/source/gl_dyn_fires.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "cmd.h" #include "console.h" @@ -38,8 +38,8 @@ #define MAX_FIRES 128 // rocket flames -static fire_t r_fires[MAX_FIRES]; -extern cvar_t *gl_fires; +static fire_t r_fires[MAX_FIRES]; +extern cvar_t *gl_fires; /* R_AddFire @@ -47,39 +47,38 @@ extern cvar_t *gl_fires; Nifty ball of fire GL effect. Kinda a meshing of the dlight and particle engine code. */ -float r_firecolor[3] = {0.9, 0.4, 0}; +float r_firecolor[3] = { 0.9, 0.4, 0 }; void R_AddFire (vec3_t start, vec3_t end, entity_t *ent) { - float len; - fire_t *f; - dlight_t *dl; - vec3_t vec; - int key; + float len; + fire_t *f; + dlight_t *dl; + vec3_t vec; + int key; if (!gl_fires->int_val) return; VectorSubtract (end, start, vec); len = VectorNormalize (vec); - key = ent-cl_visedicts+1; + key = ent - cl_visedicts + 1; - if (len) - { + if (len) { f = R_AllocFire (key); VectorCopy (end, f->origin); VectorCopy (start, f->owner); f->size = 20; f->die = cl.time + 0.5; f->decay = -1; - f->color=r_firecolor; + f->color = r_firecolor; dl = CL_AllocDlight (key); VectorCopy (end, dl->origin); dl->radius = 200; dl->die = cl.time + 0.5; - dl->color=r_firecolor; + dl->color = r_firecolor; } } @@ -88,30 +87,29 @@ R_AddFire (vec3_t start, vec3_t end, entity_t *ent) Clears out and returns a new fireball */ -fire_t * +fire_t * R_AllocFire (int key) { - int i; - fire_t *f; - if (key) // first try to find/reuse a keyed spot + int i; + fire_t *f; + + if (key) // first try to find/reuse a keyed + // spot { f = r_fires; for (i = 0; i < MAX_FIRES; i++, f++) - if (f->key == key) - { - memset (f, 0, sizeof(*f)); + if (f->key == key) { + memset (f, 0, sizeof (*f)); f->key = key; f->color = f->_color; return f; } } - f = r_fires; // no match, look for a free spot - for (i = 0; i < MAX_FIRES; i++, f++) - { - if (f->die < cl.time) - { - memset (f, 0, sizeof(*f)); + f = r_fires; // no match, look for a free spot + for (i = 0; i < MAX_FIRES; i++, f++) { + if (f->die < cl.time) { + memset (f, 0, sizeof (*f)); f->key = key; f->color = f->_color; return f; @@ -119,10 +117,10 @@ R_AllocFire (int key) } f = &r_fires[0]; - memset (f, 0, sizeof(*f)); + memset (f, 0, sizeof (*f)); f->key = key; f->color = f->_color; - return f; + return f; } /* @@ -133,10 +131,10 @@ R_AllocFire (int key) void R_DrawFire (fire_t *f) { - int i, j; - vec3_t vec,vec2; - float radius; - float *b_sin, *b_cos; + int i, j; + vec3_t vec, vec2; + float radius; + float *b_sin, *b_cos; b_sin = bubble_sintable; b_cos = bubble_costable; @@ -145,40 +143,37 @@ R_DrawFire (fire_t *f) // figure out if we're inside the area of effect VectorSubtract (f->origin, r_origin, vec); - if (Length (vec) < radius) - { + if (Length (vec) < radius) { AddLightBlend (1, 0.5, 0, f->size * 0.0003); // we are return; } - // we're not - draw it glBegin (GL_TRIANGLE_FAN); if (lighthalf) - glColor3f(f->color[0]*0.5,f->color[1]*0.5,f->color[2]*0.5); + glColor3f (f->color[0] * 0.5, f->color[1] * 0.5, f->color[2] * 0.5); else - glColor3fv(f->color); - for (i=0 ; i<3 ; i++) + glColor3fv (f->color); + for (i = 0; i < 3; i++) vec[i] = f->origin[i] - vpn[i] * radius; glVertex3fv (vec); glColor3f (0.0, 0.0, 0.0); // don't panic, this just draws a bubble... - for (i=16 ; i>=0 ; i--) - { - for (j=0 ; j<3 ; j++) { + for (i = 16; i >= 0; i--) { + for (j = 0; j < 3; j++) { vec[j] = f->origin[j] + (*b_cos * vright[j] - + vup[j]*(*b_sin)) * radius; + + vup[j] * (*b_sin)) * radius; vec2[j] = f->owner[j] + (*b_cos * vright[j] - + vup[j]*(*b_sin)) * radius; + + vup[j] * (*b_sin)) * radius; } glVertex3fv (vec); glVertex3fv (vec2); - b_sin+=2; - b_cos+=2; + b_sin += 2; + b_cos += 2; } glEnd (); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } /* @@ -189,19 +184,18 @@ R_DrawFire (fire_t *f) void R_UpdateFires (void) { - int i; - fire_t *f; + int i; + fire_t *f; if (!gl_fires->int_val) return; - glDepthMask(GL_FALSE); + glDepthMask (GL_FALSE); glDisable (GL_TEXTURE_2D); glBlendFunc (GL_ONE, GL_ONE); f = r_fires; - for (i = 0; i < MAX_FIRES; i++, f++) - { + for (i = 0; i < MAX_FIRES; i++, f++) { if (f->die < cl.time || !f->size) continue; f->size += f->decay; @@ -210,28 +204,27 @@ R_UpdateFires (void) glEnable (GL_TEXTURE_2D); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(GL_TRUE); + glDepthMask (GL_TRUE); } void R_FireColor_f (void) { - int i; + int i; - if (Cmd_Argc() == 1) { + if (Cmd_Argc () == 1) { Con_Printf ("r_firecolor %g %g %g\n", - r_firecolor[0], - r_firecolor[1], - r_firecolor[2]); + r_firecolor[0], r_firecolor[1], r_firecolor[2]); return; } - if (Cmd_Argc() == 5 || Cmd_Argc() == 6) { - Con_Printf ("Warning: obsolete 4th and 5th parameters to r_firecolor ignored\n"); - } else if (Cmd_Argc() !=4) { + if (Cmd_Argc () == 5 || Cmd_Argc () == 6) { + Con_Printf + ("Warning: obsolete 4th and 5th parameters to r_firecolor ignored\n"); + } else if (Cmd_Argc () != 4) { Con_Printf ("Usage r_firecolor R G B\n"); return; } - for (i=0; i<4; i++) { - r_firecolor[i]=atof(Cmd_Argv(i+1)); + for (i = 0; i < 4; i++) { + r_firecolor[i] = atof (Cmd_Argv (i + 1)); } } diff --git a/source/gl_dyn_part.c b/source/gl_dyn_part.c index f05361b..5fed91f 100644 --- a/source/gl_dyn_part.c +++ b/source/gl_dyn_part.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -41,60 +41,60 @@ #include #define MAX_PARTICLES 2048 // default max # of particles at one - // time -#define ABSOLUTE_MIN_PARTICLES 512 // no fewer than this no matter what's - // on the command line + // time +#define ABSOLUTE_MIN_PARTICLES 512 // no fewer than this no matter + // what's + // on the command line typedef enum { - pt_static, pt_grav, pt_blob, pt_blob2, - pt_smoke, pt_smokecloud, pt_bloodcloud, + pt_static, pt_grav, pt_blob, pt_blob2, + pt_smoke, pt_smokecloud, pt_bloodcloud, pt_fadespark, pt_fadespark2, pt_fallfadespark } ptype_t; -typedef struct particle_s -{ +typedef struct particle_s { // driver-usable fields - vec3_t org; - int tex; - float color; - float alpha; - float scale; + vec3_t org; + int tex; + float color; + float alpha; + float scale; // drivers never touch the following fields - struct particle_s *next; - vec3_t vel; - float ramp; - float die; - ptype_t type; + struct particle_s *next; + vec3_t vel; + float ramp; + float die; + ptype_t type; } particle_t; - -static particle_t *particles, **freeparticles; -static short r_numparticles, numparticles; -extern qboolean lighthalf; +static particle_t *particles, **freeparticles; +static short r_numparticles, numparticles; -extern void GDT_Init(); -extern int part_tex_smoke[8]; -extern int part_tex_dot; +extern qboolean lighthalf; -int ramp[8] = {0x6d, 0x6b, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}; +extern void GDT_Init (); +extern int part_tex_smoke[8]; +extern int part_tex_dot; + +int ramp[8] = { 0x6d, 0x6b, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }; inline particle_t * -particle_new(ptype_t type, int texnum, vec3_t org, float scale, vec3_t vel, - float die, byte color, byte alpha) +particle_new (ptype_t type, int texnum, vec3_t org, float scale, vec3_t vel, + float die, byte color, byte alpha) { particle_t *part; if (numparticles >= r_numparticles) { - //Con_Printf("FAILED PARTICLE ALLOC!\n"); + // Con_Printf("FAILED PARTICLE ALLOC!\n"); return NULL; } part = &particles[numparticles++]; part->type = type; - VectorCopy(org, part->org); - VectorCopy(vel, part->vel); + VectorCopy (org, part->org); + VectorCopy (vel, part->vel); part->die = die; part->color = color; part->alpha = alpha; @@ -105,19 +105,20 @@ particle_new(ptype_t type, int texnum, vec3_t org, float scale, vec3_t vel, } inline particle_t * -particle_new_random(ptype_t type, int texnum, vec3_t org, int org_fuzz, - float scale, int vel_fuzz, float die, byte color, byte alpha) +particle_new_random (ptype_t type, int texnum, vec3_t org, int org_fuzz, + float scale, int vel_fuzz, float die, byte color, + byte alpha) { - vec3_t porg, pvel; - int j; + vec3_t porg, pvel; + int j; - for (j=0 ; j<3 ; j++) { + for (j = 0; j < 3; j++) { if (org_fuzz) - porg[j] = lhrandom(-org_fuzz, org_fuzz) + org[j]; + porg[j] = lhrandom (-org_fuzz, org_fuzz) + org[j]; if (vel_fuzz) - pvel[j] = lhrandom(-vel_fuzz, vel_fuzz); + pvel[j] = lhrandom (-vel_fuzz, vel_fuzz); } - return particle_new(type, texnum, porg, scale, pvel, die, color, alpha); + return particle_new (type, texnum, porg, scale, pvel, die, color, alpha); } /* @@ -125,25 +126,27 @@ particle_new_random(ptype_t type, int texnum, vec3_t org, int org_fuzz, R_InitParticles =============== */ -void R_InitParticles (void) +void +R_InitParticles (void) { - int i; + int i; i = COM_CheckParm ("-particles"); if (i) { - r_numparticles = max(ABSOLUTE_MIN_PARTICLES, atoi(com_argv[i+1])); + r_numparticles = max (ABSOLUTE_MIN_PARTICLES, atoi (com_argv[i + 1])); } else { r_numparticles = MAX_PARTICLES; } particles = (particle_t *) - Hunk_AllocName (r_numparticles * sizeof(particle_t), "particles"); + Hunk_AllocName (r_numparticles * sizeof (particle_t), "particles"); + freeparticles = (void *) - Hunk_AllocName (r_numparticles * sizeof(particle_t), "particles"); + Hunk_AllocName (r_numparticles * sizeof (particle_t), "particles"); - GDT_Init(); + GDT_Init (); } @@ -152,48 +155,51 @@ void R_InitParticles (void) R_ClearParticles =============== */ -void R_ClearParticles (void) +void +R_ClearParticles (void) { numparticles = 0; } -void R_ReadPointFile_f (void) +void +R_ReadPointFile_f (void) { - QFile *f; - vec3_t org; - int r; - int c; - char name[MAX_OSPATH], *mapname, *t1; + QFile *f; + vec3_t org; + int r; + int c; + char name[MAX_OSPATH], *mapname, *t1; - mapname = strdup(cl.worldmodel->name); + mapname = strdup (cl.worldmodel->name); if (!mapname) - Sys_Error("Can't duplicate mapname!"); - t1 = strrchr(mapname, '.'); + Sys_Error ("Can't duplicate mapname!"); + t1 = strrchr (mapname, '.'); if (!t1) - Sys_Error("Can't find .!"); + Sys_Error ("Can't find .!"); t1[0] = '\0'; - snprintf (name, sizeof(name), "%s.pts", mapname); - free(mapname); + snprintf (name, sizeof (name), "%s.pts", mapname); + free (mapname); COM_FOpenFile (name, &f); if (!f) { Con_Printf ("couldn't open %s\n", name); return; } - + Con_Printf ("Reading %s...\n", name); c = 0; - for ( ;; ) { - char buf[64]; - Qgets (f, buf, sizeof(buf)); - r = sscanf (buf,"%f %f %f\n", &org[0], &org[1], &org[2]); + for (;;) { + char buf[64]; + + Qgets (f, buf, sizeof (buf)); + r = sscanf (buf, "%f %f %f\n", &org[0], &org[1], &org[2]); if (r != 3) break; c++; - - if (!particle_new(pt_static, part_tex_dot, org, 2, vec3_origin, 99999, - (-c)&15, 255)) { + + if (!particle_new (pt_static, part_tex_dot, org, 2, vec3_origin, 99999, + (-c) & 15, 255)) { Con_Printf ("Not enough free particles\n"); break; } @@ -202,20 +208,22 @@ void R_ReadPointFile_f (void) Qclose (f); Con_Printf ("%i points read\n", c); } - + /* =============== R_ParticleExplosion =============== */ -void R_ParticleExplosion (vec3_t org) +void +R_ParticleExplosion (vec3_t org) { if (!gl_particles->int_val) return; - particle_new_random(pt_smokecloud, part_tex_smoke[rand()&7], org, 8, 30, - 8, cl.time + 5, (rand()&7) + 8, 128 + (rand()&63)); + particle_new_random (pt_smokecloud, part_tex_smoke[rand () & 7], org, 8, 30, + 8, cl.time + 5, (rand () & 7) + 8, + 128 + (rand () & 63)); } /* @@ -224,38 +232,43 @@ R_BlobExplosion =============== */ -void R_BlobExplosion (vec3_t org) +void +R_BlobExplosion (vec3_t org) { - int i; - + int i; + if (!gl_particles->int_val) return; - for (i=0 ; i<512 ; i++) { - particle_new_random(pt_blob, part_tex_dot, org, 16, 2, 256, - (cl.time + 1 + (rand()&8)*0.05), (66 + rand()%6), 255); + for (i = 0; i < 512; i++) { + particle_new_random (pt_blob, part_tex_dot, org, 16, 2, 256, + (cl.time + 1 + (rand () & 8) * 0.05), + (66 + rand () % 6), 255); } - for (i=0 ; i<512 ; i++) { - particle_new_random(pt_blob2, part_tex_dot, org, 16, 2, 256, - (cl.time + 1 + (rand()&8)*0.05), (150 + rand()%6), 255); + for (i = 0; i < 512; i++) { + particle_new_random (pt_blob2, part_tex_dot, org, 16, 2, 256, + (cl.time + 1 + (rand () & 8) * 0.05), + (150 + rand () % 6), 255); } } -static void R_RunSparkEffect (vec3_t org, int count, int ofuzz) +static void +R_RunSparkEffect (vec3_t org, int count, int ofuzz) { if (!gl_particles->int_val) return; - particle_new (pt_smokecloud, part_tex_smoke[rand()&7], org, ofuzz / 8, - vec3_origin, cl.time + 99, 12 + (rand()&3), 96); + particle_new (pt_smokecloud, part_tex_smoke[rand () & 7], org, ofuzz / 8, + vec3_origin, cl.time + 99, 12 + (rand () & 3), 96); while (count--) particle_new_random (pt_fallfadespark, part_tex_dot, org, ofuzz, 1, 96, - cl.time + 5, ramp[rand()%6], lhrandom(0, 255)); + cl.time + 5, ramp[rand () % 6], lhrandom (0, 255)); } -static void R_RunGunshotEffect (vec3_t org, int count) +static void +R_RunGunshotEffect (vec3_t org, int count) { - int scale; + int scale; if (!gl_particles->int_val) return; @@ -265,17 +278,18 @@ static void R_RunGunshotEffect (vec3_t org, int count) else scale = 2; - R_RunSparkEffect(org, count * 10, 8 * scale); + R_RunSparkEffect (org, count * 10, 8 * scale); return; } -static void R_BloodPuff (vec3_t org, int count) +static void +R_BloodPuff (vec3_t org, int count) { if (!gl_particles->int_val) return; - - particle_new(pt_bloodcloud, part_tex_smoke[rand()&7], org, 12, vec3_origin, - cl.time + 99, 68+(rand()&3), 128); + + particle_new (pt_bloodcloud, part_tex_smoke[rand () & 7], org, 12, + vec3_origin, cl.time + 99, 68 + (rand () & 3), 128); } /* @@ -284,7 +298,8 @@ R_RunPuffEffect =============== */ -void R_RunPuffEffect (vec3_t org, byte type, byte count) +void +R_RunPuffEffect (vec3_t org, byte type, byte count) { if (!gl_particles->int_val) return; @@ -297,7 +312,7 @@ void R_RunPuffEffect (vec3_t org, byte type, byte count) R_BloodPuff (org, count); break; case TE_LIGHTNINGBLOOD: - R_BloodPuff (org, 5+(rand()&1)); + R_BloodPuff (org, 5 + (rand () & 1)); break; } } @@ -308,10 +323,11 @@ R_RunParticleEffect =============== */ -void R_RunParticleEffect (vec3_t org, int color, int count) +void +R_RunParticleEffect (vec3_t org, int color, int count) { - int i, j, scale; - vec3_t porg; + int i, j, scale; + vec3_t porg; if (!gl_particles->int_val) return; @@ -323,31 +339,31 @@ void R_RunParticleEffect (vec3_t org, int color, int count) else scale = 1; - for (i=0 ; iint_val) return; - for (i=-16 ; i<16 ; i++) { - for (j=-16 ; j<16 ; j++) { - dir[0] = j*8 + (rand()&7); - dir[1] = i*8 + (rand()&7); + for (i = -16; i < 16; i++) { + for (j = -16; j < 16; j++) { + dir[0] = j * 8 + (rand () & 7); + dir[1] = i * 8 + (rand () & 7); dir[2] = 256; porg[0] = org[0] + dir[0]; porg[1] = org[1] + dir[1]; - porg[2] = org[2] + (rand()&63); + porg[2] = org[2] + (rand () & 63); - VectorNormalize (dir); - vel = 50 + (rand()&63); + VectorNormalize (dir); + vel = 50 + (rand () & 63); VectorScale (dir, vel, pvel); - particle_new(pt_grav, part_tex_dot, porg, 2, pvel, - (cl.time + 2 + (rand()&31) * 0.02), (224 + (rand()&7)), 255); + particle_new (pt_grav, part_tex_dot, porg, 2, pvel, + (cl.time + 2 + (rand () & 31) * 0.02), + (224 + (rand () & 7)), 255); } } } @@ -392,56 +410,56 @@ R_TeleportSplash =============== */ -void R_TeleportSplash (vec3_t org) +void +R_TeleportSplash (vec3_t org) { - int i, j, k; - float vel; - vec3_t dir, porg, pvel; + int i, j, k; + float vel; + vec3_t dir, porg, pvel; if (!gl_particles->int_val) return; - for (i=-16 ; i<16 ; i+=4) - for (j=-16 ; j<16 ; j+=4) - for (k=-24 ; k<32 ; k+=4) - { - dir[0] = j*8; - dir[1] = i*8; - dir[2] = k*8; - - porg[0] = org[0] + i + (rand()&3); - porg[1] = org[1] + j + (rand()&3); - porg[2] = org[2] + k + (rand()&3); - - VectorNormalize (dir); - vel = 50 + (rand()&63); + for (i = -16; i < 16; i += 4) + for (j = -16; j < 16; j += 4) + for (k = -24; k < 32; k += 4) { + dir[0] = j * 8; + dir[1] = i * 8; + dir[2] = k * 8; + + porg[0] = org[0] + i + (rand () & 3); + porg[1] = org[1] + j + (rand () & 3); + porg[2] = org[2] + k + (rand () & 3); + + VectorNormalize (dir); + vel = 50 + (rand () & 63); VectorScale (dir, vel, pvel); - particle_new(pt_grav, part_tex_dot, porg, 2, pvel, - (cl.time + 0.2 + (rand()&7) * 0.02), - (7 + (rand()&7)), 255); + particle_new (pt_grav, part_tex_dot, porg, 2, pvel, + (cl.time + 0.2 + (rand () & 7) * 0.02), + (7 + (rand () & 7)), 255); } } -void R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) +void +R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) { - vec3_t vec; - float len; - int j, ptex; - ptype_t ptype; - vec3_t porg, pvel; - float pdie, pscale; - byte palpha, pcolor; + vec3_t vec; + float len; + int j, ptex; + ptype_t ptype; + vec3_t porg, pvel; + float pdie, pscale; + byte palpha, pcolor; if (type == 0) R_AddFire (start, end, ent); if (!gl_particles->int_val) return; - + VectorSubtract (end, start, vec); len = VectorNormalize (vec); - while (len > 0) - { + while (len > 0) { VectorCopy (vec3_origin, pvel); pdie = cl.time + 2; ptype = pt_static; @@ -451,71 +469,68 @@ void R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) palpha = 255; switch (type) { - case 0: // rocket trail - pcolor = (rand()&3)+12; + case 0: // rocket trail + pcolor = (rand () & 3) + 12; goto common_rocket_gren_trail; - case 1: // grenade trail - pcolor = (rand()&3)+3; + case 1: // grenade trail + pcolor = (rand () & 3) + 3; goto common_rocket_gren_trail; -common_rocket_gren_trail: + common_rocket_gren_trail: len -= 4; - ptex = part_tex_smoke[rand()&7]; - pscale = lhrandom(8, 12); - palpha = 48 + (rand()&31); + ptex = part_tex_smoke[rand () & 7]; + pscale = lhrandom (8, 12); + palpha = 48 + (rand () & 31); ptype = pt_smoke; pdie = cl.time + 1; - VectorCopy(start, porg); + VectorCopy (start, porg); break; - case 2: // blood - case 4: // slight blood + case 2: // blood + case 4: // slight blood len -= 5; ptex = part_tex_dot; pscale = 1; - pcolor = 68 + (rand()&3); + pcolor = 68 + (rand () & 3); pdie = cl.time + 2; - for (j=0 ; j<3 ; j++) { - pvel[j] = (rand()&15)-8; - porg[j] = start[j] + ((rand()%3)-2); + for (j = 0; j < 3; j++) { + pvel[j] = (rand () & 15) - 8; + porg[j] = start[j] + ((rand () % 3) - 2); } ptype = pt_grav; palpha = 255; break; - case 6: // voor trail + case 6: // voor trail len -= 3; - pcolor = 9*16 + 8 + (rand()&3); + pcolor = 9 * 16 + 8 + (rand () & 3); ptype = pt_static; - pscale = lhrandom(1, 2); + pscale = lhrandom (1, 2); pdie = cl.time + 0.3; - for (j=0 ; j<3 ; j++) - porg[j] = start[j] + ((rand()&15)-8); + for (j = 0; j < 3; j++) + porg[j] = start[j] + ((rand () & 15) - 8); break; case 3: - case 5: // tracer + case 5: // tracer { - static int tracercount; + static int tracercount; len -= 3; pdie = cl.time + 0.5; ptype = pt_static; - pscale = lhrandom(2, 4); + pscale = lhrandom (2, 4); if (type == 3) - pcolor = 52 + ((tracercount&4)<<1); + pcolor = 52 + ((tracercount & 4) << 1); else - pcolor = 230 + ((tracercount&4)<<1); + pcolor = 230 + ((tracercount & 4) << 1); tracercount++; VectorCopy (start, porg); - if (tracercount & 1) - { - pvel[0] = 30*vec[1]; - pvel[1] = 30*-vec[0]; - } - else - { - pvel[0] = 30*-vec[1]; - pvel[1] = 30*vec[0]; + if (tracercount & 1) { + pvel[0] = 30 * vec[1]; + pvel[1] = 30 * -vec[0]; + } else { + pvel[0] = 30 * -vec[1]; + pvel[1] = 30 * vec[0]; } break; } @@ -523,7 +538,7 @@ common_rocket_gren_trail: VectorAdd (start, vec, start); - particle_new(ptype, ptex, porg, pscale, pvel, pdie, pcolor, palpha); + particle_new (ptype, ptex, porg, pscale, pvel, pdie, pcolor, palpha); } } @@ -533,28 +548,29 @@ common_rocket_gren_trail: R_DrawParticles =============== */ -void R_DrawParticles (void) +void +R_DrawParticles (void) { - byte i; - float grav, fast_grav, dvel; - float minparticledist; - unsigned char *at; - byte alpha; - vec3_t up, right; - float scale, scale2; - particle_t *part; - int activeparticles, maxparticle, j, k; + byte i; + float grav, fast_grav, dvel; + float minparticledist; + unsigned char *at; + byte alpha; + vec3_t up, right; + float scale, scale2; + particle_t *part; + int activeparticles, maxparticle, j, k; // LordHavoc: particles should not affect zbuffer - glDepthMask(GL_FALSE); + glDepthMask (GL_FALSE); VectorScale (vup, 1.5, up); VectorScale (vright, 1.5, right); grav = (fast_grav = host_frametime * 800) * 0.05; - dvel = 4*host_frametime; - - minparticledist = DotProduct(r_refdef.vieworg, vpn) + 32.0f; + dvel = 4 * host_frametime; + + minparticledist = DotProduct (r_refdef.vieworg, vpn) + 32.0f; activeparticles = 0; @@ -571,119 +587,117 @@ void R_DrawParticles (void) // Don't render particles too close to us. // Note, we must still do physics and such on them. - if (!(DotProduct(part->org, vpn) < minparticledist)) { - at = (byte *)&d_8to24table[(byte)part->color]; + if (!(DotProduct (part->org, vpn) < minparticledist)) { + at = (byte *) & d_8to24table[(byte) part->color]; alpha = part->alpha; if (lighthalf) - glColor4ub((byte) ((int) at[0] >> 1), (byte) ((int) at[1] >> 1), (byte) ((int) at[2] >> 1), alpha); + glColor4ub ((byte) ((int) at[0] >> 1), + (byte) ((int) at[1] >> 1), + (byte) ((int) at[2] >> 1), alpha); else - glColor4ub(at[0], at[1], at[2], alpha); + glColor4ub (at[0], at[1], at[2], alpha); scale = part->scale * 0.75; scale2 = part->scale * -0.75; - glBindTexture(GL_TEXTURE_2D, part->tex); + glBindTexture (GL_TEXTURE_2D, part->tex); glBegin (GL_QUADS); - glTexCoord2f(0,1); - glVertex3f((part->org[0] + up[0]*scale + right[0]*scale), - (part->org[1] + up[1]*scale + right[1]*scale), - (part->org[2] + up[2]*scale + right[2]*scale)); + glTexCoord2f (0, 1); + glVertex3f ((part->org[0] + up[0] * scale + right[0] * scale), + (part->org[1] + up[1] * scale + right[1] * scale), + (part->org[2] + up[2] * scale + right[2] * scale)); - glTexCoord2f(0,0); - glVertex3f((part->org[0] + up[0]*scale2 + right[0]*scale), - (part->org[1] + up[1]*scale2 + right[1]*scale), - (part->org[2] + up[2]*scale2 + right[2]*scale)); + glTexCoord2f (0, 0); + glVertex3f ((part->org[0] + up[0] * scale2 + right[0] * scale), + (part->org[1] + up[1] * scale2 + right[1] * scale), + (part->org[2] + up[2] * scale2 + right[2] * scale)); - glTexCoord2f(1,0); - glVertex3f((part->org[0] + up[0]*scale2 + right[0]*scale2), - (part->org[1] + up[1]*scale2 + right[1]*scale2), - (part->org[2] + up[2]*scale2 + right[2]*scale2)); + glTexCoord2f (1, 0); + glVertex3f ((part->org[0] + up[0] * scale2 + right[0] * scale2), + (part->org[1] + up[1] * scale2 + right[1] * scale2), + (part->org[2] + up[2] * scale2 + right[2] * scale2)); - glTexCoord2f(1,1); - glVertex3f((part->org[0] + up[0]*scale + right[0]*scale2), - (part->org[1] + up[1]*scale + right[1]*scale2), - (part->org[2] + up[2]*scale + right[2]*scale2)); + glTexCoord2f (1, 1); + glVertex3f ((part->org[0] + up[0] * scale + right[0] * scale2), + (part->org[1] + up[1] * scale + right[1] * scale2), + (part->org[2] + up[2] * scale + right[2] * scale2)); - glEnd(); + glEnd (); } - for (i=0 ; i<3 ; i++) - part->org[i] += part->vel[i]*host_frametime; - - + for (i = 0; i < 3; i++) + part->org[i] += part->vel[i] * host_frametime; + + #define alpha_die(p) if (p->alpha < 1) part->die = -1; - switch (part->type) - { - case pt_static: - break; - - case pt_blob: - for (i=0 ; i<3 ; i++) - part->vel[i] += part->vel[i]*dvel; - part->vel[2] -= grav; - break; - - case pt_blob2: - for (i=0 ; i<2 ; i++) - part->vel[i] -= part->vel[i]*dvel; - part->vel[2] -= grav; - break; - - case pt_grav: - part->vel[2] -= grav; - break; - - case pt_smoke: - part->scale += host_frametime * 6; - part->alpha -= host_frametime * 128; - alpha_die(part); - break; - case pt_smokecloud: - part->scale += host_frametime * 60; - part->alpha -= host_frametime * 128; - alpha_die(part); - break; - case pt_bloodcloud: - /* - if (Mod_PointInLeaf(part->org, cl.worldmodel)->contents != CONTENTS_EMPTY) { - part->die = -1; + switch (part->type) { + case pt_static: + break; + + case pt_blob: + for (i = 0; i < 3; i++) + part->vel[i] += part->vel[i] * dvel; + part->vel[2] -= grav; + break; + + case pt_blob2: + for (i = 0; i < 2; i++) + part->vel[i] -= part->vel[i] * dvel; + part->vel[2] -= grav; + break; + + case pt_grav: + part->vel[2] -= grav; + break; + + case pt_smoke: + part->scale += host_frametime * 6; + part->alpha -= host_frametime * 128; + alpha_die (part); + break; + case pt_smokecloud: + part->scale += host_frametime * 60; + part->alpha -= host_frametime * 128; + alpha_die (part); + break; + case pt_bloodcloud: + /* + if (Mod_PointInLeaf(part->org, cl.worldmodel)->contents != + CONTENTS_EMPTY) { part->die = -1; break; } */ + part->scale += host_frametime * 4; + part->alpha -= host_frametime * 64; + part->vel[2] -= grav; + alpha_die (part); + break; + case pt_fadespark: + part->alpha -= host_frametime * 256; + part->vel[2] -= grav; + if (part->alpha < 1) + part->die = -1; + break; + case pt_fadespark2: + part->alpha -= host_frametime * 512; + part->vel[2] -= grav; + alpha_die (part); + break; + case pt_fallfadespark: + part->alpha -= host_frametime * 256; + part->vel[2] -= fast_grav; + if (part->alpha < 1) + part->die = -1; break; - } - */ - part->scale += host_frametime * 4; - part->alpha -= host_frametime * 64; - part->vel[2] -= grav; - alpha_die(part); - break; - case pt_fadespark: - part->alpha -= host_frametime * 256; - part->vel[2] -= grav; - if (part->alpha < 1) - part->die = -1; - break; - case pt_fadespark2: - part->alpha -= host_frametime * 512; - part->vel[2] -= grav; - alpha_die(part); - break; - case pt_fallfadespark: - part->alpha -= host_frametime * 256; - part->vel[2] -= fast_grav; - if (part->alpha < 1) - part->die = -1; - break; } } k = 0; while (maxparticle >= activeparticles) { *freeparticles[k++] = particles[maxparticle--]; - while (maxparticle >= activeparticles && particles[maxparticle].die < cl.time) - maxparticle--; + while (maxparticle >= activeparticles + && particles[maxparticle].die < cl.time) maxparticle--; } numparticles = activeparticles; - glColor3ubv(lighthalf_v); - glDepthMask(GL_TRUE); + glColor3ubv (lighthalf_v); + glDepthMask (GL_TRUE); } diff --git a/source/gl_dyn_textures.c b/source/gl_dyn_textures.c index b50e13e..3005ff3 100644 --- a/source/gl_dyn_textures.c +++ b/source/gl_dyn_textures.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "glquake.h" @@ -38,81 +38,85 @@ static void GDT_InitDotParticleTexture (void); static void GDT_InitSmokeParticleTexture (void); -int part_tex_smoke[8]; -int part_tex_dot; +int part_tex_smoke[8]; +int part_tex_dot; -void GDT_Init (void) +void +GDT_Init (void) { - GDT_InitDotParticleTexture(); - GDT_InitSmokeParticleTexture(); + GDT_InitDotParticleTexture (); + GDT_InitSmokeParticleTexture (); } -byte dottexture[4][4] = -{ - {0,1,1,0}, - {1,1,1,1}, - {1,1,1,1}, - {0,1,1,0}, +byte dottexture[4][4] = { + {0, 1, 1, 0}, + {1, 1, 1, 1}, + {1, 1, 1, 1}, + {0, 1, 1, 0}, }; -static void GDT_InitDotParticleTexture (void) +static void +GDT_InitDotParticleTexture (void) { - int x, y; - byte data[4][4][4]; + int x, y; + byte data[4][4][4]; - // + // // particle texture - // + // part_tex_dot = texture_extension_number++; glBindTexture (GL_TEXTURE_2D, part_tex_dot); - for (x=0 ; x<4 ; x++) - { - for (y=0 ; y<4 ; y++) - { + for (x = 0; x < 4; x++) { + for (y = 0; y < 4; y++) { data[y][x][0] = 244; data[y][x][1] = 244; data[y][x][2] = 244; - data[y][x][3] = dottexture[x][y]*244; + data[y][x][3] = dottexture[x][y] * 244; } } - glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 4, 4, 0, GL_RGBA, + GL_UNSIGNED_BYTE, data); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } -static void GDT_InitSmokeParticleTexture (void) +static void +GDT_InitSmokeParticleTexture (void) { - int i, x, y, d; - float dx, dy; - byte data[32][32][4], noise1[32][32], noise2[32][32]; - for (i = 0;i < 8;i++) { - fractalnoise(&noise1[0][0], 32); - fractalnoise(&noise2[0][0], 32); - for (y = 0;y < 32;y++) - for (x = 0;x < 32;x++) { - data[y][x][0] = data[y][x][1] = data[y][x][2] = (noise1[y][x] >> 1) + 128; + int i, x, y, d; + float dx, dy; + byte data[32][32][4], noise1[32][32], noise2[32][32]; + + for (i = 0; i < 8; i++) { + fractalnoise (&noise1[0][0], 32); + fractalnoise (&noise2[0][0], 32); + for (y = 0; y < 32; y++) + for (x = 0; x < 32; x++) { + data[y][x][0] = data[y][x][1] = data[y][x][2] = + (noise1[y][x] >> 1) + 128; dx = x - 16; dy = y - 16; d = noise2[y][x] * 4 - 512; if (d > 0) { if (d > 255) d = 255; - d = (d * (255 - (int) (dx*dx+dy*dy))) >> 8; - if (d < 0) d = 0; - if (d > 255) d = 255; + d = (d * (255 - (int) (dx * dx + dy * dy))) >> 8; + if (d < 0) + d = 0; + if (d > 255) + d = 255; data[y][x][3] = (byte) d; - } - else + } else data[y][x][3] = 0; } part_tex_smoke[i] = texture_extension_number++; - glBindTexture(GL_TEXTURE_2D, part_tex_smoke[i]); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 32, 32, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + glBindTexture (GL_TEXTURE_2D, part_tex_smoke[i]); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, 32, 32, 0, GL_RGBA, + GL_UNSIGNED_BYTE, data); } } - diff --git a/source/gl_mesh.c b/source/gl_mesh.c index 6184ab1..d6c9476 100644 --- a/source/gl_mesh.c +++ b/source/gl_mesh.c @@ -27,29 +27,32 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h #include "qendian.h" #include "quakefs.h" -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" @@ -61,64 +64,64 @@ ALIAS MODEL DISPLAY LIST GENERATION ================================================================= */ -model_t *aliasmodel; -aliashdr_t *paliashdr; +model_t *aliasmodel; +aliashdr_t *paliashdr; -qboolean used[8192]; +qboolean used[8192]; // the command list holds counts and s/t values that are valid for // every frame -int commands[8192]; -int numcommands; +int commands[8192]; +int numcommands; // all frames will have their vertexes rearranged and expanded // so they are in the order expected by the command list -int vertexorder[8192]; -int numorder; +int vertexorder[8192]; +int numorder; -int allverts, alltris; +int allverts, alltris; -int stripverts[128]; -int striptris[128]; -int stripcount; +int stripverts[128]; +int striptris[128]; +int stripcount; /* ================ StripLength ================ */ -int StripLength (int starttri, int startv) +int +StripLength (int starttri, int startv) { - int m1, m2; - int j; - mtriangle_t *last, *check; - int k; + int m1, m2; + int j; + mtriangle_t *last, *check; + int k; used[starttri] = 2; last = &triangles[starttri]; - stripverts[0] = last->vertindex[(startv)%3]; - stripverts[1] = last->vertindex[(startv+1)%3]; - stripverts[2] = last->vertindex[(startv+2)%3]; + stripverts[0] = last->vertindex[(startv) % 3]; + stripverts[1] = last->vertindex[(startv + 1) % 3]; + stripverts[2] = last->vertindex[(startv + 2) % 3]; striptris[0] = starttri; stripcount = 1; - m1 = last->vertindex[(startv+2)%3]; - m2 = last->vertindex[(startv+1)%3]; + m1 = last->vertindex[(startv + 2) % 3]; + m2 = last->vertindex[(startv + 1) % 3]; // look for a matching triangle nexttri: - for (j=starttri+1, check=&triangles[starttri+1] ; jmdl.numtris ; j++, check++) - { + for (j = starttri + 1, check = &triangles[starttri + 1]; + j < pheader->mdl.numtris; j++, check++) { if (check->facesfront != last->facesfront) continue; - for (k=0 ; k<3 ; k++) - { + for (k = 0; k < 3; k++) { if (check->vertindex[k] != m1) continue; - if (check->vertindex[ (k+1)%3 ] != m2) + if (check->vertindex[(k + 1) % 3] != m2) continue; // this is the next part of the fan @@ -129,11 +132,11 @@ nexttri: // the new edge if (stripcount & 1) - m2 = check->vertindex[ (k+2)%3 ]; + m2 = check->vertindex[(k + 2) % 3]; else - m1 = check->vertindex[ (k+2)%3 ]; + m1 = check->vertindex[(k + 2) % 3]; - stripverts[stripcount+2] = check->vertindex[ (k+2)%3 ]; + stripverts[stripcount + 2] = check->vertindex[(k + 2) % 3]; striptris[stripcount] = j; stripcount++; @@ -144,7 +147,7 @@ nexttri: done: // clear the temp used flags - for (j=starttri+1 ; jmdl.numtris ; j++) + for (j = starttri + 1; j < pheader->mdl.numtris; j++) if (used[j] == 2) used[j] = 0; @@ -156,39 +159,39 @@ done: FanLength =========== */ -int FanLength (int starttri, int startv) +int +FanLength (int starttri, int startv) { - int m1, m2; - int j; - mtriangle_t *last, *check; - int k; + int m1, m2; + int j; + mtriangle_t *last, *check; + int k; used[starttri] = 2; last = &triangles[starttri]; - stripverts[0] = last->vertindex[(startv)%3]; - stripverts[1] = last->vertindex[(startv+1)%3]; - stripverts[2] = last->vertindex[(startv+2)%3]; + stripverts[0] = last->vertindex[(startv) % 3]; + stripverts[1] = last->vertindex[(startv + 1) % 3]; + stripverts[2] = last->vertindex[(startv + 2) % 3]; striptris[0] = starttri; stripcount = 1; - m1 = last->vertindex[(startv+0)%3]; - m2 = last->vertindex[(startv+2)%3]; + m1 = last->vertindex[(startv + 0) % 3]; + m2 = last->vertindex[(startv + 2) % 3]; // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] ; jmdl.numtris ; j++, check++) - { + nexttri: + for (j = starttri + 1, check = &triangles[starttri + 1]; + j < pheader->mdl.numtris; j++, check++) { if (check->facesfront != last->facesfront) continue; - for (k=0 ; k<3 ; k++) - { + for (k = 0; k < 3; k++) { if (check->vertindex[k] != m1) continue; - if (check->vertindex[ (k+1)%3 ] != m2) + if (check->vertindex[(k + 1) % 3] != m2) continue; // this is the next part of the fan @@ -198,9 +201,9 @@ nexttri: goto done; // the new edge - m2 = check->vertindex[ (k+2)%3 ]; + m2 = check->vertindex[(k + 2) % 3]; - stripverts[stripcount+2] = m2; + stripverts[stripcount + 2] = m2; striptris[stripcount] = j; stripcount++; @@ -208,10 +211,10 @@ nexttri: goto nexttri; } } -done: + done: // clear the temp used flags - for (j=starttri+1 ; jmdl.numtris ; j++) + for (j = starttri + 1; j < pheader->mdl.numtris; j++) if (used[j] == 2) used[j] = 0; @@ -227,61 +230,58 @@ Generate a list of trifans or strips for the model, which holds for all frames ================ */ -void BuildTris (void) +void +BuildTris (void) { - int i, j, k; - int startv; - float s, t; - int len, bestlen, besttype = 0; - int bestverts[1024]; - int besttris[1024]; - int type; + int i, j, k; + int startv; + float s, t; + int len, bestlen, besttype = 0; + int bestverts[1024]; + int besttris[1024]; + int type; - // + // // build tristrips - // + // numorder = 0; numcommands = 0; - memset (used, 0, sizeof(used)); - for (i=0 ; imdl.numtris ; i++) - { + memset (used, 0, sizeof (used)); + for (i = 0; i < pheader->mdl.numtris; i++) { // pick an unused triangle and start the trifan if (used[i]) continue; bestlen = 0; - for (type = 0 ; type < 2 ; type++) -// type = 1; + for (type = 0; type < 2; type++) +// type = 1; { - for (startv =0 ; startv < 3 ; startv++) - { + for (startv = 0; startv < 3; startv++) { if (type == 1) len = StripLength (i, startv); else len = FanLength (i, startv); - if (len > bestlen) - { + if (len > bestlen) { besttype = type; bestlen = len; - for (j=0 ; jmdl.skinwidth; t = (t + 0.5) / pheader->mdl.skinheight; - *(float *)&commands[numcommands++] = s; - *(float *)&commands[numcommands++] = t; + *(float *) &commands[numcommands++] = s; + *(float *) &commands[numcommands++] = t; } } commands[numcommands++] = 0; // end of list marker - Con_DPrintf ("%3i tri %3i vert %3i cmd\n", pheader->mdl.numtris, numorder, numcommands); + Con_DPrintf ("%3i tri %3i vert %3i cmd\n", pheader->mdl.numtris, numorder, + numcommands); allverts += numorder; alltris += pheader->mdl.numtris; @@ -313,58 +314,56 @@ void BuildTris (void) GL_MakeAliasModelDisplayLists ================ */ -void GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr) +void +GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr) { - int i, j; - int *cmds; - trivertx_t *verts; - char cache[MAX_QPATH], fullpath[MAX_OSPATH]; - QFile *f; + int i, j; + int *cmds; + trivertx_t *verts; + char cache[MAX_QPATH], fullpath[MAX_OSPATH]; + QFile *f; aliasmodel = m; - paliashdr = hdr; // (aliashdr_t *)Mod_Extradata (m); + paliashdr = hdr; // (aliashdr_t *)Mod_Extradata (m); - // + // // look for a cached version - // + // strcpy (cache, "glquake/"); - COM_StripExtension (m->name+strlen("progs/"), cache+strlen("glquake/")); - strncat (cache, ".ms2", sizeof(cache) - strlen (cache)); + COM_StripExtension (m->name + strlen ("progs/"), + cache + strlen ("glquake/")); + strncat (cache, ".ms2", sizeof (cache) - strlen (cache)); - COM_FOpenFile (cache, &f); - if (f) - { + COM_FOpenFile (cache, &f); + if (f) { Qread (f, &numcommands, 4); Qread (f, &numorder, 4); - Qread (f, &commands, numcommands * sizeof(commands[0])); - Qread (f, &vertexorder, numorder * sizeof(vertexorder[0])); + Qread (f, &commands, numcommands * sizeof (commands[0])); + Qread (f, &vertexorder, numorder * sizeof (vertexorder[0])); Qclose (f); - } - else - { - // + } else { + // // build it from scratch - // - Con_Printf ("meshing %s...\n",m->name); + // + Con_Printf ("meshing %s...\n", m->name); - BuildTris (); // trifans or lists + BuildTris (); // trifans or lists - // + // // save out the cached version - // - snprintf (fullpath, sizeof(fullpath), "%s/%s", com_gamedir, cache); + // + snprintf (fullpath, sizeof (fullpath), "%s/%s", com_gamedir, cache); f = Qopen (fullpath, "wb"); if (!f) { COM_CreatePath (fullpath); f = Qopen (fullpath, "wb"); } - if (f) - { + if (f) { Qwrite (f, &numcommands, 4); Qwrite (f, &numorder, 4); - Qwrite (f, &commands, numcommands * sizeof(commands[0])); - Qwrite (f, &vertexorder, numorder * sizeof(vertexorder[0])); + Qwrite (f, &commands, numcommands * sizeof (commands[0])); + Qwrite (f, &vertexorder, numorder * sizeof (vertexorder[0])); Qclose (f); } } @@ -375,14 +374,14 @@ void GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr) paliashdr->poseverts = numorder; cmds = Hunk_Alloc (numcommands * 4); - paliashdr->commands = (byte *)cmds - (byte *)paliashdr; + paliashdr->commands = (byte *) cmds - (byte *) paliashdr; memcpy (cmds, commands, numcommands * 4); - verts = Hunk_Alloc (paliashdr->numposes * paliashdr->poseverts - * sizeof(trivertx_t) ); - paliashdr->posedata = (byte *)verts - (byte *)paliashdr; - for (i=0 ; inumposes ; i++) - for (j=0 ; jnumposes * paliashdr->poseverts + + * sizeof (trivertx_t)); + paliashdr->posedata = (byte *) verts - (byte *) paliashdr; + for (i = 0; i < paliashdr->numposes; i++) + for (j = 0; j < numorder; j++) *verts++ = poseverts[i][vertexorder[j]]; } - diff --git a/source/gl_model_alias.c b/source/gl_model_alias.c index 9edeeb1..b247ea1 100644 --- a/source/gl_model_alias.c +++ b/source/gl_model_alias.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -46,7 +46,7 @@ #include "console.h" #include "glquake.h" -extern model_t *loadmodel; +extern model_t *loadmodel; /* ============================================================================== @@ -56,17 +56,17 @@ ALIAS MODELS ============================================================================== */ -extern aliashdr_t *pheader; +extern aliashdr_t *pheader; -extern stvert_t stverts[MAXALIASVERTS]; -extern mtriangle_t triangles[MAXALIASTRIS]; +extern stvert_t stverts[MAXALIASVERTS]; +extern mtriangle_t triangles[MAXALIASTRIS]; // a pose is a single set of vertexes. a frame may be // an animating sequence of poses -extern trivertx_t *poseverts[MAXALIASFRAMES]; -extern int posenum; +extern trivertx_t *poseverts[MAXALIASFRAMES]; +extern int posenum; -byte player_8bit_texels[320*200]; +byte player_8bit_texels[320 * 200]; //========================================================= @@ -78,9 +78,8 @@ Fill background pixels so mipmapping doesn't have haloes - Ed ================= */ -typedef struct -{ - short x, y; +typedef struct { + short x, y; } floodfill_t; extern unsigned int d_8to24table[]; @@ -100,85 +99,92 @@ extern unsigned int d_8to24table[]; else if (pos[off] != 255) fdc = pos[off]; \ } -void Mod_FloodFillSkin( byte *skin, int skinwidth, int skinheight ) +void +Mod_FloodFillSkin (byte * skin, int skinwidth, int skinheight) { - byte fillcolor = *skin; // assume this is the pixel to fill - floodfill_t fifo[FLOODFILL_FIFO_SIZE]; - int inpt = 0, outpt = 0; - int filledcolor = -1; - int i; + byte fillcolor = *skin; // assume this is the pixel to fill + floodfill_t fifo[FLOODFILL_FIFO_SIZE]; + int inpt = 0, outpt = 0; + int filledcolor = -1; + int i; - if (filledcolor == -1) - { + if (filledcolor == -1) { filledcolor = 0; // attempt to find opaque black for (i = 0; i < 256; ++i) - if (d_8to24table[i] == (255 << 0)) // alpha 1.0 + if (d_8to24table[i] == (255 << 0)) // alpha 1.0 { filledcolor = i; break; } } - - // can't fill to filled color or to transparent color (used as visited marker) - if ((fillcolor == filledcolor) || (fillcolor == 255)) - { - //printf( "not filling skin from %d to %d\n", fillcolor, filledcolor ); + // can't fill to filled color or to transparent color (used as visited + // marker) + if ((fillcolor == filledcolor) || (fillcolor == 255)) { + // printf( "not filling skin from %d to %d\n", fillcolor, filledcolor + // ); return; } fifo[inpt].x = 0, fifo[inpt].y = 0; inpt = (inpt + 1) & FLOODFILL_FIFO_MASK; - while (outpt != inpt) - { - int x = fifo[outpt].x, y = fifo[outpt].y; - int fdc = filledcolor; - byte *pos = &skin[x + skinwidth * y]; + while (outpt != inpt) { + int x = fifo[outpt].x, y = fifo[outpt].y; + int fdc = filledcolor; + byte *pos = &skin[x + skinwidth * y]; outpt = (outpt + 1) & FLOODFILL_FIFO_MASK; - if (x > 0) FLOODFILL_STEP( -1, -1, 0 ); - if (x < skinwidth - 1) FLOODFILL_STEP( 1, 1, 0 ); - if (y > 0) FLOODFILL_STEP( -skinwidth, 0, -1 ); - if (y < skinheight - 1) FLOODFILL_STEP( skinwidth, 0, 1 ); + if (x > 0) + FLOODFILL_STEP (-1, -1, 0); + if (x < skinwidth - 1) + FLOODFILL_STEP (1, 1, 0); + if (y > 0) + FLOODFILL_STEP (-skinwidth, 0, -1); + if (y < skinheight - 1) + FLOODFILL_STEP (skinwidth, 0, 1); skin[x + skinwidth * y] = fdc; } } -int Mod_Fullbright(byte *skin, int width, int height, char *name); +int Mod_Fullbright (byte * skin, int width, int height, char *name); -void *Mod_LoadSkin (byte *skin, int skinsize, int snum, int gnum, qboolean group) +void * +Mod_LoadSkin (byte * skin, int skinsize, int snum, int gnum, qboolean group) { - char name[32]; - int fbtexnum; + char name[32]; + int fbtexnum; - Mod_FloodFillSkin( skin, pheader->mdl.skinwidth, pheader->mdl.skinheight ); + Mod_FloodFillSkin (skin, pheader->mdl.skinwidth, pheader->mdl.skinheight); // save 8 bit texels for the player model to remap - if (!strcmp(loadmodel->name,"progs/player.mdl")) { - if (skinsize > sizeof(player_8bit_texels)) + if (!strcmp (loadmodel->name, "progs/player.mdl")) { + if (skinsize > sizeof (player_8bit_texels)) SV_Error ("Player skin too large"); memcpy (player_8bit_texels, skin, skinsize); } if (group) { - snprintf(name, sizeof(name), "fb_%s_%i_%i", loadmodel->name,snum,gnum); + snprintf (name, sizeof (name), "fb_%s_%i_%i", loadmodel->name, snum, + gnum); } else { - snprintf(name, sizeof(name), "fb_%s_%i", loadmodel->name,snum); + snprintf (name, sizeof (name), "fb_%s_%i", loadmodel->name, snum); } - fbtexnum = Mod_Fullbright(skin+1, pheader->mdl.skinwidth, pheader->mdl.skinheight, name); - if ((loadmodel->hasfullbrights=(fbtexnum))) { + fbtexnum = + Mod_Fullbright (skin + 1, pheader->mdl.skinwidth, + pheader->mdl.skinheight, name); + if ((loadmodel->hasfullbrights = (fbtexnum))) { pheader->gl_fb_texturenum[snum][gnum] = fbtexnum; } if (group) { - snprintf(name, sizeof(name), "%s_%i_%i", loadmodel->name,snum,gnum); + snprintf (name, sizeof (name), "%s_%i_%i", loadmodel->name, snum, gnum); } else { - snprintf(name, sizeof(name), "%s_%i", loadmodel->name,snum); + snprintf (name, sizeof (name), "%s_%i", loadmodel->name, snum); } pheader->gl_texturenum[snum][gnum] = - GL_LoadTexture (name, pheader->mdl.skinwidth, + GL_LoadTexture (name, pheader->mdl.skinwidth, pheader->mdl.skinheight, skin, true, false, 1); - // alpha param was true for non group skins + // alpha param was true for non group skins return skin + skinsize; } @@ -187,56 +193,54 @@ void *Mod_LoadSkin (byte *skin, int skinsize, int snum, int gnum, qboolean group Mod_LoadAllSkins =============== */ -void *Mod_LoadAllSkins (int numskins, daliasskintype_t *pskintype, int *pskinindex) +void * +Mod_LoadAllSkins (int numskins, daliasskintype_t *pskintype, int *pskinindex) { - int i, j, k; - int skinsize; - byte *skin; - daliasskingroup_t *pinskingroup; - int groupskins; - daliasskininterval_t *pinskinintervals; + int i, j, k; + int skinsize; + byte *skin; + daliasskingroup_t *pinskingroup; + int groupskins; + daliasskininterval_t *pinskinintervals; if (numskins < 1 || numskins > MAX_SKINS) SV_Error ("Mod_LoadAliasModel: Invalid # of skins: %d\n", numskins); skinsize = pheader->mdl.skinwidth * pheader->mdl.skinheight; - for (i=0 ; itype == ALIAS_SKIN_SINGLE) { - skin = (byte *)(pskintype+1); + skin = (byte *) (pskintype + 1); skin = Mod_LoadSkin (skin, skinsize, i, 0, false); - for (j=1; j < 4; j++) { - pheader->gl_texturenum[i][j] = - pheader->gl_texturenum[i][j - 1]; - pheader->gl_fb_texturenum[i][j] = - pheader->gl_fb_texturenum[i][j - 1]; + for (j = 1; j < 4; j++) { + pheader->gl_texturenum[i][j] = pheader->gl_texturenum[i][j - 1]; + pheader->gl_fb_texturenum[i][j] = + pheader->gl_fb_texturenum[i][j - 1]; } } else { // animating skin group. yuck. - // Con_Printf("Animating Skin Group, if you get this message please notify warp@debian.org\n"); + // Con_Printf("Animating Skin Group, if you get this message + // please notify warp@debian.org\n"); pskintype++; - pinskingroup = (daliasskingroup_t *)pskintype; + pinskingroup = (daliasskingroup_t *) pskintype; groupskins = LittleLong (pinskingroup->numskins); - pinskinintervals = (daliasskininterval_t *)(pinskingroup + 1); + pinskinintervals = (daliasskininterval_t *) (pinskingroup + 1); - pskintype = (void *)(pinskinintervals + groupskins); - skin = (byte *)pskintype; + pskintype = (void *) (pinskinintervals + groupskins); + skin = (byte *) pskintype; - for (j=0 ; jgl_texturenum[i][j] = - pheader->gl_texturenum[i][j - k]; - pheader->gl_fb_texturenum[i][j] = - pheader->gl_fb_texturenum[i][j - k]; + for ( /* */ ; j < 4; j++) { + pheader->gl_texturenum[i][j] = pheader->gl_texturenum[i][j - k]; + pheader->gl_fb_texturenum[i][j] = + pheader->gl_fb_texturenum[i][j - k]; } } - pskintype = (daliasskintype_t*)skin; + pskintype = (daliasskintype_t *) skin; } return pskintype; @@ -247,34 +251,34 @@ void *Mod_LoadAllSkins (int numskins, daliasskintype_t *pskintype, int *pskinind Mod_LoadAliasFrame ================= */ -void * Mod_LoadAliasFrame (void * pin, maliasframedesc_t *frame) +void * +Mod_LoadAliasFrame (void *pin, maliasframedesc_t *frame) { - trivertx_t *pinframe; - int i; - daliasframe_t *pdaliasframe; - - pdaliasframe = (daliasframe_t *)pin; + trivertx_t *pinframe; + int i; + daliasframe_t *pdaliasframe; + + pdaliasframe = (daliasframe_t *) pin; strcpy (frame->name, pdaliasframe->name); frame->firstpose = posenum; frame->numposes = 1; - for (i=0 ; i<3 ; i++) - { - // these are byte values, so we don't have to worry about - // endianness + for (i = 0; i < 3; i++) { + // these are byte values, so we don't have to worry about + // endianness frame->bboxmin.v[i] = pdaliasframe->bboxmin.v[i]; frame->bboxmin.v[i] = pdaliasframe->bboxmax.v[i]; } - pinframe = (trivertx_t *)(pdaliasframe + 1); + pinframe = (trivertx_t *) (pdaliasframe + 1); poseverts[posenum] = pinframe; posenum++; pinframe += pheader->mdl.numverts; - return (void *)pinframe; + return (void *) pinframe; } /* @@ -282,41 +286,42 @@ void * Mod_LoadAliasFrame (void * pin, maliasframedesc_t *frame) Mod_LoadAliasGroup ================= */ -void *Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame) +void * +Mod_LoadAliasGroup (void *pin, maliasframedesc_t *frame) { - daliasgroup_t *pingroup; - int i, numframes; - daliasinterval_t *pin_intervals; - void *ptemp; - - pingroup = (daliasgroup_t *)pin; + daliasgroup_t *pingroup; + int i, numframes; + daliasinterval_t *pin_intervals; + void *ptemp; + + pingroup = (daliasgroup_t *) pin; numframes = LittleLong (pingroup->numframes); frame->firstpose = posenum; frame->numposes = numframes; - for (i=0 ; i<3 ; i++) - { - // these are byte values, so we don't have to worry about endianness + for (i = 0; i < 3; i++) { + // these are byte values, so we don't have to worry about endianness frame->bboxmin.v[i] = pingroup->bboxmin.v[i]; frame->bboxmin.v[i] = pingroup->bboxmax.v[i]; } - pin_intervals = (daliasinterval_t *)(pingroup + 1); + pin_intervals = (daliasinterval_t *) (pingroup + 1); frame->interval = LittleFloat (pin_intervals->interval); pin_intervals += numframes; - ptemp = (void *)pin_intervals; + ptemp = (void *) pin_intervals; - for (i=0 ; imdl.numverts; + ptemp = + (trivertx_t *) ((daliasframe_t *) ptemp + 1) + + pheader->mdl.numverts; } return ptemp; diff --git a/source/gl_model_brush.c b/source/gl_model_brush.c index 0c69322..a6eb31a 100644 --- a/source/gl_model_brush.c +++ b/source/gl_model_brush.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -40,24 +40,27 @@ #include "qendian.h" #include "quakefs.h" -int Mod_Fullbright(byte *skin, int width, int height, char *name); +int Mod_Fullbright (byte * skin, int width, int height, char *name); -extern model_t *loadmodel; -extern char loadname[]; +extern model_t *loadmodel; +extern char loadname[]; -extern byte *mod_base; +extern byte *mod_base; -const int mod_lightmap_bytes=3; +const int mod_lightmap_bytes = 3; void -Mod_ProcessTexture(miptex_t *mt, texture_t *tx) +Mod_ProcessTexture (miptex_t *mt, texture_t *tx) { - char name[32]; + char name[32]; - texture_mode = GL_LINEAR_MIPMAP_NEAREST; //_LINEAR; - snprintf (name, sizeof(name), "fb_%s", mt->name); - tx->gl_fb_texturenum = Mod_Fullbright ((byte *)(tx+1), tx->width, tx->height, name); - tx->gl_texturenum = GL_LoadTexture (mt->name, tx->width, tx->height, (byte *)(tx+1), true, false, 1); + texture_mode = GL_LINEAR_MIPMAP_NEAREST; // _LINEAR; + snprintf (name, sizeof (name), "fb_%s", mt->name); + tx->gl_fb_texturenum = + Mod_Fullbright ((byte *) (tx + 1), tx->width, tx->height, name); + tx->gl_texturenum = + GL_LoadTexture (mt->name, tx->width, tx->height, (byte *) (tx + 1), + true, false, 1); texture_mode = GL_LINEAR; } @@ -66,44 +69,44 @@ Mod_ProcessTexture(miptex_t *mt, texture_t *tx) Mod_LoadLighting ================= */ -void Mod_LoadLighting (lump_t *l) +void +Mod_LoadLighting (lump_t *l) { - int i; - byte *in, *out, *data; - byte d; - char litfilename[1024]; + int i; + byte *in, *out, *data; + byte d; + char litfilename[1024]; + loadmodel->lightdata = NULL; // LordHavoc: check for a .lit file to load - strcpy(litfilename, loadmodel->name); - COM_StripExtension(litfilename, litfilename); - strncat (litfilename, ".lit", sizeof(litfilename) - strlen (litfilename)); - data = (byte*) COM_LoadHunkFile (litfilename); - if (data) - { - if (data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T') - { - i = LittleLong(((int *)data)[1]); - if (i == 1) - { - Con_DPrintf("%s loaded", litfilename); + strcpy (litfilename, loadmodel->name); + COM_StripExtension (litfilename, litfilename); + strncat (litfilename, ".lit", sizeof (litfilename) - strlen (litfilename)); + data = (byte *) COM_LoadHunkFile (litfilename); + if (data) { + if (data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' + && data[3] == 'T') { + i = LittleLong (((int *) data)[1]); + if (i == 1) { + Con_DPrintf ("%s loaded", litfilename); loadmodel->lightdata = data + 8; return; - } - else - Con_Printf("Unknown .lit file version (%d)\n", i); - } - else - Con_Printf("Corrupt .lit file (old version?), ignoring\n"); + } else + Con_Printf ("Unknown .lit file version (%d)\n", i); + } else + Con_Printf ("Corrupt .lit file (old version?), ignoring\n"); } // LordHavoc: oh well, expand the white lighting data if (!l->filelen) return; - loadmodel->lightdata = Hunk_AllocName ( l->filelen*3, litfilename); - in = loadmodel->lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write + loadmodel->lightdata = Hunk_AllocName (l->filelen * 3, litfilename); + in = loadmodel->lightdata + l->filelen * 2; // place the file at the end, + // so it will not be + // overwritten until the very + // last write out = loadmodel->lightdata; memcpy (in, mod_base + l->fileofs, l->filelen); - for (i = 0;i < l->filelen;i++) - { + for (i = 0; i < l->filelen; i++) { d = *in++; *out++ = d; *out++ = d; diff --git a/source/gl_model_fullbright.c b/source/gl_model_fullbright.c index bb42787..78adf1f 100644 --- a/source/gl_model_fullbright.c +++ b/source/gl_model_fullbright.c @@ -40,39 +40,40 @@ #include "checksum.h" #include "glquake.h" -int Mod_Fullbright (byte *skin, int width, int height, char *name) +int +Mod_Fullbright (byte * skin, int width, int height, char *name) { - int j; - int pixels; - qboolean hasfullbrights = false; - int texnum; + int j; + int pixels; + qboolean hasfullbrights = false; + int texnum; // Check for fullbright pixels.. pixels = width * height; - for (j=0 ; j= 256-32) { + for (j = 0; j < pixels; j++) { + if (skin[j] >= 256 - 32) { hasfullbrights = true; break; } } if (hasfullbrights) { - byte *ptexels; + byte *ptexels; - //ptexels = Hunk_Alloc(s); - ptexels = malloc(pixels); + // ptexels = Hunk_Alloc(s); + ptexels = malloc (pixels); - Con_DPrintf("FB Model ID: '%s'\n", name); - for (j=0 ; j= 256-32) { + Con_DPrintf ("FB Model ID: '%s'\n", name); + for (j = 0; j < pixels; j++) { + if (skin[j] >= 256 - 32) { ptexels[j] = skin[j]; } else { ptexels[j] = 255; } } texnum = GL_LoadTexture (name, width, height, ptexels, true, true, 1); - free(ptexels); + free (ptexels); return texnum; } return 0; diff --git a/source/gl_model_sprite.c b/source/gl_model_sprite.c index aee384a..11fe6d4 100644 --- a/source/gl_model_sprite.c +++ b/source/gl_model_sprite.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -44,28 +44,29 @@ #include "qendian.h" #include "glquake.h" -extern model_t *loadmodel; -extern char loadname[]; +extern model_t *loadmodel; +extern char loadname[]; /* ================= Mod_LoadSpriteFrame ================= */ -void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int framenum) +void * +Mod_LoadSpriteFrame (void *pin, mspriteframe_t **ppframe, int framenum) { - dspriteframe_t *pinframe; - mspriteframe_t *pspriteframe; - int width, height, size, origin[2]; - char name[64]; + dspriteframe_t *pinframe; + mspriteframe_t *pspriteframe; + int width, height, size, origin[2]; + char name[64]; - pinframe = (dspriteframe_t *)pin; + pinframe = (dspriteframe_t *) pin; width = LittleLong (pinframe->width); height = LittleLong (pinframe->height); size = width * height; - pspriteframe = Hunk_AllocName (sizeof (mspriteframe_t),loadname); + pspriteframe = Hunk_AllocName (sizeof (mspriteframe_t), loadname); memset (pspriteframe, 0, sizeof (mspriteframe_t)); @@ -81,8 +82,10 @@ void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int framenum) pspriteframe->left = origin[0]; pspriteframe->right = width + origin[0]; - snprintf (name, sizeof(name), "%s_%i", loadmodel->name, framenum); - pspriteframe->gl_texturenum = GL_LoadTexture (name, width, height, (byte *)(pinframe + 1), true, true, 1); + snprintf (name, sizeof (name), "%s_%i", loadmodel->name, framenum); + pspriteframe->gl_texturenum = + GL_LoadTexture (name, width, height, (byte *) (pinframe + 1), true, + true, 1); - return (void *)((byte *)pinframe + sizeof (dspriteframe_t) + size); + return (void *) ((byte *) pinframe + sizeof (dspriteframe_t) + size); } diff --git a/source/gl_ngraph.c b/source/gl_ngraph.c index 3919ab9..7d6890a 100644 --- a/source/gl_ngraph.c +++ b/source/gl_ngraph.c @@ -32,84 +32,88 @@ #include #include -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" #include "menu.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, gl_model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, gl_model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" #include "cl_parse.h" -extern byte *draw_chars; // 8*8 graphic characters +extern byte *draw_chars; // 8*8 graphic characters extern qboolean lighthalf; -int netgraphtexture; // netgraph texture +int netgraphtexture; // netgraph texture #define NET_GRAPHHEIGHT 32 -static byte ngraph_texels[NET_GRAPHHEIGHT][NET_TIMINGS]; +static byte ngraph_texels[NET_GRAPHHEIGHT][NET_TIMINGS]; -static void R_LineGraph (int x, int h) +static void +R_LineGraph (int x, int h) { - int i; - int s; - int color; + int i; + int s; + int color; s = NET_GRAPHHEIGHT; if (h == 10000) - color = 0x6f; // yellow + color = 0x6f; // yellow else if (h == 9999) - color = 0x4f; // red + color = 0x4f; // red else if (h == 9998) - color = 0xd0; // blue + color = 0xd0; // blue else - color = 0xfe; // white + color = 0xfe; // white - if (h>s) + if (h > s) h = s; - - for (i=0 ; i>4; - col = num&15; - source = draw_chars + (row<<10) + (col<<3); + row = num >> 4; + col = num & 15; + source = draw_chars + (row << 10) + (col << 3); - for (drawline = 8; drawline; drawline--, y++) - { - for (nx=0 ; nx<8 ; nx++) + for (drawline = 8; drawline; drawline--, y++) { + for (nx = 0; nx < 8; nx++) if (source[nx] != 255) - ngraph_texels[y][nx+x] = 0x60 + source[nx]; + ngraph_texels[y][nx + x] = 0x60 + source[nx]; source += 128; } } @@ -120,19 +124,19 @@ void Draw_CharToNetGraph (int x, int y, int num) R_NetGraph ============== */ -void R_NetGraph (void) +void +R_NetGraph (void) { - int a, x, i, y; - int lost; - char st[80]; - unsigned int ngraph_pixels[NET_GRAPHHEIGHT][NET_TIMINGS]; + int a, x, i, y; + int lost; + char st[80]; + unsigned int ngraph_pixels[NET_GRAPHHEIGHT][NET_TIMINGS]; x = 0; - lost = CL_CalcNet(); - for (a=0 ; a>1); + x = -((vid.width - 320) >> 1); y = vid.height - sb_lines - 24 - NET_GRAPHHEIGHT - 1; - M_DrawTextBox (x, y, NET_TIMINGS/8, NET_GRAPHHEIGHT/8 + 1); + M_DrawTextBox (x, y, NET_TIMINGS / 8, NET_GRAPHHEIGHT / 8 + 1); y += 8; - snprintf(st, sizeof(st), "%3i%% packet loss", lost); + snprintf (st, sizeof (st), "%3i%% packet loss", lost); Draw_String8 (8, y, st); y += 8; - - glBindTexture (GL_TEXTURE_2D, netgraphtexture); - glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, - NET_TIMINGS, NET_GRAPHHEIGHT, 0, GL_RGBA, - GL_UNSIGNED_BYTE, ngraph_pixels); + glBindTexture (GL_TEXTURE_2D, netgraphtexture); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexImage2D (GL_TEXTURE_2D, 0, gl_alpha_format, + NET_TIMINGS, NET_GRAPHHEIGHT, 0, GL_RGBA, + GL_UNSIGNED_BYTE, ngraph_pixels); + + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); x = 8; glBegin (GL_QUADS); glTexCoord2f (0, 0); glVertex2f (x, y); glTexCoord2f (1, 0); - glVertex2f (x+NET_TIMINGS, y); + glVertex2f (x + NET_TIMINGS, y); glTexCoord2f (1, 1); - glVertex2f (x+NET_TIMINGS, y+NET_GRAPHHEIGHT); + glVertex2f (x + NET_TIMINGS, y + NET_GRAPHHEIGHT); glTexCoord2f (0, 1); - glVertex2f (x, y+NET_GRAPHHEIGHT); + glVertex2f (x, y + NET_GRAPHHEIGHT); glEnd (); } - diff --git a/source/gl_refrag.c b/source/gl_refrag.c index 6c76bf7..de4bfb0 100644 --- a/source/gl_refrag.c +++ b/source/gl_refrag.c @@ -32,30 +32,33 @@ #include "sys.h" #include "qargs.h" -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h #include "d_iface.h" -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" #include "menu.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, gl_model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, gl_model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" #include "quakefs.h" #include "cl_main.h" -mnode_t *r_pefragtopnode; +mnode_t *r_pefragtopnode; //=========================================================================== @@ -68,11 +71,11 @@ mnode_t *r_pefragtopnode; =============================================================================== */ -efrag_t **lastlink; +efrag_t **lastlink; -vec3_t r_emins, r_emaxs; +vec3_t r_emins, r_emaxs; -entity_t *r_addent; +entity_t *r_addent; /* @@ -82,38 +85,35 @@ R_RemoveEfrags Call when removing an object from the world or moving it to another position ================ */ -void R_RemoveEfrags (entity_t *ent) +void +R_RemoveEfrags (entity_t *ent) { - efrag_t *ef, *old, *walk, **prev; - + efrag_t *ef, *old, *walk, **prev; + ef = ent->efrag; - - while (ef) - { + + while (ef) { prev = &ef->leaf->efrags; - while (1) - { + while (1) { walk = *prev; if (!walk) break; - if (walk == ef) - { // remove this fragment + if (walk == ef) { // remove this fragment *prev = ef->leafnext; break; - } - else + } else prev = &walk->leafnext; } - + old = ef; ef = ef->entnext; - - // put it on the free list + + // put it on the free list old->entnext = cl.free_efrags; cl.free_efrags = old; } - - ent->efrag = NULL; + + ent->efrag = NULL; } /* @@ -121,68 +121,62 @@ void R_RemoveEfrags (entity_t *ent) R_SplitEntityOnNode =================== */ -void R_SplitEntityOnNode (mnode_t *node) +void +R_SplitEntityOnNode (mnode_t *node) { - efrag_t *ef; - mplane_t *splitplane; - mleaf_t *leaf; - int sides; - - if (node->contents == CONTENTS_SOLID) - { + efrag_t *ef; + mplane_t *splitplane; + mleaf_t *leaf; + int sides; + + if (node->contents == CONTENTS_SOLID) { return; } - // add an efrag if the node is a leaf - if ( node->contents < 0) - { + if (node->contents < 0) { if (!r_pefragtopnode) r_pefragtopnode = node; - leaf = (mleaf_t *)node; + leaf = (mleaf_t *) node; // grab an efrag off the free list ef = cl.free_efrags; - if (!ef) - { + if (!ef) { Con_Printf ("Too many efrags!\n"); - return; // no free fragments... + return; // no free fragments... } cl.free_efrags = cl.free_efrags->entnext; ef->entity = r_addent; - -// add the entity link + +// add the entity link *lastlink = ef; lastlink = &ef->entnext; ef->entnext = NULL; - + // set the leaf links ef->leaf = leaf; ef->leafnext = leaf->efrags; leaf->efrags = ef; - + return; } - // NODE_MIXED splitplane = node->plane; - sides = BOX_ON_PLANE_SIDE(r_emins, r_emaxs, splitplane); - - if (sides == 3) - { - // split on this plane - // if this is the first splitter of this bmodel, remember it + sides = BOX_ON_PLANE_SIDE (r_emins, r_emaxs, splitplane); + + if (sides == 3) { + // split on this plane + // if this is the first splitter of this bmodel, remember it if (!r_pefragtopnode) r_pefragtopnode = node; } - // recurse down the contacted sides if (sides & 1) R_SplitEntityOnNode (node->children[0]); - + if (sides & 2) R_SplitEntityOnNode (node->children[1]); } @@ -194,23 +188,23 @@ void R_SplitEntityOnNode (mnode_t *node) R_AddEfrags =========== */ -void R_AddEfrags (entity_t *ent) +void +R_AddEfrags (entity_t *ent) { - model_t *entmodel; - int i; - + model_t *entmodel; + int i; + if (!ent->model) return; r_addent = ent; - + lastlink = &ent->efrag; r_pefragtopnode = NULL; - + entmodel = ent->model; - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { r_emins[i] = ent->origin[i] + entmodel->mins[i]; r_emaxs[i] = ent->origin[i] + entmodel->maxs[i]; } @@ -228,41 +222,38 @@ R_StoreEfrags // FIXME: a lot of this goes away with edge-based ================ */ -void R_StoreEfrags (efrag_t **ppefrag) +void +R_StoreEfrags (efrag_t **ppefrag) { - entity_t *pent; - model_t *clmodel; - efrag_t *pefrag; + entity_t *pent; + model_t *clmodel; + efrag_t *pefrag; - while ((pefrag = *ppefrag) != NULL) - { + while ((pefrag = *ppefrag) != NULL) { pent = pefrag->entity; clmodel = pent->model; - switch (clmodel->type) - { - case mod_alias: - case mod_brush: - case mod_sprite: - pent = pefrag->entity; + switch (clmodel->type) { + case mod_alias: + case mod_brush: + case mod_sprite: + pent = pefrag->entity; - if ((pent->visframe != r_framecount) && - (cl_numvisedicts < MAX_VISEDICTS)) - { - cl_visedicts[cl_numvisedicts++] = *pent; + if ((pent->visframe != r_framecount) && + (cl_numvisedicts < MAX_VISEDICTS)) { + cl_visedicts[cl_numvisedicts++] = *pent; - // mark that we've recorded this entity for this frame - pent->visframe = r_framecount; - } + // mark that we've recorded this entity for this frame + pent->visframe = r_framecount; + } - ppefrag = &pefrag->leafnext; - break; + ppefrag = &pefrag->leafnext; + break; - default: - Sys_Error ("R_StoreEfrags: Bad entity type %d\n", clmodel->type); + default: + Sys_Error ("R_StoreEfrags: Bad entity type %d\n", + clmodel->type); } } } - - diff --git a/source/gl_rlight.c b/source/gl_rlight.c index 2e48d66..c9b044d 100644 --- a/source/gl_rlight.c +++ b/source/gl_rlight.c @@ -34,27 +34,30 @@ #include #include -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" -#include "cvar.h" // needed by: view.h -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "cvar.h" // needed by: view.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, gl_model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, gl_model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" -int r_dlightframecount; +int r_dlightframecount; extern qboolean lighthalf; @@ -63,26 +66,25 @@ extern qboolean lighthalf; R_AnimateLight ================== */ -void R_AnimateLight (void) +void +R_AnimateLight (void) { - int i,j,k; - + int i, j, k; + // // light animations // 'm' is normal light, 'a' is no light, 'z' is double bright - i = (int)(cl.time*10); - for (j=0 ; j=0 ; i--) - { - a = i/32.0 * M_PI*2; - *bub_sin++ = sin(a); - *bub_cos++ = cos(a); + for (i = 32; i >= 0; i--) { + a = i / 32.0 * M_PI * 2; + *bub_sin++ = sin (a); + *bub_cos++ = cos (a); } } -void R_RenderDlight (dlight_t *light) +void +R_RenderDlight (dlight_t *light) { - int i, j; -// float a; - vec3_t v; - float rad; - float *bub_sin, *bub_cos; + int i, j; + +// float a; + vec3_t v; + float rad; + float *bub_sin, *bub_cos; bub_sin = bubble_sintable; bub_cos = bubble_costable; rad = light->radius * 0.35; VectorSubtract (light->origin, r_origin, v); - if (Length (v) < rad) - { // view is inside the dlight + if (Length (v) < rad) { // view is inside the dlight AddLightBlend (1, 0.5, 0, light->radius * 0.0003); return; } glBegin (GL_TRIANGLE_FAN); if (lighthalf) - glColor3f(light->color[0]*0.5,light->color[1]*0.5,light->color[2]*0.5); + glColor3f (light->color[0] * 0.5, light->color[1] * 0.5, + light->color[2] * 0.5); else glColor3fv (light->color); - for (i=0 ; i<3 ; i++) - v[i] = light->origin[i] - vpn[i]*rad; + for (i = 0; i < 3; i++) + v[i] = light->origin[i] - vpn[i] * rad; glVertex3fv (v); - glColor3f (0,0,0); - for (i=16 ; i>=0 ; i--) - { -// a = i/16.0 * M_PI*2; - for (j=0 ; j<3 ; j++) - v[j] = light->origin[j] + (vright[j]*(*bub_cos) + - + vup[j]*(*bub_sin)) * rad; - bub_sin+=2; - bub_cos+=2; + glColor3f (0, 0, 0); + for (i = 16; i >= 0; i--) { +// a = i/16.0 * M_PI*2; + for (j = 0; j < 3; j++) + v[j] = light->origin[j] + (vright[j] * (*bub_cos) + + +vup[j] * (*bub_sin)) * rad; + bub_sin += 2; + bub_cos += 2; glVertex3fv (v); } glEnd (); - // No, we don't reset here, we reset in the function which calls this one. + // No, we don't reset here, we reset in the function which calls this + // one. // Largely because this is called in a big loop. // glColor3ubv(lighthalf_v); } @@ -174,25 +180,25 @@ void R_RenderDlight (dlight_t *light) R_RenderDlights ============= */ -void R_RenderDlights (void) +void +R_RenderDlights (void) { - int i; - dlight_t *l; + int i; + dlight_t *l; if (!gl_flashblend->int_val) return; r_dlightframecount = r_framecount + 1; // because the count hasn't - // advanced yet for this frame - glDepthMask(GL_FALSE); + // advanced yet for this frame + glDepthMask (GL_FALSE); glDisable (GL_TEXTURE_2D); glBlendFunc (GL_ONE, GL_ONE); if (gl_smoothdlights->int_val) glShadeModel (GL_SMOOTH); l = cl_dlights; - for (i=0 ; idie < cl.time || !l->radius) continue; R_RenderDlight (l); @@ -200,10 +206,10 @@ void R_RenderDlights (void) if (!gl_smooth->int_val) glShadeModel (GL_FLAT); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); glEnable (GL_TEXTURE_2D); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(GL_TRUE); + glDepthMask (GL_TRUE); } @@ -222,66 +228,85 @@ R_MarkLights */ // LordHavoc: heavily modified, to eliminate unnecessary texture uploads, // and support bmodel lighting better -void R_MarkLights (vec3_t lightorigin, dlight_t *light, int bit, mnode_t *node) +void +R_MarkLights (vec3_t lightorigin, dlight_t *light, int bit, mnode_t *node) { - mplane_t *splitplane; - float dist, l, maxdist; - msurface_t *surf; - int i, j, s, t; - vec3_t impact; - + mplane_t *splitplane; + float dist, l, maxdist; + msurface_t *surf; + int i, j, s, t; + vec3_t impact; + if (node->contents < 0) return; splitplane = node->plane; dist = DotProduct (lightorigin, splitplane->normal) - splitplane->dist; - - if (dist > light->radius) - { - if (node->children[0]->contents >= 0) // save some time by not pushing another stack frame + + if (dist > light->radius) { + if (node->children[0]->contents >= 0) // save some time by not + // pushing another stack + // frame R_MarkLights (lightorigin, light, bit, node->children[0]); return; } - if (dist < -light->radius) - { - if (node->children[1]->contents >= 0) // save some time by not pushing another stack frame + if (dist < -light->radius) { + if (node->children[1]->contents >= 0) // save some time by not + // pushing another stack + // frame R_MarkLights (lightorigin, light, bit, node->children[1]); return; } - maxdist = light->radius*light->radius; + maxdist = light->radius * light->radius; // mark the polygons surf = cl.worldmodel->surfaces + node->firstsurface; - for (i=0 ; inumsurfaces ; i++, surf++) - { - // LordHavoc: MAJOR dynamic light speedup here, eliminates marking of surfaces that are too far away from light, thus preventing unnecessary renders and uploads - for (j=0 ; j<3 ; j++) - impact[j] = lightorigin[j] - surf->plane->normal[j]*dist; + for (i = 0; i < node->numsurfaces; i++, surf++) { + // LordHavoc: MAJOR dynamic light speedup here, eliminates marking of + // surfaces that are too far away from light, thus preventing + // unnecessary renders and uploads + for (j = 0; j < 3; j++) + impact[j] = lightorigin[j] - surf->plane->normal[j] * dist; // clamp center of light to corner and check brightness - l = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0]; - s = l+0.5;if (s < 0) s = 0;else if (s > surf->extents[0]) s = surf->extents[0]; + l = + DotProduct (impact, + surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - + surf->texturemins[0]; + s = l + 0.5; + if (s < 0) + s = 0; + else if (s > surf->extents[0]) + s = surf->extents[0]; s = l - s; - l = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1]; - t = l+0.5;if (t < 0) t = 0;else if (t > surf->extents[1]) t = surf->extents[1]; + l = + DotProduct (impact, + surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - + surf->texturemins[1]; + t = l + 0.5; + if (t < 0) + t = 0; + else if (t > surf->extents[1]) + t = surf->extents[1]; t = l - t; // compare to minimum light - if ((s*s+t*t+dist*dist) < maxdist) - { - if (surf->dlightframe != r_dlightframecount) // not dynamic until now + if ((s * s + t * t + dist * dist) < maxdist) { + if (surf->dlightframe != r_dlightframecount) // not dynamic + // until now { surf->dlightbits = bit; surf->dlightframe = r_dlightframecount; - } - else // already dynamic + } else // already dynamic surf->dlightbits |= bit; } } - if (node->children[0]->contents >= 0) // save some time by not pushing another stack frame + if (node->children[0]->contents >= 0) // save some time by not pushing + // another stack frame R_MarkLights (lightorigin, light, bit, node->children[0]); - if (node->children[1]->contents >= 0) // save some time by not pushing another stack frame + if (node->children[1]->contents >= 0) // save some time by not pushing + // another stack frame R_MarkLights (lightorigin, light, bit, node->children[1]); } @@ -291,25 +316,25 @@ void R_MarkLights (vec3_t lightorigin, dlight_t *light, int bit, mnode_t *node) R_PushDlights ============= */ -void R_PushDlights (vec3_t entorigin) +void +R_PushDlights (vec3_t entorigin) { - int i; - dlight_t *l; - vec3_t lightorigin; + int i; + dlight_t *l; + vec3_t lightorigin; if (gl_flashblend->int_val) return; r_dlightframecount = r_framecount + 1; // because the count hasn't - // advanced yet for this frame + // advanced yet for this frame l = cl_dlights; - for (i=0 ; idie < cl.time || !l->radius) continue; - VectorSubtract(l->origin, entorigin, lightorigin); - R_MarkLights (lightorigin, l, 1<nodes ); + VectorSubtract (l->origin, entorigin, lightorigin); + R_MarkLights (lightorigin, l, 1 << i, cl.worldmodel->nodes); } } @@ -322,27 +347,28 @@ LIGHT SAMPLING ============================================================================= */ -mplane_t *lightplane; -vec3_t lightspot; +mplane_t *lightplane; +vec3_t lightspot; -int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) +int +RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) { - int r; - float front, back, frac; - int side; - mplane_t *plane; - vec3_t mid; - msurface_t *surf; - int s, t, ds, dt; - int i; - mtexinfo_t *tex; - byte *lightmap; - unsigned int scale; - int maps; + int r; + float front, back, frac; + int side; + mplane_t *plane; + vec3_t mid; + msurface_t *surf; + int s, t, ds, dt; + int i; + mtexinfo_t *tex; + byte *lightmap; + unsigned int scale; + int maps; if (node->contents < 0) - return -1; // didn't hit anything - + return -1; // didn't hit anything + // calculate mid point // FIXME: optimize for axial @@ -350,46 +376,44 @@ int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) front = DotProduct (start, plane->normal) - plane->dist; back = DotProduct (end, plane->normal) - plane->dist; side = front < 0; - - if ( (back < 0) == side) + + if ((back < 0) == side) return RecursiveLightPoint (node->children[side], start, end); - - frac = front / (front-back); - mid[0] = start[0] + (end[0] - start[0])*frac; - mid[1] = start[1] + (end[1] - start[1])*frac; - mid[2] = start[2] + (end[2] - start[2])*frac; - -// go down front side + + frac = front / (front - back); + mid[0] = start[0] + (end[0] - start[0]) * frac; + mid[1] = start[1] + (end[1] - start[1]) * frac; + mid[2] = start[2] + (end[2] - start[2]) * frac; + +// go down front side r = RecursiveLightPoint (node->children[side], start, mid); if (r >= 0) - return r; // hit something - - if ( (back < 0) == side ) - return -1; // didn't hit anuthing - + return r; // hit something + + if ((back < 0) == side) + return -1; // didn't hit anuthing + // check for impact on this node VectorCopy (mid, lightspot); lightplane = plane; surf = cl.worldmodel->surfaces + node->firstsurface; - for (i=0 ; inumsurfaces ; i++, surf++) - { + for (i = 0; i < node->numsurfaces; i++, surf++) { if (surf->flags & SURF_DRAWTILED) - continue; // no lightmaps + continue; // no lightmaps tex = surf->texinfo; - + s = DotProduct (mid, tex->vecs[0]) + tex->vecs[0][3]; t = DotProduct (mid, tex->vecs[1]) + tex->vecs[1][3];; - if (s < surf->texturemins[0] || - t < surf->texturemins[1]) + if (s < surf->texturemins[0] || t < surf->texturemins[1]) continue; - + ds = s - surf->texturemins[0]; dt = t - surf->texturemins[1]; - - if ( ds > surf->extents[0] || dt > surf->extents[1] ) + + if (ds > surf->extents[0] || dt > surf->extents[1]) continue; if (!surf->samples) @@ -400,23 +424,21 @@ int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) lightmap = surf->samples; r = 0; - if (lightmap) - { + if (lightmap) { - lightmap += dt * ((surf->extents[0]>>4)+1) + ds; + lightmap += dt * ((surf->extents[0] >> 4) + 1) + ds; - for (maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[maps] != 255 ; - maps++) - { + for (maps = 0; maps < MAXLIGHTMAPS && surf->styles[maps] != 255; + maps++) { scale = d_lightstylevalue[surf->styles[maps]]; r += *lightmap * scale; - lightmap += ((surf->extents[0]>>4)+1) * - ((surf->extents[1]>>4)+1); + lightmap += ((surf->extents[0] >> 4) + 1) * + ((surf->extents[1] >> 4) + 1); } - + r >>= 8; } - + return r; } @@ -424,23 +446,23 @@ int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) return RecursiveLightPoint (node->children[!side], mid, end); } -int R_LightPoint (vec3_t p) +int +R_LightPoint (vec3_t p) { - vec3_t end; - int r; - + vec3_t end; + int r; + if (!cl.worldmodel->lightdata) return 255; - + end[0] = p[0]; end[1] = p[1]; end[2] = p[2] - 2048; - + r = RecursiveLightPoint (cl.worldmodel->nodes, p, end); - + if (r == -1) r = 0; return r; } - diff --git a/source/gl_rmain.c b/source/gl_rmain.c index 19ef1b3..012fd85 100644 --- a/source/gl_rmain.c +++ b/source/gl_rmain.c @@ -51,88 +51,91 @@ #include "view.h" -entity_t r_worldentity; +entity_t r_worldentity; -vec3_t modelorg, r_entorigin; -entity_t *currententity; +vec3_t modelorg, r_entorigin; +entity_t *currententity; -int r_visframecount; // bumped when going to a new PVS -int r_framecount; // used for dlight push checking +int r_visframecount; // bumped when going to a new PVS +int r_framecount; // used for dlight push checking -mplane_t frustum[4]; +mplane_t frustum[4]; -int c_brush_polys, c_alias_polys; +int c_brush_polys, c_alias_polys; -qboolean envmap; // true during envmap command capture +qboolean envmap; // true during envmap command capture + + // -int playertextures; // up to 16 color translated skins +int playertextures; // up to 16 color translated skins // // view origin // -vec3_t vup; -vec3_t vpn; -vec3_t vright; -vec3_t r_origin; +vec3_t vup; +vec3_t vpn; +vec3_t vright; +vec3_t r_origin; -float r_world_matrix[16]; -float r_base_world_matrix[16]; +float r_world_matrix[16]; +float r_base_world_matrix[16]; // // screen size info // -refdef_t r_refdef; +refdef_t r_refdef; -mleaf_t *r_viewleaf, *r_oldviewleaf; +mleaf_t *r_viewleaf, *r_oldviewleaf; -int d_lightstylevalue[256]; // 8.8 fraction of base light value +int d_lightstylevalue[256]; // 8.8 fraction of base light value -vec3_t shadecolor; // Ender (Extend) Colormod -float modelalpha; // Ender (EXtend) Alpha +vec3_t shadecolor; // Ender (Extend) Colormod +float modelalpha; // Ender (EXtend) Alpha -void R_MarkLeaves (void); +void R_MarkLeaves (void); -cvar_t *r_norefresh; -cvar_t *r_drawentities; -cvar_t *r_drawviewmodel; -cvar_t *r_speeds; -cvar_t *r_shadows; -cvar_t *r_wateralpha; -cvar_t *r_waterripple; -cvar_t *r_dynamic; -cvar_t *r_novis; -cvar_t *r_netgraph; +cvar_t *r_norefresh; +cvar_t *r_drawentities; +cvar_t *r_drawviewmodel; +cvar_t *r_speeds; +cvar_t *r_shadows; +cvar_t *r_wateralpha; +cvar_t *r_waterripple; +cvar_t *r_dynamic; +cvar_t *r_novis; +cvar_t *r_netgraph; -cvar_t *gl_clear; -cvar_t *gl_cull; -cvar_t *gl_texsort; -cvar_t *gl_smooth; -cvar_t *gl_smoothdlights; -cvar_t *gl_affinemodels; -cvar_t *gl_flashblend; -cvar_t *gl_playermip; -cvar_t *gl_nocolors; -cvar_t *gl_keeptjunctions; -cvar_t *gl_particles; +cvar_t *gl_clear; +cvar_t *gl_cull; +cvar_t *gl_texsort; +cvar_t *gl_smooth; +cvar_t *gl_smoothdlights; +cvar_t *gl_affinemodels; +cvar_t *gl_flashblend; +cvar_t *gl_playermip; +cvar_t *gl_nocolors; +cvar_t *gl_keeptjunctions; +cvar_t *gl_particles; -cvar_t *r_skyname; -cvar_t *gl_skymultipass; -cvar_t *gl_sky_clip; +cvar_t *r_skyname; +cvar_t *gl_skymultipass; +cvar_t *gl_sky_clip; -cvar_t *gl_fb_models; -cvar_t *gl_fb_bmodels; +cvar_t *gl_fb_models; +cvar_t *gl_fb_bmodels; -cvar_t *brighten; +cvar_t *brighten; -extern cvar_t *scr_fov; +extern cvar_t *scr_fov; extern byte gammatable[256]; extern qboolean lighthalf; // LordHavoc: place for gl_rmain setup code -void glrmain_init() +void +glrmain_init () { }; @@ -145,8 +148,8 @@ void glrmain_init() void GL_CheckBrightness (unsigned char *pal) { - int i, inf; - float brightness; + int i, inf; + float brightness; brighten = Cvar_Get ("brighten", "1", CVAR_NONE, "Palette hack equivalent to brightness"); @@ -157,23 +160,23 @@ GL_CheckBrightness (unsigned char *pal) brightness = brighten->value; } brightness = bound (1, brightness, 5); - + Cvar_SetValue (brighten, brightness); Cvar_SetFlags (brighten, brighten->flags | CVAR_ROM); - + // Build gamma table - if (brightness == 1.0) { // screw the math + if (brightness == 1.0) { // screw the math for (i = 0; i < 256; i++) { gammatable[i] = i; } } else { - for (i = 0; i < 256; i++) { // brighten up the palette + for (i = 0; i < 256; i++) { // brighten up the palette inf = (i * brightness); inf = bound (0, inf, 255); gammatable[i] = inf; } } - + // correct the palette for (i = 0; i < 768; i++) { pal[i] = gammatable[pal[i]]; @@ -200,14 +203,15 @@ qboolean R_CullBox (vec3_t mins, vec3_t maxs) */ -void R_RotateForEntity (entity_t *e) +void +R_RotateForEntity (entity_t *e) { - glTranslatef (e->origin[0], e->origin[1], e->origin[2]); + glTranslatef (e->origin[0], e->origin[1], e->origin[2]); - glRotatef (e->angles[1], 0, 0, 1); - glRotatef (-e->angles[0], 0, 1, 0); - //ZOID: fixed z angle - glRotatef (e->angles[2], 1, 0, 0); + glRotatef (e->angles[1], 0, 0, 1); + glRotatef (-e->angles[0], 0, 1, 0); + // ZOID: fixed z angle + glRotatef (e->angles[2], 1, 0, 0); } /* @@ -223,42 +227,39 @@ void R_RotateForEntity (entity_t *e) R_GetSpriteFrame ================ */ -static mspriteframe_t *R_GetSpriteFrame (entity_t *currententity) +static mspriteframe_t * +R_GetSpriteFrame (entity_t *currententity) { - msprite_t *psprite; - mspritegroup_t *pspritegroup; - mspriteframe_t *pspriteframe; - int i, numframes, frame; - float *pintervals, fullinterval, targettime, time; + msprite_t *psprite; + mspritegroup_t *pspritegroup; + mspriteframe_t *pspriteframe; + int i, numframes, frame; + float *pintervals, fullinterval, targettime, time; psprite = currententity->model->cache.data; frame = currententity->frame; - if ((frame >= psprite->numframes) || (frame < 0)) - { + if ((frame >= psprite->numframes) || (frame < 0)) { Con_Printf ("R_DrawSprite: no such frame %d\n", frame); frame = 0; } - if (psprite->frames[frame].type == SPR_SINGLE) - { + if (psprite->frames[frame].type == SPR_SINGLE) { pspriteframe = psprite->frames[frame].frameptr; - } - else - { - pspritegroup = (mspritegroup_t *)psprite->frames[frame].frameptr; + } else { + pspritegroup = (mspritegroup_t *) psprite->frames[frame].frameptr; pintervals = pspritegroup->intervals; numframes = pspritegroup->numframes; - fullinterval = pintervals[numframes-1]; + fullinterval = pintervals[numframes - 1]; time = cl.time + currententity->syncbase; - // when loading in Mod_LoadSpriteGroup, we guaranteed all interval values - // are positive, so we don't have to worry about division by 0 - targettime = time - ((int)(time / fullinterval)) * fullinterval; + // when loading in Mod_LoadSpriteGroup, we guaranteed all interval + // values + // are positive, so we don't have to worry about division by 0 + targettime = time - ((int) (time / fullinterval)) * fullinterval; - for (i=0 ; i<(numframes-1) ; i++) - { + for (i = 0; i < (numframes - 1); i++) { if (pintervals[i] > targettime) break; } @@ -276,27 +277,25 @@ R_DrawSpriteModel ================= */ -static void R_DrawSpriteModel (entity_t *e) +static void +R_DrawSpriteModel (entity_t *e) { - vec3_t point; - mspriteframe_t *frame; - float *up, *right; - vec3_t v_forward, v_right, v_up; - msprite_t *psprite; + vec3_t point; + mspriteframe_t *frame; + float *up, *right; + vec3_t v_forward, v_right, v_up; + msprite_t *psprite; // don't even bother culling, because it's just a single // polygon without a surface cache frame = R_GetSpriteFrame (e); psprite = currententity->model->cache.data; - if (psprite->type == SPR_ORIENTED) - { // bullet marks on walls + if (psprite->type == SPR_ORIENTED) { // bullet marks on walls AngleVectors (currententity->angles, v_forward, v_right, v_up); up = v_up; right = v_right; - } - else - { // normal sprite + } else { // normal sprite up = vup; right = vright; } @@ -325,7 +324,7 @@ static void R_DrawSpriteModel (entity_t *e) VectorMA (e->origin, frame->down, up, point); VectorMA (point, frame->right, right, point); glVertex3fv (point); - + glEnd (); glDisable (GL_ALPHA_TEST); @@ -342,43 +341,44 @@ static void R_DrawSpriteModel (entity_t *e) #define NUMVERTEXNORMALS 162 -float r_avertexnormals[NUMVERTEXNORMALS][3] = { +float r_avertexnormals[NUMVERTEXNORMALS][3] = { #include "anorms.h" }; -vec3_t shadevector; -float shadelight; +vec3_t shadevector; +float shadelight; // precalculated dot products for quantized angles #define SHADEDOT_QUANT 16 -float r_avertexnormal_dots[SHADEDOT_QUANT][256] = +float r_avertexnormal_dots[SHADEDOT_QUANT][256] = #include "anorm_dots.h" -; + ; -float *shadedots = r_avertexnormal_dots[0]; +float *shadedots = r_avertexnormal_dots[0]; -int lastposenum; +int lastposenum; /* ============= GL_DrawAliasFrame ============= */ -static void GL_DrawAliasFrame (aliashdr_t *paliashdr, int posenum, qboolean fb) +static void +GL_DrawAliasFrame (aliashdr_t *paliashdr, int posenum, qboolean fb) { - float l; - trivertx_t *verts; - int *order; - int count; - + float l; + trivertx_t *verts; + int *order; + int count; + lastposenum = posenum; - verts = (trivertx_t *)((byte *)paliashdr + paliashdr->posedata); + verts = (trivertx_t *) ((byte *) paliashdr + paliashdr->posedata); verts += posenum * paliashdr->poseverts; - order = (int *)((byte *)paliashdr + paliashdr->commands); + order = (int *) ((byte *) paliashdr + paliashdr->commands); if (modelalpha != 1.0) - glDepthMask(GL_FALSE); + glDepthMask (GL_FALSE); while ((count = *order++)) { // get the vertex count and primitive type @@ -390,7 +390,7 @@ static void GL_DrawAliasFrame (aliashdr_t *paliashdr, int posenum, qboolean fb) do { // texture coordinates come from the draw list - glTexCoord2f (((float *)order)[0], ((float *)order)[1]); + glTexCoord2f (((float *) order)[0], ((float *) order)[1]); order += 2; if (fb) { @@ -400,7 +400,8 @@ static void GL_DrawAliasFrame (aliashdr_t *paliashdr, int posenum, qboolean fb) l = shadedots[verts->lightnormalindex] * shadelight; // LordHavoc: cleanup after Endy - glColor4f(shadecolor[0] * l, shadecolor[1] * l, shadecolor[2] * l, modelalpha); + glColor4f (shadecolor[0] * l, shadecolor[1] * l, + shadecolor[2] * l, modelalpha); } glVertex3f (verts->v[0], verts->v[1], verts->v[2]); @@ -411,8 +412,8 @@ static void GL_DrawAliasFrame (aliashdr_t *paliashdr, int posenum, qboolean fb) } if (modelalpha != 1.0) - glDepthMask(GL_TRUE); - glColor3ubv(lighthalf_v); + glDepthMask (GL_TRUE); + glColor3ubv (lighthalf_v); } @@ -421,61 +422,64 @@ static void GL_DrawAliasFrame (aliashdr_t *paliashdr, int posenum, qboolean fb) GL_DrawAliasShadow ============= */ -extern vec3_t lightspot; +extern vec3_t lightspot; -static void GL_DrawAliasShadow (aliashdr_t *paliashdr, int posenum) +static void +GL_DrawAliasShadow (aliashdr_t *paliashdr, int posenum) { - trivertx_t *verts; - int *order; - vec3_t point; - float height, lheight; - int count; + trivertx_t *verts; + int *order; + vec3_t point; + float height, lheight; + int count; lheight = currententity->origin[2] - lightspot[2]; height = 0; - verts = (trivertx_t *)((byte *)paliashdr + paliashdr->posedata); + verts = (trivertx_t *) ((byte *) paliashdr + paliashdr->posedata); verts += posenum * paliashdr->poseverts; - order = (int *)((byte *)paliashdr + paliashdr->commands); + order = (int *) ((byte *) paliashdr + paliashdr->commands); height = -lheight + 1.0; - while (1) - { + while (1) { // get the vertex count and primitive type count = *order++; if (!count) - break; // done - if (count < 0) - { + break; // done + if (count < 0) { count = -count; glBegin (GL_TRIANGLE_FAN); - } - else + } else glBegin (GL_TRIANGLE_STRIP); - do - { + do { // texture coordinates come from the draw list // (skipped for shadows) glTexCoord2fv ((float *)order); order += 2; // normals and vertexes come from the frame list - point[0] = verts->v[0] * paliashdr->mdl.scale[0] + paliashdr->mdl.scale_origin[0]; - point[1] = verts->v[1] * paliashdr->mdl.scale[1] + paliashdr->mdl.scale_origin[1]; - point[2] = verts->v[2] * paliashdr->mdl.scale[2] + paliashdr->mdl.scale_origin[2]; + point[0] = + verts->v[0] * paliashdr->mdl.scale[0] + + paliashdr->mdl.scale_origin[0]; + point[1] = + verts->v[1] * paliashdr->mdl.scale[1] + + paliashdr->mdl.scale_origin[1]; + point[2] = + verts->v[2] * paliashdr->mdl.scale[2] + + paliashdr->mdl.scale_origin[2]; - point[0] -= shadevector[0]*(point[2]+lheight); - point[1] -= shadevector[1]*(point[2]+lheight); + point[0] -= shadevector[0] * (point[2] + lheight); + point[1] -= shadevector[1] * (point[2] + lheight); point[2] = height; -// height -= 0.001; +// height -= 0.001; glVertex3fv (point); verts++; } while (--count); glEnd (); - } + } } @@ -486,13 +490,13 @@ R_SetupAliasFrame ================= */ -static void R_SetupAliasFrame (int frame, aliashdr_t *paliashdr, qboolean fb) +static void +R_SetupAliasFrame (int frame, aliashdr_t *paliashdr, qboolean fb) { - int pose, numposes; - float interval; + int pose, numposes; + float interval; - if ((frame >= paliashdr->mdl.numframes) || (frame < 0)) - { + if ((frame >= paliashdr->mdl.numframes) || (frame < 0)) { Con_DPrintf ("R_AliasSetupFrame: no such frame %d\n", frame); frame = 0; } @@ -500,10 +504,9 @@ static void R_SetupAliasFrame (int frame, aliashdr_t *paliashdr, qboolean fb) pose = paliashdr->frames[frame].firstpose; numposes = paliashdr->frames[frame].numposes; - if (numposes > 1) - { + if (numposes > 1) { interval = paliashdr->frames[frame].interval; - pose += (int)(cl.time / interval) % numposes; + pose += (int) (cl.time / interval) % numposes; } GL_DrawAliasFrame (paliashdr, pose, fb); @@ -516,17 +519,18 @@ R_DrawAliasModel ================= */ -static void R_DrawAliasModel (entity_t *e) +static void +R_DrawAliasModel (entity_t *e) { - int i; - int lnum; - vec3_t dist; - float add; - model_t *clmodel; - vec3_t mins, maxs; - aliashdr_t *paliashdr; - float an; - int anim; + int i; + int lnum; + vec3_t dist; + float add; + model_t *clmodel; + vec3_t mins, maxs; + aliashdr_t *paliashdr; + float an; + int anim; clmodel = currententity->model; @@ -536,12 +540,12 @@ static void R_DrawAliasModel (entity_t *e) if (R_CullBox (mins, maxs)) return; - // FIXME: shadecolor is supposed to be the lighting for the model, not just colormod + // FIXME: shadecolor is supposed to be the lighting for the model, not + // just colormod shadecolor[0] = currententity->colormod[0]; shadecolor[1] = currententity->colormod[1]; shadecolor[2] = currententity->colormod[2]; - if (!lighthalf) - { + if (!lighthalf) { shadecolor[0] *= 2.0; shadecolor[1] *= 2.0; shadecolor[2] *= 2.0; @@ -550,95 +554,96 @@ static void R_DrawAliasModel (entity_t *e) VectorCopy (currententity->origin, r_entorigin); VectorSubtract (r_origin, r_entorigin, modelorg); - // + // // get lighting information - // + // shadelight = R_LightPoint (currententity->origin); // allways give the gun some light if (e == &cl.viewent) - shadelight = max(shadelight, 24); + shadelight = max (shadelight, 24); - for (lnum=0 ; lnum= cl.time) - { + for (lnum = 0; lnum < MAX_DLIGHTS; lnum++) { + if (cl_dlights[lnum].die >= cl.time) { VectorSubtract (currententity->origin, - cl_dlights[lnum].origin, - dist); - add = (cl_dlights[lnum].radius * cl_dlights[lnum].radius * 8) / (DotProduct(dist, dist)); // FIXME Deek + cl_dlights[lnum].origin, dist); + add = + (cl_dlights[lnum].radius * cl_dlights[lnum].radius * 8) / + (DotProduct (dist, dist)); // FIXME Deek - if (add > 0) - { + if (add > 0) { shadelight += add; } } } // clamp lighting so it doesn't overbright as much - shadelight = min(shadelight, 100); + shadelight = min (shadelight, 100); // ZOID: never allow players to go totally black - if (!strcmp(clmodel->name, "progs/player.mdl")) - { - shadelight = max(shadelight, 8); - } else if (!gl_fb_models->int_val && ( - !strcmp (clmodel->name, "progs/flame.mdl") || - !strcmp (clmodel->name, "progs/flame2.mdl"))) { + if (!strcmp (clmodel->name, "progs/player.mdl")) { + shadelight = max (shadelight, 8); + } else if (!gl_fb_models->int_val + && (!strcmp (clmodel->name, "progs/flame.mdl") + || !strcmp (clmodel->name, "progs/flame2.mdl"))) { // HACK HACK HACK -- no fullbright colors, so make torches full light shadelight = 256; } - shadedots = r_avertexnormal_dots[((int)(e->angles[1] * (SHADEDOT_QUANT / 360.0))) & (SHADEDOT_QUANT - 1)]; + shadedots = + r_avertexnormal_dots[((int) (e->angles[1] * (SHADEDOT_QUANT / 360.0))) & + (SHADEDOT_QUANT - 1)]; shadelight /= 200.0; - - an = e->angles[1]/180*M_PI; - shadevector[0] = cos(-an); - shadevector[1] = sin(-an); + + an = e->angles[1] / 180 * M_PI; + shadevector[0] = cos (-an); + shadevector[1] = sin (-an); shadevector[2] = 1; VectorNormalize (shadevector); - // + // // locate the proper data - // - paliashdr = (aliashdr_t *)Mod_Extradata (currententity->model); + // + paliashdr = (aliashdr_t *) Mod_Extradata (currententity->model); c_alias_polys += paliashdr->mdl.numtris; - // + // // draw all the triangles - // + // glPushMatrix (); R_RotateForEntity (e); - if (!strcmp (clmodel->name, "progs/eyes.mdl") ) - { - glTranslatef (paliashdr->mdl.scale_origin[0], paliashdr->mdl.scale_origin[1], paliashdr->mdl.scale_origin[2] - (22 + 8)); - // double size of eyes, since they are really hard to see in gl - glScalef (paliashdr->mdl.scale[0]*2, paliashdr->mdl.scale[1]*2, paliashdr->mdl.scale[2]*2); - } - else - { - glTranslatef (paliashdr->mdl.scale_origin[0], paliashdr->mdl.scale_origin[1], paliashdr->mdl.scale_origin[2]); - glScalef (paliashdr->mdl.scale[0], paliashdr->mdl.scale[1], paliashdr->mdl.scale[2]); + if (!strcmp (clmodel->name, "progs/eyes.mdl")) { + glTranslatef (paliashdr->mdl.scale_origin[0], + paliashdr->mdl.scale_origin[1], + paliashdr->mdl.scale_origin[2] - (22 + 8)); + // double size of eyes, since they are really hard to see in gl + glScalef (paliashdr->mdl.scale[0] * 2, paliashdr->mdl.scale[1] * 2, + paliashdr->mdl.scale[2] * 2); + } else { + glTranslatef (paliashdr->mdl.scale_origin[0], + paliashdr->mdl.scale_origin[1], + paliashdr->mdl.scale_origin[2]); + glScalef (paliashdr->mdl.scale[0], paliashdr->mdl.scale[1], + paliashdr->mdl.scale[2]); } - anim = (int)(cl.time*10) & 3; - glBindTexture (GL_TEXTURE_2D, paliashdr->gl_texturenum[currententity->skinnum][anim]); + anim = (int) (cl.time * 10) & 3; + glBindTexture (GL_TEXTURE_2D, + paliashdr->gl_texturenum[currententity->skinnum][anim]); // we can't dynamically colormap textures, so they are cached // seperately for the players. Heads are just uncolored. - if (currententity->scoreboard && !gl_nocolors->int_val) - { + if (currententity->scoreboard && !gl_nocolors->int_val) { i = currententity->scoreboard - cl.players; - if (!currententity->scoreboard->skin) - { - Skin_Find(currententity->scoreboard); - R_TranslatePlayerSkin(i); + if (!currententity->scoreboard->skin) { + Skin_Find (currententity->scoreboard); + R_TranslatePlayerSkin (i); } - if (i >= 0 && i= 0 && i < MAX_CLIENTS) glBindTexture (GL_TEXTURE_2D, playertextures + i); } @@ -649,8 +654,10 @@ static void R_DrawAliasModel (entity_t *e) // This block is GL fullbright support for objects... if (clmodel->hasfullbrights && gl_fb_models->int_val && - paliashdr->gl_fb_texturenum[currententity->skinnum][anim]) { - glBindTexture (GL_TEXTURE_2D, paliashdr->gl_fb_texturenum[currententity->skinnum][anim]); + paliashdr->gl_fb_texturenum[currententity->skinnum][anim]) { + glBindTexture (GL_TEXTURE_2D, + paliashdr->gl_fb_texturenum[currententity-> + skinnum][anim]); R_SetupAliasFrame (currententity->frame, paliashdr, true); } @@ -659,15 +666,14 @@ static void R_DrawAliasModel (entity_t *e) glPopMatrix (); - if (r_shadows->int_val) - { + if (r_shadows->int_val) { glPushMatrix (); R_RotateForEntity (e); glDisable (GL_TEXTURE_2D); - glColor4f (0,0,0,0.5); + glColor4f (0, 0, 0, 0.5); GL_DrawAliasShadow (paliashdr, lastposenum); glEnable (GL_TEXTURE_2D); - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); glPopMatrix (); } @@ -680,40 +686,38 @@ static void R_DrawAliasModel (entity_t *e) R_DrawEntitiesOnList ============= */ -static void R_DrawEntitiesOnList (void) +static void +R_DrawEntitiesOnList (void) { - int i; + int i; if (!r_drawentities->int_val) return; // LordHavoc: split into 3 loops to simplify state changes - for (i=0 ; itype != mod_brush) continue; currententity = &cl_visedicts[i]; - modelalpha = currententity->alpha; + modelalpha = currententity->alpha; R_DrawBrushModel (currententity); } - for (i=0 ; itype != mod_alias) continue; currententity = &cl_visedicts[i]; - modelalpha = currententity->alpha; + modelalpha = currententity->alpha; R_DrawAliasModel (currententity); } - for (i=0 ; itype != mod_sprite) continue; currententity = &cl_visedicts[i]; - modelalpha = currententity->alpha; + modelalpha = currententity->alpha; R_DrawSpriteModel (currententity); } @@ -724,49 +728,48 @@ static void R_DrawEntitiesOnList (void) R_DrawViewModel ============= */ -static void R_DrawViewModel (void) +static void +R_DrawViewModel (void) { currententity = &cl.viewent; - if (!r_drawviewmodel->int_val - || !Cam_DrawViewModel() - || envmap - || !r_drawentities->int_val - || (cl.stats[STAT_ITEMS] & IT_INVISIBILITY) - || cl.stats[STAT_HEALTH] <= 0 - || !currententity->model) + if (!r_drawviewmodel->int_val || !Cam_DrawViewModel () + || envmap + || !r_drawentities->int_val + || (cl.stats[STAT_ITEMS] & IT_INVISIBILITY) + || cl.stats[STAT_HEALTH] <= 0 || !currententity->model) return; // this is a HACK! --KB modelalpha = currententity->alpha; // hack the depth range to prevent view model from poking into walls - glDepthRange (gldepthmin, gldepthmin + 0.3*(gldepthmax-gldepthmin)); + glDepthRange (gldepthmin, gldepthmin + 0.3 * (gldepthmax - gldepthmin)); R_DrawAliasModel (currententity); glDepthRange (gldepthmin, gldepthmax); } -static int SignbitsForPlane (mplane_t *out) +static int +SignbitsForPlane (mplane_t *out) { - int bits, j; + int bits, j; // for fast box on planeside test bits = 0; - for (j=0 ; j<3 ; j++) - { + for (j = 0; j < 3; j++) { if (out->normal[j] < 0) - bits |= 1< 0) @@ -880,35 +888,35 @@ static void R_SetupGL (void) w = x2 - x; h = y - y2; - if (envmap) - { + if (envmap) { x = y2 = 0; w = h = 256; } glViewport (glx + x, gly + y2, w, h); - screenaspect = (float)r_refdef.vrect.width/r_refdef.vrect.height; -// yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*180/M_PI; -// yfov = (2.0 * tan (scr_fov->value/360*M_PI)) / screenaspect; -// yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*(scr_fov->value*2)/M_PI; -// MYgluPerspective (yfov, screenaspect, 4, 4096); - MYgluPerspective (r_refdef.fov_y, screenaspect, 4, 4096); + screenaspect = (float) r_refdef.vrect.width / r_refdef.vrect.height; +// yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*180/M_PI; +// yfov = (2.0 * tan (scr_fov->value/360*M_PI)) / screenaspect; +// yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*(scr_fov->value*2)/M_PI; +// MYgluPerspective (yfov, screenaspect, 4, 4096); + MYgluPerspective (r_refdef.fov_y, screenaspect, 4, 4096); - glMatrixMode(GL_MODELVIEW); + glMatrixMode (GL_MODELVIEW); glLoadIdentity (); - glRotatef (-90, 1, 0, 0); // put Z going up - glRotatef (90, 0, 0, 1); // put Z going up - glRotatef (-r_refdef.viewangles[2], 1, 0, 0); - glRotatef (-r_refdef.viewangles[0], 0, 1, 0); - glRotatef (-r_refdef.viewangles[1], 0, 0, 1); - glTranslatef (-r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); + glRotatef (-90, 1, 0, 0); // put Z going up + glRotatef (90, 0, 0, 1); // put Z going up + glRotatef (-r_refdef.viewangles[2], 1, 0, 0); + glRotatef (-r_refdef.viewangles[0], 0, 1, 0); + glRotatef (-r_refdef.viewangles[1], 0, 0, 1); + glTranslatef (-r_refdef.vieworg[0], -r_refdef.vieworg[1], + -r_refdef.vieworg[2]); glGetFloatv (GL_MODELVIEW_MATRIX, r_world_matrix); - // + // // set drawing parms - // + // if (gl_cull->int_val) glEnable (GL_CULL_FACE); else @@ -929,7 +937,8 @@ static void R_SetupGL (void) R_Clear ============= */ -static void R_Clear (void) +static void +R_Clear (void) { if (gl_clear->int_val) glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -949,7 +958,8 @@ R_RenderView r_refdef must be set before the first call ================ */ -void R_RenderView (void) +void +R_RenderView (void) { if (r_norefresh->int_val) return; @@ -957,22 +967,24 @@ void R_RenderView (void) if (!r_worldentity.model || !cl.worldmodel) Sys_Error ("R_RenderView: NULL worldmodel"); -// glFinish (); +// glFinish (); R_Clear (); // render normal view - R_SetupFrame (); // Setup stuff for frame. + R_SetupFrame (); // Setup stuff for frame. R_SetFrustum (); R_SetupGL (); - R_MarkLeaves (); // done here so we know if we're in water + R_MarkLeaves (); // done here so we know if we're in + // water - R_DrawWorld (); // adds static entities to the list + R_DrawWorld (); // adds static entities to the list - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate (); // don't let sound get messed up if + // going slow R_DrawEntitiesOnList (); diff --git a/source/gl_rmisc.c b/source/gl_rmisc.c index 9c06519..4ff7eae 100644 --- a/source/gl_rmisc.c +++ b/source/gl_rmisc.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -35,66 +35,71 @@ #include #endif -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, gl_model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, gl_model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" #include "r_dynamic.h" #include "skin.h" -qboolean VID_Is8bit(void); -void R_InitBubble(); -void R_FireColor_f(void); +qboolean VID_Is8bit (void); +void R_InitBubble (); +void R_FireColor_f (void); -cvar_t *gl_fires; -qboolean allowskybox; // allow skyboxes? --KB +cvar_t *gl_fires; +qboolean allowskybox; // allow skyboxes? --KB /* ================== R_Textures_Init ================== */ -void R_Textures_Init (void) +void +R_Textures_Init (void) { - int x,y, m; - byte *dest; + int x, y, m; + byte *dest; // create a simple checkerboard texture for the default - r_notexture_mip = Hunk_AllocName (sizeof(texture_t) + 16*16+8*8+4*4+2*2, "notexture"); - + r_notexture_mip = + Hunk_AllocName (sizeof (texture_t) + 16 * 16 + 8 * 8 + 4 * 4 + 2 * 2, + "notexture"); + r_notexture_mip->width = r_notexture_mip->height = 16; - r_notexture_mip->offsets[0] = sizeof(texture_t); - r_notexture_mip->offsets[1] = r_notexture_mip->offsets[0] + 16*16; - r_notexture_mip->offsets[2] = r_notexture_mip->offsets[1] + 8*8; - r_notexture_mip->offsets[3] = r_notexture_mip->offsets[2] + 4*4; - - for (m=0 ; m<4 ; m++) - { - dest = (byte *)r_notexture_mip + r_notexture_mip->offsets[m]; - for (y=0 ; y< (16>>m) ; y++) - for (x=0 ; x< (16>>m) ; x++) - { - if ( (y< (8>>m) ) ^ (x< (8>>m) ) ) + r_notexture_mip->offsets[0] = sizeof (texture_t); + + r_notexture_mip->offsets[1] = r_notexture_mip->offsets[0] + 16 * 16; + r_notexture_mip->offsets[2] = r_notexture_mip->offsets[1] + 8 * 8; + r_notexture_mip->offsets[3] = r_notexture_mip->offsets[2] + 4 * 4; + + for (m = 0; m < 4; m++) { + dest = (byte *) r_notexture_mip + r_notexture_mip->offsets[m]; + for (y = 0; y < (16 >> m); y++) + for (x = 0; x < (16 >> m); x++) { + if ((y < (8 >> m)) ^ (x < (8 >> m))) *dest++ = 0; else *dest++ = 0xff; } - } + } } /* @@ -104,12 +109,13 @@ R_Envmap_f Grab six views for environment mapping tests =============== */ -void R_Envmap_f (void) +void +R_Envmap_f (void) { - byte buffer[256*256*4]; + byte buffer[256 * 256 * 4]; - glDrawBuffer (GL_FRONT); - glReadBuffer (GL_FRONT); + glDrawBuffer (GL_FRONT); + glReadBuffer (GL_FRONT); envmap = true; r_refdef.vrect.x = 0; @@ -123,43 +129,43 @@ void R_Envmap_f (void) GL_BeginRendering (&glx, &gly, &glwidth, &glheight); R_RenderView (); glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - COM_WriteFile ("env0.rgb", buffer, sizeof(buffer)); + COM_WriteFile ("env0.rgb", buffer, sizeof (buffer)); r_refdef.viewangles[1] = 90; GL_BeginRendering (&glx, &gly, &glwidth, &glheight); R_RenderView (); glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - COM_WriteFile ("env1.rgb", buffer, sizeof(buffer)); + COM_WriteFile ("env1.rgb", buffer, sizeof (buffer)); r_refdef.viewangles[1] = 180; GL_BeginRendering (&glx, &gly, &glwidth, &glheight); R_RenderView (); glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - COM_WriteFile ("env2.rgb", buffer, sizeof(buffer)); + COM_WriteFile ("env2.rgb", buffer, sizeof (buffer)); r_refdef.viewangles[1] = 270; GL_BeginRendering (&glx, &gly, &glwidth, &glheight); R_RenderView (); glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - COM_WriteFile ("env3.rgb", buffer, sizeof(buffer)); + COM_WriteFile ("env3.rgb", buffer, sizeof (buffer)); r_refdef.viewangles[0] = -90; r_refdef.viewangles[1] = 0; GL_BeginRendering (&glx, &gly, &glwidth, &glheight); R_RenderView (); glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - COM_WriteFile ("env4.rgb", buffer, sizeof(buffer)); + COM_WriteFile ("env4.rgb", buffer, sizeof (buffer)); r_refdef.viewangles[0] = 90; r_refdef.viewangles[1] = 0; GL_BeginRendering (&glx, &gly, &glwidth, &glheight); R_RenderView (); glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer); - COM_WriteFile ("env5.rgb", buffer, sizeof(buffer)); + COM_WriteFile ("env5.rgb", buffer, sizeof (buffer)); envmap = false; - glDrawBuffer (GL_BACK); - glReadBuffer (GL_BACK); + glDrawBuffer (GL_BACK); + glReadBuffer (GL_BACK); GL_EndRendering (); } @@ -169,13 +175,12 @@ void R_Envmap_f (void) void R_LoadSky_f (void) { - if (Cmd_Argc () != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("loadsky : load a skybox\n"); return; } - R_LoadSkys (Cmd_Argv(1)); + R_LoadSkys (Cmd_Argv (1)); } @@ -184,19 +189,21 @@ R_LoadSky_f (void) R_Init =============== */ -void R_Init (void) +void +R_Init (void) { - allowskybox = false; // server will decide if this is allowed --KB + allowskybox = false; // server will decide if this is + // allowed --KB - Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); - Cmd_AddCommand ("envmap", R_Envmap_f); + Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); + Cmd_AddCommand ("envmap", R_Envmap_f); Cmd_AddCommand ("pointfile", R_ReadPointFile_f); Cmd_AddCommand ("loadsky", R_LoadSky_f); Cmd_AddCommand ("r_firecolor", R_FireColor_f); - R_InitBubble(); - + R_InitBubble (); + R_InitParticles (); netgraphtexture = texture_extension_number; @@ -206,50 +213,51 @@ void R_Init (void) texture_extension_number += MAX_CLIENTS; } -void R_Init_Cvars (void) +void +R_Init_Cvars (void) { - r_norefresh = Cvar_Get("r_norefresh", "0", CVAR_NONE, "None"); - r_drawentities = Cvar_Get("r_drawentities", "1", CVAR_NONE, "None"); - r_drawviewmodel = Cvar_Get("r_drawviewmodel", "1", CVAR_ARCHIVE, "None"); - r_shadows = Cvar_Get("r_shadows", "0", CVAR_NONE, "None"); - r_wateralpha = Cvar_Get("r_wateralpha", "1", CVAR_NONE, "None"); + r_norefresh = Cvar_Get ("r_norefresh", "0", CVAR_NONE, "None"); + r_drawentities = Cvar_Get ("r_drawentities", "1", CVAR_NONE, "None"); + r_drawviewmodel = Cvar_Get ("r_drawviewmodel", "1", CVAR_ARCHIVE, "None"); + r_shadows = Cvar_Get ("r_shadows", "0", CVAR_NONE, "None"); + r_wateralpha = Cvar_Get ("r_wateralpha", "1", CVAR_NONE, "None"); r_waterripple = Cvar_Get ("r_waterripple", "0", CVAR_NONE, "None"); - r_dynamic = Cvar_Get("r_dynamic", "1", CVAR_NONE, "None"); - r_novis = Cvar_Get("r_novis", "0", CVAR_NONE, "None"); - r_speeds = Cvar_Get("r_speeds", "0", CVAR_NONE, "None"); - r_netgraph = Cvar_Get("r_netgraph", "0", CVAR_NONE, "None"); + r_dynamic = Cvar_Get ("r_dynamic", "1", CVAR_NONE, "None"); + r_novis = Cvar_Get ("r_novis", "0", CVAR_NONE, "None"); + r_speeds = Cvar_Get ("r_speeds", "0", CVAR_NONE, "None"); + r_netgraph = Cvar_Get ("r_netgraph", "0", CVAR_NONE, "None"); - gl_clear = Cvar_Get("gl_clear", "0", CVAR_NONE, "None"); - gl_texsort = Cvar_Get("gl_texsort", "1", CVAR_NONE, "None"); - - gl_cull = Cvar_Get("gl_cull", "1", CVAR_NONE, "None"); - gl_smooth = Cvar_Get("gl_smooth", "1", CVAR_NONE, "None"); - gl_smoothdlights = Cvar_Get("gl_smoothdlights", "1", CVAR_NONE, "None"); - gl_affinemodels = Cvar_Get("gl_affinemodels", "0", CVAR_NONE, "None"); - gl_flashblend = Cvar_Get("gl_flashblend", "0", CVAR_NONE, "None"); - gl_playermip = Cvar_Get("gl_playermip", "0", CVAR_NONE, "None"); - gl_nocolors = Cvar_Get("gl_nocolors", "0", CVAR_NONE, "None"); + gl_clear = Cvar_Get ("gl_clear", "0", CVAR_NONE, "None"); + gl_texsort = Cvar_Get ("gl_texsort", "1", CVAR_NONE, "None"); + + gl_cull = Cvar_Get ("gl_cull", "1", CVAR_NONE, "None"); + gl_smooth = Cvar_Get ("gl_smooth", "1", CVAR_NONE, "None"); + gl_smoothdlights = Cvar_Get ("gl_smoothdlights", "1", CVAR_NONE, "None"); + gl_affinemodels = Cvar_Get ("gl_affinemodels", "0", CVAR_NONE, "None"); + gl_flashblend = Cvar_Get ("gl_flashblend", "0", CVAR_NONE, "None"); + gl_playermip = Cvar_Get ("gl_playermip", "0", CVAR_NONE, "None"); + gl_nocolors = Cvar_Get ("gl_nocolors", "0", CVAR_NONE, "None"); gl_fires = Cvar_Get ("gl_fires", "0", CVAR_ARCHIVE, - "Toggles lavaball and rocket fireballs"); + "Toggles lavaball and rocket fireballs"); gl_particles = Cvar_Get ("gl_particles", "1", CVAR_ARCHIVE, - "whether or not to draw particles"); + "whether or not to draw particles"); gl_fb_models = Cvar_Get ("gl_fb_models", "1", CVAR_ARCHIVE, - "Toggles fullbright color support for models.. " - "This is very handy, but costs me 2 FPS.. (=:]"); + "Toggles fullbright color support for models.. " + "This is very handy, but costs me 2 FPS.. (=:]"); gl_fb_bmodels = Cvar_Get ("gl_fb_bmodels", "1", CVAR_ARCHIVE, - "Toggles fullbright color support for bmodels"); + "Toggles fullbright color support for bmodels"); - gl_keeptjunctions = Cvar_Get("gl_keeptjunctions", "1", CVAR_NONE, "None"); - - r_skyname = Cvar_Get("r_skyname", "none", CVAR_NONE, - "name of the current skybox"); - gl_skymultipass = Cvar_Get("gl_skymultipass", "1", CVAR_NONE, - "controls whether the skydome is single or double pass"); + gl_keeptjunctions = Cvar_Get ("gl_keeptjunctions", "1", CVAR_NONE, "None"); + + r_skyname = Cvar_Get ("r_skyname", "none", CVAR_NONE, + "name of the current skybox"); + gl_skymultipass = Cvar_Get ("gl_skymultipass", "1", CVAR_NONE, + "controls whether the skydome is single or double pass"); gl_sky_clip = Cvar_Get ("gl_sky_clip", "0", CVAR_NONE, - "controls whether sky is drawn first (0) or later (1)"); + "controls whether sky is drawn first (0) or later (1)"); } /* @@ -259,30 +267,31 @@ R_TranslatePlayerSkin Translates a skin texture by the per-player color lookup =============== */ -void R_TranslatePlayerSkin (int playernum) +void +R_TranslatePlayerSkin (int playernum) { - int top, bottom; - byte translate[256]; - unsigned int translate32[256]; - int i, j; - byte *original; - unsigned int pixels[512*256], *out; - unsigned int scaled_width, scaled_height; - int inwidth, inheight; - int tinwidth, tinheight; - byte *inrow; - unsigned int frac, fracstep; + int top, bottom; + byte translate[256]; + unsigned int translate32[256]; + int i, j; + byte *original; + unsigned int pixels[512 * 256], *out; + unsigned int scaled_width, scaled_height; + int inwidth, inheight; + int tinwidth, tinheight; + byte *inrow; + unsigned int frac, fracstep; player_info_t *player; - extern byte player_8bit_texels[320*200]; - char s[512]; + extern byte player_8bit_texels[320 * 200]; + char s[512]; player = &cl.players[playernum]; if (!player->name[0]) return; - strcpy(s, Info_ValueForKey(player->userinfo, "skin")); - COM_StripExtension(s, s); - if (player->skin && !stricmp(s, player->skin->name)) + strcpy (s, Info_ValueForKey (player->userinfo, "skin")); + COM_StripExtension (s, s); + if (player->skin && !stricmp (s, player->skin->name)) player->skin = NULL; if (player->_topcolor != player->topcolor || @@ -297,33 +306,33 @@ void R_TranslatePlayerSkin (int playernum) top *= 16; bottom *= 16; - for (i=0 ; i<256 ; i++) + for (i = 0; i < 256; i++) translate[i] = i; - for (i=0 ; i<16 ; i++) - { - if (top < 128) // the artists made some backwards ranges. sigh. - translate[TOP_RANGE+i] = top+i; + for (i = 0; i < 16; i++) { + if (top < 128) // the artists made some backwards + // ranges. sigh. + translate[TOP_RANGE + i] = top + i; else - translate[TOP_RANGE+i] = top+15-i; - + translate[TOP_RANGE + i] = top + 15 - i; + if (bottom < 128) - translate[BOTTOM_RANGE+i] = bottom+i; + translate[BOTTOM_RANGE + i] = bottom + i; else - translate[BOTTOM_RANGE+i] = bottom+15-i; + translate[BOTTOM_RANGE + i] = bottom + 15 - i; } - // + // // locate the original skin pixels - // + // // real model width tinwidth = 296; tinheight = 194; if (!player->skin) - Skin_Find(player); - if ((original = Skin_Cache(player->skin)) != NULL) { - //skin data width + Skin_Find (player); + if ((original = Skin_Cache (player->skin)) != NULL) { + // skin data width inwidth = 320; inheight = 200; } else { @@ -338,87 +347,83 @@ void R_TranslatePlayerSkin (int playernum) glBindTexture (GL_TEXTURE_2D, playertextures + playernum); #if 0 - s = 320*200; - byte translated[320*200]; + s = 320 * 200; + byte translated[320 * 200]; - for (i=0 ; iskinwidth, paliashdr->skinheight, - false, false, true); + GL_Upload8 (translated, paliashdr->skinwidth, paliashdr->skinheight, + false, false, true); #endif // FIXME deek: This 512x256 limit sucks! - scaled_width = min(gl_max_size->int_val, 512); - scaled_height = min(gl_max_size->int_val, 256); + scaled_width = min (gl_max_size->int_val, 512); + scaled_height = min (gl_max_size->int_val, 256); // allow users to crunch sizes down even more if they want scaled_width >>= gl_playermip->int_val; scaled_height >>= gl_playermip->int_val; - if (VID_Is8bit()) { // 8bit texture upload - byte *out2; + if (VID_Is8bit ()) { // 8bit texture upload + byte *out2; - out2 = (byte *)pixels; - memset(pixels, 0, sizeof(pixels)); - fracstep = tinwidth*0x10000/scaled_width; - for (i=0 ; i> 1; - for (j=0 ; j>16]]; + for (j = 0; j < scaled_width; j += 4) { + out2[j] = translate[inrow[frac >> 16]]; frac += fracstep; - out2[j+1] = translate[inrow[frac>>16]]; + out2[j + 1] = translate[inrow[frac >> 16]]; frac += fracstep; - out2[j+2] = translate[inrow[frac>>16]]; + out2[j + 2] = translate[inrow[frac >> 16]]; frac += fracstep; - out2[j+3] = translate[inrow[frac>>16]]; + out2[j + 3] = translate[inrow[frac >> 16]]; frac += fracstep; } } - GL_Upload8_EXT ((byte *)pixels, scaled_width, scaled_height, false, false); + GL_Upload8_EXT ((byte *) pixels, scaled_width, scaled_height, false, + false); return; } - for (i=0 ; i<256 ; i++) + for (i = 0; i < 256; i++) translate32[i] = d_8to24table[translate[i]]; out = pixels; - memset(pixels, 0, sizeof(pixels)); - fracstep = tinwidth*0x10000/scaled_width; - for (i=0 ; i> 1; - for (j=0 ; j>16]]; + for (j = 0; j < scaled_width; j += 4) { + out[j] = translate32[inrow[frac >> 16]]; frac += fracstep; - out[j+1] = translate32[inrow[frac>>16]]; + out[j + 1] = translate32[inrow[frac >> 16]]; frac += fracstep; - out[j+2] = translate32[inrow[frac>>16]]; + out[j + 2] = translate32[inrow[frac >> 16]]; frac += fracstep; - out[j+3] = translate32[inrow[frac>>16]]; + out[j + 3] = translate32[inrow[frac >> 16]]; frac += fracstep; } } - glTexImage2D (GL_TEXTURE_2D, 0, gl_solid_format, - scaled_width, scaled_height, 0, GL_RGBA, - GL_UNSIGNED_BYTE, pixels); + glTexImage2D (GL_TEXTURE_2D, 0, gl_solid_format, + scaled_width, scaled_height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, pixels); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } } @@ -427,22 +432,23 @@ void R_TranslatePlayerSkin (int playernum) R_NewMap =============== */ -void R_NewMap (void) +void +R_NewMap (void) { - int i; - cvar_t *r_skyname; - - for (i=0 ; i<256 ; i++) + int i; + cvar_t *r_skyname; + + for (i = 0; i < 256; i++) d_lightstylevalue[i] = 264; // normal light value - memset (&r_worldentity, 0, sizeof(r_worldentity)); + memset (&r_worldentity, 0, sizeof (r_worldentity)); r_worldentity.model = cl.worldmodel; // clear out efrags in case the level hasn't been reloaded // FIXME: is this one short? - for (i=0 ; inumleafs ; i++) + for (i = 0; i < cl.worldmodel->numleafs; i++) cl.worldmodel->leafs[i].efrags = NULL; - + r_viewleaf = NULL; R_ClearParticles (); @@ -450,13 +456,12 @@ void R_NewMap (void) // identify sky texture skytexturenum = -1; - for (i=0 ; inumtextures ; i++) - { + for (i = 0; i < cl.worldmodel->numtextures; i++) { if (!cl.worldmodel->textures[i]) continue; - if (!strncmp(cl.worldmodel->textures[i]->name,"sky",3) ) + if (!strncmp (cl.worldmodel->textures[i]->name, "sky", 3)) skytexturenum = i; - cl.worldmodel->textures[i]->texturechain = NULL; + cl.worldmodel->textures[i]->texturechain = NULL; } r_skyname = Cvar_FindVar ("r_skyname"); if (r_skyname != NULL) @@ -474,37 +479,36 @@ For program optimization ==================== */ // LordHavoc: improved appearance and accuracy of timerefresh -void R_TimeRefresh_f (void) +void +R_TimeRefresh_f (void) { - int i; - double start, stop, time; + int i; + double start, stop, time; -// glDrawBuffer (GL_FRONT); +// glDrawBuffer (GL_FRONT); glFinish (); GL_EndRendering (); start = Sys_DoubleTime (); - for (i=0 ; i<128 ; i++) - { + for (i = 0; i < 128; i++) { GL_BeginRendering (&glx, &gly, &glwidth, &glheight); - r_refdef.viewangles[1] = i/128.0*360.0; + r_refdef.viewangles[1] = i / 128.0 * 360.0; R_RenderView (); glFinish (); GL_EndRendering (); } -// glFinish (); +// glFinish (); stop = Sys_DoubleTime (); - time = stop-start; - Con_Printf ("%f seconds (%f fps)\n", time, 128/time); + time = stop - start; + Con_Printf ("%f seconds (%f fps)\n", time, 128 / time); -// glDrawBuffer (GL_BACK); -// GL_EndRendering (); +// glDrawBuffer (GL_BACK); +// GL_EndRendering (); GL_BeginRendering (&glx, &gly, &glwidth, &glheight); } -void D_FlushCaches (void) +void +D_FlushCaches (void) { } - - diff --git a/source/gl_rsurf.c b/source/gl_rsurf.c index aa6d563..f47ad3c 100644 --- a/source/gl_rsurf.c +++ b/source/gl_rsurf.c @@ -35,92 +35,100 @@ #include #include -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h #include "qargs.h" -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, gl_model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, gl_model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" -qboolean r_cache_thrash; +qboolean r_cache_thrash; -extern double realtime; -int skytexturenum; +extern double realtime; +int skytexturenum; -extern vec3_t shadecolor; // Ender (Extend) Colormod -int lightmap_bytes; // 1 or 3 +extern vec3_t shadecolor; // Ender (Extend) Colormod +int lightmap_bytes; // 1 or 3 -int lightmap_textures; +int lightmap_textures; -unsigned int blocklights[18*18*3]; +unsigned int blocklights[18 * 18 * 3]; -cvar_t *gl_colorlights; +cvar_t *gl_colorlights; #define BLOCK_WIDTH 128 #define BLOCK_HEIGHT 128 // LordHavoc: since lightmaps are now allocated only as needed, allow a ridiculous number :) #define MAX_LIGHTMAPS 1024 -int active_lightmaps; +int active_lightmaps; typedef struct glRect_s { - unsigned char l,t,w,h; + unsigned char l, t, w, h; } glRect_t; -glpoly_t *lightmap_polys[MAX_LIGHTMAPS]; -glpoly_t *fullbright_polys[MAX_GLTEXTURES]; -qboolean lightmap_modified[MAX_LIGHTMAPS]; -glRect_t lightmap_rectchange[MAX_LIGHTMAPS]; +glpoly_t *lightmap_polys[MAX_LIGHTMAPS]; +glpoly_t *fullbright_polys[MAX_GLTEXTURES]; +qboolean lightmap_modified[MAX_LIGHTMAPS]; +glRect_t lightmap_rectchange[MAX_LIGHTMAPS]; -int allocated[MAX_LIGHTMAPS][BLOCK_WIDTH]; +int allocated[MAX_LIGHTMAPS][BLOCK_WIDTH]; // the lightmap texture data needs to be kept in // main memory so texsubimage can update properly // LordHavoc: changed to be allocated at runtime (typically lower memory usage) -byte *lightmaps[MAX_LIGHTMAPS]; +byte *lightmaps[MAX_LIGHTMAPS]; -msurface_t *waterchain = NULL; -msurface_t *sky_chain; +msurface_t *waterchain = NULL; +msurface_t *sky_chain; extern qboolean lighthalf; // LordHavoc: place for gl_rsurf setup code -void glrsurf_init() +void +glrsurf_init () { - memset(&lightmaps, 0, sizeof(lightmaps)); + memset (&lightmaps, 0, sizeof (lightmaps)); } -void recursivelightupdate(mnode_t *node) +void +recursivelightupdate (mnode_t *node) { - int c; + int c; msurface_t *surf; + if (node->children[0]->contents >= 0) - recursivelightupdate(node->children[0]); + recursivelightupdate (node->children[0]); if (node->children[1]->contents >= 0) - recursivelightupdate(node->children[1]); + recursivelightupdate (node->children[1]); if ((c = node->numsurfaces)) - for (surf = cl.worldmodel->surfaces + node->firstsurface; c ; c--, surf++) - surf->cached_dlight = true; + for (surf = cl.worldmodel->surfaces + node->firstsurface; c; + c--, surf++) surf->cached_dlight = true; } // LordHavoc: function to force all lightmaps to be updated -void R_ForceLightUpdate() +void +R_ForceLightUpdate () { - if (cl.worldmodel && cl.worldmodel->nodes && cl.worldmodel->nodes->contents >= 0) - recursivelightupdate(cl.worldmodel->nodes); + if (cl.worldmodel && cl.worldmodel->nodes + && cl.worldmodel->nodes->contents >= 0) + recursivelightupdate (cl.worldmodel->nodes); } /* @@ -128,8 +136,8 @@ void R_ForceLightUpdate() LordHavoc: completely rewrote this, relies on 64bit integer math... */ -int dlightdivtable[8192]; -int dlightdivtableinitialized = 0; +int dlightdivtable[8192]; +int dlightdivtableinitialized = 0; /* =============== @@ -138,81 +146,97 @@ R_AddDynamicLights NOTE! LordHavoc was here, and it shows... (Mercury) =============== */ -void R_AddDynamicLights (msurface_t *surf) +void +R_AddDynamicLights (msurface_t *surf) { - int sdtable[18], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, smax, tmax, red, green, blue, j; - unsigned int *bl; - float dist, f; - vec3_t impact, local; + int sdtable[18], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, + smax, tmax, red, green, blue, j; + unsigned int *bl; + float dist, f; + vec3_t impact, local; + // use 64bit integer... shame it's not very standardized... #if _MSC_VER || __BORLANDC__ - __int64 k; + __int64 k; #else - long long k; + long long k; #endif - if (!dlightdivtableinitialized) - { + if (!dlightdivtableinitialized) { dlightdivtable[0] = 1048576 >> 7; - for (s = 1;s < 8192;s++) + for (s = 1; s < 8192; s++) dlightdivtable[s] = 1048576 / (s << 7); dlightdivtableinitialized = 1; } - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; - for (lnum=0 ; lnumdlightbits & (1<dlightbits & (1 << lnum))) + continue; // not lit by this light - VectorSubtract(cl_dlights[lnum].origin, currententity->origin, local); + VectorSubtract (cl_dlights[lnum].origin, currententity->origin, local); dist = DotProduct (local, surf->plane->normal) - surf->plane->dist; - for (i=0 ; i<3 ; i++) - impact[i] = cl_dlights[lnum].origin[i] - surf->plane->normal[i]*dist; + for (i = 0; i < 3; i++) + impact[i] = + cl_dlights[lnum].origin[i] - surf->plane->normal[i] * dist; - f = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0]; + f = + DotProduct (impact, + surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - + surf->texturemins[0]; i = f; // reduce calculations - t = dist*dist; - for (s = 0;s < smax;s++, i -= 16) - sdtable[s] = i*i + t; + t = dist * dist; + for (s = 0; s < smax; s++, i -= 16) + sdtable[s] = i * i + t; - f = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1]; + f = + DotProduct (impact, + surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - + surf->texturemins[1]; i = f; - maxdist = (int) ((cl_dlights[lnum].radius*cl_dlights[lnum].radius) * 0.75); // for comparisons to minimum acceptable light + maxdist = (int) ((cl_dlights[lnum].radius * cl_dlights[lnum].radius) * 0.75); // for + // comparisons + // to + // minimum + // acceptable + // light // clamp radius to avoid exceeding 8192 entry division table if (maxdist > 1048576) maxdist = 1048576; - maxdist3 = maxdist - (int) (dist*dist); + maxdist3 = maxdist - (int) (dist * dist); // convert to 8.8 blocklights format - f = cl_dlights[lnum].color[0] * maxdist;red = f; - f = cl_dlights[lnum].color[1] * maxdist;green = f; - f = cl_dlights[lnum].color[2] * maxdist;blue = f; + f = cl_dlights[lnum].color[0] * maxdist; + red = f; + f = cl_dlights[lnum].color[1] * maxdist; + green = f; + f = cl_dlights[lnum].color[2] * maxdist; + blue = f; bl = blocklights; - for (t = 0;t < tmax;t++,i -= 16) - { - td = i*i; - if (td < maxdist3) // make sure some part of it is visible on this line + for (t = 0; t < tmax; t++, i -= 16) { + td = i * i; + if (td < maxdist3) // make sure some part of it is + // visible on this line { maxdist2 = maxdist - td; - for (s = 0;s < smax;s++) - { - if (sdtable[s] < maxdist2) - { - j = dlightdivtable[(sdtable[s]+td) >> 7]; - k = (red * j) >> 7;bl[0] += k; - k = (green * j) >> 7;bl[1] += k; - k = (blue * j) >> 7;bl[2] += k; + for (s = 0; s < smax; s++) { + if (sdtable[s] < maxdist2) { + j = dlightdivtable[(sdtable[s] + td) >> 7]; + k = (red * j) >> 7; + bl[0] += k; + k = (green * j) >> 7; + bl[1] += k; + k = (blue * j) >> 7; + bl[2] += k; } bl += 3; } - } - else - bl+=smax*3; // skip line + } else + bl += smax * 3; // skip line } } } @@ -226,38 +250,37 @@ void R_AddDynamicLights (msurface_t *surf) lighting if needed. Much cleaner that way. --KB */ void -R_BuildLightMap (msurface_t *surf, byte *dest, int stride) +R_BuildLightMap (msurface_t *surf, byte * dest, int stride) { - int smax, tmax; - int t; - int i, j, size; - byte *lightmap; - unsigned int scale; - int maps; - float t2; - unsigned int *bl; + int smax, tmax; + int t; + int i, j, size; + byte *lightmap; + unsigned int scale; + int maps; + float t2; + unsigned int *bl; surf->cached_dlight = (surf->dlightframe == r_framecount); - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; - size = smax*tmax; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; + size = smax * tmax; lightmap = surf->samples; // set to full bright if no light data if (!cl.worldmodel->lightdata) { bl = blocklights; - for (i=0 ; istyles[maps] != 255; - maps++) { + for (maps = 0; maps < MAXLIGHTMAPS && surf->styles[maps] != 255; maps++) { scale = d_lightstylevalue[surf->styles[maps]]; surf->cached_light[maps] = scale; // 8.8 fraction bl = blocklights; @@ -279,36 +300,35 @@ R_BuildLightMap (msurface_t *surf, byte *dest, int stride) } } } - // add all the dynamic lights if (surf->dlightframe == r_framecount) R_AddDynamicLights (surf); -store: + store: // bound and shift if (gl_colorlights->int_val) { stride -= smax * 3; bl = blocklights; if (lighthalf) { for (i = 0; i < tmax; i++, dest += stride) { - for (j=0 ; j> 8; - *dest++ = bound(0, t, 255); + *dest++ = bound (0, t, 255); t = (int) *bl++ >> 8; - *dest++ = bound(0, t, 255); + *dest++ = bound (0, t, 255); t = (int) *bl++ >> 8; - *dest++ = bound(0, t, 255); + *dest++ = bound (0, t, 255); } } } else { for (i = 0; i < tmax; i++, dest += stride) { - for (j=0; j < smax; j++) { + for (j = 0; j < smax; j++) { t = (int) *bl++ >> 7; - *dest++ = bound(0, t, 255); + *dest++ = bound (0, t, 255); t = (int) *bl++ >> 7; - *dest++ = bound(0, t, 255); + *dest++ = bound (0, t, 255); t = (int) *bl++ >> 7; - *dest++ = bound(0, t, 255); + *dest++ = bound (0, t, 255); } } } @@ -317,27 +337,27 @@ store: bl = blocklights; if (lighthalf) { for (i = 0; i < tmax; i++, dest += stride) { - for (j=0 ; j> 8; - t2 = bound(0, t, 255); + t2 = bound (0, t, 255); t = (int) *bl++ >> 8; - t2 += bound(0, t, 255); + t2 += bound (0, t, 255); t = (int) *bl++ >> 8; - t2 += bound(0, t, 255); - t2 *= (1.0/3.0); + t2 += bound (0, t, 255); + t2 *= (1.0 / 3.0); *dest++ = t2; } } } else { for (i = 0; i < tmax; i++, dest += stride) { - for (j=0 ; j> 7; - t2 = bound(0, t, 255); + t2 = bound (0, t, 255); t = (int) *bl++ >> 7; - t2 += bound(0, t, 255); + t2 += bound (0, t, 255); t = (int) *bl++ >> 7; - t2 += bound(0, t, 255); - t2 *= (1.0/3.0); + t2 += bound (0, t, 255); + t2 *= (1.0 / 3.0); *dest++ = t2; } } @@ -352,25 +372,24 @@ R_TextureAnimation Returns the proper texture for a given time and base texture =============== */ -texture_t *R_TextureAnimation (texture_t *base) +texture_t * +R_TextureAnimation (texture_t *base) { - int relative; - int count; + int relative; + int count; - if (currententity->frame) - { + if (currententity->frame) { if (base->alternate_anims) base = base->alternate_anims; } - + if (!base->anim_total) return base; - relative = (int)(cl.time*10) % base->anim_total; + relative = (int) (cl.time * 10) % base->anim_total; - count = 0; - while (base->anim_min > relative || base->anim_max <= relative) - { + count = 0; + while (base->anim_min > relative || base->anim_max <= relative) { base = base->anim_next; if (!base) Sys_Error ("R_TextureAnimation: broken cycle"); @@ -391,16 +410,19 @@ texture_t *R_TextureAnimation (texture_t *base) */ -extern int solidskytexture; -extern int alphaskytexture; -extern float speedscale; // for top sky and bottom sky +extern int solidskytexture; +extern int alphaskytexture; +extern float speedscale; // for top sky and bottom sky -lpMTexFUNC qglMTexCoord2f = NULL; +lpMTexFUNC qglMTexCoord2f = NULL; lpSelTexFUNC qglSelectTexture = NULL; -void GL_UploadLightmap(int i, int x, int y, int w, int h) +void +GL_UploadLightmap (int i, int x, int y, int w, int h) { - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, y, BLOCK_WIDTH, h, gl_lightmap_format, GL_UNSIGNED_BYTE, lightmaps[i] + (y * BLOCK_WIDTH) * lightmap_bytes); + glTexSubImage2D (GL_TEXTURE_2D, 0, 0, y, BLOCK_WIDTH, h, gl_lightmap_format, + GL_UNSIGNED_BYTE, + lightmaps[i] + (y * BLOCK_WIDTH) * lightmap_bytes); } /* @@ -411,64 +433,69 @@ Systems that have fast state and texture changes can just do everything as it passes with no need to sort ================ */ -void R_DrawMultitexturePoly (msurface_t *s) +void +R_DrawMultitexturePoly (msurface_t *s) { - int maps; - float *v; - int i; - texture_t *texture = R_TextureAnimation (s->texinfo->texture); + int maps; + float *v; + int i; + texture_t *texture = R_TextureAnimation (s->texinfo->texture); c_brush_polys++; i = s->lightmaptexturenum; - glColor3f(1,1,1); + glColor3f (1, 1, 1); // Binds world to texture env 0 - qglSelectTexture (gl_mtex_enum+0); + qglSelectTexture (gl_mtex_enum + 0); glBindTexture (GL_TEXTURE_2D, texture->gl_texturenum); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - glEnable(GL_TEXTURE_2D); + glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glEnable (GL_TEXTURE_2D); // Binds lightmap to texenv 1 - qglSelectTexture (gl_mtex_enum+1); + qglSelectTexture (gl_mtex_enum + 1); glBindTexture (GL_TEXTURE_2D, lightmap_textures + i); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glEnable(GL_TEXTURE_2D); + glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glEnable (GL_TEXTURE_2D); // check for lightmap modification - if (r_dynamic->int_val) - { - for (maps = 0;maps < MAXLIGHTMAPS && s->styles[maps] != 255;maps++) + if (r_dynamic->int_val) { + for (maps = 0; maps < MAXLIGHTMAPS && s->styles[maps] != 255; maps++) if (d_lightstylevalue[s->styles[maps]] != s->cached_light[maps]) goto dynamic; if (s->dlightframe == r_framecount // dynamic this frame - || s->cached_dlight) // dynamic previously + || s->cached_dlight) // dynamic previously { -dynamic: - R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * lightmap_bytes, BLOCK_WIDTH*lightmap_bytes); - GL_UploadLightmap(i, s->light_s, s->light_t, (s->extents[0]>>4)+1, (s->extents[1]>>4)+1); + dynamic: + R_BuildLightMap (s, + lightmaps[s->lightmaptexturenum] + + (s->light_t * BLOCK_WIDTH + + s->light_s) * lightmap_bytes, + BLOCK_WIDTH * lightmap_bytes); + GL_UploadLightmap (i, s->light_s, s->light_t, + (s->extents[0] >> 4) + 1, + (s->extents[1] >> 4) + 1); } } - glBegin(GL_POLYGON); + glBegin (GL_POLYGON); v = s->polys->verts[0]; - for (i=0 ; ipolys->numverts ; i++, v+= VERTEXSIZE) - { + for (i = 0; i < s->polys->numverts; i++, v += VERTEXSIZE) { qglMTexCoord2f (gl_mtex_enum + 0, v[3], v[4]); qglMTexCoord2f (gl_mtex_enum + 1, v[5], v[6]); glVertex3fv (v); } glEnd (); - glDisable(GL_TEXTURE_2D); - qglSelectTexture (gl_mtex_enum+0); - glEnable(GL_TEXTURE_2D); + glDisable (GL_TEXTURE_2D); + qglSelectTexture (gl_mtex_enum + 0); + glEnable (GL_TEXTURE_2D); - if (texture->gl_fb_texturenum>0) { + if (texture->gl_fb_texturenum > 0) { s->polys->fb_chain = fullbright_polys[texture->gl_fb_texturenum]; fullbright_polys[texture->gl_fb_texturenum] = s->polys; } - glColor3ubv(lighthalf_v); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glColor3ubv (lighthalf_v); + glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } /* @@ -476,34 +503,34 @@ dynamic: R_BlendLightmaps ================ */ -void R_BlendLightmaps (void) +void +R_BlendLightmaps (void) { - int i, j; - glpoly_t *p; - float *v; + int i, j; + glpoly_t *p; + float *v; - glDepthMask(GL_FALSE); // don't bother writing Z + glDepthMask (GL_FALSE); // don't bother writing Z glBlendFunc (GL_ZERO, GL_SRC_COLOR); - glColor3f(1,1,1); + glColor3f (1, 1, 1); - for (i=0 ; ichain) - { + for (; p; p = p->chain) { glBegin (GL_POLYGON); v = p->verts[0]; - for (j=0 ; jnumverts ; j++, v+= VERTEXSIZE) - { + for (j = 0; j < p->numverts; j++, v += VERTEXSIZE) { glTexCoord2fv (&v[5]); glVertex3fv (v); } @@ -512,10 +539,10 @@ void R_BlendLightmaps (void) } // Return to normal blending --KB - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(GL_TRUE); // back to normal Z buffering + glDepthMask (GL_TRUE); // back to normal Z buffering } /* @@ -525,26 +552,26 @@ void R_BlendLightmaps (void) void R_RenderFullbrights (void) { - int i, j; - glpoly_t *p; - float *v; + int i, j; + glpoly_t *p; + float *v; - glBlendFunc(GL_ONE, GL_ONE); + glBlendFunc (GL_ONE, GL_ONE); - for (i=1; ifb_chain) { + for (p = fullbright_polys[i]; p; p = p->fb_chain) { glBegin (GL_POLYGON); - for (j=0, v=p->verts[0]; jnumverts; j++, v+=VERTEXSIZE) { + for (j = 0, v = p->verts[0]; j < p->numverts; j++, v += VERTEXSIZE) { glTexCoord2fv (&v[3]); glVertex3fv (v); } - glEnd(); + glEnd (); } } - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } /* @@ -552,25 +579,25 @@ R_RenderFullbrights (void) R_RenderBrushPoly ================ */ -void R_RenderBrushPoly (msurface_t *fa) +void +R_RenderBrushPoly (msurface_t *fa) { - byte *base; - int maps; - glRect_t *theRect; - int i; - float *v; - int smax, tmax; - texture_t *texture = R_TextureAnimation (fa->texinfo->texture); + byte *base; + int maps; + glRect_t *theRect; + int i; + float *v; + int smax, tmax; + texture_t *texture = R_TextureAnimation (fa->texinfo->texture); c_brush_polys++; - glColor3f(1, 1, 1); + glColor3f (1, 1, 1); glBindTexture (GL_TEXTURE_2D, texture->gl_texturenum); glBegin (GL_POLYGON); v = fa->polys->verts[0]; - for (i = 0;i < fa->polys->numverts;i++, v += VERTEXSIZE) - { + for (i = 0; i < fa->polys->numverts; i++, v += VERTEXSIZE) { glTexCoord2fv (&v[3]); glVertex3fv (v); } @@ -581,23 +608,20 @@ void R_RenderBrushPoly (msurface_t *fa) fa->polys->chain = lightmap_polys[fa->lightmaptexturenum]; lightmap_polys[fa->lightmaptexturenum] = fa->polys; - if (texture->gl_fb_texturenum>0) { + if (texture->gl_fb_texturenum > 0) { fa->polys->fb_chain = fullbright_polys[texture->gl_fb_texturenum]; fullbright_polys[texture->gl_fb_texturenum] = fa->polys; } - // check for lightmap modification - for (maps = 0 ; maps < MAXLIGHTMAPS && fa->styles[maps] != 255 ; - maps++) + for (maps = 0; maps < MAXLIGHTMAPS && fa->styles[maps] != 255; maps++) if (d_lightstylevalue[fa->styles[maps]] != fa->cached_light[maps]) goto dynamic; if (fa->dlightframe == r_framecount // dynamic this frame || fa->cached_dlight) // dynamic previously { -dynamic: - if (r_dynamic->int_val) - { + dynamic: + if (r_dynamic->int_val) { lightmap_modified[fa->lightmaptexturenum] = true; theRect = &lightmap_rectchange[fa->lightmaptexturenum]; if (fa->light_t < theRect->t) { @@ -610,37 +634,40 @@ dynamic: theRect->w += theRect->l - fa->light_s; theRect->l = fa->light_s; } - smax = (fa->extents[0]>>4)+1; - tmax = (fa->extents[1]>>4)+1; + smax = (fa->extents[0] >> 4) + 1; + tmax = (fa->extents[1] >> 4) + 1; if ((theRect->w + theRect->l) < (fa->light_s + smax)) - theRect->w = (fa->light_s-theRect->l)+smax; + theRect->w = (fa->light_s - theRect->l) + smax; if ((theRect->h + theRect->t) < (fa->light_t + tmax)) - theRect->h = (fa->light_t-theRect->t)+tmax; - base = lightmaps[fa->lightmaptexturenum] + (fa->light_t * BLOCK_WIDTH + fa->light_s) * lightmap_bytes; - R_BuildLightMap (fa, base, BLOCK_WIDTH*lightmap_bytes); + theRect->h = (fa->light_t - theRect->t) + tmax; + base = + lightmaps[fa->lightmaptexturenum] + (fa->light_t * BLOCK_WIDTH + + fa->light_s) * + lightmap_bytes; + R_BuildLightMap (fa, base, BLOCK_WIDTH * lightmap_bytes); } } - glColor3ubv(lighthalf_v); + glColor3ubv (lighthalf_v); } -void GL_WaterSurface(msurface_t *s) +void +GL_WaterSurface (msurface_t *s) { - int i; + int i; + i = s->texinfo->texture->gl_texturenum; glBindTexture (GL_TEXTURE_2D, i); - if (r_wateralpha->value < 1.0) - { - glDepthMask(GL_FALSE); + if (r_wateralpha->value < 1.0) { + glDepthMask (GL_FALSE); if (lighthalf) { - glColor4f(0.5,0.5,0.5,r_wateralpha->value); + glColor4f (0.5, 0.5, 0.5, r_wateralpha->value); } else { - glColor4f(1,1,1,r_wateralpha->value); + glColor4f (1, 1, 1, r_wateralpha->value); } EmitWaterPolys (s); - glColor3ubv(lighthalf_v); - glDepthMask(GL_TRUE); - } - else + glColor3ubv (lighthalf_v); + glDepthMask (GL_TRUE); + } else EmitWaterPolys (s); } @@ -649,10 +676,11 @@ void GL_WaterSurface(msurface_t *s) R_DrawWaterSurfaces ================ */ -void R_DrawWaterSurfaces (void) +void +R_DrawWaterSurfaces (void) { - int i; - msurface_t *s; + int i; + msurface_t *s; if (!waterchain) return; @@ -662,30 +690,28 @@ void R_DrawWaterSurfaces (void) glLoadMatrixf (r_world_matrix); if (r_wateralpha->value < 1.0) { - glDepthMask(GL_FALSE); + glDepthMask (GL_FALSE); if (lighthalf) { - glColor4f(0.5,0.5,0.5,r_wateralpha->value); + glColor4f (0.5, 0.5, 0.5, r_wateralpha->value); } else { - glColor4f(1,1,1,r_wateralpha->value); + glColor4f (1, 1, 1, r_wateralpha->value); } } i = -1; - for (s = waterchain;s;s = s->texturechain) - { - if (i != s->texinfo->texture->gl_texturenum) - { + for (s = waterchain; s; s = s->texturechain) { + if (i != s->texinfo->texture->gl_texturenum) { i = s->texinfo->texture->gl_texturenum; glBindTexture (GL_TEXTURE_2D, i); } EmitWaterPolys (s); } - + waterchain = NULL; if (r_wateralpha->value < 1.0) { - glDepthMask(GL_TRUE); - glColor3ubv(lighthalf_v); + glDepthMask (GL_TRUE); + glColor3ubv (lighthalf_v); } } @@ -695,23 +721,24 @@ void R_DrawWaterSurfaces (void) DrawTextureChains ================ */ -void DrawTextureChains (void) +void +DrawTextureChains (void) { - int i; - msurface_t *s; + int i; + msurface_t *s; - glDisable(GL_BLEND); + glDisable (GL_BLEND); - for (i=0 ; inumtextures ; i++) { + for (i = 0; i < cl.worldmodel->numtextures; i++) { if (!cl.worldmodel->textures[i]) continue; - for (s = cl.worldmodel->textures[i]->texturechain;s;s = s->texturechain) - R_RenderBrushPoly (s); + for (s = cl.worldmodel->textures[i]->texturechain; s; + s = s->texturechain) R_RenderBrushPoly (s); cl.worldmodel->textures[i]->texturechain = NULL; } - glEnable(GL_BLEND); + glEnable (GL_BLEND); } /* @@ -719,32 +746,29 @@ void DrawTextureChains (void) R_DrawBrushModel ================= */ -void R_DrawBrushModel (entity_t *e) +void +R_DrawBrushModel (entity_t *e) { - int i; - int k; - vec3_t mins, maxs; - msurface_t *psurf; - float dot; - mplane_t *pplane; - model_t *clmodel; - qboolean rotated; + int i; + int k; + vec3_t mins, maxs; + msurface_t *psurf; + float dot; + mplane_t *pplane; + model_t *clmodel; + qboolean rotated; currententity = e; clmodel = e->model; - if (e->angles[0] || e->angles[1] || e->angles[2]) - { + if (e->angles[0] || e->angles[1] || e->angles[2]) { rotated = true; - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { mins[i] = e->origin[i] - clmodel->radius; maxs[i] = e->origin[i] + clmodel->radius; } - } - else - { + } else { rotated = false; VectorAdd (e->origin, clmodel->mins, mins); VectorAdd (e->origin, clmodel->maxs, maxs); @@ -753,16 +777,16 @@ void R_DrawBrushModel (entity_t *e) if (R_CullBox (mins, maxs)) return; - memset (lightmap_polys, 0, sizeof(lightmap_polys)); - memset (fullbright_polys, 0, sizeof(fullbright_polys)); + memset (lightmap_polys, 0, sizeof (lightmap_polys)); + memset (fullbright_polys, 0, sizeof (fullbright_polys)); if (gl_sky_clip->int_val) { sky_chain = 0; } VectorSubtract (r_refdef.vieworg, e->origin, modelorg); if (rotated) { - vec3_t temp; - vec3_t forward, right, up; + vec3_t temp; + vec3_t forward, right, up; VectorCopy (modelorg, temp); AngleVectors (e->angles, forward, right, up); @@ -775,34 +799,32 @@ void R_DrawBrushModel (entity_t *e) // calculate dynamic lighting for bmodel if it's not an // instanced model - if (clmodel->firstmodelsurface != 0 && !gl_flashblend->int_val) - { - vec3_t lightorigin; - for (k=0 ; kfirstmodelsurface != 0 && !gl_flashblend->int_val) { + vec3_t lightorigin; + + for (k = 0; k < MAX_DLIGHTS; k++) { + if ((cl_dlights[k].die < cl.time) || (!cl_dlights[k].radius)) continue; - VectorSubtract(cl_dlights[k].origin, e->origin, lightorigin); - R_MarkLights (lightorigin, &cl_dlights[k], 1<nodes + clmodel->hulls[0].firstclipnode); + VectorSubtract (cl_dlights[k].origin, e->origin, lightorigin); + R_MarkLights (lightorigin, &cl_dlights[k], 1 << k, + clmodel->nodes + clmodel->hulls[0].firstclipnode); } } glPushMatrix (); - e->angles[0] = -e->angles[0]; // stupid quake bug + e->angles[0] = -e->angles[0]; // stupid quake bug R_RotateForEntity (e); - e->angles[0] = -e->angles[0]; // stupid quake bug + e->angles[0] = -e->angles[0]; // stupid quake bug // LordHavoc: anyone without multitexture won't want texsort 0 anyway... if (!gl_mtexable) Cvar_SetValue (gl_texsort, 1); - // + // // draw texture - // - for (i=0 ; inummodelsurfaces ; i++, psurf++) { + // + for (i = 0; i < clmodel->nummodelsurfaces; i++, psurf++) { // find which side of the node we are on pplane = psurf->plane; @@ -810,11 +832,10 @@ void R_DrawBrushModel (entity_t *e) // draw the polygon if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) - { + (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { if (psurf->flags & SURF_DRAWTURB) { - GL_WaterSurface(psurf); + GL_WaterSurface (psurf); } else if (psurf->flags & SURF_DRAWSKY) { psurf->texturechain = sky_chain; sky_chain = psurf; @@ -852,75 +873,72 @@ void R_DrawBrushModel (entity_t *e) R_RecursiveWorldNode ================ */ -void R_RecursiveWorldNode (mnode_t *node) +void +R_RecursiveWorldNode (mnode_t *node) { - int c, side; - mplane_t *plane; - msurface_t *surf, **mark; - mleaf_t *pleaf; - double dot; + int c, side; + mplane_t *plane; + msurface_t *surf, **mark; + mleaf_t *pleaf; + double dot; if (node->contents == CONTENTS_SOLID) - return; // solid + return; // solid if (node->visframe != r_visframecount) return; - if (R_CullBox (node->minmaxs, node->minmaxs+3)) + if (R_CullBox (node->minmaxs, node->minmaxs + 3)) return; // if a leaf node, draw stuff - if (node->contents < 0) - { - pleaf = (mleaf_t *)node; + if (node->contents < 0) { + pleaf = (mleaf_t *) node; - if ((c = pleaf->nummarksurfaces)) - { + if ((c = pleaf->nummarksurfaces)) { mark = pleaf->firstmarksurface; - do - { + do { (*mark)->visframe = r_framecount; mark++; } while (--c); } - - // deal with model fragments in this leaf + // deal with model fragments in this leaf if (pleaf->efrags) R_StoreEfrags (&pleaf->efrags); return; } - // node is just a decision point, so go down the apropriate sides // find which side of the node we are on plane = node->plane; - switch (plane->type) - { - case PLANE_X: - dot = modelorg[0] - plane->dist; - break; - case PLANE_Y: - dot = modelorg[1] - plane->dist; - break; - case PLANE_Z: - dot = modelorg[2] - plane->dist; - break; - default: - dot = DotProduct (modelorg, plane->normal) - plane->dist; - break; + switch (plane->type) { + case PLANE_X: + dot = modelorg[0] - plane->dist; + break; + case PLANE_Y: + dot = modelorg[1] - plane->dist; + break; + case PLANE_Z: + dot = modelorg[2] - plane->dist; + break; + default: + dot = DotProduct (modelorg, plane->normal) - plane->dist; + break; } side = dot < 0; // recurse down the children, front side first // LordHavoc: save a stack frame by avoiding a call - if (node->children[side]->contents != CONTENTS_SOLID && node->children[side]->visframe == r_visframecount && !R_CullBox (node->children[side]->minmaxs, node->children[side]->minmaxs+3)) + if (node->children[side]->contents != CONTENTS_SOLID + && node->children[side]->visframe == r_visframecount + && !R_CullBox (node->children[side]->minmaxs, + node->children[side]->minmaxs + 3)) R_RecursiveWorldNode (node->children[side]); // draw stuff - if ((c = node->numsurfaces)) - { + if ((c = node->numsurfaces)) { surf = cl.worldmodel->surfaces + node->firstsurface; if (dot < -BACKFACE_EPSILON) @@ -928,13 +946,12 @@ void R_RecursiveWorldNode (mnode_t *node) else if (dot > BACKFACE_EPSILON) side = 0; - for ( ; c ; c--, surf++) - { + for (; c; c--, surf++) { if (surf->visframe != r_framecount) continue; if ((dot < 0) ^ !!(surf->flags & SURF_PLANEBACK)) - continue; // wrong side + continue; // wrong side if (surf->flags & SURF_DRAWTURB) { @@ -952,11 +969,13 @@ void R_RecursiveWorldNode (mnode_t *node) } } } - // recurse down the back side // LordHavoc: save a stack frame by avoiding a call side = !side; - if (node->children[side]->contents != CONTENTS_SOLID && node->children[side]->visframe == r_visframecount && !R_CullBox (node->children[side]->minmaxs, node->children[side]->minmaxs+3)) + if (node->children[side]->contents != CONTENTS_SOLID + && node->children[side]->visframe == r_visframecount + && !R_CullBox (node->children[side]->minmaxs, + node->children[side]->minmaxs + 3)) R_RecursiveWorldNode (node->children[side]); } @@ -967,11 +986,12 @@ void R_RecursiveWorldNode (mnode_t *node) R_DrawWorld ============= */ -void R_DrawWorld (void) +void +R_DrawWorld (void) { - entity_t ent; + entity_t ent; - memset (&ent, 0, sizeof(ent)); + memset (&ent, 0, sizeof (ent)); ent.model = cl.worldmodel; VectorCopy (r_refdef.vieworg, modelorg); @@ -982,8 +1002,8 @@ void R_DrawWorld (void) if (!gl_mtexable) Cvar_SetValue (gl_texsort, 1); - memset (lightmap_polys, 0, sizeof(lightmap_polys)); - memset (fullbright_polys, 0, sizeof(fullbright_polys)); + memset (lightmap_polys, 0, sizeof (lightmap_polys)); + memset (fullbright_polys, 0, sizeof (fullbright_polys)); if (gl_sky_clip->int_val) { sky_chain = 0; } else { @@ -1011,34 +1031,30 @@ void R_DrawWorld (void) R_MarkLeaves =============== */ -void R_MarkLeaves (void) +void +R_MarkLeaves (void) { - byte *vis; - mnode_t *node; - int i; - byte solid[4096]; + byte *vis; + mnode_t *node; + int i; + byte solid[4096]; if (r_oldviewleaf == r_viewleaf && !r_novis->int_val) return; - + r_visframecount++; r_oldviewleaf = r_viewleaf; - if (r_novis->int_val) - { + if (r_novis->int_val) { vis = solid; - memset (solid, 0xff, (cl.worldmodel->numleafs+7)>>3); - } - else + memset (solid, 0xff, (cl.worldmodel->numleafs + 7) >> 3); + } else vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel); - - for (i=0 ; inumleafs ; i++) - { - if (vis[i>>3] & (1<<(i&7))) - { - node = (mnode_t *)&cl.worldmodel->leafs[i+1]; - do - { + + for (i = 0; i < cl.worldmodel->numleafs; i++) { + if (vis[i >> 3] & (1 << (i & 7))) { + node = (mnode_t *) &cl.worldmodel->leafs[i + 1]; + do { if (node->visframe == r_visframecount) break; node->visframe = r_visframecount; @@ -1059,29 +1075,26 @@ void R_MarkLeaves (void) */ // returns a texture number and the position inside it -int AllocBlock (int w, int h, int *x, int *y) +int +AllocBlock (int w, int h, int *x, int *y) { - int i, j; - int best, best2; - int texnum; + int i, j; + int best, best2; + int texnum; - for (texnum=0 ; texnum= best) + for (j = 0; j < w; j++) { + if (allocated[texnum][i + j] >= best) break; - if (allocated[texnum][i+j] > best2) - best2 = allocated[texnum][i+j]; + if (allocated[texnum][i + j] > best2) + best2 = allocated[texnum][i + j]; } - if (j == w) - { + if (j == w) { // this is a valid spot *x = i; *y = best = best2; @@ -1093,9 +1106,9 @@ int AllocBlock (int w, int h, int *x, int *y) // LordHavoc: allocate lightmaps only as needed if (!lightmaps[texnum]) - lightmaps[texnum] = calloc(BLOCK_WIDTH * BLOCK_HEIGHT, 3); + lightmaps[texnum] = calloc (BLOCK_WIDTH * BLOCK_HEIGHT, 3); - for (i=0 ; iedges; lnumverts = fa->numedges; vertpage = 0; - // + // // draw texture - // - poly = Hunk_Alloc (sizeof(glpoly_t) + (lnumverts-4) * VERTEXSIZE*sizeof(float)); + // + poly = + + Hunk_Alloc (sizeof (glpoly_t) + + (lnumverts - 4) * VERTEXSIZE * sizeof (float)); poly->next = fa->polys; poly->flags = fa->flags; fa->polys = poly; poly->numverts = lnumverts; - for (i=0 ; isurfedges[fa->firstedge + i]; - if (lindex > 0) - { + if (lindex > 0) { r_pedge = &pedges[lindex]; vec = r_pcurrentvertbase[r_pedge->v[0]].position; - } - else - { + } else { r_pedge = &pedges[-lindex]; vec = r_pcurrentvertbase[r_pedge->v[1]].position; } @@ -1163,54 +1176,52 @@ void BuildSurfaceDisplayList (msurface_t *fa) poly->verts[i][3] = s; poly->verts[i][4] = t; - // + // // lightmap texture coordinates - // + // s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3]; s -= fa->texturemins[0]; - s += fa->light_s*16; + s += fa->light_s * 16; s += 8; - s /= BLOCK_WIDTH*16; //fa->texinfo->texture->width; + s /= BLOCK_WIDTH * 16; // fa->texinfo->texture->width; t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3]; t -= fa->texturemins[1]; - t += fa->light_t*16; + t += fa->light_t * 16; t += 8; - t /= BLOCK_HEIGHT*16; //fa->texinfo->texture->height; + t /= BLOCK_HEIGHT * 16; // fa->texinfo->texture->height; poly->verts[i][5] = s; poly->verts[i][6] = t; } - // + // // remove co-linear points - Ed - // - if (!gl_keeptjunctions->int_val && !(fa->flags & SURF_UNDERWATER) ) - { - for (i = 0 ; i < lnumverts ; ++i) - { - vec3_t v1, v2; - float *prev, *this, *next; + // + if (!gl_keeptjunctions->int_val && !(fa->flags & SURF_UNDERWATER)) { + for (i = 0; i < lnumverts; ++i) { + vec3_t v1, v2; + float *prev, *this, *next; prev = poly->verts[(i + lnumverts - 1) % lnumverts]; this = poly->verts[i]; next = poly->verts[(i + 1) % lnumverts]; - VectorSubtract( this, prev, v1 ); - VectorNormalize( v1 ); - VectorSubtract( next, prev, v2 ); - VectorNormalize( v2 ); + VectorSubtract (this, prev, v1); + VectorNormalize (v1); + VectorSubtract (next, prev, v2); + VectorNormalize (v2); // skip co-linear points # define COLINEAR_EPSILON 0.001 - if ((fabs( v1[0] - v2[0] ) <= COLINEAR_EPSILON) && - (fabs( v1[1] - v2[1] ) <= COLINEAR_EPSILON) && - (fabs( v1[2] - v2[2] ) <= COLINEAR_EPSILON)) - { - int j; - for (j = i + 1; j < lnumverts; ++j) - { - int k; + if ((fabs (v1[0] - v2[0]) <= COLINEAR_EPSILON) && + (fabs (v1[1] - v2[1]) <= COLINEAR_EPSILON) && + (fabs (v1[2] - v2[2]) <= COLINEAR_EPSILON)) { + int j; + + for (j = i + 1; j < lnumverts; ++j) { + int k; + for (k = 0; k < VERTEXSIZE; ++k) poly->verts[j - 1][k] = poly->verts[j][k]; } @@ -1230,20 +1241,24 @@ void BuildSurfaceDisplayList (msurface_t *fa) GL_CreateSurfaceLightmap ======================== */ -void GL_CreateSurfaceLightmap (msurface_t *surf) +void +GL_CreateSurfaceLightmap (msurface_t *surf) { - int smax, tmax; - byte *base; + int smax, tmax; + byte *base; - if (surf->flags & (SURF_DRAWSKY|SURF_DRAWTURB)) + if (surf->flags & (SURF_DRAWSKY | SURF_DRAWTURB)) return; - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; - surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t); - base = lightmaps[surf->lightmaptexturenum] + (surf->light_t * BLOCK_WIDTH + surf->light_s) * lightmap_bytes; - R_BuildLightMap (surf, base, BLOCK_WIDTH*lightmap_bytes); + surf->lightmaptexturenum = + AllocBlock (smax, tmax, &surf->light_s, &surf->light_t); + base = + lightmaps[surf->lightmaptexturenum] + (surf->light_t * BLOCK_WIDTH + + surf->light_s) * lightmap_bytes; + R_BuildLightMap (surf, base, BLOCK_WIDTH * lightmap_bytes); } @@ -1255,34 +1270,30 @@ Builds the lightmap texture with all the surfaces from all brush models ================== */ -void GL_BuildLightmaps (void) +void +GL_BuildLightmaps (void) { - int i, j; - model_t *m; + int i, j; + model_t *m; - memset (allocated, 0, sizeof(allocated)); + memset (allocated, 0, sizeof (allocated)); - r_framecount = 1; // no dlightcache + r_framecount = 1; // no dlightcache - if (!lightmap_textures) - { + if (!lightmap_textures) { lightmap_textures = texture_extension_number; texture_extension_number += MAX_LIGHTMAPS; } - if (gl_colorlights->int_val) - { + if (gl_colorlights->int_val) { gl_lightmap_format = GL_RGB; lightmap_bytes = 3; - } - else - { + } else { gl_lightmap_format = GL_LUMINANCE; lightmap_bytes = 1; } - for (j=1 ; jvertexes; currentmodel = m; - for (i=0 ; inumsurfaces ; i++) - { - if ( m->surfaces[i].flags & SURF_DRAWTURB ) + for (i = 0; i < m->numsurfaces; i++) { + if (m->surfaces[i].flags & SURF_DRAWTURB) continue; GL_CreateSurfaceLightmap (m->surfaces + i); BuildSurfaceDisplayList (m->surfaces + i); } } - if (gl_mtexable && !gl_texsort->int_val) - qglSelectTexture (gl_mtex_enum+1); + if (gl_mtexable && !gl_texsort->int_val) + qglSelectTexture (gl_mtex_enum + 1); - // + // // upload all lightmaps that were filled - // - for (i=0 ; iint_val) - qglSelectTexture (gl_mtex_enum+0); + if (gl_mtexable && !gl_texsort->int_val) + qglSelectTexture (gl_mtex_enum + 0); } - diff --git a/source/gl_screen.c b/source/gl_screen.c index 3f2685d..1647036 100644 --- a/source/gl_screen.c +++ b/source/gl_screen.c @@ -423,9 +423,8 @@ SCR_Init (void) scr_initialized = true; } - /* - SCR_DrawRam - */ + /* + SCR_DrawRam */ void SCR_DrawRam (void) { @@ -505,8 +504,8 @@ SCR_DrawFPS (void) chewing on my foot! */ snprintf (st, sizeof (st), "%-3d FPS", lastfps); /* Misty: New trick! (for me) the ? makes this work like a if then else - - IE: if cl_hudswap->int_val is not null, do first case, else (else is - a : here) do second case. Deek taught me this trick */ + IE: if cl_hudswap->int_val is not null, do first case, else (else is a + : here) do second case. Deek taught me this trick */ x = cl_hudswap->int_val ? vid.width - ((strlen (st) * 8) + 8) : 8; y = vid.height - sb_lines - 8; Draw_String8 (x, y, st); @@ -1157,12 +1156,13 @@ SCR_UpdateScreen (void) Cvar_SetValue (brightness, bound (1, brightness->value, 5)); if (lighthalf) // LordHavoc: render was done at half - // brightness + // + // brightness f = brightness->value * 2; else f = brightness->value; if (f >= 1.002) { // Make sure we don't get bit by - // roundoff errors + // roundoff errors glBlendFunc (GL_DST_COLOR, GL_ONE); glBegin (GL_QUADS); while (f >= 1.002) { // precision diff --git a/source/gl_sky_clip.c b/source/gl_sky_clip.c index 8d396eb..58eb090 100644 --- a/source/gl_sky_clip.c +++ b/source/gl_sky_clip.c @@ -158,13 +158,16 @@ static int find_intersect (int face1, vec3_t x1, int face2, vec3_t x2, vec3_t y) { vec3_t n; // normal to the plane formed by the - // eye and the two points on the cube. + + // eye and the two points on the cube. vec3_t x = { 0, 0, 0 }; // point on cube edge of adjoining - // faces. always on an axis plane. + + // faces. always on an axis plane. vec3_t v = { 0, 0, 0 }; // direction vector of cube edge. - // always +ve + + // always +ve vec_t x_n, v_n; // x.n and v.n int axis; @@ -217,30 +220,30 @@ set_vertex (struct box_def *box, int face, int ind, vec3_t v) VectorCopy (v, box->face[face].poly.verts[ind]); VectorAdd (v, r_refdef.vieworg, box->face[face].poly.verts[ind]); switch (face) { - case 0: - box->face[face].poly.verts[ind][3] = (1024 - v[1]) / 2048; - box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; - break; - case 1: - box->face[face].poly.verts[ind][3] = (1024 + v[0]) / 2048; - box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; - break; - case 2: - box->face[face].poly.verts[ind][3] = (1024 + v[0]) / 2048; - box->face[face].poly.verts[ind][4] = (1024 + v[1]) / 2048; - break; - case 3: - box->face[face].poly.verts[ind][3] = (1024 + v[1]) / 2048; - box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; - break; - case 4: - box->face[face].poly.verts[ind][3] = (1024 - v[0]) / 2048; - box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; - break; - case 5: - box->face[face].poly.verts[ind][3] = (1024 + v[0]) / 2048; - box->face[face].poly.verts[ind][4] = (1024 - v[1]) / 2048; - break; + case 0: + box->face[face].poly.verts[ind][3] = (1024 - v[1]) / 2048; + box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; + break; + case 1: + box->face[face].poly.verts[ind][3] = (1024 + v[0]) / 2048; + box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; + break; + case 2: + box->face[face].poly.verts[ind][3] = (1024 + v[0]) / 2048; + box->face[face].poly.verts[ind][4] = (1024 + v[1]) / 2048; + break; + case 3: + box->face[face].poly.verts[ind][3] = (1024 + v[1]) / 2048; + box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; + break; + case 4: + box->face[face].poly.verts[ind][3] = (1024 - v[0]) / 2048; + box->face[face].poly.verts[ind][4] = (1024 - v[2]) / 2048; + break; + case 5: + box->face[face].poly.verts[ind][3] = (1024 + v[0]) / 2048; + box->face[face].poly.verts[ind][4] = (1024 - v[1]) / 2048; + break; } } @@ -365,172 +368,182 @@ process_corners (struct box_def *box) } switch (box->face_count) { - case 1: - case 2: - case 8: - // no corners - return; - case 3: - // one corner, no edges - { - vec3_t v; - - find_cube_vertex (visit[0].face, visit[1].face, visit[2].face, v); - insert_cube_vertices (box, visit[0], 1, v); - insert_cube_vertices (box, visit[1], 1, v); - insert_cube_vertices (box, visit[2], 1, v); - } - break; - case 4: - if (max_visit > 1) + case 1: + case 2: + case 8: + // no corners return; - if (abs (visit[2].face - visit[0].face) == 3 - && abs (visit[3].face - visit[1].face) == 3) { - // 4 vertices - int sum, diff; - vec3_t v[4]; + case 3: + // one corner, no edges + { + vec3_t v; - sum = visit[0].face + visit[1].face + visit[2].face + visit[3].face; - diff = visit[1].face - visit[0].face; - sum %= 3; - diff = (diff + 6) % 6; - - center = faces_table[sum][diff]; - for (i = 0; i < 4; i++) { - find_cube_vertex (visit[i].face, visit[(i + 1) & 3].face, - center, v[i]); - add_vertex (box, center, v[i]); + find_cube_vertex (visit[0].face, visit[1].face, visit[2].face, + v); + insert_cube_vertices (box, visit[0], 1, v); + insert_cube_vertices (box, visit[1], 1, v); + insert_cube_vertices (box, visit[2], 1, v); } - for (i = 0; i < 4; i++) - insert_cube_vertices (box, visit[i], 2, v[i], v[(i - 1) & 3]); - } else { - // 2 vertices - int l_f, t_f, r_f, b_f; - vec3_t v_l, v_r; - - if (abs (visit[2].face - visit[0].face) == 3) { - l_f = 0; - t_f = 1; - r_f = 2; - b_f = 3; - } else if (abs (visit[3].face - visit[1].face) == 3) { - l_f = 1; - t_f = 2; - r_f = 3; - b_f = 0; - } else { + break; + case 4: + if (max_visit > 1) return; + if (abs (visit[2].face - visit[0].face) == 3 + && abs (visit[3].face - visit[1].face) == 3) { + // 4 vertices + int sum, diff; + vec3_t v[4]; + + sum = + visit[0].face + visit[1].face + visit[2].face + + visit[3].face; + diff = visit[1].face - visit[0].face; + sum %= 3; + diff = (diff + 6) % 6; + + center = faces_table[sum][diff]; + for (i = 0; i < 4; i++) { + find_cube_vertex (visit[i].face, visit[(i + 1) & 3].face, + center, v[i]); + add_vertex (box, center, v[i]); + } + for (i = 0; i < 4; i++) + insert_cube_vertices (box, visit[i], 2, v[i], + v[(i - 1) & 3]); + } else { + // 2 vertices + int l_f, t_f, r_f, b_f; + vec3_t v_l, v_r; + + if (abs (visit[2].face - visit[0].face) == 3) { + l_f = 0; + t_f = 1; + r_f = 2; + b_f = 3; + } else if (abs (visit[3].face - visit[1].face) == 3) { + l_f = 1; + t_f = 2; + r_f = 3; + b_f = 0; + } else { + return; + } + find_cube_vertex (visit[l_f].face, visit[t_f].face, + visit[b_f].face, v_l); + find_cube_vertex (visit[r_f].face, visit[t_f].face, + visit[b_f].face, v_r); + + insert_cube_vertices (box, visit[t_f], 2, v_r, v_l); + insert_cube_vertices (box, visit[b_f], 2, v_l, v_r); + + insert_cube_vertices (box, visit[l_f], 1, v_l); + insert_cube_vertices (box, visit[r_f], 1, v_r); } - find_cube_vertex (visit[l_f].face, visit[t_f].face, visit[b_f].face, - v_l); - find_cube_vertex (visit[r_f].face, visit[t_f].face, visit[b_f].face, - v_r); + break; + case 5: + if (max_visit > 1) { + // one vertex + vec3_t v; - insert_cube_vertices (box, visit[t_f], 2, v_r, v_l); - insert_cube_vertices (box, visit[b_f], 2, v_l, v_r); + for (i = 0; i < 4; i++) { + // don't need to check the 5th visit + if (visit[(i + 2) % 5].face == visit[(i + 4) % 5].face) + break; + } + find_cube_vertex (visit[i].face, visit[(i + 1) % 5].face, + visit[(i + 2) % 5].face, v); + insert_cube_vertices (box, visit[i], 1, v); + insert_cube_vertices (box, visit[(i + 1) % 5], 1, v); + insert_cube_vertices (box, visit[(i + 4) % 5], 1, v); - insert_cube_vertices (box, visit[l_f], 1, v_l); - insert_cube_vertices (box, visit[r_f], 1, v_r); - } - break; - case 5: - if (max_visit > 1) { - // one vertex - vec3_t v; + } else { + // 3 vertices + unsigned int sel = + (((abs (visit[2].face - visit[0].face) == 3) << 2) | + ((abs (visit[3].face - visit[1].face) == 3) << 1) + | ((abs (visit[4].face - visit[2].face) == 3) << 0)); + vec3_t v[3]; - for (i = 0; i < 4; i++) { - // don't need to check the 5th visit - if (visit[(i + 2) % 5].face == visit[(i + 4) % 5].face) + center = faces_bit_magic[sel]; + // printf ("%02o %d %d %d %d %d %d\n", sel, center, + // visit[0].face, + // visit[1].face, visit[2].face, visit[3].face, + // visit[4].face); + for (i = 0; i < 3; i++) + find_cube_vertex (visit[center].face, + visit[(center + 1 + i) % 5].face, + visit[(center + 2 + i) % 5].face, v[i]); + insert_cube_vertices (box, visit[center], 3, v[0], v[1], v[2]); + insert_cube_vertices (box, visit[(center + 1) % 5], 1, v[0]); + insert_cube_vertices (box, visit[(center + 2) % 5], 2, v[1], + v[0]); + insert_cube_vertices (box, visit[(center + 3) % 5], 2, v[2], + v[1]); + insert_cube_vertices (box, visit[(center + 4) % 5], 1, v[2]); + } + break; + case 6: + if (max_visit > 2) + return; + for (i = 0; i < 5; i++) { + // don't need to check the last point + if (visit[(i + 3) % 6].face == visit[(i + 5) % 6].face + || visit[(i + 2) % 6].face == visit[(i + 5) % 6].face) break; } - find_cube_vertex (visit[i].face, visit[(i + 1) % 5].face, - visit[(i + 2) % 5].face, v); - insert_cube_vertices (box, visit[i], 1, v); - insert_cube_vertices (box, visit[(i + 1) % 5], 1, v); - insert_cube_vertices (box, visit[(i + 4) % 5], 1, v); + if (visit[(i + 3) % 6].face == visit[(i + 5) % 6].face) { + // adjacant vertices + vec3_t v[2]; - } else { - // 3 vertices - unsigned int sel = - (((abs (visit[2].face - visit[0].face) == 3) << 2) | - ((abs (visit[3].face - visit[1].face) == 3) << 1) - | ((abs (visit[4].face - visit[2].face) == 3) << 0)); - vec3_t v[3]; + find_cube_vertex (visit[i].face, visit[(i + 1) % 6].face, + visit[(i + 2) % 6].face, v[0]); + find_cube_vertex (visit[(i + 1) % 6].face, + visit[(i + 2) % 6].face, + visit[(i + 3) % 6].face, v[1]); - center = faces_bit_magic[sel]; - //printf ("%02o %d %d %d %d %d %d\n", sel, center, visit[0].face, - // visit[1].face, visit[2].face, visit[3].face, visit[4].face); - for (i = 0; i < 3; i++) - find_cube_vertex (visit[center].face, - visit[(center + 1 + i) % 5].face, - visit[(center + 2 + i) % 5].face, v[i]); - insert_cube_vertices (box, visit[center], 3, v[0], v[1], v[2]); - insert_cube_vertices (box, visit[(center + 1) % 5], 1, v[0]); - insert_cube_vertices (box, visit[(center + 2) % 5], 2, v[1], v[0]); - insert_cube_vertices (box, visit[(center + 3) % 5], 2, v[2], v[1]); - insert_cube_vertices (box, visit[(center + 4) % 5], 1, v[2]); - } - break; - case 6: - if (max_visit > 2) - return; - for (i = 0; i < 5; i++) { - // don't need to check the last point - if (visit[(i + 3) % 6].face == visit[(i + 5) % 6].face - || visit[(i + 2) % 6].face == visit[(i + 5) % 6].face) - break; - } - if (visit[(i + 3) % 6].face == visit[(i + 5) % 6].face) { - // adjacant vertices - vec3_t v[2]; + insert_cube_vertices (box, visit[(i + 5) % 6], 2, v[2], v[1]); - find_cube_vertex (visit[i].face, visit[(i + 1) % 6].face, - visit[(i + 2) % 6].face, v[0]); - find_cube_vertex (visit[(i + 1) % 6].face, visit[(i + 2) % 6].face, - visit[(i + 3) % 6].face, v[1]); + insert_cube_vertices (box, visit[i], 1, v[0]); + insert_cube_vertices (box, visit[(i + 1) % 6], 2, v[1], v[0]); + insert_cube_vertices (box, visit[(i + 2) % 6], 1, v[1]); + } else { + // opposing vertices + vec3_t v[2]; - insert_cube_vertices (box, visit[(i + 5) % 6], 2, v[2], v[1]); + find_cube_vertex (visit[i].face, visit[(i + 1) % 6].face, + visit[(i + 2) % 6].face, v[0]); + find_cube_vertex (visit[(i + 3) % 6].face, + visit[(i + 4) % 6].face, + visit[(i + 5) % 6].face, v[1]); - insert_cube_vertices (box, visit[i], 1, v[0]); - insert_cube_vertices (box, visit[(i + 1) % 6], 2, v[1], v[0]); - insert_cube_vertices (box, visit[(i + 2) % 6], 1, v[1]); - } else { - // opposing vertices - vec3_t v[2]; + insert_cube_vertices (box, visit[i], 1, v[0]); + insert_cube_vertices (box, visit[(i + 1) % 6], 1, v[0]); - find_cube_vertex (visit[i].face, visit[(i + 1) % 6].face, - visit[(i + 2) % 6].face, v[0]); - find_cube_vertex (visit[(i + 3) % 6].face, visit[(i + 4) % 6].face, - visit[(i + 5) % 6].face, v[1]); + insert_cube_vertices (box, visit[(i + 3) % 6], 1, v[1]); + insert_cube_vertices (box, visit[(i + 4) % 6], 1, v[1]); - insert_cube_vertices (box, visit[i], 1, v[0]); - insert_cube_vertices (box, visit[(i + 1) % 6], 1, v[0]); + insert_cube_vertices (box, visit[(i + 2) % 6], 1, v[1]); + insert_cube_vertices (box, visit[(i + 5) % 6], 1, v[0]); + } + break; + case 7: + for (i = 0; i < 6; i++) { + // don't need to check the last point + if (visit[(i + 2) % 6].face == visit[(i + 4) % 6].face + && visit[(i + 4) % 6].face == visit[(i + 6) % 6].face) + break; + } + { + vec3_t v; - insert_cube_vertices (box, visit[(i + 3) % 6], 1, v[1]); - insert_cube_vertices (box, visit[(i + 4) % 6], 1, v[1]); + find_cube_vertex (visit[i].face, visit[(i + 1) % 6].face, + visit[(i + 2) % 6].face, v); - insert_cube_vertices (box, visit[(i + 2) % 6], 1, v[1]); - insert_cube_vertices (box, visit[(i + 5) % 6], 1, v[0]); - } - break; - case 7: - for (i = 0; i < 6; i++) { - // don't need to check the last point - if (visit[(i + 2) % 6].face == visit[(i + 4) % 6].face - && visit[(i + 4) % 6].face == visit[(i + 6) % 6].face) - break; - } - { - vec3_t v; - - find_cube_vertex (visit[i].face, visit[(i + 1) % 6].face, - visit[(i + 2) % 6].face, v); - - insert_cube_vertices (box, visit[i], 1, v); - insert_cube_vertices (box, visit[(i + 1) % 7], 1, v); - insert_cube_vertices (box, visit[(i + 6) % 7], 1, v); - } - break; + insert_cube_vertices (box, visit[i], 1, v); + insert_cube_vertices (box, visit[(i + 1) % 7], 1, v); + insert_cube_vertices (box, visit[(i + 6) % 7], 1, v); + } + break; } } diff --git a/source/gl_trans.c b/source/gl_trans.c index d7fb581..365d610 100644 --- a/source/gl_trans.c +++ b/source/gl_trans.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -40,11 +40,12 @@ CL_NewTranslation ===================== */ -void CL_NewTranslation (int slot) +void +CL_NewTranslation (int slot) { if (slot > MAX_CLIENTS) -// Sys_Error ("CL_NewTranslation: slot > MAX_CLIENTS"); +// Sys_Error ("CL_NewTranslation: slot > MAX_CLIENTS"); Host_EndGame ("CL_NewTranslation: slot > MAX_CLIENTS"); - R_TranslatePlayerSkin(slot); + R_TranslatePlayerSkin (slot); } diff --git a/source/gl_view.c b/source/gl_view.c index 9acf9c3..1df7bb3 100644 --- a/source/gl_view.c +++ b/source/gl_view.c @@ -27,43 +27,46 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "sbar.h" -#include "render.h" // needed by: client.h, model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "glquake.h" -extern byte *host_basepal; -extern double host_frametime; -extern int onground; -extern byte gammatable[256]; +extern byte *host_basepal; +extern double host_frametime; +extern int onground; +extern byte gammatable[256]; -extern cvar_t *gl_cshiftpercent; +extern cvar_t *gl_cshiftpercent; -byte ramps[3][256]; -float v_blend[4]; +byte ramps[3][256]; +float v_blend[4]; -void V_CalcPowerupCshift (void); -qboolean V_CheckGamma (void); +void V_CalcPowerupCshift (void); +qboolean V_CheckGamma (void); /* V_CalcBlend @@ -74,47 +77,46 @@ qboolean V_CheckGamma (void); void V_CalcBlend (void) { - float r, g, b, a, a2, a3; - int j; + float r, g, b, a, a2, a3; + int j; r = 0; g = 0; b = 0; a = 0; - for (j=0 ; jvalue) continue; - a2 = ((cl.cshifts[j].percent * gl_cshiftpercent->value) / 100.0) / 255.0; + a2 = + ((cl.cshifts[j].percent * gl_cshiftpercent->value) / 100.0) / 255.0; if (!a2) continue; - a2 = min(a2, 1.0); - r += (cl.cshifts[j].destcolor[0]-r) * a2; - g += (cl.cshifts[j].destcolor[1]-g) * a2; - b += (cl.cshifts[j].destcolor[2]-b) * a2; - + a2 = min (a2, 1.0); + r += (cl.cshifts[j].destcolor[0] - r) * a2; + g += (cl.cshifts[j].destcolor[1] - g) * a2; + b += (cl.cshifts[j].destcolor[2] - b) * a2; + a3 = (1.0 - a) * (1.0 - a2); a = 1.0 - a3; } // LordHavoc: saturate color - if (a) - { + if (a) { a2 = 1.0 / a; r *= a2; g *= a2; b *= a2; - if (a > 1) // clamp alpha blend too + if (a > 1) // clamp alpha blend too a = 1; } - v_blend[0] = min(r, 255.0)/255.0; - v_blend[1] = min(g, 255.0)/255.0; - v_blend[2] = min(b, 255.0)/255.0; + v_blend[0] = min (r, 255.0) / 255.0; + v_blend[1] = min (g, 255.0) / 255.0; + v_blend[2] = min (b, 255.0) / 255.0; v_blend[3] = bound (0.0, a, 1.0); } @@ -124,16 +126,17 @@ V_UpdatePalette ============= */ -void V_UpdatePalette (void) +void +V_UpdatePalette (void) { - int i, j; - qboolean new; - qboolean force; + int i, j; + qboolean new; + qboolean force; V_CalcPowerupCshift (); - + new = false; - + for (i = 0; i < NUM_CSHIFTS; i++) { if (cl.cshifts[i].percent != cl.prev_cshifts[i].percent) { new = true; @@ -148,12 +151,12 @@ void V_UpdatePalette (void) } // drop the damage value - cl.cshifts[CSHIFT_DAMAGE].percent -= host_frametime*150; + cl.cshifts[CSHIFT_DAMAGE].percent -= host_frametime * 150; if (cl.cshifts[CSHIFT_DAMAGE].percent <= 0) cl.cshifts[CSHIFT_DAMAGE].percent = 0; // drop the bonus value - cl.cshifts[CSHIFT_BONUS].percent -= host_frametime*100; + cl.cshifts[CSHIFT_BONUS].percent -= host_frametime * 100; if (cl.cshifts[CSHIFT_BONUS].percent <= 0) cl.cshifts[CSHIFT_BONUS].percent = 0; @@ -174,7 +177,7 @@ void V_UpdatePalette (void) void BuildGammaTable (float b, float c) { - int i; + int i; for (i = 0; i < 256; i++) gammatable[i] = i; diff --git a/source/gl_warp.c b/source/gl_warp.c index 4b0ef86..40a5785 100644 --- a/source/gl_warp.c +++ b/source/gl_warp.c @@ -34,26 +34,26 @@ #include "glquake.h" #include "sys.h" -extern double realtime; -extern model_t *loadmodel; +extern double realtime; +extern model_t *loadmodel; extern qboolean lighthalf; -msurface_t *warpface; +msurface_t *warpface; extern cvar_t *gl_subdivide_size; -void BoundPoly (int numverts, float *verts, vec3_t mins, vec3_t maxs) +void +BoundPoly (int numverts, float *verts, vec3_t mins, vec3_t maxs) { - int i, j; - float *v; + int i, j; + float *v; mins[0] = mins[1] = mins[2] = 9999; maxs[0] = maxs[1] = maxs[2] = -9999; v = verts; - for (i=0 ; i maxs[j]) @@ -61,28 +61,30 @@ void BoundPoly (int numverts, float *verts, vec3_t mins, vec3_t maxs) } } -void SubdividePolygon (int numverts, float *verts) +void +SubdividePolygon (int numverts, float *verts) { - int i, j, k; - vec3_t mins, maxs; - float m; - float *v; - vec3_t front[64], back[64]; - int f, b; - float dist[64]; - float frac; - glpoly_t *poly; - float s, t; + int i, j, k; + vec3_t mins, maxs; + float m; + float *v; + vec3_t front[64], back[64]; + int f, b; + float dist[64]; + float frac; + glpoly_t *poly; + float s, t; if (numverts > 60) Sys_Error ("numverts = %i", numverts); BoundPoly (numverts, verts, mins, maxs); - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { m = (mins[i] + maxs[i]) * 0.5; - m = gl_subdivide_size->value * floor (m/gl_subdivide_size->value + 0.5); + m = + gl_subdivide_size->value * floor (m / gl_subdivide_size->value + + 0.5); if (maxs[i] - m < 8) continue; if (m - mins[i] < 8) @@ -90,36 +92,32 @@ void SubdividePolygon (int numverts, float *verts) // cut it v = verts + i; - for (j=0 ; j= 0) - { + for (j = 0; j < numverts; j++, v += 3) { + if (dist[j] >= 0) { VectorCopy (v, front[f]); f++; } - if (dist[j] <= 0) - { + if (dist[j] <= 0) { VectorCopy (v, back[b]); b++; } - if (dist[j] == 0 || dist[j+1] == 0) + if (dist[j] == 0 || dist[j + 1] == 0) continue; - if ( (dist[j] > 0) != (dist[j+1] > 0) ) - { + if ((dist[j] > 0) != (dist[j + 1] > 0)) { // clip point - frac = dist[j] / (dist[j] - dist[j+1]); - for (k=0 ; k<3 ; k++) - front[f][k] = back[b][k] = v[k] + frac*(v[3+k] - v[k]); + frac = dist[j] / (dist[j] - dist[j + 1]); + for (k = 0; k < 3; k++) + front[f][k] = back[b][k] = v[k] + frac * (v[3 + k] - v[k]); f++; b++; } @@ -130,12 +128,14 @@ void SubdividePolygon (int numverts, float *verts) return; } - poly = Hunk_Alloc (sizeof(glpoly_t) + (numverts-4) * VERTEXSIZE*sizeof(float)); + poly = + + Hunk_Alloc (sizeof (glpoly_t) + + (numverts - 4) * VERTEXSIZE * sizeof (float)); poly->next = warpface->polys; warpface->polys = poly; poly->numverts = numverts; - for (i=0 ; iverts[i]); s = DotProduct (verts, warpface->texinfo->vecs[0]); t = DotProduct (verts, warpface->texinfo->vecs[1]); @@ -153,22 +153,22 @@ boundaries so that turbulent and sky warps can be done reasonably. ================ */ -void GL_SubdivideSurface (msurface_t *fa) +void +GL_SubdivideSurface (msurface_t *fa) { - vec3_t verts[64]; - int numverts; - int i; - int lindex; - float *vec; + vec3_t verts[64]; + int numverts; + int i; + int lindex; + float *vec; warpface = fa; - // + // // convert edges back to a normal polygon - // + // numverts = 0; - for (i=0 ; inumedges ; i++) - { + for (i = 0; i < fa->numedges; i++) { lindex = loadmodel->surfedges[fa->firstedge + i]; if (lindex > 0) @@ -187,10 +187,10 @@ void GL_SubdivideSurface (msurface_t *fa) // speed up sin calculations - Ed -float turbsin[] = -{ +float turbsin[] = { # include "gl_warp_sin.h" }; + #define TURBSCALE (256.0 / (2 * M_PI)) /* @@ -200,36 +200,35 @@ EmitWaterPolys Does a water warp on the pre-fragmented glpoly_t chain ============= */ -void EmitWaterPolys (msurface_t *fa) +void +EmitWaterPolys (msurface_t *fa) { - glpoly_t *p; - float *v; - int i; - float s, t, os, ot; - vec3_t nv; + glpoly_t *p; + float *v; + int i; + float s, t, os, ot; + vec3_t nv; - for (p=fa->polys ; p ; p=p->next) - { + for (p = fa->polys; p; p = p->next) { glBegin (GL_POLYGON); - for (i=0,v=p->verts[0] ; inumverts ; i++, v+=VERTEXSIZE) - { + for (i = 0, v = p->verts[0]; i < p->numverts; i++, v += VERTEXSIZE) { os = v[3]; ot = v[4]; - s = os + turbsin[(int)((ot*0.125+realtime) * TURBSCALE) & 255]; - s *= (1.0/64); + s = os + turbsin[(int) ((ot * 0.125 + realtime) * TURBSCALE) & 255]; + s *= (1.0 / 64); - t = ot + turbsin[(int)((os*0.125+realtime) * TURBSCALE) & 255]; - t *= (1.0/64); + t = ot + turbsin[(int) ((os * 0.125 + realtime) * TURBSCALE) & 255]; + t *= (1.0 / 64); glTexCoord2f (s, t); VectorCopy (v, nv); nv[2] += r_waterripple->value - * turbsin[(int)((v[3]*0.125+realtime) * TURBSCALE) & 255] - * turbsin[(int)((v[4]*0.125+realtime) * TURBSCALE) & 255] + * turbsin[(int) ((v[3] * 0.125 + realtime) * TURBSCALE) & 255] + * turbsin[(int) ((v[4] * 0.125 + realtime) * TURBSCALE) & 255] * (1.0 / 64.0); - + glVertex3fv (nv); } glEnd (); diff --git a/source/in_null.c b/source/in_null.c index e18076f..41fd0d8 100644 --- a/source/in_null.c +++ b/source/in_null.c @@ -27,26 +27,31 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif -void IN_Init (void) +void +IN_Init (void) { } -void IN_Init_Cvars (void) +void +IN_Init_Cvars (void) { } -void IN_Shutdown (void) +void +IN_Shutdown (void) { } -void IN_Commands (void) +void +IN_Commands (void) { } -void IN_Move (usercmd_t *cmd) +void +IN_Move (usercmd_t *cmd) { } @@ -55,7 +60,7 @@ void IN_Move (usercmd_t *cmd) IN_ModeChanged =========== */ -void IN_ModeChanged (void) +void +IN_ModeChanged (void) { } - diff --git a/source/in_sdl.c b/source/in_sdl.c index 7c8a7bc..5a81e4f 100644 --- a/source/in_sdl.c +++ b/source/in_sdl.c @@ -26,7 +26,7 @@ */ #ifdef HAVE_CONFIG_H -#include "config.h" +# include "config.h" #endif #include @@ -51,19 +51,21 @@ #ifdef WIN32 // fixme: this is evil... #include -HWND mainwindow; +HWND mainwindow; #endif -cvar_t *_windowed_mouse; -int old_windowed_mouse; +cvar_t *_windowed_mouse; +int old_windowed_mouse; -int modestate; // fixme: just to avoid cross-comp. errors - remove later +int modestate; // fixme: just to avoid cross-comp. + + // errors - remove later static qboolean mouse_avail; -static float mouse_x, mouse_y; -static int mouse_oldbuttonstate = 0; +static float mouse_x, mouse_y; +static int mouse_oldbuttonstate = 0; -extern viddef_t vid; // global video state +extern viddef_t vid; // global video state /* ================ @@ -74,154 +76,252 @@ IN_SendKeyEvents void IN_SendKeyEvents (void) { - SDL_Event event; - int sym, state, but; - int modstate; + SDL_Event event; + int sym, state, but; + int modstate; - while (SDL_PollEvent(&event)) { + while (SDL_PollEvent (&event)) { switch (event.type) { - case SDL_KEYDOWN: - case SDL_KEYUP: - sym = event.key.keysym.sym; - state = event.key.state; - modstate = SDL_GetModState(); - switch(sym) { - case SDLK_DELETE: sym = K_DEL; break; - case SDLK_BACKSPACE: sym = K_BACKSPACE; break; - case SDLK_F1: sym = K_F1; break; - case SDLK_F2: sym = K_F2; break; - case SDLK_F3: sym = K_F3; break; - case SDLK_F4: sym = K_F4; break; - case SDLK_F5: sym = K_F5; break; - case SDLK_F6: sym = K_F6; break; - case SDLK_F7: sym = K_F7; break; - case SDLK_F8: sym = K_F8; break; - case SDLK_F9: sym = K_F9; break; - case SDLK_F10: sym = K_F10; break; - case SDLK_F11: sym = K_F11; break; - case SDLK_F12: sym = K_F12; break; - case SDLK_BREAK: - case SDLK_PAUSE: sym = K_PAUSE; break; - case SDLK_UP: sym = K_UPARROW; break; - case SDLK_DOWN: sym = K_DOWNARROW; break; - case SDLK_RIGHT: sym = K_RIGHTARROW; break; - case SDLK_LEFT: sym = K_LEFTARROW; break; - case SDLK_INSERT: sym = K_INS; break; - case SDLK_HOME: sym = K_HOME; break; - case SDLK_END: sym = K_END; break; - case SDLK_PAGEUP: sym = K_PGUP; break; - case SDLK_PAGEDOWN: sym = K_PGDN; break; - case SDLK_RSHIFT: - case SDLK_LSHIFT: sym = K_SHIFT; break; - case SDLK_RCTRL: - case SDLK_LCTRL: sym = K_CTRL; break; - case SDLK_RALT: - case SDLK_LALT: sym = K_ALT; break; - case SDLK_CAPSLOCK: sym = K_CAPSLOCK; break; - case SDLK_KP0: - if(modstate & KMOD_NUM) sym = K_INS; - else sym = SDLK_0; - break; - case SDLK_KP1: - if(modstate & KMOD_NUM) sym = K_END; - else sym = SDLK_1; - break; - case SDLK_KP2: - if(modstate & KMOD_NUM) sym = K_DOWNARROW; - else sym = SDLK_2; - break; - case SDLK_KP3: - if(modstate & KMOD_NUM) sym = K_PGDN; - else sym = SDLK_3; - break; - case SDLK_KP4: - if(modstate & KMOD_NUM) sym = K_LEFTARROW; - else sym = SDLK_4; - break; - case SDLK_KP5: sym = SDLK_5; break; - case SDLK_KP6: - if(modstate & KMOD_NUM) sym = K_RIGHTARROW; - else sym = SDLK_6; - break; - case SDLK_KP7: - if(modstate & KMOD_NUM) sym = K_HOME; - else sym = SDLK_7; - break; - case SDLK_KP8: - if(modstate & KMOD_NUM) sym = K_UPARROW; - else sym = SDLK_8; - break; - case SDLK_KP9: - if(modstate & KMOD_NUM) sym = K_PGUP; - else sym = SDLK_9; - break; - case SDLK_KP_PERIOD: - if(modstate & KMOD_NUM) sym = K_DEL; - else sym = SDLK_PERIOD; - break; - case SDLK_KP_DIVIDE: sym = SDLK_SLASH; break; - case SDLK_KP_MULTIPLY: sym = SDLK_ASTERISK; break; - case SDLK_KP_MINUS: sym = SDLK_MINUS; break; - case SDLK_KP_PLUS: sym = SDLK_PLUS; break; - case SDLK_KP_ENTER: sym = SDLK_RETURN; break; - case SDLK_KP_EQUALS: sym = SDLK_EQUALS; break; - } - // If we're not directly handled and still above 255 - // just force it to 0 - if(sym > 255) sym = 0; - Key_Event(sym, -1, state); - break; - - case SDL_MOUSEBUTTONDOWN: - case SDL_MOUSEBUTTONUP: - but = event.button.button; - if (but == 2) - but = 3; - else if (but == 3) - but = 2; - - switch (but) { - case 1: - case 2: - case 3: - Key_Event(K_MOUSE1 + but - 1, 0, event.type - == SDL_MOUSEBUTTONDOWN); - break; - case 4: - Key_Event(K_MWHEELUP, 0, event.type == SDL_MOUSEBUTTONDOWN); - break; - case 5: - Key_Event(K_MWHEELDOWN, 0, event.type == SDL_MOUSEBUTTONDOWN); - break; - } - break; - - case SDL_MOUSEMOTION: - if (_windowed_mouse->value) { - if ((event.motion.x != (vid.width/2)) - || (event.motion.y != (vid.height/2)) ) { - // *2 for vid_sdl.c, *10 for vid_sgl.c. - mouse_x = event.motion.xrel*2; - mouse_y = event.motion.yrel*2; - if ((event.motion.x < ((vid.width/2)-(vid.width/4))) || - (event.motion.x > ((vid.width/2)+(vid.width/4))) || - (event.motion.y < ((vid.height/2)-(vid.height/4))) || - (event.motion.y > ((vid.height/2)+(vid.height/4))) ) - SDL_WarpMouse(vid.width/2, vid.height/2); + case SDL_KEYDOWN: + case SDL_KEYUP: + sym = event.key.keysym.sym; + state = event.key.state; + modstate = SDL_GetModState (); + switch (sym) { + case SDLK_DELETE: + sym = K_DEL; + break; + case SDLK_BACKSPACE: + sym = K_BACKSPACE; + break; + case SDLK_F1: + sym = K_F1; + break; + case SDLK_F2: + sym = K_F2; + break; + case SDLK_F3: + sym = K_F3; + break; + case SDLK_F4: + sym = K_F4; + break; + case SDLK_F5: + sym = K_F5; + break; + case SDLK_F6: + sym = K_F6; + break; + case SDLK_F7: + sym = K_F7; + break; + case SDLK_F8: + sym = K_F8; + break; + case SDLK_F9: + sym = K_F9; + break; + case SDLK_F10: + sym = K_F10; + break; + case SDLK_F11: + sym = K_F11; + break; + case SDLK_F12: + sym = K_F12; + break; + case SDLK_BREAK: + case SDLK_PAUSE: + sym = K_PAUSE; + break; + case SDLK_UP: + sym = K_UPARROW; + break; + case SDLK_DOWN: + sym = K_DOWNARROW; + break; + case SDLK_RIGHT: + sym = K_RIGHTARROW; + break; + case SDLK_LEFT: + sym = K_LEFTARROW; + break; + case SDLK_INSERT: + sym = K_INS; + break; + case SDLK_HOME: + sym = K_HOME; + break; + case SDLK_END: + sym = K_END; + break; + case SDLK_PAGEUP: + sym = K_PGUP; + break; + case SDLK_PAGEDOWN: + sym = K_PGDN; + break; + case SDLK_RSHIFT: + case SDLK_LSHIFT: + sym = K_SHIFT; + break; + case SDLK_RCTRL: + case SDLK_LCTRL: + sym = K_CTRL; + break; + case SDLK_RALT: + case SDLK_LALT: + sym = K_ALT; + break; + case SDLK_CAPSLOCK: + sym = K_CAPSLOCK; + break; + case SDLK_KP0: + if (modstate & KMOD_NUM) + sym = K_INS; + else + sym = SDLK_0; + break; + case SDLK_KP1: + if (modstate & KMOD_NUM) + sym = K_END; + else + sym = SDLK_1; + break; + case SDLK_KP2: + if (modstate & KMOD_NUM) + sym = K_DOWNARROW; + else + sym = SDLK_2; + break; + case SDLK_KP3: + if (modstate & KMOD_NUM) + sym = K_PGDN; + else + sym = SDLK_3; + break; + case SDLK_KP4: + if (modstate & KMOD_NUM) + sym = K_LEFTARROW; + else + sym = SDLK_4; + break; + case SDLK_KP5: + sym = SDLK_5; + break; + case SDLK_KP6: + if (modstate & KMOD_NUM) + sym = K_RIGHTARROW; + else + sym = SDLK_6; + break; + case SDLK_KP7: + if (modstate & KMOD_NUM) + sym = K_HOME; + else + sym = SDLK_7; + break; + case SDLK_KP8: + if (modstate & KMOD_NUM) + sym = K_UPARROW; + else + sym = SDLK_8; + break; + case SDLK_KP9: + if (modstate & KMOD_NUM) + sym = K_PGUP; + else + sym = SDLK_9; + break; + case SDLK_KP_PERIOD: + if (modstate & KMOD_NUM) + sym = K_DEL; + else + sym = SDLK_PERIOD; + break; + case SDLK_KP_DIVIDE: + sym = SDLK_SLASH; + break; + case SDLK_KP_MULTIPLY: + sym = SDLK_ASTERISK; + break; + case SDLK_KP_MINUS: + sym = SDLK_MINUS; + break; + case SDLK_KP_PLUS: + sym = SDLK_PLUS; + break; + case SDLK_KP_ENTER: + sym = SDLK_RETURN; + break; + case SDLK_KP_EQUALS: + sym = SDLK_EQUALS; + break; } - } else { - // following are *2 in vid_sdl.c, vid_sgl.c is *10 - mouse_x = event.motion.xrel*10; - mouse_y = event.motion.yrel*10; - } - break; + // If we're not directly handled and still above 255 + // just force it to 0 + if (sym > 255) + sym = 0; + Key_Event (sym, -1, state); + break; - case SDL_QUIT: - CL_Disconnect (); - Sys_Quit (); - break; - default: - break; + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + but = event.button.button; + if (but == 2) + but = 3; + else if (but == 3) + but = 2; + + switch (but) { + case 1: + case 2: + case 3: + Key_Event (K_MOUSE1 + but - 1, 0, event.type + == SDL_MOUSEBUTTONDOWN); + break; + case 4: + Key_Event (K_MWHEELUP, 0, + event.type == SDL_MOUSEBUTTONDOWN); + break; + case 5: + Key_Event (K_MWHEELDOWN, 0, + event.type == SDL_MOUSEBUTTONDOWN); + break; + } + break; + + case SDL_MOUSEMOTION: + if (_windowed_mouse->value) { + if ((event.motion.x != (vid.width / 2)) + || (event.motion.y != (vid.height / 2))) { + // *2 for vid_sdl.c, *10 for vid_sgl.c. + mouse_x = event.motion.xrel * 2; + mouse_y = event.motion.yrel * 2; + if ( + (event.motion.x < + ((vid.width / 2) - (vid.width / 4))) + || (event.motion.x > + ((vid.width / 2) + (vid.width / 4))) + || (event.motion.y < + ((vid.height / 2) - (vid.height / 4))) + || (event.motion.y > + ((vid.height / 2) + (vid.height / 4)))) + SDL_WarpMouse (vid.width / 2, vid.height / 2); + } + } else { + // following are *2 in vid_sdl.c, vid_sgl.c is *10 + mouse_x = event.motion.xrel * 10; + mouse_y = event.motion.yrel * 10; + } + break; + + case SDL_QUIT: + CL_Disconnect (); + Sys_Quit (); + break; + default: + break; } } } @@ -235,11 +335,11 @@ IN_Commands (void) if (old_windowed_mouse != _windowed_mouse->value) { old_windowed_mouse = _windowed_mouse->value; if (!_windowed_mouse->value) { -// SDL_ShowCursor (0); +// SDL_ShowCursor (0); SDL_WM_GrabInput (SDL_GRAB_OFF); } else { SDL_WM_GrabInput (SDL_GRAB_ON); -// SDL_ShowCursor (1); +// SDL_ShowCursor (1); } } } @@ -249,14 +349,14 @@ IN_Init (void) { JOY_Init (); - if ( COM_CheckParm("-nomouse") && !_windowed_mouse->value) + if (COM_CheckParm ("-nomouse") && !_windowed_mouse->value) return; mouse_x = mouse_y = 0.0; mouse_avail = 1; -// SDL_ShowCursor (0); -// SDL_WM_GrabInput (SDL_GRAB_ON); -// FIXME: disable DGA if in_dgamouse says to. +// SDL_ShowCursor (0); +// SDL_WM_GrabInput (SDL_GRAB_ON); +// FIXME: disable DGA if in_dgamouse says to. } void @@ -264,8 +364,8 @@ IN_Init_Cvars (void) { JOY_Init_Cvars (); - _windowed_mouse = Cvar_Get ("_windowed_mouse","0",CVAR_ARCHIVE,"None"); - // m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE, "None"); + _windowed_mouse = Cvar_Get ("_windowed_mouse", "0", CVAR_ARCHIVE, "None"); + // m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE, "None"); } void @@ -274,22 +374,26 @@ IN_Shutdown (void) mouse_avail = 0; } -void IN_Frame(void) +void +IN_Frame (void) { - int i; - int mouse_buttonstate; + int i; + int mouse_buttonstate; - if (!mouse_avail) return; + if (!mouse_avail) + return; - i = SDL_GetMouseState(NULL, NULL); + i = SDL_GetMouseState (NULL, NULL); /* Quake swaps the second and third buttons */ - mouse_buttonstate = (i & ~0x06) | ((i & 0x02)<<1) | ((i & 0x04)>>1); - for (i=0 ; i<3 ; i++) { - if ( (mouse_buttonstate & (1<> 1); + for (i = 0; i < 3; i++) { + if ((mouse_buttonstate & (1 << i)) + && !(mouse_oldbuttonstate & (1 << i))) Key_Event (K_MOUSE1 + i, 0, + true); - if ( !(mouse_buttonstate & (1<value; mouse_y *= sensitivity->value; - if ( (in_strafe.state & 1) || (lookstrafe->value && (in_mlook.state & 1) )) + if ((in_strafe.state & 1) || (lookstrafe->value && (in_mlook.state & 1))) cmd->sidemove += m_side->value * mouse_x; else cl.viewangles[YAW] -= m_yaw->value * mouse_x; @@ -323,8 +427,9 @@ IN_Move (usercmd_t *cmd) if (freelook) V_StopPitchDrift (); - if ( freelook && !(in_strafe.state & 1)) { - cl.viewangles[PITCH] = bound (-70, cl.viewangles[PITCH] + (m_pitch->value * mouse_y), 80); + if (freelook && !(in_strafe.state & 1)) { + cl.viewangles[PITCH] = + bound (-70, cl.viewangles[PITCH] + (m_pitch->value * mouse_y), 80); } else { if ((in_strafe.state & 1) && noclip_anglehack) cmd->upmove -= m_forward->value * mouse_y; diff --git a/source/in_svgalib.c b/source/in_svgalib.c index 921026c..43d8acf 100644 --- a/source/in_svgalib.c +++ b/source/in_svgalib.c @@ -54,52 +54,57 @@ #include -static int UseKeyboard = 1; -static int UseMouse = 1; -static int in_svgalib_inited = 0; +static int UseKeyboard = 1; +static int UseMouse = 1; +static int in_svgalib_inited = 0; static unsigned char scantokey[128]; -static int mouse_buttons; -static int mouse_buttonstate; -static int mouse_oldbuttonstate; -static float mouse_x, mouse_y; -static float old_mouse_x, old_mouse_y; -static int mx, my; +static int mouse_buttons; +static int mouse_buttonstate; +static int mouse_oldbuttonstate; +static float mouse_x, mouse_y; +static float old_mouse_x, old_mouse_y; +static int mx, my; -static void IN_init_kb(); -static void IN_init_mouse(); +static void IN_init_kb (); +static void IN_init_mouse (); -cvar_t *_windowed_mouse; -cvar_t *m_filter; +cvar_t *_windowed_mouse; +cvar_t *m_filter; -static void keyhandler(int scancode, int state) +static void +keyhandler (int scancode, int state) { - int sc; + int sc; sc = scancode & 0x7f; #if 0 - Con_Printf("scancode=%x (%d%s)\n", scancode, sc, scancode&0x80?"+128":""); + Con_Printf ("scancode=%x (%d%s)\n", scancode, sc, + scancode & 0x80 ? "+128" : ""); #endif - Key_Event(scantokey[sc], -1, state == KEY_EVENTPRESS); + Key_Event (scantokey[sc], -1, state == KEY_EVENTPRESS); } -static void mousehandler(int buttonstate, int dx, int dy, int dz, int drx, int dry, int drz) +static void +mousehandler (int buttonstate, int dx, int dy, int dz, int drx, int dry, + int drz) { mouse_buttonstate = buttonstate; mx += dx; my += dy; if (drx > 0) { - Key_Event(K_MWHEELUP, 0, 1); - Key_Event(K_MWHEELUP, 0, 0); + Key_Event (K_MWHEELUP, 0, 1); + Key_Event (K_MWHEELUP, 0, 0); } else if (drx < 0) { - Key_Event(K_MWHEELDOWN, 0, 1); - Key_Event(K_MWHEELDOWN, 0, 0); + Key_Event (K_MWHEELDOWN, 0, 1); + Key_Event (K_MWHEELDOWN, 0, 0); } } -void Force_CenterView_f(void) +void +Force_CenterView_f (void) { cl.viewangles[PITCH] = 0; } @@ -108,15 +113,17 @@ void Force_CenterView_f(void) void IN_Init (void) { - if (COM_CheckParm("-nokbd")) UseKeyboard = 0; - if (COM_CheckParm("-nomouse")) UseMouse = 0; + if (COM_CheckParm ("-nokbd")) + UseKeyboard = 0; + if (COM_CheckParm ("-nomouse")) + UseMouse = 0; if (UseKeyboard) - IN_init_kb(); + IN_init_kb (); if (UseMouse) - IN_init_mouse(); + IN_init_mouse (); - JOY_Init(); + JOY_Init (); in_svgalib_inited = 1; return; @@ -125,113 +132,113 @@ IN_Init (void) void IN_Init_Cvars (void) { - JOY_Init_Cvars(); - m_filter = Cvar_Get ("m_filter","0",0,"None"); + JOY_Init_Cvars (); + m_filter = Cvar_Get ("m_filter", "0", 0, "None"); } static void IN_init_kb (void) { - int i; + int i; - for (i=0 ; i<128 ; i++) { + for (i = 0; i < 128; i++) { scantokey[i] = ' '; } - scantokey[ 1] = K_ESCAPE; - scantokey[ 2] = '1'; - scantokey[ 3] = '2'; - scantokey[ 4] = '3'; - scantokey[ 5] = '4'; - scantokey[ 6] = '5'; - scantokey[ 7] = '6'; - scantokey[ 8] = '7'; - scantokey[ 9] = '8'; - scantokey[ 10] = '9'; - scantokey[ 11] = '0'; - scantokey[ 12] = '-'; - scantokey[ 13] = '='; - scantokey[ 14] = K_BACKSPACE; - scantokey[ 15] = K_TAB; - scantokey[ 16] = 'q'; - scantokey[ 17] = 'w'; - scantokey[ 18] = 'e'; - scantokey[ 19] = 'r'; - scantokey[ 20] = 't'; - scantokey[ 21] = 'y'; - scantokey[ 22] = 'u'; - scantokey[ 23] = 'i'; - scantokey[ 24] = 'o'; - scantokey[ 25] = 'p'; - scantokey[ 26] = '['; - scantokey[ 27] = ']'; - scantokey[ 28] = K_ENTER; - scantokey[ 29] = K_CTRL; /*left */ - scantokey[ 30] = 'a'; - scantokey[ 31] = 's'; - scantokey[ 32] = 'd'; - scantokey[ 33] = 'f'; - scantokey[ 34] = 'g'; - scantokey[ 35] = 'h'; - scantokey[ 36] = 'j'; - scantokey[ 37] = 'k'; - scantokey[ 38] = 'l'; - scantokey[ 39] = ';'; - scantokey[ 40] = '\''; - scantokey[ 41] = '`'; - scantokey[ 42] = K_SHIFT; /*left */ - scantokey[ 43] = '\\'; - scantokey[ 44] = 'z'; - scantokey[ 45] = 'x'; - scantokey[ 46] = 'c'; - scantokey[ 47] = 'v'; - scantokey[ 48] = 'b'; - scantokey[ 49] = 'n'; - scantokey[ 50] = 'm'; - scantokey[ 51] = ','; - scantokey[ 52] = '.'; - scantokey[ 53] = '/'; - scantokey[ 54] = K_SHIFT; /*right */ - scantokey[ 55] = KP_MULTIPLY; - scantokey[ 56] = K_ALT; /*left */ - scantokey[ 57] = ' '; - scantokey[ 58] = K_CAPSLOCK; - scantokey[ 59] = K_F1; - scantokey[ 60] = K_F2; - scantokey[ 61] = K_F3; - scantokey[ 62] = K_F4; - scantokey[ 63] = K_F5; - scantokey[ 64] = K_F6; - scantokey[ 65] = K_F7; - scantokey[ 66] = K_F8; - scantokey[ 67] = K_F9; - scantokey[ 68] = K_F10; - scantokey[ 69] = KP_NUMLCK; - scantokey[ 70] = K_SCRLCK; - scantokey[ 71] = KP_HOME; - scantokey[ 72] = KP_UPARROW; - scantokey[ 73] = KP_PGUP; - scantokey[ 74] = KP_MINUS; - scantokey[ 75] = KP_LEFTARROW; - scantokey[ 76] = KP_5; - scantokey[ 77] = KP_RIGHTARROW; - scantokey[ 79] = KP_END; - scantokey[ 78] = KP_PLUS; - scantokey[ 80] = KP_DOWNARROW; - scantokey[ 81] = KP_PGDN; - scantokey[ 82] = KP_INS; - scantokey[ 83] = KP_DEL; + scantokey[1] = K_ESCAPE; + scantokey[2] = '1'; + scantokey[3] = '2'; + scantokey[4] = '3'; + scantokey[5] = '4'; + scantokey[6] = '5'; + scantokey[7] = '6'; + scantokey[8] = '7'; + scantokey[9] = '8'; + scantokey[10] = '9'; + scantokey[11] = '0'; + scantokey[12] = '-'; + scantokey[13] = '='; + scantokey[14] = K_BACKSPACE; + scantokey[15] = K_TAB; + scantokey[16] = 'q'; + scantokey[17] = 'w'; + scantokey[18] = 'e'; + scantokey[19] = 'r'; + scantokey[20] = 't'; + scantokey[21] = 'y'; + scantokey[22] = 'u'; + scantokey[23] = 'i'; + scantokey[24] = 'o'; + scantokey[25] = 'p'; + scantokey[26] = '['; + scantokey[27] = ']'; + scantokey[28] = K_ENTER; + scantokey[29] = K_CTRL; /* left */ + scantokey[30] = 'a'; + scantokey[31] = 's'; + scantokey[32] = 'd'; + scantokey[33] = 'f'; + scantokey[34] = 'g'; + scantokey[35] = 'h'; + scantokey[36] = 'j'; + scantokey[37] = 'k'; + scantokey[38] = 'l'; + scantokey[39] = ';'; + scantokey[40] = '\''; + scantokey[41] = '`'; + scantokey[42] = K_SHIFT; /* left */ + scantokey[43] = '\\'; + scantokey[44] = 'z'; + scantokey[45] = 'x'; + scantokey[46] = 'c'; + scantokey[47] = 'v'; + scantokey[48] = 'b'; + scantokey[49] = 'n'; + scantokey[50] = 'm'; + scantokey[51] = ','; + scantokey[52] = '.'; + scantokey[53] = '/'; + scantokey[54] = K_SHIFT; /* right */ + scantokey[55] = KP_MULTIPLY; + scantokey[56] = K_ALT; /* left */ + scantokey[57] = ' '; + scantokey[58] = K_CAPSLOCK; + scantokey[59] = K_F1; + scantokey[60] = K_F2; + scantokey[61] = K_F3; + scantokey[62] = K_F4; + scantokey[63] = K_F5; + scantokey[64] = K_F6; + scantokey[65] = K_F7; + scantokey[66] = K_F8; + scantokey[67] = K_F9; + scantokey[68] = K_F10; + scantokey[69] = KP_NUMLCK; + scantokey[70] = K_SCRLCK; + scantokey[71] = KP_HOME; + scantokey[72] = KP_UPARROW; + scantokey[73] = KP_PGUP; + scantokey[74] = KP_MINUS; + scantokey[75] = KP_LEFTARROW; + scantokey[76] = KP_5; + scantokey[77] = KP_RIGHTARROW; + scantokey[79] = KP_END; + scantokey[78] = KP_PLUS; + scantokey[80] = KP_DOWNARROW; + scantokey[81] = KP_PGDN; + scantokey[82] = KP_INS; + scantokey[83] = KP_DEL; /* 84 to 86 not used */ - scantokey[ 87] = K_F11; - scantokey[ 88] = K_F12; + scantokey[87] = K_F11; + scantokey[88] = K_F12; /* 89 to 95 not used */ - scantokey[ 96] = KP_ENTER; /* keypad enter */ - scantokey[ 97] = K_CTRL; /* right */ - scantokey[ 98] = KP_DIVIDE; - scantokey[ 99] = K_PRNTSCR; /* print screen */ - scantokey[100] = K_ALT; /* right */ + scantokey[96] = KP_ENTER; /* keypad enter */ + scantokey[97] = K_CTRL; /* right */ + scantokey[98] = KP_DIVIDE; + scantokey[99] = K_PRNTSCR; /* print screen */ + scantokey[100] = K_ALT; /* right */ - scantokey[101] = K_PAUSE; /* break */ + scantokey[101] = K_PAUSE; /* break */ scantokey[102] = K_HOME; scantokey[103] = K_UPARROW; scantokey[104] = K_PGUP; @@ -247,94 +254,100 @@ IN_init_kb (void) if (keyboard_init ()) { Sys_Error ("keyboard_init() failed"); } - keyboard_seteventhandler(keyhandler); + keyboard_seteventhandler (keyhandler); } static void -IN_init_mouse() +IN_init_mouse () { - int mtype; - char *mousedev; - int mouserate = MOUSE_DEFAULTSAMPLERATE; + int mtype; + char *mousedev; + int mouserate = MOUSE_DEFAULTSAMPLERATE; - Cmd_AddCommand("force_centerview", Force_CenterView_f); + Cmd_AddCommand ("force_centerview", Force_CenterView_f); mouse_buttons = 3; - mtype = vga_getmousetype(); + mtype = vga_getmousetype (); mousedev = "/dev/mouse"; - if (getenv("MOUSEDEV")) mousedev = getenv("MOUSEDEV"); - if (COM_CheckParm("-mdev")) { - mousedev = com_argv[COM_CheckParm("-mdev")+1]; + if (getenv ("MOUSEDEV")) + mousedev = getenv ("MOUSEDEV"); + if (COM_CheckParm ("-mdev")) { + mousedev = com_argv[COM_CheckParm ("-mdev") + 1]; } - if (getenv("MOUSERATE")) mouserate = atoi(getenv("MOUSERATE")); - if (COM_CheckParm("-mrate")) { - mouserate = atoi(com_argv[COM_CheckParm("-mrate")+1]); + if (getenv ("MOUSERATE")) + mouserate = atoi (getenv ("MOUSERATE")); + if (COM_CheckParm ("-mrate")) { + mouserate = atoi (com_argv[COM_CheckParm ("-mrate") + 1]); } - #if 0 - printf("Mouse: dev=%s,type=%s,speed=%d\n", - mousedev, mice[mtype].name, mouserate); + printf ("Mouse: dev=%s,type=%s,speed=%d\n", + mousedev, mice[mtype].name, mouserate); #endif - if (mouse_init(mousedev, mtype, mouserate)) { - Con_Printf("No mouse found\n"); + if (mouse_init (mousedev, mtype, mouserate)) { + Con_Printf ("No mouse found\n"); UseMouse = 0; - } else{ - mouse_seteventhandler((void*)mousehandler); + } else { + mouse_seteventhandler ((void *) mousehandler); } } -void IN_Shutdown(void) +void +IN_Shutdown (void) { JOY_Shutdown (); - Con_Printf("IN_Shutdown\n"); + Con_Printf ("IN_Shutdown\n"); - if (UseMouse) mouse_close(); - if (UseKeyboard) keyboard_close(); + if (UseMouse) + mouse_close (); + if (UseKeyboard) + keyboard_close (); in_svgalib_inited = 0; } -void IN_SendKeyEvents(void) +void +IN_SendKeyEvents (void) { - if (!in_svgalib_inited) return; + if (!in_svgalib_inited) + return; if (UseKeyboard) { - while ((keyboard_update())); + while ((keyboard_update ())); } } -void IN_Commands(void) +void +IN_Commands (void) { JOY_Command (); if (UseMouse) { /* Poll mouse values */ - while (mouse_update()) - ; + while (mouse_update ()); /* Perform button actions */ if ((mouse_buttonstate & MOUSE_LEFTBUTTON) && !(mouse_oldbuttonstate & MOUSE_LEFTBUTTON)) - Key_Event (K_MOUSE1, 0, true); + Key_Event (K_MOUSE1, 0, true); else if (!(mouse_buttonstate & MOUSE_LEFTBUTTON) && - (mouse_oldbuttonstate & MOUSE_LEFTBUTTON)) + (mouse_oldbuttonstate & MOUSE_LEFTBUTTON)) Key_Event (K_MOUSE1, 0, false); if ((mouse_buttonstate & MOUSE_RIGHTBUTTON) && !(mouse_oldbuttonstate & MOUSE_RIGHTBUTTON)) - Key_Event (K_MOUSE2, 0, true); + Key_Event (K_MOUSE2, 0, true); else if (!(mouse_buttonstate & MOUSE_RIGHTBUTTON) && - (mouse_oldbuttonstate & MOUSE_RIGHTBUTTON)) + (mouse_oldbuttonstate & MOUSE_RIGHTBUTTON)) Key_Event (K_MOUSE2, 0, false); if ((mouse_buttonstate & MOUSE_MIDDLEBUTTON) && !(mouse_oldbuttonstate & MOUSE_MIDDLEBUTTON)) - Key_Event (K_MOUSE3, 0, true); + Key_Event (K_MOUSE3, 0, true); else if (!(mouse_buttonstate & MOUSE_MIDDLEBUTTON) && - (mouse_oldbuttonstate & MOUSE_MIDDLEBUTTON)) + (mouse_oldbuttonstate & MOUSE_MIDDLEBUTTON)) Key_Event (K_MOUSE3, 0, false); mouse_oldbuttonstate = mouse_buttonstate; @@ -342,14 +355,15 @@ void IN_Commands(void) } -void IN_Move(usercmd_t *cmd) +void +IN_Move (usercmd_t *cmd) { JOY_Move (cmd); - if (!UseMouse) return; + if (!UseMouse) + return; /* Poll mouse values */ - while (mouse_update()) - ; + while (mouse_update ()); if (m_filter->int_val) { mouse_x = (mx + old_mouse_x) * 0.5; @@ -374,7 +388,7 @@ void IN_Move(usercmd_t *cmd) } if (freelook) - V_StopPitchDrift(); + V_StopPitchDrift (); if (freelook && !(in_strafe.state & 1)) { cl.viewangles[PITCH] += m_pitch->value * mouse_y; diff --git a/source/in_win.c b/source/in_win.c index 00cb0c0..bebec01 100644 --- a/source/in_win.c +++ b/source/in_win.c @@ -29,7 +29,7 @@ // 02/21/97 JCB Added extended DirectInput code to support external controllers. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef __MINGW32__ # define INITGUID @@ -50,36 +50,38 @@ #define DINPUT_BUFFERSIZE 16 #define iDirectInputCreate(a,b,c,d) pDirectInputCreate(a,b,c,d) -HRESULT (WINAPI *pDirectInputCreate)(HINSTANCE hinst, DWORD dwVersion, - LPDIRECTINPUT * lplpDirectInput, LPUNKNOWN punkOuter); +HRESULT (WINAPI * pDirectInputCreate) (HINSTANCE hinst, DWORD dwVersion, + LPDIRECTINPUT * lplpDirectInput, + LPUNKNOWN punkOuter); // mouse public variables -float mouse_x, mouse_y; -qboolean mouseactive; -unsigned int uiWheelMessage; +float mouse_x, mouse_y; +qboolean mouseactive; +unsigned int uiWheelMessage; // mouse local variables -static int mouse_buttons; -static int mouse_oldbuttonstate; -static POINT current_pos; -static float old_mouse_x, old_mouse_y, mx_accum, my_accum; -static qboolean mouseinitialized; -static cvar_t *m_filter; -static qboolean restore_spi; -static int originalmouseparms[3], newmouseparms[3] = {0, 0, 1}; -static qboolean mouseparmsvalid, mouseactivatetoggle; -static qboolean mouseshowtoggle = 1; -static qboolean dinput_acquired; -static unsigned int mstate_di; +static int mouse_buttons; +static int mouse_oldbuttonstate; +static POINT current_pos; +static float old_mouse_x, old_mouse_y, mx_accum, my_accum; +static qboolean mouseinitialized; +static cvar_t *m_filter; +static qboolean restore_spi; +static int originalmouseparms[3], newmouseparms[3] = { 0, 0, 1 }; +static qboolean mouseparmsvalid, mouseactivatetoggle; +static qboolean mouseshowtoggle = 1; +static qboolean dinput_acquired; +static unsigned int mstate_di; // joystick defines and variables // where should defines be moved? -#define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick -#define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, trackball -#define JOY_MAX_AXES 6 // X, Y, Z, R, U, V +#define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick +#define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, + // trackball +#define JOY_MAX_AXES 6 // X, Y, Z, R, U, V #define JOY_AXIS_X 0 #define JOY_AXIS_Y 1 #define JOY_AXIS_Z 2 @@ -87,91 +89,94 @@ static unsigned int mstate_di; #define JOY_AXIS_U 4 #define JOY_AXIS_V 5 -enum _ControlList -{ +enum _ControlList { AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn }; -static DWORD dwAxisFlags[JOY_MAX_AXES] = -{ +static DWORD dwAxisFlags[JOY_MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV }; -static DWORD dwAxisMap[JOY_MAX_AXES]; -static DWORD dwControlMap[JOY_MAX_AXES]; -static PDWORD pdwRawValue[JOY_MAX_AXES]; +static DWORD dwAxisMap[JOY_MAX_AXES]; +static DWORD dwControlMap[JOY_MAX_AXES]; +static PDWORD pdwRawValue[JOY_MAX_AXES]; // none of these cvars are saved over a session // this means that advanced controller configuration needs to be executed // each time. this avoids any problems with getting back to a default usage // or when changing from one controller to another. this way at least something // works. -static cvar_t *in_joystick; -static cvar_t *joy_name; -static cvar_t *joy_advanced; -static cvar_t *joy_advaxisx; -static cvar_t *joy_advaxisy; -static cvar_t *joy_advaxisz; -static cvar_t *joy_advaxisr; -static cvar_t *joy_advaxisu; -static cvar_t *joy_advaxisv; -static cvar_t *joy_forwardthreshold; -static cvar_t *joy_sidethreshold; -static cvar_t *joy_pitchthreshold; -static cvar_t *joy_yawthreshold; -static cvar_t *joy_forwardsensitivity; -static cvar_t *joy_sidesensitivity; -static cvar_t *joy_pitchsensitivity; -static cvar_t *joy_yawsensitivity; -static cvar_t *joy_wwhack1; -static cvar_t *joy_wwhack2; +static cvar_t *in_joystick; +static cvar_t *joy_name; +static cvar_t *joy_advanced; +static cvar_t *joy_advaxisx; +static cvar_t *joy_advaxisy; +static cvar_t *joy_advaxisz; +static cvar_t *joy_advaxisr; +static cvar_t *joy_advaxisu; +static cvar_t *joy_advaxisv; +static cvar_t *joy_forwardthreshold; +static cvar_t *joy_sidethreshold; +static cvar_t *joy_pitchthreshold; +static cvar_t *joy_yawthreshold; +static cvar_t *joy_forwardsensitivity; +static cvar_t *joy_sidesensitivity; +static cvar_t *joy_pitchsensitivity; +static cvar_t *joy_yawsensitivity; +static cvar_t *joy_wwhack1; +static cvar_t *joy_wwhack2; -static qboolean joy_avail, joy_advancedinit, joy_haspov; -static DWORD joy_oldbuttonstate, joy_oldpovstate; -static int joy_id; -static DWORD joy_flags; -static DWORD joy_numbuttons; +static qboolean joy_avail, joy_advancedinit, joy_haspov; +static DWORD joy_oldbuttonstate, joy_oldpovstate; +static int joy_id; +static DWORD joy_flags; +static DWORD joy_numbuttons; // misc locals -static LPDIRECTINPUT g_pdi; -static LPDIRECTINPUTDEVICE g_pMouse; +static LPDIRECTINPUT g_pdi; +static LPDIRECTINPUTDEVICE g_pMouse; -static JOYINFOEX ji; +static JOYINFOEX ji; static HINSTANCE hInstDI; -static qboolean dinput; +static qboolean dinput; typedef struct MYDATA { - LONG lX; // X axis goes here - LONG lY; // Y axis goes here - LONG lZ; // Z axis goes here - BYTE bButtonA; // One button goes here - BYTE bButtonB; // Another button goes here - BYTE bButtonC; // Another button goes here - BYTE bButtonD; // Another button goes here + LONG lX; // X axis goes here + LONG lY; // Y axis goes here + LONG lZ; // Z axis goes here + BYTE bButtonA; // One button goes here + BYTE bButtonB; // Another button goes here + BYTE bButtonC; // Another button goes here + BYTE bButtonD; // Another button goes here } MYDATA; static DIOBJECTDATAFORMAT rgodf[] = { - { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX), DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,}, - { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY), DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,}, - { &GUID_ZAxis, FIELD_OFFSET(MYDATA, lZ), 0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,}, - { 0, FIELD_OFFSET(MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, - { 0, FIELD_OFFSET(MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, - { 0, FIELD_OFFSET(MYDATA, bButtonC), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, - { 0, FIELD_OFFSET(MYDATA, bButtonD), 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, + {&GUID_XAxis, FIELD_OFFSET (MYDATA, lX), DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,}, + {&GUID_YAxis, FIELD_OFFSET (MYDATA, lY), DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,}, + + {&GUID_ZAxis, FIELD_OFFSET (MYDATA, lZ), + 0x80000000 | DIDFT_AXIS | DIDFT_ANYINSTANCE, 0,}, + {0, FIELD_OFFSET (MYDATA, bButtonA), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, + {0, FIELD_OFFSET (MYDATA, bButtonB), DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, + + {0, FIELD_OFFSET (MYDATA, bButtonC), + 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, + {0, FIELD_OFFSET (MYDATA, bButtonD), + 0x80000000 | DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0,}, }; #define NUM_OBJECTS (sizeof(rgodf) / sizeof(rgodf[0])) -static DIDATAFORMAT df = { - sizeof(DIDATAFORMAT), // this structure - sizeof(DIOBJECTDATAFORMAT), // size of object data format - DIDF_RELAXIS, // absolute axis coordinates - sizeof(MYDATA), // device data size - NUM_OBJECTS, // number of objects - rgodf, // and here they are +static DIDATAFORMAT df = { + sizeof (DIDATAFORMAT), // this structure + sizeof (DIOBJECTDATAFORMAT), // size of object data format + DIDF_RELAXIS, // absolute axis coordinates + sizeof (MYDATA), // device data size + NUM_OBJECTS, // number of objects + rgodf, // and here they are }; // forward-referenced functions, locals @@ -184,7 +189,8 @@ static void IN_JoyMove (usercmd_t *cmd); Force_CenterView_f =========== */ -static void Force_CenterView_f (void) +static void +Force_CenterView_f (void) { cl.viewangles[PITCH] = 0; } @@ -195,11 +201,11 @@ static void Force_CenterView_f (void) IN_UpdateClipCursor =========== */ -void IN_UpdateClipCursor (void) +void +IN_UpdateClipCursor (void) { - if (mouseinitialized && mouseactive && !dinput) - { + if (mouseinitialized && mouseactive && !dinput) { ClipCursor (&window_rect); } } @@ -210,11 +216,11 @@ void IN_UpdateClipCursor (void) IN_ShowMouse =========== */ -void IN_ShowMouse (void) +void +IN_ShowMouse (void) { - if (!mouseshowtoggle) - { + if (!mouseshowtoggle) { ShowCursor (TRUE); mouseshowtoggle = 1; } @@ -226,11 +232,11 @@ void IN_ShowMouse (void) IN_HideMouse =========== */ -void IN_HideMouse (void) +void +IN_HideMouse (void) { - if (mouseshowtoggle) - { + if (mouseshowtoggle) { ShowCursor (FALSE); mouseshowtoggle = 0; } @@ -242,32 +248,26 @@ void IN_HideMouse (void) IN_ActivateMouse =========== */ -void IN_ActivateMouse (void) +void +IN_ActivateMouse (void) { mouseactivatetoggle = true; - if (mouseinitialized) - { - if (dinput) - { - if (g_pMouse) - { - if (!dinput_acquired) - { - IDirectInputDevice_Acquire(g_pMouse); + if (mouseinitialized) { + if (dinput) { + if (g_pMouse) { + if (!dinput_acquired) { + IDirectInputDevice_Acquire (g_pMouse); dinput_acquired = true; } - } - else - { + } else { return; } - } - else - { + } else { if (mouseparmsvalid) - restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0); + restore_spi = + SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0); SetCursorPos (window_center_x, window_center_y); SetCapture (mainwindow); @@ -284,7 +284,8 @@ void IN_ActivateMouse (void) IN_SetQuakeMouseState =========== */ -void IN_SetQuakeMouseState (void) +void +IN_SetQuakeMouseState (void) { if (mouseactivatetoggle) IN_ActivateMouse (); @@ -296,32 +297,27 @@ void IN_SetQuakeMouseState (void) IN_DeactivateMouse =========== */ -void IN_DeactivateMouse (void) +void +IN_DeactivateMouse (void) { mouseactivatetoggle = false; - if (mouseinitialized) - { - if (dinput) - { - if (g_pMouse) - { - if (dinput_acquired) - { - IDirectInputDevice_Unacquire(g_pMouse); + if (mouseinitialized) { + if (dinput) { + if (g_pMouse) { + if (dinput_acquired) { + IDirectInputDevice_Unacquire (g_pMouse); dinput_acquired = false; } } - } - else - { - if (restore_spi) - SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0); + } else { + if (restore_spi) + SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0); - ClipCursor (NULL); - ReleaseCapture (); - } + ClipCursor (NULL); + ReleaseCapture (); + } mouseactive = false; } @@ -333,14 +329,13 @@ void IN_DeactivateMouse (void) IN_RestoreOriginalMouseState =========== */ -void IN_RestoreOriginalMouseState (void) +void +IN_RestoreOriginalMouseState (void) { - if (mouseactivatetoggle) - { + if (mouseactivatetoggle) { IN_DeactivateMouse (); mouseactivatetoggle = true; } - // try to redraw the cursor so it gets reinitialized, because sometimes it // has garbage after the mode switch ShowCursor (TRUE); @@ -353,84 +348,78 @@ void IN_RestoreOriginalMouseState (void) IN_InitDInput =========== */ -static qboolean IN_InitDInput (void) +static qboolean +IN_InitDInput (void) { - HRESULT hr; - DIPROPDWORD dipdw = { + HRESULT hr; + DIPROPDWORD dipdw = { { - sizeof(DIPROPDWORD), // diph.dwSize - sizeof(DIPROPHEADER), // diph.dwHeaderSize - 0, // diph.dwObj - DIPH_DEVICE, // diph.dwHow - }, - DINPUT_BUFFERSIZE, // dwData + sizeof (DIPROPDWORD), // diph.dwSize + sizeof (DIPROPHEADER), // diph.dwHeaderSize + 0, // diph.dwObj + DIPH_DEVICE, // diph.dwHow + } + , + DINPUT_BUFFERSIZE, // dwData }; - if (!hInstDI) - { - hInstDI = LoadLibrary("dinput.dll"); - - if (hInstDI == NULL) - { + if (!hInstDI) { + hInstDI = LoadLibrary ("dinput.dll"); + + if (hInstDI == NULL) { Con_Printf ("Couldn't load dinput.dll\n"); return false; } } - if (!pDirectInputCreate) - { - pDirectInputCreate = (void *)GetProcAddress(hInstDI,"DirectInputCreateA"); + if (!pDirectInputCreate) { + pDirectInputCreate = + (void *) GetProcAddress (hInstDI, "DirectInputCreateA"); - if (!pDirectInputCreate) - { + if (!pDirectInputCreate) { Con_Printf ("Couldn't get DI proc addr\n"); return false; } } - // register with DirectInput and get an IDirectInput to play with. - hr = iDirectInputCreate(global_hInstance, DIRECTINPUT_VERSION, &g_pdi, NULL); + hr = + iDirectInputCreate (global_hInstance, DIRECTINPUT_VERSION, &g_pdi, + NULL); - if (FAILED(hr)) - { + if (FAILED (hr)) { return false; } - // obtain an interface to the system mouse device. - hr = IDirectInput_CreateDevice(g_pdi, &GUID_SysMouse, &g_pMouse, NULL); + hr = IDirectInput_CreateDevice (g_pdi, &GUID_SysMouse, &g_pMouse, NULL); - if (FAILED(hr)) - { + if (FAILED (hr)) { Con_Printf ("Couldn't open DI mouse device\n"); return false; } - // set the data format to "mouse format". - hr = IDirectInputDevice_SetDataFormat(g_pMouse, &df); + hr = IDirectInputDevice_SetDataFormat (g_pMouse, &df); - if (FAILED(hr)) - { + if (FAILED (hr)) { Con_Printf ("Couldn't set DI mouse format\n"); return false; } - // set the cooperativity level. - hr = IDirectInputDevice_SetCooperativeLevel(g_pMouse, mainwindow, - DISCL_EXCLUSIVE | DISCL_FOREGROUND); + hr = IDirectInputDevice_SetCooperativeLevel (g_pMouse, mainwindow, + DISCL_EXCLUSIVE | + DISCL_FOREGROUND); - if (FAILED(hr)) - { + if (FAILED (hr)) { Con_Printf ("Couldn't set DI coop level\n"); return false; } - // set the buffer size to DINPUT_BUFFERSIZE elements. // the buffer size is a DWORD property associated with the device - hr = IDirectInputDevice_SetProperty(g_pMouse, DIPROP_BUFFERSIZE, &dipdw.diph); + hr = + IDirectInputDevice_SetProperty (g_pMouse, DIPROP_BUFFERSIZE, + &dipdw.diph); - if (FAILED(hr)) - { + if (FAILED (hr)) { Con_Printf ("Couldn't set DI buffersize\n"); return false; } @@ -444,46 +433,40 @@ static qboolean IN_InitDInput (void) IN_StartupMouse =========== */ -static void IN_StartupMouse (void) +static void +IN_StartupMouse (void) { -// HDC hdc; +// HDC hdc; - if ( COM_CheckParm ("-nomouse") ) - return; + if (COM_CheckParm ("-nomouse")) + return; mouseinitialized = true; - if (COM_CheckParm ("-dinput")) - { + if (COM_CheckParm ("-dinput")) { dinput = IN_InitDInput (); - if (dinput) - { + if (dinput) { Con_Printf ("DirectInput initialized\n"); - } - else - { + } else { Con_Printf ("DirectInput not initialized\n"); } } - if (!dinput) - { - mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0); + if (!dinput) { + mouseparmsvalid = + SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0); - if (mouseparmsvalid) - { - if ( COM_CheckParm ("-noforcemspd") ) + if (mouseparmsvalid) { + if (COM_CheckParm ("-noforcemspd")) newmouseparms[2] = originalmouseparms[2]; - if ( COM_CheckParm ("-noforcemaccel") ) - { + if (COM_CheckParm ("-noforcemaccel")) { newmouseparms[0] = originalmouseparms[0]; newmouseparms[1] = originalmouseparms[1]; } - if ( COM_CheckParm ("-noforcemparms") ) - { + if (COM_CheckParm ("-noforcemparms")) { newmouseparms[0] = originalmouseparms[0]; newmouseparms[1] = originalmouseparms[1]; newmouseparms[2] = originalmouseparms[2]; @@ -505,42 +488,51 @@ static void IN_StartupMouse (void) IN_Init =========== */ -void IN_Init (void) +void +IN_Init (void) { Cmd_AddCommand ("force_centerview", Force_CenterView_f); Cmd_AddCommand ("joyadvancedupdate", Joy_AdvancedUpdate_f); - uiWheelMessage = RegisterWindowMessage ( "MSWHEEL_ROLLMSG" ); + uiWheelMessage = RegisterWindowMessage ("MSWHEEL_ROLLMSG"); IN_StartupMouse (); IN_StartupJoystick (); } -void IN_Init_Cvars (void) +void +IN_Init_Cvars (void) { // mouse variables - m_filter = Cvar_Get("m_filter", "0", CVAR_NONE, "None"); + m_filter = Cvar_Get ("m_filter", "0", CVAR_NONE, "None"); // joystick variables - in_joystick = Cvar_Get("joystick", "0", CVAR_ARCHIVE, "None"); - joy_name = Cvar_Get("joyname", "joystick", CVAR_NONE, "None"); - joy_advanced = Cvar_Get("joyadvanced", "0", CVAR_NONE, "None"); - joy_advaxisx = Cvar_Get("joyadvaxisx", "0", CVAR_NONE, "None"); - joy_advaxisy = Cvar_Get("joyadvaxisy", "0", CVAR_NONE, "None"); - joy_advaxisz = Cvar_Get("joyadvaxisz", "0", CVAR_NONE, "None"); - joy_advaxisr = Cvar_Get("joyadvaxisr", "0", CVAR_NONE, "None"); - joy_advaxisu = Cvar_Get("joyadvaxisu", "0", CVAR_NONE, "None"); - joy_advaxisv = Cvar_Get("joyadvaxisv", "0", CVAR_NONE, "None"); - joy_forwardthreshold = Cvar_Get("joyforwardthreshold", "0.15", CVAR_NONE, "None"); - joy_sidethreshold = Cvar_Get("joysidethreshold", "0.15", CVAR_NONE, "None"); - joy_pitchthreshold = Cvar_Get("joypitchthreshold", "0.15", CVAR_NONE, "None"); - joy_yawthreshold = Cvar_Get("joyyawthreshold", "0.15", CVAR_NONE, "None"); - joy_forwardsensitivity = Cvar_Get("joyforwardsensitivity", "-1.0", CVAR_NONE, "None"); - joy_sidesensitivity = Cvar_Get("joysidesensitivity", "-1.0", CVAR_NONE, "None"); - joy_pitchsensitivity = Cvar_Get("joypitchsensitivity", "1.0", CVAR_NONE, "None"); - joy_yawsensitivity = Cvar_Get("joyyawsensitivity", "-1.0", CVAR_NONE, "None"); - joy_wwhack1 = Cvar_Get("joywwhack1", "0.0", CVAR_NONE, "None"); - joy_wwhack2 = Cvar_Get("joywwhack2", "0.0", CVAR_NONE, "None"); + in_joystick = Cvar_Get ("joystick", "0", CVAR_ARCHIVE, "None"); + joy_name = Cvar_Get ("joyname", "joystick", CVAR_NONE, "None"); + joy_advanced = Cvar_Get ("joyadvanced", "0", CVAR_NONE, "None"); + joy_advaxisx = Cvar_Get ("joyadvaxisx", "0", CVAR_NONE, "None"); + joy_advaxisy = Cvar_Get ("joyadvaxisy", "0", CVAR_NONE, "None"); + joy_advaxisz = Cvar_Get ("joyadvaxisz", "0", CVAR_NONE, "None"); + joy_advaxisr = Cvar_Get ("joyadvaxisr", "0", CVAR_NONE, "None"); + joy_advaxisu = Cvar_Get ("joyadvaxisu", "0", CVAR_NONE, "None"); + joy_advaxisv = Cvar_Get ("joyadvaxisv", "0", CVAR_NONE, "None"); + joy_forwardthreshold = + Cvar_Get ("joyforwardthreshold", "0.15", CVAR_NONE, "None"); + joy_sidethreshold = + Cvar_Get ("joysidethreshold", "0.15", CVAR_NONE, "None"); + joy_pitchthreshold = + Cvar_Get ("joypitchthreshold", "0.15", CVAR_NONE, "None"); + joy_yawthreshold = Cvar_Get ("joyyawthreshold", "0.15", CVAR_NONE, "None"); + joy_forwardsensitivity = + Cvar_Get ("joyforwardsensitivity", "-1.0", CVAR_NONE, "None"); + joy_sidesensitivity = + Cvar_Get ("joysidesensitivity", "-1.0", CVAR_NONE, "None"); + joy_pitchsensitivity = + Cvar_Get ("joypitchsensitivity", "1.0", CVAR_NONE, "None"); + joy_yawsensitivity = + Cvar_Get ("joyyawsensitivity", "-1.0", CVAR_NONE, "None"); + joy_wwhack1 = Cvar_Get ("joywwhack1", "0.0", CVAR_NONE, "None"); + joy_wwhack2 = Cvar_Get ("joywwhack2", "0.0", CVAR_NONE, "None"); } /* @@ -548,21 +540,20 @@ void IN_Init_Cvars (void) IN_Shutdown =========== */ -void IN_Shutdown (void) +void +IN_Shutdown (void) { IN_DeactivateMouse (); IN_ShowMouse (); - if (g_pMouse) - { - IDirectInputDevice_Release(g_pMouse); + if (g_pMouse) { + IDirectInputDevice_Release (g_pMouse); g_pMouse = NULL; } - if (g_pdi) - { - IDirectInput_Release(g_pdi); + if (g_pdi) { + IDirectInput_Release (g_pdi); g_pdi = NULL; } } @@ -573,28 +564,23 @@ void IN_Shutdown (void) IN_MouseEvent =========== */ -void IN_MouseEvent (int mstate) +void +IN_MouseEvent (int mstate) { - int i; + int i; - if (mouseactive && !dinput) - { - // perform button actions - for (i=0 ; ivalue) - { + if (m_filter->value) { mouse_x = (mx + old_mouse_x) * 0.5; mouse_y = (my + old_mouse_y) * 0.5; - } - else - { + } else { mouse_x = mx; mouse_y = my; } @@ -722,15 +696,15 @@ void IN_MouseMove (usercmd_t *cmd) mouse_y *= sensitivity->value; // add mouse X/Y movement to cmd - if ( (in_strafe.state & 1) || (lookstrafe->int_val && freelook)) + if ((in_strafe.state & 1) || (lookstrafe->int_val && freelook)) cmd->sidemove += m_side->value * mouse_x; else cl.viewangles[YAW] -= m_yaw->value * mouse_x; if (freelook) V_StopPitchDrift (); - - if ( freelook && !(in_strafe.state & 1)) { + + if (freelook && !(in_strafe.state & 1)) { cl.viewangles[PITCH] += m_pitch->value * mouse_y; cl.viewangles[PITCH] = bound (-70, cl.viewangles[PITCH], 80); } else { @@ -741,8 +715,7 @@ void IN_MouseMove (usercmd_t *cmd) } // if the mouse has moved, force it to the center, so there's room to move - if (mx || my) - { + if (mx || my) { SetCursorPos (window_center_x, window_center_y); } } @@ -753,11 +726,11 @@ void IN_MouseMove (usercmd_t *cmd) IN_Move =========== */ -void IN_Move (usercmd_t *cmd) +void +IN_Move (usercmd_t *cmd) { - if (ActiveApp && !Minimized) - { + if (ActiveApp && !Minimized) { IN_MouseMove (cmd); IN_JoyMove (cmd); } @@ -769,19 +742,19 @@ void IN_Move (usercmd_t *cmd) IN_Accumulate =========== */ -void IN_Accumulate (void) +void +IN_Accumulate (void) { -// int mx, my; -// HDC hdc; +// int mx, my; +// HDC hdc; - if (mouseactive) - { + if (mouseactive) { GetCursorPos (¤t_pos); mx_accum += current_pos.x - window_center_x; my_accum += current_pos.y - window_center_y; - // force the mouse to the center, so there's room to move + // force the mouse to the center, so there's room to move SetCursorPos (window_center_x, window_center_y); } } @@ -792,11 +765,11 @@ void IN_Accumulate (void) IN_ClearStates =================== */ -void IN_ClearStates (void) +void +IN_ClearStates (void) { - if (mouseactive) - { + if (mouseactive) { mx_accum = 0; my_accum = 0; mouse_oldbuttonstate = 0; @@ -808,54 +781,50 @@ void IN_ClearStates (void) =============== IN_StartupJoystick =============== -*/ -static void IN_StartupJoystick (void) -{ - int /*i,*/ numdevs; - JOYCAPS jc; - MMRESULT mmr = !JOYERR_NOERROR; - - // assume no joystick - joy_avail = false; +*/ +static void +IN_StartupJoystick (void) +{ + int /* i, */ numdevs; + JOYCAPS jc; + MMRESULT mmr = !JOYERR_NOERROR; + + // assume no joystick + joy_avail = false; // abort startup if user requests no joystick - if ( COM_CheckParm ("-nojoy") ) - return; - + if (COM_CheckParm ("-nojoy")) + return; + // verify joystick driver is present - if ((numdevs = joyGetNumDevs ()) == 0) - { + if ((numdevs = joyGetNumDevs ()) == 0) { Con_Printf ("\njoystick not found -- driver not present\n\n"); return; } - // cycle through the joystick ids for the first valid one - for (joy_id=0 ; joy_idint_val) - { + if (joy_advanced->int_val) { // default joystick initialization // 2 axes only with joystick control dwAxisMap[JOY_AXIS_X] = AxisTurn; // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS; dwAxisMap[JOY_AXIS_Y] = AxisForward; // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS; - } - else - { - if (strcmp (joy_name->string, "joystick") != 0) - { + } else { + if (strcmp (joy_name->string, "joystick") != 0) { // notify user of advanced controller Con_Printf ("\n%s configured\n\n", joy_name->string); } - // advanced initialization here // data supplied by user via joy_axisn cvars dwTemp = joy_advaxisx->int_val; @@ -960,10 +926,8 @@ static void Joy_AdvancedUpdate_f (void) // compute the axes to collect from DirectInput joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV; - for (i = 0; i < JOY_MAX_AXES; i++) - { - if (dwAxisMap[i] != AxisNada) - { + for (i = 0; i < JOY_MAX_AXES; i++) { + if (dwAxisMap[i] != AxisNada) { joy_flags |= dwAxisFlags[i]; } } @@ -975,44 +939,39 @@ static void Joy_AdvancedUpdate_f (void) IN_Commands =========== */ -void IN_Commands (void) +void +IN_Commands (void) { - int i, key_index; - DWORD buttonstate, povstate; + int i, key_index; + DWORD buttonstate, povstate; - if (!joy_avail) - { + if (!joy_avail) { return; } - // loop through the joystick buttons - // key a joystick event or auxillary event for higher number buttons for each state change + // key a joystick event or auxillary event for higher number buttons for + // each state change buttonstate = ji.dwButtons; - for (i=0 ; i < joy_numbuttons ; i++) - { - if ( (buttonstate & (1<int_val) - { + if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR) { + // this is a hack -- there is a bug in the Logitech WingMan Warrior + // DirectInput Driver + // rather than having 32768 be the zero point, they have the zero + // point at 32668 + // go figure -- anyway, now we get the full resolution out of the + // device + if (joy_wwhack1->int_val) { ji.dwUpos += 100; } return true; - } - else - { + } else { // read error occurred // turning off the joystick seems too harsh for 1 read error, // but what should be done? @@ -1080,29 +1037,25 @@ static qboolean IN_ReadJoystick (void) IN_JoyMove =========== */ -static void IN_JoyMove (usercmd_t *cmd) +static void +IN_JoyMove (usercmd_t *cmd) { - float speed, aspeed; - float fAxisValue, fTemp; - int i; + float speed, aspeed; + float fAxisValue, fTemp; + int i; // complete initialization if first time in // this is needed as cvars are not available at initialization time - if( joy_advancedinit != true ) - { - Joy_AdvancedUpdate_f(); + if (joy_advancedinit != true) { + Joy_AdvancedUpdate_f (); joy_advancedinit = true; } - // verify joystick is available and that the user wants to use it - if (!joy_avail || !in_joystick->int_val) - { - return; + if (!joy_avail || !in_joystick->int_val) { + return; } - // collect the joystick data, if possible - if (IN_ReadJoystick () != true) - { + if (IN_ReadJoystick () != true) { return; } @@ -1113,136 +1066,133 @@ static void IN_JoyMove (usercmd_t *cmd) aspeed = speed * host_frametime; // loop through the axes - for (i = 0; i < JOY_MAX_AXES; i++) - { - // get the floating point zero-centered, potentially-inverted data for the current axis + for (i = 0; i < JOY_MAX_AXES; i++) { + // get the floating point zero-centered, potentially-inverted data + // for the current axis fAxisValue = (float) *pdwRawValue[i]; // move centerpoint to zero fAxisValue -= 32768.0; - if (joy_wwhack2->int_val) - { - if (dwAxisMap[i] == AxisTurn) - { + if (joy_wwhack2->int_val) { + if (dwAxisMap[i] == AxisTurn) { // this is a special formula for the Logitech WingMan Warrior // y=ax^b; where a = 300 and b = 1.3 - // also x values are in increments of 800 (so this is factored out) - // then bounds check result to level out excessively high spin rates - fTemp = 300.0 * pow(abs(fAxisValue) / 800.0, 1.3); + // also x values are in increments of 800 (so this is + // factored out) + // then bounds check result to level out excessively high + // spin rates + fTemp = 300.0 * pow (abs (fAxisValue) / 800.0, 1.3); if (fTemp > 14000.0) fTemp = 14000.0; // restore direction information fAxisValue = (fAxisValue > 0.0) ? fTemp : -fTemp; } } - // convert range from -32768..32767 to -1..1 fAxisValue /= 32768.0; - switch (dwAxisMap[i]) - { - case AxisForward: - if (!joy_advanced->int_val && freelook) - { - // user wants forward control to become look control - if (fabs(fAxisValue) > joy_pitchthreshold->value) - { - // if mouse invert is on, invert the joystick pitch value - // only absolute control support here (joy_advanced is false) - if (m_pitch->value < 0.0) - { - cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; + switch (dwAxisMap[i]) { + case AxisForward: + if (!joy_advanced->int_val && freelook) { + // user wants forward control to become look control + if (fabs (fAxisValue) > joy_pitchthreshold->value) { + // if mouse invert is on, invert the joystick pitch + // value + // only absolute control support here (joy_advanced + // is false) + if (m_pitch->value < 0.0) { + cl.viewangles[PITCH] -= + (fAxisValue * joy_pitchsensitivity->value) * + aspeed * cl_pitchspeed->value; + } else { + cl.viewangles[PITCH] += + (fAxisValue * joy_pitchsensitivity->value) * + aspeed * cl_pitchspeed->value; + } + V_StopPitchDrift (); + } else { + // no pitch movement + // disable pitch return-to-center unless requested by + // user + // *** this code can be removed when the lookspring + // bug is fixed + // *** the bug always has the lookspring feature on + if (!lookspring->int_val) + V_StopPitchDrift (); } - else - { - cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; + } else { + // user wants forward control to be forward control + if (fabs (fAxisValue) > joy_forwardthreshold->value) { + cmd->forwardmove += + (fAxisValue * joy_forwardsensitivity->value) * + speed * cl_forwardspeed->value; } - V_StopPitchDrift(); } - else - { - // no pitch movement - // disable pitch return-to-center unless requested by user - // *** this code can be removed when the lookspring bug is fixed - // *** the bug always has the lookspring feature on - if (!lookspring->int_val) - V_StopPitchDrift(); - } - } - else - { - // user wants forward control to be forward control - if (fabs(fAxisValue) > joy_forwardthreshold->value) - { - cmd->forwardmove += (fAxisValue * joy_forwardsensitivity->value) * speed * cl_forwardspeed->value; - } - } - break; + break; - case AxisSide: - if (fabs(fAxisValue) > joy_sidethreshold->value) - { - cmd->sidemove += (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value; - } - break; - - case AxisTurn: - if ((in_strafe.state & 1) || (lookstrafe->int_val && freelook)) - { - // user wants turn control to become side control - if (fabs(fAxisValue) > joy_sidethreshold->value) - { - cmd->sidemove -= (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value; + case AxisSide: + if (fabs (fAxisValue) > joy_sidethreshold->value) { + cmd->sidemove += + (fAxisValue * joy_sidesensitivity->value) * speed * + cl_sidespeed->value; } - } - else - { - // user wants turn control to be turn control - if (fabs(fAxisValue) > joy_yawthreshold->value) - { - if(dwControlMap[i] == JOY_ABSOLUTE_AXIS) - { - cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * aspeed * cl_yawspeed->value; - } - else - { - cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * speed * 180.0; - } + break; - } - } - break; - - case AxisLook: - if (freelook) - { - if (fabs(fAxisValue) > joy_pitchthreshold->value) - { - // pitch movement detected and pitch movement desired by user - if(dwControlMap[i] == JOY_ABSOLUTE_AXIS) - { - cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; + case AxisTurn: + if ((in_strafe.state & 1) || (lookstrafe->int_val && freelook)) { + // user wants turn control to become side control + if (fabs (fAxisValue) > joy_sidethreshold->value) { + cmd->sidemove -= + (fAxisValue * joy_sidesensitivity->value) * speed * + cl_sidespeed->value; } - else - { - cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * speed * 180.0; - } - V_StopPitchDrift(); - } - else - { - // no pitch movement - // disable pitch return-to-center unless requested by user - // *** this code can be removed when the lookspring bug is fixed - // *** the bug always has the lookspring feature on - if (!lookspring->int_val) - V_StopPitchDrift(); - } - } - break; + } else { + // user wants turn control to be turn control + if (fabs (fAxisValue) > joy_yawthreshold->value) { + if (dwControlMap[i] == JOY_ABSOLUTE_AXIS) { + cl.viewangles[YAW] += + (fAxisValue * joy_yawsensitivity->value) * + aspeed * cl_yawspeed->value; + } else { + cl.viewangles[YAW] += + (fAxisValue * joy_yawsensitivity->value) * + speed * 180.0; + } - default: - break; + } + } + break; + + case AxisLook: + if (freelook) { + if (fabs (fAxisValue) > joy_pitchthreshold->value) { + // pitch movement detected and pitch movement desired + // by user + if (dwControlMap[i] == JOY_ABSOLUTE_AXIS) { + cl.viewangles[PITCH] += + (fAxisValue * joy_pitchsensitivity->value) * + aspeed * cl_pitchspeed->value; + } else { + cl.viewangles[PITCH] += + (fAxisValue * joy_pitchsensitivity->value) * + speed * 180.0; + } + V_StopPitchDrift (); + } else { + // no pitch movement + // disable pitch return-to-center unless requested by + // user + // *** this code can be removed when the lookspring + // bug is fixed + // *** the bug always has the lookspring feature on + if (!lookspring->int_val) + V_StopPitchDrift (); + } + } + break; + + default: + break; } } diff --git a/source/in_x11.c b/source/in_x11.c index 1fa439c..6108b74 100644 --- a/source/in_x11.c +++ b/source/in_x11.c @@ -30,7 +30,7 @@ */ #define _BSD -#include +# include "config.h" #include #include @@ -74,118 +74,220 @@ #include "view.h" -cvar_t *_windowed_mouse; -cvar_t *m_filter; +cvar_t *_windowed_mouse; +cvar_t *m_filter; -cvar_t *in_dga; -cvar_t *in_dga_mouseaccel; +cvar_t *in_dga; +cvar_t *in_dga_mouseaccel; static qboolean dga_avail; static qboolean dga_active; -static qboolean mouse_avail; -static float mouse_x, mouse_y; -static float old_mouse_x, old_mouse_y; -static int p_mouse_x, p_mouse_y; +static qboolean mouse_avail; +static float mouse_x, mouse_y; +static float old_mouse_x, old_mouse_y; +static int p_mouse_x, p_mouse_y; #define KEY_MASK (KeyPressMask | KeyReleaseMask) #define MOUSE_MASK (ButtonPressMask | ButtonReleaseMask | PointerMotionMask) #define INPUT_MASK (KEY_MASK | MOUSE_MASK) static int -XLateKey(XKeyEvent *ev, qboolean modified) +XLateKey (XKeyEvent * ev, qboolean modified) { - char tmp[2]; - int key = 0; - KeySym keysym; + char tmp[2]; + int key = 0; + KeySym keysym; if (!modified) { - keysym = XLookupKeysym(ev, 0); + keysym = XLookupKeysym (ev, 0); } else { - XLookupString(ev, tmp, 1, &keysym, NULL); + XLookupString (ev, tmp, 1, &keysym, NULL); } - switch(keysym) { - case XK_KP_Page_Up: key = KP_PGUP; break; - case XK_Page_Up: key = K_PGUP; break; + switch (keysym) { + case XK_KP_Page_Up: + key = KP_PGUP; + break; + case XK_Page_Up: + key = K_PGUP; + break; - case XK_KP_Page_Down: key = KP_PGDN; break; - case XK_Page_Down: key = K_PGDN; break; + case XK_KP_Page_Down: + key = KP_PGDN; + break; + case XK_Page_Down: + key = K_PGDN; + break; - case XK_KP_Home: key = KP_HOME; break; - case XK_Home: key = K_HOME; break; + case XK_KP_Home: + key = KP_HOME; + break; + case XK_Home: + key = K_HOME; + break; - case XK_KP_End: key = KP_END; break; - case XK_End: key = K_END; break; + case XK_KP_End: + key = KP_END; + break; + case XK_End: + key = K_END; + break; - case XK_KP_Left: key = KP_LEFTARROW; break; - case XK_Left: key = K_LEFTARROW; break; + case XK_KP_Left: + key = KP_LEFTARROW; + break; + case XK_Left: + key = K_LEFTARROW; + break; - case XK_KP_Right: key = KP_RIGHTARROW; break; - case XK_Right: key = K_RIGHTARROW; break; + case XK_KP_Right: + key = KP_RIGHTARROW; + break; + case XK_Right: + key = K_RIGHTARROW; + break; - case XK_KP_Down: key = KP_DOWNARROW; break; - case XK_Down: key = K_DOWNARROW; break; + case XK_KP_Down: + key = KP_DOWNARROW; + break; + case XK_Down: + key = K_DOWNARROW; + break; - case XK_KP_Up: key = KP_UPARROW; break; - case XK_Up: key = K_UPARROW; break; + case XK_KP_Up: + key = KP_UPARROW; + break; + case XK_Up: + key = K_UPARROW; + break; - case XK_Escape: key = K_ESCAPE; break; + case XK_Escape: + key = K_ESCAPE; + break; - case XK_KP_Enter: key = KP_ENTER; break; - case XK_Return: key = K_ENTER; break; + case XK_KP_Enter: + key = KP_ENTER; + break; + case XK_Return: + key = K_ENTER; + break; - case XK_Tab: key = K_TAB; break; + case XK_Tab: + key = K_TAB; + break; - case XK_F1: key = K_F1; break; - case XK_F2: key = K_F2; break; - case XK_F3: key = K_F3; break; - case XK_F4: key = K_F4; break; - case XK_F5: key = K_F5; break; - case XK_F6: key = K_F6; break; - case XK_F7: key = K_F7; break; - case XK_F8: key = K_F8; break; - case XK_F9: key = K_F9; break; - case XK_F10: key = K_F10; break; - case XK_F11: key = K_F11; break; - case XK_F12: key = K_F12; break; + case XK_F1: + key = K_F1; + break; + case XK_F2: + key = K_F2; + break; + case XK_F3: + key = K_F3; + break; + case XK_F4: + key = K_F4; + break; + case XK_F5: + key = K_F5; + break; + case XK_F6: + key = K_F6; + break; + case XK_F7: + key = K_F7; + break; + case XK_F8: + key = K_F8; + break; + case XK_F9: + key = K_F9; + break; + case XK_F10: + key = K_F10; + break; + case XK_F11: + key = K_F11; + break; + case XK_F12: + key = K_F12; + break; - case XK_BackSpace: key = K_BACKSPACE; break; + case XK_BackSpace: + key = K_BACKSPACE; + break; - case XK_KP_Delete: key = KP_DEL; break; - case XK_Delete: key = K_DEL; break; + case XK_KP_Delete: + key = KP_DEL; + break; + case XK_Delete: + key = K_DEL; + break; - case XK_Pause: key = K_PAUSE; break; + case XK_Pause: + key = K_PAUSE; + break; case XK_Shift_L: - case XK_Shift_R: key = K_SHIFT; break; + case XK_Shift_R: + key = K_SHIFT; + break; case XK_Execute: case XK_Control_L: - case XK_Control_R: key = K_CTRL; break; + case XK_Control_R: + key = K_CTRL; + break; case XK_Mode_switch: case XK_Alt_L: case XK_Meta_L: case XK_Alt_R: - case XK_Meta_R: key = K_ALT; break; + case XK_Meta_R: + key = K_ALT; + break; - case XK_Caps_Lock: key = K_CAPSLOCK; break; - case XK_KP_Begin: key = KP_5; break; + case XK_Caps_Lock: + key = K_CAPSLOCK; + break; + case XK_KP_Begin: + key = KP_5; + break; - case XK_Insert: key = K_INS; break; - case XK_KP_Insert: key = KP_INS; break; + case XK_Insert: + key = K_INS; + break; + case XK_KP_Insert: + key = KP_INS; + break; - case XK_KP_Multiply: key = KP_MULTIPLY; break; - case XK_KP_Add: key = KP_PLUS; break; - case XK_KP_Subtract: key = KP_MINUS; break; - case XK_KP_Divide: key = KP_DIVIDE; break; + case XK_KP_Multiply: + key = KP_MULTIPLY; + break; + case XK_KP_Add: + key = KP_PLUS; + break; + case XK_KP_Subtract: + key = KP_MINUS; + break; + case XK_KP_Divide: + key = KP_DIVIDE; + break; - /* For Sun keyboards */ - case XK_F27: key = K_HOME; break; - case XK_F29: key = K_PGUP; break; - case XK_F33: key = K_END; break; - case XK_F35: key = K_PGDN; break; + /* For Sun keyboards */ + case XK_F27: + key = K_HOME; + break; + case XK_F29: + key = K_PGUP; + break; + case XK_F33: + key = K_END; + break; + case XK_F35: + key = K_PGDN; + break; default: if (keysym < 128) { @@ -203,70 +305,73 @@ XLateKey(XKeyEvent *ev, qboolean modified) static void -event_key (XEvent *event) +event_key (XEvent * event) { - Key_Event (XLateKey (&event->xkey, 0), XLateKey(&event->xkey, 1), event->type == KeyPress); + Key_Event (XLateKey (&event->xkey, 0), XLateKey (&event->xkey, 1), + event->type == KeyPress); } static void -event_button (XEvent *event) +event_button (XEvent * event) { - int but; + int but; but = event->xbutton.button; - if (but == 2) but = 3; - else if (but == 3) but = 2; - switch(but) { + if (but == 2) + but = 3; + else if (but == 3) + but = 2; + switch (but) { case 1: case 2: case 3: - Key_Event(K_MOUSE1 + but - 1, 0, event->type == ButtonPress); + Key_Event (K_MOUSE1 + but - 1, 0, event->type == ButtonPress); break; case 4: - Key_Event(K_MWHEELUP, 0, event->type == ButtonPress); + Key_Event (K_MWHEELUP, 0, event->type == ButtonPress); break; case 5: - Key_Event(K_MWHEELDOWN, 0, event->type == ButtonPress); + Key_Event (K_MWHEELDOWN, 0, event->type == ButtonPress); break; } } static void -center_pointer(void) +center_pointer (void) { - XEvent event; + XEvent event; event.type = MotionNotify; event.xmotion.display = x_disp; event.xmotion.window = x_win; event.xmotion.x = vid.width / 2; event.xmotion.y = vid.height / 2; - XSendEvent(x_disp, x_win, False, PointerMotionMask, &event); - XWarpPointer(x_disp, None, x_win, 0, 0, 0, 0, - vid.width / 2, vid.height / 2); + XSendEvent (x_disp, x_win, False, PointerMotionMask, &event); + XWarpPointer (x_disp, None, x_win, 0, 0, 0, 0, + vid.width / 2, vid.height / 2); } static void -event_motion (XEvent *event) +event_motion (XEvent * event) { if (dga_active) { mouse_x += event->xmotion.x_root * in_dga_mouseaccel->value; mouse_y += event->xmotion.y_root * in_dga_mouseaccel->value; } else { if (!p_mouse_x && !p_mouse_y) { - Con_Printf("event->xmotion.x: %d\n", event->xmotion.x); - Con_Printf("event->xmotion.y: %d\n", event->xmotion.y); + Con_Printf ("event->xmotion.x: %d\n", event->xmotion.x); + Con_Printf ("event->xmotion.y: %d\n", event->xmotion.y); } if (vid_fullscreen->int_val || _windowed_mouse->int_val) { if (!event->xmotion.send_event) { mouse_x += (event->xmotion.x - p_mouse_x); mouse_y += (event->xmotion.y - p_mouse_y); - if (abs(vid.width/2 - event->xmotion.x) > vid.width / 4 - || abs(vid.height/2 - event->xmotion.y) > vid.height / 4) { - center_pointer(); + if (abs (vid.width / 2 - event->xmotion.x) > vid.width / 4 + || abs (vid.height / 2 - event->xmotion.y) > vid.height / 4) { + center_pointer (); } } } else { @@ -282,8 +387,8 @@ event_motion (XEvent *event) void IN_Commands (void) { - static int old_windowed_mouse; - static int old_in_dga; + static int old_windowed_mouse; + static int old_in_dga; JOY_Command (); @@ -292,9 +397,9 @@ IN_Commands (void) old_windowed_mouse = _windowed_mouse->int_val; old_in_dga = in_dga->int_val; - if (_windowed_mouse->int_val) { // grab the pointer + if (_windowed_mouse->int_val) { // grab the pointer XGrabPointer (x_disp, x_win, True, MOUSE_MASK, GrabModeAsync, - GrabModeAsync, x_win, None, CurrentTime); + GrabModeAsync, x_win, None, CurrentTime); #ifdef HAVE_DGA if (dga_avail && in_dga->int_val && !dga_active) { XF86DGADirectVideo (x_disp, DefaultScreen (x_disp), @@ -302,7 +407,7 @@ IN_Commands (void) dga_active = true; } #endif - } else { // ungrab the pointer + } else { // ungrab the pointer #ifdef HAVE_DGA if (dga_avail && in_dga->int_val && dga_active) { XF86DGADirectVideo (x_disp, DefaultScreen (x_disp), 0); @@ -319,7 +424,7 @@ void IN_SendKeyEvents (void) { /* Get events from X server. */ - x11_process_events(); + x11_process_events (); } @@ -327,7 +432,7 @@ void IN_Move (usercmd_t *cmd) { JOY_Move (cmd); - + if (!mouse_avail) return; @@ -346,7 +451,7 @@ IN_Move (usercmd_t *cmd) cmd->sidemove += m_side->value * mouse_x; else cl.viewangles[YAW] -= m_yaw->value * mouse_x; - + if (freelook) V_StopPitchDrift (); @@ -379,7 +484,7 @@ IN_Shutdown (void) XF86DGADirectVideo (x_disp, DefaultScreen (x_disp), 0); #endif } - x11_close_display(); + x11_close_display (); } void @@ -387,29 +492,30 @@ IN_Init (void) { // open the display if (!x_disp) - Sys_Error("IN: No display!!\n"); + Sys_Error ("IN: No display!!\n"); if (!x_win) - Sys_Error("IN: No window!!\n"); + Sys_Error ("IN: No window!!\n"); - x11_open_display (); // call to increment the reference counter + x11_open_display (); // call to increment the reference + // counter { - int attribmask = CWEventMask; + int attribmask = CWEventMask; XWindowAttributes attribs_1; XSetWindowAttributes attribs_2; - XGetWindowAttributes(x_disp, x_win, &attribs_1); + XGetWindowAttributes (x_disp, x_win, &attribs_1); attribs_2.event_mask = attribs_1.your_event_mask | INPUT_MASK; - XChangeWindowAttributes(x_disp, x_win, attribmask, &attribs_2); + XChangeWindowAttributes (x_disp, x_win, attribmask, &attribs_2); } JOY_Init (); XAutoRepeatOff (x_disp); - if (COM_CheckParm("-nomouse")) + if (COM_CheckParm ("-nomouse")) return; dga_avail = VID_CheckDGA (x_disp, NULL, NULL, NULL); @@ -421,11 +527,11 @@ IN_Init (void) mouse_x = mouse_y = 0.0; mouse_avail = 1; - x11_add_event(KeyPress, &event_key); - x11_add_event(KeyRelease, &event_key); - x11_add_event(ButtonPress, &event_button); - x11_add_event(ButtonRelease, &event_button); - x11_add_event(MotionNotify, &event_motion); + x11_add_event (KeyPress, &event_key); + x11_add_event (KeyRelease, &event_key); + x11_add_event (ButtonPress, &event_button); + x11_add_event (ButtonRelease, &event_button); + x11_add_event (MotionNotify, &event_motion); return; } @@ -438,5 +544,5 @@ IN_Init_Cvars (void) m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE, "None"); in_dga = Cvar_Get ("in_dga", "1", CVAR_ARCHIVE, "DGA Input support"); in_dga_mouseaccel = Cvar_Get ("in_dga_mouseaccel", "1", CVAR_ARCHIVE, - "None"); + "None"); } diff --git a/source/info.c b/source/info.c index dfdf87a..9b6479f 100644 --- a/source/info.c +++ b/source/info.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "console.h" @@ -54,22 +54,22 @@ Searches the string for the given key and returns the associated value, or an empty string. =============== */ -char *Info_ValueForKey (char *s, char *key) +char * +Info_ValueForKey (char *s, char *key) { - char pkey[512]; - static char value[4][512]; // use two buffers so compares - // work without stomping on each other - static int valueindex; - char *o; - + char pkey[512]; + static char value[4][512]; // use two buffers so compares + + // work without stomping on each other + static int valueindex; + char *o; + valueindex = (valueindex + 1) % 4; if (*s == '\\') s++; - while (1) - { + while (1) { o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return ""; *o++ = *s++; @@ -79,15 +79,14 @@ char *Info_ValueForKey (char *s, char *key) o = value[valueindex]; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { if (!*s) return ""; *o++ = *s++; } *o = 0; - if (!strcmp (key, pkey) ) + if (!strcmp (key, pkey)) return value[valueindex]; if (!*s) @@ -96,27 +95,25 @@ char *Info_ValueForKey (char *s, char *key) } } -void Info_RemoveKey (char *s, char *key) +void +Info_RemoveKey (char *s, char *key) { - char *start; - char pkey[512]; - char value[512]; - char *o; + char *start; + char pkey[512]; + char value[512]; + char *o; - if (strstr (key, "\\")) - { + if (strstr (key, "\\")) { Con_Printf ("Can't use a key with a \\\n"); return; } - while (1) - { + while (1) { start = s; if (*s == '\\') s++; o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return; *o++ = *s++; @@ -125,17 +122,15 @@ void Info_RemoveKey (char *s, char *key) s++; o = value; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; - if (!strcmp (key, pkey) ) - { - strcpy (start, s); // remove this part + if (!strcmp (key, pkey)) { + strcpy (start, s); // remove this part return; } @@ -145,22 +140,21 @@ void Info_RemoveKey (char *s, char *key) } -void Info_RemovePrefixedKeys (char *start, char prefix) +void +Info_RemovePrefixedKeys (char *start, char prefix) { - char *s; - char pkey[512]; - char value[512]; - char *o; + char *s; + char pkey[512]; + char value[512]; + char *o; s = start; - while (1) - { + while (1) { if (*s == '\\') s++; o = pkey; - while (*s != '\\') - { + while (*s != '\\') { if (!*s) return; *o++ = *s++; @@ -169,16 +163,14 @@ void Info_RemovePrefixedKeys (char *start, char prefix) s++; o = value; - while (*s != '\\' && *s) - { + while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; - if (pkey[0] == prefix) - { + if (pkey[0] == prefix) { Info_RemoveKey (start, pkey); s = start; } @@ -190,58 +182,53 @@ void Info_RemovePrefixedKeys (char *start, char prefix) } -void Info_SetValueForStarKey (char *s, char *key, char *value, size_t maxsize) +void +Info_SetValueForStarKey (char *s, char *key, char *value, size_t maxsize) { - char newstr[1024], *v; - int c, is_name, is_team; + char newstr[1024], *v; + int c, is_name, is_team; - if (strstr (key, "\\") || strstr (value, "\\") ) - { + if (strstr (key, "\\") || strstr (value, "\\")) { Con_Printf ("Can't use keys or values with a \\\n"); return; } - if (strstr (key, "\"") || strstr (value, "\"") ) - { + if (strstr (key, "\"") || strstr (value, "\"")) { Con_Printf ("Can't use keys or values with a \"\n"); return; } - if (strlen(key) > 63 || strlen(value) > 63) - { + if (strlen (key) > 63 || strlen (value) > 63) { Con_Printf ("Keys and values must be < 64 characters.\n"); return; } - // this next line is kinda trippy - if (*(v = Info_ValueForKey(s, key))) { - // key exists, make sure we have enough room for new value, if we don't, + if (*(v = Info_ValueForKey (s, key))) { + // key exists, make sure we have enough room for new value, if we + // don't, // don't change it! - if (strlen(value) - strlen(v) + strlen(s) > maxsize) { + if (strlen (value) - strlen (v) + strlen (s) > maxsize) { Con_Printf ("Info string length exceeded\n"); return; } } Info_RemoveKey (s, key); - if (!value || !strlen(value)) + if (!value || !strlen (value)) return; - snprintf (newstr, sizeof(newstr), "\\%s\\%s", key, value); + snprintf (newstr, sizeof (newstr), "\\%s\\%s", key, value); - if ((int)(strlen(newstr) + strlen(s)) > maxsize) - { + if ((int) (strlen (newstr) + strlen (s)) > maxsize) { Con_Printf ("Info string length exceeded\n"); return; } - // only copy ascii values - s += strlen(s); + s += strlen (s); v = newstr; - is_name = stricmp(key, "name") == 0; - is_team = stricmp(key, "team") == 0; - while (*v) - { - c = (unsigned char)*v++; + is_name = stricmp (key, "name") == 0; + is_team = stricmp (key, "team") == 0; + while (*v) { + c = (unsigned char) *v++; // client only allows highbits on name if (!is_name) { c &= 127; @@ -249,7 +236,7 @@ void Info_SetValueForStarKey (char *s, char *key, char *value, size_t maxsize) continue; // auto lowercase team if (is_team) - c = tolower(c); + c = tolower (c); } if (c > 13) *s++ = c; @@ -257,10 +244,10 @@ void Info_SetValueForStarKey (char *s, char *key, char *value, size_t maxsize) *s = 0; } -void Info_SetValueForKey (char *s, char *key, char *value, size_t maxsize) +void +Info_SetValueForKey (char *s, char *key, char *value, size_t maxsize) { - if (key[0] == '*') - { + if (key[0] == '*') { Con_Printf ("Can't set * keys\n"); return; } @@ -268,33 +255,30 @@ void Info_SetValueForKey (char *s, char *key, char *value, size_t maxsize) Info_SetValueForStarKey (s, key, value, maxsize); } -void Info_Print (char *s) +void +Info_Print (char *s) { - char key[512]; - char value[512]; - char *o; - int l; + char key[512]; + char value[512]; + char *o; + int l; if (*s == '\\') s++; - while (*s) - { + while (*s) { o = key; while (*s && *s != '\\') *o++ = *s++; l = o - key; - if (l < 20) - { - memset (o, ' ', 20-l); + if (l < 20) { + memset (o, ' ', 20 - l); key[20] = 0; - } - else + } else *o = 0; Con_Printf ("%s", key); - if (!*s) - { + if (!*s) { Con_Printf ("MISSING VALUE\n"); return; } diff --git a/source/joy_linux.c b/source/joy_linux.c index 7cd1e58..7326840 100644 --- a/source/joy_linux.c +++ b/source/joy_linux.c @@ -45,30 +45,30 @@ #define JOY_MAX_AXES 6 #define JOY_MAX_BUTTONS 10 -cvar_t *joy_device; // Joystick device name -cvar_t *joy_enable; // Joystick enabling flag -cvar_t *joy_sensitivity; // Joystick sensitivity +cvar_t *joy_device; // Joystick device name +cvar_t *joy_enable; // Joystick enabling flag +cvar_t *joy_sensitivity; // Joystick sensitivity -qboolean joy_found = false; -qboolean joy_active = false; +qboolean joy_found = false; +qboolean joy_active = false; // Variables and structures for this driver -int joy_handle; +int joy_handle; typedef struct { - char *name; - char *string; + char *name; + char *string; } ocvar_t; struct joy_axis { - cvar_t *axis; - ocvar_t var; - int current; + cvar_t *axis; + ocvar_t var; + int current; }; struct joy_button { - int old; - int current; + int old; + int current; }; struct joy_axis joy_axes[JOY_MAX_AXES] = { @@ -92,19 +92,21 @@ JOY_Command (void) while (read (joy_handle, &event, sizeof (struct js_event)) > -1) { if (event.type & JS_EVENT_BUTTON) { - if(event.number >= JOY_MAX_BUTTONS) + if (event.number >= JOY_MAX_BUTTONS) continue; - + joy_buttons[event.number].current = event.value; - - if (joy_buttons[event.number].current > joy_buttons[event.number].old) { - Key_Event(K_AUX1 + event.number, 0, true); + + if (joy_buttons[event.number].current > + joy_buttons[event.number].old) { + Key_Event (K_AUX1 + event.number, 0, true); } else { - if (joy_buttons[event.number].current < joy_buttons[event.number].old) { - Key_Event(K_AUX1 + event.number, 0, false); + if (joy_buttons[event.number].current < + joy_buttons[event.number].old) { + Key_Event (K_AUX1 + event.number, 0, false); } } - joy_buttons[event.number].old = joy_buttons[event.number].current; + joy_buttons[event.number].old = joy_buttons[event.number].current; } else { if (event.type & JS_EVENT_AXIS) { if (event.number >= JOY_MAX_AXES) @@ -118,8 +120,8 @@ JOY_Command (void) void JOY_Move (usercmd_t *cmd) { - int i; - + int i; + if (!joy_active || !joy_enable->int_val) return; @@ -127,19 +129,33 @@ JOY_Move (usercmd_t *cmd) for (i = 0; i < JOY_MAX_AXES; i++) { switch (joy_axes[i].axis->int_val) { case 1: - cl.viewangles[YAW] -= m_yaw->value * (float) (joy_axes[i].current / (201 - (joy_sensitivity->value * 4))); + cl.viewangles[YAW] -= + m_yaw->value * (float) (joy_axes[i].current / + (201 - + (joy_sensitivity->value * 4))); break; case 2: - cmd->forwardmove -= m_forward->value * (float) (joy_axes[i].current / (201 - (joy_sensitivity->value * 4))); + cmd->forwardmove -= + m_forward->value * (float) (joy_axes[i].current / + (201 - + (joy_sensitivity->value * 4))); break; case 3: - cmd->sidemove += m_side->value * (float) (joy_axes[i].current / (201 - (joy_sensitivity->value * 4))); + cmd->sidemove += + m_side->value * (float) (joy_axes[i].current / + (201 - + (joy_sensitivity->value * 4))); break; case 4: if (joy_axes[i].current) { - V_StopPitchDrift(); - cl.viewangles[PITCH] -= m_pitch->value * (float) (joy_axes[i].current / (201 - (joy_sensitivity->value * 4))); - cl.viewangles[PITCH] = bound (-70, cl.viewangles[PITCH], 80); + V_StopPitchDrift (); + cl.viewangles[PITCH] -= + m_pitch->value * (float) (joy_axes[i].current / + (201 - + (joy_sensitivity->value * + 4))); + cl.viewangles[PITCH] = + bound (-70, cl.viewangles[PITCH], 80); } break; } @@ -150,13 +166,14 @@ void JOY_Init (void) { // Open joystick device - joy_handle = open (joy_device->string, O_RDONLY|O_NONBLOCK); + joy_handle = open (joy_device->string, O_RDONLY | O_NONBLOCK); if (joy_handle < 0) { Con_Printf ("JOY: Joystick not found.\n"); } else { - int i; + int i; + joy_found = true; - + if (!joy_enable->int_val) { Con_Printf ("JOY: Joystick found, but not enabled.\n"); i = close (joy_handle); @@ -178,23 +195,29 @@ JOY_Init (void) void JOY_Init_Cvars (void) { - int i; + int i; - joy_device = Cvar_Get ("joy_device", "/dev/js0", CVAR_NONE|CVAR_ROM, "Joystick device"); - joy_enable = Cvar_Get ("joy_enable", "1", CVAR_NONE|CVAR_ARCHIVE, "Joystick enable flag"); - joy_sensitivity = Cvar_Get ("joy_sensitivity", "1", CVAR_NONE|CVAR_ARCHIVE, "Joystick sensitivity"); + joy_device = + Cvar_Get ("joy_device", "/dev/js0", CVAR_NONE | CVAR_ROM, + "Joystick device"); + joy_enable = + Cvar_Get ("joy_enable", "1", CVAR_NONE | CVAR_ARCHIVE, + "Joystick enable flag"); + joy_sensitivity = + Cvar_Get ("joy_sensitivity", "1", CVAR_NONE | CVAR_ARCHIVE, + "Joystick sensitivity"); for (i = 0; i < JOY_MAX_AXES; i++) { joy_axes[i].axis = Cvar_Get (joy_axes[i].var.name, - joy_axes[i].var.string, - CVAR_ARCHIVE, "None"); + joy_axes[i].var.string, + CVAR_ARCHIVE, "None"); } } void JOY_Shutdown (void) { - int i; + int i; if (!joy_active) return; diff --git a/source/joy_null.c b/source/joy_null.c index 5e84c73..94efbcf 100644 --- a/source/joy_null.c +++ b/source/joy_null.c @@ -36,12 +36,12 @@ #include "qtypes.h" // Joystick variables and structures -cvar_t *joy_device; // Joystick device name -cvar_t *joy_enable; // Joystick enabling flag -cvar_t *joy_sensitivity; // Joystick sensitivity +cvar_t *joy_device; // Joystick device name +cvar_t *joy_enable; // Joystick enabling flag +cvar_t *joy_sensitivity; // Joystick sensitivity -qboolean joy_found = false; -qboolean joy_active = false; +qboolean joy_found = false; +qboolean joy_active = false; void JOY_Command (void) @@ -62,9 +62,15 @@ JOY_Init (void) void JOY_Init_Cvars (void) { - joy_device = Cvar_Get ("joy_device", "none", CVAR_NONE|CVAR_ROM, "Joystick device"); - joy_enable = Cvar_Get ("joy_enable", "1", CVAR_NONE|CVAR_ARCHIVE, "Joystick enable flag"); - joy_sensitivity = Cvar_Get ("joy_sensitivity", "1", CVAR_NONE|CVAR_ARCHIVE, "Joystick sensitivity"); + joy_device = + Cvar_Get ("joy_device", "none", CVAR_NONE | CVAR_ROM, + "Joystick device"); + joy_enable = + Cvar_Get ("joy_enable", "1", CVAR_NONE | CVAR_ARCHIVE, + "Joystick enable flag"); + joy_sensitivity = + Cvar_Get ("joy_sensitivity", "1", CVAR_NONE | CVAR_ARCHIVE, + "Joystick sensitivity"); } void diff --git a/source/keys.c b/source/keys.c index 8807b32..a4df89b 100644 --- a/source/keys.c +++ b/source/keys.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef _WIN32 #include @@ -56,40 +56,44 @@ key up events are sent even if in console mode */ -cvar_t *cl_chatmode; +cvar_t *cl_chatmode; #define MAXCMDLINE 256 -char key_lines[32][MAXCMDLINE]; -int key_linepos; -int key_lastpress; +char key_lines[32][MAXCMDLINE]; +int key_linepos; +int key_lastpress; -int edit_line=0; -int history_line=0; +int edit_line = 0; +int history_line = 0; -keydest_t key_dest; +keydest_t key_dest; -char *keybindings[256]; -qboolean consolekeys[256]; // if true, can't be rebound while in console -qboolean menubound[256]; // if true, can't be rebound while in menu -int keyshift[256]; // key to map to if shift held down in console -int key_repeats[256]; // if > 1, it is autorepeating -qboolean keydown[256]; +char *keybindings[256]; +qboolean consolekeys[256]; // if true, can't be rebound while in -typedef struct -{ - char *name; - int keynum; + // console +qboolean menubound[256]; // if true, can't be rebound while in + + // menu +int keyshift[256]; // key to map to if shift held down + + // in console +int key_repeats[256]; // if > 1, it is autorepeating +qboolean keydown[256]; + +typedef struct { + char *name; + int keynum; } keyname_t; -keyname_t keynames[] = -{ +keyname_t keynames[] = { {"TAB", K_TAB}, {"ENTER", K_ENTER}, {"ESCAPE", K_ESCAPE}, {"SPACE", K_SPACE}, {"BACKSPACE", K_BACKSPACE}, - {"CAPSLOCK",K_CAPSLOCK}, + {"CAPSLOCK", K_CAPSLOCK}, {"PRINTSCR", K_PRNTSCR}, {"SCRLCK", K_SCRLCK}, {"PAUSE", K_PAUSE}, @@ -198,9 +202,10 @@ keyname_t keynames[] = {"MWHEELUP", K_MWHEELUP}, {"MWHEELDOWN", K_MWHEELDOWN}, - {"SEMICOLON", ';'}, // because a raw semicolon seperates commands + {"SEMICOLON", ';'}, // because a raw semicolon seperates + // commands - {NULL,0} + {NULL, 0} }; /* @@ -212,15 +217,15 @@ keyname_t keynames[] = */ qboolean -CheckForCommand ( void ) +CheckForCommand (void) { - char command[128]; - char *cmd, *s; - int i; + char command[128]; + char *cmd, *s; + int i; - s = key_lines[edit_line]+1; + s = key_lines[edit_line] + 1; - for (i=0 ; i<127 ; i++) + for (i = 0; i < 127; i++) if (s[i] <= ' ') break; else @@ -230,28 +235,27 @@ CheckForCommand ( void ) cmd = Cmd_CompleteCommand (command); if (!cmd || strcmp (cmd, command)) cmd = Cvar_CompleteVariable (command); - if (!cmd || strcmp (cmd, command) ) - return false; // just a chat message + if (!cmd || strcmp (cmd, command)) + return false; // just a chat message return true; } void -CompleteCommand ( void ) +CompleteCommand (void) { - char *cmd, *s; + char *cmd, *s; - s = key_lines[edit_line]+1; + s = key_lines[edit_line] + 1; if (*s == '\\' || *s == '/') s++; cmd = Cmd_CompleteCommand (s); if (!cmd) cmd = Cvar_CompleteVariable (s); - if (cmd) - { + if (cmd) { key_lines[edit_line][1] = '/'; - strcpy (key_lines[edit_line]+2, cmd); - key_linepos = strlen(cmd)+2; + strcpy (key_lines[edit_line] + 2, cmd); + key_linepos = strlen (cmd) + 2; key_lines[edit_line][key_linepos] = ' '; key_linepos++; key_lines[edit_line][key_linepos] = 0; @@ -267,47 +271,49 @@ Interactive line editing and console scrollback ==================== */ void -Key_Console ( int key ) +Key_Console (int key) { - int i; + int i; + #ifdef _WIN32 - HANDLE th; - char *clipText, *textCopied; + HANDLE th; + char *clipText, *textCopied; #endif - switch (key) - { + switch (key) { case K_ENTER: // backslash text are commands - if (key_lines[edit_line][1] == '/' && key_lines[edit_line][2] == '/') - goto no_lf; - else if (key_lines[edit_line][1] == '\\' || key_lines[edit_line][1] == '/') - Cbuf_AddText (key_lines[edit_line]+2); // skip the ]/ - else if (cl_chatmode->int_val != 1 && CheckForCommand()) - Cbuf_AddText (key_lines[edit_line]+1); // valid command - else if ((cls.state >= ca_connected && cl_chatmode->int_val == 2) || cl_chatmode->int_val == 1) - { - if (cls.state < ca_connected) // can happen if cl_chatmode is 1 - goto no_lf; // the text goes to /dev/null :) + if (key_lines[edit_line][1] == '/' + && key_lines[edit_line][2] == '/') goto no_lf; + else if (key_lines[edit_line][1] == '\\' + || key_lines[edit_line][1] == '/') + Cbuf_AddText (key_lines[edit_line] + 2); // skip the ]/ + else if (cl_chatmode->int_val != 1 && CheckForCommand ()) + Cbuf_AddText (key_lines[edit_line] + 1); // valid command + else if ((cls.state >= ca_connected && cl_chatmode->int_val == 2) + || cl_chatmode->int_val == 1) { + if (cls.state < ca_connected) // can happen if cl_chatmode + // is 1 + goto no_lf; // the text goes to /dev/null :) // convert to a chat message Cbuf_AddText ("say "); - Cbuf_AddText (key_lines[edit_line]+1); - } - else - Cbuf_AddText (key_lines[edit_line]+1); // skip the ] + Cbuf_AddText (key_lines[edit_line] + 1); + } else + Cbuf_AddText (key_lines[edit_line] + 1); // skip the ] Cbuf_AddText ("\n"); -no_lf: - Con_Printf ("%s\n",key_lines[edit_line]); + no_lf: + Con_Printf ("%s\n", key_lines[edit_line]); edit_line = (edit_line + 1) & 31; history_line = edit_line; key_lines[edit_line][0] = ']'; key_lines[edit_line][1] = 0; key_linepos = 1; if (cls.state == ca_disconnected) - SCR_UpdateScreen (); // force an update, because the command - // may take some time + SCR_UpdateScreen (); // force an update, because the + // command + // may take some time return; case K_TAB: @@ -316,20 +322,21 @@ no_lf: return; case K_BACKSPACE: - if (key_linepos > 1) - { - strcpy(key_lines[edit_line] + key_linepos - 1, key_lines[edit_line] + key_linepos); + if (key_linepos > 1) { + strcpy (key_lines[edit_line] + key_linepos - 1, + key_lines[edit_line] + key_linepos); key_linepos--; } return; case K_DEL: - if (key_linepos < strlen(key_lines[edit_line])) - strcpy(key_lines[edit_line] + key_linepos, key_lines[edit_line] + key_linepos + 1); + if (key_linepos < strlen (key_lines[edit_line])) + strcpy (key_lines[edit_line] + key_linepos, + key_lines[edit_line] + key_linepos + 1); return; case K_RIGHTARROW: - if (key_linepos < strlen(key_lines[edit_line])) + if (key_linepos < strlen (key_lines[edit_line])) key_linepos++; return; @@ -341,28 +348,27 @@ no_lf: case K_UPARROW: do { history_line = (history_line - 1) & 31; - } while (history_line != edit_line - && !key_lines[history_line][1]); + } while (history_line != edit_line && !key_lines[history_line][1]); if (history_line == edit_line) - history_line = (edit_line+1)&31; - strcpy(key_lines[edit_line], key_lines[history_line]); - key_linepos = strlen(key_lines[edit_line]); + history_line = (edit_line + 1) & 31; + strcpy (key_lines[edit_line], key_lines[history_line]); + key_linepos = strlen (key_lines[edit_line]); return; case K_DOWNARROW: - if (history_line == edit_line) return; + if (history_line == edit_line) + return; do { history_line = (history_line + 1) & 31; - } while (history_line != edit_line - && !key_lines[history_line][1]); + } while (history_line != edit_line && !key_lines[history_line][1]); if (history_line == edit_line) { key_lines[edit_line][0] = ']'; key_lines[edit_line][1] = 0; key_linepos = 1; } else { - strcpy(key_lines[edit_line], key_lines[history_line]); - key_linepos = strlen(key_lines[edit_line]); + strcpy (key_lines[edit_line], key_lines[history_line]); + key_linepos = strlen (key_lines[edit_line]); } return; @@ -380,12 +386,10 @@ no_lf: return; case K_HOME: - if (keydown[K_CTRL]) - { + if (keydown[K_CTRL]) { if (con->numlines > 10) con->display = con->current - con->numlines + 10; - } - else + } else key_linepos = 1; return; @@ -393,71 +397,73 @@ no_lf: if (keydown[K_CTRL]) con->display = con->current; else - key_linepos = strlen(key_lines[edit_line]); + key_linepos = strlen (key_lines[edit_line]); return; } #ifdef _WIN32 - if ((key=='V' || key=='v') && GetKeyState(VK_CONTROL)<0) { - if (OpenClipboard(NULL)) { - th = GetClipboardData(CF_TEXT); + if ((key == 'V' || key == 'v') && GetKeyState (VK_CONTROL) < 0) { + if (OpenClipboard (NULL)) { + th = GetClipboardData (CF_TEXT); if (th) { - clipText = GlobalLock(th); + clipText = GlobalLock (th); if (clipText) { - textCopied = malloc(GlobalSize(th)+1); - strcpy(textCopied, clipText); + textCopied = malloc (GlobalSize (th) + 1); + strcpy (textCopied, clipText); /* Substitutes a NULL for every token */ - strtok(textCopied, "\n\r\b"); - i = strlen(textCopied); - if (i + strlen(key_lines[edit_line]) > MAXCMDLINE-1) - i = MAXCMDLINE-1 - strlen(key_lines[edit_line]); - if (i > 0) - { // insert the string + strtok (textCopied, "\n\r\b"); + i = strlen (textCopied); + if (i + strlen (key_lines[edit_line]) > MAXCMDLINE - 1) + i = MAXCMDLINE - 1 - strlen (key_lines[edit_line]); + if (i > 0) { // insert the string memmove (key_lines[edit_line] + key_linepos + i, - key_lines[edit_line] + key_linepos, strlen(key_lines[edit_line]) - key_linepos + 1); - memcpy (key_lines[edit_line] + key_linepos, textCopied, i); + key_lines[edit_line] + key_linepos, + strlen (key_lines[edit_line]) - key_linepos + + 1); + memcpy (key_lines[edit_line] + key_linepos, textCopied, + i); key_linepos += i; } - free(textCopied); + free (textCopied); } - GlobalUnlock(th); + GlobalUnlock (th); } - CloseClipboard(); - return; + CloseClipboard (); + return; } } #endif if (key < 32 || key > 127) - return; // non printable + return; // non printable - i = strlen(key_lines[edit_line]); - if (i >= MAXCMDLINE-1) + i = strlen (key_lines[edit_line]); + if (i >= MAXCMDLINE - 1) return; // This also moves the ending \0 - memmove (key_lines[edit_line]+key_linepos+1, key_lines[edit_line]+key_linepos, i-key_linepos+1); + memmove (key_lines[edit_line] + key_linepos + 1, + key_lines[edit_line] + key_linepos, i - key_linepos + 1); key_lines[edit_line][key_linepos] = key; key_linepos++; } //============================================================================ -qboolean chat_team; -char chat_buffer[MAXCMDLINE]; -int chat_bufferlen = 0; +qboolean chat_team; +char chat_buffer[MAXCMDLINE]; +int chat_bufferlen = 0; void -Key_Message ( int key ) +Key_Message (int key) { - if (key == K_ENTER) - { + if (key == K_ENTER) { if (chat_team) Cbuf_AddText ("say_team \""); else Cbuf_AddText ("say \""); - Cbuf_AddText(chat_buffer); - Cbuf_AddText("\"\n"); + Cbuf_AddText (chat_buffer); + Cbuf_AddText ("\"\n"); key_dest = key_game; chat_bufferlen = 0; @@ -465,8 +471,7 @@ Key_Message ( int key ) return; } - if (key == K_ESCAPE) - { + if (key == K_ESCAPE) { key_dest = key_game; chat_bufferlen = 0; chat_buffer[0] = 0; @@ -474,20 +479,18 @@ Key_Message ( int key ) } if (key < 32 || key > 127) - return; // non printable + return; // non printable - if (key == K_BACKSPACE) - { - if (chat_bufferlen) - { + if (key == K_BACKSPACE) { + if (chat_bufferlen) { chat_bufferlen--; chat_buffer[chat_bufferlen] = 0; } return; } - if (chat_bufferlen == sizeof(chat_buffer)-1) - return; // all full + if (chat_bufferlen == sizeof (chat_buffer) - 1) + return; // all full chat_buffer[chat_bufferlen++] = key; chat_buffer[chat_bufferlen] = 0; @@ -506,18 +509,17 @@ the K_* names are matched up. =================== */ int -Key_StringToKeynum ( char *str ) +Key_StringToKeynum (char *str) { - keyname_t *kn; + keyname_t *kn; if (!str || !str[0]) return -1; if (!str[1]) return str[0]; - for (kn=keynames ; kn->name ; kn++) - { - if (!strcasecmp(str,kn->name)) + for (kn = keynames; kn->name; kn++) { + if (!strcasecmp (str, kn->name)) return kn->keynum; } return -1; @@ -532,22 +534,21 @@ given keynum. FIXME: handle quote special (general escape sequence?) =================== */ -char * -Key_KeynumToString ( int keynum ) +char * +Key_KeynumToString (int keynum) { - keyname_t *kn; - static char tinystr[2]; + keyname_t *kn; + static char tinystr[2]; if (keynum == -1) return ""; - if (keynum > 32 && keynum < 127) - { // printable ascii + if (keynum > 32 && keynum < 127) { // printable ascii tinystr[0] = keynum; tinystr[1] = 0; return tinystr; } - for (kn=keynames ; kn->name ; kn++) + for (kn = keynames; kn->name; kn++) if (keynum == kn->keynum) return kn->name; @@ -561,24 +562,22 @@ Key_SetBinding =================== */ void -Key_SetBinding ( int keynum, char *binding ) +Key_SetBinding (int keynum, char *binding) { - char *new; - int l; + char *new; + int l; if (keynum == -1) return; // free old bindings - if (keybindings[keynum]) - { + if (keybindings[keynum]) { free (keybindings[keynum]); keybindings[keynum] = NULL; } - // allocate memory for new binding l = strlen (binding); - new = malloc (l+1); + new = malloc (l + 1); strcpy (new, binding); new[l] = 0; keybindings[keynum] = new; @@ -590,20 +589,18 @@ Key_Unbind_f =================== */ void -Key_Unbind_f ( void ) +Key_Unbind_f (void) { - int b; + int b; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("unbind : remove commands from a key\n"); return; } - b = Key_StringToKeynum (Cmd_Argv(1)); - if (b==-1) - { - Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1)); + b = Key_StringToKeynum (Cmd_Argv (1)); + if (b == -1) { + Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv (1)); return; } @@ -611,11 +608,11 @@ Key_Unbind_f ( void ) } void -Key_Unbindall_f ( void ) +Key_Unbindall_f (void) { - int i; + int i; - for (i=0 ; i<256 ; i++) + for (i = 0; i < 256; i++) if (keybindings[i]) Key_SetBinding (i, ""); } @@ -627,41 +624,36 @@ Key_Bind_f =================== */ void -Key_Bind_f ( void ) +Key_Bind_f (void) { - int i, c, b; - char cmd[1024]; + int i, c, b; + char cmd[1024]; - c = Cmd_Argc(); + c = Cmd_Argc (); - if (c < 2) - { + if (c < 2) { Con_Printf ("bind [command] : attach a command to a key\n"); return; } - b = Key_StringToKeynum (Cmd_Argv(1)); - if (b==-1) - { - Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv(1)); + b = Key_StringToKeynum (Cmd_Argv (1)); + if (b == -1) { + Con_Printf ("\"%s\" isn't a valid key\n", Cmd_Argv (1)); return; } - if (c == 2) - { + if (c == 2) { if (keybindings[b]) - Con_Printf ("\"%s\" = \"%s\"\n", Cmd_Argv(1), keybindings[b] ); + Con_Printf ("\"%s\" = \"%s\"\n", Cmd_Argv (1), keybindings[b]); else - Con_Printf ("\"%s\" is not bound\n", Cmd_Argv(1) ); + Con_Printf ("\"%s\" is not bound\n", Cmd_Argv (1)); return; } - // copy the rest of the command line - cmd[0] = 0; // start out with a null string - for (i=2 ; i< c ; i++) - { - strncat (cmd, Cmd_Argv(i), sizeof(cmd) - strlen (cmd)); - if (i != (c-1)) - strncat (cmd, " ", sizeof(cmd) - strlen (cmd)); + cmd[0] = 0; // start out with a null string + for (i = 2; i < c; i++) { + strncat (cmd, Cmd_Argv (i), sizeof (cmd) - strlen (cmd)); + if (i != (c - 1)) + strncat (cmd, " ", sizeof (cmd) - strlen (cmd)); } Key_SetBinding (b, cmd); @@ -675,13 +667,15 @@ Writes lines containing "bind key value" ============ */ void -Key_WriteBindings ( QFile *f ) +Key_WriteBindings (QFile *f) { - int i; + int i; - for (i=0 ; i<256 ; i++) + for (i = 0; i < 256; i++) if (keybindings[i]) - Qprintf (f, "bind \"%s\" \"%s\"\n", Key_KeynumToString(i), keybindings[i]); // 1999-12-26 bound keys not saved in quotes fix by Maddes + Qprintf (f, "bind \"%s\" \"%s\"\n", Key_KeynumToString (i), + keybindings[i]); // 1999-12-26 bound keys not saved in + // quotes fix by Maddes } @@ -691,12 +685,11 @@ Key_Init =================== */ void -Key_Init ( void ) +Key_Init (void) { - int i; + int i; - for (i=0 ; i<32 ; i++) - { + for (i = 0; i < 32; i++) { key_lines[i][0] = ']'; key_lines[i][1] = 0; } @@ -705,7 +698,7 @@ Key_Init ( void ) // // init ascii characters in console mode // - for (i=32 ; i<128 ; i++) + for (i = 32; i < 128; i++) consolekeys[i] = true; consolekeys[K_ENTER] = true; consolekeys[K_TAB] = true; @@ -725,9 +718,9 @@ Key_Init ( void ) consolekeys['`'] = false; consolekeys['~'] = false; - for (i=0 ; i<256 ; i++) + for (i = 0; i < 256; i++) keyshift[i] = i; - for (i='a' ; i<='z' ; i++) + for (i = 'a'; i <= 'z'; i++) keyshift[i] = i - 'a' + 'A'; keyshift['1'] = '!'; keyshift['2'] = '@'; @@ -752,8 +745,8 @@ Key_Init ( void ) keyshift['\\'] = '|'; menubound[K_ESCAPE] = true; - for (i=0 ; i<12 ; i++) - menubound[K_F1+i] = true; + for (i = 0; i < 12; i++) + menubound[K_F1 + i] = true; // // register our functions @@ -764,11 +757,11 @@ Key_Init ( void ) } void -Key_Init_Cvars ( void ) +Key_Init_Cvars (void) { cl_chatmode = Cvar_Get ("cl_chatmode", "2", 0, - "Controls when console text will be treated as a chat message\n" - "0 - never, 1 - always, 2 - smart"); + "Controls when console text will be treated as a chat message\n" + "0 - never, 1 - always, 2 - smart"); } /* @@ -780,12 +773,12 @@ Should NOT be called during an interrupt! =================== */ void -Key_Event ( int key, int alt_key, qboolean down ) +Key_Event (int key, int alt_key, qboolean down) { - char *kb; - char cmd[1024]; + char *kb; + char cmd[1024]; -// Con_Printf ("%i : %i\n", key, down); //@@@ +// Con_Printf ("%i : %i\n", key, down); //@@@ // They don't prove it, fall back to interal MESS. if (alt_key == -1) { @@ -802,22 +795,20 @@ Key_Event ( int key, int alt_key, qboolean down ) key_lastpress = key; // update auto-repeat status - if (down) - { + if (down) { key_repeats[key]++; - if (key_repeats[key] > 1) - { + if (key_repeats[key] > 1) { if ((key != K_BACKSPACE && key != K_DEL - && key != K_LEFTARROW && key != K_RIGHTARROW - && key != K_PGUP && key != K_PGDN) - || (key_dest == key_game && cls.state == ca_active)) - return; // ignore most autorepeats + && key != K_LEFTARROW && key != K_RIGHTARROW + && key != K_PGUP && key != K_PGDN) + || (key_dest == key_game && cls.state == ca_active)) + return; // ignore most autorepeats } if (key >= 200 && !keybindings[key]) - Con_Printf ("%s is unbound, hit F4 to set.\n", Key_KeynumToString (key) ); + Con_Printf ("%s is unbound, hit F4 to set.\n", + Key_KeynumToString (key)); } - // Exit message mode is disconnected if (key_dest == key_message && cls.state != ca_active) key_dest = key_console; @@ -825,28 +816,25 @@ Key_Event ( int key, int alt_key, qboolean down ) // // handle escape specialy, so the user can never unbind it // - if (key == K_ESCAPE) - { + if (key == K_ESCAPE) { if (!down) return; - switch (key_dest) - { - case key_message: - Key_Message (key); - break; - case key_menu: - M_Keydown (key); - break; - case key_game: - case key_console: - M_ToggleMenu_f (); - break; - default: - Sys_Error ("Bad key_dest"); + switch (key_dest) { + case key_message: + Key_Message (key); + break; + case key_menu: + M_Keydown (key); + break; + case key_game: + case key_console: + M_ToggleMenu_f (); + break; + default: + Sys_Error ("Bad key_dest"); } return; } - // // key up events only generate commands if the game key binding is // a button command (leading + sign). These will occur even in console mode, @@ -854,50 +842,44 @@ Key_Event ( int key, int alt_key, qboolean down ) // switch. Button commands include the kenum as a parameter, so multiple // downs can be matched with ups // - if (!down) - { + if (!down) { kb = keybindings[key]; if (kb && kb[0] == '+') { - snprintf (cmd, sizeof(cmd), "-%s %i\n", kb+1, key); + snprintf (cmd, sizeof (cmd), "-%s %i\n", kb + 1, key); Cbuf_AddText (cmd); } - if (islower(key)) { - kb = keybindings[toupper(key)]; + if (islower (key)) { + kb = keybindings[toupper (key)]; if (kb && kb[0] == '+') { - snprintf (cmd, sizeof(cmd), "-%s %i\n", kb+1, key); + snprintf (cmd, sizeof (cmd), "-%s %i\n", kb + 1, key); Cbuf_AddText (cmd); } } return; } - // // during demo playback, most keys bring up the main menu // if (cls.demoplayback && down && consolekeys[key] && key_dest == key_game - && key != K_CTRL && key != K_DEL && key != K_HOME && key != K_END && key != K_TAB) - { + && key != K_CTRL && key != K_DEL && key != K_HOME && key != K_END + && key != K_TAB) { M_ToggleMenu_f (); return; } - // // if not a consolekey, send to the interpreter no matter what mode is // - if ( (key_dest == key_menu && menubound[key]) - || (key_dest == key_console && !consolekeys[key]) - || (key_dest == key_game && ( cls.state == ca_active || !consolekeys[key] ) ) ) - { + if ((key_dest == key_menu && menubound[key]) + || (key_dest == key_console && !consolekeys[key]) + || (key_dest == key_game + && (cls.state == ca_active || !consolekeys[key]))) { kb = keybindings[key]; - if (kb) - { - if (kb[0] == '+') - { // button commands add keynum as a parm - snprintf (cmd, sizeof(cmd), "%s %i\n", kb, key); + if (kb) { + if (kb[0] == '+') { // button commands add keynum as a + // parm + snprintf (cmd, sizeof (cmd), "%s %i\n", kb, key); Cbuf_AddText (cmd); - } - else - { + } else { Cbuf_AddText (kb); Cbuf_AddText ("\n"); } @@ -906,26 +888,26 @@ Key_Event ( int key, int alt_key, qboolean down ) } if (!down) - return; // other systems only care about key down events + return; // other systems only care about key + // down events if (alt_key > 0) key = alt_key; - switch (key_dest) - { - case key_message: - Key_Message (key); - break; - case key_menu: - M_Keydown (key); - break; + switch (key_dest) { + case key_message: + Key_Message (key); + break; + case key_menu: + M_Keydown (key); + break; - case key_game: - case key_console: - Key_Console (key); - break; - default: - Sys_Error ("Bad key_dest"); + case key_game: + case key_console: + Key_Console (key); + break; + default: + Sys_Error ("Bad key_dest"); } } @@ -935,12 +917,11 @@ Key_ClearStates =================== */ void -Key_ClearStates ( void ) +Key_ClearStates (void) { - int i; + int i; - for (i=0 ; i<256 ; i++) - { + for (i = 0; i < 256; i++) { keydown[i] = false; key_repeats[i] = false; } diff --git a/source/link.c b/source/link.c index 193d836..883b1dc 100644 --- a/source/link.c +++ b/source/link.c @@ -27,34 +27,38 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "link.h" // ClearLink is used for new headnodes -void ClearLink (link_t *l) +void +ClearLink (link_t *l) { l->prev = l->next = l; } -void RemoveLink (link_t *l) +void +RemoveLink (link_t *l) { l->next->prev = l->prev; l->prev->next = l->next; } -void InsertLinkBefore (link_t *l, link_t *before) +void +InsertLinkBefore (link_t *l, link_t *before) { l->next = before; l->prev = before->prev; l->prev->next = l; l->next->prev = l; } -void InsertLinkAfter (link_t *l, link_t *after) + +void +InsertLinkAfter (link_t *l, link_t *after) { l->next = after->next; l->prev = after; l->prev->next = l; l->next->prev = l; } - diff --git a/source/locs.c b/source/locs.c index c873cdf..c4dacf6 100644 --- a/source/locs.c +++ b/source/locs.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -39,28 +39,29 @@ #include "locs.h" #include "console.h" -#define LOCATION_BLOCK 128 // 128 locations per block. +#define LOCATION_BLOCK 128 // 128 locations per block. -location_t **locations = NULL; -int locations_alloced = 0; -int locations_count = 0; -int location_blocks = 0; +location_t **locations = NULL; +int locations_alloced = 0; +int locations_count = 0; +int location_blocks = 0; -void locs_add(vec3_t location, char *name); -void locs_load(char *mapname); -void locs_free(); -void locs_more(); +void locs_add (vec3_t location, char *name); +void locs_load (char *mapname); +void locs_free (); +void locs_more (); -location_t *locs_find(vec3_t target) +location_t * +locs_find (vec3_t target) { - location_t *best = NULL, *cur; - float best_distance = 9999999, distance; - int i; + location_t *best = NULL, *cur; + float best_distance = 9999999, distance; + int i; for (i = 0; i < locations_count; i++) { cur = locations[i]; - distance = VectorDistance_fast(target, cur->loc); - //distance = VectorDistance(target, cur->loc); + distance = VectorDistance_fast (target, cur->loc); + // distance = VectorDistance(target, cur->loc); if ((distance < best_distance) || !best) { best = cur; best_distance = distance; @@ -70,48 +71,51 @@ location_t *locs_find(vec3_t target) return best; } -void locs_add(vec3_t location, char *name) +void +locs_add (vec3_t location, char *name) { - int num; + int num; locations_count++; if (locations_count >= locations_alloced) - locs_more(); + locs_more (); num = locations_count - 1; - locations[num] = malloc(sizeof(location_t)); + locations[num] = malloc (sizeof (location_t)); + locations[num]->loc[0] = location[0]; locations[num]->loc[1] = location[1]; locations[num]->loc[2] = location[2]; - locations[num]->name = strdup(name); + locations[num]->name = strdup (name); if (!locations[num]->name) - Sys_Error("locs_add: Can't strdup name!"); + Sys_Error ("locs_add: Can't strdup name!"); } -void locs_load(char *mapname) +void +locs_load (char *mapname) { - QFile *file; - char *line, *t1, *t2; - vec3_t loc; - char tmp[PATH_MAX]; + QFile *file; + char *line, *t1, *t2; + vec3_t loc; + char tmp[PATH_MAX]; - snprintf(tmp, sizeof(tmp), "maps/%s.loc", mapname); - COM_FOpenFile(tmp, &file); + snprintf (tmp, sizeof (tmp), "maps/%s.loc", mapname); + COM_FOpenFile (tmp, &file); if (!file) { - Con_Printf("Couldn't load %s\n", tmp); + Con_Printf ("Couldn't load %s\n", tmp); return; } - while ((line = Qgetline(file))) { + while ((line = Qgetline (file))) { if (line[0] == '#') continue; - loc[0] = strtol(line, &t1, 0) * (1.0/8); - loc[1] = strtol(t1, &t2, 0) * (1.0/8); - loc[2] = strtol(t2, &t1, 0) * (1.0/8); + loc[0] = strtol (line, &t1, 0) * (1.0 / 8); + loc[1] = strtol (t1, &t2, 0) * (1.0 / 8); + loc[2] = strtol (t2, &t1, 0) * (1.0 / 8); t1++; - t2 = strrchr(t1, '\n'); + t2 = strrchr (t1, '\n'); if (t2) { t2[0] = '\0'; // handle dos format lines (COM_FOpenFile is binary only) @@ -119,40 +123,42 @@ void locs_load(char *mapname) if (t2 > t1 && t2[-1] == '\r') t2[-1] = '\0'; } - locs_add(loc, t1); + locs_add (loc, t1); } - Qclose(file); + Qclose (file); } -void locs_reset() +void +locs_reset () { - int i; + int i; for (i = 0; i < locations_count; i++) { - free((void *) locations[i]->name); - free((void *) locations[i]); + free ((void *) locations[i]->name); + free ((void *) locations[i]); locations[i] = NULL; } - free(locations); + free (locations); locations_alloced = 0; locations_count = 0; locations = NULL; } -void locs_more() +void +locs_more () { - size_t size; + size_t size; location_blocks++; locations_alloced += LOCATION_BLOCK; - size = (sizeof(location_t *) * LOCATION_BLOCK * location_blocks); + size = (sizeof (location_t *) * LOCATION_BLOCK * location_blocks); if (locations) - locations = realloc(locations, size); + locations = realloc (locations, size); else - locations = malloc(size); + locations = malloc (size); if (!locations) - Sys_Error("ERROR! Can not alloc memory for location block!"); + Sys_Error ("ERROR! Can not alloc memory for location block!"); } diff --git a/source/mathlib.c b/source/mathlib.c index 4701a8e..7f148bd 100644 --- a/source/mathlib.c +++ b/source/mathlib.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -37,24 +37,25 @@ #include "mathlib.h" #include "model.h" -void Sys_Error (char *error, ...); +void Sys_Error (char *error, ...); -vec3_t vec3_origin = {0,0,0}; -int nanmask = 255<<23; +vec3_t vec3_origin = { 0, 0, 0 }; +int nanmask = 255 << 23; /*-----------------------------------------------------------------*/ #define DEG2RAD( a ) ( a * M_PI ) / 180.0F -void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) +void +ProjectPointOnPlane (vec3_t dst, const vec3_t p, const vec3_t normal) { - float d; - vec3_t n; - float inv_denom; + float d; + vec3_t n; + float inv_denom; - inv_denom = 1.0F / DotProduct( normal, normal ); + inv_denom = 1.0F / DotProduct (normal, normal); - d = DotProduct( normal, p ) * inv_denom; + d = DotProduct (normal, p) * inv_denom; n[0] = normal[0] * inv_denom; n[1] = normal[1] * inv_denom; @@ -68,36 +69,32 @@ void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) /* ** assumes "src" is normalized */ -void PerpendicularVector( vec3_t dst, const vec3_t src ) +void +PerpendicularVector (vec3_t dst, const vec3_t src) { - int pos; - int i; - float minelem = 1.0F; - vec3_t tempvec; + int pos; + int i; + float minelem = 1.0F; + vec3_t tempvec; - /* - ** find the smallest magnitude axially aligned vector - */ - for ( pos = 0, i = 0; i < 3; i++ ) - { - if ( fabs( src[i] ) < minelem ) - { + /* + ** find the smallest magnitude axially aligned vector */ + for (pos = 0, i = 0; i < 3; i++) { + if (fabs (src[i]) < minelem) { pos = i; - minelem = fabs( src[i] ); + minelem = fabs (src[i]); } } tempvec[0] = tempvec[1] = tempvec[2] = 0.0F; tempvec[pos] = 1.0F; - /* - ** project the point onto the plane defined by src - */ - ProjectPointOnPlane( dst, tempvec, src ); + /* + ** project the point onto the plane defined by src */ + ProjectPointOnPlane (dst, tempvec, src); - /* - ** normalize the result - */ - VectorNormalize( dst ); + /* + ** normalize the result */ + VectorNormalize (dst); } #if defined(_WIN32) && !defined(__GNUC__) @@ -105,22 +102,24 @@ void PerpendicularVector( vec3_t dst, const vec3_t src ) #endif -void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees ) +void +RotatePointAroundVector (vec3_t dst, const vec3_t dir, const vec3_t point, + float degrees) { - float m[3][3]; - float im[3][3]; - float zrot[3][3]; - float tmpmat[3][3]; - float rot[3][3]; - int i; - vec3_t vr, vup, vf; + float m[3][3]; + float im[3][3]; + float zrot[3][3]; + float tmpmat[3][3]; + float rot[3][3]; + int i; + vec3_t vr, vup, vf; vf[0] = dir[0]; vf[1] = dir[1]; vf[2] = dir[2]; - PerpendicularVector( vr, dir ); - CrossProduct( vr, vf, vup ); + PerpendicularVector (vr, dir); + CrossProduct (vr, vf, vup); m[0][0] = vr[0]; m[1][0] = vr[1]; @@ -134,7 +133,7 @@ void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, m[1][2] = vf[1]; m[2][2] = vf[2]; - memcpy( im, m, sizeof( im ) ); + memcpy (im, m, sizeof (im)); im[0][1] = m[1][0]; im[0][2] = m[2][0]; @@ -143,20 +142,20 @@ void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, im[2][0] = m[0][2]; im[2][1] = m[1][2]; - memset( zrot, 0, sizeof( zrot ) ); + memset (zrot, 0, sizeof (zrot)); zrot[0][0] = zrot[1][1] = zrot[2][2] = 1.0F; - zrot[0][0] = cos( DEG2RAD( degrees ) ); - zrot[0][1] = sin( DEG2RAD( degrees ) ); - zrot[1][0] = -sin( DEG2RAD( degrees ) ); - zrot[1][1] = cos( DEG2RAD( degrees ) ); + zrot[0][0] = cos (DEG2RAD (degrees)); + zrot[0][1] = sin (DEG2RAD (degrees)); + zrot[1][0] = -sin (DEG2RAD (degrees)); + zrot[1][1] = cos (DEG2RAD (degrees)); - R_ConcatRotations( m, zrot, tmpmat ); - R_ConcatRotations( tmpmat, im, rot ); + R_ConcatRotations (m, zrot, tmpmat); + R_ConcatRotations (tmpmat, im, rot); - for ( i = 0; i < 3; i++ ) - { - dst[i] = rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2]; + for (i = 0; i < 3; i++) { + dst[i] = + rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2]; } } @@ -166,15 +165,16 @@ void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, /*-----------------------------------------------------------------*/ -float anglemod(float a) +float +anglemod (float a) { #if 0 if (a >= 0) - a -= 360*(int)(a/360); + a -= 360 * (int) (a / 360); else - a += 360*( 1 + (int)(-a/360) ); + a += 360 * (1 + (int) (-a / 360)); #endif - a = (360.0/65536) * ((int)(a*(65536/360.0)) & 65535); + a = (360.0 / 65536) * ((int) (a * (65536 / 360.0)) & 65535); return a; } @@ -185,7 +185,8 @@ BOPS_Error Split out like this for ASM to call. ================== */ -void BOPS_Error (void) +void +BOPS_Error (void) { Sys_Error ("BoxOnPlaneSide: Bad signbits"); } @@ -199,16 +200,18 @@ BoxOnPlaneSide Returns 1, 2, or 1 + 2 ================== */ -int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, mplane_t *p) +int +BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, mplane_t *p) { - float dist1, dist2; - int sides; + float dist1, dist2; + int sides; -#if 0 // this is done by the BOX_ON_PLANE_SIDE macro before calling this - // function +#if 0 // this is done by the + // BOX_ON_PLANE_SIDE macro before + // calling this + // function // fast axial cases - if (p->type < 3) - { + if (p->type < 3) { if (p->dist <= emins[p->type]) return 1; if (p->dist >= emaxs[p->type]) @@ -216,61 +219,88 @@ int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, mplane_t *p) return 3; } #endif - + // general case - switch (p->signbits) - { - case 0: -dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; -dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; - break; - case 1: -dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; -dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; - break; - case 2: -dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; -dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; - break; - case 3: -dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; -dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; - break; - case 4: -dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; -dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; - break; - case 5: -dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; -dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; - break; - case 6: -dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; -dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; - break; - case 7: -dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; -dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; - break; - default: - dist1 = dist2 = 0; // shut up compiler - BOPS_Error (); - break; + switch (p->signbits) { + case 0: + dist1 = + p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emaxs[2]; + dist2 = + p->normal[0] * emins[0] + p->normal[1] * emins[1] + + p->normal[2] * emins[2]; + break; + case 1: + dist1 = + p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emaxs[2]; + dist2 = + p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + + p->normal[2] * emins[2]; + break; + case 2: + dist1 = + p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + + p->normal[2] * emaxs[2]; + dist2 = + p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emins[2]; + break; + case 3: + dist1 = + p->normal[0] * emins[0] + p->normal[1] * emins[1] + + p->normal[2] * emaxs[2]; + dist2 = + p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emins[2]; + break; + case 4: + dist1 = + p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emins[2]; + dist2 = + p->normal[0] * emins[0] + p->normal[1] * emins[1] + + p->normal[2] * emaxs[2]; + break; + case 5: + dist1 = + p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emins[2]; + dist2 = + p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + + p->normal[2] * emaxs[2]; + break; + case 6: + dist1 = + p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + + p->normal[2] * emins[2]; + dist2 = + p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emaxs[2]; + break; + case 7: + dist1 = + p->normal[0] * emins[0] + p->normal[1] * emins[1] + + p->normal[2] * emins[2]; + dist2 = + p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + + p->normal[2] * emaxs[2]; + break; + default: + dist1 = dist2 = 0; // shut up compiler + BOPS_Error (); + break; } #if 0 - int i; - vec3_t corners[2]; + int i; + vec3_t corners[2]; - for (i=0 ; i<3 ; i++) - { - if (plane->normal[i] < 0) - { + for (i = 0; i < 3; i++) { + if (plane->normal[i] < 0) { corners[0][i] = emins[i]; corners[1][i] = emaxs[i]; - } - else - { + } else { corners[1][i] = emins[i]; corners[0][i] = emaxs[i]; } @@ -292,8 +322,8 @@ dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; sides |= 2; #ifdef PARANOID -if (sides == 0) - Sys_Error ("BoxOnPlaneSide: sides==0"); + if (sides == 0) + Sys_Error ("BoxOnPlaneSide: sides==0"); #endif return sides; @@ -302,137 +332,150 @@ if (sides == 0) #endif -void AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) +void +AngleVectors (vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) { - float angle; - float sr, sp, sy, cr, cp, cy; - - angle = angles[YAW] * (M_PI*2 / 360); - sy = sin(angle); - cy = cos(angle); - angle = angles[PITCH] * (M_PI*2 / 360); - sp = sin(angle); - cp = cos(angle); - angle = angles[ROLL] * (M_PI*2 / 360); - sr = sin(angle); - cr = cos(angle); + float angle; + float sr, sp, sy, cr, cp, cy; - forward[0] = cp*cy; - forward[1] = cp*sy; + angle = angles[YAW] * (M_PI * 2 / 360); + sy = sin (angle); + cy = cos (angle); + angle = angles[PITCH] * (M_PI * 2 / 360); + sp = sin (angle); + cp = cos (angle); + angle = angles[ROLL] * (M_PI * 2 / 360); + sr = sin (angle); + cr = cos (angle); + + forward[0] = cp * cy; + forward[1] = cp * sy; forward[2] = -sp; - right[0] = (-1*sr*sp*cy+-1*cr*-sy); - right[1] = (-1*sr*sp*sy+-1*cr*cy); - right[2] = -1*sr*cp; - up[0] = (cr*sp*cy+-sr*-sy); - up[1] = (cr*sp*sy+-sr*cy); - up[2] = cr*cp; + right[0] = (-1 * sr * sp * cy + -1 * cr * -sy); + right[1] = (-1 * sr * sp * sy + -1 * cr * cy); + right[2] = -1 * sr * cp; + up[0] = (cr * sp * cy + -sr * -sy); + up[1] = (cr * sp * sy + -sr * cy); + up[2] = cr * cp; } -int VectorCompare (vec3_t v1, vec3_t v2) +int +VectorCompare (vec3_t v1, vec3_t v2) { - int i; - - for (i=0 ; i<3 ; i++) + int i; + + for (i = 0; i < 3; i++) if (v1[i] != v2[i]) return 0; - + return 1; } -void VectorMA (vec3_t veca, float scale, vec3_t vecb, vec3_t vecc) +void +VectorMA (vec3_t veca, float scale, vec3_t vecb, vec3_t vecc) { - vecc[0] = veca[0] + scale*vecb[0]; - vecc[1] = veca[1] + scale*vecb[1]; - vecc[2] = veca[2] + scale*vecb[2]; + vecc[0] = veca[0] + scale * vecb[0]; + vecc[1] = veca[1] + scale * vecb[1]; + vecc[2] = veca[2] + scale * vecb[2]; } -vec_t _DotProduct (vec3_t v1, vec3_t v2) +vec_t +_DotProduct (vec3_t v1, vec3_t v2) { - return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; + return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } -void _VectorSubtract (vec3_t veca, vec3_t vecb, vec3_t out) +void +_VectorSubtract (vec3_t veca, vec3_t vecb, vec3_t out) { - out[0] = veca[0]-vecb[0]; - out[1] = veca[1]-vecb[1]; - out[2] = veca[2]-vecb[2]; + out[0] = veca[0] - vecb[0]; + out[1] = veca[1] - vecb[1]; + out[2] = veca[2] - vecb[2]; } -void _VectorAdd (vec3_t veca, vec3_t vecb, vec3_t out) +void +_VectorAdd (vec3_t veca, vec3_t vecb, vec3_t out) { - out[0] = veca[0]+vecb[0]; - out[1] = veca[1]+vecb[1]; - out[2] = veca[2]+vecb[2]; + out[0] = veca[0] + vecb[0]; + out[1] = veca[1] + vecb[1]; + out[2] = veca[2] + vecb[2]; } -void _VectorCopy (vec3_t in, vec3_t out) +void +_VectorCopy (vec3_t in, vec3_t out) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; } -void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross) +void +CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross) { - cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; - cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; - cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; + cross[0] = v1[1] * v2[2] - v1[2] * v2[1]; + cross[1] = v1[2] * v2[0] - v1[0] * v2[2]; + cross[2] = v1[0] * v2[1] - v1[1] * v2[0]; } -double sqrt(double x); +double sqrt (double x); -vec_t Length(vec3_t v) +vec_t +Length (vec3_t v) { - int i; - float length; - + int i; + float length; + length = 0; - for (i=0 ; i< 3 ; i++) - length += v[i]*v[i]; - length = sqrt (length); // FIXME + for (i = 0; i < 3; i++) + length += v[i] * v[i]; + length = sqrt (length); // FIXME return length; } -float VectorNormalize (vec3_t v) +float +VectorNormalize (vec3_t v) { - float length, ilength; + float length, ilength; - length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; - length = sqrt (length); // FIXME + length = v[0] * v[0] + v[1] * v[1] + v[2] * v[2]; + length = sqrt (length); // FIXME - if (length) - { - ilength = 1/length; + if (length) { + ilength = 1 / length; v[0] *= ilength; v[1] *= ilength; v[2] *= ilength; } - + return length; } -void VectorInverse (vec3_t v) +void +VectorInverse (vec3_t v) { v[0] = -v[0]; v[1] = -v[1]; v[2] = -v[2]; } -void VectorScale (vec3_t in, vec_t scale, vec3_t out) +void +VectorScale (vec3_t in, vec_t scale, vec3_t out) { - out[0] = in[0]*scale; - out[1] = in[1]*scale; - out[2] = in[2]*scale; + out[0] = in[0] * scale; + out[1] = in[1] * scale; + out[2] = in[2] * scale; } -int Q_log2(int val) +int +Q_log2 (int val) { - int answer=0; - while ((val>>=1) != 0) + int answer = 0; + + while ((val >>= 1) != 0) answer++; return answer; } @@ -443,26 +486,27 @@ int Q_log2(int val) R_ConcatRotations ================ */ -void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]) +void +R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + - in1[0][2] * in2[2][0]; + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + - in1[0][2] * in2[2][1]; + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + - in1[0][2] * in2[2][2]; + in1[0][2] * in2[2][2]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + - in1[1][2] * in2[2][0]; + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + - in1[1][2] * in2[2][1]; + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + - in1[1][2] * in2[2][2]; + in1[1][2] * in2[2][2]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + - in1[2][2] * in2[2][0]; + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + - in1[2][2] * in2[2][1]; + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + - in1[2][2] * in2[2][2]; + in1[2][2] * in2[2][2]; } @@ -471,32 +515,33 @@ void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]) R_ConcatTransforms ================ */ -void R_ConcatTransforms (float in1[3][4], float in2[3][4], float out[3][4]) +void +R_ConcatTransforms (float in1[3][4], float in2[3][4], float out[3][4]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + - in1[0][2] * in2[2][0]; + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + - in1[0][2] * in2[2][1]; + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + - in1[0][2] * in2[2][2]; + in1[0][2] * in2[2][2]; out[0][3] = in1[0][0] * in2[0][3] + in1[0][1] * in2[1][3] + - in1[0][2] * in2[2][3] + in1[0][3]; + in1[0][2] * in2[2][3] + in1[0][3]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + - in1[1][2] * in2[2][0]; + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + - in1[1][2] * in2[2][1]; + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + - in1[1][2] * in2[2][2]; + in1[1][2] * in2[2][2]; out[1][3] = in1[1][0] * in2[0][3] + in1[1][1] * in2[1][3] + - in1[1][2] * in2[2][3] + in1[1][3]; + in1[1][2] * in2[2][3] + in1[1][3]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + - in1[2][2] * in2[2][0]; + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + - in1[2][2] * in2[2][1]; + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + - in1[2][2] * in2[2][2]; + in1[2][2] * in2[2][2]; out[2][3] = in1[2][0] * in2[0][3] + in1[2][1] * in2[1][3] + - in1[2][2] * in2[2][3] + in1[2][3]; + in1[2][2] * in2[2][3] + in1[2][3]; } @@ -510,40 +555,37 @@ quotient must fit in 32 bits. ==================== */ -void FloorDivMod (double numer, double denom, int *quotient, - int *rem) +void +FloorDivMod (double numer, double denom, int *quotient, int *rem) { - int q, r; - double x; + int q, r; + double x; #ifndef PARANOID if (denom <= 0.0) Sys_Error ("FloorDivMod: bad denominator %d\n", denom); -// if ((floor(numer) != numer) || (floor(denom) != denom)) -// Sys_Error ("FloorDivMod: non-integer numer or denom %f %f\n", -// numer, denom); +// if ((floor(numer) != numer) || (floor(denom) != denom)) +// Sys_Error ("FloorDivMod: non-integer numer or denom %f %f\n", +// numer, denom); #endif - if (numer >= 0.0) - { + if (numer >= 0.0) { - x = floor(numer / denom); - q = (int)x; - r = (int)floor(numer - (x * denom)); - } - else - { - // - // perform operations with positive values, and fix mod to make floor-based - // - x = floor(-numer / denom); - q = -(int)x; - r = (int)floor(-numer - (x * denom)); - if (r != 0) - { + x = floor (numer / denom); + q = (int) x; + r = (int) floor (numer - (x * denom)); + } else { + // + // perform operations with positive values, and fix mod to make + // floor-based + // + x = floor (-numer / denom); + q = -(int) x; + r = (int) floor (-numer - (x * denom)); + if (r != 0) { q--; - r = (int)denom - r; + r = (int) denom - r; } } @@ -557,16 +599,14 @@ void FloorDivMod (double numer, double denom, int *quotient, GreatestCommonDivisor ==================== */ -int GreatestCommonDivisor (int i1, int i2) +int +GreatestCommonDivisor (int i1, int i2) { - if (i1 > i2) - { + if (i1 > i2) { if (i2 == 0) return (i1); return GreatestCommonDivisor (i2, i1 % i2); - } - else - { + } else { if (i1 == 0) return (i2); return GreatestCommonDivisor (i1, i2 % i1); @@ -586,13 +626,14 @@ Inverts an 8.24 value to a 16.16 value ==================== */ -fixed16_t Invert24To16(fixed16_t val) +fixed16_t +Invert24To16 (fixed16_t val) { if (val < 256) return (0xFFFFFFFF); return (fixed16_t) - (((double)0x10000 * (double)0x1000000 / (double)val) + 0.5); + (((double) 0x10000 * (double) 0x1000000 / (double) val) + 0.5); } #endif diff --git a/source/mdfour.c b/source/mdfour.c index a30f085..c88c2e1 100644 --- a/source/mdfour.c +++ b/source/mdfour.c @@ -28,17 +28,17 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif -#include /* XoXus: needed for memset call */ +#include /* XoXus: needed for memset call */ #ifndef _UINT32_H #include -#endif // _UINT32_H +#endif // _UINT32_H #ifndef _MDFOUR_H #include -#endif // _MDFOUR_H +#endif // _MDFOUR_H /* NOTE: This code makes no attempt to be fast! @@ -61,77 +61,119 @@ static struct mdfour *m; #define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) /* this applies md4 to 64 byte chunks */ -static void mdfour64(uint32 *M) +static void +mdfour64 (uint32 * M) { - int j; - uint32 AA, BB, CC, DD; - uint32 X[16]; - uint32 A,B,C,D; + int j; + uint32 AA, BB, CC, DD; + uint32 X[16]; + uint32 A, B, C, D; - for (j=0;j<16;j++) + for (j = 0; j < 16; j++) X[j] = M[j]; - A = m->A; B = m->B; C = m->C; D = m->D; - AA = A; BB = B; CC = C; DD = D; + A = m->A; + B = m->B; + C = m->C; + D = m->D; + AA = A; + BB = B; + CC = C; + DD = D; - ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); - ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); - ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); - ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); - ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); - ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); - ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); - ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); + ROUND1 (A, B, C, D, 0, 3); + ROUND1 (D, A, B, C, 1, 7); + ROUND1 (C, D, A, B, 2, 11); + ROUND1 (B, C, D, A, 3, 19); + ROUND1 (A, B, C, D, 4, 3); + ROUND1 (D, A, B, C, 5, 7); + ROUND1 (C, D, A, B, 6, 11); + ROUND1 (B, C, D, A, 7, 19); + ROUND1 (A, B, C, D, 8, 3); + ROUND1 (D, A, B, C, 9, 7); + ROUND1 (C, D, A, B, 10, 11); + ROUND1 (B, C, D, A, 11, 19); + ROUND1 (A, B, C, D, 12, 3); + ROUND1 (D, A, B, C, 13, 7); + ROUND1 (C, D, A, B, 14, 11); + ROUND1 (B, C, D, A, 15, 19); - ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); - ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); - ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); - ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); - ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); - ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); - ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); - ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); + ROUND2 (A, B, C, D, 0, 3); + ROUND2 (D, A, B, C, 4, 5); + ROUND2 (C, D, A, B, 8, 9); + ROUND2 (B, C, D, A, 12, 13); + ROUND2 (A, B, C, D, 1, 3); + ROUND2 (D, A, B, C, 5, 5); + ROUND2 (C, D, A, B, 9, 9); + ROUND2 (B, C, D, A, 13, 13); + ROUND2 (A, B, C, D, 2, 3); + ROUND2 (D, A, B, C, 6, 5); + ROUND2 (C, D, A, B, 10, 9); + ROUND2 (B, C, D, A, 14, 13); + ROUND2 (A, B, C, D, 3, 3); + ROUND2 (D, A, B, C, 7, 5); + ROUND2 (C, D, A, B, 11, 9); + ROUND2 (B, C, D, A, 15, 13); - ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); - ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); - ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); - ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); - ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); - ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); - ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); - ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); + ROUND3 (A, B, C, D, 0, 3); + ROUND3 (D, A, B, C, 8, 9); + ROUND3 (C, D, A, B, 4, 11); + ROUND3 (B, C, D, A, 12, 15); + ROUND3 (A, B, C, D, 2, 3); + ROUND3 (D, A, B, C, 10, 9); + ROUND3 (C, D, A, B, 6, 11); + ROUND3 (B, C, D, A, 14, 15); + ROUND3 (A, B, C, D, 1, 3); + ROUND3 (D, A, B, C, 9, 9); + ROUND3 (C, D, A, B, 5, 11); + ROUND3 (B, C, D, A, 13, 15); + ROUND3 (A, B, C, D, 3, 3); + ROUND3 (D, A, B, C, 11, 9); + ROUND3 (C, D, A, B, 7, 11); + ROUND3 (B, C, D, A, 15, 15); - A += AA; B += BB; C += CC; D += DD; + A += AA; + B += BB; + C += CC; + D += DD; #ifdef LARGE_INT32 - A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; - C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; + A &= 0xFFFFFFFF; + B &= 0xFFFFFFFF; + C &= 0xFFFFFFFF; + D &= 0xFFFFFFFF; #endif - for (j=0;j<16;j++) + for (j = 0; j < 16; j++) X[j] = 0; - m->A = A; m->B = B; m->C = C; m->D = D; + m->A = A; + m->B = B; + m->C = C; + m->D = D; } -static void copy64(uint32 *M, unsigned char *in) +static void +copy64 (uint32 * M, unsigned char *in) { - int i; + int i; - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); + for (i = 0; i < 16; i++) + M[i] = (in[i * 4 + 3] << 24) | (in[i * 4 + 2] << 16) | + (in[i * 4 + 1] << 8) | (in[i * 4 + 0] << 0); } -static void copy4(unsigned char *out,uint32 x) +static void +copy4 (unsigned char *out, uint32 x) { - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; + out[0] = x & 0xFF; + out[1] = (x >> 8) & 0xFF; + out[2] = (x >> 16) & 0xFF; + out[3] = (x >> 24) & 0xFF; } -void mdfour_begin(struct mdfour *md) +void +mdfour_begin (struct mdfour *md) { md->A = 0x67452301; md->B = 0xefcdab89; @@ -141,69 +183,75 @@ void mdfour_begin(struct mdfour *md) } -static void mdfour_tail(unsigned char *in, int n) +static void +mdfour_tail (unsigned char *in, int n) { unsigned char buf[128]; - uint32 M[16]; - uint32 b; + uint32 M[16]; + uint32 b; m->totalN += n; b = m->totalN * 8; - memset(buf, 0, 128); - if (n) memcpy(buf, in, n); + memset (buf, 0, 128); + if (n) + memcpy (buf, in, n); buf[n] = 0x80; if (n <= 55) { - copy4(buf+56, b); - copy64(M, buf); - mdfour64(M); + copy4 (buf + 56, b); + copy64 (M, buf); + mdfour64 (M); } else { - copy4(buf+120, b); - copy64(M, buf); - mdfour64(M); - copy64(M, buf+64); - mdfour64(M); + copy4 (buf + 120, b); + copy64 (M, buf); + mdfour64 (M); + copy64 (M, buf + 64); + mdfour64 (M); } } -void mdfour_update(struct mdfour *md, unsigned char *in, int n) +void +mdfour_update (struct mdfour *md, unsigned char *in, int n) { - uint32 M[16]; + uint32 M[16]; - if (n == 0) mdfour_tail(in, n); + if (n == 0) + mdfour_tail (in, n); m = md; while (n >= 64) { - copy64(M, in); - mdfour64(M); + copy64 (M, in); + mdfour64 (M); in += 64; n -= 64; m->totalN += 64; } - mdfour_tail(in, n); + mdfour_tail (in, n); } -void mdfour_result(struct mdfour *md, unsigned char *out) +void +mdfour_result (struct mdfour *md, unsigned char *out) { m = md; - copy4(out, m->A); - copy4(out+4, m->B); - copy4(out+8, m->C); - copy4(out+12, m->D); + copy4 (out, m->A); + copy4 (out + 4, m->B); + copy4 (out + 8, m->C); + copy4 (out + 12, m->D); } -void mdfour(unsigned char *out, unsigned char *in, int n) +void +mdfour (unsigned char *out, unsigned char *in, int n) { struct mdfour md; - mdfour_begin(&md); - mdfour_update(&md, in, n); - mdfour_result(&md, out); -} + mdfour_begin (&md); + mdfour_update (&md, in, n); + mdfour_result (&md, out); +} diff --git a/source/menu.c b/source/menu.c index ead24f1..c17afb8 100644 --- a/source/menu.c +++ b/source/menu.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -50,74 +50,78 @@ #include "cl_main.h" #include "cl_input.h" -void (*vid_menudrawfn)(void); -void (*vid_menukeyfn)(int key); +void (*vid_menudrawfn) (void); +void (*vid_menukeyfn) (int key); -enum {m_none, m_main, m_singleplayer, m_load, m_save, m_multiplayer, m_setup, m_net, m_options, m_video, m_keys, m_help, m_quit, m_serialconfig, m_modemconfig, m_lanconfig, m_gameoptions, m_search, m_sedit} m_state; +enum { m_none, m_main, m_singleplayer, m_load, m_save, m_multiplayer, m_setup, + m_net, m_options, m_video, m_keys, m_help, m_quit, m_serialconfig, + m_modemconfig, m_lanconfig, m_gameoptions, m_search, m_sedit } m_state; -void M_Menu_Main_f (void); - void M_Menu_SinglePlayer_f (void); - void M_Menu_Load_f (void); - void M_Menu_Save_f (void); - void M_Menu_MultiPlayer_f (void); - void M_Menu_SEdit_f (void); - void M_Menu_Options_f (void); - void M_Menu_Keys_f (void); - void M_Menu_Video_f (void); - void M_Menu_Help_f (void); - void M_Menu_Quit_f (void); -void M_Menu_SerialConfig_f (void); - void M_Menu_ModemConfig_f (void); -void M_Menu_LanConfig_f (void); -void M_Menu_GameOptions_f (void); -void M_Menu_Search_f (void); -void M_Menu_ServerList_f (void); +void M_Menu_Main_f (void); +void M_Menu_SinglePlayer_f (void); +void M_Menu_Load_f (void); +void M_Menu_Save_f (void); +void M_Menu_MultiPlayer_f (void); +void M_Menu_SEdit_f (void); +void M_Menu_Options_f (void); +void M_Menu_Keys_f (void); +void M_Menu_Video_f (void); +void M_Menu_Help_f (void); +void M_Menu_Quit_f (void); +void M_Menu_SerialConfig_f (void); +void M_Menu_ModemConfig_f (void); +void M_Menu_LanConfig_f (void); +void M_Menu_GameOptions_f (void); +void M_Menu_Search_f (void); +void M_Menu_ServerList_f (void); -void M_Main_Draw (void); - void M_SinglePlayer_Draw (void); - void M_Load_Draw (void); - void M_Save_Draw (void); - void M_MultiPlayer_Draw (void); - void M_Setup_Draw (void); - void M_Net_Draw (void); - void M_Options_Draw (void); - void M_Keys_Draw (void); - void M_Video_Draw (void); - void M_Help_Draw (void); - void M_Quit_Draw (void); -void M_SerialConfig_Draw (void); - void M_ModemConfig_Draw (void); -void M_LanConfig_Draw (void); -void M_GameOptions_Draw (void); -void M_Search_Draw (void); -void M_ServerList_Draw (void); +void M_Main_Draw (void); +void M_SinglePlayer_Draw (void); +void M_Load_Draw (void); +void M_Save_Draw (void); +void M_MultiPlayer_Draw (void); +void M_Setup_Draw (void); +void M_Net_Draw (void); +void M_Options_Draw (void); +void M_Keys_Draw (void); +void M_Video_Draw (void); +void M_Help_Draw (void); +void M_Quit_Draw (void); +void M_SerialConfig_Draw (void); +void M_ModemConfig_Draw (void); +void M_LanConfig_Draw (void); +void M_GameOptions_Draw (void); +void M_Search_Draw (void); +void M_ServerList_Draw (void); -void M_Main_Key (int key); - void M_SinglePlayer_Key (int key); - void M_Load_Key (int key); - void M_Save_Key (int key); - void M_MultiPlayer_Key (int key); - void M_Setup_Key (int key); - void M_Net_Key (int key); - void M_Options_Key (int key); - void M_Keys_Key (int key); - void M_Video_Key (int key); - void M_Help_Key (int key); - void M_Quit_Key (int key); -void M_SerialConfig_Key (int key); - void M_ModemConfig_Key (int key); -void M_LanConfig_Key (int key); -void M_GameOptions_Key (int key); -void M_Search_Key (int key); -void M_ServerList_Key (int key); +void M_Main_Key (int key); +void M_SinglePlayer_Key (int key); +void M_Load_Key (int key); +void M_Save_Key (int key); +void M_MultiPlayer_Key (int key); +void M_Setup_Key (int key); +void M_Net_Key (int key); +void M_Options_Key (int key); +void M_Keys_Key (int key); +void M_Video_Key (int key); +void M_Help_Key (int key); +void M_Quit_Key (int key); +void M_SerialConfig_Key (int key); +void M_ModemConfig_Key (int key); +void M_LanConfig_Key (int key); +void M_GameOptions_Key (int key); +void M_Search_Key (int key); +void M_ServerList_Key (int key); -qboolean m_entersound; // play after drawing a frame, so caching +qboolean m_entersound; // play after drawing a frame, so + + // caching // won't disrupt the sound -qboolean m_recursiveDraw; +qboolean m_recursiveDraw; -int m_return_state; -qboolean m_return_onerror; -char m_return_reason [32]; +int m_return_state; +qboolean m_return_onerror; +char m_return_reason[32]; #define StartingGame (m_multiplayer_cursor == 1) #define JoiningGame (m_multiplayer_cursor == 0) @@ -126,7 +130,7 @@ char m_return_reason [32]; #define IPXConfig (m_net_cursor == 2) #define TCPIPConfig (m_net_cursor == 3) -void M_ConfigureNetSubsystem(void); +void M_ConfigureNetSubsystem (void); //============================================================================= /* Support Routines */ @@ -138,48 +142,52 @@ M_DrawCharacter Draws one solid graphics character ================ */ -void M_DrawCharacter (int cx, int line, int num) +void +M_DrawCharacter (int cx, int line, int num) { - Draw_Character8 ( cx + ((vid.width - 320)>>1), line, num); + Draw_Character8 (cx + ((vid.width - 320) >> 1), line, num); } -void M_Print (int cx, int cy, char *str) +void +M_Print (int cx, int cy, char *str) { - while (*str) - { - M_DrawCharacter (cx, cy, (*str)+128); + while (*str) { + M_DrawCharacter (cx, cy, (*str) + 128); str++; cx += 8; } } -void M_PrintWhite (int cx, int cy, char *str) +void +M_PrintWhite (int cx, int cy, char *str) { - while (*str) - { + while (*str) { M_DrawCharacter (cx, cy, *str); str++; cx += 8; } } -void M_DrawTransPic (int x, int y, qpic_t *pic) +void +M_DrawTransPic (int x, int y, qpic_t *pic) { - Draw_Pic (x + ((vid.width - 320)>>1), y, pic); + Draw_Pic (x + ((vid.width - 320) >> 1), y, pic); } -void M_DrawPic (int x, int y, qpic_t *pic) +void +M_DrawPic (int x, int y, qpic_t *pic) { - Draw_Pic (x + ((vid.width - 320)>>1), y, pic); + Draw_Pic (x + ((vid.width - 320) >> 1), y, pic); } -byte identityTable[256]; -byte translationTable[256]; +byte identityTable[256]; +byte translationTable[256]; -void M_BuildTranslationTable(int top, int bottom) +void +M_BuildTranslationTable (int top, int bottom) { - int j; - byte *dest, *source; + int j; + byte *dest, *source; for (j = 0; j < 256; j++) identityTable[j] = j; @@ -187,31 +195,35 @@ void M_BuildTranslationTable(int top, int bottom) source = identityTable; memcpy (dest, source, 256); - if (top < 128) // the artists made some backwards ranges. sigh. + if (top < 128) // the artists made some backwards + // ranges. sigh. memcpy (dest + TOP_RANGE, source + top, 16); else - for (j=0 ; j<16 ; j++) - dest[TOP_RANGE+j] = source[top+15-j]; + for (j = 0; j < 16; j++) + dest[TOP_RANGE + j] = source[top + 15 - j]; if (bottom < 128) memcpy (dest + BOTTOM_RANGE, source + bottom, 16); else - for (j=0 ; j<16 ; j++) - dest[BOTTOM_RANGE+j] = source[bottom+15-j]; + for (j = 0; j < 16; j++) + dest[BOTTOM_RANGE + j] = source[bottom + 15 - j]; } -void M_DrawTransPicTranslate (int x, int y, qpic_t *pic) +void +M_DrawTransPicTranslate (int x, int y, qpic_t *pic) { - Draw_TransPicTranslate (x + ((vid.width - 320)>>1), y, pic, translationTable); + Draw_TransPicTranslate (x + ((vid.width - 320) >> 1), y, pic, + translationTable); } -void M_DrawTextBox (int x, int y, int width, int lines) +void +M_DrawTextBox (int x, int y, int width, int lines) { - qpic_t *p; - int cx, cy; - int n; + qpic_t *p; + int cx, cy; + int n; // draw left side cx = x; @@ -219,31 +231,28 @@ void M_DrawTextBox (int x, int y, int width, int lines) p = Draw_CachePic ("gfx/box_tl.lmp"); M_DrawTransPic (cx, cy, p); p = Draw_CachePic ("gfx/box_ml.lmp"); - for (n = 0; n < lines; n++) - { + for (n = 0; n < lines; n++) { cy += 8; M_DrawTransPic (cx, cy, p); } p = Draw_CachePic ("gfx/box_bl.lmp"); - M_DrawTransPic (cx, cy+8, p); + M_DrawTransPic (cx, cy + 8, p); // draw middle cx += 8; - while (width > 0) - { + while (width > 0) { cy = y; p = Draw_CachePic ("gfx/box_tm.lmp"); M_DrawTransPic (cx, cy, p); p = Draw_CachePic ("gfx/box_mm.lmp"); - for (n = 0; n < lines; n++) - { + for (n = 0; n < lines; n++) { cy += 8; if (n == 1) p = Draw_CachePic ("gfx/box_mm2.lmp"); M_DrawTransPic (cx, cy, p); } p = Draw_CachePic ("gfx/box_bm.lmp"); - M_DrawTransPic (cx, cy+8, p); + M_DrawTransPic (cx, cy + 8, p); width -= 2; cx += 16; } @@ -253,32 +262,30 @@ void M_DrawTextBox (int x, int y, int width, int lines) p = Draw_CachePic ("gfx/box_tr.lmp"); M_DrawTransPic (cx, cy, p); p = Draw_CachePic ("gfx/box_mr.lmp"); - for (n = 0; n < lines; n++) - { + for (n = 0; n < lines; n++) { cy += 8; M_DrawTransPic (cx, cy, p); } p = Draw_CachePic ("gfx/box_br.lmp"); - M_DrawTransPic (cx, cy+8, p); + M_DrawTransPic (cx, cy + 8, p); } //============================================================================= -int m_save_demonum; - +int m_save_demonum; + /* ================ M_ToggleMenu_f ================ */ -void M_ToggleMenu_f (void) +void +M_ToggleMenu_f (void) { m_entersound = true; - if (key_dest == key_menu) - { - if (m_state != m_main) - { + if (key_dest == key_menu) { + if (m_state != m_main) { M_Menu_Main_f (); return; } @@ -286,30 +293,28 @@ void M_ToggleMenu_f (void) m_state = m_none; return; } - if (key_dest == key_console) - { + if (key_dest == key_console) { Con_ToggleConsole_f (); - if (key_dest == key_console) //Still suck on console? + if (key_dest == key_console) // Still suck on console? M_Menu_Main_f (); - } - else - { + } else { M_Menu_Main_f (); } } - + //============================================================================= /* MAIN MENU */ -int m_main_cursor; +int m_main_cursor; + #define MAIN_ITEMS 5 -void M_Menu_Main_f (void) +void +M_Menu_Main_f (void) { - if (key_dest != key_menu) - { + if (key_dest != key_menu) { m_save_demonum = cls.demonum; cls.demonum = -1; } @@ -317,73 +322,74 @@ void M_Menu_Main_f (void) m_state = m_main; m_entersound = true; } - -void M_Main_Draw (void) + +void +M_Main_Draw (void) { - int f; - qpic_t *p; + int f; + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); + M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp")); p = Draw_CachePic ("gfx/ttl_main.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); - M_DrawTransPic (72, 32, Draw_CachePic ("gfx/mainmenu.lmp") ); + M_DrawPic ((320 - p->width) / 2, 4, p); + M_DrawTransPic (72, 32, Draw_CachePic ("gfx/mainmenu.lmp")); - f = (int)(realtime * 10)%6; - - M_DrawTransPic (54, 32 + m_main_cursor * 20,Draw_CachePic( va("gfx/menudot%i.lmp", f+1 ) ) ); + f = (int) (realtime * 10) % 6; + + M_DrawTransPic (54, 32 + m_main_cursor * 20, + Draw_CachePic (va ("gfx/menudot%i.lmp", f + 1))); } -void M_Main_Key (int key) +void +M_Main_Key (int key) { - switch (key) - { - case K_ESCAPE: - key_dest = key_game; - m_state = m_none; - cls.demonum = m_save_demonum; - if (cls.demonum != -1 && !cls.demoplayback && cls.state == ca_disconnected) - CL_NextDemo (); - break; - - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - if (++m_main_cursor >= MAIN_ITEMS) - m_main_cursor = 0; - break; - - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - if (--m_main_cursor < 0) - m_main_cursor = MAIN_ITEMS - 1; - break; - - case K_ENTER: - m_entersound = true; - - switch (m_main_cursor) - { - case 0: - M_Menu_SinglePlayer_f (); + switch (key) { + case K_ESCAPE: + key_dest = key_game; + m_state = m_none; + cls.demonum = m_save_demonum; + if (cls.demonum != -1 && !cls.demoplayback + && cls.state == ca_disconnected) CL_NextDemo (); break; - case 1: - M_Menu_MultiPlayer_f (); + case K_DOWNARROW: + S_LocalSound ("misc/menu1.wav"); + if (++m_main_cursor >= MAIN_ITEMS) + m_main_cursor = 0; break; - case 2: - M_Menu_Options_f (); + case K_UPARROW: + S_LocalSound ("misc/menu1.wav"); + if (--m_main_cursor < 0) + m_main_cursor = MAIN_ITEMS - 1; break; - case 3: - M_Menu_Help_f (); - break; + case K_ENTER: + m_entersound = true; - case 4: - M_Menu_Quit_f (); - break; - } + switch (m_main_cursor) { + case 0: + M_Menu_SinglePlayer_f (); + break; + + case 1: + M_Menu_MultiPlayer_f (); + break; + + case 2: + M_Menu_Options_f (); + break; + + case 3: + M_Menu_Help_f (); + break; + + case 4: + M_Menu_Quit_f (); + break; + } } } @@ -395,9 +401,10 @@ void M_Main_Key (int key) #define SLIDER_RANGE 10 -int options_cursor; +int options_cursor; -void M_Menu_Options_f (void) +void +M_Menu_Options_f (void) { key_dest = key_menu; m_state = m_options; @@ -405,35 +412,41 @@ void M_Menu_Options_f (void) } -void M_AdjustSliders (int dir) +void +M_AdjustSliders (int dir) { S_LocalSound ("misc/menu3.wav"); switch (options_cursor) { - case 3: // screen size - Cvar_SetValue (scr_viewsize, bound (30, scr_viewsize->int_val + (dir * 10), 120)); + case 3: // screen size + Cvar_SetValue (scr_viewsize, + bound (30, scr_viewsize->int_val + (dir * 10), 120)); break; - case 4: // Brightness - Cvar_SetValue (brightness, bound (1, brightness->value + (dir * 0.25), 5)); + case 4: // Brightness + Cvar_SetValue (brightness, + bound (1, brightness->value + (dir * 0.25), 5)); break; - case 5: // Contrast - Cvar_SetValue (contrast, bound (0.0, contrast->value + (dir * 0.05), 1)); + case 5: // Contrast + Cvar_SetValue (contrast, + bound (0.0, contrast->value + (dir * 0.05), 1)); break; - case 6: // mouse speed - Cvar_SetValue (sensitivity, bound (1, sensitivity->value + dir, 25)); + case 6: // mouse speed + Cvar_SetValue (sensitivity, + bound (1, sensitivity->value + dir, 25)); break; - case 7: // music volume + case 7: // music volume #ifdef _WIN32 Cvar_SetValue (bgmvolume, bound (0, bgmvolume->value + dir, 1)); #else - Cvar_SetValue (bgmvolume, bound (0, bgmvolume->value + (dir * 0.1), 1)); + Cvar_SetValue (bgmvolume, + bound (0, bgmvolume->value + (dir * 0.1), 1)); #endif break; - case 8: // sfx volume + case 8: // sfx volume Cvar_SetValue (volume, bound (0, volume->value + (dir * 0.1), 1)); break; - case 9: // allways run + case 9: // allways run if (cl_forwardspeed->value > 200) { Cvar_SetValue (cl_forwardspeed, 200); Cvar_SetValue (cl_backspeed, 200); @@ -443,46 +456,48 @@ void M_AdjustSliders (int dir) } break; - case 10: // invert mouse + case 10: // invert mouse Cvar_SetValue (m_pitch, -m_pitch->value); break; - case 11: // lookspring + case 11: // lookspring Cvar_SetValue (lookspring, !lookspring->int_val); break; - case 12: // lookstrafe + case 12: // lookstrafe Cvar_SetValue (lookstrafe, !lookstrafe->int_val); break; - case 13: // Use old-style sbar + case 13: // Use old-style sbar Cvar_SetValue (cl_sbar, !cl_sbar->int_val); break; - - case 14: // HUD on left side + + case 14: // HUD on left side Cvar_SetValue (cl_hudswap, !cl_hudswap->int_val); break; - case 16: // _windowed_mouse + case 16: // _windowed_mouse Cvar_SetValue (_windowed_mouse, !_windowed_mouse->int_val); break; } } -void M_DrawSlider (int x, int y, float range) +void +M_DrawSlider (int x, int y, float range) { - int i; + int i; range = bound (0, range, 1); - M_DrawCharacter (x-8, y, 128); - for (i=0 ; iwidth)/2, 4, p); - + M_DrawPic ((320 - p->width) / 2, 4, p); + M_Print (16, 32, " Customize controls"); M_Print (16, 40, " Go to console"); M_Print (16, 48, " Reset to defaults"); @@ -533,7 +549,7 @@ void M_Options_Draw (void) r = volume->value; M_DrawSlider (220, 96, r); - M_Print (16, 104, " Always Run"); + M_Print (16, 104, " Always Run"); M_DrawCheckbox (220, 104, cl_forwardspeed->value > 200); M_Print (16, 112, " Invert Mouse"); @@ -566,75 +582,76 @@ void M_Options_Draw (void) #endif // cursor - M_DrawCharacter (200, 32 + options_cursor*8, 12+((int)(realtime*4)&1)); + M_DrawCharacter (200, 32 + options_cursor * 8, + 12 + ((int) (realtime * 4) & 1)); } -void M_Options_Key (int k) +void +M_Options_Key (int k) { - switch (k) - { - case K_ESCAPE: - M_Menu_Main_f (); - break; - - case K_ENTER: - m_entersound = true; - switch (options_cursor) - { - case 0: - M_Menu_Keys_f (); + switch (k) { + case K_ESCAPE: + M_Menu_Main_f (); break; - case 1: - m_state = m_none; - Con_ToggleConsole_f (); + + case K_ENTER: + m_entersound = true; + switch (options_cursor) { + case 0: + M_Menu_Keys_f (); + break; + case 1: + m_state = m_none; + Con_ToggleConsole_f (); + break; + case 2: + Cbuf_AddText ("exec default.cfg\n"); + break; + case 15: + if (vid_menudrawfn) + M_Menu_Video_f (); + break; + default: + M_AdjustSliders (1); + break; + } + return; + + case K_UPARROW: + S_LocalSound ("misc/menu1.wav"); + options_cursor--; + if (options_cursor < 0) + options_cursor = OPTIONS_ITEMS - 1; +#ifdef _WIN32 + if (options_cursor == 16 + && (!(_windowed_mouse) + || (modestate != MS_WINDOWED))) options_cursor--; +#endif + if (options_cursor == 15 && !(vid_menudrawfn)) + options_cursor--; break; - case 2: - Cbuf_AddText ("exec default.cfg\n"); + + case K_DOWNARROW: + S_LocalSound ("misc/menu1.wav"); + options_cursor++; + if (options_cursor == 15 && !(vid_menudrawfn)) + options_cursor++; +#ifdef _WIN32 + if (options_cursor == 16 && (!(_windowed_mouse) || (modestate != MS_WINDOWED))) // ARGH!!!!! + options_cursor++; +#endif + if (options_cursor >= OPTIONS_ITEMS) + options_cursor = 0; break; - case 15: - if (vid_menudrawfn) - M_Menu_Video_f (); + + case K_LEFTARROW: + M_AdjustSliders (-1); break; - default: + + case K_RIGHTARROW: M_AdjustSliders (1); break; - } - return; - - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - options_cursor--; - if (options_cursor < 0) - options_cursor = OPTIONS_ITEMS-1; -#ifdef _WIN32 - if (options_cursor == 16 && (!(_windowed_mouse) || (modestate != MS_WINDOWED))) - options_cursor--; -#endif - if (options_cursor == 15 && !(vid_menudrawfn)) - options_cursor--; - break; - - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - options_cursor++; - if (options_cursor == 15 && !(vid_menudrawfn)) - options_cursor++; -#ifdef _WIN32 - if (options_cursor == 16 && (!(_windowed_mouse) || (modestate != MS_WINDOWED))) // ARGH!!!!! - options_cursor++; -#endif - if (options_cursor >= OPTIONS_ITEMS) - options_cursor = 0; - break; - - case K_LEFTARROW: - M_AdjustSliders (-1); - break; - - case K_RIGHTARROW: - M_AdjustSliders (1); - break; } } @@ -642,34 +659,34 @@ void M_Options_Key (int k) //============================================================================= /* KEYS MENU */ -char *bindnames[][2] = -{ -{"+attack", "attack"}, -{"impulse 10", "change weapon"}, -{"+jump", "jump / swim up"}, -{"+forward", "walk forward"}, -{"+back", "backpedal"}, -{"+left", "turn left"}, -{"+right", "turn right"}, -{"+speed", "run"}, -{"+moveleft", "step left"}, -{"+moveright", "step right"}, -{"+strafe", "sidestep"}, -{"+lookup", "look up"}, -{"+lookdown", "look down"}, -{"centerview", "center view"}, -{"+mlook", "mouse look"}, -{"+klook", "keyboard look"}, -{"+moveup", "swim up"}, -{"+movedown", "swim down"} +char *bindnames[][2] = { + {"+attack", "attack"}, + {"impulse 10", "change weapon"}, + {"+jump", "jump / swim up"}, + {"+forward", "walk forward"}, + {"+back", "backpedal"}, + {"+left", "turn left"}, + {"+right", "turn right"}, + {"+speed", "run"}, + {"+moveleft", "step left"}, + {"+moveright", "step right"}, + {"+strafe", "sidestep"}, + {"+lookup", "look up"}, + {"+lookdown", "look down"}, + {"centerview", "center view"}, + {"+mlook", "mouse look"}, + {"+klook", "keyboard look"}, + {"+moveup", "swim up"}, + {"+movedown", "swim down"} }; #define NUMCOMMANDS (sizeof(bindnames)/sizeof(bindnames[0])) -int keys_cursor; -int bind_grab; +int keys_cursor; +int bind_grab; -void M_Menu_Keys_f (void) +void +M_Menu_Keys_f (void) { key_dest = key_menu; m_state = m_keys; @@ -677,24 +694,23 @@ void M_Menu_Keys_f (void) } -void M_FindKeysForCommand (char *command, int *twokeys) +void +M_FindKeysForCommand (char *command, int *twokeys) { - int count; - int j; - int l; - char *b; + int count; + int j; + int l; + char *b; twokeys[0] = twokeys[1] = -1; - l = strlen(command); + l = strlen (command); count = 0; - for (j=0 ; j<256 ; j++) - { + for (j = 0; j < 256; j++) { b = keybindings[j]; if (!b) continue; - if (!strncmp (b, command, l) ) - { + if (!strncmp (b, command, l)) { twokeys[count] = j; count++; if (count == 2) @@ -703,140 +719,136 @@ void M_FindKeysForCommand (char *command, int *twokeys) } } -void M_UnbindCommand (char *command) +void +M_UnbindCommand (char *command) { - int j; - int l; - char *b; + int j; + int l; + char *b; - l = strlen(command); + l = strlen (command); - for (j=0 ; j<256 ; j++) - { + for (j = 0; j < 256; j++) { b = keybindings[j]; if (!b) continue; - if (!strncmp (b, command, l) ) + if (!strncmp (b, command, l)) Key_SetBinding (j, ""); } } -void M_Keys_Draw (void) +void +M_Keys_Draw (void) { - int i, l; - int keys[2]; - char *name; - int x, y; - qpic_t *p; + int i, l; + int keys[2]; + char *name; + int x, y; + qpic_t *p; p = Draw_CachePic ("gfx/ttl_cstm.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawPic ((320 - p->width) / 2, 4, p); if (bind_grab) M_Print (12, 32, "Press a key or button for this action"); else M_Print (18, 32, "Enter to change, backspace to clear"); - + // search for known bindings - for (i=0 ; i= NUMCOMMANDS) - keys_cursor = 0; - break; + case K_LEFTARROW: + case K_UPARROW: + S_LocalSound ("misc/menu1.wav"); + keys_cursor--; + if (keys_cursor < 0) + keys_cursor = NUMCOMMANDS - 1; + break; - case K_ENTER: // go into bind mode - M_FindKeysForCommand (bindnames[keys_cursor][0], keys); - S_LocalSound ("misc/menu2.wav"); - if (keys[1] != -1) + case K_DOWNARROW: + case K_RIGHTARROW: + S_LocalSound ("misc/menu1.wav"); + keys_cursor++; + if (keys_cursor >= NUMCOMMANDS) + keys_cursor = 0; + break; + + case K_ENTER: // go into bind mode + M_FindKeysForCommand (bindnames[keys_cursor][0], keys); + S_LocalSound ("misc/menu2.wav"); + if (keys[1] != -1) + M_UnbindCommand (bindnames[keys_cursor][0]); + bind_grab = true; + break; + + case K_BACKSPACE: // delete bindings + case K_DEL: // delete bindings + S_LocalSound ("misc/menu2.wav"); M_UnbindCommand (bindnames[keys_cursor][0]); - bind_grab = true; - break; - - case K_BACKSPACE: // delete bindings - case K_DEL: // delete bindings - S_LocalSound ("misc/menu2.wav"); - M_UnbindCommand (bindnames[keys_cursor][0]); - break; + break; } } //============================================================================= /* VIDEO MENU */ -void M_Menu_Video_f (void) +void +M_Menu_Video_f (void) { key_dest = key_menu; m_state = m_video; @@ -844,13 +856,15 @@ void M_Menu_Video_f (void) } -void M_Video_Draw (void) +void +M_Video_Draw (void) { (*vid_menudrawfn) (); } -void M_Video_Key (int key) +void +M_Video_Key (int key) { (*vid_menukeyfn) (key); } @@ -858,11 +872,13 @@ void M_Video_Key (int key) //============================================================================= /* HELP MENU */ -int help_page; +int help_page; + #define NUM_HELP_PAGES 6 -void M_Menu_Help_f (void) +void +M_Menu_Help_f (void) { key_dest = key_menu; m_state = m_help; @@ -872,33 +888,34 @@ void M_Menu_Help_f (void) -void M_Help_Draw (void) +void +M_Help_Draw (void) { - M_DrawPic (0, 0, Draw_CachePic ( va("gfx/help%i.lmp", help_page)) ); + M_DrawPic (0, 0, Draw_CachePic (va ("gfx/help%i.lmp", help_page))); } -void M_Help_Key (int key) +void +M_Help_Key (int key) { - switch (key) - { - case K_ESCAPE: - M_Menu_Main_f (); - break; - - case K_UPARROW: - case K_RIGHTARROW: - m_entersound = true; - if (++help_page >= NUM_HELP_PAGES) - help_page = 0; - break; + switch (key) { + case K_ESCAPE: + M_Menu_Main_f (); + break; - case K_DOWNARROW: - case K_LEFTARROW: - m_entersound = true; - if (--help_page < 0) - help_page = NUM_HELP_PAGES-1; - break; + case K_UPARROW: + case K_RIGHTARROW: + m_entersound = true; + if (++help_page >= NUM_HELP_PAGES) + help_page = 0; + break; + + case K_DOWNARROW: + case K_LEFTARROW: + m_entersound = true; + if (--help_page < 0) + help_page = NUM_HELP_PAGES - 1; + break; } } @@ -906,55 +923,55 @@ void M_Help_Key (int key) //============================================================================= /* QUIT MENU */ -int msgNumber; -int m_quit_prevstate; -qboolean wasInMenus; +int msgNumber; +int m_quit_prevstate; +qboolean wasInMenus; -char *quitMessage [] = -{ +char *quitMessage[] = { /* .........1.........2.... */ - " Are you gonna quit ", - " this game just like ", - " everything else? ", - " ", - - " Milord, methinks that ", - " thou art a lowly ", - " quitter. Is this true? ", - " ", + " Are you gonna quit ", + " this game just like ", + " everything else? ", + " ", - " Do I need to bust your ", - " face open for trying ", - " to quit? ", - " ", + " Milord, methinks that ", + " thou art a lowly ", + " quitter. Is this true? ", + " ", - " Man, I oughta smack you", - " for trying to quit! ", - " Press Y to get ", - " smacked out. ", - - " Press Y to quit like a ", - " big loser in life. ", - " Press N to stay proud ", - " and successful! ", - - " If you press Y to ", - " quit, I will summon ", - " Satan all over your ", - " hard drive! ", - - " Um, Asmodeus dislikes ", - " his children trying to ", - " quit. Press Y to return", - " to your Tinkertoys. ", - - " If you quit now, I'll ", - " throw a blanket-party ", - " for you next time! ", - " " + " Do I need to bust your ", + " face open for trying ", + " to quit? ", + " ", + + " Man, I oughta smack you", + " for trying to quit! ", + " Press Y to get ", + " smacked out. ", + + " Press Y to quit like a ", + " big loser in life. ", + " Press N to stay proud ", + " and successful! ", + + " If you press Y to ", + " quit, I will summon ", + " Satan all over your ", + " hard drive! ", + + " Um, Asmodeus dislikes ", + " his children trying to ", + " quit. Press Y to return", + " to your Tinkertoys. ", + + " If you quit now, I'll ", + " throw a blanket-party ", + " for you next time! ", + " " }; -void M_Menu_Quit_f (void) +void +M_Menu_Quit_f (void) { if (m_state == m_quit) return; @@ -963,63 +980,66 @@ void M_Menu_Quit_f (void) m_quit_prevstate = m_state; m_state = m_quit; m_entersound = true; - msgNumber = rand()&7; + msgNumber = rand () & 7; } -void M_Quit_Key (int key) +void +M_Quit_Key (int key) { - switch (key) - { - case K_ESCAPE: - case 'n': - case 'N': - if (wasInMenus) - { - m_state = m_quit_prevstate; - m_entersound = true; - } - else - { - key_dest = key_game; - m_state = m_none; - } - break; + switch (key) { + case K_ESCAPE: + case 'n': + case 'N': + if (wasInMenus) { + m_state = m_quit_prevstate; + m_entersound = true; + } else { + key_dest = key_game; + m_state = m_none; + } + break; - case 'Y': - case 'y': - key_dest = key_console; - CL_Disconnect (); - Sys_Quit (); - break; + case 'Y': + case 'y': + key_dest = key_console; + CL_Disconnect (); + Sys_Quit (); + break; - default: - break; + default: + break; } } -void M_Menu_SinglePlayer_f (void) { +void +M_Menu_SinglePlayer_f (void) +{ m_state = m_singleplayer; } -void M_SinglePlayer_Draw (void) { - qpic_t *p; +void +M_SinglePlayer_Draw (void) +{ + qpic_t *p; - M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); -// M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); + M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp")); +// M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp") ); p = Draw_CachePic ("gfx/ttl_sgl.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); -// M_DrawTransPic (72, 32, Draw_CachePic ("gfx/sp_menu.lmp") ); + M_DrawPic ((320 - p->width) / 2, 4, p); +// M_DrawTransPic (72, 32, Draw_CachePic ("gfx/sp_menu.lmp") ); - M_DrawTextBox (60, 10*8, 23, 4); - M_PrintWhite (88, 12*8, "This client is for"); - M_PrintWhite (88, 13*8, "Internet play only"); + M_DrawTextBox (60, 10 * 8, 23, 4); + M_PrintWhite (88, 12 * 8, "This client is for"); + M_PrintWhite (88, 13 * 8, "Internet play only"); } -void M_SinglePlayer_Key (key) { - if (key == K_ESCAPE || key==K_ENTER) +void +M_SinglePlayer_Key (key) +{ + if (key == K_ESCAPE || key == K_ENTER) m_state = m_main; } @@ -1028,147 +1048,161 @@ void M_SinglePlayer_Key (key) { #define STAT_X 50 #define STAT_Y 122 -int m_multip_cursor=0; -int m_multip_mins=0; -int m_multip_maxs=10; -int m_multip_horiz; +int m_multip_cursor = 0; +int m_multip_mins = 0; +int m_multip_maxs = 10; +int m_multip_horiz; -void M_Menu_MultiPlayer_f (void) { +void +M_Menu_MultiPlayer_f (void) +{ key_dest = key_menu; m_entersound = true; m_state = m_multiplayer; m_multip_horiz = 0; } -void M_MultiPlayer_Draw (void) { - int serv; - int line = 1; +void +M_MultiPlayer_Draw (void) +{ + int serv; + int line = 1; server_entry_t *cp; - qpic_t *p; - //int f; + qpic_t *p; + + // int f; + + M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp")); + p = Draw_CachePic ("gfx/p_multi.lmp"); + M_DrawPic ((320 - p->width) / 2, 4, p); - M_DrawTransPic(16,4,Draw_CachePic("gfx/qplaque.lmp")); - p = Draw_CachePic("gfx/p_multi.lmp"); - M_DrawPic((320-p->width)/2,4,p); - if (!slist) { - M_DrawTextBox(60,80,23,4); - M_PrintWhite(110,12*8,"No server list"); - M_PrintWhite(140,13*8,"found."); + M_DrawTextBox (60, 80, 23, 4); + M_PrintWhite (110, 12 * 8, "No server list"); + M_PrintWhite (140, 13 * 8, "found."); return; } - M_DrawTextBox(STAT_X,STAT_Y,23,4); - M_DrawTextBox(STAT_X,STAT_Y+38,23,3); - M_DrawTextBox(MENU_X,MENU_Y,23,(m_multip_maxs - m_multip_mins)+1); - for (serv = m_multip_mins; serv <= m_multip_maxs && serv < SL_Len(slist); serv++) { - cp = SL_Get_By_Num(slist,serv); - M_Print(MENU_X+18,line*8+MENU_Y, - va("%1.21s", - strlen(cp->desc) <= m_multip_horiz ? "" : cp->desc+m_multip_horiz)); + M_DrawTextBox (STAT_X, STAT_Y, 23, 4); + M_DrawTextBox (STAT_X, STAT_Y + 38, 23, 3); + M_DrawTextBox (MENU_X, MENU_Y, 23, (m_multip_maxs - m_multip_mins) + 1); + for (serv = m_multip_mins; serv <= m_multip_maxs && serv < SL_Len (slist); + serv++) { + cp = SL_Get_By_Num (slist, serv); + M_Print (MENU_X + 18, line * 8 + MENU_Y, + va ("%1.21s", + strlen (cp->desc) <= + m_multip_horiz ? "" : cp->desc + m_multip_horiz)); line++; } - cp = SL_Get_By_Num(slist,m_multip_cursor); - M_PrintWhite(STAT_X+18,STAT_Y+16,"IP/Hostname:"); - M_Print(STAT_X+18,STAT_Y+24,cp->server); - M_DrawCharacter(MENU_X+8,(m_multip_cursor - m_multip_mins + 1) * 8+MENU_Y, - 12+((int)(realtime*4)&1)); - //f = (int)(realtime * 10) % 6; - //M_PrintWhite(STAT_X+118,STAT_Y+58,"uakeforge!"); - //M_DrawTransPic(STAT_X+105,STAT_Y+48,Draw_CachePic(va("gfx/menudot%i.lmp",f+1))); + cp = SL_Get_By_Num (slist, m_multip_cursor); + M_PrintWhite (STAT_X + 18, STAT_Y + 16, "IP/Hostname:"); + M_Print (STAT_X + 18, STAT_Y + 24, cp->server); + M_DrawCharacter (MENU_X + 8, + (m_multip_cursor - m_multip_mins + 1) * 8 + MENU_Y, + 12 + ((int) (realtime * 4) & 1)); + // f = (int)(realtime * 10) % 6; + // M_PrintWhite(STAT_X+118,STAT_Y+58,"uakeforge!"); + // M_DrawTransPic(STAT_X+105,STAT_Y+48,Draw_CachePic(va("gfx/menudot%i.lmp",f+1))); } -void M_MultiPlayer_Key (key) { +void +M_MultiPlayer_Key (key) +{ server_entry_t *temp; + if (!slist && key != K_ESCAPE && key != K_INS) return; - switch(key) { - case K_ESCAPE: - M_Menu_Main_f(); - break; - case KP_DOWNARROW: - case K_DOWNARROW: - S_LocalSound("misc/menu1.wav"); - m_multip_cursor++; - break; - case KP_UPARROW: - case K_UPARROW: - S_LocalSound("misc/menu1.wav"); - m_multip_cursor--; - break; - case K_PGUP: - S_LocalSound("misc/menu1.wav"); - m_multip_cursor -= (m_multip_maxs - m_multip_mins); - if (m_multip_cursor < 0) - m_multip_cursor = 0; - break; - case K_PGDN: - S_LocalSound("misc/menu1.wav"); - m_multip_cursor += (m_multip_maxs - m_multip_mins); - if (SL_Len(slist) - 1 < m_multip_cursor ) - m_multip_cursor = SL_Len(slist) - 1; - break; - case K_RIGHTARROW: - S_LocalSound("misc/menu1.wav"); - if (m_multip_horiz < 256) - m_multip_horiz++; - break; - case K_LEFTARROW: - S_LocalSound("misc/menu1.wav"); - if (m_multip_horiz > 0 ) - m_multip_horiz--; - break; - case K_ENTER: - m_state = m_main; - M_ToggleMenu_f(); - CL_Disconnect(); - strncpy(cls.servername,SL_Get_By_Num(slist,m_multip_cursor)->server,sizeof(cls.servername)-1); - CL_BeginServerConnect(); - break; - case 'e': - case 'E': - M_Menu_SEdit_f(); - break; - case K_INS: - S_LocalSound("misc/menu2.wav"); - if (!slist) { - m_multip_cursor = 0; - slist = SL_Add(slist, "127.0.0.1",""); - } - else { - temp = SL_Get_By_Num(slist,m_multip_cursor); - slist = SL_InsB(slist, temp, "127.0.0.1",""); - } - break; - case K_DEL: - S_LocalSound("misc/menu2.wav"); - if (SL_Len(slist) > 0) { - slist = SL_Del(slist, SL_Get_By_Num(slist,m_multip_cursor)); - if (SL_Len(slist) == m_multip_cursor && slist) - m_multip_cursor--; - } - break; - case ']': - case '}': - S_LocalSound("misc/menu1.wav"); - if (m_multip_cursor != SL_Len(slist) - 1) { - SL_Swap(SL_Get_By_Num(slist,m_multip_cursor),SL_Get_By_Num(slist,m_multip_cursor+1)); + switch (key) { + case K_ESCAPE: + M_Menu_Main_f (); + break; + case KP_DOWNARROW: + case K_DOWNARROW: + S_LocalSound ("misc/menu1.wav"); m_multip_cursor++; - } - break; - case '[': - case '{': - S_LocalSound("misc/menu1.wav"); - if (m_multip_cursor) { - SL_Swap(SL_Get_By_Num(slist,m_multip_cursor),SL_Get_By_Num(slist,m_multip_cursor-1)); + break; + case KP_UPARROW: + case K_UPARROW: + S_LocalSound ("misc/menu1.wav"); m_multip_cursor--; - } - break; - default: - break; + break; + case K_PGUP: + S_LocalSound ("misc/menu1.wav"); + m_multip_cursor -= (m_multip_maxs - m_multip_mins); + if (m_multip_cursor < 0) + m_multip_cursor = 0; + break; + case K_PGDN: + S_LocalSound ("misc/menu1.wav"); + m_multip_cursor += (m_multip_maxs - m_multip_mins); + if (SL_Len (slist) - 1 < m_multip_cursor) + m_multip_cursor = SL_Len (slist) - 1; + break; + case K_RIGHTARROW: + S_LocalSound ("misc/menu1.wav"); + if (m_multip_horiz < 256) + m_multip_horiz++; + break; + case K_LEFTARROW: + S_LocalSound ("misc/menu1.wav"); + if (m_multip_horiz > 0) + m_multip_horiz--; + break; + case K_ENTER: + m_state = m_main; + M_ToggleMenu_f (); + CL_Disconnect (); + strncpy (cls.servername, + SL_Get_By_Num (slist, m_multip_cursor)->server, + sizeof (cls.servername) - 1); + CL_BeginServerConnect (); + break; + case 'e': + case 'E': + M_Menu_SEdit_f (); + break; + case K_INS: + S_LocalSound ("misc/menu2.wav"); + if (!slist) { + m_multip_cursor = 0; + slist = SL_Add (slist, "127.0.0.1", ""); + } else { + temp = SL_Get_By_Num (slist, m_multip_cursor); + slist = SL_InsB (slist, temp, "127.0.0.1", ""); + } + break; + case K_DEL: + S_LocalSound ("misc/menu2.wav"); + if (SL_Len (slist) > 0) { + slist = SL_Del (slist, SL_Get_By_Num (slist, m_multip_cursor)); + if (SL_Len (slist) == m_multip_cursor && slist) + m_multip_cursor--; + } + break; + case ']': + case '}': + S_LocalSound ("misc/menu1.wav"); + if (m_multip_cursor != SL_Len (slist) - 1) { + SL_Swap (SL_Get_By_Num (slist, m_multip_cursor), + SL_Get_By_Num (slist, m_multip_cursor + 1)); + m_multip_cursor++; + } + break; + case '[': + case '{': + S_LocalSound ("misc/menu1.wav"); + if (m_multip_cursor) { + SL_Swap (SL_Get_By_Num (slist, m_multip_cursor), + SL_Get_By_Num (slist, m_multip_cursor - 1)); + m_multip_cursor--; + } + break; + default: + break; } if (m_multip_cursor < 0) - m_multip_cursor = SL_Len(slist) - 1; - if (m_multip_cursor >= SL_Len(slist)) + m_multip_cursor = SL_Len (slist) - 1; + if (m_multip_cursor >= SL_Len (slist)) m_multip_cursor = 0; if (m_multip_cursor < m_multip_mins) { m_multip_maxs -= (m_multip_mins - m_multip_cursor); @@ -1179,6 +1213,7 @@ void M_MultiPlayer_Key (key) { m_multip_maxs = m_multip_cursor; } } + #define SERV_X 60 #define SERV_Y 64 #define DESC_X 60 @@ -1186,55 +1221,62 @@ void M_MultiPlayer_Key (key) { #define SERV_L 22 #define DESC_L 22 -char serv[256]; -char desc[256]; -int serv_max; -int serv_min; -int desc_max; -int desc_min; -qboolean sedit_state; +char serv[256]; +char desc[256]; +int serv_max; +int serv_min; +int desc_max; +int desc_min; +qboolean sedit_state; -void M_Menu_SEdit_f (void) { +void +M_Menu_SEdit_f (void) +{ server_entry_t *c; + key_dest = key_menu; m_entersound = true; m_state = m_sedit; sedit_state = false; - c = SL_Get_By_Num(slist,m_multip_cursor); - strncpy(serv,c->server,255); - serv[strlen(c->server) + 1] = 0; - strncpy(desc,c->desc,255); - desc[strlen(c->desc) + 1] = 0; - serv_max = strlen(serv) > SERV_L ? strlen(serv) : SERV_L; + c = SL_Get_By_Num (slist, m_multip_cursor); + strncpy (serv, c->server, 255); + serv[strlen (c->server) + 1] = 0; + strncpy (desc, c->desc, 255); + desc[strlen (c->desc) + 1] = 0; + serv_max = strlen (serv) > SERV_L ? strlen (serv) : SERV_L; serv_min = serv_max - (SERV_L); - desc_max = strlen(desc) > DESC_L ? strlen(desc) : DESC_L; + desc_max = strlen (desc) > DESC_L ? strlen (desc) : DESC_L; desc_min = desc_max - (DESC_L); } -void M_SEdit_Draw (void) { - qpic_t *p; - - M_DrawTransPic(16,4,Draw_CachePic("gfx/qplaque.lmp")); - p = Draw_CachePic("gfx/p_multi.lmp"); - M_DrawPic((320-p->width)/2,4,p); +void +M_SEdit_Draw (void) +{ + qpic_t *p; - M_DrawTextBox(SERV_X,SERV_Y,23,1); - M_DrawTextBox(DESC_X,DESC_Y,23,1); - M_PrintWhite(SERV_X,SERV_Y-4,"Hostname/IP:"); - M_PrintWhite(DESC_X,DESC_Y-4,"Description:"); - M_Print(SERV_X+9,SERV_Y+8,va("%1.22s",serv+serv_min)); - M_Print(DESC_X+9,DESC_Y+8,va("%1.22s",desc+desc_min)); + M_DrawTransPic (16, 4, Draw_CachePic ("gfx/qplaque.lmp")); + p = Draw_CachePic ("gfx/p_multi.lmp"); + M_DrawPic ((320 - p->width) / 2, 4, p); + + M_DrawTextBox (SERV_X, SERV_Y, 23, 1); + M_DrawTextBox (DESC_X, DESC_Y, 23, 1); + M_PrintWhite (SERV_X, SERV_Y - 4, "Hostname/IP:"); + M_PrintWhite (DESC_X, DESC_Y - 4, "Description:"); + M_Print (SERV_X + 9, SERV_Y + 8, va ("%1.22s", serv + serv_min)); + M_Print (DESC_X + 9, DESC_Y + 8, va ("%1.22s", desc + desc_min)); if (sedit_state == 0) - M_DrawCharacter(SERV_X+9+8*(strlen(serv)-serv_min), - SERV_Y+8,10+((int)(realtime*4)&1)); + M_DrawCharacter (SERV_X + 9 + 8 * (strlen (serv) - serv_min), + SERV_Y + 8, 10 + ((int) (realtime * 4) & 1)); if (sedit_state == 1) - M_DrawCharacter(DESC_X+9+8*(strlen(desc)-desc_min), - DESC_Y+8,10+((int)(realtime*4)&1)); + M_DrawCharacter (DESC_X + 9 + 8 * (strlen (desc) - desc_min), + DESC_Y + 8, 10 + ((int) (realtime * 4) & 1)); } -void M_SEdit_Key (int key) { - int l; +void +M_SEdit_Key (int key) +{ + int l; server_entry_t *c; switch (key) { @@ -1242,62 +1284,60 @@ void M_SEdit_Key (int key) { M_Menu_MultiPlayer_f (); break; case K_ENTER: - c = SL_Get_By_Num(slist,m_multip_cursor); - free(c->server); - free(c->desc); - c->server = malloc(strlen(serv) + 1); - c->desc = malloc(strlen(desc) + 1); - strcpy(c->server,serv); - strcpy(c->desc,desc); + c = SL_Get_By_Num (slist, m_multip_cursor); + free (c->server); + free (c->desc); + c->server = malloc (strlen (serv) + 1); + c->desc = malloc (strlen (desc) + 1); + strcpy (c->server, serv); + strcpy (c->desc, desc); M_Menu_MultiPlayer_f (); break; case K_UPARROW: - S_LocalSound("misc/menu1.wav"); - sedit_state = !sedit_state; + S_LocalSound ("misc/menu1.wav"); + sedit_state = !sedit_state; break; case K_DOWNARROW: - S_LocalSound("misc/menu1.wav"); - sedit_state = !sedit_state; + S_LocalSound ("misc/menu1.wav"); + sedit_state = !sedit_state; break; case K_BACKSPACE: if (sedit_state) { - if ((l = strlen(desc))) + if ((l = strlen (desc))) desc[--l] = 0; - if (strlen(desc)-6 < desc_min && desc_min) { + if (strlen (desc) - 6 < desc_min && desc_min) { desc_min--; desc_max--; } - } - else { - if ((l = strlen(serv))) - serv[--l] = 0; - if (strlen(serv)-6 < serv_min && serv_min) { - serv_min--; - serv_max--; - } + } else { + if ((l = strlen (serv))) + serv[--l] = 0; + if (strlen (serv) - 6 < serv_min && serv_min) { + serv_min--; + serv_max--; + } } break; default: if (key < 32 || key > 127) break; if (sedit_state) { - l = strlen(desc); + l = strlen (desc); if (l < 254) { - desc[l+1] = 0; + desc[l + 1] = 0; desc[l] = key; } - if (strlen(desc) > desc_max) { + if (strlen (desc) > desc_max) { desc_min++; desc_max++; } - } - else { - l = strlen(serv); + } else { + l = strlen (serv); if (l < 254) { - serv[l+1] = 0; + serv[l + 1] = 0; serv[l] = key; } - if (strlen(serv) > serv_max) { + if (strlen (serv) > serv_max) { serv_min++; serv_max++; } @@ -1306,40 +1346,40 @@ void M_SEdit_Key (int key) { } } -void M_Quit_Draw (void) +void +M_Quit_Draw (void) { #define VSTR(x) #x #define VSTR2(x) VSTR(x) -// char *cmsg[] = { +// char *cmsg[] = { // 0123456789012345678901234567890123456789 -// "0 QuakeWorld", -// "1 version " VSTR2(VERSION) " by id Software", -// "0Programming", -// "1 John Carmack Michael Abrash", -// "1 John Cash Christian Antkow", -// "0Additional Programming", -// "1 Dave 'Zoid' Kirsch", -// "1 Jack 'morbid' Mathews", -// "0Id Software is not responsible for", -// "0providing technical support for", -// "0QUAKEWORLD(tm). (c)1996 Id Software,", -// "0Inc. All Rights Reserved.", -// "0QUAKEWORLD(tm) is a trademark of Id", -// "0Software, Inc.", -// "1NOTICE: THE COPYRIGHT AND TRADEMARK", -// "1NOTICES APPEARING IN YOUR COPY OF", -// "1QUAKE(r) ARE NOT MODIFIED BY THE USE", -// "1OF QUAKEWORLD(tm) AND REMAIN IN FULL", -// "1FORCE.", -// "0NIN(r) is a registered trademark", -// "0licensed to Nothing Interactive, Inc.", -// "0All rights reserved. Press y to exit", -// NULL }; -// char **p; -// int y; +// "0 QuakeWorld", +// "1 version " VSTR2(VERSION) " by id Software", +// "0Programming", +// "1 John Carmack Michael Abrash", +// "1 John Cash Christian Antkow", +// "0Additional Programming", +// "1 Dave 'Zoid' Kirsch", +// "1 Jack 'morbid' Mathews", +// "0Id Software is not responsible for", +// "0providing technical support for", +// "0QUAKEWORLD(tm). (c)1996 Id Software,", +// "0Inc. All Rights Reserved.", +// "0QUAKEWORLD(tm) is a trademark of Id", +// "0Software, Inc.", +// "1NOTICE: THE COPYRIGHT AND TRADEMARK", +// "1NOTICES APPEARING IN YOUR COPY OF", +// "1QUAKE(r) ARE NOT MODIFIED BY THE USE", +// "1OF QUAKEWORLD(tm) AND REMAIN IN FULL", +// "1FORCE.", +// "0NIN(r) is a registered trademark", +// "0licensed to Nothing Interactive, Inc.", +// "0All rights reserved. Press y to exit", +// NULL }; +// char **p; +// int y; - if (wasInMenus) - { + if (wasInMenus) { m_state = m_quit_prevstate; m_recursiveDraw = true; M_Draw (); @@ -1352,14 +1392,14 @@ void M_Quit_Draw (void) if (**p == '0') M_PrintWhite (16, y, *p + 1); else - M_Print (16, y, *p + 1); + M_Print (16, y, *p + 1); } #else M_DrawTextBox (56, 76, 24, 4); - M_Print (64, 84, quitMessage[msgNumber*4+0]); - M_Print (64, 92, quitMessage[msgNumber*4+1]); - M_Print (64, 100, quitMessage[msgNumber*4+2]); - M_Print (64, 108, quitMessage[msgNumber*4+3]); + M_Print (64, 84, quitMessage[msgNumber * 4 + 0]); + M_Print (64, 92, quitMessage[msgNumber * 4 + 1]); + M_Print (64, 100, quitMessage[msgNumber * 4 + 2]); + M_Print (64, 108, quitMessage[msgNumber * 4 + 3]); #endif } @@ -1369,7 +1409,8 @@ void M_Quit_Draw (void) /* Menu Subsystem */ -void M_Init (void) +void +M_Init (void) { Cmd_AddCommand ("togglemenu", M_ToggleMenu_f); @@ -1382,115 +1423,109 @@ void M_Init (void) } -void M_Draw (void) +void +M_Draw (void) { if (m_state == m_none || key_dest != key_menu) return; - if (!m_recursiveDraw) - { + if (!m_recursiveDraw) { scr_copyeverything = 1; - if (scr_con_current) - { + if (scr_con_current) { Draw_ConsoleBackground (vid.height); VID_UnlockBuffer (); S_ExtraUpdate (); VID_LockBuffer (); - } - else + } else Draw_FadeScreen (); scr_fullupdate = 0; - } - else - { + } else { m_recursiveDraw = false; } - switch (m_state) - { - case m_none: - break; + switch (m_state) { + case m_none: + break; - case m_main: - M_Main_Draw (); - break; + case m_main: + M_Main_Draw (); + break; - case m_singleplayer: - M_SinglePlayer_Draw (); - break; + case m_singleplayer: + M_SinglePlayer_Draw (); + break; - case m_load: -// M_Load_Draw (); - break; + case m_load: +// M_Load_Draw (); + break; - case m_save: -// M_Save_Draw (); - break; + case m_save: +// M_Save_Draw (); + break; - case m_multiplayer: - M_MultiPlayer_Draw (); - break; + case m_multiplayer: + M_MultiPlayer_Draw (); + break; - case m_setup: -// M_Setup_Draw (); - break; + case m_setup: +// M_Setup_Draw (); + break; - case m_net: -// M_Net_Draw (); - break; + case m_net: +// M_Net_Draw (); + break; - case m_options: - M_Options_Draw (); - break; + case m_options: + M_Options_Draw (); + break; - case m_keys: - M_Keys_Draw (); - break; + case m_keys: + M_Keys_Draw (); + break; - case m_video: - M_Video_Draw (); - break; + case m_video: + M_Video_Draw (); + break; - case m_help: - M_Help_Draw (); - break; + case m_help: + M_Help_Draw (); + break; - case m_quit: - M_Quit_Draw (); - break; + case m_quit: + M_Quit_Draw (); + break; - case m_serialconfig: -// M_SerialConfig_Draw (); - break; + case m_serialconfig: +// M_SerialConfig_Draw (); + break; - case m_modemconfig: -// M_ModemConfig_Draw (); - break; + case m_modemconfig: +// M_ModemConfig_Draw (); + break; - case m_lanconfig: -// M_LanConfig_Draw (); - break; + case m_lanconfig: +// M_LanConfig_Draw (); + break; - case m_gameoptions: -// M_GameOptions_Draw (); - break; + case m_gameoptions: +// M_GameOptions_Draw (); + break; - case m_search: -// M_Search_Draw (); - break; + case m_search: +// M_Search_Draw (); + break; -// case m_slist: -// M_ServerList_Draw (); -// break; - case m_sedit: - M_SEdit_Draw (); - break; +// case m_slist: +// M_ServerList_Draw (); +// break; + case m_sedit: + M_SEdit_Draw (); + break; } - if (m_entersound) - { + if (m_entersound) { S_LocalSound ("misc/menu2.wav"); m_entersound = false; } @@ -1501,88 +1536,86 @@ void M_Draw (void) } -void M_Keydown (int key) +void +M_Keydown (int key) { - switch (m_state) - { - case m_none: - return; + switch (m_state) { + case m_none: + return; - case m_main: - M_Main_Key (key); - return; + case m_main: + M_Main_Key (key); + return; - case m_singleplayer: - M_SinglePlayer_Key (key); - return; + case m_singleplayer: + M_SinglePlayer_Key (key); + return; - case m_load: -// M_Load_Key (key); - return; + case m_load: +// M_Load_Key (key); + return; - case m_save: -// M_Save_Key (key); - return; + case m_save: +// M_Save_Key (key); + return; - case m_multiplayer: - M_MultiPlayer_Key (key); - return; + case m_multiplayer: + M_MultiPlayer_Key (key); + return; - case m_setup: -// M_Setup_Key (key); - return; + case m_setup: +// M_Setup_Key (key); + return; - case m_net: -// M_Net_Key (key); - return; + case m_net: +// M_Net_Key (key); + return; - case m_options: - M_Options_Key (key); - return; + case m_options: + M_Options_Key (key); + return; - case m_keys: - M_Keys_Key (key); - return; + case m_keys: + M_Keys_Key (key); + return; - case m_video: - M_Video_Key (key); - return; + case m_video: + M_Video_Key (key); + return; - case m_help: - M_Help_Key (key); - return; + case m_help: + M_Help_Key (key); + return; - case m_quit: - M_Quit_Key (key); - return; + case m_quit: + M_Quit_Key (key); + return; - case m_serialconfig: -// M_SerialConfig_Key (key); - return; + case m_serialconfig: +// M_SerialConfig_Key (key); + return; - case m_modemconfig: -// M_ModemConfig_Key (key); - return; + case m_modemconfig: +// M_ModemConfig_Key (key); + return; - case m_lanconfig: -// M_LanConfig_Key (key); - return; + case m_lanconfig: +// M_LanConfig_Key (key); + return; - case m_gameoptions: -// M_GameOptions_Key (key); - return; + case m_gameoptions: +// M_GameOptions_Key (key); + return; - case m_search: -// M_Search_Key (key); - break; + case m_search: +// M_Search_Key (key); + break; -// case m_slist: -// M_ServerList_Key (key); -// return; - case m_sedit: - M_SEdit_Key (key); - break; +// case m_slist: +// M_ServerList_Key (key); +// return; + case m_sedit: + M_SEdit_Key (key); + break; } } - - diff --git a/source/model.c b/source/model.c index 9ac06ca..c00c43d 100644 --- a/source/model.c +++ b/source/model.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -46,36 +46,39 @@ #include "server.h" #include "qendian.h" -void Mod_LoadAliasModel(model_t *mod, void *buf); -void Mod_LoadSpriteModel(model_t *mod, void *buf); -void Mod_LoadBrushModel(model_t *mod, void *buf); +void Mod_LoadAliasModel (model_t *mod, void *buf); +void Mod_LoadSpriteModel (model_t *mod, void *buf); +void Mod_LoadBrushModel (model_t *mod, void *buf); -model_t *loadmodel; -char loadname[32]; // for hunk tags +model_t *loadmodel; +char loadname[32]; // for hunk tags #define MAX_MOD_KNOWN 512 -model_t mod_known[MAX_MOD_KNOWN]; -int mod_numknown; +model_t mod_known[MAX_MOD_KNOWN]; +int mod_numknown; -cvar_t *gl_subdivide_size; +cvar_t *gl_subdivide_size; -extern byte mod_novis[MAX_MAP_LEAFS/8]; +extern byte mod_novis[MAX_MAP_LEAFS / 8]; -texture_t *r_notexture_mip; +texture_t *r_notexture_mip; /* =============== Mod_Init =============== */ -void Mod_Init (void) +void +Mod_Init (void) { - memset (mod_novis, 0xff, sizeof(mod_novis)); + memset (mod_novis, 0xff, sizeof (mod_novis)); } -void Mod_Init_Cvars (void) +void +Mod_Init_Cvars (void) { - gl_subdivide_size = Cvar_Get("gl_subdivide_size", "128", CVAR_ARCHIVE, "None"); + gl_subdivide_size = + Cvar_Get ("gl_subdivide_size", "128", CVAR_ARCHIVE, "None"); } /* @@ -83,12 +86,13 @@ void Mod_Init_Cvars (void) Mod_ClearAll =================== */ -void Mod_ClearAll (void) +void +Mod_ClearAll (void) { - int i; - model_t *mod; - - for (i=0 , mod=mod_known ; itype != mod_alias) mod->needload = true; } @@ -99,23 +103,23 @@ Mod_FindName ================== */ -model_t *Mod_FindName (char *name) +model_t * +Mod_FindName (char *name) { - int i; - model_t *mod; - + int i; + model_t *mod; + if (!name[0]) SV_Error ("Mod_ForName: NULL name"); - + // // search the currently loaded models // - for (i=0 , mod=mod_known ; iname, name) ) + for (i = 0, mod = mod_known; i < mod_numknown; i++, mod++) + if (!strcmp (mod->name, name)) break; - - if (i == mod_numknown) - { + + if (i == mod_numknown) { if (mod_numknown == MAX_MOD_KNOWN) SV_Error ("mod_numknown == MAX_MOD_KNOWN"); strcpy (mod->name, name); @@ -133,40 +137,37 @@ Mod_LoadModel Loads a model into the cache ================== */ -model_t *Mod_LoadModel (model_t *mod, qboolean crash) +model_t * +Mod_LoadModel (model_t *mod, qboolean crash) { - void *d; + void *d; unsigned int *buf; - byte stackbuf[1024]; // avoid dirtying the cache heap + byte stackbuf[1024]; // avoid dirtying the cache heap - if (!mod->needload) - { - if (mod->type == mod_alias) - { + if (!mod->needload) { + if (mod->type == mod_alias) { d = Cache_Check (&mod->cache); if (d) return mod; - } - else - return mod; // not cached at all + } else + return mod; // not cached at all } - // // load the file // - buf = (unsigned int *)COM_LoadStackFile (mod->name, stackbuf, sizeof(stackbuf)); - if (!buf) - { + buf = + (unsigned int *) COM_LoadStackFile (mod->name, stackbuf, + sizeof (stackbuf)); + if (!buf) { if (crash) SV_Error ("Mod_NumForName: %s not found", mod->name); return NULL; } - // // allocate a new model // COM_FileBase (mod->name, loadname); - + loadmodel = mod; // @@ -176,20 +177,19 @@ model_t *Mod_LoadModel (model_t *mod, qboolean crash) // call the apropriate loader mod->needload = false; mod->hasfullbrights = false; - - switch (LittleLong(*(unsigned int *)buf)) - { - case IDPOLYHEADER: - Mod_LoadAliasModel (mod, buf); - break; - - case IDSPRITEHEADER: - Mod_LoadSpriteModel (mod, buf); - break; - - default: - Mod_LoadBrushModel (mod, buf); - break; + + switch (LittleLong (*(unsigned int *) buf)) { + case IDPOLYHEADER: + Mod_LoadAliasModel (mod, buf); + break; + + case IDSPRITEHEADER: + Mod_LoadSpriteModel (mod, buf); + break; + + default: + Mod_LoadBrushModel (mod, buf); + break; } return mod; @@ -202,13 +202,14 @@ Mod_ForName Loads in a model for the given name ================== */ -model_t *Mod_ForName (char *name, qboolean crash) +model_t * +Mod_ForName (char *name, qboolean crash) { - model_t *mod; - + model_t *mod; + mod = Mod_FindName (name); - - Con_DPrintf("Mod_ForName: %s, %p\n", name, mod); + + Con_DPrintf ("Mod_ForName: %s, %p\n", name, mod); return Mod_LoadModel (mod, crash); } @@ -219,16 +220,17 @@ Mod_Init Caches the data if needed =============== */ -void *Mod_Extradata (model_t *mod) +void * +Mod_Extradata (model_t *mod) { - void *r; - + void *r; + r = Cache_Check (&mod->cache); if (r) return r; Mod_LoadModel (mod, true); - + if (!mod->cache.data) SV_Error ("Mod_Extradata: caching failed"); return mod->cache.data; @@ -240,14 +242,14 @@ Mod_TouchModel ================== */ -void Mod_TouchModel (char *name) +void +Mod_TouchModel (char *name) { - model_t *mod; - + model_t *mod; + mod = Mod_FindName (name); - - if (!mod->needload) - { + + if (!mod->needload) { if (mod->type == mod_alias) Cache_Check (&mod->cache); } @@ -258,15 +260,14 @@ void Mod_TouchModel (char *name) Mod_Print ================ */ -void Mod_Print (void) +void +Mod_Print (void) { - int i; - model_t *mod; + int i; + model_t *mod; Con_Printf ("Cached models:\n"); - for (i=0, mod=mod_known ; i < mod_numknown ; i++, mod++) - { - Con_Printf ("%8p : %s\n",mod->cache.data, mod->name); + for (i = 0, mod = mod_known; i < mod_numknown; i++, mod++) { + Con_Printf ("%8p : %s\n", mod->cache.data, mod->name); } } - diff --git a/source/model_alias.c b/source/model_alias.c index ee3d35e..8ebf51d 100644 --- a/source/model_alias.c +++ b/source/model_alias.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -53,8 +53,10 @@ extern char loadname[]; extern model_t *loadmodel; -void *Mod_LoadAllSkins (int numskins, daliasskintype_t *pskintype, int *pskinindex); -void GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr); +void *Mod_LoadAllSkins (int numskins, daliasskintype_t *pskintype, + + int *pskinindex); +void GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr); /* ============================================================================== @@ -64,18 +66,18 @@ ALIAS MODELS ============================================================================== */ -aliashdr_t *pheader; +aliashdr_t *pheader; -stvert_t stverts[MAXALIASVERTS]; -mtriangle_t triangles[MAXALIASTRIS]; +stvert_t stverts[MAXALIASVERTS]; +mtriangle_t triangles[MAXALIASTRIS]; // a pose is a single set of vertexes. a frame may be // an animating sequence of poses -trivertx_t *poseverts[MAXALIASFRAMES]; -int posenum = 0; +trivertx_t *poseverts[MAXALIASFRAMES]; +int posenum = 0; -void *Mod_LoadAliasFrame (void * pin, maliasframedesc_t *frame); -void *Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame); +void *Mod_LoadAliasFrame (void *pin, maliasframedesc_t *frame); +void *Mod_LoadAliasGroup (void *pin, maliasframedesc_t *frame); //========================================================================= @@ -85,62 +87,65 @@ void *Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame); Mod_LoadAliasModel ================= */ -void Mod_LoadAliasModel (model_t *mod, void *buffer) +void +Mod_LoadAliasModel (model_t *mod, void *buffer) { - int i, j; - mdl_t *pinmodel, *pmodel; - stvert_t *pinstverts; - dtriangle_t *pintriangles; - int version, numframes; - int size; - daliasframetype_t *pframetype; - daliasskintype_t *pskintype; - int start, end, total; + int i, j; + mdl_t *pinmodel, *pmodel; + stvert_t *pinstverts; + dtriangle_t *pintriangles; + int version, numframes; + int size; + daliasframetype_t *pframetype; + daliasskintype_t *pskintype; + int start, end, total; - if (!strcmp(loadmodel->name, "progs/player.mdl") || - !strcmp(loadmodel->name, "progs/eyes.mdl")) { + if (!strcmp (loadmodel->name, "progs/player.mdl") || + !strcmp (loadmodel->name, "progs/eyes.mdl")) { unsigned short crc; - byte *p; - int len; - char st[40]; + byte *p; + int len; + char st[40]; - CRC_Init(&crc); + CRC_Init (&crc); for (len = com_filesize, p = buffer; len; len--, p++) - CRC_ProcessByte(&crc, *p); - - snprintf(st, sizeof(st), "%d", (int) crc); - Info_SetValueForKey (cls.userinfo, - !strcmp(loadmodel->name, "progs/player.mdl") ? pmodel_name : emodel_name, - st, MAX_INFO_STRING); + CRC_ProcessByte (&crc, *p); + + snprintf (st, sizeof (st), "%d", (int) crc); + Info_SetValueForKey (cls.userinfo, + !strcmp (loadmodel->name, + "progs/player.mdl") ? pmodel_name : + emodel_name, st, MAX_INFO_STRING); if (cls.state >= ca_connected) { MSG_WriteByte (&cls.netchan.message, clc_stringcmd); - snprintf(st, sizeof(st), "setinfo %s %d", - !strcmp(loadmodel->name, "progs/player.mdl") ? pmodel_name : emodel_name, - (int)crc); + snprintf (st, sizeof (st), "setinfo %s %d", + !strcmp (loadmodel->name, + "progs/player.mdl") ? pmodel_name : emodel_name, + (int) crc); SZ_Print (&cls.netchan.message, st); } } - + start = Hunk_LowMark (); - pinmodel = (mdl_t *)buffer; + pinmodel = (mdl_t *) buffer; version = LittleLong (pinmodel->version); if (version != ALIAS_VERSION) SV_Error ("%s has wrong version number (%i should be %i)", - mod->name, version, ALIAS_VERSION); + mod->name, version, ALIAS_VERSION); // // allocate space for a working header, plus all the data except the frames, // skin and group info // - size = (int)&((aliashdr_t*)0)->frames[LittleLong (pinmodel->numframes)]; + size = (int) &((aliashdr_t *) 0)->frames[LittleLong (pinmodel->numframes)]; pheader = Hunk_AllocName (size, loadname); - memset(pheader, 0, size); + memset (pheader, 0, size); pmodel = &pheader->mdl; - pheader->model = (byte*)pmodel - (byte*)pheader; - + pheader->model = (byte *) pmodel - (byte *) pheader; + mod->flags = LittleLong (pinmodel->flags); // @@ -153,7 +158,7 @@ void Mod_LoadAliasModel (model_t *mod, void *buffer) if (pmodel->skinheight > MAX_LBM_HEIGHT) SV_Error ("model %s has a skin taller than %d", mod->name, - MAX_LBM_HEIGHT); + MAX_LBM_HEIGHT); pmodel->numverts = LittleLong (pinmodel->numverts); @@ -177,8 +182,7 @@ void Mod_LoadAliasModel (model_t *mod, void *buffer) mod->synctype = LittleLong (pinmodel->synctype); mod->numframes = pmodel->numframes; - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { pmodel->scale[i] = LittleFloat (pinmodel->scale[i]); pmodel->scale_origin[i] = LittleFloat (pinmodel->scale_origin[i]); pmodel->eyeposition[i] = LittleFloat (pinmodel->eyeposition[i]); @@ -188,16 +192,16 @@ void Mod_LoadAliasModel (model_t *mod, void *buffer) // // load the skins // - pskintype = (daliasskintype_t *)&pinmodel[1]; - pskintype = Mod_LoadAllSkins (pheader->mdl.numskins, pskintype, &pheader->skindesc); + pskintype = (daliasskintype_t *) &pinmodel[1]; + pskintype = + Mod_LoadAllSkins (pheader->mdl.numskins, pskintype, &pheader->skindesc); // // load base s and t vertices // - pinstverts = (stvert_t *)pskintype; + pinstverts = (stvert_t *) pskintype; - for (i=0 ; imdl.numverts ; i++) - { + for (i = 0; i < pheader->mdl.numverts; i++) { stverts[i].onseam = LittleLong (pinstverts[i].onseam); stverts[i].s = LittleLong (pinstverts[i].s); stverts[i].t = LittleLong (pinstverts[i].t); @@ -206,16 +210,14 @@ void Mod_LoadAliasModel (model_t *mod, void *buffer) // // load triangle lists // - pintriangles = (dtriangle_t *)&pinstverts[pheader->mdl.numverts]; + pintriangles = (dtriangle_t *) &pinstverts[pheader->mdl.numverts]; - for (i=0 ; imdl.numtris ; i++) - { + for (i = 0; i < pheader->mdl.numtris; i++) { triangles[i].facesfront = LittleLong (pintriangles[i].facesfront); - for (j=0 ; j<3 ; j++) - { + for (j = 0; j < 3; j++) { triangles[i].vertindex[j] = - LittleLong (pintriangles[i].vertindex[j]); + LittleLong (pintriangles[i].vertindex[j]); } } @@ -223,24 +225,20 @@ void Mod_LoadAliasModel (model_t *mod, void *buffer) // load the frames // posenum = 0; - pframetype = (daliasframetype_t *)&pintriangles[pheader->mdl.numtris]; + pframetype = (daliasframetype_t *) &pintriangles[pheader->mdl.numtris]; - for (i=0 ; itype); pheader->frames[i].type = frametype; - if (frametype == ALIAS_SINGLE) - { + if (frametype == ALIAS_SINGLE) { pframetype = (daliasframetype_t *) - Mod_LoadAliasFrame (pframetype + 1, &pheader->frames[i]); - } - else - { + Mod_LoadAliasFrame (pframetype + 1, &pheader->frames[i]); + } else { pframetype = (daliasframetype_t *) - Mod_LoadAliasGroup (pframetype + 1, &pheader->frames[i]); + Mod_LoadAliasGroup (pframetype + 1, &pheader->frames[i]); } } @@ -252,17 +250,17 @@ void Mod_LoadAliasModel (model_t *mod, void *buffer) mod->mins[0] = mod->mins[1] = mod->mins[2] = -16; mod->maxs[0] = mod->maxs[1] = mod->maxs[2] = 16; - // + // // build the draw lists - // + // GL_MakeAliasModelDisplayLists (mod, pheader); // // move the complete, relocatable alias model to the cache -// +// end = Hunk_LowMark (); total = end - start; - + Cache_Alloc (&mod->cache, total, loadname); if (!mod->cache.data) return; diff --git a/source/model_brush.c b/source/model_brush.c index 441fad3..d0986b2 100644 --- a/source/model_brush.c +++ b/source/model_brush.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -40,43 +40,43 @@ #include "server.h" #include "checksum.h" -extern model_t *loadmodel; -extern char loadname[]; +extern model_t *loadmodel; +extern char loadname[]; -extern const int mod_lightmap_bytes; +extern const int mod_lightmap_bytes; -byte mod_novis[MAX_MAP_LEAFS/8]; +byte mod_novis[MAX_MAP_LEAFS / 8]; -void GL_SubdivideSurface (msurface_t *fa); +void GL_SubdivideSurface (msurface_t *fa); /* =============== Mod_PointInLeaf =============== */ -mleaf_t *Mod_PointInLeaf (vec3_t p, model_t *model) +mleaf_t * +Mod_PointInLeaf (vec3_t p, model_t *model) { - mnode_t *node; - float d; - mplane_t *plane; - + mnode_t *node; + float d; + mplane_t *plane; + if (!model || !model->nodes) SV_Error ("Mod_PointInLeaf: bad model"); node = model->nodes; - while (1) - { + while (1) { if (node->contents < 0) - return (mleaf_t *)node; + return (mleaf_t *) node; plane = node->plane; - d = DotProduct (p,plane->normal) - plane->dist; + d = DotProduct (p, plane->normal) - plane->dist; if (d > 0) node = node->children[0]; else node = node->children[1]; } - - return NULL; // never reached + + return NULL; // never reached } @@ -85,51 +85,48 @@ mleaf_t *Mod_PointInLeaf (vec3_t p, model_t *model) Mod_DecompressVis =================== */ -byte *Mod_DecompressVis (byte *in, model_t *model) +byte * +Mod_DecompressVis (byte * in, model_t *model) { - static byte decompressed[MAX_MAP_LEAFS/8]; - int c; - byte *out; - int row; + static byte decompressed[MAX_MAP_LEAFS / 8]; + int c; + byte *out; + int row; - row = (model->numleafs+7)>>3; + row = (model->numleafs + 7) >> 3; out = decompressed; #if 0 memcpy (out, in, row); #else - if (!in) - { // no vis info, so make all visible - while (row) - { + if (!in) { // no vis info, so make all visible + while (row) { *out++ = 0xff; row--; } - return decompressed; + return decompressed; } - do - { - if (*in) - { + do { + if (*in) { *out++ = *in++; continue; } - + c = in[1]; in += 2; - while (c) - { + while (c) { *out++ = 0; c--; } } while (out - decompressed < row); #endif - + return decompressed; } -byte *Mod_LeafPVS (mleaf_t *leaf, model_t *model) +byte * +Mod_LeafPVS (mleaf_t *leaf, model_t *model) { if (leaf == model->leafs) return mod_novis; @@ -144,7 +141,7 @@ byte *Mod_LeafPVS (mleaf_t *leaf, model_t *model) =============================================================================== */ -byte *mod_base; +byte *mod_base; /* @@ -152,148 +149,138 @@ byte *mod_base; Mod_LoadTextures ================= */ -void Mod_LoadTextures (lump_t *l) +void +Mod_LoadTextures (lump_t *l) { - int i, j, pixels, num, max, altmax; - miptex_t *mt; - texture_t *tx, *tx2; - texture_t *anims[10]; - texture_t *altanims[10]; + int i, j, pixels, num, max, altmax; + miptex_t *mt; + texture_t *tx, *tx2; + texture_t *anims[10]; + texture_t *altanims[10]; dmiptexlump_t *m; - if (!l->filelen) - { + if (!l->filelen) { loadmodel->textures = NULL; return; } - m = (dmiptexlump_t *)(mod_base + l->fileofs); - - m->nummiptex = LittleLong (m->nummiptex); - - loadmodel->numtextures = m->nummiptex; - loadmodel->textures = Hunk_AllocName (m->nummiptex * sizeof(*loadmodel->textures) , loadname); + m = (dmiptexlump_t *) (mod_base + l->fileofs); - for (i=0 ; inummiptex ; i++) - { - m->dataofs[i] = LittleLong(m->dataofs[i]); + m->nummiptex = LittleLong (m->nummiptex); + + loadmodel->numtextures = m->nummiptex; + loadmodel->textures = + Hunk_AllocName (m->nummiptex * sizeof (*loadmodel->textures), loadname); + + for (i = 0; i < m->nummiptex; i++) { + m->dataofs[i] = LittleLong (m->dataofs[i]); if (m->dataofs[i] == -1) continue; - mt = (miptex_t *)((byte *)m + m->dataofs[i]); + mt = (miptex_t *) ((byte *) m + m->dataofs[i]); mt->width = LittleLong (mt->width); mt->height = LittleLong (mt->height); - for (j=0 ; joffsets[j] = LittleLong (mt->offsets[j]); - - if ( (mt->width & 15) || (mt->height & 15) ) + + if ((mt->width & 15) || (mt->height & 15)) SV_Error ("Texture %s is not 16 aligned", mt->name); - pixels = mt->width*mt->height/64*85; - tx = Hunk_AllocName (sizeof(texture_t) +pixels, loadname ); + pixels = mt->width * mt->height / 64 * 85; + tx = Hunk_AllocName (sizeof (texture_t) + pixels, loadname); + loadmodel->textures[i] = tx; - memcpy (tx->name, mt->name, sizeof(tx->name)); + memcpy (tx->name, mt->name, sizeof (tx->name)); tx->width = mt->width; tx->height = mt->height; - for (j=0 ; joffsets[j] = mt->offsets[j] + sizeof(texture_t) - sizeof(miptex_t); - // the pixels immediately follow the structures - memcpy ( tx+1, mt+1, pixels); + for (j = 0; j < MIPLEVELS; j++) + tx->offsets[j] = - if (!strncmp(mt->name,"sky",3)) + mt->offsets[j] + sizeof (texture_t) - sizeof (miptex_t); + // the pixels immediately follow the structures + memcpy (tx + 1, mt + 1, pixels); + + if (!strncmp (mt->name, "sky", 3)) R_InitSky (tx); - else - { - Mod_ProcessTexture(mt, tx); + else { + Mod_ProcessTexture (mt, tx); } } // // sequence the animations // - for (i=0 ; inummiptex ; i++) - { + for (i = 0; i < m->nummiptex; i++) { tx = loadmodel->textures[i]; if (!tx || tx->name[0] != '+') continue; if (tx->anim_next) - continue; // allready sequenced + continue; // allready sequenced - // find the number of frames in the animation - memset (anims, 0, sizeof(anims)); - memset (altanims, 0, sizeof(altanims)); + // find the number of frames in the animation + memset (anims, 0, sizeof (anims)); + memset (altanims, 0, sizeof (altanims)); max = tx->name[1]; altmax = 0; if (max >= 'a' && max <= 'z') max -= 'a' - 'A'; - if (max >= '0' && max <= '9') - { + if (max >= '0' && max <= '9') { max -= '0'; altmax = 0; anims[max] = tx; max++; - } - else if (max >= 'A' && max <= 'J') - { + } else if (max >= 'A' && max <= 'J') { altmax = max - 'A'; max = 0; altanims[altmax] = tx; altmax++; - } - else + } else SV_Error ("Bad animating texture %s", tx->name); - for (j=i+1 ; jnummiptex ; j++) - { + for (j = i + 1; j < m->nummiptex; j++) { tx2 = loadmodel->textures[j]; if (!tx2 || tx2->name[0] != '+') continue; - if (strcmp (tx2->name+2, tx->name+2)) + if (strcmp (tx2->name + 2, tx->name + 2)) continue; num = tx2->name[1]; if (num >= 'a' && num <= 'z') num -= 'a' - 'A'; - if (num >= '0' && num <= '9') - { + if (num >= '0' && num <= '9') { num -= '0'; anims[num] = tx2; - if (num+1 > max) + if (num + 1 > max) max = num + 1; - } - else if (num >= 'A' && num <= 'J') - { + } else if (num >= 'A' && num <= 'J') { num = num - 'A'; altanims[num] = tx2; - if (num+1 > altmax) - altmax = num+1; - } - else + if (num + 1 > altmax) + altmax = num + 1; + } else SV_Error ("Bad animating texture %s", tx->name); } - + #define ANIM_CYCLE 2 - // link them all together - for (j=0 ; jname); + SV_Error ("Missing frame %i of %s", j, tx->name); tx2->anim_total = max * ANIM_CYCLE; tx2->anim_min = j * ANIM_CYCLE; - tx2->anim_max = (j+1) * ANIM_CYCLE; - tx2->anim_next = anims[ (j+1)%max ]; + tx2->anim_max = (j + 1) * ANIM_CYCLE; + tx2->anim_next = anims[(j + 1) % max]; if (altmax) tx2->alternate_anims = altanims[0]; } - for (j=0 ; jname); + SV_Error ("Missing frame %i of %s", j, tx->name); tx2->anim_total = altmax * ANIM_CYCLE; tx2->anim_min = j * ANIM_CYCLE; - tx2->anim_max = (j+1) * ANIM_CYCLE; - tx2->anim_next = altanims[ (j+1)%altmax ]; + tx2->anim_max = (j + 1) * ANIM_CYCLE; + tx2->anim_next = altanims[(j + 1) % altmax]; if (max) tx2->alternate_anims = anims[0]; } @@ -305,14 +292,14 @@ void Mod_LoadTextures (lump_t *l) Mod_LoadVisibility ================= */ -void Mod_LoadVisibility (lump_t *l) +void +Mod_LoadVisibility (lump_t *l) { - if (!l->filelen) - { + if (!l->filelen) { loadmodel->visdata = NULL; return; } - loadmodel->visdata = Hunk_AllocName ( l->filelen, loadname); + loadmodel->visdata = Hunk_AllocName (l->filelen, loadname); memcpy (loadmodel->visdata, mod_base + l->fileofs, l->filelen); } @@ -322,14 +309,14 @@ void Mod_LoadVisibility (lump_t *l) Mod_LoadEntities ================= */ -void Mod_LoadEntities (lump_t *l) +void +Mod_LoadEntities (lump_t *l) { - if (!l->filelen) - { + if (!l->filelen) { loadmodel->entities = NULL; return; } - loadmodel->entities = Hunk_AllocName ( l->filelen, loadname); + loadmodel->entities = Hunk_AllocName (l->filelen, loadname); memcpy (loadmodel->entities, mod_base + l->fileofs, l->filelen); } @@ -339,23 +326,23 @@ void Mod_LoadEntities (lump_t *l) Mod_LoadVertexes ================= */ -void Mod_LoadVertexes (lump_t *l) +void +Mod_LoadVertexes (lump_t *l) { - dvertex_t *in; - mvertex_t *out; - int i, count; + dvertex_t *in; + mvertex_t *out; + int i, count; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->vertexes = out; loadmodel->numvertexes = count; - for ( i=0 ; iposition[0] = LittleFloat (in->point[0]); out->position[1] = LittleFloat (in->point[1]); out->position[2] = LittleFloat (in->point[2]); @@ -367,30 +354,29 @@ void Mod_LoadVertexes (lump_t *l) Mod_LoadSubmodels ================= */ -void Mod_LoadSubmodels (lump_t *l) +void +Mod_LoadSubmodels (lump_t *l) { - dmodel_t *in; - dmodel_t *out; - int i, j, count; + dmodel_t *in; + dmodel_t *out; + int i, j, count; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->submodels = out; loadmodel->numsubmodels = count; - for ( i=0 ; imins[j] = LittleFloat (in->mins[j]) - 1; out->maxs[j] = LittleFloat (in->maxs[j]) + 1; out->origin[j] = LittleFloat (in->origin[j]); } - for (j=0 ; jheadnode[j] = LittleLong (in->headnode[j]); out->visleafs = LittleLong (in->visleafs); out->firstface = LittleLong (in->firstface); @@ -403,25 +389,25 @@ void Mod_LoadSubmodels (lump_t *l) Mod_LoadEdges ================= */ -void Mod_LoadEdges (lump_t *l) +void +Mod_LoadEdges (lump_t *l) { - dedge_t *in; - medge_t *out; - int i, count; + dedge_t *in; + medge_t *out; + int i, count; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( (count + 1) * sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName ((count + 1) * sizeof (*out), loadname); loadmodel->edges = out; loadmodel->numedges = count; - for ( i=0 ; iv[0] = (unsigned short)LittleShort(in->v[0]); - out->v[1] = (unsigned short)LittleShort(in->v[1]); + for (i = 0; i < count; i++, in++, out++) { + out->v[0] = (unsigned short) LittleShort (in->v[0]); + out->v[1] = (unsigned short) LittleShort (in->v[1]); } } @@ -430,33 +416,33 @@ void Mod_LoadEdges (lump_t *l) Mod_LoadTexinfo ================= */ -void Mod_LoadTexinfo (lump_t *l) +void +Mod_LoadTexinfo (lump_t *l) { - texinfo_t *in; + texinfo_t *in; mtexinfo_t *out; - int i, j, count; - int miptex; - float len1, len2; + int i, j, count; + int miptex; + float len1, len2; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->texinfo = out; loadmodel->numtexinfo = count; - for ( i=0 ; ivecs[0][j] = LittleFloat (in->vecs[0][j]); out->vecs[1][j] = LittleFloat (in->vecs[1][j]); } len1 = Length (out->vecs[0]); len2 = Length (out->vecs[1]); - len1 = (len1 + len2)/2; + len1 = (len1 + len2) / 2; if (len1 < 0.32) out->mipadjust = 4; else if (len1 < 0.49) @@ -468,20 +454,16 @@ void Mod_LoadTexinfo (lump_t *l) miptex = LittleLong (in->miptex); out->flags = LittleLong (in->flags); - - if (!loadmodel->textures) - { + + if (!loadmodel->textures) { out->texture = r_notexture_mip; // checkerboard texture out->flags = 0; - } - else - { + } else { if (miptex >= loadmodel->numtextures) SV_Error ("miptex >= loadmodel->numtextures"); out->texture = loadmodel->textures[miptex]; - if (!out->texture) - { - out->texture = r_notexture_mip; // texture not found + if (!out->texture) { + out->texture = r_notexture_mip; // texture not found out->flags = 0; } } @@ -495,33 +477,31 @@ CalcSurfaceExtents Fills in s->texturemins[] and s->extents[] ================ */ -void CalcSurfaceExtents (msurface_t *s) +void +CalcSurfaceExtents (msurface_t *s) { - float mins[2], maxs[2], val; - int i,j, e; - mvertex_t *v; - mtexinfo_t *tex; - int bmins[2], bmaxs[2]; + float mins[2], maxs[2], val; + int i, j, e; + mvertex_t *v; + mtexinfo_t *tex; + int bmins[2], bmaxs[2]; mins[0] = mins[1] = 999999; maxs[0] = maxs[1] = -99999; tex = s->texinfo; - - for (i=0 ; inumedges ; i++) - { - e = loadmodel->surfedges[s->firstedge+i]; + + for (i = 0; i < s->numedges; i++) { + e = loadmodel->surfedges[s->firstedge + i]; if (e >= 0) v = &loadmodel->vertexes[loadmodel->edges[e].v[0]]; else v = &loadmodel->vertexes[loadmodel->edges[-e].v[1]]; - - for (j=0 ; j<2 ; j++) - { - val = v->position[0] * tex->vecs[j][0] + + + for (j = 0; j < 2; j++) { + val = v->position[0] * tex->vecs[j][0] + v->position[1] * tex->vecs[j][1] + - v->position[2] * tex->vecs[j][2] + - tex->vecs[j][3]; + v->position[2] * tex->vecs[j][2] + tex->vecs[j][3]; if (val < mins[j]) mins[j] = val; if (val > maxs[j]) @@ -529,14 +509,13 @@ void CalcSurfaceExtents (msurface_t *s) } } - for (i=0 ; i<2 ; i++) - { - bmins[i] = floor(mins[i]/16); - bmaxs[i] = ceil(maxs[i]/16); + for (i = 0; i < 2; i++) { + bmins[i] = floor (mins[i] / 16); + bmaxs[i] = ceil (maxs[i] / 16); s->texturemins[i] = bmins[i] * 16; s->extents[i] = (bmaxs[i] - bmins[i]) * 16; - if ( !(tex->flags & TEX_SPECIAL) && s->extents[i] > 512 /* 256 */ ) + if (!(tex->flags & TEX_SPECIAL) && s->extents[i] > 512 /* 256 */ ) SV_Error ("Bad surface extents"); } } @@ -547,66 +526,68 @@ void CalcSurfaceExtents (msurface_t *s) Mod_LoadFaces ================= */ -void Mod_LoadFaces (lump_t *l) +void +Mod_LoadFaces (lump_t *l) { - dface_t *in; - msurface_t *out; - int i, count, surfnum; - int planenum, side; + dface_t *in; + msurface_t *out; + int i, count, surfnum; + int planenum, side; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->surfaces = out; loadmodel->numsurfaces = count; - for ( surfnum=0 ; surfnumfirstedge = LittleLong(in->firstedge); - out->numedges = LittleShort(in->numedges); + for (surfnum = 0; surfnum < count; surfnum++, in++, out++) { + out->firstedge = LittleLong (in->firstedge); + out->numedges = LittleShort (in->numedges); out->flags = 0; - planenum = LittleShort(in->planenum); - side = LittleShort(in->side); + planenum = LittleShort (in->planenum); + side = LittleShort (in->side); if (side) - out->flags |= SURF_PLANEBACK; + out->flags |= SURF_PLANEBACK; out->plane = loadmodel->planes + planenum; out->texinfo = loadmodel->texinfo + LittleShort (in->texinfo); CalcSurfaceExtents (out); - - // lighting info - for (i=0 ; istyles[i] = in->styles[i]; - i = LittleLong(in->lightofs); + i = LittleLong (in->lightofs); if (i == -1) out->samples = NULL; else out->samples = loadmodel->lightdata + (i * mod_lightmap_bytes); - + // set the drawing flags flag // fixme: do this right?-) - if (!out->texinfo->texture) continue; - if (!out->texinfo->texture->name) continue; + if (!out->texinfo->texture) + continue; + if (!out->texinfo->texture->name) + continue; - if (!strncmp(out->texinfo->texture->name,"sky",3)) // sky + if (!strncmp (out->texinfo->texture->name, "sky", 3)) // sky { - void BuildSurfaceDisplayList (msurface_t*); + void BuildSurfaceDisplayList (msurface_t *); + out->flags |= (SURF_DRAWSKY | SURF_DRAWTILED); continue; } - - if (out->texinfo->texture->name[0] == '*') // turbulent + + if (out->texinfo->texture->name[0] == '*') // turbulent { out->flags |= (SURF_DRAWTURB | SURF_DRAWTILED); - for (i=0 ; i<2 ; i++) - { + for (i = 0; i < 2; i++) { out->extents[i] = 16384; out->texturemins[i] = -8192; } @@ -622,7 +603,8 @@ void Mod_LoadFaces (lump_t *l) Mod_SetParent ================= */ -void Mod_SetParent (mnode_t *node, mnode_t *parent) +void +Mod_SetParent (mnode_t *node, mnode_t *parent) { node->parent = parent; if (node->contents < 0) @@ -636,45 +618,43 @@ void Mod_SetParent (mnode_t *node, mnode_t *parent) Mod_LoadNodes ================= */ -void Mod_LoadNodes (lump_t *l) +void +Mod_LoadNodes (lump_t *l) { - int i, j, count, p; - dnode_t *in; - mnode_t *out; + int i, j, count, p; + dnode_t *in; + mnode_t *out; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->nodes = out; loadmodel->numnodes = count; - for ( i=0 ; iminmaxs[j] = LittleShort (in->mins[j]); - out->minmaxs[3+j] = LittleShort (in->maxs[j]); + out->minmaxs[3 + j] = LittleShort (in->maxs[j]); } - - p = LittleLong(in->planenum); + + p = LittleLong (in->planenum); out->plane = loadmodel->planes + p; out->firstsurface = LittleShort (in->firstface); out->numsurfaces = LittleShort (in->numfaces); - - for (j=0 ; j<2 ; j++) - { + + for (j = 0; j < 2; j++) { p = LittleShort (in->children[j]); if (p >= 0) out->children[j] = loadmodel->nodes + p; else - out->children[j] = (mnode_t *)(loadmodel->leafs + (-1 - p)); + out->children[j] = (mnode_t *) (loadmodel->leafs + (-1 - p)); } } - + Mod_SetParent (loadmodel->nodes, NULL); // sets nodes and leafs } @@ -683,62 +663,61 @@ void Mod_LoadNodes (lump_t *l) Mod_LoadLeafs ================= */ -void Mod_LoadLeafs (lump_t *l) +void +Mod_LoadLeafs (lump_t *l) { - dleaf_t *in; - mleaf_t *out; - int i, j, count, p; - //char s[80]; - qboolean isnotmap = true; + dleaf_t *in; + mleaf_t *out; + int i, j, count, p; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + // char s[80]; + qboolean isnotmap = true; + + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->leafs = out; loadmodel->numleafs = count; - //snprintf(s, sizeof (s), "maps/%s.bsp", Info_ValueForKey(cl.serverinfo,"map")); - if (!strncmp("maps/", loadmodel->name,5)) + // snprintf(s, sizeof (s), "maps/%s.bsp", + // Info_ValueForKey(cl.serverinfo,"map")); + if (!strncmp ("maps/", loadmodel->name, 5)) isnotmap = false; - for ( i=0 ; iminmaxs[j] = LittleShort (in->mins[j]); - out->minmaxs[3+j] = LittleShort (in->maxs[j]); + out->minmaxs[3 + j] = LittleShort (in->maxs[j]); } - p = LittleLong(in->contents); + p = LittleLong (in->contents); out->contents = p; out->firstmarksurface = loadmodel->marksurfaces + - LittleShort(in->firstmarksurface); - out->nummarksurfaces = LittleShort(in->nummarksurfaces); - - p = LittleLong(in->visofs); + LittleShort (in->firstmarksurface); + out->nummarksurfaces = LittleShort (in->nummarksurfaces); + + p = LittleLong (in->visofs); if (p == -1) out->compressed_vis = NULL; else out->compressed_vis = loadmodel->visdata + p; out->efrags = NULL; - - for (j=0 ; j<4 ; j++) + + for (j = 0; j < 4; j++) out->ambient_sound_level[j] = in->ambient_level[j]; // gl underwater warp - if (out->contents != CONTENTS_EMPTY) - { - for (j=0 ; jnummarksurfaces ; j++) + if (out->contents != CONTENTS_EMPTY) { + for (j = 0; j < out->nummarksurfaces; j++) out->firstmarksurface[j]->flags |= SURF_UNDERWATER; } - if (isnotmap) - { - for (j=0 ; jnummarksurfaces ; j++) + if (isnotmap) { + for (j = 0; j < out->nummarksurfaces; j++) out->firstmarksurface[j]->flags |= SURF_DONTWARP; } - } + } } /* @@ -746,17 +725,18 @@ void Mod_LoadLeafs (lump_t *l) Mod_LoadClipnodes ================= */ -void Mod_LoadClipnodes (lump_t *l) +void +Mod_LoadClipnodes (lump_t *l) { dclipnode_t *in, *out; - int i, count; - hull_t *hull; + int i, count; + hull_t *hull; - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->clipnodes = out; loadmodel->numclipnodes = count; @@ -764,7 +744,7 @@ void Mod_LoadClipnodes (lump_t *l) hull = &loadmodel->hulls[1]; hull->clipnodes = out; hull->firstclipnode = 0; - hull->lastclipnode = count-1; + hull->lastclipnode = count - 1; hull->planes = loadmodel->planes; hull->clip_mins[0] = -16; hull->clip_mins[1] = -16; @@ -776,7 +756,7 @@ void Mod_LoadClipnodes (lump_t *l) hull = &loadmodel->hulls[2]; hull->clipnodes = out; hull->firstclipnode = 0; - hull->lastclipnode = count-1; + hull->lastclipnode = count - 1; hull->planes = loadmodel->planes; hull->clip_mins[0] = -32; hull->clip_mins[1] = -32; @@ -785,11 +765,10 @@ void Mod_LoadClipnodes (lump_t *l) hull->clip_maxs[1] = 32; hull->clip_maxs[2] = 64; - for (i=0 ; iplanenum = LittleLong(in->planenum); - out->children[0] = LittleShort(in->children[0]); - out->children[1] = LittleShort(in->children[1]); + for (i = 0; i < count; i++, out++, in++) { + out->planenum = LittleLong (in->planenum); + out->children[0] = LittleShort (in->children[0]); + out->children[1] = LittleShort (in->children[1]); } } @@ -800,29 +779,28 @@ Mod_MakeHull0 Deplicate the drawing hull structure as a clipping hull ================= */ -void Mod_MakeHull0 (void) +void +Mod_MakeHull0 (void) { - mnode_t *in, *child; + mnode_t *in, *child; dclipnode_t *out; - int i, j, count; - hull_t *hull; - - hull = &loadmodel->hulls[0]; - + int i, j, count; + hull_t *hull; + + hull = &loadmodel->hulls[0]; + in = loadmodel->nodes; count = loadmodel->numnodes; - out = Hunk_AllocName ( count*sizeof(*out), loadname); + out = Hunk_AllocName (count * sizeof (*out), loadname); hull->clipnodes = out; hull->firstclipnode = 0; - hull->lastclipnode = count-1; + hull->lastclipnode = count - 1; hull->planes = loadmodel->planes; - for (i=0 ; iplanenum = in->plane - loadmodel->planes; - for (j=0 ; j<2 ; j++) - { + for (j = 0; j < 2; j++) { child = in->children[j]; if (child->contents < 0) out->children[j] = child->contents; @@ -837,24 +815,24 @@ void Mod_MakeHull0 (void) Mod_LoadMarksurfaces ================= */ -void Mod_LoadMarksurfaces (lump_t *l) -{ - int i, j, count; - short *in; +void +Mod_LoadMarksurfaces (lump_t *l) +{ + int i, j, count; + short *in; msurface_t **out; - - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); + + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->marksurfaces = out; loadmodel->nummarksurfaces = count; - for ( i=0 ; i= loadmodel->numsurfaces) SV_Error ("Mod_ParseMarksurfaces: bad surface number"); out[i] = loadmodel->surfaces + j; @@ -866,21 +844,22 @@ void Mod_LoadMarksurfaces (lump_t *l) Mod_LoadSurfedges ================= */ -void Mod_LoadSurfedges (lump_t *l) -{ - int i, count; - int *in, *out; - - in = (void *)(mod_base + l->fileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*sizeof(*out), loadname); +void +Mod_LoadSurfedges (lump_t *l) +{ + int i, count; + int *in, *out; + + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * sizeof (*out), loadname); loadmodel->surfedges = out; loadmodel->numsurfedges = count; - for ( i=0 ; ifileofs); - if (l->filelen % sizeof(*in)) - SV_Error ("MOD_LoadBmodel: funny lump size in %s",loadmodel->name); - count = l->filelen / sizeof(*in); - out = Hunk_AllocName ( count*2*sizeof(*out), loadname); - + int i, j; + mplane_t *out; + dplane_t *in; + int count; + int bits; + + in = (void *) (mod_base + l->fileofs); + if (l->filelen % sizeof (*in)) + SV_Error ("MOD_LoadBmodel: funny lump size in %s", loadmodel->name); + count = l->filelen / sizeof (*in); + out = Hunk_AllocName (count * 2 * sizeof (*out), loadname); + loadmodel->planes = out; loadmodel->numplanes = count; - for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); if (out->normal[j] < 0) - bits |= 1<dist = LittleFloat (in->dist); @@ -927,14 +905,15 @@ void Mod_LoadPlanes (lump_t *l) RadiusFromBounds ================= */ -float RadiusFromBounds (vec3_t mins, vec3_t maxs) +float +RadiusFromBounds (vec3_t mins, vec3_t maxs) { - int i; - vec3_t corner; + int i; + vec3_t corner; - for (i=0 ; i<3 ; i++) - { - corner[i] = fabs(mins[i]) > fabs(maxs[i]) ? fabs(mins[i]) : fabs(maxs[i]); + for (i = 0; i < 3; i++) { + corner[i] = + fabs (mins[i]) > fabs (maxs[i]) ? fabs (mins[i]) : fabs (maxs[i]); } return Length (corner); @@ -945,25 +924,29 @@ float RadiusFromBounds (vec3_t mins, vec3_t maxs) Mod_LoadBrushModel ================= */ -void Mod_LoadBrushModel (model_t *mod, void *buffer) +void +Mod_LoadBrushModel (model_t *mod, void *buffer) { - int i, j; - dheader_t *header; - dmodel_t *bm; - + int i, j; + dheader_t *header; + dmodel_t *bm; + loadmodel->type = mod_brush; - - header = (dheader_t *)buffer; + + header = (dheader_t *) buffer; i = LittleLong (header->version); if (i != BSPVERSION) - SV_Error ("Mod_LoadBrushModel: %s has wrong version number (%i should be %i)", mod->name, i, BSPVERSION); + SV_Error + ("Mod_LoadBrushModel: %s has wrong version number (%i should be %i)", + mod->name, i, BSPVERSION); // swap all the lumps - mod_base = (byte *)header; + mod_base = (byte *) header; - for (i=0 ; ichecksum = 0; @@ -972,13 +955,17 @@ void Mod_LoadBrushModel (model_t *mod, void *buffer) for (i = 0; i < HEADER_LUMPS; i++) { if (i == LUMP_ENTITIES) continue; - mod->checksum ^= LittleLong(Com_BlockChecksum(mod_base + header->lumps[i].fileofs, - header->lumps[i].filelen)); + mod->checksum ^= + LittleLong (Com_BlockChecksum + (mod_base + header->lumps[i].fileofs, + header->lumps[i].filelen)); if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES) continue; - mod->checksum2 ^= LittleLong(Com_BlockChecksum(mod_base + header->lumps[i].fileofs, - header->lumps[i].filelen)); + mod->checksum2 ^= + LittleLong (Com_BlockChecksum + (mod_base + header->lumps[i].fileofs, + header->lumps[i].filelen)); } // load into heap @@ -1000,23 +987,21 @@ void Mod_LoadBrushModel (model_t *mod, void *buffer) Mod_LoadSubmodels (&header->lumps[LUMP_MODELS]); Mod_MakeHull0 (); - - mod->numframes = 2; // regular and alternate animation - + + mod->numframes = 2; // regular and alternate animation + // // set up the submodels (FIXME: this is confusing) // - for (i=0 ; inumsubmodels ; i++) - { + for (i = 0; i < mod->numsubmodels; i++) { bm = &mod->submodels[i]; mod->hulls[0].firstclipnode = bm->headnode[0]; - for (j=1 ; jhulls[j].firstclipnode = bm->headnode[j]; - mod->hulls[j].lastclipnode = mod->numclipnodes-1; + mod->hulls[j].lastclipnode = mod->numclipnodes - 1; } - + mod->firstmodelsurface = bm->firstface; mod->nummodelsurfaces = bm->numfaces; @@ -1027,11 +1012,11 @@ void Mod_LoadBrushModel (model_t *mod, void *buffer) mod->numleafs = bm->visleafs; - if (i < mod->numsubmodels-1) - { // duplicate the basic information - char name[10]; + if (i < mod->numsubmodels - 1) { // duplicate the basic + // information + char name[10]; - snprintf (name, sizeof(name), "*%i", i+1); + snprintf (name, sizeof (name), "*%i", i + 1); loadmodel = Mod_FindName (name); *loadmodel = *mod; strcpy (loadmodel->name, name); diff --git a/source/model_sprite.c b/source/model_sprite.c index cefa748..15ccfc5 100644 --- a/source/model_sprite.c +++ b/source/model_sprite.c @@ -30,51 +30,56 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "model.h" #include "server.h" #include "qendian.h" -extern model_t *loadmodel; -extern char loadname[]; +extern model_t *loadmodel; +extern char loadname[]; -void *Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int framenum); +void *Mod_LoadSpriteFrame (void *pin, mspriteframe_t **ppframe, + + int framenum); /* ================= Mod_LoadSpriteGroup ================= */ -void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int framenum) +void * +Mod_LoadSpriteGroup (void *pin, mspriteframe_t **ppframe, int framenum) { - dspritegroup_t *pingroup; - mspritegroup_t *pspritegroup; - int i, numframes; - dspriteinterval_t *pin_intervals; - float *poutintervals; - void *ptemp; + dspritegroup_t *pingroup; + mspritegroup_t *pspritegroup; + int i, numframes; + dspriteinterval_t *pin_intervals; + float *poutintervals; + void *ptemp; - pingroup = (dspritegroup_t *)pin; + pingroup = (dspritegroup_t *) pin; numframes = LittleLong (pingroup->numframes); pspritegroup = Hunk_AllocName (sizeof (mspritegroup_t) + - (numframes - 1) * sizeof (pspritegroup->frames[0]), loadname); + (numframes - + 1) * sizeof (pspritegroup->frames[0]), + + loadname); pspritegroup->numframes = numframes; - *ppframe = (mspriteframe_t *)pspritegroup; + *ppframe = (mspriteframe_t *) pspritegroup; - pin_intervals = (dspriteinterval_t *)(pingroup + 1); + pin_intervals = (dspriteinterval_t *) (pingroup + 1); poutintervals = Hunk_AllocName (numframes * sizeof (float), loadname); pspritegroup->intervals = poutintervals; - for (i=0 ; iinterval); if (*poutintervals <= 0.0) SV_Error ("Mod_LoadSpriteGroup: interval<=0"); @@ -83,11 +88,12 @@ void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int framenum) pin_intervals++; } - ptemp = (void *)pin_intervals; + ptemp = (void *) pin_intervals; - for (i=0 ; iframes[i], framenum * 100 + i); + for (i = 0; i < numframes; i++) { + ptemp = + Mod_LoadSpriteFrame (ptemp, &pspritegroup->frames[i], + framenum * 100 + i); } return ptemp; @@ -98,26 +104,27 @@ void * Mod_LoadSpriteGroup (void * pin, mspriteframe_t **ppframe, int framenum) Mod_LoadSpriteModel ================= */ -void Mod_LoadSpriteModel (model_t *mod, void *buffer) +void +Mod_LoadSpriteModel (model_t *mod, void *buffer) { - int i; - int version; - dsprite_t *pin; - msprite_t *psprite; - int numframes; - int size; - dspriteframetype_t *pframetype; - - pin = (dsprite_t *)buffer; + int i; + int version; + dsprite_t *pin; + msprite_t *psprite; + int numframes; + int size; + dspriteframetype_t *pframetype; + + pin = (dsprite_t *) buffer; version = LittleLong (pin->version); if (version != SPRITE_VERSION) SV_Error ("%s has wrong version number " - "(%i should be %i)", mod->name, version, SPRITE_VERSION); + "(%i should be %i)", mod->name, version, SPRITE_VERSION); numframes = LittleLong (pin->numframes); - size = sizeof (msprite_t) + (numframes - 1) * sizeof (psprite->frames); + size = sizeof (msprite_t) + (numframes - 1) * sizeof (psprite->frames); psprite = Hunk_AllocName (size, loadname); @@ -130,11 +137,11 @@ void Mod_LoadSpriteModel (model_t *mod, void *buffer) mod->synctype = LittleLong (pin->synctype); psprite->numframes = numframes; - mod->mins[0] = mod->mins[1] = -psprite->maxwidth/2; - mod->maxs[0] = mod->maxs[1] = psprite->maxwidth/2; - mod->mins[2] = -psprite->maxheight/2; - mod->maxs[2] = psprite->maxheight/2; - + mod->mins[0] = mod->mins[1] = -psprite->maxwidth / 2; + mod->maxs[0] = mod->maxs[1] = psprite->maxwidth / 2; + mod->mins[2] = -psprite->maxheight / 2; + mod->maxs[2] = psprite->maxheight / 2; + // // load the frames // @@ -143,26 +150,22 @@ void Mod_LoadSpriteModel (model_t *mod, void *buffer) mod->numframes = numframes; - pframetype = (dspriteframetype_t *)(pin + 1); + pframetype = (dspriteframetype_t *) (pin + 1); - for (i=0 ; itype); psprite->frames[i].type = frametype; - if (frametype == SPR_SINGLE) - { + if (frametype == SPR_SINGLE) { pframetype = (dspriteframetype_t *) - Mod_LoadSpriteFrame (pframetype + 1, - &psprite->frames[i].frameptr, i); - } - else - { + Mod_LoadSpriteFrame (pframetype + 1, + &psprite->frames[i].frameptr, i); + } else { pframetype = (dspriteframetype_t *) - Mod_LoadSpriteGroup (pframetype + 1, - &psprite->frames[i].frameptr, i); + Mod_LoadSpriteGroup (pframetype + 1, + &psprite->frames[i].frameptr, i); } } diff --git a/source/msg.c b/source/msg.c index bf41d66..3ff50a1 100644 --- a/source/msg.c +++ b/source/msg.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -56,10 +56,11 @@ Handles byte ordering and avoids alignment errors // writing functions // -void MSG_WriteChar (sizebuf_t *sb, int c) +void +MSG_WriteChar (sizebuf_t *sb, int c) { - byte *buf; - + byte *buf; + #ifdef PARANOID if (c < -128 || c > 127) Sys_Error ("MSG_WriteChar: range error"); @@ -69,10 +70,11 @@ void MSG_WriteChar (sizebuf_t *sb, int c) buf[0] = c; } -void MSG_WriteByte (sizebuf_t *sb, int c) +void +MSG_WriteByte (sizebuf_t *sb, int c) { - byte *buf; - + byte *buf; + #ifdef PARANOID if (c < 0 || c > 255) Sys_Error ("MSG_WriteByte: range error"); @@ -82,72 +84,79 @@ void MSG_WriteByte (sizebuf_t *sb, int c) buf[0] = c; } -void MSG_WriteShort (sizebuf_t *sb, int c) +void +MSG_WriteShort (sizebuf_t *sb, int c) { - byte *buf; - + byte *buf; + #ifdef PARANOID - if (c < ((short)0x8000) || c > (short)0x7fff) + if (c < ((short) 0x8000) || c > (short) 0x7fff) Sys_Error ("MSG_WriteShort: range error"); #endif buf = SZ_GetSpace (sb, 2); - buf[0] = c&0xff; - buf[1] = c>>8; + buf[0] = c & 0xff; + buf[1] = c >> 8; } -void MSG_WriteLong (sizebuf_t *sb, int c) +void +MSG_WriteLong (sizebuf_t *sb, int c) { - byte *buf; - + byte *buf; + buf = SZ_GetSpace (sb, 4); - buf[0] = c&0xff; - buf[1] = (c>>8)&0xff; - buf[2] = (c>>16)&0xff; - buf[3] = c>>24; + buf[0] = c & 0xff; + buf[1] = (c >> 8) & 0xff; + buf[2] = (c >> 16) & 0xff; + buf[3] = c >> 24; } -void MSG_WriteFloat (sizebuf_t *sb, float f) +void +MSG_WriteFloat (sizebuf_t *sb, float f) { - union - { - float f; - int l; + union { + float f; + int l; } dat; - - + + dat.f = f; dat.l = LittleLong (dat.l); - + SZ_Write (sb, &dat.l, 4); } -void MSG_WriteString (sizebuf_t *sb, char *s) +void +MSG_WriteString (sizebuf_t *sb, char *s) { if (!s) SZ_Write (sb, "", 1); else - SZ_Write (sb, s, strlen(s)+1); + SZ_Write (sb, s, strlen (s) + 1); } -void MSG_WriteCoord (sizebuf_t *sb, float f) +void +MSG_WriteCoord (sizebuf_t *sb, float f) { - MSG_WriteShort (sb, (int)(f*8)); + MSG_WriteShort (sb, (int) (f * 8)); } -void MSG_WriteAngle (sizebuf_t *sb, float f) +void +MSG_WriteAngle (sizebuf_t *sb, float f) { - MSG_WriteByte (sb, (int)(f*256/360) & 255); + MSG_WriteByte (sb, (int) (f * 256 / 360) & 255); } -void MSG_WriteAngle16 (sizebuf_t *sb, float f) +void +MSG_WriteAngle16 (sizebuf_t *sb, float f) { - MSG_WriteShort (sb, (int)(f*65536/360) & 65535); + MSG_WriteShort (sb, (int) (f * 65536 / 360) & 65535); } -void MSG_WriteDeltaUsercmd (sizebuf_t *buf, usercmd_t *from, usercmd_t *cmd) +void +MSG_WriteDeltaUsercmd (sizebuf_t *buf, usercmd_t *from, usercmd_t *cmd) { - int bits; + int bits; // // send the movement message @@ -170,7 +179,7 @@ void MSG_WriteDeltaUsercmd (sizebuf_t *buf, usercmd_t *from, usercmd_t *cmd) if (cmd->impulse != from->impulse) bits |= CM_IMPULSE; - MSG_WriteByte (buf, bits); + MSG_WriteByte (buf, bits); if (bits & CM_ANGLE1) MSG_WriteAngle16 (buf, cmd->angles[0]); @@ -178,18 +187,18 @@ void MSG_WriteDeltaUsercmd (sizebuf_t *buf, usercmd_t *from, usercmd_t *cmd) MSG_WriteAngle16 (buf, cmd->angles[1]); if (bits & CM_ANGLE3) MSG_WriteAngle16 (buf, cmd->angles[2]); - + if (bits & CM_FORWARD) MSG_WriteShort (buf, cmd->forwardmove); if (bits & CM_SIDE) - MSG_WriteShort (buf, cmd->sidemove); + MSG_WriteShort (buf, cmd->sidemove); if (bits & CM_UP) MSG_WriteShort (buf, cmd->upmove); - if (bits & CM_BUTTONS) - MSG_WriteByte (buf, cmd->buttons); - if (bits & CM_IMPULSE) - MSG_WriteByte (buf, cmd->impulse); + if (bits & CM_BUTTONS) + MSG_WriteByte (buf, cmd->buttons); + if (bits & CM_IMPULSE) + MSG_WriteByte (buf, cmd->impulse); MSG_WriteByte (buf, cmd->msec); } @@ -197,174 +206,180 @@ void MSG_WriteDeltaUsercmd (sizebuf_t *buf, usercmd_t *from, usercmd_t *cmd) // // reading functions // -int msg_readcount; -qboolean msg_badread; +int msg_readcount; +qboolean msg_badread; -void MSG_BeginReading (void) +void +MSG_BeginReading (void) { msg_readcount = 0; msg_badread = false; } -int MSG_GetReadCount(void) +int +MSG_GetReadCount (void) { return msg_readcount; } // returns -1 and sets msg_badread if no more characters are available -int MSG_ReadChar (void) +int +MSG_ReadChar (void) { - int c; - - if (msg_readcount+1 > net_message.cursize) - { + int c; + + if (msg_readcount + 1 > net_message.cursize) { msg_badread = true; return -1; } - - c = (signed char)net_message.data[msg_readcount]; + + c = (signed char) net_message.data[msg_readcount]; msg_readcount++; - + return c; } -int MSG_ReadByte (void) +int +MSG_ReadByte (void) { - int c; - - if (msg_readcount+1 > net_message.cursize) - { + int c; + + if (msg_readcount + 1 > net_message.cursize) { msg_badread = true; return -1; } - - c = (unsigned char)net_message.data[msg_readcount]; + + c = (unsigned char) net_message.data[msg_readcount]; msg_readcount++; - + return c; } -int MSG_ReadShort (void) +int +MSG_ReadShort (void) { - int c; - - if (msg_readcount+2 > net_message.cursize) - { + int c; + + if (msg_readcount + 2 > net_message.cursize) { msg_badread = true; return -1; } - - c = (short)(net_message.data[msg_readcount] - + (net_message.data[msg_readcount+1]<<8)); - + + c = (short) (net_message.data[msg_readcount] + + (net_message.data[msg_readcount + 1] << 8)); + msg_readcount += 2; - + return c; } -int MSG_ReadLong (void) +int +MSG_ReadLong (void) { - int c; - - if (msg_readcount+4 > net_message.cursize) - { + int c; + + if (msg_readcount + 4 > net_message.cursize) { msg_badread = true; return -1; } - + c = net_message.data[msg_readcount] - + (net_message.data[msg_readcount+1]<<8) - + (net_message.data[msg_readcount+2]<<16) - + (net_message.data[msg_readcount+3]<<24); - + + (net_message.data[msg_readcount + 1] << 8) + + (net_message.data[msg_readcount + 2] << 16) + + (net_message.data[msg_readcount + 3] << 24); + msg_readcount += 4; - + return c; } -float MSG_ReadFloat (void) +float +MSG_ReadFloat (void) { - union - { - byte b[4]; - float f; - int l; + union { + byte b[4]; + float f; + int l; } dat; - - dat.b[0] = net_message.data[msg_readcount]; - dat.b[1] = net_message.data[msg_readcount+1]; - dat.b[2] = net_message.data[msg_readcount+2]; - dat.b[3] = net_message.data[msg_readcount+3]; + + dat.b[0] = net_message.data[msg_readcount]; + dat.b[1] = net_message.data[msg_readcount + 1]; + dat.b[2] = net_message.data[msg_readcount + 2]; + dat.b[3] = net_message.data[msg_readcount + 3]; msg_readcount += 4; - + dat.l = LittleLong (dat.l); - return dat.f; + return dat.f; } -char *MSG_ReadString (void) +char * +MSG_ReadString (void) { - static char string[2048]; - int l,c; - + static char string[2048]; + int l, c; + l = 0; - do - { + do { c = MSG_ReadChar (); if (c == -1 || c == 0) break; string[l] = c; l++; - } while (l < sizeof(string)-1); - + } while (l < sizeof (string) - 1); + string[l] = 0; - + return string; } -char *MSG_ReadStringLine (void) +char * +MSG_ReadStringLine (void) { - static char string[2048]; - int l,c; - + static char string[2048]; + int l, c; + l = 0; - do - { + do { c = MSG_ReadChar (); if (c == -1 || c == 0 || c == '\n') break; string[l] = c; l++; - } while (l < sizeof(string)-1); - + } while (l < sizeof (string) - 1); + string[l] = 0; - + return string; } -float MSG_ReadCoord (void) +float +MSG_ReadCoord (void) { - return MSG_ReadShort() * (1.0/8); + return MSG_ReadShort () * (1.0 / 8); } -float MSG_ReadAngle (void) +float +MSG_ReadAngle (void) { - return MSG_ReadChar() * (360.0/256); + return MSG_ReadChar () * (360.0 / 256); } -float MSG_ReadAngle16 (void) +float +MSG_ReadAngle16 (void) { - return MSG_ReadShort() * (360.0/65536); + return MSG_ReadShort () * (360.0 / 65536); } -void MSG_ReadDeltaUsercmd (usercmd_t *from, usercmd_t *move) +void +MSG_ReadDeltaUsercmd (usercmd_t *from, usercmd_t *move) { - int bits; + int bits; - memcpy (move, from, sizeof(*move)); + memcpy (move, from, sizeof (*move)); bits = MSG_ReadByte (); - + // read current angles if (bits & CM_ANGLE1) move->angles[0] = MSG_ReadAngle16 (); @@ -372,7 +387,7 @@ void MSG_ReadDeltaUsercmd (usercmd_t *from, usercmd_t *move) move->angles[1] = MSG_ReadAngle16 (); if (bits & CM_ANGLE3) move->angles[2] = MSG_ReadAngle16 (); - + // read movement if (bits & CM_FORWARD) move->forwardmove = MSG_ReadShort (); @@ -380,7 +395,7 @@ void MSG_ReadDeltaUsercmd (usercmd_t *from, usercmd_t *move) move->sidemove = MSG_ReadShort (); if (bits & CM_UP) move->upmove = MSG_ReadShort (); - + // read buttons if (bits & CM_BUTTONS) move->buttons = MSG_ReadByte (); @@ -391,4 +406,3 @@ void MSG_ReadDeltaUsercmd (usercmd_t *from, usercmd_t *move) // read time to run command move->msec = MSG_ReadByte (); } - diff --git a/source/net_chan.c b/source/net_chan.c index 5f06b7f..ad28ef4 100644 --- a/source/net_chan.c +++ b/source/net_chan.c @@ -101,11 +101,11 @@ to the new value before sending out any replies. */ -int net_drop; -cvar_t *showpackets; -cvar_t *showdrop; -cvar_t *qport; -extern qboolean is_server; +int net_drop; +cvar_t *showpackets; +cvar_t *showdrop; +cvar_t *qport; +extern qboolean is_server; /* =============== @@ -113,25 +113,27 @@ Netchan_Init =============== */ -void Netchan_Init (void) +void +Netchan_Init (void) { - int port; + int port; // pick a port value that should be nice and random #ifdef _WIN32 - port = ((int)(timeGetTime()*1000) * time(NULL)) & 0xffff; + port = ((int) (timeGetTime () * 1000) * time (NULL)) & 0xffff; #else - port = ((int)(getpid()+getuid()*1000) * time(NULL)) & 0xffff; + port = ((int) (getpid () + getuid () * 1000) * time (NULL)) & 0xffff; #endif Cvar_SetValue (qport, port); } -void Netchan_Init_Cvars (void) +void +Netchan_Init_Cvars (void) { - showpackets = Cvar_Get("showpackets", "0", CVAR_NONE, "None"); - showdrop = Cvar_Get("showdrop", "0", CVAR_NONE, "None"); - qport = Cvar_Get("qport", "0", CVAR_NONE, "None"); + showpackets = Cvar_Get ("showpackets", "0", CVAR_NONE, "None"); + showdrop = Cvar_Get ("showdrop", "0", CVAR_NONE, "None"); + qport = Cvar_Get ("qport", "0", CVAR_NONE, "None"); } /* @@ -141,29 +143,28 @@ Netchan_OutOfBand Sends an out-of-band datagram ================ */ -void Netchan_OutOfBand (netadr_t adr, int length, byte *data) +void +Netchan_OutOfBand (netadr_t adr, int length, byte * data) { - sizebuf_t send; - byte send_buf[MAX_MSGLEN + PACKET_HEADER]; + sizebuf_t send; + byte send_buf[MAX_MSGLEN + PACKET_HEADER]; // write the packet header send.data = send_buf; - send.maxsize = sizeof(send_buf); + send.maxsize = sizeof (send_buf); send.cursize = 0; - - MSG_WriteLong (&send, -1); // -1 sequence means out of band + + MSG_WriteLong (&send, -1); // -1 sequence means out of band SZ_Write (&send, data, length); // send the datagram - //zoid, no input in demo playback mode - if (!is_server) - { + // zoid, no input in demo playback mode + if (!is_server) { if (!cls.demoplayback) NET_SendPacket (send.cursize, send.data, adr); - } - else + } else NET_SendPacket (send.cursize, send.data, adr); - + } /* @@ -173,17 +174,18 @@ Netchan_OutOfBandPrint Sends a text message in an out-of-band datagram ================ */ -void Netchan_OutOfBandPrint (netadr_t adr, char *format, ...) +void +Netchan_OutOfBandPrint (netadr_t adr, char *format, ...) { - va_list argptr; - static char string[8192]; // ?? why static? - + va_list argptr; + static char string[8192]; // ?? why static? + va_start (argptr, format); - vsnprintf (string, sizeof(string), format, argptr); + vsnprintf (string, sizeof (string), format, argptr); va_end (argptr); - Netchan_OutOfBand (adr, strlen(string), (byte *)string); + Netchan_OutOfBand (adr, strlen (string), (byte *) string); } @@ -194,20 +196,21 @@ Netchan_Setup called to open a channel to a remote system ============== */ -void Netchan_Setup (netchan_t *chan, netadr_t adr, int qport) +void +Netchan_Setup (netchan_t *chan, netadr_t adr, int qport) { - memset (chan, 0, sizeof(*chan)); - + memset (chan, 0, sizeof (*chan)); + chan->remote_address = adr; chan->last_received = realtime; - + chan->message.data = chan->message_buf; chan->message.allowoverflow = true; - chan->message.maxsize = sizeof(chan->message_buf); + chan->message.maxsize = sizeof (chan->message_buf); chan->qport = qport; - - chan->rate = 1.0/2500; + + chan->rate = 1.0 / 2500; } @@ -219,9 +222,10 @@ Returns true if the bandwidth choke isn't active ================ */ #define MAX_BACKUP 200 -qboolean Netchan_CanPacket (netchan_t *chan) +qboolean +Netchan_CanPacket (netchan_t *chan) { - if (chan->cleartime < realtime + MAX_BACKUP*chan->rate) + if (chan->cleartime < realtime + MAX_BACKUP * chan->rate) return true; return false; } @@ -234,14 +238,15 @@ Netchan_CanReliable Returns true if the bandwidth choke isn't ================ */ -qboolean Netchan_CanReliable (netchan_t *chan) +qboolean +Netchan_CanReliable (netchan_t *chan) { if (chan->reliable_length) - return false; // waiting for ack + return false; // waiting for ack return Netchan_CanPacket (chan); } -qboolean ServerPaused(void); +qboolean ServerPaused (void); /* =============== @@ -253,47 +258,44 @@ transmition / retransmition of the reliable messages. A 0 length will still generate a packet and deal with the reliable messages. ================ */ -void Netchan_Transmit (netchan_t *chan, int length, byte *data) +void +Netchan_Transmit (netchan_t *chan, int length, byte * data) { - sizebuf_t send; - byte send_buf[MAX_MSGLEN + PACKET_HEADER]; - qboolean send_reliable; - unsigned int w1, w2; - int i; + sizebuf_t send; + byte send_buf[MAX_MSGLEN + PACKET_HEADER]; + qboolean send_reliable; + unsigned int w1, w2; + int i; // check for message overflow - if (chan->message.overflowed) - { + if (chan->message.overflowed) { chan->fatal_error = true; - Con_Printf ("%s:Outgoing message overflow\n" - , NET_AdrToString (chan->remote_address)); + Con_Printf ("%s:Outgoing message overflow\n", + NET_AdrToString (chan->remote_address)); return; } - // if the remote side dropped the last reliable message, resend it send_reliable = false; if (chan->incoming_acknowledged > chan->last_reliable_sequence - && chan->incoming_reliable_acknowledged != chan->reliable_sequence) + && chan->incoming_reliable_acknowledged != chan->reliable_sequence) send_reliable = true; // if the reliable transmit buffer is empty, copy the current message out - if (!chan->reliable_length && chan->message.cursize) - { + if (!chan->reliable_length && chan->message.cursize) { memcpy (chan->reliable_buf, chan->message_buf, chan->message.cursize); chan->reliable_length = chan->message.cursize; chan->message.cursize = 0; chan->reliable_sequence ^= 1; send_reliable = true; } - // write the packet header send.data = send_buf; - send.maxsize = sizeof(send_buf); + send.maxsize = sizeof (send_buf); send.cursize = 0; - w1 = chan->outgoing_sequence | (send_reliable<<31); - w2 = chan->incoming_sequence | (chan->incoming_reliable_sequence<<31); + w1 = chan->outgoing_sequence | (send_reliable << 31); + w2 = chan->incoming_sequence | (chan->incoming_reliable_sequence << 31); chan->outgoing_sequence++; @@ -301,48 +303,41 @@ void Netchan_Transmit (netchan_t *chan, int length, byte *data) MSG_WriteLong (&send, w2); // send the qport if we are a client - if(!is_server) + if (!is_server) MSG_WriteShort (&send, cls.qport); // copy the reliable message to the packet first - if (send_reliable) - { + if (send_reliable) { SZ_Write (&send, chan->reliable_buf, chan->reliable_length); chan->last_reliable_sequence = chan->outgoing_sequence; } - // add the unreliable part if space is available if (send.maxsize - send.cursize >= length) SZ_Write (&send, data, length); // send the datagram - i = chan->outgoing_sequence & (MAX_LATENT-1); + i = chan->outgoing_sequence & (MAX_LATENT - 1); chan->outgoing_size[i] = send.cursize; chan->outgoing_time[i] = realtime; - //zoid, no input in demo playback mode - if (!is_server) - { + // zoid, no input in demo playback mode + if (!is_server) { if (!cls.demoplayback) NET_SendPacket (send.cursize, send.data, chan->remote_address); - } - else + } else NET_SendPacket (send.cursize, send.data, chan->remote_address); if (chan->cleartime < realtime) - chan->cleartime = realtime + send.cursize*chan->rate; + chan->cleartime = realtime + send.cursize * chan->rate; else - chan->cleartime += send.cursize*chan->rate; - if (ServerPaused()) + chan->cleartime += send.cursize * chan->rate; + if (ServerPaused ()) chan->cleartime = realtime; if (showpackets->int_val) - Con_Printf ("--> s=%i(%i) a=%i(%i) %i\n" - , chan->outgoing_sequence - , send_reliable - , chan->incoming_sequence - , chan->incoming_reliable_sequence - , send.cursize); + Con_Printf ("--> s=%i(%i) a=%i(%i) %i\n", chan->outgoing_sequence, + send_reliable, chan->incoming_sequence, + chan->incoming_reliable_sequence, send.cursize); } @@ -354,25 +349,22 @@ called when the current net_message is from remote_address modifies net_message so that it points to the packet payload ================= */ -qboolean Netchan_Process (netchan_t *chan) +qboolean +Netchan_Process (netchan_t *chan) { - unsigned int sequence, sequence_ack; - unsigned int reliable_ack, reliable_message; - int qport; + unsigned int sequence, sequence_ack; + unsigned int reliable_ack, reliable_message; + int qport; - if (is_server) - { - if ( !NET_CompareAdr (net_from,chan->remote_address)) - return false; - } - else - { - if ( !cls.demoplayback && - !NET_CompareAdr (net_from, chan->remote_address)) + if (is_server) { + if (!NET_CompareAdr (net_from, chan->remote_address)) return false; + } else { + if (!cls.demoplayback && + !NET_CompareAdr (net_from, chan->remote_address)) return false; } -// get sequence numbers +// get sequence numbers MSG_BeginReading (); sequence = MSG_ReadLong (); sequence_ack = MSG_ReadLong (); @@ -384,40 +376,33 @@ qboolean Netchan_Process (netchan_t *chan) reliable_message = sequence >> 31; reliable_ack = sequence_ack >> 31; - sequence &= ~(1<<31); - sequence_ack &= ~(1<<31); + sequence &= ~(1 << 31); + sequence_ack &= ~(1 << 31); if (showpackets->int_val) - Con_Printf ("<-- s=%i(%i) a=%i(%i) %i\n" - , sequence - , reliable_message - , sequence_ack - , reliable_ack - , net_message.cursize); + Con_Printf ("<-- s=%i(%i) a=%i(%i) %i\n", sequence, reliable_message, + sequence_ack, reliable_ack, net_message.cursize); // get a rate estimation #if 0 - if (chan->outgoing_sequence - sequence_ack < MAX_LATENT) - { - int i; - double time, rate; - + if (chan->outgoing_sequence - sequence_ack < MAX_LATENT) { + int i; + double time, rate; + i = sequence_ack & (MAX_LATENT - 1); time = realtime - chan->outgoing_time[i]; - time -= 0.1; // subtract 100 ms - if (time <= 0) - { // gotta be a digital link for <100 ms ping - if (chan->rate > 1.0/5000) - chan->rate = 1.0/5000; - } - else - { - if (chan->outgoing_size[i] < 512) - { // only deal with small messages - rate = chan->outgoing_size[i]/time; + time -= 0.1; // subtract 100 ms + if (time <= 0) { // gotta be a digital link for <100 + // ms ping + if (chan->rate > 1.0 / 5000) + chan->rate = 1.0 / 5000; + } else { + if (chan->outgoing_size[i] < 512) { // only deal with small + // messages + rate = chan->outgoing_size[i] / time; if (rate > 5000) rate = 5000; - rate = 1.0/rate; + rate = 1.0 / rate; if (chan->rate > rate) chan->rate = rate; } @@ -428,38 +413,33 @@ qboolean Netchan_Process (netchan_t *chan) // // discard stale or duplicated packets // - if (sequence <= (unsigned int)chan->incoming_sequence) - { + if (sequence <= (unsigned int) chan->incoming_sequence) { if (showdrop->int_val) - Con_Printf ("%s:Out of order packet %i at %i\n" - , NET_AdrToString (chan->remote_address) - , sequence - , chan->incoming_sequence); + Con_Printf ("%s:Out of order packet %i at %i\n", + NET_AdrToString (chan->remote_address), sequence, + chan->incoming_sequence); return false; } - // // dropped packets don't keep the message from being used // - net_drop = sequence - (chan->incoming_sequence+1); - if (net_drop > 0) - { + net_drop = sequence - (chan->incoming_sequence + 1); + if (net_drop > 0) { chan->drop_count += 1; if (showdrop->int_val) - Con_Printf ("%s:Dropped %i packets at %i\n" - , NET_AdrToString (chan->remote_address) - , sequence-(chan->incoming_sequence+1) - , sequence); + Con_Printf ("%s:Dropped %i packets at %i\n", + NET_AdrToString (chan->remote_address), + sequence - (chan->incoming_sequence + 1) + , sequence); } - // // if the current outgoing reliable message has been acknowledged // clear the buffer to make way for the next // - if (reliable_ack == (unsigned int)chan->reliable_sequence) - chan->reliable_length = 0; // it has been received - + if (reliable_ack == (unsigned int) chan->reliable_sequence) + chan->reliable_length = 0; // it has been received + // // if this message contains a reliable message, bump incoming_reliable_sequence // @@ -473,14 +453,13 @@ qboolean Netchan_Process (netchan_t *chan) // the message can now be read from the current message pointer // update statistics counters // - chan->frame_latency = chan->frame_latency*OLD_AVG - + (chan->outgoing_sequence-sequence_ack)*(1.0-OLD_AVG); - chan->frame_rate = chan->frame_rate*OLD_AVG - + (realtime-chan->last_received)*(1.0-OLD_AVG); + chan->frame_latency = chan->frame_latency * OLD_AVG + + (chan->outgoing_sequence - sequence_ack) * (1.0 - OLD_AVG); + chan->frame_rate = chan->frame_rate * OLD_AVG + + (realtime - chan->last_received) * (1.0 - OLD_AVG); chan->good_count += 1; chan->last_received = realtime; return true; } - diff --git a/source/net_com.c b/source/net_com.c index 139c78c..c727e03 100644 --- a/source/net_com.c +++ b/source/net_com.c @@ -30,24 +30,25 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include -unsigned int Com_BlockChecksum (void *buffer, int length) +unsigned int +Com_BlockChecksum (void *buffer, int length) { - int digest[4]; - unsigned int val; + int digest[4]; + unsigned int val; - mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); + mdfour ((unsigned char *) digest, (unsigned char *) buffer, length); val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; return val; } -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) +void +Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) { - mdfour ( outbuf, (unsigned char *) buffer, len ); + mdfour (outbuf, (unsigned char *) buffer, len); } - diff --git a/source/net_udp.c b/source/net_udp.c index abc93cc..f3a610b 100644 --- a/source/net_udp.c +++ b/source/net_udp.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "net.h" @@ -90,66 +90,75 @@ typedef unsigned int socklen_t; # endif #endif -netadr_t net_local_adr; +netadr_t net_local_adr; -netadr_t net_from; -sizebuf_t net_message; -int net_socket; +netadr_t net_from; +sizebuf_t net_message; +int net_socket; #define MAX_UDP_PACKET (MAX_MSGLEN*2) -byte net_message_buffer[MAX_UDP_PACKET]; +byte net_message_buffer[MAX_UDP_PACKET]; #ifdef _WIN32 extern qboolean is_server; -WSADATA winsockdata; +WSADATA winsockdata; #endif //============================================================================= -void NetadrToSockadr (netadr_t *a, struct sockaddr_in *s) +void +NetadrToSockadr (netadr_t *a, struct sockaddr_in *s) { - memset (s, 0, sizeof(*s)); + memset (s, 0, sizeof (*s)); s->sin_family = AF_INET; - *(int *)&s->sin_addr = *(int *)&a->ip; + *(int *) &s->sin_addr = *(int *) &a->ip; s->sin_port = a->port; } -void SockadrToNetadr (struct sockaddr_in *s, netadr_t *a) +void +SockadrToNetadr (struct sockaddr_in *s, netadr_t *a) { - *(int *)&a->ip = *(int *)&s->sin_addr; + *(int *) &a->ip = *(int *) &s->sin_addr; a->port = s->sin_port; } -qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b) +qboolean +NET_CompareBaseAdr (netadr_t a, netadr_t b) { - if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3]) + if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] + && a.ip[3] == b.ip[3]) return true; return false; } -qboolean NET_CompareAdr (netadr_t a, netadr_t b) +qboolean +NET_CompareAdr (netadr_t a, netadr_t b) { - if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3] && a.port == b.port) + if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] + && a.ip[3] == b.ip[3] && a.port == b.port) return true; return false; } -char *NET_AdrToString (netadr_t a) +char * +NET_AdrToString (netadr_t a) { - static char s[64]; - - snprintf (s, sizeof(s), "%i.%i.%i.%i:%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3], ntohs(a.port)); + static char s[64]; + + snprintf (s, sizeof (s), "%i.%i.%i.%i:%i", a.ip[0], a.ip[1], a.ip[2], + a.ip[3], ntohs (a.port)); return s; } -char *NET_BaseAdrToString (netadr_t a) +char * +NET_BaseAdrToString (netadr_t a) { - static char s[64]; - - snprintf (s, sizeof(s), "%i.%i.%i.%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3]); + static char s[64]; + + snprintf (s, sizeof (s), "%i.%i.%i.%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3]); return s; } @@ -164,39 +173,36 @@ idnewt:28000 192.246.40.70:28000 ============= */ -qboolean NET_StringToAdr (char *s, netadr_t *a) +qboolean +NET_StringToAdr (char *s, netadr_t *a) { - struct hostent *h; + struct hostent *h; struct sockaddr_in sadr; - char *colon; - char copy[128]; - - - memset (&sadr, 0, sizeof(sadr)); + char *colon; + char copy[128]; + + + memset (&sadr, 0, sizeof (sadr)); sadr.sin_family = AF_INET; - + sadr.sin_port = 0; strcpy (copy, s); // strip off a trailing :port if present - for (colon = copy ; *colon ; colon++) - if (*colon == ':') - { + for (colon = copy; *colon; colon++) + if (*colon == ':') { *colon = 0; - sadr.sin_port = htons((unsigned short)atoi(colon+1)); + sadr.sin_port = htons ((unsigned short) atoi (colon + 1)); } - - if (copy[0] >= '0' && copy[0] <= '9') - { - *(int *)&sadr.sin_addr = inet_addr(copy); - } - else - { - if (! (h = gethostbyname(copy)) ) + + if (copy[0] >= '0' && copy[0] <= '9') { + *(int *) &sadr.sin_addr = inet_addr (copy); + } else { + if (!(h = gethostbyname (copy))) return 0; - *(int *)&sadr.sin_addr = *(int *)h->h_addr_list[0]; + *(int *) &sadr.sin_addr = *(int *) h->h_addr_list[0]; } - + SockadrToNetadr (&sadr, a); return true; @@ -204,29 +210,29 @@ qboolean NET_StringToAdr (char *s, netadr_t *a) // Returns true if we can't bind the address locally--in other words, // the IP is NOT one of our interfaces. -qboolean NET_IsClientLegal(netadr_t *adr) +qboolean +NET_IsClientLegal (netadr_t *adr) { #if 0 struct sockaddr_in sadr; - int newsocket; + int newsocket; if (adr->ip[0] == 127) - return false; // no local connections period + return false; // no local connections period NetadrToSockadr (adr, &sadr); if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) - Sys_Error ("NET_IsClientLegal: socket:", strerror(errno)); + Sys_Error ("NET_IsClientLegal: socket:", strerror (errno)); sadr.sin_port = 0; - if( bind (newsocket, (void *)&sadr, sizeof(sadr)) == -1) - { + if (bind (newsocket, (void *) &sadr, sizeof (sadr)) == -1) { // It is not a local address - close(newsocket); + close (newsocket); return true; } - close(newsocket); + close (newsocket); return false; #else return true; @@ -236,40 +242,45 @@ qboolean NET_IsClientLegal(netadr_t *adr) //============================================================================= -qboolean NET_GetPacket (void) +qboolean +NET_GetPacket (void) { - int ret; - struct sockaddr_in from; - socklen_t fromlen; + int ret; + struct sockaddr_in from; + socklen_t fromlen; - fromlen = sizeof(from); - ret = recvfrom(net_socket, (void*)net_message_buffer, sizeof(net_message_buffer), 0, (struct sockaddr *)&from, &fromlen); + fromlen = sizeof (from); + ret = + recvfrom (net_socket, (void *) net_message_buffer, + sizeof (net_message_buffer), 0, (struct sockaddr *) &from, + &fromlen); - SockadrToNetadr(&from, &net_from); + SockadrToNetadr (&from, &net_from); if (ret == -1) { #ifdef _WIN32 - int err = WSAGetLastError(); + int err = WSAGetLastError (); if (err == WSAEMSGSIZE) { Con_Printf ("Warning: Oversize packet from %s\n", - NET_AdrToString (net_from)); + NET_AdrToString (net_from)); return false; } #else /* _WIN32 */ - int err = errno; + int err = errno; - if (err == ECONNREFUSED) return false; + if (err == ECONNREFUSED) + return false; #endif /* _WIN32 */ - if (err == EWOULDBLOCK) return false; - Sys_Printf ("NET_GetPacket: %s\n", strerror(err)); + if (err == EWOULDBLOCK) + return false; + Sys_Printf ("NET_GetPacket: %s\n", strerror (err)); return false; } net_message.cursize = ret; - if (ret == sizeof(net_message_buffer)) { - Con_Printf ("Oversize packet from %s\n", - NET_AdrToString (net_from)); + if (ret == sizeof (net_message_buffer)) { + Con_Printf ("Oversize packet from %s\n", NET_AdrToString (net_from)); return false; } @@ -278,86 +289,96 @@ qboolean NET_GetPacket (void) //============================================================================= -void NET_SendPacket (int length, void *data, netadr_t to) +void +NET_SendPacket (int length, void *data, netadr_t to) { - int ret; - struct sockaddr_in addr; + int ret; + struct sockaddr_in addr; NetadrToSockadr (&to, &addr); - ret = sendto (net_socket, data, length, 0, (struct sockaddr *)&addr, sizeof(addr) ); + ret = + sendto (net_socket, data, length, 0, (struct sockaddr *) &addr, + sizeof (addr)); if (ret == -1) { #ifdef _WIN32 - int err = WSAGetLastError(); + int err = WSAGetLastError (); if (err == WSAEADDRNOTAVAIL) { - if (is_server) Con_DPrintf("NET_SendPacket Warning: %i\n", err); - else Con_Printf ("NET_SendPacket ERROR: %i\n", err); + if (is_server) + Con_DPrintf ("NET_SendPacket Warning: %i\n", err); + else + Con_Printf ("NET_SendPacket ERROR: %i\n", err); } #else /* _WIN32 */ - int err = errno; + int err = errno; - if (err == ECONNREFUSED) return; + if (err == ECONNREFUSED) + return; #endif /* _WIN32 */ - if (err == EWOULDBLOCK) return; + if (err == EWOULDBLOCK) + return; - Sys_Printf ("NET_SendPacket: %s\n", strerror(errno)); + Sys_Printf ("NET_SendPacket: %s\n", strerror (errno)); } } //============================================================================= -int UDP_OpenSocket (int port) +int +UDP_OpenSocket (int port) { - int newsocket; + int newsocket; struct sockaddr_in address; + #ifdef _WIN32 #define ioctl ioctlsocket unsigned long _true = true; #else - int _true = 1; + int _true = 1; #endif - int i; + int i; if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) - Sys_Error ("UDP_OpenSocket: socket:%s", strerror(errno)); + Sys_Error ("UDP_OpenSocket: socket:%s", strerror (errno)); if (ioctl (newsocket, FIONBIO, &_true) == -1) - Sys_Error ("UDP_OpenSocket: ioctl FIONBIO:%s", strerror(errno)); + Sys_Error ("UDP_OpenSocket: ioctl FIONBIO:%s", strerror (errno)); address.sin_family = AF_INET; //ZOID -- check for interface binding option - if ((i = COM_CheckParm("-ip")) != 0 && i < com_argc) { - address.sin_addr.s_addr = inet_addr(com_argv[i+1]); - Con_Printf("Binding to IP Interface Address of %s\n", - inet_ntoa(address.sin_addr)); + if ((i = COM_CheckParm ("-ip")) != 0 && i < com_argc) { + address.sin_addr.s_addr = inet_addr (com_argv[i + 1]); + Con_Printf ("Binding to IP Interface Address of %s\n", + inet_ntoa (address.sin_addr)); } else address.sin_addr.s_addr = INADDR_ANY; if (port == PORT_ANY) address.sin_port = 0; else - address.sin_port = htons((short)port); - if( bind (newsocket, (void *)&address, sizeof(address)) == -1) - Sys_Error ("UDP_OpenSocket: bind: %s", strerror(errno)); + address.sin_port = htons ((short) port); + if (bind (newsocket, (void *) &address, sizeof (address)) == -1) + Sys_Error ("UDP_OpenSocket: bind: %s", strerror (errno)); return newsocket; } -void NET_GetLocalAddress (void) +void +NET_GetLocalAddress (void) { - char buff[MAXHOSTNAMELEN]; - struct sockaddr_in address; - socklen_t namelen; + char buff[MAXHOSTNAMELEN]; + struct sockaddr_in address; + socklen_t namelen; - gethostname(buff, MAXHOSTNAMELEN); - buff[MAXHOSTNAMELEN-1] = 0; + gethostname (buff, MAXHOSTNAMELEN); + buff[MAXHOSTNAMELEN - 1] = 0; NET_StringToAdr (buff, &net_local_adr); - namelen = sizeof(address); - if (getsockname (net_socket, (struct sockaddr *)&address, &namelen) == -1) - Sys_Error ("NET_Init: getsockname: %s", strerror(errno)); + namelen = sizeof (address); + if (getsockname (net_socket, (struct sockaddr *) &address, &namelen) == -1) + Sys_Error ("NET_Init: getsockname: %s", strerror (errno)); net_local_adr.port = address.sin_port; - Con_Printf("IP address %s\n", NET_AdrToString (net_local_adr) ); + Con_Printf ("IP address %s\n", NET_AdrToString (net_local_adr)); } /* @@ -365,35 +386,36 @@ void NET_GetLocalAddress (void) NET_Init ==================== */ -void NET_Init (int port) +void +NET_Init (int port) { #ifdef _WIN32 - WORD wVersionRequested; - int r; + WORD wVersionRequested; + int r; - wVersionRequested = MAKEWORD(1, 1); + wVersionRequested = MAKEWORD (1, 1); - r = WSAStartup(MAKEWORD(1, 1), &winsockdata); + r = WSAStartup (MAKEWORD (1, 1), &winsockdata); if (r) Sys_Error ("Winsock initialization failed."); #endif /* _WIN32 */ - // + // // open the single socket to be used for all communications - // + // net_socket = UDP_OpenSocket (port); - // + // // init the message buffer - // - net_message.maxsize = sizeof(net_message_buffer); + // + net_message.maxsize = sizeof (net_message_buffer); net_message.data = net_message_buffer; - // + // // determine my name & address - // + // NET_GetLocalAddress (); - Con_Printf("UDP Initialized\n"); + Con_Printf ("UDP Initialized\n"); } /* @@ -401,11 +423,12 @@ void NET_Init (int port) NET_Shutdown ==================== */ -void NET_Shutdown (void) +void +NET_Shutdown (void) { #ifdef _WIN32 - closesocket(net_socket); - WSACleanup(); + closesocket (net_socket); + WSACleanup (); #else close (net_socket); #endif diff --git a/source/nonintel.c b/source/nonintel.c index 8160b4b..2afc005 100644 --- a/source/nonintel.c +++ b/source/nonintel.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifndef USE_INTEL_ASM @@ -37,7 +37,8 @@ R_Surf8Patch ================ */ -void R_Surf8Patch () +void +R_Surf8Patch () { // we only patch code on Intel } @@ -48,7 +49,8 @@ void R_Surf8Patch () R_Surf16Patch ================ */ -void R_Surf16Patch () +void +R_Surf16Patch () { // we only patch code on Intel } @@ -59,11 +61,11 @@ void R_Surf16Patch () R_SurfacePatch ================ */ -void R_SurfacePatch (void) +void +R_SurfacePatch (void) { // we only patch code on Intel } -#endif // !USE_INTEL_ASM - +#endif // !USE_INTEL_ASM diff --git a/source/pcx.c b/source/pcx.c index 872b719..bea9354 100644 --- a/source/pcx.c +++ b/source/pcx.c @@ -36,23 +36,24 @@ #include "qtypes.h" #include "quakefs.h" -byte *pcx_rgb; +byte *pcx_rgb; /* LoadPCX */ -void LoadPCX (QFile *f) +void +LoadPCX (QFile *f) { - pcx_t *pcx, pcxbuf; - byte palette[768]; - byte *pix; - int x, y; - int dataByte, runLength; - int count; + pcx_t *pcx, pcxbuf; + byte palette[768]; + byte *pix; + int x, y; + int dataByte, runLength; + int count; - // + // // parse the PCX file - // + // Qread (f, &pcxbuf, sizeof (pcxbuf)); pcx = &pcxbuf; @@ -69,13 +70,10 @@ void LoadPCX (QFile *f) if (pcx->manufacturer != 0x0a || pcx->version != 5 || pcx->encoding != 1 - || pcx->bits_per_pixel != 8 - || pcx->xmax >= 320 - || pcx->ymax >= 256) { + || pcx->bits_per_pixel != 8 || pcx->xmax >= 320 || pcx->ymax >= 256) { Con_Printf ("Bad pcx file\n"); return; } - // seek to palette Qseek (f, -768, SEEK_END); Qread (f, palette, 768); @@ -86,11 +84,11 @@ void LoadPCX (QFile *f) pcx_rgb = malloc (count * 4); for (y = 0; y <= pcx->ymax; y++) { - pix = pcx_rgb + 4*y*(pcx->xmax+1); + pix = pcx_rgb + 4 * y * (pcx->xmax + 1); for (x = 0; x <= pcx->ymax;) { dataByte = Qgetc (f); - if((dataByte & 0xC0) == 0xC0) { + if ((dataByte & 0xC0) == 0xC0) { runLength = dataByte & 0x3F; dataByte = Qgetc (f); } else { diff --git a/source/pmove.c b/source/pmove.c index cf265d9..502954d 100644 --- a/source/pmove.c +++ b/source/pmove.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "compat.h" #include "qtypes.h" @@ -37,41 +37,43 @@ #include -cvar_t *no_pogo_stick; -movevars_t movevars; +cvar_t *no_pogo_stick; +movevars_t movevars; -playermove_t pmove; +playermove_t pmove; -int onground; -int waterlevel; -int watertype; +int onground; +int waterlevel; +int watertype; -float frametime; +float frametime; -vec3_t forward, right, up; +vec3_t forward, right, up; -vec3_t player_mins = {-16, -16, -24}; -vec3_t player_maxs = {16, 16, 32}; +vec3_t player_mins = { -16, -16, -24 }; +vec3_t player_maxs = { 16, 16, 32 }; -// #define PM_GRAVITY 800 -// #define PM_STOPSPEED 100 -// #define PM_MAXSPEED 320 -// #define PM_SPECTATORMAXSPEED 500 -// #define PM_ACCELERATE 10 -// #define PM_AIRACCELERATE 0.7 -// #define PM_WATERACCELERATE 10 -// #define PM_FRICTION 6 -// #define PM_WATERFRICTION 1 +// #define PM_GRAVITY 800 +// #define PM_STOPSPEED 100 +// #define PM_MAXSPEED 320 +// #define PM_SPECTATORMAXSPEED 500 +// #define PM_ACCELERATE 10 +// #define PM_AIRACCELERATE 0.7 +// #define PM_WATERACCELERATE 10 +// #define PM_FRICTION 6 +// #define PM_WATERFRICTION 1 -void PM_InitBoxHull (void); -void PM_CategorizePosition (void); +void PM_InitBoxHull (void); +void PM_CategorizePosition (void); -void Pmove_Init (void) +void +Pmove_Init (void) { PM_InitBoxHull (); } -void Pmove_Init_Cvars (void) +void +Pmove_Init_Cvars (void) { no_pogo_stick = Cvar_Get ("no_pogo_stick", "0", CVAR_SERVERINFO, "disable the ability to pogo stick"); @@ -93,28 +95,28 @@ returns the blocked flags (1 = floor, 2 = step / wall) */ #define STOP_EPSILON 0.1 -int PM_ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce) +int +PM_ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce) { - float backoff; - float change; - int i, blocked; - + float backoff; + float change; + int i, blocked; + blocked = 0; if (normal[2] > 0) - blocked |= 1; // floor + blocked |= 1; // floor if (!normal[2]) - blocked |= 2; // step - + blocked |= 2; // step + backoff = DotProduct (in, normal) * overbounce; - for (i=0 ; i<3 ; i++) - { - change = normal[i]*backoff; + for (i = 0; i < 3; i++) { + change = normal[i] * backoff; out[i] = in[i] - change; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; } - + return blocked; } @@ -128,69 +130,65 @@ The basic solid body movement clip that slides along multiple planes */ #define MAX_CLIP_PLANES 5 -int PM_FlyMove (void) +int +PM_FlyMove (void) { - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity, original_velocity; - int i, j; - pmtrace_t trace; - vec3_t end; - float time_left; - int blocked; - + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity, original_velocity; + int i, j; + pmtrace_t trace; + vec3_t end; + float time_left; + int blocked; + numbumps = 4; - + blocked = 0; VectorCopy (pmove.velocity, original_velocity); VectorCopy (pmove.velocity, primal_velocity); numplanes = 0; - + time_left = frametime; - for (bumpcount=0 ; bumpcount 0) - { // actually covered some distance + if (trace.fraction > 0) { // actually covered some distance VectorCopy (trace.endpos, pmove.origin); numplanes = 0; } if (trace.fraction == 1) - break; // moved the entire distance + break; // moved the entire distance // save entity for contact pmove.touchindex[pmove.numtouch] = trace.ent; pmove.numtouch++; - if (trace.plane.normal[2] > 0.7) - { - blocked |= 1; // floor + if (trace.plane.normal[2] > 0.7) { + blocked |= 1; // floor } - if (!trace.plane.normal[2]) - { - blocked |= 2; // step + if (!trace.plane.normal[2]) { + blocked |= 2; // step } time_left -= time_left * trace.fraction; - - // cliped to another plane - if (numplanes >= MAX_CLIP_PLANES) - { // this shouldn't really happen + + // cliped to another plane + if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen VectorCopy (vec3_origin, pmove.velocity); break; } @@ -201,27 +199,21 @@ int PM_FlyMove (void) // // modify original_velocity so it parallels all of the clip planes // - for (i=0 ; i movevars.maxspeed) // there IS a spoon, Neo.. + if (pmspeed > movevars.maxspeed) // there IS a spoon, Neo.. { VectorScale (pmvel, movevars.maxspeed / pmspeed, pmvel); pmspeed = movevars.maxspeed; @@ -283,13 +276,12 @@ PM_FlymodeMove ( void ) VectorCopy (dest, start); start[2] += STEPSIZE + 1; trace = PM_PlayerMove (start, dest); - if (!trace.startsolid && !trace.allsolid) - { + if (!trace.startsolid && !trace.allsolid) { VectorCopy (trace.endpos, pmove.origin); - return; // just step up + return; // just step up } - PM_FlyMove (); // NOW we fly. + PM_FlyMove (); // NOW we fly. } @@ -300,31 +292,30 @@ PM_GroundMove Player is on ground, with no upwards velocity ============= */ -void PM_GroundMove (void) +void +PM_GroundMove (void) { - vec3_t start, dest; - pmtrace_t trace; - vec3_t original, originalvel, down, up, downvel; - float downdist, updist; + vec3_t start, dest; + pmtrace_t trace; + vec3_t original, originalvel, down, up, downvel; + float downdist, updist; pmove.velocity[2] = 0; if (!pmove.velocity[0] && !pmove.velocity[1] && !pmove.velocity[2]) return; - // first try just moving to the destination - dest[0] = pmove.origin[0] + pmove.velocity[0]*frametime; - dest[1] = pmove.origin[1] + pmove.velocity[1]*frametime; + // first try just moving to the destination + dest[0] = pmove.origin[0] + pmove.velocity[0] * frametime; + dest[1] = pmove.origin[1] + pmove.velocity[1] * frametime; dest[2] = pmove.origin[2]; // first try moving directly to the next spot VectorCopy (dest, start); trace = PM_PlayerMove (pmove.origin, dest); - if (trace.fraction == 1) - { + if (trace.fraction == 1) { VectorCopy (trace.endpos, pmove.origin); return; } - // try sliding forward both on ground and up 16 pixels // take the move that goes farthest VectorCopy (pmove.origin, original); @@ -343,11 +334,9 @@ void PM_GroundMove (void) VectorCopy (pmove.origin, dest); dest[2] += STEPSIZE; trace = PM_PlayerMove (pmove.origin, dest); - if (!trace.startsolid && !trace.allsolid) - { + if (!trace.startsolid && !trace.allsolid) { VectorCopy (trace.endpos, pmove.origin); } - // slide move PM_FlyMove (); @@ -355,26 +344,24 @@ void PM_GroundMove (void) VectorCopy (pmove.origin, dest); dest[2] -= STEPSIZE; trace = PM_PlayerMove (pmove.origin, dest); - if ( trace.plane.normal[2] < 0.7) + if (trace.plane.normal[2] < 0.7) goto usedown; - if (!trace.startsolid && !trace.allsolid) - { + if (!trace.startsolid && !trace.allsolid) { VectorCopy (trace.endpos, pmove.origin); } VectorCopy (pmove.origin, up); // decide which one went farther - downdist = (down[0] - original[0])*(down[0] - original[0]) - + (down[1] - original[1])*(down[1] - original[1]); - updist = (up[0] - original[0])*(up[0] - original[0]) - + (up[1] - original[1])*(up[1] - original[1]); + downdist = (down[0] - original[0]) * (down[0] - original[0]) + + (down[1] - original[1]) * (down[1] - original[1]); + updist = (up[0] - original[0]) * (up[0] - original[0]) + + (up[1] - original[1]) * (up[1] - original[1]); - if (downdist > updist) - { -usedown: + if (downdist > updist) { + usedown: VectorCopy (down, pmove.origin); VectorCopy (downvel, pmove.velocity); - } else // copy z value from slide move + } else // copy z value from slide move pmove.velocity[2] = downvel[2]; // if at a dead stop, retry the move with nudges to get around lips @@ -390,23 +377,23 @@ PM_Friction Handles both ground friction and water friction ================== */ -void PM_Friction (void) +void +PM_Friction (void) { - float *vel; - float speed, newspeed; - float friction; - float drop; - vec3_t start, stop; - pmtrace_t trace; - + float *vel; + float speed, newspeed; + float friction; + float drop; + vec3_t start, stop; + pmtrace_t trace; + if (pmove.waterjumptime) return; vel = pmove.velocity; - - speed = sqrt(vel[0]*vel[0] +vel[1]*vel[1] + vel[2]*vel[2]); - if (speed < 1) - { + + speed = sqrt (vel[0] * vel[0] + vel[1] * vel[1] + vel[2] * vel[2]); + if (speed < 1) { vel[0] = 0; vel[1] = 0; return; @@ -416,8 +403,8 @@ void PM_Friction (void) // if the leading edge is over a dropoff, increase friction if (onground != -1) { - start[0] = stop[0] = pmove.origin[0] + vel[0]/speed*16; - start[1] = stop[1] = pmove.origin[1] + vel[1]/speed*16; + start[0] = stop[0] = pmove.origin[0] + vel[0] / speed * 16; + start[1] = stop[1] = pmove.origin[1] + vel[1] / speed * 16; start[2] = pmove.origin[2] + player_mins[2]; stop[2] = start[2] - 34; @@ -430,12 +417,12 @@ void PM_Friction (void) drop = 0; - if (waterlevel >= 2) // apply water friction - drop += speed*movevars.waterfriction*waterlevel*frametime; - else if (pmove.flying) // apply flying friction - drop += max(movevars.stopspeed, speed) * friction * frametime; - else if (onground != -1) // apply ground friction - drop += max(movevars.stopspeed, speed) * friction * frametime; + if (waterlevel >= 2) // apply water friction + drop += speed * movevars.waterfriction * waterlevel * frametime; + else if (pmove.flying) // apply flying friction + drop += max (movevars.stopspeed, speed) * friction * frametime; + else if (onground != -1) // apply ground friction + drop += max (movevars.stopspeed, speed) * friction * frametime; // scale the velocity newspeed = speed - drop; @@ -454,10 +441,11 @@ void PM_Friction (void) PM_Accelerate ============== */ -void PM_Accelerate (vec3_t wishdir, float wishspeed, float accel) +void +PM_Accelerate (vec3_t wishdir, float wishspeed, float accel) { - int i; - float addspeed, accelspeed, currentspeed; + int i; + float addspeed, accelspeed, currentspeed; if (pmove.dead) return; @@ -468,19 +456,20 @@ void PM_Accelerate (vec3_t wishdir, float wishspeed, float accel) addspeed = wishspeed - currentspeed; if (addspeed <= 0) return; - accelspeed = accel*frametime*wishspeed; + accelspeed = accel * frametime * wishspeed; if (accelspeed > addspeed) accelspeed = addspeed; - - for (i=0 ; i<3 ; i++) - pmove.velocity[i] += accelspeed*wishdir[i]; + + for (i = 0; i < 3; i++) + pmove.velocity[i] += accelspeed * wishdir[i]; } -void PM_AirAccelerate (vec3_t wishdir, float wishspeed, float accel) +void +PM_AirAccelerate (vec3_t wishdir, float wishspeed, float accel) { - int i; - float addspeed, accelspeed, currentspeed, wishspd = wishspeed; - + int i; + float addspeed, accelspeed, currentspeed, wishspd = wishspeed; + if (pmove.dead) return; if (pmove.waterjumptime) @@ -495,9 +484,9 @@ void PM_AirAccelerate (vec3_t wishdir, float wishspeed, float accel) accelspeed = accel * wishspeed * frametime; if (accelspeed > addspeed) accelspeed = addspeed; - - for (i=0 ; i<3 ; i++) - pmove.velocity[i] += accelspeed*wishdir[i]; + + for (i = 0; i < 3; i++) + pmove.velocity[i] += accelspeed * wishdir[i]; } @@ -508,32 +497,33 @@ PM_WaterMove =================== */ -void PM_WaterMove (void) +void +PM_WaterMove (void) { - int i; - vec3_t wishvel; - float wishspeed; - vec3_t wishdir; - vec3_t start, dest; - pmtrace_t trace; + int i; + vec3_t wishvel; + float wishspeed; + vec3_t wishdir; + vec3_t start, dest; + pmtrace_t trace; // // user intentions // - for (i=0 ; i<3 ; i++) - wishvel[i] = forward[i]*pmove.cmd.forwardmove + right[i]*pmove.cmd.sidemove; + for (i = 0; i < 3; i++) + wishvel[i] = + forward[i] * pmove.cmd.forwardmove + right[i] * pmove.cmd.sidemove; if (!pmove.cmd.forwardmove && !pmove.cmd.sidemove && !pmove.cmd.upmove) - wishvel[2] -= 60; // drift towards bottom + wishvel[2] -= 60; // drift towards bottom else wishvel[2] += pmove.cmd.upmove; VectorCopy (wishvel, wishdir); - wishspeed = VectorNormalize(wishdir); + wishspeed = VectorNormalize (wishdir); - if (wishspeed > movevars.maxspeed) - { - VectorScale (wishvel, movevars.maxspeed/wishspeed, wishvel); + if (wishspeed > movevars.maxspeed) { + VectorScale (wishvel, movevars.maxspeed / wishspeed, wishvel); wishspeed = movevars.maxspeed; } wishspeed *= 0.7; @@ -541,8 +531,8 @@ void PM_WaterMove (void) // // water acceleration // -// if (pmove.waterjumptime) -// Con_Printf ("wm->%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); +// if (pmove.waterjumptime) +// Con_Printf ("wm->%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); PM_Accelerate (wishdir, wishspeed, movevars.wateraccelerate); // assume it is a stair or a slope, so press down from stepheight above @@ -551,14 +541,14 @@ void PM_WaterMove (void) start[2] += STEPSIZE + 1; trace = PM_PlayerMove (start, dest); if (!trace.startsolid && !trace.allsolid) // FIXME: check steep slope? - { // walked up the step + { // walked up the step VectorCopy (trace.endpos, pmove.origin); return; } - + PM_FlyMove (); -// if (pmove.waterjumptime) -// Con_Printf ("<-wm%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); +// if (pmove.waterjumptime) +// Con_Printf ("<-wm%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); } @@ -568,50 +558,47 @@ PM_AirMove =================== */ -void PM_AirMove (void) +void +PM_AirMove (void) { - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; - vec3_t original; + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; + vec3_t original; fmove = pmove.cmd.forwardmove; smove = pmove.cmd.sidemove; - + forward[2] = 0; right[2] = 0; VectorNormalize (forward); VectorNormalize (right); - for (i=0 ; i<2 ; i++) - wishvel[i] = forward[i]*fmove + right[i]*smove; + for (i = 0; i < 2; i++) + wishvel[i] = forward[i] * fmove + right[i] * smove; wishvel[2] = 0; VectorCopy (wishvel, wishdir); - wishspeed = VectorNormalize(wishdir); + wishspeed = VectorNormalize (wishdir); // // clamp to server defined max speed // - if (wishspeed > movevars.maxspeed) - { - VectorScale (wishvel, movevars.maxspeed/wishspeed, wishvel); + if (wishspeed > movevars.maxspeed) { + VectorScale (wishvel, movevars.maxspeed / wishspeed, wishvel); wishspeed = movevars.maxspeed; } - -// if (pmove.waterjumptime) -// Con_Printf ("am->%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); +// if (pmove.waterjumptime) +// Con_Printf ("am->%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); - if ( onground != -1) - { + if (onground != -1) { pmove.velocity[2] = 0; PM_Accelerate (wishdir, wishspeed, movevars.accelerate); pmove.velocity[2] -= movevars.entgravity * movevars.gravity * frametime; PM_GroundMove (); - } else if (pmove.flying) - { + } else if (pmove.flying) { PM_AirAccelerate (wishdir, wishspeed, movevars.accelerate); PM_FlyMove (); } else { @@ -621,17 +608,15 @@ void PM_AirMove (void) // add gravity pmove.velocity[2] -= movevars.entgravity * movevars.gravity * frametime; - if ( ! PM_FlyMove() ) - { + if (!PM_FlyMove ()) { // the move didn't get blocked PM_CategorizePosition (); - if (onground != -1) // but we're on ground now + if (onground != -1) // but we're on ground now { - // This is a hack to fix the jumping bug + // This is a hack to fix the jumping bug VectorCopy (pmove.origin, original); // Calculate correct velocity - if ( ! PM_FlyMove() ) - { + if (!PM_FlyMove ()) { // This shouldn't probably happen (?) if (pmove.velocity[2] < 0) pmove.velocity[2] = 0; @@ -642,13 +627,13 @@ void PM_AirMove (void) } //Con_Printf("airmove:vec: %4.2f %4.2f %4.2f\n", -// pmove.velocity[0], -// pmove.velocity[1], -// pmove.velocity[2]); +// pmove.velocity[0], +// pmove.velocity[1], +// pmove.velocity[2]); // -// if (pmove.waterjumptime) -// Con_Printf ("<-am%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); +// if (pmove.waterjumptime) +// Con_Printf ("<-am%f, %f, %f\n", pmove.velocity[0], pmove.velocity[1], pmove.velocity[2]); } @@ -658,40 +643,35 @@ void PM_AirMove (void) PM_CategorizePosition ============= */ -void PM_CategorizePosition (void) +void +PM_CategorizePosition (void) { - vec3_t point; - int cont; - pmtrace_t tr; + vec3_t point; + int cont; + pmtrace_t tr; // if the player hull point one unit down is solid, the player // is on ground -// see if standing on something solid +// see if standing on something solid point[0] = pmove.origin[0]; point[1] = pmove.origin[1]; point[2] = pmove.origin[2] - 1; - if (pmove.velocity[2] > 180) - { + if (pmove.velocity[2] > 180) { onground = -1; - } - else - { + } else { tr = PM_PlayerMove (pmove.origin, point); - if ( tr.plane.normal[2] < 0.7) - onground = -1; // too steep + if (tr.plane.normal[2] < 0.7) + onground = -1; // too steep else onground = tr.ent; - if (onground != -1) - { + if (onground != -1) { pmove.waterjumptime = 0; if (!tr.startsolid && !tr.allsolid) VectorCopy (tr.endpos, pmove.origin); } - // standing on an entity other than the world - if (tr.ent > 0) - { + if (tr.ent > 0) { pmove.touchindex[pmove.numtouch] = tr.ent; pmove.numtouch++; } @@ -703,17 +683,15 @@ void PM_CategorizePosition (void) waterlevel = 0; watertype = CONTENTS_EMPTY; - point[2] = pmove.origin[2] + player_mins[2] + 1; + point[2] = pmove.origin[2] + player_mins[2] + 1; cont = PM_PointContents (point); - if (cont <= CONTENTS_WATER) - { + if (cont <= CONTENTS_WATER) { watertype = cont; waterlevel = 1; - point[2] = pmove.origin[2] + (player_mins[2] + player_maxs[2])*0.5; + point[2] = pmove.origin[2] + (player_mins[2] + player_maxs[2]) * 0.5; cont = PM_PointContents (point); - if (cont <= CONTENTS_WATER) - { + if (cont <= CONTENTS_WATER) { waterlevel = 2; point[2] = pmove.origin[2] + 22; cont = PM_PointContents (point); @@ -730,22 +708,20 @@ void PM_CategorizePosition (void) void JumpButton (void) { - if (pmove.dead) - { - pmove.oldbuttons |= BUTTON_JUMP; // don't jump again until released + if (pmove.dead) { + pmove.oldbuttons |= BUTTON_JUMP; // don't jump again until + // released return; } - if (pmove.waterjumptime) - { + if (pmove.waterjumptime) { pmove.waterjumptime -= frametime; if (pmove.waterjumptime < 0) pmove.waterjumptime = 0; return; } - if (waterlevel >= 2) - { // swimming, not jumping + if (waterlevel >= 2) { // swimming, not jumping onground = -1; if (watertype == CONTENTS_WATER) @@ -759,12 +735,13 @@ JumpButton (void) if (onground == -1) { if (no_pogo_stick->int_val) - pmove.oldbuttons |= BUTTON_JUMP;// don't jump again until released - return; // in air, so no effect + pmove.oldbuttons |= BUTTON_JUMP; // don't jump again until + // released + return; // in air, so no effect } - if ( pmove.oldbuttons & BUTTON_JUMP ) - return; // don't pogo stick + if (pmove.oldbuttons & BUTTON_JUMP) + return; // don't pogo stick onground = -1; pmove.velocity[2] += 270; @@ -777,18 +754,19 @@ JumpButton (void) CheckWaterJump ============= */ -void CheckWaterJump (void) +void +CheckWaterJump (void) { - vec3_t spot; - int cont; - vec3_t flatforward; + vec3_t spot; + int cont; + vec3_t flatforward; if (pmove.waterjumptime || pmove.flying) return; // ZOID, don't hop out if we just jumped in if (pmove.velocity[2] < -180) - return; // only hop out if we are moving up + return; // only hop out if we are moving up // see if near an edge flatforward[0] = forward[0]; @@ -808,7 +786,7 @@ void CheckWaterJump (void) // jump out of water VectorScale (flatforward, 50, pmove.velocity); pmove.velocity[2] = 310; - pmove.waterjumptime = 2; // safety net + pmove.waterjumptime = 2; // safety net pmove.oldbuttons |= BUTTON_JUMP; // don't jump again until released } @@ -821,40 +799,38 @@ try nudging slightly on all axis to allow for the cut precision of the net coordinates ================= */ -void NudgePosition (void) +void +NudgePosition (void) { - vec3_t base; - int x, y, z; - int i; - static int sign[3] = {0, -1, 1}; + vec3_t base; + int x, y, z; + int i; + static int sign[3] = { 0, -1, 1 }; VectorCopy (pmove.origin, base); - for (i=0 ; i<3 ; i++) - pmove.origin[i] = ((int)(pmove.origin[i]*8)) * 0.125; -// pmove.origin[2] += 0.124; + for (i = 0; i < 3; i++) + pmove.origin[i] = ((int) (pmove.origin[i] * 8)) * 0.125; +// pmove.origin[2] += 0.124; -// if (pmove.dead) -// return; // might be a squished point, so don'y bother -// if (PM_TestPlayerPosition (pmove.origin) ) -// return; +// if (pmove.dead) +// return; // might be a squished point, so don'y bother +// if (PM_TestPlayerPosition (pmove.origin) ) +// return; - for (z=0 ; z<=2 ; z++) - { - for (x=0 ; x<=2 ; x++) - { - for (y=0 ; y<=2 ; y++) - { - pmove.origin[0] = base[0] + (sign[x] * 1.0/8); - pmove.origin[1] = base[1] + (sign[y] * 1.0/8); - pmove.origin[2] = base[2] + (sign[z] * 1.0/8); + for (z = 0; z <= 2; z++) { + for (x = 0; x <= 2; x++) { + for (y = 0; y <= 2; y++) { + pmove.origin[0] = base[0] + (sign[x] * 1.0 / 8); + pmove.origin[1] = base[1] + (sign[y] * 1.0 / 8); + pmove.origin[2] = base[2] + (sign[z] * 1.0 / 8); if (PM_TestPlayerPosition (pmove.origin)) return; } } } VectorCopy (base, pmove.origin); -// Con_DPrintf ("NudgePosition: stuck\n"); +// Con_DPrintf ("NudgePosition: stuck\n"); } /* @@ -862,30 +838,28 @@ void NudgePosition (void) SpectatorMove =============== */ -void SpectatorMove (void) +void +SpectatorMove (void) { - float speed, drop, friction, control, newspeed; - float currentspeed, addspeed, accelspeed; - int i; - vec3_t wishvel; - float fmove, smove; - vec3_t wishdir; - float wishspeed; + float speed, drop, friction, control, newspeed; + float currentspeed, addspeed, accelspeed; + int i; + vec3_t wishvel; + float fmove, smove; + vec3_t wishdir; + float wishspeed; // friction speed = Length (pmove.velocity); - if (speed < 1) - { + if (speed < 1) { VectorCopy (vec3_origin, pmove.velocity) - } - else - { + } else { drop = 0; - friction = movevars.friction*1.5; // extra friction + friction = movevars.friction * 1.5; // extra friction control = speed < movevars.stopspeed ? movevars.stopspeed : speed; - drop += control*friction*frametime; + drop += control * friction * frametime; // scale the velocity newspeed = speed - drop; @@ -899,36 +873,35 @@ void SpectatorMove (void) // accelerate fmove = pmove.cmd.forwardmove; smove = pmove.cmd.sidemove; - + VectorNormalize (forward); VectorNormalize (right); - for (i=0 ; i<3 ; i++) - wishvel[i] = forward[i]*fmove + right[i]*smove; + for (i = 0; i < 3; i++) + wishvel[i] = forward[i] * fmove + right[i] * smove; wishvel[2] += pmove.cmd.upmove; VectorCopy (wishvel, wishdir); - wishspeed = VectorNormalize(wishdir); + wishspeed = VectorNormalize (wishdir); - // + // // clamp to server defined max speed - // - if (wishspeed > movevars.spectatormaxspeed) - { - VectorScale (wishvel, movevars.spectatormaxspeed/wishspeed, wishvel); + // + if (wishspeed > movevars.spectatormaxspeed) { + VectorScale (wishvel, movevars.spectatormaxspeed / wishspeed, wishvel); wishspeed = movevars.spectatormaxspeed; } - currentspeed = DotProduct(pmove.velocity, wishdir); + currentspeed = DotProduct (pmove.velocity, wishdir); addspeed = wishspeed - currentspeed; if (addspeed <= 0) return; - accelspeed = movevars.accelerate*frametime*wishspeed; + accelspeed = movevars.accelerate * frametime * wishspeed; if (accelspeed > addspeed) accelspeed = addspeed; - - for (i=0 ; i<3 ; i++) - pmove.velocity[i] += accelspeed*wishdir[i]; + + for (i = 0; i < 3; i++) + pmove.velocity[i] += accelspeed * wishdir[i]; // move @@ -945,15 +918,15 @@ Numtouch and touchindex[] will be set if any of the physents were contacted during the move. ============= */ -void PlayerMove (void) +void +PlayerMove (void) { frametime = pmove.cmd.msec * 0.001; pmove.numtouch = 0; AngleVectors (pmove.angles, forward, right, up); - if (pmove.spectator) - { + if (pmove.spectator) { SpectatorMove (); return; } @@ -989,4 +962,3 @@ void PlayerMove (void) // set onground, watertype, and waterlevel for final spot PM_CategorizePosition (); } - diff --git a/source/pmovetst.c b/source/pmovetst.c index 08285cb..4a4baa8 100644 --- a/source/pmovetst.c +++ b/source/pmovetst.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -38,12 +38,12 @@ #include "model.h" #include "console.h" -static hull_t box_hull; -static dclipnode_t box_clipnodes[6]; -static mplane_t box_planes[6]; +static hull_t box_hull; +static dclipnode_t box_clipnodes[6]; +static mplane_t box_planes[6]; -extern vec3_t player_mins; -extern vec3_t player_maxs; +extern vec3_t player_mins; +extern vec3_t player_maxs; /* =================== @@ -53,32 +53,32 @@ Set up the planes and clipnodes so that the six floats of a bounding box can just be stored out and get a proper hull_t structure. =================== */ -void PM_InitBoxHull (void) +void +PM_InitBoxHull (void) { - int i; - int side; + int i; + int side; box_hull.clipnodes = box_clipnodes; box_hull.planes = box_planes; box_hull.firstclipnode = 0; box_hull.lastclipnode = 5; - for (i=0 ; i<6 ; i++) - { + for (i = 0; i < 6; i++) { box_clipnodes[i].planenum = i; - - side = i&1; - + + side = i & 1; + box_clipnodes[i].children[side] = CONTENTS_EMPTY; if (i != 5) - box_clipnodes[i].children[side^1] = i + 1; + box_clipnodes[i].children[side ^ 1] = i + 1; else - box_clipnodes[i].children[side^1] = CONTENTS_SOLID; - - box_planes[i].type = i>>1; - box_planes[i].normal[i>>1] = 1; + box_clipnodes[i].children[side ^ 1] = CONTENTS_SOLID; + + box_planes[i].type = i >> 1; + box_planes[i].normal[i >> 1] = 1; } - + } @@ -90,7 +90,8 @@ To keep everything totally uniform, bounding boxes are turned into small BSP trees instead of being compared directly. =================== */ -hull_t *PM_HullForBox (vec3_t mins, vec3_t maxs) +hull_t * +PM_HullForBox (vec3_t mins, vec3_t maxs) { box_planes[0].dist = maxs[0]; box_planes[1].dist = mins[0]; @@ -109,20 +110,20 @@ PM_HullPointContents ================== */ -int PM_HullPointContents (hull_t *hull, int num, vec3_t p) +int +PM_HullPointContents (hull_t *hull, int num, vec3_t p) { - float d; - dclipnode_t *node; - mplane_t *plane; + float d; + dclipnode_t *node; + mplane_t *plane; - while (num >= 0) - { + while (num >= 0) { if (num < hull->firstclipnode || num > hull->lastclipnode) Sys_Error ("PM_HullPointContents: bad node number"); - + node = hull->clipnodes + num; plane = hull->planes + node->planenum; - + if (plane->type < 3) d = p[plane->type] - plane->dist; else @@ -132,7 +133,7 @@ int PM_HullPointContents (hull_t *hull, int num, vec3_t p) else num = node->children[0]; } - + return num; } @@ -142,26 +143,26 @@ PM_PointContents ================== */ -int PM_PointContents (vec3_t p) +int +PM_PointContents (vec3_t p) { - float d; - dclipnode_t *node; - mplane_t *plane; - hull_t *hull; - int num; + float d; + dclipnode_t *node; + mplane_t *plane; + hull_t *hull; + int num; hull = &pmove.physents[0].model->hulls[0]; num = hull->firstclipnode; - while (num >= 0) - { + while (num >= 0) { if (num < hull->firstclipnode || num > hull->lastclipnode) Sys_Error ("PM_HullPointContents: bad node number"); - + node = hull->clipnodes + num; plane = hull->planes + node->planenum; - + if (plane->type < 3) d = p[plane->type] - plane->dist; else @@ -171,7 +172,7 @@ int PM_PointContents (vec3_t p) else num = node->children[0]; } - + return num; } @@ -192,36 +193,35 @@ PM_RecursiveHullCheck ================== */ -qboolean PM_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, pmtrace_t *trace) +qboolean +PM_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, + vec3_t p2, pmtrace_t *trace) { - dclipnode_t *node; - mplane_t *plane; - float t1, t2; - float frac; - int i; - vec3_t mid; - int side; - float midf; + dclipnode_t *node; + mplane_t *plane; + float t1, t2; + float frac; + int i; + vec3_t mid; + int side; + float midf; // LordHavoc: a goto! everyone flee in terror... :) -loc0: + loc0: // check for empty - if (num < 0) - { - if (num != CONTENTS_SOLID) - { + if (num < 0) { + if (num != CONTENTS_SOLID) { trace->allsolid = false; if (num == CONTENTS_EMPTY) trace->inopen = true; else trace->inwater = true; - } - else + } else trace->startsolid = true; - return true; // empty + return true; // empty } - - // LordHavoc: this can be eliminated by validating in the loader... but Mercury told me not to bother + // LordHavoc: this can be eliminated by validating in the loader... but + // Mercury told me not to bother if (num < hull->firstclipnode || num > hull->lastclipnode) Sys_Error ("PM_RecursiveHullCheck: bad node number"); @@ -231,93 +231,93 @@ loc0: node = hull->clipnodes + num; plane = hull->planes + node->planenum; - if (plane->type < 3) - { + if (plane->type < 3) { t1 = p1[plane->type] - plane->dist; t2 = p2[plane->type] - plane->dist; - } - else - { + } else { t1 = DotProduct (plane->normal, p1) - plane->dist; t2 = DotProduct (plane->normal, p2) - plane->dist; } // LordHavoc: recursion optimization if (t1 >= 0 && t2 >= 0) -// return PM_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace); +// return PM_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace); { num = node->children[0]; goto loc0; } if (t1 < 0 && t2 < 0) -// return PM_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace); +// return PM_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace); { num = node->children[1]; goto loc0; } - // put the crosspoint DIST_EPSILON pixels on the near side side = (t1 < 0); if (side) - frac = bound(0, (t1 + DIST_EPSILON) / (t1 - t2), 1); + frac = bound (0, (t1 + DIST_EPSILON) / (t1 - t2), 1); else - frac = bound(0, (t1 - DIST_EPSILON) / (t1 - t2), 1); - - midf = p1f + (p2f - p1f)*frac; - for (i=0 ; i<3 ; i++) - mid[i] = p1[i] + frac*(p2[i] - p1[i]); + frac = bound (0, (t1 - DIST_EPSILON) / (t1 - t2), 1); + + midf = p1f + (p2f - p1f) * frac; + for (i = 0; i < 3; i++) + mid[i] = p1[i] + frac * (p2[i] - p1[i]); // move up to the node - if (!PM_RecursiveHullCheck (hull, node->children[side], p1f, midf, p1, mid, trace) ) - return false; + if (!PM_RecursiveHullCheck + (hull, node->children[side], p1f, midf, p1, mid, trace)) return false; #ifdef PARANOID - if (PM_HullPointContents (pm_hullmodel, mid, node->children[side]) == CONTENTS_SOLID) - { + if (PM_HullPointContents (pm_hullmodel, mid, node->children[side]) == + CONTENTS_SOLID) { Con_Printf ("mid PointInHullSolid\n"); return false; } #endif - // LordHavoc: warning to the clumsy, this recursion can not be optimized because mid would need to be duplicated on a stack - if (PM_HullPointContents (hull, node->children[side^1], mid) != CONTENTS_SOLID) + // LordHavoc: warning to the clumsy, this recursion can not be optimized + // because mid would need to be duplicated on a stack + if (PM_HullPointContents (hull, node->children[side ^ 1], mid) != + CONTENTS_SOLID) // go past the node - return PM_RecursiveHullCheck (hull, node->children[side^1], midf, p2f, mid, p2, trace); - + return PM_RecursiveHullCheck (hull, node->children[side ^ 1], midf, p2f, + mid, p2, trace); + if (trace->allsolid) - return false; // never got out of the solid area - + return false; // never got out of the solid area + //================== // the other side of the node is solid, this is the impact point //================== - if (!side) - { + if (!side) { VectorCopy (plane->normal, trace->plane.normal); trace->plane.dist = plane->dist; - } - else - { - // LordHavoc: vec3_origin is evil; the compiler can not rely on it being '0 0 0' -// VectorSubtract (vec3_origin, plane->normal, trace->plane.normal); + } else { + // LordHavoc: vec3_origin is evil; the compiler can not rely on it + // being '0 0 0' +// VectorSubtract (vec3_origin, plane->normal, trace->plane.normal); trace->plane.normal[0] = -plane->normal[0]; trace->plane.normal[1] = -plane->normal[1]; trace->plane.normal[2] = -plane->normal[2]; trace->plane.dist = -plane->dist; } - while (PM_HullPointContents (hull, hull->firstclipnode, mid) == CONTENTS_SOLID) - { // shouldn't really happen, but does occasionally + while (PM_HullPointContents (hull, hull->firstclipnode, mid) == CONTENTS_SOLID) { // shouldn't + // really + // happen, + // but + // does + // occasionally frac -= 0.1; - if (frac < 0) - { + if (frac < 0) { trace->fraction = midf; VectorCopy (mid, trace->endpos); Con_DPrintf ("backup past 0\n"); return false; } - midf = p1f + (p2f - p1f)*frac; - for (i=0 ; i<3 ; i++) - mid[i] = p1[i] + frac*(p2[i] - p1[i]); + midf = p1f + (p2f - p1f) * frac; + for (i = 0; i < 3; i++) + mid[i] = p1[i] + frac * (p2[i] - p1[i]); } trace->fraction = midf; @@ -334,21 +334,20 @@ PM_TestPlayerPosition Returns false if the given player position is not valid (in solid) ================ */ -qboolean PM_TestPlayerPosition (vec3_t pos) +qboolean +PM_TestPlayerPosition (vec3_t pos) { - int i; - physent_t *pe; - vec3_t mins, maxs, test; - hull_t *hull; + int i; + physent_t *pe; + vec3_t mins, maxs, test; + hull_t *hull; - for (i=0 ; i< pmove.numphysent ; i++) - { + for (i = 0; i < pmove.numphysent; i++) { pe = &pmove.physents[i]; - // get the clipping hull + // get the clipping hull if (pe->model) hull = &pmove.physents[i].model->hulls[1]; - else - { + else { VectorSubtract (pe->mins, player_maxs, mins); VectorSubtract (pe->maxs, player_mins, maxs); hull = PM_HullForBox (mins, maxs); @@ -356,8 +355,8 @@ qboolean PM_TestPlayerPosition (vec3_t pos) VectorSubtract (pos, pe->origin, test); - if (PM_HullPointContents (hull, hull->firstclipnode, test) == CONTENTS_SOLID) - return false; + if (PM_HullPointContents (hull, hull->firstclipnode, test) == + CONTENTS_SOLID) return false; } return true; @@ -368,59 +367,60 @@ qboolean PM_TestPlayerPosition (vec3_t pos) PM_PlayerMove ================ */ -pmtrace_t PM_PlayerMove (vec3_t start, vec3_t end) +pmtrace_t +PM_PlayerMove (vec3_t start, vec3_t end) { - pmtrace_t trace, total; - vec3_t offset; - vec3_t start_l, end_l; - hull_t *hull; - int i; - physent_t *pe; - vec3_t mins, maxs; + pmtrace_t trace, total; + vec3_t offset; + vec3_t start_l, end_l; + hull_t *hull; + int i; + physent_t *pe; + vec3_t mins, maxs; // fill in a default trace - memset (&total, 0, sizeof(pmtrace_t)); + memset (&total, 0, sizeof (pmtrace_t)); + total.fraction = 1; total.ent = -1; VectorCopy (end, total.endpos); - for (i=0 ; i< pmove.numphysent ; i++) - { + for (i = 0; i < pmove.numphysent; i++) { pe = &pmove.physents[i]; - // get the clipping hull + // get the clipping hull if (pe->model) hull = &pmove.physents[i].model->hulls[1]; - else - { + else { VectorSubtract (pe->mins, player_maxs, mins); VectorSubtract (pe->maxs, player_mins, maxs); hull = PM_HullForBox (mins, maxs); } - // PM_HullForEntity (ent, mins, maxs, offset); - VectorCopy (pe->origin, offset); + // PM_HullForEntity (ent, mins, maxs, offset); + VectorCopy (pe->origin, offset); VectorSubtract (start, offset, start_l); VectorSubtract (end, offset, end_l); - // fill in a default trace - memset (&trace, 0, sizeof(pmtrace_t)); + // fill in a default trace + memset (&trace, 0, sizeof (pmtrace_t)); + trace.fraction = 1; trace.allsolid = true; -// trace.startsolid = true; +// trace.startsolid = true; VectorCopy (end, trace.endpos); - // trace a line through the apropriate clipping hull - PM_RecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, &trace); + // trace a line through the apropriate clipping hull + PM_RecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, + &trace); if (trace.allsolid) trace.startsolid = true; if (trace.startsolid) trace.fraction = 0; - // did we clip the move? - if (trace.fraction < total.fraction) - { + // did we clip the move? + if (trace.fraction < total.fraction) { // fix trace up by the offset VectorAdd (trace.endpos, offset, trace.endpos); total = trace; @@ -431,5 +431,3 @@ pmtrace_t PM_PlayerMove (vec3_t start, vec3_t end) return total; } - - diff --git a/source/pr_cmds.c b/source/pr_cmds.c index 555f46a..5388669 100644 --- a/source/pr_cmds.c +++ b/source/pr_cmds.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "pr_comp.h" #include "va.h" @@ -44,7 +44,7 @@ #include #include -void SV_Error (char *error, ...); +void SV_Error (char *error, ...); #define RETURN_EDICT(e) (((int *)pr_globals)[OFS_RETURN] = EDICT_TO_PROG(e)) #define RETURN_STRING(s) (((int *)pr_globals)[OFS_RETURN] = PR_SetString(s)) @@ -57,15 +57,16 @@ void SV_Error (char *error, ...); =============================================================================== */ -char *PF_VarString (int first) +char * +PF_VarString (int first) { - int i; + int i; static char out[256]; - + out[0] = 0; - for (i=first ; is_name) ,s); - ed = PROG_TO_EDICT(pr_global_struct->self); + char *s; + edict_t *ed; + + s = PF_VarString (0); + Con_Printf ("======SERVER ERROR in %s:\n%s\n", + PR_GetString (pr_xfunction->s_name), s); + ed = PROG_TO_EDICT (pr_global_struct->self); ED_Print (ed); SV_Error ("Program error"); @@ -104,17 +107,19 @@ removed, but the level can continue. objerror(value) ================= */ -void PF_objerror (void) +void +PF_objerror (void) { - char *s; - edict_t *ed; - - s = PF_VarString(0); - Con_Printf ("======OBJECT ERROR in %s:\n%s\n", PR_GetString(pr_xfunction->s_name),s); - ed = PROG_TO_EDICT(pr_global_struct->self); + char *s; + edict_t *ed; + + s = PF_VarString (0); + Con_Printf ("======OBJECT ERROR in %s:\n%s\n", + PR_GetString (pr_xfunction->s_name), s); + ed = PROG_TO_EDICT (pr_global_struct->self); ED_Print (ed); ED_Free (ed); - + SV_Error ("Program error"); } @@ -128,9 +133,11 @@ Writes new values for v_forward, v_up, and v_right based on angles makevectors(vector) ============== */ -void PF_makevectors (void) +void +PF_makevectors (void) { - AngleVectors (G_VECTOR(OFS_PARM0), pr_global_struct->v_forward, pr_global_struct->v_right, pr_global_struct->v_up); + AngleVectors (G_VECTOR (OFS_PARM0), pr_global_struct->v_forward, + pr_global_struct->v_right, pr_global_struct->v_up); } /* @@ -142,13 +149,14 @@ This is the only valid way to move an object without using the physics of the wo setorigin (entity, origin) ================= */ -void PF_setorigin (void) +void +PF_setorigin (void) { - edict_t *e; - float *org; - - e = G_EDICT(OFS_PARM0); - org = G_VECTOR(OFS_PARM1); + edict_t *e; + float *org; + + e = G_EDICT (OFS_PARM0); + org = G_VECTOR (OFS_PARM1); VectorCopy (org, e->v.origin); SV_LinkEdict (e, false); } @@ -163,14 +171,15 @@ the size box is rotated by the current angle setsize (entity, minvector, maxvector) ================= */ -void PF_setsize (void) +void +PF_setsize (void) { - edict_t *e; - float *min, *max; - - e = G_EDICT(OFS_PARM0); - min = G_VECTOR(OFS_PARM1); - max = G_VECTOR(OFS_PARM2); + edict_t *e; + float *min, *max; + + e = G_EDICT (OFS_PARM0); + min = G_VECTOR (OFS_PARM1); + max = G_VECTOR (OFS_PARM2); VectorCopy (min, e->v.mins); VectorCopy (max, e->v.maxs); VectorSubtract (max, min, e->v.size); @@ -186,30 +195,30 @@ setmodel(entity, model) Also sets size, mins, and maxs for inline bmodels ================= */ -void PF_setmodel (void) +void +PF_setmodel (void) { - edict_t *e; - char *m, **check; - int i; - model_t *mod; + edict_t *e; + char *m, **check; + int i; + model_t *mod; - e = G_EDICT(OFS_PARM0); - m = G_STRING(OFS_PARM1); + e = G_EDICT (OFS_PARM0); + m = G_STRING (OFS_PARM1); // check to see if model was properly precached - for (i=0, check = sv.model_precache ; *check ; i++, check++) - if (!strcmp(*check, m)) + for (i = 0, check = sv.model_precache; *check; i++, check++) + if (!strcmp (*check, m)) break; if (!*check) PR_RunError ("no precache: %s\n", m); - - e->v.model = PR_SetString(m); + + e->v.model = PR_SetString (m); e->v.modelindex = i; // if it is an inline model, get the size information for it - if (m[0] == '*') - { + if (m[0] == '*') { mod = Mod_ForName (m, true); VectorCopy (mod->mins, e->v.mins); VectorCopy (mod->maxs, e->v.maxs); @@ -228,14 +237,15 @@ broadcast print to everyone on server bprint(value) ================= */ -void PF_bprint (void) +void +PF_bprint (void) { - char *s; - int level; - - level = G_FLOAT(OFS_PARM0); + char *s; + int level; - s = PF_VarString(1); + level = G_FLOAT (OFS_PARM0); + + s = PF_VarString (1); SV_BroadcastPrintf (level, "%s", s); } @@ -248,26 +258,26 @@ single print to a specific client sprint(clientent, value) ================= */ -void PF_sprint (void) +void +PF_sprint (void) { - char *s; - client_t *client; - int entnum; - int level; - - entnum = G_EDICTNUM(OFS_PARM0); - level = G_FLOAT(OFS_PARM1); + char *s; + client_t *client; + int entnum; + int level; - s = PF_VarString(2); - - if (entnum < 1 || entnum > MAX_CLIENTS) - { + entnum = G_EDICTNUM (OFS_PARM0); + level = G_FLOAT (OFS_PARM1); + + s = PF_VarString (2); + + if (entnum < 1 || entnum > MAX_CLIENTS) { Con_Printf ("tried to sprint to a non-client\n"); return; } - - client = &svs.clients[entnum-1]; - + + client = &svs.clients[entnum - 1]; + SV_ClientPrintf (client, level, "%s", s); } @@ -281,24 +291,24 @@ single print to a specific client centerprint(clientent, value) ================= */ -void PF_centerprint (void) +void +PF_centerprint (void) { - char *s; - int entnum; - client_t *cl; - - entnum = G_EDICTNUM(OFS_PARM0); - s = PF_VarString(1); - - if (entnum < 1 || entnum > MAX_CLIENTS) - { + char *s; + int entnum; + client_t *cl; + + entnum = G_EDICTNUM (OFS_PARM0); + s = PF_VarString (1); + + if (entnum < 1 || entnum > MAX_CLIENTS) { Con_Printf ("tried to sprint to a non-client\n"); return; } - - cl = &svs.clients[entnum-1]; - ClientReliableWrite_Begin (cl, svc_centerprint, 2 + strlen(s)); + cl = &svs.clients[entnum - 1]; + + ClientReliableWrite_Begin (cl, svc_centerprint, 2 + strlen (s)); ClientReliableWrite_String (cl, s); } @@ -310,28 +320,28 @@ PF_normalize vector normalize(vector) ================= */ -void PF_normalize (void) +void +PF_normalize (void) { - float *value1; - vec3_t newvalue; - float new; - - value1 = G_VECTOR(OFS_PARM0); + float *value1; + vec3_t newvalue; + float new; + + value1 = G_VECTOR (OFS_PARM0); + + new = value1[0] * value1[0] + value1[1] * value1[1] + value1[2] * value1[2]; + new = sqrt (new); - new = value1[0] * value1[0] + value1[1] * value1[1] + value1[2]*value1[2]; - new = sqrt(new); - if (new == 0) newvalue[0] = newvalue[1] = newvalue[2] = 0; - else - { - new = 1/new; + else { + new = 1 / new; newvalue[0] = value1[0] * new; newvalue[1] = value1[1] * new; newvalue[2] = value1[2] * new; } - - VectorCopy (newvalue, G_VECTOR(OFS_RETURN)); + + VectorCopy (newvalue, G_VECTOR (OFS_RETURN)); } /* @@ -341,17 +351,18 @@ PF_vlen scalar vlen(vector) ================= */ -void PF_vlen (void) +void +PF_vlen (void) { - float *value1; - float new; - - value1 = G_VECTOR(OFS_PARM0); + float *value1; + float new; - new = value1[0] * value1[0] + value1[1] * value1[1] + value1[2]*value1[2]; - new = sqrt(new); - - G_FLOAT(OFS_RETURN) = new; + value1 = G_VECTOR (OFS_PARM0); + + new = value1[0] * value1[0] + value1[1] * value1[1] + value1[2] * value1[2]; + new = sqrt (new); + + G_FLOAT (OFS_RETURN) = new; } /* @@ -361,23 +372,23 @@ PF_vectoyaw float vectoyaw(vector) ================= */ -void PF_vectoyaw (void) +void +PF_vectoyaw (void) { - float *value1; - float yaw; - - value1 = G_VECTOR(OFS_PARM0); + float *value1; + float yaw; + + value1 = G_VECTOR (OFS_PARM0); if (value1[1] == 0 && value1[0] == 0) yaw = 0; - else - { - yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI); + else { + yaw = (int) (atan2 (value1[1], value1[0]) * 180 / M_PI); if (yaw < 0) yaw += 360; } - G_FLOAT(OFS_RETURN) = yaw; + G_FLOAT (OFS_RETURN) = yaw; } @@ -388,37 +399,35 @@ PF_vectoangles vector vectoangles(vector) ================= */ -void PF_vectoangles (void) +void +PF_vectoangles (void) { - float *value1; - float forward; - float yaw, pitch; - - value1 = G_VECTOR(OFS_PARM0); + float *value1; + float forward; + float yaw, pitch; - if (value1[1] == 0 && value1[0] == 0) - { + value1 = G_VECTOR (OFS_PARM0); + + if (value1[1] == 0 && value1[0] == 0) { yaw = 0; if (value1[2] > 0) pitch = 90; else pitch = 270; - } - else - { - yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI); + } else { + yaw = (int) (atan2 (value1[1], value1[0]) * 180 / M_PI); if (yaw < 0) yaw += 360; - forward = sqrt (value1[0]*value1[0] + value1[1]*value1[1]); - pitch = (int) (atan2(value1[2], forward) * 180 / M_PI); + forward = sqrt (value1[0] * value1[0] + value1[1] * value1[1]); + pitch = (int) (atan2 (value1[2], forward) * 180 / M_PI); if (pitch < 0) pitch += 360; } - G_FLOAT(OFS_RETURN+0) = pitch; - G_FLOAT(OFS_RETURN+1) = yaw; - G_FLOAT(OFS_RETURN+2) = 0; + G_FLOAT (OFS_RETURN + 0) = pitch; + G_FLOAT (OFS_RETURN + 1) = yaw; + G_FLOAT (OFS_RETURN + 2) = 0; } /* @@ -430,13 +439,14 @@ Returns a number from 0<= num < 1 random() ================= */ -void PF_random (void) +void +PF_random (void) { - float num; - - num = (rand ()&0x7fff) / ((float)0x7fff); - - G_FLOAT(OFS_RETURN) = num; + float num; + + num = (rand () & 0x7fff) / ((float) 0x7fff); + + G_FLOAT (OFS_RETURN) = num; } @@ -446,40 +456,39 @@ PF_ambientsound ================= */ -void PF_ambientsound (void) +void +PF_ambientsound (void) { - char **check; - char *samp; - float *pos; - float vol, attenuation; - int i, soundnum; + char **check; + char *samp; + float *pos; + float vol, attenuation; + int i, soundnum; + + pos = G_VECTOR (OFS_PARM0); + samp = G_STRING (OFS_PARM1); + vol = G_FLOAT (OFS_PARM2); + attenuation = G_FLOAT (OFS_PARM3); - pos = G_VECTOR (OFS_PARM0); - samp = G_STRING(OFS_PARM1); - vol = G_FLOAT(OFS_PARM2); - attenuation = G_FLOAT(OFS_PARM3); - // check to see if samp was properly precached - for (soundnum=0, check = sv.sound_precache ; *check ; check++, soundnum++) - if (!strcmp(*check,samp)) + for (soundnum = 0, check = sv.sound_precache; *check; check++, soundnum++) + if (!strcmp (*check, samp)) break; - - if (!*check) - { + + if (!*check) { Con_Printf ("no precache: %s\n", samp); return; } - // add an svc_spawnambient command to the level signon packet - MSG_WriteByte (&sv.signon,svc_spawnstaticsound); - for (i=0 ; i<3 ; i++) - MSG_WriteCoord(&sv.signon, pos[i]); + MSG_WriteByte (&sv.signon, svc_spawnstaticsound); + for (i = 0; i < 3; i++) + MSG_WriteCoord (&sv.signon, pos[i]); MSG_WriteByte (&sv.signon, soundnum); - MSG_WriteByte (&sv.signon, vol*255); - MSG_WriteByte (&sv.signon, attenuation*64); + MSG_WriteByte (&sv.signon, vol * 255); + MSG_WriteByte (&sv.signon, attenuation * 64); } @@ -498,20 +507,21 @@ Larger attenuations will drop off. ================= */ -void PF_sound (void) +void +PF_sound (void) { - char *sample; - int channel; - edict_t *entity; - int volume; - float attenuation; - - entity = G_EDICT(OFS_PARM0); - channel = G_FLOAT(OFS_PARM1); - sample = G_STRING(OFS_PARM2); - volume = G_FLOAT(OFS_PARM3) * 255; - attenuation = G_FLOAT(OFS_PARM4); - + char *sample; + int channel; + edict_t *entity; + int volume; + float attenuation; + + entity = G_EDICT (OFS_PARM0); + channel = G_FLOAT (OFS_PARM1); + sample = G_STRING (OFS_PARM2); + volume = G_FLOAT (OFS_PARM3) * 255; + attenuation = G_FLOAT (OFS_PARM4); + SV_StartSound (entity, channel, sample, volume, attenuation); } @@ -522,11 +532,12 @@ PF_break break() ================= */ -void PF_break (void) +void +PF_break (void) { -Con_Printf ("break statement\n"); -*(int *)-4 = 0; // dump to debugger -// PR_RunError ("break statement"); + Con_Printf ("break statement\n"); + *(int *) -4 = 0; // dump to debugger +// PR_RunError ("break statement"); } /* @@ -540,17 +551,18 @@ if the tryents flag is set. traceline (vector1, vector2, tryents) ================= */ -void PF_traceline (void) +void +PF_traceline (void) { - float *v1, *v2; - trace_t trace; - int nomonsters; - edict_t *ent; + float *v1, *v2; + trace_t trace; + int nomonsters; + edict_t *ent; - v1 = G_VECTOR(OFS_PARM0); - v2 = G_VECTOR(OFS_PARM1); - nomonsters = G_FLOAT(OFS_PARM2); - ent = G_EDICT(OFS_PARM3); + v1 = G_VECTOR (OFS_PARM0); + v2 = G_VECTOR (OFS_PARM1); + nomonsters = G_FLOAT (OFS_PARM2); + ent = G_EDICT (OFS_PARM3); trace = SV_Move (v1, vec3_origin, vec3_origin, v2, nomonsters, ent); @@ -561,11 +573,11 @@ void PF_traceline (void) pr_global_struct->trace_inopen = trace.inopen; VectorCopy (trace.endpos, pr_global_struct->trace_endpos); VectorCopy (trace.plane.normal, pr_global_struct->trace_plane_normal); - pr_global_struct->trace_plane_dist = trace.plane.dist; + pr_global_struct->trace_plane_dist = trace.plane.dist; if (trace.ent) - pr_global_struct->trace_ent = EDICT_TO_PROG(trace.ent); + pr_global_struct->trace_ent = EDICT_TO_PROG (trace.ent); else - pr_global_struct->trace_ent = EDICT_TO_PROG(sv.edicts); + pr_global_struct->trace_ent = EDICT_TO_PROG (sv.edicts); } /* @@ -578,21 +590,23 @@ FIXME: make work... scalar checkpos (entity, vector) ================= */ -void PF_checkpos (void) +void +PF_checkpos (void) { } //============================================================================ -byte checkpvs[MAX_MAP_LEAFS/8]; +byte checkpvs[MAX_MAP_LEAFS / 8]; -int PF_newcheckclient (int check) +int +PF_newcheckclient (int check) { - int i; - byte *pvs; - edict_t *ent; - mleaf_t *leaf; - vec3_t org; + int i; + byte *pvs; + edict_t *ent; + mleaf_t *leaf; + vec3_t org; // cycle to the next one @@ -606,24 +620,23 @@ int PF_newcheckclient (int check) else i = check + 1; - for ( ; ; i++) - { - if (i == MAX_CLIENTS+1) + for (;; i++) { + if (i == MAX_CLIENTS + 1) i = 1; - ent = EDICT_NUM(i); + ent = EDICT_NUM (i); if (i == check) - break; // didn't find anything else + break; // didn't find anything else if (ent->free) continue; if (ent->v.health <= 0) continue; - if ((int)ent->v.flags & FL_NOTARGET) + if ((int) ent->v.flags & FL_NOTARGET) continue; - // anything that is a client, or has a client as an enemy + // anything that is a client, or has a client as an enemy break; } @@ -631,7 +644,7 @@ int PF_newcheckclient (int check) VectorAdd (ent->v.origin, ent->v.view_ofs, org); leaf = Mod_PointInLeaf (org, sv.worldmodel); pvs = Mod_LeafPVS (leaf, sv.worldmodel); - memcpy (checkpvs, pvs, (sv.worldmodel->numleafs+7)>>3 ); + memcpy (checkpvs, pvs, (sv.worldmodel->numleafs + 7) >> 3); return i; } @@ -652,44 +665,39 @@ name checkclient () ================= */ #define MAX_CHECK 16 -int c_invis, c_notvis; -void PF_checkclient (void) +int c_invis, c_notvis; +void +PF_checkclient (void) { - edict_t *ent, *self; - mleaf_t *leaf; - int l; - vec3_t view; - + edict_t *ent, *self; + mleaf_t *leaf; + int l; + vec3_t view; + // find a new check if on a new frame - if (sv.time - sv.lastchecktime >= 0.1) - { + if (sv.time - sv.lastchecktime >= 0.1) { sv.lastcheck = PF_newcheckclient (sv.lastcheck); sv.lastchecktime = sv.time; } - -// return check if it might be visible - ent = EDICT_NUM(sv.lastcheck); - if (ent->free || ent->v.health <= 0) - { - RETURN_EDICT(sv.edicts); +// return check if it might be visible + ent = EDICT_NUM (sv.lastcheck); + if (ent->free || ent->v.health <= 0) { + RETURN_EDICT (sv.edicts); return; } - // if current entity can't possibly see the check entity, return 0 - self = PROG_TO_EDICT(pr_global_struct->self); + self = PROG_TO_EDICT (pr_global_struct->self); VectorAdd (self->v.origin, self->v.view_ofs, view); leaf = Mod_PointInLeaf (view, sv.worldmodel); l = (leaf - sv.worldmodel->leafs) - 1; - if ( (l<0) || !(checkpvs[l>>3] & (1<<(l&7)) ) ) - { -c_notvis++; - RETURN_EDICT(sv.edicts); + if ((l < 0) || !(checkpvs[l >> 3] & (1 << (l & 7)))) { + c_notvis++; + RETURN_EDICT (sv.edicts); return; } - // might be able to see it -c_invis++; - RETURN_EDICT(ent); + c_invis++; + RETURN_EDICT (ent); } //============================================================================ @@ -704,38 +712,36 @@ Sends text over to the client's execution buffer stuffcmd (clientent, value) ================= */ -void PF_stuffcmd (void) +void +PF_stuffcmd (void) { - int entnum; - char *str; - client_t *cl; - char *buf; - int i; - - entnum = G_EDICTNUM(OFS_PARM0); + int entnum; + char *str; + client_t *cl; + char *buf; + int i; + + entnum = G_EDICTNUM (OFS_PARM0); if (entnum < 1 || entnum > MAX_CLIENTS) PR_RunError ("Parm 0 not a client"); - str = G_STRING(OFS_PARM1); - - cl = &svs.clients[entnum-1]; + str = G_STRING (OFS_PARM1); + + cl = &svs.clients[entnum - 1]; buf = cl->stufftext_buf; - if (strlen(buf) + strlen(str) >= MAX_STUFFTEXT) + if (strlen (buf) + strlen (str) >= MAX_STUFFTEXT) PR_RunError ("stufftext buffer overflow"); - strncat (buf, str, MAX_STUFFTEXT - strlen (buf)); + strncat (buf, str, MAX_STUFFTEXT - strlen (buf)); - for (i = strlen(buf); i >= 0; i--) - { - if (buf[i] == '\n') - { - if (!strcmp(buf, "disconnect\n")) - { + for (i = strlen (buf); i >= 0; i--) { + if (buf[i] == '\n') { + if (!strcmp (buf, "disconnect\n")) { // so long and thanks for all the fish cl->drop = true; buf[0] = 0; return; } - ClientReliableWrite_Begin (cl, svc_stufftext, 2+strlen(buf)); + ClientReliableWrite_Begin (cl, svc_stufftext, 2 + strlen (buf)); ClientReliableWrite_String (cl, buf); buf[0] = 0; } @@ -751,11 +757,12 @@ Sends text over to the client's execution buffer localcmd (string) ================= */ -void PF_localcmd (void) +void +PF_localcmd (void) { - char *str; - - str = G_STRING(OFS_PARM0); + char *str; + + str = G_STRING (OFS_PARM0); Cbuf_AddText (str); } @@ -766,13 +773,14 @@ PF_cvar float cvar (string) ================= */ -void PF_cvar (void) +void +PF_cvar (void) { - char *str; - - str = G_STRING(OFS_PARM0); - - G_FLOAT(OFS_RETURN) = Cvar_VariableValue (str); + char *str; + + str = G_STRING (OFS_PARM0); + + G_FLOAT (OFS_RETURN) = Cvar_VariableValue (str); } /* @@ -782,18 +790,18 @@ PF_cvar_set float cvar (string) ================= */ -void PF_cvar_set (void) +void +PF_cvar_set (void) { - char *var_name, *val; - cvar_t *var; - - var_name = G_STRING(OFS_PARM0); - val = G_STRING(OFS_PARM1); - var = Cvar_FindVar(var_name); + char *var_name, *val; + cvar_t *var; + + var_name = G_STRING (OFS_PARM0); + val = G_STRING (OFS_PARM1); + var = Cvar_FindVar (var_name); if (!var) - var = Cvar_FindAlias(var_name); - if (!var) - { + var = Cvar_FindAlias (var_name); + if (!var) { // FIXME: make Con_DPrint? Con_Printf ("PF_cvar_set: variable %s not found\n", var_name); return; @@ -811,36 +819,38 @@ Returns a chain of entities that have origins within a spherical area findradius (origin, radius) ================= */ -void PF_findradius (void) +void +PF_findradius (void) { - edict_t *ent, *chain; - float rad; - float *org; - vec3_t eorg; - int i, j; + edict_t *ent, *chain; + float rad; + float *org; + vec3_t eorg; + int i, j; - chain = (edict_t *)sv.edicts; - - org = G_VECTOR(OFS_PARM0); - rad = G_FLOAT(OFS_PARM1); + chain = (edict_t *) sv.edicts; - ent = NEXT_EDICT(sv.edicts); - for (i=1 ; ifree) continue; if (ent->v.solid == SOLID_NOT) continue; - for (j=0 ; j<3 ; j++) - eorg[j] = org[j] - (ent->v.origin[j] + (ent->v.mins[j] + ent->v.maxs[j])*0.5); - if (Length(eorg) > rad) + for (j = 0; j < 3; j++) + eorg[j] = + org[j] - (ent->v.origin[j] + + (ent->v.mins[j] + ent->v.maxs[j]) * 0.5); + if (Length (eorg) > rad) continue; - - ent->v.chain = EDICT_TO_PROG(chain); + + ent->v.chain = EDICT_TO_PROG (chain); chain = ent; } - RETURN_EDICT(chain); + RETURN_EDICT (chain); } @@ -849,176 +859,193 @@ void PF_findradius (void) PF_dprint ========= */ -void PF_dprint (void) +void +PF_dprint (void) { - Con_Printf ("%s",PF_VarString(0)); + Con_Printf ("%s", PF_VarString (0)); } -char pr_string_temp[128]; +char pr_string_temp[128]; -void PF_ftos (void) +void +PF_ftos (void) { - float v; - int i; // 1999-07-25 FTOS fix by Maddes + float v; + int i; // 1999-07-25 FTOS fix by Maddes - v = G_FLOAT(OFS_PARM0); - - if (v == (int)v) - snprintf (pr_string_temp, sizeof(pr_string_temp), "%d",(int)v); + v = G_FLOAT (OFS_PARM0); + + if (v == (int) v) + snprintf (pr_string_temp, sizeof (pr_string_temp), "%d", (int) v); else // 1999-07-25 FTOS fix by Maddes start { - snprintf (pr_string_temp, sizeof(pr_string_temp), "%1f", v); - for (i=strlen(pr_string_temp)-1 ; i>0 && pr_string_temp[i]=='0' && pr_string_temp[i-1]!='.' ; i--) - { + snprintf (pr_string_temp, sizeof (pr_string_temp), "%1f", v); + for (i = strlen (pr_string_temp) - 1; + i > 0 && pr_string_temp[i] == '0' && pr_string_temp[i - 1] != '.'; + i--) { pr_string_temp[i] = 0; } } // 1999-07-25 FTOS fix by Maddes end - G_INT(OFS_RETURN) = PR_SetString(pr_string_temp); + G_INT (OFS_RETURN) = PR_SetString (pr_string_temp); } -void PF_fabs (void) +void +PF_fabs (void) { - float v; - v = G_FLOAT(OFS_PARM0); - G_FLOAT(OFS_RETURN) = fabs(v); + float v; + + v = G_FLOAT (OFS_PARM0); + G_FLOAT (OFS_RETURN) = fabs (v); } -void PF_vtos (void) +void +PF_vtos (void) { - snprintf (pr_string_temp, sizeof(pr_string_temp), "'%5.1f %5.1f %5.1f'", G_VECTOR(OFS_PARM0)[0], G_VECTOR(OFS_PARM0)[1], G_VECTOR(OFS_PARM0)[2]); - G_INT(OFS_RETURN) = PR_SetString(pr_string_temp); + snprintf (pr_string_temp, sizeof (pr_string_temp), "'%5.1f %5.1f %5.1f'", + G_VECTOR (OFS_PARM0)[0], G_VECTOR (OFS_PARM0)[1], + G_VECTOR (OFS_PARM0)[2]); + G_INT (OFS_RETURN) = PR_SetString (pr_string_temp); } -void PF_Spawn (void) +void +PF_Spawn (void) { - edict_t *ed; - ed = ED_Alloc(); - RETURN_EDICT(ed); + edict_t *ed; + + ed = ED_Alloc (); + RETURN_EDICT (ed); } -void PF_Remove (void) +void +PF_Remove (void) { - edict_t *ed; - - ed = G_EDICT(OFS_PARM0); + edict_t *ed; + + ed = G_EDICT (OFS_PARM0); ED_Free (ed); } // entity (entity start, .string field, string match) find = #5; -void PF_Find (void) +void +PF_Find (void) { - int e; - int f; - char *s, *t; - edict_t *ed; - - e = G_EDICTNUM(OFS_PARM0); - f = G_INT(OFS_PARM1); - s = G_STRING(OFS_PARM2); + int e; + int f; + char *s, *t; + edict_t *ed; + + e = G_EDICTNUM (OFS_PARM0); + f = G_INT (OFS_PARM1); + s = G_STRING (OFS_PARM2); if (!s) PR_RunError ("PF_Find: bad search string"); - - for (e++ ; e < sv.num_edicts ; e++) - { - ed = EDICT_NUM(e); + + for (e++; e < sv.num_edicts; e++) { + ed = EDICT_NUM (e); if (ed->free) continue; - t = E_STRING(ed,f); + t = E_STRING (ed, f); if (!t) continue; - if (!strcmp(t,s)) - { - RETURN_EDICT(ed); + if (!strcmp (t, s)) { + RETURN_EDICT (ed); return; } } - - RETURN_EDICT(sv.edicts); + + RETURN_EDICT (sv.edicts); } -void PR_CheckEmptyString (char *s) +void +PR_CheckEmptyString (char *s) { if (s[0] <= ' ') PR_RunError ("Bad string"); } -void PF_precache_file (void) -{ // precache_file is only used to copy files with qcc, it does nothing - G_INT(OFS_RETURN) = G_INT(OFS_PARM0); +void +PF_precache_file (void) +{ // precache_file is only used to copy + // files with qcc, it does nothing + G_INT (OFS_RETURN) = G_INT (OFS_PARM0); } -void PF_precache_sound (void) +void +PF_precache_sound (void) { - char *s; - int i; - + char *s; + int i; + if (sv.state != ss_loading) - PR_RunError ("PF_Precache_*: Precache can only be done in spawn functions"); - - s = G_STRING(OFS_PARM0); - G_INT(OFS_RETURN) = G_INT(OFS_PARM0); + PR_RunError + ("PF_Precache_*: Precache can only be done in spawn functions"); + + s = G_STRING (OFS_PARM0); + G_INT (OFS_RETURN) = G_INT (OFS_PARM0); PR_CheckEmptyString (s); - - for (i=0 ; iself); - yaw = G_FLOAT(OFS_PARM0); - dist = G_FLOAT(OFS_PARM1); - - if ( !( (int)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) - { - G_FLOAT(OFS_RETURN) = 0; + edict_t *ent; + float yaw, dist; + vec3_t move; + dfunction_t *oldf; + int oldself; + + ent = PROG_TO_EDICT (pr_global_struct->self); + yaw = G_FLOAT (OFS_PARM0); + dist = G_FLOAT (OFS_PARM1); + + if (!((int) ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) { + G_FLOAT (OFS_RETURN) = 0; return; } - yaw = yaw*M_PI*2 / 360; - - move[0] = cos(yaw)*dist; - move[1] = sin(yaw)*dist; + yaw = yaw * M_PI * 2 / 360; + + move[0] = cos (yaw) * dist; + move[1] = sin (yaw) * dist; move[2] = 0; // save program state, because SV_movestep may call other progs oldf = pr_xfunction; oldself = pr_global_struct->self; - - G_FLOAT(OFS_RETURN) = SV_movestep(ent, move, true); - - + + G_FLOAT (OFS_RETURN) = SV_movestep (ent, move, true); + + // restore program state pr_xfunction = oldf; pr_global_struct->self = oldself; @@ -1071,28 +1098,28 @@ PF_droptofloor void() droptofloor =============== */ -void PF_droptofloor (void) +void +PF_droptofloor (void) { - edict_t *ent; - vec3_t end; - trace_t trace; - - ent = PROG_TO_EDICT(pr_global_struct->self); + edict_t *ent; + vec3_t end; + trace_t trace; + + ent = PROG_TO_EDICT (pr_global_struct->self); VectorCopy (ent->v.origin, end); end[2] -= 256; - + trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.fraction == 1 || trace.allsolid) - G_FLOAT(OFS_RETURN) = 0; - else - { + G_FLOAT (OFS_RETURN) = 0; + else { VectorCopy (trace.endpos, ent->v.origin); SV_LinkEdict (ent, false); - ent->v.flags = (int)ent->v.flags | FL_ONGROUND; - ent->v.groundentity = EDICT_TO_PROG(trace.ent); - G_FLOAT(OFS_RETURN) = 1; + ent->v.flags = (int) ent->v.flags | FL_ONGROUND; + ent->v.groundentity = EDICT_TO_PROG (trace.ent); + G_FLOAT (OFS_RETURN) = 1; } } @@ -1103,48 +1130,55 @@ PF_lightstyle void(float style, string value) lightstyle =============== */ -void PF_lightstyle (void) +void +PF_lightstyle (void) { - int style; - char *val; - client_t *client; - int j; - - style = G_FLOAT(OFS_PARM0); - val = G_STRING(OFS_PARM1); + int style; + char *val; + client_t *client; + int j; + + style = G_FLOAT (OFS_PARM0); + val = G_STRING (OFS_PARM1); // change the string in sv sv.lightstyles[style] = val; - + // send message to all clients on this server if (sv.state != ss_active) return; - - for (j=0, client = svs.clients ; jstate == cs_spawned ) - { - ClientReliableWrite_Begin (client, svc_lightstyle, strlen(val)+3); + + for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) + if (client->state == cs_spawned) { + ClientReliableWrite_Begin (client, svc_lightstyle, + strlen (val) + 3); ClientReliableWrite_Char (client, style); ClientReliableWrite_String (client, val); } } -void PF_rint (void) +void +PF_rint (void) { - float f; - f = G_FLOAT(OFS_PARM0); + float f; + + f = G_FLOAT (OFS_PARM0); if (f > 0) - G_FLOAT(OFS_RETURN) = (int)(f + 0.5); + G_FLOAT (OFS_RETURN) = (int) (f + 0.5); else - G_FLOAT(OFS_RETURN) = (int)(f - 0.5); + G_FLOAT (OFS_RETURN) = (int) (f - 0.5); } -void PF_floor (void) + +void +PF_floor (void) { - G_FLOAT(OFS_RETURN) = floor(G_FLOAT(OFS_PARM0)); + G_FLOAT (OFS_RETURN) = floor (G_FLOAT (OFS_PARM0)); } -void PF_ceil (void) + +void +PF_ceil (void) { - G_FLOAT(OFS_RETURN) = ceil(G_FLOAT(OFS_PARM0)); + G_FLOAT (OFS_RETURN) = ceil (G_FLOAT (OFS_PARM0)); } @@ -1153,13 +1187,14 @@ void PF_ceil (void) PF_checkbottom ============= */ -void PF_checkbottom (void) +void +PF_checkbottom (void) { - edict_t *ent; - - ent = G_EDICT(OFS_PARM0); + edict_t *ent; - G_FLOAT(OFS_RETURN) = SV_CheckBottom (ent); + ent = G_EDICT (OFS_PARM0); + + G_FLOAT (OFS_RETURN) = SV_CheckBottom (ent); } /* @@ -1167,13 +1202,14 @@ void PF_checkbottom (void) PF_pointcontents ============= */ -void PF_pointcontents (void) +void +PF_pointcontents (void) { - float *v; - - v = G_VECTOR(OFS_PARM0); + float *v; - G_FLOAT(OFS_RETURN) = SV_PointContents (v); + v = G_VECTOR (OFS_PARM0); + + G_FLOAT (OFS_RETURN) = SV_PointContents (v); } /* @@ -1183,24 +1219,22 @@ PF_nextent entity nextent(entity) ============= */ -void PF_nextent (void) +void +PF_nextent (void) { - int i; - edict_t *ent; - - i = G_EDICTNUM(OFS_PARM0); - while (1) - { + int i; + edict_t *ent; + + i = G_EDICTNUM (OFS_PARM0); + while (1) { i++; - if (i == sv.num_edicts) - { - RETURN_EDICT(sv.edicts); + if (i == sv.num_edicts) { + RETURN_EDICT (sv.edicts); return; } - ent = EDICT_NUM(i); - if (!ent->free) - { - RETURN_EDICT(ent); + ent = EDICT_NUM (i); + if (!ent->free) { + RETURN_EDICT (ent); return; } } @@ -1214,89 +1248,82 @@ Pick a vector for the player to shoot along vector aim(entity, missilespeed) ============= */ -cvar_t *sv_aim; -void PF_aim (void) +cvar_t *sv_aim; +void +PF_aim (void) { - edict_t *ent, *check, *bestent; - vec3_t start, dir, end, bestdir; - int i, j; - trace_t tr; - float dist, bestdist; - float speed; - char *noaim; + edict_t *ent, *check, *bestent; + vec3_t start, dir, end, bestdir; + int i, j; + trace_t tr; + float dist, bestdist; + float speed; + char *noaim; - ent = G_EDICT(OFS_PARM0); - speed = G_FLOAT(OFS_PARM1); + ent = G_EDICT (OFS_PARM0); + speed = G_FLOAT (OFS_PARM1); VectorCopy (ent->v.origin, start); start[2] += 20; // noaim option - i = NUM_FOR_EDICT(ent); - if (i>0 && i 0) - { - VectorCopy (pr_global_struct->v_forward, G_VECTOR(OFS_RETURN)); + i = NUM_FOR_EDICT (ent); + if (i > 0 && i < MAX_CLIENTS) { + noaim = Info_ValueForKey (svs.clients[i - 1].userinfo, "noaim"); + if (atoi (noaim) > 0) { + VectorCopy (pr_global_struct->v_forward, G_VECTOR (OFS_RETURN)); return; } } - // try sending a trace straight VectorCopy (pr_global_struct->v_forward, dir); VectorMA (start, 2048, dir, end); tr = SV_Move (start, vec3_origin, vec3_origin, end, false, ent); if (tr.ent && tr.ent->v.takedamage == DAMAGE_AIM - && (!teamplay->int_val || ent->v.team <=0 || ent->v.team != tr.ent->v.team) ) - { - VectorCopy (pr_global_struct->v_forward, G_VECTOR(OFS_RETURN)); + && (!teamplay->int_val || ent->v.team <= 0 + || ent->v.team != tr.ent->v.team)) { + VectorCopy (pr_global_struct->v_forward, G_VECTOR (OFS_RETURN)); return; } - // try all possible entities VectorCopy (dir, bestdir); bestdist = sv_aim->value; bestent = NULL; - - check = NEXT_EDICT(sv.edicts); - for (i=1 ; iv.takedamage != DAMAGE_AIM) continue; if (check == ent) continue; - if (teamplay->int_val && ent->v.team > 0 && ent->v.team == check->v.team) - continue; // don't aim at teammate - for (j=0 ; j<3 ; j++) + if (teamplay->int_val && ent->v.team > 0 + && ent->v.team == check->v.team) continue; // don't aim at + // teammate + for (j = 0; j < 3; j++) end[j] = check->v.origin[j] - + 0.5*(check->v.mins[j] + check->v.maxs[j]); + + 0.5 * (check->v.mins[j] + check->v.maxs[j]); VectorSubtract (end, start, dir); VectorNormalize (dir); dist = DotProduct (dir, pr_global_struct->v_forward); if (dist < bestdist) - continue; // to far to turn + continue; // to far to turn tr = SV_Move (start, vec3_origin, vec3_origin, end, false, ent); - if (tr.ent == check) - { // can shoot at this one + if (tr.ent == check) { // can shoot at this one bestdist = dist; bestent = check; } } - - if (bestent) - { + + if (bestent) { VectorSubtract (bestent->v.origin, ent->v.origin, dir); dist = DotProduct (dir, pr_global_struct->v_forward); VectorScale (pr_global_struct->v_forward, dist, end); end[2] = dir[2]; VectorNormalize (end); - VectorCopy (end, G_VECTOR(OFS_RETURN)); - } - else - { - VectorCopy (bestdir, G_VECTOR(OFS_RETURN)); + VectorCopy (end, G_VECTOR (OFS_RETURN)); + } else { + VectorCopy (bestdir, G_VECTOR (OFS_RETURN)); } } @@ -1307,40 +1334,35 @@ PF_changeyaw This was a major timewaster in progs, so it was converted to C ============== */ -void PF_changeyaw (void) +void +PF_changeyaw (void) { - edict_t *ent; - float ideal, current, move, speed; - - ent = PROG_TO_EDICT(pr_global_struct->self); - current = anglemod( ent->v.angles[1] ); + edict_t *ent; + float ideal, current, move, speed; + + ent = PROG_TO_EDICT (pr_global_struct->self); + current = anglemod (ent->v.angles[1]); ideal = ent->v.ideal_yaw; speed = ent->v.yaw_speed; - + if (current == ideal) return; move = ideal - current; - if (ideal > current) - { + if (ideal > current) { if (move >= 180) move = move - 360; - } - else - { + } else { if (move <= -180) move = move + 360; } - if (move > 0) - { + if (move > 0) { if (move > speed) move = speed; - } - else - { + } else { if (move < -speed) move = -speed; } - + ent->v.angles[1] = anglemod (current + move); } @@ -1352,167 +1374,185 @@ MESSAGE WRITING =============================================================================== */ -#define MSG_BROADCAST 0 // unreliable to all -#define MSG_ONE 1 // reliable to one (msg_entity) -#define MSG_ALL 2 // reliable to all -#define MSG_INIT 3 // write to the init string -#define MSG_MULTICAST 4 // for multicast() +#define MSG_BROADCAST 0 // unreliable to all +#define MSG_ONE 1 // reliable to one (msg_entity) +#define MSG_ALL 2 // reliable to all +#define MSG_INIT 3 // write to the init string +#define MSG_MULTICAST 4 // for multicast() -sizebuf_t *WriteDest (void) +sizebuf_t * +WriteDest (void) { - int dest; + int dest; - dest = G_FLOAT(OFS_PARM0); - switch (dest) - { - case MSG_BROADCAST: - return &sv.datagram; - - case MSG_ONE: - SV_Error("Shouldn't be at MSG_ONE"); + dest = G_FLOAT (OFS_PARM0); + switch (dest) { + case MSG_BROADCAST: + return &sv.datagram; + + case MSG_ONE: + SV_Error ("Shouldn't be at MSG_ONE"); #if 0 - ent = PROG_TO_EDICT(pr_global_struct->msg_entity); - entnum = NUM_FOR_EDICT(ent); - if (entnum < 1 || entnum > MAX_CLIENTS) - PR_RunError ("WriteDest: not a client"); - return &svs.clients[entnum-1].netchan.message; + ent = PROG_TO_EDICT (pr_global_struct->msg_entity); + entnum = NUM_FOR_EDICT (ent); + if (entnum < 1 || entnum > MAX_CLIENTS) + PR_RunError ("WriteDest: not a client"); + return &svs.clients[entnum - 1].netchan.message; #endif - - case MSG_ALL: - return &sv.reliable_datagram; - - case MSG_INIT: - if (sv.state != ss_loading) - PR_RunError ("PF_Write_*: MSG_INIT can only be written in spawn functions"); - return &sv.signon; - case MSG_MULTICAST: - return &sv.multicast; + case MSG_ALL: + return &sv.reliable_datagram; - default: - PR_RunError ("WriteDest: bad destination"); - break; + case MSG_INIT: + if (sv.state != ss_loading) + PR_RunError + ("PF_Write_*: MSG_INIT can only be written in spawn functions"); + return &sv.signon; + + case MSG_MULTICAST: + return &sv.multicast; + + default: + PR_RunError ("WriteDest: bad destination"); + break; } - + return NULL; } -static client_t *Write_GetClient(void) +static client_t * +Write_GetClient (void) { - int entnum; - edict_t *ent; + int entnum; + edict_t *ent; - ent = PROG_TO_EDICT(pr_global_struct->msg_entity); - entnum = NUM_FOR_EDICT(ent); + ent = PROG_TO_EDICT (pr_global_struct->msg_entity); + entnum = NUM_FOR_EDICT (ent); if (entnum < 1 || entnum > MAX_CLIENTS) PR_RunError ("WriteDest: not a client"); - return &svs.clients[entnum-1]; + return &svs.clients[entnum - 1]; } -void PF_WriteByte (void) +void +PF_WriteByte (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 1); - ClientReliableWrite_Byte(cl, G_FLOAT(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 1); + ClientReliableWrite_Byte (cl, G_FLOAT (OFS_PARM1)); } else - MSG_WriteByte (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteByte (WriteDest (), G_FLOAT (OFS_PARM1)); } -void PF_WriteChar (void) +void +PF_WriteChar (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 1); - ClientReliableWrite_Char(cl, G_FLOAT(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 1); + ClientReliableWrite_Char (cl, G_FLOAT (OFS_PARM1)); } else - MSG_WriteChar (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteChar (WriteDest (), G_FLOAT (OFS_PARM1)); } -void PF_WriteShort (void) +void +PF_WriteShort (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 2); - ClientReliableWrite_Short(cl, G_FLOAT(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 2); + ClientReliableWrite_Short (cl, G_FLOAT (OFS_PARM1)); } else - MSG_WriteShort (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteShort (WriteDest (), G_FLOAT (OFS_PARM1)); } -void PF_WriteLong (void) +void +PF_WriteLong (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 4); - ClientReliableWrite_Long(cl, G_FLOAT(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 4); + ClientReliableWrite_Long (cl, G_FLOAT (OFS_PARM1)); } else - MSG_WriteLong (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteLong (WriteDest (), G_FLOAT (OFS_PARM1)); } -void PF_WriteAngle (void) +void +PF_WriteAngle (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 1); - ClientReliableWrite_Angle(cl, G_FLOAT(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 1); + ClientReliableWrite_Angle (cl, G_FLOAT (OFS_PARM1)); } else - MSG_WriteAngle (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteAngle (WriteDest (), G_FLOAT (OFS_PARM1)); } -void PF_WriteCoord (void) +void +PF_WriteCoord (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 2); - ClientReliableWrite_Coord(cl, G_FLOAT(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 2); + ClientReliableWrite_Coord (cl, G_FLOAT (OFS_PARM1)); } else - MSG_WriteCoord (WriteDest(), G_FLOAT(OFS_PARM1)); + MSG_WriteCoord (WriteDest (), G_FLOAT (OFS_PARM1)); } -void PF_WriteString (void) +void +PF_WriteString (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 1+strlen(G_STRING(OFS_PARM1))); - ClientReliableWrite_String(cl, G_STRING(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 1 + strlen (G_STRING (OFS_PARM1))); + ClientReliableWrite_String (cl, G_STRING (OFS_PARM1)); } else - MSG_WriteString (WriteDest(), G_STRING(OFS_PARM1)); + MSG_WriteString (WriteDest (), G_STRING (OFS_PARM1)); } -void PF_WriteEntity (void) +void +PF_WriteEntity (void) { - if (G_FLOAT(OFS_PARM0) == MSG_ONE) { - client_t *cl = Write_GetClient(); - ClientReliableCheckBlock(cl, 2); - ClientReliableWrite_Short(cl, G_EDICTNUM(OFS_PARM1)); + if (G_FLOAT (OFS_PARM0) == MSG_ONE) { + client_t *cl = Write_GetClient (); + + ClientReliableCheckBlock (cl, 2); + ClientReliableWrite_Short (cl, G_EDICTNUM (OFS_PARM1)); } else - MSG_WriteShort (WriteDest(), G_EDICTNUM(OFS_PARM1)); + MSG_WriteShort (WriteDest (), G_EDICTNUM (OFS_PARM1)); } //============================================================================= -int SV_ModelIndex (char *name); +int SV_ModelIndex (char *name); -void PF_makestatic (void) +void +PF_makestatic (void) { - edict_t *ent; - int i; - - ent = G_EDICT(OFS_PARM0); + edict_t *ent; + int i; - MSG_WriteByte (&sv.signon,svc_spawnstatic); + ent = G_EDICT (OFS_PARM0); - MSG_WriteByte (&sv.signon, SV_ModelIndex(PR_GetString(ent->v.model))); + MSG_WriteByte (&sv.signon, svc_spawnstatic); + + MSG_WriteByte (&sv.signon, SV_ModelIndex (PR_GetString (ent->v.model))); MSG_WriteByte (&sv.signon, ent->v.frame); MSG_WriteByte (&sv.signon, ent->v.colormap); MSG_WriteByte (&sv.signon, ent->v.skin); - for (i=0 ; i<3 ; i++) - { - MSG_WriteCoord(&sv.signon, ent->v.origin[i]); - MSG_WriteAngle(&sv.signon, ent->v.angles[i]); + for (i = 0; i < 3; i++) { + MSG_WriteCoord (&sv.signon, ent->v.origin[i]); + MSG_WriteAngle (&sv.signon, ent->v.angles[i]); } // throw the entity away now @@ -1526,21 +1566,22 @@ void PF_makestatic (void) PF_setspawnparms ============== */ -void PF_setspawnparms (void) +void +PF_setspawnparms (void) { - edict_t *ent; - int i; - client_t *client; + edict_t *ent; + int i; + client_t *client; - ent = G_EDICT(OFS_PARM0); - i = NUM_FOR_EDICT(ent); + ent = G_EDICT (OFS_PARM0); + i = NUM_FOR_EDICT (ent); if (i < 1 || i > MAX_CLIENTS) PR_RunError ("Entity is not a client"); // copy spawn parms out of the client_t - client = svs.clients + (i-1); + client = svs.clients + (i - 1); - for (i=0 ; i< NUM_SPAWN_PARMS ; i++) + for (i = 0; i < NUM_SPAWN_PARMS; i++) (&pr_global_struct->parm1)[i] = client->spawn_parms[i]; } @@ -1549,18 +1590,19 @@ void PF_setspawnparms (void) PF_changelevel ============== */ -void PF_changelevel (void) +void +PF_changelevel (void) { - char *s; - static int last_spawncount; + char *s; + static int last_spawncount; // make sure we don't issue two changelevels if (svs.spawncount == last_spawncount) return; last_spawncount = svs.spawncount; - - s = G_STRING(OFS_PARM0); - Cbuf_AddText (va("map %s\n",s)); + + s = G_STRING (OFS_PARM0); + Cbuf_AddText (va ("map %s\n", s)); } @@ -1571,25 +1613,25 @@ PF_logfrag logfrag (killer, killee) ============== */ -void PF_logfrag (void) +void +PF_logfrag (void) { - edict_t *ent1, *ent2; - int e1, e2; - char *s; + edict_t *ent1, *ent2; + int e1, e2; + char *s; - ent1 = G_EDICT(OFS_PARM0); - ent2 = G_EDICT(OFS_PARM1); + ent1 = G_EDICT (OFS_PARM0); + ent2 = G_EDICT (OFS_PARM1); - e1 = NUM_FOR_EDICT(ent1); - e2 = NUM_FOR_EDICT(ent2); - - if (e1 < 1 || e1 > MAX_CLIENTS - || e2 < 1 || e2 > MAX_CLIENTS) + e1 = NUM_FOR_EDICT (ent1); + e2 = NUM_FOR_EDICT (ent2); + + if (e1 < 1 || e1 > MAX_CLIENTS || e2 < 1 || e2 > MAX_CLIENTS) return; - - s = va("\\%s\\%s\\\n",svs.clients[e1-1].name, svs.clients[e2-1].name); - SZ_Print (&svs.log[svs.logsequence&1], s); + s = va ("\\%s\\%s\\\n", svs.clients[e1 - 1].name, svs.clients[e2 - 1].name); + + SZ_Print (&svs.log[svs.logsequence & 1], s); if (sv_fraglogfile) { Qprintf (sv_fraglogfile, s); Qflush (sv_fraglogfile); @@ -1604,35 +1646,39 @@ PF_infokey string(entity e, string key) infokey ============== */ -void PF_infokey (void) +void +PF_infokey (void) { - edict_t *e; - int e1; - char *value; - char *key; - static char ov[256]; + edict_t *e; + int e1; + char *value; + char *key; + static char ov[256]; - e = G_EDICT(OFS_PARM0); - e1 = NUM_FOR_EDICT(e); - key = G_STRING(OFS_PARM1); + e = G_EDICT (OFS_PARM0); + e1 = NUM_FOR_EDICT (e); + key = G_STRING (OFS_PARM1); if (e1 == 0) { - if ((value = Info_ValueForKey (svs.info, key)) == NULL || - !*value) - value = Info_ValueForKey(localinfo, key); + if ((value = Info_ValueForKey (svs.info, key)) == NULL || !*value) + value = Info_ValueForKey (localinfo, key); } else if (e1 <= MAX_CLIENTS) { - if (!strcmp(key, "ip")) - value = strcpy(ov, NET_BaseAdrToString (svs.clients[e1-1].netchan.remote_address)); - else if (!strcmp(key, "ping")) { - int ping = SV_CalcPing (&svs.clients[e1-1]); - snprintf(ov, sizeof(ov), "%d", ping); + if (!strcmp (key, "ip")) + value = + strcpy (ov, + NET_BaseAdrToString (svs.clients[e1 - 1].netchan. + remote_address)); + else if (!strcmp (key, "ping")) { + int ping = SV_CalcPing (&svs.clients[e1 - 1]); + + snprintf (ov, sizeof (ov), "%d", ping); value = ov; } else - value = Info_ValueForKey (svs.clients[e1-1].userinfo, key); + value = Info_ValueForKey (svs.clients[e1 - 1].userinfo, key); } else value = ""; - RETURN_STRING(value); + RETURN_STRING (value); } /* @@ -1642,13 +1688,14 @@ PF_stof float(string s) stof ============== */ -void PF_stof (void) +void +PF_stof (void) { - char *s; + char *s; - s = G_STRING(OFS_PARM0); + s = G_STRING (OFS_PARM0); - G_FLOAT(OFS_RETURN) = atof(s); + G_FLOAT (OFS_RETURN) = atof (s); } @@ -1659,122 +1706,153 @@ PF_multicast void(vector where, float set) multicast ============== */ -void PF_multicast (void) +void +PF_multicast (void) { - float *o; - int to; + float *o; + int to; - o = G_VECTOR(OFS_PARM0); - to = G_FLOAT(OFS_PARM1); + o = G_VECTOR (OFS_PARM0); + to = G_FLOAT (OFS_PARM1); SV_Multicast (o, to); } -void PF_Fixme (void) +void +PF_Fixme (void) { PR_RunError ("unimplemented bulitin"); } -builtin_t pr_builtin[] = -{ +builtin_t pr_builtin[] = { PF_Fixme, -PF_makevectors, // void(entity e) makevectors = #1; -PF_setorigin, // void(entity e, vector o) setorigin = #2; -PF_setmodel, // void(entity e, string m) setmodel = #3; -PF_setsize, // void(entity e, vector min, vector max) setsize = #4; -PF_Fixme, // void(entity e, vector min, vector max) setabssize = #5; -PF_break, // void() break = #6; -PF_random, // float() random = #7; -PF_sound, // void(entity e, float chan, string samp) sound = #8; -PF_normalize, // vector(vector v) normalize = #9; -PF_error, // void(string e) error = #10; -PF_objerror, // void(string e) objerror = #11; -PF_vlen, // float(vector v) vlen = #12; -PF_vectoyaw, // float(vector v) vectoyaw = #13; -PF_Spawn, // entity() spawn = #14; -PF_Remove, // void(entity e) remove = #15; -PF_traceline, // float(vector v1, vector v2, float tryents) traceline = #16; -PF_checkclient, // entity() clientlist = #17; -PF_Find, // entity(entity start, .string fld, string match) find = #18; -PF_precache_sound, // void(string s) precache_sound = #19; -PF_precache_model, // void(string s) precache_model = #20; -PF_stuffcmd, // void(entity client, string s)stuffcmd = #21; -PF_findradius, // entity(vector org, float rad) findradius = #22; -PF_bprint, // void(string s) bprint = #23; -PF_sprint, // void(entity client, string s) sprint = #24; -PF_dprint, // void(string s) dprint = #25; -PF_ftos, // void(string s) ftos = #26; -PF_vtos, // void(string s) vtos = #27; -PF_coredump, -PF_traceon, -PF_traceoff, -PF_eprint, // void(entity e) debug print an entire entity -PF_walkmove, // float(float yaw, float dist) walkmove -PF_Fixme, // float(float yaw, float dist) walkmove -PF_droptofloor, -PF_lightstyle, -PF_rint, -PF_floor, -PF_ceil, -PF_Fixme, -PF_checkbottom, -PF_pointcontents, -PF_Fixme, -PF_fabs, -PF_aim, -PF_cvar, -PF_localcmd, -PF_nextent, -PF_Fixme, -PF_changeyaw, -PF_Fixme, -PF_vectoangles, + PF_makevectors, // void(entity e) makevectors + // = #1; + PF_setorigin, // void(entity e, vector o) setorigin + // = #2; + PF_setmodel, // void(entity e, string m) setmodel + // = #3; + PF_setsize, // void(entity e, vector min, vector + // max) setsize = #4; + PF_Fixme, // void(entity e, vector min, vector + // max) setabssize = #5; + PF_break, // void() break = + // #6; + PF_random, // float() random + // = #7; + PF_sound, // void(entity e, float chan, string + // samp) sound = #8; + PF_normalize, // vector(vector v) normalize + // = #9; + PF_error, // void(string e) error = + // #10; + PF_objerror, // void(string e) objerror + // = #11; + PF_vlen, // float(vector v) vlen = + // #12; + PF_vectoyaw, // float(vector v) vectoyaw = + // #13; + PF_Spawn, // entity() spawn + // = #14; + PF_Remove, // void(entity e) remove + // = #15; + PF_traceline, // float(vector v1, vector v2, float + // tryents) traceline = #16; + PF_checkclient, // entity() clientlist + // = #17; + PF_Find, // entity(entity start, .string fld, + // string match) find = #18; + PF_precache_sound, // void(string s) precache_sound + // = #19; + PF_precache_model, // void(string s) precache_model + // = #20; + PF_stuffcmd, // void(entity client, string + // s)stuffcmd = #21; + PF_findradius, // entity(vector org, float rad) + // findradius = #22; + PF_bprint, // void(string s) bprint + // = #23; + PF_sprint, // void(entity client, string s) + // sprint = #24; + PF_dprint, // void(string s) dprint + // = #25; + PF_ftos, // void(string s) ftos = + // #26; + PF_vtos, // void(string s) vtos = + // #27; + PF_coredump, + PF_traceon, + PF_traceoff, + PF_eprint, // void(entity e) debug print an + // entire entity + PF_walkmove, // float(float yaw, float dist) + // walkmove + PF_Fixme, // float(float yaw, float dist) + // walkmove + PF_droptofloor, + PF_lightstyle, + PF_rint, + PF_floor, + PF_ceil, + PF_Fixme, + PF_checkbottom, + PF_pointcontents, + PF_Fixme, + PF_fabs, + PF_aim, + PF_cvar, + PF_localcmd, + PF_nextent, + PF_Fixme, + PF_changeyaw, + PF_Fixme, + PF_vectoangles, -PF_WriteByte, -PF_WriteChar, -PF_WriteShort, -PF_WriteLong, -PF_WriteCoord, -PF_WriteAngle, -PF_WriteString, -PF_WriteEntity, + PF_WriteByte, + PF_WriteChar, + PF_WriteShort, + PF_WriteLong, + PF_WriteCoord, + PF_WriteAngle, + PF_WriteString, + PF_WriteEntity, -PF_Fixme, -PF_Fixme, -PF_Fixme, -PF_Fixme, -PF_Fixme, -PF_Fixme, -PF_Fixme, + PF_Fixme, + PF_Fixme, + PF_Fixme, + PF_Fixme, + PF_Fixme, + PF_Fixme, + PF_Fixme, -SV_MoveToGoal, -PF_precache_file, -PF_makestatic, + SV_MoveToGoal, + PF_precache_file, + PF_makestatic, -PF_changelevel, -PF_Fixme, + PF_changelevel, + PF_Fixme, -PF_cvar_set, -PF_centerprint, + PF_cvar_set, + PF_centerprint, -PF_ambientsound, + PF_ambientsound, -PF_precache_model, -PF_precache_sound, // precache_sound2 is different only for qcc -PF_precache_file, + PF_precache_model, + PF_precache_sound, // precache_sound2 is different only + // for qcc + PF_precache_file, -PF_setspawnparms, + PF_setspawnparms, -PF_logfrag, + PF_logfrag, -PF_infokey, -PF_stof, -PF_multicast + PF_infokey, + PF_stof, + PF_multicast }; -builtin_t *pr_builtins = pr_builtin; -int pr_numbuiltins = sizeof(pr_builtin)/sizeof(pr_builtin[0]); - +builtin_t *pr_builtins = pr_builtin; +int pr_numbuiltins = sizeof (pr_builtin) / sizeof (pr_builtin[0]); diff --git a/source/pr_edict.c b/source/pr_edict.c index d0ba594..5b2cbc7 100644 --- a/source/pr_edict.c +++ b/source/pr_edict.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "pr_comp.h" #include "progs.h" @@ -48,43 +48,47 @@ #include #endif -cvar_t *r_skyname; -cvar_t *pr_boundscheck; +cvar_t *r_skyname; +cvar_t *pr_boundscheck; -void SV_Error (char *error, ...); -void FindEdictFieldOffsets(); +void SV_Error (char *error, ...); +void FindEdictFieldOffsets (); -dprograms_t *progs; -dfunction_t *pr_functions; -char *pr_strings; -ddef_t *pr_fielddefs; -ddef_t *pr_globaldefs; -dstatement_t *pr_statements; -globalvars_t *pr_global_struct; -float *pr_globals; // same as pr_global_struct -int pr_edict_size; // in bytes -int pr_edictareasize; // LordHavoc: in bytes +dprograms_t *progs; +dfunction_t *pr_functions; +char *pr_strings; +ddef_t *pr_fielddefs; +ddef_t *pr_globaldefs; +dstatement_t *pr_statements; +globalvars_t *pr_global_struct; +float *pr_globals; // same as pr_global_struct +int pr_edict_size; // in bytes +int pr_edictareasize; // LordHavoc: in bytes -int type_size[8] = {1,sizeof(void *)/4,1,3,1,1,sizeof(void *)/4,sizeof(void *)/4}; +int type_size[8] = + { 1, sizeof (void *) / 4, 1, 3, 1, 1, sizeof (void *) / 4, + sizeof (void *) / 4 }; -ddef_t *ED_FieldAtOfs (int ofs); -qboolean ED_ParseEpair (void *base, ddef_t *key, char *s); +ddef_t *ED_FieldAtOfs (int ofs); +qboolean ED_ParseEpair (void *base, ddef_t *key, char *s); #define MAX_FIELD_LEN 64 #define GEFV_CACHESIZE 2 typedef struct { - ddef_t *pcache; - char field[MAX_FIELD_LEN]; + ddef_t *pcache; + char field[MAX_FIELD_LEN]; } gefv_cache; -static gefv_cache gefvCache[GEFV_CACHESIZE] = {{NULL, ""}, {NULL, ""}}; +static gefv_cache gefvCache[GEFV_CACHESIZE] = { {NULL, ""}, {NULL, ""} }; -func_t EndFrame; // 2000-01-02 EndFrame function by Maddes/FrikaC +func_t EndFrame; // 2000-01-02 EndFrame function by -func_t SpectatorConnect; -func_t SpectatorThink; -func_t SpectatorDisconnect; + // Maddes/FrikaC + +func_t SpectatorConnect; +func_t SpectatorThink; +func_t SpectatorDisconnect; /* @@ -94,7 +98,8 @@ ED_ClearEdict Sets everything to NULL ================= */ -void ED_ClearEdict (edict_t *e) +void +ED_ClearEdict (edict_t *e) { memset (&e->v, 0, progs->entityfields * 4); e->free = false; @@ -111,33 +116,30 @@ instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ -edict_t *ED_Alloc (void) +edict_t * +ED_Alloc (void) { - int i; - edict_t *e; + int i; + edict_t *e; - for ( i=MAX_CLIENTS+1 ; ifree && ( e->freetime < 2 || sv.time - e->freetime > 0.5 ) ) - { + if (e->free && (e->freetime < 2 || sv.time - e->freetime > 0.5)) { ED_ClearEdict (e); return e; } } - - if (i == MAX_EDICTS) - { + + if (i == MAX_EDICTS) { Con_Printf ("WARNING: ED_Alloc: no free edicts\n"); - i--; // step on whatever is the last edict - e = EDICT_NUM(i); - SV_UnlinkEdict(e); - } - else + i--; // step on whatever is the last edict + e = EDICT_NUM (i); + SV_UnlinkEdict (e); + } else sv.num_edicts++; - e = EDICT_NUM(i); + e = EDICT_NUM (i); ED_ClearEdict (e); return e; @@ -151,9 +153,10 @@ Marks the edict as free FIXME: walk all entities and NULL out references to this entity ================= */ -void ED_Free (edict_t *ed) +void +ED_Free (edict_t *ed) { - SV_UnlinkEdict (ed); // unlink from world bsp + SV_UnlinkEdict (ed); // unlink from world bsp ed->free = true; ed->v.model = 0; @@ -166,7 +169,7 @@ void ED_Free (edict_t *ed) VectorCopy (vec3_origin, ed->v.angles); ed->v.nextthink = -1; ed->v.solid = 0; - + ed->freetime = sv.time; } @@ -177,13 +180,13 @@ void ED_Free (edict_t *ed) ED_GlobalAtOfs ============ */ -ddef_t *ED_GlobalAtOfs (int ofs) +ddef_t * +ED_GlobalAtOfs (int ofs) { - ddef_t *def; - int i; - - for (i=0 ; inumglobaldefs ; i++) - { + ddef_t *def; + int i; + + for (i = 0; i < progs->numglobaldefs; i++) { def = &pr_globaldefs[i]; if (def->ofs == ofs) return def; @@ -196,13 +199,13 @@ ddef_t *ED_GlobalAtOfs (int ofs) ED_FieldAtOfs ============ */ -ddef_t *ED_FieldAtOfs (int ofs) +ddef_t * +ED_FieldAtOfs (int ofs) { - ddef_t *def; - int i; - - for (i=0 ; inumfielddefs ; i++) - { + ddef_t *def; + int i; + + for (i = 0; i < progs->numfielddefs; i++) { def = &pr_fielddefs[i]; if (def->ofs == ofs) return def; @@ -215,15 +218,15 @@ ddef_t *ED_FieldAtOfs (int ofs) ED_FindField ============ */ -ddef_t *ED_FindField (char *name) +ddef_t * +ED_FindField (char *name) { - ddef_t *def; - int i; - - for (i=0 ; inumfielddefs ; i++) - { + ddef_t *def; + int i; + + for (i = 0; i < progs->numfielddefs; i++) { def = &pr_fielddefs[i]; - if (!strcmp(PR_GetString(def->s_name),name) ) + if (!strcmp (PR_GetString (def->s_name), name)) return def; } return NULL; @@ -235,15 +238,15 @@ ddef_t *ED_FindField (char *name) ED_FindGlobal ============ */ -ddef_t *ED_FindGlobal (char *name) +ddef_t * +ED_FindGlobal (char *name) { - ddef_t *def; - int i; - - for (i=0 ; inumglobaldefs ; i++) - { + ddef_t *def; + int i; + + for (i = 0; i < progs->numglobaldefs; i++) { def = &pr_globaldefs[i]; - if (!strcmp(PR_GetString(def->s_name),name) ) + if (!strcmp (PR_GetString (def->s_name), name)) return def; } return NULL; @@ -255,30 +258,29 @@ ddef_t *ED_FindGlobal (char *name) ED_FindFunction ============ */ -dfunction_t *ED_FindFunction (char *name) +dfunction_t * +ED_FindFunction (char *name) { - dfunction_t *func; - int i; - - for (i=0 ; inumfunctions ; i++) - { + dfunction_t *func; + int i; + + for (i = 0; i < progs->numfunctions; i++) { func = &pr_functions[i]; - if (!strcmp(PR_GetString(func->s_name),name) ) + if (!strcmp (PR_GetString (func->s_name), name)) return func; } return NULL; } -eval_t *GetEdictFieldValue(edict_t *ed, char *field) +eval_t * +GetEdictFieldValue (edict_t *ed, char *field) { - ddef_t *def = NULL; - int i; - static int rep = 0; + ddef_t *def = NULL; + int i; + static int rep = 0; - for (i=0 ; iv + def->ofs*4); + return (eval_t *) ((char *) &ed->v + def->ofs * 4); } /* @@ -307,47 +308,49 @@ PR_ValueString Returns a string describing *data in a type specific manner ============= */ -char *PR_ValueString (etype_t type, eval_t *val) +char * +PR_ValueString (etype_t type, eval_t *val) { - static char line[256]; - ddef_t *def; - dfunction_t *f; - + static char line[256]; + ddef_t *def; + dfunction_t *f; + type &= ~DEF_SAVEGLOBAL; - switch (type) - { - case ev_string: - snprintf (line, sizeof(line), "%s", PR_GetString(val->string)); - break; - case ev_entity: - snprintf (line, sizeof(line), "entity %i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict)) ); - break; - case ev_function: - f = pr_functions + val->function; - snprintf (line, sizeof(line), "%s()", PR_GetString(f->s_name)); - break; - case ev_field: - def = ED_FieldAtOfs ( val->_int ); - snprintf (line, sizeof(line), ".%s", PR_GetString(def->s_name)); - break; - case ev_void: - strcpy (line, "void"); - break; - case ev_float: - snprintf (line, sizeof(line), "%5.1f", val->_float); - break; - case ev_vector: - snprintf (line, sizeof(line), "'%5.1f %5.1f %5.1f'", val->vector[0], val->vector[1], val->vector[2]); - break; - case ev_pointer: - strcpy (line, "pointer"); - break; - default: - snprintf (line, sizeof(line), "bad type %i", type); - break; + switch (type) { + case ev_string: + snprintf (line, sizeof (line), "%s", PR_GetString (val->string)); + break; + case ev_entity: + snprintf (line, sizeof (line), "entity %i", + NUM_FOR_EDICT (PROG_TO_EDICT (val->edict))); + break; + case ev_function: + f = pr_functions + val->function; + snprintf (line, sizeof (line), "%s()", PR_GetString (f->s_name)); + break; + case ev_field: + def = ED_FieldAtOfs (val->_int); + snprintf (line, sizeof (line), ".%s", PR_GetString (def->s_name)); + break; + case ev_void: + strcpy (line, "void"); + break; + case ev_float: + snprintf (line, sizeof (line), "%5.1f", val->_float); + break; + case ev_vector: + snprintf (line, sizeof (line), "'%5.1f %5.1f %5.1f'", + val->vector[0], val->vector[1], val->vector[2]); + break; + case ev_pointer: + strcpy (line, "pointer"); + break; + default: + snprintf (line, sizeof (line), "bad type %i", type); + break; } - + return line; } @@ -359,44 +362,46 @@ Returns a string describing *data in a type specific manner Easier to parse than PR_ValueString ============= */ -char *PR_UglyValueString (etype_t type, eval_t *val) +char * +PR_UglyValueString (etype_t type, eval_t *val) { - static char line[256]; - ddef_t *def; - dfunction_t *f; - + static char line[256]; + ddef_t *def; + dfunction_t *f; + type &= ~DEF_SAVEGLOBAL; - switch (type) - { - case ev_string: - snprintf (line, sizeof(line), "%s", PR_GetString(val->string)); - break; - case ev_entity: - snprintf (line, sizeof(line), "%i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); - break; - case ev_function: - f = pr_functions + val->function; - snprintf (line, sizeof(line), "%s", PR_GetString(f->s_name)); - break; - case ev_field: - def = ED_FieldAtOfs ( val->_int ); - snprintf (line, sizeof(line), "%s", PR_GetString(def->s_name)); - break; - case ev_void: - strcpy (line, "void"); - break; - case ev_float: - snprintf (line, sizeof(line), "%f", val->_float); - break; - case ev_vector: - snprintf (line, sizeof(line), "%f %f %f", val->vector[0], val->vector[1], val->vector[2]); - break; - default: - snprintf (line, sizeof(line), "bad type %i", type); - break; + switch (type) { + case ev_string: + snprintf (line, sizeof (line), "%s", PR_GetString (val->string)); + break; + case ev_entity: + snprintf (line, sizeof (line), "%i", + NUM_FOR_EDICT (PROG_TO_EDICT (val->edict))); + break; + case ev_function: + f = pr_functions + val->function; + snprintf (line, sizeof (line), "%s", PR_GetString (f->s_name)); + break; + case ev_field: + def = ED_FieldAtOfs (val->_int); + snprintf (line, sizeof (line), "%s", PR_GetString (def->s_name)); + break; + case ev_void: + strcpy (line, "void"); + break; + case ev_float: + snprintf (line, sizeof (line), "%f", val->_float); + break; + case ev_vector: + snprintf (line, sizeof (line), "%f %f %f", val->vector[0], + val->vector[1], val->vector[2]); + break; + default: + snprintf (line, sizeof (line), "bad type %i", type); + break; } - + return line; } @@ -408,49 +413,52 @@ Returns a string with a description and the contents of a global, padded to 20 field width ============ */ -char *PR_GlobalString (int ofs) +char * +PR_GlobalString (int ofs) { - char *s; - int i; - ddef_t *def; - void *val; - static char line[128]; - - val = (void *)&pr_globals[ofs]; - def = ED_GlobalAtOfs(ofs); + char *s; + int i; + ddef_t *def; + void *val; + static char line[128]; + + val = (void *) &pr_globals[ofs]; + def = ED_GlobalAtOfs (ofs); if (!def) - snprintf (line, sizeof(line), "%i(?)", ofs); - else - { + snprintf (line, sizeof (line), "%i(?)", ofs); + else { s = PR_ValueString (def->type, val); - snprintf (line, sizeof(line), "%i(%s)%s", ofs, PR_GetString(def->s_name), s); + snprintf (line, sizeof (line), "%i(%s)%s", ofs, + PR_GetString (def->s_name), s); } - - i = strlen(line); - for ( ; i<20 ; i++) - strncat (line, " ", sizeof(line) - strlen (line)); - strncat (line, " ", sizeof(line) - strlen (line)); - + + i = strlen (line); + for (; i < 20; i++) + strncat (line, " ", sizeof (line) - strlen (line)); + strncat (line, " ", sizeof (line) - strlen (line)); + return line; } -char *PR_GlobalStringNoContents (int ofs) +char * +PR_GlobalStringNoContents (int ofs) { - int i; - ddef_t *def; - static char line[128]; - - def = ED_GlobalAtOfs(ofs); + int i; + ddef_t *def; + static char line[128]; + + def = ED_GlobalAtOfs (ofs); if (!def) - snprintf (line, sizeof(line), "%i(?)", ofs); + snprintf (line, sizeof (line), "%i(?)", ofs); else - snprintf (line, sizeof(line), "%i(%s)", ofs, PR_GetString(def->s_name)); - - i = strlen(line); - for ( ; i<20 ; i++) - strncat (line, " ", sizeof(line) - strlen (line)); - strncat (line, " ", sizeof(line) - strlen (line)); - + snprintf (line, sizeof (line), "%i(%s)", ofs, + PR_GetString (def->s_name)); + + i = strlen (line); + for (; i < 20; i++) + strncat (line, " ", sizeof (line) - strlen (line)); + strncat (line, " ", sizeof (line) - strlen (line)); + return line; } @@ -462,45 +470,44 @@ ED_Print For debugging ============= */ -void ED_Print (edict_t *ed) +void +ED_Print (edict_t *ed) { - int l; - ddef_t *d; - int *v; - int i, j; - char *name; - int type; + int l; + ddef_t *d; + int *v; + int i, j; + char *name; + int type; - if (ed->free) - { + if (ed->free) { Con_Printf ("FREE\n"); return; } - - for (i=1 ; inumfielddefs ; i++) - { - d = &pr_fielddefs[i]; - name = PR_GetString(d->s_name); - if (name[strlen(name)-2] == '_') - continue; // skip _x, _y, _z vars - - v = (int *)((char *)&ed->v + d->ofs*4); - // if the value is still all 0, skip the field + for (i = 1; i < progs->numfielddefs; i++) { + d = &pr_fielddefs[i]; + name = PR_GetString (d->s_name); + if (name[strlen (name) - 2] == '_') + continue; // skip _x, _y, _z vars + + v = (int *) ((char *) &ed->v + d->ofs * 4); + + // if the value is still all 0, skip the field type = d->type & ~DEF_SAVEGLOBAL; - - for (j=0 ; jtype, (eval_t *)v)); + Con_Printf ("%s\n", PR_ValueString (d->type, (eval_t *) v)); } } @@ -511,49 +518,49 @@ ED_Write For savegames ============= */ -void ED_Write (QFile *f, edict_t *ed) +void +ED_Write (QFile *f, edict_t *ed) { - ddef_t *d; - int *v; - int i, j; - char *name; - int type; + ddef_t *d; + int *v; + int i, j; + char *name; + int type; Qprintf (f, "{\n"); - if (ed->free) - { + if (ed->free) { Qprintf (f, "}\n"); return; } - - for (i=1 ; inumfielddefs ; i++) - { - d = &pr_fielddefs[i]; - name = PR_GetString(d->s_name); - if (name[strlen(name)-2] == '_') - continue; // skip _x, _y, _z vars - - v = (int *)((char *)&ed->v + d->ofs*4); - // if the value is still all 0, skip the field + for (i = 1; i < progs->numfielddefs; i++) { + d = &pr_fielddefs[i]; + name = PR_GetString (d->s_name); + if (name[strlen (name) - 2] == '_') + continue; // skip _x, _y, _z vars + + v = (int *) ((char *) &ed->v + d->ofs * 4); + + // if the value is still all 0, skip the field type = d->type & ~DEF_SAVEGLOBAL; - for (j=0 ; jtype, (eval_t *)v)); + + Qprintf (f, "\"%s\" ", name); + Qprintf (f, "\"%s\"\n", PR_UglyValueString (d->type, (eval_t *) v)); } Qprintf (f, "}\n"); } -void ED_PrintNum (int ent) +void +ED_PrintNum (int ent) { - ED_Print (EDICT_NUM(ent)); + ED_Print (EDICT_NUM (ent)); } /* @@ -563,14 +570,14 @@ ED_PrintEdicts For debugging, prints all the entities in the current server ============= */ -void ED_PrintEdicts (void) +void +ED_PrintEdicts (void) { - int i; - + int i; + Con_Printf ("%i entities\n", sv.num_edicts); - for (i=0 ; ifree) continue; active++; @@ -641,32 +649,31 @@ FIXME: need to tag constants, doesn't really work ED_WriteGlobals ============= */ -void ED_WriteGlobals (QFile *f) +void +ED_WriteGlobals (QFile *f) { - ddef_t *def; - int i; - char *name; - int type; + ddef_t *def; + int i; + char *name; + int type; - Qprintf (f,"{\n"); - for (i=0 ; inumglobaldefs ; i++) - { + Qprintf (f, "{\n"); + for (i = 0; i < progs->numglobaldefs; i++) { def = &pr_globaldefs[i]; type = def->type; - if ( !(def->type & DEF_SAVEGLOBAL) ) + if (!(def->type & DEF_SAVEGLOBAL)) continue; type &= ~DEF_SAVEGLOBAL; - if (type != ev_string - && type != ev_float - && type != ev_entity) + if (type != ev_string && type != ev_float && type != ev_entity) continue; - name = PR_GetString(def->s_name); - Qprintf (f,"\"%s\" ", name); - Qprintf (f,"\"%s\"\n", PR_UglyValueString(type, (eval_t *)&pr_globals[def->ofs])); + name = PR_GetString (def->s_name); + Qprintf (f, "\"%s\" ", name); + Qprintf (f, "\"%s\"\n", + PR_UglyValueString (type, (eval_t *) &pr_globals[def->ofs])); } - Qprintf (f,"}\n"); + Qprintf (f, "}\n"); } /* @@ -674,14 +681,14 @@ void ED_WriteGlobals (QFile *f) ED_ParseGlobals ============= */ -void ED_ParseGlobals (char *data) +void +ED_ParseGlobals (char *data) { - char keyname[64]; - ddef_t *key; + char keyname[64]; + ddef_t *key; - while (1) - { - // parse key + while (1) { + // parse key data = COM_Parse (data); if (com_token[0] == '}') break; @@ -690,7 +697,7 @@ void ED_ParseGlobals (char *data) strcpy (keyname, com_token); - // parse value + // parse value data = COM_Parse (data); if (!data) SV_Error ("ED_ParseEntity: EOF without closing brace"); @@ -699,13 +706,12 @@ void ED_ParseGlobals (char *data) SV_Error ("ED_ParseEntity: closing brace without data"); key = ED_FindGlobal (keyname); - if (!key) - { + if (!key) { Con_Printf ("%s is not a global\n", keyname); continue; } - if (!ED_ParseEpair ((void *)pr_globals, key, com_token)) + if (!ED_ParseEpair ((void *) pr_globals, key, com_token)) SV_Error ("ED_ParseGlobals: parse error"); } } @@ -718,29 +724,27 @@ void ED_ParseGlobals (char *data) ED_NewString ============= */ -char *ED_NewString (char *string) +char * +ED_NewString (char *string) { - char *new, *new_p; - int i,l; - - l = strlen(string) + 1; + char *new, *new_p; + int i, l; + + l = strlen (string) + 1; new = Hunk_Alloc (l); new_p = new; - for (i=0 ; i< l ; i++) - { - if (string[i] == '\\' && i < l-1) - { + for (i = 0; i < l; i++) { + if (string[i] == '\\' && i < l - 1) { i++; if (string[i] == 'n') *new_p++ = '\n'; else *new_p++ = '\\'; - } - else + } else *new_p++ = string[i]; } - + return new; } @@ -753,67 +757,64 @@ Can parse either fields or globals returns false if error ============= */ -qboolean ED_ParseEpair (void *base, ddef_t *key, char *s) +qboolean +ED_ParseEpair (void *base, ddef_t *key, char *s) { - int i; - char string[128]; - ddef_t *def; - char *v, *w; - void *d; - dfunction_t *func; - - d = (void *)((int *)base + key->ofs); - - switch (key->type & ~DEF_SAVEGLOBAL) - { - case ev_string: - *(string_t *)d = PR_SetString(ED_NewString (s)); - break; - - case ev_float: - *(float *)d = atof (s); - break; - - case ev_vector: - strcpy (string, s); - v = string; - w = string; - for (i=0 ; i<3 ; i++) - { - while (*v && *v != ' ') - v++; - *v = 0; - ((float *)d)[i] = atof (w); - w = v = v+1; - } - break; - - case ev_entity: - *(int *)d = EDICT_TO_PROG(EDICT_NUM(atoi (s))); - break; - - case ev_field: - def = ED_FindField (s); - if (!def) - { - Con_Printf ("Can't find field %s\n", s); - return false; - } - *(int *)d = G_INT(def->ofs); - break; - - case ev_function: - func = ED_FindFunction (s); - if (!func) - { - Con_Printf ("Can't find function %s\n", s); - return false; - } - *(func_t *)d = func - pr_functions; - break; - - default: - break; + int i; + char string[128]; + ddef_t *def; + char *v, *w; + void *d; + dfunction_t *func; + + d = (void *) ((int *) base + key->ofs); + + switch (key->type & ~DEF_SAVEGLOBAL) { + case ev_string: + *(string_t *) d = PR_SetString (ED_NewString (s)); + break; + + case ev_float: + *(float *) d = atof (s); + break; + + case ev_vector: + strcpy (string, s); + v = string; + w = string; + for (i = 0; i < 3; i++) { + while (*v && *v != ' ') + v++; + *v = 0; + ((float *) d)[i] = atof (w); + w = v = v + 1; + } + break; + + case ev_entity: + *(int *) d = EDICT_TO_PROG (EDICT_NUM (atoi (s))); + break; + + case ev_field: + def = ED_FindField (s); + if (!def) { + Con_Printf ("Can't find field %s\n", s); + return false; + } + *(int *) d = G_INT (def->ofs); + break; + + case ev_function: + func = ED_FindFunction (s); + if (!func) { + Con_Printf ("Can't find function %s\n", s); + return false; + } + *(func_t *) d = func - pr_functions; + break; + + default: + break; } return true; } @@ -827,45 +828,44 @@ ed should be a properly initialized empty edict. Used for initial level load and for savegames. ==================== */ -char *ED_ParseEdict (char *data, edict_t *ent) +char * +ED_ParseEdict (char *data, edict_t *ent) { - ddef_t *key; - qboolean anglehack; - qboolean init; - char keyname[256]; + ddef_t *key; + qboolean anglehack; + qboolean init; + char keyname[256]; init = false; // clear it - if (ent != sv.edicts) // hack + if (ent != sv.edicts) // hack memset (&ent->v, 0, progs->entityfields * 4); // go through all the dictionary pairs - while (1) - { - // parse key + while (1) { + // parse key data = COM_Parse (data); if (com_token[0] == '}') break; if (!data) SV_Error ("ED_ParseEntity: EOF without closing brace"); - + // anglehack is to allow QuakeEd to write single scalar angles // and allow them to be turned into vectors. (FIXME...) - if (!strcmp(com_token, "angle")) - { + if (!strcmp (com_token, "angle")) { strcpy (com_token, "angles"); anglehack = true; } else anglehack = false; // FIXME: change light to _light to get rid of this hack - if (!strcmp(com_token, "light")) + if (!strcmp (com_token, "light")) strcpy (com_token, "light_lev"); // hack for single light def strcpy (keyname, com_token); - - // parse value + + // parse value data = COM_Parse (data); if (!data) SV_Error ("ED_ParseEntity: EOF without closing brace"); @@ -873,7 +873,7 @@ char *ED_ParseEdict (char *data, edict_t *ent) if (com_token[0] == '}') SV_Error ("ED_ParseEntity: closing brace without data"); - init = true; + init = true; // keynames with a leading underscore are used for utility comments, // and are immediately discarded by quake @@ -881,33 +881,33 @@ char *ED_ParseEdict (char *data, edict_t *ent) continue; // If skyname is set, we want to allow skyboxes and set what - // the skybox name should be. "qlsky" is supported since - // at least one other map uses it already. --KB - if (stricmp (keyname, "sky") == 0 || // LordHavoc: added "sky" key (Quake2 and DarkPlaces use this) + // the skybox name should be. "qlsky" is supported since + // at least one other map uses it already. --KB + if (stricmp (keyname, "sky") == 0 || // LordHavoc: added "sky" key + // (Quake2 and DarkPlaces use + // this) stricmp (keyname, "skyname") == 0 || - stricmp (keyname, "qlsky") == 0) - { + stricmp (keyname, "qlsky") == 0) { Info_SetValueForKey (svs.info, "skybox", - "1", MAX_SERVERINFO_STRING); - Cvar_Set(r_skyname, com_token); + "1", MAX_SERVERINFO_STRING); + Cvar_Set (r_skyname, com_token); continue; } key = ED_FindField (keyname); - if (!key) - { + if (!key) { Con_Printf ("%s is not a field\n", keyname); continue; } - if (anglehack) - { - char temp[32]; + if (anglehack) { + char temp[32]; + strcpy (temp, com_token); - snprintf (com_token, sizeof(com_token), "0 %s 0", temp); + snprintf (com_token, sizeof (com_token), "0 %s 0", temp); } - if (!ED_ParseEpair ((void *)&ent->v, key, com_token)) + if (!ED_ParseEpair ((void *) &ent->v, key, com_token)) SV_Error ("ED_ParseEdict: parse error"); } @@ -933,66 +933,61 @@ Used for both fresh maps and savegame loads. A fresh map would also need to call ED_CallSpawnFunctions () to let the objects initialize themselves. ================ */ -void ED_LoadFromFile (char *data) -{ - edict_t *ent; - int inhibit; - dfunction_t *func; - +void +ED_LoadFromFile (char *data) +{ + edict_t *ent; + int inhibit; + dfunction_t *func; + ent = NULL; inhibit = 0; pr_global_struct->time = sv.time; - + // parse ents - while (1) - { -// parse the opening brace + while (1) { +// parse the opening brace data = COM_Parse (data); if (!data) break; if (com_token[0] != '{') - SV_Error ("ED_LoadFromFile: found %s when expecting {",com_token); + SV_Error ("ED_LoadFromFile: found %s when expecting {", com_token); if (!ent) - ent = EDICT_NUM(0); + ent = EDICT_NUM (0); else ent = ED_Alloc (); data = ED_ParseEdict (data, ent); - + // remove things from different skill levels or deathmatch - if (((int)ent->v.spawnflags & SPAWNFLAG_NOT_DEATHMATCH)) - { - ED_Free (ent); + if (((int) ent->v.spawnflags & SPAWNFLAG_NOT_DEATHMATCH)) { + ED_Free (ent); inhibit++; continue; } - // // immediately call spawn function // - if (!ent->v.classname) - { + if (!ent->v.classname) { Con_Printf ("No classname for:\n"); ED_Print (ent); ED_Free (ent); continue; } - - // look for the spawn function - func = ED_FindFunction ( PR_GetString(ent->v.classname) ); + // look for the spawn function + func = ED_FindFunction (PR_GetString (ent->v.classname)); - if (!func) - { + if (!func) { Con_Printf ("No spawn function for:\n"); ED_Print (ent); ED_Free (ent); continue; } - pr_global_struct->self = EDICT_TO_PROG(ent); + pr_global_struct->self = EDICT_TO_PROG (ent); PR_ExecuteProgram (func - pr_functions); - SV_FlushSignon(); - } + SV_FlushSignon (); + } Con_DPrintf ("%i entities inhibited\n", inhibit); } @@ -1002,209 +997,230 @@ void ED_LoadFromFile (char *data) PR_LoadProgs =============== */ -void PR_LoadProgs (void) +void +PR_LoadProgs (void) { - int i; - char num[32]; + int i; + char num[32]; dstatement_t *st; dfunction_t *f; // flush the non-C variable lookup cache - for (i=0 ; iversion != PROG_VERSION) - SV_Error ("progs.dat has wrong version number (%i should be %i)", progs->version, PROG_VERSION); + SV_Error ("progs.dat has wrong version number (%i should be %i)", + progs->version, PROG_VERSION); if (progs->crc != PROGHEADER_CRC) SV_Error ("You must have the qwprogs.dat from QuakeWorld installed"); - pr_functions = (dfunction_t *)((byte *)progs + progs->ofs_functions); - pr_strings = (char *)progs + progs->ofs_strings; - pr_globaldefs = (ddef_t *)((byte *)progs + progs->ofs_globaldefs); - pr_fielddefs = (ddef_t *)((byte *)progs + progs->ofs_fielddefs); - pr_statements = (dstatement_t *)((byte *)progs + progs->ofs_statements); + pr_functions = (dfunction_t *) ((byte *) progs + progs->ofs_functions); + pr_strings = (char *) progs + progs->ofs_strings; + pr_globaldefs = (ddef_t *) ((byte *) progs + progs->ofs_globaldefs); + pr_fielddefs = (ddef_t *) ((byte *) progs + progs->ofs_fielddefs); + pr_statements = (dstatement_t *) ((byte *) progs + progs->ofs_statements); num_prstr = 0; - pr_global_struct = (globalvars_t *)((byte *)progs + progs->ofs_globals); - pr_globals = (float *)pr_global_struct; - - pr_edict_size = progs->entityfields * 4 + sizeof (edict_t) - sizeof(entvars_t); + pr_global_struct = (globalvars_t *) ((byte *) progs + progs->ofs_globals); + pr_globals = (float *) pr_global_struct; + + pr_edict_size = + + progs->entityfields * 4 + sizeof (edict_t) - sizeof (entvars_t); pr_edictareasize = pr_edict_size * MAX_EDICTS; // byte swap the lumps - for (i=0 ; inumstatements ; i++) - { - pr_statements[i].op = LittleShort(pr_statements[i].op); - pr_statements[i].a = LittleShort(pr_statements[i].a); - pr_statements[i].b = LittleShort(pr_statements[i].b); - pr_statements[i].c = LittleShort(pr_statements[i].c); + for (i = 0; i < progs->numstatements; i++) { + pr_statements[i].op = LittleShort (pr_statements[i].op); + pr_statements[i].a = LittleShort (pr_statements[i].a); + pr_statements[i].b = LittleShort (pr_statements[i].b); + pr_statements[i].c = LittleShort (pr_statements[i].c); } - for (i=0 ; inumfunctions; i++) - { - pr_functions[i].first_statement = LittleLong (pr_functions[i].first_statement); + for (i = 0; i < progs->numfunctions; i++) { + pr_functions[i].first_statement = + LittleLong (pr_functions[i].first_statement); pr_functions[i].parm_start = LittleLong (pr_functions[i].parm_start); pr_functions[i].s_name = LittleLong (pr_functions[i].s_name); pr_functions[i].s_file = LittleLong (pr_functions[i].s_file); pr_functions[i].numparms = LittleLong (pr_functions[i].numparms); pr_functions[i].locals = LittleLong (pr_functions[i].locals); - } + } - for (i=0 ; inumglobaldefs ; i++) - { + for (i = 0; i < progs->numglobaldefs; i++) { pr_globaldefs[i].type = LittleShort (pr_globaldefs[i].type); pr_globaldefs[i].ofs = LittleShort (pr_globaldefs[i].ofs); pr_globaldefs[i].s_name = LittleLong (pr_globaldefs[i].s_name); } - for (i=0 ; inumfielddefs ; i++) - { + for (i = 0; i < progs->numfielddefs; i++) { pr_fielddefs[i].type = LittleShort (pr_fielddefs[i].type); if (pr_fielddefs[i].type & DEF_SAVEGLOBAL) - SV_Error ("PR_LoadProgs: pr_fielddefs[i].type & DEF_SAVEGLOBAL"); + SV_Error ("PR_LoadProgs: pr_fielddefs[i].type & DEF_SAVEGLOBAL"); pr_fielddefs[i].ofs = LittleShort (pr_fielddefs[i].ofs); pr_fielddefs[i].s_name = LittleLong (pr_fielddefs[i].s_name); } - for (i=0 ; inumglobals ; i++) - ((int *)pr_globals)[i] = LittleLong (((int *)pr_globals)[i]); + for (i = 0; i < progs->numglobals; i++) + ((int *) pr_globals)[i] = LittleLong (((int *) pr_globals)[i]); // Zoid, find the spectator functions SpectatorConnect = SpectatorThink = SpectatorDisconnect = 0; if ((f = ED_FindFunction ("SpectatorConnect")) != NULL) - SpectatorConnect = (func_t)(f - pr_functions); + SpectatorConnect = (func_t) (f - pr_functions); if ((f = ED_FindFunction ("SpectatorThink")) != NULL) - SpectatorThink = (func_t)(f - pr_functions); + SpectatorThink = (func_t) (f - pr_functions); if ((f = ED_FindFunction ("SpectatorDisconnect")) != NULL) - SpectatorDisconnect = (func_t)(f - pr_functions); + SpectatorDisconnect = (func_t) (f - pr_functions); // 2000-01-02 EndFrame function by Maddes/FrikaC start EndFrame = 0; if ((f = ED_FindFunction ("EndFrame")) != NULL) - EndFrame = (func_t)(f - pr_functions); + EndFrame = (func_t) (f - pr_functions); // 2000-01-02 EndFrame function by Maddes/FrikaC end // LordHavoc: Ender added this - FindEdictFieldOffsets(); + FindEdictFieldOffsets (); // LordHavoc: bounds check anything static - for (i = 0,st = pr_statements;i < progs->numstatements;i++,st++) - { - switch (st->op) - { - case OP_IF: - case OP_IFNOT: - if ((unsigned short) st->a >= progs->numglobals || st->b + i < 0 || st->b + i >= progs->numstatements) - SV_Error("PR_LoadProgs: out of bounds IF/IFNOT (statement %d)\n", i); - break; - case OP_GOTO: - if (st->a + i < 0 || st->a + i >= progs->numstatements) - SV_Error("PR_LoadProgs: out of bounds GOTO (statement %d)\n", i); - break; - // global global global - case OP_ADD_F: - case OP_ADD_V: - case OP_SUB_F: - case OP_SUB_V: - case OP_MUL_F: - case OP_MUL_V: - case OP_MUL_FV: - case OP_MUL_VF: - case OP_DIV_F: - case OP_BITAND: - case OP_BITOR: - case OP_GE: - case OP_LE: - case OP_GT: - case OP_LT: - case OP_AND: - case OP_OR: - case OP_EQ_F: - case OP_EQ_V: - case OP_EQ_S: - case OP_EQ_E: - case OP_EQ_FNC: - case OP_NE_F: - case OP_NE_V: - case OP_NE_S: - case OP_NE_E: - case OP_NE_FNC: - case OP_ADDRESS: - case OP_LOAD_F: - case OP_LOAD_FLD: - case OP_LOAD_ENT: - case OP_LOAD_S: - case OP_LOAD_FNC: - case OP_LOAD_V: - if ((unsigned short) st->a >= progs->numglobals || (unsigned short) st->b >= progs->numglobals || (unsigned short) st->c >= progs->numglobals) - SV_Error("PR_LoadProgs: out of bounds global index (statement %d)\n", i); - break; - // global none global - case OP_NOT_F: - case OP_NOT_V: - case OP_NOT_S: - case OP_NOT_FNC: - case OP_NOT_ENT: - if ((unsigned short) st->a >= progs->numglobals || (unsigned short) st->c >= progs->numglobals) - SV_Error("PR_LoadProgs: out of bounds global index (statement %d)\n", i); - break; - // 2 globals - case OP_STOREP_F: - case OP_STOREP_ENT: - case OP_STOREP_FLD: - case OP_STOREP_S: - case OP_STOREP_FNC: - case OP_STORE_F: - case OP_STORE_ENT: - case OP_STORE_FLD: - case OP_STORE_S: - case OP_STORE_FNC: - case OP_STATE: - case OP_STOREP_V: - case OP_STORE_V: - if ((unsigned short) st->a >= progs->numglobals || (unsigned short) st->b >= progs->numglobals) - SV_Error("PR_LoadProgs: out of bounds global index (statement %d)\n", i); - break; - // 1 global - case OP_CALL0: - case OP_CALL1: - case OP_CALL2: - case OP_CALL3: - case OP_CALL4: - case OP_CALL5: - case OP_CALL6: - case OP_CALL7: - case OP_CALL8: - case OP_DONE: - case OP_RETURN: - if ((unsigned short) st->a >= progs->numglobals) - SV_Error("PR_LoadProgs: out of bounds global index (statement %d)\n", i); - break; - default: - SV_Error("PR_LoadProgs: unknown opcode %d at statement %d\n", st->op, i); - break; + for (i = 0, st = pr_statements; i < progs->numstatements; i++, st++) { + switch (st->op) { + case OP_IF: + case OP_IFNOT: + if ((unsigned short) st->a >= progs->numglobals || st->b + i < 0 + || st->b + i >= progs->numstatements) + SV_Error + ("PR_LoadProgs: out of bounds IF/IFNOT (statement %d)\n", + i); + break; + case OP_GOTO: + if (st->a + i < 0 || st->a + i >= progs->numstatements) + SV_Error + ("PR_LoadProgs: out of bounds GOTO (statement %d)\n", + i); + break; + // global global global + case OP_ADD_F: + case OP_ADD_V: + case OP_SUB_F: + case OP_SUB_V: + case OP_MUL_F: + case OP_MUL_V: + case OP_MUL_FV: + case OP_MUL_VF: + case OP_DIV_F: + case OP_BITAND: + case OP_BITOR: + case OP_GE: + case OP_LE: + case OP_GT: + case OP_LT: + case OP_AND: + case OP_OR: + case OP_EQ_F: + case OP_EQ_V: + case OP_EQ_S: + case OP_EQ_E: + case OP_EQ_FNC: + case OP_NE_F: + case OP_NE_V: + case OP_NE_S: + case OP_NE_E: + case OP_NE_FNC: + case OP_ADDRESS: + case OP_LOAD_F: + case OP_LOAD_FLD: + case OP_LOAD_ENT: + case OP_LOAD_S: + case OP_LOAD_FNC: + case OP_LOAD_V: + if ((unsigned short) st->a >= progs->numglobals + || (unsigned short) st->b >= progs->numglobals + || (unsigned short) st->c >= progs->numglobals) + SV_Error + ("PR_LoadProgs: out of bounds global index (statement %d)\n", + i); + break; + // global none global + case OP_NOT_F: + case OP_NOT_V: + case OP_NOT_S: + case OP_NOT_FNC: + case OP_NOT_ENT: + if ((unsigned short) st->a >= progs->numglobals + || (unsigned short) st->c >= progs->numglobals) + SV_Error + ("PR_LoadProgs: out of bounds global index (statement %d)\n", + i); + break; + // 2 globals + case OP_STOREP_F: + case OP_STOREP_ENT: + case OP_STOREP_FLD: + case OP_STOREP_S: + case OP_STOREP_FNC: + case OP_STORE_F: + case OP_STORE_ENT: + case OP_STORE_FLD: + case OP_STORE_S: + case OP_STORE_FNC: + case OP_STATE: + case OP_STOREP_V: + case OP_STORE_V: + if ((unsigned short) st->a >= progs->numglobals + || (unsigned short) st->b >= progs->numglobals) + SV_Error + ("PR_LoadProgs: out of bounds global index (statement %d)\n", + i); + break; + // 1 global + case OP_CALL0: + case OP_CALL1: + case OP_CALL2: + case OP_CALL3: + case OP_CALL4: + case OP_CALL5: + case OP_CALL6: + case OP_CALL7: + case OP_CALL8: + case OP_DONE: + case OP_RETURN: + if ((unsigned short) st->a >= progs->numglobals) + SV_Error + ("PR_LoadProgs: out of bounds global index (statement %d)\n", + i); + break; + default: + SV_Error ("PR_LoadProgs: unknown opcode %d at statement %d\n", + st->op, i); + break; } } - FindEdictFieldOffsets(); // LordHavoc: update field offset list + FindEdictFieldOffsets (); // LordHavoc: update field offset + // list } /* @@ -1212,7 +1228,8 @@ void PR_LoadProgs (void) PR_Init =============== */ -void PR_Init (void) +void +PR_Init (void) { Cmd_AddCommand ("edict", ED_PrintEdict_f); Cmd_AddCommand ("edicts", ED_PrintEdicts); @@ -1220,31 +1237,35 @@ void PR_Init (void) Cmd_AddCommand ("profile", PR_Profile_f); } -void PR_Init_Cvars (void) +void +PR_Init_Cvars (void) { - r_skyname = Cvar_Get ("r_skyname", com_token, CVAR_SERVERINFO, "name of skybox"); - pr_boundscheck = Cvar_Get("pr_boundscheck", "1", CVAR_NONE, "Server progs bounds checking"); + r_skyname = + Cvar_Get ("r_skyname", com_token, CVAR_SERVERINFO, "name of skybox"); + pr_boundscheck = + Cvar_Get ("pr_boundscheck", "1", CVAR_NONE, + "Server progs bounds checking"); } -edict_t *EDICT_NUM(int n) +edict_t * +EDICT_NUM (int n) { if (n < 0 || n >= MAX_EDICTS) SV_Error ("EDICT_NUM: bad number %i", n); - return (edict_t *)((byte *)sv.edicts+ (n)*pr_edict_size); + return (edict_t *) ((byte *) sv.edicts + (n) * pr_edict_size); } -int NUM_FOR_EDICT(edict_t *e) +int +NUM_FOR_EDICT (edict_t *e) { - int b; - - b = (byte *)e - (byte *)sv.edicts; + int b; + + b = (byte *) e - (byte *) sv.edicts; b = b / pr_edict_size; - + if (b < 0 || b >= sv.num_edicts) SV_Error ("NUM_FOR_EDICT: bad pointer"); return b; } - - diff --git a/source/pr_exec.c b/source/pr_exec.c index eef5ed7..fee6d7f 100644 --- a/source/pr_exec.c +++ b/source/pr_exec.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "pr_comp.h" #include "progs.h" @@ -393,7 +393,7 @@ PR_ExecuteProgram (func_t fnum) while (1) { st++; - if (++profile > 1000000) // LordHavoc: increased runaway loop + if (++profile > 1000000) // LordHavoc: increased runaway loop // limit 10x { pr_xstatement = st - pr_statements; @@ -524,9 +524,9 @@ PR_ExecuteProgram (func_t fnum) // ================== case OP_STORE_F: case OP_STORE_ENT: - case OP_STORE_FLD: // integers + case OP_STORE_FLD: // integers case OP_STORE_S: - case OP_STORE_FNC: // pointers + case OP_STORE_FNC: // pointers OPB->_int = OPA->_int; break; case OP_STORE_V: @@ -537,9 +537,9 @@ PR_ExecuteProgram (func_t fnum) case OP_STOREP_F: case OP_STOREP_ENT: - case OP_STOREP_FLD: // integers + case OP_STOREP_FLD: // integers case OP_STOREP_S: - case OP_STOREP_FNC: // pointers + case OP_STOREP_FNC: // pointers if (pr_boundscheck->int_val && (OPB->_int < 0 || OPB->_int + 4 > pr_edictareasize)) { pr_xstatement = st - pr_statements; @@ -626,8 +626,7 @@ PR_ExecuteProgram (func_t fnum) return; } if (pr_boundscheck->int_val - && (OPB->_int < 0 - || OPB->_int + 2 >= progs->entityfields)) { + && (OPB->_int < 0 || OPB->_int + 2 >= progs->entityfields)) { pr_xstatement = st - pr_statements; PR_RunError ("Progs attempted to read an invalid field in an edict\n"); @@ -651,7 +650,7 @@ PR_ExecuteProgram (func_t fnum) st += st->b - 1; // offset the s++ break; case OP_GOTO: - st += st->a - 1; // offset the s++ + st += st->a - 1; // offset the s++ break; case OP_CALL0: case OP_CALL1: @@ -691,7 +690,7 @@ PR_ExecuteProgram (func_t fnum) pr_globals[(unsigned short) st->a + 2]; st = &pr_statements[PR_LeaveFunction ()]; if (pr_depth == exitdepth) - return; // all done + return; // all done break; case OP_STATE: ed = PROG_TO_EDICT (pr_global_struct->self); @@ -984,7 +983,7 @@ char * PR_GetString (int num) { if (num < 0) { - //Con_DPrintf("GET:%d == %s\n", num, pr_strtbl[-num]); + // Con_DPrintf("GET:%d == %s\n", num, pr_strtbl[-num]); return pr_strtbl[-num]; } return pr_strings + num; @@ -1005,7 +1004,7 @@ PR_SetString (char *s) Sys_Error ("MAX_PRSTR"); num_prstr++; pr_strtbl[num_prstr] = s; - //Con_DPrintf("SET:%d == %s\n", -num_prstr, s); + // Con_DPrintf("SET:%d == %s\n", -num_prstr, s); return -num_prstr; } return (int) (s - pr_strings); diff --git a/source/pr_offs.c b/source/pr_offs.c index b9f08d6..daef8b0 100644 --- a/source/pr_offs.c +++ b/source/pr_offs.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "pr_comp.h" #include "progs.h" @@ -43,32 +43,38 @@ #include #include -int eval_alpha, eval_scale, eval_glowsize, eval_glowcolor, eval_colormod; +int eval_alpha, eval_scale, eval_glowsize, eval_glowcolor, -int FindFieldOffset(char *field) + eval_colormod; + +int +FindFieldOffset (char *field) { - ddef_t *d; - d = ED_FindField(field); + ddef_t *d; + + d = ED_FindField (field); if (!d) return 0; - return d->ofs*4; + return d->ofs * 4; } -eval_t *GETEDICTFIELDVALUE(edict_t *ed, int fieldoffset) +eval_t * +GETEDICTFIELDVALUE (edict_t *ed, int fieldoffset) { if (!fieldoffset) return NULL; - return (eval_t*)((char*)&ed->v + fieldoffset); + return (eval_t *) ((char *) &ed->v + fieldoffset); } -void FindEdictFieldOffsets() +void +FindEdictFieldOffsets () { - eval_alpha = FindFieldOffset("alpha"); - eval_scale = FindFieldOffset("scale"); - eval_glowsize = FindFieldOffset("glow_size"); - eval_glowcolor = FindFieldOffset("glow_color"); - eval_colormod = FindFieldOffset("colormod"); + eval_alpha = FindFieldOffset ("alpha"); + eval_scale = FindFieldOffset ("scale"); + eval_glowsize = FindFieldOffset ("glow_size"); + eval_glowcolor = FindFieldOffset ("glow_color"); + eval_colormod = FindFieldOffset ("colormod"); }; diff --git a/source/qargs.c b/source/qargs.c index 19c2b86..9268569 100644 --- a/source/qargs.c +++ b/source/qargs.c @@ -30,7 +30,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "string.h" #include "ctype.h" @@ -46,21 +46,22 @@ #include -usercmd_t nullcmd; // guarenteed to be zero +usercmd_t nullcmd; // guarenteed to be zero -static char **largv; -static char *argvdummy = " "; +static char **largv; +static char *argvdummy = " "; -static char *safeargvs[] = - {"-stdvid", "-nolan", "-nosound", "-nocdaudio", "-nojoy", "-nomouse", "-dibonly"}; +static char *safeargvs[] = + { "-stdvid", "-nolan", "-nosound", "-nocdaudio", "-nojoy", "-nomouse", + "-dibonly" }; #define NUM_SAFE_ARGVS (sizeof(safeargvs)/sizeof(safeargvs[0])) -int com_argc; -char **com_argv; -char *com_cmdline; +int com_argc; +char **com_argv; +char *com_cmdline; -qboolean nouse = false; // 1999-10-29 +USE fix by Maddes +qboolean nouse = false; // 1999-10-29 +USE fix by Maddes /* ================ @@ -70,15 +71,16 @@ Returns the position (1 to argc-1) in the program's argument list where the given parameter apears, or 0 if not present ================ */ -int COM_CheckParm (char *parm) +int +COM_CheckParm (char *parm) { - int i; + int i; - for (i=1 ; i 0); - strncat (com_cmdline, " ", len - strlen (com_cmdline)); + assert (len - strlen (com_cmdline) > 0); + strncat (com_cmdline, " ", len - strlen (com_cmdline)); } com_cmdline[len - 1] = '\0'; } - if (safe) - { - // force all the safe-mode switches. Note that we reserved extra space in - // case we need to add these, so we don't need an overflow check - for (i=0 ; i +# include "config.h" #endif #include @@ -43,21 +43,21 @@ ============================================================================ */ -qboolean bigendien; -short (*BigShort) (short l); -short (*LittleShort) (short l); -int (*BigLong) (int l); -int (*LittleLong) (int l); -float (*BigFloat) (float l); -float (*LittleFloat) (float l); +qboolean bigendien; +short (*BigShort) (short l); +short (*LittleShort) (short l); +int (*BigLong) (int l); +int (*LittleLong) (int l); +float (*BigFloat) (float l); +float (*LittleFloat) (float l); short ShortSwap (short l) { - byte b1, b2; + byte b1, b2; b1 = l & 255; - b2 = (l >> 8)&255; + b2 = (l >> 8) & 255; return (b1 << 8) + b2; } @@ -71,7 +71,7 @@ ShortNoSwap (short l) int LongSwap (int l) { - byte b1, b2, b3, b4; + byte b1, b2, b3, b4; b1 = l & 255; b2 = (l >> 8) & 255; @@ -91,9 +91,9 @@ float FloatSwap (float f) { union { - float f; - byte b[4]; - } dat1, dat2; + float f; + byte b[4]; + } dat1 , dat2; dat1.f = f; diff --git a/source/qfgl_ext.c b/source/qfgl_ext.c index 7b6d742..16a6be8 100644 --- a/source/qfgl_ext.c +++ b/source/qfgl_ext.c @@ -65,10 +65,10 @@ string. Don't be fooled by sub-strings, etc. */ qboolean -QFGL_ParseExtensionList (const GLubyte *list, const char *name) +QFGL_ParseExtensionList (const GLubyte * list, const char *name) { - const char *start; - char *where, *terminator; + const char *start; + char *where, *terminator; // Extension names must not have spaces. where = (GLubyte *) strchr (name, ' '); @@ -92,25 +92,28 @@ QFGL_ParseExtensionList (const GLubyte *list, const char *name) qboolean QFGL_ExtensionPresent (const char *name) { - static const GLubyte *gl_extensions = NULL; -#ifdef _WIN32 - static const GLubyte *wgl_extensions = NULL; + static const GLubyte *gl_extensions = NULL; - static qboolean extensionFunc_present = true; - static QF_wglGetExtensionsStringEXT extensionFunc = NULL; +#ifdef _WIN32 + static const GLubyte *wgl_extensions = NULL; + + static qboolean extensionFunc_present = true; + static QF_wglGetExtensionsStringEXT extensionFunc = NULL; #endif - if (!gl_extensions) { // get and save GL extension list + if (!gl_extensions) { // get and save GL extension list gl_extensions = glGetString (GL_EXTENSIONS); } - #ifdef _WIN32 - if (!wgl_extensions) { // get and save WGL extension list + if (!wgl_extensions) { // get and save WGL extension list if (extensionFunc_present && !extensionFunc) { - if (!(QFGL_ParseExtensionList (gl_extensions, "WGL_EXT_extensions_string"))) { + if (! + (QFGL_ParseExtensionList + (gl_extensions, "WGL_EXT_extensions_string"))) { extensionFunc_present = false; } else { - extensionFunc = QFGL_ExtensionAddress ("WGL_EXT_extension_string"); + extensionFunc = + QFGL_ExtensionAddress ("WGL_EXT_extension_string"); } } @@ -132,14 +135,14 @@ QFGL_ExtensionPresent (const char *name) } -void * +void * QFGL_ExtensionAddress (const char *name) { #if defined(HAVE_GLX) && defined(HAVE_DLOPEN) - void *dlhand = NULL; + void *dlhand = NULL; - static qboolean glProcAddress_present = true; - static QF_glXGetProcAddressARB qfglXGetProcAddress = NULL; + static qboolean glProcAddress_present = true; + static QF_glXGetProcAddressARB qfglXGetProcAddress = NULL; if (glProcAddress_present && !qfglXGetProcAddress) { if (QFGL_ExtensionPresent ("GLX_ARB_get_proc_address")) { @@ -161,7 +164,8 @@ QFGL_ExtensionAddress (const char *name) return qfglXGetProcAddress ((const GLubyte *) name); } else { if ((dlhand = dlopen (NULL, RTLD_LAZY))) { - void *handle; + void *handle; + handle = dlsym (dlhand, name); dlclose (dlhand); return handle; diff --git a/source/quakefs.c b/source/quakefs.c index f66712b..328140e 100644 --- a/source/quakefs.c +++ b/source/quakefs.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "qtypes.h" #include "quakefs.h" @@ -74,11 +74,13 @@ #endif #ifndef HAVE_FNMATCH_PROTO -int fnmatch (__const char *__pattern, __const char *__string, int __flags); +int fnmatch (__const char *__pattern, __const char *__string, + + int __flags); #endif -extern qboolean is_server; +extern qboolean is_server; /* @@ -112,61 +114,57 @@ QUAKE FILESYSTEM ============================================================================= */ -char gamedirfile[MAX_OSPATH]; +char gamedirfile[MAX_OSPATH]; -cvar_t *fs_userpath; -cvar_t *fs_sharepath; -cvar_t *fs_basegame; +cvar_t *fs_userpath; +cvar_t *fs_sharepath; +cvar_t *fs_basegame; -int com_filesize; +int com_filesize; /* In-memory pack file structs */ -typedef struct -{ - char name[MAX_QPATH]; - int filepos, filelen; +typedef struct { + char name[MAX_QPATH]; + int filepos, filelen; } packfile_t; -typedef struct pack_s -{ - char filename[MAX_OSPATH]; - QFile *handle; - int numfiles; - packfile_t *files; +typedef struct pack_s { + char filename[MAX_OSPATH]; + QFile *handle; + int numfiles; + packfile_t *files; } pack_t; /* Structs for pack files on disk */ -typedef struct -{ - char name[56]; - int filepos, filelen; +typedef struct { + char name[56]; + int filepos, filelen; } dpackfile_t; -typedef struct -{ - char id[4]; - int dirofs; - int dirlen; +typedef struct { + char id[4]; + int dirofs; + int dirlen; } dpackheader_t; #define MAX_FILES_IN_PACK 2048 -char com_gamedir[MAX_OSPATH]; +char com_gamedir[MAX_OSPATH]; -typedef struct searchpath_s -{ - char filename[MAX_OSPATH]; - pack_t *pack; // only one of filename / pack will be used +typedef struct searchpath_s { + char filename[MAX_OSPATH]; + pack_t *pack; // only one of filename / pack will + // be used struct searchpath_s *next; } searchpath_t; -searchpath_t *com_searchpaths; -searchpath_t *com_base_searchpaths; // without gamedirs +searchpath_t *com_searchpaths; +searchpath_t *com_base_searchpaths; // without gamedirs /* COM_FileBase @@ -174,23 +172,21 @@ searchpath_t *com_base_searchpaths; // without gamedirs void COM_FileBase (char *in, char *out) { - char *s, *s2; - - s = in + strlen(in) - 1; - + char *s, *s2; + + s = in + strlen (in) - 1; + while (s != in && *s != '.') s--; - - for (s2 = s ; *s2 && *s2 != '/' ; s2--) - ; - - if (s-s2 < 2) - strcpy (out,"?model?"); - else - { + + for (s2 = s; *s2 && *s2 != '/'; s2--); + + if (s - s2 < 2) + strcpy (out, "?model?"); + else { s--; - strncpy (out,s2+1, s-s2); - out[s-s2] = 0; + strncpy (out, s2 + 1, s - s2); + out[s - s2] = 0; } } @@ -200,8 +196,8 @@ COM_FileBase (char *in, char *out) int COM_filelength (QFile *f) { - int pos; - int end; + int pos; + int end; pos = Qtell (f); Qseek (f, 0, SEEK_END); @@ -217,17 +213,16 @@ COM_filelength (QFile *f) int COM_FileOpenRead (char *path, QFile **hndl) { - QFile *f; + QFile *f; - f = Qopen(path, "rbz"); - if (!f) - { + f = Qopen (path, "rbz"); + if (!f) { *hndl = NULL; return -1; } *hndl = f; - return COM_filelength(f); + return COM_filelength (f); } /* @@ -236,15 +231,15 @@ COM_FileOpenRead (char *path, QFile **hndl) void COM_Path_f (void) { - searchpath_t *s; + searchpath_t *s; Con_Printf ("Current search path:\n"); - for (s=com_searchpaths ; s ; s=s->next) - { + for (s = com_searchpaths; s; s = s->next) { if (s == com_base_searchpaths) Con_Printf ("----------\n"); if (s->pack) - Con_Printf ("%s (%i files)\n", s->pack->filename, s->pack->numfiles); + Con_Printf ("%s (%i files)\n", s->pack->filename, + s->pack->numfiles); else Con_Printf ("%s\n", s->filename); } @@ -257,32 +252,33 @@ COM_Path_f (void) */ struct maplist { - char **list; - int count; - int size; + char **list; + int count; + int size; }; -static struct maplist* -maplist_new() +static struct maplist * +maplist_new () { - return calloc(1, sizeof(struct maplist)); + return calloc (1, sizeof (struct maplist)); } static void -maplist_free(struct maplist *maplist) +maplist_free (struct maplist *maplist) { free (maplist->list); free (maplist); } static void -maplist_add_map(struct maplist *maplist, char *fname) +maplist_add_map (struct maplist *maplist, char *fname) { - char **new_list; + char **new_list; if (maplist->count == maplist->size) { maplist->size += 32; - new_list = realloc (maplist->list, maplist->size * sizeof(char*)); + new_list = realloc (maplist->list, maplist->size * sizeof (char *)); + if (!new_list) { maplist->size -= 32; return; @@ -293,13 +289,13 @@ maplist_add_map(struct maplist *maplist, char *fname) } static int -maplist_cmp(const void *_a, const void *_b) +maplist_cmp (const void *_a, const void *_b) { - char *a = *(char**)_a; - char *b = *(char**)_b; - int al = strstr (a, ".bsp") - a; - int bl = strstr (b, ".bsp") - b; - int cmp = strncmp (a, b, min (al, bl)); + char *a = *(char **) _a; + char *b = *(char **) _b; + int al = strstr (a, ".bsp") - a; + int bl = strstr (b, ".bsp") - b; + int cmp = strncmp (a, b, min (al, bl)); if (cmp == 0) return al - bl; @@ -307,15 +303,16 @@ maplist_cmp(const void *_a, const void *_b) } static void -maplist_print(struct maplist *maplist) +maplist_print (struct maplist *maplist) { - int i; - char *end; - char *name; + int i; + char *end; + char *name; if (maplist->count) { - qsort(maplist->list, maplist->count, sizeof(char *), maplist_cmp); - for (i=0; icount - 1; i++) { + qsort (maplist->list, maplist->count, sizeof (char *), maplist_cmp); + + for (i = 0; i < maplist->count - 1; i++) { name = maplist->list[i]; end = strstr (name, ".bsp"); Con_Printf ("%-8.*s%c", end - name, name, @@ -328,34 +325,35 @@ maplist_print(struct maplist *maplist) } void -COM_Maplist_f ( void ) +COM_Maplist_f (void) { - searchpath_t *search; - DIR *dir_ptr; - struct dirent *dirent; - char buf[MAX_OSPATH]; + searchpath_t *search; + DIR *dir_ptr; + struct dirent *dirent; + char buf[MAX_OSPATH]; - for (search = com_searchpaths ; search != NULL ; search = search->next) { + for (search = com_searchpaths; search != NULL; search = search->next) { if (search->pack) { - int i; - pack_t *pak = search->pack; + int i; + pack_t *pak = search->pack; struct maplist *maplist = maplist_new (); - Con_Printf ("Looking in %s...\n",search->pack->filename); - for (i=0 ; inumfiles ; i++) { - char *name=pak->files[i].name; + Con_Printf ("Looking in %s...\n", search->pack->filename); + for (i = 0; i < pak->numfiles; i++) { + char *name = pak->files[i].name; + if (!fnmatch ("maps/*.bsp", name, FNM_PATHNAME) || !fnmatch ("maps/*.bsp.gz", name, FNM_PATHNAME)) - maplist_add_map (maplist, name+5); + maplist_add_map (maplist, name + 5); } maplist_print (maplist); maplist_free (maplist); } else { struct maplist *maplist = maplist_new (); - snprintf (buf, sizeof(buf), "%s/maps", search->filename); - dir_ptr = opendir(buf); - Con_Printf ("Looking in %s...\n",buf); + snprintf (buf, sizeof (buf), "%s/maps", search->filename); + dir_ptr = opendir (buf); + Con_Printf ("Looking in %s...\n", buf); if (!dir_ptr) continue; while ((dirent = readdir (dir_ptr))) @@ -375,16 +373,16 @@ COM_Maplist_f ( void ) The filename will be prefixed by the current game directory */ void -COM_WriteFile ( char *filename, void *data, int len ) +COM_WriteFile (char *filename, void *data, int len) { - QFile *f; - char name[MAX_OSPATH]; + QFile *f; + char name[MAX_OSPATH]; - snprintf(name, sizeof(name), "%s/%s", com_gamedir, filename); + snprintf (name, sizeof (name), "%s/%s", com_gamedir, filename); f = Qopen (name, "wb"); if (!f) { - Sys_mkdir(com_gamedir); + Sys_mkdir (com_gamedir); f = Qopen (name, "wb"); if (!f) Sys_Error ("Error opening %s", filename); @@ -402,16 +400,16 @@ COM_WriteFile ( char *filename, void *data, int len ) Only used for CopyFile and download */ void -COM_CreatePath ( char *path ) +COM_CreatePath (char *path) { - char *ofs; - char e_path[MAX_OSPATH]; + char *ofs; + char e_path[MAX_OSPATH]; Qexpand_squiggle (path, e_path); path = e_path; - for (ofs = path+1 ; *ofs ; ofs++) { - if (*ofs == '/') { // create the directory + for (ofs = path + 1; *ofs; ofs++) { + if (*ofs == '/') { // create the directory *ofs = 0; Sys_mkdir (path); *ofs = '/'; @@ -430,23 +428,23 @@ COM_CreatePath ( char *path ) void COM_CopyFile (char *netpath, char *cachepath) { - QFile *in, *out; - int remaining, count; - char buf[4096]; + QFile *in, *out; + int remaining, count; + char buf[4096]; remaining = COM_FileOpenRead (netpath, &in); - COM_CreatePath (cachepath); // create directories up to the cache file - out = Qopen(cachepath, "wb"); + COM_CreatePath (cachepath); // create directories up to the cache + // file + out = Qopen (cachepath, "wb"); if (!out) Sys_Error ("Error opening %s", cachepath); - while (remaining) - { - if (remaining < sizeof(buf)) + while (remaining) { + if (remaining < sizeof (buf)) count = remaining; else - count = sizeof(buf); - Qread (in, buf, count); + count = sizeof (buf); + Qread (in, buf, count); Qwrite (out, buf, count); remaining -= count; } @@ -458,47 +456,50 @@ COM_CopyFile (char *netpath, char *cachepath) /* COM_OpenRead */ -QFile * +QFile * COM_OpenRead (const char *path, int offs, int len, int zip) { - int fd=open(path,O_RDONLY); + int fd = open (path, O_RDONLY); unsigned char id[2]; unsigned char len_bytes[4]; - if (fd==-1) { + + if (fd == -1) { Sys_Error ("Couldn't open %s", path); return 0; } - if (offs<0 || len<0) { + if (offs < 0 || len < 0) { // normal file - offs=0; - len=lseek(fd,0,SEEK_END); - lseek(fd,0,SEEK_SET); + offs = 0; + len = lseek (fd, 0, SEEK_END); + lseek (fd, 0, SEEK_SET); } - lseek(fd,offs,SEEK_SET); + lseek (fd, offs, SEEK_SET); if (zip) { - read(fd,id,2); - if (id[0]==0x1f && id[1]==0x8b) { - lseek(fd,offs+len-4,SEEK_SET); - read(fd,len_bytes,4); - len=((len_bytes[3]<<24) - |(len_bytes[2]<<16) - |(len_bytes[1]<<8) - |(len_bytes[0])); + read (fd, id, 2); + if (id[0] == 0x1f && id[1] == 0x8b) { + lseek (fd, offs + len - 4, SEEK_SET); + read (fd, len_bytes, 4); + len = ((len_bytes[3] << 24) + | (len_bytes[2] << 16) + | (len_bytes[1] << 8) + | (len_bytes[0])); } } - lseek(fd,offs,SEEK_SET); - com_filesize=len; + lseek (fd, offs, SEEK_SET); + com_filesize = len; #ifdef WIN32 - setmode(fd,O_BINARY); + setmode (fd, O_BINARY); #endif if (zip) - return Qdopen(fd,"rbz"); + return Qdopen (fd, "rbz"); else - return Qdopen(fd,"rb"); + return Qdopen (fd, "rb"); } -int file_from_pak; // global indicating file came from pack file ZOID +int file_from_pak; // global indicating file came from + + // pack file ZOID /* COM_FOpenFile @@ -509,18 +510,19 @@ int file_from_pak; // global indicating file came from pack file ZOID int _COM_FOpenFile (char *filename, QFile **gzfile, char *foundname, int zip) { - searchpath_t *search; - char netpath[MAX_OSPATH]; - pack_t *pak; - int i; - int findtime; -#ifdef HAVE_ZLIB - char gzfilename[MAX_OSPATH]; - int filenamelen;; + searchpath_t *search; + char netpath[MAX_OSPATH]; + pack_t *pak; + int i; + int findtime; - filenamelen = strlen(filename); - strncpy(gzfilename,filename,sizeof(gzfilename)); - strncat(gzfilename,".gz",sizeof(gzfilename) - strlen (gzfilename)); +#ifdef HAVE_ZLIB + char gzfilename[MAX_OSPATH]; + int filenamelen;; + + filenamelen = strlen (filename); + strncpy (gzfilename, filename, sizeof (gzfilename)); + strncat (gzfilename, ".gz", sizeof (gzfilename) - strlen (gzfilename)); #endif file_from_pak = 0; @@ -528,68 +530,65 @@ _COM_FOpenFile (char *filename, QFile **gzfile, char *foundname, int zip) // // search through the path, one element at a time // - for (search = com_searchpaths ; search ; search = search->next) - { - // is the element a pak file? - if (search->pack) - { - // look through all the pak file elements + for (search = com_searchpaths; search; search = search->next) { + // is the element a pak file? + if (search->pack) { + // look through all the pak file elements pak = search->pack; - for (i=0 ; inumfiles ; i++) { - char *fn=0; + for (i = 0; i < pak->numfiles; i++) { + char *fn = 0; + #ifdef HAVE_ZLIB - if (!strncmp(pak->files[i].name, filename, filenamelen)) { + if (!strncmp (pak->files[i].name, filename, filenamelen)) { if (!pak->files[i].name[filenamelen]) - fn=filename; + fn = filename; else if (!strcmp (pak->files[i].name, gzfilename)) - fn=gzfilename; + fn = gzfilename; } #else if (!strcmp (pak->files[i].name, filename)) - fn=filename; + fn = filename; #endif - if (fn) - { // found it! + if (fn) { // found it! if (developer->int_val) - Sys_Printf ("PackFile: %s : %s\n",pak->filename, fn); + Sys_Printf ("PackFile: %s : %s\n", pak->filename, fn); // open a new file on the pakfile - strncpy(foundname, fn, MAX_OSPATH); - *gzfile=COM_OpenRead(pak->filename, pak->files[i].filepos, - pak->files[i].filelen, zip); + strncpy (foundname, fn, MAX_OSPATH); + *gzfile = + COM_OpenRead (pak->filename, pak->files[i].filepos, + pak->files[i].filelen, zip); file_from_pak = 1; return com_filesize; } } - } - else - { - // check a file in the directory tree - snprintf(netpath, sizeof(netpath), "%s/%s",search->filename, - filename); + } else { + // check a file in the directory tree + snprintf (netpath, sizeof (netpath), "%s/%s", search->filename, + filename); - strncpy(foundname, filename, MAX_OSPATH); + strncpy (foundname, filename, MAX_OSPATH); findtime = Sys_FileTime (netpath); if (findtime == -1) { #ifdef HAVE_ZLIB - strncpy(foundname, gzfilename, MAX_OSPATH); - snprintf(netpath, sizeof(netpath), "%s/%s",search->filename, - gzfilename); + strncpy (foundname, gzfilename, MAX_OSPATH); + snprintf (netpath, sizeof (netpath), "%s/%s", search->filename, + gzfilename); findtime = Sys_FileTime (netpath); if (findtime == -1) #endif continue; } - if(developer->int_val) - Sys_Printf ("FindFile: %s\n",netpath); + if (developer->int_val) + Sys_Printf ("FindFile: %s\n", netpath); - *gzfile=COM_OpenRead(netpath, -1, -1, zip); + *gzfile = COM_OpenRead (netpath, -1, -1, zip); return com_filesize; } } - if(developer->int_val) + if (developer->int_val) Sys_Printf ("FindFile: can't find %s\n", filename); *gzfile = NULL; @@ -600,13 +599,14 @@ _COM_FOpenFile (char *filename, QFile **gzfile, char *foundname, int zip) int COM_FOpenFile (char *filename, QFile **gzfile) { - char foundname[MAX_OSPATH]; + char foundname[MAX_OSPATH]; + return _COM_FOpenFile (filename, gzfile, foundname, 1); } cache_user_t *loadcache; -byte *loadbuf; -int loadsize; +byte *loadbuf; +int loadsize; /* COM_LoadFile @@ -614,15 +614,15 @@ int loadsize; Filename are relative to the quake directory. Allways appends a 0 byte to the loaded data. */ -byte * +byte * COM_LoadFile (char *path, int usehunk) { - QFile *h; - byte *buf; - char base[32]; - int len; + QFile *h; + byte *buf; + char base[32]; + int len; - buf = NULL; // quiet compiler warning + buf = NULL; // quiet compiler warning // look for it in the filesystem or pack files len = com_filesize = COM_FOpenFile (path, &h); @@ -633,46 +633,44 @@ COM_LoadFile (char *path, int usehunk) COM_FileBase (path, base); if (usehunk == 1) - buf = Hunk_AllocName (len+1, base); + buf = Hunk_AllocName (len + 1, base); else if (usehunk == 2) - buf = Hunk_TempAlloc (len+1); + buf = Hunk_TempAlloc (len + 1); else if (usehunk == 0) - buf = calloc (1, len+1); + buf = calloc (1, len + 1); else if (usehunk == 3) - buf = Cache_Alloc (loadcache, len+1, base); - else if (usehunk == 4) - { - if (len+1 > loadsize) - buf = Hunk_TempAlloc (len+1); + buf = Cache_Alloc (loadcache, len + 1, base); + else if (usehunk == 4) { + if (len + 1 > loadsize) + buf = Hunk_TempAlloc (len + 1); else buf = loadbuf; - } - else + } else Sys_Error ("COM_LoadFile: bad usehunk"); if (!buf) Sys_Error ("COM_LoadFile: not enough space for %s", path); - ((byte *)buf)[len] = 0; + ((byte *) buf)[len] = 0; if (!is_server) { - Draw_BeginDisc(); + Draw_BeginDisc (); } Qread (h, buf, len); Qclose (h); if (!is_server) { - Draw_EndDisc(); + Draw_EndDisc (); } return buf; } -byte * +byte * COM_LoadHunkFile (char *path) { return COM_LoadFile (path, 1); } -byte * +byte * COM_LoadTempFile (char *path) { return COM_LoadFile (path, 2); @@ -686,12 +684,12 @@ COM_LoadCacheFile (char *path, struct cache_user_s *cu) } // uses temp hunk if larger than bufsize -byte * +byte * COM_LoadStackFile (char *path, void *buffer, int bufsize) { - byte *buf; + byte *buf; - loadbuf = (byte *)buffer; + loadbuf = (byte *) buffer; loadsize = bufsize; buf = COM_LoadFile (path, 4); @@ -706,44 +704,43 @@ COM_LoadStackFile (char *path, void *buffer, int bufsize) Loads the header and directory, adding the files at the beginning of the list so they override previous pack files. */ -pack_t * +pack_t * COM_LoadPackFile (char *packfile) { - dpackheader_t header; - int i; - packfile_t *newfiles; - int numpackfiles; - pack_t *pack; - QFile *packhandle; - dpackfile_t info[MAX_FILES_IN_PACK]; + dpackheader_t header; + int i; + packfile_t *newfiles; + int numpackfiles; + pack_t *pack; + QFile *packhandle; + dpackfile_t info[MAX_FILES_IN_PACK]; if (COM_FileOpenRead (packfile, &packhandle) == -1) return NULL; - Qread (packhandle, &header, sizeof(header)); + Qread (packhandle, &header, sizeof (header)); if (header.id[0] != 'P' || header.id[1] != 'A' - || header.id[2] != 'C' || header.id[3] != 'K') + || header.id[2] != 'C' || header.id[3] != 'K') Sys_Error ("%s is not a packfile", packfile); header.dirofs = LittleLong (header.dirofs); header.dirlen = LittleLong (header.dirlen); - numpackfiles = header.dirlen / sizeof(dpackfile_t); + numpackfiles = header.dirlen / sizeof (dpackfile_t); if (numpackfiles > MAX_FILES_IN_PACK) Sys_Error ("%s has %i files", packfile, numpackfiles); - newfiles = calloc (1, numpackfiles * sizeof(packfile_t)); + newfiles = calloc (1, numpackfiles * sizeof (packfile_t)); Qseek (packhandle, header.dirofs, SEEK_SET); Qread (packhandle, info, header.dirlen); // parse the directory - for (i=0 ; id_name, 0)) { + while ((dirent = readdir (dir_ptr))) { + if (!fnmatch ("*.pak", dirent->d_name, 0)) { if (count >= bufsize) { bufsize += FBLOCK_SIZE; - pakfiles = realloc(pakfiles, bufsize * sizeof(char *)); + pakfiles = realloc (pakfiles, bufsize * sizeof (char *)); + if (!pakfiles) goto COM_LoadGameDirectory_free; for (i = count; i < bufsize; i++) pakfiles[i] = NULL; } - pakfiles[count] = malloc(FNAME_SIZE); - snprintf(pakfiles[count], FNAME_SIZE - 1, "%s/%s", dir, - dirent->d_name); + pakfiles[count] = malloc (FNAME_SIZE); + snprintf (pakfiles[count], FNAME_SIZE - 1, "%s/%s", dir, + dirent->d_name); pakfiles[count][FNAME_SIZE - 1] = '\0'; count++; } } - closedir(dir_ptr); + closedir (dir_ptr); // XXX WARNING!!! This is /NOT/ subtable for strcmp!!!!! // This passes 'char **' instead of 'char *' to the cmp function! - qsort(pakfiles, count, sizeof(char *), - (int (*)(const void *, const void *)) qstrcmp); + qsort (pakfiles, count, sizeof (char *), + (int (*)(const void *, const void *)) qstrcmp); for (i = 0; i < count; i++) { - pak = COM_LoadPackFile(pakfiles[i]); + pak = COM_LoadPackFile (pakfiles[i]); if (!pak) { - Sys_Error(va("Bad pakfile %s!!", pakfiles[i])); + Sys_Error (va ("Bad pakfile %s!!", pakfiles[i])); } else { - search = calloc (1, sizeof(searchpath_t)); + search = calloc (1, sizeof (searchpath_t)); search->pack = pak; search->next = com_searchpaths; com_searchpaths = search; } } -COM_LoadGameDirectory_free: + COM_LoadGameDirectory_free: for (i = 0; i < count; i++) - free(pakfiles[i]); - free(pakfiles); + free (pakfiles[i]); + free (pakfiles); } /* @@ -870,25 +871,25 @@ COM_LoadGameDirectory_free: void COM_AddDirectory (char *dir) { - searchpath_t *search; - char *p; - char e_dir[MAX_OSPATH]; + searchpath_t *search; + char *p; + char e_dir[MAX_OSPATH]; Qexpand_squiggle (dir, e_dir); dir = e_dir; - if ((p = strrchr(dir, '/')) != NULL) { + if ((p = strrchr (dir, '/')) != NULL) { strcpy (gamedirfile, ++p); strcpy (com_gamedir, dir); } else { strcpy (gamedirfile, dir); - strcpy (com_gamedir, va("%s/%s", fs_userpath->string, dir)); + strcpy (com_gamedir, va ("%s/%s", fs_userpath->string, dir)); } // // add the directory to the search path // - search = calloc (1, sizeof(searchpath_t)); + search = calloc (1, sizeof (searchpath_t)); strcpy (search->filename, dir); search->next = com_searchpaths; com_searchpaths = search; @@ -912,11 +913,11 @@ void COM_AddGameDirectory (char *dir) { Con_DPrintf ("COM_AddGameDirectory (\"%s/%s\")\n", - fs_sharepath->string, dir); + fs_sharepath->string, dir); if (strcmp (fs_sharepath->string, fs_userpath->string) != 0) - COM_AddDirectory (va("%s/%s", fs_sharepath->string, dir)); - COM_AddDirectory (va("%s/%s", fs_userpath->string, dir)); + COM_AddDirectory (va ("%s/%s", fs_sharepath->string, dir)); + COM_AddDirectory (va ("%s/%s", fs_userpath->string, dir)); } /* @@ -927,26 +928,23 @@ COM_AddGameDirectory (char *dir) void COM_Gamedir (char *dir) { - searchpath_t *next; + searchpath_t *next; - if (strstr(dir, "..") || strstr(dir, "/") - || strstr(dir, "\\") || strstr(dir, ":") ) - { + if (strstr (dir, "..") || strstr (dir, "/") + || strstr (dir, "\\") || strstr (dir, ":")) { Con_Printf ("Gamedir should be a single filename, not a path\n"); return; } if (strcmp (gamedirfile, dir) == 0) - return; // still the same + return; // still the same strcpy (gamedirfile, dir); - // + // // free up any current game dir info - // - while (com_searchpaths != com_base_searchpaths) - { - if (com_searchpaths->pack) - { + // + while (com_searchpaths != com_base_searchpaths) { + if (com_searchpaths->pack) { Qclose (com_searchpaths->pack->handle); free (com_searchpaths->pack->files); free (com_searchpaths->pack); @@ -956,15 +954,14 @@ COM_Gamedir (char *dir) com_searchpaths = next; } - // + // // flush all data, so it will be forced to reload - // + // Cache_Flush (); if (strcmp (dir, fs_basegame->string) == 0) return; - if (strcmp (dir, "qw") == 0 - && strcmp (fs_basegame->string, "id1") == 0) + if (strcmp (dir, "qw") == 0 && strcmp (fs_basegame->string, "id1") == 0) return; COM_AddGameDirectory (dir); @@ -978,27 +975,25 @@ Sets the gamedir and path to a different directory. ================ */ -void COM_Gamedir_f (void) +void +COM_Gamedir_f (void) { - char *dir; + char *dir; - if (Cmd_Argc() == 1) - { + if (Cmd_Argc () == 1) { Con_Printf ("Current gamedir: %s\n", gamedirfile); return; } - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("Usage: gamedir \n"); return; } - dir = Cmd_Argv(1); + dir = Cmd_Argv (1); - if (strstr(dir, "..") || strstr(dir, "/") - || strstr(dir, "\\") || strstr(dir, ":") ) - { + if (strstr (dir, "..") || strstr (dir, "/") + || strstr (dir, "\\") || strstr (dir, ":")) { Con_Printf ("Gamedir should be a single filename, not a path\n"); return; } @@ -1018,8 +1013,7 @@ void COM_CreateGameDirectory (char *gamename) { if (strcmp (fs_userpath->string, FS_USERPATH)) - COM_CreatePath (va("%s/%s/dummy", fs_userpath->string, - gamename)); + COM_CreatePath (va ("%s/%s/dummy", fs_userpath->string, gamename)); COM_AddGameDirectory (gamename); } @@ -1027,9 +1021,9 @@ COM_CreateGameDirectory (char *gamename) COM_InitFilesystem */ void -COM_Filesystem_Init ( void ) +COM_Filesystem_Init (void) { - int i; + int i; Cmd_AddCommand ("gamedir", COM_Gamedir_f); @@ -1044,31 +1038,30 @@ COM_Filesystem_Init ( void ) } if ((i = COM_CheckParm ("-game")) && i < com_argc - 1) { - char *gamedirs = NULL; - char *where; + char *gamedirs = NULL; + char *where; - gamedirs = strdup (com_argv[i+1]); + gamedirs = strdup (com_argv[i + 1]); where = strtok (gamedirs, ","); while (where) { COM_CreateGameDirectory (where); where = strtok (NULL, ","); } free (gamedirs); - } - + } // any set gamedirs will be freed up to here com_base_searchpaths = com_searchpaths; } void -COM_Filesystem_Init_Cvars ( void ) +COM_Filesystem_Init_Cvars (void) { fs_sharepath = Cvar_Get ("fs_sharepath", FS_SHAREPATH, CVAR_ROM, - "location of shared (read only) game directories"); + "location of shared (read only) game directories"); fs_userpath = Cvar_Get ("fs_userpath", FS_USERPATH, CVAR_ROM, - "location of your game directories"); + "location of your game directories"); fs_basegame = Cvar_Get ("fs_basegame", BASEGAME, CVAR_ROM, - "game to use by default"); + "game to use by default"); } /* @@ -1076,15 +1069,15 @@ COM_Filesystem_Init_Cvars ( void ) COM_SkipPath ============ */ -char *COM_SkipPath (char *pathname) +char * +COM_SkipPath (char *pathname) { - char *last; - + char *last; + last = pathname; - while (*pathname) - { - if (*pathname=='/') - last = pathname+1; + while (*pathname) { + if (*pathname == '/') + last = pathname + 1; pathname++; } return last; @@ -1095,7 +1088,8 @@ char *COM_SkipPath (char *pathname) COM_StripExtension ============ */ -void COM_StripExtension (char *in, char *out) +void +COM_StripExtension (char *in, char *out) { while (*in && *in != '.') *out++ = *in++; @@ -1107,17 +1101,18 @@ void COM_StripExtension (char *in, char *out) COM_FileExtension ============ */ -char *COM_FileExtension (char *in) +char * +COM_FileExtension (char *in) { static char exten[8]; - int i; + int i; while (*in && *in != '.') in++; if (!*in) return ""; in++; - for (i=0 ; i<7 && *in ; i++,in++) + for (i = 0; i < 7 && *in; i++, in++) exten[i] = *in; exten[i] = 0; return exten; @@ -1129,21 +1124,22 @@ char *COM_FileExtension (char *in) COM_DefaultExtension ================== */ -void COM_DefaultExtension (char *path, char *extension) +void +COM_DefaultExtension (char *path, char *extension) { - char *src; + char *src; + // // if path doesn't have a .EXT, append extension // (extension should include the .) // - src = path + strlen(path) - 1; + src = path + strlen (path) - 1; - while (*src != '/' && src != path) - { + while (*src != '/' && src != path) { if (*src == '.') - return; // it has an extension + return; // it has an extension src--; } - strncat (path, extension, MAX_OSPATH - strlen (path)); + strncat (path, extension, MAX_OSPATH - strlen (path)); } diff --git a/source/quakeio.c b/source/quakeio.c index 589cc7f..95cd0ee 100644 --- a/source/quakeio.c +++ b/source/quakeio.c @@ -29,7 +29,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_MALLOC_H @@ -56,44 +56,45 @@ #include "quakefs.h" #ifdef WIN32 -#ifndef __BORLANDC__ -# define setmode _setmode -# define O_BINARY _O_BINARY -#endif +# ifndef __BORLANDC__ +# define setmode _setmode +# define O_BINARY _O_BINARY +# endif #endif void -Qexpand_squiggle(const char *path, char *dest) +Qexpand_squiggle (const char *path, char *dest) { - char *home; + char *home; + #ifndef _WIN32 struct passwd *pwd_ent; #endif - if (strncmp (path, "~/",2) != 0) { - strcpy (dest,path); + if (strncmp (path, "~/", 2) != 0) { + strcpy (dest, path); return; } - #ifndef _WIN32 - if ((pwd_ent = getpwuid (getuid()))) { + if ((pwd_ent = getpwuid (getuid ()))) { home = pwd_ent->pw_dir; } else #endif - home = getenv("HOME"); + home = getenv ("HOME"); if (home) { strcpy (dest, home); - strncat (dest, path+1, MAX_OSPATH - strlen (dest)); // skip leading ~ + strncat (dest, path + 1, MAX_OSPATH - strlen (dest)); // skip + // leading ~ } else - strcpy (dest,path); + strcpy (dest, path); } int -Qrename(const char *old, const char *new) +Qrename (const char *old, const char *new) { - char e_old[PATH_MAX]; - char e_new[PATH_MAX]; + char e_old[PATH_MAX]; + char e_new[PATH_MAX]; Qexpand_squiggle (old, e_old); Qexpand_squiggle (new, e_new); @@ -101,41 +102,41 @@ Qrename(const char *old, const char *new) } QFile * -Qopen(const char *path, const char *mode) +Qopen (const char *path, const char *mode) { - QFile *file; - char m[80],*p; - int zip=0; - char e_path[PATH_MAX]; + QFile *file; + char m[80], *p; + int zip = 0; + char e_path[PATH_MAX]; Qexpand_squiggle (path, e_path); path = e_path; - for (p=m; *mode && p-m<(sizeof(m)-1); mode++) { - if (*mode=='z') { - zip=1; + for (p = m; *mode && p - m < (sizeof (m) - 1); mode++) { + if (*mode == 'z') { + zip = 1; continue; } - *p++=*mode; + *p++ = *mode; } - *p=0; + *p = 0; - file=calloc(sizeof(*file),1); + file = calloc (sizeof (*file), 1); if (!file) return 0; #ifdef HAVE_ZLIB if (zip) { - file->gzfile=gzopen(path,m); + file->gzfile = gzopen (path, m); if (!file->gzfile) { - free(file); + free (file); return 0; } } else #endif { - file->file=fopen(path,m); + file->file = fopen (path, m); if (!file->file) { - free(file); + free (file); return 0; } } @@ -143,68 +144,68 @@ Qopen(const char *path, const char *mode) } QFile * -Qdopen(int fd, const char *mode) +Qdopen (int fd, const char *mode) { - QFile *file; - char m[80],*p; - int zip=0; + QFile *file; + char m[80], *p; + int zip = 0; - for (p=m; *mode && p-m<(sizeof(m)-1); mode++) { - if (*mode=='z') { - zip=1; + for (p = m; *mode && p - m < (sizeof (m) - 1); mode++) { + if (*mode == 'z') { + zip = 1; continue; } - *p++=*mode; + *p++ = *mode; } - *p=0; + *p = 0; - file=calloc(sizeof(*file),1); + file = calloc (sizeof (*file), 1); if (!file) return 0; #ifdef HAVE_ZLIB if (zip) { - file->gzfile=gzdopen(fd,m); + file->gzfile = gzdopen (fd, m); if (!file->gzfile) { - free(file); + free (file); return 0; } } else #endif { - file->file=fdopen(fd,m); + file->file = fdopen (fd, m); if (!file->file) { - free(file); + free (file); return 0; } } #ifdef WIN32 if (file->file) - setmode(_fileno(file->file),O_BINARY); + setmode (_fileno (file->file), O_BINARY); #endif return file; } void -Qclose(QFile *file) +Qclose (QFile *file) { if (file->file) - fclose(file->file); + fclose (file->file); #ifdef HAVE_ZLIB else - gzclose(file->gzfile); + gzclose (file->gzfile); #endif - free(file); + free (file); } int -Qread(QFile *file, void *buf, int count) +Qread (QFile *file, void *buf, int count) { if (file->file) - return fread(buf, 1, count, file->file); + return fread (buf, 1, count, file->file); #ifdef HAVE_ZLIB else - return gzread(file->gzfile,buf,count); + return gzread (file->gzfile, buf, count); #else return -1; #endif @@ -214,129 +215,131 @@ int Qwrite (QFile *file, void *buf, int count) { if (file->file) - return fwrite(buf, 1, count, file->file); + return fwrite (buf, 1, count, file->file); #ifdef HAVE_ZLIB else - return gzwrite(file->gzfile,buf,count); + return gzwrite (file->gzfile, buf, count); #else return -1; #endif } int -Qprintf(QFile *file, const char *fmt, ...) +Qprintf (QFile *file, const char *fmt, ...) { - va_list args; - int ret=-1; + va_list args; + int ret = -1; - va_start(args,fmt); + va_start (args, fmt); if (file->file) - ret=vfprintf(file->file, fmt, args); + ret = vfprintf (file->file, fmt, args); #ifdef HAVE_ZLIB else { - char buf[4096]; - va_start(args, fmt); + char buf[4096]; + + va_start (args, fmt); #ifdef HAVE_VSNPRINTF - (void)vsnprintf(buf, sizeof(buf), fmt, args); + (void) vsnprintf (buf, sizeof (buf), fmt, args); #else - (void)vsprintf(buf, fmt, args); + (void) vsprintf (buf, fmt, args); #endif - va_end(args); - ret = strlen(buf); /* some *snprintf don't return the nb of bytes written */ - if (ret>0) - ret=gzwrite(file, buf, (unsigned)ret); + va_end (args); + ret = strlen (buf); /* some *snprintf don't return the nb + of bytes written */ + if (ret > 0) + ret = gzwrite (file, buf, (unsigned) ret); } #endif - va_end(args); + va_end (args); return ret; } char * -Qgets(QFile *file, char *buf, int count) +Qgets (QFile *file, char *buf, int count) { if (file->file) - return fgets(buf, count, file->file); + return fgets (buf, count, file->file); #ifdef HAVE_ZLIB else - return gzgets(file->gzfile,buf,count); + return gzgets (file->gzfile, buf, count); #else return 0; #endif } int -Qgetc(QFile *file) +Qgetc (QFile *file) { if (file->file) - return fgetc(file->file); + return fgetc (file->file); #ifdef HAVE_ZLIB else - return gzgetc(file->gzfile); + return gzgetc (file->gzfile); #else return -1; #endif } int -Qputc(QFile *file, int c) +Qputc (QFile *file, int c) { if (file->file) - return fputc(c, file->file); + return fputc (c, file->file); #ifdef HAVE_ZLIB else - return gzputc(file->gzfile,c); + return gzputc (file->gzfile, c); #else return -1; #endif } int -Qseek(QFile *file, long offset, int whence) +Qseek (QFile *file, long offset, int whence) { if (file->file) - return fseek(file->file, offset, whence); + return fseek (file->file, offset, whence); #ifdef HAVE_ZLIB else - return gzseek(file->gzfile,offset,whence); + return gzseek (file->gzfile, offset, whence); #else return -1; #endif } long -Qtell(QFile *file) +Qtell (QFile *file) { if (file->file) - return ftell(file->file); + return ftell (file->file); #ifdef HAVE_ZLIB else - return gztell(file->gzfile); + return gztell (file->gzfile); #else return -1; #endif } int -Qflush(QFile *file) +Qflush (QFile *file) { if (file->file) - return fflush(file->file); + return fflush (file->file); #ifdef HAVE_ZLIB else - return gzflush(file->gzfile,Z_SYNC_FLUSH); + return gzflush (file->gzfile, Z_SYNC_FLUSH); #else return -1; #endif } int -Qeof(QFile *file) +Qeof (QFile *file) { if (file->file) - return feof(file->file); + return feof (file->file); #ifdef HAVE_ZLIB else - return gzeof(file->gzfile); + return gzeof (file->gzfile); #else return -1; #endif @@ -350,26 +353,27 @@ Qeof(QFile *file) */ char * -Qgetline(QFile *file) +Qgetline (QFile *file) { - static int size = 256; + static int size = 256; static char *buf = 0; - int len; + int len; if (!buf) buf = malloc (size); - if (!Qgets(file, buf, size)) + if (!Qgets (file, buf, size)) return 0; len = strlen (buf); while (buf[len - 1] != '\n') { - char *t = realloc (buf, size + 256); + char *t = realloc (buf, size + 256); + if (!t) return 0; buf = t; size += 256; - if (!Qgets(file, buf+len, size - len)) + if (!Qgets (file, buf + len, size - len)) break; len = strlen (buf); } diff --git a/source/r_aclip.c b/source/r_aclip.c index 6a636c7..e06de77 100644 --- a/source/r_aclip.c +++ b/source/r_aclip.c @@ -27,23 +27,27 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" #include "d_local.h" -static finalvert_t fv[2][8]; -static auxvert_t av[8]; +static finalvert_t fv[2][8]; +static auxvert_t av[8]; -void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av); -void R_Alias_clip_top (finalvert_t *pfv0, finalvert_t *pfv1, - finalvert_t *out); -void R_Alias_clip_bottom (finalvert_t *pfv0, finalvert_t *pfv1, - finalvert_t *out); -void R_Alias_clip_left (finalvert_t *pfv0, finalvert_t *pfv1, - finalvert_t *out); -void R_Alias_clip_right (finalvert_t *pfv0, finalvert_t *pfv1, - finalvert_t *out); +void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av); +void R_Alias_clip_top (finalvert_t *pfv0, finalvert_t *pfv1, + + finalvert_t *out); +void R_Alias_clip_bottom (finalvert_t *pfv0, finalvert_t *pfv1, + + finalvert_t *out); +void R_Alias_clip_left (finalvert_t *pfv0, finalvert_t *pfv1, + + finalvert_t *out); +void R_Alias_clip_right (finalvert_t *pfv0, finalvert_t *pfv1, + + finalvert_t *out); /* @@ -53,39 +57,37 @@ R_Alias_clip_z pfv0 is the unclipped vertex, pfv1 is the z-clipped vertex ================ */ -void R_Alias_clip_z (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) +void +R_Alias_clip_z (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) { - float scale; - auxvert_t *pav0, *pav1, avout; + float scale; + auxvert_t *pav0, *pav1, avout; pav0 = &av[pfv0 - &fv[0][0]]; pav1 = &av[pfv1 - &fv[0][0]]; - if (pfv0->v[1] >= pfv1->v[1]) - { + if (pfv0->v[1] >= pfv1->v[1]) { scale = (ALIAS_Z_CLIP_PLANE - pav0->fv[2]) / - (pav1->fv[2] - pav0->fv[2]); - + (pav1->fv[2] - pav0->fv[2]); + avout.fv[0] = pav0->fv[0] + (pav1->fv[0] - pav0->fv[0]) * scale; avout.fv[1] = pav0->fv[1] + (pav1->fv[1] - pav0->fv[1]) * scale; avout.fv[2] = ALIAS_Z_CLIP_PLANE; - - out->v[2] = pfv0->v[2] + (pfv1->v[2] - pfv0->v[2]) * scale; - out->v[3] = pfv0->v[3] + (pfv1->v[3] - pfv0->v[3]) * scale; - out->v[4] = pfv0->v[4] + (pfv1->v[4] - pfv0->v[4]) * scale; - } - else - { + + out->v[2] = pfv0->v[2] + (pfv1->v[2] - pfv0->v[2]) * scale; + out->v[3] = pfv0->v[3] + (pfv1->v[3] - pfv0->v[3]) * scale; + out->v[4] = pfv0->v[4] + (pfv1->v[4] - pfv0->v[4]) * scale; + } else { scale = (ALIAS_Z_CLIP_PLANE - pav1->fv[2]) / - (pav0->fv[2] - pav1->fv[2]); - + (pav0->fv[2] - pav1->fv[2]); + avout.fv[0] = pav1->fv[0] + (pav0->fv[0] - pav1->fv[0]) * scale; avout.fv[1] = pav1->fv[1] + (pav0->fv[1] - pav1->fv[1]) * scale; avout.fv[2] = ALIAS_Z_CLIP_PLANE; - - out->v[2] = pfv1->v[2] + (pfv0->v[2] - pfv1->v[2]) * scale; - out->v[3] = pfv1->v[3] + (pfv0->v[3] - pfv1->v[3]) * scale; - out->v[4] = pfv1->v[4] + (pfv0->v[4] - pfv1->v[4]) * scale; + + out->v[2] = pfv1->v[2] + (pfv0->v[2] - pfv1->v[2]) * scale; + out->v[3] = pfv1->v[3] + (pfv0->v[3] - pfv1->v[3]) * scale; + out->v[4] = pfv1->v[4] + (pfv0->v[4] - pfv1->v[4]) * scale; } R_AliasProjectFinalVert (out, &avout); @@ -97,123 +99,113 @@ void R_Alias_clip_z (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) if (out->v[0] > r_refdef.aliasvrectright) out->flags |= ALIAS_RIGHT_CLIP; if (out->v[1] > r_refdef.aliasvrectbottom) - out->flags |= ALIAS_BOTTOM_CLIP; + out->flags |= ALIAS_BOTTOM_CLIP; } #ifndef USE_INTEL_ASM -void R_Alias_clip_left (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) +void +R_Alias_clip_left (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) { - float scale; - int i; + float scale; + int i; - if (pfv0->v[1] >= pfv1->v[1]) - { - scale = (float)(r_refdef.aliasvrect.x - pfv0->v[0]) / - (pfv1->v[0] - pfv0->v[0]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i])*scale + 0.5; - } - else - { - scale = (float)(r_refdef.aliasvrect.x - pfv1->v[0]) / - (pfv0->v[0] - pfv1->v[0]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i])*scale + 0.5; + if (pfv0->v[1] >= pfv1->v[1]) { + scale = (float) (r_refdef.aliasvrect.x - pfv0->v[0]) / + (pfv1->v[0] - pfv0->v[0]); + for (i = 0; i < 6; i++) + out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i]) * scale + 0.5; + } else { + scale = (float) (r_refdef.aliasvrect.x - pfv1->v[0]) / + (pfv0->v[0] - pfv1->v[0]); + for (i = 0; i < 6; i++) + out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i]) * scale + 0.5; } } -void R_Alias_clip_right (finalvert_t *pfv0, finalvert_t *pfv1, - finalvert_t *out) +void +R_Alias_clip_right (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) { - float scale; - int i; + float scale; + int i; - if (pfv0->v[1] >= pfv1->v[1]) - { - scale = (float)(r_refdef.aliasvrectright - pfv0->v[0]) / - (pfv1->v[0] - pfv0->v[0]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i])*scale + 0.5; - } - else - { - scale = (float)(r_refdef.aliasvrectright - pfv1->v[0]) / - (pfv0->v[0] - pfv1->v[0]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i])*scale + 0.5; + if (pfv0->v[1] >= pfv1->v[1]) { + scale = (float) (r_refdef.aliasvrectright - pfv0->v[0]) / + (pfv1->v[0] - pfv0->v[0]); + for (i = 0; i < 6; i++) + out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i]) * scale + 0.5; + } else { + scale = (float) (r_refdef.aliasvrectright - pfv1->v[0]) / + (pfv0->v[0] - pfv1->v[0]); + for (i = 0; i < 6; i++) + out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i]) * scale + 0.5; } } -void R_Alias_clip_top (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) +void +R_Alias_clip_top (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) { - float scale; - int i; + float scale; + int i; - if (pfv0->v[1] >= pfv1->v[1]) - { - scale = (float)(r_refdef.aliasvrect.y - pfv0->v[1]) / - (pfv1->v[1] - pfv0->v[1]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i])*scale + 0.5; - } - else - { - scale = (float)(r_refdef.aliasvrect.y - pfv1->v[1]) / - (pfv0->v[1] - pfv1->v[1]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i])*scale + 0.5; + if (pfv0->v[1] >= pfv1->v[1]) { + scale = (float) (r_refdef.aliasvrect.y - pfv0->v[1]) / + (pfv1->v[1] - pfv0->v[1]); + for (i = 0; i < 6; i++) + out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i]) * scale + 0.5; + } else { + scale = (float) (r_refdef.aliasvrect.y - pfv1->v[1]) / + (pfv0->v[1] - pfv1->v[1]); + for (i = 0; i < 6; i++) + out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i]) * scale + 0.5; } } -void R_Alias_clip_bottom (finalvert_t *pfv0, finalvert_t *pfv1, - finalvert_t *out) +void +R_Alias_clip_bottom (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) { - float scale; - int i; + float scale; + int i; - if (pfv0->v[1] >= pfv1->v[1]) - { - scale = (float)(r_refdef.aliasvrectbottom - pfv0->v[1]) / - (pfv1->v[1] - pfv0->v[1]); + if (pfv0->v[1] >= pfv1->v[1]) { + scale = (float) (r_refdef.aliasvrectbottom - pfv0->v[1]) / + (pfv1->v[1] - pfv0->v[1]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i])*scale + 0.5; - } - else - { - scale = (float)(r_refdef.aliasvrectbottom - pfv1->v[1]) / - (pfv0->v[1] - pfv1->v[1]); + for (i = 0; i < 6; i++) + out->v[i] = pfv0->v[i] + (pfv1->v[i] - pfv0->v[i]) * scale + 0.5; + } else { + scale = (float) (r_refdef.aliasvrectbottom - pfv1->v[1]) / + (pfv0->v[1] - pfv1->v[1]); - for (i=0 ; i<6 ; i++) - out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i])*scale + 0.5; + for (i = 0; i < 6; i++) + out->v[i] = pfv1->v[i] + (pfv0->v[i] - pfv1->v[i]) * scale + 0.5; } } #endif -int R_AliasClip (finalvert_t *in, finalvert_t *out, int flag, int count, - void(*clip)(finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out) ) +int +R_AliasClip (finalvert_t *in, finalvert_t *out, int flag, int count, + void (*clip) (finalvert_t *pfv0, finalvert_t *pfv1, + finalvert_t *out)) { - int i,j,k; - int flags, oldflags; - - j = count-1; + int i, j, k; + int flags, oldflags; + + j = count - 1; k = 0; - for (i=0 ; i r_refdef.aliasvrectright) out[k].flags |= ALIAS_RIGHT_CLIP; if (out[k].v[1] > r_refdef.aliasvrectbottom) - out[k].flags |= ALIAS_BOTTOM_CLIP; + out[k].flags |= ALIAS_BOTTOM_CLIP; k++; } - if (!flags) - { + if (!flags) { out[k] = in[i]; k++; } } - + return k; } @@ -242,26 +233,23 @@ int R_AliasClip (finalvert_t *in, finalvert_t *out, int flag, int count, R_AliasClipTriangle ================ */ -void R_AliasClipTriangle (mtriangle_t *ptri) +void +R_AliasClipTriangle (mtriangle_t *ptri) { - int i, k, pingpong; - mtriangle_t mtri; - unsigned int clipflags; + int i, k, pingpong; + mtriangle_t mtri; + unsigned int clipflags; // copy vertexes and fix seam texture coordinates - if (ptri->facesfront) - { + if (ptri->facesfront) { fv[0][0] = pfinalverts[ptri->vertindex[0]]; fv[0][1] = pfinalverts[ptri->vertindex[1]]; fv[0][2] = pfinalverts[ptri->vertindex[2]]; - } - else - { - for (i=0 ; i<3 ; i++) - { + } else { + for (i = 0; i < 3; i++) { fv[0][i] = pfinalverts[ptri->vertindex[i]]; - - if (!ptri->facesfront && (fv[0][i].flags & ALIAS_ONSEAM) ) + + if (!ptri->facesfront && (fv[0][i].flags & ALIAS_ONSEAM)) fv[0][i].v[2] += r_affinetridesc.seamfixupX16; } } @@ -269,9 +257,8 @@ void R_AliasClipTriangle (mtriangle_t *ptri) // clip clipflags = fv[0][0].flags | fv[0][1].flags | fv[0][2].flags; - if (clipflags & ALIAS_Z_CLIP) - { - for (i=0 ; i<3 ; i++) + if (clipflags & ALIAS_Z_CLIP) { + for (i = 0; i < 3; i++) av[i] = pauxverts[ptri->vertindex[i]]; k = R_AliasClip (fv[0], fv[1], ALIAS_Z_CLIP, 3, R_Alias_clip_z); @@ -280,55 +267,48 @@ void R_AliasClipTriangle (mtriangle_t *ptri) pingpong = 1; clipflags = fv[1][0].flags | fv[1][1].flags | fv[1][2].flags; - } - else - { + } else { pingpong = 0; k = 3; } - if (clipflags & ALIAS_LEFT_CLIP) - { + if (clipflags & ALIAS_LEFT_CLIP) { k = R_AliasClip (fv[pingpong], fv[pingpong ^ 1], - ALIAS_LEFT_CLIP, k, R_Alias_clip_left); + ALIAS_LEFT_CLIP, k, R_Alias_clip_left); if (k == 0) return; pingpong ^= 1; } - if (clipflags & ALIAS_RIGHT_CLIP) - { + if (clipflags & ALIAS_RIGHT_CLIP) { k = R_AliasClip (fv[pingpong], fv[pingpong ^ 1], - ALIAS_RIGHT_CLIP, k, R_Alias_clip_right); + ALIAS_RIGHT_CLIP, k, R_Alias_clip_right); if (k == 0) return; pingpong ^= 1; } - if (clipflags & ALIAS_BOTTOM_CLIP) - { + if (clipflags & ALIAS_BOTTOM_CLIP) { k = R_AliasClip (fv[pingpong], fv[pingpong ^ 1], - ALIAS_BOTTOM_CLIP, k, R_Alias_clip_bottom); + ALIAS_BOTTOM_CLIP, k, R_Alias_clip_bottom); if (k == 0) return; pingpong ^= 1; } - if (clipflags & ALIAS_TOP_CLIP) - { + if (clipflags & ALIAS_TOP_CLIP) { k = R_AliasClip (fv[pingpong], fv[pingpong ^ 1], - ALIAS_TOP_CLIP, k, R_Alias_clip_top); + ALIAS_TOP_CLIP, k, R_Alias_clip_top); if (k == 0) return; pingpong ^= 1; } - for (i=0 ; i r_refdef.aliasvrectright) @@ -349,11 +329,9 @@ void R_AliasClipTriangle (mtriangle_t *ptri) // FIXME: do all at once as trifan? mtri.vertindex[0] = 0; - for (i=1 ; i +# include "config.h" #endif #include "sys.h" #include "console.h" @@ -35,61 +35,63 @@ #include "r_local.h" #include "skin.h" -#define LIGHT_MIN 5 // lowest light value we'll allow, to avoid the - // need for inner-loop light clamping +#define LIGHT_MIN 5 // lowest light value we'll allow, to + // avoid the + // need for inner-loop light clamping -mtriangle_t *ptriangles; -affinetridesc_t r_affinetridesc; +mtriangle_t *ptriangles; +affinetridesc_t r_affinetridesc; -void * acolormap; // FIXME: should go away +void *acolormap; // FIXME: should go away -trivertx_t *r_apverts; +trivertx_t *r_apverts; // TODO: these probably will go away with optimized rasterization -mdl_t *pmdl; -vec3_t r_plightvec; -int r_ambientlight; -float r_shadelight; -aliashdr_t *paliashdr; -finalvert_t *pfinalverts; -auxvert_t *pauxverts; -static float ziscale; -static model_t *pmodel; +mdl_t *pmdl; +vec3_t r_plightvec; +int r_ambientlight; +float r_shadelight; +aliashdr_t *paliashdr; +finalvert_t *pfinalverts; +auxvert_t *pauxverts; +static float ziscale; +static model_t *pmodel; -static vec3_t alias_forward, alias_right, alias_up; +static vec3_t alias_forward, alias_right, alias_up; -static maliasskindesc_t *pskindesc; +static maliasskindesc_t *pskindesc; -int r_amodels_drawn; -int a_skinwidth; -int r_anumverts; +int r_amodels_drawn; +int a_skinwidth; +int r_anumverts; -float aliastransform[3][4]; +float aliastransform[3][4]; typedef struct { - int index0; - int index1; + int index0; + int index1; } aedge_t; -static aedge_t aedges[12] = { -{0, 1}, {1, 2}, {2, 3}, {3, 0}, -{4, 5}, {5, 6}, {6, 7}, {7, 4}, -{0, 5}, {1, 4}, {2, 7}, {3, 6} +static aedge_t aedges[12] = { + {0, 1}, {1, 2}, {2, 3}, {3, 0}, + {4, 5}, {5, 6}, {6, 7}, {7, 4}, + {0, 5}, {1, 4}, {2, 7}, {3, 6} }; #define NUMVERTEXNORMALS 162 -float r_avertexnormals[NUMVERTEXNORMALS][3] = { +float r_avertexnormals[NUMVERTEXNORMALS][3] = { #include "anorms.h" }; -void R_AliasTransformAndProjectFinalVerts (finalvert_t *fv, - stvert_t *pstverts); -void R_AliasSetUpTransform (int trivial_accept); -void R_AliasTransformVector (vec3_t in, vec3_t out); -void R_AliasTransformFinalVert (finalvert_t *fv, auxvert_t *av, - trivertx_t *pverts, stvert_t *pstverts); -void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av); +void R_AliasTransformAndProjectFinalVerts (finalvert_t *fv, + + stvert_t *pstverts); +void R_AliasSetUpTransform (int trivial_accept); +void R_AliasTransformVector (vec3_t in, vec3_t out); +void R_AliasTransformFinalVert (finalvert_t *fv, auxvert_t *av, + trivertx_t *pverts, stvert_t *pstverts); +void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av); /* @@ -97,34 +99,33 @@ void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av); R_AliasCheckBBox ================ */ -qboolean R_AliasCheckBBox (void) +qboolean +R_AliasCheckBBox (void) { - int i, flags, frame, numv; - aliashdr_t *pahdr; - float zi, basepts[8][3], v0, v1, frac; - finalvert_t *pv0, *pv1, viewpts[16]; - auxvert_t *pa0, *pa1, viewaux[16]; - maliasframedesc_t *pframedesc; - qboolean zclipped, zfullyclipped; - unsigned int anyclip, allclip; - int minz; - + int i, flags, frame, numv; + aliashdr_t *pahdr; + float zi, basepts[8][3], v0, v1, frac; + finalvert_t *pv0, *pv1, viewpts[16]; + auxvert_t *pa0, *pa1, viewaux[16]; + maliasframedesc_t *pframedesc; + qboolean zclipped, zfullyclipped; + unsigned int anyclip, allclip; + int minz; + // expand, rotate, and translate points into worldspace currententity->trivial_accept = 0; pmodel = currententity->model; pahdr = Mod_Extradata (pmodel); - pmdl = (mdl_t *)((byte *)pahdr + pahdr->model); + pmdl = (mdl_t *) ((byte *) pahdr + pahdr->model); R_AliasSetUpTransform (0); // construct the base bounding box for this frame frame = currententity->frame; // TODO: don't repeat this check when drawing? - if ((frame >= pmdl->numframes) || (frame < 0)) - { - Con_DPrintf ("No such frame %d %s\n", frame, - pmodel->name); + if ((frame >= pmdl->numframes) || (frame < 0)) { + Con_DPrintf ("No such frame %d %s\n", frame, pmodel->name); frame = 0; } @@ -132,38 +133,34 @@ qboolean R_AliasCheckBBox (void) // x worldspace coordinates basepts[0][0] = basepts[1][0] = basepts[2][0] = basepts[3][0] = - (float)pframedesc->bboxmin.v[0]; + (float) pframedesc->bboxmin.v[0]; basepts[4][0] = basepts[5][0] = basepts[6][0] = basepts[7][0] = - (float)pframedesc->bboxmax.v[0]; + (float) pframedesc->bboxmax.v[0]; // y worldspace coordinates basepts[0][1] = basepts[3][1] = basepts[5][1] = basepts[6][1] = - (float)pframedesc->bboxmin.v[1]; + (float) pframedesc->bboxmin.v[1]; basepts[1][1] = basepts[2][1] = basepts[4][1] = basepts[7][1] = - (float)pframedesc->bboxmax.v[1]; + (float) pframedesc->bboxmax.v[1]; // z worldspace coordinates basepts[0][2] = basepts[1][2] = basepts[4][2] = basepts[5][2] = - (float)pframedesc->bboxmin.v[2]; + (float) pframedesc->bboxmin.v[2]; basepts[2][2] = basepts[3][2] = basepts[6][2] = basepts[7][2] = - (float)pframedesc->bboxmax.v[2]; + (float) pframedesc->bboxmax.v[2]; zclipped = false; zfullyclipped = true; minz = 9999; - for (i=0; i<8 ; i++) - { - R_AliasTransformVector (&basepts[i][0], &viewaux[i].fv[0]); + for (i = 0; i < 8; i++) { + R_AliasTransformVector (&basepts[i][0], &viewaux[i].fv[0]); - if (viewaux[i].fv[2] < ALIAS_Z_CLIP_PLANE) - { - // we must clip points that are closer than the near clip plane + if (viewaux[i].fv[2] < ALIAS_Z_CLIP_PLANE) { + // we must clip points that are closer than the near clip plane viewpts[i].flags = ALIAS_Z_CLIP; zclipped = true; - } - else - { + } else { if (viewaux[i].fv[2] < minz) minz = viewaux[i].fv[2]; viewpts[i].flags = 0; @@ -171,56 +168,51 @@ qboolean R_AliasCheckBBox (void) } } - - if (zfullyclipped) - { - return false; // everything was near-z-clipped + + if (zfullyclipped) { + return false; // everything was near-z-clipped } numv = 8; - if (zclipped) - { - // organize points by edges, use edges to get new points (possible trivial - // reject) - for (i=0 ; i<12 ; i++) - { - // edge endpoints + if (zclipped) { + // organize points by edges, use edges to get new points (possible + // trivial + // reject) + for (i = 0; i < 12; i++) { + // edge endpoints pv0 = &viewpts[aedges[i].index0]; pv1 = &viewpts[aedges[i].index1]; pa0 = &viewaux[aedges[i].index0]; pa1 = &viewaux[aedges[i].index1]; - // if one end is clipped and the other isn't, make a new point - if (pv0->flags ^ pv1->flags) - { + // if one end is clipped and the other isn't, make a new point + if (pv0->flags ^ pv1->flags) { frac = (ALIAS_Z_CLIP_PLANE - pa0->fv[2]) / - (pa1->fv[2] - pa0->fv[2]); + (pa1->fv[2] - pa0->fv[2]); viewaux[numv].fv[0] = pa0->fv[0] + - (pa1->fv[0] - pa0->fv[0]) * frac; + (pa1->fv[0] - pa0->fv[0]) * frac; viewaux[numv].fv[1] = pa0->fv[1] + - (pa1->fv[1] - pa0->fv[1]) * frac; + (pa1->fv[1] - pa0->fv[1]) * frac; viewaux[numv].fv[2] = ALIAS_Z_CLIP_PLANE; viewpts[numv].flags = 0; numv++; } } } - // project the vertices that remain after clipping anyclip = 0; allclip = ALIAS_XY_CLIP_MASK; // TODO: probably should do this loop in ASM, especially if we use floats - for (i=0 ; itrivial_accept = !anyclip & !zclipped; - if (currententity->trivial_accept) - { - if (minz > (r_aliastransition + (pmdl->size * r_resfudge))) - { + if (currententity->trivial_accept) { + if (minz > (r_aliastransition + (pmdl->size * r_resfudge))) { currententity->trivial_accept |= 2; } } @@ -261,11 +251,12 @@ qboolean R_AliasCheckBBox (void) R_AliasTransformVector ================ */ -void R_AliasTransformVector (vec3_t in, vec3_t out) +void +R_AliasTransformVector (vec3_t in, vec3_t out) { - out[0] = DotProduct(in, aliastransform[0]) + aliastransform[0][3]; - out[1] = DotProduct(in, aliastransform[1]) + aliastransform[1][3]; - out[2] = DotProduct(in, aliastransform[2]) + aliastransform[2][3]; + out[0] = DotProduct (in, aliastransform[0]) + aliastransform[0][3]; + out[1] = DotProduct (in, aliastransform[1]) + aliastransform[1][3]; + out[2] = DotProduct (in, aliastransform[2]) + aliastransform[2][3]; } @@ -276,28 +267,27 @@ R_AliasPreparePoints General clipped case ================ */ -void R_AliasPreparePoints (void) +void +R_AliasPreparePoints (void) { - int i; - stvert_t *pstverts; - finalvert_t *fv; - auxvert_t *av; - mtriangle_t *ptri; - finalvert_t *pfv[3]; + int i; + stvert_t *pstverts; + finalvert_t *fv; + auxvert_t *av; + mtriangle_t *ptri; + finalvert_t *pfv[3]; - pstverts = (stvert_t *)((byte *)paliashdr + paliashdr->stverts); + pstverts = (stvert_t *) ((byte *) paliashdr + paliashdr->stverts); r_anumverts = pmdl->numverts; - fv = pfinalverts; + fv = pfinalverts; av = pauxverts; - for (i=0 ; ifv[2] < ALIAS_Z_CLIP_PLANE) fv->flags |= ALIAS_Z_CLIP; - else - { - R_AliasProjectFinalVert (fv, av); + else { + R_AliasProjectFinalVert (fv, av); if (fv->v[0] < r_refdef.aliasvrect.x) fv->flags |= ALIAS_LEFT_CLIP; @@ -306,7 +296,7 @@ void R_AliasPreparePoints (void) if (fv->v[0] > r_refdef.aliasvrectright) fv->flags |= ALIAS_RIGHT_CLIP; if (fv->v[1] > r_refdef.aliasvrectbottom) - fv->flags |= ALIAS_BOTTOM_CLIP; + fv->flags |= ALIAS_BOTTOM_CLIP; } } @@ -315,25 +305,22 @@ void R_AliasPreparePoints (void) // r_affinetridesc.numtriangles = 1; - ptri = (mtriangle_t *)((byte *)paliashdr + paliashdr->triangles); - for (i=0 ; inumtris ; i++, ptri++) - { + ptri = (mtriangle_t *) ((byte *) paliashdr + paliashdr->triangles); + for (i = 0; i < pmdl->numtris; i++, ptri++) { pfv[0] = &pfinalverts[ptri->vertindex[0]]; pfv[1] = &pfinalverts[ptri->vertindex[1]]; pfv[2] = &pfinalverts[ptri->vertindex[2]]; - if ( pfv[0]->flags & pfv[1]->flags & pfv[2]->flags & (ALIAS_XY_CLIP_MASK | ALIAS_Z_CLIP) ) - continue; // completely clipped - - if ( ! ( (pfv[0]->flags | pfv[1]->flags | pfv[2]->flags) & - (ALIAS_XY_CLIP_MASK | ALIAS_Z_CLIP) ) ) - { // totally unclipped + if (pfv[0]->flags & pfv[1]->flags & pfv[2]-> + flags & (ALIAS_XY_CLIP_MASK | ALIAS_Z_CLIP)) + continue; // completely clipped + + if (!((pfv[0]->flags | pfv[1]->flags | pfv[2]->flags) & + (ALIAS_XY_CLIP_MASK | ALIAS_Z_CLIP))) { // totally unclipped r_affinetridesc.pfinalverts = pfinalverts; r_affinetridesc.ptriangles = ptri; D_PolysetDraw (); - } - else - { // partially clipped + } else { // partially clipped R_AliasClipTriangle (ptri); } } @@ -345,13 +332,14 @@ void R_AliasPreparePoints (void) R_AliasSetUpTransform ================ */ -void R_AliasSetUpTransform (int trivial_accept) +void +R_AliasSetUpTransform (int trivial_accept) { - int i; - float rotationmatrix[3][4], t2matrix[3][4]; - static float tmatrix[3][4]; - static float viewmatrix[3][4]; - vec3_t angles; + int i; + float rotationmatrix[3][4], t2matrix[3][4]; + static float tmatrix[3][4]; + static float viewmatrix[3][4]; + vec3_t angles; // TODO: should really be stored with the entity instead of being reconstructed // TODO: should use a look-up table @@ -372,8 +360,7 @@ void R_AliasSetUpTransform (int trivial_accept) // TODO: can do this with simple matrix rearrangement - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { t2matrix[i][0] = alias_forward[i]; t2matrix[i][1] = -alias_right[i]; t2matrix[i][2] = alias_up[i]; @@ -392,9 +379,9 @@ void R_AliasSetUpTransform (int trivial_accept) VectorInverse (viewmatrix[1]); VectorCopy (vpn, viewmatrix[2]); -// viewmatrix[0][3] = 0; -// viewmatrix[1][3] = 0; -// viewmatrix[2][3] = 0; +// viewmatrix[0][3] = 0; +// viewmatrix[1][3] = 0; +// viewmatrix[2][3] = 0; R_ConcatTransforms (viewmatrix, rotationmatrix, aliastransform); @@ -403,15 +390,13 @@ void R_AliasSetUpTransform (int trivial_accept) // Also scale down z, so 1/z is scaled 31 bits for free, and scale down x and y // correspondingly so the projected x and y come out right // FIXME: make this work for clipped case too? - if (trivial_accept) - { - for (i=0 ; i<4 ; i++) - { + if (trivial_accept) { + for (i = 0; i < 4; i++) { aliastransform[0][i] *= aliasxscale * - (1.0 / ((float)0x8000 * 0x10000)); + (1.0 / ((float) 0x8000 * 0x10000)); aliastransform[1][i] *= aliasyscale * - (1.0 / ((float)0x8000 * 0x10000)); - aliastransform[2][i] *= 1.0 / ((float)0x8000 * 0x10000); + (1.0 / ((float) 0x8000 * 0x10000)); + aliastransform[2][i] *= 1.0 / ((float) 0x8000 * 0x10000); } } @@ -423,18 +408,19 @@ void R_AliasSetUpTransform (int trivial_accept) R_AliasTransformFinalVert ================ */ -void R_AliasTransformFinalVert (finalvert_t *fv, auxvert_t *av, - trivertx_t *pverts, stvert_t *pstverts) +void +R_AliasTransformFinalVert (finalvert_t *fv, auxvert_t *av, + trivertx_t *pverts, stvert_t *pstverts) { - int temp; - float lightcos, *plightnormal; + int temp; + float lightcos, *plightnormal; - av->fv[0] = DotProduct(pverts->v, aliastransform[0]) + - aliastransform[0][3]; - av->fv[1] = DotProduct(pverts->v, aliastransform[1]) + - aliastransform[1][3]; - av->fv[2] = DotProduct(pverts->v, aliastransform[2]) + - aliastransform[2][3]; + av->fv[0] = DotProduct (pverts->v, aliastransform[0]) + + aliastransform[0][3]; + av->fv[1] = DotProduct (pverts->v, aliastransform[1]) + + aliastransform[1][3]; + av->fv[2] = DotProduct (pverts->v, aliastransform[2]) + + aliastransform[2][3]; fv->v[2] = pstverts->s; fv->v[3] = pstverts->t; @@ -446,12 +432,12 @@ void R_AliasTransformFinalVert (finalvert_t *fv, auxvert_t *av, lightcos = DotProduct (plightnormal, r_plightvec); temp = r_ambientlight; - if (lightcos < 0) - { - temp += (int)(r_shadelight * lightcos); + if (lightcos < 0) { + temp += (int) (r_shadelight * lightcos); - // clamp; because we limited the minimum ambient and shading light, we - // don't have to clamp low light, just bright + // clamp; because we limited the minimum ambient and shading light, + // we + // don't have to clamp low light, just bright if (temp < 0) temp = 0; } @@ -467,45 +453,46 @@ void R_AliasTransformFinalVert (finalvert_t *fv, auxvert_t *av, R_AliasTransformAndProjectFinalVerts ================ */ -void R_AliasTransformAndProjectFinalVerts (finalvert_t *fv, stvert_t *pstverts) +void +R_AliasTransformAndProjectFinalVerts (finalvert_t *fv, stvert_t *pstverts) { - int i, temp; - float lightcos, *plightnormal, zi; - trivertx_t *pverts; + int i, temp; + float lightcos, *plightnormal, zi; + trivertx_t *pverts; pverts = r_apverts; - for (i=0 ; iv, aliastransform[2]) + - aliastransform[2][3]); + for (i = 0; i < r_anumverts; i++, fv++, pverts++, pstverts++) { + // transform and project + zi = 1.0 / (DotProduct (pverts->v, aliastransform[2]) + + aliastransform[2][3]); - // x, y, and z are scaled down by 1/2**31 in the transform, so 1/z is - // scaled up by 1/2**31, and the scaling cancels out for x and y in the - // projection + // x, y, and z are scaled down by 1/2**31 in the transform, so 1/z is + // scaled up by 1/2**31, and the scaling cancels out for x and y in + // the + // projection fv->v[5] = zi; - fv->v[0] = ((DotProduct(pverts->v, aliastransform[0]) + - aliastransform[0][3]) * zi) + aliasxcenter; - fv->v[1] = ((DotProduct(pverts->v, aliastransform[1]) + - aliastransform[1][3]) * zi) + aliasycenter; + fv->v[0] = ((DotProduct (pverts->v, aliastransform[0]) + + aliastransform[0][3]) * zi) + aliasxcenter; + fv->v[1] = ((DotProduct (pverts->v, aliastransform[1]) + + aliastransform[1][3]) * zi) + aliasycenter; fv->v[2] = pstverts->s; fv->v[3] = pstverts->t; fv->flags = pstverts->onseam; - // lighting + // lighting plightnormal = r_avertexnormals[pverts->lightnormalindex]; lightcos = DotProduct (plightnormal, r_plightvec); temp = r_ambientlight; - if (lightcos < 0) - { - temp += (int)(r_shadelight * lightcos); + if (lightcos < 0) { + temp += (int) (r_shadelight * lightcos); - // clamp; because we limited the minimum ambient and shading light, we - // don't have to clamp low light, just bright + // clamp; because we limited the minimum ambient and shading + // light, we + // don't have to clamp low light, just bright if (temp < 0) temp = 0; } @@ -522,9 +509,10 @@ void R_AliasTransformAndProjectFinalVerts (finalvert_t *fv, stvert_t *pstverts) R_AliasProjectFinalVert ================ */ -void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av) +void +R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av) { - float zi; + float zi; // project points zi = 1.0 / av->fv[2]; @@ -541,12 +529,13 @@ void R_AliasProjectFinalVert (finalvert_t *fv, auxvert_t *av) R_AliasPrepareUnclippedPoints ================ */ -void R_AliasPrepareUnclippedPoints (void) +void +R_AliasPrepareUnclippedPoints (void) { - stvert_t *pstverts; - finalvert_t *fv; + stvert_t *pstverts; + finalvert_t *fv; - pstverts = (stvert_t *)((byte *)paliashdr + paliashdr->stverts); + pstverts = (stvert_t *) ((byte *) paliashdr + paliashdr->stverts); r_anumverts = pmdl->numverts; // FIXME: just use pfinalverts directly? fv = pfinalverts; @@ -558,7 +547,7 @@ void R_AliasPrepareUnclippedPoints (void) r_affinetridesc.pfinalverts = pfinalverts; r_affinetridesc.ptriangles = (mtriangle_t *) - ((byte *)paliashdr + paliashdr->triangles); + ((byte *) paliashdr + paliashdr->triangles); r_affinetridesc.numtriangles = pmdl->numtris; D_PolysetDraw (); @@ -569,65 +558,61 @@ void R_AliasPrepareUnclippedPoints (void) R_AliasSetupSkin =============== */ -void R_AliasSetupSkin (void) +void +R_AliasSetupSkin (void) { - int skinnum; - int i, numskins; - maliasskingroup_t *paliasskingroup; - float *pskinintervals, fullskininterval; - float skintargettime, skintime; + int skinnum; + int i, numskins; + maliasskingroup_t *paliasskingroup; + float *pskinintervals, fullskininterval; + float skintargettime, skintime; skinnum = currententity->skinnum; - if ((skinnum >= pmdl->numskins) || (skinnum < 0)) - { + if ((skinnum >= pmdl->numskins) || (skinnum < 0)) { Con_DPrintf ("R_AliasSetupSkin: no such skin # %d\n", skinnum); skinnum = 0; } pskindesc = ((maliasskindesc_t *) - ((byte *)paliashdr + paliashdr->skindesc)) + skinnum; + ((byte *) paliashdr + paliashdr->skindesc)) + skinnum; a_skinwidth = pmdl->skinwidth; - if (pskindesc->type == ALIAS_SKIN_GROUP) - { - paliasskingroup = (maliasskingroup_t *)((byte *)paliashdr + - pskindesc->skin); + if (pskindesc->type == ALIAS_SKIN_GROUP) { + paliasskingroup = (maliasskingroup_t *) ((byte *) paliashdr + + pskindesc->skin); pskinintervals = (float *) - ((byte *)paliashdr + paliasskingroup->intervals); + ((byte *) paliashdr + paliasskingroup->intervals); numskins = paliasskingroup->numskins; - fullskininterval = pskinintervals[numskins-1]; - + fullskininterval = pskinintervals[numskins - 1]; + skintime = cl.time + currententity->syncbase; - - // when loading in Mod_LoadAliasSkinGroup, we guaranteed all interval - // values are positive, so we don't have to worry about division by 0 + + // when loading in Mod_LoadAliasSkinGroup, we guaranteed all interval + // values are positive, so we don't have to worry about division by 0 skintargettime = skintime - - ((int)(skintime / fullskininterval)) * fullskininterval; - - for (i=0 ; i<(numskins-1) ; i++) - { + ((int) (skintime / fullskininterval)) * fullskininterval; + + for (i = 0; i < (numskins - 1); i++) { if (pskinintervals[i] > skintargettime) break; } - + pskindesc = &paliasskingroup->skindescs[i]; } r_affinetridesc.pskindesc = pskindesc; - r_affinetridesc.pskin = (void *)((byte *)paliashdr + pskindesc->skin); + r_affinetridesc.pskin = (void *) ((byte *) paliashdr + pskindesc->skin); r_affinetridesc.skinwidth = a_skinwidth; - r_affinetridesc.seamfixupX16 = (a_skinwidth >> 1) << 16; + r_affinetridesc.seamfixupX16 = (a_skinwidth >> 1) << 16; r_affinetridesc.skinheight = pmdl->skinheight; - if (currententity->scoreboard) - { - byte *base; + if (currententity->scoreboard) { + byte *base; if (!currententity->scoreboard->skin) Skin_Find (currententity->scoreboard); base = Skin_Cache (currententity->scoreboard->skin); - if (base) - { + if (base) { r_affinetridesc.pskin = base; r_affinetridesc.skinwidth = 320; r_affinetridesc.skinheight = 200; @@ -640,7 +625,8 @@ void R_AliasSetupSkin (void) R_AliasSetupLighting ================ */ -void R_AliasSetupLighting (alight_t *plighting) +void +R_AliasSetupLighting (alight_t *plighting) { // guarantee that no vertex will ever be lit below LIGHT_MIN, so we don't have @@ -675,32 +661,31 @@ R_AliasSetupFrame set r_apverts ================= */ -void R_AliasSetupFrame (void) +void +R_AliasSetupFrame (void) { - int frame; - int i, numframes; - maliasgroup_t *paliasgroup; - float *pintervals, fullinterval, targettime, time; + int frame; + int i, numframes; + maliasgroup_t *paliasgroup; + float *pintervals, fullinterval, targettime, time; frame = currententity->frame; - if ((frame >= pmdl->numframes) || (frame < 0)) - { + if ((frame >= pmdl->numframes) || (frame < 0)) { Con_DPrintf ("R_AliasSetupFrame: no such frame %d\n", frame); frame = 0; } - if (paliashdr->frames[frame].type == ALIAS_SINGLE) - { + if (paliashdr->frames[frame].type == ALIAS_SINGLE) { r_apverts = (trivertx_t *) - ((byte *)paliashdr + paliashdr->frames[frame].frame); + ((byte *) paliashdr + paliashdr->frames[frame].frame); return; } - + paliasgroup = (maliasgroup_t *) - ((byte *)paliashdr + paliashdr->frames[frame].frame); - pintervals = (float *)((byte *)paliashdr + paliasgroup->intervals); + ((byte *) paliashdr + paliashdr->frames[frame].frame); + pintervals = (float *) ((byte *) paliashdr + paliasgroup->intervals); numframes = paliasgroup->numframes; - fullinterval = pintervals[numframes-1]; + fullinterval = pintervals[numframes - 1]; time = cl.time + currententity->syncbase; @@ -708,16 +693,15 @@ void R_AliasSetupFrame (void) // when loading in Mod_LoadAliasGroup, we guaranteed all interval values // are positive, so we don't have to worry about division by 0 // - targettime = time - ((int)(time / fullinterval)) * fullinterval; + targettime = time - ((int) (time / fullinterval)) * fullinterval; - for (i=0 ; i<(numframes-1) ; i++) - { + for (i = 0; i < (numframes - 1); i++) { if (pintervals[i] > targettime) break; } r_apverts = (trivertx_t *) - ((byte *)paliashdr + paliasgroup->frames[i].frame); + ((byte *) paliashdr + paliasgroup->frames[i].frame); } @@ -726,21 +710,22 @@ void R_AliasSetupFrame (void) R_AliasDrawModel ================ */ -void R_AliasDrawModel (alight_t *plighting) +void +R_AliasDrawModel (alight_t *plighting) { - finalvert_t finalverts[MAXALIASVERTS + - ((CACHE_SIZE - 1) / sizeof(finalvert_t)) + 1]; - auxvert_t auxverts[MAXALIASVERTS]; + finalvert_t finalverts[MAXALIASVERTS + + ((CACHE_SIZE - 1) / sizeof (finalvert_t)) + 1]; + auxvert_t auxverts[MAXALIASVERTS]; r_amodels_drawn++; // cache align pfinalverts = (finalvert_t *) - (((long)&finalverts[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); + (((long) &finalverts[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); pauxverts = &auxverts[0]; - paliashdr = (aliashdr_t *)Mod_Extradata (currententity->model); - pmdl = (mdl_t *)((byte *)paliashdr + paliashdr->model); + paliashdr = (aliashdr_t *) Mod_Extradata (currententity->model); + pmdl = (mdl_t *) ((byte *) paliashdr + paliashdr->model); R_AliasSetupSkin (); R_AliasSetUpTransform (currententity->trivial_accept); @@ -751,14 +736,11 @@ void R_AliasDrawModel (alight_t *plighting) Sys_Error ("R_AliasDrawModel: !currententity->colormap"); r_affinetridesc.drawtype = (currententity->trivial_accept == 3) && - r_recursiveaffinetriangles; + r_recursiveaffinetriangles; - if (r_affinetridesc.drawtype) - { + if (r_affinetridesc.drawtype) { D_PolysetUpdateTables (); // FIXME: precalc... - } - else - { + } else { #ifdef USE_INTEL_ASM D_Aff8Patch (currententity->colormap); #endif @@ -767,13 +749,13 @@ void R_AliasDrawModel (alight_t *plighting) acolormap = currententity->colormap; if (currententity != &cl.viewent) - ziscale = (float)0x8000 * (float)0x10000; + ziscale = (float) 0x8000 *(float) 0x10000; + else - ziscale = (float)0x8000 * (float)0x10000 * 3.0; + ziscale = (float) 0x8000 *(float) 0x10000 *3.0; if (currententity->trivial_accept) R_AliasPrepareUnclippedPoints (); else R_AliasPreparePoints (); } - diff --git a/source/r_bsp.c b/source/r_bsp.c index 8ea0dd3..393bfd1 100644 --- a/source/r_bsp.c +++ b/source/r_bsp.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "console.h" @@ -38,32 +38,35 @@ // // current entity info // -qboolean insubmodel; -entity_t *currententity; -vec3_t modelorg, base_modelorg; +qboolean insubmodel; +entity_t *currententity; +vec3_t modelorg, base_modelorg; + // modelorg is the viewpoint reletive to // the currently rendering entity -vec3_t r_entorigin; // the currently rendering entity in world +vec3_t r_entorigin; // the currently rendering entity in + + // world // coordinates -float entity_rotation[3][3]; +float entity_rotation[3][3]; -vec3_t r_worldmodelorg; +vec3_t r_worldmodelorg; -int r_currentbkey; +int r_currentbkey; -typedef enum {touchessolid, drawnode, nodrawnode} solidstate_t; +typedef enum { touchessolid, drawnode, nodrawnode } solidstate_t; #define MAX_BMODEL_VERTS 500 // 6K #define MAX_BMODEL_EDGES 1000 // 12K -static mvertex_t *pbverts; -static bedge_t *pbedges; -static int numbverts, numbedges; +static mvertex_t *pbverts; +static bedge_t *pbedges; +static int numbverts, numbedges; -static mvertex_t *pfrontenter, *pfrontexit; +static mvertex_t *pfrontenter, *pfrontexit; -static qboolean makeclippededge; +static qboolean makeclippededge; //=========================================================================== @@ -73,9 +76,10 @@ static qboolean makeclippededge; R_EntityRotate ================ */ -void R_EntityRotate (vec3_t vec) +void +R_EntityRotate (vec3_t vec) { - vec3_t tvec; + vec3_t tvec; VectorCopy (vec, tvec); vec[0] = DotProduct (entity_rotation[0], tvec); @@ -89,9 +93,10 @@ void R_EntityRotate (vec3_t vec) R_RotateBmodel ================ */ -void R_RotateBmodel (void) +void +R_RotateBmodel (void) { - float angle, s, c, temp1[3][3], temp2[3][3], temp3[3][3]; + float angle, s, c, temp1[3][3], temp2[3][3], temp3[3][3]; // TODO: should use a look-up table // TODO: should really be stored with the entity instead of being reconstructed @@ -99,10 +104,10 @@ void R_RotateBmodel (void) // TODO: share work with R_SetUpAliasTransform // yaw - angle = currententity->angles[YAW]; - angle = angle * M_PI*2 / 360; - s = sin(angle); - c = cos(angle); + angle = currententity->angles[YAW]; + angle = angle * M_PI * 2 / 360; + s = sin (angle); + c = cos (angle); temp1[0][0] = c; temp1[0][1] = s; @@ -116,10 +121,10 @@ void R_RotateBmodel (void) // pitch - angle = currententity->angles[PITCH]; - angle = angle * M_PI*2 / 360; - s = sin(angle); - c = cos(angle); + angle = currententity->angles[PITCH]; + angle = angle * M_PI * 2 / 360; + s = sin (angle); + c = cos (angle); temp2[0][0] = c; temp2[0][1] = 0; @@ -134,10 +139,10 @@ void R_RotateBmodel (void) R_ConcatRotations (temp2, temp1, temp3); // roll - angle = currententity->angles[ROLL]; - angle = angle * M_PI*2 / 360; - s = sin(angle); - c = cos(angle); + angle = currententity->angles[ROLL]; + angle = angle * M_PI * 2 / 360; + s = sin (angle); + c = cos (angle); temp1[0][0] = 1; temp1[0][1] = 0; @@ -168,14 +173,15 @@ void R_RotateBmodel (void) R_RecursiveClipBPoly ================ */ -void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) +void +R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) { - bedge_t *psideedges[2], *pnextedge, *ptedge; - int i, side, lastside; - float dist, frac, lastdist; - mplane_t *splitplane, tplane; - mvertex_t *pvert, *plastvert, *ptvert; - mnode_t *pn; + bedge_t *psideedges[2], *pnextedge, *ptedge; + int i, side, lastside; + float dist, frac, lastdist; + mplane_t *splitplane, tplane; + mvertex_t *pvert, *plastvert, *ptvert; + mnode_t *pn; psideedges[0] = psideedges[1] = NULL; @@ -185,21 +191,20 @@ void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) // FIXME: cache these? splitplane = pnode->plane; tplane.dist = splitplane->dist - - DotProduct(r_entorigin, splitplane->normal); + DotProduct (r_entorigin, splitplane->normal); tplane.normal[0] = DotProduct (entity_rotation[0], splitplane->normal); tplane.normal[1] = DotProduct (entity_rotation[1], splitplane->normal); tplane.normal[2] = DotProduct (entity_rotation[2], splitplane->normal); // clip edges to BSP plane - for ( ; pedges ; pedges = pnextedge) - { + for (; pedges; pedges = pnextedge) { pnextedge = pedges->pnext; - // set the status for the last point as the previous point - // FIXME: cache this stuff somehow? + // set the status for the last point as the previous point + // FIXME: cache this stuff somehow? plastvert = pedges->v[0]; lastdist = DotProduct (plastvert->position, tplane.normal) - - tplane.dist; + tplane.dist; if (lastdist > 0) lastside = 0; @@ -215,30 +220,25 @@ void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) else side = 1; - if (side != lastside) - { - // clipped + if (side != lastside) { + // clipped if (numbverts >= MAX_BMODEL_VERTS) return; - // generate the clipped vertex + // generate the clipped vertex frac = lastdist / (lastdist - dist); ptvert = &pbverts[numbverts++]; ptvert->position[0] = plastvert->position[0] + - frac * (pvert->position[0] - - plastvert->position[0]); + frac * (pvert->position[0] - plastvert->position[0]); ptvert->position[1] = plastvert->position[1] + - frac * (pvert->position[1] - - plastvert->position[1]); + frac * (pvert->position[1] - plastvert->position[1]); ptvert->position[2] = plastvert->position[2] + - frac * (pvert->position[2] - - plastvert->position[2]); + frac * (pvert->position[2] - plastvert->position[2]); - // split into two edges, one on each side, and remember entering - // and exiting points - // FIXME: share the clip edge by having a winding direction flag? - if (numbedges >= (MAX_BMODEL_EDGES - 1)) - { + // split into two edges, one on each side, and remember entering + // and exiting points + // FIXME: share the clip edge by having a winding direction flag? + if (numbedges >= (MAX_BMODEL_EDGES - 1)) { Con_Printf ("Out of edges for bmodel\n"); return; } @@ -257,21 +257,16 @@ void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) numbedges += 2; - if (side == 0) - { - // entering for front, exiting for back + if (side == 0) { + // entering for front, exiting for back pfrontenter = ptvert; makeclippededge = true; - } - else - { + } else { pfrontexit = ptvert; makeclippededge = true; } - } - else - { - // add the edge to the appropriate side + } else { + // add the edge to the appropriate side pedges->pnext = psideedges[side]; psideedges[side] = pedges; } @@ -279,10 +274,8 @@ void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) // if anything was clipped, reconstitute and add the edges along the clip // plane to both sides (but in opposite directions) - if (makeclippededge) - { - if (numbedges >= (MAX_BMODEL_EDGES - 2)) - { + if (makeclippededge) { + if (numbedges >= (MAX_BMODEL_EDGES - 2)) { Con_Printf ("Out of edges for bmodel\n"); return; } @@ -301,31 +294,25 @@ void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) numbedges += 2; } - // draw or recurse further - for (i=0 ; i<2 ; i++) - { - if (psideedges[i]) - { - // draw if we've reached a non-solid leaf, done if all that's left is a - // solid leaf, and continue down the tree if it's not a leaf + for (i = 0; i < 2; i++) { + if (psideedges[i]) { + // draw if we've reached a non-solid leaf, done if all that's + // left is a + // solid leaf, and continue down the tree if it's not a leaf pn = pnode->children[i]; - // we're done with this branch if the node or leaf isn't in the PVS - if (pn->visframe == r_visframecount) - { - if (pn->contents < 0) - { - if (pn->contents != CONTENTS_SOLID) - { - r_currentbkey = ((mleaf_t *)pn)->key; + // we're done with this branch if the node or leaf isn't in the + // PVS + if (pn->visframe == r_visframecount) { + if (pn->contents < 0) { + if (pn->contents != CONTENTS_SOLID) { + r_currentbkey = ((mleaf_t *) pn)->key; R_RenderBmodelFace (psideedges[i], psurf); } - } - else - { + } else { R_RecursiveClipBPoly (psideedges[i], pnode->children[i], - psurf); + psurf); } } } @@ -338,16 +325,17 @@ void R_RecursiveClipBPoly (bedge_t *pedges, mnode_t *pnode, msurface_t *psurf) R_DrawSolidClippedSubmodelPolygons ================ */ -void R_DrawSolidClippedSubmodelPolygons (model_t *pmodel) +void +R_DrawSolidClippedSubmodelPolygons (model_t *pmodel) { - int i, j, lindex; - vec_t dot; - msurface_t *psurf; - int numsurfaces; - mplane_t *pplane; - mvertex_t bverts[MAX_BMODEL_VERTS]; - bedge_t bedges[MAX_BMODEL_EDGES], *pbedge; - medge_t *pedge, *pedges; + int i, j, lindex; + vec_t dot; + msurface_t *psurf; + int numsurfaces; + mplane_t *pplane; + mvertex_t bverts[MAX_BMODEL_VERTS]; + bedge_t bedges[MAX_BMODEL_EDGES], *pbedge; + medge_t *pedge, *pedges; // FIXME: use bounding-box-based frustum clipping info? @@ -355,59 +343,51 @@ void R_DrawSolidClippedSubmodelPolygons (model_t *pmodel) numsurfaces = pmodel->nummodelsurfaces; pedges = pmodel->edges; - for (i=0 ; iplane; dot = DotProduct (modelorg, pplane->normal) - pplane->dist; - // draw the polygon + // draw the polygon if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) - { - // FIXME: use bounding-box-based frustum clipping info? + (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { + // FIXME: use bounding-box-based frustum clipping info? - // copy the edges to bedges, flipping if necessary so always - // clockwise winding - // FIXME: if edges and vertices get caches, these assignments must move - // outside the loop, and overflow checking must be done here + // copy the edges to bedges, flipping if necessary so always + // clockwise winding + // FIXME: if edges and vertices get caches, these assignments + // must move + // outside the loop, and overflow checking must be done here pbverts = bverts; pbedges = bedges; numbverts = numbedges = 0; - if (psurf->numedges > 0) - { + if (psurf->numedges > 0) { pbedge = &bedges[numbedges]; numbedges += psurf->numedges; - for (j=0 ; jnumedges ; j++) - { - lindex = pmodel->surfedges[psurf->firstedge+j]; + for (j = 0; j < psurf->numedges; j++) { + lindex = pmodel->surfedges[psurf->firstedge + j]; - if (lindex > 0) - { + if (lindex > 0) { pedge = &pedges[lindex]; pbedge[j].v[0] = &r_pcurrentvertbase[pedge->v[0]]; pbedge[j].v[1] = &r_pcurrentvertbase[pedge->v[1]]; - } - else - { + } else { lindex = -lindex; pedge = &pedges[lindex]; pbedge[j].v[0] = &r_pcurrentvertbase[pedge->v[1]]; pbedge[j].v[1] = &r_pcurrentvertbase[pedge->v[0]]; } - pbedge[j].pnext = &pbedge[j+1]; + pbedge[j].pnext = &pbedge[j + 1]; } - pbedge[j-1].pnext = NULL; // mark end of edges + pbedge[j - 1].pnext = NULL; // mark end of edges R_RecursiveClipBPoly (pbedge, currententity->topnode, psurf); - } - else - { + } else { Sys_Error ("no edges in bmodel"); } } @@ -420,33 +400,32 @@ void R_DrawSolidClippedSubmodelPolygons (model_t *pmodel) R_DrawSubmodelPolygons ================ */ -void R_DrawSubmodelPolygons (model_t *pmodel, int clipflags) +void +R_DrawSubmodelPolygons (model_t *pmodel, int clipflags) { - int i; - vec_t dot; - msurface_t *psurf; - int numsurfaces; - mplane_t *pplane; + int i; + vec_t dot; + msurface_t *psurf; + int numsurfaces; + mplane_t *pplane; // FIXME: use bounding-box-based frustum clipping info? psurf = &pmodel->surfaces[pmodel->firstmodelsurface]; numsurfaces = pmodel->nummodelsurfaces; - for (i=0 ; iplane; dot = DotProduct (modelorg, pplane->normal) - pplane->dist; - // draw the polygon + // draw the polygon if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) - { - r_currentkey = ((mleaf_t *)currententity->topnode)->key; + (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { + r_currentkey = ((mleaf_t *) currententity->topnode)->key; - // FIXME: use bounding-box-based frustum clipping info? + // FIXME: use bounding-box-based frustum clipping info? R_RenderFace (psurf, clipflags); } } @@ -458,17 +437,18 @@ void R_DrawSubmodelPolygons (model_t *pmodel, int clipflags) R_RecursiveWorldNode ================ */ -void R_RecursiveWorldNode (mnode_t *node, int clipflags) +void +R_RecursiveWorldNode (mnode_t *node, int clipflags) { - int i, c, side, *pindex; - vec3_t acceptpt, rejectpt; - mplane_t *plane; - msurface_t *surf, **mark; - mleaf_t *pleaf; - double d, dot; + int i, c, side, *pindex; + vec3_t acceptpt, rejectpt; + mplane_t *plane; + msurface_t *surf, **mark; + mleaf_t *pleaf; + double d, dot; if (node->contents == CONTENTS_SOLID) - return; // solid + return; // solid if (node->visframe != r_visframecount) return; @@ -476,164 +456,133 @@ void R_RecursiveWorldNode (mnode_t *node, int clipflags) // cull the clipping planes if not trivial accept // FIXME: the compiler is doing a lousy job of optimizing here; it could be // twice as fast in ASM - if (clipflags) - { - for (i=0 ; i<4 ; i++) - { - if (! (clipflags & (1<minmaxs[pindex[0]]; - rejectpt[1] = (float)node->minmaxs[pindex[1]]; - rejectpt[2] = (float)node->minmaxs[pindex[2]]; - + rejectpt[0] = (float) node->minmaxs[pindex[0]]; + rejectpt[1] = (float) node->minmaxs[pindex[1]]; + rejectpt[2] = (float) node->minmaxs[pindex[2]]; + d = DotProduct (rejectpt, view_clipplanes[i].normal); d -= view_clipplanes[i].dist; if (d <= 0) return; - acceptpt[0] = (float)node->minmaxs[pindex[3+0]]; - acceptpt[1] = (float)node->minmaxs[pindex[3+1]]; - acceptpt[2] = (float)node->minmaxs[pindex[3+2]]; + acceptpt[0] = (float) node->minmaxs[pindex[3 + 0]]; + acceptpt[1] = (float) node->minmaxs[pindex[3 + 1]]; + acceptpt[2] = (float) node->minmaxs[pindex[3 + 2]]; d = DotProduct (acceptpt, view_clipplanes[i].normal); d -= view_clipplanes[i].dist; if (d >= 0) - clipflags &= ~(1<contents < 0) - { - pleaf = (mleaf_t *)node; + if (node->contents < 0) { + pleaf = (mleaf_t *) node; mark = pleaf->firstmarksurface; c = pleaf->nummarksurfaces; - if (c) - { - do - { + if (c) { + do { (*mark)->visframe = r_framecount; mark++; } while (--c); } - - // deal with model fragments in this leaf - if (pleaf->efrags) - { + // deal with model fragments in this leaf + if (pleaf->efrags) { R_StoreEfrags (&pleaf->efrags); } pleaf->key = r_currentkey; - r_currentkey++; // all bmodels in a leaf share the same key - } - else - { - // node is just a decision point, so go down the apropriate sides + r_currentkey++; // all bmodels in a leaf share the + // same key + } else { + // node is just a decision point, so go down the apropriate sides - // find which side of the node we are on + // find which side of the node we are on plane = node->plane; - switch (plane->type) - { - case PLANE_X: - dot = modelorg[0] - plane->dist; - break; - case PLANE_Y: - dot = modelorg[1] - plane->dist; - break; - case PLANE_Z: - dot = modelorg[2] - plane->dist; - break; - default: - dot = DotProduct (modelorg, plane->normal) - plane->dist; - break; + switch (plane->type) { + case PLANE_X: + dot = modelorg[0] - plane->dist; + break; + case PLANE_Y: + dot = modelorg[1] - plane->dist; + break; + case PLANE_Z: + dot = modelorg[2] - plane->dist; + break; + default: + dot = DotProduct (modelorg, plane->normal) - plane->dist; + break; } - + if (dot >= 0) side = 0; else side = 1; - // recurse down the children, front side first + // recurse down the children, front side first R_RecursiveWorldNode (node->children[side], clipflags); - // draw stuff + // draw stuff c = node->numsurfaces; - if (c) - { + if (c) { surf = cl.worldmodel->surfaces + node->firstsurface; - if (dot < -BACKFACE_EPSILON) - { - do - { + if (dot < -BACKFACE_EPSILON) { + do { if ((surf->flags & SURF_PLANEBACK) && - (surf->visframe == r_framecount)) - { - if (r_drawpolys) - { - if (r_worldpolysbacktofront) - { - if (numbtofpolys < MAX_BTOFPOLYS) - { + (surf->visframe == r_framecount)) { + if (r_drawpolys) { + if (r_worldpolysbacktofront) { + if (numbtofpolys < MAX_BTOFPOLYS) { pbtofpolys[numbtofpolys].clipflags = - clipflags; + clipflags; pbtofpolys[numbtofpolys].psurf = surf; numbtofpolys++; } - } - else - { + } else { R_RenderPoly (surf, clipflags); } - } - else - { + } else { R_RenderFace (surf, clipflags); } } surf++; } while (--c); - } - else if (dot > BACKFACE_EPSILON) - { - do - { + } else if (dot > BACKFACE_EPSILON) { + do { if (!(surf->flags & SURF_PLANEBACK) && - (surf->visframe == r_framecount)) - { - if (r_drawpolys) - { - if (r_worldpolysbacktofront) - { - if (numbtofpolys < MAX_BTOFPOLYS) - { + (surf->visframe == r_framecount)) { + if (r_drawpolys) { + if (r_worldpolysbacktofront) { + if (numbtofpolys < MAX_BTOFPOLYS) { pbtofpolys[numbtofpolys].clipflags = - clipflags; + clipflags; pbtofpolys[numbtofpolys].psurf = surf; numbtofpolys++; } - } - else - { + } else { R_RenderPoly (surf, clipflags); } - } - else - { + } else { R_RenderFace (surf, clipflags); } } @@ -641,12 +590,10 @@ void R_RecursiveWorldNode (mnode_t *node, int clipflags) surf++; } while (--c); } - - // all surfaces on the same node share the same sequence number + // all surfaces on the same node share the same sequence number r_currentkey++; } - - // recurse down the back side + // recurse down the back side R_RecursiveWorldNode (node->children[!side], clipflags); } } @@ -658,11 +605,12 @@ void R_RecursiveWorldNode (mnode_t *node, int clipflags) R_RenderWorld ================ */ -void R_RenderWorld (void) +void +R_RenderWorld (void) { - int i; - model_t *clmodel; - btofpoly_t btofpolys[MAX_BTOFPOLYS]; + int i; + model_t *clmodel; + btofpoly_t btofpolys[MAX_BTOFPOLYS]; pbtofpolys = btofpolys; @@ -675,13 +623,9 @@ void R_RenderWorld (void) // if the driver wants the polygons back to front, play the visible ones back // in that order - if (r_worldpolysbacktofront) - { - for (i=numbtofpolys-1 ; i>=0 ; i--) - { + if (r_worldpolysbacktofront) { + for (i = numbtofpolys - 1; i >= 0; i--) { R_RenderPoly (btofpolys[i].psurf, btofpolys[i].clipflags); } } } - - diff --git a/source/r_draw.c b/source/r_draw.c index 59e1c12..ba15527 100644 --- a/source/r_draw.c +++ b/source/r_draw.c @@ -27,10 +27,11 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" -#include "d_local.h" // FIXME: shouldn't need to include this +#include "d_local.h" // FIXME: shouldn't need to include + // this #define MAXLEFTCLIPEDGES 100 @@ -38,44 +39,43 @@ #define FULLY_CLIPPED_CACHED 0x80000000 #define FRAMECOUNT_MASK 0x7FFFFFFF -unsigned int cacheoffset; +unsigned int cacheoffset; -int c_faceclip; // number of faces clipped +int c_faceclip; // number of faces clipped -zpointdesc_t r_zpointdesc; +zpointdesc_t r_zpointdesc; -polydesc_t r_polydesc; +polydesc_t r_polydesc; -clipplane_t *entity_clipplanes; -clipplane_t view_clipplanes[4]; -clipplane_t world_clipplanes[16]; +clipplane_t *entity_clipplanes; +clipplane_t view_clipplanes[4]; +clipplane_t world_clipplanes[16]; -medge_t *r_pedge; +medge_t *r_pedge; -qboolean r_leftclipped, r_rightclipped; -static qboolean makeleftedge, makerightedge; -qboolean r_nearzionly; +qboolean r_leftclipped, r_rightclipped; +static qboolean makeleftedge, makerightedge; +qboolean r_nearzionly; -int sintable[1280]; -int intsintable[1280]; +int sintable[1280]; +int intsintable[1280]; -mvertex_t r_leftenter, r_leftexit; -mvertex_t r_rightenter, r_rightexit; +mvertex_t r_leftenter, r_leftexit; +mvertex_t r_rightenter, r_rightexit; -typedef struct -{ - float u,v; - int ceilv; +typedef struct { + float u, v; + int ceilv; } evert_t; -int r_emitted; -float r_nearzi; -float r_u1, r_v1, r_lzi1; -int r_ceilv1; +int r_emitted; +float r_nearzi; +float r_u1, r_v1, r_lzi1; +int r_ceilv1; -qboolean r_lastvertvalid; +qboolean r_lastvertvalid; #ifndef USE_INTEL_ASM @@ -85,53 +85,51 @@ qboolean r_lastvertvalid; R_EmitEdge ================ */ -void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) +void +R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) { - edge_t *edge, *pcheck; - int u_check; - float u, u_step; - vec3_t local, transformed; - float *world; - int v, v2, ceilv0; - float scale, lzi0, u0, v0; - int side; + edge_t *edge, *pcheck; + int u_check; + float u, u_step; + vec3_t local, transformed; + float *world; + int v, v2, ceilv0; + float scale, lzi0, u0, v0; + int side; - if (r_lastvertvalid) - { + if (r_lastvertvalid) { u0 = r_u1; v0 = r_v1; lzi0 = r_lzi1; ceilv0 = r_ceilv1; - } - else - { + } else { world = &pv0->position[0]; - - // transform and project + + // transform and project VectorSubtract (world, modelorg, local); TransformVector (local, transformed); - + if (transformed[2] < NEAR_CLIP) transformed[2] = NEAR_CLIP; - + lzi0 = 1.0 / transformed[2]; - - // FIXME: build x/yscale into transform? + + // FIXME: build x/yscale into transform? scale = xscale * lzi0; - u0 = (xcenter + scale*transformed[0]); + u0 = (xcenter + scale * transformed[0]); if (u0 < r_refdef.fvrectx_adj) u0 = r_refdef.fvrectx_adj; if (u0 > r_refdef.fvrectright_adj) u0 = r_refdef.fvrectright_adj; - + scale = yscale * lzi0; - v0 = (ycenter - scale*transformed[1]); + v0 = (ycenter - scale * transformed[1]); if (v0 < r_refdef.fvrecty_adj) v0 = r_refdef.fvrecty_adj; if (v0 > r_refdef.fvrectbottom_adj) v0 = r_refdef.fvrectbottom_adj; - - ceilv0 = (int) ceil(v0); + + ceilv0 = (int) ceil (v0); } world = &pv1->position[0]; @@ -146,14 +144,14 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) r_lzi1 = 1.0 / transformed[2]; scale = xscale * r_lzi1; - r_u1 = (xcenter + scale*transformed[0]); + r_u1 = (xcenter + scale * transformed[0]); if (r_u1 < r_refdef.fvrectx_adj) r_u1 = r_refdef.fvrectx_adj; if (r_u1 > r_refdef.fvrectright_adj) r_u1 = r_refdef.fvrectright_adj; scale = yscale * r_lzi1; - r_v1 = (ycenter - scale*transformed[1]); + r_v1 = (ycenter - scale * transformed[1]); if (r_v1 < r_refdef.fvrecty_adj) r_v1 = r_refdef.fvrecty_adj; if (r_v1 > r_refdef.fvrectbottom_adj) @@ -162,7 +160,7 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) if (r_lzi1 > lzi0) lzi0 = r_lzi1; - if (lzi0 > r_nearzi) // for mipmap finding + if (lzi0 > r_nearzi) // for mipmap finding r_nearzi = lzi0; // for right edges, all we want is the effect on 1/z @@ -171,20 +169,18 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) r_emitted = 1; - r_ceilv1 = (int) ceil(r_v1); + r_ceilv1 = (int) ceil (r_v1); // create the edge - if (ceilv0 == r_ceilv1) - { - // we cache unclipped horizontal edges as fully clipped - if (cacheoffset != 0x7FFFFFFF) - { + if (ceilv0 == r_ceilv1) { + // we cache unclipped horizontal edges as fully clipped + if (cacheoffset != 0x7FFFFFFF) { cacheoffset = FULLY_CLIPPED_CACHED | - (r_framecount & FRAMECOUNT_MASK); + (r_framecount & FRAMECOUNT_MASK); } - return; // horizontal edge + return; // horizontal edge } side = ceilv0 > r_ceilv1; @@ -195,9 +191,8 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) edge->nearzi = lzi0; - if (side == 0) - { - // trailing edge (go from p1 to p2) + if (side == 0) { + // trailing edge (go from p1 to p2) v = ceilv0; v2 = r_ceilv1 - 1; @@ -205,11 +200,9 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) edge->surfs[1] = 0; u_step = ((r_u1 - u0) / (r_v1 - v0)); - u = u0 + ((float)v - v0) * u_step; - } - else - { - // leading edge (go from p2 to p1) + u = u0 + ((float) v - v0) * u_step; + } else { + // leading edge (go from p2 to p1) v2 = ceilv0 - 1; v = r_ceilv1; @@ -217,11 +210,11 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) edge->surfs[1] = surface_p - surfaces; u_step = ((u0 - r_u1) / (v0 - r_v1)); - u = r_u1 + ((float)v - r_v1) * u_step; + u = r_u1 + ((float) v - r_v1) * u_step; } - edge->u_step = u_step*0x100000; - edge->u = u*0x100000 + 0xFFFFF; + edge->u_step = u_step * 0x100000; + edge->u = u * 0x100000 + 0xFFFFF; // we need to do this to avoid stepping off the edges if a very nearly // horizontal edge is less than epsilon above a scan, and numeric error causes @@ -238,15 +231,12 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) // u_check = edge->u; if (edge->surfs[0]) - u_check++; // sort trailers after leaders + u_check++; // sort trailers after leaders - if (!newedges[v] || newedges[v]->u >= u_check) - { + if (!newedges[v] || newedges[v]->u >= u_check) { edge->next = newedges[v]; newedges[v] = edge; - } - else - { + } else { pcheck = newedges[v]; while (pcheck->next && pcheck->next->u < u_check) pcheck = pcheck->next; @@ -264,88 +254,74 @@ void R_EmitEdge (mvertex_t *pv0, mvertex_t *pv1) R_ClipEdge ================ */ -void R_ClipEdge (mvertex_t *pv0, mvertex_t *pv1, clipplane_t *clip) +void +R_ClipEdge (mvertex_t *pv0, mvertex_t *pv1, clipplane_t *clip) { - float d0, d1, f; - mvertex_t clipvert; + float d0, d1, f; + mvertex_t clipvert; - if (clip) - { - do - { + if (clip) { + do { d0 = DotProduct (pv0->position, clip->normal) - clip->dist; d1 = DotProduct (pv1->position, clip->normal) - clip->dist; - if (d0 >= 0) - { - // point 0 is unclipped - if (d1 >= 0) - { - // both points are unclipped + if (d0 >= 0) { + // point 0 is unclipped + if (d1 >= 0) { + // both points are unclipped continue; } + // only point 1 is clipped - // only point 1 is clipped - - // we don't cache clipped edges + // we don't cache clipped edges cacheoffset = 0x7FFFFFFF; f = d0 / (d0 - d1); clipvert.position[0] = pv0->position[0] + - f * (pv1->position[0] - pv0->position[0]); + f * (pv1->position[0] - pv0->position[0]); clipvert.position[1] = pv0->position[1] + - f * (pv1->position[1] - pv0->position[1]); + f * (pv1->position[1] - pv0->position[1]); clipvert.position[2] = pv0->position[2] + - f * (pv1->position[2] - pv0->position[2]); + f * (pv1->position[2] - pv0->position[2]); - if (clip->leftedge) - { + if (clip->leftedge) { r_leftclipped = true; r_leftexit = clipvert; - } - else if (clip->rightedge) - { + } else if (clip->rightedge) { r_rightclipped = true; r_rightexit = clipvert; } R_ClipEdge (pv0, &clipvert, clip->next); return; - } - else - { - // point 0 is clipped - if (d1 < 0) - { - // both points are clipped - // we do cache fully clipped edges + } else { + // point 0 is clipped + if (d1 < 0) { + // both points are clipped + // we do cache fully clipped edges if (!r_leftclipped) cacheoffset = FULLY_CLIPPED_CACHED | - (r_framecount & FRAMECOUNT_MASK); + (r_framecount & FRAMECOUNT_MASK); return; } - - // only point 0 is clipped + // only point 0 is clipped r_lastvertvalid = false; - // we don't cache partially clipped edges + // we don't cache partially clipped edges cacheoffset = 0x7FFFFFFF; f = d0 / (d0 - d1); clipvert.position[0] = pv0->position[0] + - f * (pv1->position[0] - pv0->position[0]); + f * (pv1->position[0] - pv0->position[0]); clipvert.position[1] = pv0->position[1] + - f * (pv1->position[1] - pv0->position[1]); + f * (pv1->position[1] - pv0->position[1]); clipvert.position[2] = pv0->position[2] + - f * (pv1->position[2] - pv0->position[2]); + f * (pv1->position[2] - pv0->position[2]); - if (clip->leftedge) - { + if (clip->leftedge) { r_leftclipped = true; r_leftenter = clipvert; - } - else if (clip->rightedge) - { + } else if (clip->rightedge) { r_rightclipped = true; r_rightenter = clipvert; } @@ -355,12 +331,11 @@ void R_ClipEdge (mvertex_t *pv0, mvertex_t *pv1, clipplane_t *clip) } } while ((clip = clip->next) != NULL); } - // add the edge R_EmitEdge (pv0, pv1); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -368,18 +343,19 @@ void R_ClipEdge (mvertex_t *pv0, mvertex_t *pv1, clipplane_t *clip) R_EmitCachedEdge ================ */ -void R_EmitCachedEdge (void) +void +R_EmitCachedEdge (void) { - edge_t *pedge_t; + edge_t *pedge_t; - pedge_t = (edge_t *)((unsigned long)r_edges + r_pedge->cachededgeoffset); + pedge_t = (edge_t *) ((unsigned long) r_edges + r_pedge->cachededgeoffset); if (!pedge_t->surfs[0]) pedge_t->surfs[0] = surface_p - surfaces; else pedge_t->surfs[1] = surface_p - surfaces; - if (pedge_t->nearzi > r_nearzi) // for mipmap finding + if (pedge_t->nearzi > r_nearzi) // for mipmap finding r_nearzi = pedge_t->nearzi; r_emitted = 1; @@ -391,26 +367,24 @@ void R_EmitCachedEdge (void) R_RenderFace ================ */ -void R_RenderFace (msurface_t *fa, int clipflags) +void +R_RenderFace (msurface_t *fa, int clipflags) { - int i, lindex; - unsigned int mask; - mplane_t *pplane; - float distinv; - vec3_t p_normal; - medge_t *pedges, tedge; - clipplane_t *pclip; + int i, lindex; + unsigned int mask; + mplane_t *pplane; + float distinv; + vec3_t p_normal; + medge_t *pedges, tedge; + clipplane_t *pclip; // skip out if no more surfs - if ((surface_p) >= surf_max) - { + if ((surface_p) >= surf_max) { r_outofsurfaces++; return; } - // ditto if not enough edges left, or switch to auxedges if possible - if ((edge_p + fa->numedges + 4) >= edge_max) - { + if ((edge_p + fa->numedges + 4) >= edge_max) { r_outofedges += fa->numedges; return; } @@ -420,10 +394,8 @@ void R_RenderFace (msurface_t *fa, int clipflags) // set up clip planes pclip = NULL; - for (i=3, mask = 0x08 ; i>=0 ; i--, mask >>= 1) - { - if (clipflags & mask) - { + for (i = 3, mask = 0x08; i >= 0; i--, mask >>= 1) { + if (clipflags & mask) { view_clipplanes[i].next = pclip; pclip = &view_clipplanes[i]; } @@ -437,46 +409,37 @@ void R_RenderFace (msurface_t *fa, int clipflags) pedges = currententity->model->edges; r_lastvertvalid = false; - for (i=0 ; inumedges ; i++) - { + for (i = 0; i < fa->numedges; i++) { lindex = currententity->model->surfedges[fa->firstedge + i]; - if (lindex > 0) - { + if (lindex > 0) { r_pedge = &pedges[lindex]; - // if the edge is cached, we can just reuse the edge - if (!insubmodel) - { - if (r_pedge->cachededgeoffset & FULLY_CLIPPED_CACHED) - { + // if the edge is cached, we can just reuse the edge + if (!insubmodel) { + if (r_pedge->cachededgeoffset & FULLY_CLIPPED_CACHED) { if ((r_pedge->cachededgeoffset & FRAMECOUNT_MASK) == - r_framecount) - { + r_framecount) { r_lastvertvalid = false; continue; } - } - else - { - if ((((unsigned long)edge_p - (unsigned long)r_edges) > + } else { + if ((((unsigned long) edge_p - (unsigned long) r_edges) > r_pedge->cachededgeoffset) && - (((edge_t *)((unsigned long)r_edges + - r_pedge->cachededgeoffset))->owner == r_pedge)) - { + (((edge_t *) ((unsigned long) r_edges + + r_pedge->cachededgeoffset))->owner == + r_pedge)) { R_EmitCachedEdge (); r_lastvertvalid = false; continue; } } } - - // assume it's cacheable - cacheoffset = (byte *)edge_p - (byte *)r_edges; + // assume it's cacheable + cacheoffset = (byte *) edge_p - (byte *) r_edges; r_leftclipped = r_rightclipped = false; R_ClipEdge (&r_pcurrentvertbase[r_pedge->v[0]], - &r_pcurrentvertbase[r_pedge->v[1]], - pclip); + &r_pcurrentvertbase[r_pedge->v[1]], pclip); r_pedge->cachededgeoffset = cacheoffset; if (r_leftclipped) @@ -484,45 +447,36 @@ void R_RenderFace (msurface_t *fa, int clipflags) if (r_rightclipped) makerightedge = true; r_lastvertvalid = true; - } - else - { + } else { lindex = -lindex; r_pedge = &pedges[lindex]; - // if the edge is cached, we can just reuse the edge - if (!insubmodel) - { - if (r_pedge->cachededgeoffset & FULLY_CLIPPED_CACHED) - { + // if the edge is cached, we can just reuse the edge + if (!insubmodel) { + if (r_pedge->cachededgeoffset & FULLY_CLIPPED_CACHED) { if ((r_pedge->cachededgeoffset & FRAMECOUNT_MASK) == - r_framecount) - { + r_framecount) { r_lastvertvalid = false; continue; } - } - else - { - // it's cached if the cached edge is valid and is owned - // by this medge_t - if ((((unsigned long)edge_p - (unsigned long)r_edges) > + } else { + // it's cached if the cached edge is valid and is owned + // by this medge_t + if ((((unsigned long) edge_p - (unsigned long) r_edges) > r_pedge->cachededgeoffset) && - (((edge_t *)((unsigned long)r_edges + - r_pedge->cachededgeoffset))->owner == r_pedge)) - { + (((edge_t *) ((unsigned long) r_edges + + r_pedge->cachededgeoffset))->owner == + r_pedge)) { R_EmitCachedEdge (); r_lastvertvalid = false; continue; } } } - - // assume it's cacheable - cacheoffset = (byte *)edge_p - (byte *)r_edges; + // assume it's cacheable + cacheoffset = (byte *) edge_p - (byte *) r_edges; r_leftclipped = r_rightclipped = false; R_ClipEdge (&r_pcurrentvertbase[r_pedge->v[1]], - &r_pcurrentvertbase[r_pedge->v[0]], - pclip); + &r_pcurrentvertbase[r_pedge->v[0]], pclip); r_pedge->cachededgeoffset = cacheoffset; if (r_leftclipped) @@ -536,29 +490,25 @@ void R_RenderFace (msurface_t *fa, int clipflags) // if there was a clip off the left edge, add that edge too // FIXME: faster to do in screen space? // FIXME: share clipped edges? - if (makeleftedge) - { + if (makeleftedge) { r_pedge = &tedge; r_lastvertvalid = false; R_ClipEdge (&r_leftexit, &r_leftenter, pclip->next); } - // if there was a clip off the right edge, get the right r_nearzi - if (makerightedge) - { + if (makerightedge) { r_pedge = &tedge; r_lastvertvalid = false; r_nearzionly = true; R_ClipEdge (&r_rightexit, &r_rightenter, view_clipplanes[1].next); } - // if no edges made it out, return without posting the surface if (!r_emitted) return; r_polycount++; - surface_p->data = (void *)fa; + surface_p->data = (void *) fa; surface_p->nearzi = r_nearzi; surface_p->flags = fa->flags; surface_p->insubmodel = insubmodel; @@ -576,10 +526,9 @@ void R_RenderFace (msurface_t *fa, int clipflags) surface_p->d_zistepu = p_normal[0] * xscaleinv * distinv; surface_p->d_zistepv = -p_normal[1] * yscaleinv * distinv; surface_p->d_ziorigin = p_normal[2] * distinv - - xcenter * surface_p->d_zistepu - - ycenter * surface_p->d_zistepv; + xcenter * surface_p->d_zistepu - ycenter * surface_p->d_zistepv; -//JDC VectorCopy (r_worldmodelorg, surface_p->modelorg); +//JDC VectorCopy (r_worldmodelorg, surface_p->modelorg); surface_p++; } @@ -589,26 +538,24 @@ void R_RenderFace (msurface_t *fa, int clipflags) R_RenderBmodelFace ================ */ -void R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) +void +R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) { - int i; - unsigned int mask; - mplane_t *pplane; - float distinv; - vec3_t p_normal; - medge_t tedge; - clipplane_t *pclip; + int i; + unsigned int mask; + mplane_t *pplane; + float distinv; + vec3_t p_normal; + medge_t tedge; + clipplane_t *pclip; // skip out if no more surfs - if (surface_p >= surf_max) - { + if (surface_p >= surf_max) { r_outofsurfaces++; return; } - // ditto if not enough edges left, or switch to auxedges if possible - if ((edge_p + psurf->numedges + 4) >= edge_max) - { + if ((edge_p + psurf->numedges + 4) >= edge_max) { r_outofedges += psurf->numedges; return; } @@ -621,10 +568,8 @@ void R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) // set up clip planes pclip = NULL; - for (i=3, mask = 0x08 ; i>=0 ; i--, mask >>= 1) - { - if (r_clipflags & mask) - { + for (i = 3, mask = 0x08; i >= 0; i--, mask >>= 1) { + if (r_clipflags & mask) { view_clipplanes[i].next = pclip; pclip = &view_clipplanes[i]; } @@ -639,8 +584,7 @@ void R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) // can be used? r_lastvertvalid = false; - for ( ; pedges ; pedges = pedges->pnext) - { + for (; pedges; pedges = pedges->pnext) { r_leftclipped = r_rightclipped = false; R_ClipEdge (pedges->v[0], pedges->v[1], pclip); @@ -653,27 +597,23 @@ void R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) // if there was a clip off the left edge, add that edge too // FIXME: faster to do in screen space? // FIXME: share clipped edges? - if (makeleftedge) - { + if (makeleftedge) { r_pedge = &tedge; R_ClipEdge (&r_leftexit, &r_leftenter, pclip->next); } - // if there was a clip off the right edge, get the right r_nearzi - if (makerightedge) - { + if (makerightedge) { r_pedge = &tedge; r_nearzionly = true; R_ClipEdge (&r_rightexit, &r_rightenter, view_clipplanes[1].next); } - // if no edges made it out, return without posting the surface if (!r_emitted) return; r_polycount++; - surface_p->data = (void *)psurf; + surface_p->data = (void *) psurf; surface_p->nearzi = r_nearzi; surface_p->flags = psurf->flags; surface_p->insubmodel = true; @@ -691,10 +631,9 @@ void R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) surface_p->d_zistepu = p_normal[0] * xscaleinv * distinv; surface_p->d_zistepv = -p_normal[1] * yscaleinv * distinv; surface_p->d_ziorigin = p_normal[2] * distinv - - xcenter * surface_p->d_zistepu - - ycenter * surface_p->d_zistepv; + xcenter * surface_p->d_zistepu - ycenter * surface_p->d_zistepv; -//JDC VectorCopy (r_worldmodelorg, surface_p->modelorg); +//JDC VectorCopy (r_worldmodelorg, surface_p->modelorg); surface_p++; } @@ -704,32 +643,31 @@ void R_RenderBmodelFace (bedge_t *pedges, msurface_t *psurf) R_RenderPoly ================ */ -void R_RenderPoly (msurface_t *fa, int clipflags) +void +R_RenderPoly (msurface_t *fa, int clipflags) { - int i, lindex, lnumverts, s_axis, t_axis; - float dist, lastdist, lzi, scale, u, v, frac; - unsigned int mask; - vec3_t local, transformed; - clipplane_t *pclip; - medge_t *pedges; - mplane_t *pplane; - mvertex_t verts[2][100]; //FIXME: do real number - polyvert_t pverts[100]; //FIXME: do real number, safely - int vertpage, newverts, newpage, lastvert; - qboolean visible; + int i, lindex, lnumverts, s_axis, t_axis; + float dist, lastdist, lzi, scale, u, v, frac; + unsigned int mask; + vec3_t local, transformed; + clipplane_t *pclip; + medge_t *pedges; + mplane_t *pplane; + mvertex_t verts[2][100]; // FIXME: do real number + polyvert_t pverts[100]; // FIXME: do real number, safely + int vertpage, newverts, newpage, lastvert; + qboolean visible; // FIXME: clean this up and make it faster // FIXME: guard against running out of vertices - s_axis = t_axis = 0; // keep compiler happy + s_axis = t_axis = 0; // keep compiler happy // set up clip planes pclip = NULL; - for (i=3, mask = 0x08 ; i>=0 ; i--, mask >>= 1) - { - if (clipflags & mask) - { + for (i = 3, mask = 0x08; i >= 0; i--, mask >>= 1) { + if (clipflags & mask) { view_clipplanes[i].next = pclip; pclip = &view_clipplanes[i]; } @@ -741,25 +679,20 @@ void R_RenderPoly (msurface_t *fa, int clipflags) lnumverts = fa->numedges; vertpage = 0; - for (i=0 ; imodel->surfedges[fa->firstedge + i]; - if (lindex > 0) - { + if (lindex > 0) { r_pedge = &pedges[lindex]; verts[0][i] = r_pcurrentvertbase[r_pedge->v[0]]; - } - else - { + } else { r_pedge = &pedges[-lindex]; verts[0][i] = r_pcurrentvertbase[r_pedge->v[1]]; } } // clip the polygon, done if not visible - while (pclip) - { + while (pclip) { lastvert = lnumverts - 1; lastdist = DotProduct (verts[vertpage][lastvert].position, pclip->normal) - pclip->dist; @@ -768,31 +701,28 @@ void R_RenderPoly (msurface_t *fa, int clipflags) newverts = 0; newpage = vertpage ^ 1; - for (i=0 ; inormal) - - pclip->dist; + pclip->dist; - if ((lastdist > 0) != (dist > 0)) - { + if ((lastdist > 0) != (dist > 0)) { frac = dist / (dist - lastdist); verts[newpage][newverts].position[0] = - verts[vertpage][i].position[0] + - ((verts[vertpage][lastvert].position[0] - - verts[vertpage][i].position[0]) * frac); + verts[vertpage][i].position[0] + + ((verts[vertpage][lastvert].position[0] - + verts[vertpage][i].position[0]) * frac); verts[newpage][newverts].position[1] = - verts[vertpage][i].position[1] + - ((verts[vertpage][lastvert].position[1] - - verts[vertpage][i].position[1]) * frac); + verts[vertpage][i].position[1] + + ((verts[vertpage][lastvert].position[1] - + verts[vertpage][i].position[1]) * frac); verts[newpage][newverts].position[2] = - verts[vertpage][i].position[2] + - ((verts[vertpage][lastvert].position[2] - - verts[vertpage][i].position[2]) * frac); + verts[vertpage][i].position[2] + + ((verts[vertpage][lastvert].position[2] - + verts[vertpage][i].position[2]) * frac); newverts++; } - if (dist >= 0) - { + if (dist >= 0) { verts[newpage][newverts] = verts[vertpage][i]; newverts++; visible = true; @@ -813,30 +743,28 @@ void R_RenderPoly (msurface_t *fa, int clipflags) // transform and project, remembering the z values at the vertices and // r_nearzi, and extract the s and t coordinates at the vertices pplane = fa->plane; - switch (pplane->type) - { - case PLANE_X: - case PLANE_ANYX: - s_axis = 1; - t_axis = 2; - break; - case PLANE_Y: - case PLANE_ANYY: - s_axis = 0; - t_axis = 2; - break; - case PLANE_Z: - case PLANE_ANYZ: - s_axis = 0; - t_axis = 1; - break; + switch (pplane->type) { + case PLANE_X: + case PLANE_ANYX: + s_axis = 1; + t_axis = 2; + break; + case PLANE_Y: + case PLANE_ANYY: + s_axis = 0; + t_axis = 2; + break; + case PLANE_Z: + case PLANE_ANYZ: + s_axis = 0; + t_axis = 1; + break; } r_nearzi = 0; - for (i=0 ; i r_nearzi) // for mipmap finding + if (lzi > r_nearzi) // for mipmap finding r_nearzi = lzi; - // FIXME: build x/yscale into transform? + // FIXME: build x/yscale into transform? scale = xscale * lzi; - u = (xcenter + scale*transformed[0]); + u = (xcenter + scale * transformed[0]); if (u < r_refdef.fvrectx_adj) u = r_refdef.fvrectx_adj; if (u > r_refdef.fvrectright_adj) u = r_refdef.fvrectright_adj; scale = yscale * lzi; - v = (ycenter - scale*transformed[1]); + v = (ycenter - scale * transformed[1]); if (v < r_refdef.fvrecty_adj) v = r_refdef.fvrecty_adj; if (v > r_refdef.fvrectbottom_adj) @@ -887,30 +815,28 @@ void R_RenderPoly (msurface_t *fa, int clipflags) R_ZDrawSubmodelPolys ================ */ -void R_ZDrawSubmodelPolys (model_t *pmodel) +void +R_ZDrawSubmodelPolys (model_t *pmodel) { - int i, numsurfaces; - msurface_t *psurf; - float dot; - mplane_t *pplane; + int i, numsurfaces; + msurface_t *psurf; + float dot; + mplane_t *pplane; psurf = &pmodel->surfaces[pmodel->firstmodelsurface]; numsurfaces = pmodel->nummodelsurfaces; - for (i=0 ; iplane; dot = DotProduct (modelorg, pplane->normal) - pplane->dist; - // draw the polygon + // draw the polygon if (((psurf->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) || - (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) - { - // FIXME: use bounding-box-based frustum clipping info? + (!(psurf->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON))) { + // FIXME: use bounding-box-based frustum clipping info? R_RenderPoly (psurf, 15); } } } - diff --git a/source/r_edge.c b/source/r_edge.c index d905b4a..82128ee 100644 --- a/source/r_edge.c +++ b/source/r_edge.c @@ -27,60 +27,63 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "d_ifacea.h" #include "r_local.h" #if 0 // FIXME -the complex cases add new polys on most lines, so dont optimize for keeping them the same -have multiple free span lists to try to get better coherence? -low depth complexity -- 1 to 3 or so +the complex cases add new polys on most lines, + so dont optimize for keeping them the same have multiple free span lists to + try to get better coherence ? low depth complexity-- 1 to 3 or so this + breaks spans at every edge, even hidden +ones (bad) -this breaks spans at every edge, even hidden ones (bad) - -have a sentinal at both ends? +have a sentinal at both ends ? #endif +edge_t *auxedges; +edge_t *r_edges, *edge_p, *edge_max; - -edge_t *auxedges; -edge_t *r_edges, *edge_p, *edge_max; - -surf_t *surfaces, *surface_p, *surf_max; +surf_t *surfaces, *surface_p, *surf_max; // surfaces are generated in back to front order by the bsp, so if a surf // pointer is greater than another one, it should be drawn in front // surfaces[1] is the background, and is used as the active surface stack -edge_t *newedges[MAXHEIGHT]; -edge_t *removeedges[MAXHEIGHT]; +edge_t *newedges[MAXHEIGHT]; +edge_t *removeedges[MAXHEIGHT]; -espan_t *span_p, *max_span_p; +espan_t *span_p, *max_span_p; -int r_currentkey; +int r_currentkey; -extern int screenwidth; +extern int screenwidth; -int current_iv; +int current_iv; -int edge_head_u_shift20, edge_tail_u_shift20; +int edge_head_u_shift20, edge_tail_u_shift20; -static void (*pdrawfunc)(void); +static void (*pdrawfunc) (void); -edge_t edge_head; -edge_t edge_tail; -edge_t edge_aftertail; -edge_t edge_sentinel; +edge_t edge_head; +edge_t edge_tail; +edge_t edge_aftertail; +edge_t edge_sentinel; -float fv; +float fv; -void R_GenerateSpans (void); -void R_GenerateSpansBackward (void); +void +R_GenerateSpans (void); +void +R_GenerateSpansBackward (void); -void R_LeadingEdge (edge_t *edge); -void R_LeadingEdgeBackwards (edge_t *edge); -void R_TrailingEdge (surf_t *surf, edge_t *edge); +void +R_LeadingEdge (edge_t *edge); +void +R_LeadingEdgeBackwards (edge_t *edge); +void +R_TrailingEdge (surf_t *surf, edge_t *edge); //============================================================================= @@ -91,37 +94,31 @@ void R_TrailingEdge (surf_t *surf, edge_t *edge); R_DrawCulledPolys ============== */ -void R_DrawCulledPolys (void) +void +R_DrawCulledPolys (void) { - surf_t *s; - msurface_t *pface; + surf_t *s; + msurface_t *pface; currententity = &r_worldentity; - if (r_worldpolysbacktofront) - { - for (s=surface_p-1 ; s>&surfaces[1] ; s--) - { + if (r_worldpolysbacktofront) { + for (s = surface_p - 1; s > &surfaces[1]; s--) { if (!s->spans) continue; - if (!(s->flags & SURF_DRAWBACKGROUND)) - { - pface = (msurface_t *)s->data; + if (!(s->flags & SURF_DRAWBACKGROUND)) { + pface = (msurface_t *) s->data; R_RenderPoly (pface, 15); } } - } - else - { - for (s = &surfaces[1] ; sspans) continue; - if (!(s->flags & SURF_DRAWBACKGROUND)) - { - pface = (msurface_t *)s->data; + if (!(s->flags & SURF_DRAWBACKGROUND)) { + pface = (msurface_t *) s->data; R_RenderPoly (pface, 15); } } @@ -134,35 +131,32 @@ void R_DrawCulledPolys (void) R_BeginEdgeFrame ============== */ -void R_BeginEdgeFrame (void) +void +R_BeginEdgeFrame (void) { - int v; + int v; edge_p = r_edges; edge_max = &r_edges[r_numallocatededges]; - surface_p = &surfaces[2]; // background is surface 1, - // surface 0 is a dummy - surfaces[1].spans = NULL; // no background spans yet + surface_p = &surfaces[2]; // background is surface 1, + // surface 0 is a dummy + surfaces[1].spans = NULL; // no background spans yet surfaces[1].flags = SURF_DRAWBACKGROUND; // put the background behind everything in the world - if (r_draworder->int_val) - { + if (r_draworder->int_val) { pdrawfunc = R_GenerateSpansBackward; surfaces[1].key = 0; r_currentkey = 1; - } - else - { + } else { pdrawfunc = R_GenerateSpans; surfaces[1].key = 0x7FFFFFFF; r_currentkey = 0; } // FIXME: set with memset - for (v=r_refdef.vrect.y ; vnext; -edgesearch: + edgesearch: if (edgelist->u >= edgestoadd->u) goto addedge; - edgelist=edgelist->next; + edgelist = edgelist->next; if (edgelist->u >= edgestoadd->u) goto addedge; - edgelist=edgelist->next; + edgelist = edgelist->next; if (edgelist->u >= edgestoadd->u) goto addedge; - edgelist=edgelist->next; + edgelist = edgelist->next; if (edgelist->u >= edgestoadd->u) goto addedge; - edgelist=edgelist->next; + edgelist = edgelist->next; goto edgesearch; - // insert edgestoadd before edgelist -addedge: + // insert edgestoadd before edgelist + addedge: edgestoadd->next = edgelist; edgestoadd->prev = edgelist->prev; edgelist->prev->next = edgestoadd; @@ -211,8 +205,8 @@ addedge: } while ((edgestoadd = next_edge) != NULL); } -#endif // !USE_INTEL_ASM - +#endif // !USE_INTEL_ASM + #ifndef USE_INTEL_ASM @@ -221,17 +215,17 @@ addedge: R_RemoveEdges ============== */ -void R_RemoveEdges (edge_t *pedge) +void +R_RemoveEdges (edge_t *pedge) { - do - { + do { pedge->next->prev = pedge->prev; pedge->prev->next = pedge->next; } while ((pedge = pedge->nextremove) != NULL); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM #ifndef USE_INTEL_ASM @@ -241,55 +235,54 @@ void R_RemoveEdges (edge_t *pedge) R_StepActiveU ============== */ -void R_StepActiveU (edge_t *pedge) +void +R_StepActiveU (edge_t *pedge) { - edge_t *pnext_edge, *pwedge; + edge_t *pnext_edge, *pwedge; - while (1) - { -nextedge: + while (1) { + nextedge: pedge->u += pedge->u_step; if (pedge->u < pedge->prev->u) goto pushback; pedge = pedge->next; - + pedge->u += pedge->u_step; if (pedge->u < pedge->prev->u) goto pushback; pedge = pedge->next; - + pedge->u += pedge->u_step; if (pedge->u < pedge->prev->u) goto pushback; pedge = pedge->next; - + pedge->u += pedge->u_step; if (pedge->u < pedge->prev->u) goto pushback; pedge = pedge->next; - - goto nextedge; - -pushback: + + goto nextedge; + + pushback: if (pedge == &edge_aftertail) return; - - // push it back to keep it sorted + + // push it back to keep it sorted pnext_edge = pedge->next; - // pull the edge out of the edge list + // pull the edge out of the edge list pedge->next->prev = pedge->prev; pedge->prev->next = pedge->next; - // find out where the edge goes in the edge list + // find out where the edge goes in the edge list pwedge = pedge->prev->prev; - while (pwedge->u > pedge->u) - { + while (pwedge->u > pedge->u) { pwedge = pwedge->prev; } - // put the edge back into the edge list + // put the edge back into the edge list pedge->next = pwedge->next; pedge->prev = pwedge; pedge->next->prev = pedge; @@ -301,7 +294,7 @@ pushback: } } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -309,18 +302,18 @@ pushback: R_CleanupSpan ============== */ -void R_CleanupSpan () +void +R_CleanupSpan () { - surf_t *surf; - int iu; - espan_t *span; + surf_t *surf; + int iu; + espan_t *span; // now that we've reached the right edge of the screen, we're done with any // unfinished surfaces, so emit a span for whatever's on top surf = surfaces[1].next; iu = edge_tail_u_shift20; - if (iu > surf->last_u) - { + if (iu > surf->last_u) { span = span_p++; span->u = surf->last_u; span->count = iu - span->u; @@ -328,10 +321,8 @@ void R_CleanupSpan () span->pnext = surf->spans; surf->spans = span; } - // reset spanstate for all surfaces in the surface stack - do - { + do { surf->spanstate = 0; surf = surf->next; } while (surf != &surfaces[1]); @@ -343,11 +334,12 @@ void R_CleanupSpan () R_LeadingEdgeBackwards ============== */ -void R_LeadingEdgeBackwards (edge_t *edge) +void +R_LeadingEdgeBackwards (edge_t *edge) { - espan_t *span; - surf_t *surf, *surf2; - int iu; + espan_t *span; + surf_t *surf, *surf2; + int iu; // it's adding a new surface in, so find the correct place surf = &surfaces[edge->surfs[1]]; @@ -355,48 +347,45 @@ void R_LeadingEdgeBackwards (edge_t *edge) // don't start a span if this is an inverted span, with the end // edge preceding the start edge (that is, we've already seen the // end edge) - if (++surf->spanstate == 1) - { + if (++surf->spanstate == 1) { surf2 = surfaces[1].next; if (surf->key > surf2->key) goto newtop; - // if it's two surfaces on the same plane, the one that's already - // active is in front, so keep going unless it's a bmodel - if (surf->insubmodel && (surf->key == surf2->key)) - { - // must be two bmodels in the same leaf; don't care, because they'll - // never be farthest anyway + // if it's two surfaces on the same plane, the one that's already + // active is in front, so keep going unless it's a bmodel + if (surf->insubmodel && (surf->key == surf2->key)) { + // must be two bmodels in the same leaf; don't care, because + // they'll + // never be farthest anyway goto newtop; } -continue_search: + continue_search: - do - { + do { surf2 = surf2->next; } while (surf->key < surf2->key); - if (surf->key == surf2->key) - { - // if it's two surfaces on the same plane, the one that's already - // active is in front, so keep going unless it's a bmodel + if (surf->key == surf2->key) { + // if it's two surfaces on the same plane, the one that's already + // active is in front, so keep going unless it's a bmodel if (!surf->insubmodel) goto continue_search; - // must be two bmodels in the same leaf; don't care which is really - // in front, because they'll never be farthest anyway + // must be two bmodels in the same leaf; don't care which is + // really + // in front, because they'll never be farthest anyway } goto gotposition; -newtop: - // emit a span (obscures current top) + newtop: + // emit a span (obscures current top) iu = edge->u >> 20; - if (iu > surf2->last_u) - { + if (iu > surf2->last_u) { span = span_p++; span->u = surf2->last_u; span->count = iu - span->u; @@ -404,12 +393,11 @@ newtop: span->pnext = surf2->spans; surf2->spans = span; } - // set last_u on the new span surf->last_u = iu; - -gotposition: - // insert before surf2 + + gotposition: + // insert before surf2 surf->next = surf2; surf->prev = surf2->prev; surf2->prev->next = surf; @@ -423,25 +411,23 @@ gotposition: R_TrailingEdge ============== */ -void R_TrailingEdge (surf_t *surf, edge_t *edge) +void +R_TrailingEdge (surf_t *surf, edge_t *edge) { - espan_t *span; - int iu; + espan_t *span; + int iu; // don't generate a span if this is an inverted span, with the end // edge preceding the start edge (that is, we haven't seen the // start edge yet) - if (--surf->spanstate == 0) - { + if (--surf->spanstate == 0) { if (surf->insubmodel) r_bmodelactive--; - if (surf == surfaces[1].next) - { - // emit a span (current top going away) + if (surf == surfaces[1].next) { + // emit a span (current top going away) iu = edge->u >> 20; - if (iu > surf->last_u) - { + if (iu > surf->last_u) { span = span_p++; span->u = surf->last_u; span->count = iu - span->u; @@ -449,8 +435,7 @@ void R_TrailingEdge (surf_t *surf, edge_t *edge) span->pnext = surf->spans; surf->spans = span; } - - // set last_u on the surface below + // set last_u on the surface below surf->next->last_u = iu; } @@ -467,23 +452,22 @@ void R_TrailingEdge (surf_t *surf, edge_t *edge) R_LeadingEdge ============== */ -void R_LeadingEdge (edge_t *edge) +void +R_LeadingEdge (edge_t *edge) { - espan_t *span; - surf_t *surf, *surf2; - int iu; - double fu, newzi, testzi, newzitop, newzibottom; + espan_t *span; + surf_t *surf, *surf2; + int iu; + double fu, newzi, testzi, newzitop, newzibottom; - if (edge->surfs[1]) - { - // it's adding a new surface in, so find the correct place + if (edge->surfs[1]) { + // it's adding a new surface in, so find the correct place surf = &surfaces[edge->surfs[1]]; - // don't start a span if this is an inverted span, with the end - // edge preceding the start edge (that is, we've already seen the - // end edge) - if (++surf->spanstate == 1) - { + // don't start a span if this is an inverted span, with the end + // edge preceding the start edge (that is, we've already seen the + // end edge) + if (++surf->spanstate == 1) { if (surf->insubmodel) r_bmodelactive++; @@ -492,67 +476,59 @@ void R_LeadingEdge (edge_t *edge) if (surf->key < surf2->key) goto newtop; - // if it's two surfaces on the same plane, the one that's already - // active is in front, so keep going unless it's a bmodel - if (surf->insubmodel && (surf->key == surf2->key)) - { - // must be two bmodels in the same leaf; sort on 1/z - fu = (float)(edge->u - 0xFFFFF) * (1.0 / 0x100000); - newzi = surf->d_ziorigin + fv*surf->d_zistepv + - fu*surf->d_zistepu; + // if it's two surfaces on the same plane, the one that's already + // active is in front, so keep going unless it's a bmodel + if (surf->insubmodel && (surf->key == surf2->key)) { + // must be two bmodels in the same leaf; sort on 1/z + fu = (float) (edge->u - 0xFFFFF) * (1.0 / 0x100000); + newzi = surf->d_ziorigin + fv * surf->d_zistepv + + fu * surf->d_zistepu; newzibottom = newzi * 0.99; - testzi = surf2->d_ziorigin + fv*surf2->d_zistepv + - fu*surf2->d_zistepu; + testzi = surf2->d_ziorigin + fv * surf2->d_zistepv + + fu * surf2->d_zistepu; - if (newzibottom >= testzi) - { + if (newzibottom >= testzi) { goto newtop; } newzitop = newzi * 1.01; - if (newzitop >= testzi) - { - if (surf->d_zistepu >= surf2->d_zistepu) - { + if (newzitop >= testzi) { + if (surf->d_zistepu >= surf2->d_zistepu) { goto newtop; } } } -continue_search: + continue_search: - do - { + do { surf2 = surf2->next; } while (surf->key > surf2->key); - if (surf->key == surf2->key) - { - // if it's two surfaces on the same plane, the one that's already - // active is in front, so keep going unless it's a bmodel + if (surf->key == surf2->key) { + // if it's two surfaces on the same plane, the one that's + // already + // active is in front, so keep going unless it's a bmodel if (!surf->insubmodel) goto continue_search; - // must be two bmodels in the same leaf; sort on 1/z - fu = (float)(edge->u - 0xFFFFF) * (1.0 / 0x100000); - newzi = surf->d_ziorigin + fv*surf->d_zistepv + - fu*surf->d_zistepu; + // must be two bmodels in the same leaf; sort on 1/z + fu = (float) (edge->u - 0xFFFFF) * (1.0 / 0x100000); + newzi = surf->d_ziorigin + fv * surf->d_zistepv + + fu * surf->d_zistepu; newzibottom = newzi * 0.99; - testzi = surf2->d_ziorigin + fv*surf2->d_zistepv + - fu*surf2->d_zistepu; + testzi = surf2->d_ziorigin + fv * surf2->d_zistepv + + fu * surf2->d_zistepu; - if (newzibottom >= testzi) - { + if (newzibottom >= testzi) { goto gotposition; } newzitop = newzi * 1.01; - if (newzitop >= testzi) - { - if (surf->d_zistepu >= surf2->d_zistepu) - { + if (newzitop >= testzi) { + if (surf->d_zistepu >= surf2->d_zistepu) { goto gotposition; } } @@ -562,12 +538,11 @@ continue_search: goto gotposition; -newtop: - // emit a span (obscures current top) + newtop: + // emit a span (obscures current top) iu = edge->u >> 20; - if (iu > surf2->last_u) - { + if (iu > surf2->last_u) { span = span_p++; span->u = surf2->last_u; span->count = iu - span->u; @@ -575,12 +550,11 @@ newtop: span->pnext = surf2->spans; surf2->spans = span; } - // set last_u on the new span surf->last_u = iu; - -gotposition: - // insert before surf2 + + gotposition: + // insert before surf2 surf->next = surf2; surf->prev = surf2->prev; surf2->prev->next = surf; @@ -595,10 +569,11 @@ gotposition: R_GenerateSpans ============== */ -void R_GenerateSpans (void) +void +R_GenerateSpans (void) { - edge_t *edge; - surf_t *surf; + edge_t *edge; + surf_t *surf; r_bmodelactive = 0; @@ -607,11 +582,10 @@ void R_GenerateSpans (void) surfaces[1].last_u = edge_head_u_shift20; // generate spans - for (edge=edge_head.next ; edge != &edge_tail; edge=edge->next) - { - if (edge->surfs[0]) - { - // it has a left surface, so a surface is going away for this span + for (edge = edge_head.next; edge != &edge_tail; edge = edge->next) { + if (edge->surfs[0]) { + // it has a left surface, so a surface is going away for this + // span surf = &surfaces[edge->surfs[0]]; R_TrailingEdge (surf, edge); @@ -626,7 +600,7 @@ void R_GenerateSpans (void) R_CleanupSpan (); } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -634,9 +608,10 @@ void R_GenerateSpans (void) R_GenerateSpansBackward ============== */ -void R_GenerateSpansBackward (void) +void +R_GenerateSpansBackward (void) { - edge_t *edge; + edge_t *edge; r_bmodelactive = 0; @@ -645,8 +620,7 @@ void R_GenerateSpansBackward (void) surfaces[1].last_u = edge_head_u_shift20; // generate spans - for (edge=edge_head.next ; edge != &edge_tail; edge=edge->next) - { + for (edge = edge_head.next; edge != &edge_tail; edge = edge->next) { if (edge->surfs[0]) R_TrailingEdge (&surfaces[edge->surfs[0]], edge); @@ -670,15 +644,16 @@ Output: Each surface has a linked list of its visible spans ============== */ -void R_ScanEdges (void) +void +R_ScanEdges (void) { - int iv, bottom; - byte basespans[MAXSPANS*sizeof(espan_t)+CACHE_SIZE]; - espan_t *basespan_p; - surf_t *s; + int iv, bottom; + byte basespans[MAXSPANS * sizeof (espan_t) + CACHE_SIZE]; + espan_t *basespan_p; + surf_t *s; basespan_p = (espan_t *) - ((long)(basespans + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); + ((long) (basespans + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); max_span_p = &basespan_p[MAXSPANS - r_refdef.vrect.width]; span_p = basespan_p; @@ -692,7 +667,7 @@ void R_ScanEdges (void) edge_head.next = &edge_tail; edge_head.surfs[0] = 0; edge_head.surfs[1] = 1; - + edge_tail.u = (r_refdef.vrectright << 20) + 0xFFFFF; edge_tail_u_shift20 = edge_tail.u >> 20; edge_tail.u_step = 0; @@ -700,8 +675,8 @@ void R_ScanEdges (void) edge_tail.next = &edge_aftertail; edge_tail.surfs[0] = 1; edge_tail.surfs[1] = 0; - - edge_aftertail.u = -1; // force a move + + edge_aftertail.u = -1; // force a move edge_aftertail.u_step = 0; edge_aftertail.next = &edge_sentinel; edge_aftertail.prev = &edge_tail; @@ -710,41 +685,40 @@ void R_ScanEdges (void) edge_sentinel.u = 2000 << 24; // make sure nothing sorts past this edge_sentinel.prev = &edge_aftertail; -// +// // process all scan lines // bottom = r_refdef.vrectbottom - 1; - for (iv=r_refdef.vrect.y ; iv max_span_p) - { + // flush the span list if we can't be sure we have enough spans left + // for + // the next scan + if (span_p > max_span_p) { VID_UnlockBuffer (); - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate (); // don't let sound get messed up if + // going slow VID_LockBuffer (); - + if (r_drawculledpolys) R_DrawCulledPolys (); else D_DrawSurfaces (); - // clear the surface span pointers - for (s = &surfaces[1] ; sspans = NULL; span_p = basespan_p; @@ -760,7 +734,7 @@ void R_ScanEdges (void) // do the last scan (no need to step or sort or remove on the last scan) current_iv = iv; - fv = (float)iv; + fv = (float) iv; // mark that the head (background start) span is pre-included surfaces[1].spanstate = 1; @@ -776,5 +750,3 @@ void R_ScanEdges (void) else D_DrawSurfaces (); } - - diff --git a/source/r_efrag.c b/source/r_efrag.c index 98297c8..c820002 100644 --- a/source/r_efrag.c +++ b/source/r_efrag.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "console.h" @@ -35,7 +35,7 @@ #include "r_local.h" #include "cl_main.h" -mnode_t *r_pefragtopnode; +mnode_t *r_pefragtopnode; //=========================================================================== @@ -48,11 +48,11 @@ mnode_t *r_pefragtopnode; =============================================================================== */ -efrag_t **lastlink; +efrag_t **lastlink; -vec3_t r_emins, r_emaxs; +vec3_t r_emins, r_emaxs; -entity_t *r_addent; +entity_t *r_addent; /* @@ -62,38 +62,35 @@ R_RemoveEfrags Call when removing an object from the world or moving it to another position ================ */ -void R_RemoveEfrags (entity_t *ent) +void +R_RemoveEfrags (entity_t *ent) { - efrag_t *ef, *old, *walk, **prev; - + efrag_t *ef, *old, *walk, **prev; + ef = ent->efrag; - - while (ef) - { + + while (ef) { prev = &ef->leaf->efrags; - while (1) - { + while (1) { walk = *prev; if (!walk) break; - if (walk == ef) - { // remove this fragment + if (walk == ef) { // remove this fragment *prev = ef->leafnext; break; - } - else + } else prev = &walk->leafnext; } - + old = ef; ef = ef->entnext; - - // put it on the free list + + // put it on the free list old->entnext = cl.free_efrags; cl.free_efrags = old; } - - ent->efrag = NULL; + + ent->efrag = NULL; } /* @@ -101,68 +98,62 @@ void R_RemoveEfrags (entity_t *ent) R_SplitEntityOnNode =================== */ -void R_SplitEntityOnNode (mnode_t *node) +void +R_SplitEntityOnNode (mnode_t *node) { - efrag_t *ef; - mplane_t *splitplane; - mleaf_t *leaf; - int sides; - - if (node->contents == CONTENTS_SOLID) - { + efrag_t *ef; + mplane_t *splitplane; + mleaf_t *leaf; + int sides; + + if (node->contents == CONTENTS_SOLID) { return; } - // add an efrag if the node is a leaf - if ( node->contents < 0) - { + if (node->contents < 0) { if (!r_pefragtopnode) r_pefragtopnode = node; - leaf = (mleaf_t *)node; + leaf = (mleaf_t *) node; // grab an efrag off the free list ef = cl.free_efrags; - if (!ef) - { + if (!ef) { Con_Printf ("Too many efrags!\n"); - return; // no free fragments... + return; // no free fragments... } cl.free_efrags = cl.free_efrags->entnext; ef->entity = r_addent; - -// add the entity link + +// add the entity link *lastlink = ef; lastlink = &ef->entnext; ef->entnext = NULL; - + // set the leaf links ef->leaf = leaf; ef->leafnext = leaf->efrags; leaf->efrags = ef; - + return; } - // NODE_MIXED splitplane = node->plane; - sides = BOX_ON_PLANE_SIDE(r_emins, r_emaxs, splitplane); - - if (sides == 3) - { - // split on this plane - // if this is the first splitter of this bmodel, remember it + sides = BOX_ON_PLANE_SIDE (r_emins, r_emaxs, splitplane); + + if (sides == 3) { + // split on this plane + // if this is the first splitter of this bmodel, remember it if (!r_pefragtopnode) r_pefragtopnode = node; } - // recurse down the contacted sides if (sides & 1) R_SplitEntityOnNode (node->children[0]); - + if (sides & 2) R_SplitEntityOnNode (node->children[1]); } @@ -173,32 +164,31 @@ void R_SplitEntityOnNode (mnode_t *node) R_SplitEntityOnNode2 =================== */ -void R_SplitEntityOnNode2 (mnode_t *node) +void +R_SplitEntityOnNode2 (mnode_t *node) { - mplane_t *splitplane; - int sides; + mplane_t *splitplane; + int sides; if (node->visframe != r_visframecount) return; - - if (node->contents < 0) - { + + if (node->contents < 0) { if (node->contents != CONTENTS_SOLID) - r_pefragtopnode = node; // we've reached a non-solid leaf, so it's - // visible and not BSP clipped + r_pefragtopnode = node; // we've reached a non-solid leaf, so + // it's + // visible and not BSP clipped return; } - + splitplane = node->plane; - sides = BOX_ON_PLANE_SIDE(r_emins, r_emaxs, splitplane); - - if (sides == 3) - { - // remember first splitter + sides = BOX_ON_PLANE_SIDE (r_emins, r_emaxs, splitplane); + + if (sides == 3) { + // remember first splitter r_pefragtopnode = node; return; } - // not split yet; recurse down the contacted side if (sides & 1) R_SplitEntityOnNode2 (node->children[0]); @@ -212,26 +202,26 @@ void R_SplitEntityOnNode2 (mnode_t *node) R_AddEfrags =========== */ -void R_AddEfrags (entity_t *ent) +void +R_AddEfrags (entity_t *ent) { - model_t *entmodel; - int i; - + model_t *entmodel; + int i; + if (!ent->model) return; if (ent == &r_worldentity) - return; // never add the world + return; // never add the world r_addent = ent; - + lastlink = &ent->efrag; r_pefragtopnode = NULL; - + entmodel = ent->model; - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { r_emins[i] = ent->origin[i] + entmodel->mins[i]; r_emaxs[i] = ent->origin[i] + entmodel->maxs[i]; } @@ -249,41 +239,38 @@ R_StoreEfrags // FIXME: a lot of this goes away with edge-based ================ */ -void R_StoreEfrags (efrag_t **ppefrag) +void +R_StoreEfrags (efrag_t **ppefrag) { - entity_t *pent; - model_t *clmodel; - efrag_t *pefrag; + entity_t *pent; + model_t *clmodel; + efrag_t *pefrag; - while ((pefrag = *ppefrag) != NULL) - { + while ((pefrag = *ppefrag) != NULL) { pent = pefrag->entity; clmodel = pent->model; - switch (clmodel->type) - { - case mod_alias: - case mod_brush: - case mod_sprite: - pent = pefrag->entity; + switch (clmodel->type) { + case mod_alias: + case mod_brush: + case mod_sprite: + pent = pefrag->entity; - if ((pent->visframe != r_framecount) && - (cl_numvisedicts < MAX_VISEDICTS)) - { - cl_visedicts[cl_numvisedicts++] = *pent; + if ((pent->visframe != r_framecount) && + (cl_numvisedicts < MAX_VISEDICTS)) { + cl_visedicts[cl_numvisedicts++] = *pent; - // mark that we've recorded this entity for this frame - pent->visframe = r_framecount; - } + // mark that we've recorded this entity for this frame + pent->visframe = r_framecount; + } - ppefrag = &pefrag->leafnext; - break; + ppefrag = &pefrag->leafnext; + break; - default: - Sys_Error ("R_StoreEfrags: Bad entity type %d\n", clmodel->type); + default: + Sys_Error ("R_StoreEfrags: Bad entity type %d\n", + clmodel->type); } } } - - diff --git a/source/r_light.c b/source/r_light.c index 5025ccf..f253038 100644 --- a/source/r_light.c +++ b/source/r_light.c @@ -27,11 +27,11 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" -int r_dlightframecount; +int r_dlightframecount; /* @@ -39,26 +39,25 @@ int r_dlightframecount; R_AnimateLight ================== */ -void R_AnimateLight (void) +void +R_AnimateLight (void) { - int i,j,k; - + int i, j, k; + // // light animations // 'm' is normal light, 'a' is no light, 'z' is double bright - i = (int)(cl.time*10); - for (j=0 ; jcontents < 0) return; splitplane = node->plane; dist = DotProduct (lightorigin, splitplane->normal) - splitplane->dist; - - if (dist > light->radius) - { + + if (dist > light->radius) { R_MarkLights (lightorigin, light, bit, node->children[0]); return; } - if (dist < -light->radius) - { + if (dist < -light->radius) { R_MarkLights (lightorigin, light, bit, node->children[1]); return; } - // mark the polygons surf = cl.worldmodel->surfaces + node->firstsurface; - for (i=0 ; inumsurfaces ; i++, surf++) - { - if (surf->dlightframe != r_dlightframecount) - { + for (i = 0; i < node->numsurfaces; i++, surf++) { + if (surf->dlightframe != r_dlightframecount) { surf->dlightbits = 0; surf->dlightframe = r_dlightframecount; } @@ -121,22 +116,22 @@ void R_MarkLights (vec3_t lightorigin, dlight_t *light, int bit, mnode_t *node) R_PushDlights ============= */ -void R_PushDlights (vec3_t entorigin) +void +R_PushDlights (vec3_t entorigin) { - int i; - dlight_t *l; - vec3_t lightorigin; + int i; + dlight_t *l; + vec3_t lightorigin; r_dlightframecount = r_framecount + 1; // because the count hasn't - // advanced yet for this frame + // advanced yet for this frame l = cl_dlights; - for (i=0 ; idie < cl.time || !l->radius) continue; - VectorSubtract(l->origin, entorigin, lightorigin); - R_MarkLights (lightorigin, l, 1<nodes ); + VectorSubtract (l->origin, entorigin, lightorigin); + R_MarkLights (lightorigin, l, 1 << i, cl.worldmodel->nodes); } } @@ -149,24 +144,25 @@ LIGHT SAMPLING ============================================================================= */ -int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) +int +RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) { - int r; - float front, back, frac; - int side; - mplane_t *plane; - vec3_t mid; - msurface_t *surf; - int s, t, ds, dt; - int i; - mtexinfo_t *tex; - byte *lightmap; - unsigned int scale; - int maps; + int r; + float front, back, frac; + int side; + mplane_t *plane; + vec3_t mid; + msurface_t *surf; + int s, t, ds, dt; + int i; + mtexinfo_t *tex; + byte *lightmap; + unsigned int scale; + int maps; if (node->contents < 0) - return -1; // didn't hit anything - + return -1; // didn't hit anything + // calculate mid point // FIXME: optimize for axial @@ -174,44 +170,42 @@ int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) front = DotProduct (start, plane->normal) - plane->dist; back = DotProduct (end, plane->normal) - plane->dist; side = front < 0; - - if ( (back < 0) == side) + + if ((back < 0) == side) return RecursiveLightPoint (node->children[side], start, end); - - frac = front / (front-back); - mid[0] = start[0] + (end[0] - start[0])*frac; - mid[1] = start[1] + (end[1] - start[1])*frac; - mid[2] = start[2] + (end[2] - start[2])*frac; - -// go down front side + + frac = front / (front - back); + mid[0] = start[0] + (end[0] - start[0]) * frac; + mid[1] = start[1] + (end[1] - start[1]) * frac; + mid[2] = start[2] + (end[2] - start[2]) * frac; + +// go down front side r = RecursiveLightPoint (node->children[side], start, mid); if (r >= 0) - return r; // hit something - - if ( (back < 0) == side ) - return -1; // didn't hit anuthing - + return r; // hit something + + if ((back < 0) == side) + return -1; // didn't hit anuthing + // check for impact on this node surf = cl.worldmodel->surfaces + node->firstsurface; - for (i=0 ; inumsurfaces ; i++, surf++) - { + for (i = 0; i < node->numsurfaces; i++, surf++) { if (surf->flags & SURF_DRAWTILED) - continue; // no lightmaps + continue; // no lightmaps tex = surf->texinfo; - + s = DotProduct (mid, tex->vecs[0]) + tex->vecs[0][3]; t = DotProduct (mid, tex->vecs[1]) + tex->vecs[1][3];; - if (s < surf->texturemins[0] || - t < surf->texturemins[1]) + if (s < surf->texturemins[0] || t < surf->texturemins[1]) continue; - + ds = s - surf->texturemins[0]; dt = t - surf->texturemins[1]; - - if ( ds > surf->extents[0] || dt > surf->extents[1] ) + + if (ds > surf->extents[0] || dt > surf->extents[1]) continue; if (!surf->samples) @@ -222,23 +216,21 @@ int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) lightmap = surf->samples; r = 0; - if (lightmap) - { + if (lightmap) { - lightmap += dt * ((surf->extents[0]>>4)+1) + ds; + lightmap += dt * ((surf->extents[0] >> 4) + 1) + ds; - for (maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[maps] != 255 ; - maps++) - { + for (maps = 0; maps < MAXLIGHTMAPS && surf->styles[maps] != 255; + maps++) { scale = d_lightstylevalue[surf->styles[maps]]; r += *lightmap * scale; - lightmap += ((surf->extents[0]>>4)+1) * - ((surf->extents[1]>>4)+1); + lightmap += ((surf->extents[0] >> 4) + 1) * + ((surf->extents[1] >> 4) + 1); } - + r >>= 8; } - + return r; } @@ -246,20 +238,21 @@ int RecursiveLightPoint (mnode_t *node, vec3_t start, vec3_t end) return RecursiveLightPoint (node->children[!side], mid, end); } -int R_LightPoint (vec3_t p) +int +R_LightPoint (vec3_t p) { - vec3_t end; - int r; - + vec3_t end; + int r; + if (!cl.worldmodel->lightdata) return 255; - + end[0] = p[0]; end[1] = p[1]; end[2] = p[2] - 2048; - + r = RecursiveLightPoint (cl.worldmodel->nodes, p, end); - + if (r == -1) r = 0; @@ -268,4 +261,3 @@ int R_LightPoint (vec3_t p) return r; } - diff --git a/source/r_main.c b/source/r_main.c index ae18f27..f2359ce 100644 --- a/source/r_main.c +++ b/source/r_main.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -44,194 +44,202 @@ #include -//define PASSAGES +//define PASSAGES -void *colormap; -vec3_t viewlightvec; -alight_t r_viewlighting = {128, 192, viewlightvec}; -float r_time1; -int r_numallocatededges; -qboolean r_drawpolys; -qboolean r_drawculledpolys; -qboolean r_worldpolysbacktofront; -qboolean r_recursiveaffinetriangles = true; -int r_pixbytes = 1; -float r_aliasuvscale = 1.0; -int r_outofsurfaces; -int r_outofedges; +void *colormap; +vec3_t viewlightvec; +alight_t r_viewlighting = { 128, 192, viewlightvec }; +float r_time1; +int r_numallocatededges; +qboolean r_drawpolys; +qboolean r_drawculledpolys; +qboolean r_worldpolysbacktofront; +qboolean r_recursiveaffinetriangles = true; +int r_pixbytes = 1; +float r_aliasuvscale = 1.0; +int r_outofsurfaces; +int r_outofedges; -qboolean r_dowarp, r_dowarpold, r_viewchanged; +qboolean r_dowarp, r_dowarpold, r_viewchanged; -int numbtofpolys; -btofpoly_t *pbtofpolys; -mvertex_t *r_pcurrentvertbase; +int numbtofpolys; +btofpoly_t *pbtofpolys; +mvertex_t *r_pcurrentvertbase; -int c_surf; -int r_maxsurfsseen, r_maxedgesseen, r_cnumsurfs; -qboolean r_surfsonstack; -int r_clipflags; +int c_surf; +int r_maxsurfsseen, r_maxedgesseen, r_cnumsurfs; +qboolean r_surfsonstack; +int r_clipflags; -byte *r_warpbuffer; +byte *r_warpbuffer; -byte *r_stack_start; +byte *r_stack_start; -qboolean r_fov_greater_than_90; +qboolean r_fov_greater_than_90; -entity_t r_worldentity; +entity_t r_worldentity; -mplane_t frustum[4]; +mplane_t frustum[4]; // // view origin // -vec3_t vup, base_vup; -vec3_t vpn, base_vpn; -vec3_t vright, base_vright; -vec3_t r_origin; +vec3_t vup, base_vup; +vec3_t vpn, base_vpn; +vec3_t vright, base_vright; +vec3_t r_origin; // // screen size info // -refdef_t r_refdef; -float xcenter, ycenter; -float xscale, yscale; -float xscaleinv, yscaleinv; -float xscaleshrink, yscaleshrink; -float aliasxscale, aliasyscale, aliasxcenter, aliasycenter; +refdef_t r_refdef; +float xcenter, ycenter; +float xscale, yscale; +float xscaleinv, yscaleinv; +float xscaleshrink, yscaleshrink; +float aliasxscale, aliasyscale, aliasxcenter, aliasycenter; -int screenwidth; +int screenwidth; -float pixelAspect; -float screenAspect; -float verticalFieldOfView; -float xOrigin, yOrigin; +float pixelAspect; +float screenAspect; +float verticalFieldOfView; +float xOrigin, yOrigin; -mplane_t screenedge[4]; +mplane_t screenedge[4]; // // refresh flags // -int r_framecount = 1; // so frame counts initialized to 0 don't match -int r_visframecount; -int d_spanpixcount; -int r_polycount; -int r_drawnpolycount; -int r_wholepolycount; +int r_framecount = 1; // so frame counts initialized to 0 -int *pfrustum_indexes[4]; -int r_frustum_indexes[4*6]; + // don't match +int r_visframecount; +int d_spanpixcount; +int r_polycount; +int r_drawnpolycount; +int r_wholepolycount; -int reinit_surfcache = 1; // if 1, surface cache is currently empty and - // must be reinitialized for current cache size +int *pfrustum_indexes[4]; +int r_frustum_indexes[4 * 6]; -mleaf_t *r_viewleaf, *r_oldviewleaf; +int reinit_surfcache = 1; // if 1, surface cache is currently -float r_aliastransition, r_resfudge; + // empty and + // must be reinitialized for current cache + // size -int d_lightstylevalue[256]; // 8.8 fraction of base light value +mleaf_t *r_viewleaf, *r_oldviewleaf; -float dp_time1, dp_time2, db_time1, db_time2, rw_time1, rw_time2; -float se_time1, se_time2, de_time1, de_time2, dv_time1, dv_time2; +float r_aliastransition, r_resfudge; -void R_MarkLeaves (void); +int d_lightstylevalue[256]; // 8.8 fraction of base light value -cvar_t *r_draworder; -cvar_t *r_speeds; -cvar_t *r_timegraph; -cvar_t *r_netgraph; -cvar_t *r_zgraph; -cvar_t *r_graphheight; -cvar_t *r_clearcolor; -cvar_t *r_waterwarp; -cvar_t *r_drawentities; -cvar_t *r_drawviewmodel; -cvar_t *r_aliasstats; -cvar_t *r_dspeeds; -cvar_t *r_drawflat; -cvar_t *r_ambient; -cvar_t *r_reportsurfout; -cvar_t *r_maxsurfs; -cvar_t *r_numsurfs; -cvar_t *r_reportedgeout; -cvar_t *r_maxedges; -cvar_t *r_numedges; -cvar_t *r_aliastransbase; -cvar_t *r_aliastransadj; +float dp_time1, dp_time2, db_time1, db_time2, rw_time1, rw_time2; +float se_time1, se_time2, de_time1, de_time2, dv_time1, dv_time2; -cvar_t *gl_flashblend; +void R_MarkLeaves (void); -extern cvar_t *scr_fov; +cvar_t *r_draworder; +cvar_t *r_speeds; +cvar_t *r_timegraph; +cvar_t *r_netgraph; +cvar_t *r_zgraph; +cvar_t *r_graphheight; +cvar_t *r_clearcolor; +cvar_t *r_waterwarp; +cvar_t *r_drawentities; +cvar_t *r_drawviewmodel; +cvar_t *r_aliasstats; +cvar_t *r_dspeeds; +cvar_t *r_drawflat; +cvar_t *r_ambient; +cvar_t *r_reportsurfout; +cvar_t *r_maxsurfs; +cvar_t *r_numsurfs; +cvar_t *r_reportedgeout; +cvar_t *r_maxedges; +cvar_t *r_numedges; +cvar_t *r_aliastransbase; +cvar_t *r_aliastransadj; -void CreatePassages (void); -void SetVisibilityByPassages (void); +cvar_t *gl_flashblend; -void R_NetGraph (void); -void R_ZGraph (void); +extern cvar_t *scr_fov; + +void CreatePassages (void); +void SetVisibilityByPassages (void); + +void R_NetGraph (void); +void R_ZGraph (void); /* ================== R_Textures_Init ================== */ -void R_Textures_Init (void) +void +R_Textures_Init (void) { - int x,y, m; - byte *dest; - + int x, y, m; + byte *dest; + // create a simple checkerboard texture for the default - r_notexture_mip = Hunk_AllocName (sizeof(texture_t) + 16*16+8*8+4*4+2*2, "notexture"); - + r_notexture_mip = + Hunk_AllocName (sizeof (texture_t) + 16 * 16 + 8 * 8 + 4 * 4 + 2 * 2, + "notexture"); + r_notexture_mip->width = r_notexture_mip->height = 16; - r_notexture_mip->offsets[0] = sizeof(texture_t); - r_notexture_mip->offsets[1] = r_notexture_mip->offsets[0] + 16*16; - r_notexture_mip->offsets[2] = r_notexture_mip->offsets[1] + 8*8; - r_notexture_mip->offsets[3] = r_notexture_mip->offsets[2] + 4*4; - - for (m=0 ; m<4 ; m++) - { - dest = (byte *)r_notexture_mip + r_notexture_mip->offsets[m]; - for (y=0 ; y< (16>>m) ; y++) - for (x=0 ; x< (16>>m) ; x++) - { - if ( (y< (8>>m) ) ^ (x< (8>>m) ) ) + r_notexture_mip->offsets[0] = sizeof (texture_t); + + r_notexture_mip->offsets[1] = r_notexture_mip->offsets[0] + 16 * 16; + r_notexture_mip->offsets[2] = r_notexture_mip->offsets[1] + 8 * 8; + r_notexture_mip->offsets[3] = r_notexture_mip->offsets[2] + 4 * 4; + + for (m = 0; m < 4; m++) { + dest = (byte *) r_notexture_mip + r_notexture_mip->offsets[m]; + for (y = 0; y < (16 >> m); y++) + for (x = 0; x < (16 >> m); x++) { + if ((y < (8 >> m)) ^ (x < (8 >> m))) *dest++ = 0; else *dest++ = 0xff; } - } + } } -void R_LoadSky_f (void); +void R_LoadSky_f (void); /* =============== R_Init =============== */ -void R_Init (void) +void +R_Init (void) { - int dummy; + int dummy; - allowskybox = false; // server decides this --KB + allowskybox = false; // server decides this --KB // get stack position so we can guess if we are going to overflow - r_stack_start = (byte *)&dummy; - + r_stack_start = (byte *) & dummy; + R_InitTurb (); - - Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); - Cmd_AddCommand ("pointfile", R_ReadPointFile_f); + + Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); + Cmd_AddCommand ("pointfile", R_ReadPointFile_f); Cmd_AddCommand ("loadsky", R_LoadSky_f); - Cvar_SetValue (r_maxedges, (float)NUMSTACKEDGES); - Cvar_SetValue (r_maxsurfs, (float)NUMSTACKSURFACES); + Cvar_SetValue (r_maxedges, (float) NUMSTACKEDGES); + Cvar_SetValue (r_maxsurfs, (float) NUMSTACKSURFACES); view_clipplanes[0].leftedge = true; view_clipplanes[1].rightedge = true; view_clipplanes[1].leftedge = view_clipplanes[2].leftedge = - view_clipplanes[3].leftedge = false; + view_clipplanes[3].leftedge = false; view_clipplanes[0].rightedge = view_clipplanes[2].rightedge = - view_clipplanes[3].rightedge = false; + view_clipplanes[3].rightedge = false; r_refdef.xOrigin = XCENTERING; r_refdef.yOrigin = YCENTERING; @@ -240,40 +248,44 @@ void R_Init (void) // TODO: collect 386-specific code in one place #ifdef USE_INTEL_ASM - Sys_MakeCodeWriteable ((long)R_EdgeCodeStart, - (long)R_EdgeCodeEnd - (long)R_EdgeCodeStart); -#endif // USE_INTEL_ASM + Sys_MakeCodeWriteable ((long) R_EdgeCodeStart, + (long) R_EdgeCodeEnd - (long) R_EdgeCodeStart); +#endif // USE_INTEL_ASM D_Init (); } -void R_Init_Cvars (void) +void +R_Init_Cvars (void) { D_Init_Cvars (); - r_draworder = Cvar_Get("r_draworder", "0", CVAR_NONE, "None"); - r_speeds = Cvar_Get("r_speeds", "0", CVAR_NONE, "None"); - r_timegraph = Cvar_Get("r_timegraph", "0", CVAR_NONE, "None"); - r_netgraph = Cvar_Get("r_netgraph", "0", CVAR_NONE, "None"); - r_zgraph = Cvar_Get("r_zgraph", "0", CVAR_NONE, "None"); - r_graphheight = Cvar_Get("r_graphheight", "15", CVAR_NONE, "None"); - r_drawflat = Cvar_Get("r_drawflat", "0", CVAR_NONE, "None"); - r_ambient = Cvar_Get("r_ambient", "0", CVAR_NONE, "None"); - r_clearcolor = Cvar_Get("r_clearcolor", "2", CVAR_NONE, "None"); - r_waterwarp = Cvar_Get("r_waterwarp", "1", CVAR_NONE, "None"); - r_drawentities = Cvar_Get("r_drawentities", "1", CVAR_NONE, "None"); - r_drawviewmodel = Cvar_Get("r_drawviewmodel", "1", CVAR_ARCHIVE, "None"); - r_aliasstats = Cvar_Get("r_polymodelstats", "0", CVAR_NONE, "None"); - r_dspeeds = Cvar_Get("r_dspeeds", "0", CVAR_NONE, "None"); - r_reportsurfout = Cvar_Get("r_reportsurfout", "0", CVAR_NONE, "None"); - r_maxsurfs = Cvar_Get("r_maxsurfs", "0", CVAR_NONE, "None"); - r_numsurfs = Cvar_Get("r_numsurfs", "0", CVAR_NONE, "None"); - r_reportedgeout = Cvar_Get("r_reportedgeout", "0", CVAR_NONE, "None"); - r_maxedges = Cvar_Get("r_maxedges", "0", CVAR_NONE, "None"); - r_numedges = Cvar_Get("r_numedges", "0", CVAR_NONE, "None"); - r_aliastransbase = Cvar_Get("r_aliastransbase", "200", CVAR_NONE, "None"); - r_aliastransadj = Cvar_Get("r_aliastransadj", "100", CVAR_NONE, "None"); - gl_flashblend = Cvar_Get("gl_flashblend", "0", CVAR_NONE, "None"); // FIXME: remove this! --KB + r_draworder = Cvar_Get ("r_draworder", "0", CVAR_NONE, "None"); + r_speeds = Cvar_Get ("r_speeds", "0", CVAR_NONE, "None"); + r_timegraph = Cvar_Get ("r_timegraph", "0", CVAR_NONE, "None"); + r_netgraph = Cvar_Get ("r_netgraph", "0", CVAR_NONE, "None"); + r_zgraph = Cvar_Get ("r_zgraph", "0", CVAR_NONE, "None"); + r_graphheight = Cvar_Get ("r_graphheight", "15", CVAR_NONE, "None"); + r_drawflat = Cvar_Get ("r_drawflat", "0", CVAR_NONE, "None"); + r_ambient = Cvar_Get ("r_ambient", "0", CVAR_NONE, "None"); + r_clearcolor = Cvar_Get ("r_clearcolor", "2", CVAR_NONE, "None"); + r_waterwarp = Cvar_Get ("r_waterwarp", "1", CVAR_NONE, "None"); + r_drawentities = Cvar_Get ("r_drawentities", "1", CVAR_NONE, "None"); + r_drawviewmodel = Cvar_Get ("r_drawviewmodel", "1", CVAR_ARCHIVE, "None"); + r_aliasstats = Cvar_Get ("r_polymodelstats", "0", CVAR_NONE, "None"); + r_dspeeds = Cvar_Get ("r_dspeeds", "0", CVAR_NONE, "None"); + r_reportsurfout = Cvar_Get ("r_reportsurfout", "0", CVAR_NONE, "None"); + r_maxsurfs = Cvar_Get ("r_maxsurfs", "0", CVAR_NONE, "None"); + r_numsurfs = Cvar_Get ("r_numsurfs", "0", CVAR_NONE, "None"); + r_reportedgeout = Cvar_Get ("r_reportedgeout", "0", CVAR_NONE, "None"); + r_maxedges = Cvar_Get ("r_maxedges", "0", CVAR_NONE, "None"); + r_numedges = Cvar_Get ("r_numedges", "0", CVAR_NONE, "None"); + r_aliastransbase = Cvar_Get ("r_aliastransbase", "200", CVAR_NONE, "None"); + r_aliastransadj = Cvar_Get ("r_aliastransadj", "100", CVAR_NONE, "None"); + gl_flashblend = Cvar_Get ("gl_flashblend", "0", CVAR_NONE, "None"); // FIXME: + // remove + // this! + // --KB } @@ -282,18 +294,19 @@ void R_Init_Cvars (void) R_NewMap =============== */ -void R_NewMap (void) +void +R_NewMap (void) { - int i; - - memset (&r_worldentity, 0, sizeof(r_worldentity)); + int i; + + memset (&r_worldentity, 0, sizeof (r_worldentity)); r_worldentity.model = cl.worldmodel; // clear out efrags in case the level hasn't been reloaded // FIXME: is this one short? - for (i=0 ; inumleafs ; i++) + for (i = 0; i < cl.worldmodel->numleafs; i++) cl.worldmodel->leafs[i].efrags = NULL; - + r_viewleaf = NULL; R_ClearParticles (); @@ -302,19 +315,17 @@ void R_NewMap (void) if (r_cnumsurfs <= MINSURFACES) r_cnumsurfs = MINSURFACES; - if (r_cnumsurfs > NUMSTACKSURFACES) - { - surfaces = Hunk_AllocName (r_cnumsurfs * sizeof(surf_t), "surfaces"); + if (r_cnumsurfs > NUMSTACKSURFACES) { + surfaces = Hunk_AllocName (r_cnumsurfs * sizeof (surf_t), "surfaces"); + surface_p = surfaces; surf_max = &surfaces[r_cnumsurfs]; r_surfsonstack = false; - // surface 0 doesn't really exist; it's just a dummy because index 0 - // is used to indicate no edge attached to surface + // surface 0 doesn't really exist; it's just a dummy because index 0 + // is used to indicate no edge attached to surface surfaces--; R_SurfacePatch (); - } - else - { + } else { r_surfsonstack = true; } @@ -326,13 +337,10 @@ void R_NewMap (void) if (r_numallocatededges < MINEDGES) r_numallocatededges = MINEDGES; - if (r_numallocatededges <= NUMSTACKEDGES) - { + if (r_numallocatededges <= NUMSTACKEDGES) { auxedges = NULL; - } - else - { - auxedges = Hunk_AllocName (r_numallocatededges * sizeof(edge_t), + } else { + auxedges = Hunk_AllocName (r_numallocatededges * sizeof (edge_t), "edges"); } @@ -346,11 +354,12 @@ void R_NewMap (void) R_SetVrect =============== */ -void R_SetVrect (vrect_t *pvrectin, vrect_t *pvrect, int lineadj) +void +R_SetVrect (vrect_t *pvrectin, vrect_t *pvrect, int lineadj) { - int h; - float size; - qboolean full = false; + int h; + float size; + qboolean full = false; if (scr_viewsize->int_val >= 100) { size = 100.0; @@ -358,8 +367,7 @@ void R_SetVrect (vrect_t *pvrectin, vrect_t *pvrect, int lineadj) } else size = scr_viewsize->int_val; - if (cl.intermission) - { + if (cl.intermission) { full = true; size = 100.0; lineadj = 0; @@ -371,33 +379,31 @@ void R_SetVrect (vrect_t *pvrectin, vrect_t *pvrect, int lineadj) else h = pvrectin->height - lineadj; -// h = (!cl_sbar->int_val && size==1.0) ? pvrectin->height : (pvrectin->height - lineadj); -// h = pvrectin->height - lineadj; +// h = (!cl_sbar->int_val && size==1.0) ? pvrectin->height : (pvrectin->height - lineadj); +// h = pvrectin->height - lineadj; if (full) pvrect->width = pvrectin->width; else pvrect->width = pvrectin->width * size; - if (pvrect->width < 96) - { + if (pvrect->width < 96) { size = 96.0 / pvrectin->width; - pvrect->width = 96; // min for icons + pvrect->width = 96; // min for icons } pvrect->width &= ~7; pvrect->height = pvrectin->height * size; if (cl_sbar->int_val || !full) { if (pvrect->height > pvrectin->height - lineadj) pvrect->height = pvrectin->height - lineadj; - } else - if (pvrect->height > pvrectin->height) - pvrect->height = pvrectin->height; + } else if (pvrect->height > pvrectin->height) + pvrect->height = pvrectin->height; pvrect->height &= ~1; - pvrect->x = (pvrectin->width - pvrect->width)/2; + pvrect->x = (pvrectin->width - pvrect->width) / 2; if (full) pvrect->y = 0; else - pvrect->y = (h - pvrect->height)/2; + pvrect->y = (h - pvrect->height) / 2; } @@ -409,45 +415,46 @@ Called every time the vid structure or r_refdef changes. Guaranteed to be called before the first refresh =============== */ -void R_ViewChanged (vrect_t *pvrect, int lineadj, float aspect) +void +R_ViewChanged (vrect_t *pvrect, int lineadj, float aspect) { - int i; - float res_scale; + int i; + float res_scale; r_viewchanged = true; R_SetVrect (pvrect, &r_refdef.vrect, lineadj); - r_refdef.horizontalFieldOfView = 2.0 * tan (r_refdef.fov_x/360*M_PI); - r_refdef.fvrectx = (float)r_refdef.vrect.x; - r_refdef.fvrectx_adj = (float)r_refdef.vrect.x - 0.5; - r_refdef.vrect_x_adj_shift20 = (r_refdef.vrect.x<<20) + (1<<19) - 1; - r_refdef.fvrecty = (float)r_refdef.vrect.y; - r_refdef.fvrecty_adj = (float)r_refdef.vrect.y - 0.5; + r_refdef.horizontalFieldOfView = 2.0 * tan (r_refdef.fov_x / 360 * M_PI); + r_refdef.fvrectx = (float) r_refdef.vrect.x; + r_refdef.fvrectx_adj = (float) r_refdef.vrect.x - 0.5; + r_refdef.vrect_x_adj_shift20 = (r_refdef.vrect.x << 20) + (1 << 19) - 1; + r_refdef.fvrecty = (float) r_refdef.vrect.y; + r_refdef.fvrecty_adj = (float) r_refdef.vrect.y - 0.5; r_refdef.vrectright = r_refdef.vrect.x + r_refdef.vrect.width; - r_refdef.vrectright_adj_shift20 = (r_refdef.vrectright<<20) + (1<<19) - 1; - r_refdef.fvrectright = (float)r_refdef.vrectright; - r_refdef.fvrectright_adj = (float)r_refdef.vrectright - 0.5; - r_refdef.vrectrightedge = (float)r_refdef.vrectright - 0.99; + r_refdef.vrectright_adj_shift20 = + (r_refdef.vrectright << 20) + (1 << 19) - 1; + r_refdef.fvrectright = (float) r_refdef.vrectright; + r_refdef.fvrectright_adj = (float) r_refdef.vrectright - 0.5; + r_refdef.vrectrightedge = (float) r_refdef.vrectright - 0.99; r_refdef.vrectbottom = r_refdef.vrect.y + r_refdef.vrect.height; - r_refdef.fvrectbottom = (float)r_refdef.vrectbottom; - r_refdef.fvrectbottom_adj = (float)r_refdef.vrectbottom - 0.5; + r_refdef.fvrectbottom = (float) r_refdef.vrectbottom; + r_refdef.fvrectbottom_adj = (float) r_refdef.vrectbottom - 0.5; - r_refdef.aliasvrect.x = (int)(r_refdef.vrect.x * r_aliasuvscale); - r_refdef.aliasvrect.y = (int)(r_refdef.vrect.y * r_aliasuvscale); - r_refdef.aliasvrect.width = (int)(r_refdef.vrect.width * r_aliasuvscale); - r_refdef.aliasvrect.height = (int)(r_refdef.vrect.height * r_aliasuvscale); + r_refdef.aliasvrect.x = (int) (r_refdef.vrect.x * r_aliasuvscale); + r_refdef.aliasvrect.y = (int) (r_refdef.vrect.y * r_aliasuvscale); + r_refdef.aliasvrect.width = (int) (r_refdef.vrect.width * r_aliasuvscale); + r_refdef.aliasvrect.height = (int) (r_refdef.vrect.height * r_aliasuvscale); r_refdef.aliasvrectright = r_refdef.aliasvrect.x + - r_refdef.aliasvrect.width; + r_refdef.aliasvrect.width; r_refdef.aliasvrectbottom = r_refdef.aliasvrect.y + - r_refdef.aliasvrect.height; + r_refdef.aliasvrect.height; pixelAspect = aspect; xOrigin = r_refdef.xOrigin; yOrigin = r_refdef.yOrigin; - - screenAspect = r_refdef.vrect.width*pixelAspect / - r_refdef.vrect.height; + + screenAspect = r_refdef.vrect.width * pixelAspect / r_refdef.vrect.height; // 320*200 1.0 pixelAspect = 1.6 screenAspect // 320*240 1.0 pixelAspect = 1.3333 screenAspect // proper 320*200 pixelAspect = 0.8333333 @@ -460,11 +467,11 @@ void R_ViewChanged (vrect_t *pvrect, int lineadj, float aspect) // the polygon rasterization will never render in the first row or column // but will definately render in the [range] row and column, so adjust the // buffer origin to get an exact edge to edge fill - xcenter = ((float)r_refdef.vrect.width * XCENTERING) + - r_refdef.vrect.x - 0.5; + xcenter = ((float) r_refdef.vrect.width * XCENTERING) + + r_refdef.vrect.x - 0.5; aliasxcenter = xcenter * r_aliasuvscale; - ycenter = ((float)r_refdef.vrect.height * YCENTERING) + - r_refdef.vrect.y - 0.5; + ycenter = ((float) r_refdef.vrect.height * YCENTERING) + + r_refdef.vrect.y - 0.5; aliasycenter = ycenter * r_aliasuvscale; xscale = r_refdef.vrect.width / r_refdef.horizontalFieldOfView; @@ -473,40 +480,39 @@ void R_ViewChanged (vrect_t *pvrect, int lineadj, float aspect) yscale = xscale * pixelAspect; aliasyscale = yscale * r_aliasuvscale; yscaleinv = 1.0 / yscale; - xscaleshrink = (r_refdef.vrect.width-6)/r_refdef.horizontalFieldOfView; - yscaleshrink = xscaleshrink*pixelAspect; + xscaleshrink = (r_refdef.vrect.width - 6) / r_refdef.horizontalFieldOfView; + yscaleshrink = xscaleshrink * pixelAspect; // left side clip - screenedge[0].normal[0] = -1.0 / (xOrigin*r_refdef.horizontalFieldOfView); + screenedge[0].normal[0] = -1.0 / (xOrigin * r_refdef.horizontalFieldOfView); screenedge[0].normal[1] = 0; screenedge[0].normal[2] = 1; screenedge[0].type = PLANE_ANYZ; - + // right side clip screenedge[1].normal[0] = - 1.0 / ((1.0-xOrigin)*r_refdef.horizontalFieldOfView); + 1.0 / ((1.0 - xOrigin) * r_refdef.horizontalFieldOfView); screenedge[1].normal[1] = 0; screenedge[1].normal[2] = 1; screenedge[1].type = PLANE_ANYZ; - + // top side clip screenedge[2].normal[0] = 0; - screenedge[2].normal[1] = -1.0 / (yOrigin*verticalFieldOfView); + screenedge[2].normal[1] = -1.0 / (yOrigin * verticalFieldOfView); screenedge[2].normal[2] = 1; screenedge[2].type = PLANE_ANYZ; - + // bottom side clip screenedge[3].normal[0] = 0; - screenedge[3].normal[1] = 1.0 / ((1.0-yOrigin)*verticalFieldOfView); - screenedge[3].normal[2] = 1; + screenedge[3].normal[1] = 1.0 / ((1.0 - yOrigin) * verticalFieldOfView); + screenedge[3].normal[2] = 1; screenedge[3].type = PLANE_ANYZ; - - for (i=0 ; i<4 ; i++) + + for (i = 0; i < 4; i++) VectorNormalize (screenedge[i].normal); - res_scale = sqrt ((double)(r_refdef.vrect.width * r_refdef.vrect.height) / - (320.0 * 152.0)) * - (2.0 / r_refdef.horizontalFieldOfView); + res_scale = sqrt ((double) (r_refdef.vrect.width * r_refdef.vrect.height) / + (320.0 * 152.0)) * (2.0 / r_refdef.horizontalFieldOfView); r_aliastransition = r_aliastransbase->value * res_scale; r_resfudge = r_aliastransadj->value * res_scale; @@ -517,21 +523,18 @@ void R_ViewChanged (vrect_t *pvrect, int lineadj, float aspect) // TODO: collect 386-specific code in one place #ifdef USE_INTEL_ASM - if (r_pixbytes == 1) - { - Sys_MakeCodeWriteable ((long)R_Surf8Start, - (long)R_Surf8End - (long)R_Surf8Start); + if (r_pixbytes == 1) { + Sys_MakeCodeWriteable ((long) R_Surf8Start, + (long) R_Surf8End - (long) R_Surf8Start); colormap = vid.colormap; R_Surf8Patch (); - } - else - { - Sys_MakeCodeWriteable ((long)R_Surf16Start, - (long)R_Surf16End - (long)R_Surf16Start); + } else { + Sys_MakeCodeWriteable ((long) R_Surf16Start, + (long) R_Surf16End - (long) R_Surf16Start); colormap = vid.colormap16; R_Surf16Patch (); } -#endif // USE_INTEL_ASM +#endif // USE_INTEL_ASM D_ViewChanged (); } @@ -542,27 +545,25 @@ void R_ViewChanged (vrect_t *pvrect, int lineadj, float aspect) R_MarkLeaves =============== */ -void R_MarkLeaves (void) +void +R_MarkLeaves (void) { - byte *vis; - mnode_t *node; - int i; + byte *vis; + mnode_t *node; + int i; if (r_oldviewleaf == r_viewleaf) return; - + r_visframecount++; r_oldviewleaf = r_viewleaf; vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel); - - for (i=0 ; inumleafs ; i++) - { - if (vis[i>>3] & (1<<(i&7))) - { - node = (mnode_t *)&cl.worldmodel->leafs[i+1]; - do - { + + for (i = 0; i < cl.worldmodel->numleafs; i++) { + if (vis[i >> 3] & (1 << (i & 7))) { + node = (mnode_t *) &cl.worldmodel->leafs[i + 1]; + do { if (node->visframe == r_visframecount) break; node->visframe = r_visframecount; @@ -578,73 +579,70 @@ void R_MarkLeaves (void) R_DrawEntitiesOnList ============= */ -void R_DrawEntitiesOnList (void) +void +R_DrawEntitiesOnList (void) { - int i, j; - int lnum; - alight_t lighting; + int i, j; + int lnum; + alight_t lighting; + // FIXME: remove and do real lighting - float lightvec[3] = {-1, 0, 0}; - vec3_t dist; - float add; + float lightvec[3] = { -1, 0, 0 }; + vec3_t dist; + float add; if (!r_drawentities->int_val) return; - for (i=0 ; imodel->type) - { - case mod_sprite: - VectorCopy (currententity->origin, r_entorigin); - VectorSubtract (r_origin, r_entorigin, modelorg); - R_DrawSprite (); - break; + switch (currententity->model->type) { + case mod_sprite: + VectorCopy (currententity->origin, r_entorigin); + VectorSubtract (r_origin, r_entorigin, modelorg); + R_DrawSprite (); + break; - case mod_alias: - VectorCopy (currententity->origin, r_entorigin); - VectorSubtract (r_origin, r_entorigin, modelorg); + case mod_alias: + VectorCopy (currententity->origin, r_entorigin); + VectorSubtract (r_origin, r_entorigin, modelorg); - // see if the bounding box lets us trivially reject, also sets - // trivial accept status - if (R_AliasCheckBBox ()) - { - j = R_LightPoint (currententity->origin); - - lighting.ambientlight = j; - lighting.shadelight = j; + // see if the bounding box lets us trivially reject, also + // sets + // trivial accept status + if (R_AliasCheckBBox ()) { + j = R_LightPoint (currententity->origin); - lighting.plightvec = lightvec; + lighting.ambientlight = j; + lighting.shadelight = j; - for (lnum=0 ; lnum= cl.time) - { - VectorSubtract (currententity->origin, - cl_dlights[lnum].origin, - dist); - add = cl_dlights[lnum].radius - Length(dist); - - if (add > 0) - lighting.ambientlight += add; + lighting.plightvec = lightvec; + + for (lnum = 0; lnum < MAX_DLIGHTS; lnum++) { + if (cl_dlights[lnum].die >= cl.time) { + VectorSubtract (currententity->origin, + cl_dlights[lnum].origin, dist); + add = cl_dlights[lnum].radius - Length (dist); + + if (add > 0) + lighting.ambientlight += add; + } } + + // clamp lighting so it doesn't overbright as much + if (lighting.ambientlight > 128) + lighting.ambientlight = 128; + if (lighting.ambientlight + lighting.shadelight > 192) + lighting.shadelight = 192 - lighting.ambientlight; + + R_AliasDrawModel (&lighting); } - - // clamp lighting so it doesn't overbright as much - if (lighting.ambientlight > 128) - lighting.ambientlight = 128; - if (lighting.ambientlight + lighting.shadelight > 192) - lighting.shadelight = 192 - lighting.ambientlight; - R_AliasDrawModel (&lighting); - } + break; - break; - - default: - break; + default: + break; } } } @@ -654,18 +652,19 @@ void R_DrawEntitiesOnList (void) R_DrawViewModel ============= */ -void R_DrawViewModel (void) +void +R_DrawViewModel (void) { // FIXME: remove and do real lighting - float lightvec[3] = {-1, 0, 0}; - int j; - int lnum; - vec3_t dist; - float add; - dlight_t *dl; - - if (!r_drawviewmodel->int_val || r_fov_greater_than_90 || !Cam_DrawViewModel()) - return; + float lightvec[3] = { -1, 0, 0 }; + int j; + int lnum; + vec3_t dist; + float add; + dlight_t *dl; + + if (!r_drawviewmodel->int_val || r_fov_greater_than_90 + || !Cam_DrawViewModel ())return; if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY) return; @@ -686,13 +685,12 @@ void R_DrawViewModel (void) j = R_LightPoint (currententity->origin); if (j < 24) - j = 24; // allways give some light on gun + j = 24; // allways give some light on gun r_viewlighting.ambientlight = j; r_viewlighting.shadelight = j; -// add dynamic lights - for (lnum=0 ; lnumradius) continue; @@ -702,7 +700,7 @@ void R_DrawViewModel (void) continue; VectorSubtract (currententity->origin, dl->origin, dist); - add = dl->radius - Length(dist); + add = dl->radius - Length (dist); if (add > 0) r_viewlighting.ambientlight += add; } @@ -724,19 +722,18 @@ void R_DrawViewModel (void) R_BmodelCheckBBox ============= */ -int R_BmodelCheckBBox (model_t *clmodel, float *minmaxs) +int +R_BmodelCheckBBox (model_t *clmodel, float *minmaxs) { - int i, *pindex, clipflags; - vec3_t acceptpt, rejectpt; - double d; + int i, *pindex, clipflags; + vec3_t acceptpt, rejectpt; + double d; clipflags = 0; if (currententity->angles[0] || currententity->angles[1] - || currententity->angles[2]) - { - for (i=0 ; i<4 ; i++) - { + || currententity->angles[2]) { + for (i = 0; i < 4; i++) { d = DotProduct (currententity->origin, view_clipplanes[i].normal); d -= view_clipplanes[i].dist; @@ -744,38 +741,36 @@ int R_BmodelCheckBBox (model_t *clmodel, float *minmaxs) return BMODEL_FULLY_CLIPPED; if (d <= clmodel->radius) - clipflags |= (1<int_val) return; @@ -802,112 +798,104 @@ void R_DrawBEntitiesOnList (void) insubmodel = true; r_dlightframecount = r_framecount; - for (i=0 ; imodel->type) - { - case mod_brush: + switch (currententity->model->type) { + case mod_brush: - clmodel = currententity->model; + clmodel = currententity->model; - // see if the bounding box lets us trivially reject, also sets - // trivial accept status - for (j=0 ; j<3 ; j++) - { - minmaxs[j] = currententity->origin[j] + - clmodel->mins[j]; - minmaxs[3+j] = currententity->origin[j] + + // see if the bounding box lets us trivially reject, also + // sets + // trivial accept status + for (j = 0; j < 3; j++) { + minmaxs[j] = currententity->origin[j] + clmodel->mins[j]; + minmaxs[3 + j] = currententity->origin[j] + clmodel->maxs[j]; - } - - clipflags = R_BmodelCheckBBox (clmodel, minmaxs); - - if (clipflags != BMODEL_FULLY_CLIPPED) - { - VectorCopy (currententity->origin, r_entorigin); - VectorSubtract (r_origin, r_entorigin, modelorg); - // FIXME: is this needed? - VectorCopy (modelorg, r_worldmodelorg); - - r_pcurrentvertbase = clmodel->vertexes; - - // FIXME: stop transforming twice - R_RotateBmodel (); - - // calculate dynamic lighting for bmodel if it's not an - // instanced model - if (clmodel->firstmodelsurface != 0) - { - vec3_t lightorigin; - for (k=0 ; korigin, lightorigin); - R_MarkLights (lightorigin, &cl_dlights[k], 1<nodes + clmodel->hulls[0].firstclipnode); - } } - // if the driver wants polygons, deliver those. Z-buffering is on - // at this point, so no clipping to the world tree is needed, just - // frustum clipping - if (r_drawpolys | r_drawculledpolys) - { - R_ZDrawSubmodelPolys (clmodel); - } - else - { - r_pefragtopnode = NULL; + clipflags = R_BmodelCheckBBox (clmodel, minmaxs); - for (j=0 ; j<3 ; j++) - { - r_emins[j] = minmaxs[j]; - r_emaxs[j] = minmaxs[3+j]; - } + if (clipflags != BMODEL_FULLY_CLIPPED) { + VectorCopy (currententity->origin, r_entorigin); + VectorSubtract (r_origin, r_entorigin, modelorg); + // FIXME: is this needed? + VectorCopy (modelorg, r_worldmodelorg); - R_SplitEntityOnNode2 (cl.worldmodel->nodes); + r_pcurrentvertbase = clmodel->vertexes; - if (r_pefragtopnode) - { - currententity->topnode = r_pefragtopnode; - - if (r_pefragtopnode->contents >= 0) - { - // not a leaf; has to be clipped to the world BSP - r_clipflags = clipflags; - R_DrawSolidClippedSubmodelPolygons (clmodel); + // FIXME: stop transforming twice + R_RotateBmodel (); + + // calculate dynamic lighting for bmodel if it's not an + // instanced model + if (clmodel->firstmodelsurface != 0) { + vec3_t lightorigin; + + for (k = 0; k < MAX_DLIGHTS; k++) { + if ((cl_dlights[k].die < cl.time) || + (!cl_dlights[k].radius)) continue; + + VectorSubtract (cl_dlights[k].origin, + currententity->origin, lightorigin); + R_MarkLights (lightorigin, &cl_dlights[k], 1 << k, + clmodel->nodes + + clmodel->hulls[0].firstclipnode); } - else - { - // falls entirely in one leaf, so we just put all the - // edges in the edge list and let 1/z sorting handle - // drawing order - R_DrawSubmodelPolygons (clmodel, clipflags); - } - - currententity->topnode = NULL; } + // if the driver wants polygons, deliver those. + // Z-buffering is on + // at this point, so no clipping to the world tree is + // needed, just + // frustum clipping + if (r_drawpolys | r_drawculledpolys) { + R_ZDrawSubmodelPolys (clmodel); + } else { + r_pefragtopnode = NULL; + + for (j = 0; j < 3; j++) { + r_emins[j] = minmaxs[j]; + r_emaxs[j] = minmaxs[3 + j]; + } + + R_SplitEntityOnNode2 (cl.worldmodel->nodes); + + if (r_pefragtopnode) { + currententity->topnode = r_pefragtopnode; + + if (r_pefragtopnode->contents >= 0) { + // not a leaf; has to be clipped to the world + // BSP + r_clipflags = clipflags; + R_DrawSolidClippedSubmodelPolygons (clmodel); + } else { + // falls entirely in one leaf, so we just put + // all the + // edges in the edge list and let 1/z sorting + // handle + // drawing order + R_DrawSubmodelPolygons (clmodel, clipflags); + } + + currententity->topnode = NULL; + } + } + + // put back world rotation and frustum clipping + // FIXME: R_RotateBmodel should just work off base_vxx + VectorCopy (base_vpn, vpn); + VectorCopy (base_vup, vup); + VectorCopy (base_vright, vright); + VectorCopy (base_modelorg, modelorg); + VectorCopy (oldorigin, modelorg); + R_TransformFrustum (); } - // put back world rotation and frustum clipping - // FIXME: R_RotateBmodel should just work off base_vxx - VectorCopy (base_vpn, vpn); - VectorCopy (base_vup, vup); - VectorCopy (base_vright, vright); - VectorCopy (base_modelorg, modelorg); - VectorCopy (oldorigin, modelorg); - R_TransformFrustum (); - } + break; - break; - - default: - break; + default: + break; } } @@ -920,38 +908,36 @@ void R_DrawBEntitiesOnList (void) R_EdgeDrawing ================ */ -void R_EdgeDrawing (void) +void +R_EdgeDrawing (void) { - edge_t ledges[NUMSTACKEDGES + - ((CACHE_SIZE - 1) / sizeof(edge_t)) + 1]; - surf_t lsurfs[NUMSTACKSURFACES + - ((CACHE_SIZE - 1) / sizeof(surf_t)) + 1]; + edge_t ledges[NUMSTACKEDGES + - if (auxedges) - { + ((CACHE_SIZE - 1) / sizeof (edge_t)) + 1]; + surf_t lsurfs[NUMSTACKSURFACES + + + ((CACHE_SIZE - 1) / sizeof (surf_t)) + 1]; + + if (auxedges) { r_edges = auxedges; - } - else - { - r_edges = (edge_t *) - (((long)&ledges[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); + } else { + r_edges = (edge_t *) + (((long) &ledges[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); } - if (r_surfsonstack) - { - surfaces = (surf_t *) - (((long)&lsurfs[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); + if (r_surfsonstack) { + surfaces = (surf_t *) + (((long) &lsurfs[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1)); surf_max = &surfaces[r_cnumsurfs]; - // surface 0 doesn't really exist; it's just a dummy because index 0 - // is used to indicate no edge attached to surface + // surface 0 doesn't really exist; it's just a dummy because index 0 + // is used to indicate no edge attached to surface surfaces--; R_SurfacePatch (); } R_BeginEdgeFrame (); - if (r_dspeeds->int_val) - { + if (r_dspeeds->int_val) { rw_time1 = Sys_DoubleTime (); } @@ -964,27 +950,25 @@ void R_EdgeDrawing (void) // z writes, so have the driver turn z compares on now D_TurnZOn (); - if (r_dspeeds->int_val) - { + if (r_dspeeds->int_val) { rw_time2 = Sys_DoubleTime (); db_time1 = rw_time2; } R_DrawBEntitiesOnList (); - if (r_dspeeds->int_val) - { + if (r_dspeeds->int_val) { db_time2 = Sys_DoubleTime (); se_time1 = db_time2; } - if (!r_dspeeds->int_val) - { + if (!r_dspeeds->int_val) { VID_UnlockBuffer (); - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate (); // don't let sound get messed up if + // going slow VID_LockBuffer (); } - + if (!(r_drawpolys | r_drawculledpolys)) R_ScanEdges (); } @@ -997,9 +981,10 @@ R_RenderView r_refdef must be set before the first call ================ */ -void R_RenderView_ (void) +void +R_RenderView_ (void) { - byte warpbuffer[WARP_WIDTH * WARP_HEIGHT]; + byte warpbuffer[WARP_WIDTH * WARP_HEIGHT]; r_warpbuffer = warpbuffer; @@ -1009,9 +994,10 @@ void R_RenderView_ (void) R_SetupFrame (); #ifdef PASSAGES -SetVisibilityByPassages (); + SetVisibilityByPassages (); #else - R_MarkLeaves (); // done here so we know if we're in water + R_MarkLeaves (); // done here so we know if we're in + // water #endif // make FDIV fast. This reduces timing precision after we've been running for a @@ -1022,41 +1008,38 @@ SetVisibilityByPassages (); if (!r_worldentity.model || !cl.worldmodel) Sys_Error ("R_RenderView: NULL worldmodel"); - - if (!r_dspeeds->int_val) - { + + if (!r_dspeeds->int_val) { VID_UnlockBuffer (); - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate (); // don't let sound get messed up if + // going slow VID_LockBuffer (); } - + R_EdgeDrawing (); - if (!r_dspeeds->int_val) - { + if (!r_dspeeds->int_val) { VID_UnlockBuffer (); - S_ExtraUpdate (); // don't let sound get messed up if going slow + S_ExtraUpdate (); // don't let sound get messed up if + // going slow VID_LockBuffer (); } - - if (r_dspeeds->int_val) - { + + if (r_dspeeds->int_val) { se_time2 = Sys_DoubleTime (); de_time1 = se_time2; } R_DrawEntitiesOnList (); - if (r_dspeeds->int_val) - { + if (r_dspeeds->int_val) { de_time2 = Sys_DoubleTime (); dv_time1 = de_time2; } R_DrawViewModel (); - if (r_dspeeds->int_val) - { + if (r_dspeeds->int_val) { dv_time2 = Sys_DoubleTime (); dp_time1 = Sys_DoubleTime (); } @@ -1082,7 +1065,7 @@ SetVisibilityByPassages (); if (r_aliasstats->int_val) R_PrintAliasStats (); - + if (r_speeds->int_val) R_PrintTimes (); @@ -1099,22 +1082,23 @@ SetVisibilityByPassages (); Sys_HighFPPrecision (); } -void R_RenderView (void) +void +R_RenderView (void) { - int dummy; - int delta; - - delta = (byte *)&dummy - r_stack_start; + int dummy; + int delta; + + delta = (byte *) & dummy - r_stack_start; if (delta < -10000 || delta > 10000) Sys_Error ("R_RenderView: called without enough stack"); - if ( Hunk_LowMark() & 3 ) + if (Hunk_LowMark () & 3) Sys_Error ("Hunk is missaligned"); - if ( (long)(&dummy) & 3 ) + if ((long) (&dummy) & 3) Sys_Error ("Stack is missaligned"); - if ( (long)(&r_warpbuffer) & 3 ) + if ((long) (&r_warpbuffer) & 3) Sys_Error ("Globals are missaligned"); R_RenderView_ (); @@ -1125,14 +1109,15 @@ void R_RenderView (void) R_InitTurb ================ */ -void R_InitTurb (void) +void +R_InitTurb (void) { - int i; - - for (i=0 ; i<1280 ; i++) - { - sintable[i] = AMP + sin(i*3.14159*2/CYCLE)*AMP; - intsintable[i] = AMP2 + sin(i*3.14159*2/CYCLE)*AMP2; // AMP2, not 20 + int i; + + for (i = 0; i < 1280; i++) { + sintable[i] = AMP + sin (i * 3.14159 * 2 / CYCLE) * AMP; + intsintable[i] = AMP2 + sin (i * 3.14159 * 2 / CYCLE) * AMP2; // AMP2, + // not + // 20 } } - diff --git a/source/r_misc.c b/source/r_misc.c index edec086..a0ed1b5 100644 --- a/source/r_misc.c +++ b/source/r_misc.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -40,14 +40,17 @@ #include "menu.h" #include "cl_parse.h" -qboolean allowskybox; // whether or not to allow skyboxes --KB +qboolean allowskybox; // whether or not to allow skyboxes + + // --KB /* =============== R_CheckVariables =============== */ -void R_CheckVariables (void) +void +R_CheckVariables (void) { } @@ -59,9 +62,10 @@ Show Debugging use ============ */ -void Show (void) +void +Show (void) { - vrect_t vr; + vrect_t vr; vr.x = vr.y = 0; vr.width = vid.width; @@ -77,19 +81,19 @@ R_TimeRefresh_f For program optimization ==================== */ -void R_TimeRefresh_f (void) +void +R_TimeRefresh_f (void) { - int i; - float start, stop, time; - int startangle; - vrect_t vr; + int i; + float start, stop, time; + int startangle; + vrect_t vr; startangle = r_refdef.viewangles[1]; - + start = Sys_DoubleTime (); - for (i=0 ; i<128 ; i++) - { - r_refdef.viewangles[1] = i/128.0*360.0; + for (i = 0; i < 128; i++) { + r_refdef.viewangles[1] = i / 128.0 * 360.0; VID_LockBuffer (); @@ -105,9 +109,9 @@ void R_TimeRefresh_f (void) VID_Update (&vr); } stop = Sys_DoubleTime (); - time = stop-start; - Con_Printf ("%f seconds (%f fps)\n", time, 128/time); - + time = stop - start; + Con_Printf ("%f seconds (%f fps)\n", time, 128 / time); + r_refdef.viewangles[1] = startangle; } @@ -118,13 +122,12 @@ void R_TimeRefresh_f (void) void R_LoadSky_f (void) { - if (Cmd_Argc () != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("loadsky : load a skybox\n"); return; } - R_LoadSkys (Cmd_Argv(1)); + R_LoadSkys (Cmd_Argv (1)); } @@ -135,44 +138,43 @@ R_LineGraph Only called by R_DisplayTime ================ */ -void R_LineGraph (int x, int y, int h) +void +R_LineGraph (int x, int y, int h) { - int i; - byte *dest; - int s; - int color; + int i; + byte *dest; + int s; + int color; // FIXME: should be disabled on no-buffer adapters, or should be in the driver - -// x += r_refdef.vrect.x; -// y += r_refdef.vrect.y; - - dest = vid.buffer + vid.rowbytes*y + x; - + +// x += r_refdef.vrect.x; +// y += r_refdef.vrect.y; + + dest = vid.buffer + vid.rowbytes * y + x; + s = r_graphheight->int_val; if (h == 10000) - color = 0x6f; // yellow + color = 0x6f; // yellow else if (h == 9999) - color = 0x4f; // red + color = 0x4f; // red else if (h == 9998) - color = 0xd0; // blue + color = 0xd0; // blue else - color = 0xff; // pink + color = 0xff; // pink - if (h>s) + if (h > s) h = s; - - for (i=0 ; ivalue; //a = (int)((pmove.velocity[2] + 500)/10); @@ -205,28 +208,27 @@ void R_TimeGraph (void) //a = ((int)fabs(origin[0])/8)%20; //a = (cl.idealpitch + 30)/5; //a = (int)(cl.simangles[YAW] * 64/360) & 63; -a = graphval; + a = graphval; r_timings[timex] = a; a = timex; if (r_refdef.vrect.width <= MAX_TIMINGS) - x = r_refdef.vrect.width-1; + x = r_refdef.vrect.width - 1; else - x = r_refdef.vrect.width - - (r_refdef.vrect.width - MAX_TIMINGS)/2; - do - { - R_LineGraph (x, r_refdef.vrect.height-2, r_timings[a]); - if (x==0) - break; // screen too small to hold entire thing + x = r_refdef.vrect.width - (r_refdef.vrect.width - MAX_TIMINGS) / 2; + do { + R_LineGraph (x, r_refdef.vrect.height - 2, r_timings[a]); + if (x == 0) + break; // screen too small to hold entire + // thing x--; a--; if (a == -1) - a = MAX_TIMINGS-1; + a = MAX_TIMINGS - 1; } while (a != timex); - timex = (timex+1)%MAX_TIMINGS; + timex = (timex + 1) % MAX_TIMINGS; } /* @@ -234,32 +236,32 @@ a = graphval; R_NetGraph ============== */ -void R_NetGraph (void) +void +R_NetGraph (void) { - int a, x, y, y2, w, i; - int lost; - char st[80]; + int a, x, y, y2, w, i; + int lost; + char st[80]; if (vid.width - 16 <= NET_TIMINGS) w = vid.width - 16; else w = NET_TIMINGS; - x = w - ((vid.width - 320)>>1); - y = vid.height - sb_lines - 24 - r_graphheight->int_val*2 - 2; + x = w - ((vid.width - 320) >> 1); + y = vid.height - sb_lines - 24 - r_graphheight->int_val * 2 - 2; - M_DrawTextBox (x, y, (w+7)/8, (r_graphheight->int_val*2+7)/8 + 1); + M_DrawTextBox (x, y, (w + 7) / 8, (r_graphheight->int_val * 2 + 7) / 8 + 1); y2 = y + 8; y = vid.height - sb_lines - 8 - 2; x = 8; - lost = CL_CalcNet(); - for (a=NET_TIMINGS-w ; anormal); *dist = p->dist - d; // TODO: when we have rotating entities, this will need to use the view matrix @@ -432,29 +441,25 @@ void R_TransformPlane (mplane_t *p, float *normal, float *dist) R_SetUpFrustumIndexes =============== */ -void R_SetUpFrustumIndexes (void) +void +R_SetUpFrustumIndexes (void) { - int i, j, *pindex; + int i, j, *pindex; pindex = r_frustum_indexes; - for (i=0 ; i<4 ; i++) - { - for (j=0 ; j<3 ; j++) - { - if (view_clipplanes[i].normal[j] < 0) - { + for (i = 0; i < 4; i++) { + for (j = 0; j < 3; j++) { + if (view_clipplanes[i].normal[j] < 0) { pindex[j] = j; - pindex[j+3] = j+3; - } - else - { - pindex[j] = j+3; - pindex[j+3] = j; + pindex[j + 3] = j + 3; + } else { + pindex[j] = j + 3; + pindex[j + 3] = j; } } - // FIXME: do just once at start + // FIXME: do just once at start pfrustum_indexes[i] = pindex; pindex += 6; } @@ -466,23 +471,24 @@ void R_SetUpFrustumIndexes (void) R_SetupFrame =============== */ -void R_SetupFrame (void) +void +R_SetupFrame (void) { - int edgecount; - vrect_t vrect; - float w, h; + int edgecount; + vrect_t vrect; + float w, h; // don't allow cheats in multiplayer - Cvar_SetValue(r_draworder, 0); - Cvar_SetValue(r_ambient, 0); - Cvar_SetValue(r_drawflat, 0); + Cvar_SetValue (r_draworder, 0); + Cvar_SetValue (r_ambient, 0); + Cvar_SetValue (r_drawflat, 0); if (r_numsurfs->int_val) { if ((surface_p - surfaces) > r_maxsurfsseen) r_maxsurfsseen = surface_p - surfaces; Con_Printf ("Used %d of %d surfs; %d max\n", surface_p - surfaces, - surf_max - surfaces, r_maxsurfsseen); + surf_max - surfaces, r_maxsurfsseen); } if (r_numedges->int_val) { @@ -492,15 +498,15 @@ void R_SetupFrame (void) r_maxedgesseen = edgecount; Con_Printf ("Used %d of %d edges; %d max\n", edgecount, - r_numallocatededges, r_maxedgesseen); + r_numallocatededges, r_maxedgesseen); } - r_refdef.ambientlight = max(r_ambient->value, 0); + r_refdef.ambientlight = max (r_ambient->value, 0); + + Cvar_SetValue (r_draworder, 0); - Cvar_SetValue(r_draworder, 0); - R_CheckVariables (); - + R_AnimateLight (); r_framecount++; @@ -530,50 +536,42 @@ void R_SetupFrame (void) r_dowarpold = r_dowarp; r_dowarp = r_waterwarp->int_val && (r_viewleaf->contents <= CONTENTS_WATER); - if ((r_dowarp != r_dowarpold) || r_viewchanged) - { - if (r_dowarp) - { + if ((r_dowarp != r_dowarpold) || r_viewchanged) { + if (r_dowarp) { if ((vid.width <= vid.maxwarpwidth) && - (vid.height <= vid.maxwarpheight)) - { + (vid.height <= vid.maxwarpheight)) { vrect.x = 0; vrect.y = 0; vrect.width = vid.width; vrect.height = vid.height; R_ViewChanged (&vrect, sb_lines, vid.aspect); - } - else - { + } else { w = vid.width; h = vid.height; - if (w > vid.maxwarpwidth) - { - h *= (float)vid.maxwarpwidth / w; + if (w > vid.maxwarpwidth) { + h *= (float) vid.maxwarpwidth / w; w = vid.maxwarpwidth; } - if (h > vid.maxwarpheight) - { + if (h > vid.maxwarpheight) { h = vid.maxwarpheight; - w *= (float)vid.maxwarpheight / h; + w *= (float) vid.maxwarpheight / h; } vrect.x = 0; vrect.y = 0; - vrect.width = (int)w; - vrect.height = (int)h; + vrect.width = (int) w; + vrect.height = (int) h; R_ViewChanged (&vrect, - (int)((float)sb_lines * (h/(float)vid.height)), - vid.aspect * (h / w) * - ((float)vid.width / (float)vid.height)); + (int) ((float) sb_lines * + (h / (float) vid.height)), + vid.aspect * (h / w) * ((float) vid.width / + (float) vid.height)); } - } - else - { + } else { vrect.x = 0; vrect.y = 0; vrect.width = vid.width; @@ -584,7 +582,6 @@ void R_SetupFrame (void) r_viewchanged = false; } - // start off with just the four screen edge clip planes R_TransformFrustum (); @@ -612,4 +609,3 @@ void R_SetupFrame (void) D_SetupFrame (); } - diff --git a/source/r_part.c b/source/r_part.c index f07cfcb..ae54bb3 100644 --- a/source/r_part.c +++ b/source/r_part.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -40,20 +40,21 @@ #include #define MAX_PARTICLES 2048 // default max # of particles at one - // time -#define ABSOLUTE_MIN_PARTICLES 512 // no fewer than this no matter what's - // on the command line + // time +#define ABSOLUTE_MIN_PARTICLES 512 // no fewer than this no matter + // what's + // on the command line -int ramp1[8] = {0x6f, 0x6d, 0x6b, 0x69, 0x67, 0x65, 0x63, 0x61}; -int ramp2[8] = {0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x68, 0x66}; -int ramp3[8] = {0x6d, 0x6b, 6, 5, 4, 3}; +int ramp1[8] = { 0x6f, 0x6d, 0x6b, 0x69, 0x67, 0x65, 0x63, 0x61 }; +int ramp2[8] = { 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x68, 0x66 }; +int ramp3[8] = { 0x6d, 0x6b, 6, 5, 4, 3 }; -particle_t *active_particles, *free_particles; +particle_t *active_particles, *free_particles; -particle_t *particles; -int r_numparticles; +particle_t *particles; +int r_numparticles; -vec3_t r_pright, r_pup, r_ppn; +vec3_t r_pright, r_pup, r_ppn; /* @@ -61,25 +62,23 @@ vec3_t r_pright, r_pup, r_ppn; R_InitParticles =============== */ -void R_InitParticles (void) +void +R_InitParticles (void) { - int i; + int i; i = COM_CheckParm ("-particles"); - if (i) - { - r_numparticles = (int)(atoi(com_argv[i+1])); + if (i) { + r_numparticles = (int) (atoi (com_argv[i + 1])); if (r_numparticles < ABSOLUTE_MIN_PARTICLES) r_numparticles = ABSOLUTE_MIN_PARTICLES; - } - else - { + } else { r_numparticles = MAX_PARTICLES; } particles = (particle_t *) - Hunk_AllocName (r_numparticles * sizeof(particle_t), "particles"); + Hunk_AllocName (r_numparticles * sizeof (particle_t), "particles"); } @@ -88,50 +87,50 @@ void R_InitParticles (void) R_ClearParticles =============== */ -void R_ClearParticles (void) +void +R_ClearParticles (void) { - int i; - + int i; + free_particles = &particles[0]; active_particles = NULL; - for (i=0 ;inext; p->next = active_particles; active_particles = p; - + p->die = 99999; - p->color = (-c)&15; + p->color = (-c) & 15; p->type = pt_static; VectorCopy (vec3_origin, p->vel); VectorCopy (org, p->org); @@ -150,8 +149,9 @@ void R_ReadPointFile_f (void) Qclose (f); Con_Printf ("%i points read\n", c); } - -void R_RunSpikeEffect (vec3_t pos, byte type) + +void +R_RunSpikeEffect (vec3_t pos, byte type) { switch (type) { case TE_WIZSPIKE: @@ -169,15 +169,15 @@ void R_RunSpikeEffect (vec3_t pos, byte type) } } -void R_RunPuffEffect (vec3_t pos, byte type, byte cnt) +void +R_RunPuffEffect (vec3_t pos, byte type, byte cnt) { - switch (type) - { + switch (type) { case TE_GUNSHOT: - R_RunParticleEffect (pos, 0, 20*cnt); + R_RunParticleEffect (pos, 0, 20 * cnt); break; case TE_BLOOD: - R_RunParticleEffect (pos, 73, 20*cnt); + R_RunParticleEffect (pos, 73, 20 * cnt); break; case TE_LIGHTNINGBLOOD: R_RunParticleEffect (pos, 225, 50); @@ -191,13 +191,13 @@ R_ParticleExplosion =============== */ -void R_ParticleExplosion (vec3_t org) +void +R_ParticleExplosion (vec3_t org) { - int i, j; - particle_t *p; - - for (i=0 ; i<1024 ; i++) - { + int i, j; + particle_t *p; + + for (i = 0; i < 1024; i++) { if (!free_particles) return; p = free_particles; @@ -207,23 +207,18 @@ void R_ParticleExplosion (vec3_t org) p->die = cl.time + 5; p->color = ramp1[0]; - p->ramp = rand()&3; - if (i & 1) - { + p->ramp = rand () & 3; + if (i & 1) { p->type = pt_explode; - for (j=0 ; j<3 ; j++) - { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + for (j = 0; j < 3; j++) { + p->org[j] = org[j] + ((rand () % 32) - 16); + p->vel[j] = (rand () % 512) - 256; } - } - else - { + } else { p->type = pt_explode2; - for (j=0 ; j<3 ; j++) - { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + for (j = 0; j < 3; j++) { + p->org[j] = org[j] + ((rand () % 32) - 16); + p->vel[j] = (rand () % 512) - 256; } } } @@ -235,13 +230,13 @@ R_BlobExplosion =============== */ -void R_BlobExplosion (vec3_t org) +void +R_BlobExplosion (vec3_t org) { - int i, j; - particle_t *p; - - for (i=0 ; i<1024 ; i++) - { + int i, j; + particle_t *p; + + for (i = 0; i < 1024; i++) { if (!free_particles) return; p = free_particles; @@ -249,26 +244,21 @@ void R_BlobExplosion (vec3_t org) p->next = active_particles; active_particles = p; - p->die = cl.time + 1 + (rand()&8)*0.05; + p->die = cl.time + 1 + (rand () & 8) * 0.05; - if (i & 1) - { + if (i & 1) { p->type = pt_blob; - p->color = 66 + rand()%6; - for (j=0 ; j<3 ; j++) - { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->color = 66 + rand () % 6; + for (j = 0; j < 3; j++) { + p->org[j] = org[j] + ((rand () % 32) - 16); + p->vel[j] = (rand () % 512) - 256; } - } - else - { + } else { p->type = pt_blob2; - p->color = 150 + rand()%6; - for (j=0 ; j<3 ; j++) - { - p->org[j] = org[j] + ((rand()%32)-16); - p->vel[j] = (rand()%512)-256; + p->color = 150 + rand () % 6; + for (j = 0; j < 3; j++) { + p->org[j] = org[j] + ((rand () % 32) - 16); + p->vel[j] = (rand () % 512) - 256; } } } @@ -280,11 +270,12 @@ R_RunParticleEffect =============== */ -void R_RunParticleEffect (vec3_t org, int color, int count) +void +R_RunParticleEffect (vec3_t org, int color, int count) { - int i, j; - particle_t *p; - int scale; + int i, j; + particle_t *p; + int scale; if (count > 130) scale = 3; @@ -293,8 +284,7 @@ void R_RunParticleEffect (vec3_t org, int color, int count) else scale = 1; - for (i=0 ; inext = active_particles; active_particles = p; - p->die = cl.time + 0.1*(rand()%5); - p->color = (color&~7) + (rand()&7); + p->die = cl.time + 0.1 * (rand () % 5); + p->color = (color & ~7) + (rand () & 7); p->type = pt_grav; - for (j=0 ; j<3 ; j++) - { - p->org[j] = org[j] + scale*((rand()&15)-8); - p->vel[j] = vec3_origin[j];// + (rand()%300)-150; + for (j = 0; j < 3; j++) { + p->org[j] = org[j] + scale * ((rand () & 15) - 8); + p->vel[j] = vec3_origin[j]; // + (rand()%300)-150; } } } @@ -320,38 +309,38 @@ R_LavaSplash =============== */ -void R_LavaSplash (vec3_t org) +void +R_LavaSplash (vec3_t org) { - int i, j, k; - particle_t *p; - float vel; - vec3_t dir; + int i, j, k; + particle_t *p; + float vel; + vec3_t dir; - for (i=-16 ; i<16 ; i++) - for (j=-16 ; j<16 ; j++) - for (k=0 ; k<1 ; k++) - { + for (i = -16; i < 16; i++) + for (j = -16; j < 16; j++) + for (k = 0; k < 1; k++) { if (!free_particles) return; p = free_particles; free_particles = p->next; p->next = active_particles; active_particles = p; - - p->die = cl.time + 2 + (rand()&31) * 0.02; - p->color = 224 + (rand()&7); + + p->die = cl.time + 2 + (rand () & 31) * 0.02; + p->color = 224 + (rand () & 7); p->type = pt_grav; - - dir[0] = j*8 + (rand()&7); - dir[1] = i*8 + (rand()&7); + + dir[0] = j * 8 + (rand () & 7); + dir[1] = i * 8 + (rand () & 7); dir[2] = 256; - + p->org[0] = org[0] + dir[0]; p->org[1] = org[1] + dir[1]; - p->org[2] = org[2] + (rand()&63); - - VectorNormalize (dir); - vel = 50 + (rand()&63); + p->org[2] = org[2] + (rand () & 63); + + VectorNormalize (dir); + vel = 50 + (rand () & 63); VectorScale (dir, vel, p->vel); } } @@ -362,53 +351,53 @@ R_TeleportSplash =============== */ -void R_TeleportSplash (vec3_t org) +void +R_TeleportSplash (vec3_t org) { - int i, j, k; - particle_t *p; - float vel; - vec3_t dir; + int i, j, k; + particle_t *p; + float vel; + vec3_t dir; - for (i=-16 ; i<16 ; i+=4) - for (j=-16 ; j<16 ; j+=4) - for (k=-24 ; k<32 ; k+=4) - { + for (i = -16; i < 16; i += 4) + for (j = -16; j < 16; j += 4) + for (k = -24; k < 32; k += 4) { if (!free_particles) return; p = free_particles; free_particles = p->next; p->next = active_particles; active_particles = p; - - p->die = cl.time + 0.2 + (rand()&7) * 0.02; - p->color = 7 + (rand()&7); + + p->die = cl.time + 0.2 + (rand () & 7) * 0.02; + p->color = 7 + (rand () & 7); p->type = pt_grav; - - dir[0] = j*8; - dir[1] = i*8; - dir[2] = k*8; - - p->org[0] = org[0] + i + (rand()&3); - p->org[1] = org[1] + j + (rand()&3); - p->org[2] = org[2] + k + (rand()&3); - - VectorNormalize (dir); - vel = 50 + (rand()&63); + + dir[0] = j * 8; + dir[1] = i * 8; + dir[2] = k * 8; + + p->org[0] = org[0] + i + (rand () & 3); + p->org[1] = org[1] + j + (rand () & 3); + p->org[2] = org[2] + k + (rand () & 3); + + VectorNormalize (dir); + vel = 50 + (rand () & 63); VectorScale (dir, vel, p->vel); } } -void R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) +void +R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) { - vec3_t vec; - float len; - int j; - particle_t *p; + vec3_t vec; + float len; + int j; + particle_t *p; VectorSubtract (end, start, vec); len = VectorNormalize (vec); - while (len > 0) - { + while (len > 0) { len -= 3; if (!free_particles) @@ -417,76 +406,62 @@ void R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) free_particles = p->next; p->next = active_particles; active_particles = p; - + VectorCopy (vec3_origin, p->vel); p->die = cl.time + 2; - if (type == 4) - { // slight blood + if (type == 4) { // slight blood p->type = pt_slowgrav; - p->color = 67 + (rand()&3); - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); + p->color = 67 + (rand () & 3); + for (j = 0; j < 3; j++) + p->org[j] = start[j] + ((rand () % 6) - 3); len -= 3; - } - else if (type == 2) - { // blood + } else if (type == 2) { // blood p->type = pt_slowgrav; - p->color = 67 + (rand()&3); - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - } - else if (type == 6) - { // voor trail - p->color = 9*16 + 8 + (rand()&3); + p->color = 67 + (rand () & 3); + for (j = 0; j < 3; j++) + p->org[j] = start[j] + ((rand () % 6) - 3); + } else if (type == 6) { // voor trail + p->color = 9 * 16 + 8 + (rand () & 3); p->type = pt_static; p->die = cl.time + 0.3; - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()&15)-8); - } - else if (type == 1) - { // smoke smoke - p->ramp = (rand()&3) + 2; - p->color = ramp3[(int)p->ramp]; + for (j = 0; j < 3; j++) + p->org[j] = start[j] + ((rand () & 15) - 8); + } else if (type == 1) { // smoke smoke + p->ramp = (rand () & 3) + 2; + p->color = ramp3[(int) p->ramp]; p->type = pt_fire; - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - } - else if (type == 0) - { // rocket trail - p->ramp = (rand()&3); - p->color = ramp3[(int)p->ramp]; + for (j = 0; j < 3; j++) + p->org[j] = start[j] + ((rand () % 6) - 3); + } else if (type == 0) { // rocket trail + p->ramp = (rand () & 3); + p->color = ramp3[(int) p->ramp]; p->type = pt_fire; - for (j=0 ; j<3 ; j++) - p->org[j] = start[j] + ((rand()%6)-3); - } - else if (type == 3 || type == 5) - { // tracer - static int tracercount; + for (j = 0; j < 3; j++) + p->org[j] = start[j] + ((rand () % 6) - 3); + } else if (type == 3 || type == 5) { // tracer + static int tracercount; p->die = cl.time + 0.5; p->type = pt_static; if (type == 3) - p->color = 52 + ((tracercount&4)<<1); + p->color = 52 + ((tracercount & 4) << 1); else - p->color = 230 + ((tracercount&4)<<1); - + p->color = 230 + ((tracercount & 4) << 1); + tracercount++; VectorCopy (start, p->org); - if (tracercount & 1) - { - p->vel[0] = 30*vec[1]; - p->vel[1] = 30*-vec[0]; + if (tracercount & 1) { + p->vel[0] = 30 * vec[1]; + p->vel[1] = 30 * -vec[0]; + } else { + p->vel[0] = 30 * -vec[1]; + p->vel[1] = 30 * vec[0]; } - else - { - p->vel[0] = 30*-vec[1]; - p->vel[1] = 30*vec[0]; - } - + } - + VectorAdd (start, vec, start); } @@ -498,15 +473,17 @@ void R_RocketTrail (vec3_t start, vec3_t end, int type, entity_t *ent) R_DrawParticles =============== */ -void R_DrawParticles (void) +void +R_DrawParticles (void) { - particle_t *p, **particle; - float grav; - int i; - float time2, time3; - float time1; - float dvel; - float frametime; + particle_t *p, **particle; + float grav; + int i; + float time2, time3; + float time1; + float dvel; + float frametime; + D_StartParticles (); VectorScale (vright, xscaleshrink, r_pright); @@ -515,12 +492,12 @@ void R_DrawParticles (void) frametime = host_frametime; time3 = frametime * 15; - time2 = frametime * 10; // 15; + time2 = frametime * 10; // 15; time1 = frametime * 5; grav = frametime * 800 * 0.05; - dvel = 4*frametime; - - for (particle = &active_particles; *particle; ) { + dvel = 4 * frametime; + + for (particle = &active_particles; *particle;) { if ((*particle)->die < cl.time) { p = (*particle)->next; (*particle)->next = free_particles; @@ -532,64 +509,63 @@ void R_DrawParticles (void) D_DrawParticle (p); - p->org[0] += p->vel[0]*frametime; - p->org[1] += p->vel[1]*frametime; - p->org[2] += p->vel[2]*frametime; + p->org[0] += p->vel[0] * frametime; + p->org[1] += p->vel[1] * frametime; + p->org[2] += p->vel[2] * frametime; switch (p->type) { - case pt_static: - break; - case pt_fire: - p->ramp += time1; - if (p->ramp >= 6) - p->die = -1; - else - p->color = ramp3[(int)p->ramp]; - p->vel[2] += grav; - break; + case pt_static: + break; + case pt_fire: + p->ramp += time1; + if (p->ramp >= 6) + p->die = -1; + else + p->color = ramp3[(int) p->ramp]; + p->vel[2] += grav; + break; - case pt_explode: - p->ramp += time2; - if (p->ramp >=8) - p->die = -1; - else - p->color = ramp1[(int)p->ramp]; - for (i=0 ; i<3 ; i++) - p->vel[i] += p->vel[i]*dvel; - p->vel[2] -= grav; - break; + case pt_explode: + p->ramp += time2; + if (p->ramp >= 8) + p->die = -1; + else + p->color = ramp1[(int) p->ramp]; + for (i = 0; i < 3; i++) + p->vel[i] += p->vel[i] * dvel; + p->vel[2] -= grav; + break; - case pt_explode2: - p->ramp += time3; - if (p->ramp >=8) - p->die = -1; - else - p->color = ramp2[(int)p->ramp]; - for (i=0 ; i<3 ; i++) - p->vel[i] -= p->vel[i]*frametime; - p->vel[2] -= grav; - break; + case pt_explode2: + p->ramp += time3; + if (p->ramp >= 8) + p->die = -1; + else + p->color = ramp2[(int) p->ramp]; + for (i = 0; i < 3; i++) + p->vel[i] -= p->vel[i] * frametime; + p->vel[2] -= grav; + break; - case pt_blob: - for (i=0 ; i<3 ; i++) - p->vel[i] += p->vel[i]*dvel; - p->vel[2] -= grav; - break; + case pt_blob: + for (i = 0; i < 3; i++) + p->vel[i] += p->vel[i] * dvel; + p->vel[2] -= grav; + break; - case pt_blob2: - for (i=0 ; i<2 ; i++) - p->vel[i] -= p->vel[i]*dvel; - p->vel[2] -= grav; - break; + case pt_blob2: + for (i = 0; i < 2; i++) + p->vel[i] -= p->vel[i] * dvel; + p->vel[2] -= grav; + break; - case pt_slowgrav: - case pt_grav: - p->vel[2] -= grav; - break; + case pt_slowgrav: + case pt_grav: + p->vel[2] -= grav; + break; } } } D_EndParticles (); } - diff --git a/source/r_sky.c b/source/r_sky.c index 445aced..799c043 100644 --- a/source/r_sky.c +++ b/source/r_sky.c @@ -27,32 +27,34 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" #include "d_local.h" -int iskyspeed = 8; -int iskyspeed2 = 2; -float skyspeed, skyspeed2; +int iskyspeed = 8; +int iskyspeed2 = 2; +float skyspeed, skyspeed2; -float skytime; +float skytime; -byte *r_skysource; +byte *r_skysource; -int r_skymade; -int r_skydirect; // not used? +int r_skymade; +int r_skydirect; // not used? // TODO: clean up these routines -byte bottomsky[128*131]; -byte bottommask[128*131]; -byte newsky[128*256]; // newsky and topsky both pack in here, 128 bytes - // of newsky on the left of each scan, 128 bytes - // of topsky on the right, because the low-level - // drawers need 256-byte scan widths +byte bottomsky[128 * 131]; +byte bottommask[128 * 131]; +byte newsky[128 * 256]; // newsky and topsky both pack in + + // here, 128 bytes + // of newsky on the left of each scan, 128 bytes + // of topsky on the right, because the low-level + // drawers need 256-byte scan widths /* @@ -62,38 +64,32 @@ R_InitSky A sky texture is 256*128, with the right side being a masked overlay ============== */ -void R_InitSky (texture_t *mt) +void +R_InitSky (texture_t *mt) { - int i, j; - byte *src; + int i, j; + byte *src; - src = (byte *)mt + mt->offsets[0]; + src = (byte *) mt + mt->offsets[0]; - for (i=0 ; i<128 ; i++) - { - for (j=0 ; j<128 ; j++) - { - newsky[(i*256) + j + 128] = src[i*256 + j + 128]; + for (i = 0; i < 128; i++) { + for (j = 0; j < 128; j++) { + newsky[(i * 256) + j + 128] = src[i * 256 + j + 128]; } } - for (i=0 ; i<128 ; i++) - { - for (j=0 ; j<131 ; j++) - { - if (src[i*256 + (j & 0x7F)]) - { - bottomsky[(i*131) + j] = src[i*256 + (j & 0x7F)]; - bottommask[(i*131) + j] = 0; - } - else - { - bottomsky[(i*131) + j] = 0; - bottommask[(i*131) + j] = 0xff; + for (i = 0; i < 128; i++) { + for (j = 0; j < 131; j++) { + if (src[i * 256 + (j & 0x7F)]) { + bottomsky[(i * 131) + j] = src[i * 256 + (j & 0x7F)]; + bottommask[(i * 131) + j] = 0; + } else { + bottomsky[(i * 131) + j] = 0; + bottommask[(i * 131) + j] = 0xff; } } } - + r_skysource = newsky; } @@ -103,54 +99,53 @@ void R_InitSky (texture_t *mt) R_MakeSky ================= */ -void R_MakeSky (void) +void +R_MakeSky (void) { - int x, y; - int ofs, baseofs; - int xshift, yshift; - unsigned int *pnewsky; - static int xlast = -1, ylast = -1; + int x, y; + int ofs, baseofs; + int xshift, yshift; + unsigned int *pnewsky; + static int xlast = -1, ylast = -1; - xshift = skytime*skyspeed; - yshift = skytime*skyspeed; + xshift = skytime * skyspeed; + yshift = skytime * skyspeed; if ((xshift == xlast) && (yshift == ylast)) return; xlast = xshift; ylast = yshift; - - pnewsky = (unsigned int *)&newsky[0]; - for (y=0 ; y +# include "config.h" #endif #include "sys.h" #include "console.h" @@ -36,22 +36,23 @@ #include #include -static int clip_current; -static vec5_t clip_verts[2][MAXWORKINGVERTS]; -static int sprite_width, sprite_height; +static int clip_current; +static vec5_t clip_verts[2][MAXWORKINGVERTS]; +static int sprite_width, sprite_height; + +spritedesc_t r_spritedesc; -spritedesc_t r_spritedesc; - /* ================ R_RotateSprite ================ */ -void R_RotateSprite (float beamlength) +void +R_RotateSprite (float beamlength) { - vec3_t vec; - + vec3_t vec; + if (beamlength == 0.0) return; @@ -69,36 +70,33 @@ Clips the winding at clip_verts[clip_current] and changes clip_current Throws out the back side ============== */ -int R_ClipSpriteFace (int nump, clipplane_t *pclipplane) +int +R_ClipSpriteFace (int nump, clipplane_t *pclipplane) { - int i, outcount; - float dists[MAXWORKINGVERTS+1]; - float frac, clipdist, *pclipnormal; - float *in, *instep, *outstep, *vert2; + int i, outcount; + float dists[MAXWORKINGVERTS + 1]; + float frac, clipdist, *pclipnormal; + float *in, *instep, *outstep, *vert2; clipdist = pclipplane->dist; pclipnormal = pclipplane->normal; - + // calc dists - if (clip_current) - { + if (clip_current) { in = clip_verts[1][0]; outstep = clip_verts[0][0]; clip_current = 0; - } - else - { + } else { in = clip_verts[0][0]; outstep = clip_verts[1][0]; clip_current = 1; } - + instep = in; - for (i=0 ; i= 0) - { + for (i = 0; i < nump; i++, instep += sizeof (vec5_t) / sizeof (float)) { + if (dists[i] >= 0) { memcpy (outstep, instep, sizeof (vec5_t)); outstep += sizeof (vec5_t) / sizeof (float); + outcount++; } - if (dists[i] == 0 || dists[i+1] == 0) + if (dists[i] == 0 || dists[i + 1] == 0) continue; - if ( (dists[i] > 0) == (dists[i+1] > 0) ) + if ((dists[i] > 0) == (dists[i + 1] > 0)) continue; - - // split it into a new vertex - frac = dists[i] / (dists[i] - dists[i+1]); - + + // split it into a new vertex + frac = dists[i] / (dists[i] - dists[i + 1]); + vert2 = instep + sizeof (vec5_t) / sizeof (float); - - outstep[0] = instep[0] + frac*(vert2[0] - instep[0]); - outstep[1] = instep[1] + frac*(vert2[1] - instep[1]); - outstep[2] = instep[2] + frac*(vert2[2] - instep[2]); - outstep[3] = instep[3] + frac*(vert2[3] - instep[3]); - outstep[4] = instep[4] + frac*(vert2[4] - instep[4]); + + outstep[0] = instep[0] + frac * (vert2[0] - instep[0]); + outstep[1] = instep[1] + frac * (vert2[1] - instep[1]); + outstep[2] = instep[2] + frac * (vert2[2] - instep[2]); + outstep[3] = instep[3] + frac * (vert2[3] - instep[3]); + outstep[4] = instep[4] + frac * (vert2[4] - instep[4]); outstep += sizeof (vec5_t) / sizeof (float); + outcount++; - } - + } + return outcount; } @@ -147,13 +145,14 @@ int R_ClipSpriteFace (int nump, clipplane_t *pclipplane) R_SetupAndDrawSprite ================ */ -void R_SetupAndDrawSprite () +void +R_SetupAndDrawSprite () { - int i, nump; - float dot, scale, *pv; - vec5_t *pverts; - vec3_t left, up, right, down, transformed, local; - emitpoint_t outverts[MAXWORKINGVERTS+1], *pout; + int i, nump; + float dot, scale, *pv; + vec5_t *pverts; + vec3_t left, up, right, down, transformed, local; + emitpoint_t outverts[MAXWORKINGVERTS + 1], *pout; dot = DotProduct (r_spritedesc.vpn, modelorg); @@ -197,21 +196,19 @@ void R_SetupAndDrawSprite () nump = 4; clip_current = 0; - for (i=0 ; i<4 ; i++) - { + for (i = 0; i < 4; i++) { nump = R_ClipSpriteFace (nump, &view_clipplanes[i]); if (nump < 3) return; if (nump >= MAXWORKINGVERTS) - Sys_Error("R_SetupAndDrawSprite: too many points"); + Sys_Error ("R_SetupAndDrawSprite: too many points"); } // transform vertices into viewspace and project pv = &clip_verts[clip_current][0][0]; r_spritedesc.nearzi = -999999; - for (i=0 ; is = pv[3]; pout->t = pv[4]; - + scale = xscale * pout->zi; pout->u = (xcenter + scale * transformed[0]); @@ -247,40 +244,37 @@ void R_SetupAndDrawSprite () R_GetSpriteframe ================ */ -mspriteframe_t *R_GetSpriteframe (msprite_t *psprite) +mspriteframe_t * +R_GetSpriteframe (msprite_t *psprite) { - mspritegroup_t *pspritegroup; - mspriteframe_t *pspriteframe; - int i, numframes, frame; - float *pintervals, fullinterval, targettime, time; + mspritegroup_t *pspritegroup; + mspriteframe_t *pspriteframe; + int i, numframes, frame; + float *pintervals, fullinterval, targettime, time; frame = currententity->frame; - if ((frame >= psprite->numframes) || (frame < 0)) - { + if ((frame >= psprite->numframes) || (frame < 0)) { Con_Printf ("R_DrawSprite: no such frame %d\n", frame); frame = 0; } - if (psprite->frames[frame].type == SPR_SINGLE) - { + if (psprite->frames[frame].type == SPR_SINGLE) { pspriteframe = psprite->frames[frame].frameptr; - } - else - { - pspritegroup = (mspritegroup_t *)psprite->frames[frame].frameptr; + } else { + pspritegroup = (mspritegroup_t *) psprite->frames[frame].frameptr; pintervals = pspritegroup->intervals; numframes = pspritegroup->numframes; - fullinterval = pintervals[numframes-1]; + fullinterval = pintervals[numframes - 1]; time = cl.time + currententity->syncbase; - // when loading in Mod_LoadSpriteGroup, we guaranteed all interval values - // are positive, so we don't have to worry about division by 0 - targettime = time - ((int)(time / fullinterval)) * fullinterval; + // when loading in Mod_LoadSpriteGroup, we guaranteed all interval + // values + // are positive, so we don't have to worry about division by 0 + targettime = time - ((int) (time / fullinterval)) * fullinterval; - for (i=0 ; i<(numframes-1) ; i++) - { + for (i = 0; i < (numframes - 1); i++) { if (pintervals[i] > targettime) break; } @@ -297,12 +291,13 @@ mspriteframe_t *R_GetSpriteframe (msprite_t *psprite) R_DrawSprite ================ */ -void R_DrawSprite (void) +void +R_DrawSprite (void) { - int i; - msprite_t *psprite; - vec3_t tvec; - float dot, angle, sr, cr; + int i; + msprite_t *psprite; + vec3_t tvec; + float dot, angle, sr, cr; psprite = currententity->model->cache.data; @@ -312,99 +307,102 @@ void R_DrawSprite (void) sprite_height = r_spritedesc.pspriteframe->height; // TODO: make this caller-selectable - if (psprite->type == SPR_FACING_UPRIGHT) - { - // generate the sprite's axes, with vup straight up in worldspace, and - // r_spritedesc.vright perpendicular to modelorg. - // This will not work if the view direction is very close to straight up or - // down, because the cross product will be between two nearly parallel - // vectors and starts to approach an undefined state, so we don't draw if - // the two vectors are less than 1 degree apart + if (psprite->type == SPR_FACING_UPRIGHT) { + // generate the sprite's axes, with vup straight up in worldspace, + // and + // r_spritedesc.vright perpendicular to modelorg. + // This will not work if the view direction is very close to straight + // up or + // down, because the cross product will be between two nearly + // parallel + // vectors and starts to approach an undefined state, so we don't + // draw if + // the two vectors are less than 1 degree apart tvec[0] = -modelorg[0]; tvec[1] = -modelorg[1]; tvec[2] = -modelorg[2]; VectorNormalize (tvec); - dot = tvec[2]; // same as DotProduct (tvec, r_spritedesc.vup) because - // r_spritedesc.vup is 0, 0, 1 - if ((dot > 0.999848) || (dot < -0.999848)) // cos(1 degree) = 0.999848 + dot = tvec[2]; // same as DotProduct (tvec, + // r_spritedesc.vup) because + // r_spritedesc.vup is 0, 0, 1 + if ((dot > 0.999848) || (dot < -0.999848)) // cos(1 degree) = + // 0.999848 return; r_spritedesc.vup[0] = 0; r_spritedesc.vup[1] = 0; r_spritedesc.vup[2] = 1; r_spritedesc.vright[0] = tvec[1]; - // CrossProduct(r_spritedesc.vup, -modelorg, + // CrossProduct(r_spritedesc.vup, -modelorg, r_spritedesc.vright[1] = -tvec[0]; - // r_spritedesc.vright) + // r_spritedesc.vright) r_spritedesc.vright[2] = 0; VectorNormalize (r_spritedesc.vright); r_spritedesc.vpn[0] = -r_spritedesc.vright[1]; r_spritedesc.vpn[1] = r_spritedesc.vright[0]; r_spritedesc.vpn[2] = 0; - // CrossProduct (r_spritedesc.vright, r_spritedesc.vup, - // r_spritedesc.vpn) - } - else if (psprite->type == SPR_VP_PARALLEL) - { - // generate the sprite's axes, completely parallel to the viewplane. There - // are no problem situations, because the sprite is always in the same - // position relative to the viewer - for (i=0 ; i<3 ; i++) - { + // CrossProduct (r_spritedesc.vright, r_spritedesc.vup, + // r_spritedesc.vpn) + } else if (psprite->type == SPR_VP_PARALLEL) { + // generate the sprite's axes, completely parallel to the viewplane. + // There + // are no problem situations, because the sprite is always in the + // same + // position relative to the viewer + for (i = 0; i < 3; i++) { r_spritedesc.vup[i] = vup[i]; r_spritedesc.vright[i] = vright[i]; r_spritedesc.vpn[i] = vpn[i]; } - } - else if (psprite->type == SPR_VP_PARALLEL_UPRIGHT) - { - // generate the sprite's axes, with vup straight up in worldspace, and - // r_spritedesc.vright parallel to the viewplane. - // This will not work if the view direction is very close to straight up or - // down, because the cross product will be between two nearly parallel - // vectors and starts to approach an undefined state, so we don't draw if - // the two vectors are less than 1 degree apart - dot = vpn[2]; // same as DotProduct (vpn, r_spritedesc.vup) because - // r_spritedesc.vup is 0, 0, 1 - if ((dot > 0.999848) || (dot < -0.999848)) // cos(1 degree) = 0.999848 + } else if (psprite->type == SPR_VP_PARALLEL_UPRIGHT) { + // generate the sprite's axes, with vup straight up in worldspace, + // and + // r_spritedesc.vright parallel to the viewplane. + // This will not work if the view direction is very close to straight + // up or + // down, because the cross product will be between two nearly + // parallel + // vectors and starts to approach an undefined state, so we don't + // draw if + // the two vectors are less than 1 degree apart + dot = vpn[2]; // same as DotProduct (vpn, + // r_spritedesc.vup) because + // r_spritedesc.vup is 0, 0, 1 + if ((dot > 0.999848) || (dot < -0.999848)) // cos(1 degree) = + // 0.999848 return; r_spritedesc.vup[0] = 0; r_spritedesc.vup[1] = 0; r_spritedesc.vup[2] = 1; r_spritedesc.vright[0] = vpn[1]; - // CrossProduct (r_spritedesc.vup, vpn, - r_spritedesc.vright[1] = -vpn[0]; // r_spritedesc.vright) + // CrossProduct (r_spritedesc.vup, vpn, + r_spritedesc.vright[1] = -vpn[0]; // r_spritedesc.vright) r_spritedesc.vright[2] = 0; VectorNormalize (r_spritedesc.vright); r_spritedesc.vpn[0] = -r_spritedesc.vright[1]; r_spritedesc.vpn[1] = r_spritedesc.vright[0]; r_spritedesc.vpn[2] = 0; - // CrossProduct (r_spritedesc.vright, r_spritedesc.vup, - // r_spritedesc.vpn) - } - else if (psprite->type == SPR_ORIENTED) - { - // generate the sprite's axes, according to the sprite's world orientation + // CrossProduct (r_spritedesc.vright, r_spritedesc.vup, + // r_spritedesc.vpn) + } else if (psprite->type == SPR_ORIENTED) { + // generate the sprite's axes, according to the sprite's world + // orientation AngleVectors (currententity->angles, r_spritedesc.vpn, r_spritedesc.vright, r_spritedesc.vup); - } - else if (psprite->type == SPR_VP_PARALLEL_ORIENTED) - { - // generate the sprite's axes, parallel to the viewplane, but rotated in - // that plane around the center according to the sprite entity's roll - // angle. So vpn stays the same, but vright and vup rotate - angle = currententity->angles[ROLL] * (M_PI*2 / 360); - sr = sin(angle); - cr = cos(angle); + } else if (psprite->type == SPR_VP_PARALLEL_ORIENTED) { + // generate the sprite's axes, parallel to the viewplane, but rotated + // in + // that plane around the center according to the sprite entity's roll + // angle. So vpn stays the same, but vright and vup rotate + angle = currententity->angles[ROLL] * (M_PI * 2 / 360); + sr = sin (angle); + cr = cos (angle); - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { r_spritedesc.vpn[i] = vpn[i]; r_spritedesc.vright[i] = vright[i] * cr + vup[i] * sr; r_spritedesc.vup[i] = vright[i] * -sr + vup[i] * cr; } - } - else - { + } else { Sys_Error ("R_DrawSprite: Bad sprite type %d", psprite->type); } @@ -412,4 +410,3 @@ void R_DrawSprite (void) R_SetupAndDrawSprite (); } - diff --git a/source/r_surf.c b/source/r_surf.c index a8898dc..d1a7b32 100644 --- a/source/r_surf.c +++ b/source/r_surf.c @@ -27,104 +27,102 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "r_local.h" -drawsurf_t r_drawsurf; +drawsurf_t r_drawsurf; -int lightleft, sourcesstep, blocksize, sourcetstep; -int lightdelta, lightdeltastep; -int lightright, lightleftstep, lightrightstep, blockdivshift; -unsigned int blockdivmask; -void *prowdestbase; -unsigned char *pbasesource; -int surfrowbytes; // used by ASM files -unsigned int *r_lightptr; -int r_stepback; -int r_lightwidth; -int r_numhblocks, r_numvblocks; -unsigned char *r_source, *r_sourcemax; +int lightleft, sourcesstep, blocksize, sourcetstep; +int lightdelta, lightdeltastep; +int lightright, lightleftstep, lightrightstep, blockdivshift; +unsigned int blockdivmask; +void *prowdestbase; +unsigned char *pbasesource; +int surfrowbytes; // used by ASM files +unsigned int *r_lightptr; +int r_stepback; +int r_lightwidth; +int r_numhblocks, r_numvblocks; +unsigned char *r_source, *r_sourcemax; -void R_DrawSurfaceBlock8_mip0 (void); -void R_DrawSurfaceBlock8_mip1 (void); -void R_DrawSurfaceBlock8_mip2 (void); -void R_DrawSurfaceBlock8_mip3 (void); +void R_DrawSurfaceBlock8_mip0 (void); +void R_DrawSurfaceBlock8_mip1 (void); +void R_DrawSurfaceBlock8_mip2 (void); +void R_DrawSurfaceBlock8_mip3 (void); -static void (*surfmiptable[4])(void) = { +static void (*surfmiptable[4]) (void) = { R_DrawSurfaceBlock8_mip0, - R_DrawSurfaceBlock8_mip1, - R_DrawSurfaceBlock8_mip2, - R_DrawSurfaceBlock8_mip3 -}; + R_DrawSurfaceBlock8_mip1, + + R_DrawSurfaceBlock8_mip2, R_DrawSurfaceBlock8_mip3}; -unsigned int blocklights[18*18]; +unsigned int blocklights[18 * 18]; /* =============== R_AddDynamicLights =============== */ -void R_AddDynamicLights (void) +void +R_AddDynamicLights (void) { msurface_t *surf; - int lnum; - int sd, td; - float dist, rad, minlight; - vec3_t impact, local, lightorigin; - int s, t; - int i; - int smax, tmax; - mtexinfo_t *tex; + int lnum; + int sd, td; + float dist, rad, minlight; + vec3_t impact, local, lightorigin; + int s, t; + int i; + int smax, tmax; + mtexinfo_t *tex; surf = r_drawsurf.surf; - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; tex = surf->texinfo; - for (lnum=0 ; lnumdlightbits & (1<dlightbits & (1 << lnum))) + continue; // not lit by this light - VectorSubtract(cl_dlights[lnum].origin, currententity->origin, lightorigin); + VectorSubtract (cl_dlights[lnum].origin, currententity->origin, + lightorigin); rad = cl_dlights[lnum].radius; dist = DotProduct (lightorigin, surf->plane->normal) - - surf->plane->dist; - rad -= fabs(dist); + surf->plane->dist; + rad -= fabs (dist); minlight = cl_dlights[lnum].minlight; if (rad < minlight) continue; minlight = rad - minlight; - for (i=0 ; i<3 ; i++) - impact[i] = lightorigin[i] - surf->plane->normal[i]*dist; + for (i = 0; i < 3; i++) + impact[i] = lightorigin[i] - surf->plane->normal[i] * dist; local[0] = DotProduct (impact, tex->vecs[0]) + tex->vecs[0][3]; local[1] = DotProduct (impact, tex->vecs[1]) + tex->vecs[1][3]; local[0] -= surf->texturemins[0]; local[1] -= surf->texturemins[1]; - - for (t = 0 ; t td) - dist = sd + (td>>1); + dist = sd + (td >> 1); else - dist = td + (sd>>1); + dist = td + (sd >> 1); if (dist < minlight) - blocklights[t*smax + s] += (rad - dist)*256; + blocklights[t * smax + s] += (rad - dist) * 256; } } } @@ -137,54 +135,49 @@ R_BuildLightMap Combine and scale multiple lightmaps into the 8.8 format in blocklights =============== */ -void R_BuildLightMap (void) +void +R_BuildLightMap (void) { - int smax, tmax; - int t; - int i, size; - byte *lightmap; - unsigned int scale; - int maps; - msurface_t *surf; + int smax, tmax; + int t; + int i, size; + byte *lightmap; + unsigned int scale; + int maps; + msurface_t *surf; surf = r_drawsurf.surf; - smax = (surf->extents[0]>>4)+1; - tmax = (surf->extents[1]>>4)+1; - size = smax*tmax; + smax = (surf->extents[0] >> 4) + 1; + tmax = (surf->extents[1] >> 4) + 1; + size = smax * tmax; lightmap = surf->samples; - if (!cl.worldmodel->lightdata) - { - for (i=0 ; ilightdata) { + for (i = 0; i < size; i++) blocklights[i] = 0; return; } - // clear to ambient - for (i=0 ; istyles[maps] != 255 ; - maps++) - { - scale = r_drawsurf.lightadj[maps]; // 8.8 fraction - for (i=0 ; istyles[maps] != 255; maps++) { + scale = r_drawsurf.lightadj[maps]; // 8.8 fraction + for (i = 0; i < size; i++) blocklights[i] += lightmap[i] * scale; - lightmap += size; // skip to next lightmap + lightmap += size; // skip to next lightmap } - // add all the dynamic lights if (surf->dlightframe == r_framecount) R_AddDynamicLights (); // bound, invert, and shift - for (i=0 ; i> (8 - VID_CBITS); + for (i = 0; i < size; i++) { + t = (255 * 256 - (int) blocklights[i]) >> (8 - VID_CBITS); if (t < (1 << 6)) t = (1 << 6); @@ -201,25 +194,24 @@ R_TextureAnimation Returns the proper texture for a given time and base texture =============== */ -texture_t *R_TextureAnimation (texture_t *base) +texture_t * +R_TextureAnimation (texture_t *base) { - int reletive; - int count; + int reletive; + int count; - if (currententity->frame) - { + if (currententity->frame) { if (base->alternate_anims) base = base->alternate_anims; } - + if (!base->anim_total) return base; - reletive = (int)(cl.time*10) % base->anim_total; + reletive = (int) (cl.time * 10) % base->anim_total; - count = 0; - while (base->anim_min > reletive || base->anim_max <= reletive) - { + count = 0; + while (base->anim_min > reletive || base->anim_max <= reletive) { base = base->anim_next; if (!base) Sys_Error ("R_TextureAnimation: broken cycle"); @@ -236,52 +228,50 @@ texture_t *R_TextureAnimation (texture_t *base) R_DrawSurface =============== */ -void R_DrawSurface (void) +void +R_DrawSurface (void) { - unsigned char *basetptr; - int smax, tmax, twidth; - int u; - int soffset, basetoffset, texwidth; - int horzblockstep; - unsigned char *pcolumndest; - void (*pblockdrawer)(void); - texture_t *mt; + unsigned char *basetptr; + int smax, tmax, twidth; + int u; + int soffset, basetoffset, texwidth; + int horzblockstep; + unsigned char *pcolumndest; + void (*pblockdrawer) (void); + texture_t *mt; // calculate the lightings R_BuildLightMap (); - + surfrowbytes = r_drawsurf.rowbytes; mt = r_drawsurf.texture; - - r_source = (byte *)mt + mt->offsets[r_drawsurf.surfmip]; - + + r_source = (byte *) mt + mt->offsets[r_drawsurf.surfmip]; + // the fractional light values should range from 0 to (VID_GRADES - 1) << 16 // from a source range of 0 - 255 - + texwidth = mt->width >> r_drawsurf.surfmip; blocksize = 16 >> r_drawsurf.surfmip; blockdivshift = 4 - r_drawsurf.surfmip; blockdivmask = (1 << blockdivshift) - 1; - - r_lightwidth = (r_drawsurf.surf->extents[0]>>4)+1; + + r_lightwidth = (r_drawsurf.surf->extents[0] >> 4) + 1; r_numhblocks = r_drawsurf.surfwidth >> blockdivshift; r_numvblocks = r_drawsurf.surfheight >> blockdivshift; //============================== - if (r_pixbytes == 1) - { + if (r_pixbytes == 1) { pblockdrawer = surfmiptable[r_drawsurf.surfmip]; - // TODO: only needs to be set when there is a display settings change + // TODO: only needs to be set when there is a display settings change horzblockstep = blocksize; - } - else - { + } else { pblockdrawer = R_DrawSurfaceBlock16; - // TODO: only needs to be set when there is a display settings change + // TODO: only needs to be set when there is a display settings change horzblockstep = blocksize << 1; } @@ -298,20 +288,19 @@ void R_DrawSurface (void) // << 16 components are to guarantee positive values for % soffset = ((soffset >> r_drawsurf.surfmip) + (smax << 16)) % smax; - basetptr = &r_source[((((basetoffset >> r_drawsurf.surfmip) - + (tmax << 16)) % tmax) * twidth)]; + basetptr = &r_source[((((basetoffset >> r_drawsurf.surfmip) + + (tmax << 16)) % tmax) * twidth)]; pcolumndest = r_drawsurf.surfdat; - for (u=0 ; u= smax) @@ -331,39 +320,37 @@ void R_DrawSurface (void) R_DrawSurfaceBlock8_mip0 ================ */ -void R_DrawSurfaceBlock8_mip0 (void) +void +R_DrawSurfaceBlock8_mip0 (void) { - int v, i, b, lightstep, lighttemp, light; - unsigned char pix, *psource, *prowdest; + int v, i, b, lightstep, lighttemp, light; + unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; - for (v=0 ; v> 4; lightrightstep = (r_lightptr[1] - lightright) >> 4; - for (i=0 ; i<16 ; i++) - { + for (i = 0; i < 16; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 4; light = lightright; - for (b=15; b>=0; b--) - { + for (b = 15; b >= 0; b--) { pix = psource[b]; - prowdest[b] = ((unsigned char *)vid.colormap) - [(light & 0xFF00) + pix]; + prowdest[b] = ((unsigned char *) vid.colormap) + [(light & 0xFF00) + pix]; light += lightstep; } - + psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; @@ -381,39 +368,37 @@ void R_DrawSurfaceBlock8_mip0 (void) R_DrawSurfaceBlock8_mip1 ================ */ -void R_DrawSurfaceBlock8_mip1 (void) +void +R_DrawSurfaceBlock8_mip1 (void) { - int v, i, b, lightstep, lighttemp, light; - unsigned char pix, *psource, *prowdest; + int v, i, b, lightstep, lighttemp, light; + unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; - for (v=0 ; v> 3; lightrightstep = (r_lightptr[1] - lightright) >> 3; - for (i=0 ; i<8 ; i++) - { + for (i = 0; i < 8; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 3; light = lightright; - for (b=7; b>=0; b--) - { + for (b = 7; b >= 0; b--) { pix = psource[b]; - prowdest[b] = ((unsigned char *)vid.colormap) - [(light & 0xFF00) + pix]; + prowdest[b] = ((unsigned char *) vid.colormap) + [(light & 0xFF00) + pix]; light += lightstep; } - + psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; @@ -431,39 +416,37 @@ void R_DrawSurfaceBlock8_mip1 (void) R_DrawSurfaceBlock8_mip2 ================ */ -void R_DrawSurfaceBlock8_mip2 (void) +void +R_DrawSurfaceBlock8_mip2 (void) { - int v, i, b, lightstep, lighttemp, light; - unsigned char pix, *psource, *prowdest; + int v, i, b, lightstep, lighttemp, light; + unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; - for (v=0 ; v> 2; lightrightstep = (r_lightptr[1] - lightright) >> 2; - for (i=0 ; i<4 ; i++) - { + for (i = 0; i < 4; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 2; light = lightright; - for (b=3; b>=0; b--) - { + for (b = 3; b >= 0; b--) { pix = psource[b]; - prowdest[b] = ((unsigned char *)vid.colormap) - [(light & 0xFF00) + pix]; + prowdest[b] = ((unsigned char *) vid.colormap) + [(light & 0xFF00) + pix]; light += lightstep; } - + psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; @@ -481,39 +464,37 @@ void R_DrawSurfaceBlock8_mip2 (void) R_DrawSurfaceBlock8_mip3 ================ */ -void R_DrawSurfaceBlock8_mip3 (void) +void +R_DrawSurfaceBlock8_mip3 (void) { - int v, i, b, lightstep, lighttemp, light; - unsigned char pix, *psource, *prowdest; + int v, i, b, lightstep, lighttemp, light; + unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; - for (v=0 ; v> 1; lightrightstep = (r_lightptr[1] - lightright) >> 1; - for (i=0 ; i<2 ; i++) - { + for (i = 0; i < 2; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 1; light = lightright; - for (b=1; b>=0; b--) - { + for (b = 1; b >= 0; b--) { pix = psource[b]; - prowdest[b] = ((unsigned char *)vid.colormap) - [(light & 0xFF00) + pix]; + prowdest[b] = ((unsigned char *) vid.colormap) + [(light & 0xFF00) + pix]; light += lightstep; } - + psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; @@ -533,20 +514,20 @@ R_DrawSurfaceBlock16 FIXME: make this work ================ */ -void R_DrawSurfaceBlock16 (void) +void +R_DrawSurfaceBlock16 (void) { - int k; - unsigned char *psource; - int lighttemp, lightstep, light; - unsigned short *prowdest; + int k; + unsigned char *psource; + int lighttemp, lightstep, light; + unsigned short *prowdest; - prowdest = (unsigned short *)prowdestbase; + prowdest = (unsigned short *) prowdestbase; - for (k=0 ; k> 16) & 63; - t = (((i << 16) + turb[j & (CYCLE-1)]) >> 16) & 63; - *pd++ = *(pbasetex + (t<<6) + s); + turb = sintable + ((int) (cl.time * SPEED) & (CYCLE - 1)); + pd = (byte *) pdest; + + for (i = 0; i < TILE_SIZE; i++) { + for (j = 0; j < TILE_SIZE; j++) { + s = (((j << 16) + turb[i & (CYCLE - 1)]) >> 16) & 63; + t = (((i << 16) + turb[j & (CYCLE - 1)]) >> 16) & 63; + *pd++ = *(pbasetex + (t << 6) + s); } } } @@ -609,22 +588,21 @@ void R_GenTurbTile (pixel_t *pbasetex, void *pdest) R_GenTurbTile16 ================ */ -void R_GenTurbTile16 (pixel_t *pbasetex, void *pdest) +void +R_GenTurbTile16 (pixel_t *pbasetex, void *pdest) { - int *turb; - int i, j, s, t; - unsigned short *pd; + int *turb; + int i, j, s, t; + unsigned short *pd; - turb = sintable + ((int)(cl.time*SPEED)&(CYCLE-1)); - pd = (unsigned short *)pdest; + turb = sintable + ((int) (cl.time * SPEED) & (CYCLE - 1)); + pd = (unsigned short *) pdest; - for (i=0 ; i> 16) & 63; - t = (((i << 16) + turb[j & (CYCLE-1)]) >> 16) & 63; - *pd++ = d_8to16table[*(pbasetex + (t<<6) + s)]; + for (i = 0; i < TILE_SIZE; i++) { + for (j = 0; j < TILE_SIZE; j++) { + s = (((j << 16) + turb[i & (CYCLE - 1)]) >> 16) & 63; + t = (((i << 16) + turb[j & (CYCLE - 1)]) >> 16) & 63; + *pd++ = d_8to16table[*(pbasetex + (t << 6) + s)]; } } } @@ -635,35 +613,28 @@ void R_GenTurbTile16 (pixel_t *pbasetex, void *pdest) R_GenTile ================ */ -void R_GenTile (msurface_t *psurf, void *pdest) +void +R_GenTile (msurface_t *psurf, void *pdest) { - if (psurf->flags & SURF_DRAWTURB) - { - if (r_pixbytes == 1) - { + if (psurf->flags & SURF_DRAWTURB) { + if (r_pixbytes == 1) { R_GenTurbTile ((pixel_t *) - ((byte *)psurf->texinfo->texture + psurf->texinfo->texture->offsets[0]), pdest); - } - else - { + + ((byte *) psurf->texinfo->texture + + psurf->texinfo->texture->offsets[0]), pdest); + } else { R_GenTurbTile16 ((pixel_t *) - ((byte *)psurf->texinfo->texture + psurf->texinfo->texture->offsets[0]), pdest); + + ((byte *) psurf->texinfo->texture + + psurf->texinfo->texture->offsets[0]), pdest); } - } - else if (psurf->flags & SURF_DRAWSKY) - { - if (r_pixbytes == 1) - { + } else if (psurf->flags & SURF_DRAWSKY) { + if (r_pixbytes == 1) { R_GenSkyTile (pdest); - } - else - { + } else { R_GenSkyTile16 (pdest); } - } - else - { + } else { Sys_Error ("Unknown tile type"); } } - diff --git a/source/r_vars.c b/source/r_vars.c index 838ca65..aa188cc 100644 --- a/source/r_vars.c +++ b/source/r_vars.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifndef USE_INTEL_ASM @@ -42,7 +42,6 @@ // FIXME: make into one big structure, like cl or sv // FIXME: do separately for refresh engine and driver -int r_bmodelactive; - -#endif // !USE_INTEL_ASM +int r_bmodelactive; +#endif // !USE_INTEL_ASM diff --git a/source/r_view.c b/source/r_view.c index 1084279..93be34c 100644 --- a/source/r_view.c +++ b/source/r_view.c @@ -51,36 +51,36 @@ when crossing a water boudnary. */ -cvar_t *cl_rollspeed; -cvar_t *cl_rollangle; +cvar_t *cl_rollspeed; +cvar_t *cl_rollangle; -cvar_t *cl_bob; -cvar_t *cl_bobcycle; -cvar_t *cl_bobup; +cvar_t *cl_bob; +cvar_t *cl_bobcycle; +cvar_t *cl_bobup; -cvar_t *v_kicktime; -cvar_t *v_kickroll; -cvar_t *v_kickpitch; +cvar_t *v_kicktime; +cvar_t *v_kickroll; +cvar_t *v_kickpitch; -cvar_t *v_iyaw_cycle; -cvar_t *v_iroll_cycle; -cvar_t *v_ipitch_cycle; -cvar_t *v_iyaw_level; -cvar_t *v_iroll_level; -cvar_t *v_ipitch_level; +cvar_t *v_iyaw_cycle; +cvar_t *v_iroll_cycle; +cvar_t *v_ipitch_cycle; +cvar_t *v_iyaw_level; +cvar_t *v_iroll_level; +cvar_t *v_ipitch_level; -cvar_t *v_idlescale; +cvar_t *v_idlescale; -cvar_t *v_contentblend; +cvar_t *v_contentblend; -float v_dmg_time, v_dmg_roll, v_dmg_pitch; +float v_dmg_time, v_dmg_roll, v_dmg_pitch; -extern int in_forward, in_forward2, in_back; +extern int in_forward, in_forward2, in_back; -frame_t *view_frame; -player_state_t *view_message; +frame_t *view_frame; +player_state_t *view_message; -void BuildGammaTable (float, float); +void BuildGammaTable (float, float); /* =============== @@ -88,27 +88,28 @@ V_CalcRoll =============== */ -float V_CalcRoll (vec3_t angles, vec3_t velocity) +float +V_CalcRoll (vec3_t angles, vec3_t velocity) { - vec3_t forward, right, up; - float sign; - float side; - float value; - + vec3_t forward, right, up; + float sign; + float side; + float value; + AngleVectors (angles, forward, right, up); side = DotProduct (velocity, right); sign = side < 0 ? -1 : 1; - side = fabs(side); - + side = fabs (side); + value = cl_rollangle->value; if (side < cl_rollspeed->value) side = side * value / cl_rollspeed->value; else side = value; - - return side*sign; - + + return side * sign; + } @@ -118,64 +119,69 @@ V_CalcBob =============== */ -float V_CalcBob (void) +float +V_CalcBob (void) { - static double bobtime; - static float bob; - float cycle; - + static double bobtime; + static float bob; + float cycle; + if (cl.spectator) return 0; if (onground == -1) - return bob; // just use old value + return bob; // just use old value bobtime += host_frametime; - cycle = bobtime - (int)(bobtime/cl_bobcycle->value)*cl_bobcycle->value; + cycle = bobtime - (int) (bobtime / cl_bobcycle->value) * cl_bobcycle->value; cycle /= cl_bobcycle->value; if (cycle < cl_bobup->value) cycle = M_PI * cycle / cl_bobup->value; else - cycle = M_PI + M_PI*(cycle-cl_bobup->value)/(1.0 - cl_bobup->value); + cycle = + M_PI + M_PI * (cycle - cl_bobup->value) / (1.0 - cl_bobup->value); // bob is proportional to simulated velocity in the xy plane // (don't count Z, or jumping messes it up) - bob = sqrt(cl.simvel[0]*cl.simvel[0] + cl.simvel[1]*cl.simvel[1]) * cl_bob->value; - bob = bob*0.3 + bob*0.7*sin(cycle); + bob = + sqrt (cl.simvel[0] * cl.simvel[0] + + cl.simvel[1] * cl.simvel[1]) * cl_bob->value; + bob = bob * 0.3 + bob * 0.7 * sin (cycle); if (bob > 4) bob = 4; else if (bob < -7) bob = -7; return bob; - + } //============================================================================= -cvar_t *v_centermove; -cvar_t *v_centerspeed; +cvar_t *v_centermove; +cvar_t *v_centerspeed; -void V_StartPitchDrift (void) +void +V_StartPitchDrift (void) { #if 1 - if (cl.laststop == cl.time) - { - return; // something else is keeping it from drifting + if (cl.laststop == cl.time) { + return; // something else is keeping it from + // drifting } #endif - if (cl.nodrift || !cl.pitchvel) - { + if (cl.nodrift || !cl.pitchvel) { cl.pitchvel = v_centerspeed->value; cl.nodrift = false; cl.driftmove = 0; } } -void V_StopPitchDrift (void) +void +V_StopPitchDrift (void) { cl.laststop = cl.time; cl.nodrift = true; @@ -195,58 +201,51 @@ Drifting is enabled when the center view key is hit, mlook is released and lookspring is non 0, or when =============== */ -void V_DriftPitch (void) +void +V_DriftPitch (void) { - float delta, move; + float delta, move; - if (view_message->onground == -1 || cls.demoplayback ) - { + if (view_message->onground == -1 || cls.demoplayback) { cl.driftmove = 0; cl.pitchvel = 0; return; } - // don't count small mouse motion - if (cl.nodrift) - { - if ( fabs(cl.frames[(cls.netchan.outgoing_sequence-1)&UPDATE_MASK].cmd.forwardmove) < 200) + if (cl.nodrift) { + if (fabs + (cl.frames[(cls.netchan.outgoing_sequence - 1) & UPDATE_MASK].cmd. + forwardmove) < 200) cl.driftmove = 0; else cl.driftmove += host_frametime; - - if ( cl.driftmove > v_centermove->value) - { + + if (cl.driftmove > v_centermove->value) { V_StartPitchDrift (); } return; } - + delta = 0 - cl.viewangles[PITCH]; - if (!delta) - { + if (!delta) { cl.pitchvel = 0; return; } move = host_frametime * cl.pitchvel; cl.pitchvel += host_frametime * v_centerspeed->value; - + //Con_Printf ("move: %f (%f)\n", move, host_frametime); - if (delta > 0) - { - if (move > delta) - { + if (delta > 0) { + if (move > delta) { cl.pitchvel = 0; move = delta; } cl.viewangles[PITCH] += move; - } - else if (delta < 0) - { - if (move > -delta) - { + } else if (delta < 0) { + if (move > -delta) { cl.pitchvel = 0; move = -delta; } @@ -260,38 +259,39 @@ void V_DriftPitch (void) PALETTE FLASHES ============================================================================== -*/ +*/ -cvar_t *gl_cshiftpercent; +cvar_t *gl_cshiftpercent; -cshift_t cshift_empty = { {130,80,50}, 0 }; -cshift_t cshift_water = { {130,80,50}, 128 }; -cshift_t cshift_slime = { {0,25,5}, 150 }; -cshift_t cshift_lava = { {255,80,0}, 150 }; +cshift_t cshift_empty = { {130, 80, 50}, 0 }; +cshift_t cshift_water = { {130, 80, 50}, 128 }; +cshift_t cshift_slime = { {0, 25, 5}, 150 }; +cshift_t cshift_lava = { {255, 80, 0}, 150 }; -cvar_t *brightness; -cvar_t *contrast; +cvar_t *brightness; +cvar_t *contrast; -byte gammatable[256]; // palette is sent through this +byte gammatable[256]; // palette is sent through this /* ================= V_CheckGamma ================= */ -qboolean V_CheckGamma (void) +qboolean +V_CheckGamma (void) { static float oldbrightness; static float oldcontrast; - + if ((brightness->value == oldbrightness) && contrast->value == oldcontrast) return false; oldbrightness = brightness->value; oldcontrast = contrast->value; - + BuildGammaTable (brightness->value, contrast->value); vid.recalc_refdef = 1; // force a surface cache flush - + return true; } @@ -302,27 +302,28 @@ qboolean V_CheckGamma (void) V_ParseDamage =============== */ -void V_ParseDamage (void) +void +V_ParseDamage (void) { - int armor, blood; - vec3_t from; - int i; - vec3_t forward, right, up; - float side; - float count; - + int armor, blood; + vec3_t from; + int i; + vec3_t forward, right, up; + float side; + float count; + armor = MSG_ReadByte (); blood = MSG_ReadByte (); - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) from[i] = MSG_ReadCoord (); - count = blood*0.5 + armor*0.5; + count = blood * 0.5 + armor * 0.5; if (count < 10) count = 10; - cl.faceanimtime = cl.time + 0.2; // but sbar face into pain frame + cl.faceanimtime = cl.time + 0.2; // but sbar face into pain frame - cl.cshifts[CSHIFT_DAMAGE].percent += 3*count; + cl.cshifts[CSHIFT_DAMAGE].percent += 3 * count; if (cl.cshifts[CSHIFT_DAMAGE].percent < 0) cl.cshifts[CSHIFT_DAMAGE].percent = 0; if (cl.cshifts[CSHIFT_DAMAGE].percent > 150) @@ -347,14 +348,14 @@ void V_ParseDamage (void) // VectorSubtract (from, cl.simorg, from); VectorNormalize (from); - + AngleVectors (cl.simangles, forward, right, up); side = DotProduct (from, right); - v_dmg_roll = count*side*v_kickroll->value; - + v_dmg_roll = count * side * v_kickroll->value; + side = DotProduct (from, forward); - v_dmg_pitch = count*side*v_kickpitch->value; + v_dmg_pitch = count * side * v_kickpitch->value; v_dmg_time = v_kicktime->value; } @@ -365,12 +366,13 @@ void V_ParseDamage (void) V_cshift_f ================== */ -void V_cshift_f (void) +void +V_cshift_f (void) { - cshift_empty.destcolor[0] = atoi(Cmd_Argv(1)); - cshift_empty.destcolor[1] = atoi(Cmd_Argv(2)); - cshift_empty.destcolor[2] = atoi(Cmd_Argv(3)); - cshift_empty.percent = atoi(Cmd_Argv(4)); + cshift_empty.destcolor[0] = atoi (Cmd_Argv (1)); + cshift_empty.destcolor[1] = atoi (Cmd_Argv (2)); + cshift_empty.destcolor[2] = atoi (Cmd_Argv (3)); + cshift_empty.percent = atoi (Cmd_Argv (4)); } @@ -381,7 +383,8 @@ V_BonusFlash_f When you run over an item, the server sends this command ================== */ -void V_BonusFlash_f (void) +void +V_BonusFlash_f (void) { cl.cshifts[CSHIFT_BONUS].destcolor[0] = 215; cl.cshifts[CSHIFT_BONUS].destcolor[1] = 186; @@ -396,7 +399,8 @@ V_SetContentsColor Underwater, lava, etc each has a color shift ============= */ -void V_SetContentsColor (int contents) +void +V_SetContentsColor (int contents) { if (!v_contentblend->int_val) { cl.cshifts[CSHIFT_CONTENTS] = cshift_empty; @@ -404,18 +408,18 @@ void V_SetContentsColor (int contents) } switch (contents) { - case CONTENTS_EMPTY: - cl.cshifts[CSHIFT_CONTENTS] = cshift_empty; - break; - case CONTENTS_LAVA: - cl.cshifts[CSHIFT_CONTENTS] = cshift_lava; - break; - case CONTENTS_SOLID: - case CONTENTS_SLIME: - cl.cshifts[CSHIFT_CONTENTS] = cshift_slime; - break; - default: - cl.cshifts[CSHIFT_CONTENTS] = cshift_water; + case CONTENTS_EMPTY: + cl.cshifts[CSHIFT_CONTENTS] = cshift_empty; + break; + case CONTENTS_LAVA: + cl.cshifts[CSHIFT_CONTENTS] = cshift_lava; + break; + case CONTENTS_SOLID: + case CONTENTS_SLIME: + cl.cshifts[CSHIFT_CONTENTS] = cshift_slime; + break; + default: + cl.cshifts[CSHIFT_CONTENTS] = cshift_water; } } @@ -424,9 +428,10 @@ void V_SetContentsColor (int contents) V_CalcPowerupCshift ============= */ -void V_CalcPowerupCshift (void) +void +V_CalcPowerupCshift (void) { - if (cl.stats[STAT_ITEMS] & IT_QUAD) { + if (cl.stats[STAT_ITEMS] & IT_QUAD) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 255; @@ -456,11 +461,12 @@ void V_CalcPowerupCshift (void) VIEW RENDERING ============================================================================== -*/ +*/ -float angledelta (float a) +float +angledelta (float a) { - a = anglemod(a); + a = anglemod (a); if (a > 180) a -= 360; return a; @@ -471,48 +477,43 @@ float angledelta (float a) CalcGunAngle ================== */ -void CalcGunAngle (void) -{ - float yaw, pitch, move; +void +CalcGunAngle (void) +{ + float yaw, pitch, move; static float oldyaw = 0; static float oldpitch = 0; - + yaw = r_refdef.viewangles[YAW]; pitch = -r_refdef.viewangles[PITCH]; - yaw = angledelta(yaw - r_refdef.viewangles[YAW]) * 0.4; + yaw = angledelta (yaw - r_refdef.viewangles[YAW]) * 0.4; yaw = bound (-10, yaw, 10); - pitch = angledelta(-pitch - r_refdef.viewangles[PITCH]) * 0.4; + pitch = angledelta (-pitch - r_refdef.viewangles[PITCH]) * 0.4; pitch = bound (-10, pitch, 10); - - move = host_frametime*20; - if (yaw > oldyaw) - { + + move = host_frametime * 20; + if (yaw > oldyaw) { if (oldyaw + move < yaw) yaw = oldyaw + move; - } - else - { + } else { if (oldyaw - move > yaw) yaw = oldyaw - move; } - - if (pitch > oldpitch) - { + + if (pitch > oldpitch) { if (oldpitch + move < pitch) pitch = oldpitch + move; - } - else - { + } else { if (oldpitch - move > pitch) pitch = oldpitch - move; } - + oldyaw = yaw; oldpitch = pitch; cl.viewent.angles[YAW] = r_refdef.viewangles[YAW] + yaw; - cl.viewent.angles[PITCH] = - (r_refdef.viewangles[PITCH] + pitch); + cl.viewent.angles[PITCH] = -(r_refdef.viewangles[PITCH] + pitch); } /* @@ -520,7 +521,8 @@ void CalcGunAngle (void) V_BoundOffsets ============== */ -void V_BoundOffsets (void) +void +V_BoundOffsets (void) { // absolutely bound refresh reletive to entity clipping hull // so the view can never be inside a solid wall @@ -546,15 +548,28 @@ V_AddIdle Idle swaying ============== */ -void V_AddIdle (void) +void +V_AddIdle (void) { - r_refdef.viewangles[ROLL] += v_idlescale->value * sin(cl.time*v_iroll_cycle->value) * v_iroll_level->value; - r_refdef.viewangles[PITCH] += v_idlescale->value * sin(cl.time*v_ipitch_cycle->value) * v_ipitch_level->value; - r_refdef.viewangles[YAW] += v_idlescale->value * sin(cl.time*v_iyaw_cycle->value) * v_iyaw_level->value; + r_refdef.viewangles[ROLL] += + v_idlescale->value * sin (cl.time * v_iroll_cycle->value) * + v_iroll_level->value; + r_refdef.viewangles[PITCH] += + v_idlescale->value * sin (cl.time * v_ipitch_cycle->value) * + v_ipitch_level->value; + r_refdef.viewangles[YAW] += + v_idlescale->value * sin (cl.time * v_iyaw_cycle->value) * + v_iyaw_level->value; - cl.viewent.angles[ROLL] -= v_idlescale->value * sin(cl.time*v_iroll_cycle->value) * v_iroll_level->value; - cl.viewent.angles[PITCH] -= v_idlescale->value * sin(cl.time*v_ipitch_cycle->value) * v_ipitch_level->value; - cl.viewent.angles[YAW] -= v_idlescale->value * sin(cl.time*v_iyaw_cycle->value) * v_iyaw_level->value; + cl.viewent.angles[ROLL] -= + v_idlescale->value * sin (cl.time * v_iroll_cycle->value) * + v_iroll_level->value; + cl.viewent.angles[PITCH] -= + v_idlescale->value * sin (cl.time * v_ipitch_cycle->value) * + v_ipitch_level->value; + cl.viewent.angles[YAW] -= + v_idlescale->value * sin (cl.time * v_iyaw_cycle->value) * + v_iyaw_level->value; } @@ -565,17 +580,19 @@ V_CalcViewRoll Roll is induced by movement and damage ============== */ -void V_CalcViewRoll (void) +void +V_CalcViewRoll (void) { - float side; - + float side; + side = V_CalcRoll (cl.simangles, cl.simvel); r_refdef.viewangles[ROLL] += side; - if (v_dmg_time > 0) - { - r_refdef.viewangles[ROLL] += v_dmg_time/v_kicktime->value*v_dmg_roll; - r_refdef.viewangles[PITCH] += v_dmg_time/v_kicktime->value*v_dmg_pitch; + if (v_dmg_time > 0) { + r_refdef.viewangles[ROLL] += + v_dmg_time / v_kicktime->value * v_dmg_roll; + r_refdef.viewangles[PITCH] += + v_dmg_time / v_kicktime->value * v_dmg_pitch; v_dmg_time -= host_frametime; } @@ -588,10 +605,11 @@ V_CalcIntermissionRefdef ================== */ -void V_CalcIntermissionRefdef (void) +void +V_CalcIntermissionRefdef (void) { - entity_t *view; - float old; + entity_t *view; + float old; // view is the weapon model view = &cl.viewent; @@ -602,9 +620,9 @@ void V_CalcIntermissionRefdef (void) // allways idle in intermission old = v_idlescale->value; - Cvar_SetValue(v_idlescale, 1); + Cvar_SetValue (v_idlescale, 1); V_AddIdle (); - Cvar_SetValue(v_idlescale, old); + Cvar_SetValue (v_idlescale, old); } /* @@ -613,14 +631,15 @@ V_CalcRefdef ================== */ -void V_CalcRefdef (void) +void +V_CalcRefdef (void) { - entity_t *view; - int i; - vec3_t forward, right, up; - float bob; - static float oldz = 0; - int zofs = 22; + entity_t *view; + int i; + vec3_t forward, right, up; + float bob; + static float oldz = 0; + int zofs = 22; if (cl.stdver) zofs = cl.stats[STAT_VIEWHEIGHT]; @@ -631,7 +650,7 @@ void V_CalcRefdef (void) view = &cl.viewent; bob = V_CalcBob (); - + // refresh position from simulated origin VectorCopy (cl.simorg, r_refdef.vieworg); @@ -640,41 +659,40 @@ void V_CalcRefdef (void) // never let it sit exactly on a node line, because a water plane can // dissapear when viewed with the eye exactly on it. // the server protocol only specifies to 1/8 pixel, so add 1/16 in each axis - r_refdef.vieworg[0] += 1.0/16; - r_refdef.vieworg[1] += 1.0/16; - r_refdef.vieworg[2] += 1.0/16; + r_refdef.vieworg[0] += 1.0 / 16; + r_refdef.vieworg[1] += 1.0 / 16; + r_refdef.vieworg[2] += 1.0 / 16; VectorCopy (cl.simangles, r_refdef.viewangles); V_CalcViewRoll (); V_AddIdle (); if (view_message->flags & PF_GIB) - r_refdef.vieworg[2] += 8; // gib view height + r_refdef.vieworg[2] += 8; // gib view height else if (view_message->flags & PF_DEAD) - r_refdef.vieworg[2] -= 16; // corpse view height + r_refdef.vieworg[2] -= 16; // corpse view height else r_refdef.vieworg[2] += zofs; // view height - if (view_message->flags & PF_DEAD) // PF_GIB will also set PF_DEAD + if (view_message->flags & PF_DEAD) // PF_GIB will also set PF_DEAD r_refdef.viewangles[ROLL] = 80; // dead view angle // offsets AngleVectors (cl.simangles, forward, right, up); - + // set up gun position VectorCopy (cl.simangles, view->angles); - + CalcGunAngle (); VectorCopy (cl.simorg, view->origin); view->origin[2] += zofs; - for (i=0 ; i<3 ; i++) - { - view->origin[i] += forward[i]*bob*0.4; -// view->origin[i] += right[i]*bob*0.4; -// view->origin[i] += up[i]*bob*0.8; + for (i = 0; i < 3; i++) { + view->origin[i] += forward[i] * bob * 0.4; +// view->origin[i] += right[i]*bob*0.4; +// view->origin[i] += up[i]*bob*0.8; } view->origin[2] += bob; @@ -689,9 +707,9 @@ void V_CalcRefdef (void) else if (scr_viewsize->int_val == 80) view->origin[2] += 0.5; - if (view_message->flags & (PF_GIB|PF_DEAD) ) - view->model = NULL; - else + if (view_message->flags & (PF_GIB | PF_DEAD)) + view->model = NULL; + else view->model = cl.model_precache[cl.stats[STAT_WEAPON]]; view->frame = view_message->weaponframe; view->colormap = vid.colormap; @@ -703,12 +721,11 @@ void V_CalcRefdef (void) r_refdef.viewangles[PITCH] += cl.punchangle; // smooth out stair step ups - if ( (view_message->onground != -1) && (cl.simorg[2] - oldz > 0) ) - { - float steptime; - + if ((view_message->onground != -1) && (cl.simorg[2] - oldz > 0)) { + float steptime; + steptime = host_frametime; - + oldz += steptime * 80; if (oldz > cl.simorg[2]) oldz = cl.simorg[2]; @@ -716,8 +733,7 @@ void V_CalcRefdef (void) oldz = cl.simorg[2] - 12; r_refdef.vieworg[2] += oldz - cl.simorg[2]; view->origin[2] += oldz - cl.simorg[2]; - } - else + } else oldz = cl.simorg[2]; } @@ -726,9 +742,10 @@ void V_CalcRefdef (void) DropPunchAngle ============= */ -void DropPunchAngle (void) +void +DropPunchAngle (void) { - cl.punchangle -= 10*host_frametime; + cl.punchangle -= 10 * host_frametime; if (cl.punchangle < 0) cl.punchangle = 0; } @@ -743,11 +760,12 @@ the entity origin, so any view position inside that will be valid */ extern vrect_t scr_vrect; -void V_RenderView (void) +void +V_RenderView (void) { -// if (cl.simangles[ROLL]) -// Sys_Error ("cl.simangles[ROLL]"); // DEBUG - cl.simangles[ROLL] = 0; // FIXME @@@ +// if (cl.simangles[ROLL]) +// Sys_Error ("cl.simangles[ROLL]"); // DEBUG + cl.simangles[ROLL] = 0; // FIXME @@@ if (cls.state != ca_active) return; @@ -756,12 +774,9 @@ void V_RenderView (void) view_message = &view_frame->playerstate[cl.playernum]; DropPunchAngle (); - if (cl.intermission) - { // intermission / finale rendering - V_CalcIntermissionRefdef (); - } - else - { + if (cl.intermission) { // intermission / finale rendering + V_CalcIntermissionRefdef (); + } else { V_CalcRefdef (); } @@ -777,44 +792,46 @@ void V_RenderView (void) V_Init ============= */ -void V_Init (void) +void +V_Init (void) { - Cmd_AddCommand ("v_cshift", V_cshift_f); + Cmd_AddCommand ("v_cshift", V_cshift_f); Cmd_AddCommand ("bf", V_BonusFlash_f); Cmd_AddCommand ("centerview", V_StartPitchDrift); - BuildGammaTable (1.0, 1.0); // no gamma yet + BuildGammaTable (1.0, 1.0); // no gamma yet } -void V_Init_Cvars (void) +void +V_Init_Cvars (void) { - v_centermove = Cvar_Get("v_centermove", "0.15", CVAR_NONE, "None"); - v_centerspeed = Cvar_Get("v_centerspeed", "500", CVAR_NONE, "None"); + v_centermove = Cvar_Get ("v_centermove", "0.15", CVAR_NONE, "None"); + v_centerspeed = Cvar_Get ("v_centerspeed", "500", CVAR_NONE, "None"); - v_iyaw_cycle = Cvar_Get("v_iyaw_cycle", "2", CVAR_NONE, "None"); - v_iroll_cycle = Cvar_Get("v_iroll_cycle", "0.5", CVAR_NONE, "None"); - v_ipitch_cycle = Cvar_Get("v_ipitch_cycle", "1", CVAR_NONE, "None"); - v_iyaw_level = Cvar_Get("v_iyaw_level", "0.3", CVAR_NONE, "None"); - v_iroll_level = Cvar_Get("v_iroll_level", "0.1", CVAR_NONE, "None"); - v_ipitch_level = Cvar_Get("v_ipitch_level", "0.3", CVAR_NONE, "None"); + v_iyaw_cycle = Cvar_Get ("v_iyaw_cycle", "2", CVAR_NONE, "None"); + v_iroll_cycle = Cvar_Get ("v_iroll_cycle", "0.5", CVAR_NONE, "None"); + v_ipitch_cycle = Cvar_Get ("v_ipitch_cycle", "1", CVAR_NONE, "None"); + v_iyaw_level = Cvar_Get ("v_iyaw_level", "0.3", CVAR_NONE, "None"); + v_iroll_level = Cvar_Get ("v_iroll_level", "0.1", CVAR_NONE, "None"); + v_ipitch_level = Cvar_Get ("v_ipitch_level", "0.3", CVAR_NONE, "None"); - v_contentblend = Cvar_Get("v_contentblend", "1", CVAR_NONE, "None"); + v_contentblend = Cvar_Get ("v_contentblend", "1", CVAR_NONE, "None"); - v_idlescale = Cvar_Get("v_idlescale", "0", CVAR_NONE, "None"); + v_idlescale = Cvar_Get ("v_idlescale", "0", CVAR_NONE, "None"); - cl_rollspeed = Cvar_Get("cl_rollspeed", "200", CVAR_NONE, "None"); - cl_rollangle = Cvar_Get("cl_rollangle", "2.0", CVAR_NONE, "None"); + cl_rollspeed = Cvar_Get ("cl_rollspeed", "200", CVAR_NONE, "None"); + cl_rollangle = Cvar_Get ("cl_rollangle", "2.0", CVAR_NONE, "None"); - cl_bob = Cvar_Get("cl_bob", "0.02", CVAR_NONE, "None"); - cl_bobcycle = Cvar_Get("cl_bobcycle", "0.6", CVAR_NONE, "None"); - cl_bobup = Cvar_Get("cl_bobup", "0.5", CVAR_NONE, "None"); + cl_bob = Cvar_Get ("cl_bob", "0.02", CVAR_NONE, "None"); + cl_bobcycle = Cvar_Get ("cl_bobcycle", "0.6", CVAR_NONE, "None"); + cl_bobup = Cvar_Get ("cl_bobup", "0.5", CVAR_NONE, "None"); - v_kicktime = Cvar_Get("v_kicktime", "0.5", CVAR_NONE, "None"); - v_kickroll = Cvar_Get("v_kickroll", "0.6", CVAR_NONE, "None"); - v_kickpitch = Cvar_Get("v_kickpitch", "0.6", CVAR_NONE, "None"); + v_kicktime = Cvar_Get ("v_kicktime", "0.5", CVAR_NONE, "None"); + v_kickroll = Cvar_Get ("v_kickroll", "0.6", CVAR_NONE, "None"); + v_kickpitch = Cvar_Get ("v_kickpitch", "0.6", CVAR_NONE, "None"); - gl_cshiftpercent = Cvar_Get("gl_cshiftpercent", "100", CVAR_NONE, "None"); + gl_cshiftpercent = Cvar_Get ("gl_cshiftpercent", "100", CVAR_NONE, "None"); - brightness = Cvar_Get("brightness", "1", CVAR_ARCHIVE, "None"); - contrast = Cvar_Get("contrast", "1", CVAR_ARCHIVE, "None"); + brightness = Cvar_Get ("brightness", "1", CVAR_ARCHIVE, "None"); + contrast = Cvar_Get ("contrast", "1", CVAR_ARCHIVE, "None"); } diff --git a/source/sbar.c b/source/sbar.c index f4dffb8..e0d819a 100644 --- a/source/sbar.c +++ b/source/sbar.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sbar.h" #include "screen.h" @@ -45,36 +45,42 @@ #include #include -int sb_updates; // if >= vid.numpages, no update needed +int sb_updates; // if >= vid.numpages, no update -#define STAT_MINUS 10 // num frame for '-' stats digit -qpic_t *sb_nums[2][11]; -qpic_t *sb_colon, *sb_slash; -qpic_t *sb_ibar; -qpic_t *sb_sbar; -qpic_t *sb_scorebar; + // needed -qpic_t *sb_weapons[7][8]; // 0 is active, 1 is owned, 2-5 are flashes -qpic_t *sb_ammo[4]; -qpic_t *sb_sigil[4]; -qpic_t *sb_armor[3]; -qpic_t *sb_items[32]; +#define STAT_MINUS 10 // num frame for '-' stats digit +qpic_t *sb_nums[2][11]; +qpic_t *sb_colon, *sb_slash; +qpic_t *sb_ibar; +qpic_t *sb_sbar; +qpic_t *sb_scorebar; -qpic_t *sb_faces[7][2]; // 0 is gibbed, 1 is dead, 2-6 are alive +qpic_t *sb_weapons[7][8]; // 0 is active, 1 is owned, 2-5 are + + // flashes +qpic_t *sb_ammo[4]; +qpic_t *sb_sigil[4]; +qpic_t *sb_armor[3]; +qpic_t *sb_items[32]; + +qpic_t *sb_faces[7][2]; // 0 is gibbed, 1 is dead, 2-6 are + + // alive // 0 is static, 1 is temporary animation -qpic_t *sb_face_invis; -qpic_t *sb_face_quad; -qpic_t *sb_face_invuln; -qpic_t *sb_face_invis_invuln; +qpic_t *sb_face_invis; +qpic_t *sb_face_quad; +qpic_t *sb_face_invuln; +qpic_t *sb_face_invis_invuln; -qboolean sb_showscores; -qboolean sb_showteamscores; +qboolean sb_showscores; +qboolean sb_showteamscores; -int sb_lines; // scan lines to draw +int sb_lines; // scan lines to draw -void Sbar_DeathmatchOverlay (int start); -void Sbar_TeamOverlay (void); -void Sbar_MiniDeathmatchOverlay (void); +void Sbar_DeathmatchOverlay (int start); +void Sbar_TeamOverlay (void); +void Sbar_MiniDeathmatchOverlay (void); static qboolean largegame = false; @@ -85,7 +91,8 @@ Sbar_ShowTeamScores Tab key down =============== */ -void Sbar_ShowTeamScores (void) +void +Sbar_ShowTeamScores (void) { if (sb_showteamscores) return; @@ -101,7 +108,8 @@ Sbar_DontShowTeamScores Tab key up =============== */ -void Sbar_DontShowTeamScores (void) +void +Sbar_DontShowTeamScores (void) { sb_showteamscores = false; sb_updates = 0; @@ -114,7 +122,8 @@ Sbar_ShowScores Tab key down =============== */ -void Sbar_ShowScores (void) +void +Sbar_ShowScores (void) { if (sb_showscores) return; @@ -130,7 +139,8 @@ Sbar_DontShowScores Tab key up =============== */ -void Sbar_DontShowScores (void) +void +Sbar_DontShowScores (void) { sb_showscores = false; sb_updates = 0; @@ -141,9 +151,10 @@ void Sbar_DontShowScores (void) Sbar_Changed =============== */ -void Sbar_Changed (void) +void +Sbar_Changed (void) { - sb_updates = 0; // update next frame + sb_updates = 0; // update next frame } /* @@ -151,14 +162,14 @@ void Sbar_Changed (void) Sbar_Init =============== */ -void Sbar_Init (void) +void +Sbar_Init (void) { - int i; + int i; - for (i=0 ; i<10 ; i++) - { - sb_nums[0][i] = Draw_PicFromWad (va("num_%i",i)); - sb_nums[1][i] = Draw_PicFromWad (va("anum_%i",i)); + for (i = 0; i < 10; i++) { + sb_nums[0][i] = Draw_PicFromWad (va ("num_%i", i)); + sb_nums[1][i] = Draw_PicFromWad (va ("anum_%i", i)); } sb_nums[0][10] = Draw_PicFromWad ("num_minus"); @@ -174,7 +185,7 @@ void Sbar_Init (void) sb_weapons[0][4] = Draw_PicFromWad ("inv_rlaunch"); sb_weapons[0][5] = Draw_PicFromWad ("inv_srlaunch"); sb_weapons[0][6] = Draw_PicFromWad ("inv_lightng"); - + sb_weapons[1][0] = Draw_PicFromWad ("inv2_shotgun"); sb_weapons[1][1] = Draw_PicFromWad ("inv2_sshotgun"); sb_weapons[1][2] = Draw_PicFromWad ("inv2_nailgun"); @@ -182,16 +193,15 @@ void Sbar_Init (void) sb_weapons[1][4] = Draw_PicFromWad ("inv2_rlaunch"); sb_weapons[1][5] = Draw_PicFromWad ("inv2_srlaunch"); sb_weapons[1][6] = Draw_PicFromWad ("inv2_lightng"); - - for (i=0 ; i<5 ; i++) - { - sb_weapons[2+i][0] = Draw_PicFromWad (va("inva%i_shotgun",i+1)); - sb_weapons[2+i][1] = Draw_PicFromWad (va("inva%i_sshotgun",i+1)); - sb_weapons[2+i][2] = Draw_PicFromWad (va("inva%i_nailgun",i+1)); - sb_weapons[2+i][3] = Draw_PicFromWad (va("inva%i_snailgun",i+1)); - sb_weapons[2+i][4] = Draw_PicFromWad (va("inva%i_rlaunch",i+1)); - sb_weapons[2+i][5] = Draw_PicFromWad (va("inva%i_srlaunch",i+1)); - sb_weapons[2+i][6] = Draw_PicFromWad (va("inva%i_lightng",i+1)); + + for (i = 0; i < 5; i++) { + sb_weapons[2 + i][0] = Draw_PicFromWad (va ("inva%i_shotgun", i + 1)); + sb_weapons[2 + i][1] = Draw_PicFromWad (va ("inva%i_sshotgun", i + 1)); + sb_weapons[2 + i][2] = Draw_PicFromWad (va ("inva%i_nailgun", i + 1)); + sb_weapons[2 + i][3] = Draw_PicFromWad (va ("inva%i_snailgun", i + 1)); + sb_weapons[2 + i][4] = Draw_PicFromWad (va ("inva%i_rlaunch", i + 1)); + sb_weapons[2 + i][5] = Draw_PicFromWad (va ("inva%i_srlaunch", i + 1)); + sb_weapons[2 + i][6] = Draw_PicFromWad (va ("inva%i_lightng", i + 1)); } sb_ammo[0] = Draw_PicFromWad ("sb_shells"); @@ -233,10 +243,10 @@ void Sbar_Init (void) Cmd_AddCommand ("+showscores", Sbar_ShowScores); Cmd_AddCommand ("-showscores", Sbar_DontShowScores); - + Cmd_AddCommand ("+showteamscores", Sbar_ShowTeamScores); Cmd_AddCommand ("-showteamscores", Sbar_DontShowTeamScores); - + sb_sbar = Draw_PicFromWad ("sbar"); sb_ibar = Draw_PicFromWad ("ibar"); sb_scorebar = Draw_PicFromWad ("scorebar"); @@ -252,9 +262,11 @@ void Sbar_Init (void) Sbar_DrawPic ============= */ -void Sbar_DrawPic (int x, int y, qpic_t *pic) +void +Sbar_DrawPic (int x, int y, qpic_t *pic) { - Draw_Pic (x /* + ((vid.width - 320)>>1) */, y + (vid.height-SBAR_HEIGHT), pic); + Draw_Pic (x /* + ((vid.width - 320)>>1) */ , y + (vid.height - SBAR_HEIGHT), + pic); } /* @@ -264,9 +276,12 @@ Sbar_DrawSubPic JACK: Draws a portion of the picture in the status bar. */ -void Sbar_DrawSubPic(int x, int y, qpic_t *pic, int srcx, int srcy, int width, int height) +void +Sbar_DrawSubPic (int x, int y, qpic_t *pic, int srcx, int srcy, int width, + int height) { - Draw_SubPic (x, y+(vid.height-SBAR_HEIGHT), pic, srcx, srcy, width, height); + Draw_SubPic (x, y + (vid.height - SBAR_HEIGHT), pic, srcx, srcy, width, + height); } @@ -275,9 +290,11 @@ void Sbar_DrawSubPic(int x, int y, qpic_t *pic, int srcx, int srcy, int width, i Sbar_DrawTransPic ============= */ -void Sbar_DrawTransPic (int x, int y, qpic_t *pic) +void +Sbar_DrawTransPic (int x, int y, qpic_t *pic) { - Draw_Pic (x /*+ ((vid.width - 320)>>1) */, y + (vid.height-SBAR_HEIGHT), pic); + Draw_Pic (x /* + ((vid.width - 320)>>1) */ , y + (vid.height - SBAR_HEIGHT), + pic); } /* @@ -287,9 +304,11 @@ Sbar_DrawCharacter Draws one solid graphics character ================ */ -void Sbar_DrawCharacter (int x, int y, int num) +void +Sbar_DrawCharacter (int x, int y, int num) { - Draw_Character8 ( x /*+ ((vid.width - 320)>>1) */ + 4, y + vid.height-SBAR_HEIGHT, num); + Draw_Character8 (x /* + ((vid.width - 320)>>1) */ + 4, + y + vid.height - SBAR_HEIGHT, num); } /* @@ -297,9 +316,11 @@ void Sbar_DrawCharacter (int x, int y, int num) Sbar_DrawString ================ */ -void Sbar_DrawString (int x, int y, char *str) +void +Sbar_DrawString (int x, int y, char *str) { - Draw_String8 (x /*+ ((vid.width - 320)>>1) */, y+ vid.height-SBAR_HEIGHT, str); + Draw_String8 (x /* + ((vid.width - 320)>>1) */ , + y + vid.height - SBAR_HEIGHT, str); } /* @@ -307,34 +328,32 @@ void Sbar_DrawString (int x, int y, char *str) Sbar_itoa ============= */ -int Sbar_itoa (int num, char *buf) +int +Sbar_itoa (int num, char *buf) { - char *str; - int pow10; - int dig; - + char *str; + int pow10; + int dig; + str = buf; - - if (num < 0) - { + + if (num < 0) { *str++ = '-'; num = -num; } - - for (pow10 = 10 ; num >= pow10 ; pow10 *= 10) - ; - - do - { + + for (pow10 = 10; num >= pow10; pow10 *= 10); + + do { pow10 /= 10; - dig = num/pow10; - *str++ = '0'+dig; - num -= dig*pow10; + dig = num / pow10; + *str++ = '0' + dig; + num -= dig * pow10; } while (pow10 != 1); - + *str = 0; - - return str-buf; + + return str - buf; } @@ -343,27 +362,27 @@ int Sbar_itoa (int num, char *buf) Sbar_DrawNum ============= */ -void Sbar_DrawNum (int x, int y, int num, int digits, int color) +void +Sbar_DrawNum (int x, int y, int num, int digits, int color) { - char str[12]; - char *ptr; - int l, frame; + char str[12]; + char *ptr; + int l, frame; l = Sbar_itoa (num, str); ptr = str; if (l > digits) - ptr += (l-digits); + ptr += (l - digits); if (l < digits) - x += (digits-l)*24; + x += (digits - l) * 24; - while (*ptr) - { + while (*ptr) { if (*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - Sbar_DrawTransPic (x,y,sb_nums[color][frame]); + Sbar_DrawTransPic (x, y, sb_nums[color][frame]); x += 24; ptr++; } @@ -372,68 +391,67 @@ void Sbar_DrawNum (int x, int y, int num, int digits, int color) //============================================================================= //ZOID: this should be MAX_CLIENTS, not MAX_SCOREBOARD!! -//int fragsort[MAX_SCOREBOARD]; -int fragsort[MAX_CLIENTS]; -int scoreboardlines; +//int fragsort[MAX_SCOREBOARD]; +int fragsort[MAX_CLIENTS]; +int scoreboardlines; typedef struct { - char team[16+1]; - int frags; - int players; - int plow, phigh, ptotal; + char team[16 + 1]; + int frags; + int players; + int plow, phigh, ptotal; } team_t; -team_t teams[MAX_CLIENTS]; -int teamsort[MAX_CLIENTS]; -int scoreboardteams; +team_t teams[MAX_CLIENTS]; +int teamsort[MAX_CLIENTS]; +int scoreboardteams; /* =============== Sbar_SortFrags =============== */ -void Sbar_SortFrags (qboolean includespec) +void +Sbar_SortFrags (qboolean includespec) { - int i, j, k; - + int i, j, k; + // sort by frags scoreboardlines = 0; - for (i=0 ; iuserinfo, "team"), 16); + strncpy (t, Info_ValueForKey (s->userinfo, "team"), 16); if (!t || !t[0]) - continue; // not on team + continue; // not on team for (j = 0; j < scoreboardteams; j++) - if (!strcmp(teams[j].team, t)) { + if (!strcmp (teams[j].team, t)) { teams[j].frags += s->frags; teams[j].players++; goto addpinginfo; } - if (j == scoreboardteams) { // must add him + if (j == scoreboardteams) { // must add him j = scoreboardteams++; - strcpy(teams[j].team, t); + strcpy (teams[j].team, t); teams[j].frags = s->frags; teams[j].players = 1; -addpinginfo: + addpinginfo: if (teams[j].plow > s->ping) teams[j].plow = s->ping; if (teams[j].phigh < s->ping) @@ -483,7 +501,8 @@ addpinginfo: } } -int Sbar_ColorForMap (int m) +int +Sbar_ColorForMap (int m) { return (bound (0, m, 13) * 16) + 8; } @@ -494,19 +513,20 @@ int Sbar_ColorForMap (int m) Sbar_SoloScoreboard =============== */ -void Sbar_SoloScoreboard (void) +void +Sbar_SoloScoreboard (void) { - char str[80]; - int minutes, seconds, tens, units; + char str[80]; + int minutes, seconds, tens, units; Sbar_DrawPic (0, 0, sb_scorebar); // time minutes = cl.time / 60; - seconds = cl.time - 60*minutes; + seconds = cl.time - 60 * minutes; tens = seconds / 10; - units = seconds - 10*tens; - snprintf (str, sizeof(str),"Time :%3i:%i%i", minutes, tens, units); + units = seconds - 10 * tens; + snprintf (str, sizeof (str), "Time :%3i:%i%i", minutes, tens, units); Sbar_DrawString (184, 4, str); } @@ -517,103 +537,102 @@ void Sbar_SoloScoreboard (void) Sbar_DrawInventory =============== */ -void Sbar_DrawInventory (void) -{ - int i; - char num[6]; - float time; - int flashon; - qboolean headsup; +void +Sbar_DrawInventory (void) +{ + int i; + char num[6]; + float time; + int flashon; + qboolean headsup; qboolean hudswap; - headsup = !(cl_sbar->int_val || scr_viewsize->int_val<100); + headsup = !(cl_sbar->int_val || scr_viewsize->int_val < 100); hudswap = cl_hudswap->int_val; if (!headsup) Sbar_DrawPic (0, -24, sb_ibar); // weapons - for (i=0 ; i<7 ; i++) - { - if (cl.stats[STAT_ITEMS] & (IT_SHOTGUN<= 10) - { - if ( cl.stats[STAT_ACTIVEWEAPON] == (IT_SHOTGUN<= 10) { + if (cl.stats[STAT_ACTIVEWEAPON] == (IT_SHOTGUN << i)) flashon = 1; else flashon = 0; - } - else - flashon = (flashon%5) + 2; + } else + flashon = (flashon % 5) + 2; if (headsup) { - if (i || vid.height>200) - Sbar_DrawSubPic ((hudswap) ? 0 : (vid.width-24),-68-(7-i)*16 , sb_weapons[flashon][i],0,0,24,16); - - } else - Sbar_DrawPic (i*24, -16, sb_weapons[flashon][i]); -// Sbar_DrawSubPic (0,0,20,20,i*24, -16, sb_weapons[flashon][i]); + if (i || vid.height > 200) + Sbar_DrawSubPic ((hudswap) ? 0 : (vid.width - 24), + -68 - (7 - i) * 16, sb_weapons[flashon][i], + 0, 0, 24, 16); + + } else + Sbar_DrawPic (i * 24, -16, sb_weapons[flashon][i]); +// Sbar_DrawSubPic (0,0,20,20,i*24, -16, sb_weapons[flashon][i]); if (flashon > 1) - sb_updates = 0; // force update to remove flash + sb_updates = 0; // force update to remove flash } } // ammo counts - for (i=0 ; i<4 ; i++) - { - snprintf (num, sizeof(num), "%3i",cl.stats[STAT_SHELLS+i] ); + for (i = 0; i < 4; i++) { + snprintf (num, sizeof (num), "%3i", cl.stats[STAT_SHELLS + i]); if (headsup) { -// Sbar_DrawSubPic(3, -24, sb_ibar, 3, 0, 42,11); - Sbar_DrawSubPic((hudswap) ? 0 : (vid.width-42), -24 - (4-i)*11, sb_ibar, 3+(i*48), 0, 42, 11); +// Sbar_DrawSubPic(3, -24, sb_ibar, 3, 0, 42,11); + Sbar_DrawSubPic ((hudswap) ? 0 : (vid.width - 42), + -24 - (4 - i) * 11, sb_ibar, 3 + (i * 48), 0, 42, + 11); if (num[0] != ' ') - Sbar_DrawCharacter ( (hudswap) ? 3 : (vid.width-39), -24 - (4-i)*11, 18 + num[0] - '0'); + Sbar_DrawCharacter ((hudswap) ? 3 : (vid.width - 39), + -24 - (4 - i) * 11, 18 + num[0] - '0'); if (num[1] != ' ') - Sbar_DrawCharacter ( (hudswap) ? 11 : (vid.width-31), -24 - (4-i)*11, 18 + num[1] - '0'); + Sbar_DrawCharacter ((hudswap) ? 11 : (vid.width - 31), + -24 - (4 - i) * 11, 18 + num[1] - '0'); if (num[2] != ' ') - Sbar_DrawCharacter ( (hudswap) ? 19 : (vid.width-23), -24 - (4-i)*11, 18 + num[2] - '0'); + Sbar_DrawCharacter ((hudswap) ? 19 : (vid.width - 23), + -24 - (4 - i) * 11, 18 + num[2] - '0'); } else { - if (num[0] != ' ') - Sbar_DrawCharacter ( (6*i+1)*8 - 2, -24, 18 + num[0] - '0'); - if (num[1] != ' ') - Sbar_DrawCharacter ( (6*i+2)*8 - 2, -24, 18 + num[1] - '0'); - if (num[2] != ' ') - Sbar_DrawCharacter ( (6*i+3)*8 - 2, -24, 18 + num[2] - '0'); + if (num[0] != ' ') + Sbar_DrawCharacter ((6 * i + 1) * 8 - 2, -24, + 18 + num[0] - '0'); + if (num[1] != ' ') + Sbar_DrawCharacter ((6 * i + 2) * 8 - 2, -24, + 18 + num[1] - '0'); + if (num[2] != ' ') + Sbar_DrawCharacter ((6 * i + 3) * 8 - 2, -24, + 18 + num[2] - '0'); + } } - } - + flashon = 0; // items - for (i=0 ; i<6 ; i++) - if (cl.stats[STAT_ITEMS] & (1<<(17+i))) - { - time = cl.item_gettime[17+i]; - if (time && time > cl.time - 2 && flashon ) - { // flash frame + for (i = 0; i < 6; i++) + if (cl.stats[STAT_ITEMS] & (1 << (17 + i))) { + time = cl.item_gettime[17 + i]; + if (time && time > cl.time - 2 && flashon) { // flash frame sb_updates = 0; - } - else - Sbar_DrawPic (192 + i*16, -16, sb_items[i]); - if (time && time > cl.time - 2) + } else + Sbar_DrawPic (192 + i * 16, -16, sb_items[i]); + if (time && time > cl.time - 2) sb_updates = 0; } - // sigils - for (i=0 ; i<4 ; i++) - if (cl.stats[STAT_ITEMS] & (1<<(28+i))) - { - time = cl.item_gettime[28+i]; - if (time && time > cl.time - 2 && flashon ) - { // flash frame + for (i = 0; i < 4; i++) + if (cl.stats[STAT_ITEMS] & (1 << (28 + i))) { + time = cl.item_gettime[28 + i]; + if (time && time > cl.time - 2 && flashon) { // flash frame sb_updates = 0; - } - else - Sbar_DrawPic (320-32 + i*8, -16, sb_sigil[i]); - if (time && time > cl.time - 2) + } else + Sbar_DrawPic (320 - 32 + i * 8, -16, sb_sigil[i]); + if (time && time > cl.time - 2) sb_updates = 0; } } @@ -625,25 +644,25 @@ void Sbar_DrawInventory (void) Sbar_DrawFrags =============== */ -void Sbar_DrawFrags (void) -{ - int i, k, l; - int top, bottom; - int x, y, f; - char num[12]; - player_info_t *s; - +void +Sbar_DrawFrags (void) +{ + int i, k, l; + int top, bottom; + int x, y, f; + char num[12]; + player_info_t *s; + Sbar_SortFrags (false); // draw the text l = scoreboardlines <= 4 ? scoreboardlines : 4; - + x = 23; -// xofs = (vid.width - 320)>>1; +// xofs = (vid.width - 320)>>1; y = vid.height - SBAR_HEIGHT - 23; - for (i=0 ; iname[0]) @@ -651,7 +670,7 @@ void Sbar_DrawFrags (void) if (s->spectator) continue; - // draw background + // draw background top = s->topcolor; bottom = s->bottomcolor; top = (top < 0) ? 0 : ((top > 13) ? 13 : top); @@ -659,26 +678,25 @@ void Sbar_DrawFrags (void) top = Sbar_ColorForMap (top); bottom = Sbar_ColorForMap (bottom); - -// Draw_Fill (xofs + x*8 + 10, y, 28, 4, top); -// Draw_Fill (xofs + x*8 + 10, y+4, 28, 3, bottom); - Draw_Fill (x*8 + 10, y, 28, 4, top); - Draw_Fill (x*8 + 10, y+4, 28, 3, bottom); - // draw number +// Draw_Fill (xofs + x*8 + 10, y, 28, 4, top); +// Draw_Fill (xofs + x*8 + 10, y+4, 28, 3, bottom); + Draw_Fill (x * 8 + 10, y, 28, 4, top); + Draw_Fill (x * 8 + 10, y + 4, 28, 3, bottom); + + // draw number f = s->frags; - snprintf (num, sizeof(num), "%3i",f); - - Sbar_DrawCharacter ( (x+1)*8 , -24, num[0]); - Sbar_DrawCharacter ( (x+2)*8 , -24, num[1]); - Sbar_DrawCharacter ( (x+3)*8 , -24, num[2]); + snprintf (num, sizeof (num), "%3i", f); - if (k == cl.playernum) - { - Sbar_DrawCharacter (x*8+2, -24, 16); - Sbar_DrawCharacter ( (x+4)*8-4, -24, 17); + Sbar_DrawCharacter ((x + 1) * 8, -24, num[0]); + Sbar_DrawCharacter ((x + 2) * 8, -24, num[1]); + Sbar_DrawCharacter ((x + 3) * 8, -24, num[2]); + + if (k == cl.playernum) { + Sbar_DrawCharacter (x * 8 + 2, -24, 16); + Sbar_DrawCharacter ((x + 4) * 8 - 4, -24, 17); } - x+=4; + x += 4; } } @@ -690,28 +708,25 @@ void Sbar_DrawFrags (void) Sbar_DrawFace =============== */ -void Sbar_DrawFace (void) +void +Sbar_DrawFace (void) { - int f, anim; + int f, anim; - if ( (cl.stats[STAT_ITEMS] & (IT_INVISIBILITY | IT_INVULNERABILITY) ) - == (IT_INVISIBILITY | IT_INVULNERABILITY) ) - { + if ((cl.stats[STAT_ITEMS] & (IT_INVISIBILITY | IT_INVULNERABILITY)) + == (IT_INVISIBILITY | IT_INVULNERABILITY)) { Sbar_DrawPic (112, 0, sb_face_invis_invuln); return; } - if (cl.stats[STAT_ITEMS] & IT_QUAD) - { - Sbar_DrawPic (112, 0, sb_face_quad ); + if (cl.stats[STAT_ITEMS] & IT_QUAD) { + Sbar_DrawPic (112, 0, sb_face_quad); return; } - if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY) - { - Sbar_DrawPic (112, 0, sb_face_invis ); + if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY) { + Sbar_DrawPic (112, 0, sb_face_invis); return; } - if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY) - { + if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY) { Sbar_DrawPic (112, 0, sb_face_invuln); return; } @@ -720,13 +735,11 @@ void Sbar_DrawFace (void) f = 4; else f = cl.stats[STAT_HEALTH] / 20; - - if (cl.time <= cl.faceanimtime) - { + + if (cl.time <= cl.faceanimtime) { anim = 1; - sb_updates = 0; // make sure the anim gets drawn over - } - else + sb_updates = 0; // make sure the anim gets drawn over + } else anim = 0; Sbar_DrawPic (112, 0, sb_faces[f][anim]); } @@ -736,21 +749,19 @@ void Sbar_DrawFace (void) Sbar_DrawNormal ============= */ -void Sbar_DrawNormal (void) +void +Sbar_DrawNormal (void) { - if (cl_sbar->int_val || scr_viewsize->int_val<100) + if (cl_sbar->int_val || scr_viewsize->int_val < 100) Sbar_DrawPic (0, 0, sb_sbar); // armor - if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY) - { + if (cl.stats[STAT_ITEMS] & IT_INVULNERABILITY) { Sbar_DrawNum (24, 0, 666, 3, 1); Sbar_DrawPic (0, 0, draw_disc); - } - else - { - Sbar_DrawNum (24, 0, cl.stats[STAT_ARMOR], 3 - , cl.stats[STAT_ARMOR] <= 25); + } else { + Sbar_DrawNum (24, 0, cl.stats[STAT_ARMOR], 3, + cl.stats[STAT_ARMOR] <= 25); if (cl.stats[STAT_ITEMS] & IT_ARMOR3) Sbar_DrawPic (0, 0, sb_armor[2]); else if (cl.stats[STAT_ITEMS] & IT_ARMOR2) @@ -758,13 +769,13 @@ void Sbar_DrawNormal (void) else if (cl.stats[STAT_ITEMS] & IT_ARMOR1) Sbar_DrawPic (0, 0, sb_armor[0]); } - + // face Sbar_DrawFace (); - + // health - Sbar_DrawNum (136, 0, cl.stats[STAT_HEALTH], 3 - , cl.stats[STAT_HEALTH] <= 25); + Sbar_DrawNum (136, 0, cl.stats[STAT_HEALTH], 3, + cl.stats[STAT_HEALTH] <= 25); // ammo icon if (cl.stats[STAT_ITEMS] & IT_SHELLS) @@ -775,9 +786,8 @@ void Sbar_DrawNormal (void) Sbar_DrawPic (224, 0, sb_ammo[2]); else if (cl.stats[STAT_ITEMS] & IT_CELLS) Sbar_DrawPic (224, 0, sb_ammo[3]); - - Sbar_DrawNum (248, 0, cl.stats[STAT_AMMO], 3 - , cl.stats[STAT_AMMO] <= 10); + + Sbar_DrawNum (248, 0, cl.stats[STAT_AMMO], 3, cl.stats[STAT_AMMO] <= 10); } /* @@ -785,72 +795,68 @@ void Sbar_DrawNormal (void) Sbar_Draw =============== */ -void Sbar_Draw (void) +void +Sbar_Draw (void) { - qboolean headsup; - char st[512]; + qboolean headsup; + char st[512]; - headsup = !(cl_sbar->int_val || scr_viewsize->int_val<100); + headsup = !(cl_sbar->int_val || scr_viewsize->int_val < 100); if ((sb_updates >= vid.numpages) && !headsup) return; if (scr_con_current == vid.height) - return; // console is full screen + return; // console is full screen scr_copyeverything = 1; -// scr_fullupdate = 0; +// scr_fullupdate = 0; sb_updates++; - + // top line - if (sb_lines > 24) - { + if (sb_lines > 24) { if (!cl.spectator || autocam == CAM_TRACK) Sbar_DrawInventory (); - if (!headsup || vid.width<512) + if (!headsup || vid.width < 512) Sbar_DrawFrags (); - } - + } // main area - if (sb_lines > 0) - { + if (sb_lines > 0) { if (cl.spectator) { if (autocam != CAM_TRACK) { Sbar_DrawPic (0, 0, sb_scorebar); - Sbar_DrawString (160-7*8,4, "SPECTATOR MODE"); - Sbar_DrawString(160-14*8+4, 12, "Press [ATTACK] for AutoCamera"); + Sbar_DrawString (160 - 7 * 8, 4, "SPECTATOR MODE"); + Sbar_DrawString (160 - 14 * 8 + 4, 12, + "Press [ATTACK] for AutoCamera"); } else { if (sb_showscores || cl.stats[STAT_HEALTH] <= 0) Sbar_SoloScoreboard (); else Sbar_DrawNormal (); -// Sbar_DrawString (160-14*8+4,4, "SPECTATOR MODE - TRACK CAMERA"); - snprintf (st, sizeof(st), "Tracking %-.13s, [JUMP] for next", - cl.players[spec_track].name); - Sbar_DrawString(0, -8, st); +// Sbar_DrawString (160-14*8+4,4, "SPECTATOR MODE - TRACK CAMERA"); + snprintf (st, sizeof (st), "Tracking %-.13s, [JUMP] for next", + cl.players[spec_track].name); + Sbar_DrawString (0, -8, st); } } else if (sb_showscores || cl.stats[STAT_HEALTH] <= 0) Sbar_SoloScoreboard (); else Sbar_DrawNormal (); } - // main screen deathmatch rankings // if we're dead show team scores in team games if (cl.stats[STAT_HEALTH] <= 0 && !cl.spectator) - if (atoi(Info_ValueForKey(cl.serverinfo, "teamplay")) > 0 && - !sb_showscores) - Sbar_TeamOverlay(); + if (atoi (Info_ValueForKey (cl.serverinfo, "teamplay")) > 0 && + !sb_showscores) Sbar_TeamOverlay (); else Sbar_DeathmatchOverlay (0); else if (sb_showscores) Sbar_DeathmatchOverlay (0); else if (sb_showteamscores) - Sbar_TeamOverlay(); + Sbar_TeamOverlay (); - if (sb_showscores || sb_showteamscores || - cl.stats[STAT_HEALTH] <= 0) + if (sb_showscores || sb_showteamscores || cl.stats[STAT_HEALTH] <= 0) sb_updates = 0; if (vid.width > 320 && !headsup) Draw_TileClear (320, vid.height - sb_lines, vid.width - 320, sb_lines); @@ -867,27 +873,27 @@ Sbar_IntermissionNumber ================== */ -void Sbar_IntermissionNumber (int x, int y, int num, int digits, int color) +void +Sbar_IntermissionNumber (int x, int y, int num, int digits, int color) { - char str[12]; - char *ptr; - int l, frame; + char str[12]; + char *ptr; + int l, frame; l = Sbar_itoa (num, str); ptr = str; if (l > digits) - ptr += (l-digits); + ptr += (l - digits); if (l < digits) - x += (digits-l)*24; + x += (digits - l) * 24; - while (*ptr) - { + while (*ptr) { if (*ptr == '-') frame = STAT_MINUS; else - frame = *ptr -'0'; + frame = *ptr - '0'; - Draw_Pic (x,y,sb_nums[color][frame]); + Draw_Pic (x, y, sb_nums[color][frame]); x += 24; ptr++; } @@ -901,22 +907,23 @@ team frags added by Zoid ================== */ -void Sbar_TeamOverlay (void) +void +Sbar_TeamOverlay (void) { - qpic_t *pic; - int i, k, l; - int x, y; - char num[12]; - int teamplay; - char team[5]; - team_t *tm; - int plow, phigh, pavg; + qpic_t *pic; + int i, k, l; + int x, y; + char num[12]; + int teamplay; + char team[5]; + team_t *tm; + int plow, phigh, pavg; // request new ping times every two second - teamplay = atoi(Info_ValueForKey(cl.serverinfo, "teamplay")); + teamplay = atoi (Info_ValueForKey (cl.serverinfo, "teamplay")); if (!teamplay) { - Sbar_DeathmatchOverlay(0); + Sbar_DeathmatchOverlay (0); return; } @@ -924,28 +931,28 @@ void Sbar_TeamOverlay (void) scr_fullupdate = 0; pic = Draw_CachePic ("gfx/ranking.lmp"); - Draw_Pic (160-pic->width/2, 0, pic); + Draw_Pic (160 - pic->width / 2, 0, pic); y = 24; x = 36; Draw_String8 (x, y, "low/avg/high team total players"); y += 8; -// Draw_String8 (x, y, "------------ ---- ----- -------"); - Draw_String8 (x, y, "\x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1e\x1e\x1f"); +// Draw_String8 (x, y, "------------ ---- ----- -------"); + Draw_String8 (x, y, + "\x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1e\x1e\x1f"); y += 8; // sort the teams - Sbar_SortTeams(); + Sbar_SortTeams (); // draw the text l = scoreboardlines; - for (i=0 ; i < scoreboardteams && y <= vid.height-10 ; i++) - { + for (i = 0; i < scoreboardteams && y <= vid.height - 10; i++) { k = teamsort[i]; tm = teams + k; - // draw pings + // draw pings plow = tm->plow; if (plow < 0 || plow > 999) plow = 999; @@ -959,32 +966,32 @@ void Sbar_TeamOverlay (void) if (pavg < 0 || pavg > 999) pavg = 999; - snprintf (num, sizeof(num), "%3i/%3i/%3i", plow, pavg, phigh); - Draw_String8 ( x, y, num); + snprintf (num, sizeof (num), "%3i/%3i/%3i", plow, pavg, phigh); + Draw_String8 (x, y, num); - // draw team + // draw team team[4] = 0; strncpy (team, tm->team, 4); Draw_String8 (x + 104, y, team); - // draw total - snprintf (num, sizeof(num), "%5i", tm->frags); + // draw total + snprintf (num, sizeof (num), "%5i", tm->frags); Draw_String8 (x + 104 + 40, y, num); - - // draw players - snprintf (num, sizeof(num), "%5i", tm->players); + + // draw players + snprintf (num, sizeof (num), "%5i", tm->players); Draw_String8 (x + 104 + 88, y, num); - - if (!strncmp(Info_ValueForKey(cl.players[cl.playernum].userinfo, - "team"), tm->team, 16)) { - Draw_Character8 ( x + 104 - 8, y, 16); - Draw_Character8 ( x + 104 + 32, y, 17); + + if (!strncmp (Info_ValueForKey (cl.players[cl.playernum].userinfo, + "team"), tm->team, 16)) { + Draw_Character8 (x + 104 - 8, y, 16); + Draw_Character8 (x + 104 + 32, y, 17); } - + y += 8; } y += 8; - Sbar_DeathmatchOverlay(y); + Sbar_DeathmatchOverlay (y); } /* @@ -994,43 +1001,42 @@ Sbar_DeathmatchOverlay ping time frags name ================== */ -void Sbar_DeathmatchOverlay (int start) +void +Sbar_DeathmatchOverlay (int start) { - qpic_t *pic; - int i, k, l; - int top, bottom; - int x, y, f; - char num[12]; - player_info_t *s; - int total; - int minutes; - int p; - int teamplay; - char team[5]; - int skip = 10; + qpic_t *pic; + int i, k, l; + int top, bottom; + int x, y, f; + char num[12]; + player_info_t *s; + int total; + int minutes; + int p; + int teamplay; + char team[5]; + int skip = 10; if (largegame) skip = 8; // request new ping times every two second - if (realtime - cl.last_ping_request > 2) - { + if (realtime - cl.last_ping_request > 2) { cl.last_ping_request = realtime; MSG_WriteByte (&cls.netchan.message, clc_stringcmd); SZ_Print (&cls.netchan.message, "pings"); } - teamplay = atoi(Info_ValueForKey(cl.serverinfo, "teamplay")); + teamplay = atoi (Info_ValueForKey (cl.serverinfo, "teamplay")); scr_copyeverything = 1; scr_fullupdate = 0; if (!start) { pic = Draw_CachePic ("gfx/ranking.lmp"); - Draw_Pic (160-pic->width/2, 0, pic); + Draw_Pic (160 - pic->width / 2, 0, pic); } - -// scores +// scores Sbar_SortFrags (true); // draw the text @@ -1040,29 +1046,27 @@ void Sbar_DeathmatchOverlay (int start) y = start; else y = 24; - if (teamplay) - { + if (teamplay) { x = 4; // 0 40 64 104 152 192 - Draw_String8 ( x , y, "ping pl time frags team name"); + Draw_String8 (x, y, "ping pl time frags team name"); y += 8; -// Draw_String8 ( x , y, "---- -- ---- ----- ---- ----------------"); - Draw_String8 ( x , y, "\x1d\x1e\x1e\x1f \x1d\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f"); +// Draw_String8 ( x , y, "---- -- ---- ----- ---- ----------------"); + Draw_String8 (x, y, + "\x1d\x1e\x1e\x1f \x1d\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f"); y += 8; - } - else - { + } else { x = 16; // 0 40 64 104 152 - Draw_String8 ( x , y, "ping pl time frags name"); + Draw_String8 (x, y, "ping pl time frags name"); y += 8; -// Draw_String8 ( x , y, "---- -- ---- ----- ----------------"); - Draw_String8 ( x , y, "\x1d\x1e\x1e\x1f \x1d\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f"); +// Draw_String8 ( x , y, "---- -- ---- ----- ----------------"); + Draw_String8 (x, y, + "\x1d\x1e\x1e\x1f \x1d\x1f \x1d\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1f \x1d\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1f"); y += 8; } - for (i=0 ; iname[0]) @@ -1072,83 +1076,78 @@ void Sbar_DeathmatchOverlay (int start) p = s->ping; if (p < 0 || p > 999) p = 999; - snprintf (num, sizeof(num), "%4i", p); - Draw_String8 ( x, y, num); + snprintf (num, sizeof (num), "%4i", p); + Draw_String8 (x, y, num); // draw pl p = s->pl; - snprintf (num, sizeof(num), "%3i", p); + snprintf (num, sizeof (num), "%3i", p); if (p > 25) - Draw_AltString8 ( x+32, y, num); + Draw_AltString8 (x + 32, y, num); else - Draw_String8 ( x+32, y, num); + Draw_String8 (x + 32, y, num); - if (s->spectator) - { - Draw_String8 (x+40, y, "(spectator)"); + if (s->spectator) { + Draw_String8 (x + 40, y, "(spectator)"); // draw name if (teamplay) - Draw_String8 (x+152+40, y, s->name); + Draw_String8 (x + 152 + 40, y, s->name); else - Draw_String8 (x+152, y, s->name); + Draw_String8 (x + 152, y, s->name); y += skip; continue; } - // draw time if (cl.intermission) total = cl.completed_time - s->entertime; else total = realtime - s->entertime; - minutes = (int)total/60; - snprintf (num, sizeof(num), "%4i", minutes); - Draw_String8 ( x+64 , y, num); + minutes = (int) total / 60; + snprintf (num, sizeof (num), "%4i", minutes); + Draw_String8 (x + 64, y, num); // draw background top = s->topcolor; bottom = s->bottomcolor; top = Sbar_ColorForMap (top); bottom = Sbar_ColorForMap (bottom); - + if (largegame) - Draw_Fill ( x+104, y+1, 40, 3, top); + Draw_Fill (x + 104, y + 1, 40, 3, top); else - Draw_Fill ( x+104, y, 40, 4, top); - Draw_Fill ( x+104, y+4, 40, 4, bottom); + Draw_Fill (x + 104, y, 40, 4, top); + Draw_Fill (x + 104, y + 4, 40, 4, bottom); - // draw number + // draw number f = s->frags; - snprintf (num, sizeof(num), "%3i",f); - - Draw_Character8 ( x+112 , y, num[0]); - Draw_Character8 ( x+120 , y, num[1]); - Draw_Character8 ( x+128 , y, num[2]); + snprintf (num, sizeof (num), "%3i", f); - if (k == cl.playernum) - { - Draw_Character8 ( x + 104, y, 16); - Draw_Character8 ( x + 136, y, 17); + Draw_Character8 (x + 112, y, num[0]); + Draw_Character8 (x + 120, y, num[1]); + Draw_Character8 (x + 128, y, num[2]); + + if (k == cl.playernum) { + Draw_Character8 (x + 104, y, 16); + Draw_Character8 (x + 136, y, 17); } - // team - if (teamplay) - { + if (teamplay) { team[4] = 0; - strncpy (team, Info_ValueForKey(s->userinfo, "team"), 4); - Draw_String8 (x+152, y, team); + strncpy (team, Info_ValueForKey (s->userinfo, "team"), 4); + Draw_String8 (x + 152, y, team); } - // draw name if (teamplay) - Draw_String8 (x+152+40, y, s->name); + Draw_String8 (x + 152 + 40, y, s->name); else - Draw_String8 (x+152, y, s->name); - + Draw_String8 (x + 152, y, s->name); + y += skip; } - if (y >= vid.height-10) // we ran over the screen size, squish + if (y >= vid.height - 10) // we ran over the screen size, + // squish largegame = true; } @@ -1161,50 +1160,52 @@ frags team name displayed to right of status bar if there's room ================== */ -void Sbar_MiniDeathmatchOverlay (void) +void +Sbar_MiniDeathmatchOverlay (void) { - int i, k; - int top, bottom; - int x, y, f; - char num[12]; - player_info_t *s; - int teamplay; - char team[5]; - int numlines; - char name[16+1]; - team_t *tm; + int i, k; + int top, bottom; + int x, y, f; + char num[12]; + player_info_t *s; + int teamplay; + char team[5]; + int numlines; + char name[16 + 1]; + team_t *tm; if (vid.width < 512 || !sb_lines) - return; // not enuff room + return; // not enuff room - teamplay = atoi(Info_ValueForKey(cl.serverinfo, "teamplay")); + teamplay = atoi (Info_ValueForKey (cl.serverinfo, "teamplay")); scr_copyeverything = 1; scr_fullupdate = 0; -// scores +// scores Sbar_SortFrags (false); if (vid.width >= 640) - Sbar_SortTeams(); + Sbar_SortTeams (); if (!scoreboardlines) - return; // no one there? + return; // no one there? // draw the text y = vid.height - sb_lines - 1; - numlines = sb_lines/8; + numlines = sb_lines / 8; if (numlines < 3) - return; // not enough room + return; // not enough room // find us - for (i=0 ; i < scoreboardlines; i++) + for (i = 0; i < scoreboardlines; i++) if (fragsort[i] == cl.playernum) break; - if (i == scoreboardlines) // we're not there, we are probably a spectator, just display top + if (i == scoreboardlines) // we're not there, we are probably a + // spectator, just display top i = 0; - else // figure out start - i = i - numlines/2; + else // figure out start + i = i - numlines / 2; if (i > scoreboardlines - numlines) i = scoreboardlines - numlines; @@ -1213,51 +1214,46 @@ void Sbar_MiniDeathmatchOverlay (void) x = 324; - for (/* */ ; i < scoreboardlines && y < vid.height - 8 + 1; i++) - { + for ( /* */ ; i < scoreboardlines && y < vid.height - 8 + 1; i++) { k = fragsort[i]; s = &cl.players[k]; if (!s->name[0]) continue; - // draw ping + // draw ping top = s->topcolor; bottom = s->bottomcolor; top = Sbar_ColorForMap (top); bottom = Sbar_ColorForMap (bottom); - - Draw_Fill ( x, y+1, 40, 3, top); - Draw_Fill ( x, y+4, 40, 4, bottom); - // draw number + Draw_Fill (x, y + 1, 40, 3, top); + Draw_Fill (x, y + 4, 40, 4, bottom); + + // draw number f = s->frags; - snprintf (num, sizeof(num), "%3i",f); - - Draw_Character8 ( x+8 , y, num[0]); - Draw_Character8 ( x+16, y, num[1]); - Draw_Character8 ( x+24, y, num[2]); + snprintf (num, sizeof (num), "%3i", f); - if (k == cl.playernum) - { - Draw_Character8 ( x, y, 16); - Draw_Character8 ( x + 32, y, 17); + Draw_Character8 (x + 8, y, num[0]); + Draw_Character8 (x + 16, y, num[1]); + Draw_Character8 (x + 24, y, num[2]); + + if (k == cl.playernum) { + Draw_Character8 (x, y, 16); + Draw_Character8 (x + 32, y, 17); } - - // team - if (teamplay) - { + // team + if (teamplay) { team[4] = 0; - strncpy (team, Info_ValueForKey(s->userinfo, "team"), 4); - Draw_String8 (x+48, y, team); + strncpy (team, Info_ValueForKey (s->userinfo, "team"), 4); + Draw_String8 (x + 48, y, team); } - - // draw name + // draw name name[16] = 0; - strncpy(name, s->name, 16); + strncpy (name, s->name, 16); if (teamplay) - Draw_String8 (x+48+40, y, name); + Draw_String8 (x + 48 + 40, y, name); else - Draw_String8 (x+48, y, name); + Draw_String8 (x + 48, y, name); y += 8; } @@ -1274,26 +1270,25 @@ void Sbar_MiniDeathmatchOverlay (void) x += 16; y = vid.height - sb_lines; - for (i=0 ; i < scoreboardteams && y <= vid.height; i++) - { + for (i = 0; i < scoreboardteams && y <= vid.height; i++) { k = teamsort[i]; tm = teams + k; - // draw pings + // draw pings team[4] = 0; strncpy (team, tm->team, 4); Draw_String8 (x, y, team); - // draw total - snprintf (num, sizeof(num), "%5i", tm->frags); + // draw total + snprintf (num, sizeof (num), "%5i", tm->frags); Draw_String8 (x + 40, y, num); - - if (!strncmp(Info_ValueForKey(cl.players[cl.playernum].userinfo, - "team"), tm->team, 16)) { - Draw_Character8 ( x - 8, y, 16); - Draw_Character8 ( x + 32, y, 17); + + if (!strncmp (Info_ValueForKey (cl.players[cl.playernum].userinfo, + "team"), tm->team, 16)) { + Draw_Character8 (x - 8, y, 16); + Draw_Character8 (x + 32, y, 17); } - + y += 8; } @@ -1306,13 +1301,14 @@ Sbar_IntermissionOverlay ================== */ -void Sbar_IntermissionOverlay (void) +void +Sbar_IntermissionOverlay (void) { scr_copyeverything = 1; scr_fullupdate = 0; - if (atoi(Info_ValueForKey(cl.serverinfo, "teamplay")) > 0 && !sb_showscores) - Sbar_TeamOverlay (); + if (atoi (Info_ValueForKey (cl.serverinfo, "teamplay")) > 0 + && !sb_showscores) Sbar_TeamOverlay (); else Sbar_DeathmatchOverlay (0); } @@ -1324,14 +1320,13 @@ Sbar_FinaleOverlay ================== */ -void Sbar_FinaleOverlay (void) +void +Sbar_FinaleOverlay (void) { - qpic_t *pic; + qpic_t *pic; scr_copyeverything = 1; pic = Draw_CachePic ("gfx/finale.lmp"); - Draw_Pic ( (vid.width-pic->width)/2, 16, pic); + Draw_Pic ((vid.width - pic->width) / 2, 16, pic); } - - diff --git a/source/screen.c b/source/screen.c index 0e824f3..3754cab 100644 --- a/source/screen.c +++ b/source/screen.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -308,8 +308,8 @@ SCR_CalcRefdef (void) { vrect_t vrect; float size; - int h; - qboolean full = false; + int h; + qboolean full = false; scr_fullupdate = 0; // force a background redraw vid.recalc_refdef = 0; @@ -550,8 +550,8 @@ SCR_DrawFPS (void) } snprintf (st, sizeof (st), "%-3d FPS", lastfps); /* Misty: New trick! (for me) the ? makes this work like a if then else - - IE: if cl_hudswap->int_val is not null, do first case, else (else is - a : here) do second case. Deek taught me this trick */ + IE: if cl_hudswap->int_val is not null, do first case, else (else is a + : here) do second case. Deek taught me this trick */ x = cl_hudswap->int_val ? vid.width - ((strlen (st) * 8) + 8) : 8; y = vid.height - sb_lines - 8; Draw_String8 (x, y, st); @@ -787,14 +787,14 @@ SCR_ScreenShot_f (void) // save the pcx file // D_EnableBackBufferAccess (); // enable direct drawing of console - // to back + // to back // buffer WritePCXfile (pcxname, vid.buffer, vid.width, vid.height, vid.rowbytes, host_basepal, false); D_DisableBackBufferAccess (); // for adapters that can't stay - // mapped in + // mapped in // for linear writes all the time Con_Printf ("Wrote %s\n", pcxname); @@ -932,7 +932,7 @@ SCR_RSShot_f (void) // save the pcx file // D_EnableBackBufferAccess (); // enable direct drawing of console - // to back + // to back // buffer w = (vid.width < RSSHOT_WIDTH) ? vid.width : RSSHOT_WIDTH; @@ -994,7 +994,7 @@ SCR_RSShot_f (void) free (newbuf); D_DisableBackBufferAccess (); // for adapters that can't stay - // mapped in + // mapped in // for linear writes all the time // Con_Printf ("Wrote %s\n", pcxname); @@ -1109,7 +1109,7 @@ SCR_UpdateScreen (void) // do 3D refresh drawing, and then update the screen // D_EnableBackBufferAccess (); // of all overlay stuff if drawing - // directly + // directly if (scr_fullupdate++ < vid.numpages) { // clear the entire screen scr_copyeverything = 1; @@ -1124,7 +1124,7 @@ SCR_UpdateScreen (void) SCR_EraseCenterString (); D_DisableBackBufferAccess (); // for adapters that can't stay - // mapped in + // mapped in // for linear writes all the time VID_LockBuffer (); @@ -1132,7 +1132,7 @@ SCR_UpdateScreen (void) VID_UnlockBuffer (); D_EnableBackBufferAccess (); // of all overlay stuff if drawing - // directly + // directly if (cl.intermission == 1 && key_dest == key_game) { Sbar_IntermissionOverlay (); @@ -1157,7 +1157,7 @@ SCR_UpdateScreen (void) D_DisableBackBufferAccess (); // for adapters that can't stay - // mapped in + // mapped in // for linear writes all the time if (pconupdate) { D_UpdateRects (pconupdate); diff --git a/source/sizebuf.c b/source/sizebuf.c index 6fc4201..6dbcd8d 100644 --- a/source/sizebuf.c +++ b/source/sizebuf.c @@ -40,48 +40,57 @@ #include "sizebuf.h" #include "sys.h" -void SZ_Clear (sizebuf_t *buf) +void +SZ_Clear (sizebuf_t *buf) { buf->cursize = 0; buf->overflowed = false; } -void *SZ_GetSpace (sizebuf_t *buf, int length) +void * +SZ_GetSpace (sizebuf_t *buf, int length) { - void *data; - - if (buf->cursize + length > buf->maxsize) - { + void *data; + + if (buf->cursize + length > buf->maxsize) { if (!buf->allowoverflow) - Sys_Error ("SZ_GetSpace: overflow without allowoverflow set (%d)", buf->maxsize); - + Sys_Error ("SZ_GetSpace: overflow without allowoverflow set (%d)", + buf->maxsize); + if (length > buf->maxsize) Sys_Error ("SZ_GetSpace: %i is > full buffer size", length); - - Sys_Printf ("SZ_GetSpace: overflow\n"); // because Con_Printf may be redirected - SZ_Clear (buf); + + Sys_Printf ("SZ_GetSpace: overflow\n"); // because Con_Printf may be + // redirected + SZ_Clear (buf); buf->overflowed = true; } data = buf->data + buf->cursize; buf->cursize += length; - + return data; } -void SZ_Write (sizebuf_t *buf, void *data, int length) +void +SZ_Write (sizebuf_t *buf, void *data, int length) { - memcpy (SZ_GetSpace(buf,length),data,length); + memcpy (SZ_GetSpace (buf, length), data, length); } -void SZ_Print (sizebuf_t *buf, char *data) +void +SZ_Print (sizebuf_t *buf, char *data) { - int len; - - len = strlen(data)+1; + int len; - if (!buf->cursize || buf->data[buf->cursize-1]) - memcpy ((byte *)SZ_GetSpace(buf, len),data,len); // no trailing 0 + len = strlen (data) + 1; + + if (!buf->cursize || buf->data[buf->cursize - 1]) + memcpy ((byte *) SZ_GetSpace (buf, len), data, len); // no + // trailing 0 else - memcpy ((byte *)SZ_GetSpace(buf, len-1)-1,data,len); // write over trailing 0 + memcpy ((byte *) SZ_GetSpace (buf, len - 1) - 1, data, len); // write + // over + // trailing + // 0 } diff --git a/source/skin.c b/source/skin.c index 62ae9fd..4177026 100644 --- a/source/skin.c +++ b/source/skin.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -43,13 +43,14 @@ #include "skin.h" #include "cl_parse.h" -cvar_t *baseskin; -cvar_t *noskins; +cvar_t *baseskin; +cvar_t *noskins; + +char allskins[128]; -char allskins[128]; #define MAX_CACHED_SKINS 128 -skin_t skins[MAX_CACHED_SKINS]; -int numskins; +skin_t skins[MAX_CACHED_SKINS]; +int numskins; /* ================ @@ -60,16 +61,16 @@ Skin_Find ================ */ -void Skin_Find (player_info_t *sc) +void +Skin_Find (player_info_t *sc) { - skin_t *skin; - int i; - char name[128], *s; + skin_t *skin; + int i; + char name[128], *s; if (allskins[0]) strcpy (name, allskins); - else - { + else { s = Info_ValueForKey (sc->userinfo, "skin"); if (s && s[0]) strcpy (name, s); @@ -82,18 +83,16 @@ void Skin_Find (player_info_t *sc) COM_StripExtension (name, name); - for (i=0 ; iskin = &skins[i]; Skin_Cache (sc->skin); return; } } - if (numskins == MAX_CACHED_SKINS) - { // ran out of spots, so flush everything + if (numskins == MAX_CACHED_SKINS) { // ran out of spots, so flush + // everything Skin_Skins_f (); return; } @@ -102,8 +101,8 @@ void Skin_Find (player_info_t *sc) sc->skin = skin; numskins++; - memset (skin, 0, sizeof(*skin)); - strncpy(skin->name, name, sizeof(skin->name) - 1); + memset (skin, 0, sizeof (*skin)); + strncpy (skin->name, name, sizeof (skin->name) - 1); } @@ -114,21 +113,23 @@ Skin_Cache Returns a pointer to the skin bitmap, or NULL to use the default ========== */ -byte *Skin_Cache (skin_t *skin) +byte * +Skin_Cache (skin_t *skin) { - char name[1024]; - byte *raw; - byte *out, *pix; - pcx_t *pcx; - int x, y; - int dataByte; - int runLength; + char name[1024]; + byte *raw; + byte *out, *pix; + pcx_t *pcx; + int x, y; + int dataByte; + int runLength; if (cls.downloadtype == dl_skin) - return NULL; // use base until downloaded + return NULL; // use base until downloaded - if (noskins->int_val) // JACK: So NOSKINS > 1 will show skins, but - return NULL; // not download new ones. + if (noskins->int_val) // JACK: So NOSKINS > 1 will show + // skins, but + return NULL; // not download new ones. if (skin->failedload) return NULL; @@ -140,24 +141,21 @@ byte *Skin_Cache (skin_t *skin) // // load the pic from disk // - snprintf (name, sizeof(name), "skins/%s.pcx", skin->name); + snprintf (name, sizeof (name), "skins/%s.pcx", skin->name); raw = COM_LoadTempFile (name); - if (!raw) - { + if (!raw) { Con_Printf ("Couldn't load skin %s\n", name); - snprintf (name, sizeof(name), "skins/%s.pcx", baseskin->string); + snprintf (name, sizeof (name), "skins/%s.pcx", baseskin->string); raw = COM_LoadTempFile (name); - if (!raw) - { + if (!raw) { skin->failedload = true; return NULL; } } - // // parse the PCX file // - pcx = (pcx_t *)raw; + pcx = (pcx_t *) raw; raw = &pcx->data; pcx->xmax = LittleShort (pcx->xmax); @@ -172,65 +170,59 @@ byte *Skin_Cache (skin_t *skin) if (pcx->manufacturer != 0x0a || pcx->version != 5 || pcx->encoding != 1 - || pcx->bits_per_pixel != 8 - || pcx->xmax >= 320 - || pcx->ymax >= 200) - { + || pcx->bits_per_pixel != 8 || pcx->xmax >= 320 || pcx->ymax >= 200) { skin->failedload = true; Con_Printf ("Bad skin %s\n", name); return NULL; } - - out = Cache_Alloc (&skin->cache, 320*200, skin->name); + + out = Cache_Alloc (&skin->cache, 320 * 200, skin->name); if (!out) Sys_Error ("Skin_Cache: couldn't allocate"); pix = out; - memset (out, 0, 320*200); + memset (out, 0, 320 * 200); - for (y=0 ; yymax ; y++, pix += 320) - { - for (x=0 ; x<=pcx->xmax ; ) - { - if (raw - (byte*)pcx > com_filesize) - { + for (y = 0; y < pcx->ymax; y++, pix += 320) { + for (x = 0; x <= pcx->xmax;) { + if (raw - (byte *) pcx > com_filesize) { Cache_Free (&skin->cache); skin->failedload = true; - Con_Printf ("Skin %s was malformed. You should delete it.\n", name); + Con_Printf ("Skin %s was malformed. You should delete it.\n", + name); return NULL; } dataByte = *raw++; - if((dataByte & 0xC0) == 0xC0) - { + if ((dataByte & 0xC0) == 0xC0) { runLength = dataByte & 0x3F; - if (raw - (byte*)pcx > com_filesize) - { + if (raw - (byte *) pcx > com_filesize) { Cache_Free (&skin->cache); skin->failedload = true; - Con_Printf ("Skin %s was malformed. You should delete it.\n", name); + Con_Printf + ("Skin %s was malformed. You should delete it.\n", + name); return NULL; } dataByte = *raw++; - } - else + } else runLength = 1; // skin sanity check if (runLength + x > pcx->xmax + 2) { Cache_Free (&skin->cache); skin->failedload = true; - Con_Printf ("Skin %s was malformed. You should delete it.\n", name); + Con_Printf ("Skin %s was malformed. You should delete it.\n", + name); return NULL; } - while(runLength-- > 0) + while (runLength-- > 0) pix[x++] = dataByte; } } - if ( raw - (byte *)pcx > com_filesize) - { + if (raw - (byte *) pcx > com_filesize) { Cache_Free (&skin->cache); skin->failedload = true; Con_Printf ("Skin %s was malformed. You should delete it.\n", name); @@ -248,34 +240,31 @@ byte *Skin_Cache (skin_t *skin) Skin_NextDownload ================= */ -void Skin_NextDownload (void) +void +Skin_NextDownload (void) { - player_info_t *sc; - int i; + player_info_t *sc; + int i; if (cls.downloadnumber == 0) Con_Printf ("Checking skins...\n"); cls.downloadtype = dl_skin; - for ( - ; cls.downloadnumber != MAX_CLIENTS - ; cls.downloadnumber++) - { + for (; cls.downloadnumber != MAX_CLIENTS; cls.downloadnumber++) { sc = &cl.players[cls.downloadnumber]; if (!sc->name[0]) continue; Skin_Find (sc); if (noskins->int_val) continue; - if (!CL_CheckOrDownloadFile(va("skins/%s.pcx", sc->skin->name))) - return; // started a download + if (!CL_CheckOrDownloadFile (va ("skins/%s.pcx", sc->skin->name))) + return; // started a download } cls.downloadtype = dl_none; // now load them in for real - for (i=0 ; iname[0]) continue; @@ -283,12 +272,10 @@ void Skin_NextDownload (void) sc->skin = NULL; } - if (cls.state != ca_active) - { // get next signon phase + if (cls.state != ca_active) { // get next signon phase MSG_WriteByte (&cls.netchan.message, clc_stringcmd); - MSG_WriteString (&cls.netchan.message, - va("begin %i", cl.servercount)); - Cache_Report (); // print remaining memory + MSG_WriteString (&cls.netchan.message, va ("begin %i", cl.servercount)); + Cache_Report (); // print remaining memory } } @@ -300,12 +287,12 @@ Skin_Skins_f Refind all skins, downloading if needed. ========== */ -void Skin_Skins_f (void) +void +Skin_Skins_f (void) { - int i; + int i; - for (i=0 ; i +# include "config.h" #endif #include @@ -63,7 +63,7 @@ # define MAP_FAILED ((void*)-1) #endif -static int snd_inited; +static int snd_inited; static snd_pcm_t *pcm_handle; static struct snd_pcm_channel_info cinfo; @@ -71,38 +71,39 @@ static struct snd_pcm_channel_params params; static struct snd_pcm_channel_setup setup; static snd_pcm_mmap_control_t *mmap_control = NULL; static char *mmap_data = NULL; -static int card=-1,dev=-1; +static int card = -1, dev = -1; -int check_card(int card) +int +check_card (int card) { - snd_ctl_t *handle; + snd_ctl_t *handle; snd_ctl_hw_info_t info; - int rc; + int rc; - if ((rc = snd_ctl_open(&handle, card)) < 0) { - Con_Printf("Error: control open (%i): %s\n", card, snd_strerror(rc)); + if ((rc = snd_ctl_open (&handle, card)) < 0) { + Con_Printf ("Error: control open (%i): %s\n", card, snd_strerror (rc)); return rc; } - if ((rc = snd_ctl_hw_info(handle, &info)) < 0) { - Con_Printf("Error: control hardware info (%i): %s\n", card, - snd_strerror(rc)); - snd_ctl_close(handle); + if ((rc = snd_ctl_hw_info (handle, &info)) < 0) { + Con_Printf ("Error: control hardware info (%i): %s\n", card, + snd_strerror (rc)); + snd_ctl_close (handle); return rc; } - snd_ctl_close(handle); - if (dev==-1) { + snd_ctl_close (handle); + if (dev == -1) { for (dev = 0; dev < info.pcmdevs; dev++) { - if ((rc=snd_pcm_open(&pcm_handle,card,dev, - SND_PCM_OPEN_PLAYBACK - | SND_PCM_OPEN_NONBLOCK))==0) { + if ((rc = snd_pcm_open (&pcm_handle, card, dev, + SND_PCM_OPEN_PLAYBACK + | SND_PCM_OPEN_NONBLOCK)) == 0) { return 0; } } } else { - if (dev>=0 && dev = 0 && dev < info.pcmdevs) { + if ((rc = snd_pcm_open (&pcm_handle, card, dev, + SND_PCM_OPEN_PLAYBACK + | SND_PCM_OPEN_NONBLOCK)) == 0) { return 0; } } @@ -110,192 +111,208 @@ int check_card(int card) return 1; } -qboolean SNDDMA_Init(void) +qboolean +SNDDMA_Init (void) { - int rc=0,i; - char *err_msg=""; - int rate=-1,format=-1,bps,stereo=-1,frag_size; + int rc = 0, i; + char *err_msg = ""; + int rate = -1, format = -1, bps, stereo = -1, frag_size; unsigned int mask; - mask = snd_cards_mask(); + mask = snd_cards_mask (); if (!mask) { - Con_Printf("No sound cards detected\n"); + Con_Printf ("No sound cards detected\n"); return 0; } - if ((i=COM_CheckParm("-sndcard"))!=0) { - card=atoi(com_argv[i+1]); + if ((i = COM_CheckParm ("-sndcard")) != 0) { + card = atoi (com_argv[i + 1]); } - if ((i=COM_CheckParm("-snddev"))!=0) { - dev=atoi(com_argv[i+1]); + if ((i = COM_CheckParm ("-snddev")) != 0) { + dev = atoi (com_argv[i + 1]); } - if ((i=COM_CheckParm("-sndbits")) != 0) { - i = atoi(com_argv[i+1]); - if (i==16) { + if ((i = COM_CheckParm ("-sndbits")) != 0) { + i = atoi (com_argv[i + 1]); + if (i == 16) { format = SND_PCM_SFMT_S16_LE; - } else if (i==8) { + } else if (i == 8) { format = SND_PCM_SFMT_U8; } else { - Con_Printf("Error: invalid sample bits: %d\n", i); + Con_Printf ("Error: invalid sample bits: %d\n", i); return 0; } } - if ((i=COM_CheckParm("-sndspeed")) != 0) { - rate = atoi(com_argv[i+1]); - if (rate!=44100 && rate!=22050 && rate!=11025) { - Con_Printf("Error: invalid sample rate: %d\n", rate); + if ((i = COM_CheckParm ("-sndspeed")) != 0) { + rate = atoi (com_argv[i + 1]); + if (rate != 44100 && rate != 22050 && rate != 11025) { + Con_Printf ("Error: invalid sample rate: %d\n", rate); return 0; } } - if ((i=COM_CheckParm("-sndmono")) != 0) { - stereo=0; + if ((i = COM_CheckParm ("-sndmono")) != 0) { + stereo = 0; } - if (card==-1) { - for (card=0; card=2) { - stereo=1; + if (stereo && cinfo.max_voices >= 2) { + stereo = 1; } else { - stereo=0; - frag_size/=2; + stereo = 0; + frag_size /= 2; } -// err_msg="audio flush"; -// if ((rc=snd_pcm_channel_flush(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) -// goto error; - err_msg="audio munmap"; - if ((rc=snd_pcm_munmap(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) +// err_msg="audio flush"; +// if ((rc=snd_pcm_channel_flush(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) +// goto error; + err_msg = "audio munmap"; + if ((rc = snd_pcm_munmap (pcm_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0) goto error; - memset(¶ms, 0, sizeof(params)); + memset (¶ms, 0, sizeof (params)); params.channel = SND_PCM_CHANNEL_PLAYBACK; params.mode = SND_PCM_MODE_BLOCK; - params.format.interleave=1; - params.format.format=format; - params.format.rate=rate; - params.format.voices=stereo+1; + params.format.interleave = 1; + params.format.format = format; + params.format.rate = rate; + params.format.voices = stereo + 1; params.start_mode = SND_PCM_START_GO; params.stop_mode = SND_PCM_STOP_ROLLOVER; - params.buf.block.frag_size=frag_size; - params.buf.block.frags_min=1; - params.buf.block.frags_max=-1; -// err_msg="audio flush"; -// if ((rc=snd_pcm_channel_flush(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) -// goto error; - err_msg="audio params"; - if ((rc=snd_pcm_channel_params(pcm_handle, ¶ms))<0) + params.buf.block.frag_size = frag_size; + params.buf.block.frags_min = 1; + params.buf.block.frags_max = -1; +// err_msg="audio flush"; +// if ((rc=snd_pcm_channel_flush(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) +// goto error; + err_msg = "audio params"; + if ((rc = snd_pcm_channel_params (pcm_handle, ¶ms)) < 0) goto error; - err_msg="audio mmap"; - if ((rc=snd_pcm_mmap(pcm_handle, SND_PCM_CHANNEL_PLAYBACK, &mmap_control, (void **)&mmap_data))<0) - goto error; - err_msg="audio prepare"; - if ((rc=snd_pcm_plugin_prepare(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) + err_msg = "audio mmap"; + if ( + (rc = + snd_pcm_mmap (pcm_handle, SND_PCM_CHANNEL_PLAYBACK, &mmap_control, + (void **) &mmap_data)) < 0) goto error; + err_msg = "audio prepare"; + if ((rc = snd_pcm_plugin_prepare (pcm_handle, SND_PCM_CHANNEL_PLAYBACK)) < + 0) goto error; - memset(&setup, 0, sizeof(setup)); + memset (&setup, 0, sizeof (setup)); setup.mode = SND_PCM_MODE_BLOCK; setup.channel = SND_PCM_CHANNEL_PLAYBACK; - err_msg="audio setup"; - if ((rc=snd_pcm_channel_setup(pcm_handle, &setup))<0) + err_msg = "audio setup"; + if ((rc = snd_pcm_channel_setup (pcm_handle, &setup)) < 0) goto error; - shm=&sn; - memset((dma_t*)shm,0,sizeof(*shm)); - shm->splitbuffer = 0; - shm->channels=setup.format.voices; - shm->submission_chunk=128; // don't mix less than this # - shm->samplepos=0; // in mono samples - shm->samplebits=setup.format.format==SND_PCM_SFMT_S16_LE?16:8; - shm->samples=setup.buf.block.frags*setup.buf.block.frag_size/(shm->samplebits/8); // mono samples in buffer - shm->speed=setup.format.rate; - shm->buffer=(unsigned char*)mmap_data; - Con_Printf("%5d stereo\n", shm->channels - 1); - Con_Printf("%5d samples\n", shm->samples); - Con_Printf("%5d samplepos\n", shm->samplepos); - Con_Printf("%5d samplebits\n", shm->samplebits); - Con_Printf("%5d submission_chunk\n", shm->submission_chunk); - Con_Printf("%5d speed\n", shm->speed); - Con_Printf("0x%x dma buffer\n", (int)shm->buffer); - Con_Printf("%5d total_channels\n", total_channels); + shm = &sn; + memset ((dma_t *) shm, 0, sizeof (*shm)); + shm->splitbuffer = 0; + shm->channels = setup.format.voices; + shm->submission_chunk = 128; // don't mix less than this # + shm->samplepos = 0; // in mono samples + shm->samplebits = setup.format.format == SND_PCM_SFMT_S16_LE ? 16 : 8; + shm->samples = + setup.buf.block.frags * setup.buf.block.frag_size / (shm->samplebits / 8); // mono + // samples + // in + // buffer + shm->speed = setup.format.rate; + shm->buffer = (unsigned char *) mmap_data; + Con_Printf ("%5d stereo\n", shm->channels - 1); + Con_Printf ("%5d samples\n", shm->samples); + Con_Printf ("%5d samplepos\n", shm->samplepos); + Con_Printf ("%5d samplebits\n", shm->samplebits); + Con_Printf ("%5d submission_chunk\n", shm->submission_chunk); + Con_Printf ("%5d speed\n", shm->speed); + Con_Printf ("0x%x dma buffer\n", (int) shm->buffer); + Con_Printf ("%5d total_channels\n", total_channels); - snd_inited=1; + snd_inited = 1; return 1; - error: - Con_Printf("Error: %s: %s\n", err_msg, snd_strerror(rc)); - error_2: - snd_pcm_close(pcm_handle); + error: + Con_Printf ("Error: %s: %s\n", err_msg, snd_strerror (rc)); + error_2: + snd_pcm_close (pcm_handle); return 0; } -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { - if (!snd_inited) return 0; - shm->samplepos=(mmap_control->status.frag_io+1)*setup.buf.block.frag_size/(shm->samplebits/8); + if (!snd_inited) + return 0; + shm->samplepos = + (mmap_control->status.frag_io + + 1) * setup.buf.block.frag_size / (shm->samplebits / 8); return shm->samplepos; } -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { - if (snd_inited) - { - snd_pcm_close(pcm_handle); + if (snd_inited) { + snd_pcm_close (pcm_handle); snd_inited = 0; } } @@ -307,37 +324,42 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { - int count=paintedtime-soundtime; - int i,s,e; - int rc; + int count = paintedtime - soundtime; + int i, s, e; + int rc; - count+=setup.buf.block.frag_size-1; - count/=setup.buf.block.frag_size; - s=soundtime/setup.buf.block.frag_size; - e=s+count; - for (i=s; ifragments[i % setup.buf.block.frags].data=1; + count += setup.buf.block.frag_size - 1; + count /= setup.buf.block.frag_size; + s = soundtime / setup.buf.block.frag_size; + e = s + count; + for (i = s; i < e; i++) + mmap_control->fragments[i % setup.buf.block.frags].data = 1; switch (mmap_control->status.status) { - case SND_PCM_STATUS_PREPARED: - if ((rc=snd_pcm_channel_go(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) { - fprintf(stderr, "unable to start playback. %s\n", - snd_strerror(rc)); - exit(1); - } - break; - case SND_PCM_STATUS_RUNNING: - break; - case SND_PCM_STATUS_UNDERRUN: - if ((rc=snd_pcm_plugin_prepare(pcm_handle, SND_PCM_CHANNEL_PLAYBACK))<0) { - fprintf(stderr, "underrun: playback channel prepare error. %s\n", - snd_strerror(rc)); - exit(1); - } - break; - default: - break; + case SND_PCM_STATUS_PREPARED: + if ((rc = snd_pcm_channel_go (pcm_handle, SND_PCM_CHANNEL_PLAYBACK)) + < 0) { + fprintf (stderr, "unable to start playback. %s\n", + snd_strerror (rc)); + exit (1); + } + break; + case SND_PCM_STATUS_RUNNING: + break; + case SND_PCM_STATUS_UNDERRUN: + if ( + (rc = + snd_pcm_plugin_prepare (pcm_handle, + SND_PCM_CHANNEL_PLAYBACK)) < 0) { + fprintf (stderr, + "underrun: playback channel prepare error. %s\n", + snd_strerror (rc)); + exit (1); + } + break; + default: + break; } } - diff --git a/source/snd_alsa_0_6.c b/source/snd_alsa_0_6.c index 3facf71..b5b2d02 100644 --- a/source/snd_alsa_0_6.c +++ b/source/snd_alsa_0_6.c @@ -41,44 +41,45 @@ #include "sound.h" #include "va.h" -static int snd_inited; +static int snd_inited; static snd_pcm_t *pcm_handle; static snd_pcm_hw_info_t hwinfo; static snd_pcm_hw_params_t hwparams; static snd_pcm_channel_area_t mmap_running_areas[2]; -static int card=-1,dev=-1; +static int card = -1, dev = -1; -int check_card(int card) +int +check_card (int card) { - snd_ctl_t *handle; + snd_ctl_t *handle; snd_ctl_hw_info_t info; - int rc; + int rc; - if ((rc = snd_ctl_open(&handle, va("hw:%d", card))) < 0) { - Con_Printf("Error: control open (%i): %s\n", card, snd_strerror(rc)); + if ((rc = snd_ctl_open (&handle, va ("hw:%d", card))) < 0) { + Con_Printf ("Error: control open (%i): %s\n", card, snd_strerror (rc)); return rc; } - if ((rc = snd_ctl_hw_info(handle, &info)) < 0) { - Con_Printf("Error: control hardware info (%i): %s\n", card, - snd_strerror(rc)); - snd_ctl_close(handle); + if ((rc = snd_ctl_hw_info (handle, &info)) < 0) { + Con_Printf ("Error: control hardware info (%i): %s\n", card, + snd_strerror (rc)); + snd_ctl_close (handle); return rc; } - snd_ctl_close(handle); - if (dev==-1) { + snd_ctl_close (handle); + if (dev == -1) { for (dev = 0; dev < info.pcmdevs; dev++) { - if ((rc=snd_pcm_open (&pcm_handle, va ("hw:%d,%d", card, dev), - SND_PCM_STREAM_PLAYBACK, - SND_PCM_NONBLOCK))==0) { + if ((rc = snd_pcm_open (&pcm_handle, va ("hw:%d,%d", card, dev), + SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK)) == 0) { return 0; } } } else { - if (dev>=0 && dev = 0 && dev < info.pcmdevs) { + if ((rc = snd_pcm_open (&pcm_handle, va ("hw:%d,%d", card, dev), + SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK)) == 0) { return 0; } } @@ -86,172 +87,179 @@ int check_card(int card) return 1; } -qboolean SNDDMA_Init(void) +qboolean +SNDDMA_Init (void) { - int rc=0,i; - char *err_msg=""; - int rate=-1,format=-1,stereo=-1,frag_size; + int rc = 0, i; + char *err_msg = ""; + int rate = -1, format = -1, stereo = -1, frag_size; unsigned int mask; - mask = snd_cards_mask(); + mask = snd_cards_mask (); if (!mask) { - Con_Printf("No sound cards detected\n"); + Con_Printf ("No sound cards detected\n"); return 0; } - if ((i=COM_CheckParm("-sndcard"))!=0) { - card=atoi(com_argv[i+1]); + if ((i = COM_CheckParm ("-sndcard")) != 0) { + card = atoi (com_argv[i + 1]); } - if ((i=COM_CheckParm("-snddev"))!=0) { - dev=atoi(com_argv[i+1]); + if ((i = COM_CheckParm ("-snddev")) != 0) { + dev = atoi (com_argv[i + 1]); } - if ((i=COM_CheckParm("-sndbits")) != 0) { - i = atoi(com_argv[i+1]); - if (i==16) { + if ((i = COM_CheckParm ("-sndbits")) != 0) { + i = atoi (com_argv[i + 1]); + if (i == 16) { format = SND_PCM_FMTBIT_S16_LE; - } else if (i==8) { + } else if (i == 8) { format = SND_PCM_FMTBIT_U8; } else { - Con_Printf("Error: invalid sample bits: %d\n", i); + Con_Printf ("Error: invalid sample bits: %d\n", i); return 0; } } - if ((i=COM_CheckParm("-sndspeed")) != 0) { - rate = atoi(com_argv[i+1]); - if (rate!=44100 && rate!=22050 && rate!=11025) { - Con_Printf("Error: invalid sample rate: %d\n", rate); + if ((i = COM_CheckParm ("-sndspeed")) != 0) { + rate = atoi (com_argv[i + 1]); + if (rate != 44100 && rate != 22050 && rate != 11025) { + Con_Printf ("Error: invalid sample rate: %d\n", rate); return 0; } } - if ((i=COM_CheckParm("-sndmono")) != 0) { - stereo=0; + if ((i = COM_CheckParm ("-sndmono")) != 0) { + stereo = 0; } - if (card==-1) { - for (card=0; card=2) { - stereo=1; + // XXX can't support non-interleaved stereo + if (stereo && (hwinfo.access_mask & SND_PCM_INFO_INTERLEAVED) + && hwinfo.channels_max >= 2) { + stereo = 1; } else { - stereo=0; + stereo = 0; } - memset(&hwparams, 0, sizeof(hwparams)); - //XXX can't support non-interleaved stereo + memset (&hwparams, 0, sizeof (hwparams)); + // XXX can't support non-interleaved stereo hwparams.access = stereo ? SND_PCM_ACCESS_MMAP_INTERLEAVED - : SND_PCM_ACCESS_MMAP_NONINTERLEAVED; - hwparams.format=format; - hwparams.rate=rate; - hwparams.channels=stereo+1; + : SND_PCM_ACCESS_MMAP_NONINTERLEAVED; + hwparams.format = format; + hwparams.rate = rate; + hwparams.channels = stereo + 1; hwparams.fragment_size = frag_size; hwparams.fragments = (1 << 17) / frag_size; while (1) { - err_msg="audio params"; - if ((rc=snd_pcm_hw_params(pcm_handle, &hwparams))<0) + err_msg = "audio params"; + if ((rc = snd_pcm_hw_params (pcm_handle, &hwparams)) < 0) goto error; - break;//XXX + break; // XXX } - err_msg="audio prepare"; - if ((rc=snd_pcm_prepare(pcm_handle))<0) + err_msg = "audio prepare"; + if ((rc = snd_pcm_prepare (pcm_handle)) < 0) goto error; - shm=&sn; - memset((dma_t*)shm,0,sizeof(*shm)); - shm->splitbuffer = 0; - shm->channels=hwparams.channels; - shm->submission_chunk=frag_size; // don't mix less than this # - shm->samplepos=0; // in mono samples - shm->samplebits=hwparams.format==SND_PCM_FMTBIT_S16_LE?16:8; - shm->samples=hwparams.fragments*shm->channels; // mono samples in buffer - shm->speed=hwparams.rate; - shm->buffer=(unsigned char*)mmap_running_areas->addr; - Con_Printf("%5d stereo\n", shm->channels - 1); - Con_Printf("%5d samples\n", shm->samples); - Con_Printf("%5d samplepos\n", shm->samplepos); - Con_Printf("%5d samplebits\n", shm->samplebits); - Con_Printf("%5d submission_chunk\n", shm->submission_chunk); - Con_Printf("%5d speed\n", shm->speed); - Con_Printf("0x%x dma buffer\n", (int)shm->buffer); - Con_Printf("%5d total_channels\n", total_channels); + shm = &sn; + memset ((dma_t *) shm, 0, sizeof (*shm)); + shm->splitbuffer = 0; + shm->channels = hwparams.channels; + shm->submission_chunk = frag_size; // don't mix less than this # + shm->samplepos = 0; // in mono samples + shm->samplebits = hwparams.format == SND_PCM_FMTBIT_S16_LE ? 16 : 8; + shm->samples = hwparams.fragments * shm->channels; // mono samples in + // buffer + shm->speed = hwparams.rate; + shm->buffer = (unsigned char *) mmap_running_areas->addr; + Con_Printf ("%5d stereo\n", shm->channels - 1); + Con_Printf ("%5d samples\n", shm->samples); + Con_Printf ("%5d samplepos\n", shm->samplepos); + Con_Printf ("%5d samplebits\n", shm->samplebits); + Con_Printf ("%5d submission_chunk\n", shm->submission_chunk); + Con_Printf ("%5d speed\n", shm->speed); + Con_Printf ("0x%x dma buffer\n", (int) shm->buffer); + Con_Printf ("%5d total_channels\n", total_channels); - snd_inited=1; + snd_inited = 1; return 1; - error: - Con_Printf("Error: %s: %s\n", err_msg, snd_strerror(rc)); - //XXXerror_2: - snd_pcm_close(pcm_handle); + error: + Con_Printf ("Error: %s: %s\n", err_msg, snd_strerror (rc)); + // XXXerror_2: + snd_pcm_close (pcm_handle); return 0; } static inline int -get_hw_ptr() +get_hw_ptr () { - size_t app_ptr; - ssize_t delay; - int hw_ptr; + size_t app_ptr; + ssize_t delay; + int hw_ptr; if (snd_pcm_state (pcm_handle) != SND_PCM_STATE_RUNNING) return 0; @@ -261,23 +269,25 @@ get_hw_ptr() return hw_ptr; } -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { - int hw_ptr; + int hw_ptr; - if (!snd_inited) return 0; + if (!snd_inited) + return 0; - hw_ptr = get_hw_ptr(); + hw_ptr = get_hw_ptr (); hw_ptr *= shm->channels; shm->samplepos = hw_ptr; return shm->samplepos; } -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { - if (snd_inited) - { - snd_pcm_close(pcm_handle); + if (snd_inited) { + snd_pcm_close (pcm_handle); snd_inited = 0; } } @@ -289,44 +299,44 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { - int count = paintedtime - soundtime; - int avail; - int missed; - int state; - int hw_ptr; - int offset; + int count = paintedtime - soundtime; + int avail; + int missed; + int state; + int hw_ptr; + int offset; state = snd_pcm_state (pcm_handle); switch (state) { - case SND_PCM_STATE_PREPARED: - snd_pcm_mmap_forward (pcm_handle, count); - snd_pcm_start (pcm_handle); - break; - case SND_PCM_STATE_RUNNING: - hw_ptr = get_hw_ptr(); - missed = hw_ptr - shm->samplepos / shm->channels; - count -= missed; - offset = snd_pcm_mmap_offset (pcm_handle); - if (offset > hw_ptr) - count -= (offset - hw_ptr); - else - count -= (hwparams.fragments - hw_ptr + offset); - if (count < 0) { - snd_pcm_rewind (pcm_handle, -count); - } else if (count > 0) { - avail = snd_pcm_avail_update(pcm_handle); - if (avail > 0 && count > avail) { - snd_pcm_mmap_forward (pcm_handle, avail); - count -= avail; - } + case SND_PCM_STATE_PREPARED: snd_pcm_mmap_forward (pcm_handle, count); - } - break; - default: - break; + snd_pcm_start (pcm_handle); + break; + case SND_PCM_STATE_RUNNING: + hw_ptr = get_hw_ptr (); + missed = hw_ptr - shm->samplepos / shm->channels; + count -= missed; + offset = snd_pcm_mmap_offset (pcm_handle); + if (offset > hw_ptr) + count -= (offset - hw_ptr); + else + count -= (hwparams.fragments - hw_ptr + offset); + if (count < 0) { + snd_pcm_rewind (pcm_handle, -count); + } else if (count > 0) { + avail = snd_pcm_avail_update (pcm_handle); + if (avail > 0 && count > avail) { + snd_pcm_mmap_forward (pcm_handle, avail); + count -= avail; + } + snd_pcm_mmap_forward (pcm_handle, count); + } + break; + default: + break; } } - diff --git a/source/snd_disk.c b/source/snd_disk.c index 7112bba..b32a660 100644 --- a/source/snd_disk.c +++ b/source/snd_disk.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -44,45 +44,48 @@ #include "qargs.h" #include "console.h" -static int snd_inited; -QFile *snd_file; +static int snd_inited; +QFile *snd_file; -qboolean SNDDMA_Init(void) +qboolean +SNDDMA_Init (void) { - shm=&sn; - memset((dma_t*)shm,0,sizeof(*shm)); - shm->splitbuffer = 0; - shm->channels=2; - shm->submission_chunk=1; // don't mix less than this # - shm->samplepos=0; // in mono samples - shm->samplebits=16; - shm->samples=16384; // mono samples in buffer - shm->speed=44100; - shm->buffer=malloc (shm->samples * shm->channels * shm->samplebits / 8); + shm = &sn; + memset ((dma_t *) shm, 0, sizeof (*shm)); + shm->splitbuffer = 0; + shm->channels = 2; + shm->submission_chunk = 1; // don't mix less than this # + shm->samplepos = 0; // in mono samples + shm->samplebits = 16; + shm->samples = 16384; // mono samples in buffer + shm->speed = 44100; + shm->buffer = malloc (shm->samples * shm->channels * shm->samplebits / 8); - Con_Printf("%5d stereo\n", shm->channels - 1); - Con_Printf("%5d samples\n", shm->samples); - Con_Printf("%5d samplepos\n", shm->samplepos); - Con_Printf("%5d samplebits\n", shm->samplebits); - Con_Printf("%5d submission_chunk\n", shm->submission_chunk); - Con_Printf("%5d speed\n", shm->speed); - Con_Printf("0x%x dma buffer\n", (int)shm->buffer); - Con_Printf("%5d total_channels\n", total_channels); + Con_Printf ("%5d stereo\n", shm->channels - 1); + Con_Printf ("%5d samples\n", shm->samples); + Con_Printf ("%5d samplepos\n", shm->samplepos); + Con_Printf ("%5d samplebits\n", shm->samplebits); + Con_Printf ("%5d submission_chunk\n", shm->submission_chunk); + Con_Printf ("%5d speed\n", shm->speed); + Con_Printf ("0x%x dma buffer\n", (int) shm->buffer); + Con_Printf ("%5d total_channels\n", total_channels); if (!(snd_file = Qopen ("qf.raw", "wb"))) return 0; - snd_inited=1; + snd_inited = 1; return 1; } -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { shm->samplepos = 0; return shm->samplepos; } -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { if (snd_inited) { Qclose (snd_file); @@ -99,8 +102,10 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { - int count = (paintedtime - soundtime) * shm->samplebits / 8; + int count = (paintedtime - soundtime) * shm->samplebits / 8; + Qwrite (snd_file, shm->buffer, count); } diff --git a/source/snd_dma.c b/source/snd_dma.c index c63bab5..ae3fe2e 100644 --- a/source/snd_dma.c +++ b/source/snd_dma.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -51,12 +51,12 @@ #include #include -void S_Play(void); -void S_PlayVol(void); -void S_SoundList(void); -void S_Update_(); -void S_StopAllSounds(qboolean clear); -void S_StopAllSoundsC(void); +void S_Play (void); +void S_PlayVol (void); +void S_SoundList (void); +void S_Update_ (); +void S_StopAllSounds (qboolean clear); +void S_StopAllSoundsC (void); // QuakeWorld hack... #define viewentity playernum+1 @@ -66,49 +66,49 @@ void S_StopAllSoundsC(void); // ======================================================================= channel_t channels[MAX_CHANNELS]; -int total_channels; +int total_channels; -int snd_blocked = 0; -static qboolean snd_ambient = 1; -qboolean snd_initialized = false; +int snd_blocked = 0; +static qboolean snd_ambient = 1; +qboolean snd_initialized = false; // pointer should go away -volatile dma_t *shm = 0; +volatile dma_t *shm = 0; volatile dma_t sn; -vec3_t listener_origin; -vec3_t listener_forward; -vec3_t listener_right; -vec3_t listener_up; -vec_t sound_nominal_clip_dist=1000.0; +vec3_t listener_origin; +vec3_t listener_forward; +vec3_t listener_right; +vec3_t listener_up; +vec_t sound_nominal_clip_dist = 1000.0; -int soundtime; // sample PAIRS -int paintedtime; // sample PAIRS +int soundtime; // sample PAIRS +int paintedtime; // sample PAIRS #define MAX_SFX 512 -sfx_t *known_sfx; // hunk allocated [MAX_SFX] -int num_sfx; +sfx_t *known_sfx; // hunk allocated [MAX_SFX] +int num_sfx; -sfx_t *ambient_sfx[NUM_AMBIENTS]; +sfx_t *ambient_sfx[NUM_AMBIENTS]; -int desired_speed = 11025; -int desired_bits = 16; +int desired_speed = 11025; +int desired_bits = 16; -int sound_started=0; +int sound_started = 0; -cvar_t *bgmvolume; -cvar_t *volume; +cvar_t *bgmvolume; +cvar_t *volume; -cvar_t *nosound; -cvar_t *precache; -cvar_t *loadas8bit; -cvar_t *ambient_level; -cvar_t *ambient_fade; -cvar_t *snd_noextraupdate; -cvar_t *snd_show; -cvar_t *snd_interp; -cvar_t *_snd_mixahead; +cvar_t *nosound; +cvar_t *precache; +cvar_t *loadas8bit; +cvar_t *ambient_level; +cvar_t *ambient_fade; +cvar_t *snd_noextraupdate; +cvar_t *snd_show; +cvar_t *snd_interp; +cvar_t *_snd_mixahead; // ==================================================================== @@ -122,38 +122,40 @@ cvar_t *_snd_mixahead; // number of times S_Update() is called per second. // -qboolean fakedma = false; -int fakedma_updates = 15; +qboolean fakedma = false; +int fakedma_updates = 15; -void S_AmbientOff (void) +void +S_AmbientOff (void) { snd_ambient = false; } -void S_AmbientOn (void) +void +S_AmbientOn (void) { snd_ambient = true; } -void S_SoundInfo_f(void) +void +S_SoundInfo_f (void) { - if (!sound_started || !shm) - { + if (!sound_started || !shm) { Con_Printf ("sound system not started\n"); return; } - - Con_Printf("%5d stereo\n", shm->channels - 1); - Con_Printf("%5d samples\n", shm->samples); - Con_Printf("%5d samplepos\n", shm->samplepos); - Con_Printf("%5d samplebits\n", shm->samplebits); - Con_Printf("%5d submission_chunk\n", shm->submission_chunk); - Con_Printf("%5d speed\n", shm->speed); - Con_Printf("0x%lx dma buffer\n", (unsigned long)shm->buffer); - Con_Printf("%5d total_channels\n", total_channels); + + Con_Printf ("%5d stereo\n", shm->channels - 1); + Con_Printf ("%5d samples\n", shm->samples); + Con_Printf ("%5d samplepos\n", shm->samplepos); + Con_Printf ("%5d samplebits\n", shm->samplebits); + Con_Printf ("%5d submission_chunk\n", shm->submission_chunk); + Con_Printf ("%5d speed\n", shm->speed); + Con_Printf ("0x%lx dma buffer\n", (unsigned long) shm->buffer); + Con_Printf ("%5d total_channels\n", total_channels); } @@ -163,21 +165,20 @@ S_Startup ================ */ -void S_Startup (void) +void +S_Startup (void) { - int rc; + int rc; if (!snd_initialized) return; - if (!fakedma) - { - rc = SNDDMA_Init(); + if (!fakedma) { + rc = SNDDMA_Init (); - if (!rc) - { + if (!rc) { #ifndef _WIN32 - Con_Printf("S_Startup: SNDDMA_Init failed.\n"); + Con_Printf ("S_Startup: SNDDMA_Init failed.\n"); #endif sound_started = 0; return; @@ -193,26 +194,26 @@ void S_Startup (void) S_Init ================ */ -void S_Init (void) +void +S_Init (void) { -// Con_Printf("\nSound Initialization\n"); +// Con_Printf("\nSound Initialization\n"); - Cmd_AddCommand("play", S_Play); - Cmd_AddCommand("playvol", S_PlayVol); - Cmd_AddCommand("stopsound", S_StopAllSoundsC); - Cmd_AddCommand("soundlist", S_SoundList); - Cmd_AddCommand("soundinfo", S_SoundInfo_f); + Cmd_AddCommand ("play", S_Play); + Cmd_AddCommand ("playvol", S_PlayVol); + Cmd_AddCommand ("stopsound", S_StopAllSoundsC); + Cmd_AddCommand ("soundlist", S_SoundList); + Cmd_AddCommand ("soundinfo", S_SoundInfo_f); - if (COM_CheckParm("-nosound")) + if (COM_CheckParm ("-nosound")) return; - if (COM_CheckParm("-simsound")) + if (COM_CheckParm ("-simsound")) fakedma = true; - if (host_parms.memsize < 0x800000) - { + if (host_parms.memsize < 0x800000) { Cvar_Set (loadas8bit, "1"); Con_Printf ("loading all sounds as 8bit\n"); } @@ -223,19 +224,19 @@ void S_Init (void) S_Startup (); - if (sound_started == 0) // sound startup failed? Bail out. + if (sound_started == 0) // sound startup failed? Bail out. return; SND_InitScaletable (); - known_sfx = Hunk_AllocName (MAX_SFX*sizeof(sfx_t), "sfx_t"); + known_sfx = Hunk_AllocName (MAX_SFX * sizeof (sfx_t), "sfx_t"); + num_sfx = 0; // create a piece of DMA memory - if (fakedma) - { - shm = (void *) Hunk_AllocName(sizeof(*shm), "shm"); + if (fakedma) { + shm = (void *) Hunk_AllocName (sizeof (*shm), "shm"); shm->splitbuffer = 0; shm->samplebits = 16; shm->speed = 22050; @@ -245,15 +246,14 @@ void S_Init (void) shm->soundalive = true; shm->gamealive = true; shm->submission_chunk = 1; - shm->buffer = Hunk_AllocName(1<<16, "shmbuf"); + shm->buffer = Hunk_AllocName (1 << 16, "shmbuf"); } - -// Con_Printf ("Sound sampling rate: %i\n", shm->speed); +// Con_Printf ("Sound sampling rate: %i\n", shm->speed); // provides a tick sound until washed clean -// if (shm->buffer) -// shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging +// if (shm->buffer) +// shm->buffer[4] = shm->buffer[5] = 0x7f; // force a pop for debugging ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav"); ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav"); @@ -261,19 +261,22 @@ void S_Init (void) S_StopAllSounds (true); } -void S_Init_Cvars (void) +void +S_Init_Cvars (void) { - nosound = Cvar_Get("nosound", "0", CVAR_NONE, "None"); - volume = Cvar_Get("volume", "0.7", CVAR_ARCHIVE, "None"); - precache = Cvar_Get("precache", "1", CVAR_NONE, "None"); - loadas8bit = Cvar_Get("loadas8bit", "0", CVAR_NONE, "None"); - bgmvolume = Cvar_Get("bgmvolume", "1", CVAR_ARCHIVE, "None"); - ambient_level = Cvar_Get("ambient_level", "0.3", CVAR_NONE, "None"); - ambient_fade = Cvar_Get("ambient_fade", "100", CVAR_NONE, "None"); - snd_noextraupdate = Cvar_Get("snd_noextraupdate", "0", CVAR_NONE, "None"); - snd_show = Cvar_Get("snd_show", "0", CVAR_NONE, "None"); - snd_interp = Cvar_Get("snd_interp", "1", CVAR_ARCHIVE, "control sample interpolation"); - _snd_mixahead = Cvar_Get("_snd_mixahead", "0.1", CVAR_ARCHIVE, "None"); + nosound = Cvar_Get ("nosound", "0", CVAR_NONE, "None"); + volume = Cvar_Get ("volume", "0.7", CVAR_ARCHIVE, "None"); + precache = Cvar_Get ("precache", "1", CVAR_NONE, "None"); + loadas8bit = Cvar_Get ("loadas8bit", "0", CVAR_NONE, "None"); + bgmvolume = Cvar_Get ("bgmvolume", "1", CVAR_ARCHIVE, "None"); + ambient_level = Cvar_Get ("ambient_level", "0.3", CVAR_NONE, "None"); + ambient_fade = Cvar_Get ("ambient_fade", "100", CVAR_NONE, "None"); + snd_noextraupdate = Cvar_Get ("snd_noextraupdate", "0", CVAR_NONE, "None"); + snd_show = Cvar_Get ("snd_show", "0", CVAR_NONE, "None"); + snd_interp = + Cvar_Get ("snd_interp", "1", CVAR_ARCHIVE, + "control sample interpolation"); + _snd_mixahead = Cvar_Get ("_snd_mixahead", "0.1", CVAR_ARCHIVE, "None"); } @@ -281,7 +284,8 @@ void S_Init_Cvars (void) // Shutdown sound engine // ======================================================================= -void S_Shutdown(void) +void +S_Shutdown (void) { if (!sound_started) @@ -293,9 +297,8 @@ void S_Shutdown(void) shm = 0; sound_started = 0; - if (!fakedma) - { - SNDDMA_Shutdown(); + if (!fakedma) { + SNDDMA_Shutdown (); } } @@ -310,32 +313,32 @@ S_FindName ================== */ -sfx_t *S_FindName (char *name) +sfx_t * +S_FindName (char *name) { - int i; - sfx_t *sfx; + int i; + sfx_t *sfx; if (!name) Sys_Error ("S_FindName: NULL\n"); - if (strlen(name) >= MAX_QPATH) + if (strlen (name) >= MAX_QPATH) Sys_Error ("Sound name too long: %s", name); // see if already loaded - for (i=0 ; i < num_sfx ; i++) - if (!strcmp(known_sfx[i].name, name)) - { + for (i = 0; i < num_sfx; i++) + if (!strcmp (known_sfx[i].name, name)) { return &known_sfx[i]; } if (num_sfx == MAX_SFX) Sys_Error ("S_FindName: out of sfx_t"); - + sfx = &known_sfx[i]; strcpy (sfx->name, name); num_sfx++; - + return sfx; } @@ -346,10 +349,11 @@ S_TouchSound ================== */ -void S_TouchSound (char *name) +void +S_TouchSound (char *name) { - sfx_t *sfx; - + sfx_t *sfx; + if (!sound_started) return; @@ -363,19 +367,20 @@ S_PrecacheSound ================== */ -sfx_t *S_PrecacheSound (char *name) +sfx_t * +S_PrecacheSound (char *name) { - sfx_t *sfx; + sfx_t *sfx; if (!sound_started || nosound->int_val) return NULL; sfx = S_FindName (name); - + // cache it in if (precache->int_val) S_LoadSound (sfx); - + return sfx; } @@ -387,35 +392,39 @@ sfx_t *S_PrecacheSound (char *name) SND_PickChannel ================= */ -channel_t *SND_PickChannel(int entnum, int entchannel) +channel_t * +SND_PickChannel (int entnum, int entchannel) { - int ch_idx; - int first_to_die; - int life_left; + int ch_idx; + int first_to_die; + int life_left; // Check for replacement sound, or find the best one to replace - first_to_die = -1; - life_left = 0x7fffffff; - for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++) - { - if (entchannel != 0 // channel 0 never overrides - && channels[ch_idx].entnum == entnum - && (channels[ch_idx].entchannel == entchannel || entchannel == -1) ) - { // allways override sound from same entity + first_to_die = -1; + life_left = 0x7fffffff; + for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; + ch_idx++) { + if (entchannel != 0 // channel 0 never overrides + && channels[ch_idx].entnum == entnum + && (channels[ch_idx].entchannel == entchannel || entchannel == -1)) { // allways + // override + // sound + // from + // same + // entity first_to_die = ch_idx; break; } - // don't let monster sounds override player sounds - if (channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity && channels[ch_idx].sfx) + if (channels[ch_idx].entnum == cl.viewentity && entnum != cl.viewentity + && channels[ch_idx].sfx) continue; - if (channels[ch_idx].end - paintedtime < life_left) - { + if (channels[ch_idx].end - paintedtime < life_left) { life_left = channels[ch_idx].end - paintedtime; first_to_die = ch_idx; } - } + } if (first_to_die == -1) return NULL; @@ -423,46 +432,42 @@ channel_t *SND_PickChannel(int entnum, int entchannel) if (channels[first_to_die].sfx) channels[first_to_die].sfx = NULL; - return &channels[first_to_die]; -} + return &channels[first_to_die]; +} /* ================= SND_Spatialize ================= */ -void SND_Spatialize(channel_t *ch) +void +SND_Spatialize (channel_t *ch) { - vec_t dot; - vec_t dist; - vec_t lscale, rscale, scale; - vec3_t source_vec; - sfx_t *snd; + vec_t dot; + vec_t dist; + vec_t lscale, rscale, scale; + vec3_t source_vec; + sfx_t *snd; // anything coming from the view entity will allways be full volume - if (ch->entnum == cl.viewentity) - { + if (ch->entnum == cl.viewentity) { ch->leftvol = ch->master_vol; ch->rightvol = ch->master_vol; return; } - // calculate stereo seperation and distance attenuation snd = ch->sfx; - VectorSubtract(ch->origin, listener_origin, source_vec); - - dist = VectorNormalize(source_vec) * ch->dist_mult; - - dot = DotProduct(listener_right, source_vec); + VectorSubtract (ch->origin, listener_origin, source_vec); - if (shm->channels == 1) - { + dist = VectorNormalize (source_vec) * ch->dist_mult; + + dot = DotProduct (listener_right, source_vec); + + if (shm->channels == 1) { rscale = 1.0; lscale = 1.0; - } - else - { + } else { rscale = 1.0 + dot; lscale = 1.0 - dot; } @@ -477,20 +482,22 @@ void SND_Spatialize(channel_t *ch) ch->leftvol = (int) (ch->master_vol * scale); if (ch->leftvol < 0) ch->leftvol = 0; -} +} // ======================================================================= // Start a sound effect // ======================================================================= -void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation) +void +S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, + float attenuation) { - channel_t *target_chan, *check; - sfxcache_t *sc; - int vol; - int ch_idx; - int skip; + channel_t *target_chan, *check; + sfxcache_t *sc; + int vol; + int ch_idx; + int skip; if (!sound_started) return; @@ -501,66 +508,63 @@ void S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float f if (nosound->int_val) return; - vol = fvol*255; + vol = fvol * 255; // pick a channel to play on - target_chan = SND_PickChannel(entnum, entchannel); + target_chan = SND_PickChannel (entnum, entchannel); if (!target_chan) return; - + // spatialize - memset (target_chan, 0, sizeof(*target_chan)); - VectorCopy(origin, target_chan->origin); + memset (target_chan, 0, sizeof (*target_chan)); + VectorCopy (origin, target_chan->origin); target_chan->dist_mult = attenuation / sound_nominal_clip_dist; target_chan->master_vol = vol; target_chan->entnum = entnum; target_chan->entchannel = entchannel; - SND_Spatialize(target_chan); + SND_Spatialize (target_chan); if (!target_chan->leftvol && !target_chan->rightvol) - return; // not audible at all + return; // not audible at all // new channel sc = S_LoadSound (sfx); - if (!sc) - { + if (!sc) { target_chan->sfx = NULL; - return; // couldn't load the sound's data + return; // couldn't load the sound's data } target_chan->sfx = sfx; target_chan->pos = 0.0; - target_chan->end = paintedtime + sc->length; + target_chan->end = paintedtime + sc->length; // if an identical sound has also been started this frame, offset the pos // a bit to keep it from just making the first one louder check = &channels[NUM_AMBIENTS]; - for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++) - { + for (ch_idx = NUM_AMBIENTS; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS; + ch_idx++, check++) { if (check == target_chan) continue; - if (check->sfx == sfx && !check->pos) - { - skip = rand () % (int)(0.1*shm->speed); + if (check->sfx == sfx && !check->pos) { + skip = rand () % (int) (0.1 * shm->speed); if (skip >= target_chan->end) skip = target_chan->end - 1; target_chan->pos += skip; target_chan->end -= skip; break; } - + } } -void S_StopSound(int entnum, int entchannel) +void +S_StopSound (int entnum, int entchannel) { - int i; + int i; - for (i=0 ; ibuffer && !pDSBuf)) #else @@ -609,43 +616,38 @@ void S_ClearBuffer (void) clear = 0; #ifdef _WIN32 - if (pDSBuf) - { - DWORD dwSize; - DWORD *pData; - int reps; - HRESULT hresult; + if (pDSBuf) { + DWORD dwSize; + DWORD *pData; + int reps; + HRESULT hresult; reps = 0; - while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, - (LPVOID *)&pData, &dwSize, - NULL, NULL, 0)) != DS_OK) - { - if (hresult != DSERR_BUFFERLOST) - { + while ((hresult = pDSBuf->lpVtbl->Lock (pDSBuf, 0, gSndBufSize, + (LPVOID *) & pData, &dwSize, + NULL, NULL, 0)) != DS_OK) { + if (hresult != DSERR_BUFFERLOST) { Con_Printf ("S_ClearBuffer: DS::Lock Sound Buffer Failed\n"); S_Shutdown (); return; } - if (++reps > 10000) - { + if (++reps > 10000) { Con_Printf ("S_ClearBuffer: DS: couldn't restore buffer\n"); S_Shutdown (); return; } } - memset(pData, clear, shm->samples * shm->samplebits/8); + memset (pData, clear, shm->samples * shm->samplebits / 8); - pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0); - - } - else + pDSBuf->lpVtbl->Unlock (pDSBuf, pData, dwSize, NULL, 0); + + } else #endif { - memset(shm->buffer, clear, shm->samples * shm->samplebits/8); + memset (shm->buffer, clear, shm->samples * shm->samplebits / 8); } } @@ -655,16 +657,16 @@ void S_ClearBuffer (void) S_StaticSound ================= */ -void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) +void +S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) { - channel_t *ss; - sfxcache_t *sc; + channel_t *ss; + sfxcache_t *sc; if (!sfx) return; - if (total_channels == MAX_CHANNELS) - { + if (total_channels == MAX_CHANNELS) { Con_Printf ("total_channels == MAX_CHANNELS\n"); return; } @@ -676,18 +678,17 @@ void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) if (!sc) return; - if (sc->loopstart == -1) - { + if (sc->loopstart == -1) { Con_Printf ("Sound %s not looped\n", sfx->name); return; } - + ss->sfx = sfx; VectorCopy (origin, ss->origin); ss->master_vol = vol; - ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist; - ss->end = paintedtime + sc->length; - + ss->dist_mult = (attenuation / 64) / sound_nominal_clip_dist; + ss->end = paintedtime + sc->length; + SND_Spatialize (ss); } @@ -699,12 +700,13 @@ void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) S_UpdateAmbientSounds =================== */ -void S_UpdateAmbientSounds (void) +void +S_UpdateAmbientSounds (void) { - mleaf_t *l; - float vol; - int ambient_channel; - channel_t *chan; + mleaf_t *l; + float vol; + int ambient_channel; + channel_t *chan; if (!snd_ambient) return; @@ -714,36 +716,32 @@ void S_UpdateAmbientSounds (void) return; l = Mod_PointInLeaf (listener_origin, cl.worldmodel); - if (!l || !ambient_level->value) - { - for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++) + if (!l || !ambient_level->value) { + for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; + ambient_channel++) channels[ambient_channel].sfx = NULL; return; } - for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++) - { - chan = &channels[ambient_channel]; + for (ambient_channel = 0; ambient_channel < NUM_AMBIENTS; ambient_channel++) { + chan = &channels[ambient_channel]; chan->sfx = ambient_sfx[ambient_channel]; - + vol = ambient_level->value * l->ambient_sound_level[ambient_channel]; if (vol < 8) vol = 0; - // don't adjust volume too fast - if (chan->master_vol < vol) - { + // don't adjust volume too fast + if (chan->master_vol < vol) { chan->master_vol += host_frametime * ambient_fade->value; if (chan->master_vol > vol) chan->master_vol = vol; - } - else if (chan->master_vol > vol) - { + } else if (chan->master_vol > vol) { chan->master_vol -= host_frametime * ambient_fade->value; if (chan->master_vol < vol) chan->master_vol = vol; } - + chan->leftvol = chan->rightvol = chan->master_vol; } } @@ -756,63 +754,57 @@ S_Update Called once each time through the main loop ============ */ -void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) +void +S_Update (vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) { - int i, j; - int total; - channel_t *ch; - channel_t *combine; + int i, j; + int total; + channel_t *ch; + channel_t *combine; if (!sound_started || (snd_blocked > 0)) return; - VectorCopy(origin, listener_origin); - VectorCopy(forward, listener_forward); - VectorCopy(right, listener_right); - VectorCopy(up, listener_up); - + VectorCopy (origin, listener_origin); + VectorCopy (forward, listener_forward); + VectorCopy (right, listener_right); + VectorCopy (up, listener_up); + // update general area ambient sound sources S_UpdateAmbientSounds (); combine = NULL; -// update spatialization for static and dynamic sounds - ch = channels+NUM_AMBIENTS; - for (i=NUM_AMBIENTS ; isfx) continue; - SND_Spatialize(ch); // respatialize channel + SND_Spatialize (ch); // respatialize channel if (!ch->leftvol && !ch->rightvol) continue; - // try to combine static sounds with a previous channel of the same - // sound effect so we don't mix five torches every frame - - if (i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS) - { - // see if it can just use the last one - if (combine && combine->sfx == ch->sfx) - { + // try to combine static sounds with a previous channel of the same + // sound effect so we don't mix five torches every frame + + if (i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS) { + // see if it can just use the last one + if (combine && combine->sfx == ch->sfx) { combine->leftvol += ch->leftvol; combine->rightvol += ch->rightvol; ch->leftvol = ch->rightvol = 0; continue; } - // search for one - combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS; - for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; jsfx == ch->sfx) break; - - if (j == total_channels) - { + + if (j == total_channels) { combine = NULL; - } - else - { - if (combine != ch) - { + } else { + if (combine != ch) { combine->leftvol += ch->leftvol; combine->rightvol += ch->rightvol; ch->leftvol = ch->rightvol = 0; @@ -820,50 +812,48 @@ void S_Update(vec3_t origin, vec3_t forward, vec3_t right, vec3_t up) continue; } } - - + + } // // debugging output // - if (snd_show->int_val) - { + if (snd_show->int_val) { total = 0; ch = channels; - for (i=0 ; isfx && (ch->leftvol || ch->rightvol) ) - { - //Con_Printf ("%3i %3i %s\n", ch->leftvol, ch->rightvol, ch->sfx->name); + for (i = 0; i < total_channels; i++, ch++) + if (ch->sfx && (ch->leftvol || ch->rightvol)) { + // Con_Printf ("%3i %3i %s\n", ch->leftvol, ch->rightvol, + // ch->sfx->name); total++; } - + Con_Printf ("----(%i)----\n", total); } - // mix some sound - S_Update_(); + S_Update_ (); } -void GetSoundtime(void) +void +GetSoundtime (void) { - int samplepos; - static int buffers; - static int oldsamplepos; - int fullsamples; - + int samplepos; + static int buffers; + static int oldsamplepos; + int fullsamples; + fullsamples = shm->samples / shm->channels; // it is possible to miscount buffers if it has wrapped twice between // calls to S_Update. Oh well. - samplepos = SNDDMA_GetDMAPos(); + samplepos = SNDDMA_GetDMAPos (); - if (samplepos < oldsamplepos) - { - buffers++; // buffer wrapped - - if (paintedtime > 0x40000000) - { // time to chop things off to avoid 32 bit limits + if (samplepos < oldsamplepos) { + buffers++; // buffer wrapped + + if (paintedtime > 0x40000000) { // time to chop things off to avoid + // 32 bit limits buffers = 0; paintedtime = fullsamples; S_StopAllSounds (true); @@ -871,10 +861,11 @@ void GetSoundtime(void) } oldsamplepos = samplepos; - soundtime = buffers*fullsamples + samplepos/shm->channels; + soundtime = buffers * fullsamples + samplepos / shm->channels; } -void S_ExtraUpdate (void) +void +S_ExtraUpdate (void) { #ifdef _WIN32 @@ -882,51 +873,49 @@ void S_ExtraUpdate (void) #endif if (snd_noextraupdate->int_val) - return; // don't pollute timings - S_Update_(); + return; // don't pollute timings + S_Update_ (); } -void S_Update_(void) +void +S_Update_ (void) { - unsigned int endtime; - int samps; - + unsigned int endtime; + int samps; + if (!sound_started || (snd_blocked > 0)) return; // Updates DMA time - GetSoundtime(); + GetSoundtime (); // check to make sure that we haven't overshot - if (paintedtime < soundtime) - { - //Con_Printf ("S_Update_ : overflow\n"); + if (paintedtime < soundtime) { + // Con_Printf ("S_Update_ : overflow\n"); paintedtime = soundtime; } - // mix ahead of current position endtime = soundtime + _snd_mixahead->value * shm->speed; - samps = shm->samples >> (shm->channels-1); + samps = shm->samples >> (shm->channels - 1); if (endtime - soundtime > samps) endtime = soundtime + samps; #ifdef _WIN32 // if the buffer was lost or stopped, restore it and/or restart it { - DWORD dwStatus; + DWORD dwStatus; - if (pDSBuf) - { + if (pDSBuf) { if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DD_OK) Con_Printf ("Couldn't get sound buffer status\n"); - + if (dwStatus & DSBSTATUS_BUFFERLOST) pDSBuf->lpVtbl->Restore (pDSBuf); - + if (!(dwStatus & DSBSTATUS_PLAYING)) - pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING); + pDSBuf->lpVtbl->Play (pDSBuf, 0, 0, DSBPLAY_LOOPING); } } #endif @@ -944,91 +933,87 @@ console functions =============================================================================== */ -void S_Play(void) +void +S_Play (void) { - static int hash=345; - int i; - char name[256]; - sfx_t *sfx; - + static int hash = 345; + int i; + char name[256]; + sfx_t *sfx; + i = 1; - while (icache); if (!sc) continue; - size = sc->length*sc->width*(sc->stereo+1); + size = sc->length * sc->width * (sc->stereo + 1); total += size; if (sc->loopstart >= 0) Con_Printf ("L"); else Con_Printf (" "); - Con_Printf("(%2db) %6i : %s\n",sc->width*8, size, sfx->name); + Con_Printf ("(%2db) %6i : %s\n", sc->width * 8, size, sfx->name); } Con_Printf ("Total resident: %i\n", total); } -void S_LocalSound (char *sound) +void +S_LocalSound (char *sound) { - sfx_t *sfx; + sfx_t *sfx; if (nosound->int_val) return; if (!sound_started) return; - + sfx = S_PrecacheSound (sound); - if (!sfx) - { + if (!sfx) { Con_Printf ("S_LocalSound: can't cache %s\n", sound); return; } @@ -1036,17 +1021,19 @@ void S_LocalSound (char *sound) } -void S_ClearPrecache (void) +void +S_ClearPrecache (void) { } -void S_BeginPrecaching (void) +void +S_BeginPrecaching (void) { } -void S_EndPrecaching (void) +void +S_EndPrecaching (void) { } - diff --git a/source/snd_mem.c b/source/snd_mem.c index 832ab7c..a355d5d 100644 --- a/source/snd_mem.c +++ b/source/snd_mem.c @@ -38,36 +38,38 @@ #include "quakefs.h" #include "console.h" -int cache_full_cycle; +int cache_full_cycle; -byte *S_Alloc (int size); +byte *S_Alloc (int size); /* ================ ResampleSfx ================ */ -void ResampleSfx (sfx_t *sfx, int inrate, int inwidth, byte *data) +void +ResampleSfx (sfx_t *sfx, int inrate, int inwidth, byte * data) { - int outcount; - int srcsample; - float stepscale; - int i; - int sample, samplefrac, fracstep; - sfxcache_t *sc; - short *is, *os; - unsigned char *ib, *ob; - + int outcount; + int srcsample; + float stepscale; + int i; + int sample, samplefrac, fracstep; + sfxcache_t *sc; + short *is, *os; + unsigned char *ib, *ob; + sc = Cache_Check (&sfx->cache); if (!sc) return; - is = (short*)data; - os = (short*)sc->data; + is = (short *) data; + os = (short *) sc->data; ib = data; ob = sc->data; - stepscale = (float)inrate / shm->speed; // this is usually 0.5, 1, or 2 + stepscale = (float) inrate / shm->speed; // this is usually 0.5, 1, or + // 2 outcount = sc->length / stepscale; @@ -81,30 +83,30 @@ void ResampleSfx (sfx_t *sfx, int inrate, int inwidth, byte *data) // resample / decimate to the current source rate if (stepscale == 1) { if (inwidth == 1 && sc->width == 1) { - for (i=0 ; iwidth == 2) { - for (i=0 ; iwidth == 1) { - for (i=0 ; i> 8; } } else if (inwidth == 2 && sc->width == 2) { - for (i=0 ; iint_val && stepscale < 1) { - int points = 1/stepscale; - int j; + int points = 1 / stepscale; + int j; for (i = 0; i < sc->length; i++) { - int s1, s2; + int s1, s2; if (inwidth == 2) { s2 = s1 = LittleShort (is[0]); @@ -118,7 +120,7 @@ void ResampleSfx (sfx_t *sfx, int inrate, int inwidth, byte *data) ib++; } for (j = 0; j < points; j++) { - sample = s1 + (s2 - s1) * ((float)j) / points; + sample = s1 + (s2 - s1) * ((float) j) / points; if (sc->width == 2) { os[j] = sample; } else { @@ -133,19 +135,19 @@ void ResampleSfx (sfx_t *sfx, int inrate, int inwidth, byte *data) } } else { samplefrac = 0; - fracstep = stepscale*256; - for (i=0 ; i> 8; samplefrac += fracstep; if (inwidth == 2) - sample = LittleShort ( ((short *)data)[srcsample] ); + sample = LittleShort (((short *) data)[srcsample]); else - sample = (int)( (unsigned char)(data[srcsample]) - 128) << 8; + sample = + (int) ((unsigned char) (data[srcsample]) - 128) << 8; if (sc->width == 2) - ((short *)sc->data)[i] = sample; + ((short *) sc->data)[i] = sample; else - ((signed char *)sc->data)[i] = sample >> 8; + ((signed char *) sc->data)[i] = sample >> 8; } } } @@ -162,15 +164,16 @@ void ResampleSfx (sfx_t *sfx, int inrate, int inwidth, byte *data) S_LoadSound ============== */ -sfxcache_t *S_LoadSound (sfx_t *s) +sfxcache_t * +S_LoadSound (sfx_t *s) { - char namebuffer[256]; - byte *data; - wavinfo_t info; - int len; - float stepscale; - sfxcache_t *sc; - byte stackbuf[1*1024]; // avoid dirtying the cache heap + char namebuffer[256]; + byte *data; + wavinfo_t info; + int len; + float stepscale; + sfxcache_t *sc; + byte stackbuf[1 * 1024]; // avoid dirtying the cache heap // see if still in memory sc = Cache_Check (&s->cache); @@ -179,27 +182,25 @@ sfxcache_t *S_LoadSound (sfx_t *s) //Con_Printf ("S_LoadSound: %x\n", (int)stackbuf); // load it in - strcpy(namebuffer, "sound/"); - strncat (namebuffer, s->name, sizeof(namebuffer) - strlen (namebuffer)); + strcpy (namebuffer, "sound/"); + strncat (namebuffer, s->name, sizeof (namebuffer) - strlen (namebuffer)); -// Con_Printf ("loading %s\n",namebuffer); +// Con_Printf ("loading %s\n",namebuffer); - data = COM_LoadStackFile(namebuffer, stackbuf, sizeof(stackbuf)); + data = COM_LoadStackFile (namebuffer, stackbuf, sizeof (stackbuf)); - if (!data) - { + if (!data) { Con_Printf ("Couldn't load %s\n", namebuffer); return NULL; } info = GetWavinfo (s->name, data, com_filesize); - if (info.channels != 1) - { - Con_Printf ("%s is a stereo sample\n",s->name); + if (info.channels != 1) { + Con_Printf ("%s is a stereo sample\n", s->name); return NULL; } - stepscale = (float)info.rate / shm->speed; + stepscale = (float) info.rate / shm->speed; len = info.samples / stepscale; if (loadas8bit->int_val) { @@ -208,10 +209,11 @@ sfxcache_t *S_LoadSound (sfx_t *s) len = len * 2 * info.channels; } - sc = Cache_Alloc ( &s->cache, len + sizeof(sfxcache_t), s->name); + sc = Cache_Alloc (&s->cache, len + sizeof (sfxcache_t), s->name); + if (!sc) return NULL; - + sc->length = info.samples; sc->loopstart = info.loopstart; sc->speed = info.rate; @@ -234,80 +236,83 @@ WAV loading */ -byte *data_p; -byte *iff_end; -byte *last_chunk; -byte *iff_data; -int iff_chunk_len; +byte *data_p; +byte *iff_end; +byte *last_chunk; +byte *iff_data; +int iff_chunk_len; -short GetLittleShort(void) +short +GetLittleShort (void) { - short val = 0; + short val = 0; + val = *data_p; - val = val + (*(data_p+1)<<8); + val = val + (*(data_p + 1) << 8); data_p += 2; return val; } -int GetLittleLong(void) +int +GetLittleLong (void) { - int val = 0; + int val = 0; + val = *data_p; - val = val + (*(data_p+1)<<8); - val = val + (*(data_p+2)<<16); - val = val + (*(data_p+3)<<24); + val = val + (*(data_p + 1) << 8); + val = val + (*(data_p + 2) << 16); + val = val + (*(data_p + 3) << 24); data_p += 4; return val; } -void FindNextChunk(char *name) +void +FindNextChunk (char *name) { - while (1) - { - data_p=last_chunk; + while (1) { + data_p = last_chunk; - if (data_p >= iff_end) - { // didn't find the chunk + if (data_p >= iff_end) { // didn't find the chunk data_p = NULL; return; } - + data_p += 4; - iff_chunk_len = GetLittleLong(); - if (iff_chunk_len < 0) - { + iff_chunk_len = GetLittleLong (); + if (iff_chunk_len < 0) { data_p = NULL; return; } -// if (iff_chunk_len > 1024*1024) -// Sys_Error ("FindNextChunk: %i length is past the 1 meg sanity limit", iff_chunk_len); +// if (iff_chunk_len > 1024*1024) +// Sys_Error ("FindNextChunk: %i length is past the 1 meg sanity limit", iff_chunk_len); data_p -= 8; - last_chunk = data_p + 8 + ( (iff_chunk_len + 1) & ~1 ); - if (!strncmp(data_p, name, 4)) + last_chunk = data_p + 8 + ((iff_chunk_len + 1) & ~1); + if (!strncmp (data_p, name, 4)) return; } } -void FindChunk(char *name) +void +FindChunk (char *name) { last_chunk = iff_data; FindNextChunk (name); } -void DumpChunks(void) +void +DumpChunks (void) { - char str[5]; - + char str[5]; + str[4] = 0; - data_p=iff_data; - do - { + data_p = iff_data; + do { memcpy (str, data_p, 4); data_p += 4; - iff_chunk_len = GetLittleLong(); - Con_Printf ("0x%x : %s (%d)\n", (int)(data_p - 4), str, iff_chunk_len); + iff_chunk_len = GetLittleLong (); + Con_Printf ("0x%x : %s (%d)\n", (int) (data_p - 4), str, iff_chunk_len); data_p += (iff_chunk_len + 1) & ~1; } while (data_p < iff_end); } @@ -317,97 +322,89 @@ void DumpChunks(void) GetWavinfo ============ */ -wavinfo_t GetWavinfo (char *name, byte *wav, int wavlength) +wavinfo_t +GetWavinfo (char *name, byte * wav, int wavlength) { - wavinfo_t info; - int i; - int format; - int samples; + wavinfo_t info; + int i; + int format; + int samples; - memset (&info, 0, sizeof(info)); + memset (&info, 0, sizeof (info)); if (!wav) return info; - + iff_data = wav; iff_end = wav + wavlength; // find "RIFF" chunk - FindChunk("RIFF"); - if (!(data_p && !strncmp(data_p+8, "WAVE", 4))) - { - Con_Printf("Missing RIFF/WAVE chunks\n"); + FindChunk ("RIFF"); + if (!(data_p && !strncmp (data_p + 8, "WAVE", 4))) { + Con_Printf ("Missing RIFF/WAVE chunks\n"); return info; } - // get "fmt " chunk iff_data = data_p + 12; // DumpChunks (); - FindChunk("fmt "); - if (!data_p) - { - Con_Printf("Missing fmt chunk\n"); + FindChunk ("fmt "); + if (!data_p) { + Con_Printf ("Missing fmt chunk\n"); return info; } data_p += 8; - format = GetLittleShort(); - if (format != 1) - { - Con_Printf("Microsoft PCM format only\n"); + format = GetLittleShort (); + if (format != 1) { + Con_Printf ("Microsoft PCM format only\n"); return info; } - info.channels = GetLittleShort(); - info.rate = GetLittleLong(); - data_p += 4+2; - info.width = GetLittleShort() / 8; + info.channels = GetLittleShort (); + info.rate = GetLittleLong (); + data_p += 4 + 2; + info.width = GetLittleShort () / 8; // get cue chunk - FindChunk("cue "); - if (data_p) - { + FindChunk ("cue "); + if (data_p) { data_p += 32; - info.loopstart = GetLittleLong(); -// Con_Printf("loopstart=%d\n", sfx->loopstart); + info.loopstart = GetLittleLong (); +// Con_Printf("loopstart=%d\n", sfx->loopstart); - // if the next chunk is a LIST chunk, look for a cue length marker + // if the next chunk is a LIST chunk, look for a cue length marker FindNextChunk ("LIST"); - if (data_p) - { - if (!strncmp (data_p + 28, "mark", 4)) - { // this is not a proper parse, but it works with cooledit... + if (data_p) { + if (!strncmp (data_p + 28, "mark", 4)) { // this is not a + // proper parse, but + // it works with + // cooledit... data_p += 24; i = GetLittleLong (); // samples in loop info.samples = info.loopstart + i; -// Con_Printf("looped length: %i\n", i); +// Con_Printf("looped length: %i\n", i); } } - } - else + } else info.loopstart = -1; // find data chunk - FindChunk("data"); - if (!data_p) - { - Con_Printf("Missing data chunk\n"); + FindChunk ("data"); + if (!data_p) { + Con_Printf ("Missing data chunk\n"); return info; } data_p += 4; samples = GetLittleLong () / info.width; - if (info.samples) - { + if (info.samples) { if (samples < info.samples) Sys_Error ("Sound %s has a bad loop length", name); - } - else + } else info.samples = samples; info.dataofs = data_p - wav; - + return info; } - diff --git a/source/snd_mix.c b/source/snd_mix.c index 78fa4f0..1d6c607 100644 --- a/source/snd_mix.c +++ b/source/snd_mix.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -48,219 +48,215 @@ #define PAINTBUFFER_SIZE 512 portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE]; -int snd_scaletable[32][256]; -int *snd_p, snd_linear_count, snd_vol; -short *snd_out; +int snd_scaletable[32][256]; +int *snd_p, snd_linear_count, snd_vol; +short *snd_out; -void Snd_WriteLinearBlastStereo16 (void); +void Snd_WriteLinearBlastStereo16 (void); #ifndef USE_INTEL_ASM -void Snd_WriteLinearBlastStereo16 (void) +void +Snd_WriteLinearBlastStereo16 (void) { - int i; - int val; + int i; + int val; - for (i=0 ; i>8; + for (i = 0; i < snd_linear_count; i += 2) { + val = (snd_p[i] * snd_vol) >> 8; if (val > 0x7fff) snd_out[i] = 0x7fff; - else if (val < (short)0x8000) - snd_out[i] = (short)0x8000; + else if (val < (short) 0x8000) + snd_out[i] = (short) 0x8000; else snd_out[i] = val; - val = (snd_p[i+1]*snd_vol)>>8; + val = (snd_p[i + 1] * snd_vol) >> 8; if (val > 0x7fff) - snd_out[i+1] = 0x7fff; - else if (val < (short)0x8000) - snd_out[i+1] = (short)0x8000; + snd_out[i + 1] = 0x7fff; + else if (val < (short) 0x8000) + snd_out[i + 1] = (short) 0x8000; else - snd_out[i+1] = val; + snd_out[i + 1] = val; } } #endif -void S_TransferStereo16 (int endtime) +void +S_TransferStereo16 (int endtime) { - int lpos; - int lpaintedtime; - DWORD *pbuf; + int lpos; + int lpaintedtime; + DWORD *pbuf; + #ifdef _WIN32 - int reps; - DWORD dwSize,dwSize2; - DWORD *pbuf2; - HRESULT hresult; + int reps; + DWORD dwSize, dwSize2; + DWORD *pbuf2; + HRESULT hresult; #endif - - snd_vol = volume->value*256; + + snd_vol = volume->value * 256; snd_p = (int *) paintbuffer; lpaintedtime = paintedtime; #ifdef _WIN32 - if (pDSBuf) - { + if (pDSBuf) { reps = 0; - while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, - (LPVOID *)&pbuf, &dwSize, - (LPVOID *)&pbuf2, &dwSize2, 0)) != DS_OK) { - if (hresult != DSERR_BUFFERLOST) - { - Con_Printf ("S_TransferStereo16: DS::Lock Sound Buffer Failed\n"); + while ((hresult = pDSBuf->lpVtbl->Lock (pDSBuf, 0, gSndBufSize, + (LPVOID *) & pbuf, &dwSize, + (LPVOID *) & pbuf2, &dwSize2, + 0)) != DS_OK) { + if (hresult != DSERR_BUFFERLOST) { + Con_Printf + ("S_TransferStereo16: DS::Lock Sound Buffer Failed\n"); S_Shutdown (); S_Startup (); return; } - if (++reps > 10000) - { - Con_Printf ("S_TransferStereo16: DS: couldn't restore buffer\n"); + if (++reps > 10000) { + Con_Printf + ("S_TransferStereo16: DS: couldn't restore buffer\n"); S_Shutdown (); S_Startup (); return; } } - } - else + } else #endif { - pbuf = (DWORD *)shm->buffer; + pbuf = (DWORD *) shm->buffer; } - while (lpaintedtime < endtime) - { - // handle recirculating buffer issues - lpos = lpaintedtime & ((shm->samples>>1)-1); + while (lpaintedtime < endtime) { + // handle recirculating buffer issues + lpos = lpaintedtime & ((shm->samples >> 1) - 1); - snd_out = (short *) pbuf + (lpos<<1); + snd_out = (short *) pbuf + (lpos << 1); - snd_linear_count = (shm->samples>>1) - lpos; + snd_linear_count = (shm->samples >> 1) - lpos; if (lpaintedtime + snd_linear_count > endtime) snd_linear_count = endtime - lpaintedtime; snd_linear_count <<= 1; - // write a linear blast of samples + // write a linear blast of samples Snd_WriteLinearBlastStereo16 (); snd_p += snd_linear_count; - lpaintedtime += (snd_linear_count>>1); + lpaintedtime += (snd_linear_count >> 1); } #ifdef _WIN32 if (pDSBuf) - pDSBuf->lpVtbl->Unlock(pDSBuf, pbuf, dwSize, NULL, 0); + pDSBuf->lpVtbl->Unlock (pDSBuf, pbuf, dwSize, NULL, 0); #endif } -void S_TransferPaintBuffer(int endtime) +void +S_TransferPaintBuffer (int endtime) { - int out_idx; - int count; - int out_mask; - int *p; - int step; - int val; - int snd_vol; - DWORD *pbuf; + int out_idx; + int count; + int out_mask; + int *p; + int step; + int val; + int snd_vol; + DWORD *pbuf; + #ifdef _WIN32 - int reps; - DWORD dwSize,dwSize2; - DWORD *pbuf2; - HRESULT hresult; + int reps; + DWORD dwSize, dwSize2; + DWORD *pbuf2; + HRESULT hresult; #endif - if (shm->samplebits == 16 && shm->channels == 2) - { + if (shm->samplebits == 16 && shm->channels == 2) { S_TransferStereo16 (endtime); return; } - + p = (int *) paintbuffer; count = (endtime - paintedtime) * shm->channels; - out_mask = shm->samples - 1; + out_mask = shm->samples - 1; out_idx = paintedtime * shm->channels & out_mask; step = 3 - shm->channels; - snd_vol = volume->value*256; - -#ifdef _WIN32 - if (pDSBuf) - { - reps = 0; - - while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, - (LPVOID *)&pbuf, &dwSize, - (LPVOID *)&pbuf2, &dwSize2, 0)) != DS_OK) { - if (hresult != DSERR_BUFFERLOST) - { - Con_Printf ("S_TransferPaintBuffer: DS::Lock Sound Buffer Failed\n"); - S_Shutdown (); - S_Startup (); - return; - } - - if (++reps > 10000) - { - Con_Printf ("S_TransferPaintBuffer: DS: couldn't restore buffer\n"); - S_Shutdown (); - S_Startup (); - return; - } - } - } - else -#endif - { - pbuf = (DWORD *)shm->buffer; - } - - if (shm->samplebits == 16) - { - short *out = (short *) pbuf; - while (count--) - { - val = (*p * snd_vol) >> 8; - p+= step; - if (val > 0x7fff) - val = 0x7fff; - else if (val < (short)0x8000) - val = (short)0x8000; - out[out_idx] = val; - out_idx = (out_idx + 1) & out_mask; - } - } - else if (shm->samplebits == 8) - { - unsigned char *out = (unsigned char *) pbuf; - while (count--) - { - val = (*p * snd_vol) >> 8; - p+= step; - if (val > 0x7fff) - val = 0x7fff; - else if (val < (short)0x8000) - val = (short)0x8000; - out[out_idx] = (val>>8) + 128; - out_idx = (out_idx + 1) & out_mask; - } - } + snd_vol = volume->value * 256; #ifdef _WIN32 if (pDSBuf) { - DWORD dwNewpos, dwWrite; - int il = paintedtime; - int ir = endtime - paintedtime; - + reps = 0; + + while ((hresult = pDSBuf->lpVtbl->Lock (pDSBuf, 0, gSndBufSize, + (LPVOID *) & pbuf, &dwSize, + (LPVOID *) & pbuf2, &dwSize2, + 0)) != DS_OK) { + if (hresult != DSERR_BUFFERLOST) { + Con_Printf + ("S_TransferPaintBuffer: DS::Lock Sound Buffer Failed\n"); + S_Shutdown (); + S_Startup (); + return; + } + + if (++reps > 10000) { + Con_Printf + ("S_TransferPaintBuffer: DS: couldn't restore buffer\n"); + S_Shutdown (); + S_Startup (); + return; + } + } + } else +#endif + { + pbuf = (DWORD *) shm->buffer; + } + + if (shm->samplebits == 16) { + short *out = (short *) pbuf; + + while (count--) { + val = (*p * snd_vol) >> 8; + p += step; + if (val > 0x7fff) + val = 0x7fff; + else if (val < (short) 0x8000) + val = (short) 0x8000; + out[out_idx] = val; + out_idx = (out_idx + 1) & out_mask; + } + } else if (shm->samplebits == 8) { + unsigned char *out = (unsigned char *) pbuf; + + while (count--) { + val = (*p * snd_vol) >> 8; + p += step; + if (val > 0x7fff) + val = 0x7fff; + else if (val < (short) 0x8000) + val = (short) 0x8000; + out[out_idx] = (val >> 8) + 128; + out_idx = (out_idx + 1) & out_mask; + } + } +#ifdef _WIN32 + if (pDSBuf) { + DWORD dwNewpos, dwWrite; + int il = paintedtime; + int ir = endtime - paintedtime; + ir += il; - pDSBuf->lpVtbl->Unlock(pDSBuf, pbuf, dwSize, NULL, 0); + pDSBuf->lpVtbl->Unlock (pDSBuf, pbuf, dwSize, NULL, 0); - pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &dwNewpos, &dwWrite); + pDSBuf->lpVtbl->GetCurrentPosition (pDSBuf, &dwNewpos, &dwWrite); -// if ((dwNewpos >= il) && (dwNewpos <= ir)) -// Con_Printf("%d-%d p %d c\n", il, ir, dwNewpos); +// if ((dwNewpos >= il) && (dwNewpos <= ir)) +// Con_Printf("%d-%d p %d c\n", il, ir, dwNewpos); } #endif } @@ -274,31 +270,32 @@ CHANNEL MIXING =============================================================================== */ -void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int endtime); -void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int endtime); +void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int endtime); +void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int endtime); -void S_PaintChannels(int endtime) +void +S_PaintChannels (int endtime) { - int i; - int end; - channel_t *ch; - sfxcache_t *sc; - int ltime, count; + int i; + int end; + channel_t *ch; + sfxcache_t *sc; + int ltime, count; - while (paintedtime < endtime) - { - // if paintbuffer is smaller than DMA buffer + while (paintedtime < endtime) { + // if paintbuffer is smaller than DMA buffer end = endtime; if (endtime - paintedtime > PAINTBUFFER_SIZE) end = paintedtime + PAINTBUFFER_SIZE; - // clear the paint buffer - memset(paintbuffer, 0, (end - paintedtime) * sizeof(portable_samplepair_t)); + // clear the paint buffer + memset (paintbuffer, 0, - // paint in the channels. + (end - paintedtime) * sizeof (portable_samplepair_t)); + + // paint in the channels. ch = channels; - for (i=0; isfx) continue; if (!ch->leftvol && !ch->rightvol) @@ -309,102 +306,96 @@ void S_PaintChannels(int endtime) ltime = paintedtime; - while (ltime < end) - { // paint up to end + while (ltime < end) { // paint up to end if (ch->end < end) count = ch->end - ltime; else count = end - ltime; - if (count > 0) - { + if (count > 0) { if (sc->width == 1) - SND_PaintChannelFrom8(ch, sc, count); + SND_PaintChannelFrom8 (ch, sc, count); else - SND_PaintChannelFrom16(ch, sc, count); - + SND_PaintChannelFrom16 (ch, sc, count); + ltime += count; } - - // if at end of loop, restart - if (ltime >= ch->end) - { - if (sc->loopstart >= 0) - { + // if at end of loop, restart + if (ltime >= ch->end) { + if (sc->loopstart >= 0) { ch->pos = sc->loopstart; ch->end = ltime + sc->length - ch->pos; - } - else - { // channel just stopped + } else { // channel just stopped ch->sfx = NULL; break; } } } - + } - // transfer out according to DMA format - S_TransferPaintBuffer(end); + // transfer out according to DMA format + S_TransferPaintBuffer (end); paintedtime = end; } } -void SND_InitScaletable (void) +void +SND_InitScaletable (void) { - int i, j; - - for (i=0 ; i<32 ; i++) - for (j=0 ; j<256 ; j++) - snd_scaletable[i][j] = ((signed char)j) * i * 8; + int i, j; + + for (i = 0; i < 32; i++) + for (j = 0; j < 256; j++) + snd_scaletable[i][j] = ((signed char) j) * i * 8; } #ifndef USE_INTEL_ASM -void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int count) +void +SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int count) { - int data; - int *lscale, *rscale; + int data; + int *lscale, *rscale; unsigned char *sfx; - int i; + int i; if (ch->leftvol > 255) ch->leftvol = 255; if (ch->rightvol > 255) ch->rightvol = 255; - + lscale = snd_scaletable[ch->leftvol >> 3]; rscale = snd_scaletable[ch->rightvol >> 3]; - sfx = (signed char *)sc->data + ch->pos; + sfx = (signed char *) sc->data + ch->pos; - for (i=0 ; ipos += count; } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM -void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int count) +void +SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int count) { - int data; - int left, right; - int leftvol, rightvol; + int data; + int left, right; + int leftvol, rightvol; signed short *sfx; - int i; + int i; leftvol = ch->leftvol; rightvol = ch->rightvol; - sfx = (signed short *)sc->data + ch->pos; + sfx = (signed short *) sc->data + ch->pos; - for (i=0 ; i> 8; right = (data * rightvol) >> 8; @@ -414,4 +405,3 @@ void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int count) ch->pos += count; } - diff --git a/source/snd_null.c b/source/snd_null.c index c3de40e..9f473dd 100644 --- a/source/snd_null.c +++ b/source/snd_null.c @@ -37,14 +37,14 @@ // FIXME - should be put in one place // ======================================================================= channel_t channels[MAX_CHANNELS]; -int total_channels; -volatile dma_t *shm = 0; -cvar_t *loadas8bit; -int paintedtime; // sample PAIRS +int total_channels; +volatile dma_t *shm = 0; +cvar_t *loadas8bit; +int paintedtime; // sample PAIRS -cvar_t *bgmvolume; -cvar_t *volume; +cvar_t *bgmvolume; +cvar_t *volume; void @@ -56,9 +56,9 @@ S_Init (void) void S_Init_Cvars (void) { - volume = Cvar_Get("volume", "0.7", CVAR_ARCHIVE, "None"); - loadas8bit = Cvar_Get("loadas8bit", "0", CVAR_NONE, "None"); - bgmvolume = Cvar_Get("bgmvolume", "1", CVAR_ARCHIVE, "None"); + volume = Cvar_Get ("volume", "0.7", CVAR_ARCHIVE, "None"); + loadas8bit = Cvar_Get ("loadas8bit", "0", CVAR_NONE, "None"); + bgmvolume = Cvar_Get ("bgmvolume", "1", CVAR_ARCHIVE, "None"); } void @@ -92,7 +92,8 @@ S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation) } void -S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation) +S_StartSound (int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, + float attenuation) { } @@ -101,7 +102,7 @@ S_StopSound (int entnum, int entchannel) { } -sfx_t * +sfx_t * S_PrecacheSound (char *sample) { return NULL; @@ -141,4 +142,3 @@ void S_LocalSound (char *s) { } - diff --git a/source/snd_oss.c b/source/snd_oss.c index e9e2695..5ecd163 100644 --- a/source/snd_oss.c +++ b/source/snd_oss.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -64,30 +64,31 @@ # define MAP_FAILED ((void *) -1) #endif -int audio_fd; -int snd_inited; +int audio_fd; +int snd_inited; -static int tryrates[] = { 11025, 22051, 44100, 8000 }; +static int tryrates[] = { 11025, 22051, 44100, 8000 }; qboolean -SNDDMA_Init(void) +SNDDMA_Init (void) { - int rc; - int fmt; - int tmp; - int i; - char *s; + int rc; + int fmt; + int tmp; + int i; + char *s; struct audio_buf_info info; - int caps; - int retries = 3; + int caps; + int retries = 3; snd_inited = 0; // open /dev/dsp, confirm capability to mmap, and get size of dma buffer audio_fd = open ("/dev/dsp", O_RDWR); - if (audio_fd < 0) { // Failed open, retry up to 3 times if it's busy + if (audio_fd < 0) { // Failed open, retry up to 3 times + // if it's busy while ((audio_fd < 0) && retries-- && - ((errno == EAGAIN) || (errno == EBUSY))) { + ((errno == EAGAIN) || (errno == EBUSY))) { sleep (1); audio_fd = open ("/dev/dsp", O_RDWR); } @@ -118,19 +119,19 @@ SNDDMA_Init(void) return 0; } - if (ioctl (audio_fd, SNDCTL_DSP_GETOSPACE, &info) == -1) { + if (ioctl (audio_fd, SNDCTL_DSP_GETOSPACE, &info) == -1) { perror ("GETOSPACE"); Con_Printf ("Um, can't do GETOSPACE?\n"); close (audio_fd); return 0; } - + shm = &sn; shm->splitbuffer = 0; // set sample bits & speed if ((i = COM_CheckParm ("-sndbits"))) { - shm->samplebits = atoi (com_argv[i+1]); + shm->samplebits = atoi (com_argv[i + 1]); } else { if ((s = getenv ("QF_SND_BITS"))) { shm->samplebits = atoi (s); @@ -140,19 +141,19 @@ SNDDMA_Init(void) if (shm->samplebits != 16 && shm->samplebits != 8) { ioctl (audio_fd, SNDCTL_DSP_GETFMTS, &fmt); - if (fmt & AFMT_S16_LE) { // little-endian 16-bit signed + if (fmt & AFMT_S16_LE) { // little-endian 16-bit signed shm->samplebits = 16; } else { - if (fmt & AFMT_U8) { // unsigned 8-bit ulaw + if (fmt & AFMT_U8) { // unsigned 8-bit ulaw shm->samplebits = 8; } } } if ((i = COM_CheckParm ("-sndspeed"))) { - shm->speed = atoi (com_argv[i+1]); + shm->speed = atoi (com_argv[i + 1]); } else if ((s = getenv ("QF_SND_SPEED"))) { - shm->speed = atoi (s); + shm->speed = atoi (s); } else { for (i = 0; i < (sizeof (tryrates) / 4); i++) if (!ioctl (audio_fd, SNDCTL_DSP_SPEED, &tryrates[i])) @@ -170,85 +171,87 @@ SNDDMA_Init(void) shm->channels = 2; } - shm->samples = info.fragstotal * info.fragsize / (shm->samplebits/8); + shm->samples = info.fragstotal * info.fragsize / (shm->samplebits / 8); shm->submission_chunk = 1; // memory map the dma buffer - shm->buffer = (unsigned char *) mmap(NULL, info.fragstotal - * info.fragsize, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, audio_fd, 0); + shm->buffer = (unsigned char *) mmap (NULL, info.fragstotal + * info.fragsize, + PROT_READ | PROT_WRITE, + MAP_FILE | MAP_SHARED, audio_fd, 0); if (shm->buffer == MAP_FAILED) { - perror("/dev/dsp"); - Con_Printf("Could not mmap /dev/dsp\n"); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not mmap /dev/dsp\n"); + close (audio_fd); return 0; } tmp = 0; if (shm->channels == 2) tmp = 1; - rc = ioctl(audio_fd, SNDCTL_DSP_STEREO, &tmp); + rc = ioctl (audio_fd, SNDCTL_DSP_STEREO, &tmp); if (rc < 0) { - perror("/dev/dsp"); - Con_Printf("Could not set /dev/dsp to stereo=%d", shm->channels); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not set /dev/dsp to stereo=%d", shm->channels); + close (audio_fd); return 0; } - + if (tmp) shm->channels = 2; else shm->channels = 1; - rc = ioctl(audio_fd, SNDCTL_DSP_SPEED, &shm->speed); + rc = ioctl (audio_fd, SNDCTL_DSP_SPEED, &shm->speed); if (rc < 0) { - perror("/dev/dsp"); - Con_Printf("Could not set /dev/dsp speed to %d", shm->speed); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not set /dev/dsp speed to %d", shm->speed); + close (audio_fd); return 0; } if (shm->samplebits == 16) { rc = AFMT_S16_LE; - rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc); + rc = ioctl (audio_fd, SNDCTL_DSP_SETFMT, &rc); if (rc < 0) { - perror("/dev/dsp"); - Con_Printf("Could not support 16-bit data. Try 8-bit.\n"); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not support 16-bit data. Try 8-bit.\n"); + close (audio_fd); return 0; } } else if (shm->samplebits == 8) { rc = AFMT_U8; - rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc); + rc = ioctl (audio_fd, SNDCTL_DSP_SETFMT, &rc); if (rc < 0) { - perror("/dev/dsp"); - Con_Printf("Could not support 8-bit data.\n"); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not support 8-bit data.\n"); + close (audio_fd); return 0; } } else { - perror("/dev/dsp"); - Con_Printf("%d-bit sound not supported.", shm->samplebits); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("%d-bit sound not supported.", shm->samplebits); + close (audio_fd); return 0; } // toggle the trigger & start her up tmp = 0; - rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp); + rc = ioctl (audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp); if (rc < 0) { - perror("/dev/dsp"); - Con_Printf("Could not toggle.\n"); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not toggle.\n"); + close (audio_fd); return 0; } tmp = PCM_ENABLE_OUTPUT; - rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp); + rc = ioctl (audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp); if (rc < 0) { - perror("/dev/dsp"); - Con_Printf("Could not toggle.\n"); - close(audio_fd); + perror ("/dev/dsp"); + Con_Printf ("Could not toggle.\n"); + close (audio_fd); return 0; } @@ -259,34 +262,35 @@ SNDDMA_Init(void) } -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { struct count_info count; - if (!snd_inited) return 0; + if (!snd_inited) + return 0; - if (ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &count)==-1) - { - perror("/dev/dsp"); - Con_Printf("Uh, sound dead.\n"); - close(audio_fd); + if (ioctl (audio_fd, SNDCTL_DSP_GETOPTR, &count) == -1) { + perror ("/dev/dsp"); + Con_Printf ("Uh, sound dead.\n"); + close (audio_fd); snd_inited = 0; return 0; } -// shm->samplepos = (count.bytes / (shm->samplebits / 8)) & (shm->samples-1); -// fprintf(stderr, "%d \r", count.ptr); +// shm->samplepos = (count.bytes / (shm->samplebits / 8)) & (shm->samples-1); +// fprintf(stderr, "%d \r", count.ptr); shm->samplepos = count.ptr / (shm->samplebits / 8); return shm->samplepos; } -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { - if (snd_inited) - { - close(audio_fd); + if (snd_inited) { + close (audio_fd); snd_inited = 0; } } @@ -298,7 +302,7 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { } - diff --git a/source/snd_sdl.c b/source/snd_sdl.c index 6be22e4..a331421 100644 --- a/source/snd_sdl.c +++ b/source/snd_sdl.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -38,22 +38,24 @@ #include "cmd.h" static dma_t the_shm; -static int snd_inited; +static int snd_inited; -extern int desired_speed; -extern int desired_bits; +extern int desired_speed; +extern int desired_bits; -static void paint_audio(void *unused, Uint8 *stream, int len) +static void +paint_audio (void *unused, Uint8 * stream, int len) { - if ( shm ) { + if (shm) { shm->buffer = stream; - shm->samplepos += len/(shm->samplebits/8); + shm->samplepos += len / (shm->samplebits / 8); // Check for samplepos overflow? S_PaintChannels (shm->samplepos); } } -qboolean SNDDMA_Init(void) +qboolean +SNDDMA_Init (void) { SDL_AudioSpec desired, obtained; @@ -66,14 +68,13 @@ qboolean SNDDMA_Init(void) desired.format = AUDIO_U8; break; case 16: - if ( SDL_BYTEORDER == SDL_BIG_ENDIAN ) + if (SDL_BYTEORDER == SDL_BIG_ENDIAN) desired.format = AUDIO_S16MSB; else desired.format = AUDIO_S16LSB; break; default: - Con_Printf("Unknown number of audio bits: %d\n", - desired_bits); + Con_Printf ("Unknown number of audio bits: %d\n", desired_bits); return 0; } desired.channels = 2; @@ -81,8 +82,8 @@ qboolean SNDDMA_Init(void) desired.callback = paint_audio; /* Open the audio device */ - if ( SDL_OpenAudio(&desired, &obtained) < 0 ) { - Con_Printf("Couldn't open SDL audio: %s\n", SDL_GetError()); + if (SDL_OpenAudio (&desired, &obtained) < 0) { + Con_Printf ("Couldn't open SDL audio: %s\n", SDL_GetError ()); return 0; } @@ -93,26 +94,25 @@ qboolean SNDDMA_Init(void) break; case AUDIO_S16LSB: case AUDIO_S16MSB: - if ( ((obtained.format == AUDIO_S16LSB) && - (SDL_BYTEORDER == SDL_LIL_ENDIAN)) || - ((obtained.format == AUDIO_S16MSB) && - (SDL_BYTEORDER == SDL_BIG_ENDIAN)) ) { + if (((obtained.format == AUDIO_S16LSB) && + (SDL_BYTEORDER == SDL_LIL_ENDIAN)) || + ((obtained.format == AUDIO_S16MSB) && + (SDL_BYTEORDER == SDL_BIG_ENDIAN))) { /* Supported */ break; } - /* Unsupported, fall through */; + /* Unsupported, fall through */ ; default: /* Not supported -- force SDL to do our bidding */ - SDL_CloseAudio(); - if ( SDL_OpenAudio(&desired, NULL) < 0 ) { - Con_Printf("Couldn't open SDL audio: %s\n", - SDL_GetError()); + SDL_CloseAudio (); + if (SDL_OpenAudio (&desired, NULL) < 0) { + Con_Printf ("Couldn't open SDL audio: %s\n", SDL_GetError ()); return 0; } - memcpy(&obtained, &desired, sizeof(desired)); + memcpy (&obtained, &desired, sizeof (desired)); break; } - SDL_PauseAudio(0); + SDL_PauseAudio (0); /* Fill the audio DMA information block */ shm = &the_shm; @@ -120,7 +120,7 @@ qboolean SNDDMA_Init(void) shm->samplebits = (obtained.format & 0xFF); shm->speed = obtained.freq; shm->channels = obtained.channels; - shm->samples = obtained.samples*shm->channels; + shm->samples = obtained.samples * shm->channels; shm->samplepos = 0; shm->submission_chunk = 1; shm->buffer = NULL; @@ -129,15 +129,17 @@ qboolean SNDDMA_Init(void) return 1; } -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { return shm->samplepos; } -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { if (snd_inited) { - SDL_CloseAudio(); + SDL_CloseAudio (); snd_inited = 0; } } @@ -149,7 +151,7 @@ void SNDDMA_Shutdown(void) Send sound to device if buffer isn't really the dma buffer */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { } - diff --git a/source/snd_sun.c b/source/snd_sun.c index 3b6d21d..83baafb 100644 --- a/source/snd_sun.c +++ b/source/snd_sun.c @@ -28,7 +28,7 @@ $Id$ */ -#include +# include "config.h" #include #include #include @@ -48,56 +48,56 @@ #include #include -int audio_fd; -int snd_inited; +int audio_fd; +int snd_inited; -static int wbufp; +static int wbufp; static audio_info_t info; #define BUFFER_SIZE 8192 unsigned char dma_buffer[BUFFER_SIZE]; unsigned char pend_buffer[BUFFER_SIZE]; -int pending; +int pending; -qboolean SNDDMA_Init(void) +qboolean +SNDDMA_Init (void) { if (snd_inited) { - printf("Sound already init'd\n"); + printf ("Sound already init'd\n"); return 0; } shm = &sn; shm->splitbuffer = 0; - audio_fd = open("/dev/audio", O_WRONLY|O_NDELAY); + audio_fd = open ("/dev/audio", O_WRONLY | O_NDELAY); if (audio_fd < 0) { if (errno == EBUSY) { - Con_Printf("Audio device is being used by another process\n"); + Con_Printf ("Audio device is being used by another process\n"); } - perror("/dev/audio"); - Con_Printf("Could not open /dev/audio\n"); + perror ("/dev/audio"); + Con_Printf ("Could not open /dev/audio\n"); return (0); } - if (ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { - perror("/dev/audio"); - Con_Printf("Could not communicate with audio device.\n"); - close(audio_fd); + if (ioctl (audio_fd, AUDIO_GETINFO, &info) < 0) { + perror ("/dev/audio"); + Con_Printf ("Could not communicate with audio device.\n"); + close (audio_fd); return 0; } - - // + // // set to nonblock - // - if (fcntl(audio_fd, F_SETFL, O_NONBLOCK) < 0) { - perror("/dev/audio"); - close(audio_fd); + // + if (fcntl (audio_fd, F_SETFL, O_NONBLOCK) < 0) { + perror ("/dev/audio"); + close (audio_fd); return 0; } - AUDIO_INITINFO(&info); + AUDIO_INITINFO (&info); shm->speed = 11025; @@ -107,61 +107,63 @@ qboolean SNDDMA_Init(void) info.play.channels = 2; info.play.precision = 16; - if (ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) { + if (ioctl (audio_fd, AUDIO_SETINFO, &info) < 0) { info.play.encoding = AUDIO_ENCODING_LINEAR; info.play.sample_rate = 11025; info.play.channels = 1; info.play.precision = 16; - if (ioctl(audio_fd, AUDIO_SETINFO, &info) < 0) { - Con_Printf("Incapable sound hardware.\n"); - close(audio_fd); + if (ioctl (audio_fd, AUDIO_SETINFO, &info) < 0) { + Con_Printf ("Incapable sound hardware.\n"); + close (audio_fd); return 0; } - Con_Printf("16 bit mono sound initialized\n"); + Con_Printf ("16 bit mono sound initialized\n"); shm->samplebits = 16; shm->channels = 1; - } else { // 16 bit stereo - Con_Printf("16 bit stereo sound initialized\n"); + } else { // 16 bit stereo + Con_Printf ("16 bit stereo sound initialized\n"); shm->samplebits = 16; shm->channels = 2; } shm->soundalive = true; - shm->samples = sizeof(dma_buffer) / (shm->samplebits/8); + shm->samples = sizeof (dma_buffer) / (shm->samplebits / 8); shm->samplepos = 0; shm->submission_chunk = 1; - shm->buffer = (unsigned char *)dma_buffer; + shm->buffer = (unsigned char *) dma_buffer; snd_inited = 1; return 1; } -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { if (!snd_inited) return (0); - if (ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { - perror("/dev/audio"); - Con_Printf("Could not communicate with audio device.\n"); - close(audio_fd); + if (ioctl (audio_fd, AUDIO_GETINFO, &info) < 0) { + perror ("/dev/audio"); + Con_Printf ("Could not communicate with audio device.\n"); + close (audio_fd); snd_inited = 0; return (0); } - return ((info.play.samples*shm->channels) % shm->samples); + return ((info.play.samples * shm->channels) % shm->samples); } -int SNDDMA_GetSamples(void) +int +SNDDMA_GetSamples (void) { if (!snd_inited) return (0); - if (ioctl(audio_fd, AUDIO_GETINFO, &info) < 0) { - perror("/dev/audio"); - Con_Printf("Could not communicate with audio device.\n"); - close(audio_fd); + if (ioctl (audio_fd, AUDIO_GETINFO, &info) < 0) { + perror ("/dev/audio"); + Con_Printf ("Could not communicate with audio device.\n"); + close (audio_fd); snd_inited = 0; return (0); } @@ -169,10 +171,11 @@ int SNDDMA_GetSamples(void) return info.play.samples; } -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { if (snd_inited) { - close(audio_fd); + close (audio_fd); snd_inited = 0; } } @@ -184,31 +187,32 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { - int bsize; - int bytes, b; + int bsize; + int bytes, b; static unsigned char writebuf[1024]; unsigned char *p; - int idx; - int stop = paintedtime; + int idx; + int stop = paintedtime; if (paintedtime < wbufp) - wbufp = 0; // reset + wbufp = 0; // reset - bsize = shm->channels * (shm->samplebits/8); + bsize = shm->channels * (shm->samplebits / 8); bytes = (paintedtime - wbufp) * bsize; if (!bytes) return; - if (bytes > sizeof(writebuf)) { - bytes = sizeof(writebuf); - stop = wbufp + bytes/bsize; + if (bytes > sizeof (writebuf)) { + bytes = sizeof (writebuf); + stop = wbufp + bytes / bsize; } p = writebuf; - idx = (wbufp*bsize) & (BUFFER_SIZE - 1); + idx = (wbufp * bsize) & (BUFFER_SIZE - 1); for (b = bytes; b; b--) { *p++ = dma_buffer[idx]; @@ -217,8 +221,7 @@ void SNDDMA_Submit(void) wbufp = stop; - if (write(audio_fd, writebuf, bytes) < bytes) - printf("audio can't keep up!\n"); + if (write (audio_fd, writebuf, bytes) < bytes) + printf ("audio can't keep up!\n"); } - diff --git a/source/snd_win.c b/source/snd_win.c index f23e859..c4f8005 100644 --- a/source/snd_win.c +++ b/source/snd_win.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "winquake.h" #include "qargs.h" @@ -36,7 +36,9 @@ #define iDirectSoundCreate(a,b,c) pDirectSoundCreate(a,b,c) -HRESULT (WINAPI *pDirectSoundCreate)(GUID FAR *lpGUID, LPDIRECTSOUND FAR *lplpDS, IUnknown FAR *pUnkOuter); +HRESULT (WINAPI * pDirectSoundCreate) (GUID FAR * lpGUID, + LPDIRECTSOUND FAR * lplpDS, + IUnknown FAR * pUnkOuter); // 64K is > 1 second at 16-bit, 22050 Hz #define WAV_BUFFERS 64 @@ -44,44 +46,44 @@ HRESULT (WINAPI *pDirectSoundCreate)(GUID FAR *lpGUID, LPDIRECTSOUND FAR *lplpDS #define WAV_BUFFER_SIZE 0x0400 #define SECONDARY_BUFFER_SIZE 0x10000 -typedef enum {SIS_SUCCESS, SIS_FAILURE, SIS_NOTAVAIL} sndinitstat; +typedef enum { SIS_SUCCESS, SIS_FAILURE, SIS_NOTAVAIL } sndinitstat; -static qboolean wavonly; -static qboolean dsound_init; -static qboolean wav_init; -static qboolean snd_firsttime = true, snd_isdirect, snd_iswave; -static qboolean primary_format_set; +static qboolean wavonly; +static qboolean dsound_init; +static qboolean wav_init; +static qboolean snd_firsttime = true, snd_isdirect, snd_iswave; +static qboolean primary_format_set; -static int sample16; -static int snd_sent, snd_completed; +static int sample16; +static int snd_sent, snd_completed; /* * Global variables. Must be visible to window-procedure function * so it can unlock and free the data block after it has been played. - */ + */ -HANDLE hData; -HPSTR lpData, lpData2; +HANDLE hData; +HPSTR lpData, lpData2; -HGLOBAL hWaveHdr; -LPWAVEHDR lpWaveHdr; +HGLOBAL hWaveHdr; +LPWAVEHDR lpWaveHdr; -HWAVEOUT hWaveOut; +HWAVEOUT hWaveOut; -WAVEOUTCAPS wavecaps; +WAVEOUTCAPS wavecaps; -DWORD gSndBufSize; +DWORD gSndBufSize; -MMTIME mmstarttime; +MMTIME mmstarttime; LPDIRECTSOUND pDS; LPDIRECTSOUNDBUFFER pDSBuf, pDSPBuf; -HINSTANCE hInstDS; +HINSTANCE hInstDS; sndinitstat SNDDMA_InitDirect (void); -qboolean SNDDMA_InitWav (void); +qboolean SNDDMA_InitWav (void); /* @@ -89,12 +91,12 @@ qboolean SNDDMA_InitWav (void); S_BlockSound ================== */ -void S_BlockSound (void) +void +S_BlockSound (void) { // DirectSound takes care of blocking itself - if (snd_iswave) - { + if (snd_iswave) { snd_blocked++; if (snd_blocked == 1) @@ -108,12 +110,12 @@ void S_BlockSound (void) S_UnblockSound ================== */ -void S_UnblockSound (void) +void +S_UnblockSound (void) { // DirectSound takes care of blocking itself - if (snd_iswave) - { + if (snd_iswave) { snd_blocked--; } } @@ -124,50 +126,44 @@ void S_UnblockSound (void) FreeSound ================== */ -void FreeSound (void) +void +FreeSound (void) { - int i; + int i; - if (pDSBuf) - { - pDSBuf->lpVtbl->Stop(pDSBuf); - pDSBuf->lpVtbl->Release(pDSBuf); + if (pDSBuf) { + pDSBuf->lpVtbl->Stop (pDSBuf); + pDSBuf->lpVtbl->Release (pDSBuf); } - // only release primary buffer if it's not also the mixing buffer we just released - if (pDSPBuf && (pDSBuf != pDSPBuf)) - { - pDSPBuf->lpVtbl->Release(pDSPBuf); + if (pDSPBuf && (pDSBuf != pDSPBuf)) { + pDSPBuf->lpVtbl->Release (pDSPBuf); } - if (pDS) - { + if (pDS) { pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_NORMAL); - pDS->lpVtbl->Release(pDS); + pDS->lpVtbl->Release (pDS); } - if (hWaveOut) - { + if (hWaveOut) { waveOutReset (hWaveOut); - if (lpWaveHdr) - { - for (i=0 ; i< WAV_BUFFERS ; i++) - waveOutUnprepareHeader (hWaveOut, lpWaveHdr+i, sizeof(WAVEHDR)); + if (lpWaveHdr) { + for (i = 0; i < WAV_BUFFERS; i++) + waveOutUnprepareHeader (hWaveOut, lpWaveHdr + i, + sizeof (WAVEHDR)); } waveOutClose (hWaveOut); - if (hWaveHdr) - { - GlobalUnlock(hWaveHdr); - GlobalFree(hWaveHdr); + if (hWaveHdr) { + GlobalUnlock (hWaveHdr); + GlobalFree (hWaveHdr); } - if (hData) - { - GlobalUnlock(hData); - GlobalFree(hData); + if (hData) { + GlobalUnlock (hData); + GlobalFree (hData); } } @@ -192,17 +188,18 @@ SNDDMA_InitDirect Direct-Sound support ================== */ -sndinitstat SNDDMA_InitDirect (void) +sndinitstat +SNDDMA_InitDirect (void) { - DSBUFFERDESC dsbuf; - DSBCAPS dsbcaps; - DWORD dwSize, dwWrite; - DSCAPS dscaps; - WAVEFORMATEX format, pformat; - HRESULT hresult; - int reps; + DSBUFFERDESC dsbuf; + DSBCAPS dsbcaps; + DWORD dwSize, dwWrite; + DSCAPS dscaps; + WAVEFORMATEX format, pformat; + HRESULT hresult; + int reps; - memset ((void *)&sn, 0, sizeof (sn)); + memset ((void *) &sn, 0, sizeof (sn)); shm = &sn; @@ -210,124 +207,110 @@ sndinitstat SNDDMA_InitDirect (void) shm->samplebits = 16; shm->speed = 11025; - memset (&format, 0, sizeof(format)); + memset (&format, 0, sizeof (format)); format.wFormatTag = WAVE_FORMAT_PCM; - format.nChannels = shm->channels; - format.wBitsPerSample = shm->samplebits; - format.nSamplesPerSec = shm->speed; - format.nBlockAlign = format.nChannels - *format.wBitsPerSample / 8; - format.cbSize = 0; - format.nAvgBytesPerSec = format.nSamplesPerSec - *format.nBlockAlign; + format.nChannels = shm->channels; + format.wBitsPerSample = shm->samplebits; + format.nSamplesPerSec = shm->speed; + format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8; + format.cbSize = 0; + format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; - if (!hInstDS) - { - hInstDS = LoadLibrary("dsound.dll"); - - if (hInstDS == NULL) - { + if (!hInstDS) { + hInstDS = LoadLibrary ("dsound.dll"); + + if (hInstDS == NULL) { Con_Printf ("Couldn't load dsound.dll\n"); return SIS_FAILURE; } - pDirectSoundCreate = (void *)GetProcAddress(hInstDS,"DirectSoundCreate"); + pDirectSoundCreate = + (void *) GetProcAddress (hInstDS, "DirectSoundCreate"); - if (!pDirectSoundCreate) - { + if (!pDirectSoundCreate) { Con_Printf ("Couldn't get DS proc addr\n"); return SIS_FAILURE; } } - while ((hresult = iDirectSoundCreate(NULL, &pDS, NULL)) != DS_OK) - { - if (hresult != DSERR_ALLOCATED) - { + while ((hresult = iDirectSoundCreate (NULL, &pDS, NULL)) != DS_OK) { + if (hresult != DSERR_ALLOCATED) { Con_Printf ("DirectSound create failed\n"); return SIS_FAILURE; } - -// if (MessageBox (NULL, -// "The sound hardware is in use by another app.\n\n" -// "Select Retry to try to start sound again or Cancel to run Quake with no sound.", -// "Sound not available", -// MB_RETRYCANCEL | MB_SETFOREGROUND | MB_ICONEXCLAMATION) != IDRETRY) -// { - Con_Printf ("DirectSoundCreate failure\n" - " hardware already in use\n"); - return SIS_NOTAVAIL; -// } +// if (MessageBox (NULL, +// "The sound hardware is in use by another app.\n\n" +// "Select Retry to try to start sound again or Cancel to run Quake with no sound.", +// "Sound not available", +// MB_RETRYCANCEL | MB_SETFOREGROUND | MB_ICONEXCLAMATION) != IDRETRY) +// { + Con_Printf ("DirectSoundCreate failure\n" + " hardware already in use\n"); + return SIS_NOTAVAIL; +// } } - dscaps.dwSize = sizeof(dscaps); + dscaps.dwSize = sizeof (dscaps); - if (DS_OK != pDS->lpVtbl->GetCaps (pDS, &dscaps)) - { + if (DS_OK != pDS->lpVtbl->GetCaps (pDS, &dscaps)) { Con_Printf ("Couldn't get DS caps\n"); } - if (dscaps.dwFlags & DSCAPS_EMULDRIVER) - { + if (dscaps.dwFlags & DSCAPS_EMULDRIVER) { Con_Printf ("No DirectSound driver installed\n"); FreeSound (); return SIS_FAILURE; } - if (DS_OK != pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_EXCLUSIVE)) - { + if (DS_OK != + pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_EXCLUSIVE)) { Con_Printf ("Set coop level failed\n"); FreeSound (); return SIS_FAILURE; } - // get access to the primary buffer, if possible, so we can set the // sound hardware format - memset (&dsbuf, 0, sizeof(dsbuf)); - dsbuf.dwSize = sizeof(DSBUFFERDESC); + memset (&dsbuf, 0, sizeof (dsbuf)); + dsbuf.dwSize = sizeof (DSBUFFERDESC); dsbuf.dwFlags = DSBCAPS_PRIMARYBUFFER; dsbuf.dwBufferBytes = 0; dsbuf.lpwfxFormat = NULL; - memset(&dsbcaps, 0, sizeof(dsbcaps)); - dsbcaps.dwSize = sizeof(dsbcaps); + memset (&dsbcaps, 0, sizeof (dsbcaps)); + dsbcaps.dwSize = sizeof (dsbcaps); primary_format_set = false; - if (!COM_CheckParm ("-snoforceformat")) - { - if (DS_OK == pDS->lpVtbl->CreateSoundBuffer(pDS, &dsbuf, &pDSPBuf, NULL)) - { + if (!COM_CheckParm ("-snoforceformat")) { + if (DS_OK == + pDS->lpVtbl->CreateSoundBuffer (pDS, &dsbuf, &pDSPBuf, NULL)) { pformat = format; - if (DS_OK != pDSPBuf->lpVtbl->SetFormat (pDSPBuf, &pformat)) - { -// if (snd_firsttime) -// Con_Printf ("Set primary sound buffer format: no\n"); - } - else -// { -// if (snd_firsttime) -// Con_Printf ("Set primary sound buffer format: yes\n"); + if (DS_OK != pDSPBuf->lpVtbl->SetFormat (pDSPBuf, &pformat)) { +// if (snd_firsttime) +// Con_Printf ("Set primary sound buffer format: no\n"); + } else +// { +// if (snd_firsttime) +// Con_Printf ("Set primary sound buffer format: yes\n"); primary_format_set = true; -// } +// } } } - if (!primary_format_set || !COM_CheckParm ("-primarysound")) - { - // create the secondary buffer we'll actually work with - memset (&dsbuf, 0, sizeof(dsbuf)); - dsbuf.dwSize = sizeof(DSBUFFERDESC); + if (!primary_format_set || !COM_CheckParm ("-primarysound")) { + // create the secondary buffer we'll actually work with + memset (&dsbuf, 0, sizeof (dsbuf)); + dsbuf.dwSize = sizeof (DSBUFFERDESC); dsbuf.dwFlags = DSBCAPS_CTRLFREQUENCY | DSBCAPS_LOCSOFTWARE; dsbuf.dwBufferBytes = SECONDARY_BUFFER_SIZE; dsbuf.lpwfxFormat = &format; - memset(&dsbcaps, 0, sizeof(dsbcaps)); - dsbcaps.dwSize = sizeof(dsbcaps); + memset (&dsbcaps, 0, sizeof (dsbcaps)); + dsbcaps.dwSize = sizeof (dsbcaps); - if (DS_OK != pDS->lpVtbl->CreateSoundBuffer(pDS, &dsbuf, &pDSBuf, NULL)) - { + if (DS_OK != + pDS->lpVtbl->CreateSoundBuffer (pDS, &dsbuf, &pDSBuf, NULL)) { Con_Printf ("DS:CreateSoundBuffer Failed"); FreeSound (); return SIS_FAILURE; @@ -337,61 +320,55 @@ sndinitstat SNDDMA_InitDirect (void) shm->samplebits = format.wBitsPerSample; shm->speed = format.nSamplesPerSec; - if (DS_OK != pDSBuf->lpVtbl->GetCaps (pDSBuf, &dsbcaps)) - { + if (DS_OK != pDSBuf->lpVtbl->GetCaps (pDSBuf, &dsbcaps)) { Con_Printf ("DS:GetCaps failed\n"); FreeSound (); return SIS_FAILURE; } - -// if (snd_firsttime) -// Con_Printf ("Using secondary sound buffer\n"); - } - else - { - if (DS_OK != pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, DSSCL_WRITEPRIMARY)) - { +// if (snd_firsttime) +// Con_Printf ("Using secondary sound buffer\n"); + } else { + if (DS_OK != + pDS->lpVtbl->SetCooperativeLevel (pDS, mainwindow, + DSSCL_WRITEPRIMARY)) { Con_Printf ("Set coop level failed\n"); FreeSound (); return SIS_FAILURE; } - if (DS_OK != pDSPBuf->lpVtbl->GetCaps (pDSPBuf, &dsbcaps)) - { + if (DS_OK != pDSPBuf->lpVtbl->GetCaps (pDSPBuf, &dsbcaps)) { Con_Printf ("DS:GetCaps failed\n"); return SIS_FAILURE; } pDSBuf = pDSPBuf; -// Con_Printf ("Using primary sound buffer\n"); +// Con_Printf ("Using primary sound buffer\n"); } // Make sure mixer is active - pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING); + pDSBuf->lpVtbl->Play (pDSBuf, 0, 0, DSBPLAY_LOOPING); /* if (snd_firsttime) Con_Printf(" %d channel(s)\n" " %d bits/sample\n" " %d bytes/sec\n", shm->channels, shm->samplebits, shm->speed);*/ - + gSndBufSize = dsbcaps.dwBufferBytes; // initialize the buffer reps = 0; - while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, - (LPVOID *)&lpData, &dwSize, NULL, - NULL, 0)) != DS_OK) { - if (hresult != DSERR_BUFFERLOST) - { + while ((hresult = pDSBuf->lpVtbl->Lock (pDSBuf, 0, gSndBufSize, + (LPVOID *) & lpData, &dwSize, NULL, + NULL, 0)) != DS_OK) { + if (hresult != DSERR_BUFFERLOST) { Con_Printf ("SNDDMA_InitDirect: DS::Lock Sound Buffer Failed\n"); FreeSound (); return SIS_FAILURE; } - if (++reps > 10000) - { + if (++reps > 10000) { Con_Printf ("SNDDMA_InitDirect: DS: couldn't restore buffer\n"); FreeSound (); return SIS_FAILURE; @@ -399,25 +376,27 @@ sndinitstat SNDDMA_InitDirect (void) } - memset(lpData, 0, dwSize); -// lpData[4] = lpData[5] = 0x7f; // force a pop for debugging + memset (lpData, 0, dwSize); +// lpData[4] = lpData[5] = 0x7f; // force a pop for debugging - pDSBuf->lpVtbl->Unlock(pDSBuf, lpData, dwSize, NULL, 0); + pDSBuf->lpVtbl->Unlock (pDSBuf, lpData, dwSize, NULL, 0); - /* we don't want anyone to access the buffer directly w/o locking it first. */ - lpData = NULL; + /* we don't want anyone to access the buffer directly w/o locking it + first. */ + lpData = NULL; - pDSBuf->lpVtbl->Stop(pDSBuf); - pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &mmstarttime.u.sample, &dwWrite); - pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING); + pDSBuf->lpVtbl->Stop (pDSBuf); + pDSBuf->lpVtbl->GetCurrentPosition (pDSBuf, &mmstarttime.u.sample, + &dwWrite); + pDSBuf->lpVtbl->Play (pDSBuf, 0, 0, DSBPLAY_LOOPING); shm->soundalive = true; shm->splitbuffer = false; - shm->samples = gSndBufSize/(shm->samplebits/8); + shm->samples = gSndBufSize / (shm->samplebits / 8); shm->samplepos = 0; shm->submission_chunk = 1; shm->buffer = (unsigned char *) lpData; - sample16 = (shm->samplebits/8) - 1; + sample16 = (shm->samplebits / 8) - 1; dsound_init = true; @@ -432,12 +411,13 @@ SNDDM_InitWav Crappy windows multimedia base ================== */ -qboolean SNDDMA_InitWav (void) +qboolean +SNDDMA_InitWav (void) { - WAVEFORMATEX format; - int i; - HRESULT hr; - + WAVEFORMATEX format; + int i; + HRESULT hr; + snd_sent = 0; snd_completed = 0; @@ -447,98 +427,86 @@ qboolean SNDDMA_InitWav (void) shm->samplebits = 16; shm->speed = 11025; - memset (&format, 0, sizeof(format)); + memset (&format, 0, sizeof (format)); format.wFormatTag = WAVE_FORMAT_PCM; format.nChannels = shm->channels; format.wBitsPerSample = shm->samplebits; format.nSamplesPerSec = shm->speed; - format.nBlockAlign = format.nChannels - *format.wBitsPerSample / 8; + format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8; format.cbSize = 0; - format.nAvgBytesPerSec = format.nSamplesPerSec - *format.nBlockAlign; - - /* Open a waveform device for output using window callback. */ - while ((hr = waveOutOpen((LPHWAVEOUT)&hWaveOut, WAVE_MAPPER, - &format, - 0, 0L, CALLBACK_NULL)) != MMSYSERR_NOERROR) - { - if (hr != MMSYSERR_ALLOCATED) - { + format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; + + /* Open a waveform device for output using window callback. */ + while ((hr = waveOutOpen ((LPHWAVEOUT) & hWaveOut, WAVE_MAPPER, + &format, + 0, 0L, CALLBACK_NULL)) != MMSYSERR_NOERROR) { + if (hr != MMSYSERR_ALLOCATED) { Con_Printf ("waveOutOpen failed\n"); return false; } - -// if (MessageBox (NULL, -// "The sound hardware is in use by another app.\n\n" -// "Select Retry to try to start sound again or Cancel to run Quake with no sound.", -// "Sound not available", -// MB_RETRYCANCEL | MB_SETFOREGROUND | MB_ICONEXCLAMATION) != IDRETRY) -// { - Con_Printf ("waveOutOpen failure;\n" - " hardware already in use\n"); - return false; -// } - } +// if (MessageBox (NULL, +// "The sound hardware is in use by another app.\n\n" +// "Select Retry to try to start sound again or Cancel to run Quake with no sound.", +// "Sound not available", +// MB_RETRYCANCEL | MB_SETFOREGROUND | MB_ICONEXCLAMATION) != IDRETRY) +// { + Con_Printf ("waveOutOpen failure;\n" " hardware already in use\n"); + return false; +// } + } /* * Allocate and lock memory for the waveform data. The memory * for waveform data must be globally allocated with * GMEM_MOVEABLE and GMEM_SHARE flags. - */ - gSndBufSize = WAV_BUFFERS*WAV_BUFFER_SIZE; - hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, gSndBufSize); - if (!hData) - { + */ + gSndBufSize = WAV_BUFFERS * WAV_BUFFER_SIZE; + hData = GlobalAlloc (GMEM_MOVEABLE | GMEM_SHARE, gSndBufSize); + if (!hData) { Con_Printf ("Sound: Out of memory.\n"); FreeSound (); - return false; + return false; } - lpData = GlobalLock(hData); - if (!lpData) - { + lpData = GlobalLock (hData); + if (!lpData) { Con_Printf ("Sound: Failed to lock.\n"); FreeSound (); - return false; - } + return false; + } memset (lpData, 0, gSndBufSize); /* * Allocate and lock memory for the header. This memory must * also be globally allocated with GMEM_MOVEABLE and * GMEM_SHARE flags. - */ - hWaveHdr = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, - (DWORD) sizeof(WAVEHDR) * WAV_BUFFERS); + */ + hWaveHdr = GlobalAlloc (GMEM_MOVEABLE | GMEM_SHARE, + (DWORD) sizeof (WAVEHDR) * WAV_BUFFERS); - if (hWaveHdr == NULL) - { + if (hWaveHdr == NULL) { Con_Printf ("Sound: Failed to Alloc header.\n"); FreeSound (); - return false; - } - - lpWaveHdr = (LPWAVEHDR) GlobalLock(hWaveHdr); - - if (lpWaveHdr == NULL) - { - Con_Printf ("Sound: Failed to lock header.\n"); - FreeSound (); - return false; + return false; } - memset (lpWaveHdr, 0, sizeof(WAVEHDR) * WAV_BUFFERS); + lpWaveHdr = (LPWAVEHDR) GlobalLock (hWaveHdr); - /* After allocation, set up and prepare headers. */ - for (i=0 ; isoundalive = true; shm->splitbuffer = false; - shm->samples = gSndBufSize/(shm->samplebits/8); + shm->samples = gSndBufSize / (shm->samplebits / 8); shm->samplepos = 0; shm->submission_chunk = 1; shm->buffer = (unsigned char *) lpData; - sample16 = (shm->samplebits/8) - 1; + sample16 = (shm->samplebits / 8) - 1; wav_init = true; @@ -567,57 +535,48 @@ Returns false if nothing is found. ================== */ -qboolean SNDDMA_Init(void) +qboolean +SNDDMA_Init (void) { - sndinitstat stat; + sndinitstat stat; if (COM_CheckParm ("-wavonly")) wavonly = true; dsound_init = wav_init = 0; - stat = SIS_FAILURE; // assume DirectSound won't initialize + stat = SIS_FAILURE; // assume DirectSound won't + // initialize /* Init DirectSound */ - if (!wavonly) - { - if (snd_firsttime || snd_isdirect) - { + if (!wavonly) { + if (snd_firsttime || snd_isdirect) { stat = SNDDMA_InitDirect ();; - if (stat == SIS_SUCCESS) - { + if (stat == SIS_SUCCESS) { snd_isdirect = true; if (snd_firsttime) Con_Printf ("DirectSound initialized\n"); - } - else - { + } else { snd_isdirect = false; Con_Printf ("DirectSound failed to init\n"); } } } - // if DirectSound didn't succeed in initializing, try to initialize // waveOut sound, unless DirectSound failed because the hardware is // already allocated (in which case the user has already chosen not // to have sound) - if (!dsound_init && (stat != SIS_NOTAVAIL)) - { - if (snd_firsttime || snd_iswave) - { + if (!dsound_init && (stat != SIS_NOTAVAIL)) { + if (snd_firsttime || snd_iswave) { snd_iswave = SNDDMA_InitWav (); - if (snd_iswave) - { + if (snd_iswave) { if (snd_firsttime) Con_Printf ("Wave sound initialized\n"); - } - else - { + } else { Con_Printf ("Wave sound failed to init\n"); } } @@ -625,8 +584,7 @@ qboolean SNDDMA_Init(void) snd_firsttime = false; - if (!dsound_init && !wav_init) - { + if (!dsound_init && !wav_init) { if (snd_firsttime) Con_Printf ("No sound device initialized\n"); @@ -645,27 +603,25 @@ inside the recirculating dma buffer, so the mixing code will know how many sample are required to fill it up. =============== */ -int SNDDMA_GetDMAPos(void) +int +SNDDMA_GetDMAPos (void) { - MMTIME mmtime; - int s = 0; - DWORD dwWrite; + MMTIME mmtime; + int s = 0; + DWORD dwWrite; - if (dsound_init) - { + if (dsound_init) { mmtime.wType = TIME_SAMPLES; - pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &mmtime.u.sample, &dwWrite); + pDSBuf->lpVtbl->GetCurrentPosition (pDSBuf, &mmtime.u.sample, &dwWrite); s = mmtime.u.sample - mmstarttime.u.sample; - } - else if (wav_init) - { + } else if (wav_init) { s = snd_sent * WAV_BUFFER_SIZE; } s >>= sample16; - s &= (shm->samples-1); + s &= (shm->samples - 1); return s; } @@ -677,54 +633,50 @@ SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ -void SNDDMA_Submit(void) +void +SNDDMA_Submit (void) { - LPWAVEHDR h; - int wResult; + LPWAVEHDR h; + int wResult; if (!wav_init) return; - // + // // find which sound blocks have completed - // - while (1) - { - if ( snd_completed == snd_sent ) - { + // + while (1) { + if (snd_completed == snd_sent) { Con_DPrintf ("Sound overrun\n"); break; } - if ( ! (lpWaveHdr[ snd_completed & WAV_MASK].dwFlags & WHDR_DONE) ) - { + if (!(lpWaveHdr[snd_completed & WAV_MASK].dwFlags & WHDR_DONE)) { break; } - snd_completed++; // this buffer has been played + snd_completed++; // this buffer has been played } - // + // // submit two new sound blocks - // - while (((snd_sent - snd_completed) >> sample16) < 4) - { - h = lpWaveHdr + ( snd_sent&WAV_MASK ); + // + while (((snd_sent - snd_completed) >> sample16) < 4) { + h = lpWaveHdr + (snd_sent & WAV_MASK); snd_sent++; /* * Now the data block can be sent to the output device. The * waveOutWrite function returns immediately and waveform * data is sent to the output device in the background. - */ - wResult = waveOutWrite(hWaveOut, h, sizeof(WAVEHDR)); + */ + wResult = waveOutWrite (hWaveOut, h, sizeof (WAVEHDR)); - if (wResult != MMSYSERR_NOERROR) - { + if (wResult != MMSYSERR_NOERROR) { Con_Printf ("Failed to write block to device\n"); FreeSound (); - return; - } + return; + } } } @@ -735,8 +687,8 @@ SNDDMA_Shutdown Reset the sound device for exiting =============== */ -void SNDDMA_Shutdown(void) +void +SNDDMA_Shutdown (void) { FreeSound (); } - diff --git a/source/sv_ccmds.c b/source/sv_ccmds.c index a9efb41..af828af 100644 --- a/source/sv_ccmds.c +++ b/source/sv_ccmds.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "server.h" #include "crc.h" @@ -50,10 +50,10 @@ #include #endif -qboolean sv_allow_cheats; +qboolean sv_allow_cheats; -int fp_messages=4, fp_persecond=4, fp_secondsdead=10; -char fp_msg[255] = { 0 }; +int fp_messages = 4, fp_persecond = 4, fp_secondsdead = 10; +char fp_msg[255] = { 0 }; extern cvar_t *cl_warncmd; extern redirect_t sv_redirected; @@ -74,30 +74,31 @@ SV_SetMaster_f Make a master server current ==================== */ -void SV_SetMaster_f (void) +void +SV_SetMaster_f (void) { - char data[2]; - int i; + char data[2]; + int i; - memset (&master_adr, 0, sizeof(master_adr)); + memset (&master_adr, 0, sizeof (master_adr)); - for (i=1 ; istate) continue; - if (cl->userid == idnum) - { + if (cl->userid == idnum) { host_client = cl; sv_player = host_client->edict; return true; @@ -223,43 +220,42 @@ SV_God_f Sets client to godmode ================== */ -void SV_God_f (void) +void +SV_God_f (void) { - if (!sv_allow_cheats) - { - Con_Printf ("You must run the server with -cheats to enable this command.\n"); + if (!sv_allow_cheats) { + Con_Printf + ("You must run the server with -cheats to enable this command.\n"); return; } if (!SV_SetPlayer ()) return; - sv_player->v.flags = (int)sv_player->v.flags ^ FL_GODMODE; - if (!((int)sv_player->v.flags & FL_GODMODE) ) + sv_player->v.flags = (int) sv_player->v.flags ^ FL_GODMODE; + if (!((int) sv_player->v.flags & FL_GODMODE)) SV_ClientPrintf (host_client, PRINT_HIGH, "godmode OFF\n"); else SV_ClientPrintf (host_client, PRINT_HIGH, "godmode ON\n"); } -void SV_Noclip_f (void) +void +SV_Noclip_f (void) { - if (!sv_allow_cheats) - { - Con_Printf ("You must run the server with -cheats to enable this command.\n"); + if (!sv_allow_cheats) { + Con_Printf + ("You must run the server with -cheats to enable this command.\n"); return; } if (!SV_SetPlayer ()) return; - if (sv_player->v.movetype != MOVETYPE_NOCLIP) - { + if (sv_player->v.movetype != MOVETYPE_NOCLIP) { sv_player->v.movetype = MOVETYPE_NOCLIP; SV_ClientPrintf (host_client, PRINT_HIGH, "noclip ON\n"); - } - else - { + } else { sv_player->v.movetype = MOVETYPE_WALK; SV_ClientPrintf (host_client, PRINT_HIGH, "noclip OFF\n"); } @@ -271,56 +267,58 @@ void SV_Noclip_f (void) SV_Give_f ================== */ -void SV_Give_f (void) +void +SV_Give_f (void) { - char *t; - int v; - - if (!sv_allow_cheats) - { - Con_Printf ("You must run the server with -cheats to enable this command.\n"); + char *t; + int v; + + if (!sv_allow_cheats) { + Con_Printf + ("You must run the server with -cheats to enable this command.\n"); return; } - + if (!SV_SetPlayer ()) return; - t = Cmd_Argv(2); - v = atoi (Cmd_Argv(3)); - - switch (t[0]) - { - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - sv_player->v.items = (int)sv_player->v.items | IT_SHOTGUN<< (t[0] - '2'); - break; - - case 's': - sv_player->v.ammo_shells = v; - break; - case 'n': - sv_player->v.ammo_nails = v; - break; - case 'r': - sv_player->v.ammo_rockets = v; - break; - case 'h': - sv_player->v.health = v; - break; - case 'c': - sv_player->v.ammo_cells = v; - break; + t = Cmd_Argv (2); + v = atoi (Cmd_Argv (3)); + + switch (t[0]) { + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + sv_player->v.items = + (int) sv_player->v.items | IT_SHOTGUN << (t[0] - '2'); + break; + + case 's': + sv_player->v.ammo_shells = v; + break; + case 'n': + sv_player->v.ammo_nails = v; + break; + case 'r': + sv_player->v.ammo_rockets = v; + break; + case 'h': + sv_player->v.health = v; + break; + case 'c': + sv_player->v.ammo_cells = v; + break; } } // Use this to keep track of current level --KB -static char curlevel[MAX_QPATH] = ""; +static char curlevel[MAX_QPATH] = ""; + /* ====================== SV_Map_f @@ -330,30 +328,29 @@ map command from the console or progs. ====================== */ -void SV_Map_f (void) +void +SV_Map_f (void) { - char level[MAX_QPATH]; - char expanded[MAX_QPATH]; - QFile *f; + char level[MAX_QPATH]; + char expanded[MAX_QPATH]; + QFile *f; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("map : continue game on a new level\n"); return; } - strcpy (level, Cmd_Argv(1)); + strcpy (level, Cmd_Argv (1)); // check to make sure the level exists - snprintf (expanded, sizeof(expanded), "maps/%s.bsp", level); + snprintf (expanded, sizeof (expanded), "maps/%s.bsp", level); COM_FOpenFile (expanded, &f); - if (!f) - { + if (!f) { Con_Printf ("Can't find %s\n", expanded); // If curlevel == level, something is SCREWED! --KB if (stricmp (level, curlevel) == 0) SV_Error ("map: cannot restart level\n"); else - Cbuf_AddText (va("map %s", curlevel)); + Cbuf_AddText (va ("map %s", curlevel)); return; } Qclose (f); @@ -375,25 +372,24 @@ SV_Kick_f Kick a user off of the server ================== */ -void SV_Kick_f (void) +void +SV_Kick_f (void) { - int i; - client_t *cl; - int uid; + int i; + client_t *cl; + int uid; - uid = atoi(Cmd_Argv(1)); - - for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) - { + uid = atoi (Cmd_Argv (1)); + + for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (!cl->state) continue; - if (cl->userid == uid) - { + if (cl->userid == uid) { SV_BroadcastPrintf (PRINT_HIGH, "%s was kicked\n", cl->name); // print directly, because the dropped client won't get the // SV_BroadcastPrintf message SV_ClientPrintf (cl, PRINT_HIGH, "You were kicked from the game\n"); - SV_DropClient (cl); + SV_DropClient (cl); return; } } @@ -407,96 +403,94 @@ void SV_Kick_f (void) SV_Status_f ================ */ -void SV_Status_f (void) +void +SV_Status_f (void) { - int i; - client_t *cl; - float cpu, avg, pak; - char *s; + int i; + client_t *cl; + float cpu, avg, pak; + char *s; - cpu = (svs.stats.latched_active+svs.stats.latched_idle); + cpu = (svs.stats.latched_active + svs.stats.latched_idle); if (cpu) - cpu = 100*svs.stats.latched_active/cpu; - avg = 1000*svs.stats.latched_active / STATFRAMES; - pak = (float)svs.stats.latched_packets/ STATFRAMES; + cpu = 100 * svs.stats.latched_active / cpu; + avg = 1000 * svs.stats.latched_active / STATFRAMES; + pak = (float) svs.stats.latched_packets / STATFRAMES; - Con_Printf ("net address : %s\n",NET_AdrToString (net_local_adr)); - Con_Printf ("cpu utilization : %3i%%\n",(int)cpu); - Con_Printf ("avg response time: %i ms\n",(int)avg); + Con_Printf ("net address : %s\n", NET_AdrToString (net_local_adr)); + Con_Printf ("cpu utilization : %3i%%\n", (int) cpu); + Con_Printf ("avg response time: %i ms\n", (int) avg); Con_Printf ("packets/frame : %5.2f (%d)\n", pak, num_prstr); // min fps lat drp if (sv_redirected != RD_NONE) { // most remote clients are 40 columns - // 0123456789012345678901234567890123456789 + // 0123456789012345678901234567890123456789 Con_Printf ("name userid frags\n"); Con_Printf (" address rate ping drop\n"); Con_Printf (" ---------------- ---- ---- -----\n"); - for (i=0,cl=svs.clients ; istate) continue; Con_Printf ("%-16.16s ", cl->name); - Con_Printf ("%6i %5i", cl->userid, (int)cl->edict->v.frags); + Con_Printf ("%6i %5i", cl->userid, (int) cl->edict->v.frags); if (cl->spectator) - Con_Printf(" (s)\n"); + Con_Printf (" (s)\n"); else - Con_Printf("\n"); + Con_Printf ("\n"); - s = NET_BaseAdrToString ( cl->netchan.remote_address); + s = NET_BaseAdrToString (cl->netchan.remote_address); Con_Printf (" %-16.16s", s); - if (cl->state == cs_connected) - { + if (cl->state == cs_connected) { Con_Printf ("CONNECTING\n"); continue; } - if (cl->state == cs_zombie) - { + if (cl->state == cs_zombie) { Con_Printf ("ZOMBIE\n"); continue; } - Con_Printf ("%4i %4i %5.2f\n" - , (int)(1000*cl->netchan.frame_rate) - , (int)SV_CalcPing (cl) - , 100.0*cl->netchan.drop_count / cl->netchan.incoming_sequence); + Con_Printf ("%4i %4i %5.2f\n", (int) (1000 * cl->netchan.frame_rate) + , (int) SV_CalcPing (cl) + , + 100.0 * cl->netchan.drop_count / + cl->netchan.incoming_sequence); } } else { - Con_Printf ("frags userid address name rate ping drop qport\n"); - Con_Printf ("----- ------ --------------- --------------- ---- ---- ----- -----\n"); - for (i=0,cl=svs.clients ; istate) continue; - Con_Printf ("%5i %6i ", (int)cl->edict->v.frags, cl->userid); + Con_Printf ("%5i %6i ", (int) cl->edict->v.frags, cl->userid); - s = NET_BaseAdrToString ( cl->netchan.remote_address); + s = NET_BaseAdrToString (cl->netchan.remote_address); Con_Printf ("%-15.15s ", s); Con_Printf ("%-15.15s ", cl->name); - if (cl->state == cs_connected) - { + if (cl->state == cs_connected) { Con_Printf ("CONNECTING\n"); continue; } - if (cl->state == cs_zombie) - { + if (cl->state == cs_zombie) { Con_Printf ("ZOMBIE\n"); continue; } - Con_Printf ("%4i %4i %3.1f %4i" - , (int)(1000*cl->netchan.frame_rate) - , (int)SV_CalcPing (cl) - , 100.0*cl->netchan.drop_count / cl->netchan.incoming_sequence - , cl->netchan.qport); + Con_Printf ("%4i %4i %3.1f %4i", + (int) (1000 * cl->netchan.frame_rate), + (int) SV_CalcPing (cl), + 100.0 * cl->netchan.drop_count / + cl->netchan.incoming_sequence, cl->netchan.qport); if (cl->spectator) - Con_Printf(" (s)\n"); + Con_Printf (" (s)\n"); else - Con_Printf("\n"); + Con_Printf ("\n"); } @@ -509,32 +503,31 @@ void SV_Status_f (void) SV_ConSay_f ================== */ -void SV_ConSay_f(void) +void +SV_ConSay_f (void) { - client_t *client; - int j; - char *p; - char text[1024]; + client_t *client; + int j; + char *p; + char text[1024]; if (Cmd_Argc () < 2) return; strcpy (text, "console: "); - p = Cmd_Args(); + p = Cmd_Args (); - if (*p == '"') - { + if (*p == '"') { p++; - p[strlen(p)-1] = 0; + p[strlen (p) - 1] = 0; } - strncat (text, p, sizeof(text) - strlen (text)); + strncat (text, p, sizeof (text) - strlen (text)); - for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) - { + for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) { if (client->state != cs_spawned) continue; - SV_ClientPrintf(client, PRINT_CHAT, "%s\n", text); + SV_ClientPrintf (client, PRINT_CHAT, "%s\n", text); } } @@ -544,12 +537,14 @@ void SV_ConSay_f(void) SV_Heartbeat_f ================== */ -void SV_Heartbeat_f (void) +void +SV_Heartbeat_f (void) { svs.last_heartbeat = -9999; } -void SV_SendServerInfoChange(char *key, char *value) +void +SV_SendServerInfoChange (char *key, char *value) { if (!sv.state) return; @@ -566,39 +561,38 @@ SV_Serverinfo_f Examine or change the serverinfo string =========== */ -char *CopyString(char *s); -void SV_Serverinfo_f (void) +char *CopyString (char *s); +void +SV_Serverinfo_f (void) { - cvar_t *var; + cvar_t *var; - if (Cmd_Argc() == 1) - { + if (Cmd_Argc () == 1) { Con_Printf ("Server info settings:\n"); Info_Print (svs.info); return; } - if (Cmd_Argc() != 3) - { + if (Cmd_Argc () != 3) { Con_Printf ("usage: serverinfo [ ]\n"); return; } - if (Cmd_Argv(1)[0] == '*') - { + if (Cmd_Argv (1)[0] == '*') { Con_Printf ("Star variables cannot be changed.\n"); return; } - Info_SetValueForKey (svs.info, Cmd_Argv(1), Cmd_Argv(2), MAX_SERVERINFO_STRING); + Info_SetValueForKey (svs.info, Cmd_Argv (1), Cmd_Argv (2), + MAX_SERVERINFO_STRING); - // if this is a cvar, change it too - var = Cvar_FindVar (Cmd_Argv(1)); + // if this is a cvar, change it too + var = Cvar_FindVar (Cmd_Argv (1)); if (var) - Cvar_Set (var, Cmd_Argv(2)); + Cvar_Set (var, Cmd_Argv (2)); if (!var || !(var->flags & CVAR_SERVERINFO)) // Cvar_Set will send the change if CVAR_SERVERINFO is set - SV_SendServerInfoChange(Cmd_Argv(1), Cmd_Argv(2)); + SV_SendServerInfoChange (Cmd_Argv (1), Cmd_Argv (2)); } @@ -609,28 +603,27 @@ SV_Serverinfo_f Examine or change the serverinfo string =========== */ -char *CopyString(char *s); -void SV_Localinfo_f (void) +char *CopyString (char *s); +void +SV_Localinfo_f (void) { - if (Cmd_Argc() == 1) - { + if (Cmd_Argc () == 1) { Con_Printf ("Local info settings:\n"); Info_Print (localinfo); return; } - if (Cmd_Argc() != 3) - { + if (Cmd_Argc () != 3) { Con_Printf ("usage: localinfo [ ]\n"); return; } - if (Cmd_Argv(1)[0] == '*') - { + if (Cmd_Argv (1)[0] == '*') { Con_Printf ("Star variables cannot be changed.\n"); return; } - Info_SetValueForKey (localinfo, Cmd_Argv(1), Cmd_Argv(2), MAX_LOCALINFO_STRING); + Info_SetValueForKey (localinfo, Cmd_Argv (1), Cmd_Argv (2), + MAX_LOCALINFO_STRING); } @@ -641,10 +634,10 @@ SV_User_f Examine a users info strings =========== */ -void SV_User_f (void) +void +SV_User_f (void) { - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("Usage: info \n"); return; } @@ -662,27 +655,26 @@ SV_Gamedir Sets the fake *gamedir to a different directory. ================ */ -void SV_Gamedir (void) +void +SV_Gamedir (void) { - char *dir; + char *dir; - if (Cmd_Argc() == 1) - { - Con_Printf ("Current *gamedir: %s\n", Info_ValueForKey (svs.info, "*gamedir")); + if (Cmd_Argc () == 1) { + Con_Printf ("Current *gamedir: %s\n", + Info_ValueForKey (svs.info, "*gamedir")); return; } - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("Usage: sv_gamedir \n"); return; } - dir = Cmd_Argv(1); + dir = Cmd_Argv (1); - if (strstr(dir, "..") || strstr(dir, "/") - || strstr(dir, "\\") || strstr(dir, ":") ) - { + if (strstr (dir, "..") || strstr (dir, "/") + || strstr (dir, "\\") || strstr (dir, ":")) { Con_Printf ("*Gamedir should be a single filename, not a path\n"); return; } @@ -698,56 +690,59 @@ Sets the gamedir and path to a different directory. ================ */ -void SV_Floodprot_f (void) +void +SV_Floodprot_f (void) { - int arg1, arg2, arg3; - - if (Cmd_Argc() == 1) - { + int arg1, arg2, arg3; + + if (Cmd_Argc () == 1) { if (fp_messages) { - Con_Printf ("Current floodprot settings: \nAfter %d msgs per %d seconds, silence for %d seconds\n", - fp_messages, fp_persecond, fp_secondsdead); + Con_Printf + ("Current floodprot settings: \nAfter %d msgs per %d seconds, silence for %d seconds\n", + fp_messages, fp_persecond, fp_secondsdead); return; } else Con_Printf ("No floodprots enabled.\n"); } - if (Cmd_Argc() != 4) - { - Con_Printf ("Usage: floodprot <# of messages> \n"); - Con_Printf ("Use floodprotmsg to set a custom message to say to the flooder.\n"); + if (Cmd_Argc () != 4) { + Con_Printf + ("Usage: floodprot <# of messages> \n"); + Con_Printf + ("Use floodprotmsg to set a custom message to say to the flooder.\n"); return; } - arg1 = atoi(Cmd_Argv(1)); - arg2 = atoi(Cmd_Argv(2)); - arg3 = atoi(Cmd_Argv(3)); + arg1 = atoi (Cmd_Argv (1)); + arg2 = atoi (Cmd_Argv (2)); + arg3 = atoi (Cmd_Argv (3)); - if (arg1<=0 || arg2 <= 0 || arg3<=0) { + if (arg1 <= 0 || arg2 <= 0 || arg3 <= 0) { Con_Printf ("All values must be positive numbers\n"); return; } - + if (arg1 > 10) { Con_Printf ("Can only track up to 10 messages.\n"); return; } - fp_messages = arg1; + fp_messages = arg1; fp_persecond = arg2; fp_secondsdead = arg3; } -void SV_Floodprotmsg_f (void) +void +SV_Floodprotmsg_f (void) { - if (Cmd_Argc() == 1) { - Con_Printf("Current msg: %s\n", fp_msg); + if (Cmd_Argc () == 1) { + Con_Printf ("Current msg: %s\n", fp_msg); return; - } else if (Cmd_Argc() != 2) { - Con_Printf("Usage: floodprotmsg \"\"\n"); + } else if (Cmd_Argc () != 2) { + Con_Printf ("Usage: floodprotmsg \"\"\n"); return; } - snprintf (fp_msg, sizeof(fp_msg), "%s", Cmd_Argv(1)); + snprintf (fp_msg, sizeof (fp_msg), "%s", Cmd_Argv (1)); } /* @@ -755,15 +750,15 @@ void SV_Floodprotmsg_f (void) SV_Snap ================ */ -void SV_Snap (int uid) +void +SV_Snap (int uid) { - client_t *cl; - char pcxname[80]; - char checkname[MAX_OSPATH]; - int i; + client_t *cl; + char pcxname[80]; + char checkname[MAX_OSPATH]; + int i; - for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) - { + for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (!cl->state) continue; if (cl->userid == uid) @@ -774,27 +769,26 @@ void SV_Snap (int uid) return; } - snprintf (pcxname, sizeof(pcxname), "%d-00.pcx", uid); + snprintf (pcxname, sizeof (pcxname), "%d-00.pcx", uid); - snprintf (checkname, sizeof(checkname), "%s/snap", com_gamedir); + snprintf (checkname, sizeof (checkname), "%s/snap", com_gamedir); COM_CreatePath (va ("%s/dummy", checkname)); - - for (i=0 ; i<=99 ; i++) - { - pcxname[strlen(pcxname) - 6] = i/10 + '0'; - pcxname[strlen(pcxname) - 5] = i%10 + '0'; - snprintf (checkname, sizeof(checkname), "%s/snap/%s", com_gamedir, pcxname); - if (Sys_FileTime(checkname) == -1) - break; // file doesn't exist - } - if (i==100) - { - Con_Printf ("Snap: Couldn't create a file, clean some out.\n"); + + for (i = 0; i <= 99; i++) { + pcxname[strlen (pcxname) - 6] = i / 10 + '0'; + pcxname[strlen (pcxname) - 5] = i % 10 + '0'; + snprintf (checkname, sizeof (checkname), "%s/snap/%s", com_gamedir, + pcxname); + if (Sys_FileTime (checkname) == -1) + break; // file doesn't exist + } + if (i == 100) { + Con_Printf ("Snap: Couldn't create a file, clean some out.\n"); return; } - strcpy(cl->uploadfn, checkname); + strcpy (cl->uploadfn, checkname); - memcpy(&cl->snap_from, &net_from, sizeof(net_from)); + memcpy (&cl->snap_from, &net_from, sizeof (net_from)); if (sv_redirected != RD_NONE) cl->remote_snap = true; else @@ -810,19 +804,19 @@ void SV_Snap (int uid) SV_Snap_f ================ */ -void SV_Snap_f (void) +void +SV_Snap_f (void) { - int uid; + int uid; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { Con_Printf ("Usage: snap \n"); return; } - uid = atoi(Cmd_Argv(1)); + uid = atoi (Cmd_Argv (1)); - SV_Snap(uid); + SV_Snap (uid); } /* @@ -830,16 +824,16 @@ void SV_Snap_f (void) SV_Snap ================ */ -void SV_SnapAll_f (void) +void +SV_SnapAll_f (void) { - client_t *cl; - int i; + client_t *cl; + int i; - for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) - { + for (i = 0, cl = svs.clients; i < MAX_CLIENTS; i++, cl++) { if (cl->state < cs_connected || cl->spectator) continue; - SV_Snap(cl->userid); + SV_Snap (cl->userid); } } @@ -848,12 +842,13 @@ void SV_SnapAll_f (void) SV_InitOperatorCommands ================== */ -void SV_InitOperatorCommands (void) +void +SV_InitOperatorCommands (void) { - if (COM_CheckParm ("-cheats")) - { + if (COM_CheckParm ("-cheats")) { sv_allow_cheats = true; - Info_SetValueForStarKey (svs.info, "*cheats", "ON", MAX_SERVERINFO_STRING); + Info_SetValueForStarKey (svs.info, "*cheats", "ON", + MAX_SERVERINFO_STRING); } Cmd_AddCommand ("logfile", SV_Logfile_f); @@ -881,5 +876,8 @@ void SV_InitOperatorCommands (void) Cmd_AddCommand ("floodprotmsg", SV_Floodprotmsg_f); Cmd_AddCommand ("maplist", COM_Maplist_f); - cl_warncmd = Cvar_Get ("cl_warncmd", "1", CVAR_NONE, "dunno. equiv to sh -x?"); // FIXME poor description + cl_warncmd = + Cvar_Get ("cl_warncmd", "1", CVAR_NONE, "dunno. equiv to sh -x?"); // FIXME + // poor + // description } diff --git a/source/sv_cvar.c b/source/sv_cvar.c index c0f2004..eab8efc 100644 --- a/source/sv_cvar.c +++ b/source/sv_cvar.c @@ -27,14 +27,14 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "cvar.h" #include "server.h" -void SV_SendServerInfoChange(char *key, char *value); +void SV_SendServerInfoChange (char *key, char *value); -extern cvar_t *sv_highchars; +extern cvar_t *sv_highchars; /* @@ -45,25 +45,28 @@ extern cvar_t *sv_highchars; */ -void Cvar_Info (cvar_t *var) +void +Cvar_Info (cvar_t *var) { - if (var->flags & CVAR_SERVERINFO) - { + if (var->flags & CVAR_SERVERINFO) { unsigned char info[1024], *p, *c; - if (! sv_highchars->int_val) { - for (p=info, c=var->string; *c && (p-infoint_val) { + for (p = info, c = var->string; + *c && (p - info < sizeof (info) - 1);) { *c &= 0x7f; - if (*c >= 32) *p++ = *c; + if (*c >= 32) + *p++ = *c; c++; } - *p=0; - Info_SetValueForKey (svs.info, var->name, info, MAX_SERVERINFO_STRING); - } - else - Info_SetValueForKey (svs.info, var->name, var->string, MAX_SERVERINFO_STRING); + *p = 0; + Info_SetValueForKey (svs.info, var->name, info, + MAX_SERVERINFO_STRING); + } else + Info_SetValueForKey (svs.info, var->name, var->string, + MAX_SERVERINFO_STRING); SV_SendServerInfoChange (var->name, var->string); -// SV_BroadcastCommand ("fullserverinfo \"%s\"\n", svs.info); +// SV_BroadcastCommand ("fullserverinfo \"%s\"\n", svs.info); } } diff --git a/source/sv_ents.c b/source/sv_ents.c index 084b69c..1f4a5aa 100644 --- a/source/sv_ents.c +++ b/source/sv_ents.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -43,9 +43,11 @@ // LordHavoc: added and removed certain eval_ items // Ender Extends (QSG - Begin) -extern int eval_alpha, eval_scale, eval_glowsize, eval_glowcolor, eval_colormod; +extern int eval_alpha, eval_scale, eval_glowsize, eval_glowcolor, + + eval_colormod; // Ender Extends (QSG - End) -extern eval_t *GETEDICTFIELDVALUE(edict_t *ed, int fieldoffset); +extern eval_t *GETEDICTFIELDVALUE (edict_t *ed, int fieldoffset); /* ============================================================================= @@ -58,38 +60,35 @@ crosses a waterline. ============================================================================= */ -int fatbytes; -byte fatpvs[MAX_MAP_LEAFS/8]; +int fatbytes; +byte fatpvs[MAX_MAP_LEAFS / 8]; -void SV_AddToFatPVS (vec3_t org, mnode_t *node) +void +SV_AddToFatPVS (vec3_t org, mnode_t *node) { - int i; - byte *pvs; - mplane_t *plane; - float d; + int i; + byte *pvs; + mplane_t *plane; + float d; - while (1) - { - // if this is a leaf, accumulate the pvs bits - if (node->contents < 0) - { - if (node->contents != CONTENTS_SOLID) - { - pvs = Mod_LeafPVS ( (mleaf_t *)node, sv.worldmodel); - for (i=0 ; icontents < 0) { + if (node->contents != CONTENTS_SOLID) { + pvs = Mod_LeafPVS ((mleaf_t *) node, sv.worldmodel); + for (i = 0; i < fatbytes; i++) fatpvs[i] |= pvs[i]; } return; } - + plane = node->plane; d = DotProduct (org, plane->normal) - plane->dist; if (d > 8) node = node->children[0]; else if (d < -8) node = node->children[1]; - else - { // go down both + else { // go down both SV_AddToFatPVS (org, node->children[0]); node = node->children[1]; } @@ -104,9 +103,10 @@ Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the given point. ============= */ -byte *SV_FatPVS (vec3_t org) +byte * +SV_FatPVS (vec3_t org) { - fatbytes = (sv.worldmodel->numleafs+31)>>3; + fatbytes = (sv.worldmodel->numleafs + 31) >> 3; memset (fatpvs, 0, fatbytes); SV_AddToFatPVS (org, sv.worldmodel->nodes); return fatpvs; @@ -117,16 +117,16 @@ byte *SV_FatPVS (vec3_t org) // because there can be a lot of nails, there is a special // network protocol for them #define MAX_NAILS 32 -edict_t *nails[MAX_NAILS]; -int numnails; +edict_t *nails[MAX_NAILS]; +int numnails; -extern int sv_nailmodel, sv_supernailmodel, sv_playermodel; +extern int sv_nailmodel, sv_supernailmodel, sv_playermodel; -qboolean SV_AddNailUpdate (edict_t *ent) +qboolean +SV_AddNailUpdate (edict_t *ent) { if (ent->v.modelindex != sv_nailmodel - && ent->v.modelindex != sv_supernailmodel) - return false; + && ent->v.modelindex != sv_supernailmodel) return false; if (numnails == MAX_NAILS) return true; nails[numnails] = ent; @@ -134,12 +134,13 @@ qboolean SV_AddNailUpdate (edict_t *ent) return true; } -void SV_EmitNailUpdate (sizebuf_t *msg) +void +SV_EmitNailUpdate (sizebuf_t *msg) { - byte bits[6]; // [48 bits] xyzpy 12 12 12 4 8 - int n, i; - edict_t *ent; - int x, y, z, p, yaw; + byte bits[6]; // [48 bits] xyzpy 12 12 12 4 8 + int n, i; + edict_t *ent; + int x, y, z, p, yaw; if (!numnails) return; @@ -147,23 +148,22 @@ void SV_EmitNailUpdate (sizebuf_t *msg) MSG_WriteByte (msg, svc_nails); MSG_WriteByte (msg, numnails); - for (n=0 ; nv.origin[0]+4096)>>1; - y = (int)(ent->v.origin[1]+4096)>>1; - z = (int)(ent->v.origin[2]+4096)>>1; - p = (int)(16*ent->v.angles[0]/360)&15; - yaw = (int)(256*ent->v.angles[1]/360)&255; + x = (int) (ent->v.origin[0] + 4096) >> 1; + y = (int) (ent->v.origin[1] + 4096) >> 1; + z = (int) (ent->v.origin[2] + 4096) >> 1; + p = (int) (16 * ent->v.angles[0] / 360) & 15; + yaw = (int) (256 * ent->v.angles[1] / 360) & 255; bits[0] = x; - bits[1] = (x>>8) | (y<<4); - bits[2] = (y>>4); + bits[1] = (x >> 8) | (y << 4); + bits[2] = (y >> 4); bits[3] = z; - bits[4] = (z>>8) | (p<<4); + bits[4] = (z >> 8) | (p << 4); bits[5] = yaw; - for (i=0 ; i<6 ; i++) + for (i = 0; i < 6; i++) MSG_WriteByte (msg, bits[i]); } } @@ -179,63 +179,63 @@ Writes part of a packetentities message. Can delta from either a baseline or a previous packet_entity ================== */ -void SV_WriteDelta (entity_state_t *from, entity_state_t *to, sizebuf_t *msg, qboolean force, int stdver) +void +SV_WriteDelta (entity_state_t *from, entity_state_t *to, sizebuf_t *msg, + qboolean force, int stdver) { - int bits; - int i; - float miss; + int bits; + int i; + float miss; // send an update bits = 0; - - for (i=0 ; i<3 ; i++) - { + + for (i = 0; i < 3; i++) { miss = to->origin[i] - from->origin[i]; - if ( miss < -0.1 || miss > 0.1 ) - bits |= U_ORIGIN1< 0.1) + bits |= U_ORIGIN1 << i; } - if ( to->angles[0] != from->angles[0] ) + if (to->angles[0] != from->angles[0]) bits |= U_ANGLE1; - - if ( to->angles[1] != from->angles[1] ) + + if (to->angles[1] != from->angles[1]) bits |= U_ANGLE2; - - if ( to->angles[2] != from->angles[2] ) + + if (to->angles[2] != from->angles[2]) bits |= U_ANGLE3; - - if ( to->colormap != from->colormap ) + + if (to->colormap != from->colormap) bits |= U_COLORMAP; - - if ( to->skinnum != from->skinnum ) + + if (to->skinnum != from->skinnum) bits |= U_SKIN; - - if ( to->frame != from->frame ) + + if (to->frame != from->frame) bits |= U_FRAME; - - if ( to->effects != from->effects ) + + if (to->effects != from->effects) bits |= U_EFFECTS; - - if ( to->modelindex != from->modelindex ) + + if (to->modelindex != from->modelindex) bits |= U_MODEL; // LordHavoc: cleaned up Endy's coding style, and added missing effects // Ender (QSG - Begin) - if (stdver > 1) - { - if (to->alpha != from->alpha) + if (stdver > 1) { + if (to->alpha != from->alpha) bits |= U_ALPHA; - if (to->scale != from->scale) + if (to->scale != from->scale) bits |= U_SCALE; - if (to->glowsize != from->glowsize) + if (to->glowsize != from->glowsize) bits |= U_GLOWSIZE; - if (to->glowcolor != from->glowcolor) + if (to->glowcolor != from->glowcolor) bits |= U_GLOWCOLOR; - if (to->colormod != from->colormod) + if (to->colormod != from->colormod) bits |= U_COLORMOD; } @@ -251,34 +251,34 @@ void SV_WriteDelta (entity_state_t *from, entity_state_t *to, sizebuf_t *msg, qb if (to->flags & U_SOLID) bits |= U_SOLID; - // + // // write the message - // + // if (!to->number) SV_Error ("Unset entity number"); if (to->number >= 512) SV_Error ("Entity number >= 512"); if (!bits && !force) - return; // nothing to send! - i = to->number | (bits&~511); + return; // nothing to send! + i = to->number | (bits & ~511); if (i & U_REMOVE) Sys_Error ("U_REMOVE"); MSG_WriteShort (msg, i); - + if (bits & U_MOREBITS) - MSG_WriteByte (msg, bits&255); + MSG_WriteByte (msg, bits & 255); // LordHavoc: cleaned up Endy's tabs // Ender (QSG - Begin) if (bits & U_EXTEND1) - MSG_WriteByte (msg, bits>>16); + MSG_WriteByte (msg, bits >> 16); if (bits & U_EXTEND2) - MSG_WriteByte (msg, bits>>24); + MSG_WriteByte (msg, bits >> 24); // Ender (QSG - End) if (bits & U_MODEL) - MSG_WriteByte (msg, to->modelindex); + MSG_WriteByte (msg, to->modelindex); if (bits & U_FRAME) MSG_WriteByte (msg, to->frame); if (bits & U_COLORMAP) @@ -288,34 +288,35 @@ void SV_WriteDelta (entity_state_t *from, entity_state_t *to, sizebuf_t *msg, qb if (bits & U_EFFECTS) MSG_WriteByte (msg, to->effects); if (bits & U_ORIGIN1) - MSG_WriteCoord (msg, to->origin[0]); + MSG_WriteCoord (msg, to->origin[0]); if (bits & U_ANGLE1) - MSG_WriteAngle(msg, to->angles[0]); + MSG_WriteAngle (msg, to->angles[0]); if (bits & U_ORIGIN2) MSG_WriteCoord (msg, to->origin[1]); if (bits & U_ANGLE2) - MSG_WriteAngle(msg, to->angles[1]); + MSG_WriteAngle (msg, to->angles[1]); if (bits & U_ORIGIN3) MSG_WriteCoord (msg, to->origin[2]); if (bits & U_ANGLE3) - MSG_WriteAngle(msg, to->angles[2]); + MSG_WriteAngle (msg, to->angles[2]); - // LordHavoc: cleaned up Endy's tabs, rearranged bytes, and implemented missing effects + // LordHavoc: cleaned up Endy's tabs, rearranged bytes, and implemented + // missing effects // Ender (QSG - Begin) if (bits & U_ALPHA) - MSG_WriteByte(msg, to->alpha); + MSG_WriteByte (msg, to->alpha); if (bits & U_SCALE) - MSG_WriteByte(msg, to->scale); + MSG_WriteByte (msg, to->scale); if (bits & U_EFFECTS2) - MSG_WriteByte(msg, (to->effects >> 8)); + MSG_WriteByte (msg, (to->effects >> 8)); if (bits & U_GLOWSIZE) - MSG_WriteByte(msg, to->glowsize); + MSG_WriteByte (msg, to->glowsize); if (bits & U_GLOWCOLOR) - MSG_WriteByte(msg, to->glowcolor); + MSG_WriteByte (msg, to->glowcolor); if (bits & U_COLORMOD) - MSG_WriteByte(msg, to->colormod); + MSG_WriteByte (msg, to->colormod); if (bits & U_FRAME2) - MSG_WriteByte(msg, (to->frame >> 8)); + MSG_WriteByte (msg, (to->frame >> 8)); // Ender (QSG - End) } @@ -327,28 +328,26 @@ Writes a delta update of a packet_entities_t to the message. ============= */ -void SV_EmitPacketEntities (client_t *client, packet_entities_t *to, sizebuf_t *msg) +void +SV_EmitPacketEntities (client_t *client, packet_entities_t *to, sizebuf_t *msg) { - edict_t *ent; - client_frame_t *fromframe; + edict_t *ent; + client_frame_t *fromframe; packet_entities_t *from; - int oldindex, newindex; - int oldnum, newnum; - int oldmax; + int oldindex, newindex; + int oldnum, newnum; + int oldmax; // this is the frame that we are going to delta update from - if (client->delta_sequence != -1) - { + if (client->delta_sequence != -1) { fromframe = &client->frames[client->delta_sequence & UPDATE_MASK]; from = &fromframe->entities; oldmax = from->num_entities; MSG_WriteByte (msg, svc_deltapacketentities); MSG_WriteByte (msg, client->delta_sequence); - } - else - { - oldmax = 0; // no delta update + } else { + oldmax = 0; // no delta update from = NULL; MSG_WriteByte (msg, svc_packetentities); @@ -357,32 +356,33 @@ void SV_EmitPacketEntities (client_t *client, packet_entities_t *to, sizebuf_t * newindex = 0; oldindex = 0; //Con_Printf ("---%i to %i ----\n", client->delta_sequence & UPDATE_MASK -// , client->netchan.outgoing_sequence & UPDATE_MASK); - while (newindex < to->num_entities || oldindex < oldmax) - { - newnum = newindex >= to->num_entities ? 9999 : to->entities[newindex].number; +// , client->netchan.outgoing_sequence & UPDATE_MASK); + while (newindex < to->num_entities || oldindex < oldmax) { + newnum = + newindex >= to->num_entities ? 9999 : to->entities[newindex].number; oldnum = oldindex >= oldmax ? 9999 : from->entities[oldindex].number; - if (newnum == oldnum) - { // delta update from old position + if (newnum == oldnum) { // delta update from old position //Con_Printf ("delta %i\n", newnum); - SV_WriteDelta (&from->entities[oldindex], &to->entities[newindex], msg, false, client->stdver); + SV_WriteDelta (&from->entities[oldindex], &to->entities[newindex], + msg, false, client->stdver); oldindex++; newindex++; continue; } - if (newnum < oldnum) - { // this is a new entity, send it from the baseline - ent = EDICT_NUM(newnum); + if (newnum < oldnum) { // this is a new entity, send it from + // the baseline + ent = EDICT_NUM (newnum); //Con_Printf ("baseline %i\n", newnum); - SV_WriteDelta (&ent->baseline, &to->entities[newindex], msg, true, client->stdver); + SV_WriteDelta (&ent->baseline, &to->entities[newindex], msg, true, + client->stdver); newindex++; continue; } - if (newnum > oldnum) - { // the old entity isn't present in the new message + if (newnum > oldnum) { // the old entity isn't present in + // the new message //Con_Printf ("remove %i\n", oldnum); MSG_WriteShort (msg, oldnum | U_REMOVE); oldindex++; @@ -390,7 +390,7 @@ void SV_EmitPacketEntities (client_t *client, packet_entities_t *to, sizebuf_t * } } - MSG_WriteShort (msg, 0); // end of packetentities + MSG_WriteShort (msg, 0); // end of packetentities } /* @@ -399,17 +399,18 @@ SV_WritePlayersToClient ============= */ -void SV_WritePlayersToClient (client_t *client, edict_t *clent, byte *pvs, sizebuf_t *msg) +void +SV_WritePlayersToClient (client_t *client, edict_t *clent, byte * pvs, + sizebuf_t *msg) { - int i, j; - client_t *cl; - edict_t *ent; - int msec; - usercmd_t cmd; - int pflags; + int i, j; + client_t *cl; + edict_t *ent; + int msec; + usercmd_t cmd; + int pflags; - for (j=0,cl=svs.clients ; jstate != cs_spawned) continue; @@ -417,26 +418,25 @@ void SV_WritePlayersToClient (client_t *client, edict_t *clent, byte *pvs, sizeb // ZOID visibility tracking if (ent != clent && - !(client->spec_track && client->spec_track - 1 == j)) - { + !(client->spec_track && client->spec_track - 1 == j)) { if (cl->spectator) continue; // ignore if not touching a PV leaf - for (i=0 ; i < ent->num_leafs ; i++) - if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i]&7) )) + for (i = 0; i < ent->num_leafs; i++) + if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i] & 7))) break; if (i == ent->num_leafs) - continue; // not visible + continue; // not visible } - + pflags = PF_MSEC | PF_COMMAND; - + if (ent->v.modelindex != sv_playermodel) pflags |= PF_MODEL; - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) if (ent->v.velocity[i]) - pflags |= PF_VELOCITY1<v.effects) pflags |= PF_EFFECTS; if (ent->v.skin) @@ -446,57 +446,53 @@ void SV_WritePlayersToClient (client_t *client, edict_t *clent, byte *pvs, sizeb if (ent->v.mins[2] != -24) pflags |= PF_GIB; - if (cl->spectator) - { // only sent origin and velocity to spectators + if (cl->spectator) { // only sent origin and velocity to + // spectators pflags &= PF_VELOCITY1 | PF_VELOCITY2 | PF_VELOCITY3; - } - else if (ent == clent) - { // don't send a lot of data on personal entity - pflags &= ~(PF_MSEC|PF_COMMAND); + } else if (ent == clent) { // don't send a lot of data on + // personal entity + pflags &= ~(PF_MSEC | PF_COMMAND); if (ent->v.weaponframe) pflags |= PF_WEAPONFRAME; } if (client->spec_track && client->spec_track - 1 == j && - ent->v.weaponframe) - pflags |= PF_WEAPONFRAME; + ent->v.weaponframe) pflags |= PF_WEAPONFRAME; MSG_WriteByte (msg, svc_playerinfo); MSG_WriteByte (msg, j); MSG_WriteShort (msg, pflags); - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) MSG_WriteCoord (msg, ent->v.origin[i]); - + MSG_WriteByte (msg, ent->v.frame); - if (pflags & PF_MSEC) - { - msec = 1000*(sv.time - cl->localtime); + if (pflags & PF_MSEC) { + msec = 1000 * (sv.time - cl->localtime); if (msec > 255) msec = 255; MSG_WriteByte (msg, msec); } - - if (pflags & PF_COMMAND) - { + + if (pflags & PF_COMMAND) { cmd = cl->lastcmd; - if (ent->v.health <= 0) - { // don't show the corpse looking around... + if (ent->v.health <= 0) { // don't show the corpse looking + // around... cmd.angles[0] = 0; cmd.angles[1] = ent->v.angles[1]; cmd.angles[0] = 0; } - cmd.buttons = 0; // never send buttons - cmd.impulse = 0; // never send impulses + cmd.buttons = 0; // never send buttons + cmd.impulse = 0; // never send impulses MSG_WriteDeltaUsercmd (msg, &nullcmd, &cmd); } - for (i=0 ; i<3 ; i++) - if (pflags & (PF_VELOCITY1<v.velocity[i]); if (pflags & PF_MODEL) @@ -524,16 +520,17 @@ a svc_nails message and svc_playerinfo messages ============= */ -void SV_WriteEntitiesToClient (client_t *client, sizebuf_t *msg) +void +SV_WriteEntitiesToClient (client_t *client, sizebuf_t *msg) { - int e, i; - byte *pvs; - vec3_t org; - edict_t *ent; - packet_entities_t *pack; - edict_t *clent; - client_frame_t *frame; - entity_state_t *state; + int e, i; + byte *pvs; + vec3_t org; + edict_t *ent; + packet_entities_t *pack; + edict_t *clent; + client_frame_t *frame; + entity_state_t *state; // this is the frame we are creating frame = &client->frames[client->netchan.incoming_sequence & UPDATE_MASK]; @@ -545,33 +542,34 @@ void SV_WriteEntitiesToClient (client_t *client, sizebuf_t *msg) // send over the players in the PVS SV_WritePlayersToClient (client, clent, pvs, msg); - - // put other visible entities into either a packet_entities or a nails message + + // put other visible entities into either a packet_entities or a nails + // message pack = &frame->entities; pack->num_entities = 0; numnails = 0; - for (e=MAX_CLIENTS+1, ent=EDICT_NUM(e) ; ev.modelindex || !*PR_GetString(ent->v.model)) + if (!ent->v.modelindex || !*PR_GetString (ent->v.model)) continue; // ignore if not touching a PV leaf - for (i=0 ; i < ent->num_leafs ; i++) - if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i]&7) )) + for (i = 0; i < ent->num_leafs; i++) + if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i] & 7))) break; - + if (i == ent->num_leafs) - continue; // not visible + continue; // not visible if (SV_AddNailUpdate (ent)) - continue; // added to the special update list + continue; // added to the special update list // add to the packetentities if (pack->num_entities == MAX_PACKET_ENTITIES) - continue; // all full + continue; // all full state = &pack->entities[pack->num_entities]; pack->num_entities++; @@ -587,30 +585,40 @@ void SV_WriteEntitiesToClient (client_t *client, sizebuf_t *msg) state->effects = ent->v.effects; // LordHavoc: cleaned up Endy's coding style, shortened the code, - // and implemented missing effects + // and implemented missing effects // Ender: EXTEND (QSG - Begin) { - eval_t *val; - state->alpha = 255; - state->scale = 16; - state->glowsize = 0; - state->glowcolor = 254; - state->colormod = 255; + eval_t *val; - if ((val = GETEDICTFIELDVALUE(ent, eval_alpha)) && val->_float != 0) - state->alpha = bound(0, val->_float, 1) * 255.0; + state->alpha = 255; + state->scale = 16; + state->glowsize = 0; + state->glowcolor = 254; + state->colormod = 255; - if ((val = GETEDICTFIELDVALUE(ent, eval_scale)) && val->_float != 0) - state->scale = bound(0, val->_float, 15.9375) * 16.0; + if ((val = GETEDICTFIELDVALUE (ent, eval_alpha)) + && val->_float != 0) state->alpha = + bound (0, val->_float, 1) * 255.0; - if ((val = GETEDICTFIELDVALUE(ent, eval_glowsize)) && val->_float != 0) - state->glowsize = bound(-1024, (int)val->_float, 1016) >> 3; + if ((val = GETEDICTFIELDVALUE (ent, eval_scale)) + && val->_float != 0) state->scale = + bound (0, val->_float, 15.9375) * 16.0; - if ((val = GETEDICTFIELDVALUE(ent, eval_glowcolor)) && val->_float != 0) + if ((val = GETEDICTFIELDVALUE (ent, eval_glowsize)) + && val->_float != 0) + state->glowsize = bound (-1024, (int) val->_float, 1016) >> 3; + + if ((val = GETEDICTFIELDVALUE (ent, eval_glowcolor)) + && val->_float != 0) state->glowcolor = (int) val->_float; - if ((val = GETEDICTFIELDVALUE(ent, eval_colormod)) && (val->vector[0] != 0 || val->vector[1] != 0 || val->vector[2] != 0)) - state->colormod = ((int) (bound(0, val->vector[0], 1) * 7.0) << 5) | ((int) (bound(0, val->vector[1], 1) * 7.0) << 2) | (int) (bound(0, val->vector[2], 1) * 3.0); + if ((val = GETEDICTFIELDVALUE (ent, eval_colormod)) + && (val->vector[0] != 0 || val->vector[1] != 0 + || val->vector[2] != 0)) + state->colormod = + ((int) (bound (0, val->vector[0], 1) * 7.0) << 5) | + ((int) (bound (0, val->vector[1], 1) * 7.0) << 2) | + (int) (bound (0, val->vector[2], 1) * 3.0); } // Ender: EXTEND (QSG - End) } @@ -623,4 +631,3 @@ void SV_WriteEntitiesToClient (client_t *client, sizebuf_t *msg) // now add the specialized nail update SV_EmitNailUpdate (msg); } - diff --git a/source/sv_init.c b/source/sv_init.c index de59747..bffd472 100644 --- a/source/sv_init.c +++ b/source/sv_init.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "server.h" #include "crc.h" @@ -38,11 +38,11 @@ #include -server_t sv; // local server +server_t sv; // local server -char localmodels[MAX_MODELS][5]; // inline model names for precache +char localmodels[MAX_MODELS][5]; // inline model names for precache -char localinfo[MAX_LOCALINFO_STRING+1]; // local game info +char localinfo[MAX_LOCALINFO_STRING + 1]; // local game info /* ================ @@ -50,17 +50,18 @@ SV_ModelIndex ================ */ -int SV_ModelIndex (char *name) +int +SV_ModelIndex (char *name) { - int i; - + int i; + if (!name || !name[0]) return 0; - for (i=0 ; ifree) continue; // create baselines for all player slots, @@ -111,23 +113,20 @@ void SV_CreateBaseline (void) if (entnum > MAX_CLIENTS && !svent->v.modelindex) continue; - // - // create entity baseline - // + // + // create entity baseline + // VectorCopy (svent->v.origin, svent->baseline.origin); VectorCopy (svent->v.angles, svent->baseline.angles); svent->baseline.frame = svent->v.frame; svent->baseline.skinnum = svent->v.skin; - if (entnum > 0 && entnum <= MAX_CLIENTS) - { + if (entnum > 0 && entnum <= MAX_CLIENTS) { svent->baseline.colormap = entnum; - svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl"); - } - else - { + svent->baseline.modelindex = SV_ModelIndex ("progs/player.mdl"); + } else { svent->baseline.colormap = 0; svent->baseline.modelindex = - SV_ModelIndex(PR_GetString(svent->v.model)); + SV_ModelIndex (PR_GetString (svent->v.model)); } // LordHavoc: setup baseline to include new effects svent->baseline.alpha = 255; @@ -136,26 +135,25 @@ void SV_CreateBaseline (void) svent->baseline.glowcolor = 254; svent->baseline.colormap = 255; - // + // // flush the signon message out to a seperate buffer if // nearly full - // + // SV_FlushSignon (); - // + // // add to the message - // - MSG_WriteByte (&sv.signon,svc_spawnbaseline); - MSG_WriteShort (&sv.signon,entnum); + // + MSG_WriteByte (&sv.signon, svc_spawnbaseline); + MSG_WriteShort (&sv.signon, entnum); MSG_WriteByte (&sv.signon, svent->baseline.modelindex); MSG_WriteByte (&sv.signon, svent->baseline.frame); MSG_WriteByte (&sv.signon, svent->baseline.colormap); MSG_WriteByte (&sv.signon, svent->baseline.skinnum); - for (i=0 ; i<3 ; i++) - { - MSG_WriteCoord(&sv.signon, svent->baseline.origin[i]); - MSG_WriteAngle(&sv.signon, svent->baseline.angles[i]); + for (i = 0; i < 3; i++) { + MSG_WriteCoord (&sv.signon, svent->baseline.origin[i]); + MSG_WriteAngle (&sv.signon, svent->baseline.angles[i]); } } } @@ -170,18 +168,18 @@ and each client for saving across the transition to another level ================ */ -void SV_SaveSpawnparms (void) +void +SV_SaveSpawnparms (void) { - int i, j; + int i, j; if (!sv.state) - return; // no progs loaded yet + return; // no progs loaded yet // serverflags is the only game related thing maintained svs.serverflags = pr_global_struct->serverflags; - for (i=0, host_client = svs.clients ; istate != cs_spawned) continue; @@ -189,9 +187,9 @@ void SV_SaveSpawnparms (void) host_client->state = cs_connected; // call the progs to get default spawn parms for the new client - pr_global_struct->self = EDICT_TO_PROG(host_client->edict); + pr_global_struct->self = EDICT_TO_PROG (host_client->edict); PR_ExecuteProgram (pr_global_struct->SetChangeParms); - for (j=0 ; jspawn_parms[j] = (&pr_global_struct->parm1)[j]; } } @@ -204,89 +202,86 @@ Expands the PVS and calculates the PHS (Potentially Hearable Set) ================ */ -void SV_CalcPHS (void) +void +SV_CalcPHS (void) { - int rowbytes, rowwords; - int i, j, k, l, index, num; - int bitbyte; - unsigned int *dest, *src; - byte *scan; - int count, vcount; + int rowbytes, rowwords; + int i, j, k, l, index, num; + int bitbyte; + unsigned int *dest, *src; + byte *scan; + int count, vcount; Con_Printf ("Building PHS...\n"); num = sv.worldmodel->numleafs; - rowwords = (num+31)>>5; - rowbytes = rowwords*4; + rowwords = (num + 31) >> 5; + rowbytes = rowwords * 4; - sv.pvs = Hunk_Alloc (rowbytes*num); + sv.pvs = Hunk_Alloc (rowbytes * num); scan = sv.pvs; vcount = 0; - for (i=0 ; ileafs+i, sv.worldmodel), - rowbytes); + for (i = 0; i < num; i++, scan += rowbytes) { + memcpy (scan, Mod_LeafPVS (sv.worldmodel->leafs + i, sv.worldmodel), + rowbytes); if (i == 0) continue; - for (j=0 ; j>3] & (1<<(j&7)) ) - { + for (j = 0; j < num; j++) { + if (scan[j >> 3] & (1 << (j & 7))) { vcount++; } } } - sv.phs = Hunk_Alloc (rowbytes*num); + sv.phs = Hunk_Alloc (rowbytes * num); count = 0; scan = sv.pvs; - dest = (unsigned int *)sv.phs; - for (i=0 ; i= num) continue; - src = (unsigned int *)sv.pvs + index*rowwords; - for (l=0 ; l>3] & (1<<(j&7)) ) + for (j = 0; j < num; j++) + if (((byte *) dest)[j >> 3] & (1 << (j & 7))) count++; } - Con_Printf ("Average leafs visible / hearable / total: %i / %i / %i\n" - , vcount/num, count/num, num); + Con_Printf ("Average leafs visible / hearable / total: %i / %i / %i\n", + vcount / num, count / num, num); } -unsigned int SV_CheckModel(char *mdl) +unsigned int +SV_CheckModel (char *mdl) { - byte stackbuf[1024]; // avoid dirtying the cache heap - byte *buf; + byte stackbuf[1024]; // avoid dirtying the cache heap + byte *buf; unsigned short crc; -// int len; - buf = (byte *)COM_LoadStackFile (mdl, stackbuf, sizeof(stackbuf)); - crc = CRC_Block(buf, com_filesize); -// for (len = com_filesize; len; len--, buf++) -// CRC_ProcessByte(&crc, *buf); +// int len; + + buf = (byte *) COM_LoadStackFile (mdl, stackbuf, sizeof (stackbuf)); + crc = CRC_Block (buf, com_filesize); +// for (len = com_filesize; len; len--, buf++) +// CRC_ProcessByte(&crc, *buf); return crc; } @@ -301,17 +296,19 @@ clients along with it. This is only called from the SV_Map_f() function. ================ */ -void SV_SpawnServer (char *server) +void +SV_SpawnServer (char *server) { - edict_t *ent; - int i; + edict_t *ent; + int i; + + Con_DPrintf ("SpawnServer: %s\n", server); - Con_DPrintf ("SpawnServer: %s\n",server); - SV_SaveSpawnparms (); - svs.spawncount++; // any partially connected client will be - // restarted + svs.spawncount++; // any partially connected client + // will be + // restarted sv.state = ss_dead; @@ -319,22 +316,22 @@ void SV_SpawnServer (char *server) Hunk_FreeToLowMark (host_hunklevel); // wipe the entire per-level structure - memset (&sv, 0, sizeof(sv)); + memset (&sv, 0, sizeof (sv)); - sv.datagram.maxsize = sizeof(sv.datagram_buf); + sv.datagram.maxsize = sizeof (sv.datagram_buf); sv.datagram.data = sv.datagram_buf; sv.datagram.allowoverflow = true; - sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf); + sv.reliable_datagram.maxsize = sizeof (sv.reliable_datagram_buf); sv.reliable_datagram.data = sv.reliable_datagram_buf; - - sv.multicast.maxsize = sizeof(sv.multicast_buf); + + sv.multicast.maxsize = sizeof (sv.multicast_buf); sv.multicast.data = sv.multicast_buf; - - sv.master.maxsize = sizeof(sv.master_buf); + + sv.master.maxsize = sizeof (sv.master_buf); sv.master.data = sv.master_buf; - - sv.signon.maxsize = sizeof(sv.signon_buffers[0]); + + sv.signon.maxsize = sizeof (sv.signon_buffers[0]); sv.signon.data = sv.signon_buffers[0]; sv.num_signon_buffers = 1; @@ -345,64 +342,62 @@ void SV_SpawnServer (char *server) PR_LoadProgs (); // allocate edicts - sv.edicts = Hunk_AllocName (MAX_EDICTS*pr_edict_size, "edicts"); - + sv.edicts = Hunk_AllocName (MAX_EDICTS * pr_edict_size, "edicts"); + // leave slots at start for clients only - sv.num_edicts = MAX_CLIENTS+1; - for (i=0 ; inumsubmodels ; i++) - { - sv.model_precache[1+i] = localmodels[i]; - sv.models[i+1] = Mod_ForName (localmodels[i], false); + for (i = 1; i < sv.worldmodel->numsubmodels; i++) { + sv.model_precache[1 + i] = localmodels[i]; + sv.models[i + 1] = Mod_ForName (localmodels[i], false); } - //check player/eyes models for hacks - sv.model_player_checksum = SV_CheckModel("progs/player.mdl"); - sv.eyes_player_checksum = SV_CheckModel("progs/eyes.mdl"); + // check player/eyes models for hacks + sv.model_player_checksum = SV_CheckModel ("progs/player.mdl"); + sv.eyes_player_checksum = SV_CheckModel ("progs/eyes.mdl"); - // + // // spawn the rest of the entities on the map - // + // // precache and static commands can be issued during // map initialization sv.state = ss_loading; - ent = EDICT_NUM(0); + ent = EDICT_NUM (0); ent->free = false; - ent->v.model = PR_SetString(sv.worldmodel->name); - ent->v.modelindex = 1; // world model + ent->v.model = PR_SetString (sv.worldmodel->name); + ent->v.modelindex = 1; // world model ent->v.solid = SOLID_BSP; ent->v.movetype = MOVETYPE_PUSH; - pr_global_struct->mapname = PR_SetString(sv.name); + pr_global_struct->mapname = PR_SetString (sv.name); // serverflags are for cross level information (sigils) pr_global_struct->serverflags = svs.serverflags; - + // run the frame start qc function to let progs check cvars SV_ProgStartFrame (); @@ -415,20 +410,19 @@ void SV_SpawnServer (char *server) // all spawning is completed, any further precache statements // or prog writes to the signon message are errors sv.state = ss_active; - + // run two frames to allow everything to settle sv_frametime = 0.1; SV_Physics (); SV_Physics (); // save movement vars - SV_SetMoveVars(); + SV_SetMoveVars (); // create a baseline for more efficient communications SV_CreateBaseline (); - sv.signon_buffer_size[sv.num_signon_buffers-1] = sv.signon.cursize; + sv.signon_buffer_size[sv.num_signon_buffers - 1] = sv.signon.cursize; Info_SetValueForKey (svs.info, "map", sv.name, MAX_SERVERINFO_STRING); Con_DPrintf ("Server spawned.\n"); } - diff --git a/source/sv_main.c b/source/sv_main.c index 3dea195..d1e0b4b 100644 --- a/source/sv_main.c +++ b/source/sv_main.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -54,88 +54,98 @@ #include "world.h" quakeparms_t host_parms; -qboolean host_initialized; // true if into command execution +qboolean host_initialized; // true if into command execution -double sv_frametime; -double realtime; // without any filtering or bounding +double sv_frametime; +double realtime; // without any filtering or bounding -int host_hunklevel; +int host_hunklevel; -netadr_t master_adr[MAX_MASTERS]; // address of group servers +netadr_t master_adr[MAX_MASTERS]; // address of group servers -client_t *host_client; // current client +client_t *host_client; // current client // DoS protection // FLOOD_PING, FLOOD_LOG, FLOOD_CONNECT, FLOOD_STATUS, FLOOD_RCON, FLOOD_BAN // fixme: these default values need to be tweaked after more testing -double netdosexpire[DOSFLOODCMDS] = { 1, 1, 2, 0.9, 1, 5 }; -double netdosvalues[DOSFLOODCMDS] = { 12, 1, 3, 1, 1, 1 }; +double netdosexpire[DOSFLOODCMDS] = { 1, 1, 2, 0.9, 1, 5 }; +double netdosvalues[DOSFLOODCMDS] = { 12, 1, 3, 1, 1, 1 }; -cvar_t *sv_netdosprotect; // tone down DoS from quake servers +cvar_t *sv_netdosprotect; // tone down DoS from quake servers -cvar_t *sv_allow_status; -cvar_t *sv_allow_log; -cvar_t *sv_allow_ping; +cvar_t *sv_allow_status; +cvar_t *sv_allow_log; +cvar_t *sv_allow_ping; -cvar_t *fs_globalcfg; +cvar_t *fs_globalcfg; -cvar_t *sv_mintic; // bound the size of the -cvar_t *sv_maxtic; // physics time tic +cvar_t *sv_mintic; // bound the size of the +cvar_t *sv_maxtic; // physics time tic -cvar_t *developer; // show extra messages +cvar_t *developer; // show extra messages -cvar_t *timeout; // seconds without any message -cvar_t *zombietime; // seconds to sink messages after disconnect +cvar_t *timeout; // seconds without any message +cvar_t *zombietime; // seconds to sink messages after -cvar_t *rcon_password; // password for remote server commands + // disconnect -cvar_t *password; // password for entering the game -cvar_t *spectator_password; // password for entering as a spectator +cvar_t *rcon_password; // password for remote server -cvar_t *allow_download; -cvar_t *allow_download_skins; -cvar_t *allow_download_models; -cvar_t *allow_download_sounds; -cvar_t *allow_download_maps; + // commands -cvar_t *sv_highchars; +cvar_t *password; // password for entering the game +cvar_t *spectator_password; // password for entering as a -cvar_t *sv_phs; + // spectator -cvar_t *pausable; +cvar_t *allow_download; +cvar_t *allow_download_skins; +cvar_t *allow_download_models; +cvar_t *allow_download_sounds; +cvar_t *allow_download_maps; -extern cvar_t *sv_timekick; -extern cvar_t *sv_timekick_fuzz; -extern cvar_t *sv_timekick_interval; +cvar_t *sv_highchars; -cvar_t *sv_minqfversion; // Minimum QF version allowed to connect -cvar_t *sv_maxrate; // Maximum allowable rate (silently capped) +cvar_t *sv_phs; -cvar_t *sv_timestamps; -cvar_t *sv_timefmt; +cvar_t *pausable; + +extern cvar_t *sv_timekick; +extern cvar_t *sv_timekick_fuzz; +extern cvar_t *sv_timekick_interval; + +cvar_t *sv_minqfversion; // Minimum QF version allowed to + + // connect +cvar_t *sv_maxrate; // Maximum allowable rate (silently + + // capped) + +cvar_t *sv_timestamps; +cvar_t *sv_timefmt; // // game rules mirrored in svs.info // -cvar_t *fraglimit; -cvar_t *timelimit; -cvar_t *teamplay; -cvar_t *samelevel; -cvar_t *maxclients; -cvar_t *maxspectators; -cvar_t *deathmatch; // 0, 1, or 2 -cvar_t *spawn; -cvar_t *watervis; +cvar_t *fraglimit; +cvar_t *timelimit; +cvar_t *teamplay; +cvar_t *samelevel; +cvar_t *maxclients; +cvar_t *maxspectators; +cvar_t *deathmatch; // 0, 1, or 2 +cvar_t *spawn; +cvar_t *watervis; -cvar_t *hostname; +cvar_t *hostname; -QFile *sv_logfile; -QFile *sv_fraglogfile; +QFile *sv_logfile; +QFile *sv_fraglogfile; -void SV_AcceptClient (netadr_t adr, int userid, char *userinfo); -void Master_Shutdown (void); -void PR_Init_Cvars (void); +void SV_AcceptClient (netadr_t adr, int userid, char *userinfo); +void Master_Shutdown (void); +void PR_Init_Cvars (void); //============================================================================ @@ -317,7 +327,7 @@ SV_FullClientUpdate (client_t *client, sizebuf_t *buf) i = client - svs.clients; -// Sys_Printf("SV_FullClientUpdate: Updated frags for client %d\n", i); +// Sys_Printf("SV_FullClientUpdate: Updated frags for client %d\n", i); MSG_WriteByte (buf, svc_updatefrags); MSG_WriteByte (buf, i); @@ -532,10 +542,10 @@ SVC_Log (void) seq = -1; if (seq == svs.logsequence - 1 || !sv_fraglogfile) { // they allready - // have this - // data, or we - // aren't logging - // frags + // have this + // data, or we + // aren't logging + // frags data[0] = A2A_NACK; NET_SendPacket (1, data, net_from); return; @@ -545,7 +555,8 @@ SVC_Log (void) NET_AdrToString (net_from)); // snprintf (data, sizeof (data), "stdlog %i\n", svs.logsequence-1); - // strncat (data, (char *)svs.log_buf[((svs.logsequence-1)&1)], sizeof(data) - strlen (data)); + // strncat (data, (char *)svs.log_buf[((svs.logsequence-1)&1)], + // sizeof(data) - strlen (data)); snprintf (data, sizeof (data), "stdlog %i\n%s", svs.logsequence - 1, (char *) svs.log_buf[((svs.logsequence - 1) & 1)]); @@ -673,7 +684,7 @@ SVC_DirectConnect (void) } s = Info_ValueForKey (userinfo, "*qf_version"); - if ((!s[0]) || sv_minqfversion->value) { // kick old clients? + if ((!s[0]) || sv_minqfversion->value) { // kick old clients? if (ver_compare (s, sv_minqfversion->string) < 0) { Con_Printf ("%s: Version %s is less than minimum version %s.\n", NET_AdrToString (net_from), s, sv_minqfversion->string); @@ -790,7 +801,6 @@ SVC_DirectConnect (void) Con_Printf ("WARNING: miscounted available clients\n"); return; } - // build a new connection // accept the new client // this is the only place a client_t is ever initialized @@ -1210,7 +1220,7 @@ SV_SendBan (void) data[0] = data[1] = data[2] = data[3] = 0xff; data[4] = A2C_PRINT; data[5] = 0; - strncat (data, "\nbanned.\n", sizeof(data) - strlen (data)); + strncat (data, "\nbanned.\n", sizeof (data) - strlen (data)); NET_SendPacket (strlen (data), data, net_from); } @@ -1282,8 +1292,8 @@ SV_ReadPackets (void) cl->netchan.remote_address.port = net_from.port; } if (Netchan_Process (&cl->netchan)) { // this is a valid, - // sequenced packet, so - // process it + // sequenced packet, so + // process it svs.stats.packets++; good = true; cl->send_message = true; // reply at end of frame @@ -1518,7 +1528,8 @@ SV_InitLocal (void) "Time cheat check interval"); sv_minqfversion = - Cvar_Get ("sv_minqfversion", "0", CVAR_SERVERINFO, "Minimum QF version on client"); + Cvar_Get ("sv_minqfversion", "0", CVAR_SERVERINFO, + "Minimum QF version on client"); sv_maxrate = Cvar_Get ("sv_maxrate", "0", CVAR_SERVERINFO, "Maximum allowable rate"); diff --git a/source/sv_misc.c b/source/sv_misc.c index f4c1478..81bc6f2 100644 --- a/source/sv_misc.c +++ b/source/sv_misc.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "client.h" #include "server.h" @@ -42,12 +42,12 @@ client_static_t cls; void -Draw_BeginDisc(void) +Draw_BeginDisc (void) { } void -Draw_EndDisc(void) +Draw_EndDisc (void) { } diff --git a/source/sv_model.c b/source/sv_model.c index 72ccba8..d051248 100644 --- a/source/sv_model.c +++ b/source/sv_model.c @@ -28,7 +28,7 @@ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "server.h" #include "crc.h" @@ -39,35 +39,35 @@ #include "sys.h" #include "pmove.h" -const int mod_lightmap_bytes=1; -mplane_t frustum[4]; +const int mod_lightmap_bytes = 1; +mplane_t frustum[4]; -void Mod_LoadBrushModel (model_t *mod, void *buffer); +void Mod_LoadBrushModel (model_t *mod, void *buffer); void -Mod_LoadLighting(lump_t *l) +Mod_LoadLighting (lump_t *l) { } void -Mod_LoadAliasModel(model_t *mod, void *buf) +Mod_LoadAliasModel (model_t *mod, void *buf) { Mod_LoadBrushModel (mod, buf); } void -Mod_LoadSpriteModel(model_t *mod, void *buf) +Mod_LoadSpriteModel (model_t *mod, void *buf) { Mod_LoadBrushModel (mod, buf); } void -R_InitSky(struct texture_s *mt) +R_InitSky (struct texture_s *mt) { } void -Mod_ProcessTexture(miptex_t *mx, texture_t *tx) +Mod_ProcessTexture (miptex_t *mx, texture_t *tx) { } diff --git a/source/sv_move.c b/source/sv_move.c index 765f711..94ae244 100644 --- a/source/sv_move.c +++ b/source/sv_move.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "server.h" #include "crc.h" @@ -52,15 +52,16 @@ is not a staircase. ============= */ -int c_yes, c_no; +int c_yes, c_no; -qboolean SV_CheckBottom (edict_t *ent) +qboolean +SV_CheckBottom (edict_t *ent) { - vec3_t mins, maxs, start, stop; - trace_t trace; - int x, y; - float mid, bottom; - + vec3_t mins, maxs, start, stop; + trace_t trace; + int x, y; + float mid, bottom; + VectorAdd (ent->v.origin, ent->v.mins, mins); VectorAdd (ent->v.origin, ent->v.maxs, maxs); @@ -68,9 +69,8 @@ qboolean SV_CheckBottom (edict_t *ent) // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; - for (x=0 ; x<=1 ; x++) - for (y=0 ; y<=1 ; y++) - { + for (x = 0; x <= 1; x++) + for (y = 0; y <= 1; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; if (SV_PointContents (start) != CONTENTS_SOLID) @@ -78,34 +78,33 @@ qboolean SV_CheckBottom (edict_t *ent) } c_yes++; - return true; // we got out easy + return true; // we got out easy -realcheck: + realcheck: c_no++; // // check it for real... // start[2] = mins[2]; - + // the midpoint must be within 16 of the bottom - start[0] = stop[0] = (mins[0] + maxs[0])*0.5; - start[1] = stop[1] = (mins[1] + maxs[1])*0.5; - stop[2] = start[2] - 2*STEPSIZE; + start[0] = stop[0] = (mins[0] + maxs[0]) * 0.5; + start[1] = stop[1] = (mins[1] + maxs[1]) * 0.5; + stop[2] = start[2] - 2 * STEPSIZE; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; - -// the corners must be within 16 of the midpoint - for (x=0 ; x<=1 ; x++) - for (y=0 ; y<=1 ; y++) - { + +// the corners must be within 16 of the midpoint + for (x = 0; x <= 1; x++) + for (y = 0; y <= 1; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; - + trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); - + if (trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) @@ -127,94 +126,91 @@ possible, no move is done, false is returned, and pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ -qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) +qboolean +SV_movestep (edict_t *ent, vec3_t move, qboolean relink) { - float dz; - vec3_t oldorg, neworg, end; - trace_t trace; - int i; - edict_t *enemy; + float dz; + vec3_t oldorg, neworg, end; + trace_t trace; + int i; + edict_t *enemy; -// try the move +// try the move VectorCopy (ent->v.origin, oldorg); VectorAdd (ent->v.origin, move, neworg); // flying monsters don't step up - if ( (int)ent->v.flags & (FL_SWIM | FL_FLY) ) - { - // try one move with vertical motion, then one without - for (i=0 ; i<2 ; i++) - { + if ((int) ent->v.flags & (FL_SWIM | FL_FLY)) { + // try one move with vertical motion, then one without + for (i = 0; i < 2; i++) { VectorAdd (ent->v.origin, move, neworg); - enemy = PROG_TO_EDICT(ent->v.enemy); - if (i == 0 && enemy != sv.edicts) - { - dz = ent->v.origin[2] - PROG_TO_EDICT(ent->v.enemy)->v.origin[2]; + enemy = PROG_TO_EDICT (ent->v.enemy); + if (i == 0 && enemy != sv.edicts) { + dz = + ent->v.origin[2] - + PROG_TO_EDICT (ent->v.enemy)->v.origin[2]; if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, ent); - - if (trace.fraction == 1) - { - if ( ((int)ent->v.flags & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY ) - return false; // swim monster left water - + trace = + SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, + ent); + + if (trace.fraction == 1) { + if (((int) ent->v.flags & FL_SWIM) + && SV_PointContents (trace.endpos) == CONTENTS_EMPTY) + return false; // swim monster left water + VectorCopy (trace.endpos, ent->v.origin); if (relink) SV_LinkEdict (ent, true); return true; } - + if (enemy == sv.edicts) break; } - + return false; } - // push down from a step height above the wished position neworg[2] += STEPSIZE; VectorCopy (neworg, end); - end[2] -= STEPSIZE*2; + end[2] -= STEPSIZE * 2; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid) return false; - if (trace.startsolid) - { + if (trace.startsolid) { neworg[2] -= STEPSIZE; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid || trace.startsolid) return false; } - if (trace.fraction == 1) - { - // if monster had the ground pulled out, go ahead and fall - if ( (int)ent->v.flags & FL_PARTIALGROUND ) - { + if (trace.fraction == 1) { + // if monster had the ground pulled out, go ahead and fall + if ((int) ent->v.flags & FL_PARTIALGROUND) { VectorAdd (ent->v.origin, move, ent->v.origin); if (relink) SV_LinkEdict (ent, true); - ent->v.flags = (int)ent->v.flags & ~FL_ONGROUND; -// Con_Printf ("fall down\n"); + ent->v.flags = (int) ent->v.flags & ~FL_ONGROUND; +// Con_Printf ("fall down\n"); return true; } - - return false; // walked off an edge - } + return false; // walked off an edge + } // check point traces down for dangling corners VectorCopy (trace.endpos, ent->v.origin); - - if (!SV_CheckBottom (ent)) - { - if ( (int)ent->v.flags & FL_PARTIALGROUND ) - { // entity had floor mostly pulled out from underneath it + + if (!SV_CheckBottom (ent)) { + if ((int) ent->v.flags & FL_PARTIALGROUND) { // entity had floor + // mostly pulled out + // from underneath it // and is trying to correct if (relink) SV_LinkEdict (ent, true); @@ -224,12 +220,11 @@ qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) return false; } - if ( (int)ent->v.flags & FL_PARTIALGROUND ) - { -// Con_Printf ("back on ground\n"); - ent->v.flags = (int)ent->v.flags & ~FL_PARTIALGROUND; + if ((int) ent->v.flags & FL_PARTIALGROUND) { +// Con_Printf ("back on ground\n"); + ent->v.flags = (int) ent->v.flags & ~FL_PARTIALGROUND; } - ent->v.groundentity = EDICT_TO_PROG(trace.ent); + ent->v.groundentity = EDICT_TO_PROG (trace.ent); // the move is ok if (relink) @@ -249,33 +244,33 @@ facing it. ====================== */ -void PF_changeyaw (void); -qboolean SV_StepDirection (edict_t *ent, float yaw, float dist) +void PF_changeyaw (void); +qboolean +SV_StepDirection (edict_t *ent, float yaw, float dist) { - vec3_t move, oldorigin; - float delta; - + vec3_t move, oldorigin; + float delta; + ent->v.ideal_yaw = yaw; - PF_changeyaw(); - - yaw = yaw*M_PI*2 / 360; - move[0] = cos(yaw)*dist; - move[1] = sin(yaw)*dist; + PF_changeyaw (); + + yaw = yaw * M_PI * 2 / 360; + move[0] = cos (yaw) * dist; + move[1] = sin (yaw) * dist; move[2] = 0; VectorCopy (ent->v.origin, oldorigin); - if (SV_movestep (ent, move, false)) - { + if (SV_movestep (ent, move, false)) { delta = ent->v.angles[YAW] - ent->v.ideal_yaw; - if (delta > 45 && delta < 315) - { // not turned far enough, so don't take the step + if (delta > 45 && delta < 315) { // not turned far enough, so + // don't take the step VectorCopy (oldorigin, ent->v.origin); } SV_LinkEdict (ent, true); return true; } SV_LinkEdict (ent, true); - + return false; } @@ -285,11 +280,12 @@ SV_FixCheckBottom ====================== */ -void SV_FixCheckBottom (edict_t *ent) +void +SV_FixCheckBottom (edict_t *ent) { -// Con_Printf ("SV_FixCheckBottom\n"); - - ent->v.flags = (int)ent->v.flags | FL_PARTIALGROUND; +// Con_Printf ("SV_FixCheckBottom\n"); + + ent->v.flags = (int) ent->v.flags | FL_PARTIALGROUND; } @@ -301,78 +297,72 @@ SV_NewChaseDir ================ */ #define DI_NODIR -1 -void SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist) +void +SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist) { - float deltax,deltay; - float d[3]; - float tdir, olddir, turnaround; + float deltax, deltay; + float d[3]; + float tdir, olddir, turnaround; - olddir = anglemod( (int)(actor->v.ideal_yaw/45)*45 ); - turnaround = anglemod(olddir - 180); + olddir = anglemod ((int) (actor->v.ideal_yaw / 45) * 45); + turnaround = anglemod (olddir - 180); deltax = enemy->v.origin[0] - actor->v.origin[0]; deltay = enemy->v.origin[1] - actor->v.origin[1]; - if (deltax>10) - d[1]= 0; - else if (deltax<-10) - d[1]= 180; + if (deltax > 10) + d[1] = 0; + else if (deltax < -10) + d[1] = 180; else - d[1]= DI_NODIR; - if (deltay<-10) - d[2]= 270; - else if (deltay>10) - d[2]= 90; + d[1] = DI_NODIR; + if (deltay < -10) + d[2] = 270; + else if (deltay > 10) + d[2] = 90; else - d[2]= DI_NODIR; + d[2] = DI_NODIR; // try direct route - if (d[1] != DI_NODIR && d[2] != DI_NODIR) - { + if (d[1] != DI_NODIR && d[2] != DI_NODIR) { if (d[1] == 0) tdir = d[2] == 90 ? 45 : 315; else tdir = d[2] == 90 ? 135 : 215; - - if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) + + if (tdir != turnaround && SV_StepDirection (actor, tdir, dist)) return; } - // try other directions - if ( ((rand()&3) & 1) || abs(deltay)>abs(deltax)) - { - tdir=d[1]; - d[1]=d[2]; - d[2]=tdir; + if (((rand () & 3) & 1) || abs (deltay) > abs (deltax)) { + tdir = d[1]; + d[1] = d[2]; + d[2] = tdir; } - if (d[1]!=DI_NODIR && d[1]!=turnaround - && SV_StepDirection(actor, d[1], dist)) - return; + if (d[1] != DI_NODIR && d[1] != turnaround + && SV_StepDirection (actor, d[1], dist)) return; - if (d[2]!=DI_NODIR && d[2]!=turnaround - && SV_StepDirection(actor, d[2], dist)) - return; + if (d[2] != DI_NODIR && d[2] != turnaround + && SV_StepDirection (actor, d[2], dist)) return; /* there is no direct path to the player, so pick another direction */ - if (olddir!=DI_NODIR && SV_StepDirection(actor, olddir, dist)) - return; + if (olddir != DI_NODIR && SV_StepDirection (actor, olddir, dist)) + return; - if (rand()&1) /*randomly determine direction of search*/ - { - for (tdir=0 ; tdir<=315 ; tdir += 45) - if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) - return; - } - else - { - for (tdir=315 ; tdir >=0 ; tdir -= 45) - if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) - return; + if (rand () & 1) { /* randomly determine direction of + search */ + for (tdir = 0; tdir <= 315; tdir += 45) + if (tdir != turnaround && SV_StepDirection (actor, tdir, dist)) + return; + } else { + for (tdir = 315; tdir >= 0; tdir -= 45) + if (tdir != turnaround && SV_StepDirection (actor, tdir, dist)) + return; } - if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist) ) - return; + if (turnaround != DI_NODIR && SV_StepDirection (actor, turnaround, dist)) + return; actor->v.ideal_yaw = olddir; // can't move @@ -390,12 +380,12 @@ SV_CloseEnough ====================== */ -qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) +qboolean +SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) { - int i; - - for (i=0 ; i<3 ; i++) - { + int i; + + for (i = 0; i < 3; i++) { if (goal->v.absmin[i] > ent->v.absmax[i] + dist) return false; if (goal->v.absmax[i] < ent->v.absmin[i] - dist) @@ -410,30 +400,26 @@ SV_MoveToGoal ====================== */ -void SV_MoveToGoal (void) +void +SV_MoveToGoal (void) { - edict_t *ent, *goal; - float dist; - - ent = PROG_TO_EDICT(pr_global_struct->self); - goal = PROG_TO_EDICT(ent->v.goalentity); - dist = G_FLOAT(OFS_PARM0); + edict_t *ent, *goal; + float dist; - if ( !( (int)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) - { - G_FLOAT(OFS_RETURN) = 0; + ent = PROG_TO_EDICT (pr_global_struct->self); + goal = PROG_TO_EDICT (ent->v.goalentity); + dist = G_FLOAT (OFS_PARM0); + + if (!((int) ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) { + G_FLOAT (OFS_RETURN) = 0; return; } - // if the next step hits the enemy, return immediately - if ( PROG_TO_EDICT(ent->v.enemy) != sv.edicts && SV_CloseEnough (ent, goal, dist) ) - return; + if (PROG_TO_EDICT (ent->v.enemy) != sv.edicts + && SV_CloseEnough (ent, goal, dist)) return; // bump around... - if ( (rand()&3)==1 || - !SV_StepDirection (ent, ent->v.ideal_yaw, dist)) - { + if ((rand () & 3) == 1 || !SV_StepDirection (ent, ent->v.ideal_yaw, dist)) { SV_NewChaseDir (ent, goal, dist); } } - diff --git a/source/sv_nchan.c b/source/sv_nchan.c index de7c5dd..f445999 100644 --- a/source/sv_nchan.c +++ b/source/sv_nchan.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -42,17 +42,17 @@ #include "pmove.h" // check to see if client block will fit, if not, rotate buffers -void ClientReliableCheckBlock(client_t *cl, int maxsize) +void +ClientReliableCheckBlock (client_t *cl, int maxsize) { if (cl->num_backbuf || - cl->netchan.message.cursize > - cl->netchan.message.maxsize - maxsize - 1) { + cl->netchan.message.cursize > cl->netchan.message.maxsize - maxsize - 1) { // we would probably overflow the buffer, save it for next if (!cl->num_backbuf) { - memset(&cl->backbuf, 0, sizeof(cl->backbuf)); + memset (&cl->backbuf, 0, sizeof (cl->backbuf)); cl->backbuf.allowoverflow = true; cl->backbuf.data = cl->backbuf_data[0]; - cl->backbuf.maxsize = sizeof(cl->backbuf_data[0]); + cl->backbuf.maxsize = sizeof (cl->backbuf_data[0]); cl->backbuf_size[0] = 0; cl->num_backbuf++; } @@ -60,14 +60,16 @@ void ClientReliableCheckBlock(client_t *cl, int maxsize) if (cl->backbuf.cursize > cl->backbuf.maxsize - maxsize - 1) { if (cl->num_backbuf == MAX_BACK_BUFFERS) { Con_Printf ("WARNING: MAX_BACK_BUFFERS for %s\n", cl->name); - cl->backbuf.cursize = 0; // don't overflow without allowoverflow set - cl->netchan.message.overflowed = true; // this will drop the client + cl->backbuf.cursize = 0; // don't overflow without + // allowoverflow set + cl->netchan.message.overflowed = true; // this will drop the + // client return; } - memset(&cl->backbuf, 0, sizeof(cl->backbuf)); + memset (&cl->backbuf, 0, sizeof (cl->backbuf)); cl->backbuf.allowoverflow = true; cl->backbuf.data = cl->backbuf_data[cl->num_backbuf]; - cl->backbuf.maxsize = sizeof(cl->backbuf_data[cl->num_backbuf]); + cl->backbuf.maxsize = sizeof (cl->backbuf_data[cl->num_backbuf]); cl->backbuf_size[cl->num_backbuf] = 0; cl->num_backbuf++; } @@ -75,111 +77,124 @@ void ClientReliableCheckBlock(client_t *cl, int maxsize) } // begin a client block, estimated maximum size -void ClientReliableWrite_Begin(client_t *cl, int c, int maxsize) +void +ClientReliableWrite_Begin (client_t *cl, int c, int maxsize) { - ClientReliableCheckBlock(cl, maxsize); - ClientReliableWrite_Byte(cl, c); + ClientReliableCheckBlock (cl, maxsize); + ClientReliableWrite_Byte (cl, c); } -void ClientReliable_FinishWrite(client_t *cl) +void +ClientReliable_FinishWrite (client_t *cl) { if (cl->num_backbuf) { cl->backbuf_size[cl->num_backbuf - 1] = cl->backbuf.cursize; if (cl->backbuf.overflowed) { - Con_Printf ("WARNING: backbuf [%d] reliable overflow for %s\n",cl->num_backbuf,cl->name); - cl->netchan.message.overflowed = true; // this will drop the client + Con_Printf ("WARNING: backbuf [%d] reliable overflow for %s\n", + cl->num_backbuf, cl->name); + cl->netchan.message.overflowed = true; // this will drop the + // client } } } -void ClientReliableWrite_Angle(client_t *cl, float f) +void +ClientReliableWrite_Angle (client_t *cl, float f) { if (cl->num_backbuf) { - MSG_WriteAngle(&cl->backbuf, f); - ClientReliable_FinishWrite(cl); + MSG_WriteAngle (&cl->backbuf, f); + ClientReliable_FinishWrite (cl); } else - MSG_WriteAngle(&cl->netchan.message, f); + MSG_WriteAngle (&cl->netchan.message, f); } -void ClientReliableWrite_Angle16(client_t *cl, float f) +void +ClientReliableWrite_Angle16 (client_t *cl, float f) { if (cl->num_backbuf) { - MSG_WriteAngle16(&cl->backbuf, f); - ClientReliable_FinishWrite(cl); + MSG_WriteAngle16 (&cl->backbuf, f); + ClientReliable_FinishWrite (cl); } else - MSG_WriteAngle16(&cl->netchan.message, f); + MSG_WriteAngle16 (&cl->netchan.message, f); } -void ClientReliableWrite_Byte(client_t *cl, int c) +void +ClientReliableWrite_Byte (client_t *cl, int c) { if (cl->num_backbuf) { - MSG_WriteByte(&cl->backbuf, c); - ClientReliable_FinishWrite(cl); + MSG_WriteByte (&cl->backbuf, c); + ClientReliable_FinishWrite (cl); } else - MSG_WriteByte(&cl->netchan.message, c); + MSG_WriteByte (&cl->netchan.message, c); } -void ClientReliableWrite_Char(client_t *cl, int c) +void +ClientReliableWrite_Char (client_t *cl, int c) { if (cl->num_backbuf) { - MSG_WriteChar(&cl->backbuf, c); - ClientReliable_FinishWrite(cl); + MSG_WriteChar (&cl->backbuf, c); + ClientReliable_FinishWrite (cl); } else - MSG_WriteChar(&cl->netchan.message, c); + MSG_WriteChar (&cl->netchan.message, c); } -void ClientReliableWrite_Float(client_t *cl, float f) +void +ClientReliableWrite_Float (client_t *cl, float f) { if (cl->num_backbuf) { - MSG_WriteFloat(&cl->backbuf, f); - ClientReliable_FinishWrite(cl); + MSG_WriteFloat (&cl->backbuf, f); + ClientReliable_FinishWrite (cl); } else - MSG_WriteFloat(&cl->netchan.message, f); + MSG_WriteFloat (&cl->netchan.message, f); } -void ClientReliableWrite_Coord(client_t *cl, float f) +void +ClientReliableWrite_Coord (client_t *cl, float f) { if (cl->num_backbuf) { - MSG_WriteCoord(&cl->backbuf, f); - ClientReliable_FinishWrite(cl); + MSG_WriteCoord (&cl->backbuf, f); + ClientReliable_FinishWrite (cl); } else - MSG_WriteCoord(&cl->netchan.message, f); + MSG_WriteCoord (&cl->netchan.message, f); } -void ClientReliableWrite_Long(client_t *cl, int c) +void +ClientReliableWrite_Long (client_t *cl, int c) { if (cl->num_backbuf) { - MSG_WriteLong(&cl->backbuf, c); - ClientReliable_FinishWrite(cl); + MSG_WriteLong (&cl->backbuf, c); + ClientReliable_FinishWrite (cl); } else - MSG_WriteLong(&cl->netchan.message, c); + MSG_WriteLong (&cl->netchan.message, c); } -void ClientReliableWrite_Short(client_t *cl, int c) +void +ClientReliableWrite_Short (client_t *cl, int c) { if (cl->num_backbuf) { - MSG_WriteShort(&cl->backbuf, c); - ClientReliable_FinishWrite(cl); + MSG_WriteShort (&cl->backbuf, c); + ClientReliable_FinishWrite (cl); } else - MSG_WriteShort(&cl->netchan.message, c); + MSG_WriteShort (&cl->netchan.message, c); } -void ClientReliableWrite_String(client_t *cl, char *s) +void +ClientReliableWrite_String (client_t *cl, char *s) { if (cl->num_backbuf) { - MSG_WriteString(&cl->backbuf, s); - ClientReliable_FinishWrite(cl); + MSG_WriteString (&cl->backbuf, s); + ClientReliable_FinishWrite (cl); } else - MSG_WriteString(&cl->netchan.message, s); + MSG_WriteString (&cl->netchan.message, s); } -void ClientReliableWrite_SZ(client_t *cl, void *data, int len) +void +ClientReliableWrite_SZ (client_t *cl, void *data, int len) { if (cl->num_backbuf) { - SZ_Write(&cl->backbuf, data, len); - ClientReliable_FinishWrite(cl); + SZ_Write (&cl->backbuf, data, len); + ClientReliable_FinishWrite (cl); } else - SZ_Write(&cl->netchan.message, data, len); + SZ_Write (&cl->netchan.message, data, len); } - diff --git a/source/sv_phys.c b/source/sv_phys.c index 3d2b439..3257a00 100644 --- a/source/sv_phys.c +++ b/source/sv_phys.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "server.h" #include "crc.h" @@ -56,22 +56,22 @@ solid_edge items only clip against bsp models. */ -cvar_t *sv_maxvelocity; +cvar_t *sv_maxvelocity; -cvar_t *sv_gravity; -cvar_t *sv_stopspeed; -cvar_t *sv_maxspeed; -cvar_t *sv_spectatormaxspeed; -cvar_t *sv_accelerate; -cvar_t *sv_airaccelerate; -cvar_t *sv_wateraccelerate; -cvar_t *sv_friction; -cvar_t *sv_waterfriction; +cvar_t *sv_gravity; +cvar_t *sv_stopspeed; +cvar_t *sv_maxspeed; +cvar_t *sv_spectatormaxspeed; +cvar_t *sv_accelerate; +cvar_t *sv_airaccelerate; +cvar_t *sv_wateraccelerate; +cvar_t *sv_friction; +cvar_t *sv_waterfriction; #define MOVE_EPSILON 0.01 -void SV_Physics_Toss (edict_t *ent); +void SV_Physics_Toss (edict_t *ent); /* ================ @@ -79,21 +79,19 @@ SV_CheckAllEnts ================ */ void -SV_CheckAllEnts ( void ) +SV_CheckAllEnts (void) { - int e; - edict_t *check; + int e; + edict_t *check; // see if any solid entities are inside the final position - check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) continue; if (check->v.movetype == MOVETYPE_PUSH - || check->v.movetype == MOVETYPE_NONE - || check->v.movetype == MOVETYPE_NOCLIP) - continue; + || check->v.movetype == MOVETYPE_NONE + || check->v.movetype == MOVETYPE_NOCLIP) continue; if (SV_TestEntityPosition (check)) Con_Printf ("entity in invalid position\n"); @@ -106,33 +104,34 @@ SV_CheckVelocity ================ */ void -SV_CheckVelocity ( edict_t *ent ) +SV_CheckVelocity (edict_t *ent) { - int i; - float wishspeed; // 1999-10-18 SV_MAXVELOCITY fix by Maddes + int i; + float wishspeed; // 1999-10-18 SV_MAXVELOCITY fix by + + // Maddes // // bound velocity // - for (i=0 ; i<3 ; i++) - { - if (IS_NAN(ent->v.velocity[i])) - { - Con_Printf ("Got a NaN velocity on %s\n", PR_GetString(ent->v.classname)); + for (i = 0; i < 3; i++) { + if (IS_NAN (ent->v.velocity[i])) { + Con_Printf ("Got a NaN velocity on %s\n", + PR_GetString (ent->v.classname)); ent->v.velocity[i] = 0; } - if (IS_NAN(ent->v.origin[i])) - { - Con_Printf ("Got a NaN origin on %s\n", PR_GetString(ent->v.classname)); + if (IS_NAN (ent->v.origin[i])) { + Con_Printf ("Got a NaN origin on %s\n", + PR_GetString (ent->v.classname)); ent->v.origin[i] = 0; } } // 1999-10-18 SV_MAXVELOCITY fix by Maddes start - wishspeed = Length(ent->v.velocity); - if (wishspeed > sv_maxvelocity->value) - { - VectorScale (ent->v.velocity, sv_maxvelocity->value/wishspeed, ent->v.velocity); + wishspeed = Length (ent->v.velocity); + if (wishspeed > sv_maxvelocity->value) { + VectorScale (ent->v.velocity, sv_maxvelocity->value / wishspeed, + ent->v.velocity); } // 1999-10-18 SV_MAXVELOCITY fix by Maddes end } @@ -148,12 +147,11 @@ Returns false if the entity removed itself. ============= */ qboolean -SV_RunThink ( edict_t *ent ) +SV_RunThink (edict_t *ent) { - float thinktime; + float thinktime; - do - { + do { thinktime = ent->v.nextthink; if (thinktime <= 0) return true; @@ -161,13 +159,13 @@ SV_RunThink ( edict_t *ent ) return true; if (thinktime < sv.time) - thinktime = sv.time; // don't let things stay in the past. - // it is possible to start that way - // by a trigger with a local time. + thinktime = sv.time; // don't let things stay in the past. + // it is possible to start that way + // by a trigger with a local time. ent->v.nextthink = 0; pr_global_struct->time = thinktime; - pr_global_struct->self = EDICT_TO_PROG(ent); - pr_global_struct->other = EDICT_TO_PROG(sv.edicts); + pr_global_struct->self = EDICT_TO_PROG (ent); + pr_global_struct->other = EDICT_TO_PROG (sv.edicts); PR_ExecuteProgram (ent->v.think); if (ent->free) @@ -185,25 +183,23 @@ Two entities have touched, so run their touch functions ================== */ void -SV_Impact ( edict_t *e1, edict_t *e2 ) +SV_Impact (edict_t *e1, edict_t *e2) { - int old_self, old_other; + int old_self, old_other; old_self = pr_global_struct->self; old_other = pr_global_struct->other; pr_global_struct->time = sv.time; - if (e1->v.touch && e1->v.solid != SOLID_NOT) - { - pr_global_struct->self = EDICT_TO_PROG(e1); - pr_global_struct->other = EDICT_TO_PROG(e2); + if (e1->v.touch && e1->v.solid != SOLID_NOT) { + pr_global_struct->self = EDICT_TO_PROG (e1); + pr_global_struct->other = EDICT_TO_PROG (e2); PR_ExecuteProgram (e1->v.touch); } - if (e2->v.touch && e2->v.solid != SOLID_NOT) - { - pr_global_struct->self = EDICT_TO_PROG(e2); - pr_global_struct->other = EDICT_TO_PROG(e1); + if (e2->v.touch && e2->v.solid != SOLID_NOT) { + pr_global_struct->self = EDICT_TO_PROG (e2); + pr_global_struct->other = EDICT_TO_PROG (e1); PR_ExecuteProgram (e2->v.touch); } @@ -223,23 +219,22 @@ returns the blocked flags (1 = floor, 2 = step / wall) #define STOP_EPSILON 0.1 int -ClipVelocity ( vec3_t in, vec3_t normal, vec3_t out, float overbounce ) +ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce) { - float backoff; - float change; - int i, blocked; + float backoff; + float change; + int i, blocked; blocked = 0; if (normal[2] > 0) - blocked |= 1; // floor + blocked |= 1; // floor if (!normal[2]) - blocked |= 2; // step + blocked |= 2; // step backoff = DotProduct (in, normal) * overbounce; - for (i=0 ; i<3 ; i++) - { - change = normal[i]*backoff; + for (i = 0; i < 3; i++) { + change = normal[i] * backoff; out[i] = in[i] - change; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; @@ -263,19 +258,19 @@ If steptrace is not NULL, the trace of any vertical wall hit will be stored */ #define MAX_CLIP_PLANES 5 int -SV_FlyMove ( edict_t *ent, float time, trace_t *steptrace ) +SV_FlyMove (edict_t *ent, float time, trace_t *steptrace) { - int bumpcount, numbumps; - vec3_t dir; - float d; - int numplanes; - vec3_t planes[MAX_CLIP_PLANES]; - vec3_t primal_velocity, original_velocity, new_velocity; - int i, j; - trace_t trace; - vec3_t end; - float time_left; - int blocked; + int bumpcount, numbumps; + vec3_t dir; + float d; + int numplanes; + vec3_t planes[MAX_CLIP_PLANES]; + vec3_t primal_velocity, original_velocity, new_velocity; + int i, j; + trace_t trace; + vec3_t end; + float time_left; + int blocked; numbumps = 4; @@ -286,61 +281,55 @@ SV_FlyMove ( edict_t *ent, float time, trace_t *steptrace ) time_left = time; - for (bumpcount=0 ; bumpcountv.origin[i] + time_left * ent->v.velocity[i]; - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); + trace = + SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); - if (trace.allsolid) - { // entity is trapped in another solid + if (trace.allsolid) { // entity is trapped in another solid VectorCopy (vec3_origin, ent->v.velocity); return 3; } - if (trace.fraction > 0) - { // actually covered some distance + if (trace.fraction > 0) { // actually covered some distance VectorCopy (trace.endpos, ent->v.origin); VectorCopy (ent->v.velocity, original_velocity); numplanes = 0; } if (trace.fraction == 1) - break; // moved the entire distance + break; // moved the entire distance if (!trace.ent) SV_Error ("SV_FlyMove: !trace.ent"); - if (trace.plane.normal[2] > 0.7) - { - blocked |= 1; // floor - if ((trace.ent->v.solid == SOLID_BSP) || (trace.ent->v.movetype == MOVETYPE_PPUSH)) - { - ent->v.flags = (int)ent->v.flags | FL_ONGROUND; - ent->v.groundentity = EDICT_TO_PROG(trace.ent); + if (trace.plane.normal[2] > 0.7) { + blocked |= 1; // floor + if ((trace.ent->v.solid == SOLID_BSP) + || (trace.ent->v.movetype == MOVETYPE_PPUSH)) { + ent->v.flags = (int) ent->v.flags | FL_ONGROUND; + ent->v.groundentity = EDICT_TO_PROG (trace.ent); } } - if (!trace.plane.normal[2]) - { - blocked |= 2; // step + if (!trace.plane.normal[2]) { + blocked |= 2; // step if (steptrace) - *steptrace = trace; // save for player extrafriction + *steptrace = trace; // save for player extrafriction } - // // run the impact function // SV_Impact (ent, trace.ent); if (ent->free) - break; // removed by the impact function + break; // removed by the impact function time_left -= time_left * trace.fraction; - // cliped to another plane - if (numplanes >= MAX_CLIP_PLANES) - { // this shouldn't really happen + // cliped to another plane + if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen VectorCopy (vec3_origin, ent->v.velocity); return 3; } @@ -351,28 +340,22 @@ SV_FlyMove ( edict_t *ent, float time, trace_t *steptrace ) // // modify original_velocity so it parallels all of the clip planes // - for (i=0 ; iv.velocity); - } - else - { // go along the crease - if (numplanes != 2) - { -// Con_Printf ("clip velocity, numplanes == %i\n",numplanes); + } else { // go along the crease + if (numplanes != 2) { +// Con_Printf ("clip velocity, numplanes == %i\n",numplanes); VectorCopy (vec3_origin, ent->v.velocity); return 7; } @@ -385,8 +368,7 @@ SV_FlyMove ( edict_t *ent, float time, trace_t *steptrace ) // if original velocity is against the original velocity, stop dead // to avoid tiny occilations in sloping corners // - if (DotProduct (ent->v.velocity, primal_velocity) <= 0) - { + if (DotProduct (ent->v.velocity, primal_velocity) <= 0) { VectorCopy (vec3_origin, ent->v.velocity); return blocked; } @@ -403,7 +385,7 @@ SV_AddGravity ============ */ void -SV_AddGravity ( edict_t *ent, float scale ) +SV_AddGravity (edict_t *ent, float scale) { ent->v.velocity[2] -= scale * movevars.gravity * sv_frametime; } @@ -424,20 +406,26 @@ Does not change the entities velocity at all ============ */ trace_t -SV_PushEntity ( edict_t *ent, vec3_t push ) +SV_PushEntity (edict_t *ent, vec3_t push) { - trace_t trace; - vec3_t end; + trace_t trace; + vec3_t end; VectorAdd (ent->v.origin, push, end); if (ent->v.movetype == MOVETYPE_FLYMISSILE) - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_MISSILE, ent); + trace = + SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_MISSILE, + ent); else if (ent->v.solid == SOLID_TRIGGER || ent->v.solid == SOLID_NOT) - // only clip against bmodels - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NOMONSTERS, ent); + // only clip against bmodels + trace = + SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, + MOVE_NOMONSTERS, ent); else - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NORMAL, ent); + trace = + SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, end, MOVE_NORMAL, + ent); VectorCopy (trace.endpos, ent->v.origin); SV_LinkEdict (ent, true); @@ -456,19 +444,20 @@ SV_Push ============ */ qboolean -SV_Push ( edict_t *pusher, vec3_t move ) +SV_Push (edict_t *pusher, vec3_t move) { - int i, e; - edict_t *check, *block; - vec3_t mins, maxs; - vec3_t pushorig; - int num_moved; - edict_t *moved_edict[MAX_EDICTS]; - vec3_t moved_from[MAX_EDICTS]; - float solid_save; // for Lord Havoc's SOLID_BSP fix --KB + int i, e; + edict_t *check, *block; + vec3_t mins, maxs; + vec3_t pushorig; + int num_moved; + edict_t *moved_edict[MAX_EDICTS]; + vec3_t moved_from[MAX_EDICTS]; + float solid_save; // for Lord Havoc's SOLID_BSP fix - for (i=0 ; i<3 ; i++) - { + // --KB + + for (i = 0; i < 3; i++) { mins[i] = pusher->v.absmin[i] + move[i]; maxs[i] = pusher->v.absmax[i] + move[i]; } @@ -482,39 +471,37 @@ SV_Push ( edict_t *pusher, vec3_t move ) // see if any solid entities are inside the final position num_moved = 0; - check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) continue; if (check->v.movetype == MOVETYPE_PUSH - || check->v.movetype == MOVETYPE_NONE - || check->v.movetype == MOVETYPE_PPUSH - || check->v.movetype == MOVETYPE_NOCLIP) - continue; + || check->v.movetype == MOVETYPE_NONE + || check->v.movetype == MOVETYPE_PPUSH + || check->v.movetype == MOVETYPE_NOCLIP) continue; // Don't assume SOLID_BSP ! --KB solid_save = pusher->v.solid; pusher->v.solid = SOLID_NOT; block = SV_TestEntityPosition (check); - // pusher->v.solid = SOLID_BSP; + // pusher->v.solid = SOLID_BSP; pusher->v.solid = solid_save; if (block) continue; - // if the entity is standing on the pusher, it will definately be moved - if ( ! ( ((int)check->v.flags & FL_ONGROUND) - && PROG_TO_EDICT(check->v.groundentity) == pusher) ) - { - if ( check->v.absmin[0] >= maxs[0] - || check->v.absmin[1] >= maxs[1] - || check->v.absmin[2] >= maxs[2] - || check->v.absmax[0] <= mins[0] - || check->v.absmax[1] <= mins[1] - || check->v.absmax[2] <= mins[2] ) + // if the entity is standing on the pusher, it will definately be + // moved + if (!(((int) check->v.flags & FL_ONGROUND) + && PROG_TO_EDICT (check->v.groundentity) == pusher)) { + if (check->v.absmin[0] >= maxs[0] + || check->v.absmin[1] >= maxs[1] + || check->v.absmin[2] >= maxs[2] + || check->v.absmax[0] <= mins[0] + || check->v.absmax[1] <= mins[1] + || check->v.absmax[2] <= mins[2]) continue; - // see if the ent's bbox is inside the pusher's final position + // see if the ent's bbox is inside the pusher's final position if (!SV_TestEntityPosition (check)) continue; } @@ -526,29 +513,23 @@ SV_Push ( edict_t *pusher, vec3_t move ) // try moving the contacted entity VectorAdd (check->v.origin, move, check->v.origin); block = SV_TestEntityPosition (check); - if (!block) - { // pushed ok + if (!block) { // pushed ok SV_LinkEdict (check, false); continue; } - // if it is ok to leave in the old position, do it VectorSubtract (check->v.origin, move, check->v.origin); block = SV_TestEntityPosition (check); - if (!block) - { + if (!block) { num_moved--; continue; } - - // if it is still inside the pusher, block - if (check->v.mins[0] == check->v.maxs[0]) - { + // if it is still inside the pusher, block + if (check->v.mins[0] == check->v.maxs[0]) { SV_LinkEdict (check, false); continue; } - if (check->v.solid == SOLID_NOT || check->v.solid == SOLID_TRIGGER) - { // corpse + if (check->v.solid == SOLID_NOT || check->v.solid == SOLID_TRIGGER) { // corpse check->v.mins[0] = check->v.mins[1] = 0; VectorCopy (check->v.mins, check->v.maxs); SV_LinkEdict (check, false); @@ -560,16 +541,13 @@ SV_Push ( edict_t *pusher, vec3_t move ) // if the pusher has a "blocked" function, call it // otherwise, just stay in place until the obstacle is gone - if (pusher->v.blocked) - { - pr_global_struct->self = EDICT_TO_PROG(pusher); - pr_global_struct->other = EDICT_TO_PROG(check); + if (pusher->v.blocked) { + pr_global_struct->self = EDICT_TO_PROG (pusher); + pr_global_struct->other = EDICT_TO_PROG (check); PR_ExecuteProgram (pusher->v.blocked); } - - // move back any entities we already moved - for (i=0 ; iv.origin); SV_LinkEdict (moved_edict[i], false); } @@ -586,18 +564,18 @@ SV_PushMove ============ */ void -SV_PushMove ( edict_t *pusher, float movetime ) +SV_PushMove (edict_t *pusher, float movetime) { - int i; - vec3_t move; + int i; + vec3_t move; - if (!pusher->v.velocity[0] && !pusher->v.velocity[1] && !pusher->v.velocity[2]) - { + if (!pusher->v.velocity[0] && !pusher->v.velocity[1] + && !pusher->v.velocity[2]) { pusher->v.ltime += movetime; return; } - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) move[i] = pusher->v.velocity[i] * movetime; if (SV_Push (pusher, move)) @@ -612,47 +590,43 @@ SV_Physics_Pusher ================ */ void -SV_Physics_Pusher ( edict_t *ent ) +SV_Physics_Pusher (edict_t *ent) { - float thinktime; - float oldltime; - float movetime; - vec3_t oldorg, move; - float l; + float thinktime; + float oldltime; + float movetime; + vec3_t oldorg, move; + float l; oldltime = ent->v.ltime; thinktime = ent->v.nextthink; - if (thinktime < ent->v.ltime + sv_frametime) - { + if (thinktime < ent->v.ltime + sv_frametime) { movetime = thinktime - ent->v.ltime; if (movetime < 0) movetime = 0; - } - else + } else movetime = sv_frametime; - if (movetime) - { - SV_PushMove (ent, movetime); // advances ent->v.ltime if not blocked + if (movetime) { + SV_PushMove (ent, movetime); // advances ent->v.ltime if not + // blocked } - if (thinktime > oldltime && thinktime <= ent->v.ltime) - { + if (thinktime > oldltime && thinktime <= ent->v.ltime) { VectorCopy (ent->v.origin, oldorg); ent->v.nextthink = 0; pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(ent); - pr_global_struct->other = EDICT_TO_PROG(sv.edicts); + pr_global_struct->self = EDICT_TO_PROG (ent); + pr_global_struct->other = EDICT_TO_PROG (sv.edicts); PR_ExecuteProgram (ent->v.think); if (ent->free) return; VectorSubtract (ent->v.origin, oldorg, move); - l = Length(move); - if (l > 1.0/64) - { -// Con_Printf ("**** snap: %f\n", Length (l)); + l = Length (move); + if (l > 1.0 / 64) { +// Con_Printf ("**** snap: %f\n", Length (l)); VectorCopy (oldorg, ent->v.origin); SV_Push (ent, move); } @@ -668,7 +642,7 @@ Non moving objects can only think ============= */ void -SV_Physics_None ( edict_t *ent ) +SV_Physics_None (edict_t *ent) { // regular thinking SV_RunThink (ent); @@ -682,7 +656,7 @@ A moving object that doesn't obey physics ============= */ void -SV_Physics_Noclip ( edict_t *ent ) +SV_Physics_Noclip (edict_t *ent) { // regular thinking if (!SV_RunThink (ent)) @@ -709,31 +683,27 @@ SV_CheckWaterTransition ============= */ void -SV_CheckWaterTransition ( edict_t *ent ) +SV_CheckWaterTransition (edict_t *ent) { - int cont; + int cont; cont = SV_PointContents (ent->v.origin); - if (!ent->v.watertype) - { // just spawned here + if (!ent->v.watertype) { // just spawned here ent->v.watertype = cont; ent->v.waterlevel = 1; return; } - if (cont <= CONTENTS_WATER) - { - if (ent->v.watertype == CONTENTS_EMPTY) - { // just crossed into water + if (cont <= CONTENTS_WATER) { + if (ent->v.watertype == CONTENTS_EMPTY) { // just crossed into + // water SV_StartSound (ent, 0, "misc/h2ohit1.wav", 255, 1); } ent->v.watertype = cont; ent->v.waterlevel = 1; - } - else - { - if (ent->v.watertype != CONTENTS_EMPTY) - { // just crossed into water + } else { + if (ent->v.watertype != CONTENTS_EMPTY) { // just crossed into + // water SV_StartSound (ent, 0, "misc/h2ohit1.wav", 255, 1); } ent->v.watertype = CONTENTS_EMPTY; @@ -749,29 +719,28 @@ Toss, bounce, and fly movement. When onground, do nothing. ============= */ void -SV_Physics_Toss ( edict_t *ent ) +SV_Physics_Toss (edict_t *ent) { - trace_t trace; - vec3_t move; - float backoff; + trace_t trace; + vec3_t move; + float backoff; // regular thinking if (!SV_RunThink (ent)) return; if (ent->v.velocity[2] > 0) - ent->v.flags = (int)ent->v.flags & ~FL_ONGROUND; + ent->v.flags = (int) ent->v.flags & ~FL_ONGROUND; // if onground, return without moving - if ( ((int)ent->v.flags & FL_ONGROUND) ) + if (((int) ent->v.flags & FL_ONGROUND)) return; SV_CheckVelocity (ent); // add gravity if (ent->v.movetype != MOVETYPE_FLY - && ent->v.movetype != MOVETYPE_FLYMISSILE) - SV_AddGravity (ent, 1.0); + && ent->v.movetype != MOVETYPE_FLYMISSILE) SV_AddGravity (ent, 1.0); // move angles VectorMA (ent->v.angles, sv_frametime, ent->v.avelocity, ent->v.angles); @@ -789,20 +758,18 @@ SV_Physics_Toss ( edict_t *ent ) else backoff = 1; - ClipVelocity (ent->v.velocity, trace.plane.normal, ent->v.velocity, backoff); + ClipVelocity (ent->v.velocity, trace.plane.normal, ent->v.velocity, + backoff); // stop if on ground - if (trace.plane.normal[2] > 0.7) - { - if (ent->v.velocity[2] < 60 || ent->v.movetype != MOVETYPE_BOUNCE ) - { - ent->v.flags = (int)ent->v.flags | FL_ONGROUND; - ent->v.groundentity = EDICT_TO_PROG(trace.ent); + if (trace.plane.normal[2] > 0.7) { + if (ent->v.velocity[2] < 60 || ent->v.movetype != MOVETYPE_BOUNCE) { + ent->v.flags = (int) ent->v.flags | FL_ONGROUND; + ent->v.groundentity = EDICT_TO_PROG (trace.ent); VectorCopy (vec3_origin, ent->v.velocity); VectorCopy (vec3_origin, ent->v.avelocity); } } - // check for in water SV_CheckWaterTransition (ent); } @@ -828,14 +795,13 @@ FIXME: is this true? ============= */ void -SV_Physics_Step ( edict_t *ent ) +SV_Physics_Step (edict_t *ent) { - qboolean hitsound; + qboolean hitsound; // frefall if not onground - if ( ! ((int)ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM) ) ) - { - if (ent->v.velocity[2] < movevars.gravity*-0.1) + if (!((int) ent->v.flags & (FL_ONGROUND | FL_FLY | FL_SWIM))) { + if (ent->v.velocity[2] < movevars.gravity * -0.1) hitsound = true; else hitsound = false; @@ -845,13 +811,12 @@ SV_Physics_Step ( edict_t *ent ) SV_FlyMove (ent, sv_frametime, NULL); SV_LinkEdict (ent, true); - if ( (int)ent->v.flags & FL_ONGROUND ) // just hit ground + if ((int) ent->v.flags & FL_ONGROUND) // just hit ground { if (hitsound) SV_StartSound (ent, 0, "demon/dland2.wav", 255, 1); } } - // regular thinking SV_RunThink (ent); @@ -859,24 +824,25 @@ SV_Physics_Step ( edict_t *ent ) } void -SV_PPushMove ( edict_t *pusher, float movetime ) // player push +SV_PPushMove (edict_t *pusher, float movetime) // player push { - int i, e; - edict_t *check; - vec3_t mins, maxs, move; - int oldsolid; - trace_t trace; + int i, e; + edict_t *check; + vec3_t mins, maxs, move; + int oldsolid; + trace_t trace; - SV_CheckVelocity(pusher); - for (i=0 ; i<3 ; i++) - { + SV_CheckVelocity (pusher); + for (i = 0; i < 3; i++) { move[i] = pusher->v.velocity[i] * movetime; mins[i] = pusher->v.absmin[i] + move[i]; maxs[i] = pusher->v.absmax[i] + move[i]; } - VectorCopy (pusher->v.origin, pusher->v.oldorigin); // Backup origin - trace = SV_Move (pusher->v.origin, pusher->v.mins, pusher->v.maxs, move, MOVE_NOMONSTERS, pusher); + VectorCopy (pusher->v.origin, pusher->v.oldorigin); // Backup origin + trace = + SV_Move (pusher->v.origin, pusher->v.mins, pusher->v.maxs, move, + MOVE_NOMONSTERS, pusher); if (trace.fraction == 1) { VectorCopy (pusher->v.origin, pusher->v.oldorigin); // Revert @@ -890,25 +856,23 @@ SV_PPushMove ( edict_t *pusher, float movetime ) // player push oldsolid = pusher->v.solid; - check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) // What entity? + check = NEXT_EDICT (sv.edicts); + for (e = 1; e < sv.num_edicts; e++, check = NEXT_EDICT (check)) { + if (check->free) // What entity? continue; // Stage 1: Is it in contact with me? - if (!SV_TestEntityPosition (check)) // Nope + if (!SV_TestEntityPosition (check)) // Nope continue; // Stage 2: Is it a player we can push? if (check->v.movetype == MOVETYPE_WALK) { - Con_Printf("Pusher encountered a player\n"); // Yes!@#!@ + Con_Printf ("Pusher encountered a player\n"); // Yes!@#!@ pusher->v.solid = SOLID_NOT; SV_PushEntity (check, move); pusher->v.solid = oldsolid; continue; } - // Stage 3: No.. Is it something that blocks us? if (check->v.mins[0] == check->v.maxs[0]) continue; @@ -917,9 +881,9 @@ SV_PPushMove ( edict_t *pusher, float movetime ) // player push // Stage 4: Yes, it must be. Fail the move. VectorCopy (pusher->v.origin, pusher->v.oldorigin); // Revert - if (pusher->v.blocked) { // Blocked func? - pr_global_struct->self = EDICT_TO_PROG(pusher); - pr_global_struct->other = EDICT_TO_PROG(check); + if (pusher->v.blocked) { // Blocked func? + pr_global_struct->self = EDICT_TO_PROG (pusher); + pr_global_struct->other = EDICT_TO_PROG (check); PR_ExecuteProgram (pusher->v.blocked); } @@ -928,36 +892,35 @@ SV_PPushMove ( edict_t *pusher, float movetime ) // player push } void -SV_Physics_PPusher ( edict_t *ent ) +SV_Physics_PPusher (edict_t *ent) { - float thinktime; - float oldltime; - float movetime; -// float l; + float thinktime; + float oldltime; + float movetime; + +// float l; oldltime = ent->v.ltime; thinktime = ent->v.nextthink; - if (thinktime < ent->v.ltime + sv_frametime) - { + if (thinktime < ent->v.ltime + sv_frametime) { movetime = thinktime - ent->v.ltime; if (movetime < 0) movetime = 0; - } - else + } else movetime = sv_frametime; -// if (movetime) -// { - SV_PPushMove (ent, 0.0009); // advances ent->v.ltime if not blocked -// } +// if (movetime) +// { + SV_PPushMove (ent, 0.0009); // advances ent->v.ltime if not + // blocked +// } - if (thinktime > oldltime && thinktime <= ent->v.ltime) - { + if (thinktime > oldltime && thinktime <= ent->v.ltime) { ent->v.nextthink = 0; pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(ent); - pr_global_struct->other = EDICT_TO_PROG(sv.edicts); + pr_global_struct->self = EDICT_TO_PROG (ent); + pr_global_struct->other = EDICT_TO_PROG (sv.edicts); PR_ExecuteProgram (ent->v.think); if (ent->free) return; @@ -967,11 +930,11 @@ SV_Physics_PPusher ( edict_t *ent ) //============================================================================ void -SV_ProgStartFrame ( void ) +SV_ProgStartFrame (void) { // let the progs know that a new frame has started - pr_global_struct->self = EDICT_TO_PROG(sv.edicts); - pr_global_struct->other = EDICT_TO_PROG(sv.edicts); + pr_global_struct->self = EDICT_TO_PROG (sv.edicts); + pr_global_struct->other = EDICT_TO_PROG (sv.edicts); pr_global_struct->time = sv.time; PR_ExecuteProgram (pr_global_struct->StartFrame); } @@ -983,37 +946,36 @@ SV_RunEntity ================ */ void -SV_RunEntity ( edict_t *ent ) +SV_RunEntity (edict_t *ent) { - if (ent->v.lastruntime == (float)realtime) + if (ent->v.lastruntime == (float) realtime) return; - ent->v.lastruntime = (float)realtime; + ent->v.lastruntime = (float) realtime; - switch ( (int)ent->v.movetype) - { - case MOVETYPE_PUSH: - SV_Physics_Pusher (ent); - break; - case MOVETYPE_PPUSH: - SV_Physics_PPusher (ent); - break; - case MOVETYPE_NONE: - SV_Physics_None (ent); - break; - case MOVETYPE_NOCLIP: - SV_Physics_Noclip (ent); - break; - case MOVETYPE_STEP: - SV_Physics_Step (ent); - break; - case MOVETYPE_TOSS: - case MOVETYPE_BOUNCE: - case MOVETYPE_FLY: - case MOVETYPE_FLYMISSILE: - SV_Physics_Toss (ent); - break; - default: - SV_Error ("SV_Physics: bad movetype %i", (int)ent->v.movetype); + switch ((int) ent->v.movetype) { + case MOVETYPE_PUSH: + SV_Physics_Pusher (ent); + break; + case MOVETYPE_PPUSH: + SV_Physics_PPusher (ent); + break; + case MOVETYPE_NONE: + SV_Physics_None (ent); + break; + case MOVETYPE_NOCLIP: + SV_Physics_Noclip (ent); + break; + case MOVETYPE_STEP: + SV_Physics_Step (ent); + break; + case MOVETYPE_TOSS: + case MOVETYPE_BOUNCE: + case MOVETYPE_FLY: + case MOVETYPE_FLYMISSILE: + SV_Physics_Toss (ent); + break; + default: + SV_Error ("SV_Physics: bad movetype %i", (int) ent->v.movetype); } } @@ -1024,13 +986,13 @@ SV_RunNewmis ================ */ void -SV_RunNewmis ( void ) +SV_RunNewmis (void) { - edict_t *ent; + edict_t *ent; if (!pr_global_struct->newmis) return; - ent = PROG_TO_EDICT(pr_global_struct->newmis); + ent = PROG_TO_EDICT (pr_global_struct->newmis); sv_frametime = 0.05; pr_global_struct->newmis = 0; @@ -1044,11 +1006,11 @@ SV_Physics ================ */ void -SV_Physics ( void ) +SV_Physics (void) { - int i; - edict_t *ent; - static double old_time; + int i; + edict_t *ent; + static double old_time; // don't bother running a frame if sys_ticrate seconds haven't passed sv_frametime = realtime - old_time; @@ -1067,8 +1029,7 @@ SV_Physics ( void ) // even the world gets a chance to think // ent = sv.edicts; - for (i=0 ; ifree) continue; @@ -1076,7 +1037,8 @@ SV_Physics ( void ) SV_LinkEdict (ent, true); // force retouch even for stationary if (i > 0 && i <= MAX_CLIENTS) - continue; // clients are run directly from packets + continue; // clients are run directly from + // packets SV_RunEntity (ent); SV_RunNewmis (); @@ -1086,11 +1048,10 @@ SV_Physics ( void ) pr_global_struct->force_retouch--; // 2000-01-02 EndFrame function by Maddes/FrikaC start - if (EndFrame) - { + if (EndFrame) { // let the progs know that the frame has ended - pr_global_struct->self = EDICT_TO_PROG(sv.edicts); - pr_global_struct->other = EDICT_TO_PROG(sv.edicts); + pr_global_struct->self = EDICT_TO_PROG (sv.edicts); + pr_global_struct->other = EDICT_TO_PROG (sv.edicts); pr_global_struct->time = sv.time; PR_ExecuteProgram (EndFrame); } @@ -1098,16 +1059,16 @@ SV_Physics ( void ) } void -SV_SetMoveVars ( void ) +SV_SetMoveVars (void) { - movevars.gravity = sv_gravity->value; - movevars.stopspeed = sv_stopspeed->value; - movevars.maxspeed = sv_maxspeed->value; - movevars.spectatormaxspeed = sv_spectatormaxspeed->value; - movevars.accelerate = sv_accelerate->value; - movevars.airaccelerate = sv_airaccelerate->value; - movevars.wateraccelerate = sv_wateraccelerate->value; - movevars.friction = sv_friction->value; - movevars.waterfriction = sv_waterfriction->value; - movevars.entgravity = 1.0; + movevars.gravity = sv_gravity->value; + movevars.stopspeed = sv_stopspeed->value; + movevars.maxspeed = sv_maxspeed->value; + movevars.spectatormaxspeed = sv_spectatormaxspeed->value; + movevars.accelerate = sv_accelerate->value; + movevars.airaccelerate = sv_airaccelerate->value; + movevars.wateraccelerate = sv_wateraccelerate->value; + movevars.friction = sv_friction->value; + movevars.waterfriction = sv_waterfriction->value; + movevars.entgravity = 1.0; } diff --git a/source/sv_send.c b/source/sv_send.c index 1fc4c16..7c91683 100644 --- a/source/sv_send.c +++ b/source/sv_send.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "server.h" #include "crc.h" @@ -58,41 +58,39 @@ Con_Printf redirection ============================================================================= */ -char outputbuf[8000]; +char outputbuf[8000]; -redirect_t sv_redirected; +redirect_t sv_redirected; -extern cvar_t *sv_phs; -extern cvar_t *sv_timestamps; -extern cvar_t *sv_timefmt; +extern cvar_t *sv_phs; +extern cvar_t *sv_timestamps; +extern cvar_t *sv_timefmt; /* ================== SV_FlushRedirect ================== */ -void SV_FlushRedirect (void) +void +SV_FlushRedirect (void) { - char send[8000+6]; + char send[8000 + 6]; - if (sv_redirected == RD_PACKET) - { + if (sv_redirected == RD_PACKET) { send[0] = 0xff; send[1] = 0xff; send[2] = 0xff; send[3] = 0xff; send[4] = A2C_PRINT; - memcpy (send+5, outputbuf, strlen(outputbuf)+1); + memcpy (send + 5, outputbuf, strlen (outputbuf) + 1); - NET_SendPacket (strlen(send)+1, send, net_from); - } - else if (sv_redirected == RD_CLIENT) - { - ClientReliableWrite_Begin (host_client, svc_print, strlen(outputbuf)+3); + NET_SendPacket (strlen (send) + 1, send, net_from); + } else if (sv_redirected == RD_CLIENT) { + ClientReliableWrite_Begin (host_client, svc_print, + strlen (outputbuf) + 3); ClientReliableWrite_Byte (host_client, PRINT_HIGH); ClientReliableWrite_String (host_client, outputbuf); } - // clear it outputbuf[0] = 0; } @@ -106,13 +104,15 @@ SV_BeginRedirect instead of the console ================== */ -void SV_BeginRedirect (redirect_t rd) +void +SV_BeginRedirect (redirect_t rd) { sv_redirected = rd; outputbuf[0] = 0; } -void SV_EndRedirect (void) +void +SV_EndRedirect (void) { SV_FlushRedirect (); sv_redirected = RD_NONE; @@ -128,29 +128,31 @@ Handles cursor positioning, line wrapping, etc */ #define MAXPRINTMSG 4096 -void Con_Printf (char *fmt, ...) +void +Con_Printf (char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; - char msg2[MAXPRINTMSG]; - char msg3[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; + char msg2[MAXPRINTMSG]; + char msg3[MAXPRINTMSG]; - time_t mytime = 0; - struct tm *local = NULL; - qboolean timestamps = false; + time_t mytime = 0; + struct tm *local = NULL; + qboolean timestamps = false; va_start (argptr, fmt); vsnprintf (msg, sizeof (msg), fmt, argptr); va_end (argptr); - if (sv_redirected) { // Add to redirected message + if (sv_redirected) { // Add to redirected message if (strlen (msg) + strlen (outputbuf) > sizeof (outputbuf) - 1) SV_FlushRedirect (); - strncat (outputbuf, msg, sizeof(outputbuf) - strlen (outputbuf)); + strncat (outputbuf, msg, sizeof (outputbuf) - strlen (outputbuf)); return; - } else { // We want to output to console and maybe logfile - if (sv_timestamps && sv_timefmt && sv_timefmt->string && sv_timestamps->int_val) - timestamps = true; + } else { // We want to output to console and + // maybe logfile + if (sv_timestamps && sv_timefmt && sv_timefmt->string + && sv_timestamps->int_val) timestamps = true; if (timestamps) { mytime = time (NULL); @@ -162,7 +164,7 @@ void Con_Printf (char *fmt, ...) snprintf (msg2, sizeof (msg2), "%s", msg); } - Sys_Printf ("%s", msg2); // also echo to debugging console + Sys_Printf ("%s", msg2); // also echo to debugging console if (sv_logfile) Qprintf (sv_logfile, "%s", msg2); } @@ -175,10 +177,11 @@ Con_DPrintf A Con_Printf that only shows up if the "developer" cvar is set ================ */ -void Con_DPrintf (char *fmt, ...) +void +Con_DPrintf (char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; if (!developer->int_val) return; @@ -186,7 +189,7 @@ void Con_DPrintf (char *fmt, ...) va_start (argptr, fmt); vsnprintf (msg, sizeof (msg), fmt, argptr); va_end (argptr); - + Con_Printf ("%s", msg); } @@ -198,9 +201,10 @@ EVENT MESSAGES ============================================================================= */ -static void SV_PrintToClient(client_t *cl, int level, char *string) +static void +SV_PrintToClient (client_t *cl, int level, char *string) { - ClientReliableWrite_Begin (cl, svc_print, strlen(string)+3); + ClientReliableWrite_Begin (cl, svc_print, strlen (string) + 3); ClientReliableWrite_Byte (cl, level); ClientReliableWrite_String (cl, string); } @@ -213,19 +217,20 @@ SV_ClientPrintf Sends text across to be displayed if the level passes ================= */ -void SV_ClientPrintf (client_t *cl, int level, char *fmt, ...) +void +SV_ClientPrintf (client_t *cl, int level, char *fmt, ...) { - va_list argptr; - char string[1024]; - + va_list argptr; + char string[1024]; + if (level < cl->messagelevel) return; - + va_start (argptr, fmt); - vsnprintf (string, sizeof(string), fmt, argptr); + vsnprintf (string, sizeof (string), fmt, argptr); va_end (argptr); - SV_PrintToClient(cl, level, string); + SV_PrintToClient (cl, level, string); } /* @@ -235,27 +240,27 @@ SV_BroadcastPrintf Sends text to all active clients ================= */ -void SV_BroadcastPrintf (int level, char *fmt, ...) +void +SV_BroadcastPrintf (int level, char *fmt, ...) { - va_list argptr; - char string[1024]; - client_t *cl; - int i; + va_list argptr; + char string[1024]; + client_t *cl; + int i; va_start (argptr, fmt); - vsnprintf (string, sizeof(string), fmt, argptr); + vsnprintf (string, sizeof (string), fmt, argptr); va_end (argptr); - - Sys_Printf ("%s", string); // print to the console - for (i=0, cl = svs.clients ; imessagelevel) continue; if (!cl->state) continue; - SV_PrintToClient(cl, level, string); + SV_PrintToClient (cl, level, string); } } @@ -266,15 +271,16 @@ SV_BroadcastCommand Sends text to all active clients ================= */ -void SV_BroadcastCommand (char *fmt, ...) +void +SV_BroadcastCommand (char *fmt, ...) { - va_list argptr; - char string[1024]; - + va_list argptr; + char string[1024]; + if (!sv.state) return; va_start (argptr, fmt); - vsnprintf (string, sizeof(string), fmt, argptr); + vsnprintf (string, sizeof (string), fmt, argptr); va_end (argptr); MSG_WriteByte (&sv.reliable_datagram, svc_stufftext); @@ -294,14 +300,15 @@ MULTICAST_PVS send to clients potentially visible from org MULTICAST_PHS send to clients potentially hearable from org ================= */ -void SV_Multicast (vec3_t origin, int to) +void +SV_Multicast (vec3_t origin, int to) { - client_t *client; - byte *mask; - mleaf_t *leaf; - int leafnum; - int j; - qboolean reliable; + client_t *client; + byte *mask; + mleaf_t *leaf; + int leafnum; + int j; + qboolean reliable; leaf = Mod_PointInLeaf (origin, sv.worldmodel); if (!leaf) @@ -311,62 +318,61 @@ void SV_Multicast (vec3_t origin, int to) reliable = false; - switch (to) - { - case MULTICAST_ALL_R: - reliable = true; // intentional fallthrough - case MULTICAST_ALL: - mask = sv.pvs; // leaf 0 is everything; - break; + switch (to) { + case MULTICAST_ALL_R: + reliable = true; // intentional fallthrough + case MULTICAST_ALL: + mask = sv.pvs; // leaf 0 is everything; + break; - case MULTICAST_PHS_R: - reliable = true; // intentional fallthrough - case MULTICAST_PHS: - mask = sv.phs + leafnum * 4*((sv.worldmodel->numleafs+31)>>5); - break; + case MULTICAST_PHS_R: + reliable = true; // intentional fallthrough + case MULTICAST_PHS: + mask = sv.phs + leafnum * 4 * ((sv.worldmodel->numleafs + 31) >> 5); + break; - case MULTICAST_PVS_R: - reliable = true; // intentional fallthrough - case MULTICAST_PVS: - mask = sv.pvs + leafnum * 4*((sv.worldmodel->numleafs+31)>>5); - break; + case MULTICAST_PVS_R: + reliable = true; // intentional fallthrough + case MULTICAST_PVS: + mask = sv.pvs + leafnum * 4 * ((sv.worldmodel->numleafs + 31) >> 5); + break; - default: - mask = NULL; - SV_Error ("SV_Multicast: bad to:%i", to); + default: + mask = NULL; + SV_Error ("SV_Multicast: bad to:%i", to); } // send the data to all relevent clients - for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) - { + for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) { if (client->state != cs_spawned) continue; if (to == MULTICAST_PHS_R || to == MULTICAST_PHS) { - vec3_t delta; - VectorSubtract(origin, client->edict->v.origin, delta); - if (Length(delta) <= 1024) + vec3_t delta; + + VectorSubtract (origin, client->edict->v.origin, delta); + if (Length (delta) <= 1024) goto inrange; } leaf = Mod_PointInLeaf (client->edict->v.origin, sv.worldmodel); - if (leaf) - { + if (leaf) { // -1 is because pvs rows are 1 based, not 0 based like leafs leafnum = leaf - sv.worldmodel->leafs - 1; - if ( !(mask[leafnum>>3] & (1<<(leafnum&7)) ) ) - { -// Con_Printf ("supressed multicast\n"); + if (!(mask[leafnum >> 3] & (1 << (leafnum & 7)))) { +// Con_Printf ("supressed multicast\n"); continue; } } -inrange: + inrange: if (reliable) { - ClientReliableCheckBlock(client, sv.multicast.cursize); - ClientReliableWrite_SZ(client, sv.multicast.data, sv.multicast.cursize); + ClientReliableCheckBlock (client, sv.multicast.cursize); + ClientReliableWrite_SZ (client, sv.multicast.data, + sv.multicast.cursize); } else - SZ_Write (&client->datagram, sv.multicast.data, sv.multicast.cursize); + SZ_Write (&client->datagram, sv.multicast.data, + sv.multicast.cursize); } SZ_Clear (&sv.multicast); @@ -387,17 +393,18 @@ An attenuation of 0 will play full volume everywhere in the level. Larger attenuations will drop off. (max 4 attenuation) ================== -*/ -void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, - float attenuation) -{ - int sound_num; - int field_mask; - int i; - int ent; - vec3_t origin; - qboolean use_phs; - qboolean reliable = false; +*/ +void +SV_StartSound (edict_t *entity, int channel, char *sample, int volume, + float attenuation) +{ + int sound_num; + int field_mask; + int i; + int ent; + vec3_t origin; + qboolean use_phs; + qboolean reliable = false; if (volume < 0 || volume > 255) SV_Error ("SV_StartSound: volume = %i", volume); @@ -409,33 +416,32 @@ void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, SV_Error ("SV_StartSound: channel = %i", channel); // find precache number for sound - for (sound_num=1 ; sound_numint_val) // no PHS flag { if (channel & 8) - reliable = true; // sounds that break the phs are reliable + reliable = true; // sounds that break the phs are + // reliable use_phs = false; channel &= 7; - } - else + } else use_phs = true; -// if (channel == CHAN_BODY || channel == CHAN_VOICE) -// reliable = true; +// if (channel == CHAN_BODY || channel == CHAN_VOICE) +// reliable = true; - channel = (ent<<3) | channel; + channel = (ent << 3) | channel; field_mask = 0; if (volume != DEFAULT_SOUND_PACKET_VOLUME) @@ -444,13 +450,12 @@ void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, channel |= SND_ATTENUATION; // use the entity origin unless it is a bmodel - if (entity->v.solid == SOLID_BSP) - { - for (i=0 ; i<3 ; i++) - origin[i] = entity->v.origin[i]+0.5*(entity->v.mins[i]+entity->v.maxs[i]); - } - else - { + if (entity->v.solid == SOLID_BSP) { + for (i = 0; i < 3; i++) + origin[i] = + entity->v.origin[i] + 0.5 * (entity->v.mins[i] + + entity->v.maxs[i]); + } else { VectorCopy (entity->v.origin, origin); } @@ -459,16 +464,16 @@ void SV_StartSound (edict_t *entity, int channel, char *sample, int volume, if (channel & SND_VOLUME) MSG_WriteByte (&sv.multicast, volume); if (channel & SND_ATTENUATION) - MSG_WriteByte (&sv.multicast, attenuation*64); + MSG_WriteByte (&sv.multicast, attenuation * 64); MSG_WriteByte (&sv.multicast, sound_num); - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) MSG_WriteCoord (&sv.multicast, origin[i]); if (use_phs) SV_Multicast (origin, reliable ? MULTICAST_PHS_R : MULTICAST_PHS); else SV_Multicast (origin, reliable ? MULTICAST_ALL_R : MULTICAST_ALL); -} +} /* @@ -479,25 +484,25 @@ FRAME UPDATES =============================================================================== */ -int sv_nailmodel, sv_supernailmodel, sv_playermodel; +int sv_nailmodel, sv_supernailmodel, sv_playermodel; -void SV_FindModelNumbers (void) +void +SV_FindModelNumbers (void) { - int i; + int i; sv_nailmodel = -1; sv_supernailmodel = -1; sv_playermodel = -1; - for (i=0 ; iedict; // send the chokecount for r_netgraph - if (client->chokecount) - { + if (client->chokecount) { MSG_WriteByte (msg, svc_chokecount); MSG_WriteByte (msg, client->chokecount); client->chokecount = 0; } - // send a damage message if the player got hit this frame - if (ent->v.dmg_take || ent->v.dmg_save) - { - other = PROG_TO_EDICT(ent->v.dmg_inflictor); + if (ent->v.dmg_take || ent->v.dmg_save) { + other = PROG_TO_EDICT (ent->v.dmg_inflictor); MSG_WriteByte (msg, svc_damage); MSG_WriteByte (msg, ent->v.dmg_save); MSG_WriteByte (msg, ent->v.dmg_take); - for (i=0 ; i<3 ; i++) - MSG_WriteCoord (msg, other->v.origin[i] + 0.5*(other->v.mins[i] + other->v.maxs[i])); - + for (i = 0; i < 3; i++) + MSG_WriteCoord (msg, + other->v.origin[i] + 0.5 * (other->v.mins[i] + + other->v.maxs[i])); + ent->v.dmg_take = 0; ent->v.dmg_save = 0; } - // a fixangle might get lost in a dropped packet. Oh well. - if ( ent->v.fixangle ) - { + if (ent->v.fixangle) { MSG_WriteByte (msg, svc_setangle); - for (i=0 ; i < 3 ; i++) - MSG_WriteAngle (msg, ent->v.angles[i] ); + for (i = 0; i < 3; i++) + MSG_WriteAngle (msg, ent->v.angles[i]); ent->v.fixangle = 0; } } @@ -557,22 +560,23 @@ Performs a delta update of the stats array. This should only be performed when a reliable message can be delivered this frame. ======================= */ -void SV_UpdateClientStats (client_t *client) +void +SV_UpdateClientStats (client_t *client) { - edict_t *ent; - int stats[MAX_CL_STATS]; - int i; - + edict_t *ent; + int stats[MAX_CL_STATS]; + int i; + ent = client->edict; - memset (stats, 0, sizeof(stats)); - + memset (stats, 0, sizeof (stats)); + // if we are a spectator and we are tracking a player, we get his stats // so our status bar reflects his if (client->spectator && client->spec_track > 0) ent = svs.clients[client->spec_track - 1].edict; stats[STAT_HEALTH] = ent->v.health; - stats[STAT_WEAPON] = SV_ModelIndex(PR_GetString(ent->v.weaponmodel)); + stats[STAT_WEAPON] = SV_ModelIndex (PR_GetString (ent->v.weaponmodel)); stats[STAT_AMMO] = ent->v.currentammo; stats[STAT_ARMOR] = ent->v.armorvalue; stats[STAT_SHELLS] = ent->v.ammo_shells; @@ -582,34 +586,31 @@ void SV_UpdateClientStats (client_t *client) if (!client->spectator) stats[STAT_ACTIVEWEAPON] = ent->v.weapon; // stuff the sigil bits into the high bits of items for sbar - stats[STAT_ITEMS] = (int)ent->v.items | ((int)pr_global_struct->serverflags << 28); + stats[STAT_ITEMS] = + (int) ent->v.items | ((int) pr_global_struct->serverflags << 28); // Extensions to the QW 2.40 protocol for Mega2k --KB - stats[STAT_VIEWHEIGHT] = (int)ent->v.view_ofs[2]; + stats[STAT_VIEWHEIGHT] = (int) ent->v.view_ofs[2]; // FIXME: this should become a * key! --KB - if (ent->v.movetype == MOVETYPE_FLY && !atoi(Info_ValueForKey - (svs.info, "playerfly"))) + if (ent->v.movetype == MOVETYPE_FLY && !atoi (Info_ValueForKey + (svs.info, "playerfly"))) ent->v.movetype = MOVETYPE_WALK; - + stats[STAT_FLYMODE] = (ent->v.movetype == MOVETYPE_FLY); - for (i=0 ; istats[i]) - { + for (i = 0; i < MAX_CL_STATS; i++) + if (stats[i] != client->stats[i]) { client->stats[i] = stats[i]; - if (stats[i] >=0 && stats[i] <= 255) - { - ClientReliableWrite_Begin(client, svc_updatestat, 3); - ClientReliableWrite_Byte(client, i); - ClientReliableWrite_Byte(client, stats[i]); - } - else - { - ClientReliableWrite_Begin(client, svc_updatestatlong, 6); - ClientReliableWrite_Byte(client, i); - ClientReliableWrite_Long(client, stats[i]); + if (stats[i] >= 0 && stats[i] <= 255) { + ClientReliableWrite_Begin (client, svc_updatestat, 3); + ClientReliableWrite_Byte (client, i); + ClientReliableWrite_Byte (client, stats[i]); + } else { + ClientReliableWrite_Begin (client, svc_updatestatlong, 6); + ClientReliableWrite_Byte (client, i); + ClientReliableWrite_Long (client, stats[i]); } } } @@ -619,13 +620,14 @@ void SV_UpdateClientStats (client_t *client) SV_SendClientDatagram ======================= */ -qboolean SV_SendClientDatagram (client_t *client) +qboolean +SV_SendClientDatagram (client_t *client) { - byte buf[MAX_DATAGRAM]; - sizebuf_t msg; + byte buf[MAX_DATAGRAM]; + sizebuf_t msg; msg.data = buf; - msg.maxsize = sizeof(buf); + msg.maxsize = sizeof (buf); msg.cursize = 0; msg.allowoverflow = true; msg.overflowed = false; @@ -650,12 +652,10 @@ qboolean SV_SendClientDatagram (client_t *client) if (Netchan_CanReliable (&client->netchan)) SV_UpdateClientStats (client); - if (msg.overflowed) - { + if (msg.overflowed) { Con_Printf ("WARNING: msg overflowed for %s\n", client->name); SZ_Clear (&msg); } - // send the datagram Netchan_Transmit (&client->netchan, msg.cursize, buf); @@ -667,51 +667,47 @@ qboolean SV_SendClientDatagram (client_t *client) SV_UpdateToReliableMessages ======================= */ -void SV_UpdateToReliableMessages (void) +void +SV_UpdateToReliableMessages (void) { - int i, j; - client_t *client; - eval_t *val; - edict_t *ent; + int i, j; + client_t *client; + eval_t *val; + edict_t *ent; // check for changes to be sent over the reliable streams to all clients - for (i=0, host_client = svs.clients ; istate != cs_spawned) continue; - if (host_client->sendinfo) - { + if (host_client->sendinfo) { host_client->sendinfo = false; SV_FullClientUpdate (host_client, &sv.reliable_datagram); } - if (host_client->old_frags != host_client->edict->v.frags) - { - for (j=0, client = svs.clients ; jold_frags != host_client->edict->v.frags) { + for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) { if (client->state < cs_connected) continue; - ClientReliableWrite_Begin(client, svc_updatefrags, 4); - ClientReliableWrite_Byte(client, i); - ClientReliableWrite_Short(client, host_client->edict->v.frags); + ClientReliableWrite_Begin (client, svc_updatefrags, 4); + ClientReliableWrite_Byte (client, i); + ClientReliableWrite_Short (client, host_client->edict->v.frags); } host_client->old_frags = host_client->edict->v.frags; } - // maxspeed/entgravity changes ent = host_client->edict; - val = GetEdictFieldValue(ent, "gravity"); + val = GetEdictFieldValue (ent, "gravity"); if (val && host_client->entgravity != val->_float) { host_client->entgravity = val->_float; - ClientReliableWrite_Begin(host_client, svc_entgravity, 5); - ClientReliableWrite_Float(host_client, host_client->entgravity); + ClientReliableWrite_Begin (host_client, svc_entgravity, 5); + ClientReliableWrite_Float (host_client, host_client->entgravity); } - val = GetEdictFieldValue(ent, "maxspeed"); + val = GetEdictFieldValue (ent, "maxspeed"); if (val && host_client->maxspeed != val->_float) { host_client->maxspeed = val->_float; - ClientReliableWrite_Begin(host_client, svc_maxspeed, 5); - ClientReliableWrite_Float(host_client, host_client->maxspeed); + ClientReliableWrite_Begin (host_client, svc_maxspeed, 5); + ClientReliableWrite_Float (host_client, host_client->maxspeed); } } @@ -720,19 +716,18 @@ void SV_UpdateToReliableMessages (void) SZ_Clear (&sv.datagram); // append the broadcast messages to each client messages - for (j=0, client = svs.clients ; jstate < cs_connected) - continue; // reliables go to all connected or spawned + continue; // reliables go to all connected or + // spawned - ClientReliableCheckBlock(client, sv.reliable_datagram.cursize); - ClientReliableWrite_SZ(client, sv.reliable_datagram.data, sv.reliable_datagram.cursize); + ClientReliableCheckBlock (client, sv.reliable_datagram.cursize); + ClientReliableWrite_SZ (client, sv.reliable_datagram.data, + sv.reliable_datagram.cursize); if (client->state != cs_spawned) - continue; // datagrams only go to spawned - SZ_Write (&client->datagram - , sv.datagram.data - , sv.datagram.cursize); + continue; // datagrams only go to spawned + SZ_Write (&client->datagram, sv.datagram.data, sv.datagram.cursize); } SZ_Clear (&sv.reliable_datagram); @@ -750,85 +745,82 @@ void SV_UpdateToReliableMessages (void) SV_SendClientMessages ======================= */ -void SV_SendClientMessages (void) +void +SV_SendClientMessages (void) { - int i, j; - client_t *c; + int i, j; + client_t *c; // update frags, names, etc SV_UpdateToReliableMessages (); // build individual updates - for (i=0, c = svs.clients ; istate) continue; if (c->drop) { - SV_DropClient(c); + SV_DropClient (c); c->drop = false; continue; } - // check to see if we have a backbuf to stick in the reliable if (c->num_backbuf) { // will it fit? if (c->netchan.message.cursize + c->backbuf_size[0] < c->netchan.message.maxsize) { - Con_DPrintf("%s: backbuf %d bytes\n", - c->name, c->backbuf_size[0]); + Con_DPrintf ("%s: backbuf %d bytes\n", + c->name, c->backbuf_size[0]); // it'll fit - SZ_Write(&c->netchan.message, c->backbuf_data[0], - c->backbuf_size[0]); - - //move along, move along + SZ_Write (&c->netchan.message, c->backbuf_data[0], + c->backbuf_size[0]); + + // move along, move along for (j = 1; j < c->num_backbuf; j++) { - memcpy(c->backbuf_data[j - 1], c->backbuf_data[j], - c->backbuf_size[j]); + memcpy (c->backbuf_data[j - 1], c->backbuf_data[j], + c->backbuf_size[j]); c->backbuf_size[j - 1] = c->backbuf_size[j]; } c->num_backbuf--; if (c->num_backbuf) { - memset(&c->backbuf, 0, sizeof(c->backbuf)); + memset (&c->backbuf, 0, sizeof (c->backbuf)); c->backbuf.data = c->backbuf_data[c->num_backbuf - 1]; c->backbuf.cursize = c->backbuf_size[c->num_backbuf - 1]; - c->backbuf.maxsize = sizeof(c->backbuf_data[c->num_backbuf - 1]); + c->backbuf.maxsize = + sizeof (c->backbuf_data[c->num_backbuf - 1]); } } } - // if the reliable message overflowed, // drop the client - if (c->netchan.message.overflowed) - { + if (c->netchan.message.overflowed) { SZ_Clear (&c->netchan.message); SZ_Clear (&c->datagram); SV_BroadcastPrintf (PRINT_HIGH, "%s overflowed\n", c->name); - Con_Printf ("WARNING: reliable overflow for %s\n",c->name); + Con_Printf ("WARNING: reliable overflow for %s\n", c->name); SV_DropClient (c); c->send_message = true; c->netchan.cleartime = 0; // don't choke this message } - // only send messages if the client has sent one // and the bandwidth is not choked if (!c->send_message) continue; - c->send_message = false; // try putting this after choke? - if (!sv.paused && !Netchan_CanPacket (&c->netchan)) - { + c->send_message = false; // try putting this after choke? + if (!sv.paused && !Netchan_CanPacket (&c->netchan)) { c->chokecount++; - continue; // bandwidth choke + continue; // bandwidth choke } if (c->state == cs_spawned) SV_SendClientDatagram (c); else - Netchan_Transmit (&c->netchan, 0, NULL); // just update reliable - + Netchan_Transmit (&c->netchan, 0, NULL); // just update + // reliable + } } @@ -845,14 +837,16 @@ SV_SendMessagesToAll FIXME: does this sequence right? ======================= */ -void SV_SendMessagesToAll (void) +void +SV_SendMessagesToAll (void) { - int i; - client_t *c; + int i; + client_t *c; - for (i=0, c = svs.clients ; istate) // FIXME: should this only send to active? + for (i = 0, c = svs.clients; i < MAX_CLIENTS; i++, c++) + if (c->state) // FIXME: should this only send to + // active? c->send_message = true; - + SV_SendClientMessages (); } diff --git a/source/sv_sys_unix.c b/source/sv_sys_unix.c index d4361ad..6549b33 100644 --- a/source/sv_sys_unix.c +++ b/source/sv_sys_unix.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #ifdef HAVE_STRINGS_H @@ -54,10 +54,10 @@ #endif -cvar_t *sys_extrasleep; +cvar_t *sys_extrasleep; -qboolean is_server = true; -qboolean stdin_ready; +qboolean is_server = true; +qboolean stdin_ready; #define BASEDIR "." @@ -75,16 +75,17 @@ qboolean stdin_ready; Sys_Error ================ */ -void Sys_Error (char *error, ...) +void +Sys_Error (char *error, ...) { - va_list argptr; - char string[1024]; - + va_list argptr; + char string[1024]; + va_start (argptr, error); - vsnprintf (string, sizeof(string), error,argptr); + vsnprintf (string, sizeof (string), error, argptr); va_end (argptr); - printf ("Fatal error: %s\n",string); - + printf ("Fatal error: %s\n", string); + exit (1); } @@ -94,12 +95,13 @@ void Sys_Error (char *error, ...) Sys_Quit ================ */ -void Sys_Quit (void) +void +Sys_Quit (void) { - exit (0); // appkit isn't running + exit (0); // appkit isn't running } -static int do_stdin = 1; +static int do_stdin = 1; /* ================ @@ -109,16 +111,17 @@ Checks for a complete line of text typed in at the console, then forwards it to the host command processor ================ */ -char *Sys_ConsoleInput (void) +char * +Sys_ConsoleInput (void) { - static char text[256]; - int len; + static char text[256]; + int len; if (!stdin_ready || !do_stdin) - return NULL; // the select didn't say it was ready + return NULL; // the select didn't say it was ready stdin_ready = false; - len = read (0, text, sizeof(text)); + len = read (0, text, sizeof (text)); if (len == 0) { // end of file do_stdin = 0; @@ -126,8 +129,8 @@ char *Sys_ConsoleInput (void) } if (len < 1) return NULL; - text[len-1] = 0; // rip off the /n and terminate - + text[len - 1] = 0; // rip off the /n and terminate + return text; } @@ -139,17 +142,18 @@ Quake calls this so the system can register variables before host_hunklevel is marked ============= */ -void Sys_Init_Cvars (void) +void +Sys_Init_Cvars (void) { - sys_nostdout = Cvar_Get("sys_nostdout", "0", CVAR_NONE, "None"); - sys_extrasleep = Cvar_Get("sys_extrasleep", "0", CVAR_NONE, "None"); + sys_nostdout = Cvar_Get ("sys_nostdout", "0", CVAR_NONE, "None"); + sys_extrasleep = Cvar_Get ("sys_extrasleep", "0", CVAR_NONE, "None"); } void Sys_Init (void) { #ifdef USE_INTEL_ASM - Sys_SetFPCW(); + Sys_SetFPCW (); #endif } @@ -158,63 +162,64 @@ Sys_Init (void) main ============= */ -int main(int argc, char *argv[]) +int +main (int argc, char *argv[]) { - double time, oldtime, newtime; - fd_set fdset; - extern int net_socket; - struct timeval timeout; - int j; + double time, oldtime, newtime; + fd_set fdset; + extern int net_socket; + struct timeval timeout; + int j; - memset (&host_parms, 0, sizeof(host_parms)); + memset (&host_parms, 0, sizeof (host_parms)); - COM_InitArgv (argc, argv); + COM_InitArgv (argc, argv); host_parms.argc = com_argc; host_parms.argv = com_argv; - host_parms.memsize = 16*1024*1024; + host_parms.memsize = 16 * 1024 * 1024; - j = COM_CheckParm("-mem"); + j = COM_CheckParm ("-mem"); if (j) - host_parms.memsize = (int) (atof(com_argv[j+1]) * 1024 * 1024); + host_parms.memsize = (int) (atof (com_argv[j + 1]) * 1024 * 1024); if ((host_parms.membase = malloc (host_parms.memsize)) == NULL) - Sys_Error("Can't allocate %d\n", host_parms.memsize); + Sys_Error ("Can't allocate %d\n", host_parms.memsize); SV_Init (); // run one frame immediately for first heartbeat - SV_Frame (0.1); + SV_Frame (0.1); - // + // // main loop - // + // oldtime = Sys_DoubleTime () - 0.1; while (1) { // select on the net socket and stdin // the only reason we have a timeout at all is so that if the last // connected client times out, the message would not otherwise // be printed until the next event. - FD_ZERO(&fdset); + FD_ZERO (&fdset); if (do_stdin) - FD_SET(0, &fdset); - FD_SET(net_socket, &fdset); + FD_SET (0, &fdset); + FD_SET (net_socket, &fdset); timeout.tv_sec = 1; timeout.tv_usec = 0; - if (select (net_socket+1, &fdset, NULL, NULL, &timeout) == -1) + if (select (net_socket + 1, &fdset, NULL, NULL, &timeout) == -1) continue; - stdin_ready = FD_ISSET(0, &fdset); + stdin_ready = FD_ISSET (0, &fdset); // find time passed since last cycle newtime = Sys_DoubleTime (); time = newtime - oldtime; oldtime = newtime; - - SV_Frame (time); - + + SV_Frame (time); + // extrasleep is just a way to generate a fucked up connection on // purpose if (sys_extrasleep->int_val) usleep (sys_extrasleep->int_val); - } + } return 1; } diff --git a/source/sv_sys_win.c b/source/sv_sys_win.c index da9437e..19dd5ff 100644 --- a/source/sv_sys_win.c +++ b/source/sv_sys_win.c @@ -41,28 +41,28 @@ #include "sys.h" -qboolean is_server = true; -qboolean WinNT; +qboolean is_server = true; +qboolean WinNT; -extern cvar_t *sys_nostdout; -cvar_t *sys_sleep; +extern cvar_t *sys_nostdout; +cvar_t *sys_sleep; /* ================ Sys_FileTime ================ */ -int Sys_FileTime (char *path) +int +Sys_FileTime (char *path) { - QFile *f; - - f = Qopen(path, "rb"); - if (f) - { - Qclose(f); + QFile *f; + + f = Qopen (path, "rb"); + if (f) { + Qclose (f); return 1; } - + return -1; } @@ -72,13 +72,14 @@ int Sys_FileTime (char *path) Sys_Error ================ */ -void Sys_Error (char *error, ...) +void +Sys_Error (char *error, ...) { - va_list argptr; - char text[1024]; + va_list argptr; + char text[1024]; - va_start (argptr,error); - vsnprintf (text, sizeof(text), error,argptr); + va_start (argptr, error); + vsnprintf (text, sizeof (text), error, argptr); va_end (argptr); // MessageBox(NULL, text, "Error", 0 /* MB_OK */ ); @@ -93,28 +94,25 @@ void Sys_Error (char *error, ...) Sys_ConsoleInput ================ */ -char *Sys_ConsoleInput (void) +char * +Sys_ConsoleInput (void) { - static char text[256]; - static int len; - int c; + static char text[256]; + static int len; + int c; // read a line out - while (kbhit()) - { - c = _getch(); + while (kbhit ()) { + c = _getch (); putch (c); - if (c == '\r') - { + if (c == '\r') { text[len] = 0; putch ('\n'); len = 0; return text; } - if (c == 8) - { - if (len) - { + if (c == 8) { + if (len) { putch (' '); putch (c); len--; @@ -125,7 +123,7 @@ char *Sys_ConsoleInput (void) text[len] = c; len++; text[len] = 0; - if (len == sizeof(text)) + if (len == sizeof (text)) len = 0; } @@ -137,7 +135,8 @@ char *Sys_ConsoleInput (void) Sys_Quit ================ */ -void Sys_Quit (void) +void +Sys_Quit (void) { exit (0); } @@ -154,29 +153,29 @@ is marked void Sys_Init_Cvars (void) { - sys_nostdout = Cvar_Get("sys_nostdout", "0", CVAR_NONE, "None"); - sys_sleep = Cvar_Get("sys_sleep", "8", CVAR_NONE, "None"); + sys_nostdout = Cvar_Get ("sys_nostdout", "0", CVAR_NONE, "None"); + sys_sleep = Cvar_Get ("sys_sleep", "8", CVAR_NONE, "None"); } -void Sys_Init (void) +void +Sys_Init (void) { - OSVERSIONINFO vinfo; + OSVERSIONINFO vinfo; #ifdef USE_INTEL_ASM - Sys_SetFPCW(); + Sys_SetFPCW (); #endif // make sure the timer is high precision, otherwise // NT gets 18ms resolution - timeBeginPeriod( 1 ); + timeBeginPeriod (1); - vinfo.dwOSVersionInfoSize = sizeof(vinfo); + vinfo.dwOSVersionInfoSize = sizeof (vinfo); if (!GetVersionEx (&vinfo)) Sys_Error ("Couldn't get OS info"); if ((vinfo.dwMajorVersion < 4) || - (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) - { + (vinfo.dwPlatformId == VER_PLATFORM_WIN32s)) { Sys_Error (PROGRAM " requires at least Win95 or NT 4.0"); } @@ -192,45 +191,41 @@ main ================== */ -char *newargv[256]; +char *newargv[256]; -int main (int argc, char **argv) +int +main (int argc, char **argv) { - double newtime, time, oldtime; - struct timeval timeout; - fd_set fdset; - int t; - int sleep_msec; + double newtime, time, oldtime; + struct timeval timeout; + fd_set fdset; + int t; + int sleep_msec; COM_InitArgv (argc, argv); - + host_parms.argc = com_argc; host_parms.argv = com_argv; - host_parms.memsize = 16*1024*1024; + host_parms.memsize = 16 * 1024 * 1024; - if ((t = COM_CheckParm ("-heapsize")) != 0 && - t + 1 < com_argc) + if ((t = COM_CheckParm ("-heapsize")) != 0 && t + 1 < com_argc) host_parms.memsize = atoi (com_argv[t + 1]) * 1024; - if ((t = COM_CheckParm ("-mem")) != 0 && - t + 1 < com_argc) + if ((t = COM_CheckParm ("-mem")) != 0 && t + 1 < com_argc) host_parms.memsize = atoi (com_argv[t + 1]) * 1024 * 1024; host_parms.membase = malloc (host_parms.memsize); if (!host_parms.membase) - Sys_Error("Insufficient memory.\n"); + Sys_Error ("Insufficient memory.\n"); SV_Init (); - if (COM_CheckParm ("-nopriority")) - { + if (COM_CheckParm ("-nopriority")) { Cvar_Set (sys_sleep, "0"); - } - else - { - if ( ! SetPriorityClass (GetCurrentProcess(), HIGH_PRIORITY_CLASS)) + } else { + if (!SetPriorityClass (GetCurrentProcess (), HIGH_PRIORITY_CLASS)) Con_Printf ("SetPriorityClass() failed\n"); else Con_Printf ("Process priority class set to HIGH\n"); @@ -241,44 +236,39 @@ int main (int argc, char **argv) Cvar_Set (sys_sleep, "0"); // run one frame immediately for first heartbeat - SV_Frame (0.1); + SV_Frame (0.1); // // main loop // oldtime = Sys_DoubleTime () - 0.1; - while (1) - { - // Now we want to give some processing time to other applications, - // such as qw_client, running on this machine. + while (1) { + // Now we want to give some processing time to other applications, + // such as qw_client, running on this machine. sleep_msec = sys_sleep->int_val; - if (sleep_msec > 0) - { + if (sleep_msec > 0) { if (sleep_msec > 13) sleep_msec = 13; Sleep (sleep_msec); } - - // select on the net socket and stdin - // the only reason we have a timeout at all is so that if the last - // connected client times out, the message would not otherwise - // be printed until the next event. - FD_ZERO(&fdset); - FD_SET(net_socket, &fdset); + // select on the net socket and stdin + // the only reason we have a timeout at all is so that if the last + // connected client times out, the message would not otherwise + // be printed until the next event. + FD_ZERO (&fdset); + FD_SET (net_socket, &fdset); timeout.tv_sec = 0; timeout.tv_usec = 100; - if (select (net_socket+1, &fdset, NULL, NULL, &timeout) == -1) + if (select (net_socket + 1, &fdset, NULL, NULL, &timeout) == -1) continue; - // find time passed since last cycle + // find time passed since last cycle newtime = Sys_DoubleTime (); time = newtime - oldtime; oldtime = newtime; - - SV_Frame (time); - } + + SV_Frame (time); + } return true; } - - diff --git a/source/sv_user.c b/source/sv_user.c index 54da881..f1c3e98 100644 --- a/source/sv_user.c +++ b/source/sv_user.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "va.h" #include "server.h" @@ -50,29 +50,29 @@ #include #include -edict_t *sv_player; +edict_t *sv_player; -usercmd_t cmd; +usercmd_t cmd; -cvar_t *cl_rollspeed; -cvar_t *cl_rollangle; -cvar_t *sv_spectalk; +cvar_t *cl_rollspeed; +cvar_t *cl_rollangle; +cvar_t *sv_spectalk; -cvar_t *sv_mapcheck; +cvar_t *sv_mapcheck; -cvar_t *sv_timekick; -cvar_t *sv_timekick_fuzz; -cvar_t *sv_timekick_interval; +cvar_t *sv_timekick; +cvar_t *sv_timekick_fuzz; +cvar_t *sv_timekick_interval; -extern cvar_t *sv_maxrate; +extern cvar_t *sv_maxrate; -extern vec3_t player_mins; +extern vec3_t player_mins; -extern int fp_messages, fp_persecond, fp_secondsdead; +extern int fp_messages, fp_persecond, fp_secondsdead; extern char fp_msg[]; extern cvar_t *pausable; -void SV_FullClientUpdateToClient (client_t *client, client_t *cl); +void SV_FullClientUpdateToClient (client_t *client, client_t *cl); /* ============================================================ @@ -91,11 +91,12 @@ Sends the first message from the server to a connected client. This will be sent on the initial connection and upon each server load. ================ */ -void SV_New_f (void) +void +SV_New_f (void) { - char *gamedir; - int playernum; - cvar_t *r_skyname; + char *gamedir; + int playernum; + cvar_t *r_skyname; if (host_client->state == cs_spawned) return; @@ -104,8 +105,8 @@ void SV_New_f (void) host_client->connection_started = realtime; // send the info about the new client to all connected clients -// SV_FullClientUpdate (host_client, &sv.reliable_datagram); -// host_client->sendinfo = true; +// SV_FullClientUpdate (host_client, &sv.reliable_datagram); +// host_client->sendinfo = true; gamedir = Info_ValueForKey (svs.info, "*gamedir"); if (!gamedir[0]) @@ -114,36 +115,37 @@ void SV_New_f (void) //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (host_client->num_backbuf) { - Con_Printf("WARNING %s: [SV_New] Back buffered (%d0, clearing", host_client->name, host_client->netchan.message.cursize); + Con_Printf ("WARNING %s: [SV_New] Back buffered (%d0, clearing", + host_client->name, host_client->netchan.message.cursize); host_client->num_backbuf = 0; - SZ_Clear(&host_client->netchan.message); + SZ_Clear (&host_client->netchan.message); } - // send the serverdata MSG_WriteByte (&host_client->netchan.message, svc_serverdata); MSG_WriteLong (&host_client->netchan.message, PROTOCOL_VERSION); MSG_WriteLong (&host_client->netchan.message, svs.spawncount); MSG_WriteString (&host_client->netchan.message, gamedir); - playernum = NUM_FOR_EDICT(host_client->edict)-1; + playernum = NUM_FOR_EDICT (host_client->edict) - 1; if (host_client->spectator) playernum |= 128; MSG_WriteByte (&host_client->netchan.message, playernum); // send full levelname - MSG_WriteString (&host_client->netchan.message, PR_GetString(sv.edicts->v.message)); + MSG_WriteString (&host_client->netchan.message, + PR_GetString (sv.edicts->v.message)); // send the movevars - MSG_WriteFloat(&host_client->netchan.message, movevars.gravity); - MSG_WriteFloat(&host_client->netchan.message, movevars.stopspeed); - MSG_WriteFloat(&host_client->netchan.message, movevars.maxspeed); - MSG_WriteFloat(&host_client->netchan.message, movevars.spectatormaxspeed); - MSG_WriteFloat(&host_client->netchan.message, movevars.accelerate); - MSG_WriteFloat(&host_client->netchan.message, movevars.airaccelerate); - MSG_WriteFloat(&host_client->netchan.message, movevars.wateraccelerate); - MSG_WriteFloat(&host_client->netchan.message, movevars.friction); - MSG_WriteFloat(&host_client->netchan.message, movevars.waterfriction); - MSG_WriteFloat(&host_client->netchan.message, movevars.entgravity); + MSG_WriteFloat (&host_client->netchan.message, movevars.gravity); + MSG_WriteFloat (&host_client->netchan.message, movevars.stopspeed); + MSG_WriteFloat (&host_client->netchan.message, movevars.maxspeed); + MSG_WriteFloat (&host_client->netchan.message, movevars.spectatormaxspeed); + MSG_WriteFloat (&host_client->netchan.message, movevars.accelerate); + MSG_WriteFloat (&host_client->netchan.message, movevars.airaccelerate); + MSG_WriteFloat (&host_client->netchan.message, movevars.wateraccelerate); + MSG_WriteFloat (&host_client->netchan.message, movevars.friction); + MSG_WriteFloat (&host_client->netchan.message, movevars.waterfriction); + MSG_WriteFloat (&host_client->netchan.message, movevars.entgravity); // send music MSG_WriteByte (&host_client->netchan.message, svc_cdtrack); @@ -151,15 +153,15 @@ void SV_New_f (void) // send server info string MSG_WriteByte (&host_client->netchan.message, svc_stufftext); - MSG_WriteString (&host_client->netchan.message, va("fullserverinfo \"%s\"\n", svs.info) ); + MSG_WriteString (&host_client->netchan.message, + va ("fullserverinfo \"%s\"\n", svs.info)); // Send our current skybox r_skyname = Cvar_FindVar ("r_skyname"); - if (r_skyname != NULL) - { + if (r_skyname != NULL) { MSG_WriteByte (&host_client->netchan.message, svc_stufftext); - MSG_WriteString (&host_client->netchan.message, va("r_skyname %s", - r_skyname->string)); + MSG_WriteString (&host_client->netchan.message, va ("r_skyname %s", + r_skyname->string)); } } @@ -168,46 +170,43 @@ void SV_New_f (void) SV_Soundlist_f ================== */ -void SV_Soundlist_f (void) +void +SV_Soundlist_f (void) { - char **s; - unsigned n; + char **s; + unsigned n; - if (host_client->state != cs_connected) - { + if (host_client->state != cs_connected) { Con_Printf ("soundlist not valid -- allready spawned\n"); return; } - // handle the case of a level changing while a client was connecting - if ( atoi(Cmd_Argv(1)) != svs.spawncount ) - { + if (atoi (Cmd_Argv (1)) != svs.spawncount) { Con_Printf ("SV_Soundlist_f from different level\n"); SV_New_f (); return; } - n = atoi(Cmd_Argv(2)); + n = atoi (Cmd_Argv (2)); if (n >= MAX_SOUNDS) { Con_Printf ("SV_Soundlist_f: Invalid soundlist index\n"); SV_New_f (); return; } - //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (host_client->num_backbuf) { - Con_Printf("WARNING %s: [SV_Soundlist] Back buffered (%d0, clearing", host_client->name, host_client->netchan.message.cursize); + Con_Printf ("WARNING %s: [SV_Soundlist] Back buffered (%d0, clearing", + host_client->name, host_client->netchan.message.cursize); host_client->num_backbuf = 0; - SZ_Clear(&host_client->netchan.message); + SZ_Clear (&host_client->netchan.message); } MSG_WriteByte (&host_client->netchan.message, svc_soundlist); MSG_WriteByte (&host_client->netchan.message, n); - for (s = sv.sound_precache+1 + n ; - *s && host_client->netchan.message.cursize < (MAX_MSGLEN/2); - s++, n++) - MSG_WriteString (&host_client->netchan.message, *s); + for (s = sv.sound_precache + 1 + n; + *s && host_client->netchan.message.cursize < (MAX_MSGLEN / 2); + s++, n++) MSG_WriteString (&host_client->netchan.message, *s); MSG_WriteByte (&host_client->netchan.message, 0); @@ -223,46 +222,43 @@ void SV_Soundlist_f (void) SV_Modellist_f ================== */ -void SV_Modellist_f (void) +void +SV_Modellist_f (void) { - char **s; - unsigned n; + char **s; + unsigned n; - if (host_client->state != cs_connected) - { + if (host_client->state != cs_connected) { Con_Printf ("modellist not valid -- allready spawned\n"); return; } - // handle the case of a level changing while a client was connecting - if ( atoi(Cmd_Argv(1)) != svs.spawncount ) - { + if (atoi (Cmd_Argv (1)) != svs.spawncount) { Con_Printf ("SV_Modellist_f from different level\n"); SV_New_f (); return; } - n = atoi(Cmd_Argv(2)); + n = atoi (Cmd_Argv (2)); if (n >= MAX_MODELS) { Con_Printf ("SV_Modellist_f: Invalid modellist index\n"); SV_New_f (); return; } - //NOTE: This doesn't go through ClientReliableWrite since it's before the user //spawns. These functions are written to not overflow if (host_client->num_backbuf) { - Con_Printf("WARNING %s: [SV_Modellist] Back buffered (%d0, clearing", host_client->name, host_client->netchan.message.cursize); + Con_Printf ("WARNING %s: [SV_Modellist] Back buffered (%d0, clearing", + host_client->name, host_client->netchan.message.cursize); host_client->num_backbuf = 0; - SZ_Clear(&host_client->netchan.message); + SZ_Clear (&host_client->netchan.message); } MSG_WriteByte (&host_client->netchan.message, svc_modellist); MSG_WriteByte (&host_client->netchan.message, n); - for (s = sv.model_precache+1+n ; - *s && host_client->netchan.message.cursize < (MAX_MSGLEN/2); - s++, n++) - MSG_WriteString (&host_client->netchan.message, *s); + for (s = sv.model_precache + 1 + n; + *s && host_client->netchan.message.cursize < (MAX_MSGLEN / 2); + s++, n++) MSG_WriteString (&host_client->netchan.message, *s); MSG_WriteByte (&host_client->netchan.message, 0); // next msg @@ -277,66 +273,67 @@ void SV_Modellist_f (void) SV_PreSpawn_f ================== */ -void SV_PreSpawn_f (void) +void +SV_PreSpawn_f (void) { - unsigned int buf; - unsigned int check; + unsigned int buf; + unsigned int check; - if (host_client->state != cs_connected) - { + if (host_client->state != cs_connected) { Con_Printf ("prespawn not valid -- allready spawned\n"); return; } - // handle the case of a level changing while a client was connecting if (atoi (Cmd_Argv (1)) != svs.spawncount) { Con_Printf ("SV_PreSpawn_f from different level\n"); SV_New_f (); return; } - - buf = atoi(Cmd_Argv(2)); + + buf = atoi (Cmd_Argv (2)); if (buf >= sv.num_signon_buffers) buf = 0; if (!buf) { // should be three numbers following containing checksums - check = atoi(Cmd_Argv(3)); + check = atoi (Cmd_Argv (3)); -// Con_DPrintf("Client check = %d\n", check); +// Con_DPrintf("Client check = %d\n", check); if (sv_mapcheck->int_val && check != sv.worldmodel->checksum && check != sv.worldmodel->checksum2) { - SV_ClientPrintf (host_client, PRINT_HIGH, - "Map model file does not match (%s), %i != %i/%i.\n" - "You may need a new version of the map, or the proper install files.\n", - sv.modelname, check, sv.worldmodel->checksum, sv.worldmodel->checksum2); - SV_DropClient (host_client); + SV_ClientPrintf (host_client, PRINT_HIGH, + "Map model file does not match (%s), %i != %i/%i.\n" + "You may need a new version of the map, or the proper install files.\n", + sv.modelname, check, sv.worldmodel->checksum, + sv.worldmodel->checksum2); + SV_DropClient (host_client); return; } host_client->checksum = check; } - - // NOTE: This doesn't go through ClientReliableWrite since it's before the user + // NOTE: This doesn't go through ClientReliableWrite since it's before + // the user // spawns. These functions are written to not overflow if (host_client->num_backbuf) { - Con_Printf("WARNING %s: [SV_PreSpawn] Back buffered (%d0, clearing", host_client->name, host_client->netchan.message.cursize); + Con_Printf ("WARNING %s: [SV_PreSpawn] Back buffered (%d0, clearing", + host_client->name, host_client->netchan.message.cursize); host_client->num_backbuf = 0; - SZ_Clear(&host_client->netchan.message); + SZ_Clear (&host_client->netchan.message); } - SZ_Write (&host_client->netchan.message, - sv.signon_buffers[buf], - sv.signon_buffer_size[buf]); + SZ_Write (&host_client->netchan.message, + sv.signon_buffers[buf], sv.signon_buffer_size[buf]); buf++; if (buf == sv.num_signon_buffers) { // all done prespawning MSG_WriteByte (&host_client->netchan.message, svc_stufftext); - MSG_WriteString (&host_client->netchan.message, va("cmd spawn %i 0\n",svs.spawncount) ); - } else { // need to prespawn more + MSG_WriteString (&host_client->netchan.message, + va ("cmd spawn %i 0\n", svs.spawncount)); + } else { // need to prespawn more MSG_WriteByte (&host_client->netchan.message, svc_stufftext); - MSG_WriteString (&host_client->netchan.message, - va("cmd prespawn %i %i\n", svs.spawncount, buf) ); + MSG_WriteString (&host_client->netchan.message, + va ("cmd prespawn %i %i\n", svs.spawncount, buf)); } } @@ -345,19 +342,19 @@ void SV_PreSpawn_f (void) SV_Spawn_f ================== */ -void SV_Spawn_f (void) +void +SV_Spawn_f (void) { - int i; - client_t *client; - edict_t *ent; - eval_t *val; - int n; + int i; + client_t *client; + edict_t *ent; + eval_t *val; + int n; if (host_client->state != cs_connected) { Con_Printf ("Spawn not valid -- allready spawned\n"); return; } - // handle the case of a level changing while a client was connecting if (atoi (Cmd_Argv (1)) != svs.spawncount) { Con_Printf ("SV_Spawn_f from different level\n"); @@ -373,7 +370,6 @@ void SV_Spawn_f (void) SV_New_f (); return; } - // send all current names, colors, and frag counts // FIXME: is this a good thing? SZ_Clear (&host_client->netchan.message); @@ -381,14 +377,18 @@ void SV_Spawn_f (void) // send current status of all other players // normally this could overflow, but no need to check due to backbuf - for (i=n, client = svs.clients + n ; iedict; memset (&ent->v, 0, progs->entityfields * 4); - ent->v.colormap = NUM_FOR_EDICT(ent); - ent->v.team = 0; // FIXME - ent->v.netname = PR_SetString(host_client->name); + ent->v.colormap = NUM_FOR_EDICT (ent); + ent->v.team = 0; // FIXME + ent->v.netname = PR_SetString (host_client->name); host_client->entgravity = 1.0; - val = GetEdictFieldValue(ent, "gravity"); + val = GetEdictFieldValue (ent, "gravity"); if (val) val->_float = 1.0; host_client->maxspeed = sv_maxspeed->value; - val = GetEdictFieldValue(ent, "maxspeed"); + val = GetEdictFieldValue (ent, "maxspeed"); if (val) val->_float = sv_maxspeed->value; // // force stats to be updated // - memset (host_client->stats, 0, sizeof(host_client->stats)); + memset (host_client->stats, 0, sizeof (host_client->stats)); ClientReliableWrite_Begin (host_client, svc_updatestatlong, 6); ClientReliableWrite_Byte (host_client, STAT_TOTALSECRETS); @@ -433,7 +433,7 @@ void SV_Spawn_f (void) // get the client to check and download skins // when that is completed, a begin command will be issued ClientReliableWrite_Begin (host_client, svc_stufftext, 8); - ClientReliableWrite_String (host_client, "skins\n" ); + ClientReliableWrite_String (host_client, "skins\n"); } /* @@ -441,21 +441,20 @@ void SV_Spawn_f (void) SV_SpawnSpectator ================== */ -void SV_SpawnSpectator (void) +void +SV_SpawnSpectator (void) { - int i; - edict_t *e; + int i; + edict_t *e; VectorCopy (vec3_origin, sv_player->v.origin); VectorCopy (vec3_origin, sv_player->v.view_ofs); sv_player->v.view_ofs[2] = 22; // search for an info_playerstart to spawn the spectator at - for (i=MAX_CLIENTS-1 ; iv.classname), "info_player_start")) - { + for (i = MAX_CLIENTS - 1; i < sv.num_edicts; i++) { + e = EDICT_NUM (i); + if (!strcmp (PR_GetString (e->v.classname), "info_player_start")) { VectorCopy (e->v.origin, sv_player->v.origin); return; } @@ -468,16 +467,17 @@ void SV_SpawnSpectator (void) SV_Begin_f ================== */ -void SV_Begin_f (void) +void +SV_Begin_f (void) { unsigned int pmodel = 0, emodel = 0; - int i; + int i; if (host_client->state == cs_spawned) - return; // don't begin again + return; // don't begin again host_client->state = cs_spawned; - + // handle the case of a level changing while a client was connecting if (atoi (Cmd_Argv (1)) != svs.spawncount) { Con_Printf ("SV_Begin_f from different level\n"); @@ -492,10 +492,10 @@ void SV_Begin_f (void) // copy spawn parms out of the client_t for (i = 0; i < NUM_SPAWN_PARMS; i++) (&pr_global_struct->parm1)[i] = host_client->spawn_parms[i]; - + // call the spawn function pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (SpectatorConnect); } } else { @@ -505,13 +505,13 @@ void SV_Begin_f (void) // call the spawn function pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (pr_global_struct->ClientConnect); // actually spawn the player pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); - PR_ExecuteProgram (pr_global_struct->PutClientInServer); + pr_global_struct->self = EDICT_TO_PROG (sv_player); + PR_ExecuteProgram (pr_global_struct->PutClientInServer); } // clear the net statistics, because connecting gives a bogus picture @@ -526,15 +526,16 @@ void SV_Begin_f (void) emodel = atoi (Info_ValueForKey (host_client->userinfo, "emodel")); if (pmodel != sv.model_player_checksum || emodel != sv.eyes_player_checksum) - SV_BroadcastPrintf (PRINT_HIGH, "%s WARNING: non standard player/eyes model detected\n", host_client->name); + SV_BroadcastPrintf (PRINT_HIGH, + "%s WARNING: non standard player/eyes model detected\n", + host_client->name); // if we are paused, tell the client if (sv.paused) { ClientReliableWrite_Begin (host_client, svc_setpause, 2); ClientReliableWrite_Byte (host_client, sv.paused); - SV_ClientPrintf(host_client, PRINT_HIGH, "Server is paused.\n"); + SV_ClientPrintf (host_client, PRINT_HIGH, "Server is paused.\n"); } - #if 0 // // send a fixangle over the reliable channel to make sure it gets there @@ -542,11 +543,11 @@ void SV_Begin_f (void) // in a state where it is expecting the client to correct the angle // and it won't happen if the game was just loaded, so you wind up // with a permanent head tilt - ent = EDICT_NUM( 1 + (host_client - svs.clients) ); + ent = EDICT_NUM (1 + (host_client - svs.clients)); MSG_WriteByte (&host_client->netchan.message, svc_setangle); - for (i=0 ; i < 2 ; i++) - MSG_WriteAngle (&host_client->netchan.message, ent->v.angles[i] ); - MSG_WriteAngle (&host_client->netchan.message, 0 ); + for (i = 0; i < 2; i++) + MSG_WriteAngle (&host_client->netchan.message, ent->v.angles[i]); + MSG_WriteAngle (&host_client->netchan.message, 0); #endif } @@ -557,12 +558,13 @@ void SV_Begin_f (void) SV_NextDownload_f ================== */ -void SV_NextDownload_f (void) +void +SV_NextDownload_f (void) { - byte buffer[1024]; - int r; - int percent; - int size; + byte buffer[1024]; + int r; + int percent; + int size; if (!host_client->download) return; @@ -571,14 +573,14 @@ void SV_NextDownload_f (void) if (r > 768) r = 768; r = Qread (host_client->download, buffer, r); - ClientReliableWrite_Begin (host_client, svc_download, 6+r); + ClientReliableWrite_Begin (host_client, svc_download, 6 + r); ClientReliableWrite_Short (host_client, r); host_client->downloadcount += r; size = host_client->downloadsize; if (!size) size = 1; - percent = host_client->downloadcount*100/size; + percent = host_client->downloadcount * 100 / size; ClientReliableWrite_Byte (host_client, percent); ClientReliableWrite_SZ (host_client, buffer, r); @@ -590,21 +592,22 @@ void SV_NextDownload_f (void) } -void OutofBandPrintf(netadr_t where, char *fmt, ...) +void +OutofBandPrintf (netadr_t where, char *fmt, ...) { - va_list argptr; - char send[1024]; - + va_list argptr; + char send[1024]; + send[0] = 0xff; send[1] = 0xff; send[2] = 0xff; send[3] = 0xff; send[4] = A2C_PRINT; va_start (argptr, fmt); - vsnprintf (send+5, sizeof(send-5), fmt, argptr); + vsnprintf (send + 5, sizeof (send - 5), fmt, argptr); va_end (argptr); - NET_SendPacket (strlen(send)+1, send, where); + NET_SendPacket (strlen (send) + 1, send, where); } /* @@ -612,18 +615,20 @@ void OutofBandPrintf(netadr_t where, char *fmt, ...) SV_NextUpload ================== */ -void SV_NextUpload (void) +void +SV_NextUpload (void) { - int percent; - int size; + int percent; + int size; if (!*host_client->uploadfn) { - SV_ClientPrintf(host_client, PRINT_HIGH, "Upload denied\n"); + SV_ClientPrintf (host_client, PRINT_HIGH, "Upload denied\n"); ClientReliableWrite_Begin (host_client, svc_stufftext, 8); ClientReliableWrite_String (host_client, "stopul"); // suck out rest of packet - size = MSG_ReadShort (); MSG_ReadByte (); + size = MSG_ReadShort (); + MSG_ReadByte (); msg_readcount += size; return; } @@ -631,25 +636,27 @@ void SV_NextUpload (void) size = MSG_ReadShort (); percent = MSG_ReadByte (); - if (!host_client->upload) - { - host_client->upload = Qopen(host_client->uploadfn, "wb"); + if (!host_client->upload) { + host_client->upload = Qopen (host_client->uploadfn, "wb"); if (!host_client->upload) { - Sys_Printf("Can't create %s\n", host_client->uploadfn); + Sys_Printf ("Can't create %s\n", host_client->uploadfn); ClientReliableWrite_Begin (host_client, svc_stufftext, 8); ClientReliableWrite_String (host_client, "stopul"); *host_client->uploadfn = 0; return; } - Sys_Printf("Receiving %s from %d...\n", host_client->uploadfn, host_client->userid); + Sys_Printf ("Receiving %s from %d...\n", host_client->uploadfn, + host_client->userid); if (host_client->remote_snap) - OutofBandPrintf(host_client->snap_from, "Server receiving %s from %d...\n", host_client->uploadfn, host_client->userid); + OutofBandPrintf (host_client->snap_from, + "Server receiving %s from %d...\n", + host_client->uploadfn, host_client->userid); } Qwrite (host_client->upload, net_message.data + msg_readcount, size); msg_readcount += size; -Con_DPrintf ("UPLOAD: %d received\n", size); + Con_DPrintf ("UPLOAD: %d received\n", size); if (percent != 100) { ClientReliableWrite_Begin (host_client, svc_stufftext, 8); @@ -658,17 +665,18 @@ Con_DPrintf ("UPLOAD: %d received\n", size); Qclose (host_client->upload); host_client->upload = NULL; - Sys_Printf("%s upload completed.\n", host_client->uploadfn); + Sys_Printf ("%s upload completed.\n", host_client->uploadfn); if (host_client->remote_snap) { - char *p; + char *p; - if ((p = strchr(host_client->uploadfn, '/')) != NULL) + if ((p = strchr (host_client->uploadfn, '/')) != NULL) p++; else p = host_client->uploadfn; - OutofBandPrintf(host_client->snap_from, "%s upload completed.\nTo download, enter:\ndownload %s\n", - host_client->uploadfn, p); + OutofBandPrintf (host_client->snap_from, + "%s upload completed.\nTo download, enter:\ndownload %s\n", + host_client->uploadfn, p); } } @@ -679,40 +687,40 @@ Con_DPrintf ("UPLOAD: %d received\n", size); SV_BeginDownload_f ================== */ -void SV_BeginDownload_f(void) +void +SV_BeginDownload_f (void) { - char *name; - QFile *file; - int size; - char realname[MAX_OSPATH]; - int zip; + char *name; + QFile *file; + int size; + char realname[MAX_OSPATH]; + int zip; - extern cvar_t *allow_download; - extern cvar_t *allow_download_skins; - extern cvar_t *allow_download_models; - extern cvar_t *allow_download_sounds; - extern cvar_t *allow_download_maps; - extern int file_from_pak; // ZOID did file come from pak? + extern cvar_t *allow_download; + extern cvar_t *allow_download_skins; + extern cvar_t *allow_download_models; + extern cvar_t *allow_download_sounds; + extern cvar_t *allow_download_maps; + extern int file_from_pak; // ZOID did file come from pak? - name = Cmd_Argv(1); + name = Cmd_Argv (1); // hacked by zoid to allow more conrol over download - // first off, no .. or global allow check + // first off, no .. or global allow check if (strstr (name, "..") || !allow_download->int_val // leading dot is no good - || *name == '.' + || *name == '.' // leading slash bad as well, must be in subdir || *name == '/' // next up, skin check - || (strncmp(name, "skins/", 6) == 0 && !allow_download_skins->int_val) + || (strncmp (name, "skins/", 6) == 0 && !allow_download_skins->int_val) // now models - || (strncmp(name, "progs/", 6) == 0 && !allow_download_models->int_val) + || (strncmp (name, "progs/", 6) == 0 && !allow_download_models->int_val) // now sounds - || (strncmp(name, "sound/", 6) == 0 && !allow_download_sounds->int_val) + || (strncmp (name, "sound/", 6) == 0 && !allow_download_sounds->int_val) // now maps (note special case for maps, must not be in pak) - || (strncmp(name, "maps/", 6) == 0 && !allow_download_maps->int_val) - // MUST be in a subdirectory - || !strstr (name, "/") ) - { // don't allow anything with .. path + || (strncmp (name, "maps/", 6) == 0 && !allow_download_maps->int_val) + // MUST be in a subdirectory + || !strstr (name, "/")) { // don't allow anything with .. path ClientReliableWrite_Begin (host_client, svc_download, 4); ClientReliableWrite_Short (host_client, -1); ClientReliableWrite_Byte (host_client, 0); @@ -723,16 +731,15 @@ void SV_BeginDownload_f(void) Qclose (host_client->download); host_client->download = NULL; } - // lowercase name (needed for casesen file systems) { - char *p; + char *p; for (p = name; *p; p++) - *p = tolower((int)*p); + *p = tolower ((int) *p); } - zip = strchr(Info_ValueForKey (host_client->userinfo, "*cap"), 'z') != 0; + zip = strchr (Info_ValueForKey (host_client->userinfo, "*cap"), 'z') != 0; size = _COM_FOpenFile (name, &file, realname, !zip); @@ -743,10 +750,9 @@ void SV_BeginDownload_f(void) if (!host_client->download // special check for maps, if it came from a pak file, don't allow // download ZOID - || (strncmp(name, "maps/", 5) == 0 && file_from_pak)) - { + || (strncmp (name, "maps/", 5) == 0 && file_from_pak)) { if (host_client->download) { - Qclose(host_client->download); + Qclose (host_client->download); host_client->download = NULL; } @@ -760,7 +766,7 @@ void SV_BeginDownload_f(void) if (zip && strcmp (realname, name)) { Sys_Printf ("download renamed to %s\n", realname); ClientReliableWrite_Begin (host_client, svc_download, - strlen(realname)+5); + strlen (realname) + 5); ClientReliableWrite_Short (host_client, -2); ClientReliableWrite_Byte (host_client, 0); ClientReliableWrite_String (host_client, realname); @@ -778,50 +784,52 @@ void SV_BeginDownload_f(void) SV_Say ================== */ -void SV_Say (qboolean team) +void +SV_Say (qboolean team) { - client_t *client; - int j, tmp; - char *p; - char text[2048]; - char t1[32], *t2; + client_t *client; + int j, tmp; + char *p; + char text[2048]; + char t1[32], *t2; if (Cmd_Argc () < 2) return; - if (team) - { + if (team) { strncpy (t1, Info_ValueForKey (host_client->userinfo, "team"), 31); t1[31] = 0; } if (host_client->spectator && (!sv_spectalk->int_val || team)) - snprintf (text, sizeof(text), "[SPEC] %s: ", host_client->name); + snprintf (text, sizeof (text), "[SPEC] %s: ", host_client->name); else if (team) - snprintf (text, sizeof(text), "(%s): ", host_client->name); + snprintf (text, sizeof (text), "(%s): ", host_client->name); else { - snprintf (text, sizeof(text), "%s: ", host_client->name); + snprintf (text, sizeof (text), "%s: ", host_client->name); } if (fp_messages) { - if (!sv.paused && realtimelockedtill) { - SV_ClientPrintf(host_client, PRINT_CHAT, - "You can't talk for %d more seconds\n", - (int) (host_client->lockedtill - realtime)); + if (!sv.paused && realtime < host_client->lockedtill) { + SV_ClientPrintf (host_client, PRINT_CHAT, + "You can't talk for %d more seconds\n", + (int) (host_client->lockedtill - realtime)); return; } tmp = host_client->whensaidhead - fp_messages + 1; if (tmp < 0) - tmp = 10+tmp; + tmp = 10 + tmp; if (!sv.paused && - host_client->whensaid[tmp] && (realtime-host_client->whensaid[tmp] < fp_persecond)) { + host_client->whensaid[tmp] + && (realtime - host_client->whensaid[tmp] < fp_persecond)) { host_client->lockedtill = realtime + fp_secondsdead; if (fp_msg[0]) - SV_ClientPrintf(host_client, PRINT_CHAT, - "FloodProt: %s\n", fp_msg); + SV_ClientPrintf (host_client, PRINT_CHAT, + "FloodProt: %s\n", fp_msg); else - SV_ClientPrintf(host_client, PRINT_CHAT, - "FloodProt: You can't talk for %d seconds.\n", fp_secondsdead); + SV_ClientPrintf (host_client, PRINT_CHAT, + "FloodProt: You can't talk for %d seconds.\n", + fp_secondsdead); return; } host_client->whensaidhead++; @@ -830,40 +838,37 @@ void SV_Say (qboolean team) host_client->whensaid[host_client->whensaidhead] = realtime; } - p = Cmd_Args(); + p = Cmd_Args (); - if (*p == '"') - { + if (*p == '"') { p++; - p[strlen(p)-1] = 0; + p[strlen (p) - 1] = 0; } - strncat (text, p, sizeof(text) - strlen (text)); - strncat (text, "\n", sizeof(text) - strlen (text)); + strncat (text, p, sizeof (text) - strlen (text)); + strncat (text, "\n", sizeof (text) - strlen (text)); Sys_Printf ("%s", text); - for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) - { + for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) { if (client->state != cs_spawned) continue; if (host_client->spectator && !sv_spectalk->int_val) if (!client->spectator) continue; - if (team) - { + if (team) { // the spectator team if (host_client->spectator) { if (!client->spectator) continue; } else { t2 = Info_ValueForKey (client->userinfo, "team"); - if (strcmp(t1, t2) || client->spectator) - continue; // on different teams + if (strcmp (t1, t2) || client->spectator) + continue; // on different teams } } - SV_ClientPrintf(client, PRINT_CHAT, "%s", text); + SV_ClientPrintf (client, PRINT_CHAT, "%s", text); } } @@ -873,16 +878,19 @@ void SV_Say (qboolean team) SV_Say_f ================== */ -void SV_Say_f(void) +void +SV_Say_f (void) { SV_Say (false); } + /* ================== SV_Say_Team_f ================== */ -void SV_Say_Team_f(void) +void +SV_Say_Team_f (void) { SV_Say (true); } @@ -899,19 +907,19 @@ The client is showing the scoreboard, so send new ping times for all clients ================= */ -void SV_Pings_f (void) +void +SV_Pings_f (void) { - client_t *client; - int j; + client_t *client; + int j; - for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) - { + for (j = 0, client = svs.clients; j < MAX_CLIENTS; j++, client++) { if (client->state != cs_spawned) continue; ClientReliableWrite_Begin (host_client, svc_updateping, 4); ClientReliableWrite_Byte (host_client, j); - ClientReliableWrite_Short (host_client, SV_CalcPing(client)); + ClientReliableWrite_Short (host_client, SV_CalcPing (client)); ClientReliableWrite_Begin (host_client, svc_updatepl, 4); ClientReliableWrite_Byte (host_client, j); ClientReliableWrite_Byte (host_client, client->lossage); @@ -925,16 +933,17 @@ void SV_Pings_f (void) SV_Kill_f ================== */ -void SV_Kill_f (void) +void +SV_Kill_f (void) { - if (sv_player->v.health <= 0) - { - SV_ClientPrintf (host_client, PRINT_HIGH, "Can't suicide -- allready dead!\n"); + if (sv_player->v.health <= 0) { + SV_ClientPrintf (host_client, PRINT_HIGH, + "Can't suicide -- allready dead!\n"); return; } - + pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (pr_global_struct->ClientKill); } @@ -943,10 +952,11 @@ void SV_Kill_f (void) SV_TogglePause ================== */ -void SV_TogglePause (const char *msg) +void +SV_TogglePause (const char *msg) { - int i; - client_t *cl; + int i; + client_t *cl; sv.paused ^= 1; @@ -954,8 +964,7 @@ void SV_TogglePause (const char *msg) SV_BroadcastPrintf (PRINT_HIGH, "%s", msg); // send notification to all clients - for (i=0, cl = svs.clients ; istate) continue; ClientReliableWrite_Begin (cl, svc_setpause, 2); @@ -969,20 +978,21 @@ void SV_TogglePause (const char *msg) SV_Pause_f ================== */ -void SV_Pause_f (void) +void +SV_Pause_f (void) { static double lastpausetime; - double currenttime; - char st[sizeof(host_client->name) + 32]; + double currenttime; + char st[sizeof (host_client->name) + 32]; - currenttime=Sys_DoubleTime(); + currenttime = Sys_DoubleTime (); - if (lastpausetime+1>currenttime) { + if (lastpausetime + 1 > currenttime) { SV_ClientPrintf (host_client, PRINT_HIGH, "Pause flood not allowed.\n"); return; - } + } - lastpausetime=currenttime; + lastpausetime = currenttime; if (!pausable->int_val) { SV_ClientPrintf (host_client, PRINT_HIGH, "Pause not allowed.\n"); @@ -990,16 +1000,17 @@ void SV_Pause_f (void) } if (host_client->spectator) { - SV_ClientPrintf (host_client, PRINT_HIGH, "Spectators can not pause.\n"); + SV_ClientPrintf (host_client, PRINT_HIGH, + "Spectators can not pause.\n"); return; } if (!sv.paused) - snprintf (st, sizeof(st), "%s paused the game\n", host_client->name); + snprintf (st, sizeof (st), "%s paused the game\n", host_client->name); else - snprintf (st, sizeof(st), "%s unpaused the game\n", host_client->name); + snprintf (st, sizeof (st), "%s unpaused the game\n", host_client->name); - SV_TogglePause(st); + SV_TogglePause (st); } @@ -1010,12 +1021,13 @@ SV_Drop_f The client is going to disconnect, so remove the connection immediately ================= */ -void SV_Drop_f (void) +void +SV_Drop_f (void) { SV_EndRedirect (); if (!host_client->spectator) SV_BroadcastPrintf (PRINT_HIGH, "%s dropped\n", host_client->name); - SV_DropClient (host_client); + SV_DropClient (host_client); } /* @@ -1025,39 +1037,39 @@ SV_PTrack_f Change the bandwidth estimate for a client ================= */ -void SV_PTrack_f (void) +void +SV_PTrack_f (void) { - int i; - edict_t *ent, *tent; - + int i; + edict_t *ent, *tent; + if (!host_client->spectator) return; - if (Cmd_Argc() != 2) - { + if (Cmd_Argc () != 2) { // turn off tracking host_client->spec_track = 0; - ent = EDICT_NUM(host_client - svs.clients + 1); - tent = EDICT_NUM(0); - ent->v.goalentity = EDICT_TO_PROG(tent); + ent = EDICT_NUM (host_client - svs.clients + 1); + tent = EDICT_NUM (0); + ent->v.goalentity = EDICT_TO_PROG (tent); return; } - - i = atoi(Cmd_Argv(1)); + + i = atoi (Cmd_Argv (1)); if (i < 0 || i >= MAX_CLIENTS || svs.clients[i].state != cs_spawned || svs.clients[i].spectator) { SV_ClientPrintf (host_client, PRINT_HIGH, "Invalid client to track\n"); host_client->spec_track = 0; - ent = EDICT_NUM(host_client - svs.clients + 1); - tent = EDICT_NUM(0); - ent->v.goalentity = EDICT_TO_PROG(tent); + ent = EDICT_NUM (host_client - svs.clients + 1); + tent = EDICT_NUM (0); + ent->v.goalentity = EDICT_TO_PROG (tent); return; } - host_client->spec_track = i + 1; // now tracking + host_client->spec_track = i + 1; // now tracking - ent = EDICT_NUM(host_client - svs.clients + 1); - tent = EDICT_NUM(i + 1); - ent->v.goalentity = EDICT_TO_PROG(tent); + ent = EDICT_NUM (host_client - svs.clients + 1); + tent = EDICT_NUM (i + 1); + ent->v.goalentity = EDICT_TO_PROG (tent); } @@ -1069,14 +1081,14 @@ void SV_PTrack_f (void) void SV_Rate_f (void) { - int rate; - + int rate; + if (Cmd_Argc () != 2) { SV_ClientPrintf (host_client, PRINT_HIGH, "Current rate is %i\n", - (int) (1.0 / host_client->netchan.rate + 0.5)); + (int) (1.0 / host_client->netchan.rate + 0.5)); return; } - + rate = atoi (Cmd_Argv (1)); if ((sv_maxrate->int_val) && (rate > sv_maxrate->int_val)) { rate = bound (500, rate, sv_maxrate->int_val); @@ -1096,17 +1108,17 @@ SV_Rate_f (void) */ void SV_Msg_f (void) -{ - if (Cmd_Argc () != 2) - { +{ + if (Cmd_Argc () != 2) { SV_ClientPrintf (host_client, PRINT_HIGH, "Current msg level is %i\n", - host_client->messagelevel); + host_client->messagelevel); return; } - + host_client->messagelevel = atoi (Cmd_Argv (1)); - SV_ClientPrintf (host_client, PRINT_HIGH, "Msg level set to %i\n", host_client->messagelevel); + SV_ClientPrintf (host_client, PRINT_HIGH, "Msg level set to %i\n", + host_client->messagelevel); } /* @@ -1117,8 +1129,8 @@ SV_Msg_f (void) void SV_SetInfo_f (void) { - int i; - char oldval[MAX_INFO_STRING]; + int i; + char oldval[MAX_INFO_STRING]; if (Cmd_Argc () == 1) { @@ -1133,19 +1145,22 @@ SV_SetInfo_f (void) } if (Cmd_Argv (1)[0] == '*') - return; // don't set priveledged values + return; // don't set priveledged values strcpy (oldval, Info_ValueForKey (host_client->userinfo, Cmd_Argv (1))); - Info_SetValueForKey (host_client->userinfo, Cmd_Argv (1), Cmd_Argv (2), MAX_INFO_STRING); + Info_SetValueForKey (host_client->userinfo, Cmd_Argv (1), Cmd_Argv (2), + MAX_INFO_STRING); // name is extracted below in ExtractFromUserInfo -// strncpy (host_client->name, Info_ValueForKey (host_client->userinfo, "name") -// , sizeof(host_client->name)-1); -// SV_FullClientUpdate (host_client, &sv.reliable_datagram); -// host_client->sendinfo = true; +// strncpy (host_client->name, Info_ValueForKey (host_client->userinfo, "name") +// , sizeof(host_client->name)-1); +// SV_FullClientUpdate (host_client, &sv.reliable_datagram); +// host_client->sendinfo = true; - if (strequal (Info_ValueForKey (host_client->userinfo, Cmd_Argv (1)), oldval)) - return; // key hasn't changed + if (strequal + (Info_ValueForKey (host_client->userinfo, Cmd_Argv (1)), oldval)) return; // key + // hasn't + // changed // process any changed values SV_ExtractFromUserinfo (host_client); @@ -1153,8 +1168,9 @@ SV_SetInfo_f (void) i = host_client - svs.clients; MSG_WriteByte (&sv.reliable_datagram, svc_setinfo); MSG_WriteByte (&sv.reliable_datagram, i); - MSG_WriteString (&sv.reliable_datagram, Cmd_Argv(1)); - MSG_WriteString (&sv.reliable_datagram, Info_ValueForKey(host_client->userinfo, Cmd_Argv(1))); + MSG_WriteString (&sv.reliable_datagram, Cmd_Argv (1)); + MSG_WriteString (&sv.reliable_datagram, + Info_ValueForKey (host_client->userinfo, Cmd_Argv (1))); } /* @@ -1173,16 +1189,17 @@ SV_NoSnap_f (void) { if (*host_client->uploadfn) { *host_client->uploadfn = 0; - SV_BroadcastPrintf (PRINT_HIGH, "%s refused remote screenshot\n", host_client->name); + SV_BroadcastPrintf (PRINT_HIGH, "%s refused remote screenshot\n", + host_client->name); } } typedef struct { - char *name; - void (*func) (void); + char *name; + void (*func) (void); } ucmd_t; -ucmd_t ucmds[] = { +ucmd_t ucmds[] = { {"new", SV_New_f}, {"modellist", SV_Modellist_f}, {"soundlist", SV_Soundlist_f}, @@ -1193,7 +1210,7 @@ ucmd_t ucmds[] = { {"drop", SV_Drop_f}, {"pings", SV_Pings_f}, -// issued by hand at client consoles +// issued by hand at client consoles {"rate", SV_Rate_f}, {"kill", SV_Kill_f}, {"pause", SV_Pause_f}, @@ -1209,10 +1226,10 @@ ucmd_t ucmds[] = { {"download", SV_BeginDownload_f}, {"nextdl", SV_NextDownload_f}, - {"ptrack", SV_PTrack_f}, //ZOID - used with autocam + {"ptrack", SV_PTrack_f}, // ZOID - used with autocam {"snap", SV_NoSnap_f}, - + {NULL, NULL} }; @@ -1224,8 +1241,8 @@ ucmd_t ucmds[] = { void SV_ExecuteUserCommand (char *s) { - ucmd_t *u; - + ucmd_t *u; + Cmd_TokenizeString (s); sv_player = host_client->edict; @@ -1262,25 +1279,25 @@ Used by view and sv_user float SV_CalcRoll (vec3_t angles, vec3_t velocity) { - vec3_t forward, right, up; - float sign; - float side; - float value; - + vec3_t forward, right, up; + float sign; + float side; + float value; + AngleVectors (angles, forward, right, up); side = DotProduct (velocity, right); sign = side < 0 ? -1 : 1; - side = fabs(side); - + side = fabs (side); + value = cl_rollangle->value; if (side < cl_rollspeed->value) side = side * value / cl_rollspeed->value; else side = value; - - return side*sign; - + + return side * sign; + } @@ -1288,7 +1305,7 @@ SV_CalcRoll (vec3_t angles, vec3_t velocity) //============================================================================ -vec3_t pmove_mins, pmove_maxs; +vec3_t pmove_mins, pmove_maxs; /* ==================== @@ -1296,34 +1313,32 @@ AddLinksToPmove ==================== */ -void AddLinksToPmove ( areanode_t *node ) +void +AddLinksToPmove (areanode_t *node) { - link_t *l, *next; - edict_t *check; - int pl; - int i; - physent_t *pe; + link_t *l, *next; + edict_t *check; + int pl; + int i; + physent_t *pe; - pl = EDICT_TO_PROG(sv_player); + pl = EDICT_TO_PROG (sv_player); // touch linked edicts - for (l = node->solid_edicts.next ; l != &node->solid_edicts ; l = next) - { + for (l = node->solid_edicts.next; l != &node->solid_edicts; l = next) { next = l->next; - check = EDICT_FROM_AREA(l); + check = EDICT_FROM_AREA (l); if (check->v.owner == pl) - continue; // player's own missile - if (check->v.solid == SOLID_BSP - || check->v.solid == SOLID_BBOX - || check->v.solid == SOLID_SLIDEBOX) - { + continue; // player's own missile + if (check->v.solid == SOLID_BSP + || check->v.solid == SOLID_BBOX || check->v.solid == SOLID_SLIDEBOX) { if (check == sv_player) continue; - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) if (check->v.absmin[i] > pmove_maxs[i] - || check->v.absmax[i] < pmove_mins[i]) + || check->v.absmax[i] < pmove_mins[i]) break; if (i != 3) continue; @@ -1333,10 +1348,10 @@ void AddLinksToPmove ( areanode_t *node ) pmove.numphysent++; VectorCopy (check->v.origin, pe->origin); - pe->info = NUM_FOR_EDICT(check); + pe->info = NUM_FOR_EDICT (check); if (check->v.solid == SOLID_BSP) { - pe->model = sv.models[(int)(check->v.modelindex)]; + pe->model = sv.models[(int) (check->v.modelindex)]; } else { pe->model = NULL; VectorCopy (check->v.mins, pe->mins); @@ -1344,7 +1359,7 @@ void AddLinksToPmove ( areanode_t *node ) } } } - + // recurse down both sides if (node->axis == -1) return; @@ -1364,32 +1379,30 @@ AddAllEntsToPmove For debugging ================ */ -void AddAllEntsToPmove (void) +void +AddAllEntsToPmove (void) { - int e; - edict_t *check; - int i; - physent_t *pe; - int pl; + int e; + edict_t *check; + int i; + physent_t *pe; + int pl; - pl = EDICT_TO_PROG(sv_player); - check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) continue; if (check->v.owner == pl) continue; - if (check->v.solid == SOLID_BSP - || check->v.solid == SOLID_BBOX - || check->v.solid == SOLID_SLIDEBOX) - { + if (check->v.solid == SOLID_BSP + || check->v.solid == SOLID_BBOX || check->v.solid == SOLID_SLIDEBOX) { if (check == sv_player) continue; - for (i=0 ; i<3 ; i++) + for (i = 0; i < 3; i++) if (check->v.absmin[i] > pmove_maxs[i] - || check->v.absmax[i] < pmove_mins[i]) + || check->v.absmax[i] < pmove_mins[i]) break; if (i != 3) continue; @@ -1398,9 +1411,8 @@ void AddAllEntsToPmove (void) VectorCopy (check->v.origin, pe->origin); pmove.physents[pmove.numphysent].info = e; if (check->v.solid == SOLID_BSP) - pe->model = sv.models[(int)(check->v.modelindex)]; - else - { + pe->model = sv.models[(int) (check->v.modelindex)]; + else { pe->model = NULL; VectorCopy (check->v.mins, pe->mins); VectorCopy (check->v.maxs, pe->maxs); @@ -1418,11 +1430,12 @@ SV_PreRunCmd =========== Done before running a player command. Clears the touch array */ -byte playertouch[(MAX_EDICTS+7)/8]; +byte playertouch[(MAX_EDICTS + 7) / 8]; -void SV_PreRunCmd(void) +void +SV_PreRunCmd (void) { - memset(playertouch, 0, sizeof(playertouch)); + memset (playertouch, 0, sizeof (playertouch)); } /* @@ -1430,36 +1443,42 @@ void SV_PreRunCmd(void) SV_RunCmd =========== */ -extern qboolean nouse; // 1999-10-29 +USE fix by Maddes +extern qboolean nouse; // 1999-10-29 +USE fix by Maddes void SV_RunCmd (usercmd_t *ucmd, qboolean inside) { - edict_t *ent; - int i, n, oldmsec; - double tmp_time; - int tmp_time1; + edict_t *ent; + int i, n, oldmsec; + double tmp_time; + int tmp_time1; - if (!inside) { // prevent infinite loop + if (!inside) { // prevent infinite loop host_client->msecs += ucmd->msec; if ((sv_timekick->int_val) - && ((tmp_time = realtime - host_client->last_check) >= sv_timekick_interval->value)) { - + && ((tmp_time = realtime - host_client->last_check) >= + sv_timekick_interval->value)) { + tmp_time1 = tmp_time * (1000 + sv_timekick_fuzz->value); - if ((host_client->last_check != -1) // don't do it if new player - && (host_client->msecs > tmp_time1)) { + if ((host_client->last_check != -1) // don't do it if new player + && (host_client->msecs > tmp_time1)) { host_client->msec_cheating++; SV_BroadcastPrintf (PRINT_HIGH, - va ("%s thinks there are %d ms in %d seconds (Strike %d/%d)\n", - host_client->name, host_client->msecs, (int) tmp_time, - host_client->msec_cheating, sv_timekick->int_val)); + va + ("%s thinks there are %d ms in %d seconds (Strike %d/%d)\n", + host_client->name, host_client->msecs, + (int) tmp_time, host_client->msec_cheating, + sv_timekick->int_val)); if (host_client->msec_cheating >= sv_timekick->int_val) { SV_BroadcastPrintf (PRINT_HIGH, va ("Strike %d for %s!!\n", - host_client->msec_cheating, host_client->name)); - SV_BroadcastPrintf (PRINT_HIGH, "Please see http://www.quakeforge.net/speed_cheat.php for infomation on QuakeForge's time cheat protection, and to explain how some may be cheating without knowing it.\n"); + host_client-> + msec_cheating, + host_client->name)); + SV_BroadcastPrintf (PRINT_HIGH, + "Please see http://www.quakeforge.net/speed_cheat.php for infomation on QuakeForge's time cheat protection, and to explain how some may be cheating without knowing it.\n"); SV_DropClient (host_client); } } @@ -1474,9 +1493,9 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) // chop up very long commands if (cmd.msec > 50) { oldmsec = ucmd->msec; - cmd.msec = oldmsec/2; + cmd.msec = oldmsec / 2; SV_RunCmd (&cmd, 1); - cmd.msec = oldmsec/2; + cmd.msec = oldmsec / 2; cmd.impulse = 0; SV_RunCmd (&cmd, 1); return; @@ -1487,12 +1506,11 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) sv_player->v.button0 = ucmd->buttons & 1; // 1999-10-29 +USE fix by Maddes start - if (!nouse) - { - sv_player->v.button1 = (ucmd->buttons & 4)>>2; + if (!nouse) { + sv_player->v.button1 = (ucmd->buttons & 4) >> 2; } // 1999-10-29 +USE fix by Maddes end - sv_player->v.button2 = (ucmd->buttons & 2)>>1; + sv_player->v.button2 = (ucmd->buttons & 2) >> 1; if (ucmd->impulse) sv_player->v.impulse = ucmd->impulse; @@ -1501,27 +1519,28 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) // show 1/3 the pitch angle and all the roll angle if (sv_player->v.health > 0) { if (!sv_player->v.fixangle) { - sv_player->v.angles[PITCH] = -sv_player->v.v_angle[PITCH]/3; + sv_player->v.angles[PITCH] = -sv_player->v.v_angle[PITCH] / 3; sv_player->v.angles[YAW] = sv_player->v.v_angle[YAW]; } sv_player->v.angles[ROLL] = - SV_CalcRoll (sv_player->v.angles, sv_player->v.velocity)*4; + SV_CalcRoll (sv_player->v.angles, sv_player->v.velocity) * 4; } - sv_frametime = min(0.1, ucmd->msec * 0.001); - + sv_frametime = min (0.1, ucmd->msec * 0.001); + if (!host_client->spectator) { pr_global_struct->frametime = sv_frametime; pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (pr_global_struct->PlayerPreThink); SV_RunThink (sv_player); } - for (i=0 ; i<3 ; i++) - pmove.origin[i] = sv_player->v.origin[i] + (sv_player->v.mins[i] - player_mins[i]); + for (i = 0; i < 3; i++) + pmove.origin[i] = + sv_player->v.origin[i] + (sv_player->v.mins[i] - player_mins[i]); VectorCopy (sv_player->v.velocity, pmove.velocity); VectorCopy (sv_player->v.v_angle, pmove.angles); @@ -1537,7 +1556,7 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) movevars.entgravity = host_client->entgravity; movevars.maxspeed = host_client->maxspeed; - for (i=0 ; i<3 ; i++) { + for (i = 0; i < 3; i++) { pmove_mins[i] = pmove.origin[i] - 256; pmove_maxs[i] = pmove.origin[i] + 256; } @@ -1548,16 +1567,17 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) #endif #if 0 -{ - int before, after; + { + int before, after; - before = PM_TestPlayerPosition (pmove.origin); - PlayerMove (); - after = PM_TestPlayerPosition (pmove.origin); + before = PM_TestPlayerPosition (pmove.origin); + PlayerMove (); + after = PM_TestPlayerPosition (pmove.origin); - if (sv_player->v.health > 0 && before && !after ) - Con_Printf ("player %s got stuck in playermove!!!!\n", host_client->name); -} + if (sv_player->v.health > 0 && before && !after) + Con_Printf ("player %s got stuck in playermove!!!!\n", + host_client->name); + } #else PlayerMove (); #endif @@ -1567,18 +1587,20 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) sv_player->v.waterlevel = waterlevel; sv_player->v.watertype = watertype; if (onground != -1) { - sv_player->v.flags = (int)sv_player->v.flags | FL_ONGROUND; - sv_player->v.groundentity = EDICT_TO_PROG(EDICT_NUM(pmove.physents[onground].info)); + sv_player->v.flags = (int) sv_player->v.flags | FL_ONGROUND; + sv_player->v.groundentity = + EDICT_TO_PROG (EDICT_NUM (pmove.physents[onground].info)); } else { - sv_player->v.flags = (int)sv_player->v.flags & ~FL_ONGROUND; + sv_player->v.flags = (int) sv_player->v.flags & ~FL_ONGROUND; } - for (i=0 ; i<3 ; i++) - sv_player->v.origin[i] = pmove.origin[i] - (sv_player->v.mins[i] - player_mins[i]); + for (i = 0; i < 3; i++) + sv_player->v.origin[i] = + pmove.origin[i] - (sv_player->v.mins[i] - player_mins[i]); #if 0 // truncate velocity the same way the net protocol will - for (i=0 ; i<3 ; i++) - sv_player->v.velocity[i] = (int)pmove.velocity[i]; + for (i = 0; i < 3; i++) + sv_player->v.velocity[i] = (int) pmove.velocity[i]; #else VectorCopy (pmove.velocity, sv_player->v.velocity); #endif @@ -1590,15 +1612,15 @@ SV_RunCmd (usercmd_t *ucmd, qboolean inside) SV_LinkEdict (sv_player, true); // touch other objects - for (i=0 ; iv.touch || (playertouch[n/8]&(1<<(n%8)))) + ent = EDICT_NUM (n); + if (!ent->v.touch || (playertouch[n / 8] & (1 << (n % 8)))) continue; - pr_global_struct->self = EDICT_TO_PROG(ent); - pr_global_struct->other = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (ent); + pr_global_struct->other = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (ent->v.touch); - playertouch[n/8] |= 1 << (n%8); + playertouch[n / 8] |= 1 << (n % 8); } } } @@ -1609,18 +1631,19 @@ SV_PostRunCmd =========== Done after running a player command. */ -void SV_PostRunCmd(void) +void +SV_PostRunCmd (void) { // run post-think if (!host_client->spectator) { pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (pr_global_struct->PlayerPostThink); SV_RunNewmis (); } else if (SpectatorThink) { pr_global_struct->time = sv.time; - pr_global_struct->self = EDICT_TO_PROG(sv_player); + pr_global_struct->self = EDICT_TO_PROG (sv_player); PR_ExecuteProgram (SpectatorThink); } } @@ -1633,17 +1656,18 @@ SV_ExecuteClientMessage The current net_message is parsed for the given client =================== */ -void SV_ExecuteClientMessage (client_t *cl) +void +SV_ExecuteClientMessage (client_t *cl) { - int c; - char *s; - usercmd_t oldest, oldcmd, newcmd; - client_frame_t *frame; - vec3_t o; - qboolean move_issued = false; //only allow one move command - int checksumIndex; - byte checksum, calculatedChecksum; - int seq_hash; + int c; + char *s; + usercmd_t oldest, oldcmd, newcmd; + client_frame_t *frame; + vec3_t o; + qboolean move_issued = false; // only allow one move command + int checksumIndex; + byte checksum, calculatedChecksum; + int seq_hash; // calc ping time frame = &cl->frames[cl->netchan.incoming_acknowledged & UPDATE_MASK]; @@ -1654,7 +1678,8 @@ void SV_ExecuteClientMessage (client_t *cl) if (cl->netchan.incoming_sequence >= cl->netchan.outgoing_sequence) cl->netchan.outgoing_sequence = cl->netchan.incoming_sequence; else - cl->send_message = false; // don't reply, sequences have slipped + cl->send_message = false; // don't reply, sequences have + // slipped // save time for ping calculations cl->frames[cl->netchan.outgoing_sequence & UPDATE_MASK].senttime = realtime; @@ -1663,116 +1688,113 @@ void SV_ExecuteClientMessage (client_t *cl) host_client = cl; sv_player = host_client->edict; -// seq_hash = (cl->netchan.incoming_sequence & 0xffff) ; // ^ QW_CHECK_HASH; +// seq_hash = (cl->netchan.incoming_sequence & 0xffff) ; // ^ QW_CHECK_HASH; seq_hash = cl->netchan.incoming_sequence; - + // mark time so clients will know how much to predict // other players - cl->localtime = sv.time; - cl->delta_sequence = -1; // no delta unless requested - while (1) - { - if (msg_badread) - { + cl->localtime = sv.time; + cl->delta_sequence = -1; // no delta unless requested + while (1) { + if (msg_badread) { Con_Printf ("SV_ReadClientMessage: badread\n"); SV_DropClient (cl); return; - } + } c = MSG_ReadByte (); if (c == -1) - return; // Ender: Patched :) - - switch (c) - { - default: - Con_Printf ("SV_ReadClientMessage: unknown command char\n"); - SV_DropClient (cl); - return; - - case clc_nop: - break; + return; // Ender: Patched :) - case clc_delta: - cl->delta_sequence = MSG_ReadByte (); - break; + switch (c) { + default: + Con_Printf ("SV_ReadClientMessage: unknown command char\n"); + SV_DropClient (cl); + return; - case clc_move: - if (move_issued) - return; // someone is trying to cheat... - - move_issued = true; - - checksumIndex = MSG_GetReadCount(); - checksum = (byte)MSG_ReadByte (); - - // read loss percentage - cl->lossage = MSG_ReadByte(); - - MSG_ReadDeltaUsercmd (&nullcmd, &oldest); - MSG_ReadDeltaUsercmd (&oldest, &oldcmd); - MSG_ReadDeltaUsercmd (&oldcmd, &newcmd); - - if ( cl->state != cs_spawned ) + case clc_nop: break; - // if the checksum fails, ignore the rest of the packet - calculatedChecksum = COM_BlockSequenceCRCByte( - net_message.data + checksumIndex + 1, - MSG_GetReadCount() - checksumIndex - 1, - seq_hash); + case clc_delta: + cl->delta_sequence = MSG_ReadByte (); + break; - if (calculatedChecksum != checksum) - { - Con_DPrintf ("Failed command checksum for %s(%d) (%d != %d)\n", - cl->name, cl->netchan.incoming_sequence, checksum, calculatedChecksum); - return; - } + case clc_move: + if (move_issued) + return; // someone is trying to cheat... - if (!sv.paused) { - SV_PreRunCmd(); + move_issued = true; - if (net_drop < 20) - { - while (net_drop > 2) - { - SV_RunCmd (&cl->lastcmd, 0); - net_drop--; - } - if (net_drop > 1) - SV_RunCmd (&oldest, 0); - if (net_drop > 0) - SV_RunCmd (&oldcmd, 0); + checksumIndex = MSG_GetReadCount (); + checksum = (byte) MSG_ReadByte (); + + // read loss percentage + cl->lossage = MSG_ReadByte (); + + MSG_ReadDeltaUsercmd (&nullcmd, &oldest); + MSG_ReadDeltaUsercmd (&oldest, &oldcmd); + MSG_ReadDeltaUsercmd (&oldcmd, &newcmd); + + if (cl->state != cs_spawned) + break; + + // if the checksum fails, ignore the rest of the packet + calculatedChecksum = + COM_BlockSequenceCRCByte (net_message.data + checksumIndex + + 1, + MSG_GetReadCount () - + checksumIndex - 1, seq_hash); + + if (calculatedChecksum != checksum) { + Con_DPrintf + ("Failed command checksum for %s(%d) (%d != %d)\n", + cl->name, cl->netchan.incoming_sequence, checksum, + calculatedChecksum); + return; } - SV_RunCmd (&newcmd, 0); - SV_PostRunCmd(); - } + if (!sv.paused) { + SV_PreRunCmd (); - cl->lastcmd = newcmd; - cl->lastcmd.buttons = 0; // avoid multiple fires on lag - break; + if (net_drop < 20) { + while (net_drop > 2) { + SV_RunCmd (&cl->lastcmd, 0); + net_drop--; + } + if (net_drop > 1) + SV_RunCmd (&oldest, 0); + if (net_drop > 0) + SV_RunCmd (&oldcmd, 0); + } + SV_RunCmd (&newcmd, 0); + + SV_PostRunCmd (); + } + + cl->lastcmd = newcmd; + cl->lastcmd.buttons = 0; // avoid multiple fires on lag + break; - case clc_stringcmd: - s = MSG_ReadString (); - SV_ExecuteUserCommand (s); - break; + case clc_stringcmd: + s = MSG_ReadString (); + SV_ExecuteUserCommand (s); + break; - case clc_tmove: - o[0] = MSG_ReadCoord(); - o[1] = MSG_ReadCoord(); - o[2] = MSG_ReadCoord(); - // only allowed by spectators - if (host_client->spectator) { - VectorCopy(o, sv_player->v.origin); - SV_LinkEdict(sv_player, false); - } - break; + case clc_tmove: + o[0] = MSG_ReadCoord (); + o[1] = MSG_ReadCoord (); + o[2] = MSG_ReadCoord (); + // only allowed by spectators + if (host_client->spectator) { + VectorCopy (o, sv_player->v.origin); + SV_LinkEdict (sv_player, false); + } + break; - case clc_upload: - SV_NextUpload(); - break; + case clc_upload: + SV_NextUpload (); + break; } } @@ -1783,12 +1805,11 @@ void SV_ExecuteClientMessage (client_t *cl) SV_UserInit ============== */ -void SV_UserInit (void) +void +SV_UserInit (void) { - cl_rollspeed = Cvar_Get("cl_rollspeed", "200", CVAR_NONE, "None"); - cl_rollangle = Cvar_Get("cl_rollangle", "2", CVAR_NONE, "None"); - sv_spectalk = Cvar_Get("sv_spectalk", "1", CVAR_NONE, "None"); - sv_mapcheck = Cvar_Get("sv_mapcheck", "1", CVAR_NONE, "None"); + cl_rollspeed = Cvar_Get ("cl_rollspeed", "200", CVAR_NONE, "None"); + cl_rollangle = Cvar_Get ("cl_rollangle", "2", CVAR_NONE, "None"); + sv_spectalk = Cvar_Get ("sv_spectalk", "1", CVAR_NONE, "None"); + sv_mapcheck = Cvar_Get ("sv_mapcheck", "1", CVAR_NONE, "None"); } - - diff --git a/source/sw_model_alias.c b/source/sw_model_alias.c index 3c6712c..3d40e3b 100644 --- a/source/sw_model_alias.c +++ b/source/sw_model_alias.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "r_local.h" @@ -51,38 +51,39 @@ ALIAS MODELS ============================================================================== */ -extern aliashdr_t *pheader; +extern aliashdr_t *pheader; -extern stvert_t stverts[MAXALIASVERTS]; -extern mtriangle_t triangles[MAXALIASTRIS]; +extern stvert_t stverts[MAXALIASVERTS]; +extern mtriangle_t triangles[MAXALIASTRIS]; // a pose is a single set of vertexes. a frame may be // an animating sequence of poses -extern trivertx_t *poseverts[MAXALIASFRAMES]; -extern int posenum; +extern trivertx_t *poseverts[MAXALIASFRAMES]; +extern int posenum; -void *Mod_LoadSkin (byte *skin, int skinsize, int *pskinindex, int snum, int gnum) +void * +Mod_LoadSkin (byte * skin, int skinsize, int *pskinindex, int snum, int gnum) { - byte *pskin; - unsigned short *pusskin; - int i; + byte *pskin; + unsigned short *pusskin; + int i; pskin = Hunk_AllocName (skinsize * r_pixbytes, loadname); - *pskinindex = (byte *)pskin - (byte *)pheader; + *pskinindex = (byte *) pskin - (byte *) pheader; switch (r_pixbytes) { - case 1: - memcpy (pskin, skin, skinsize); - break; - case 2: - pusskin = (unsigned short*)skin; - for (i=0; i MAX_SKINS) Sys_Error ("Mod_LoadAliasModel: Invalid # of skins: %d\n", numskins); skinsize = pheader->mdl.skinwidth * pheader->mdl.skinheight; - pskindesc = Hunk_AllocName (numskins * sizeof (maliasskindesc_t), - loadname); - pheader->skindesc = (byte *)pskindesc - (byte *)pheader; + pskindesc = Hunk_AllocName (numskins * sizeof (maliasskindesc_t), loadname); - for (snum=0 ; snumskindesc = (byte *) pskindesc - (byte *) pheader; + + for (snum = 0; snum < numskins; snum++) { if (pskintype->type == ALIAS_SKIN_SINGLE) { - skin = (byte*)(pskintype+1); - skin = Mod_LoadSkin (skin, skinsize, &pskindesc[snum].skin, snum, 0); + skin = (byte *) (pskintype + 1); + skin = + Mod_LoadSkin (skin, skinsize, &pskindesc[snum].skin, snum, 0); } else { pskintype++; - pinskingroup = (daliasskingroup_t *)pskintype; + pinskingroup = (daliasskingroup_t *) pskintype; groupskins = LittleLong (pinskingroup->numskins); - t = (int)&((maliasskingroup_t*)0)->skindescs[groupskins]; + t = (int) &((maliasskingroup_t *) 0)->skindescs[groupskins]; paliasskingroup = Hunk_AllocName (t, loadname); paliasskingroup->numskins = groupskins; - *pskinindex = (byte *)paliasskingroup - (byte *)pheader; + *pskinindex = (byte *) paliasskingroup - (byte *) pheader; - pinskinintervals = (daliasskininterval_t *)(pinskingroup + 1); - poutskinintervals = Hunk_AllocName (groupskins * sizeof (float),loadname); - paliasskingroup->intervals = (byte *)poutskinintervals - (byte *)pheader; - for (gnum=0 ; gnumintervals = + (byte *) poutskinintervals - (byte *) pheader; + for (gnum = 0; gnum < groupskins; gnum++) { *poutskinintervals = LittleFloat (pinskinintervals->interval); if (*poutskinintervals <= 0) Sys_Error ("Mod_LoadAliasSkinGroup: interval<=0"); @@ -140,43 +145,48 @@ void *Mod_LoadAllSkins (int numskins, daliasskintype_t *pskintype, int *pskinind pinskinintervals++; } - pskintype = (void *)pinskinintervals; - skin = (byte *)pskintype; + pskintype = (void *) pinskinintervals; + skin = (byte *) pskintype; - for (gnum=0 ; gnumskindescs[snum].skin, snum, gnum); + for (gnum = 0; gnum < groupskins; gnum++) { + skin = + Mod_LoadSkin (skin, skinsize, + &paliasskingroup->skindescs[snum].skin, snum, + gnum); } } - pskintype = (daliasskintype_t*)skin; + pskintype = (daliasskintype_t *) skin; } return pskintype; } -void GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr) +void +GL_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr) { - int i, j; - stvert_t *pstverts; + int i, j; + stvert_t *pstverts; mtriangle_t *ptri; - int numv = hdr->mdl.numverts; - int numt = hdr->mdl.numtris; + int numv = hdr->mdl.numverts; + int numt = hdr->mdl.numtris; - pstverts = (stvert_t *)Hunk_AllocName(numv * sizeof(stvert_t),loadname); - ptri = (mtriangle_t *)Hunk_AllocName(numt * sizeof(mtriangle_t),loadname); + pstverts = (stvert_t *) Hunk_AllocName (numv * sizeof (stvert_t), loadname); + ptri = - hdr->stverts = (byte *)pstverts - (byte *)hdr; - hdr->triangles = (byte *)ptri - (byte *)hdr; + (mtriangle_t *) Hunk_AllocName (numt * sizeof (mtriangle_t), loadname); - for (i=0; istverts = (byte *) pstverts - (byte *) hdr; + hdr->triangles = (byte *) ptri - (byte *) hdr; + + for (i = 0; i < numv; i++) { pstverts[i].onseam = stverts[i].onseam; pstverts[i].s = stverts[i].s << 16; pstverts[i].t = stverts[i].t << 16; } - for (i=0; iname, pdaliasframe->name); - for (i=0 ; i<3 ; i++) - { - // these are byte values, so we don't have to worry about - // endianness + for (i = 0; i < 3; i++) { + // these are byte values, so we don't have to worry about + // endianness frame->bboxmin.v[i] = pdaliasframe->bboxmin.v[i]; frame->bboxmax.v[i] = pdaliasframe->bboxmax.v[i]; } - pinframe = (trivertx_t *)(pdaliasframe + 1); - pframe = Hunk_AllocName (pheader->mdl.numverts * sizeof(*pframe), loadname); + pinframe = (trivertx_t *) (pdaliasframe + 1); + pframe = + Hunk_AllocName (pheader->mdl.numverts * sizeof (*pframe), loadname); - frame->frame = (byte *)pframe - (byte *)pheader; + frame->frame = (byte *) pframe - (byte *) pheader; - for (j=0 ; jmdl.numverts ; j++) - { - int k; + for (j = 0; j < pheader->mdl.numverts; j++) { + int k; - // these are all byte values, so no need to deal with endianness + // these are all byte values, so no need to deal with endianness pframe[j].lightnormalindex = pinframe[j].lightnormalindex; - for (k=0 ; k<3 ; k++) - { + for (k = 0; k < 3; k++) { pframe[j].v[k] = pinframe[j].v[k]; } } pinframe += pheader->mdl.numverts; - return (void *)pinframe; + return (void *) pinframe; } @@ -234,41 +243,43 @@ void * Mod_LoadAliasFrame (void * pin, maliasframedesc_t *frame) Mod_LoadAliasGroup ================= */ -void * Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame) +void * +Mod_LoadAliasGroup (void *pin, maliasframedesc_t *frame) { - daliasgroup_t *pingroup; - maliasgroup_t *paliasgroup; - int i, numframes; - daliasinterval_t *pin_intervals; - float *poutintervals; - void *ptemp; - - pingroup = (daliasgroup_t *)pin; + daliasgroup_t *pingroup; + maliasgroup_t *paliasgroup; + int i, numframes; + daliasinterval_t *pin_intervals; + float *poutintervals; + void *ptemp; + + pingroup = (daliasgroup_t *) pin; numframes = LittleLong (pingroup->numframes); paliasgroup = Hunk_AllocName (sizeof (maliasgroup_t) + - (numframes - 1) * sizeof (paliasgroup->frames[0]), loadname); + (numframes - + 1) * sizeof (paliasgroup->frames[0]), + + loadname); paliasgroup->numframes = numframes; - for (i=0 ; i<3 ; i++) - { - // these are byte values, so we don't have to worry about endianness + for (i = 0; i < 3; i++) { + // these are byte values, so we don't have to worry about endianness frame->bboxmin.v[i] = pingroup->bboxmin.v[i]; frame->bboxmax.v[i] = pingroup->bboxmax.v[i]; } - frame->frame = (byte *)paliasgroup - (byte *)pheader; + frame->frame = (byte *) paliasgroup - (byte *) pheader; - pin_intervals = (daliasinterval_t *)(pingroup + 1); + pin_intervals = (daliasinterval_t *) (pingroup + 1); poutintervals = Hunk_AllocName (numframes * sizeof (float), loadname); - paliasgroup->intervals = (byte *)poutintervals - (byte *)pheader; + paliasgroup->intervals = (byte *) poutintervals - (byte *) pheader; - for (i=0 ; iinterval); if (*poutintervals <= 0.0) SV_Error ("Mod_LoadAliasGroup: interval<=0"); @@ -277,11 +288,12 @@ void * Mod_LoadAliasGroup (void * pin, maliasframedesc_t *frame) pin_intervals++; } - ptemp = (void *)pin_intervals; + ptemp = (void *) pin_intervals; - for (i=0 ; iframes[i]); + for (i = 0; i < numframes; i++) { + ptemp = + Mod_LoadAliasFrame (ptemp, + (maliasframedesc_t *) &paliasgroup->frames[i]); } return ptemp; diff --git a/source/sw_model_brush.c b/source/sw_model_brush.c index f1b8cad..053ea86 100644 --- a/source/sw_model_brush.c +++ b/source/sw_model_brush.c @@ -30,24 +30,24 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "model.h" -extern model_t *loadmodel; -extern char loadname[]; -extern byte *mod_base; +extern model_t *loadmodel; +extern char loadname[]; +extern byte *mod_base; -const int mod_lightmap_bytes=1; +const int mod_lightmap_bytes = 1; void -GL_SubdivideSurface(msurface_t *fa) +GL_SubdivideSurface (msurface_t *fa) { } void -Mod_ProcessTexture(miptex_t *mt, texture_t *tx) +Mod_ProcessTexture (miptex_t *mt, texture_t *tx) { } @@ -56,13 +56,13 @@ Mod_ProcessTexture(miptex_t *mt, texture_t *tx) Mod_LoadLighting ================= */ -void Mod_LoadLighting (lump_t *l) +void +Mod_LoadLighting (lump_t *l) { - if (!l->filelen) - { + if (!l->filelen) { loadmodel->lightdata = NULL; return; } - loadmodel->lightdata = Hunk_AllocName ( l->filelen, loadname); + loadmodel->lightdata = Hunk_AllocName (l->filelen, loadname); memcpy (loadmodel->lightdata, mod_base + l->fileofs, l->filelen); } diff --git a/source/sw_model_sprite.c b/source/sw_model_sprite.c index e5d7f93..66da552 100644 --- a/source/sw_model_sprite.c +++ b/source/sw_model_sprite.c @@ -30,7 +30,7 @@ // on the same machine. #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "model.h" @@ -38,32 +38,35 @@ #include "d_iface.h" #include "qendian.h" -extern model_t *loadmodel; -extern char loadname[]; +extern model_t *loadmodel; +extern char loadname[]; /* ================= Mod_LoadSpriteFrame ================= */ -void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int framenum) +void * +Mod_LoadSpriteFrame (void *pin, mspriteframe_t **ppframe, int framenum) { - dspriteframe_t *pinframe; - mspriteframe_t *pspriteframe; - int i, width, height, size, origin[2]; - unsigned short *ppixout; - byte *ppixin; + dspriteframe_t *pinframe; + mspriteframe_t *pspriteframe; + int i, width, height, size, origin[2]; + unsigned short *ppixout; + byte *ppixin; - pinframe = (dspriteframe_t *)pin; + pinframe = (dspriteframe_t *) pin; width = LittleLong (pinframe->width); height = LittleLong (pinframe->height); size = width * height; - pspriteframe = Hunk_AllocName (sizeof (mspriteframe_t) + size*r_pixbytes, + pspriteframe = Hunk_AllocName (sizeof (mspriteframe_t) + size * r_pixbytes, + loadname); memset (pspriteframe, 0, sizeof (mspriteframe_t) + size); + *ppframe = pspriteframe; pspriteframe->width = width; @@ -76,23 +79,18 @@ void * Mod_LoadSpriteFrame (void * pin, mspriteframe_t **ppframe, int framenum) pspriteframe->left = origin[0]; pspriteframe->right = width + origin[0]; - if (r_pixbytes == 1) - { - memcpy (&pspriteframe->pixels[0], (byte *)(pinframe + 1), size); - } - else if (r_pixbytes == 2) - { - ppixin = (byte *)(pinframe + 1); - ppixout = (unsigned short *)&pspriteframe->pixels[0]; + if (r_pixbytes == 1) { + memcpy (&pspriteframe->pixels[0], (byte *) (pinframe + 1), size); + } else if (r_pixbytes == 2) { + ppixin = (byte *) (pinframe + 1); + ppixout = (unsigned short *) &pspriteframe->pixels[0]; - for (i=0 ; i +# include "config.h" #endif #include "host.h" #include "r_local.h" -extern byte gammatable[256]; +extern byte gammatable[256]; -void V_CalcPowerupCshift (void); -qboolean V_CheckGamma (void); +void V_CalcPowerupCshift (void); +qboolean V_CheckGamma (void); /* ============= V_UpdatePalette ============= */ -void V_UpdatePalette (void) +void +V_UpdatePalette (void) { - int i, j; - qboolean new; - byte *basepal, *newpal; - byte pal[768]; - int r,g,b; - qboolean force; + int i, j; + qboolean new; + byte *basepal, *newpal; + byte pal[768]; + int r, g, b; + qboolean force; V_CalcPowerupCshift (); new = false; - for (i=0; i < NUM_CSHIFTS; i++) { + for (i = 0; i < NUM_CSHIFTS; i++) { if (cl.cshifts[i].percent != cl.prev_cshifts[i].percent) { new = true; cl.prev_cshifts[i].percent = cl.cshifts[i].percent; @@ -70,12 +71,12 @@ void V_UpdatePalette (void) } // drop the damage value - cl.cshifts[CSHIFT_DAMAGE].percent -= host_frametime*150; + cl.cshifts[CSHIFT_DAMAGE].percent -= host_frametime * 150; if (cl.cshifts[CSHIFT_DAMAGE].percent <= 0) cl.cshifts[CSHIFT_DAMAGE].percent = 0; // drop the bonus value - cl.cshifts[CSHIFT_BONUS].percent -= host_frametime*100; + cl.cshifts[CSHIFT_BONUS].percent -= host_frametime * 100; if (cl.cshifts[CSHIFT_BONUS].percent <= 0) cl.cshifts[CSHIFT_BONUS].percent = 0; @@ -86,16 +87,19 @@ void V_UpdatePalette (void) basepal = host_basepal; newpal = pal; - for (i=0 ; i<256 ; i++) { + for (i = 0; i < 256; i++) { r = basepal[0]; g = basepal[1]; b = basepal[2]; basepal += 3; - for (j=0 ; j>8; - g += (cl.cshifts[j].percent*(cl.cshifts[j].destcolor[1]-g))>>8; - b += (cl.cshifts[j].percent*(cl.cshifts[j].destcolor[2]-b))>>8; + for (j = 0; j < NUM_CSHIFTS; j++) { + r += + (cl.cshifts[j].percent * (cl.cshifts[j].destcolor[0] - r)) >> 8; + g += + (cl.cshifts[j].percent * (cl.cshifts[j].destcolor[1] - g)) >> 8; + b += + (cl.cshifts[j].percent * (cl.cshifts[j].destcolor[2] - b)) >> 8; } newpal[0] = gammatable[r]; @@ -109,18 +113,19 @@ void V_UpdatePalette (void) void BuildGammaTable (float b, float c) { - int i, inf; - + int i, inf; + if ((b == 1.0) && (c == 1.0)) { for (i = 0; i < 256; i++) gammatable[i] = i; return; } - - for (i = 0; i < 256; i++) { // weighted average toward the median, 127 - inf = (i * b); // gamma is brightness now, and positive + + for (i = 0; i < 256; i++) { // weighted average toward the + // median, 127 + inf = (i * b); // gamma is brightness now, and + // positive inf = bound (0, inf, 255); gammatable[i] = inf + (int) ((127 - inf) * (1 - c)); } } - diff --git a/source/sys_null.c b/source/sys_null.c index c7ed476..92edf4c 100644 --- a/source/sys_null.c +++ b/source/sys_null.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "errno.h" @@ -37,10 +37,11 @@ filelength ================ */ -int filelength (QFile *f) +int +filelength (QFile *f) { - int pos; - int end; + int pos; + int end; pos = Qtell (f); Qseek (f, 0, SEEK_END); @@ -51,21 +52,22 @@ int filelength (QFile *f) } -int Sys_FileTime (char *path) +int +Sys_FileTime (char *path) { - QFile *f; - - f = Qopen(path, "rb"); - if (f) - { - Qclose(f); + QFile *f; + + f = Qopen (path, "rb"); + if (f) { + Qclose (f); return 1; } - + return -1; } -void Sys_mkdir (char *path) +void +Sys_mkdir (char *path) { } @@ -78,75 +80,87 @@ SYSTEM IO =============================================================================== */ -void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) +void +Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) { } -void Sys_DebugLog(char *file, char *fmt, ...) +void +Sys_DebugLog (char *file, char *fmt, ...) { } -void Sys_Error (char *error, ...) +void +Sys_Error (char *error, ...) { - va_list argptr; + va_list argptr; - printf ("I_Error: "); - va_start (argptr,error); - vprintf (error,argptr); + printf ("I_Error: "); + va_start (argptr, error); + vprintf (error, argptr); va_end (argptr); printf ("\n"); exit (1); } -void Sys_Printf (char *fmt, ...) +void +Sys_Printf (char *fmt, ...) { - va_list argptr; - - va_start (argptr,fmt); - vprintf (fmt,argptr); + va_list argptr; + + va_start (argptr, fmt); + vprintf (fmt, argptr); va_end (argptr); } -void Sys_Quit (void) +void +Sys_Quit (void) { exit (0); } -double Sys_FloatTime (void) +double +Sys_FloatTime (void) { static double t; - + t += 0.1; - + return t; } -char *Sys_ConsoleInput (void) +char * +Sys_ConsoleInput (void) { return NULL; } -void Sys_Sleep (void) +void +Sys_Sleep (void) { } -void IN_SendKeyEvents (void) +void +IN_SendKeyEvents (void) { } -void Sys_HighFPPrecision (void) +void +Sys_HighFPPrecision (void) { } -void Sys_LowFPPrecision (void) +void +Sys_LowFPPrecision (void) { } //============================================================================= -void main (int argc, char **argv) +void +main (int argc, char **argv) { host_parms.memsize = 5861376; host_parms.membase = malloc (host_parms.memsize); @@ -158,10 +172,7 @@ void main (int argc, char **argv) printf ("Host_Init\n"); Host_Init (); - while (1) - { + while (1) { Host_Frame (0.1); } } - - diff --git a/source/sys_unix.c b/source/sys_unix.c index c8fbce4..82dd2cd 100644 --- a/source/sys_unix.c +++ b/source/sys_unix.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -45,46 +45,45 @@ #include "server.h" /* This is unused in the client, but we need the symbol there too. */ -server_static_t svs; +server_static_t svs; -cvar_t *sys_nostdout; +cvar_t *sys_nostdout; /* The translation table between the graphical font and plain ASCII --KB */ -static char qfont_table[256] = -{ - '\0', '#', '#', '#', '#', '.', '#', '#', - '#', 9, 10, '#', ' ', 13, '.', '.', - '[', ']', '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', '.', '<', '=', '>', - ' ', '!', '"', '#', '$', '%', '&', '\'', - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', - 'x', 'y', 'z', '{', '|', '}', '~', '<', +static char qfont_table[256] = { + '\0', '#', '#', '#', '#', '.', '#', '#', + '#', 9, 10, '#', ' ', 13, '.', '.', + '[', ']', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '.', '<', '=', '>', + ' ', '!', '"', '#', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', ':', ';', '<', '=', '>', '?', + '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z', '{', '|', '}', '~', '<', - '<', '=', '>', '#', '#', '.', '#', '#', - '#', '#', ' ', '#', ' ', '>', '.', '.', - '[', ']', '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', '.', '<', '=', '>', - ' ', '!', '"', '#', '$', '%', '&', '\'', - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', - 'x', 'y', 'z', '{', '|', '}', '~', '<' + '<', '=', '>', '#', '#', '.', '#', '#', + '#', '#', ' ', '#', ' ', '>', '.', '.', + '[', ']', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '.', '<', '=', '>', + ' ', '!', '"', '#', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', ':', ';', '<', '=', '>', '?', + '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z', '{', '|', '}', '~', '<' }; #define MAXPRINTMSG 4096 @@ -93,18 +92,19 @@ static char qfont_table[256] = Sys_Printf ================ */ -void Sys_Printf (char *fmt, ...) +void +Sys_Printf (char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; - unsigned char *p; + unsigned char *p; if (sys_nostdout && sys_nostdout->int_val) return; va_start (argptr, fmt); - vsnprintf(msg, sizeof (msg), fmt, argptr); + vsnprintf (msg, sizeof (msg), fmt, argptr); va_end (argptr); /* translate to ASCII instead of printing [xx] --KB */ @@ -122,12 +122,14 @@ Sys_FileTime returns -1 if not present ============ */ -int Sys_FileTime (char *path) +int +Sys_FileTime (char *path) { - struct stat buf; - - if (stat(path,&buf) == -1) return -1; - + struct stat buf; + + if (stat (path, &buf) == -1) + return -1; + return buf.st_mtime; } @@ -138,10 +140,13 @@ Sys_mkdir ============ */ -void Sys_mkdir (char *path) +void +Sys_mkdir (char *path) { - if (mkdir(path, 0777) == 0) return; - if (errno != EEXIST) Sys_Error("mkdir %s: %s",path, strerror(errno)); + if (mkdir (path, 0777) == 0) + return; + if (errno != EEXIST) + Sys_Error ("mkdir %s: %s", path, strerror (errno)); } @@ -150,19 +155,19 @@ void Sys_mkdir (char *path) Sys_DoubleTime ================ */ -double Sys_DoubleTime (void) +double +Sys_DoubleTime (void) { struct timeval tp; struct timezone tzp; - static int secbase; + static int secbase; - gettimeofday(&tp, &tzp); - - if (!secbase) - { + gettimeofday (&tp, &tzp); + + if (!secbase) { secbase = tp.tv_sec; - return tp.tv_usec/1000000.0; + return tp.tv_usec / 1000000.0; } - - return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0; + + return (tp.tv_sec - secbase) + tp.tv_usec / 1000000.0; } diff --git a/source/sys_win.c b/source/sys_win.c index 9900fc8..90194b7 100644 --- a/source/sys_win.c +++ b/source/sys_win.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "winquake.h" @@ -36,46 +36,45 @@ #include "server.h" /* This is unused in the client, but we need the symbol there too. */ -server_static_t svs; +server_static_t svs; -cvar_t *sys_nostdout; +cvar_t *sys_nostdout; /* The translation table between the graphical font and plain ASCII --KB */ -static char qfont_table[256] = -{ - '\0', '#', '#', '#', '#', '.', '#', '#', - '#', 9, 10, '#', ' ', 13, '.', '.', - '[', ']', '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', '.', '<', '=', '>', - ' ', '!', '"', '#', '$', '%', '&', '\'', - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', - 'x', 'y', 'z', '{', '|', '}', '~', '<', +static char qfont_table[256] = { + '\0', '#', '#', '#', '#', '.', '#', '#', + '#', 9, 10, '#', ' ', 13, '.', '.', + '[', ']', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '.', '<', '=', '>', + ' ', '!', '"', '#', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', ':', ';', '<', '=', '>', '?', + '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z', '{', '|', '}', '~', '<', - '<', '=', '>', '#', '#', '.', '#', '#', - '#', '#', ' ', '#', ' ', '>', '.', '.', - '[', ']', '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', '.', '<', '=', '>', - ' ', '!', '"', '#', '$', '%', '&', '\'', - '(', ')', '*', '+', ',', '-', '.', '/', - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', ':', ';', '<', '=', '>', '?', - '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', - 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', - 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', - 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', - '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', - 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', - 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', - 'x', 'y', 'z', '{', '|', '}', '~', '<' + '<', '=', '>', '#', '#', '.', '#', '#', + '#', '#', ' ', '#', ' ', '>', '.', '.', + '[', ']', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '.', '<', '=', '>', + ' ', '!', '"', '#', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', ':', ';', '<', '=', '>', '?', + '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z', '{', '|', '}', '~', '<' }; /* @@ -83,13 +82,14 @@ static char qfont_table[256] = Sys_DoubleTime ============== */ -double Sys_DoubleTime (void) +double +Sys_DoubleTime (void) { static DWORD starttime; static qboolean first = true; - DWORD now; + DWORD now; - now = timeGetTime(); + now = timeGetTime (); if (first) { first = false; @@ -97,7 +97,7 @@ double Sys_DoubleTime (void) return 0.0; } - if (now < starttime) // wrapped? + if (now < starttime) // wrapped? return (now / 1000.0) + (LONG_MAX - starttime / 1000.0); if (now - starttime == 0) @@ -112,12 +112,13 @@ double Sys_DoubleTime (void) Sys_Printf ================ */ -void Sys_Printf (char *fmt, ...) +void +Sys_Printf (char *fmt, ...) { - va_list argptr; - char msg[MAXPRINTMSG]; + va_list argptr; + char msg[MAXPRINTMSG]; - unsigned char *p; + unsigned char *p; if (sys_nostdout && sys_nostdout->int_val) return; @@ -138,8 +139,8 @@ void Sys_Printf (char *fmt, ...) Sys_mkdir ================ */ -void Sys_mkdir (char *path) +void +Sys_mkdir (char *path) { - _mkdir(path); + _mkdir (path); } - diff --git a/source/teamplay.c b/source/teamplay.c index 0247c15..2fd47cd 100644 --- a/source/teamplay.c +++ b/source/teamplay.c @@ -38,31 +38,30 @@ #include "console.h" #include "quakefs.h" -extern cvar_t *skin; -cvar_t *cl_deadbodyfilter; -cvar_t *cl_gibfilter; -cvar_t *cl_parsesay; -cvar_t *cl_nofake; -static qboolean died = false, recorded_location = false; -static vec3_t death_location, last_recorded_location; +extern cvar_t *skin; +cvar_t *cl_deadbodyfilter; +cvar_t *cl_gibfilter; +cvar_t *cl_parsesay; +cvar_t *cl_nofake; +static qboolean died = false, recorded_location = false; +static vec3_t death_location, last_recorded_location; -void Team_BestWeaponImpulse (void) +void +Team_BestWeaponImpulse (void) { - int best, i, imp, items; - extern int in_impulse; + int best, i, imp, items; + extern int in_impulse; items = cl.stats[STAT_ITEMS]; best = 0; - for (i = Cmd_Argc() - 1; i > 0; i--) - { - imp = atoi(Cmd_Argv(i)); + for (i = Cmd_Argc () - 1; i > 0; i--) { + imp = atoi (Cmd_Argv (i)); if (imp < 1 || imp > 8) continue; - switch (imp) - { + switch (imp) { case 1: if (items & IT_AXE) best = 1; @@ -94,40 +93,55 @@ void Team_BestWeaponImpulse (void) case 8: if (items & IT_LIGHTNING && cl.stats[STAT_CELLS] >= 1) best = 8; - + } } - + if (best) in_impulse = best; } -char *Team_ParseSay (char *s) +char * +Team_ParseSay (char *s) { - static char buf[1024]; - int i, bracket; - char c, chr, *t1, t2[128], t3[128]; - static location_t *location = NULL; + static char buf[1024]; + int i, bracket; + char c, chr, *t1, t2[128], t3[128]; + static location_t *location = NULL; if (!cl_parsesay->int_val) return s; i = 0; - while (*s && (i <= sizeof(buf))) { + while (*s && (i <= sizeof (buf))) { if (*s == '$') { c = 0; switch (s[1]) { - case '\\': c = 13; break; // fake message - case '[': c = 0x90; break; // colored brackets - case ']': c = 0x91; break; - case 'G': c = 0x86; break; // ocrana leds - case 'R': c = 0x87; break; - case 'Y': c = 0x88; break; - case 'B': c = 0x89; break; + case '\\': + c = 13; + break; // fake message + case '[': + c = 0x90; + break; // colored brackets + case ']': + c = 0x91; + break; + case 'G': + c = 0x86; + break; // ocrana leds + case 'R': + c = 0x87; + break; + case 'Y': + c = 0x88; + break; + case 'B': + c = 0x89; + break; } - + if (c) { buf[i++] = c; s += 2; @@ -135,8 +149,8 @@ char *Team_ParseSay (char *s) } } else if (*s == '%') { t1 = NULL; - memset(t2, '\0', sizeof(t2)); - memset(t3, '\0', sizeof(t3)); + memset (t2, '\0', sizeof (t2)); + memset (t3, '\0', sizeof (t3)); if ((s[1] == '[') && (s[3] == ']')) { bracket = 1; @@ -160,10 +174,10 @@ char *Team_ParseSay (char *s) case 'd': bracket = 0; if (died) { - location = locs_find(death_location); + location = locs_find (death_location); if (location) { recorded_location = true; - VectorCopy(death_location, last_recorded_location); + VectorCopy (death_location, last_recorded_location); t1 = location->name; break; } @@ -172,7 +186,7 @@ char *Team_ParseSay (char *s) case 'r': bracket = 0; if (recorded_location) { - location = locs_find(last_recorded_location); + location = locs_find (last_recorded_location); if (location) { t1 = location->name; break; @@ -180,15 +194,15 @@ char *Team_ParseSay (char *s) } goto location; case 'l': -location: + location: bracket = 0; - location = locs_find(cl.simorg); + location = locs_find (cl.simorg); if (location) { recorded_location = true; - VectorCopy(cl.simorg, last_recorded_location); + VectorCopy (cl.simorg, last_recorded_location); t1 = location->name; } else - snprintf(t2, sizeof(t2), "Unknown!\n"); + snprintf (t2, sizeof (t2), "Unknown!\n"); break; case 'a': if (bracket) { @@ -209,9 +223,10 @@ location: t2[4] = '!' | 0x80; } - snprintf(t2, sizeof(t2), "%sa:%i", t3, cl.stats[STAT_ARMOR]); + snprintf (t2, sizeof (t2), "%sa:%i", t3, + cl.stats[STAT_ARMOR]); } else - snprintf(t2, sizeof(t2), "%i", cl.stats[STAT_ARMOR]); + snprintf (t2, sizeof (t2), "%i", cl.stats[STAT_ARMOR]); break; case 'A': bracket = 0; @@ -233,9 +248,10 @@ location: if (bracket) { if (cl.stats[STAT_HEALTH] > 50) bracket = 0; - snprintf(t2, sizeof(t2), "h:%i", cl.stats[STAT_HEALTH]); + snprintf (t2, sizeof (t2), "h:%i", + cl.stats[STAT_HEALTH]); } else - snprintf(t2, sizeof(t2), "%i", cl.stats[STAT_HEALTH]); + snprintf (t2, sizeof (t2), "%i", cl.stats[STAT_HEALTH]); break; default: bracket = 0; @@ -251,19 +267,20 @@ location: } if (bracket) - buf[i++] = 0x90; // '[' + buf[i++] = 0x90; // '[' if (t1) { - int len; - len = strlen(t1); - if (i + len >= sizeof(buf)) - continue; // No more space in buffer, icky. - strncpy(buf + i, t1, len); + int len; + + len = strlen (t1); + if (i + len >= sizeof (buf)) + continue; // No more space in buffer, icky. + strncpy (buf + i, t1, len); i += len; } if (bracket) - buf[i++] = 0x91; // ']' + buf[i++] = 0x91; // ']' continue; } @@ -271,43 +288,48 @@ location: } buf[i] = 0; - return buf; + return buf; } -void Team_Dead () +void +Team_Dead () { died = true; - VectorCopy(cl.simorg, death_location); + VectorCopy (cl.simorg, death_location); } -void Team_NewMap () +void +Team_NewMap () { - char *mapname, *t1, *t2; + char *mapname, *t1, *t2; died = false; recorded_location = false; - mapname = strdup(cl.worldmodel->name); + mapname = strdup (cl.worldmodel->name); if (!mapname) - Sys_Error("Can't duplicate mapname!"); - t1 = strrchr(mapname, '/'); - t2 = strrchr(mapname, '.'); + Sys_Error ("Can't duplicate mapname!"); + t1 = strrchr (mapname, '/'); + t2 = strrchr (mapname, '.'); if (!t1 || !t2) - Sys_Error("Can't find / or .!"); - t1++; // skip over / + Sys_Error ("Can't find / or .!"); + t1++; // skip over / t2[0] = '\0'; - locs_reset(); - locs_load(t1); - free(mapname); + locs_reset (); + locs_load (t1); + free (mapname); } -void Team_Init_Cvars (void) +void +Team_Init_Cvars (void) { - cl_deadbodyfilter = Cvar_Get("cl_deadbodyfilter", "0", CVAR_NONE, "Hide dead player models"); - cl_gibfilter = Cvar_Get("cl_gibfilter", "0", CVAR_NONE, "Hide gibs"); - cl_parsesay = Cvar_Get("cl_parsesay", "0", CVAR_NONE, "None"); - cl_nofake = Cvar_Get("cl_nofake", "0", CVAR_NONE, "Unhide fake messages"); + cl_deadbodyfilter = + Cvar_Get ("cl_deadbodyfilter", "0", CVAR_NONE, + "Hide dead player models"); + cl_gibfilter = Cvar_Get ("cl_gibfilter", "0", CVAR_NONE, "Hide gibs"); + cl_parsesay = Cvar_Get ("cl_parsesay", "0", CVAR_NONE, "None"); + cl_nofake = Cvar_Get ("cl_nofake", "0", CVAR_NONE, "Unhide fake messages"); } /* @@ -318,48 +340,53 @@ void Team_Init_Cvars (void) // FIXME: No gzip'd loc file support -void locs_markloc() +void +locs_markloc () { - vec3_t loc; - char *mapname, *t1; - QFile *locfd; - char locfile[MAX_OSPATH]; - - if (Cmd_Argc() != 2) { - Con_Printf("markloc :marks the current location with the description and records the information into a loc file.\n"); + vec3_t loc; + char *mapname, *t1; + QFile *locfd; + char locfile[MAX_OSPATH]; + + if (Cmd_Argc () != 2) { + Con_Printf + ("markloc :marks the current location with the description and records the information into a loc file.\n"); return; } - VectorCopy(cl.simorg,loc); - locs_add(loc,Cmd_Argv(1)); + VectorCopy (cl.simorg, loc); + locs_add (loc, Cmd_Argv (1)); loc[0] *= 8; loc[1] *= 8; loc[2] *= 8; - mapname = strdup(cl.worldmodel->name); + mapname = strdup (cl.worldmodel->name); if (!mapname) - Sys_Error("Can't duplicate mapname!"); - t1 = strrchr(mapname, '.'); + Sys_Error ("Can't duplicate mapname!"); + t1 = strrchr (mapname, '.'); if (!t1) - Sys_Error("Can't find / or .!"); - t1++; // skip over / + Sys_Error ("Can't find / or .!"); + t1++; // skip over / t1[0] = 'l'; t1[1] = 'o'; t1[2] = 'c'; - snprintf(locfile, sizeof(locfile), "%s/%s",com_gamedir,mapname); - locfd = Qopen(locfile,"a+"); + snprintf (locfile, sizeof (locfile), "%s/%s", com_gamedir, mapname); + locfd = Qopen (locfile, "a+"); if (locfd == 0) { - Qopen(locfile,"w+"); + Qopen (locfile, "w+"); if (locfd == 0) { - Con_Printf("ERROR: Unable to open %s : %s\n",mapname,strerror(errno)); - free(mapname); + Con_Printf ("ERROR: Unable to open %s : %s\n", mapname, + strerror (errno)); + free (mapname); return; } } - Qprintf(locfd,"%.0f %.0f %.0f %s\n",loc[0],loc[1],loc[2],Cmd_Argv(1)); - Qclose(locfd); - free(mapname); + Qprintf (locfd, "%.0f %.0f %.0f %s\n", loc[0], loc[1], loc[2], + Cmd_Argv (1)); + Qclose (locfd); + free (mapname); } - void Locs_Init() + +void +Locs_Init () { - Cmd_AddCommand("markloc",locs_markloc); + Cmd_AddCommand ("markloc", locs_markloc); } - diff --git a/source/tga.c b/source/tga.c index 27255e3..e089f29 100644 --- a/source/tga.c +++ b/source/tga.c @@ -35,24 +35,25 @@ #include "tga.h" typedef struct _TargaHeader { - unsigned char id_length, colormap_type, image_type; - unsigned short colormap_index, colormap_length; - unsigned char colormap_size; - unsigned short x_origin, y_origin, width, height; - unsigned char pixel_size, attributes; + unsigned char id_length, colormap_type, image_type; + unsigned short colormap_index, colormap_length; + unsigned char colormap_size; + unsigned short x_origin, y_origin, width, height; + unsigned char pixel_size, attributes; } TargaHeader; static int fgetLittleShort (QFile *f) { - byte b1, b2; + byte b1, b2; - b1 = Qgetc(f); - b2 = Qgetc(f); + b1 = Qgetc (f); + b2 = Qgetc (f); - return (short)(b1 + b2*256); + return (short) (b1 + b2 * 256); } + /* static int fgetLittleLong (QFile *f) @@ -74,154 +75,157 @@ fgetLittleLong (QFile *f) LoadTGA ============= */ -byte * +byte * LoadTGA (QFile *fin) { - int columns, rows, numPixels; - byte *pixbuf; - int row, column; - unsigned char red = 0, green = 0, blue = 0, alphabyte = 0; + int columns, rows, numPixels; + byte *pixbuf; + int row, column; + unsigned char red = 0, green = 0, blue = 0, alphabyte = 0; - TargaHeader targa_header; - byte *targa_rgba; + TargaHeader targa_header; + byte *targa_rgba; - targa_header.id_length = Qgetc(fin); - targa_header.colormap_type = Qgetc(fin); - targa_header.image_type = Qgetc(fin); - - targa_header.colormap_index = fgetLittleShort(fin); - targa_header.colormap_length = fgetLittleShort(fin); - targa_header.colormap_size = Qgetc(fin); - targa_header.x_origin = fgetLittleShort(fin); - targa_header.y_origin = fgetLittleShort(fin); - targa_header.width = fgetLittleShort(fin); - targa_header.height = fgetLittleShort(fin); - targa_header.pixel_size = Qgetc(fin); - targa_header.attributes = Qgetc(fin); + targa_header.id_length = Qgetc (fin); + targa_header.colormap_type = Qgetc (fin); + targa_header.image_type = Qgetc (fin); - if (targa_header.image_type!=2 - && targa_header.image_type!=10) + targa_header.colormap_index = fgetLittleShort (fin); + targa_header.colormap_length = fgetLittleShort (fin); + targa_header.colormap_size = Qgetc (fin); + targa_header.x_origin = fgetLittleShort (fin); + targa_header.y_origin = fgetLittleShort (fin); + targa_header.width = fgetLittleShort (fin); + targa_header.height = fgetLittleShort (fin); + targa_header.pixel_size = Qgetc (fin); + targa_header.attributes = Qgetc (fin); + + if (targa_header.image_type != 2 && targa_header.image_type != 10) Sys_Error ("LoadTGA: Only type 2 and 10 targa RGB images supported\n"); - if (targa_header.colormap_type !=0 - || (targa_header.pixel_size!=32 && targa_header.pixel_size!=24)) - Sys_Error ("Texture_LoadTGA: Only 32 or 24 bit images supported (no colormaps)\n"); + if (targa_header.colormap_type != 0 + || (targa_header.pixel_size != 32 && targa_header.pixel_size != 24)) + Sys_Error + ("Texture_LoadTGA: Only 32 or 24 bit images supported (no colormaps)\n"); columns = targa_header.width; rows = targa_header.height; numPixels = columns * rows; - targa_rgba = malloc (numPixels*4); - + targa_rgba = malloc (numPixels * 4); + if (targa_header.id_length != 0) - Qseek(fin, targa_header.id_length, SEEK_CUR); // skip TARGA image comment - - if (targa_header.image_type==2) { // Uncompressed, RGB images - for(row=rows-1; row>=0; row--) { - pixbuf = targa_rgba + row*columns*4; - for(column=0; column= 0; row--) { + pixbuf = targa_rgba + row * columns * 4; + for (column = 0; column < columns; column++) { switch (targa_header.pixel_size) { case 24: - - blue = Qgetc(fin); - green = Qgetc(fin); - red = Qgetc(fin); - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; + + blue = Qgetc (fin); + green = Qgetc (fin); + red = Qgetc (fin); + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = 255; + break; case 32: - blue = Qgetc(fin); - green = Qgetc(fin); - red = Qgetc(fin); - alphabyte = Qgetc(fin); - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - break; + blue = Qgetc (fin); + green = Qgetc (fin); + red = Qgetc (fin); + alphabyte = Qgetc (fin); + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = alphabyte; + break; } } } - } - else if (targa_header.image_type==10) { // Runlength encoded RGB images + } else if (targa_header.image_type == 10) { // Runlength encoded RGB + // images unsigned char packetHeader, packetSize, j; - for(row=rows-1; row>=0; row--) { - pixbuf = targa_rgba + row*columns*4; - for(column=0; column= 0; row--) { + pixbuf = targa_rgba + row * columns * 4; + for (column = 0; column < columns;) { + packetHeader = Qgetc (fin); packetSize = 1 + (packetHeader & 0x7f); - if (packetHeader & 0x80) { // run-length packet + if (packetHeader & 0x80) { // run-length packet switch (targa_header.pixel_size) { case 24: - blue = Qgetc(fin); - green = Qgetc(fin); - red = Qgetc(fin); - alphabyte = 255; - break; + blue = Qgetc (fin); + green = Qgetc (fin); + red = Qgetc (fin); + alphabyte = 255; + break; case 32: - blue = Qgetc(fin); - green = Qgetc(fin); - red = Qgetc(fin); - alphabyte = Qgetc(fin); - break; + blue = Qgetc (fin); + green = Qgetc (fin); + red = Qgetc (fin); + alphabyte = Qgetc (fin); + break; } - - for(j=0;j0) + if (column == columns) { // run spans across rows + column = 0; + if (row > 0) row--; else goto breakOut; - pixbuf = targa_rgba + row*columns*4; + pixbuf = targa_rgba + row * columns * 4; } } - } else { // non run-length packet - for(j=0;j0) + if (column == columns) { // pixel packet run spans + // across rows + column = 0; + if (row > 0) row--; else goto breakOut; - pixbuf = targa_rgba + row*columns*4; - } + pixbuf = targa_rgba + row * columns * 4; + } } } } - breakOut:; + breakOut:; } } - - Qclose(fin); + + Qclose (fin); return targa_rgba; } diff --git a/source/va.c b/source/va.c index df2a1b1..2fc1cba 100644 --- a/source/va.c +++ b/source/va.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -41,15 +41,15 @@ varargs versions of all text functions. FIXME: make this buffer size safe someday */ -char * -va(char *format, ...) +char * +va (char *format, ...) { - va_list argptr; - static char string[1024]; - + va_list argptr; + static char string[1024]; + va_start (argptr, format); - vsnprintf (string, sizeof(string), format, argptr); + vsnprintf (string, sizeof (string), format, argptr); va_end (argptr); - return string; + return string; } diff --git a/source/ver_check.c b/source/ver_check.c index a23dee0..65b5000 100644 --- a/source/ver_check.c +++ b/source/ver_check.c @@ -28,7 +28,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include @@ -44,9 +44,9 @@ int ver_compare (const char *value, const char *reference) { - const char *valptr, *refptr; - int vc, rc; - long vl, rl; + const char *valptr, *refptr; + int vc, rc; + long vl, rl; if (!value) value = ""; @@ -55,11 +55,13 @@ ver_compare (const char *value, const char *reference) for (;;) { valptr = value; - while (*valptr && !isdigit(*valptr)) // Scan past any non-digit chars + while (*valptr && !isdigit (*valptr)) // Scan past any non-digit + // chars valptr++; refptr = reference; - while (*refptr && !isdigit(*refptr)) // get past non-digits here too + while (*refptr && !isdigit (*refptr)) // get past non-digits here + // too refptr++; for (;;) { @@ -68,9 +70,11 @@ ver_compare (const char *value, const char *reference) if ((!vc) && (!rc)) break; - - if (vc && !isalpha (vc)) vc += 256; // ASCII charset - if (rc && !isalpha (rc)) rc += 256; + + if (vc && !isalpha (vc)) + vc += 256; // ASCII charset + if (rc && !isalpha (rc)) + rc += 256; if (vc != rc) return (vc - rc); @@ -80,22 +84,22 @@ ver_compare (const char *value, const char *reference) reference = refptr; vl = rl = 0; - + if (isdigit (*valptr)) vl = strtol (value, (char **) &value, 10); - + if (isdigit (*refptr)) rl = strtol (reference, (char **) &reference, 10); - + if (vl != rl) return (vl - rl); - + if ((!*value) && (!*reference)) return 0; - + if (!*value) return -1; - + if (!*reference) return 1; } diff --git a/source/vid.c b/source/vid.c index 5c991dd..9638b47 100644 --- a/source/vid.c +++ b/source/vid.c @@ -36,51 +36,53 @@ #include "qargs.h" #include "sys.h" -extern viddef_t vid; // global video state +extern viddef_t vid; // global video state -int scr_width, scr_height; -cvar_t *vid_width; -cvar_t *vid_height; +int scr_width, scr_height; +cvar_t *vid_width; +cvar_t *vid_height; void VID_GetWindowSize (int def_w, int def_h) { - int pnum; + int pnum; - vid_width = Cvar_Get ("vid_width", va ("%d", def_w), CVAR_NONE, "screen width"); - vid_height = Cvar_Get ("vid_height", va ("%d", def_h), CVAR_NONE, "screen height"); + vid_width = + Cvar_Get ("vid_width", va ("%d", def_w), CVAR_NONE, "screen width"); + vid_height = + Cvar_Get ("vid_height", va ("%d", def_h), CVAR_NONE, "screen height"); if ((pnum = COM_CheckParm ("-width"))) { - if (pnum >= com_argc-1) + if (pnum >= com_argc - 1) Sys_Error ("VID: -width \n"); - Cvar_Set (vid_width, com_argv[pnum+1]); + Cvar_Set (vid_width, com_argv[pnum + 1]); if (!vid_width->int_val) Sys_Error ("VID: Bad window width\n"); } if ((pnum = COM_CheckParm ("-height"))) { - if (pnum >= com_argc-1) + if (pnum >= com_argc - 1) Sys_Error ("VID: -height \n"); - Cvar_Set (vid_height, com_argv[pnum+1]); + Cvar_Set (vid_height, com_argv[pnum + 1]); if (!vid_height->int_val) Sys_Error ("VID: Bad window height\n"); } if ((pnum = COM_CheckParm ("-winsize"))) { - if (pnum >= com_argc-2) + if (pnum >= com_argc - 2) Sys_Error ("VID: -winsize \n"); - Cvar_Set (vid_width, com_argv[pnum+1]); - Cvar_Set (vid_height, com_argv[pnum+2]); + Cvar_Set (vid_width, com_argv[pnum + 1]); + Cvar_Set (vid_height, com_argv[pnum + 2]); if (!vid_width->int_val || !vid_height->int_val) Sys_Error ("VID: Bad window width/height\n"); } - + Cvar_SetFlags (vid_width, vid_width->flags | CVAR_ROM); Cvar_SetFlags (vid_height, vid_height->flags | CVAR_ROM); diff --git a/source/vid_3dfxsvga.c b/source/vid_3dfxsvga.c index 76524c8..65e9459 100644 --- a/source/vid_3dfxsvga.c +++ b/source/vid_3dfxsvga.c @@ -30,7 +30,7 @@ */ #ifdef HAVE_CONFIG_H -#include "config.h" +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -55,48 +55,49 @@ #define WARP_HEIGHT 200 // FIXME!!!!! This belongs in include/qfgl_ext.h -- deek -typedef void (GLAPIENTRY *QF_3DfxSetDitherModeEXT) (GrDitherMode_t mode); +typedef void (GLAPIENTRY * QF_3DfxSetDitherModeEXT) (GrDitherMode_t mode); static fxMesaContext fc = NULL; -int VID_options_items = 0; +int VID_options_items = 0; extern void GL_Init_Common (void); extern void VID_Init8bitPalette (void); + /*-----------------------------------------------------------------------*/ void -VID_Shutdown(void) +VID_Shutdown (void) { if (!fc) return; - fxMesaDestroyContext(fc); + fxMesaDestroyContext (fc); } void -signal_handler(int sig) +signal_handler (int sig) { - printf("Received signal %d, exiting...\n", sig); - Host_Shutdown(); - abort(); -// Sys_Quit(); - exit(0); + printf ("Received signal %d, exiting...\n", sig); + Host_Shutdown (); + abort (); +// Sys_Quit(); + exit (0); } void InitSig (void) { - signal(SIGHUP, signal_handler); - signal(SIGINT, signal_handler); - signal(SIGQUIT, signal_handler); - signal(SIGILL, signal_handler); - signal(SIGTRAP, signal_handler); -// signal(SIGIOT, signal_handler); - signal(SIGBUS, signal_handler); -// signal(SIGFPE, signal_handler); - signal(SIGSEGV, signal_handler); - signal(SIGTERM, signal_handler); + signal (SIGHUP, signal_handler); + signal (SIGINT, signal_handler); + signal (SIGQUIT, signal_handler); + signal (SIGILL, signal_handler); + signal (SIGTRAP, signal_handler); +// signal(SIGIOT, signal_handler); + signal (SIGBUS, signal_handler); +// signal(SIGFPE, signal_handler); + signal (SIGSEGV, signal_handler); + signal (SIGTERM, signal_handler); } /* @@ -117,13 +118,13 @@ GL_Init (void) dither_select = QFGL_ExtensionAddress ("gl3DfxSetDitherModeEXT"); if (COM_CheckParm ("-dither_2x2")) { - dither_select(GR_DITHER_2x2); + dither_select (GR_DITHER_2x2); Con_Printf ("2x2.\n"); } else if (COM_CheckParm ("-dither_4x4")) { - dither_select(GR_DITHER_4x4); + dither_select (GR_DITHER_4x4); Con_Printf ("4x4.\n"); } else { - glDisable(GL_DITHER); + glDisable (GL_DITHER); Con_Printf ("disabled.\n"); } } @@ -137,52 +138,52 @@ GL_EndRendering (void) Sbar_Changed (); } -static int resolutions[][3] = { - { 320, 200, GR_RESOLUTION_320x200 }, - { 320, 240, GR_RESOLUTION_320x240 }, - { 400, 256, GR_RESOLUTION_400x256 }, - { 400, 300, GR_RESOLUTION_400x300 }, - { 512, 256, GR_RESOLUTION_512x256 }, - { 512, 384, GR_RESOLUTION_512x384 }, - { 640, 200, GR_RESOLUTION_640x200 }, - { 640, 350, GR_RESOLUTION_640x350 }, - { 640, 400, GR_RESOLUTION_640x400 }, - { 640, 480, GR_RESOLUTION_640x480 }, - { 800, 600, GR_RESOLUTION_800x600 }, - { 856, 480, GR_RESOLUTION_856x480 }, - { 960, 720, GR_RESOLUTION_960x720 }, +static int resolutions[][3] = { + {320, 200, GR_RESOLUTION_320x200}, + {320, 240, GR_RESOLUTION_320x240}, + {400, 256, GR_RESOLUTION_400x256}, + {400, 300, GR_RESOLUTION_400x300}, + {512, 256, GR_RESOLUTION_512x256}, + {512, 384, GR_RESOLUTION_512x384}, + {640, 200, GR_RESOLUTION_640x200}, + {640, 350, GR_RESOLUTION_640x350}, + {640, 400, GR_RESOLUTION_640x400}, + {640, 480, GR_RESOLUTION_640x480}, + {800, 600, GR_RESOLUTION_800x600}, + {856, 480, GR_RESOLUTION_856x480}, + {960, 720, GR_RESOLUTION_960x720}, #ifdef GR_RESOLUTION_1024x768 - { 1024, 768, GR_RESOLUTION_1024x768 }, + {1024, 768, GR_RESOLUTION_1024x768}, #endif #ifdef GR_RESOLUTION_1152x864 - { 1152, 864, GR_RESOLUTION_1152x864 }, + {1152, 864, GR_RESOLUTION_1152x864}, #endif #ifdef GR_RESOLUTION_1280x960 - { 1280, 960, GR_RESOLUTION_1280x960 }, + {1280, 960, GR_RESOLUTION_1280x960}, #endif #ifdef GR_RESOLUTION_1280x1024 - { 1280, 1024, GR_RESOLUTION_1280x1024 }, + {1280, 1024, GR_RESOLUTION_1280x1024}, #endif #ifdef GR_RESOLUTION_1600x1024 - { 1600, 1024, GR_RESOLUTION_1600x1024 }, + {1600, 1024, GR_RESOLUTION_1600x1024}, #endif #ifdef GR_RESOLUTION_1600x1200 - { 1600, 1200, GR_RESOLUTION_1600x1200 }, + {1600, 1200, GR_RESOLUTION_1600x1200}, #endif #ifdef GR_RESOLUTION_1792x1344 - { 1792, 1344, GR_RESOLUTION_1792x1344 }, + {1792, 1344, GR_RESOLUTION_1792x1344}, #endif #ifdef GR_RESOLUTION_1856x1392 - { 1856, 1392, GR_RESOLUTION_1856x1392 }, + {1856, 1392, GR_RESOLUTION_1856x1392}, #endif #ifdef GR_RESOLUTION_1920x1440 - { 1920, 1440, GR_RESOLUTION_1920x1440 }, + {1920, 1440, GR_RESOLUTION_1920x1440}, #endif #ifdef GR_RESOLUTION_2048x1536 - { 2048, 1536, GR_RESOLUTION_2048x1536 }, + {2048, 1536, GR_RESOLUTION_2048x1536}, #endif #ifdef GR_RESOLUTION_2048x2048 - { 2048, 2048, GR_RESOLUTION_2048x2048 } + {2048, 2048, GR_RESOLUTION_2048x2048} #endif }; @@ -192,11 +193,10 @@ static int resolutions[][3] = { static int findres (int *width, int *height) { - int i; + int i; - for(i=0; i < NUM_RESOLUTIONS; i++) { - if((*width <= resolutions[i][0]) && - (*height <= resolutions[i][1])) { + for (i = 0; i < NUM_RESOLUTIONS; i++) { + if ((*width <= resolutions[i][0]) && (*height <= resolutions[i][1])) { *width = resolutions[i][0]; *height = resolutions[i][1]; return resolutions[i][2]; @@ -211,8 +211,8 @@ findres (int *width, int *height) void VID_Init (unsigned char *palette) { - int i; - GLint attribs[32]; + int i; + GLint attribs[32]; VID_GetWindowSize (640, 480); @@ -232,24 +232,24 @@ VID_Init (unsigned char *palette) attribs[5] = FXMESA_NONE; if ((i = COM_CheckParm ("-conwidth"))) - vid.conwidth = atoi(com_argv[i+1]); + vid.conwidth = atoi (com_argv[i + 1]); else vid.conwidth = 640; - vid.conwidth &= 0xfff8; // make it a multiple of eight + vid.conwidth &= 0xfff8; // make it a multiple of eight vid.conwidth = max (vid.conwidth, 320); // pick a conheight that matches with correct aspect vid.conheight = vid.conwidth * 3 / 4; - if ((i = COM_CheckParm("-conheight")) != 0) - vid.conheight = atoi(com_argv[i+1]); + if ((i = COM_CheckParm ("-conheight")) != 0) + vid.conheight = atoi (com_argv[i + 1]); vid.conheight = max (vid.conheight, 200); fc = fxMesaCreateContext (0, findres (&scr_width, &scr_height), - GR_REFRESH_75Hz, attribs); + GR_REFRESH_75Hz, attribs); if (!fc) Sys_Error ("Unable to create 3DFX context.\n"); @@ -261,7 +261,7 @@ VID_Init (unsigned char *palette) vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); vid.numpages = 2; - InitSig (); // trap evil signals + InitSig (); // trap evil signals GL_Init (); diff --git a/source/vid_common_gl.c b/source/vid_common_gl.c index 0869059..ea4d0af 100644 --- a/source/vid_common_gl.c +++ b/source/vid_common_gl.c @@ -50,17 +50,17 @@ #define WARP_WIDTH 320 #define WARP_HEIGHT 200 -//unsigned short d_8to16table[256]; -unsigned int d_8to24table[256]; -unsigned char d_15to8table[65536]; +//unsigned short d_8to16table[256]; +unsigned int d_8to24table[256]; +unsigned char d_15to8table[65536]; -cvar_t *vid_mode; +cvar_t *vid_mode; /*-----------------------------------------------------------------------*/ -int texture_mode = GL_LINEAR; -int texture_extension_number = 1; -float gldepthmin, gldepthmax; +int texture_mode = GL_LINEAR; +int texture_extension_number = 1; +float gldepthmin, gldepthmax; const char *gl_vendor; const char *gl_renderer; @@ -68,12 +68,12 @@ const char *gl_version; const char *gl_extensions; // ARB Multitexture -int gl_mtex_enum = TEXTURE0_SGIS; -qboolean gl_arb_mtex = false; -qboolean gl_mtexable = false; +int gl_mtex_enum = TEXTURE0_SGIS; +qboolean gl_arb_mtex = false; +qboolean gl_mtexable = false; static qboolean is8bit = false; -cvar_t *vid_use8bit; +cvar_t *vid_use8bit; /*-----------------------------------------------------------------------*/ @@ -121,37 +121,38 @@ CheckMultiTextureExtensions (void) void VID_SetPalette (unsigned char *palette) { - byte *pal; - unsigned int r,g,b; + byte *pal; + unsigned int r, g, b; unsigned int v; - int r1,g1,b1; - int k; + int r1, g1, b1; + int k; unsigned short i; - unsigned int *table; - QFile *f; - char s[255]; - float dist, bestdist; + unsigned int *table; + QFile *f; + char s[255]; + float dist, bestdist; static qboolean palflag = false; // // 8 8 8 encoding // -// Con_Printf("Converting 8to24\n"); +// Con_Printf("Converting 8to24\n"); pal = palette; table = d_8to24table; - for (i = 0; i < 255; i++) { // used to be i<256, see d_8to24table below + for (i = 0; i < 255; i++) { // used to be i<256, see d_8to24table + // below r = pal[0]; g = pal[1]; b = pal[2]; pal += 3; -// v = (255<<24) + (r<<16) + (g<<8) + (b<<0); -// v = (255<<0) + (r<<8) + (g<<16) + (b<<24); - v = (255<<24) + (r<<0) + (g<<8) + (b<<16); +// v = (255<<24) + (r<<16) + (g<<8) + (b<<0); +// v = (255<<0) + (r<<8) + (g<<16) + (b<<24); + v = (255 << 24) + (r << 0) + (g << 8) + (b << 16); *table++ = v; } - d_8to24table[255] = 0; // 255 is transparent + d_8to24table[255] = 0; // 255 is transparent // JACK: 3D distance calcs - k is last closest, l is the distance. // FIXME: Precalculate this and cache to disk. @@ -159,41 +160,38 @@ VID_SetPalette (unsigned char *palette) return; palflag = true; - COM_FOpenFile("glquake/15to8.pal", &f); + COM_FOpenFile ("glquake/15to8.pal", &f); if (f) { - Qread(f, d_15to8table, 1<<15); - Qclose(f); + Qread (f, d_15to8table, 1 << 15); + Qclose (f); } else { - for (i = 0; i < (1<<15); i++) { - /* Maps - 000000000000000 - 000000000011111 = Red = 0x1F - 000001111100000 = Blue = 0x03E0 - 111110000000000 = Grn = 0x7C00 - */ - r = ((i & 0x1F) << 3) + 4; - g = ((i & 0x03E0) >> 2) + 4; - b = ((i & 0x7C00) >> 7) + 4; + for (i = 0; i < (1 << 15); i++) { + /* Maps 000000000000000 000000000011111 = Red = 0x1F + 000001111100000 = Blue = 0x03E0 111110000000000 = Grn = + 0x7C00 */ + r = ((i & 0x1F) << 3) + 4; + g = ((i & 0x03E0) >> 2) + 4; + b = ((i & 0x7C00) >> 7) + 4; pal = (unsigned char *) d_8to24table; - for (v=0, k=0, bestdist = 10000.0; v<256; v++,pal+=4) { - r1 = (int)r - (int)pal[0]; - g1 = (int)g - (int)pal[1]; - b1 = (int)b - (int)pal[2]; - dist = sqrt(((r1*r1)+(g1*g1)+(b1*b1))); + for (v = 0, k = 0, bestdist = 10000.0; v < 256; v++, pal += 4) { + r1 = (int) r - (int) pal[0]; + g1 = (int) g - (int) pal[1]; + b1 = (int) b - (int) pal[2]; + dist = sqrt (((r1 * r1) + (g1 * g1) + (b1 * b1))); if (dist < bestdist) { - k=v; + k = v; bestdist = dist; } } - d_15to8table[i]=k; + d_15to8table[i] = k; } - snprintf(s, sizeof(s), "%s/glquake/15to8.pal", com_gamedir); + snprintf (s, sizeof (s), "%s/glquake/15to8.pal", com_gamedir); COM_CreatePath (s); - if ((f = Qopen(s, "wb")) != NULL) { - Qwrite(f, d_15to8table, 1<<15); - Qclose(f); + if ((f = Qopen (s, "wb")) != NULL) { + Qwrite (f, d_15to8table, 1 << 15); + Qclose (f); } } } @@ -265,7 +263,7 @@ void Tdfx_Init8bitPalette (void) { // Check for 8bit Extensions and initialize them. - int i; + int i; if (is8bit) { return; @@ -273,17 +271,19 @@ Tdfx_Init8bitPalette (void) if (QFGL_ExtensionPresent ("3DFX_set_global_palette")) { - char *oldpal; - GLubyte table[256][4]; + char *oldpal; + GLubyte table[256][4]; QF_gl3DfxSetPaletteEXT qgl3DfxSetPaletteEXT = NULL; - if (!(qgl3DfxSetPaletteEXT = QFGL_ExtensionAddress ("gl3DfxSetPaletteEXT"))) { + if (! + (qgl3DfxSetPaletteEXT = + QFGL_ExtensionAddress ("gl3DfxSetPaletteEXT"))) { return; } Con_Printf ("3DFX_set_global_palette.\n"); - oldpal = (char *) d_8to24table; //d_8to24table3dfx; + oldpal = (char *) d_8to24table; // d_8to24table3dfx; for (i = 0; i < 256; i++) { table[i][2] = *oldpal++; table[i][1] = *oldpal++; @@ -300,9 +300,9 @@ Tdfx_Init8bitPalette (void) void Shared_Init8bitPalette (void) { - int i; - GLubyte thePalette[256][4]; - GLubyte *oldPalette; + int i; + GLubyte thePalette[256][4]; + GLubyte *oldPalette; QF_glColorTableEXT qglColorTableEXT = NULL; @@ -317,7 +317,7 @@ Shared_Init8bitPalette (void) Con_Printf ("GL_EXT_shared_texture_palette\n"); - oldPalette = (GLubyte *) d_8to24table; //d_8to24table3dfx; + oldPalette = (GLubyte *) d_8to24table; // d_8to24table3dfx; for (i = 0; i < 256; i++) { thePalette[i][0] = *oldPalette++; thePalette[i][1] = *oldPalette++; @@ -325,7 +325,8 @@ Shared_Init8bitPalette (void) thePalette[i][3] = *oldPalette++; } glEnable (GL_SHARED_TEXTURE_PALETTE_EXT); - qglColorTableEXT (GL_SHARED_TEXTURE_PALETTE_EXT, GL_RGBA, 256, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid *) thePalette); + qglColorTableEXT (GL_SHARED_TEXTURE_PALETTE_EXT, GL_RGBA, 256, GL_RGBA, + GL_UNSIGNED_BYTE, (GLvoid *) thePalette); is8bit = true; } } @@ -334,7 +335,8 @@ Shared_Init8bitPalette (void) void VID_Init8bitPalette (void) { - vid_use8bit = Cvar_Get ("vid_use8bit", "1", CVAR_ROM, "Use 8-bit shared palettes."); + vid_use8bit = + Cvar_Get ("vid_use8bit", "1", CVAR_ROM, "Use 8-bit shared palettes."); Con_Printf ("Checking for 8-bit extension: "); if (vid_use8bit->int_val) { @@ -361,7 +363,7 @@ VID_UnlockBuffer (void) } void -D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { } diff --git a/source/vid_ggi.c b/source/vid_ggi.c index 08e6cdc..c5d68cc 100644 --- a/source/vid_ggi.c +++ b/source/vid_ggi.c @@ -31,7 +31,7 @@ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include #include @@ -39,26 +39,29 @@ #include #include -#include "bothdefs.h" // needed by: common.h, net.h, client.h +#include "bothdefs.h" // needed by: common.h, net.h, + // client.h -#include "bspfile.h" // needed by: glquake.h +#include "bspfile.h" // needed by: glquake.h #include "vid.h" #include "sys.h" -#include "mathlib.h" // needed by: protocol.h, render.h, client.h, - // modelgen.h, glmodel.h +#include "mathlib.h" // needed by: protocol.h, render.h, + // client.h, + // modelgen.h, glmodel.h #include "wad.h" #include "draw.h" #include "cvar.h" -#include "net.h" // needed by: client.h -#include "protocol.h" // needed by: client.h +#include "net.h" // needed by: client.h +#include "protocol.h" // needed by: client.h #include "cmd.h" #include "host.h" #include "keys.h" #include "sbar.h" #include "sound.h" -#include "render.h" // needed by: client.h, gl_model.h, glquake.h -#include "client.h" // need cls in this file -#include "model.h" // needed by: glquake.h +#include "render.h" // needed by: client.h, gl_model.h, + // glquake.h +#include "client.h" // need cls in this file +#include "model.h" // needed by: glquake.h #include "console.h" #include "qendian.h" #include "qargs.h" @@ -69,51 +72,53 @@ #include "view.h" #include "joystick.h" -extern viddef_t vid; // global video state -unsigned short d_8to16table[256]; +extern viddef_t vid; // global video state +unsigned short d_8to16table[256]; -cvar_t *m_filter; -cvar_t *_windowed_mouse; +cvar_t *m_filter; +cvar_t *_windowed_mouse; /* Unused */ -int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; -byte *VGA_pagebase; +int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; +byte *VGA_pagebase; #define NUM_STDBUTTONS 3 #define NUM_BUTTONS 10 -static qboolean mouse_avail; -static float mouse_x, mouse_y; -static float old_mouse_x, old_mouse_y; -static int p_mouse_x, p_mouse_y; -static float old_windowed_mouse; +static qboolean mouse_avail; +static float mouse_x, mouse_y; +static float old_mouse_x, old_mouse_y; +static int p_mouse_x, p_mouse_y; +static float old_windowed_mouse; -static ggi_visual_t ggivis = NULL; -static ggi_mode mode; -static const ggi_directbuffer *dbuf1 = NULL, *dbuf2 = NULL; +static ggi_visual_t ggivis = NULL; +static ggi_mode mode; +static const ggi_directbuffer *dbuf1 = NULL, *dbuf2 = NULL; -static uint8 *drawptr = NULL; -static void *frameptr[2] = { NULL, NULL }; -static void *oneline = NULL; -static void *palette = NULL; -static int curframe = 0; +static uint8 *drawptr = NULL; +static void *frameptr[2] = { NULL, NULL }; +static void *oneline = NULL; +static void *palette = NULL; +static int curframe = 0; -static int realwidth, realheight; -static int doublebuffer; -static int scale; -static int stride, drawstride; -static int pixelsize; -static int usedbuf, havedbuf; +static int realwidth, realheight; +static int doublebuffer; +static int scale; +static int stride, drawstride; +static int pixelsize; +static int usedbuf, havedbuf; -int VID_options_items = 1; +int VID_options_items = 1; static void -do_scale8(int xsize, int ysize, uint8 *dest, uint8 *src) +do_scale8 (int xsize, int ysize, uint8 * dest, uint8 * src) { - int i, j, destinc = stride*2-xsize*2; + int i, j, destinc = stride * 2 - xsize * 2; + for (j = 0; j < ysize; j++) { - for (i = 0; i < xsize; /* i is incremented below */) { + for (i = 0; i < xsize; /* i is incremented below */ ) { register uint32 pix1 = src[i++], pix2 = src[i++]; + #ifdef GGI_LITTLE_ENDIAN *((uint32 *) (dest + stride)) = *((uint32 *) dest) @@ -133,13 +138,15 @@ do_scale8(int xsize, int ysize, uint8 *dest, uint8 *src) } static void -do_scale16(int xsize, int ysize, uint8 *dest, uint8 *src) +do_scale16 (int xsize, int ysize, uint8 * dest, uint8 * src) { - int i, j, destinc = stride*2-xsize*4; - uint16 *palptr = palette; + int i, j, destinc = stride * 2 - xsize * 4; + uint16 *palptr = palette; + for (j = 0; j < ysize; j++) { - for (i = 0; i < xsize; /* i is incremented below */) { + for (i = 0; i < xsize; /* i is incremented below */ ) { register uint32 pixel = palptr[src[i++]]; + *((uint32 *) (dest + stride)) = *((uint32 *) dest) = pixel | (pixel << 16); @@ -151,13 +158,15 @@ do_scale16(int xsize, int ysize, uint8 *dest, uint8 *src) } static void -do_scale32(int xsize, int ysize, uint8 *dest, uint8 *src) +do_scale32 (int xsize, int ysize, uint8 * dest, uint8 * src) { - int i, j, destinc = stride*2-xsize*8; - uint32 *palptr = palette; + int i, j, destinc = stride * 2 - xsize * 8; + uint32 *palptr = palette; + for (j = 0; j < ysize; j++) { - for (i = 0; i < xsize; /* i is incremented below */) { + for (i = 0; i < xsize; /* i is incremented below */ ) { register uint32 pixel = palptr[src[i++]]; + *((uint32 *) (dest + stride)) = *((uint32 *) (dest)) = pixel; dest += 4; @@ -172,10 +181,10 @@ do_scale32(int xsize, int ysize, uint8 *dest, uint8 *src) static void -do_copy8(int xsize, int ysize, uint8 *dest, uint8 *src) +do_copy8 (int xsize, int ysize, uint8 * dest, uint8 * src) { - int i, j; - uint8 *palptr = palette; + int i, j; + uint8 *palptr = palette; for (j = 0; j < ysize; j++) { for (i = 0; i < xsize; i++) { @@ -187,15 +196,16 @@ do_copy8(int xsize, int ysize, uint8 *dest, uint8 *src) } static void -do_copy16(int xsize, int ysize, void *destptr, uint8 *src) +do_copy16 (int xsize, int ysize, void *destptr, uint8 * src) { - int i, j, destinc = (stride/2 - xsize)/2; - uint16 *palptr = palette; - uint32 *dest = destptr; + int i, j, destinc = (stride / 2 - xsize) / 2; + uint16 *palptr = palette; + uint32 *dest = destptr; for (j = 0; j < ysize; j++) { - for (i = 0; i < xsize; /* i is incremented below */) { + for (i = 0; i < xsize; /* i is incremented below */ ) { register uint32 pixel = palptr[src[i++]]; + #ifdef GGI_LITTLE_ENDIAN *(dest++) = pixel | (palptr[src[i++]] << 16); #else @@ -208,10 +218,10 @@ do_copy16(int xsize, int ysize, void *destptr, uint8 *src) } static void -do_copy32(int xsize, int ysize, uint32 *dest, uint8 *src) +do_copy32 (int xsize, int ysize, uint32 * dest, uint8 * src) { - int i, j, destinc = stride/4; - uint32 *palptr = palette; + int i, j, destinc = stride / 4; + uint32 *palptr = palette; for (j = 0; j < ysize; j++) { for (i = 0; i < xsize; i++) { @@ -224,21 +234,20 @@ do_copy32(int xsize, int ysize, uint32 *dest, uint8 *src) void -ResetFrameBuffer(void) +ResetFrameBuffer (void) { - int tbuffersize, tcachesize; - void *vid_surfcache; + int tbuffersize, tcachesize; + void *vid_surfcache; // Calculate the sizes we want first tbuffersize = vid.width * vid.height * sizeof (*d_pzbuffer); - tcachesize = D_SurfaceCacheForRes(vid.width, vid.height); + tcachesize = D_SurfaceCacheForRes (vid.width, vid.height); // Free the old z-buffer if (d_pzbuffer) { free (d_pzbuffer); d_pzbuffer = NULL; } - // Free the old surface cache vid_surfcache = D_SurfaceCacheAddress (); if (vid_surfcache) { @@ -246,13 +255,11 @@ ResetFrameBuffer(void) free (vid_surfcache); vid_surfcache = NULL; } - // Allocate the new z-buffer d_pzbuffer = calloc (tbuffersize, 1); if (!d_pzbuffer) { Sys_Error ("Not enough memory for video mode\n"); } - // Allocate the new surface cache; free the z-buffer if we fail vid_surfcache = calloc (tcachesize, 1); if (!vid_surfcache) { @@ -272,60 +279,58 @@ ResetFrameBuffer(void) void VID_Init (unsigned char *pal) { - int pnum; + int pnum; vid.width = GGI_AUTO; vid.height = GGI_AUTO; - srandom(getpid()); + srandom (getpid ()); - if (ggiInit() < 0) { - Sys_Error("VID: Unable to init LibGGI\n"); + if (ggiInit () < 0) { + Sys_Error ("VID: Unable to init LibGGI\n"); } - ggivis = ggiOpen(NULL); + ggivis = ggiOpen (NULL); if (!ggivis) { - Sys_Error("VID: Unable to open default visual\n"); + Sys_Error ("VID: Unable to open default visual\n"); } /* Go into async mode */ - ggiSetFlags(ggivis, GGIFLAG_ASYNC); + ggiSetFlags (ggivis, GGIFLAG_ASYNC); /* check for command-line window size */ - if ((pnum=COM_CheckParm("-winsize"))) - { - if (pnum >= com_argc-2) - Sys_Error("VID: -winsize \n"); - vid.width = atoi(com_argv[pnum+1]); - vid.height = atoi(com_argv[pnum+2]); + if ((pnum = COM_CheckParm ("-winsize"))) { + if (pnum >= com_argc - 2) + Sys_Error ("VID: -winsize \n"); + vid.width = atoi (com_argv[pnum + 1]); + vid.height = atoi (com_argv[pnum + 2]); if (!vid.width || !vid.height) - Sys_Error("VID: Bad window width/height\n"); + Sys_Error ("VID: Bad window width/height\n"); } - if ((pnum=COM_CheckParm("-width"))) { - if (pnum >= com_argc-1) - Sys_Error("VID: -width \n"); - vid.width = atoi(com_argv[pnum+1]); + if ((pnum = COM_CheckParm ("-width"))) { + if (pnum >= com_argc - 1) + Sys_Error ("VID: -width \n"); + vid.width = atoi (com_argv[pnum + 1]); if (!vid.width) - Sys_Error("VID: Bad window width\n"); + Sys_Error ("VID: Bad window width\n"); } - if ((pnum=COM_CheckParm("-height"))) { - if (pnum >= com_argc-1) - Sys_Error("VID: -height \n"); - vid.height = atoi(com_argv[pnum+1]); + if ((pnum = COM_CheckParm ("-height"))) { + if (pnum >= com_argc - 1) + Sys_Error ("VID: -height \n"); + vid.height = atoi (com_argv[pnum + 1]); if (!vid.height) - Sys_Error("VID: Bad window height\n"); + Sys_Error ("VID: Bad window height\n"); } - scale = COM_CheckParm("-scale"); + scale = COM_CheckParm ("-scale"); /* specify a LibGGI mode */ - if ((pnum=COM_CheckParm("-ggimode"))) - { - if (pnum >= com_argc-1) - Sys_Error("VID: -ggimode \n"); - ggiParseMode(com_argv[pnum+1], &mode); + if ((pnum = COM_CheckParm ("-ggimode"))) { + if (pnum >= com_argc - 1) + Sys_Error ("VID: -ggimode \n"); + ggiParseMode (com_argv[pnum + 1], &mode); } else { /* This will give the default mode */ - ggiParseMode("", &mode); + ggiParseMode ("", &mode); /* Now put in any parameters given above */ mode.visible.x = vid.width; mode.visible.y = vid.height; @@ -337,82 +342,85 @@ VID_Init (unsigned char *pal) } /* We prefer 8 bit mode unless otherwise specified */ - if (mode.graphtype == GT_AUTO) mode.graphtype = GT_8BIT; + if (mode.graphtype == GT_AUTO) + mode.graphtype = GT_8BIT; /* We want double buffering if possible */ if (mode.frames == GGI_AUTO) { - ggi_mode tmpmode = mode; + ggi_mode tmpmode = mode; tmpmode.frames = 2; - if (ggiCheckMode(ggivis, &tmpmode) == 0) { + if (ggiCheckMode (ggivis, &tmpmode) == 0) { mode = tmpmode; } else { tmpmode.frames = 2; - if (ggiCheckMode(ggivis, &tmpmode) == 0) { + if (ggiCheckMode (ggivis, &tmpmode) == 0) { mode = tmpmode; } } } - if (ggiSetMode(ggivis, &mode) != 0) { + if (ggiSetMode (ggivis, &mode) != 0) { /* Try again with suggested mode */ - if (ggiSetMode(ggivis, &mode) != 0) { - Sys_Error("VID: LibGGI can't set any modes!\n"); + if (ggiSetMode (ggivis, &mode) != 0) { + Sys_Error ("VID: LibGGI can't set any modes!\n"); } } /* Pixel size must be 1, 2 or 4 bytes */ - if (GT_SIZE(mode.graphtype) != 8 && - GT_SIZE(mode.graphtype) != 16 && - GT_SIZE(mode.graphtype) != 32) { - if (GT_SIZE(mode.graphtype) == 24) { - Sys_Error("VID: 24 bits per pixel not supported - try using the palemu target.\n"); + if (GT_SIZE (mode.graphtype) != 8 && + GT_SIZE (mode.graphtype) != 16 && GT_SIZE (mode.graphtype) != 32) { + if (GT_SIZE (mode.graphtype) == 24) { + Sys_Error + ("VID: 24 bits per pixel not supported - try using the palemu target.\n"); } else { - Sys_Error("VID: %d bits per pixel not supported by GGI Quake.\n", - GT_SIZE(mode.graphtype)); + Sys_Error ("VID: %d bits per pixel not supported by GGI Quake.\n", + GT_SIZE (mode.graphtype)); } } - realwidth = mode.visible.x; + realwidth = mode.visible.x; realheight = mode.visible.y; if (scale) { - vid.width = realwidth / 2; + vid.width = realwidth / 2; vid.height = realheight / 2; } else { - vid.width = realwidth; + vid.width = realwidth; vid.height = realheight; } - if (mode.frames >= 2) doublebuffer = 1; - else doublebuffer = 0; + if (mode.frames >= 2) + doublebuffer = 1; + else + doublebuffer = 0; - pixelsize = (GT_SIZE(mode.graphtype)+7) / 8; + pixelsize = (GT_SIZE (mode.graphtype) + 7) / 8; if (mode.graphtype != GT_8BIT) { - if ((palette = malloc(pixelsize*256)) == NULL) { - Sys_Error("VID: Unable to allocate palette table\n"); + if ((palette = malloc (pixelsize * 256)) == NULL) { + Sys_Error ("VID: Unable to allocate palette table\n"); } } - VID_SetPalette(pal); + VID_SetPalette (pal); usedbuf = havedbuf = 0; drawstride = vid.width; - stride = realwidth*pixelsize; - if ((dbuf1 = ggiDBGetBuffer(ggivis, 0)) != NULL && - (dbuf1->type & GGI_DB_SIMPLE_PLB)) { + stride = realwidth * pixelsize; + if ((dbuf1 = ggiDBGetBuffer (ggivis, 0)) != NULL && + (dbuf1->type & GGI_DB_SIMPLE_PLB)) { havedbuf = 1; stride = dbuf1->buffer.plb.stride; if (doublebuffer) { - if ((dbuf2 = ggiDBGetBuffer(ggivis, 1)) == NULL || - !(dbuf2->type & GGI_DB_SIMPLE_PLB)) { + if ((dbuf2 = ggiDBGetBuffer (ggivis, 1)) == NULL || + !(dbuf2->type & GGI_DB_SIMPLE_PLB)) { /* Only one DB? No double buffering then */ doublebuffer = 0; } } if (doublebuffer) { - fprintf(stderr, "VID: Got two DirectBuffers\n"); + fprintf (stderr, "VID: Got two DirectBuffers\n"); } else { - fprintf(stderr, "VID: Got one DirectBuffer\n"); + fprintf (stderr, "VID: Got one DirectBuffer\n"); } if (doublebuffer && !scale && !palette) { usedbuf = 1; @@ -424,26 +432,27 @@ VID_Init (unsigned char *pal) frameptr[1] = frameptr[0]; } drawptr = frameptr[0]; - fprintf(stderr, "VID: Drawing into DirectBuffer\n"); + fprintf (stderr, "VID: Drawing into DirectBuffer\n"); } } if (!usedbuf) { - if ((drawptr = malloc(vid.width * vid.height)) == NULL) { - Sys_Error("VID: Unable to allocate draw buffer\n"); + if ((drawptr = malloc (vid.width * vid.height)) == NULL) { + Sys_Error ("VID: Unable to allocate draw buffer\n"); } if (!havedbuf && (scale || palette)) { - int linesize = pixelsize*realwidth; - if (scale) linesize *= 4; - if ((oneline = malloc(linesize)) == NULL) { - Sys_Error("VID: Unable to allocate line buffer\n"); + int linesize = pixelsize * realwidth; + + if (scale) + linesize *= 4; + if ((oneline = malloc (linesize)) == NULL) { + Sys_Error ("VID: Unable to allocate line buffer\n"); } } - fprintf(stderr, - "VID: Drawing into offscreen memory\n"); + fprintf (stderr, "VID: Drawing into offscreen memory\n"); } - ResetFrameBuffer(); + ResetFrameBuffer (); curframe = 0; vid.maxwarpwidth = WARP_WIDTH; @@ -457,14 +466,14 @@ VID_Init (unsigned char *pal) vid.conrowbytes = vid.rowbytes; vid.conwidth = vid.width; vid.conheight = vid.height; - vid.aspect = ((float)vid.height / (float)vid.width) * (320.0 / 240.0); - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); + vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); + vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); } void -VID_ShiftPalette(unsigned char *pal) +VID_ShiftPalette (unsigned char *pal) { - VID_SetPalette(pal); + VID_SetPalette (pal); } @@ -472,18 +481,18 @@ void VID_SetPalette (unsigned char *pal) { - int i; - ggi_color colors[256]; + int i; + ggi_color colors[256]; - for (i=0 ; i<256 ; i++) { - colors[i].r = pal[i*3] * 257; - colors[i].g = pal[i*3+1] * 257; - colors[i].b = pal[i*3+2] * 257; + for (i = 0; i < 256; i++) { + colors[i].r = pal[i * 3] * 257; + colors[i].g = pal[i * 3 + 1] * 257; + colors[i].b = pal[i * 3 + 2] * 257; } if (palette) { - ggiPackColors(ggivis, palette, colors, 256); + ggiPackColors (ggivis, palette, colors, 256); } else { - ggiSetPalette(ggivis, 0, 256, colors); + ggiSetPalette (ggivis, 0, 256, colors); } } @@ -492,25 +501,25 @@ VID_SetPalette (unsigned char *pal) void VID_Shutdown (void) { - Con_Printf("VID_Shutdown\n"); + Con_Printf ("VID_Shutdown\n"); if (!usedbuf) { - free(drawptr); + free (drawptr); drawptr = NULL; } if (oneline) { - free(oneline); + free (oneline); oneline = NULL; } if (palette) { - free(palette); + free (palette); palette = NULL; } if (ggivis) { - ggiClose(ggivis); + ggiClose (ggivis); ggivis = NULL; } - ggiExit(); + ggiExit (); } @@ -519,58 +528,57 @@ VID_Shutdown (void) void VID_Update (vrect_t *rects) { - int height = 0; + int height = 0; #if 0 // if the window changes dimension, skip this frame - if (config_notify) - { - fprintf(stderr, "config notify\n"); + if (config_notify) { + fprintf (stderr, "config notify\n"); config_notify = 0; vid.width = config_notify_width & ~7; vid.height = config_notify_height; if (doShm) - ResetSharedFrameBuffers(); + ResetSharedFrameBuffers (); else - ResetFrameBuffer(); + ResetFrameBuffer (); vid.rowbytes = x_framebuffer[0]->bytes_per_line; vid.buffer = x_framebuffer[curframe]->data; vid.conbuffer = vid.buffer; vid.conwidth = vid.width; vid.conheight = vid.height; vid.conrowbytes = vid.rowbytes; - vid.recalc_refdef = 1; // force a surface cache flush - Con_CheckResize(); - Con_Clear_f(); + vid.recalc_refdef = 1; // force a surface cache flush + Con_CheckResize (); + Con_Clear_f (); return; } - // force full update if not 8bit if (x_visinfo->depth != 8) { - extern int scr_fullupdate; + extern int scr_fullupdate; scr_fullupdate = 0; } #endif while (rects) { - int y = rects->y + rects->height; - if (y > height) height = y; + int y = rects->y + rects->height; + + if (y > height) + height = y; rects = rects->pnext; } if (!usedbuf) { - int i; + int i; if (havedbuf) { - if (ggiResourceAcquire(dbuf1->resource, - GGI_ACTYPE_WRITE) != 0 || - (doublebuffer ? - ggiResourceAcquire(dbuf2->resource, - GGI_ACTYPE_WRITE) != 0 - : 0)) { - ggiPanic("Unable to acquire DirectBuffer!\n"); + if (ggiResourceAcquire (dbuf1->resource, + GGI_ACTYPE_WRITE) != 0 || + (doublebuffer ? + ggiResourceAcquire (dbuf2->resource, + GGI_ACTYPE_WRITE) != 0 : 0)) { + ggiPanic ("Unable to acquire DirectBuffer!\n"); } /* ->write is allowed to change at acquire time */ frameptr[0] = dbuf1->write; @@ -582,134 +590,134 @@ VID_Update (vrect_t *rects) } if (scale) { switch (pixelsize) { - case 1: if (havedbuf) { - do_scale8(vid.width, height, - frameptr[curframe], drawptr); - } else { - uint8 *buf = drawptr; - for (i=0; i < height; i++) { - do_scale8(vid.width, 1, oneline,buf); - ggiPutBox(ggivis, 0, i*2, realwidth, - 2, oneline); - buf += vid.width; - } - } - break; - case 2: if (havedbuf) { - do_scale16(vid.width, height, - frameptr[curframe], drawptr); - } else { - uint8 *buf = drawptr; - for (i=0; i < height; i++) { - do_scale16(vid.width, 1, - oneline, buf); - ggiPutBox(ggivis, 0, i*2, realwidth, - 2, oneline); - buf += vid.width; - } - } - break; - case 4: if (havedbuf) { - do_scale32(vid.width, height, - frameptr[curframe], drawptr); - } else { - uint8 *buf = drawptr; - for (i=0; i < height; i++) { - do_scale32(vid.width, 1, - oneline, buf); - ggiPutBox(ggivis, 0, i*2, realwidth, - 2, oneline); - buf += vid.width; - } - } - break; + case 1: + if (havedbuf) { + do_scale8 (vid.width, height, + frameptr[curframe], drawptr); + } else { + uint8 *buf = drawptr; + + for (i = 0; i < height; i++) { + do_scale8 (vid.width, 1, oneline, buf); + ggiPutBox (ggivis, 0, i * 2, realwidth, 2, oneline); + buf += vid.width; + } + } + break; + case 2: + if (havedbuf) { + do_scale16 (vid.width, height, + frameptr[curframe], drawptr); + } else { + uint8 *buf = drawptr; + + for (i = 0; i < height; i++) { + do_scale16 (vid.width, 1, oneline, buf); + ggiPutBox (ggivis, 0, i * 2, realwidth, 2, oneline); + buf += vid.width; + } + } + break; + case 4: + if (havedbuf) { + do_scale32 (vid.width, height, + frameptr[curframe], drawptr); + } else { + uint8 *buf = drawptr; + + for (i = 0; i < height; i++) { + do_scale32 (vid.width, 1, oneline, buf); + ggiPutBox (ggivis, 0, i * 2, realwidth, 2, oneline); + buf += vid.width; + } + } + break; } } else if (palette) { switch (pixelsize) { - case 1: if (havedbuf) { - do_copy8(vid.width, height, - frameptr[curframe], drawptr); - } else { - uint8 *buf = drawptr; - for (i=0; i < height; i++) { - do_copy8(vid.width, 1, oneline,buf); - ggiPutBox(ggivis, 0, i, realwidth, - 1, oneline); - buf += vid.width; - } - } - break; - case 2: if (havedbuf) { - do_copy16(vid.width, height, - frameptr[curframe], drawptr); - } else { - uint8 *buf = drawptr; - for (i=0; i < height; i++) { - do_copy16(vid.width, 1, - oneline, buf); - ggiPutBox(ggivis, 0, i, realwidth, - 1, oneline); - buf += vid.width; - } - } - break; - case 4: if (havedbuf) { - do_copy32(vid.width, height, - frameptr[curframe], drawptr); - } else { - uint8 *buf = drawptr; - for (i=0; i < height; i++) { - do_copy32(vid.width, 1, - oneline, buf); - ggiPutBox(ggivis, 0, i, realwidth, - 1, oneline); - buf += vid.width; - } - } - break; + case 1: + if (havedbuf) { + do_copy8 (vid.width, height, + frameptr[curframe], drawptr); + } else { + uint8 *buf = drawptr; + + for (i = 0; i < height; i++) { + do_copy8 (vid.width, 1, oneline, buf); + ggiPutBox (ggivis, 0, i, realwidth, 1, oneline); + buf += vid.width; + } + } + break; + case 2: + if (havedbuf) { + do_copy16 (vid.width, height, + frameptr[curframe], drawptr); + } else { + uint8 *buf = drawptr; + + for (i = 0; i < height; i++) { + do_copy16 (vid.width, 1, oneline, buf); + ggiPutBox (ggivis, 0, i, realwidth, 1, oneline); + buf += vid.width; + } + } + break; + case 4: + if (havedbuf) { + do_copy32 (vid.width, height, + frameptr[curframe], drawptr); + } else { + uint8 *buf = drawptr; + + for (i = 0; i < height; i++) { + do_copy32 (vid.width, 1, oneline, buf); + ggiPutBox (ggivis, 0, i, realwidth, 1, oneline); + buf += vid.width; + } + } + break; } } else { - ggiPutBox(ggivis, 0, 0, vid.width, height, - drawptr); + ggiPutBox (ggivis, 0, 0, vid.width, height, drawptr); } if (havedbuf) { - ggiResourceRelease(dbuf1->resource); + ggiResourceRelease (dbuf1->resource); if (doublebuffer) { - ggiResourceRelease(dbuf2->resource); + ggiResourceRelease (dbuf2->resource); } } } if (doublebuffer) { - ggiSetDisplayFrame(ggivis, curframe); + ggiSetDisplayFrame (ggivis, curframe); curframe = !curframe; if (usedbuf) { vid.buffer = vid.conbuffer = vid.direct = drawptr = frameptr[curframe]; } - ggiSetWriteFrame(ggivis, curframe); + ggiSetWriteFrame (ggivis, curframe); } - #if 0 - if (GT_SIZE(mode.graphtype) == 16) { - do_copy16(vid.width, height, - (uint16*)frameptr, drawptr); - } else if (GT_SIZE(mode.graphtype) == 32) { - do_copy32(vid.width, height, - (uint32*)frameptr, drawptr); + if (GT_SIZE (mode.graphtype) == 16) { + do_copy16 (vid.width, height, (uint16 *) frameptr, drawptr); + } else if (GT_SIZE (mode.graphtype) == 32) { + do_copy32 (vid.width, height, (uint32 *) frameptr, drawptr); } #endif - ggiFlush(ggivis); + ggiFlush (ggivis); } -void D_BeginDirectRect(int x, int y, byte *pbitmap, int width, int height) +void +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { // direct drawing of the "accessing disk" icon isn't supported under Linux } -void D_EndDirectRect (int x, int y, int width, int height) +void +D_EndDirectRect (int x, int y, int width, int height) { // direct drawing of the "accessing disk" icon isn't supported under Linux } @@ -721,238 +729,358 @@ void D_EndDirectRect (int x, int y, int width, int height) *************************************************************************** */ -static int XLateKey(ggi_key_event *ev) +static int +XLateKey (ggi_key_event * ev) { - int key = 0; + int key = 0; - if (GII_KTYP(ev->label) == GII_KT_DEAD) { - ev->label = GII_KVAL(ev->label); + if (GII_KTYP (ev->label) == GII_KT_DEAD) { + ev->label = GII_KVAL (ev->label); } - switch(ev->label) { - case GIIK_P9: key = KP_PGUP; break; - case GIIK_PageUp: key = K_PGUP; break; + switch (ev->label) { + case GIIK_P9: + key = KP_PGUP; + break; + case GIIK_PageUp: + key = K_PGUP; + break; - case GIIK_P3: key = KP_PGDN; break; - case GIIK_PageDown: key = K_PGDN; break; + case GIIK_P3: + key = KP_PGDN; + break; + case GIIK_PageDown: + key = K_PGDN; + break; - case GIIK_P7: key = KP_HOME; break; - case GIIK_Home: key = K_HOME; break; + case GIIK_P7: + key = KP_HOME; + break; + case GIIK_Home: + key = K_HOME; + break; - case GIIK_P1: key = KP_END; break; - case GIIK_End: key = K_END; break; + case GIIK_P1: + key = KP_END; + break; + case GIIK_End: + key = K_END; + break; - case GIIK_P4: key = KP_LEFTARROW; break; - case GIIK_Left: key = K_LEFTARROW; break; + case GIIK_P4: + key = KP_LEFTARROW; + break; + case GIIK_Left: + key = K_LEFTARROW; + break; - case GIIK_P6: key = KP_RIGHTARROW; break; - case GIIK_Right: key = K_RIGHTARROW; break; + case GIIK_P6: + key = KP_RIGHTARROW; + break; + case GIIK_Right: + key = K_RIGHTARROW; + break; - case GIIK_P2: key = KP_DOWNARROW; break; - case GIIK_Down: key = K_DOWNARROW; break; + case GIIK_P2: + key = KP_DOWNARROW; + break; + case GIIK_Down: + key = K_DOWNARROW; + break; - case GIIK_P8: key = KP_UPARROW; break; - case GIIK_Up: key = K_UPARROW; break; + case GIIK_P8: + key = KP_UPARROW; + break; + case GIIK_Up: + key = K_UPARROW; + break; - case GIIK_P5: key = KP_5; break; - case GIIK_PBegin: key = K_AUX32; break; + case GIIK_P5: + key = KP_5; + break; + case GIIK_PBegin: + key = K_AUX32; + break; - case GIIK_P0: key = KP_INS; break; - case GIIK_Insert: key = K_INS; break; + case GIIK_P0: + key = KP_INS; + break; + case GIIK_Insert: + key = K_INS; + break; - case GIIK_PSeparator: - case GIIK_PDecimal: key = KP_DEL; break; - case GIIUC_Delete: key = K_DEL; break; + case GIIK_PSeparator: + case GIIK_PDecimal: + key = KP_DEL; + break; + case GIIUC_Delete: + key = K_DEL; + break; - case GIIK_PStar: key = KP_MULTIPLY; break; - case GIIK_PPlus: key = KP_PLUS; break; - case GIIK_PMinus: key = KP_MINUS; break; - case GIIK_PSlash: key = KP_DIVIDE; break; + case GIIK_PStar: + key = KP_MULTIPLY; + break; + case GIIK_PPlus: + key = KP_PLUS; + break; + case GIIK_PMinus: + key = KP_MINUS; + break; + case GIIK_PSlash: + key = KP_DIVIDE; + break; - case GIIK_PEnter: key = KP_ENTER; break; - case GIIUC_Return: key = K_ENTER; break; + case GIIK_PEnter: + key = KP_ENTER; + break; + case GIIUC_Return: + key = K_ENTER; + break; - case GIIUC_Escape: key = K_ESCAPE; break; + case GIIUC_Escape: + key = K_ESCAPE; + break; - case GIIUC_Tab: key = K_TAB; break; + case GIIUC_Tab: + key = K_TAB; + break; - case GIIK_F1: key = K_F1; break; - case GIIK_F2: key = K_F2; break; - case GIIK_F3: key = K_F3; break; - case GIIK_F4: key = K_F4; break; - case GIIK_F5: key = K_F5; break; - case GIIK_F6: key = K_F6; break; - case GIIK_F7: key = K_F7; break; - case GIIK_F8: key = K_F8; break; - case GIIK_F9: key = K_F9; break; - case GIIK_F10: key = K_F10; break; - case GIIK_F11: key = K_F11; break; - case GIIK_F12: key = K_F12; break; + case GIIK_F1: + key = K_F1; + break; + case GIIK_F2: + key = K_F2; + break; + case GIIK_F3: + key = K_F3; + break; + case GIIK_F4: + key = K_F4; + break; + case GIIK_F5: + key = K_F5; + break; + case GIIK_F6: + key = K_F6; + break; + case GIIK_F7: + key = K_F7; + break; + case GIIK_F8: + key = K_F8; + break; + case GIIK_F9: + key = K_F9; + break; + case GIIK_F10: + key = K_F10; + break; + case GIIK_F11: + key = K_F11; + break; + case GIIK_F12: + key = K_F12; + break; - case GIIUC_BackSpace: key = K_BACKSPACE; break; + case GIIUC_BackSpace: + key = K_BACKSPACE; + break; - case GIIK_ShiftL: - case GIIK_ShiftR: key = K_SHIFT; break; + case GIIK_ShiftL: + case GIIK_ShiftR: + key = K_SHIFT; + break; - case GIIK_Execute: - case GIIK_CtrlL: - case GIIK_CtrlR: key = K_CTRL; break; + case GIIK_Execute: + case GIIK_CtrlL: + case GIIK_CtrlR: + key = K_CTRL; + break; - case GIIK_AltL: - case GIIK_MetaL: - case GIIK_AltR: - case GIIK_MetaR: - case GIIK_AltGr: - case GIIK_ModeSwitch: key = K_ALT; break; + case GIIK_AltL: + case GIIK_MetaL: + case GIIK_AltR: + case GIIK_MetaR: + case GIIK_AltGr: + case GIIK_ModeSwitch: + key = K_ALT; + break; - case GIIK_Caps: key = K_CAPSLOCK; break; - case GIIK_PrintScreen: key = K_PRNTSCR; break; - case GIIK_ScrollLock: key = K_SCRLCK; break; - case GIIK_Pause: key = K_PAUSE; break; - case GIIK_NumLock: key = KP_NUMLCK; break; + case GIIK_Caps: + key = K_CAPSLOCK; + break; + case GIIK_PrintScreen: + key = K_PRNTSCR; + break; + case GIIK_ScrollLock: + key = K_SCRLCK; + break; + case GIIK_Pause: + key = K_PAUSE; + break; + case GIIK_NumLock: + key = KP_NUMLCK; + break; - case GIIUC_Comma: case GIIUC_Minus: case GIIUC_Period: - key = ev->label; - break; - case GIIUC_Section: key = '~'; break; + case GIIUC_Comma: + case GIIUC_Minus: + case GIIUC_Period: + key = ev->label; + break; + case GIIUC_Section: + key = '~'; + break; - default: - if (ev->label >= 0 && ev->label <= 9) return ev->label; - if (ev->label >= 'A' && ev->label <= 'Z') { - return ev->label - 'A' + 'a'; - } - if (ev->label >= 'a' && ev->label <= 'z') return ev->label; - - if (ev->sym <= 0x7f) { - key = ev->sym; - if (key >= 'A' && key <= 'Z') { - key = key - 'A' + 'a'; + default: + if (ev->label >= 0 && ev->label <= 9) + return ev->label; + if (ev->label >= 'A' && ev->label <= 'Z') { + return ev->label - 'A' + 'a'; } - return key; - } - if (ev->label <= 0x7f) { - return ev->label; - } - break; + if (ev->label >= 'a' && ev->label <= 'z') + return ev->label; + + if (ev->sym <= 0x7f) { + key = ev->sym; + if (key >= 'A' && key <= 'Z') { + key = key - 'A' + 'a'; + } + return key; + } + if (ev->label <= 0x7f) { + return ev->label; + } + break; } return key; } -static void GetEvent(void) +static void +GetEvent (void) { - ggi_event ev; - uint32 b; + ggi_event ev; + uint32 b; - ggiEventRead(ggivis, &ev, emAll); - switch(ev.any.type) { - case evKeyPress: - Key_Event(XLateKey(&ev.key), 0, true); - break; + ggiEventRead (ggivis, &ev, emAll); + switch (ev.any.type) { + case evKeyPress: + Key_Event (XLateKey (&ev.key), 0, true); + break; - case evKeyRelease: - Key_Event(XLateKey(&ev.key), 0, false); - break; + case evKeyRelease: + Key_Event (XLateKey (&ev.key), 0, false); + break; - case evPtrRelative: - mouse_x += (float) ev.pmove.x; - mouse_y += (float) ev.pmove.y; - break; + case evPtrRelative: + mouse_x += (float) ev.pmove.x; + mouse_y += (float) ev.pmove.y; + break; - case evPtrAbsolute: - mouse_x += (float) (ev.pmove.x-p_mouse_x); - mouse_y += (float) (ev.pmove.y-p_mouse_y); - p_mouse_x = ev.pmove.x; - p_mouse_y = ev.pmove.y; - break; + case evPtrAbsolute: + mouse_x += (float) (ev.pmove.x - p_mouse_x); + mouse_y += (float) (ev.pmove.y - p_mouse_y); + p_mouse_x = ev.pmove.x; + p_mouse_y = ev.pmove.y; + break; - case evPtrButtonPress: - if (!mouse_avail) return; + case evPtrButtonPress: + if (!mouse_avail) + return; - b = ev.pbutton.button - 1; + b = ev.pbutton.button - 1; - if (b < NUM_STDBUTTONS) { - Key_Event(K_MOUSE1 + b, 0, true); - } else if (b < NUM_STDBUTTONS+2) { - b-=3; - if (b) Key_Event(K_MWHEELDOWN, 0, true); - else Key_Event(K_MWHEELUP, 0, true); - } else if (b < NUM_BUTTONS) { - Key_Event(K_AUX32 - NUM_BUTTONS + b, 0, true); - } - break; + if (b < NUM_STDBUTTONS) { + Key_Event (K_MOUSE1 + b, 0, true); + } else if (b < NUM_STDBUTTONS + 2) { + b -= 3; + if (b) + Key_Event (K_MWHEELDOWN, 0, true); + else + Key_Event (K_MWHEELUP, 0, true); + } else if (b < NUM_BUTTONS) { + Key_Event (K_AUX32 - NUM_BUTTONS + b, 0, true); + } + break; - case evPtrButtonRelease: - if (!mouse_avail) return; + case evPtrButtonRelease: + if (!mouse_avail) + return; - b = ev.pbutton.button - 1; + b = ev.pbutton.button - 1; - if (b < NUM_STDBUTTONS) { - Key_Event(K_MOUSE1 + b, 0, false); - } else if (b < NUM_STDBUTTONS+2) { - b-=3; - if (b) Key_Event(K_MWHEELDOWN, 0, false); - else Key_Event(K_MWHEELUP, 0, false); - } else if (b < NUM_BUTTONS) { - Key_Event(K_AUX32 - NUM_BUTTONS + b, 0, false); - } - break; + if (b < NUM_STDBUTTONS) { + Key_Event (K_MOUSE1 + b, 0, false); + } else if (b < NUM_STDBUTTONS + 2) { + b -= 3; + if (b) + Key_Event (K_MWHEELDOWN, 0, false); + else + Key_Event (K_MWHEELUP, 0, false); + } else if (b < NUM_BUTTONS) { + Key_Event (K_AUX32 - NUM_BUTTONS + b, 0, false); + } + break; #if 0 - case ConfigureNotify: + case ConfigureNotify: //printf("config notify\n"); - config_notify_width = ev.xconfigure.width; - config_notify_height = ev.xconfigure.height; - config_notify = 1; - break; + config_notify_width = ev.xconfigure.width; + config_notify_height = ev.xconfigure.height; + config_notify = 1; + break; - default: + default: #endif } } -void IN_SendKeyEvents(void) +void +IN_SendKeyEvents (void) { /* Get events from LibGGI */ if (ggivis) { - struct timeval t = {0,0}; + struct timeval t = { 0, 0 }; - if (ggiEventPoll(ggivis, emAll, &t)) { - int i = ggiEventsQueued(ggivis, emAll); - while (i--) GetEvent(); + if (ggiEventPoll (ggivis, emAll, &t)) { + int i = ggiEventsQueued (ggivis, emAll); + + while (i--) + GetEvent (); } } } void -IN_Init(void) +IN_Init (void) { JOY_Init (); - old_windowed_mouse = -1; /* Force update */ - if (COM_CheckParm ("-nomouse")) return; + old_windowed_mouse = -1; /* Force update */ + if (COM_CheckParm ("-nomouse")) + return; mouse_x = mouse_y = 0.0; mouse_avail = 1; } void -IN_Init_Cvars(void) +IN_Init_Cvars (void) { JOY_Init_Cvars (); - _windowed_mouse = Cvar_Get("_windowed_mouse", "0", CVAR_ARCHIVE, "None"); - m_filter = Cvar_Get("m_filter", "0", CVAR_ARCHIVE, "None"); + _windowed_mouse = Cvar_Get ("_windowed_mouse", "0", CVAR_ARCHIVE, "None"); + m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE, "None"); } void -IN_Shutdown(void) +IN_Shutdown (void) { JOY_Shutdown (); - Con_Printf("IN_Shutdown\n"); + Con_Printf ("IN_Shutdown\n"); mouse_avail = 0; } @@ -965,27 +1093,27 @@ IN_Commands (void) /* Only supported by LibGII 0.7 or later. */ #ifdef GII_CMDCODE_PREFER_RELPTR if (old_windowed_mouse != _windowed_mouse->int_val) { - gii_event ev; + gii_event ev; old_windowed_mouse = _windowed_mouse->int_val; - ev.cmd.size = sizeof(gii_cmd_nodata_event); + ev.cmd.size = sizeof (gii_cmd_nodata_event); ev.cmd.type = evCommand; ev.cmd.target = GII_EV_TARGET_ALL; ev.cmd.code = _windowed_mouse->int_val ? GII_CMDCODE_PREFER_RELPTR : GII_CMDCODE_PREFER_ABSPTR; - ggiEventSend(ggivis, &ev); + ggiEventSend (ggivis, &ev); } #endif } void -IN_Move(usercmd_t *cmd) +IN_Move (usercmd_t *cmd) { JOY_Move (cmd); - + if (!mouse_avail) return; @@ -1000,7 +1128,7 @@ IN_Move(usercmd_t *cmd) mouse_x *= sensitivity->value; mouse_y *= sensitivity->value; - if ( (in_strafe.state & 1) || (lookstrafe->int_val && freelook)) + if ((in_strafe.state & 1) || (lookstrafe->int_val && freelook)) cmd->sidemove += m_side->value * mouse_x; else cl.viewangles[YAW] -= m_yaw->value * mouse_x; @@ -1020,19 +1148,22 @@ IN_Move(usercmd_t *cmd) } -void VID_Init_Cvars(void) +void +VID_Init_Cvars (void) { } -void VID_LockBuffer(void) +void +VID_LockBuffer (void) { } -void VID_UnlockBuffer(void) +void +VID_UnlockBuffer (void) { } -void VID_SetCaption (char *text) +void +VID_SetCaption (char *text) { } - diff --git a/source/vid_glx.c b/source/vid_glx.c index 444aeb5..1166e4b 100644 --- a/source/vid_glx.c +++ b/source/vid_glx.c @@ -56,12 +56,13 @@ #define WARP_WIDTH 320 #define WARP_HEIGHT 200 -static qboolean vid_initialized = false; +static qboolean vid_initialized = false; -static GLXContext ctx = NULL; +static GLXContext ctx = NULL; extern void GL_Init_Common (void); extern void VID_Init8bitPalette (void); + /*-----------------------------------------------------------------------*/ const char *gl_vendor; @@ -128,8 +129,8 @@ GL_EndRendering (void) void VID_Init (unsigned char *palette) { - int i; - int attrib[] = { + int i; + int attrib[] = { GLX_RGBA, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, @@ -145,31 +146,32 @@ VID_Init (unsigned char *palette) vid.colormap = host_colormap; vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); - /* Interpret command-line params - */ + /* Interpret command-line params */ /* Set vid parameters */ if ((i = COM_CheckParm ("-conwidth"))) - vid.conwidth = atoi(com_argv[i+1]); + vid.conwidth = atoi (com_argv[i + 1]); else vid.conwidth = scr_width; - vid.conwidth &= 0xfff8; // make it a multiple of eight + vid.conwidth &= 0xfff8; // make it a multiple of eight vid.conwidth = max (vid.conwidth, 320); // pick a conheight that matches with correct aspect vid.conheight = vid.conwidth * 3 / 4; - if ((i = COM_CheckParm ("-conheight"))) // conheight no smaller than 200px - vid.conheight = atoi (com_argv[i+1]); + if ((i = COM_CheckParm ("-conheight"))) // conheight no smaller than + // 200px + vid.conheight = atoi (com_argv[i + 1]); vid.conheight = max (vid.conheight, 200); x11_open_display (); x_visinfo = glXChooseVisual (x_disp, x_screen, attrib); if (!x_visinfo) { - fprintf (stderr, "Error couldn't get an RGB, Double-buffered, Depth visual\n"); + fprintf (stderr, + "Error couldn't get an RGB, Double-buffered, Depth visual\n"); exit (1); } x_vis = x_visinfo->visual; @@ -193,7 +195,7 @@ VID_Init (unsigned char *palette) vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); vid.numpages = 2; - //InitSig (); // trap evil signals + // InitSig (); // trap evil signals GL_Init (); @@ -207,20 +209,21 @@ VID_Init (unsigned char *palette) vid_initialized = true; - vid.recalc_refdef = 1; // force a surface cache flush + vid.recalc_refdef = 1; // force a surface cache flush } void VID_Init_Cvars () { - x11_Init_Cvars(); + x11_Init_Cvars (); } void VID_SetCaption (char *text) { if (text && *text) { - char *temp = strdup (text); + char *temp = strdup (text); + x11_set_caption (va ("%s %s: %s", PROGRAM, VERSION, temp)); free (temp); } else { diff --git a/source/vid_mgl.c b/source/vid_mgl.c index 80080dc..d5a9e88 100644 --- a/source/vid_mgl.c +++ b/source/vid_mgl.c @@ -54,41 +54,45 @@ #define MAX_MODE_LIST 30 #define VID_ROW_SIZE 3 -extern void (*vid_menudrawfn)(void); -extern void (*vid_menukeyfn)(int); +extern void (*vid_menudrawfn) (void); +extern void (*vid_menukeyfn) (int); /* Unused */ -int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; -byte *VGA_pagebase; +int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; +byte *VGA_pagebase; -qboolean dibonly; +qboolean dibonly; extern qboolean Minimized; -HWND mainwindow; +HWND mainwindow; HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow); -int DIBWidth, DIBHeight; -qboolean DDActive; -RECT WindowRect; -DWORD WindowStyle, ExWindowStyle; +int DIBWidth, DIBHeight; +qboolean DDActive; +RECT WindowRect; +DWORD WindowStyle, ExWindowStyle; -int window_center_x, window_center_y, window_x, window_y, window_width, window_height; -RECT window_rect; +int window_center_x, window_center_y, window_x, window_y, window_width, -static DEVMODE gdevmode; -static qboolean startwindowed = 0, windowed_mode_set = 0; -static int firstupdate = 1; -static qboolean vid_initialized = false, vid_palettized; -static int lockcount; -static int vid_fulldib_on_focus_mode; -static qboolean force_minimized, in_mode_set, is_mode0x13, force_mode_set; -static int vid_stretched, windowed_mouse; -static qboolean palette_changed, syscolchg, vid_mode_set, hide_window, pal_is_nostatic; -static HICON hIcon; + window_height; +RECT window_rect; -extern viddef_t vid; // global video state +static DEVMODE gdevmode; +static qboolean startwindowed = 0, windowed_mode_set = 0; +static int firstupdate = 1; +static qboolean vid_initialized = false, vid_palettized; +static int lockcount; +static int vid_fulldib_on_focus_mode; +static qboolean force_minimized, in_mode_set, is_mode0x13, force_mode_set; +static int vid_stretched, windowed_mouse; +static qboolean palette_changed, syscolchg, vid_mode_set, hide_window, + + pal_is_nostatic; +static HICON hIcon; + +extern viddef_t vid; // global video state #define MODE_WINDOWED 0 #define MODE_SETTABLE_WINDOW 2 @@ -96,101 +100,100 @@ extern viddef_t vid; // global video state #define MODE_FULLSCREEN_DEFAULT (MODE_WINDOWED + 3) // Note that 0 is MODE_WINDOWED -cvar_t *vid_mode; +cvar_t *vid_mode; + // Note that 0 is MODE_WINDOWED // Note that 3 is MODE_FULLSCREEN_DEFAULT -cvar_t *_vid_default_mode_win; -cvar_t *vid_nopageflip; -cvar_t *vid_config_x; -cvar_t *vid_config_y; -cvar_t *vid_stretch_by_2; -cvar_t *_windowed_mouse; -cvar_t *vid_fullscreen_mode; -cvar_t *vid_windowed_mode; -cvar_t *block_switch; -cvar_t *vid_window_x; -cvar_t *vid_window_y; +cvar_t *_vid_default_mode_win; +cvar_t *vid_nopageflip; +cvar_t *vid_config_x; +cvar_t *vid_config_y; +cvar_t *vid_stretch_by_2; +cvar_t *_windowed_mouse; +cvar_t *vid_fullscreen_mode; +cvar_t *vid_windowed_mode; +cvar_t *block_switch; +cvar_t *vid_window_x; +cvar_t *vid_window_y; typedef struct { - int width; - int height; + int width; + int height; } lmode_t; -lmode_t lowresmodes[] = { +lmode_t lowresmodes[] = { {320, 200}, {320, 240}, {400, 300}, {512, 384}, }; -int vid_modenum = NO_MODE; -int vid_testingmode, vid_realmode; -double vid_testendtime; -int vid_default = MODE_WINDOWED; -static int windowed_default; +int vid_modenum = NO_MODE; +int vid_testingmode, vid_realmode; +double vid_testendtime; +int vid_default = MODE_WINDOWED; +static int windowed_default; -modestate_t modestate = MS_UNINIT; +modestate_t modestate = MS_UNINIT; -static byte *vid_surfcache; -static int vid_surfcachesize; -static int VID_highhunkmark; +static byte *vid_surfcache; +static int vid_surfcachesize; +static int VID_highhunkmark; -unsigned char vid_curpal[256*3]; +unsigned char vid_curpal[256 * 3]; -unsigned short d_8to16table[256]; -unsigned int d_8to24table[256]; +unsigned short d_8to16table[256]; +unsigned int d_8to24table[256]; -int driver = grDETECT,mode; -qboolean useWinDirect = true, useDirectDraw = true; -MGLDC *mgldc = NULL,*memdc = NULL,*dibdc = NULL,*windc = NULL; +int driver = grDETECT, mode; +qboolean useWinDirect = true, useDirectDraw = true; +MGLDC *mgldc = NULL, *memdc = NULL, *dibdc = NULL, *windc = NULL; typedef struct { - modestate_t type; - int width; - int height; - int modenum; - int mode13; - int stretched; - int dib; - int fullscreen; - int bpp; - int halfscreen; - char modedesc[13]; + modestate_t type; + int width; + int height; + int modenum; + int mode13; + int stretched; + int dib; + int fullscreen; + int bpp; + int halfscreen; + char modedesc[13]; } vmode_t; -static vmode_t modelist[MAX_MODE_LIST]; -static int nummodes; +static vmode_t modelist[MAX_MODE_LIST]; +static int nummodes; -int aPage; // Current active display page -int vPage; // Current visible display page -int waitVRT = true; // True to wait for retrace on flip +int aPage; // Current active display page +int vPage; // Current visible display page +int waitVRT = true; // True to wait for retrace on flip -static vmode_t badmode; +static vmode_t badmode; -static byte backingbuf[48*24]; +static byte backingbuf[48 * 24]; -void VID_MenuDraw (void); -void VID_MenuKey (int key); +void VID_MenuDraw (void); +void VID_MenuKey (int key); LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); -void AppActivate(BOOL fActive, BOOL minimize); +void AppActivate (BOOL fActive, BOOL minimize); /* ================ VID_RememberWindowPos ================ */ -void VID_RememberWindowPos (void) +void +VID_RememberWindowPos (void) { - RECT rect; + RECT rect; - if (GetWindowRect (mainwindow, &rect)) - { + if (GetWindowRect (mainwindow, &rect)) { if ((rect.left < GetSystemMetrics (SM_CXSCREEN)) && - (rect.top < GetSystemMetrics (SM_CYSCREEN)) && - (rect.right > 0) && - (rect.bottom > 0)) - { + (rect.top < GetSystemMetrics (SM_CYSCREEN)) && + (rect.right > 0) && (rect.bottom > 0)) { Cvar_SetValue (vid_window_x, rect.left); Cvar_SetValue (vid_window_y, rect.top); } @@ -203,16 +206,15 @@ void VID_RememberWindowPos (void) VID_CheckWindowXY ================ */ -void VID_CheckWindowXY (void) +void +VID_CheckWindowXY (void) { if ((vid_window_x->int_val > (GetSystemMetrics (SM_CXSCREEN) - 160)) || (vid_window_y->int_val > (GetSystemMetrics (SM_CYSCREEN) - 120)) || - (vid_window_x->int_val < 0) || - (vid_window_y->int_val < 0)) - { + (vid_window_x->int_val < 0) || (vid_window_y->int_val < 0)) { Cvar_SetValue (vid_window_x, 0.0); - Cvar_SetValue (vid_window_y, 0.0 ); + Cvar_SetValue (vid_window_y, 0.0); } } @@ -222,7 +224,8 @@ void VID_CheckWindowXY (void) VID_UpdateWindowStatus ================ */ -void VID_UpdateWindowStatus (void) +void +VID_UpdateWindowStatus (void) { window_rect.left = window_x; @@ -243,9 +246,10 @@ extern void CL_ClearStates (); ClearAllStates ================ */ -void ClearAllStates (void) +void +ClearAllStates (void) { - CL_ClearStates (); + CL_ClearStates (); Key_ClearStates (); IN_ClearStates (); } @@ -256,7 +260,8 @@ void ClearAllStates (void) VID_CheckAdequateMem ================ */ -qboolean VID_CheckAdequateMem (int width, int height) +qboolean +VID_CheckAdequateMem (int width, int height) { return true; } @@ -270,19 +275,18 @@ qboolean VID_CheckAdequateMem (int width, int height) qboolean VID_AllocBuffers (int width, int height) { - int zbuffersize, cachesize; + int zbuffersize, cachesize; // Calculate the sizes we want first zbuffersize = width * height * sizeof (*d_pzbuffer); - cachesize = D_SurfaceCacheForRes(width, height); + cachesize = D_SurfaceCacheForRes (width, height); // Free the old z-buffer if (d_pzbuffer) { free (d_pzbuffer); d_pzbuffer = NULL; } - // Free the old surface cache vid_surfcache = D_SurfaceCacheAddress (); @@ -291,14 +295,12 @@ VID_AllocBuffers (int width, int height) free (vid_surfcache); vid_surfcache = NULL; } - // Allocate the new z-buffer d_pzbuffer = calloc (zbuffersize, 1); if (!d_pzbuffer) { Sys_Error ("Not enough memory for video mode\n"); return false; } - // Allocate the new surface cache; free the z-buffer if we fail vid_surfcache = calloc (cachesize, 1); if (!vid_surfcache) { @@ -313,41 +315,42 @@ VID_AllocBuffers (int width, int height) } -void initFatalError(void) +void +initFatalError (void) { - MGL_exit(); - MGL_fatalError(MGL_errorMsg(MGL_result())); - exit(EXIT_FAILURE); + MGL_exit (); + MGL_fatalError (MGL_errorMsg (MGL_result ())); + exit (EXIT_FAILURE); } -#if 0 //def NEW_SUSPEND +#if 0 // def NEW_SUSPEND -int VID_Suspend (MGLDC *dc, int flags) +int +VID_Suspend (MGLDC * dc, int flags) { - int i; - if (flags & MGL_DEACTIVATE) - { + int i; + + if (flags & MGL_DEACTIVATE) { IN_RestoreOriginalMouseState (); CDAudio_Pause (); // keep WM_PAINT from trying to redraw in_mode_set = true; block_drawing = true; - } - else if (flags & MGL_REACTIVATE) - { + } else if (flags & MGL_REACTIVATE) { IN_SetQuakeMouseState (); - // fix the leftover Alt from any Alt-Tab or the like that switched us away + // fix the leftover Alt from any Alt-Tab or the like that switched us + // away ClearAllStates (); CDAudio_Resume (); in_mode_set = false; block_drawing = false; -// vid.recalc_refdef = 1; +// vid.recalc_refdef = 1; force_mode_set = 1; i = msg_suppress_1; msg_suppress_1 = 1; - VID_Fullscreen_f(); + VID_Fullscreen_f (); msg_suppress_1 = i; force_mode_set = 0; } @@ -357,14 +360,13 @@ int VID_Suspend (MGLDC *dc, int flags) #else -int VID_Suspend (MGLDC *dc, int flags) +int +VID_Suspend (MGLDC * dc, int flags) { - if (flags & MGL_DEACTIVATE) - { - // FIXME: this doesn't currently work on NT - if (block_switch->int_val && !WinNT) - { + if (flags & MGL_DEACTIVATE) { + // FIXME: this doesn't currently work on NT + if (block_switch->int_val && !WinNT) { return MGL_NO_DEACTIVATE; } @@ -374,15 +376,15 @@ int VID_Suspend (MGLDC *dc, int flags) IN_RestoreOriginalMouseState (); CDAudio_Pause (); - // keep WM_PAINT from trying to redraw + // keep WM_PAINT from trying to redraw in_mode_set = true; - block_drawing = true; // so we don't try to draw while switched away - } - else if (flags & MGL_REACTIVATE) - { + block_drawing = true; // so we don't try to draw while + // switched away + } else if (flags & MGL_REACTIVATE) { IN_SetQuakeMouseState (); - // fix the leftover Alt from any Alt-Tab or the like that switched us away + // fix the leftover Alt from any Alt-Tab or the like that switched us + // away ClearAllStates (); CDAudio_Resume (); S_UnblockSound (); @@ -399,103 +401,92 @@ int VID_Suspend (MGLDC *dc, int flags) #endif -void registerAllDispDrivers(void) +void +registerAllDispDrivers (void) { - /* Event though these driver require WinDirect, we register - * them so that they will still be available even if DirectDraw - * is present and the user has disable the high performance - * WinDirect modes. - */ - MGL_registerDriver(MGL_VGA8NAME,VGA8_driver); -// MGL_registerDriver(MGL_VGAXNAME,VGAX_driver); + /* Event though these driver require WinDirect, we register * them so + that they will still be available even if DirectDraw * is present and + the user has disable the high performance * WinDirect modes. */ + MGL_registerDriver (MGL_VGA8NAME, VGA8_driver); +// MGL_registerDriver(MGL_VGAXNAME,VGAX_driver); /* Register display drivers */ - if (useWinDirect) - { -//we don't want VESA 1.X drivers MGL_registerDriver(MGL_SVGA8NAME,SVGA8_driver); - MGL_registerDriver(MGL_LINEAR8NAME,LINEAR8_driver); + if (useWinDirect) { +//we don't want VESA 1.X drivers MGL_registerDriver(MGL_SVGA8NAME,SVGA8_driver); + MGL_registerDriver (MGL_LINEAR8NAME, LINEAR8_driver); if (!COM_CheckParm ("-novbeaf")) - MGL_registerDriver(MGL_ACCEL8NAME,ACCEL8_driver); + MGL_registerDriver (MGL_ACCEL8NAME, ACCEL8_driver); } - if (useDirectDraw) - { - MGL_registerDriver(MGL_DDRAW8NAME,DDRAW8_driver); + if (useDirectDraw) { + MGL_registerDriver (MGL_DDRAW8NAME, DDRAW8_driver); } } -void registerAllMemDrivers(void) +void +registerAllMemDrivers (void) { /* Register memory context drivers */ - MGL_registerDriver(MGL_PACKED8NAME,PACKED8_driver); + MGL_registerDriver (MGL_PACKED8NAME, PACKED8_driver); } -void VID_InitMGLFull (HINSTANCE hInstance) +void +VID_InitMGLFull (HINSTANCE hInstance) { - int i, xRes, yRes, bits, lowres, curmode, temp; - int lowstretchedres, stretchedmode = 0, lowstretched; - uchar *m; + int i, xRes, yRes, bits, lowres, curmode, temp; + int lowstretchedres, stretchedmode = 0, lowstretched; + uchar *m; // FIXME: NT is checked for because MGL currently has a bug that causes it // to try to use WinDirect modes even on NT - if (COM_CheckParm("-nowindirect") || - COM_CheckParm("-nowd") || - COM_CheckParm("-novesa") || - WinNT) - { + if (COM_CheckParm ("-nowindirect") || + COM_CheckParm ("-nowd") || COM_CheckParm ("-novesa") || WinNT) { useWinDirect = false; } - if (COM_CheckParm("-nodirectdraw") || COM_CheckParm("-noddraw") || COM_CheckParm("-nodd")) + if (COM_CheckParm ("-nodirectdraw") || COM_CheckParm ("-noddraw") + || COM_CheckParm ("-nodd")) useDirectDraw = false; // Initialise the MGL - MGL_unregisterAllDrivers(); - registerAllDispDrivers(); - registerAllMemDrivers(); - MGL_detectGraph(&driver,&mode); - m = MGL_availableModes(); + MGL_unregisterAllDrivers (); + registerAllDispDrivers (); + registerAllMemDrivers (); + MGL_detectGraph (&driver, &mode); + m = MGL_availableModes (); - if (m[0] != 0xFF) - { + if (m[0] != 0xFF) { lowres = lowstretchedres = 99999; lowstretched = 0; curmode = 0; - // find the lowest-res mode, or a mode we can stretch up to and get - // lowest-res that way - for (i = 0; m[i] != 0xFF; i++) - { - MGL_modeResolution(m[i], &xRes, &yRes,&bits); + // find the lowest-res mode, or a mode we can stretch up to and get + // lowest-res that way + for (i = 0; m[i] != 0xFF; i++) { + MGL_modeResolution (m[i], &xRes, &yRes, &bits); if ((bits == 8) && (xRes <= MAXWIDTH) && - (yRes <= MAXHEIGHT) && - (curmode < MAX_MODE_LIST)) - { + (yRes <= MAXHEIGHT) && (curmode < MAX_MODE_LIST)) { if (m[i] == grVGA_320x200x256) is_mode0x13 = true; - if (!COM_CheckParm("-noforcevga")) - { - if (m[i] == grVGA_320x200x256) - { + if (!COM_CheckParm ("-noforcevga")) { + if (m[i] == grVGA_320x200x256) { mode = i; break; } } - if (xRes < lowres) - { + if (xRes < lowres) { lowres = xRes; mode = i; } - if ((xRes < lowstretchedres) && ((xRes >> 1) >= 320)) - { + if ((xRes < lowstretchedres) && ((xRes >> 1) >= 320)) { lowstretchedres = xRes >> 1; stretchedmode = i; } @@ -504,49 +495,43 @@ void VID_InitMGLFull (HINSTANCE hInstance) curmode++; } - // if there's a mode we can stretch by 2 up to, thereby effectively getting - // a lower-res mode than the lowest-res real but still at least 320x200, that - // will be our default mode - if (lowstretchedres < lowres) - { + // if there's a mode we can stretch by 2 up to, thereby effectively + // getting + // a lower-res mode than the lowest-res real but still at least + // 320x200, that + // will be our default mode + if (lowstretchedres < lowres) { mode = stretchedmode; lowres = lowstretchedres; lowstretched = 1; } + // build the mode list, leaving room for the low-res stretched mode, + // if any + nummodes++; // leave room for default mode - // build the mode list, leaving room for the low-res stretched mode, if any - nummodes++; // leave room for default mode - - for (i = 0; m[i] != 0xFF; i++) - { - MGL_modeResolution(m[i], &xRes, &yRes,&bits); + for (i = 0; m[i] != 0xFF; i++) { + MGL_modeResolution (m[i], &xRes, &yRes, &bits); if ((bits == 8) && (xRes <= MAXWIDTH) && - (yRes <= MAXHEIGHT) && - (nummodes < MAX_MODE_LIST)) - { - if (i == mode) - { - if (lowstretched) - { + (yRes <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST)) { + if (i == mode) { + if (lowstretched) { stretchedmode = nummodes; curmode = nummodes++; - } - else - { + } else { curmode = MODE_FULLSCREEN_DEFAULT; } - } - else - { + } else { curmode = nummodes++; } modelist[curmode].type = MS_FULLSCREEN; modelist[curmode].width = xRes; modelist[curmode].height = yRes; - snprintf (modelist[curmode].modedesc, sizeof(modelist[curmode].modedesc), "%dx%d", xRes, yRes); + snprintf (modelist[curmode].modedesc, + sizeof (modelist[curmode].modedesc), "%dx%d", xRes, + yRes); if (m[i] == grVGA_320x200x256) modelist[curmode].mode13 = 1; @@ -562,32 +547,32 @@ void VID_InitMGLFull (HINSTANCE hInstance) } } - if (lowstretched) - { + if (lowstretched) { modelist[MODE_FULLSCREEN_DEFAULT] = modelist[stretchedmode]; modelist[MODE_FULLSCREEN_DEFAULT].stretched = 1; modelist[MODE_FULLSCREEN_DEFAULT].width >>= 1; modelist[MODE_FULLSCREEN_DEFAULT].height >>= 1; - snprintf (modelist[MODE_FULLSCREEN_DEFAULT].modedesc, sizeof(modelist[MODE_FULLSCREEN_DEFAULT].modedesc), "%dx%d", - modelist[MODE_FULLSCREEN_DEFAULT].width, - modelist[MODE_FULLSCREEN_DEFAULT].height); + snprintf (modelist[MODE_FULLSCREEN_DEFAULT].modedesc, + sizeof (modelist[MODE_FULLSCREEN_DEFAULT].modedesc), + "%dx%d", modelist[MODE_FULLSCREEN_DEFAULT].width, + modelist[MODE_FULLSCREEN_DEFAULT].height); } vid_default = MODE_FULLSCREEN_DEFAULT; temp = m[0]; - if (!MGL_init(&driver, &temp, "")) - { - initFatalError(); + if (!MGL_init (&driver, &temp, "")) { + initFatalError (); } } - MGL_setSuspendAppCallback(VID_Suspend); + MGL_setSuspendAppCallback (VID_Suspend); } -MGLDC *createDisplayDC(int forcemem) +MGLDC * +createDisplayDC (int forcemem) /**************************************************************************** * * Function: createDisplayDC @@ -601,56 +586,49 @@ MGLDC *createDisplayDC(int forcemem) * ****************************************************************************/ { - MGLDC *dc; - pixel_format_t pf; - int npages; + MGLDC *dc; + pixel_format_t pf; + int npages; // Start the specified video mode - if (!MGL_changeDisplayMode(mode)) - initFatalError(); + if (!MGL_changeDisplayMode (mode)) + initFatalError (); - npages = MGL_availablePages(mode); + npages = MGL_availablePages (mode); if (npages > 3) npages = 3; - if (!COM_CheckParm ("-notriplebuf")) - { - if (npages > 2) - { + if (!COM_CheckParm ("-notriplebuf")) { + if (npages > 2) { npages = 2; } } - if ((dc = MGL_createDisplayDC(npages)) == NULL) + if ((dc = MGL_createDisplayDC (npages)) == NULL) return NULL; - if (!forcemem && (MGL_surfaceAccessType(dc)) == MGL_LINEAR_ACCESS && (dc->mi.maxPage > 0)) - { - MGL_makeCurrentDC(dc); + if (!forcemem && (MGL_surfaceAccessType (dc)) == MGL_LINEAR_ACCESS + && (dc->mi.maxPage > 0)) { + MGL_makeCurrentDC (dc); memdc = NULL; - } - else - { + } else { // Set up for blitting from a memory buffer - memdc = MGL_createMemoryDC(MGL_sizex(dc)+1,MGL_sizey(dc)+1,8,&pf); - MGL_makeCurrentDC(memdc); + memdc = + MGL_createMemoryDC (MGL_sizex (dc) + 1, MGL_sizey (dc) + 1, 8, &pf); + MGL_makeCurrentDC (memdc); } // Enable page flipping even for even for blitted surfaces - if (forcemem) - { + if (forcemem) { vid.numpages = 1; - } - else - { + } else { vid.numpages = dc->mi.maxPage + 1; - if (vid.numpages > 1) - { + if (vid.numpages > 1) { // Set up for page flipping - MGL_setActivePage(dc, aPage = 1); - MGL_setVisualPage(dc, vPage = 0, false); + MGL_setActivePage (dc, aPage = 1); + MGL_setVisualPage (dc, vPage = 0, false); } if (vid.numpages > 3) @@ -666,33 +644,34 @@ MGLDC *createDisplayDC(int forcemem) } -void VID_InitMGLDIB (HINSTANCE hInstance) +void +VID_InitMGLDIB (HINSTANCE hInstance) { - WNDCLASS wc; - HDC hdc; + WNDCLASS wc; + HDC hdc; - hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON1)); + hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON1)); /* Register the frame class */ - wc.style = 0; - wc.lpfnWndProc = (WNDPROC)MainWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = hInstance; - wc.hIcon = 0; - wc.hCursor = LoadCursor (NULL,IDC_ARROW); + wc.style = 0; + wc.lpfnWndProc = (WNDPROC) MainWndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = 0; + wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hbrBackground = NULL; - wc.lpszMenuName = 0; - wc.lpszClassName = "WinQuake"; + wc.lpszMenuName = 0; + wc.lpszClassName = "WinQuake"; - if (!RegisterClass (&wc) ) + if (!RegisterClass (&wc)) Sys_Error ("Couldn't register window class"); /* Find the size for the DIB window */ /* Initialise the MGL for windowed operation */ - MGL_setAppInstance(hInstance); - registerAllMemDrivers(); - MGL_initWindowed(""); + MGL_setAppInstance (hInstance); + registerAllMemDrivers (); + MGL_initWindowed (""); modelist[0].type = MS_WINDOWED; modelist[0].width = 320; @@ -731,22 +710,20 @@ void VID_InitMGLDIB (HINSTANCE hInstance) modelist[2].bpp = 8; // automatically stretch the default mode up if > 640x480 desktop resolution - hdc = GetDC(NULL); + hdc = GetDC (NULL); - if ((GetDeviceCaps(hdc, HORZRES) > 640) && !COM_CheckParm("-noautostretch")) - { + if ((GetDeviceCaps (hdc, HORZRES) > 640) + && !COM_CheckParm ("-noautostretch")) { vid_default = MODE_WINDOWED + 1; - } - else - { + } else { vid_default = MODE_WINDOWED; } windowed_default = vid_default; - ReleaseDC(NULL,hdc); + ReleaseDC (NULL, hdc); - nummodes = 3; // reserve space for windowed mode + nummodes = 3; // reserve space for windowed mode DDActive = 0; } @@ -757,35 +734,30 @@ void VID_InitMGLDIB (HINSTANCE hInstance) VID_InitFullDIB ================= */ -void VID_InitFullDIB (HINSTANCE hInstance) +void +VID_InitFullDIB (HINSTANCE hInstance) { - DEVMODE devmode; - int i, j, modenum, existingmode, originalnummodes, lowestres; - int numlowresmodes, bpp, done; - int cstretch, istretch, mstretch = 0; - BOOL stat; + DEVMODE devmode; + int i, j, modenum, existingmode, originalnummodes, lowestres; + int numlowresmodes, bpp, done; + int cstretch, istretch, mstretch = 0; + BOOL stat; // enumerate 8 bpp modes originalnummodes = nummodes; modenum = 0; lowestres = 99999; - do - { + do { stat = EnumDisplaySettings (NULL, modenum, &devmode); if ((devmode.dmBitsPerPel == 8) && (devmode.dmPelsWidth <= MAXWIDTH) && - (devmode.dmPelsHeight <= MAXHEIGHT) && - (nummodes < MAX_MODE_LIST)) - { - devmode.dmFields = DM_BITSPERPEL | - DM_PELSWIDTH | - DM_PELSHEIGHT; + (devmode.dmPelsHeight <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST)) { + devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == - DISP_CHANGE_SUCCESSFUL) - { + DISP_CHANGE_SUCCESSFUL) { modelist[nummodes].type = MS_FULLDIB; modelist[nummodes].width = devmode.dmPelsWidth; modelist[nummodes].height = devmode.dmPelsHeight; @@ -796,35 +768,34 @@ void VID_InitFullDIB (HINSTANCE hInstance) modelist[nummodes].dib = 1; modelist[nummodes].fullscreen = 1; modelist[nummodes].bpp = devmode.dmBitsPerPel; - snprintf (modelist[nummodes].modedesc, sizeof(modelist[nummodes].modedesc),"%ldx%ld", - devmode.dmPelsWidth, devmode.dmPelsHeight); + snprintf (modelist[nummodes].modedesc, + sizeof (modelist[nummodes].modedesc), "%ldx%ld", + devmode.dmPelsWidth, devmode.dmPelsHeight); - // if the width is more than twice the height, reduce it by half because this - // is probably a dual-screen monitor - if (!COM_CheckParm("-noadjustaspect")) - { - if (modelist[nummodes].width > (modelist[nummodes].height << 1)) - { + // if the width is more than twice the height, reduce it by + // half because this + // is probably a dual-screen monitor + if (!COM_CheckParm ("-noadjustaspect")) { + if (modelist[nummodes].width > + (modelist[nummodes].height << 1)) { modelist[nummodes].width >>= 1; modelist[nummodes].halfscreen = 1; - snprintf (modelist[nummodes].modedesc, sizeof(modelist[nummodes].modedesc), "%dx%d", - modelist[nummodes].width, - modelist[nummodes].height); + snprintf (modelist[nummodes].modedesc, + sizeof (modelist[nummodes].modedesc), "%dx%d", + modelist[nummodes].width, + modelist[nummodes].height); } } - for (i=originalnummodes, existingmode = 0 ; i 8 bpp - if (nummodes == originalnummodes) - { + if (nummodes == originalnummodes) { modenum = 0; lowestres = 99999; Con_Printf ("No 8-bpp fullscreen DIB modes found\n"); - do - { + do { stat = EnumDisplaySettings (NULL, modenum, &devmode); if ((((devmode.dmPelsWidth <= MAXWIDTH) && (devmode.dmPelsHeight <= MAXHEIGHT)) || - (!COM_CheckParm("-noadjustaspect") && - (devmode.dmPelsWidth <= (MAXWIDTH*2)) && - (devmode.dmPelsWidth > (devmode.dmPelsHeight*2)))) && - (nummodes < MAX_MODE_LIST) && - (devmode.dmBitsPerPel > 8)) - { - devmode.dmFields = DM_BITSPERPEL | - DM_PELSWIDTH | - DM_PELSHEIGHT; + (!COM_CheckParm ("-noadjustaspect") && + (devmode.dmPelsWidth <= (MAXWIDTH * 2)) && + (devmode.dmPelsWidth > (devmode.dmPelsHeight * 2)))) && + (nummodes < MAX_MODE_LIST) && (devmode.dmBitsPerPel > 8)) { + devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; - if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == - DISP_CHANGE_SUCCESSFUL) - { + if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) + == DISP_CHANGE_SUCCESSFUL) { modelist[nummodes].type = MS_FULLDIB; modelist[nummodes].width = devmode.dmPelsWidth; modelist[nummodes].height = devmode.dmPelsHeight; @@ -875,29 +839,31 @@ void VID_InitFullDIB (HINSTANCE hInstance) modelist[nummodes].dib = 1; modelist[nummodes].fullscreen = 1; modelist[nummodes].bpp = devmode.dmBitsPerPel; - snprintf (modelist[nummodes].modedesc, sizeof(modelist[nummodes].modedesc),"%ldx%ld", - devmode.dmPelsWidth, devmode.dmPelsHeight); + snprintf (modelist[nummodes].modedesc, + sizeof (modelist[nummodes].modedesc), "%ldx%ld", + devmode.dmPelsWidth, devmode.dmPelsHeight); - // if the width is more than twice the height, reduce it by half because this - // is probably a dual-screen monitor - if (!COM_CheckParm("-noadjustaspect")) - { - if (modelist[nummodes].width > (modelist[nummodes].height*2)) - { + // if the width is more than twice the height, reduce it + // by half because this + // is probably a dual-screen monitor + if (!COM_CheckParm ("-noadjustaspect")) { + if (modelist[nummodes].width > + (modelist[nummodes].height * 2)) { modelist[nummodes].width >>= 1; modelist[nummodes].halfscreen = 1; - snprintf (modelist[nummodes].modedesc, sizeof(modelist[nummodes].modedesc), "%dx%d", - modelist[nummodes].width, - modelist[nummodes].height); + snprintf (modelist[nummodes].modedesc, + sizeof (modelist[nummodes].modedesc), + "%dx%d", modelist[nummodes].width, + modelist[nummodes].height); } } - for (i=originalnummodes, existingmode = 0 ; i= modelist[i].bpp)) - { + (modelist[nummodes].bpp >= modelist[i].bpp)) { existingmode = 1; break; } } - if (!existingmode) - { + if (!existingmode) { if (modelist[nummodes].width < lowestres) lowestres = modelist[nummodes].width; @@ -984,8 +942,7 @@ void VID_InitFullDIB (HINSTANCE hInstance) } } - switch (bpp) - { + switch (bpp) { case 8: bpp = 16; break; @@ -1003,13 +960,10 @@ void VID_InitFullDIB (HINSTANCE hInstance) // now add the lowest stretch-by-2 pseudo-modes between 320-wide // (inclusive) and lowest real res (not inclusive) // don't bother if we have a real VGA mode 0x13 mode - if (!is_mode0x13) - { - for (i=originalnummodes, cstretch=0 ; i> 1) < lowestres) && - ((modelist[i].width >> 1) >= 320)) - { + ((modelist[i].width >> 1) >= 320)) { lowestres = modelist[i].width >> 1; cstretch = 1; mstretch = i; @@ -1019,10 +973,9 @@ void VID_InitFullDIB (HINSTANCE hInstance) if ((nummodes + cstretch) > MAX_MODE_LIST) cstretch = MAX_MODE_LIST - nummodes; - if (cstretch > 0) - { - for (i=(nummodes-1) ; i>=originalnummodes ; i--) - modelist[i+cstretch] = modelist[i]; + if (cstretch > 0) { + for (i = (nummodes - 1); i >= originalnummodes; i--) + modelist[i + cstretch] = modelist[i]; nummodes += cstretch; istretch = originalnummodes; @@ -1031,8 +984,9 @@ void VID_InitFullDIB (HINSTANCE hInstance) modelist[istretch].width >>= 1; modelist[istretch].height >>= 1; modelist[istretch].stretched = 1; - snprintf (modelist[istretch].modedesc, sizeof(modelist[istretch].modedesc),"%dx%d", - modelist[istretch].width, modelist[istretch].height); + snprintf (modelist[istretch].modedesc, + sizeof (modelist[istretch].modedesc), "%dx%d", + modelist[istretch].width, modelist[istretch].height); } } @@ -1048,18 +1002,20 @@ void VID_InitFullDIB (HINSTANCE hInstance) VID_NumModes ================= */ -int VID_NumModes (void) +int +VID_NumModes (void) { return nummodes; } - + /* ================= VID_GetModePtr ================= */ -vmode_t *VID_GetModePtr (int modenum) +vmode_t * +VID_GetModePtr (int modenum) { if ((modenum >= 0) && (modenum < nummodes)) @@ -1074,20 +1030,24 @@ vmode_t *VID_GetModePtr (int modenum) VID_CheckModedescFixup ================= */ -void VID_CheckModedescFixup (int mode) +void +VID_CheckModedescFixup (int mode) { - int x, y, stretch; + int x, y, stretch; if (mode == MODE_SETTABLE_WINDOW) { modelist[mode].stretched = vid_stretch_by_2->int_val; stretch = modelist[mode].stretched; - Cvar_SetValue (vid_config_x, max (vid_config_x->int_val, 320 << stretch)); - Cvar_SetValue (vid_config_y, max (vid_config_y->int_val, 200 << stretch)); + Cvar_SetValue (vid_config_x, + max (vid_config_x->int_val, 320 << stretch)); + Cvar_SetValue (vid_config_y, + max (vid_config_y->int_val, 200 << stretch)); x = vid_config_x->int_val; y = vid_config_y->int_val; - snprintf (modelist[mode].modedesc, sizeof(modelist[mode].modedesc), "%dx%d", x, y); + snprintf (modelist[mode].modedesc, sizeof (modelist[mode].modedesc), + "%dx%d", x, y); modelist[mode].width = x; modelist[mode].height = y; } @@ -1099,10 +1059,11 @@ void VID_CheckModedescFixup (int mode) VID_GetModeDescriptionMemCheck ================= */ -char *VID_GetModeDescriptionMemCheck (int mode) +char * +VID_GetModeDescriptionMemCheck (int mode) { - char *pinfo; - vmode_t *pv; + char *pinfo; + vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; @@ -1125,10 +1086,11 @@ char *VID_GetModeDescriptionMemCheck (int mode) VID_GetModeDescription ================= */ -char *VID_GetModeDescription (int mode) +char * +VID_GetModeDescription (int mode) { - char *pinfo; - vmode_t *pv; + char *pinfo; + vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; @@ -1148,10 +1110,11 @@ VID_GetModeDescription2 Tacks on "windowed" or "fullscreen" ================= */ -char *VID_GetModeDescription2 (int mode) +char * +VID_GetModeDescription2 (int mode) { - static char pinfo[40]; - vmode_t *pv; + static char pinfo[40]; + vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; @@ -1160,17 +1123,12 @@ char *VID_GetModeDescription2 (int mode) pv = VID_GetModePtr (mode); - if (modelist[mode].type == MS_FULLSCREEN) - { - snprintf(pinfo,sizeof(pinfo),"%s fullscreen", pv->modedesc); - } - else if (modelist[mode].type == MS_FULLDIB) - { - snprintf(pinfo,sizeof(pinfo),"%s fullscreen", pv->modedesc); - } - else - { - snprintf(pinfo,sizeof(pinfo), "%s windowed", pv->modedesc); + if (modelist[mode].type == MS_FULLSCREEN) { + snprintf (pinfo, sizeof (pinfo), "%s fullscreen", pv->modedesc); + } else if (modelist[mode].type == MS_FULLDIB) { + snprintf (pinfo, sizeof (pinfo), "%s fullscreen", pv->modedesc); + } else { + snprintf (pinfo, sizeof (pinfo), "%s windowed", pv->modedesc); } return pinfo; @@ -1179,10 +1137,11 @@ char *VID_GetModeDescription2 (int mode) // KJB: Added this to return the mode driver name in description for console -char *VID_GetExtModeDescription (int mode) +char * +VID_GetExtModeDescription (int mode) { - static char pinfo[40]; - vmode_t *pv; + static char pinfo[40]; + vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; @@ -1190,45 +1149,40 @@ char *VID_GetExtModeDescription (int mode) VID_CheckModedescFixup (mode); pv = VID_GetModePtr (mode); - if (modelist[mode].type == MS_FULLSCREEN) - { - snprintf(pinfo, sizeof(pinfo), "%s fullscreen %s",pv->modedesc, - MGL_modeDriverName(pv->modenum)); - } - else if (modelist[mode].type == MS_FULLDIB) - { - snprintf(pinfo, sizeof(pinfo), "%s fullscreen DIB", pv->modedesc); - } - else - { - snprintf(pinfo, sizeof(pinfo), "%s windowed", pv->modedesc); + if (modelist[mode].type == MS_FULLSCREEN) { + snprintf (pinfo, sizeof (pinfo), "%s fullscreen %s", pv->modedesc, + MGL_modeDriverName (pv->modenum)); + } else if (modelist[mode].type == MS_FULLDIB) { + snprintf (pinfo, sizeof (pinfo), "%s fullscreen DIB", pv->modedesc); + } else { + snprintf (pinfo, sizeof (pinfo), "%s windowed", pv->modedesc); } return pinfo; } -void DestroyDIBWindow (void) +void +DestroyDIBWindow (void) { - if (modestate == MS_WINDOWED) - { - // destroy the associated MGL DC's; the window gets reused + if (modestate == MS_WINDOWED) { + // destroy the associated MGL DC's; the window gets reused if (windc) - MGL_destroyDC(windc); + MGL_destroyDC (windc); if (dibdc) - MGL_destroyDC(dibdc); + MGL_destroyDC (dibdc); windc = dibdc = NULL; } } -void DestroyFullscreenWindow (void) +void +DestroyFullscreenWindow (void) { - if (modestate == MS_FULLSCREEN) - { - // destroy the existing fullscreen mode and DC's + if (modestate == MS_FULLSCREEN) { + // destroy the existing fullscreen mode and DC's if (mgldc) MGL_destroyDC (mgldc); if (memdc) @@ -1239,33 +1193,32 @@ void DestroyFullscreenWindow (void) -void DestroyFullDIBWindow (void) +void +DestroyFullDIBWindow (void) { - if (modestate == MS_FULLDIB) - { + if (modestate == MS_FULLDIB) { ChangeDisplaySettings (NULL, CDS_FULLSCREEN); - // Destroy the fullscreen DIB window and associated MGL DC's + // Destroy the fullscreen DIB window and associated MGL DC's if (windc) - MGL_destroyDC(windc); + MGL_destroyDC (windc); if (dibdc) - MGL_destroyDC(dibdc); + MGL_destroyDC (dibdc); windc = dibdc = NULL; } } -qboolean VID_SetWindowedMode (int modenum) +qboolean +VID_SetWindowedMode (int modenum) { - HDC hdc; - pixel_format_t pf; - qboolean stretched; - int lastmodestate; + HDC hdc; + pixel_format_t pf; + qboolean stretched; + int lastmodestate; - if (!windowed_mode_set) - { - if (COM_CheckParm ("-resetwinpos")) - { + if (!windowed_mode_set) { + if (COM_CheckParm ("-resetwinpos")) { Cvar_SetValue (vid_window_x, 0.0); Cvar_SetValue (vid_window_y, 0.0); } @@ -1282,14 +1235,14 @@ qboolean VID_SetWindowedMode (int modenum) DestroyFullDIBWindow (); if (windc) - MGL_destroyDC(windc); + MGL_destroyDC (windc); if (dibdc) - MGL_destroyDC(dibdc); + MGL_destroyDC (dibdc); windc = dibdc = NULL; // KJB: Signal to the MGL that we are going back to windowed mode - if (!MGL_changeDisplayMode(grWINDOWED)) - initFatalError(); + if (!MGL_changeDisplayMode (grWINDOWED)) + initFatalError (); WindowRect.top = WindowRect.left = 0; @@ -1300,59 +1253,48 @@ qboolean VID_SetWindowedMode (int modenum) DIBWidth = modelist[modenum].width; DIBHeight = modelist[modenum].height; - if (stretched) - { + if (stretched) { DIBWidth >>= 1; DIBHeight >>= 1; } WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | - WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPSIBLINGS | - WS_CLIPCHILDREN; + WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; ExWindowStyle = 0; - AdjustWindowRectEx(&WindowRect, WindowStyle, FALSE, 0); + AdjustWindowRectEx (&WindowRect, WindowStyle, FALSE, 0); // the first time we're called to set the mode, create the window we'll use // for the rest of the session - if (!vid_mode_set) - { - mainwindow = CreateWindowEx ( - ExWindowStyle, - "WinQuake", - PROGRAM, - WindowStyle, - 0, 0, - WindowRect.right - WindowRect.left, - WindowRect.bottom - WindowRect.top, - NULL, - NULL, - global_hInstance, - NULL); + if (!vid_mode_set) { + mainwindow = CreateWindowEx (ExWindowStyle, + "WinQuake", + PROGRAM, + WindowStyle, + 0, 0, + WindowRect.right - WindowRect.left, + WindowRect.bottom - WindowRect.top, + NULL, NULL, global_hInstance, NULL); if (!mainwindow) Sys_Error ("Couldn't create DIB window"); - // tell MGL to use this window for fullscreen modes + // tell MGL to use this window for fullscreen modes MGL_registerFullScreenWindow (mainwindow); vid_mode_set = true; - } - else - { - SetWindowLong(mainwindow, GWL_STYLE, WindowStyle | WS_VISIBLE); - SetWindowLong(mainwindow, GWL_EXSTYLE, ExWindowStyle); + } else { + SetWindowLong (mainwindow, GWL_STYLE, WindowStyle | WS_VISIBLE); + SetWindowLong (mainwindow, GWL_EXSTYLE, ExWindowStyle); } if (!SetWindowPos (mainwindow, - NULL, - 0, 0, - WindowRect.right - WindowRect.left, - WindowRect.bottom - WindowRect.top, - SWP_NOCOPYBITS | SWP_NOZORDER | - SWP_HIDEWINDOW)) - { - Sys_Error ("Couldn't resize DIB window"); - } + NULL, + 0, 0, + WindowRect.right - WindowRect.left, + WindowRect.bottom - WindowRect.top, + SWP_NOCOPYBITS | SWP_NOZORDER | SWP_HIDEWINDOW)) { + Sys_Error ("Couldn't resize DIB window"); + } if (hide_window) return true; @@ -1377,18 +1319,18 @@ qboolean VID_SetWindowedMode (int modenum) // (to avoid flickering when re-sizing the window on the desktop), // we clear the window to black when created, otherwise it will be // empty while Quake starts up. - hdc = GetDC(mainwindow); - PatBlt(hdc,0,0,WindowRect.right,WindowRect.bottom,BLACKNESS); - ReleaseDC(mainwindow, hdc); + hdc = GetDC (mainwindow); + PatBlt (hdc, 0, 0, WindowRect.right, WindowRect.bottom, BLACKNESS); + ReleaseDC (mainwindow, hdc); /* Create the MGL window DC and the MGL memory DC */ - if ((windc = MGL_createWindowedDC(mainwindow)) == NULL) - MGL_fatalError("Unable to create Windowed DC!"); + if ((windc = MGL_createWindowedDC (mainwindow)) == NULL) + MGL_fatalError ("Unable to create Windowed DC!"); - if ((dibdc = MGL_createMemoryDC(DIBWidth,DIBHeight,8,&pf)) == NULL) - MGL_fatalError("Unable to create Memory DC!"); + if ((dibdc = MGL_createMemoryDC (DIBWidth, DIBHeight, 8, &pf)) == NULL) + MGL_fatalError ("Unable to create Memory DC!"); - MGL_makeCurrentDC(dibdc); + MGL_makeCurrentDC (dibdc); vid.buffer = vid.conbuffer = vid.direct = dibdc->surface; vid.rowbytes = vid.conrowbytes = dibdc->mi.bytesPerLine; @@ -1397,19 +1339,19 @@ qboolean VID_SetWindowedMode (int modenum) vid.maxwarpheight = WARP_HEIGHT; vid.height = vid.conheight = DIBHeight; vid.width = vid.conwidth = DIBWidth; - vid.aspect = ((float)vid.height / (float)vid.width) * - (320.0 / 240.0); + vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); vid_stretched = stretched; - SendMessage (mainwindow, WM_SETICON, (WPARAM)TRUE, (LPARAM)hIcon); - SendMessage (mainwindow, WM_SETICON, (WPARAM)FALSE, (LPARAM)hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) TRUE, (LPARAM) hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) FALSE, (LPARAM) hIcon); return true; } -qboolean VID_SetFullscreenMode (int modenum) +qboolean +VID_SetFullscreenMode (int modenum) { DDActive = 1; @@ -1427,8 +1369,7 @@ qboolean VID_SetFullscreenMode (int modenum) mgldc = memdc = NULL; if ((mgldc = createDisplayDC (modelist[modenum].stretched || - vid_nopageflip->int_val)) == NULL) - { + vid_nopageflip->int_val)) == NULL) { return false; } @@ -1440,8 +1381,7 @@ qboolean VID_SetFullscreenMode (int modenum) vid.maxwarpheight = WARP_HEIGHT; DIBHeight = vid.height = vid.conheight = modelist[modenum].height; DIBWidth = vid.width = vid.conwidth = modelist[modenum].width; - vid.aspect = ((float)vid.height / (float)vid.width) * - (320.0 / 240.0); + vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); vid_stretched = modelist[modenum].stretched; @@ -1450,8 +1390,8 @@ qboolean VID_SetFullscreenMode (int modenum) window_y = 0; // set the large icon, so the Quake icon will show up in the taskbar - SendMessage (mainwindow, WM_SETICON, (WPARAM)1, (LPARAM)hIcon); - SendMessage (mainwindow, WM_SETICON, (WPARAM)0, (LPARAM)hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) 1, (LPARAM) hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) 0, (LPARAM) hIcon); // shouldn't be needed, but Kendall needs to let us get the activation // message for this not to be needed on NT @@ -1461,11 +1401,12 @@ qboolean VID_SetFullscreenMode (int modenum) } -qboolean VID_SetFullDIBMode (int modenum) +qboolean +VID_SetFullDIBMode (int modenum) { - HDC hdc; - pixel_format_t pf; - int lastmodestate; + HDC hdc; + pixel_format_t pf; + int lastmodestate; DDActive = 0; @@ -1473,24 +1414,26 @@ qboolean VID_SetFullDIBMode (int modenum) DestroyDIBWindow (); if (windc) - MGL_destroyDC(windc); + MGL_destroyDC (windc); if (dibdc) - MGL_destroyDC(dibdc); + MGL_destroyDC (dibdc); windc = dibdc = NULL; // KJB: Signal to the MGL that we are going back to windowed mode - if (!MGL_changeDisplayMode(grWINDOWED)) - initFatalError(); + if (!MGL_changeDisplayMode (grWINDOWED)) + initFatalError (); gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; gdevmode.dmBitsPerPel = modelist[modenum].bpp; - gdevmode.dmPelsWidth = modelist[modenum].width << modelist[modenum].stretched << - modelist[modenum].halfscreen; - gdevmode.dmPelsHeight = modelist[modenum].height << modelist[modenum].stretched; + gdevmode.dmPelsWidth = + modelist[modenum].width << modelist[modenum]. + stretched << modelist[modenum].halfscreen; + gdevmode.dmPelsHeight = + modelist[modenum].height << modelist[modenum].stretched; gdevmode.dmSize = sizeof (gdevmode); - if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) - Sys_Error ("Couldn't set fullscreen DIB mode"); + if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != + DISP_CHANGE_SUCCESSFUL) Sys_Error ("Couldn't set fullscreen DIB mode"); lastmodestate = modestate; modestate = MS_FULLDIB; @@ -1498,33 +1441,31 @@ qboolean VID_SetFullDIBMode (int modenum) WindowRect.top = WindowRect.left = 0; - hdc = GetDC(NULL); + hdc = GetDC (NULL); WindowRect.right = modelist[modenum].width << modelist[modenum].stretched; WindowRect.bottom = modelist[modenum].height << modelist[modenum].stretched; - ReleaseDC(NULL,hdc); + ReleaseDC (NULL, hdc); DIBWidth = modelist[modenum].width; DIBHeight = modelist[modenum].height; WindowStyle = WS_POPUP | WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; ExWindowStyle = 0; - AdjustWindowRectEx(&WindowRect, WindowStyle, FALSE, 0); + AdjustWindowRectEx (&WindowRect, WindowStyle, FALSE, 0); - SetWindowLong(mainwindow, GWL_STYLE, WindowStyle | WS_VISIBLE); - SetWindowLong(mainwindow, GWL_EXSTYLE, ExWindowStyle); + SetWindowLong (mainwindow, GWL_STYLE, WindowStyle | WS_VISIBLE); + SetWindowLong (mainwindow, GWL_EXSTYLE, ExWindowStyle); if (!SetWindowPos (mainwindow, - NULL, - 0, 0, - WindowRect.right - WindowRect.left, - WindowRect.bottom - WindowRect.top, - SWP_NOCOPYBITS | SWP_NOZORDER)) - { - Sys_Error ("Couldn't resize DIB window"); - } - + NULL, + 0, 0, + WindowRect.right - WindowRect.left, + WindowRect.bottom - WindowRect.top, + SWP_NOCOPYBITS | SWP_NOZORDER)) { + Sys_Error ("Couldn't resize DIB window"); + } // position and show the DIB window SetWindowPos (mainwindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW | SWP_DRAWFRAME); @@ -1535,18 +1476,18 @@ qboolean VID_SetFullDIBMode (int modenum) // (to avoid flickering when re-sizing the window on the desktop), we // clear the window to black when created, otherwise it will be // empty while Quake starts up. - hdc = GetDC(mainwindow); - PatBlt(hdc,0,0,WindowRect.right,WindowRect.bottom,BLACKNESS); - ReleaseDC(mainwindow, hdc); + hdc = GetDC (mainwindow); + PatBlt (hdc, 0, 0, WindowRect.right, WindowRect.bottom, BLACKNESS); + ReleaseDC (mainwindow, hdc); /* Create the MGL window DC and the MGL memory DC */ - if ((windc = MGL_createWindowedDC(mainwindow)) == NULL) - MGL_fatalError("Unable to create Fullscreen DIB DC!"); + if ((windc = MGL_createWindowedDC (mainwindow)) == NULL) + MGL_fatalError ("Unable to create Fullscreen DIB DC!"); - if ((dibdc = MGL_createMemoryDC(DIBWidth,DIBHeight,8,&pf)) == NULL) - MGL_fatalError("Unable to create Memory DC!"); + if ((dibdc = MGL_createMemoryDC (DIBWidth, DIBHeight, 8, &pf)) == NULL) + MGL_fatalError ("Unable to create Memory DC!"); - MGL_makeCurrentDC(dibdc); + MGL_makeCurrentDC (dibdc); vid.buffer = vid.conbuffer = vid.direct = dibdc->surface; vid.rowbytes = vid.conrowbytes = dibdc->mi.bytesPerLine; @@ -1555,8 +1496,7 @@ qboolean VID_SetFullDIBMode (int modenum) vid.maxwarpheight = WARP_HEIGHT; vid.height = vid.conheight = DIBHeight; vid.width = vid.conwidth = DIBWidth; - vid.aspect = ((float)vid.height / (float)vid.width) * - (320.0 / 240.0); + vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); vid_stretched = modelist[modenum].stretched; @@ -1568,9 +1508,10 @@ qboolean VID_SetFullDIBMode (int modenum) } -void VID_RestoreOldMode (int original_mode) +void +VID_RestoreOldMode (int original_mode) { - static qboolean inerror = false; + static qboolean inerror = false; if (inerror) return; @@ -1581,8 +1522,7 @@ void VID_RestoreOldMode (int original_mode) // make sure mode set happens (video mode changes) vid_modenum = original_mode - 1; - if (!VID_SetMode (original_mode, vid_curpal)) - { + if (!VID_SetMode (original_mode, vid_curpal)) { vid_modenum = MODE_WINDOWED - 1; if (!VID_SetMode (windowed_default, vid_curpal)) @@ -1593,7 +1533,8 @@ void VID_RestoreOldMode (int original_mode) } -void VID_SetDefaultMode (void) +void +VID_SetDefaultMode (void) { if (vid_initialized) @@ -1603,30 +1544,24 @@ void VID_SetDefaultMode (void) } -int VID_SetMode (int modenum, unsigned char *palette) +int +VID_SetMode (int modenum, unsigned char *palette) { - int original_mode, temp; - qboolean stat; - MSG msg; - HDC hdc; + int original_mode, temp; + qboolean stat; + MSG msg; + HDC hdc; - while ((modenum >= nummodes) || (modenum < 0)) - { - if (vid_modenum == NO_MODE) - { - if (modenum == vid_default) - { + while ((modenum >= nummodes) || (modenum < 0)) { + if (vid_modenum == NO_MODE) { + if (modenum == vid_default) { modenum = windowed_default; - } - else - { + } else { modenum = vid_default; } Cvar_SetValue (vid_mode, modenum); - } - else - { + } else { Cvar_SetValue (vid_mode, vid_modenum); return 0; } @@ -1649,30 +1584,22 @@ int VID_SetMode (int modenum, unsigned char *palette) original_mode = vid_modenum; // Set either the fullscreen or windowed mode - if (modelist[modenum].type == MS_WINDOWED) - { - if (_windowed_mouse->int_val && key_dest == key_game) - { - stat = VID_SetWindowedMode(modenum); + if (modelist[modenum].type == MS_WINDOWED) { + if (_windowed_mouse->int_val && key_dest == key_game) { + stat = VID_SetWindowedMode (modenum); IN_ActivateMouse (); IN_HideMouse (); - } - else - { + } else { IN_DeactivateMouse (); IN_ShowMouse (); - stat = VID_SetWindowedMode(modenum); + stat = VID_SetWindowedMode (modenum); } - } - else if (modelist[modenum].type == MS_FULLDIB) - { - stat = VID_SetFullDIBMode(modenum); + } else if (modelist[modenum].type == MS_FULLDIB) { + stat = VID_SetFullDIBMode (modenum); IN_ActivateMouse (); IN_HideMouse (); - } - else - { - stat = VID_SetFullscreenMode(modenum); + } else { + stat = VID_SetFullscreenMode (modenum); IN_ActivateMouse (); IN_HideMouse (); } @@ -1684,8 +1611,7 @@ int VID_SetMode (int modenum, unsigned char *palette) CDAudio_Resume (); scr_disabled_for_loading = temp; - if (!stat) - { + if (!stat) { VID_RestoreOldMode (original_mode); return false; } @@ -1702,51 +1628,49 @@ int VID_SetMode (int modenum, unsigned char *palette) if (!force_minimized) SetForegroundWindow (mainwindow); - hdc = GetDC(NULL); + hdc = GetDC (NULL); - if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) + if (GetDeviceCaps (hdc, RASTERCAPS) & RC_PALETTE) vid_palettized = true; else vid_palettized = false; VID_SetPalette (palette); - ReleaseDC(NULL,hdc); + ReleaseDC (NULL, hdc); vid_modenum = modenum; Cvar_SetValue (vid_mode, vid_modenum); - if (!VID_AllocBuffers (vid.width, vid.height)) - { - // couldn't get memory for this mode; try to fall back to previous mode + if (!VID_AllocBuffers (vid.width, vid.height)) { + // couldn't get memory for this mode; try to fall back to previous + // mode VID_RestoreOldMode (original_mode); return false; } - D_InitCaches (vid_surfcache, vid_surfcachesize); + D_InitCaches (vid_surfcache, vid_surfcachesize); - while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) - { - TranslateMessage (&msg); - DispatchMessage (&msg); + while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage (&msg); + DispatchMessage (&msg); } Sleep (100); - if (!force_minimized) - { + if (!force_minimized) { SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, - SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | - SWP_NOCOPYBITS); + SWP_DRAWFRAME | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | + SWP_NOCOPYBITS); SetForegroundWindow (mainwindow); } - // fix the leftover Alt from any Alt-Tab or the like that switched us away ClearAllStates (); if (!msg_suppress_1) - Con_Printf ("Video mode %s initialized\n", VID_GetModeDescription (vid_modenum)); + Con_Printf ("Video mode %s initialized\n", + VID_GetModeDescription (vid_modenum)); VID_SetPalette (palette); @@ -1756,7 +1680,8 @@ int VID_SetMode (int modenum, unsigned char *palette) return true; } -void VID_LockBuffer (void) +void +VID_LockBuffer (void) { if (dibdc) @@ -1767,16 +1692,13 @@ void VID_LockBuffer (void) if (lockcount > 1) return; - MGL_beginDirectAccess(); + MGL_beginDirectAccess (); - if (memdc) - { + if (memdc) { // Update surface pointer for linear access modes vid.buffer = vid.conbuffer = vid.direct = memdc->surface; vid.rowbytes = vid.conrowbytes = memdc->mi.bytesPerLine; - } - else if (mgldc) - { + } else if (mgldc) { // Update surface pointer for linear access modes vid.buffer = vid.conbuffer = vid.direct = mgldc->surface; vid.rowbytes = vid.conrowbytes = mgldc->mi.bytesPerLine; @@ -1785,16 +1707,17 @@ void VID_LockBuffer (void) if (r_dowarp) d_viewbuffer = r_warpbuffer; else - d_viewbuffer = (void *)(byte *)vid.buffer; + d_viewbuffer = (void *) (byte *) vid.buffer; if (r_dowarp) screenwidth = WARP_WIDTH; else screenwidth = vid.rowbytes; } - - -void VID_UnlockBuffer (void) + + +void +VID_UnlockBuffer (void) { if (dibdc) return; @@ -1807,7 +1730,7 @@ void VID_UnlockBuffer (void) if (lockcount < 0) Sys_Error ("Unbalanced unlock"); - MGL_endDirectAccess(); + MGL_endDirectAccess (); // to turn up any unlocked accesses vid.buffer = vid.conbuffer = vid.direct = d_viewbuffer = NULL; @@ -1815,21 +1738,19 @@ void VID_UnlockBuffer (void) } -int VID_ForceUnlockedAndReturnState (void) +int +VID_ForceUnlockedAndReturnState (void) { - int lk; + int lk; if (!lockcount) return 0; lk = lockcount; - if (dibdc) - { + if (dibdc) { lockcount = 0; - } - else - { + } else { lockcount = 1; VID_UnlockBuffer (); } @@ -1838,11 +1759,11 @@ int VID_ForceUnlockedAndReturnState (void) } -void VID_ForceLockState (int lk) +void +VID_ForceLockState (int lk) { - if (!dibdc && lk) - { + if (!dibdc && lk) { lockcount = 0; VID_LockBuffer (); } @@ -1851,77 +1772,70 @@ void VID_ForceLockState (int lk) } -void VID_SetPalette (unsigned char *palette) +void +VID_SetPalette (unsigned char *palette) { - INT i; - palette_t pal[256]; - HDC hdc; + INT i; + palette_t pal[256]; + HDC hdc; - if (!Minimized) - { + if (!Minimized) { palette_changed = true; - // make sure we have the static colors if we're the active app - hdc = GetDC(NULL); + // make sure we have the static colors if we're the active app + hdc = GetDC (NULL); - if (vid_palettized && ActiveApp) - { - if (GetSystemPaletteUse(hdc) == SYSPAL_STATIC) - { - // switch to SYSPAL_NOSTATIC and remap the colors - SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC); + if (vid_palettized && ActiveApp) { + if (GetSystemPaletteUse (hdc) == SYSPAL_STATIC) { + // switch to SYSPAL_NOSTATIC and remap the colors + SetSystemPaletteUse (hdc, SYSPAL_NOSTATIC); syscolchg = true; pal_is_nostatic = true; } } - ReleaseDC(NULL,hdc); + ReleaseDC (NULL, hdc); // Translate the palette values to an MGL palette array and // set the values. - for (i = 0; i < 256; i++) - { - pal[i].red = palette[i*3]; - pal[i].green = palette[i*3+1]; - pal[i].blue = palette[i*3+2]; + for (i = 0; i < 256; i++) { + pal[i].red = palette[i * 3]; + pal[i].green = palette[i * 3 + 1]; + pal[i].blue = palette[i * 3 + 2]; } - if (DDActive) - { + if (DDActive) { if (!mgldc) return; - MGL_setPalette(mgldc,pal,256,0); - MGL_realizePalette(mgldc,256,0,false); + MGL_setPalette (mgldc, pal, 256, 0); + MGL_realizePalette (mgldc, 256, 0, false); if (memdc) - MGL_setPalette(memdc,pal,256,0); - } - else - { + MGL_setPalette (memdc, pal, 256, 0); + } else { if (!windc) return; - MGL_setPalette(windc,pal,256,0); - MGL_realizePalette(windc,256,0,false); - if (dibdc) - { - MGL_setPalette(dibdc,pal,256,0); - MGL_realizePalette(dibdc,256,0,false); + MGL_setPalette (windc, pal, 256, 0); + MGL_realizePalette (windc, 256, 0, false); + if (dibdc) { + MGL_setPalette (dibdc, pal, 256, 0); + MGL_realizePalette (dibdc, 256, 0, false); } } } - memcpy (vid_curpal, palette, sizeof(vid_curpal)); + memcpy (vid_curpal, palette, sizeof (vid_curpal)); - if (syscolchg) - { - PostMessage (HWND_BROADCAST, WM_SYSCOLORCHANGE, (WPARAM)0, (LPARAM)0); + if (syscolchg) { + PostMessage (HWND_BROADCAST, WM_SYSCOLORCHANGE, (WPARAM) 0, (LPARAM) 0); syscolchg = false; } } -void VID_ShiftPalette (unsigned char *palette) +void +VID_ShiftPalette (unsigned char *palette) { VID_SetPalette (palette); } @@ -1932,7 +1846,8 @@ void VID_ShiftPalette (unsigned char *palette) VID_DescribeCurrentMode_f ================= */ -void VID_DescribeCurrentMode_f (void) +void +VID_DescribeCurrentMode_f (void) { Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum)); } @@ -1943,7 +1858,8 @@ void VID_DescribeCurrentMode_f (void) VID_NumModes_f ================= */ -void VID_NumModes_f (void) +void +VID_NumModes_f (void) { if (nummodes == 1) @@ -1958,11 +1874,12 @@ void VID_NumModes_f (void) VID_DescribeMode_f ================= */ -void VID_DescribeMode_f (void) +void +VID_DescribeMode_f (void) { - int modenum; - - modenum = atoi (Cmd_Argv(1)); + int modenum; + + modenum = atoi (Cmd_Argv (1)); Con_Printf ("%s\n", VID_GetExtModeDescription (modenum)); } @@ -1973,35 +1890,31 @@ void VID_DescribeMode_f (void) VID_DescribeModes_f ================= */ -void VID_DescribeModes_f (void) +void +VID_DescribeModes_f (void) { - int i, lnummodes; - char *pinfo; - qboolean na; - vmode_t *pv; + int i, lnummodes; + char *pinfo; + qboolean na; + vmode_t *pv; na = false; lnummodes = VID_NumModes (); - for (i=0 ; iwidth, pv->height)) - { + if (VID_CheckAdequateMem (pv->width, pv->height)) { Con_Printf ("%2d: %s\n", i, pinfo); - } - else - { + } else { Con_Printf ("**: %s\n", pinfo); na = true; } } - if (na) - { + if (na) { Con_Printf ("\n[**: not enough system RAM for mode]\n"); } } @@ -2012,19 +1925,18 @@ void VID_DescribeModes_f (void) VID_TestMode_f ================= */ -void VID_TestMode_f (void) +void +VID_TestMode_f (void) { - int modenum; - double testduration; + int modenum; + double testduration; - if (!vid_testingmode) - { - modenum = atoi (Cmd_Argv(1)); + if (!vid_testingmode) { + modenum = atoi (Cmd_Argv (1)); - if (VID_SetMode (modenum, vid_curpal)) - { + if (VID_SetMode (modenum, vid_curpal)) { vid_testingmode = 1; - testduration = atof (Cmd_Argv(2)); + testduration = atof (Cmd_Argv (2)); if (testduration == 0) testduration = 5.0; vid_testendtime = realtime + testduration; @@ -2037,7 +1949,8 @@ void VID_TestMode_f (void) VID_Windowed_f ================= */ -void VID_Windowed_f (void) +void +VID_Windowed_f (void) { VID_SetMode (vid_windowed_mode->int_val, vid_curpal); @@ -2049,7 +1962,8 @@ void VID_Windowed_f (void) VID_Fullscreen_f ================= */ -void VID_Fullscreen_f (void) +void +VID_Fullscreen_f (void) { VID_SetMode (vid_fullscreen_mode->int_val, vid_curpal); @@ -2060,7 +1974,8 @@ void VID_Fullscreen_f (void) VID_Minimize_f ================= */ -void VID_Minimize_f (void) +void +VID_Minimize_f (void) { // we only support minimizing windows; if you're fullscreen, @@ -2076,13 +1991,13 @@ void VID_Minimize_f (void) VID_ForceMode_f ================= */ -void VID_ForceMode_f (void) +void +VID_ForceMode_f (void) { - int modenum; + int modenum; - if (!vid_testingmode) - { - modenum = atoi (Cmd_Argv(1)); + if (!vid_testingmode) { + modenum = atoi (Cmd_Argv (1)); force_mode_set = 1; VID_SetMode (modenum, vid_curpal); @@ -2094,9 +2009,9 @@ void VID_ForceMode_f (void) void VID_Init (unsigned char *palette) { - int i, bestmatch = 0, bestmatchmetric, t, dr, dg, db; - int basenummodes; - byte *ptmp; + int i, bestmatch = 0, bestmatchmetric, t, dr, dg, db; + int basenummodes; + byte *ptmp; Cmd_AddCommand ("vid_testmode", VID_TestMode_f); Cmd_AddCommand ("vid_nummodes", VID_NumModes_f); @@ -2123,31 +2038,28 @@ VID_Init (unsigned char *palette) if (((nummodes == basenummodes) || ((nummodes == (basenummodes + 1)) && is_mode0x13)) && !COM_CheckParm ("-nofulldib")) - - { + { VID_InitFullDIB (global_hInstance); } vid.maxwarpwidth = WARP_WIDTH; vid.maxwarpheight = WARP_HEIGHT; vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); + vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); vid_testingmode = 0; // GDI doesn't let us remap palette index 0, so we'll remap color // mappings from that black to another one - bestmatchmetric = 256*256*3; + bestmatchmetric = 256 * 256 * 3; - for (i=1 ; i<256 ; i++) - { - dr = palette[0] - palette[i*3]; - dg = palette[1] - palette[i*3+1]; - db = palette[2] - palette[i*3+2]; + for (i = 1; i < 256; i++) { + dr = palette[0] - palette[i * 3]; + dg = palette[1] - palette[i * 3 + 1]; + db = palette[2] - palette[i * 3 + 2]; t = (dr * dr) + (dg * dg) + (db * db); - if (t < bestmatchmetric) - { + if (t < bestmatchmetric) { bestmatchmetric = t; bestmatch = i; @@ -2156,14 +2068,12 @@ VID_Init (unsigned char *palette) } } - for (i=0, ptmp = vid.colormap ; i<(1<<(VID_CBITS+8)) ; i++, ptmp++) - { + for (i = 0, ptmp = vid.colormap; i < (1 << (VID_CBITS + 8)); i++, ptmp++) { if (*ptmp == 0) *ptmp = bestmatch; } - if (COM_CheckParm("-startwindowed") || COM_CheckParm("-window")) - { + if (COM_CheckParm ("-startwindowed") || COM_CheckParm ("-window")) { startwindowed = 1; vid_default = windowed_default; } @@ -2180,7 +2090,7 @@ VID_Init (unsigned char *palette) hide_window = true; VID_SetMode (MODE_WINDOWED, palette); hide_window = false; -// S_Init (); +// S_Init (); vid_initialized = true; @@ -2198,34 +2108,39 @@ VID_Init (unsigned char *palette) strcpy (badmode.modedesc, "Bad mode"); } -void VID_Init_Cvars () +void +VID_Init_Cvars () { - vid_mode = Cvar_Get("vid_mode", "0", CVAR_NONE, "None"); - vid_nopageflip = Cvar_Get("vid_nopageflip", "0", CVAR_ARCHIVE, "None"); - _vid_default_mode_win = Cvar_Get("_vid_default_mode_win", "3", CVAR_ARCHIVE, "None"); - vid_config_x = Cvar_Get("vid_config_x", "800", CVAR_ARCHIVE, "None"); - vid_config_y = Cvar_Get("vid_config_y", "600", CVAR_ARCHIVE, "None"); - vid_stretch_by_2 = Cvar_Get("vid_stretch_by_2", "1", CVAR_ARCHIVE, "None"); - _windowed_mouse = Cvar_Get("_windowed_mouse", "0", CVAR_ARCHIVE, "None"); - vid_fullscreen_mode = Cvar_Get("vid_fullscreen_mode", "3", CVAR_ARCHIVE, "None"); - vid_windowed_mode = Cvar_Get("vid_windowed_mode", "0", CVAR_ARCHIVE, "None"); - block_switch = Cvar_Get("block_switch", "0", CVAR_ARCHIVE, "None"); - vid_window_x = Cvar_Get("vid_window_x", "0", CVAR_ARCHIVE, "None"); - vid_window_y = Cvar_Get("vid_window_y", "0", CVAR_ARCHIVE, "None"); + vid_mode = Cvar_Get ("vid_mode", "0", CVAR_NONE, "None"); + vid_nopageflip = Cvar_Get ("vid_nopageflip", "0", CVAR_ARCHIVE, "None"); + _vid_default_mode_win = + Cvar_Get ("_vid_default_mode_win", "3", CVAR_ARCHIVE, "None"); + vid_config_x = Cvar_Get ("vid_config_x", "800", CVAR_ARCHIVE, "None"); + vid_config_y = Cvar_Get ("vid_config_y", "600", CVAR_ARCHIVE, "None"); + vid_stretch_by_2 = Cvar_Get ("vid_stretch_by_2", "1", CVAR_ARCHIVE, "None"); + _windowed_mouse = Cvar_Get ("_windowed_mouse", "0", CVAR_ARCHIVE, "None"); + vid_fullscreen_mode = + Cvar_Get ("vid_fullscreen_mode", "3", CVAR_ARCHIVE, "None"); + vid_windowed_mode = + Cvar_Get ("vid_windowed_mode", "0", CVAR_ARCHIVE, "None"); + block_switch = Cvar_Get ("block_switch", "0", CVAR_ARCHIVE, "None"); + vid_window_x = Cvar_Get ("vid_window_x", "0", CVAR_ARCHIVE, "None"); + vid_window_y = Cvar_Get ("vid_window_y", "0", CVAR_ARCHIVE, "None"); } -void VID_Shutdown (void) +void +VID_Shutdown (void) { - if (vid_initialized) - { + if (vid_initialized) { if (modestate == MS_FULLDIB) ChangeDisplaySettings (NULL, CDS_FULLSCREEN); - PostMessage (HWND_BROADCAST, WM_PALETTECHANGED, (WPARAM)mainwindow, (LPARAM)0); - PostMessage (HWND_BROADCAST, WM_SYSCOLORCHANGE, (WPARAM)0, (LPARAM)0); + PostMessage (HWND_BROADCAST, WM_PALETTECHANGED, (WPARAM) mainwindow, + (LPARAM) 0); + PostMessage (HWND_BROADCAST, WM_SYSCOLORCHANGE, (WPARAM) 0, (LPARAM) 0); - AppActivate(false, false); + AppActivate (false, false); DestroyDIBWindow (); DestroyFullscreenWindow (); DestroyFullDIBWindow (); @@ -2234,9 +2149,9 @@ void VID_Shutdown (void) DestroyWindow (hwnd_dialog); if (mainwindow) - DestroyWindow(mainwindow); + DestroyWindow (mainwindow); - MGL_exit(); + MGL_exit (); vid_testingmode = 0; vid_initialized = 0; @@ -2249,97 +2164,85 @@ void VID_Shutdown (void) FlipScreen ================ */ -void FlipScreen(vrect_t *rects) +void +FlipScreen (vrect_t *rects) { /* Flip the surfaces */ - if (DDActive) - { - if (mgldc) - { - if (memdc) - { - while (rects) - { - if (vid_stretched) - { - MGL_stretchBltCoord(mgldc, memdc, - rects->x, - rects->y, - rects->x + rects->width, - rects->y + rects->height, - rects->x << 1, - rects->y << 1, - (rects->x + rects->width) << 1, - (rects->y + rects->height) << 1); - } - else - { - MGL_bitBltCoord(mgldc, memdc, - rects->x, rects->y, - (rects->x + rects->width), - (rects->y + rects->height), - rects->x, rects->y, MGL_REPLACE_MODE); + if (DDActive) { + if (mgldc) { + if (memdc) { + while (rects) { + if (vid_stretched) { + MGL_stretchBltCoord (mgldc, memdc, + rects->x, + rects->y, + rects->x + rects->width, + rects->y + rects->height, + rects->x << 1, + rects->y << 1, + (rects->x + rects->width) << 1, + (rects->y + rects->height) << 1); + } else { + MGL_bitBltCoord (mgldc, memdc, + rects->x, rects->y, + (rects->x + rects->width), + (rects->y + rects->height), + rects->x, rects->y, MGL_REPLACE_MODE); } rects = rects->pnext; } } - if (vid.numpages > 1) - { + if (vid.numpages > 1) { // We have a flipping surface, so do a hard page flip - aPage = (aPage+1) % vid.numpages; - vPage = (vPage+1) % vid.numpages; - MGL_setActivePage(mgldc,aPage); - MGL_setVisualPage(mgldc,vPage,waitVRT); + aPage = (aPage + 1) % vid.numpages; + vPage = (vPage + 1) % vid.numpages; + MGL_setActivePage (mgldc, aPage); + MGL_setVisualPage (mgldc, vPage, waitVRT); } } - } - else - { - HDC hdcScreen; + } else { + HDC hdcScreen; - hdcScreen = GetDC(mainwindow); + hdcScreen = GetDC (mainwindow); - if (windc && dibdc) - { - MGL_setWinDC(windc,hdcScreen); + if (windc && dibdc) { + MGL_setWinDC (windc, hdcScreen); - while (rects) - { - if (vid_stretched) - { - MGL_stretchBltCoord(windc,dibdc, - rects->x, rects->y, - rects->x + rects->width, rects->y + rects->height, - rects->x << 1, rects->y << 1, - (rects->x + rects->width) << 1, - (rects->y + rects->height) << 1); - } - else - { - MGL_bitBltCoord(windc,dibdc, - rects->x, rects->y, - rects->x + rects->width, rects->y + rects->height, - rects->x, rects->y, MGL_REPLACE_MODE); + while (rects) { + if (vid_stretched) { + MGL_stretchBltCoord (windc, dibdc, + rects->x, rects->y, + rects->x + rects->width, + rects->y + rects->height, + rects->x << 1, rects->y << 1, + (rects->x + rects->width) << 1, + (rects->y + rects->height) << 1); + } else { + MGL_bitBltCoord (windc, dibdc, + rects->x, rects->y, + rects->x + rects->width, + rects->y + rects->height, rects->x, + rects->y, MGL_REPLACE_MODE); } rects = rects->pnext; } } - ReleaseDC(mainwindow, hdcScreen); + ReleaseDC (mainwindow, hdcScreen); } } -void VID_Update (vrect_t *rects) +void +VID_Update (vrect_t *rects) { - vrect_t rect; - RECT trect; + vrect_t rect; + RECT trect; - if (!vid_palettized && palette_changed) - { + if (!vid_palettized && palette_changed) { palette_changed = false; rect.x = 0; rect.y = 0; @@ -2349,77 +2252,65 @@ void VID_Update (vrect_t *rects) rects = ▭ } - if (firstupdate) - { - if (modestate == MS_WINDOWED) - { + if (firstupdate) { + if (modestate == MS_WINDOWED) { GetWindowRect (mainwindow, &trect); if ((trect.left != vid_window_x->int_val) || - (trect.top != vid_window_y->int_val)) - { - if (COM_CheckParm ("-resetwinpos")) - { + (trect.top != vid_window_y->int_val)) { + if (COM_CheckParm ("-resetwinpos")) { Cvar_SetValue (vid_window_x, 0.0); Cvar_SetValue (vid_window_y, 0.0); } VID_CheckWindowXY (); SetWindowPos (mainwindow, NULL, vid_window_x->int_val, - vid_window_y->int_val, 0, 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME); + vid_window_y->int_val, 0, 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | + SWP_DRAWFRAME); } } if ((_vid_default_mode_win->int_val != vid_default) && - (!startwindowed || (_vid_default_mode_win->int_val < MODE_FULLSCREEN_DEFAULT))) - { + (!startwindowed + || (_vid_default_mode_win->int_val < MODE_FULLSCREEN_DEFAULT))) { firstupdate = 0; - if (COM_CheckParm ("-resetwinpos")) - { + if (COM_CheckParm ("-resetwinpos")) { Cvar_SetValue (vid_window_x, 0.0); Cvar_SetValue (vid_window_y, 0.0); } if ((_vid_default_mode_win->int_val < 0) || - (_vid_default_mode_win->int_val >= nummodes)) - { + (_vid_default_mode_win->int_val >= nummodes)) { Cvar_SetValue (_vid_default_mode_win, windowed_default); } Cvar_SetValue (vid_mode, _vid_default_mode_win->int_val); } } - // We've drawn the frame; copy it to the screen FlipScreen (rects); - if (vid_testingmode) - { - if (realtime >= vid_testendtime) - { + if (vid_testingmode) { + if (realtime >= vid_testendtime) { VID_SetMode (vid_realmode, vid_curpal); vid_testingmode = 0; } - } - else - { - if (vid_mode->int_val != vid_realmode) - { + } else { + if (vid_mode->int_val != vid_realmode) { VID_SetMode (vid_mode->int_val, vid_curpal); Cvar_SetValue (vid_mode, vid_modenum); - // so if mode set fails, we don't keep on - // trying to set that mode + // so if mode set fails, we don't keep on + // trying to set that mode vid_realmode = vid_modenum; } } // handle the mouse state when windowed if that's changed - if (modestate == MS_WINDOWED) - { + if (modestate == MS_WINDOWED) { if (!_windowed_mouse->int_val) { - if (windowed_mouse) { + if (windowed_mouse) { IN_DeactivateMouse (); IN_ShowMouse (); } @@ -2443,42 +2334,37 @@ void VID_Update (vrect_t *rects) D_BeginDirectRect ================ */ -void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +void +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { - int i, j, reps, repshift; - vrect_t rect; + int i, j, reps, repshift; + vrect_t rect; if (!vid_initialized) return; - if (vid.aspect > 1.5) - { + if (vid.aspect > 1.5) { reps = 2; repshift = 1; - } - else - { + } else { reps = 1; repshift = 0; } - if (vid.numpages == 1) - { + if (vid.numpages == 1) { VID_LockBuffer (); if (!vid.direct) Sys_Error ("NULL vid.direct pointer"); - for (i=0 ; i<(height << repshift) ; i += reps) - { - for (j=0 ; j> repshift) * width], - width); + vid.direct + x + ((y << repshift) + i + + j) * vid.rowbytes, width); + memcpy (vid.direct + x + + ((y << repshift) + i + j) * vid.rowbytes, + &pbitmap[(i >> repshift) * width], width); } } @@ -2491,44 +2377,39 @@ void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) rect.pnext = NULL; FlipScreen (&rect); - } - else - { - // unlock if locked + } else { + // unlock if locked if (lockcount > 0) - MGL_endDirectAccess(); + MGL_endDirectAccess (); - // set the active page to the displayed page + // set the active page to the displayed page MGL_setActivePage (mgldc, vPage); - // lock the screen + // lock the screen MGL_beginDirectAccess (); - // save from and draw to screen - for (i=0 ; i<(height << repshift) ; i += reps) - { - for (j=0 ; jsurface + x + - ((y << repshift) + i + j) * mgldc->mi.bytesPerLine, - width); - memcpy ((byte *)mgldc->surface + x + - ((y << repshift) + i + j) * mgldc->mi.bytesPerLine, - &pbitmap[(i >> repshift) * width], + (byte *) mgldc->surface + x + + ((y << repshift) + i + j) * mgldc->mi.bytesPerLine, width); + memcpy ((byte *) mgldc->surface + x + + ((y << repshift) + i + j) * mgldc->mi.bytesPerLine, + &pbitmap[(i >> repshift) * width], width); } } - // unlock the screen + // unlock the screen MGL_endDirectAccess (); - // restore the original active page + // restore the original active page MGL_setActivePage (mgldc, aPage); - // relock the screen if it was locked + // relock the screen if it was locked if (lockcount > 0) - MGL_beginDirectAccess(); + MGL_beginDirectAccess (); } } @@ -2538,39 +2419,34 @@ void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) D_EndDirectRect ================ */ -void D_EndDirectRect (int x, int y, int width, int height) +void +D_EndDirectRect (int x, int y, int width, int height) { - int i, j, reps, repshift; - vrect_t rect; + int i, j, reps, repshift; + vrect_t rect; if (!vid_initialized) return; - if (vid.aspect > 1.5) - { + if (vid.aspect > 1.5) { reps = 2; repshift = 1; - } - else - { + } else { reps = 1; repshift = 0; } - if (vid.numpages == 1) - { + if (vid.numpages == 1) { VID_LockBuffer (); if (!vid.direct) Sys_Error ("NULL vid.direct pointer"); - for (i=0 ; i<(height << repshift) ; i += reps) - { - for (j=0 ; j 0) - MGL_endDirectAccess(); + MGL_endDirectAccess (); - // set the active page to the displayed page + // set the active page to the displayed page MGL_setActivePage (mgldc, vPage); - // lock the screen + // lock the screen MGL_beginDirectAccess (); - // restore to the screen - for (i=0 ; i<(height << repshift) ; i += reps) - { - for (j=0 ; jsurface + x + - ((y << repshift) + i + j) * mgldc->mi.bytesPerLine, - &backingbuf[(i + j) * 24], - width); + // restore to the screen + for (i = 0; i < (height << repshift); i += reps) { + for (j = 0; j < reps; j++) { + memcpy ((byte *) mgldc->surface + x + + ((y << repshift) + i + j) * mgldc->mi.bytesPerLine, + &backingbuf[(i + j) * 24], width); } } - // unlock the screen + // unlock the screen MGL_endDirectAccess (); - // restore the original active page + // restore the original active page MGL_setActivePage (mgldc, aPage); - // relock the screen if it was locked + // relock the screen if it was locked if (lockcount > 0) - MGL_beginDirectAccess(); + MGL_beginDirectAccess (); } } //========================================================================== -byte scantokey[128] = -{ +byte scantokey[128] = { // 0 1 2 3 4 5 6 7 // 8 9 A B C D E F - 0 , 27, '1', '2', '3', '4', '5', '6', - '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 - 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', - 'o', 'p', '[', ']', 13, K_CTRL, 'a', 's', // 1 - 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', - '\'', '`', K_SHIFT,'\\', 'z', 'x', 'c', 'v', // 2 - 'b', 'n', 'm', ',', '.', '/', K_SHIFT,KP_MULTIPLY, - K_ALT, ' ', K_CAPSLOCK,K_F1, K_F2, K_F3, K_F4, K_F5, // 3 - K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE,K_SCRLCK,KP_HOME, - KP_UPARROW,KP_PGUP,KP_MINUS,KP_LEFTARROW,KP_5,KP_RIGHTARROW,KP_PLUS,KP_END, // 4 - KP_DOWNARROW,KP_PGDN,KP_INS,KP_DEL,0, 0, 0, K_F11, - K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0 + 0, 27, '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 + 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', + 'o', 'p', '[', ']', 13, K_CTRL, 'a', 's', // 1 + 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', + '\'', '`', K_SHIFT, '\\', 'z', 'x', 'c', 'v', // 2 + 'b', 'n', 'm', ',', '.', '/', K_SHIFT, KP_MULTIPLY, + K_ALT, ' ', K_CAPSLOCK, K_F1, K_F2, K_F3, K_F4, K_F5, // 3 + K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE, K_SCRLCK, KP_HOME, + KP_UPARROW, KP_PGUP, KP_MINUS, KP_LEFTARROW, KP_5, KP_RIGHTARROW, KP_PLUS, KP_END, // 4 + KP_DOWNARROW, KP_PGDN, KP_INS, KP_DEL, 0, 0, 0, K_F11, + K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }; -byte extscantokey[128] = -{ +byte extscantokey[128] = { // 0 1 2 3 4 5 6 7 // 8 9 A B C D E F - 0 , 27, '1', '2', '3', '4', '5', '6', - '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 - 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', - 'o', 'p', '[', ']', KP_ENTER,K_CTRL,'a', 's', // 1 - 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', - '\'', '`', K_SHIFT,'\\', 'z', 'x', 'c', 'v', // 2 - 'b', 'n', 'm', ',', '.', KP_DIVIDE,K_SHIFT,'*', - K_ALT, ' ', K_CAPSLOCK,K_F1,K_F2, K_F3, K_F4, K_F5, // 3 - K_F6, K_F7, K_F8, K_F9, K_F10, KP_NUMLCK,0, K_HOME, - K_UPARROW,K_PGUP,'-',K_LEFTARROW,'5',K_RIGHTARROW,'+', K_END, // 4 - K_DOWNARROW,K_PGDN,K_INS,K_DEL, 0, 0, 0, K_F11, - K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0 + 0, 27, '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 + 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', + 'o', 'p', '[', ']', KP_ENTER, K_CTRL, 'a', 's', // 1 + 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', + '\'', '`', K_SHIFT, '\\', 'z', 'x', 'c', 'v', // 2 + 'b', 'n', 'm', ',', '.', KP_DIVIDE, K_SHIFT, '*', + K_ALT, ' ', K_CAPSLOCK, K_F1, K_F2, K_F3, K_F4, K_F5, // 3 + K_F6, K_F7, K_F8, K_F9, K_F10, KP_NUMLCK, 0, K_HOME, + K_UPARROW, K_PGUP, '-', K_LEFTARROW, '5', K_RIGHTARROW, '+', K_END, // 4 + K_DOWNARROW, K_PGDN, K_INS, K_DEL, 0, 0, 0, K_F11, + K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }; @@ -2676,13 +2545,14 @@ MapKey Map from windows to quake keynums ======= */ -int MapKey (int key) +int +MapKey (int key) { - int extended; + int extended; extended = (key >> 24) & 1; - key = (key>>16)&255; + key = (key >> 16) & 255; if (key > 127) return 0; @@ -2693,7 +2563,8 @@ int MapKey (int key) } -void AppActivate(BOOL fActive, BOOL minimize) +void +AppActivate (BOOL fActive, BOOL minimize) /**************************************************************************** * * Function: AppActivate @@ -2705,49 +2576,40 @@ void AppActivate(BOOL fActive, BOOL minimize) * ****************************************************************************/ { - HDC hdc; - int i, t; - static BOOL sound_active; + HDC hdc; + int i, t; + static BOOL sound_active; ActiveApp = fActive; // messy, but it seems to work - if (vid_fulldib_on_focus_mode) - { - Minimized = minimize; + if (vid_fulldib_on_focus_mode) { + Minimized = minimize; - if (Minimized) + if (Minimized) ActiveApp = false; } - MGL_appActivate(windc, ActiveApp); + MGL_appActivate (windc, ActiveApp); - if (vid_initialized) - { - // yield the palette if we're losing the focus - hdc = GetDC(NULL); + if (vid_initialized) { + // yield the palette if we're losing the focus + hdc = GetDC (NULL); - if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) - { - if (ActiveApp) - { - if ((modestate == MS_WINDOWED) || (modestate == MS_FULLDIB)) - { - if (GetSystemPaletteUse(hdc) == SYSPAL_STATIC) - { - // switch to SYSPAL_NOSTATIC and remap the colors - SetSystemPaletteUse(hdc, SYSPAL_NOSTATIC); - syscolchg = true; + if (GetDeviceCaps (hdc, RASTERCAPS) & RC_PALETTE) { + if (ActiveApp) { + if ((modestate == MS_WINDOWED) || (modestate == MS_FULLDIB)) { + if (GetSystemPaletteUse (hdc) == SYSPAL_STATIC) { + // switch to SYSPAL_NOSTATIC and remap the colors + SetSystemPaletteUse (hdc, SYSPAL_NOSTATIC); + syscolchg = true; pal_is_nostatic = true; + } } - } - } - else if (pal_is_nostatic) - { - if (GetSystemPaletteUse(hdc) == SYSPAL_NOSTATIC) - { - // switch back to SYSPAL_STATIC and the old mapping - SetSystemPaletteUse(hdc, SYSPAL_STATIC); + } else if (pal_is_nostatic) { + if (GetSystemPaletteUse (hdc) == SYSPAL_NOSTATIC) { + // switch back to SYSPAL_STATIC and the old mapping + SetSystemPaletteUse (hdc, SYSPAL_STATIC); syscolchg = true; } @@ -2760,33 +2622,25 @@ void AppActivate(BOOL fActive, BOOL minimize) scr_fullupdate = 0; - ReleaseDC(NULL,hdc); + ReleaseDC (NULL, hdc); } - // enable/disable sound on focus gain/loss - if (!ActiveApp && sound_active) - { + if (!ActiveApp && sound_active) { S_BlockSound (); S_ClearBuffer (); sound_active = false; - } - else if (ActiveApp && !sound_active) - { + } else if (ActiveApp && !sound_active) { S_UnblockSound (); S_ClearBuffer (); sound_active = true; } - // minimize/restore fulldib windows/mouse-capture normal windows on demand - if (!in_mode_set) - { - if (ActiveApp) - { - if (vid_fulldib_on_focus_mode) - { - if (vid_initialized) - { - msg_suppress_1 = true; // don't want to see normal mode set message + if (!in_mode_set) { + if (ActiveApp) { + if (vid_fulldib_on_focus_mode) { + if (vid_initialized) { + msg_suppress_1 = true; // don't want to see normal mode + // set message VID_SetMode (vid_fulldib_on_focus_mode, vid_curpal); msg_suppress_1 = false; @@ -2799,29 +2653,28 @@ void AppActivate(BOOL fActive, BOOL minimize) IN_ActivateMouse (); IN_HideMouse (); } - else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val && key_dest == key_game) - { + else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val + && key_dest == key_game) { IN_ActivateMouse (); IN_HideMouse (); } } - if (!ActiveApp) - { - if (modestate == MS_FULLDIB) - { - if (vid_initialized) - { + if (!ActiveApp) { + if (modestate == MS_FULLDIB) { + if (vid_initialized) { force_minimized = true; i = vid_fulldib_on_focus_mode; - msg_suppress_1 = true; // don't want to see normal mode set message + msg_suppress_1 = true; // don't want to see normal mode + // set message VID_SetMode (windowed_default, vid_curpal); msg_suppress_1 = false; vid_fulldib_on_focus_mode = i; force_minimized = false; - // we never seem to get WM_ACTIVATE inactive from this mode set, so we'll - // do it manually + // we never seem to get WM_ACTIVATE inactive from this + // mode set, so we'll + // do it manually t = in_mode_set; in_mode_set = true; AppActivate (false, true); @@ -2830,9 +2683,9 @@ void AppActivate(BOOL fActive, BOOL minimize) IN_DeactivateMouse (); IN_ShowMouse (); - } - else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val /* && mouseactive */) - { + } else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val /* && + mouseactive + */ ) { IN_DeactivateMouse (); IN_ShowMouse (); } @@ -2846,18 +2699,15 @@ void AppActivate(BOOL fActive, BOOL minimize) VID_HandlePause ================ */ -void VID_HandlePause (qboolean pause) +void +VID_HandlePause (qboolean pause) { #if 0 - if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val) - { - if (pause) - { + if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val) { + if (pause) { IN_DeactivateMouse (); IN_ShowMouse (); - } - else - { + } else { IN_ActivateMouse (); IN_HideMouse (); } @@ -2865,7 +2715,7 @@ void VID_HandlePause (qboolean pause) #endif } - + /* =================================================================== @@ -2874,42 +2724,39 @@ MAIN WINDOW =================================================================== */ -LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); +LONG CDAudio_MessageHandler (HWND hWnd, UINT uMsg, WPARAM wParam, + + LPARAM lParam); /* main window procedure */ -LONG WINAPI MainWndProc ( - HWND hWnd, - UINT uMsg, - WPARAM wParam, - LPARAM lParam) +LONG WINAPI +MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - LONG lRet = 0; - int fActive, fMinimized, temp; - HDC hdc; - PAINTSTRUCT ps; + LONG lRet = 0; + int fActive, fMinimized, temp; + HDC hdc; + PAINTSTRUCT ps; extern unsigned int uiWheelMessage; - if ( uMsg == uiWheelMessage ) { + if (uMsg == uiWheelMessage) { uMsg = WM_MOUSEWHEEL; wParam <<= 16; } - switch (uMsg) - { + switch (uMsg) { case WM_CREATE: break; case WM_SYSCOMMAND: - // Check for maximize being hit - switch (wParam & ~0x0F) - { + // Check for maximize being hit + switch (wParam & ~0x0F) { case SC_MAXIMIZE: - // if minimized, bring up as a window before going fullscreen, - // so MGL will have the right state to restore - if (Minimized) - { + // if minimized, bring up as a window before going + // fullscreen, + // so MGL will have the right state to restore + if (Minimized) { force_mode_set = true; VID_SetMode (vid_modenum, vid_curpal); force_mode_set = false; @@ -2918,36 +2765,34 @@ LONG WINAPI MainWndProc ( VID_SetMode (vid_fullscreen_mode->int_val, vid_curpal); break; - case SC_SCREENSAVE: - case SC_MONITORPOWER: - if (modestate != MS_WINDOWED) - { - // don't call DefWindowProc() because we don't want to start - // the screen saver fullscreen + case SC_SCREENSAVE: + case SC_MONITORPOWER: + if (modestate != MS_WINDOWED) { + // don't call DefWindowProc() because we don't want + // to start + // the screen saver fullscreen break; } - - // fall through windowed and allow the screen saver to start + // fall through windowed and allow the screen saver to + // start default: - if (!in_mode_set) - { - S_BlockSound (); - S_ClearBuffer (); - } + if (!in_mode_set) { + S_BlockSound (); + S_ClearBuffer (); + } - lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); + lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); - if (!in_mode_set) - { - S_UnblockSound (); - } + if (!in_mode_set) { + S_UnblockSound (); + } } break; case WM_MOVE: - window_x = (int) LOWORD(lParam); - window_y = (int) HIWORD(lParam); + window_x = (int) LOWORD (lParam); + window_y = (int) HIWORD (lParam); VID_UpdateWindowStatus (); if ((modestate == MS_WINDOWED) && !in_mode_set && !Minimized) @@ -2957,59 +2802,60 @@ LONG WINAPI MainWndProc ( case WM_SIZE: Minimized = false; - - if (!(wParam & SIZE_RESTORED)) - { + + if (!(wParam & SIZE_RESTORED)) { if (wParam & SIZE_MINIMIZED) Minimized = true; } break; case WM_SYSCHAR: - // keep Alt-Space from happening + // keep Alt-Space from happening break; case WM_ACTIVATE: - fActive = LOWORD(wParam); - fMinimized = (BOOL) HIWORD(wParam); - AppActivate(!(fActive == WA_INACTIVE), fMinimized); + fActive = LOWORD (wParam); + fMinimized = (BOOL) HIWORD (wParam); + AppActivate (!(fActive == WA_INACTIVE), fMinimized); - // fix the leftover Alt from any Alt-Tab or the like that switched us away + // fix the leftover Alt from any Alt-Tab or the like that + // switched us away ClearAllStates (); - if (!in_mode_set) - { + if (!in_mode_set) { if (windc) - MGL_activatePalette(windc,true); + MGL_activatePalette (windc, true); - VID_SetPalette(vid_curpal); + VID_SetPalette (vid_curpal); } break; case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); + hdc = BeginPaint (hWnd, &ps); if (!in_mode_set && host_initialized) SCR_UpdateWholeScreen (); - EndPaint(hWnd, &ps); + EndPaint (hWnd, &ps); break; case WM_KEYDOWN: case WM_SYSKEYDOWN: if (!in_mode_set) - Key_Event (MapKey(lParam), -1, true); + Key_Event (MapKey (lParam), -1, true); break; case WM_KEYUP: case WM_SYSKEYUP: if (!in_mode_set) - Key_Event (MapKey(lParam), -1, false); + Key_Event (MapKey (lParam), -1, false); break; - // this is complicated because Win32 seems to pack multiple mouse events into - // one update sometimes, so we always check all states and look for events + // this is complicated because Win32 seems to pack multiple mouse + // events into + // one update sometimes, so we always check all states and look + // for events case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: @@ -3017,8 +2863,7 @@ LONG WINAPI MainWndProc ( case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MOUSEMOVE: - if (!in_mode_set) - { + if (!in_mode_set) { temp = 0; if (wParam & MK_LBUTTON) @@ -3033,80 +2878,84 @@ LONG WINAPI MainWndProc ( IN_MouseEvent (temp); } break; - // JACK: This is the mouse wheel with the Intellimouse - // Its delta is either positive or neg, and we generate the proper - // Event. - case WM_MOUSEWHEEL: - if ((short) HIWORD(wParam) > 0) { - Key_Event(K_MWHEELUP, -1, true); - Key_Event(K_MWHEELUP, -1, false); + // JACK: This is the mouse wheel with the Intellimouse + // Its delta is either positive or neg, and we generate the + // proper + // Event. + case WM_MOUSEWHEEL: + if ((short) HIWORD (wParam) > 0) { + Key_Event (K_MWHEELUP, -1, true); + Key_Event (K_MWHEELUP, -1, false); } else { - Key_Event(K_MWHEELDOWN, -1, true); - Key_Event(K_MWHEELDOWN, -1, false); + Key_Event (K_MWHEELDOWN, -1, true); + Key_Event (K_MWHEELDOWN, -1, false); } break; - // KJB: Added these new palette functions + // KJB: Added these new palette functions case WM_PALETTECHANGED: - if ((HWND)wParam == hWnd) + if ((HWND) wParam == hWnd) break; /* Fall through to WM_QUERYNEWPALETTE */ case WM_QUERYNEWPALETTE: - hdc = GetDC(NULL); + hdc = GetDC (NULL); - if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) + if (GetDeviceCaps (hdc, RASTERCAPS) & RC_PALETTE) vid_palettized = true; else vid_palettized = false; - ReleaseDC(NULL,hdc); + ReleaseDC (NULL, hdc); scr_fullupdate = 0; - if (vid_initialized && !in_mode_set && windc && MGL_activatePalette(windc,false) && !Minimized) - { + if (vid_initialized && !in_mode_set && windc + && MGL_activatePalette (windc, false) && !Minimized) { VID_SetPalette (vid_curpal); InvalidateRect (mainwindow, NULL, false); - // specifically required if WM_QUERYNEWPALETTE realizes a new palette + // specifically required if WM_QUERYNEWPALETTE realizes a new + // palette lRet = TRUE; } break; case WM_DISPLAYCHANGE: - if (!in_mode_set && (modestate == MS_WINDOWED) && !vid_fulldib_on_focus_mode) - { + if (!in_mode_set && (modestate == MS_WINDOWED) + && !vid_fulldib_on_focus_mode) { force_mode_set = true; VID_SetMode (vid_modenum, vid_curpal); force_mode_set = false; } break; - case WM_CLOSE: - // this causes Close in the right-click task bar menu not to work, but right - // now bad things happen if Close is handled in that case (garbage and a - // crash on Win95) - if (!in_mode_set) - { - if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", - MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES) - { + case WM_CLOSE: + // this causes Close in the right-click task bar menu not to + // work, but right + // now bad things happen if Close is handled in that case + // (garbage and a + // crash on Win95) + if (!in_mode_set) { + if (MessageBox + (mainwindow, "Are you sure you want to quit?", + "Confirm Exit", + MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES) { Sys_Quit (); } } break; case MM_MCINOTIFY: - lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam); + lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam); break; default: - /* pass all unhandled messages to DefWindowProc */ - lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); - break; - } + /* pass all unhandled messages to DefWindowProc */ + lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); + break; + } - /* return 0 if handled message, 1 if not */ - return lRet; + /* return 0 if handled message, 1 if not */ + return lRet; } @@ -3117,42 +2966,41 @@ extern void M_DrawCharacter (int cx, int line, int num); extern void M_DrawTransPic (int x, int y, qpic_t *pic); extern void M_DrawPic (int x, int y, qpic_t *pic); -static int vid_line, vid_wmodes; +static int vid_line, vid_wmodes; -typedef struct -{ - int modenum; - char *desc; - int iscur; - int ismode13; - int width; +typedef struct { + int modenum; + char *desc; + int iscur; + int ismode13; + int width; } modedesc_t; #define MAX_COLUMN_SIZE 5 #define MODE_AREA_HEIGHT (MAX_COLUMN_SIZE + 6) #define MAX_MODEDESCS (MAX_COLUMN_SIZE*3) -static modedesc_t modedescs[MAX_MODEDESCS]; +static modedesc_t modedescs[MAX_MODEDESCS]; /* ================ VID_MenuDraw ================ */ -void VID_MenuDraw (void) +void +VID_MenuDraw (void) { - qpic_t *p; - char *ptr; - int lnummodes, i, j, k, column, row, dup, dupmode = 0; - char temp[100]; - vmode_t *pv; - modedesc_t tmodedesc; + qpic_t *p; + char *ptr; + int lnummodes, i, j, k, column, row, dup, dupmode = 0; + char temp[100]; + vmode_t *pv; + modedesc_t tmodedesc; p = Draw_CachePic ("gfx/vidmodes.lmp"); - M_DrawPic ( (320-p->width)/2, 4, p); + M_DrawPic ((320 - p->width) / 2, 4, p); - for (i=0 ; i<3 ; i++) - { + for (i = 0; i < 3; i++) { ptr = VID_GetModeDescriptionMemCheck (i); modedescs[i].modenum = modelist[i].modenum; modedescs[i].desc = ptr; @@ -3165,39 +3013,31 @@ void VID_MenuDraw (void) vid_wmodes = 3; lnummodes = VID_NumModes (); - - for (i=3 ; iwidth != 360) || COM_CheckParm("-allow360"))) - { + // we only have room for 15 fullscreen modes, so don't allow + // 360-wide modes, because if there are 5 320-wide modes and + // 5 360-wide modes, we'll run out of space + if (ptr && ((pv->width != 360) || COM_CheckParm ("-allow360"))) { dup = 0; - for (j=3 ; j modedescs[j].width) - { + for (i = 3; i < (vid_wmodes - 1); i++) { + for (j = (i + 1); j < vid_wmodes; j++) { + if (modedescs[i].width > modedescs[j].width) { tmodedesc = modedescs[i]; modedescs[i] = modedescs[j]; modedescs[j] = tmodedesc; @@ -3233,86 +3070,74 @@ void VID_MenuDraw (void) } - M_Print (13*8, 36, "Windowed Modes"); + M_Print (13 * 8, 36, "Windowed Modes"); column = 16; - row = 36+2*8; + row = 36 + 2 * 8; - for (i=0 ; i<3; i++) - { + for (i = 0; i < 3; i++) { if (modedescs[i].iscur) M_PrintWhite (column, row, modedescs[i].desc); else M_Print (column, row, modedescs[i].desc); - column += 13*8; + column += 13 * 8; } - if (vid_wmodes > 3) - { - M_Print (12*8, 36+4*8, "Fullscreen Modes"); + if (vid_wmodes > 3) { + M_Print (12 * 8, 36 + 4 * 8, "Fullscreen Modes"); column = 16; - row = 36+6*8; + row = 36 + 6 * 8; - for (i=3 ; iint_val); - if (ptr) - { - snprintf (temp, sizeof(temp), "Current default: %s", ptr); - M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, temp); + if (ptr) { + snprintf (temp, sizeof (temp), "Current default: %s", ptr); + M_Print (3 * 8, 36 + MODE_AREA_HEIGHT * 8 + 8 * 6, temp); } - M_Print (15*8, 36 + MODE_AREA_HEIGHT * 8 + 8*8, - "Esc to exit"); + M_Print (15 * 8, 36 + MODE_AREA_HEIGHT * 8 + 8 * 8, "Esc to exit"); - row = 36 + 2*8 + (vid_line / VID_ROW_SIZE) * 8; - column = 8 + (vid_line % VID_ROW_SIZE) * 13*8; + row = 36 + 2 * 8 + (vid_line / VID_ROW_SIZE) * 8; + column = 8 + (vid_line % VID_ROW_SIZE) * 13 * 8; if (vid_line >= 3) - row += 3*8; + row += 3 * 8; - M_DrawCharacter (column, row, 12+((int)(realtime*4)&1)); + M_DrawCharacter (column, row, 12 + ((int) (realtime * 4) & 1)); } } @@ -3322,105 +3147,104 @@ void VID_MenuDraw (void) VID_MenuKey ================ */ -void VID_MenuKey (int key) +void +VID_MenuKey (int key) { if (vid_testingmode) return; - switch (key) - { - case K_ESCAPE: - S_LocalSound ("misc/menu1.wav"); - M_Menu_Options_f (); - break; + switch (key) { + case K_ESCAPE: + S_LocalSound ("misc/menu1.wav"); + M_Menu_Options_f (); + break; - case K_LEFTARROW: + case K_LEFTARROW: - S_LocalSound ("misc/menu1.wav"); - vid_line = ((vid_line / VID_ROW_SIZE) * VID_ROW_SIZE) + - ((vid_line + 2) % VID_ROW_SIZE); + S_LocalSound ("misc/menu1.wav"); + vid_line = ((vid_line / VID_ROW_SIZE) * VID_ROW_SIZE) + + ((vid_line + 2) % VID_ROW_SIZE); - if (vid_line >= vid_wmodes) - vid_line = vid_wmodes - 1; - break; + if (vid_line >= vid_wmodes) + vid_line = vid_wmodes - 1; + break; - case K_RIGHTARROW: - S_LocalSound ("misc/menu1.wav"); - vid_line = ((vid_line / VID_ROW_SIZE) * VID_ROW_SIZE) + - ((vid_line + 4) % VID_ROW_SIZE); + case K_RIGHTARROW: + S_LocalSound ("misc/menu1.wav"); + vid_line = ((vid_line / VID_ROW_SIZE) * VID_ROW_SIZE) + + ((vid_line + 4) % VID_ROW_SIZE); - if (vid_line >= vid_wmodes) - vid_line = (vid_line / VID_ROW_SIZE) * VID_ROW_SIZE; - break; + if (vid_line >= vid_wmodes) + vid_line = (vid_line / VID_ROW_SIZE) * VID_ROW_SIZE; + break; - case K_UPARROW: - S_LocalSound ("misc/menu1.wav"); - vid_line -= VID_ROW_SIZE; + case K_UPARROW: + S_LocalSound ("misc/menu1.wav"); + vid_line -= VID_ROW_SIZE; - if (vid_line < 0) - { - vid_line += ((vid_wmodes + (VID_ROW_SIZE - 1)) / - VID_ROW_SIZE) * VID_ROW_SIZE; + if (vid_line < 0) { + vid_line += ((vid_wmodes + (VID_ROW_SIZE - 1)) / + VID_ROW_SIZE) * VID_ROW_SIZE; - while (vid_line >= vid_wmodes) - vid_line -= VID_ROW_SIZE; - } - break; + while (vid_line >= vid_wmodes) + vid_line -= VID_ROW_SIZE; + } + break; - case K_DOWNARROW: - S_LocalSound ("misc/menu1.wav"); - vid_line += VID_ROW_SIZE; + case K_DOWNARROW: + S_LocalSound ("misc/menu1.wav"); + vid_line += VID_ROW_SIZE; - if (vid_line >= vid_wmodes) - { - vid_line -= ((vid_wmodes + (VID_ROW_SIZE - 1)) / - VID_ROW_SIZE) * VID_ROW_SIZE; + if (vid_line >= vid_wmodes) { + vid_line -= ((vid_wmodes + (VID_ROW_SIZE - 1)) / + VID_ROW_SIZE) * VID_ROW_SIZE; - while (vid_line < 0) - vid_line += VID_ROW_SIZE; - } - break; + while (vid_line < 0) + vid_line += VID_ROW_SIZE; + } + break; - case K_ENTER: - S_LocalSound ("misc/menu1.wav"); - VID_SetMode (modedescs[vid_line].modenum, vid_curpal); - break; + case K_ENTER: + S_LocalSound ("misc/menu1.wav"); + VID_SetMode (modedescs[vid_line].modenum, vid_curpal); + break; - case 'T': - case 't': - S_LocalSound ("misc/menu1.wav"); - // have to set this before setting the mode because WM_PAINT - // happens during the mode set and does a VID_Update, which - // checks vid_testingmode - vid_testingmode = 1; - vid_testendtime = realtime + 5.0; + case 'T': + case 't': + S_LocalSound ("misc/menu1.wav"); + // have to set this before setting the mode because WM_PAINT + // happens during the mode set and does a VID_Update, which + // checks vid_testingmode + vid_testingmode = 1; + vid_testendtime = realtime + 5.0; - if (!VID_SetMode (modedescs[vid_line].modenum, vid_curpal)) - { - vid_testingmode = 0; - } - break; + if (!VID_SetMode (modedescs[vid_line].modenum, vid_curpal)) { + vid_testingmode = 0; + } + break; - case 'D': - case 'd': - S_LocalSound ("misc/menu1.wav"); - firstupdate = 0; - Cvar_SetValue (_vid_default_mode_win, vid_modenum); - break; + case 'D': + case 'd': + S_LocalSound ("misc/menu1.wav"); + firstupdate = 0; + Cvar_SetValue (_vid_default_mode_win, vid_modenum); + break; - default: - break; + default: + break; } } -void VID_SetCaption (char *text) +void +VID_SetCaption (char *text) { if (text && *text) { - char *temp = strdup (text); - SetWindowText (mainwindow, (LPSTR) va ("%s %s: %s", PROGRAM, VERSION, text)); + char *temp = strdup (text); + + SetWindowText (mainwindow, + (LPSTR) va ("%s %s: %s", PROGRAM, VERSION, text)); free (temp); } else { SetWindowText (mainwindow, (LPSTR) va ("%s %s", PROGRAM, VERSION)); } } - diff --git a/source/vid_null.c b/source/vid_null.c index 1e1032a..93a7eb0 100644 --- a/source/vid_null.c +++ b/source/vid_null.c @@ -27,54 +27,60 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "d_local.h" -viddef_t vid; // global video state +viddef_t vid; // global video state #define BASEWIDTH 320 #define BASEHEIGHT 200 -byte vid_buffer[BASEWIDTH*BASEHEIGHT]; -short zbuffer[BASEWIDTH*BASEHEIGHT]; -byte surfcache[256*1024]; +byte vid_buffer[BASEWIDTH * BASEHEIGHT]; +short zbuffer[BASEWIDTH * BASEHEIGHT]; +byte surfcache[256 * 1024]; -unsigned short d_8to16table[256]; -unsigned int d_8to24table[256]; +unsigned short d_8to16table[256]; +unsigned int d_8to24table[256]; -void VID_SetPalette (unsigned char *palette) +void +VID_SetPalette (unsigned char *palette) { } -void VID_ShiftPalette (unsigned char *palette) +void +VID_ShiftPalette (unsigned char *palette) { } -void VID_Init (unsigned char *palette) +void +VID_Init (unsigned char *palette) { vid.maxwarpwidth = vid.width = vid.conwidth = BASEWIDTH; vid.maxwarpheight = vid.height = vid.conheight = BASEHEIGHT; vid.aspect = 1.0; vid.numpages = 1; vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); + vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); vid.buffer = vid.conbuffer = vid_buffer; vid.rowbytes = vid.conrowbytes = BASEWIDTH; - + d_pzbuffer = zbuffer; - D_InitCaches (surfcache, sizeof(surfcache)); + D_InitCaches (surfcache, sizeof (surfcache)); } -void VID_Init_Cvars () +void +VID_Init_Cvars () { } -void VID_Shutdown (void) +void +VID_Shutdown (void) { } -void VID_Update (vrect_t *rects) +void +VID_Update (vrect_t *rects) { } @@ -83,7 +89,8 @@ void VID_Update (vrect_t *rects) D_BeginDirectRect ================ */ -void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +void +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { } @@ -93,10 +100,12 @@ void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) D_EndDirectRect ================ */ -void D_EndDirectRect (int x, int y, int width, int height) +void +D_EndDirectRect (int x, int y, int width, int height) { } -void VID_SetCaption (char *text) +void +VID_SetCaption (char *text) { } diff --git a/source/vid_sdl.c b/source/vid_sdl.c index 60cc81b..53f6ef2 100644 --- a/source/vid_sdl.c +++ b/source/vid_sdl.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -#include "config.h" +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -45,37 +45,38 @@ // static float oldin_grab = 0; -cvar_t *vid_fullscreen; -extern viddef_t vid; // global video state -unsigned short d_8to16table[256]; +cvar_t *vid_fullscreen; +extern viddef_t vid; // global video state +unsigned short d_8to16table[256]; + +int modestate; // fixme: just to avoid cross-comp. + + // errors - remove later -int modestate; // fixme: just to avoid cross-comp. errors - remove later - // The original defaults #define BASEWIDTH 320 #define BASEHEIGHT 200 -int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes = 0; -byte *VGA_pagebase; +int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes = 0; +byte *VGA_pagebase; static SDL_Surface *screen = NULL; void VID_InitBuffers (int width, int height) { - int tbuffersize, tcachesize; - void *vid_surfcache; + int tbuffersize, tcachesize; + void *vid_surfcache; // Calculate the sizes we want first tbuffersize = vid.width * vid.height * sizeof (*d_pzbuffer); - tcachesize = D_SurfaceCacheForRes(width, height); + tcachesize = D_SurfaceCacheForRes (width, height); // Free the old z-buffer if (d_pzbuffer) { free (d_pzbuffer); d_pzbuffer = NULL; } - // Free the old surface cache vid_surfcache = D_SurfaceCacheAddress (); if (vid_surfcache) { @@ -83,13 +84,11 @@ VID_InitBuffers (int width, int height) free (vid_surfcache); vid_surfcache = NULL; } - // Allocate the new z-buffer d_pzbuffer = calloc (tbuffersize, 1); if (!d_pzbuffer) { Sys_Error ("Not enough memory for video mode\n"); } - // Allocate the new surface cache; free the z-buffer if we fail vid_surfcache = calloc (tcachesize, 1); if (!vid_surfcache) { @@ -104,109 +103,112 @@ VID_InitBuffers (int width, int height) void VID_SetPalette (unsigned char *palette) { - int i; - SDL_Color colors[256]; + int i; + SDL_Color colors[256]; - for ( i=0; i<256; ++i ) { - colors[i].r = *palette++; - colors[i].g = *palette++; - colors[i].b = *palette++; - } - SDL_SetColors (screen, colors, 0, 256); + for (i = 0; i < 256; ++i) { + colors[i].r = *palette++; + colors[i].g = *palette++; + colors[i].b = *palette++; + } + SDL_SetColors (screen, colors, 0, 256); } void VID_ShiftPalette (unsigned char *palette) { - VID_SetPalette (palette); + VID_SetPalette (palette); } void VID_Init (unsigned char *palette) { - //Uint8 video_bpp; - //Uint16 video_w, video_h; - Uint32 flags; + // Uint8 video_bpp; + // Uint16 video_w, video_h; + Uint32 flags; - // Load the SDL library - if (SDL_Init(SDL_INIT_VIDEO)<0) //|SDL_INIT_AUDIO|SDL_INIT_CDROM) < 0) - Sys_Error("VID: Couldn't load SDL: %s", SDL_GetError()); + // Load the SDL library + if (SDL_Init (SDL_INIT_VIDEO) < 0) // |SDL_INIT_AUDIO|SDL_INIT_CDROM) < + // 0) + Sys_Error ("VID: Couldn't load SDL: %s", SDL_GetError ()); - // Set up display mode (width and height) - VID_GetWindowSize (BASEWIDTH, BASEHEIGHT); - vid.maxwarpwidth = WARP_WIDTH; - vid.maxwarpheight = WARP_HEIGHT; + // Set up display mode (width and height) + VID_GetWindowSize (BASEWIDTH, BASEHEIGHT); + vid.maxwarpwidth = WARP_WIDTH; + vid.maxwarpheight = WARP_HEIGHT; - // Set video width, height and flags - flags = (SDL_SWSURFACE|SDL_HWPALETTE); - if ( vid_fullscreen->int_val ) - flags |= SDL_FULLSCREEN; + // Set video width, height and flags + flags = (SDL_SWSURFACE | SDL_HWPALETTE); + if (vid_fullscreen->int_val) + flags |= SDL_FULLSCREEN; - // Initialize display - if (!(screen = SDL_SetVideoMode(vid.width, vid.height, 8, flags))) - Sys_Error("VID: Couldn't set video mode: %s\n", SDL_GetError()); - VID_SetPalette(palette); - VID_SetCaption(""); + // Initialize display + if (!(screen = SDL_SetVideoMode (vid.width, vid.height, 8, flags))) + Sys_Error ("VID: Couldn't set video mode: %s\n", SDL_GetError ()); + VID_SetPalette (palette); + VID_SetCaption (""); - // now know everything we need to know about the buffer - VGA_width = vid.conwidth = vid.width; - VGA_height = vid.conheight = vid.height; - vid.aspect = ((float)vid.height / (float)vid.width) * (320.0 / 240.0); - vid.numpages = 1; - vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); - VGA_pagebase = vid.buffer = screen->pixels; - VGA_rowbytes = vid.rowbytes = screen->pitch; - vid.conbuffer = vid.buffer; - vid.conrowbytes = vid.rowbytes; - vid.direct = 0; + // now know everything we need to know about the buffer + VGA_width = vid.conwidth = vid.width; + VGA_height = vid.conheight = vid.height; + vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); + vid.numpages = 1; + vid.colormap = host_colormap; + vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); + VGA_pagebase = vid.buffer = screen->pixels; + VGA_rowbytes = vid.rowbytes = screen->pitch; + vid.conbuffer = vid.buffer; + vid.conrowbytes = vid.rowbytes; + vid.direct = 0; - // allocate z buffer and surface cache - VID_InitBuffers (vid.width, vid.height); + // allocate z buffer and surface cache + VID_InitBuffers (vid.width, vid.height); - // initialize the mouse - SDL_ShowCursor(0); + // initialize the mouse + SDL_ShowCursor (0); } void VID_Init_Cvars () { - vid_fullscreen = Cvar_Get ("vid_fullscreen", "0", CVAR_ROM, "Toggles fullscreen game mode"); + vid_fullscreen = + Cvar_Get ("vid_fullscreen", "0", CVAR_ROM, + "Toggles fullscreen game mode"); } void VID_Shutdown (void) { - SDL_Quit(); + SDL_Quit (); } void VID_Update (vrect_t *rects) { - SDL_Rect *sdlrects; - int n, i; - vrect_t *rect; + SDL_Rect *sdlrects; + int n, i; + vrect_t *rect; - // Two-pass system, since Quake doesn't do it the SDL way... + // Two-pass system, since Quake doesn't do it the SDL way... - // First, count the number of rectangles - n = 0; - for (rect = rects; rect; rect = rect->pnext) - ++n; + // First, count the number of rectangles + n = 0; + for (rect = rects; rect; rect = rect->pnext) + ++n; - // Second, copy them to SDL rectangles and update - if(!(sdlrects=(SDL_Rect *)calloc(1,n*sizeof(SDL_Rect)))) - Sys_Error("Out of memory!"); - i = 0; - for (rect = rects; rect; rect = rect->pnext) { - sdlrects[i].x = rect->x; - sdlrects[i].y = rect->y; - sdlrects[i].w = rect->width; - sdlrects[i].h = rect->height; - ++i; - } - SDL_UpdateRects(screen, n, sdlrects); + // Second, copy them to SDL rectangles and update + if (!(sdlrects = (SDL_Rect *) calloc (1, n * sizeof (SDL_Rect)))) + Sys_Error ("Out of memory!"); + i = 0; + for (rect = rects; rect; rect = rect->pnext) { + sdlrects[i].x = rect->x; + sdlrects[i].y = rect->y; + sdlrects[i].w = rect->width; + sdlrects[i].h = rect->height; + ++i; + } + SDL_UpdateRects (screen, n, sdlrects); } /* @@ -215,19 +217,21 @@ D_BeginDirectRect ================ */ void -D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { - Uint8 *offset; + Uint8 *offset; - if (!screen) return; - if ( x < 0 ) x = screen->w+x-1; - offset = (Uint8 *)screen->pixels + y*screen->pitch + x; - while ( height-- ) { - memcpy(offset, pbitmap, width); - offset += screen->pitch; - pbitmap += width; - } + if (!screen) + return; + if (x < 0) + x = screen->w + x - 1; + offset = (Uint8 *) screen->pixels + y * screen->pitch + x; + while (height--) { + memcpy (offset, pbitmap, width); + offset += screen->pitch; + pbitmap += width; + } } /* @@ -238,29 +242,32 @@ D_EndDirectRect void D_EndDirectRect (int x, int y, int width, int height) { - if (!screen) return; - if (x < 0) x = screen->w+x-1; - SDL_UpdateRect(screen, x, y, width, height); + if (!screen) + return; + if (x < 0) + x = screen->w + x - 1; + SDL_UpdateRect (screen, x, y, width, height); } -void -VID_LockBuffer ( void ) +void +VID_LockBuffer (void) { -} +} void -VID_UnlockBuffer ( void ) +VID_UnlockBuffer (void) { -} +} void VID_SetCaption (char *text) { if (text && *text) { - char *temp = strdup (text); - SDL_WM_SetCaption(va ("%s %s: %s", PROGRAM, VERSION, temp), NULL); + char *temp = strdup (text); + + SDL_WM_SetCaption (va ("%s %s: %s", PROGRAM, VERSION, temp), NULL); free (temp); } else { - SDL_WM_SetCaption(va ("%s %s", PROGRAM, VERSION), NULL); + SDL_WM_SetCaption (va ("%s %s", PROGRAM, VERSION), NULL); } } diff --git a/source/vid_sgl.c b/source/vid_sgl.c index 9577783..b78614c 100644 --- a/source/vid_sgl.c +++ b/source/vid_sgl.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -#include "config.h" +# include "config.h" #endif #ifdef HAVE_STRING_H #include @@ -48,16 +48,17 @@ #define WARP_WIDTH 320 #define WARP_HEIGHT 200 -static qboolean vid_initialized = false; +static qboolean vid_initialized = false; -cvar_t *vid_fullscreen; +cvar_t *vid_fullscreen; -int VID_options_items = 1; -int modestate; +int VID_options_items = 1; +int modestate; extern void GL_Init_Common (void); extern void VID_Init8bitPalette (void); -/*-----------------------------------------------------------------------*/ + +/*-----------------------------------------------------------------------*/ void VID_Shutdown (void) @@ -72,33 +73,33 @@ VID_Shutdown (void) #ifndef WIN32 static void -signal_handler(int sig) +signal_handler (int sig) { - printf("Received signal %d, exiting...\n", sig); - Sys_Quit(); - exit(sig); + printf ("Received signal %d, exiting...\n", sig); + Sys_Quit (); + exit (sig); } static void -InitSig(void) +InitSig (void) { - signal(SIGHUP, signal_handler); - signal(SIGINT, signal_handler); - signal(SIGQUIT, signal_handler); - signal(SIGILL, signal_handler); - signal(SIGTRAP, signal_handler); - signal(SIGIOT, signal_handler); - signal(SIGBUS, signal_handler); -// signal(SIGFPE, signal_handler); - signal(SIGSEGV, signal_handler); - signal(SIGTERM, signal_handler); + signal (SIGHUP, signal_handler); + signal (SIGINT, signal_handler); + signal (SIGQUIT, signal_handler); + signal (SIGILL, signal_handler); + signal (SIGTRAP, signal_handler); + signal (SIGIOT, signal_handler); + signal (SIGBUS, signal_handler); +// signal(SIGFPE, signal_handler); + signal (SIGSEGV, signal_handler); + signal (SIGTERM, signal_handler); } #endif void GL_Init (void) { - GL_Init_Common(); + GL_Init_Common (); } void @@ -111,25 +112,25 @@ GL_EndRendering (void) void VID_Init (unsigned char *palette) { - Uint32 flags = SDL_OPENGL; - int i; + Uint32 flags = SDL_OPENGL; + int i; VID_GetWindowSize (640, 480); vid.maxwarpwidth = WARP_WIDTH; vid.maxwarpheight = WARP_HEIGHT; vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); + vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); // Interpret command-line params // Set vid parameters if ((i = COM_CheckParm ("-conwidth")) != 0) - vid.conwidth = atoi(com_argv[i+1]); + vid.conwidth = atoi (com_argv[i + 1]); else vid.conwidth = scr_width; - vid.conwidth &= 0xfff8; // make it a multiple of eight + vid.conwidth &= 0xfff8; // make it a multiple of eight if (vid.conwidth < 320) vid.conwidth = 320; @@ -137,19 +138,21 @@ VID_Init (unsigned char *palette) vid.conheight = vid.conwidth * 3 / 4; i = COM_CheckParm ("-conheight"); - if ( i != 0 ) // Set console height, but no smaller than 200 px - vid.conheight = max (atoi (com_argv[i+1]), 200); + if (i != 0) // Set console height, but no smaller + // than 200 px + vid.conheight = max (atoi (com_argv[i + 1]), 200); // Initialize the SDL library - if (SDL_Init (SDL_INIT_VIDEO) < 0) - Sys_Error ("Couldn't initialize SDL: %s\n", SDL_GetError ()); + if (SDL_Init (SDL_INIT_VIDEO) < 0) + Sys_Error ("Couldn't initialize SDL: %s\n", SDL_GetError ()); // Check if we want fullscreen if (vid_fullscreen->value) { flags |= SDL_FULLSCREEN; // Don't annoy Mesa/3dfx folks #ifndef WIN32 - // FIXME: Maybe this could be put in a different spot, but I don't know where. + // FIXME: Maybe this could be put in a different spot, but I don't + // know where. // Anyway, it's to work around a 3Dfx Glide bug. SDL_ShowCursor (0); SDL_WM_GrabInput (SDL_GRAB_ON); @@ -165,10 +168,10 @@ VID_Init (unsigned char *palette) SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 1); SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 1); - + if (SDL_SetVideoMode (scr_width, scr_height, 8, flags) == NULL) { - Sys_Error ("Couldn't set video mode: %s\n", SDL_GetError ()); - SDL_Quit (); + Sys_Error ("Couldn't set video mode: %s\n", SDL_GetError ()); + SDL_Quit (); } vid.height = vid.conheight = min (vid.conheight, scr_height); @@ -178,36 +181,36 @@ VID_Init (unsigned char *palette) vid.numpages = 2; #ifndef WIN32 - InitSig (); // trap evil signals + InitSig (); // trap evil signals #endif - GL_Init(); + GL_Init (); GL_CheckBrightness (palette); VID_SetPalette (palette); // Check for 3DFX Extensions and initialize them. - VID_Init8bitPalette(); + VID_Init8bitPalette (); - Con_Printf ("Video mode %dx%d initialized.\n", - scr_width, scr_height); + Con_Printf ("Video mode %dx%d initialized.\n", scr_width, scr_height); vid_initialized = true; - vid.recalc_refdef = 1; // force a surface cache flush + vid.recalc_refdef = 1; // force a surface cache flush } void VID_Init_Cvars () { - vid_fullscreen = Cvar_Get ("vid_fullscreen","0",0,"None"); + vid_fullscreen = Cvar_Get ("vid_fullscreen", "0", 0, "None"); } void VID_SetCaption (char *text) { if (text && *text) { - char *temp = strdup (text); + char *temp = strdup (text); + SDL_WM_SetCaption (va ("%s %s: %s", PROGRAM, VERSION, temp), NULL); free (temp); } else { diff --git a/source/vid_svgalib.c b/source/vid_svgalib.c index d9a4f6c..ecba2ba 100644 --- a/source/vid_svgalib.c +++ b/source/vid_svgalib.c @@ -32,7 +32,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "host.h" @@ -58,41 +58,42 @@ #include -void VGA_UpdatePlanarScreen (void *srcbuffer); +void VGA_UpdatePlanarScreen (void *srcbuffer); -unsigned short d_8to16table[256]; +unsigned short d_8to16table[256]; -static int num_modes, current_mode; -static vga_modeinfo *modes; +static int num_modes, current_mode; +static vga_modeinfo *modes; static byte vid_current_palette[768]; -static int svgalib_inited=0; -static int svgalib_backgrounded=0; -static int UseDisplay = 1; +static int svgalib_inited = 0; +static int svgalib_backgrounded = 0; +static int UseDisplay = 1; -static cvar_t *vid_mode; -static cvar_t *vid_redrawfull; -static cvar_t *vid_waitforrefresh; +static cvar_t *vid_mode; +static cvar_t *vid_redrawfull; +static cvar_t *vid_waitforrefresh; -static char *framebuffer_ptr; +static char *framebuffer_ptr; -static byte backingbuf[48*24]; +static byte backingbuf[48 * 24]; -int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; -byte *VGA_pagebase; +int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes, VGA_planar; +byte *VGA_pagebase; -int VID_options_items = 0; +int VID_options_items = 0; void -D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { - int i, j, k, plane, reps, repshift, offset, vidpage, off; + int i, j, k, plane, reps, repshift, offset, vidpage, off; - if (!svgalib_inited || !vid.direct || svgalib_backgrounded || !vga_oktowrite()) return; + if (!svgalib_inited || !vid.direct || svgalib_backgrounded + || !vga_oktowrite ())return; if (vid.aspect > 1.5) { reps = 2; @@ -103,44 +104,41 @@ D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) } vidpage = 0; - vga_setpage(0); + vga_setpage (0); if (VGA_planar) { - for (plane=0 ; plane<4 ; plane++) { + for (plane = 0; plane < 4; plane++) { /* Select the correct plane for reading and writing */ - outb(0x02, 0x3C4); - outb(1 << plane, 0x3C5); - outb(4, 0x3CE); - outb(plane, 0x3CF); + outb (0x02, 0x3C4); + outb (1 << plane, 0x3C5); + outb (4, 0x3CE); + outb (plane, 0x3CF); - for (i=0 ; i<(height << repshift) ; i += reps) { - for (k=0 ; k> 2) ; j++) { + for (i = 0; i < (height << repshift); i += reps) { + for (k = 0; k < reps; k++) { + for (j = 0; j < (width >> 2); j++) { backingbuf[(i + k) * 24 + (j << 2) + plane] = vid.direct[(y + i + k) * VGA_rowbytes + - (x >> 2) + j]; - vid.direct[(y + i + k) * VGA_rowbytes + (x>>2) + j] = - pbitmap[(i >> repshift) * 24 + - (j << 2) + plane]; + (x >> 2) + j]; + vid.direct[(y + i + k) * VGA_rowbytes + (x >> 2) + j] = + pbitmap[(i >> repshift) * 24 + (j << 2) + plane]; } } } } } else { - for (i=0 ; i<(height << repshift) ; i += reps) { - for (j=0 ; j> repshift)*width], - width); + &pbitmap[(i >> repshift) * width], width); } } } @@ -150,9 +148,10 @@ D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) void D_EndDirectRect (int x, int y, int width, int height) { - int i, j, k, plane, reps, repshift, offset, vidpage, off; + int i, j, k, plane, reps, repshift, offset, vidpage, off; - if (!svgalib_inited || !vid.direct || svgalib_backgrounded || !vga_oktowrite()) return; + if (!svgalib_inited || !vid.direct || svgalib_backgrounded + || !vga_oktowrite ())return; if (vid.aspect > 1.5) { reps = 2; @@ -163,37 +162,36 @@ D_EndDirectRect (int x, int y, int width, int height) } vidpage = 0; - vga_setpage(0); + vga_setpage (0); if (VGA_planar) { - for (plane=0 ; plane<4 ; plane++) { + for (plane = 0; plane < 4; plane++) { /* Select the correct plane for writing */ - outb(2, 0x3C4); - outb(1 << plane, 0x3C5); - outb(4, 0x3CE); - outb(plane, 0x3CF); + outb (2, 0x3C4); + outb (1 << plane, 0x3C5); + outb (4, 0x3CE); + outb (plane, 0x3CF); - for (i=0 ; i<(height << repshift) ; i += reps) { - for (k=0 ; k> 2) ; j++) { - vid.direct[(y + i + k) * VGA_rowbytes + (x>>2) + j] = + for (i = 0; i < (height << repshift); i += reps) { + for (k = 0; k < reps; k++) { + for (j = 0; j < (width >> 2); j++) { + vid.direct[(y + i + k) * VGA_rowbytes + (x >> 2) + j] = backingbuf[(i + k) * 24 + (j << 2) + plane]; } } } } } else { - for (i=0 ; i<(height << repshift) ; i += reps) { - for (j=0 ; j 255) inf = 255; + for (i = 0; i < 768; i++) { + f = pow ((host_basepal[i] + 1) / 256.0, gamma); + inf = f * 255 + 0.5; + if (inf < 0) + inf = 0; + if (inf > 255) + inf = 255; palette[i] = inf; } @@ -229,37 +229,36 @@ VID_Gamma_f(void) static void -VID_DescribeMode_f(void) +VID_DescribeMode_f (void) { - int modenum; + int modenum; - modenum = atoi (Cmd_Argv(1)); - if ((modenum >= num_modes) || (modenum < 0 ) || - !modes[modenum].width) { - Con_Printf("Invalid video mode: %d!\n", modenum); + modenum = atoi (Cmd_Argv (1)); + if ((modenum >= num_modes) || (modenum < 0) || !modes[modenum].width) { + Con_Printf ("Invalid video mode: %d!\n", modenum); } - Con_Printf("%d: %d x %d - ", modenum, - modes[modenum].width, modes[modenum].height); + Con_Printf ("%d: %d x %d - ", modenum, + modes[modenum].width, modes[modenum].height); if (modes[modenum].bytesperpixel == 0) { - Con_Printf("ModeX\n"); + Con_Printf ("ModeX\n"); } else { - Con_Printf("%d bpp\n", modes[modenum].bytesperpixel<<3); + Con_Printf ("%d bpp\n", modes[modenum].bytesperpixel << 3); } } static void -VID_DescribeModes_f(void) +VID_DescribeModes_f (void) { - int i; + int i; - for (i=0;i> 2; } - if (UseDisplay && vga_oktowrite()) { - vga_setpalvec(0, 256, tmppal); + if (UseDisplay && vga_oktowrite ()) { + vga_setpalvec (0, 256, tmppal); } } } @@ -466,12 +461,12 @@ VID_SetPalette(byte *palette) int VID_SetMode (int modenum, unsigned char *palette) { - int err; + int err; if ((modenum >= num_modes) || (modenum < 0) || !modes[modenum].width) { - Cvar_SetValue(vid_mode, current_mode); + Cvar_SetValue (vid_mode, current_mode); - Con_Printf("No such video mode: %d\n",modenum); + Con_Printf ("No such video mode: %d\n", modenum); return 0; } @@ -490,12 +485,12 @@ VID_SetMode (int modenum, unsigned char *palette) vid.rowbytes = modes[current_mode].linewidth; if (VGA_planar) { VGA_bufferrowbytes = modes[current_mode].linewidth * 4; - vid.rowbytes = modes[current_mode].linewidth*4; + vid.rowbytes = modes[current_mode].linewidth * 4; } - vid.aspect = ((float)vid.height / (float)vid.width) * (320.0 / 240.0); + vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); vid.colormap = (pixel_t *) host_colormap; - vid.fullbright = 256 - LittleLong (*((int *)vid.colormap + 2048)); + vid.fullbright = 256 - LittleLong (*((int *) vid.colormap + 2048)); vid.conrowbytes = vid.rowbytes; vid.conwidth = vid.width; vid.conheight = vid.height; @@ -508,23 +503,23 @@ VID_SetMode (int modenum, unsigned char *palette) VID_InitBuffers (); /* get goin' */ - err = vga_setmode(current_mode); + err = vga_setmode (current_mode); if (err) { - Sys_Error("Video mode failed: %d\n",modenum); + Sys_Error ("Video mode failed: %d\n", modenum); } - VID_SetPalette(palette); + VID_SetPalette (palette); - VGA_pagebase = vid.direct = framebuffer_ptr = (char *) vga_getgraphmem(); + VGA_pagebase = vid.direct = framebuffer_ptr = (char *) vga_getgraphmem (); #if 0 - if (vga_setlinearaddressing() > 0) { - framebuffer_ptr = (char *) vga_getgraphmem(); + if (vga_setlinearaddressing () > 0) { + framebuffer_ptr = (char *) vga_getgraphmem (); } #endif if (!framebuffer_ptr) { - Sys_Error("This mode isn't hapnin'\n"); + Sys_Error ("This mode isn't hapnin'\n"); } - vga_setpage(0); + vga_setpage (0); svgalib_inited = 1; @@ -548,23 +543,24 @@ comefrom_background (void) void -VID_Init(unsigned char *palette) +VID_Init (unsigned char *palette) { - int w, h, d; - int err; + int w, h, d; + int err; - //plugin_load("in_svgalib.so"); + // plugin_load("in_svgalib.so"); - if (svgalib_inited) return; + if (svgalib_inited) + return; #if 0 Cmd_AddCommand ("gamma", VID_Gamma_f); #endif if (UseDisplay) { - err = vga_init(); + err = vga_init (); if (err) - Sys_Error("SVGALib failed to allocate a new VC\n"); + Sys_Error ("SVGALib failed to allocate a new VC\n"); if (vga_runinbackground_version () == 1) { Con_Printf ("SVGALIB background support detected\n"); @@ -575,84 +571,85 @@ VID_Init(unsigned char *palette) vga_runinbackground (0); } - VID_InitModes(); + VID_InitModes (); - Cmd_AddCommand("vid_nummodes", VID_NumModes_f); - Cmd_AddCommand("vid_describemode", VID_DescribeMode_f); - Cmd_AddCommand("vid_describemodes", VID_DescribeModes_f); - Cmd_AddCommand("vid_debug", VID_Debug_f); + Cmd_AddCommand ("vid_nummodes", VID_NumModes_f); + Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f); + Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f); + Cmd_AddCommand ("vid_debug", VID_Debug_f); /* Interpret command-line params */ w = h = d = 0; - if (getenv("GSVGAMODE")) { - current_mode = get_mode(getenv("GSVGAMODE"), w, h, d); - } else if (COM_CheckParm("-mode")) { - current_mode = get_mode(com_argv[COM_CheckParm("-mode")+1], w, h, d); - } else if (COM_CheckParm("-w") || COM_CheckParm("-h") - || COM_CheckParm("-d")) { - if (COM_CheckParm("-w")) { - w = atoi(com_argv[COM_CheckParm("-w")+1]); + if (getenv ("GSVGAMODE")) { + current_mode = get_mode (getenv ("GSVGAMODE"), w, h, d); + } else if (COM_CheckParm ("-mode")) { + current_mode = + get_mode (com_argv[COM_CheckParm ("-mode") + 1], w, h, d); + } else if (COM_CheckParm ("-w") || COM_CheckParm ("-h") + || COM_CheckParm ("-d")) { + if (COM_CheckParm ("-w")) { + w = atoi (com_argv[COM_CheckParm ("-w") + 1]); } - if (COM_CheckParm("-h")) { - h = atoi(com_argv[COM_CheckParm("-h")+1]); + if (COM_CheckParm ("-h")) { + h = atoi (com_argv[COM_CheckParm ("-h") + 1]); } - if (COM_CheckParm("-d")) { - d = atoi(com_argv[COM_CheckParm("-d")+1]); + if (COM_CheckParm ("-d")) { + d = atoi (com_argv[COM_CheckParm ("-d") + 1]); } - current_mode = get_mode(0, w, h, d); + current_mode = get_mode (0, w, h, d); } else { current_mode = G320x200x256; } /* Set vid parameters */ - VID_SetMode(current_mode, palette); + VID_SetMode (current_mode, palette); - VID_SetPalette(palette); + VID_SetPalette (palette); } } void VID_Init_Cvars () { - vid_mode = Cvar_Get ("vid_mode","5",0,"None"); - vid_redrawfull = Cvar_Get ("vid_redrawfull","0",0,"None"); - vid_waitforrefresh = Cvar_Get ("vid_waitforrefresh","0", - CVAR_ARCHIVE,"None"); + vid_mode = Cvar_Get ("vid_mode", "5", 0, "None"); + vid_redrawfull = Cvar_Get ("vid_redrawfull", "0", 0, "None"); + vid_waitforrefresh = Cvar_Get ("vid_waitforrefresh", "0", + CVAR_ARCHIVE, "None"); } void -VID_Update(vrect_t *rects) +VID_Update (vrect_t *rects) { - if (!svgalib_inited || svgalib_backgrounded) return; + if (!svgalib_inited || svgalib_backgrounded) + return; - if (!vga_oktowrite()) { + if (!vga_oktowrite ()) { /* Can't update screen if it's not active */ return; } if (vid_waitforrefresh->int_val) { - vga_waitretrace(); + vga_waitretrace (); } if (VGA_planar) { - VGA_UpdatePlanarScreen(vid.buffer); + VGA_UpdatePlanarScreen (vid.buffer); } else if (vid_redrawfull->int_val) { - int total = vid.rowbytes * vid.height; - int offset; + int total = vid.rowbytes * vid.height; + int offset; - for (offset=0;offset0x10000) - ? 0x10000 : (total-offset))); + for (offset = 0; offset < total; offset += 0x10000) { + vga_setpage (offset / 0x10000); + memcpy (framebuffer_ptr, vid.buffer + offset, + ((total - offset > 0x10000) ? 0x10000 : (total - offset))); } } else { - int ycount; - int offset; - int vidpage=0; + int ycount; + int offset; + int vidpage = 0; - vga_setpage(0); + vga_setpage (0); while (rects) { ycount = rects->height; @@ -661,21 +658,19 @@ VID_Update(vrect_t *rects) register int i = offset % 0x10000; if ((offset / 0x10000) != vidpage) { - vidpage=offset / 0x10000; - vga_setpage(vidpage); + vidpage = offset / 0x10000; + vga_setpage (vidpage); } if (rects->width + i > 0x10000) { - memcpy(framebuffer_ptr + i, - vid.buffer + offset, - 0x10000 - i); - vga_setpage(++vidpage); - memcpy(framebuffer_ptr, + memcpy (framebuffer_ptr + i, + vid.buffer + offset, 0x10000 - i); + vga_setpage (++vidpage); + memcpy (framebuffer_ptr, vid.buffer + offset + 0x10000 - i, rects->width - 0x10000 + i); } else { - memcpy(framebuffer_ptr + i, - vid.buffer + offset, - rects->width); + memcpy (framebuffer_ptr + i, + vid.buffer + offset, rects->width); } offset += vid.rowbytes; } @@ -689,10 +684,10 @@ VID_Update(vrect_t *rects) } -static int dither = 0; +static int dither = 0; void -VID_DitherOn(void) +VID_DitherOn (void) { if (dither == 0) { #if 0 @@ -704,7 +699,7 @@ VID_DitherOn(void) void -VID_DitherOff(void) +VID_DitherOff (void) { if (dither) { #if 0 @@ -720,15 +715,15 @@ VID_DitherOff(void) VID_ModeInfo ================ */ -char * +char * VID_ModeInfo (int modenum) { static char *badmodestr = "Bad mode number"; - static char modestr[40]; + static char modestr[40]; if (modenum == 0) { - snprintf(modestr, sizeof(modestr), "%d x %d, %d bpp", - vid.width, vid.height, modes[current_mode].bytesperpixel*8); + snprintf (modestr, sizeof (modestr), "%d x %d, %d bpp", + vid.width, vid.height, modes[current_mode].bytesperpixel * 8); return (modestr); } else { return (badmodestr); @@ -737,33 +732,34 @@ VID_ModeInfo (int modenum) void -VID_ExtraOptionDraw(unsigned int options_draw_cursor) +VID_ExtraOptionDraw (unsigned int options_draw_cursor) { /* No extra option menu items yet */ } void -VID_ExtraOptionCmd(int option_cursor) +VID_ExtraOptionCmd (int option_cursor) { #if 0 - switch(option_cursor) { - case 1: // Always start with 1 - break; - } + switch (option_cursor) { + case 1: // Always start with 1 + break; + } #endif } -void -VID_LockBuffer ( void ) -{ -} - void -VID_UnlockBuffer ( void ) -{ -} - -void VID_SetCaption (char *text) +VID_LockBuffer (void) +{ +} + +void +VID_UnlockBuffer (void) +{ +} + +void +VID_SetCaption (char *text) { } diff --git a/source/vid_wgl.c b/source/vid_wgl.c index b5d8e03..46f47d6 100644 --- a/source/vid_wgl.c +++ b/source/vid_wgl.c @@ -47,8 +47,8 @@ #include "sbar.h" #include "host.h" -extern void (*vid_menudrawfn)(void); -extern void (*vid_menukeyfn)(int); +extern void (*vid_menudrawfn) (void); +extern void (*vid_menukeyfn) (int); #define MAX_MODE_LIST 30 #define VID_ROW_SIZE 3 @@ -64,23 +64,23 @@ extern void (*vid_menukeyfn)(int); #define MODE_FULLSCREEN_DEFAULT (MODE_WINDOWED + 1) typedef struct { - modestate_t type; - int width; - int height; - int modenum; - int dib; - int fullscreen; - int bpp; - int halfscreen; - char modedesc[17]; + modestate_t type; + int width; + int height; + int modenum; + int dib; + int fullscreen; + int bpp; + int halfscreen; + char modedesc[17]; } vmode_t; typedef struct { - int width; - int height; + int width; + int height; } lmode_t; -lmode_t lowresmodes[] = { +lmode_t lowresmodes[] = { {320, 200}, {320, 240}, {400, 300}, @@ -92,133 +92,144 @@ const char *gl_renderer; const char *gl_version; const char *gl_extensions; -qboolean DDActive; -qboolean scr_skipupdate; +qboolean DDActive; +qboolean scr_skipupdate; -static vmode_t modelist[MAX_MODE_LIST]; -static int nummodes; -static vmode_t *pcurrentmode; -static vmode_t badmode; +static vmode_t modelist[MAX_MODE_LIST]; +static int nummodes; +static vmode_t *pcurrentmode; +static vmode_t badmode; -static DEVMODE gdevmode; -static qboolean vid_initialized = false; -static qboolean windowed, leavecurrentmode; +static DEVMODE gdevmode; +static qboolean vid_initialized = false; +static qboolean windowed, leavecurrentmode; static qboolean vid_canalttab = false; static qboolean vid_wassuspended = false; -static int windowed_mouse; -static HICON hIcon; +static int windowed_mouse; +static HICON hIcon; -int DIBWidth, DIBHeight; -RECT WindowRect; -DWORD WindowStyle, ExWindowStyle; +int DIBWidth, DIBHeight; +RECT WindowRect; +DWORD WindowStyle, ExWindowStyle; -HWND mainwindow, dibwindow; +HWND mainwindow, dibwindow; -int vid_modenum = NO_MODE; -int vid_realmode; -int vid_default = MODE_WINDOWED; -static int windowed_default; -unsigned char vid_curpal[256*3]; +int vid_modenum = NO_MODE; +int vid_realmode; +int vid_default = MODE_WINDOWED; +static int windowed_default; +unsigned char vid_curpal[256 * 3]; static qboolean fullsbardraw = true; -HGLRC baseRC; -HDC maindc; +HGLRC baseRC; +HDC maindc; -glvert_t glv; +glvert_t glv; HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow); -extern viddef_t vid; // global video state +extern viddef_t vid; // global video state -unsigned short d_8to16table[256]; -unsigned int d_8to24table[256]; +unsigned short d_8to16table[256]; +unsigned int d_8to24table[256]; unsigned char d_15to8table[65536]; -float gldepthmin, gldepthmax; +float gldepthmin, gldepthmax; -modestate_t modestate = MS_UNINIT; +modestate_t modestate = MS_UNINIT; -void VID_MenuDraw (void); -void VID_MenuKey (int key); +void VID_MenuDraw (void); +void VID_MenuKey (int key); LONG WINAPI MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); -void AppActivate(BOOL fActive, BOOL minimize); -char *VID_GetModeDescription (int mode); -void ClearAllStates (void); -void VID_UpdateWindowStatus (void); -void GL_Init (void); +void AppActivate (BOOL fActive, BOOL minimize); +char *VID_GetModeDescription (int mode); +void ClearAllStates (void); +void VID_UpdateWindowStatus (void); +void GL_Init (void); -PROC glArrayElementEXT; -PROC glColorPointerEXT; -PROC glTexCoordPointerEXT; -PROC glVertexPointerEXT; +PROC glArrayElementEXT; +PROC glColorPointerEXT; +PROC glTexCoordPointerEXT; +PROC glVertexPointerEXT; -typedef void (APIENTRY *lp3DFXFUNC) (int, int, int, int, int, const void*); -lp3DFXFUNC glColorTableEXT; -qboolean is8bit = false; -qboolean isPermedia = false; -int gl_mtex_enum = TEXTURE0_SGIS; -qboolean gl_arb_mtex = false; -qboolean gl_mtexable = false; +typedef void (APIENTRY * lp3DFXFUNC) (int, int, int, int, int, const void *); +lp3DFXFUNC glColorTableEXT; +qboolean is8bit = false; +qboolean isPermedia = false; +int gl_mtex_enum = TEXTURE0_SGIS; +qboolean gl_arb_mtex = false; +qboolean gl_mtexable = false; //==================================== -cvar_t *_windowed_mouse; +cvar_t *_windowed_mouse; -int window_center_x, window_center_y, window_x, window_y, window_width, window_height; -RECT window_rect; +int window_center_x, window_center_y, window_x, window_y, window_width, + + window_height; +RECT window_rect; // direct draw software compatability stuff -void VID_HandlePause (qboolean pause) +void +VID_HandlePause (qboolean pause) { } -void VID_ForceLockState (int lk) +void +VID_ForceLockState (int lk) { } -void VID_LockBuffer (void) +void +VID_LockBuffer (void) { } -void VID_UnlockBuffer (void) +void +VID_UnlockBuffer (void) { } -int VID_ForceUnlockedAndReturnState (void) +int +VID_ForceUnlockedAndReturnState (void) { return 0; } -void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +void +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { } -void D_EndDirectRect (int x, int y, int width, int height) +void +D_EndDirectRect (int x, int y, int width, int height) { } -void CenterWindow(HWND hWndCenter, int width, int height, BOOL lefttopjustify) +void +CenterWindow (HWND hWndCenter, int width, int height, BOOL lefttopjustify) { - int CenterX, CenterY; + int CenterX, CenterY; - CenterX = (GetSystemMetrics(SM_CXSCREEN) - width) / 2; - CenterY = (GetSystemMetrics(SM_CYSCREEN) - height) / 2; - if (CenterX > CenterY*2) - CenterX >>= 1; // dual screens - CenterX = (CenterX < 0) ? 0: CenterX; - CenterY = (CenterY < 0) ? 0: CenterY; + CenterX = (GetSystemMetrics (SM_CXSCREEN) - width) / 2; + CenterY = (GetSystemMetrics (SM_CYSCREEN) - height) / 2; + if (CenterX > CenterY * 2) + CenterX >>= 1; // dual screens + CenterX = (CenterX < 0) ? 0 : CenterX; + CenterY = (CenterY < 0) ? 0 : CenterY; SetWindowPos (hWndCenter, NULL, CenterX, CenterY, 0, 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME); + SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME); } -qboolean VID_SetWindowedMode (int modenum) +qboolean +VID_SetWindowedMode (int modenum) { - HDC hdc; - int lastmodestate, width, height; - RECT rect; + HDC hdc; + int lastmodestate, width, height; + RECT rect; lastmodestate = modestate; @@ -231,35 +242,30 @@ qboolean VID_SetWindowedMode (int modenum) DIBHeight = modelist[modenum].height; WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | - WS_MINIMIZEBOX; + WS_MINIMIZEBOX; ExWindowStyle = 0; rect = WindowRect; - AdjustWindowRectEx(&rect, WindowStyle, FALSE, 0); + AdjustWindowRectEx (&rect, WindowStyle, FALSE, 0); width = rect.right - rect.left; height = rect.bottom - rect.top; // Create the DIB window - dibwindow = CreateWindowEx ( - ExWindowStyle, - "WinQuake", - "GLQuake", - WindowStyle, - rect.left, rect.top, - width, - height, - NULL, - NULL, - global_hInstance, - NULL); + dibwindow = CreateWindowEx (ExWindowStyle, + "WinQuake", + "GLQuake", + WindowStyle, + rect.left, rect.top, + width, + height, NULL, NULL, global_hInstance, NULL); if (!dibwindow) Sys_Error ("Couldn't create DIB window"); // Center and show the DIB window - CenterWindow(dibwindow, WindowRect.right - WindowRect.left, - WindowRect.bottom - WindowRect.top, false); + CenterWindow (dibwindow, WindowRect.right - WindowRect.left, + WindowRect.bottom - WindowRect.top, false); ShowWindow (dibwindow, SW_SHOWDEFAULT); UpdateWindow (dibwindow); @@ -270,9 +276,9 @@ qboolean VID_SetWindowedMode (int modenum) // (to avoid flickering when re-sizing the window on the desktop), // we clear the window to black when created, otherwise it will be // empty while Quake starts up. - hdc = GetDC(dibwindow); - PatBlt(hdc,0,0,WindowRect.right,WindowRect.bottom,BLACKNESS); - ReleaseDC(dibwindow, hdc); + hdc = GetDC (dibwindow); + PatBlt (hdc, 0, 0, WindowRect.right, WindowRect.bottom, BLACKNESS); + ReleaseDC (dibwindow, hdc); if (vid.conheight > modelist[modenum].height) vid.conheight = modelist[modenum].height; @@ -285,30 +291,31 @@ qboolean VID_SetWindowedMode (int modenum) mainwindow = dibwindow; - SendMessage (mainwindow, WM_SETICON, (WPARAM)TRUE, (LPARAM)hIcon); - SendMessage (mainwindow, WM_SETICON, (WPARAM)FALSE, (LPARAM)hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) TRUE, (LPARAM) hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) FALSE, (LPARAM) hIcon); return true; } -qboolean VID_SetFullDIBMode (int modenum) +qboolean +VID_SetFullDIBMode (int modenum) { - HDC hdc; - int lastmodestate, width, height; - RECT rect; + HDC hdc; + int lastmodestate, width, height; + RECT rect; - if (!leavecurrentmode) - { + if (!leavecurrentmode) { gdevmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; gdevmode.dmBitsPerPel = modelist[modenum].bpp; gdevmode.dmPelsWidth = modelist[modenum].width << - modelist[modenum].halfscreen; + modelist[modenum].halfscreen; gdevmode.dmPelsHeight = modelist[modenum].height; gdevmode.dmSize = sizeof (gdevmode); - if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) - Sys_Error ("Couldn't set fullscreen DIB mode"); + if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != + DISP_CHANGE_SUCCESSFUL) + Sys_Error ("Couldn't set fullscreen DIB mode"); } lastmodestate = modestate; @@ -326,24 +333,19 @@ qboolean VID_SetFullDIBMode (int modenum) ExWindowStyle = 0; rect = WindowRect; - AdjustWindowRectEx(&rect, WindowStyle, FALSE, 0); + AdjustWindowRectEx (&rect, WindowStyle, FALSE, 0); width = rect.right - rect.left; height = rect.bottom - rect.top; // Create the DIB window - dibwindow = CreateWindowEx ( - ExWindowStyle, - "WinQuake", - "GLQuake", - WindowStyle, - rect.left, rect.top, - width, - height, - NULL, - NULL, - global_hInstance, - NULL); + dibwindow = CreateWindowEx (ExWindowStyle, + "WinQuake", + "GLQuake", + WindowStyle, + rect.left, rect.top, + width, + height, NULL, NULL, global_hInstance, NULL); if (!dibwindow) Sys_Error ("Couldn't create DIB window"); @@ -355,9 +357,9 @@ qboolean VID_SetFullDIBMode (int modenum) // (to avoid flickering when re-sizing the window on the desktop), we // clear the window to black when created, otherwise it will be // empty while Quake starts up. - hdc = GetDC(dibwindow); - PatBlt(hdc,0,0,WindowRect.right,WindowRect.bottom,BLACKNESS); - ReleaseDC(dibwindow, hdc); + hdc = GetDC (dibwindow); + PatBlt (hdc, 0, 0, WindowRect.right, WindowRect.bottom, BLACKNESS); + ReleaseDC (dibwindow, hdc); if (vid.conheight > modelist[modenum].height) vid.conheight = modelist[modenum].height; @@ -374,26 +376,24 @@ qboolean VID_SetFullDIBMode (int modenum) mainwindow = dibwindow; - SendMessage (mainwindow, WM_SETICON, (WPARAM)TRUE, (LPARAM)hIcon); - SendMessage (mainwindow, WM_SETICON, (WPARAM)FALSE, (LPARAM)hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) TRUE, (LPARAM) hIcon); + SendMessage (mainwindow, WM_SETICON, (WPARAM) FALSE, (LPARAM) hIcon); return true; } -int VID_SetMode (int modenum, unsigned char *palette) +int +VID_SetMode (int modenum, unsigned char *palette) { - int original_mode, temp; - qboolean stat; - MSG msg; + int original_mode, temp; + qboolean stat; + MSG msg; if ((windowed && (modenum != 0)) || - (!windowed && (modenum < 1)) || - (!windowed && (modenum >= nummodes))) - { + (!windowed && (modenum < 1)) || (!windowed && (modenum >= nummodes))) { Sys_Error ("Bad video mode\n"); } - // so Con_Printfs don't mess us up by forcing vid and snd updates temp = scr_disabled_for_loading; scr_disabled_for_loading = true; @@ -406,29 +406,21 @@ int VID_SetMode (int modenum, unsigned char *palette) original_mode = vid_modenum; // Set either the fullscreen or windowed mode - if (modelist[modenum].type == MS_WINDOWED) - { - if (_windowed_mouse->int_val && key_dest == key_game) - { - stat = VID_SetWindowedMode(modenum); + if (modelist[modenum].type == MS_WINDOWED) { + if (_windowed_mouse->int_val && key_dest == key_game) { + stat = VID_SetWindowedMode (modenum); IN_ActivateMouse (); IN_HideMouse (); - } - else - { + } else { IN_DeactivateMouse (); IN_ShowMouse (); - stat = VID_SetWindowedMode(modenum); + stat = VID_SetWindowedMode (modenum); } - } - else if (modelist[modenum].type == MS_FULLDIB) - { - stat = VID_SetFullDIBMode(modenum); + } else if (modelist[modenum].type == MS_FULLDIB) { + stat = VID_SetFullDIBMode (modenum); IN_ActivateMouse (); IN_HideMouse (); - } - else - { + } else { Sys_Error ("VID_SetMode: Bad mode type in modelist"); } @@ -439,11 +431,9 @@ int VID_SetMode (int modenum, unsigned char *palette) CDAudio_Resume (); scr_disabled_for_loading = temp; - if (!stat) - { + if (!stat) { Sys_Error ("Couldn't set video mode"); } - // now we try to make sure we get the focus on the mode switch, because // sometimes in some systems we don't. We grab the foreground, then // finish setting up, pump all our messages, and sleep for a little while @@ -454,10 +444,9 @@ int VID_SetMode (int modenum, unsigned char *palette) VID_SetPalette (palette); vid_modenum = modenum; - while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) - { - TranslateMessage (&msg); - DispatchMessage (&msg); + while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage (&msg); + DispatchMessage (&msg); } Sleep (100); @@ -472,7 +461,8 @@ int VID_SetMode (int modenum, unsigned char *palette) ClearAllStates (); if (!msg_suppress_1) - Con_Printf ("Video mode %s initialized.\n", VID_GetModeDescription (vid_modenum)); + Con_Printf ("Video mode %s initialized.\n", + VID_GetModeDescription (vid_modenum)); VID_SetPalette (palette); @@ -487,7 +477,8 @@ int VID_SetMode (int modenum, unsigned char *palette) VID_UpdateWindowStatus ================ */ -void VID_UpdateWindowStatus (void) +void +VID_UpdateWindowStatus (void) { window_rect.left = window_x; @@ -502,22 +493,29 @@ void VID_UpdateWindowStatus (void) -void CheckArrayExtensions (void) +void +CheckArrayExtensions (void) { - char *tmp; + char *tmp; /* check for texture extension */ - tmp = (unsigned char *)glGetString(GL_EXTENSIONS); - while (*tmp) - { - if (strncmp((const char*)tmp, "GL_EXT_vertex_array", strlen("GL_EXT_vertex_array")) == 0) - { + tmp = (unsigned char *) glGetString (GL_EXTENSIONS); + while (*tmp) { + if (strncmp + ((const char *) tmp, "GL_EXT_vertex_array", + strlen ("GL_EXT_vertex_array")) == 0) { if ( -((glArrayElementEXT = wglGetProcAddress("glArrayElementEXT")) == NULL) || -((glColorPointerEXT = wglGetProcAddress("glColorPointerEXT")) == NULL) || -((glTexCoordPointerEXT = wglGetProcAddress("glTexCoordPointerEXT")) == NULL) || -((glVertexPointerEXT = wglGetProcAddress("glVertexPointerEXT")) == NULL) ) - { + ((glArrayElementEXT = wglGetProcAddress ("glArrayElementEXT")) + == NULL) + || + ((glColorPointerEXT = wglGetProcAddress ("glColorPointerEXT")) + == NULL) + || + ((glTexCoordPointerEXT + = wglGetProcAddress ("glTexCoordPointerEXT")) == NULL) + || + ((glVertexPointerEXT = wglGetProcAddress ("glVertexPointerEXT")) + == NULL)) { Sys_Error ("GetProcAddress for vertex extension failed"); return; } @@ -529,51 +527,43 @@ void CheckArrayExtensions (void) Sys_Error ("Vertex array extension not present"); } -//int texture_mode = GL_NEAREST; -//int texture_mode = GL_NEAREST_MIPMAP_NEAREST; -//int texture_mode = GL_NEAREST_MIPMAP_LINEAR; -int texture_mode = GL_LINEAR; -//int texture_mode = GL_LINEAR_MIPMAP_NEAREST; -//int texture_mode = GL_LINEAR_MIPMAP_LINEAR; +//int texture_mode = GL_NEAREST; +//int texture_mode = GL_NEAREST_MIPMAP_NEAREST; +//int texture_mode = GL_NEAREST_MIPMAP_LINEAR; +int texture_mode = GL_LINEAR; -int texture_extension_number = 1; +//int texture_mode = GL_LINEAR_MIPMAP_NEAREST; +//int texture_mode = GL_LINEAR_MIPMAP_LINEAR; + +int texture_extension_number = 1; #ifdef _WIN32 -void CheckMultiTextureExtensions(void) +void +CheckMultiTextureExtensions (void) { - Con_Printf("Checking for multitexture... "); - if (COM_CheckParm ("-nomtex")) - { + Con_Printf ("Checking for multitexture... "); + if (COM_CheckParm ("-nomtex")) { Con_Printf ("disabled\n"); return; } - if (strstr(gl_extensions, "GL_ARB_multitexture ")) - { + if (strstr (gl_extensions, "GL_ARB_multitexture ")) { Con_Printf ("GL_ARB_multitexture\n"); - qglMTexCoord2f = - (void *)wglGetProcAddress("glMultiTexCoord2fARB"); - qglSelectTexture = - (void *)wglGetProcAddress("glActiveTextureARB"); + qglMTexCoord2f = (void *) wglGetProcAddress ("glMultiTexCoord2fARB"); + qglSelectTexture = (void *) wglGetProcAddress ("glActiveTextureARB"); gl_mtex_enum = GL_TEXTURE0_ARB; gl_mtexable = true; gl_arb_mtex = true; - } else if (strstr(gl_extensions, "GL_SGIS_multitexture ")) - { + } else if (strstr (gl_extensions, "GL_SGIS_multitexture ")) { Con_Printf ("GL_SGIS_multitexture\n"); - qglMTexCoord2f = - (void *)wglGetProcAddress("glMTexCoord2fSGIS"); - qglSelectTexture = - (void *)wglGetProcAddress("glSelectTextureSGIS"); + qglMTexCoord2f = (void *) wglGetProcAddress ("glMTexCoord2fSGIS"); + qglSelectTexture = (void *) wglGetProcAddress ("glSelectTextureSGIS"); gl_mtex_enum = TEXTURE0_SGIS; gl_mtexable = true; gl_arb_mtex = false; - } else if (strstr(gl_extensions, "GL_EXT_multitexture ")) - { + } else if (strstr (gl_extensions, "GL_EXT_multitexture ")) { Con_Printf ("GL_EXT_multitexture\n"); - qglMTexCoord2f = - (void *)wglGetProcAddress("glMTexCoord2fEXT"); - qglSelectTexture = - (void *)wglGetProcAddress("glSelectTextureEXT"); + qglMTexCoord2f = (void *) wglGetProcAddress ("glMTexCoord2fEXT"); + qglSelectTexture = (void *) wglGetProcAddress ("glSelectTextureEXT"); gl_mtex_enum = TEXTURE0_SGIS; gl_mtexable = true; gl_arb_mtex = false; @@ -582,9 +572,10 @@ void CheckMultiTextureExtensions(void) } } #else -void CheckMultiTextureExtensions(void) +void +CheckMultiTextureExtensions (void) { - gl_mtexable = true; + gl_mtexable = true; } #endif @@ -593,7 +584,8 @@ void CheckMultiTextureExtensions(void) GL_Init =============== */ -void GL_Init (void) +void +GL_Init (void) { gl_vendor = glGetString (GL_VENDOR); Con_Printf ("GL_VENDOR: %s\n", gl_vendor); @@ -605,36 +597,36 @@ void GL_Init (void) gl_extensions = glGetString (GL_EXTENSIONS); Con_Printf ("GL_EXTENSIONS: %s\n", gl_extensions); -// Con_Printf ("%s %s\n", gl_renderer, gl_version); +// Con_Printf ("%s %s\n", gl_renderer, gl_version); - if (strnicmp(gl_renderer,"PowerVR",7)==0) - fullsbardraw = true; + if (strnicmp (gl_renderer, "PowerVR", 7) == 0) + fullsbardraw = true; - if (strnicmp(gl_renderer,"Permedia",8)==0) - isPermedia = true; + if (strnicmp (gl_renderer, "Permedia", 8) == 0) + isPermedia = true; CheckMultiTextureExtensions (); - glClearColor (0,0,0,0); - glCullFace(GL_FRONT); - glEnable(GL_TEXTURE_2D); + glClearColor (0, 0, 0, 0); + glCullFace (GL_FRONT); + glEnable (GL_TEXTURE_2D); - glEnable(GL_ALPHA_TEST); - glAlphaFunc(GL_GREATER, 0.666); + glEnable (GL_ALPHA_TEST); + glAlphaFunc (GL_GREATER, 0.666); glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); glShadeModel (GL_FLAT); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glEnable(GL_BLEND); + glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); #if 0 CheckArrayExtensions (); @@ -653,7 +645,8 @@ GL_BeginRendering ================= */ -void GL_BeginRendering (int *x, int *y, int *width, int *height) +void +GL_BeginRendering (int *x, int *y, int *width, int *height) { extern cvar_t *gl_clear; @@ -662,22 +655,22 @@ void GL_BeginRendering (int *x, int *y, int *width, int *height) *height = WindowRect.bottom - WindowRect.top; // if (!wglMakeCurrent( maindc, baseRC )) -// Sys_Error ("wglMakeCurrent failed"); +// Sys_Error ("wglMakeCurrent failed"); -// glViewport (*x, *y, *width, *height); +// glViewport (*x, *y, *width, *height); } -void GL_EndRendering (void) +void +GL_EndRendering (void) { if (!scr_skipupdate || block_drawing) - SwapBuffers(maindc); + SwapBuffers (maindc); // handle the mouse state when windowed if that's changed - if (modestate == MS_WINDOWED) - { + if (modestate == MS_WINDOWED) { if (!_windowed_mouse->int_val) { - if (windowed_mouse) { + if (windowed_mouse) { IN_DeactivateMouse (); IN_ShowMouse (); windowed_mouse = false; @@ -694,22 +687,22 @@ void GL_EndRendering (void) } } if (fullsbardraw) - Sbar_Changed(); + Sbar_Changed (); } void VID_SetPalette (unsigned char *palette) { - byte *pal; - unsigned int r,g,b; + byte *pal; + unsigned int r, g, b; unsigned int v; - int r1,g1,b1; - int k; + int r1, g1, b1; + int k; unsigned short i; - unsigned int *table; - QFile *f; - char s[255]; - float dist, bestdist; + unsigned int *table; + QFile *f; + char s[255]; + float dist, bestdist; static qboolean palflag = false; // @@ -719,19 +712,18 @@ VID_SetPalette (unsigned char *palette) pal = palette; table = d_8to24table; - for (i=0 ; i<256 ; i++) - { + for (i = 0; i < 256; i++) { r = pal[0]; g = pal[1]; b = pal[2]; pal += 3; -// v = (255<<24) + (r<<16) + (g<<8) + (b<<0); -// v = (255<<0) + (r<<8) + (g<<16) + (b<<24); - v = (255<<24) + (r<<0) + (g<<8) + (b<<16); +// v = (255<<24) + (r<<16) + (g<<8) + (b<<0); +// v = (255<<0) + (r<<8) + (g<<16) + (b<<24); + v = (255 << 24) + (r << 0) + (g << 8) + (b << 16); *table++ = v; } - d_8to24table[255] &= 0; // 255 is transparent + d_8to24table[255] &= 0; // 255 is transparent // JACK: 3D distance calcs - k is last closest, l is the distance. // FIXME: Precalculate this and cache to disk. @@ -739,86 +731,85 @@ VID_SetPalette (unsigned char *palette) return; palflag = true; - COM_FOpenFile("glquake/15to8.pal", &f); + COM_FOpenFile ("glquake/15to8.pal", &f); if (f) { - Qread(f, d_15to8table, 1<<15); - Qclose(f); + Qread (f, d_15to8table, 1 << 15); + Qclose (f); } else { - for (i=0; i < (1<<15); i++) { - /* Maps - 000000000000000 - 000000000011111 = Red = 0x1F - 000001111100000 = Blue = 0x03E0 - 111110000000000 = Grn = 0x7C00 - */ - r = ((i & 0x1F) << 3)+4; - g = ((i & 0x03E0) >> 2)+4; - b = ((i & 0x7C00) >> 7)+4; - pal = (unsigned char *)d_8to24table; - for (v=0,k=0,bestdist=10000.0; v<256; v++,pal+=4) { - r1 = (int)r - (int)pal[0]; - g1 = (int)g - (int)pal[1]; - b1 = (int)b - (int)pal[2]; - dist = sqrt(((r1*r1)+(g1*g1)+(b1*b1))); + for (i = 0; i < (1 << 15); i++) { + /* Maps 000000000000000 000000000011111 = Red = 0x1F + 000001111100000 = Blue = 0x03E0 111110000000000 = Grn = + 0x7C00 */ + r = ((i & 0x1F) << 3) + 4; + g = ((i & 0x03E0) >> 2) + 4; + b = ((i & 0x7C00) >> 7) + 4; + pal = (unsigned char *) d_8to24table; + for (v = 0, k = 0, bestdist = 10000.0; v < 256; v++, pal += 4) { + r1 = (int) r - (int) pal[0]; + g1 = (int) g - (int) pal[1]; + b1 = (int) b - (int) pal[2]; + dist = sqrt (((r1 * r1) + (g1 * g1) + (b1 * b1))); if (dist < bestdist) { - k=v; + k = v; bestdist = dist; } } - d_15to8table[i]=k; + d_15to8table[i] = k; } - snprintf(s, sizeof(s), "%s/glquake/15to8.pal", com_gamedir); + snprintf (s, sizeof (s), "%s/glquake/15to8.pal", com_gamedir); COM_CreatePath (s); - if ((f = Qopen(s, "wb")) != NULL) { - Qwrite(f, d_15to8table, 1<<15); - Qclose(f); + if ((f = Qopen (s, "wb")) != NULL) { + Qwrite (f, d_15to8table, 1 << 15); + Qclose (f); } } } -BOOL gammaworks; +BOOL gammaworks; -void VID_ShiftPalette (unsigned char *palette) +void +VID_ShiftPalette (unsigned char *palette) { - extern byte ramps[3][256]; + extern byte ramps[3][256]; -// VID_SetPalette (palette); +// VID_SetPalette (palette); -// gammaworks = SetDeviceGammaRamp (maindc, ramps); +// gammaworks = SetDeviceGammaRamp (maindc, ramps); } -void VID_SetDefaultMode (void) +void +VID_SetDefaultMode (void) { IN_DeactivateMouse (); } -void VID_Shutdown (void) +void +VID_Shutdown (void) { - HGLRC hRC; - HDC hDC; - int i,temp[8192]; + HGLRC hRC; + HDC hDC; + int i, temp[8192]; - if (vid_initialized) - { + if (vid_initialized) { vid_canalttab = false; - hRC = wglGetCurrentContext(); - hDC = wglGetCurrentDC(); + hRC = wglGetCurrentContext (); + hDC = wglGetCurrentDC (); - wglMakeCurrent(NULL, NULL); + wglMakeCurrent (NULL, NULL); - // LordHavoc: free textures before closing (may help NVIDIA) - for (i = 0;i < 8192;i++) - temp[i] = i; - glDeleteTextures(8192, temp); + // LordHavoc: free textures before closing (may help NVIDIA) + for (i = 0; i < 8192; i++) + temp[i] = i; + glDeleteTextures (8192, temp); - if (hRC) - wglDeleteContext(hRC); + if (hRC) + wglDeleteContext (hRC); if (hDC && dibwindow) - ReleaseDC(dibwindow, hDC); + ReleaseDC (dibwindow, hDC); if (modestate == MS_FULLDIB) ChangeDisplaySettings (NULL, 0); @@ -826,7 +817,7 @@ void VID_Shutdown (void) if (maindc && dibwindow) ReleaseDC (dibwindow, maindc); - AppActivate(false, false); + AppActivate (false, false); } } @@ -834,90 +825,87 @@ void VID_Shutdown (void) //========================================================================== -BOOL bSetupPixelFormat(HDC hDC) +BOOL +bSetupPixelFormat (HDC hDC) { - static PIXELFORMATDESCRIPTOR pfd = { - sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd - 1, // version number - PFD_DRAW_TO_WINDOW // support window - | PFD_SUPPORT_OPENGL // support OpenGL - | PFD_DOUBLEBUFFER , // double buffered - PFD_TYPE_RGBA, // RGBA type - 24, // 24-bit color depth - 0, 0, 0, 0, 0, 0, // color bits ignored - 0, // no alpha buffer - 0, // shift bit ignored - 0, // no accumulation buffer - 0, 0, 0, 0, // accum bits ignored - 32, // 32-bit z-buffer - 0, // no stencil buffer - 0, // no auxiliary buffer - PFD_MAIN_PLANE, // main layer - 0, // reserved - 0, 0, 0 // layer masks ignored - }; - int pixelformat; + static PIXELFORMATDESCRIPTOR pfd = { + sizeof (PIXELFORMATDESCRIPTOR), // size of this pfd + 1, // version number + PFD_DRAW_TO_WINDOW // support window + | PFD_SUPPORT_OPENGL // support OpenGL + | PFD_DOUBLEBUFFER, // double buffered + PFD_TYPE_RGBA, // RGBA type + 24, // 24-bit color depth + 0, 0, 0, 0, 0, 0, // color bits ignored + 0, // no alpha buffer + 0, // shift bit ignored + 0, // no accumulation buffer + 0, 0, 0, 0, // accum bits ignored + 32, // 32-bit z-buffer + 0, // no stencil buffer + 0, // no auxiliary buffer + PFD_MAIN_PLANE, // main layer + 0, // reserved + 0, 0, 0 // layer masks ignored + }; + int pixelformat; - if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 ) - { - MessageBox(NULL, "ChoosePixelFormat failed", "Error", MB_OK); - return FALSE; - } + if ((pixelformat = ChoosePixelFormat (hDC, &pfd)) == 0) { + MessageBox (NULL, "ChoosePixelFormat failed", "Error", MB_OK); + return FALSE; + } - if (SetPixelFormat(hDC, pixelformat, &pfd) == FALSE) - { - MessageBox(NULL, "SetPixelFormat failed", "Error", MB_OK); - return FALSE; - } + if (SetPixelFormat (hDC, pixelformat, &pfd) == FALSE) { + MessageBox (NULL, "SetPixelFormat failed", "Error", MB_OK); + return FALSE; + } - return TRUE; + return TRUE; } //========================================================================== -byte scantokey[128] = -{ +byte scantokey[128] = { // 0 1 2 3 4 5 6 7 // 8 9 A B C D E F - 0 , 27, '1', '2', '3', '4', '5', '6', - '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 - 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', - 'o', 'p', '[', ']', 13, K_CTRL, 'a', 's', // 1 - 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', - '\'', '`', K_SHIFT,'\\', 'z', 'x', 'c', 'v', // 2 - 'b', 'n', 'm', ',', '.', '/', K_SHIFT,KP_MULTIPLY, - K_ALT, ' ', K_CAPSLOCK,K_F1, K_F2, K_F3, K_F4, K_F5, // 3 - K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE,K_SCRLCK,KP_HOME, - KP_UPARROW,KP_PGUP,KP_MINUS,KP_LEFTARROW,KP_5,KP_RIGHTARROW,KP_PLUS,KP_END, // 4 - KP_DOWNARROW,KP_PGDN,KP_INS,KP_DEL,0, 0, 0, K_F11, - K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0 + 0, 27, '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 + 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', + 'o', 'p', '[', ']', 13, K_CTRL, 'a', 's', // 1 + 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', + '\'', '`', K_SHIFT, '\\', 'z', 'x', 'c', 'v', // 2 + 'b', 'n', 'm', ',', '.', '/', K_SHIFT, KP_MULTIPLY, + K_ALT, ' ', K_CAPSLOCK, K_F1, K_F2, K_F3, K_F4, K_F5, // 3 + K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE, K_SCRLCK, KP_HOME, + KP_UPARROW, KP_PGUP, KP_MINUS, KP_LEFTARROW, KP_5, KP_RIGHTARROW, KP_PLUS, KP_END, // 4 + KP_DOWNARROW, KP_PGDN, KP_INS, KP_DEL, 0, 0, 0, K_F11, + K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }; -byte extscantokey[128] = -{ +byte extscantokey[128] = { // 0 1 2 3 4 5 6 7 // 8 9 A B C D E F - 0 , 27, '1', '2', '3', '4', '5', '6', - '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 - 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', - 'o', 'p', '[', ']', KP_ENTER,K_CTRL,'a', 's', // 1 - 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', - '\'', '`', K_SHIFT,'\\', 'z', 'x', 'c', 'v', // 2 - 'b', 'n', 'm', ',', '.', KP_DIVIDE,K_SHIFT,'*', - K_ALT, ' ', K_CAPSLOCK,K_F1,K_F2, K_F3, K_F4, K_F5, // 3 - K_F6, K_F7, K_F8, K_F9, K_F10, KP_NUMLCK,0, K_HOME, - K_UPARROW,K_PGUP,'-',K_LEFTARROW,'5',K_RIGHTARROW,'+', K_END, // 4 - K_DOWNARROW,K_PGDN,K_INS,K_DEL, 0, 0, 0, K_F11, - K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0 + 0, 27, '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '-', '=', K_BACKSPACE, 9, // 0 + 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', + 'o', 'p', '[', ']', KP_ENTER, K_CTRL, 'a', 's', // 1 + 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', + '\'', '`', K_SHIFT, '\\', 'z', 'x', 'c', 'v', // 2 + 'b', 'n', 'm', ',', '.', KP_DIVIDE, K_SHIFT, '*', + K_ALT, ' ', K_CAPSLOCK, K_F1, K_F2, K_F3, K_F4, K_F5, // 3 + K_F6, K_F7, K_F8, K_F9, K_F10, KP_NUMLCK, 0, K_HOME, + K_UPARROW, K_PGUP, '-', K_LEFTARROW, '5', K_RIGHTARROW, '+', K_END, // 4 + K_DOWNARROW, K_PGDN, K_INS, K_DEL, 0, 0, 0, K_F11, + K_F12, 0, 0, 0, 0, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 }; @@ -929,13 +917,14 @@ MapKey Map from windows to quake keynums ======= */ -int MapKey (int key) +int +MapKey (int key) { - int extended; + int extended; extended = (key >> 24) & 1; - key = (key>>16)&255; + key = (key >> 16) & 255; if (key > 127) return 0; @@ -961,14 +950,16 @@ extern void CL_ClearStates (); ClearAllStates ================ */ -void ClearAllStates (void) +void +ClearAllStates (void) { CL_ClearStates (); Key_ClearStates (); IN_ClearStates (); } -void AppActivate(BOOL fActive, BOOL minimize) +void +AppActivate (BOOL fActive, BOOL minimize) /**************************************************************************** * * Function: AppActivate @@ -980,55 +971,46 @@ void AppActivate(BOOL fActive, BOOL minimize) * ****************************************************************************/ { - static BOOL sound_active; + static BOOL sound_active; ActiveApp = fActive; Minimized = minimize; // enable/disable sound on focus gain/loss - if (!ActiveApp && sound_active) - { + if (!ActiveApp && sound_active) { S_BlockSound (); sound_active = false; - } - else if (ActiveApp && !sound_active) - { + } else if (ActiveApp && !sound_active) { S_UnblockSound (); sound_active = true; } - if (fActive) - { - if (modestate == MS_FULLDIB) - { + if (fActive) { + if (modestate == MS_FULLDIB) { IN_ActivateMouse (); IN_HideMouse (); if (vid_canalttab && vid_wassuspended) { vid_wassuspended = false; ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN); - ShowWindow(mainwindow, SW_SHOWNORMAL); + ShowWindow (mainwindow, SW_SHOWNORMAL); } } - else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val && key_dest == key_game) - { + else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val + && key_dest == key_game) { IN_ActivateMouse (); IN_HideMouse (); } } - if (!fActive) - { - if (modestate == MS_FULLDIB) - { + if (!fActive) { + if (modestate == MS_FULLDIB) { IN_DeactivateMouse (); IN_ShowMouse (); - if (vid_canalttab) { + if (vid_canalttab) { ChangeDisplaySettings (NULL, 0); vid_wassuspended = true; } - } - else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val) - { + } else if ((modestate == MS_WINDOWED) && _windowed_mouse->int_val) { IN_DeactivateMouse (); IN_ShowMouse (); } @@ -1036,53 +1018,53 @@ void AppActivate(BOOL fActive, BOOL minimize) } -LONG CDAudio_MessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); +LONG CDAudio_MessageHandler (HWND hWnd, UINT uMsg, WPARAM wParam, + + LPARAM lParam); /* main window procedure */ -LONG WINAPI MainWndProc ( - HWND hWnd, - UINT uMsg, - WPARAM wParam, - LPARAM lParam) +LONG WINAPI +MainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - LONG lRet = 1; - int fActive, fMinimized, temp; + LONG lRet = 1; + int fActive, fMinimized, temp; extern unsigned int uiWheelMessage; - if ( uMsg == uiWheelMessage ) + if (uMsg == uiWheelMessage) uMsg = WM_MOUSEWHEEL; - switch (uMsg) - { + switch (uMsg) { case WM_KILLFOCUS: if (modestate == MS_FULLDIB) - ShowWindow(mainwindow, SW_SHOWMINNOACTIVE); + ShowWindow (mainwindow, SW_SHOWMINNOACTIVE); break; case WM_CREATE: break; case WM_MOVE: - window_x = (int) LOWORD(lParam); - window_y = (int) HIWORD(lParam); + window_x = (int) LOWORD (lParam); + window_y = (int) HIWORD (lParam); VID_UpdateWindowStatus (); break; case WM_KEYDOWN: case WM_SYSKEYDOWN: - Key_Event (MapKey(lParam), -1, true); + Key_Event (MapKey (lParam), -1, true); break; - + case WM_KEYUP: case WM_SYSKEYUP: - Key_Event (MapKey(lParam), -1, false); + Key_Event (MapKey (lParam), -1, false); break; case WM_SYSCHAR: - // keep Alt-Space from happening + // keep Alt-Space from happening break; - // this is complicated because Win32 seems to pack multiple mouse events into - // one update sometimes, so we always check all states and look for events + // this is complicated because Win32 seems to pack multiple mouse + // events into + // one update sometimes, so we always check all states and look + // for events case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: @@ -1105,62 +1087,64 @@ LONG WINAPI MainWndProc ( break; - // JACK: This is the mouse wheel with the Intellimouse - // Its delta is either positive or neg, and we generate the proper - // Event. - case WM_MOUSEWHEEL: - if ((short) HIWORD(wParam) > 0) { - Key_Event(K_MWHEELUP, -1, true); - Key_Event(K_MWHEELUP, -1, false); + // JACK: This is the mouse wheel with the Intellimouse + // Its delta is either positive or neg, and we generate the + // proper + // Event. + case WM_MOUSEWHEEL: + if ((short) HIWORD (wParam) > 0) { + Key_Event (K_MWHEELUP, -1, true); + Key_Event (K_MWHEELUP, -1, false); } else { - Key_Event(K_MWHEELDOWN, -1, true); - Key_Event(K_MWHEELDOWN, -1, false); + Key_Event (K_MWHEELDOWN, -1, true); + Key_Event (K_MWHEELDOWN, -1, false); } break; - case WM_SIZE: - break; + case WM_SIZE: + break; - case WM_CLOSE: - if (MessageBox (mainwindow, "Are you sure you want to quit?", "Confirm Exit", - MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES) - { + case WM_CLOSE: + if (MessageBox + (mainwindow, "Are you sure you want to quit?", "Confirm Exit", + MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION) == IDYES) { Sys_Quit (); } - break; + break; case WM_ACTIVATE: - fActive = LOWORD(wParam); - fMinimized = (BOOL) HIWORD(wParam); - AppActivate(!(fActive == WA_INACTIVE), fMinimized); + fActive = LOWORD (wParam); + fMinimized = (BOOL) HIWORD (wParam); + AppActivate (!(fActive == WA_INACTIVE), fMinimized); - // fix the leftover Alt from any Alt-Tab or the like that switched us away + // fix the leftover Alt from any Alt-Tab or the like that + // switched us away ClearAllStates (); break; - case WM_DESTROY: - { - if (dibwindow) - DestroyWindow (dibwindow); + case WM_DESTROY: + { + if (dibwindow) + DestroyWindow (dibwindow); - PostQuitMessage (0); - } - break; - - case MM_MCINOTIFY: - lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam); + PostQuitMessage (0); + } break; - default: - /* pass all unhandled messages to DefWindowProc */ - lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); - break; - } + case MM_MCINOTIFY: + lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam); + break; - /* return 1 if handled message, 0 if not */ - return lRet; + default: + /* pass all unhandled messages to DefWindowProc */ + lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); + break; + } + + /* return 1 if handled message, 0 if not */ + return lRet; } @@ -1169,18 +1153,20 @@ LONG WINAPI MainWndProc ( VID_NumModes ================= */ -int VID_NumModes (void) +int +VID_NumModes (void) { return nummodes; } - + /* ================= VID_GetModePtr ================= */ -vmode_t *VID_GetModePtr (int modenum) +vmode_t * +VID_GetModePtr (int modenum) { if ((modenum >= 0) && (modenum < nummodes)) @@ -1195,25 +1181,23 @@ vmode_t *VID_GetModePtr (int modenum) VID_GetModeDescription ================= */ -char *VID_GetModeDescription (int mode) +char * +VID_GetModeDescription (int mode) { - char *pinfo; - vmode_t *pv; - static char temp[100]; + char *pinfo; + vmode_t *pv; + static char temp[100]; if ((mode < 0) || (mode >= nummodes)) return NULL; - if (!leavecurrentmode) - { + if (!leavecurrentmode) { pv = VID_GetModePtr (mode); pinfo = pv->modedesc; - } - else - { - snprintf (temp, sizeof(temp), "Desktop resolution (%dx%d)", - modelist[MODE_FULLSCREEN_DEFAULT].width, - modelist[MODE_FULLSCREEN_DEFAULT].height); + } else { + snprintf (temp, sizeof (temp), "Desktop resolution (%dx%d)", + modelist[MODE_FULLSCREEN_DEFAULT].width, + modelist[MODE_FULLSCREEN_DEFAULT].height); pinfo = temp; } @@ -1223,34 +1207,29 @@ char *VID_GetModeDescription (int mode) // KJB: Added this to return the mode driver name in description for console -char *VID_GetExtModeDescription (int mode) +char * +VID_GetExtModeDescription (int mode) { - static char pinfo[40]; - vmode_t *pv; + static char pinfo[40]; + vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; pv = VID_GetModePtr (mode); - if (modelist[mode].type == MS_FULLDIB) - { - if (!leavecurrentmode) - { - snprintf (pinfo, sizeof(pinfo), "%s fullscreen", pv->modedesc); + if (modelist[mode].type == MS_FULLDIB) { + if (!leavecurrentmode) { + snprintf (pinfo, sizeof (pinfo), "%s fullscreen", pv->modedesc); + } else { + snprintf (pinfo, sizeof (pinfo), "Desktop resolution (%dx%d)", + modelist[MODE_FULLSCREEN_DEFAULT].width, + modelist[MODE_FULLSCREEN_DEFAULT].height); } - else - { - snprintf (pinfo, sizeof(pinfo), "Desktop resolution (%dx%d)", - modelist[MODE_FULLSCREEN_DEFAULT].width, - modelist[MODE_FULLSCREEN_DEFAULT].height); - } - } - else - { + } else { if (modestate == MS_WINDOWED) - snprintf (pinfo, sizeof(pinfo), "%s windowed", pv->modedesc); + snprintf (pinfo, sizeof (pinfo), "%s windowed", pv->modedesc); else - snprintf (pinfo, sizeof(pinfo), "windowed"); + snprintf (pinfo, sizeof (pinfo), "windowed"); } return pinfo; @@ -1262,7 +1241,8 @@ char *VID_GetExtModeDescription (int mode) VID_DescribeCurrentMode_f ================= */ -void VID_DescribeCurrentMode_f (void) +void +VID_DescribeCurrentMode_f (void) { Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum)); } @@ -1273,7 +1253,8 @@ void VID_DescribeCurrentMode_f (void) VID_NumModes_f ================= */ -void VID_NumModes_f (void) +void +VID_NumModes_f (void) { if (nummodes == 1) @@ -1288,11 +1269,12 @@ void VID_NumModes_f (void) VID_DescribeMode_f ================= */ -void VID_DescribeMode_f (void) +void +VID_DescribeMode_f (void) { - int t, modenum; - - modenum = atoi (Cmd_Argv(1)); + int t, modenum; + + modenum = atoi (Cmd_Argv (1)); t = leavecurrentmode; leavecurrentmode = 0; @@ -1308,19 +1290,19 @@ void VID_DescribeMode_f (void) VID_DescribeModes_f ================= */ -void VID_DescribeModes_f (void) +void +VID_DescribeModes_f (void) { - int i, lnummodes, t; - char *pinfo; - vmode_t *pv; + int i, lnummodes, t; + char *pinfo; + vmode_t *pv; lnummodes = VID_NumModes (); t = leavecurrentmode; leavecurrentmode = 0; - for (i=1 ; i8 bpp modes originalnummodes = nummodes; modenum = 0; - do - { + do { stat = EnumDisplaySettings (NULL, modenum, &devmode); if ((devmode.dmBitsPerPel >= 15) && (devmode.dmPelsWidth <= MAXWIDTH) && - (devmode.dmPelsHeight <= MAXHEIGHT) && - (nummodes < MAX_MODE_LIST)) - { - devmode.dmFields = DM_BITSPERPEL | - DM_PELSWIDTH | - DM_PELSHEIGHT; + (devmode.dmPelsHeight <= MAXHEIGHT) && (nummodes < MAX_MODE_LIST)) { + devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == - DISP_CHANGE_SUCCESSFUL) - { + DISP_CHANGE_SUCCESSFUL) { modelist[nummodes].type = MS_FULLDIB; modelist[nummodes].width = devmode.dmPelsWidth; modelist[nummodes].height = devmode.dmPelsHeight; @@ -1420,38 +1398,37 @@ void VID_InitFullDIB (HINSTANCE hInstance) modelist[nummodes].dib = 1; modelist[nummodes].fullscreen = 1; modelist[nummodes].bpp = devmode.dmBitsPerPel; - snprintf (modelist[nummodes].modedesc, sizeof(modelist[nummodes].modedesc), "%dx%dx%d", - devmode.dmPelsWidth, devmode.dmPelsHeight, - devmode.dmBitsPerPel); + snprintf (modelist[nummodes].modedesc, + sizeof (modelist[nummodes].modedesc), "%dx%dx%d", + devmode.dmPelsWidth, devmode.dmPelsHeight, + devmode.dmBitsPerPel); - // if the width is more than twice the height, reduce it by half because this - // is probably a dual-screen monitor - if (!COM_CheckParm("-noadjustaspect")) - { - if (modelist[nummodes].width > (modelist[nummodes].height << 1)) - { + // if the width is more than twice the height, reduce it by + // half because this + // is probably a dual-screen monitor + if (!COM_CheckParm ("-noadjustaspect")) { + if (modelist[nummodes].width > + (modelist[nummodes].height << 1)) { modelist[nummodes].width >>= 1; modelist[nummodes].halfscreen = 1; - snprintf (modelist[nummodes].modedesc, sizeof(modelist[nummodes].modedesc), "%dx%dx%d", - modelist[nummodes].width, - modelist[nummodes].height, - modelist[nummodes].bpp); + snprintf (modelist[nummodes].modedesc, + sizeof (modelist[nummodes].modedesc), + "%dx%dx%d", modelist[nummodes].width, + modelist[nummodes].height, + modelist[nummodes].bpp); } } - for (i=originalnummodes, existingmode = 0 ; iwidth)/2, 4, p); + M_DrawPic ((320 - p->width) / 2, 4, p); vid_wmodes = 0; lnummodes = VID_NumModes (); - - for (i=1 ; (i 0) - { - M_Print (2*8, 36+0*8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)"); + if (vid_wmodes > 0) { + M_Print (2 * 8, 36 + 0 * 8, "Fullscreen Modes (WIDTHxHEIGHTxBPP)"); column = 8; - row = 36+2*8; + row = 36 + 2 * 8; - for (i=0 ; i"); - M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, + M_Print (3 * 8, 36 + MODE_AREA_HEIGHT * 8 + 8 * 4, "and -bpp "); - M_Print (3*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, + M_Print (3 * 8, 36 + MODE_AREA_HEIGHT * 8 + 8 * 6, "Select windowed mode with -window"); } @@ -1920,27 +1862,30 @@ void VID_MenuDraw (void) VID_MenuKey ================ */ -void VID_MenuKey (int key) +void +VID_MenuKey (int key) { - switch (key) - { - case K_ESCAPE: - S_LocalSound ("misc/menu1.wav"); - M_Menu_Options_f (); - break; + switch (key) { + case K_ESCAPE: + S_LocalSound ("misc/menu1.wav"); + M_Menu_Options_f (); + break; - default: - break; + default: + break; } } -void VID_SetCaption (char *text) +void +VID_SetCaption (char *text) { if (text && *text) { - char *temp = strdup (text); - SetWindowText(mainwindow,(LPSTR) va ("%s %s: %s", PROGRAM, VERSION, temp)); + char *temp = strdup (text); + + SetWindowText (mainwindow, + (LPSTR) va ("%s %s: %s", PROGRAM, VERSION, temp)); free (temp); } else { - SetWindowText(mainwindow,(LPSTR) va ("%s %s", PROGRAM, VERSION)); + SetWindowText (mainwindow, (LPSTR) va ("%s %s", PROGRAM, VERSION)); } } diff --git a/source/vid_x11.c b/source/vid_x11.c index eb7ff39..06f83dd 100644 --- a/source/vid_x11.c +++ b/source/vid_x11.c @@ -32,7 +32,7 @@ #define _BSD -#include +# include "config.h" #include #include #include @@ -79,43 +79,43 @@ #include "sys.h" #include "va.h" -extern viddef_t vid; // global video state -unsigned short d_8to16table[256]; +extern viddef_t vid; // global video state +unsigned short d_8to16table[256]; -static Colormap x_cmap; -static GC x_gc; +static Colormap x_cmap; +static GC x_gc; -int XShmQueryExtension (Display *); -int XShmGetEventBase (Display *); +int XShmQueryExtension (Display *); +int XShmGetEventBase (Display *); -static qboolean doShm; -static XShmSegmentInfo x_shminfo[2]; +static qboolean doShm; +static XShmSegmentInfo x_shminfo[2]; -static int current_framebuffer; -static XImage *x_framebuffer[2] = { 0, 0 }; +static int current_framebuffer; +static XImage *x_framebuffer[2] = { 0, 0 }; -static int verbose = 0; +static int verbose = 0; -int VID_options_items = 1; +int VID_options_items = 1; -static byte current_palette[768]; +static byte current_palette[768]; -typedef unsigned short PIXEL16; -typedef unsigned long PIXEL24; +typedef unsigned short PIXEL16; +typedef unsigned long PIXEL24; -static PIXEL16 st2d_8to16table[256]; -static PIXEL24 st2d_8to24table[256]; -static int shiftmask_fl = 0; -static long r_shift, g_shift, b_shift; -static unsigned long r_mask, g_mask, b_mask; +static PIXEL16 st2d_8to16table[256]; +static PIXEL24 st2d_8to24table[256]; +static int shiftmask_fl = 0; +static long r_shift, g_shift, b_shift; +static unsigned long r_mask, g_mask, b_mask; -cvar_t *vid_width; -cvar_t *vid_height; +cvar_t *vid_width; +cvar_t *vid_height; static void shiftmask_init (void) { - unsigned int x; + unsigned int x; r_mask = x_vis->red_mask; g_mask = x_vis->green_mask; @@ -130,19 +130,19 @@ shiftmask_init (void) shiftmask_fl = 1; } -static PIXEL16 -xlib_rgb16(int r, int g, int b) +static PIXEL16 +xlib_rgb16 (int r, int g, int b) { - PIXEL16 p = 0; + PIXEL16 p = 0; if (!shiftmask_fl) shiftmask_init (); if (r_shift > 0) { - p=(r << (r_shift)) & r_mask; + p = (r << (r_shift)) & r_mask; } else { if (r_shift < 0) { - p =(r >> (-r_shift)) & r_mask; + p = (r >> (-r_shift)) & r_mask; } else { p |= (r & r_mask); } @@ -172,10 +172,10 @@ xlib_rgb16(int r, int g, int b) } -static PIXEL24 +static PIXEL24 xlib_rgb24 (int r, int g, int b) { - PIXEL24 p = 0; + PIXEL24 p = 0; if (!shiftmask_fl) shiftmask_init (); @@ -214,11 +214,11 @@ xlib_rgb24 (int r, int g, int b) } static void -st2_fixup (XImage *framebuf, int x, int y, int width, int height) +st2_fixup (XImage * framebuf, int x, int y, int width, int height) { - int xi, yi; - unsigned char *src; - PIXEL16 *dest; + int xi, yi; + unsigned char *src; + PIXEL16 *dest; if (x < 0 || y < 0) return; @@ -226,7 +226,7 @@ st2_fixup (XImage *framebuf, int x, int y, int width, int height) for (yi = y; yi < (y + height); yi++) { src = &framebuf->data[yi * framebuf->bytes_per_line]; dest = (PIXEL16 *) src; - for(xi = (x + width - 1); xi >= x; xi--) { + for (xi = (x + width - 1); xi >= x; xi--) { dest[xi] = st2d_8to16table[src[xi]]; } } @@ -234,39 +234,49 @@ st2_fixup (XImage *framebuf, int x, int y, int width, int height) static void -st3_fixup (XImage *framebuf, int x, int y, int width, int height) +st3_fixup (XImage * framebuf, int x, int y, int width, int height) { - int yi; - unsigned char *src; - PIXEL24 *dest; - register int count, n; + int yi; + unsigned char *src; + PIXEL24 *dest; + register int count, n; - if (x < 0 || y < 0) return; + if (x < 0 || y < 0) + return; - for (yi = y; yi < (y+height); yi++) { - src = &framebuf->data [yi * framebuf->bytes_per_line]; + for (yi = y; yi < (y + height); yi++) { + src = &framebuf->data[yi * framebuf->bytes_per_line]; // Duff's Device count = width; n = (count + 7) / 8; - dest = ((PIXEL24 *)src) + x+width - 1; - src += x+width - 1; + dest = ((PIXEL24 *) src) + x + width - 1; + src += x + width - 1; switch (count % 8) { - case 0: do { *dest-- = st2d_8to24table[*src--]; - case 7: *dest-- = st2d_8to24table[*src--]; - case 6: *dest-- = st2d_8to24table[*src--]; - case 5: *dest-- = st2d_8to24table[*src--]; - case 4: *dest-- = st2d_8to24table[*src--]; - case 3: *dest-- = st2d_8to24table[*src--]; - case 2: *dest-- = st2d_8to24table[*src--]; - case 1: *dest-- = st2d_8to24table[*src--]; - } while (--n > 0); + case 0: + do { + *dest-- = st2d_8to24table[*src--]; + case 7: + *dest-- = st2d_8to24table[*src--]; + case 6: + *dest-- = st2d_8to24table[*src--]; + case 5: + *dest-- = st2d_8to24table[*src--]; + case 4: + *dest-- = st2d_8to24table[*src--]; + case 3: + *dest-- = st2d_8to24table[*src--]; + case 2: + *dest-- = st2d_8to24table[*src--]; + case 1: + *dest-- = st2d_8to24table[*src--]; + } while (--n > 0); } -// for(xi = (x+width-1); xi >= x; xi--) { -// dest[xi] = st2d_8to16table[src[xi]]; -// } +// for(xi = (x+width-1); xi >= x; xi--) { +// dest[xi] = st2d_8to16table[src[xi]]; +// } } } @@ -276,7 +286,7 @@ D_BeginDirectRect ================ */ void -D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) +D_BeginDirectRect (int x, int y, byte * pbitmap, int width, int height) { // direct drawing of the "accessing disk" icon isn't supported } @@ -302,28 +312,28 @@ Keybinding command ================= */ -byte vid_gamma[256]; +byte vid_gamma[256]; void VID_Gamma_f (void) { - float g, f, inf; - int i; + float g, f, inf; + int i; if (Cmd_Argc () == 2) { g = atof (Cmd_Argv (1)); for (i = 0; i < 255; i++) { f = pow ((i + 1) / 256.0, g); - inf = f*255 + 0.5; + inf = f * 255 + 0.5; inf = bound (0, inf, 255); vid_gamma[i] = inf; } VID_SetPalette (current_palette); - vid.recalc_refdef = 1; // force a surface cache flush + vid.recalc_refdef = 1; // force a surface cache flush } } @@ -331,10 +341,10 @@ VID_Gamma_f (void) static void ResetFrameBuffer (void) { - int tbuffersize, tcachesize; - - void *vid_surfcache; - int mem, pwidth; + int tbuffersize, tcachesize; + + void *vid_surfcache; + int mem, pwidth; // Calculate the sizes we want first tbuffersize = vid.width * vid.height * sizeof (*d_pzbuffer); @@ -343,13 +353,11 @@ ResetFrameBuffer (void) if (x_framebuffer[0]) { XDestroyImage (x_framebuffer[0]); } - // Free the old z-buffer if (d_pzbuffer) { free (d_pzbuffer); d_pzbuffer = NULL; } - // Free the old surface cache vid_surfcache = D_SurfaceCacheAddress (); if (vid_surfcache) { @@ -357,13 +365,11 @@ ResetFrameBuffer (void) free (vid_surfcache); vid_surfcache = NULL; } - // Allocate the new z-buffer d_pzbuffer = calloc (tbuffersize, 1); if (!d_pzbuffer) { Sys_Error ("Not enough memory for video mode\n"); } - // Allocate the new surface cache; free the z-buffer if we fail vid_surfcache = calloc (tcachesize, 1); if (!vid_surfcache) { @@ -378,11 +384,11 @@ ResetFrameBuffer (void) if (pwidth == 3) pwidth = 4; - mem = ((vid.width * pwidth + 7) &~ 7) * vid.height; + mem = ((vid.width * pwidth + 7) & ~7) * vid.height; x_framebuffer[0] = XCreateImage (x_disp, x_vis, x_visinfo->depth, - ZPixmap, 0, malloc (mem), vid.width, - vid.height, 32, 0); + ZPixmap, 0, malloc (mem), vid.width, + vid.height, 32, 0); if (!x_framebuffer[0]) { Sys_Error ("VID: XCreateImage failed\n"); @@ -392,13 +398,13 @@ ResetFrameBuffer (void) static void ResetSharedFrameBuffers (void) { - int tbuffersize, tcachesize; - void *vid_surfcache; - - int size; - int key; - int minsize = getpagesize (); - int frm; + int tbuffersize, tcachesize; + void *vid_surfcache; + + int size; + int key; + int minsize = getpagesize (); + int frm; // Calculate the sizes we want first tbuffersize = vid.width * vid.height * sizeof (*d_pzbuffer); @@ -409,7 +415,6 @@ ResetSharedFrameBuffers (void) free (d_pzbuffer); d_pzbuffer = NULL; } - // Free the old surface cache vid_surfcache = D_SurfaceCacheAddress (); if (vid_surfcache) { @@ -417,13 +422,11 @@ ResetSharedFrameBuffers (void) free (vid_surfcache); vid_surfcache = NULL; } - // Allocate the new z-buffer d_pzbuffer = calloc (tbuffersize, 1); if (!d_pzbuffer) { Sys_Error ("Not enough memory for video mode\n"); } - // Allocate the new surface cache; free the z-buffer if we fail vid_surfcache = calloc (tcachesize, 1); if (!vid_surfcache) { @@ -437,16 +440,15 @@ ResetSharedFrameBuffers (void) for (frm = 0; frm < 2; frm++) { // free up old frame buffer memory - if (x_framebuffer[frm]) { + if (x_framebuffer[frm]) { XShmDetach (x_disp, &x_shminfo[frm]); free (x_framebuffer[frm]); shmdt (x_shminfo[frm].shmaddr); } - // create the image x_framebuffer[frm] = XShmCreateImage (x_disp, x_vis, x_visinfo->depth, - ZPixmap, 0, &x_shminfo[frm], - vid.width, vid.height ); + ZPixmap, 0, &x_shminfo[frm], + vid.width, vid.height); // grab shared memory size = x_framebuffer[frm]->bytes_per_line * x_framebuffer[frm]->height; @@ -454,16 +456,16 @@ ResetSharedFrameBuffers (void) if (size < minsize) Sys_Error ("VID: Window must use at least %d bytes\n", minsize); - key = random(); - x_shminfo[frm].shmid = shmget((key_t)key, size, IPC_CREAT|0777); - if (x_shminfo[frm].shmid==-1) + key = random (); + x_shminfo[frm].shmid = shmget ((key_t) key, size, IPC_CREAT | 0777); + if (x_shminfo[frm].shmid == -1) Sys_Error ("VID: Could not get any shared memory\n"); // attach to the shared memory segment x_shminfo[frm].shmaddr = (void *) shmat (x_shminfo[frm].shmid, 0, 0); printf ("VID: shared memory id=%d, addr=0x%lx\n", x_shminfo[frm].shmid, - (long) x_shminfo[frm].shmaddr); + (long) x_shminfo[frm].shmaddr); x_framebuffer[frm]->data = x_shminfo[frm].shmaddr; @@ -478,9 +480,9 @@ ResetSharedFrameBuffers (void) } static void -event_shm (XEvent *event) +event_shm (XEvent * event) { - if (doShm) + if (doShm) oktodraw = true; } @@ -494,16 +496,17 @@ event_shm (XEvent *event) void VID_Init (unsigned char *palette) { - int pnum, i; + int pnum, i; XVisualInfo template; - int num_visuals; - int template_mask; + int num_visuals; + int template_mask; VID_GetWindowSize (320, 200); -// plugin_load ("in_x11.so"); -// Cmd_AddCommand ("gamma", VID_Gamma_f); - for (i=0; i < 256; i++) vid_gamma[i] = i; +// plugin_load ("in_x11.so"); +// Cmd_AddCommand ("gamma", VID_Gamma_f); + for (i = 0; i < 256; i++) + vid_gamma[i] = i; vid.width = vid_width->int_val; vid.height = vid_height->int_val; @@ -524,11 +527,12 @@ VID_Init (unsigned char *palette) // specify a visual id if ((pnum = COM_CheckParm ("-visualid"))) { - if (pnum >= com_argc-1) + if (pnum >= com_argc - 1) Sys_Error ("VID: -visualid \n"); - template.visualid = atoi (com_argv[pnum+1]); + template.visualid = atoi (com_argv[pnum + 1]); template_mask = VisualIDMask; - } else { // If not specified, use default visual + } else { // If not specified, use default + // visual template.visualid = XVisualIDFromVisual (XDefaultVisual (x_disp, x_screen)); template_mask = VisualIDMask; @@ -553,14 +557,14 @@ VID_Init (unsigned char *palette) } if (verbose) { - printf ("Using visualid %d:\n", (int) x_visinfo->visualid); - printf (" class %d\n", x_visinfo->class); - printf (" screen %d\n", x_visinfo->screen); - printf (" depth %d\n", x_visinfo->depth); - printf (" red_mask 0x%x\n", (int) x_visinfo->red_mask); + printf ("Using visualid %d:\n", (int) x_visinfo->visualid); + printf (" class %d\n", x_visinfo->class); + printf (" screen %d\n", x_visinfo->screen); + printf (" depth %d\n", x_visinfo->depth); + printf (" red_mask 0x%x\n", (int) x_visinfo->red_mask); printf (" green_mask 0x%x\n", (int) x_visinfo->green_mask); - printf (" blue_mask 0x%x\n", (int) x_visinfo->blue_mask); - printf (" colormap_size %d\n",x_visinfo->colormap_size); + printf (" blue_mask 0x%x\n", (int) x_visinfo->blue_mask); + printf (" colormap_size %d\n", x_visinfo->colormap_size); printf (" bits_per_rgb %d\n", x_visinfo->bits_per_rgb); } @@ -581,21 +585,21 @@ VID_Init (unsigned char *palette) XSetWindowColormap (x_disp, x_win, x_cmap); } } - // create the GC { - XGCValues xgcvalues; - int valuemask = GCGraphicsExposures; + XGCValues xgcvalues; + int valuemask = GCGraphicsExposures; xgcvalues.graphics_exposures = False; - x_gc = XCreateGC (x_disp, x_win, valuemask, &xgcvalues ); + x_gc = XCreateGC (x_disp, x_win, valuemask, &xgcvalues); } x11_grab_keyboard (); // wait for first exposure event { - XEvent event; + XEvent event; + do { XNextEvent (x_disp, &event); if (event.type == Expose && !event.xexpose.count) @@ -606,8 +610,8 @@ VID_Init (unsigned char *palette) // even if MITSHM is available, make sure it's a local connection if (XShmQueryExtension (x_disp)) { - char *displayname; - char *d; + char *displayname; + char *d; doShm = true; @@ -615,7 +619,7 @@ VID_Init (unsigned char *palette) if ((d = strchr (displayname, ':'))) *d = '\0'; - if (!(!strcasecmp(displayname, "unix") || !*displayname)) + if (!(!strcasecmp (displayname, "unix") || !*displayname)) doShm = false; } } @@ -637,7 +641,7 @@ VID_Init (unsigned char *palette) vid.conheight = vid.height; vid.aspect = ((float) vid.height / (float) vid.width) * (320.0 / 240.0); -// XSynchronize (x_disp, False); +// XSynchronize (x_disp, False); x11_add_event (x_shmeventtype, event_shm); } @@ -658,14 +662,14 @@ VID_ShiftPalette (unsigned char *p) void VID_SetPalette (unsigned char *palette) { - int i; - XColor colors[256]; + int i; + XColor colors[256]; for (i = 0; i < 256; i++) { - st2d_8to16table[i] = xlib_rgb16 (palette[i*3], palette[i*3+1], - palette[i*3+2]); - st2d_8to24table[i] = xlib_rgb24 (palette[i*3], palette[i*3+1], - palette[i*3+2]); + st2d_8to16table[i] = xlib_rgb16 (palette[i * 3], palette[i * 3 + 1], + palette[i * 3 + 2]); + st2d_8to24table[i] = xlib_rgb24 (palette[i * 3], palette[i * 3 + 1], + palette[i * 3 + 2]); } if (x_visinfo->class == PseudoColor && x_visinfo->depth == 8) { @@ -673,11 +677,11 @@ VID_SetPalette (unsigned char *palette) memcpy (current_palette, palette, 768); } for (i = 0; i < 256; i++) { - colors[i].pixel = i; - colors[i].flags = DoRed|DoGreen|DoBlue; - colors[i].red = vid_gamma[palette[i*3]] * 256; - colors[i].green = vid_gamma[palette[i*3+1]] * 256; - colors[i].blue = vid_gamma[palette[i*3+2]] * 256; + colors[i].pixel = i; + colors[i].flags = DoRed | DoGreen | DoBlue; + colors[i].red = vid_gamma[palette[i * 3]] * 256; + colors[i].green = vid_gamma[palette[i * 3 + 1]] * 256; + colors[i].blue = vid_gamma[palette[i * 3 + 2]] * 256; } XStoreColors (x_disp, x_cmap, colors, 256); } @@ -699,9 +703,9 @@ VID_Shutdown (void) } } -static int config_notify = 0; -static int config_notify_width; -static int config_notify_height; +static int config_notify = 0; +static int config_notify_width; +static int config_notify_height; /* VID_Update @@ -715,7 +719,7 @@ VID_Update (vrect_t *rects) if (config_notify) { fprintf (stderr, "config notify\n"); config_notify = 0; - vid.width = config_notify_width &~ 7; + vid.width = config_notify_width & ~7; vid.height = config_notify_height; if (doShm) @@ -729,7 +733,7 @@ VID_Update (vrect_t *rects) vid.conwidth = vid.width; vid.conheight = vid.height; vid.conrowbytes = vid.rowbytes; - vid.recalc_refdef = 1; /* force a surface cache flush */ + vid.recalc_refdef = 1; /* force a surface cache flush */ Con_CheckResize (); Con_Clear_f (); return; @@ -739,20 +743,18 @@ VID_Update (vrect_t *rects) switch (x_visinfo->depth) { case 16: st2_fixup (x_framebuffer[current_framebuffer], - rects->x, rects->y, rects->width, - rects->height); + rects->x, rects->y, rects->width, rects->height); break; case 24: st3_fixup (x_framebuffer[current_framebuffer], - rects->x, rects->y, rects->width, - rects->height); + rects->x, rects->y, rects->width, rects->height); break; } if (doShm) { if (!XShmPutImage (x_disp, x_win, x_gc, - x_framebuffer[current_framebuffer], - rects->x, rects->y, rects->x, rects->y, - rects->width, rects->height, True)) { + x_framebuffer[current_framebuffer], + rects->x, rects->y, rects->x, rects->y, + rects->width, rects->height, True)) { Sys_Error ("VID_Update: XShmPutImage failed\n"); } oktodraw = false; @@ -796,21 +798,22 @@ VID_DitherOff (void) } } -void +void VID_LockBuffer (void) -{ -} +{ +} void VID_UnlockBuffer (void) -{ -} +{ +} void VID_SetCaption (char *text) { if (text && *text) { - char *temp = strdup (text); + char *temp = strdup (text); + x11_set_caption (va ("%s %s: %s", PROGRAM, VERSION, temp)); free (temp); } else { diff --git a/source/wad.c b/source/wad.c index 79a1ab6..2f59923 100644 --- a/source/wad.c +++ b/source/wad.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #ifdef HAVE_STRING_H @@ -42,11 +42,11 @@ #include "quakefs.h" #include "qendian.h" -int wad_numlumps; -lumpinfo_t *wad_lumps; -byte *wad_base; +int wad_numlumps; +lumpinfo_t *wad_lumps; +byte *wad_base; -void SwapPic (qpic_t *pic); +void SwapPic (qpic_t *pic); /* ================== @@ -59,23 +59,23 @@ Space padding is so names can be printed nicely in tables. Can safely be performed in place. ================== */ -void W_CleanupName (char *in, char *out) +void +W_CleanupName (char *in, char *out) { - int i; - int c; - - for (i=0 ; i<16 ; i++ ) - { + int i; + int c; + + for (i = 0; i < 16; i++) { c = in[i]; if (!c) break; - + if (c >= 'A' && c <= 'Z') c += ('a' - 'A'); out[i] = c; } - - for ( ; i< 16 ; i++ ) + + for (; i < 16; i++) out[i] = 0; } @@ -86,36 +86,35 @@ void W_CleanupName (char *in, char *out) W_LoadWadFile ==================== */ -void W_LoadWadFile (char *filename) +void +W_LoadWadFile (char *filename) { - lumpinfo_t *lump_p; - wadinfo_t *header; - unsigned int i; - int infotableofs; - + lumpinfo_t *lump_p; + wadinfo_t *header; + unsigned int i; + int infotableofs; + wad_base = COM_LoadHunkFile (filename); if (!wad_base) Sys_Error ("W_LoadWadFile: couldn't load %s", filename); - header = (wadinfo_t *)wad_base; - + header = (wadinfo_t *) wad_base; + if (header->identification[0] != 'W' - || header->identification[1] != 'A' - || header->identification[2] != 'D' - || header->identification[3] != '2') - Sys_Error ("Wad file %s doesn't have WAD2 id\n",filename); - - wad_numlumps = LittleLong(header->numlumps); - infotableofs = LittleLong(header->infotableofs); - wad_lumps = (lumpinfo_t *)(wad_base + infotableofs); - - for (i=0, lump_p = wad_lumps ; ifilepos = LittleLong(lump_p->filepos); - lump_p->size = LittleLong(lump_p->size); + || header->identification[1] != 'A' + || header->identification[2] != 'D' || header->identification[3] != '2') + Sys_Error ("Wad file %s doesn't have WAD2 id\n", filename); + + wad_numlumps = LittleLong (header->numlumps); + infotableofs = LittleLong (header->infotableofs); + wad_lumps = (lumpinfo_t *) (wad_base + infotableofs); + + for (i = 0, lump_p = wad_lumps; i < wad_numlumps; i++, lump_p++) { + lump_p->filepos = LittleLong (lump_p->filepos); + lump_p->size = LittleLong (lump_p->size); W_CleanupName (lump_p->name, lump_p->name); if (lump_p->type == TYP_QPIC) - SwapPic ( (qpic_t *)(wad_base + lump_p->filepos)); + SwapPic ((qpic_t *) (wad_base + lump_p->filepos)); } } @@ -125,43 +124,45 @@ void W_LoadWadFile (char *filename) W_GetLumpinfo ============= */ -lumpinfo_t *W_GetLumpinfo (char *name) +lumpinfo_t * +W_GetLumpinfo (char *name) { - int i; - lumpinfo_t *lump_p; - char clean[16]; - + int i; + lumpinfo_t *lump_p; + char clean[16]; + W_CleanupName (name, clean); - - for (lump_p=wad_lumps, i=0 ; iname)) + + for (lump_p = wad_lumps, i = 0; i < wad_numlumps; i++, lump_p++) { + if (!strcmp (clean, lump_p->name)) return lump_p; } - + Sys_Error ("W_GetLumpinfo: %s not found", name); return NULL; } -void *W_GetLumpName (char *name) +void * +W_GetLumpName (char *name) { - lumpinfo_t *lump; - + lumpinfo_t *lump; + lump = W_GetLumpinfo (name); - - return (void *)(wad_base + lump->filepos); + + return (void *) (wad_base + lump->filepos); } -void *W_GetLumpNum (int num) +void * +W_GetLumpNum (int num) { - lumpinfo_t *lump; - + lumpinfo_t *lump; + if (num < 0 || num > wad_numlumps) Sys_Error ("W_GetLumpNum: bad number: %i", num); - + lump = wad_lumps + num; - - return (void *)(wad_base + lump->filepos); + + return (void *) (wad_base + lump->filepos); } /* @@ -172,8 +173,9 @@ automatic byte swapping ============================================================================= */ -void SwapPic (qpic_t *pic) +void +SwapPic (qpic_t *pic) { - pic->width = LittleLong(pic->width); - pic->height = LittleLong(pic->height); + pic->width = LittleLong (pic->width); + pic->height = LittleLong (pic->height); } diff --git a/source/world.c b/source/world.c index c96fe75..690c711 100644 --- a/source/world.c +++ b/source/world.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "world.h" #include "server.h" @@ -49,19 +49,20 @@ line of sight checks trace->crosscontent, but bullets don't */ -typedef struct -{ - vec3_t boxmins, boxmaxs;// enclose the test object along entire move - float *mins, *maxs; // size of the moving object - vec3_t mins2, maxs2; // size when clipping against mosnters - float *start, *end; - trace_t trace; - int type; - edict_t *passedict; +typedef struct { + vec3_t boxmins, boxmaxs; // enclose the test object along + // entire move + float *mins, *maxs; // size of the moving object + vec3_t mins2, maxs2; // size when clipping against + // mosnters + float *start, *end; + trace_t trace; + int type; + edict_t *passedict; } moveclip_t; -int SV_HullPointContents (hull_t *hull, int num, vec3_t p); +int SV_HullPointContents (hull_t *hull, int num, vec3_t p); /* =============================================================================== @@ -72,9 +73,9 @@ HULL BOXES */ -static hull_t box_hull; -static dclipnode_t box_clipnodes[6]; -static mplane_t box_planes[6]; +static hull_t box_hull; +static dclipnode_t box_clipnodes[6]; +static mplane_t box_planes[6]; /* =================== @@ -84,32 +85,32 @@ Set up the planes and clipnodes so that the six floats of a bounding box can just be stored out and get a proper hull_t structure. =================== */ -void SV_InitBoxHull (void) +void +SV_InitBoxHull (void) { - int i; - int side; + int i; + int side; box_hull.clipnodes = box_clipnodes; box_hull.planes = box_planes; box_hull.firstclipnode = 0; box_hull.lastclipnode = 5; - for (i=0 ; i<6 ; i++) - { + for (i = 0; i < 6; i++) { box_clipnodes[i].planenum = i; - - side = i&1; - + + side = i & 1; + box_clipnodes[i].children[side] = CONTENTS_EMPTY; if (i != 5) - box_clipnodes[i].children[side^1] = i + 1; + box_clipnodes[i].children[side ^ 1] = i + 1; else - box_clipnodes[i].children[side^1] = CONTENTS_SOLID; - - box_planes[i].type = i>>1; - box_planes[i].normal[i>>1] = 1; + box_clipnodes[i].children[side ^ 1] = CONTENTS_SOLID; + + box_planes[i].type = i >> 1; + box_planes[i].normal[i >> 1] = 1; } - + } @@ -121,7 +122,8 @@ To keep everything totally uniform, bounding boxes are turned into small BSP trees instead of being compared directly. =================== */ -hull_t *SV_HullForBox (vec3_t mins, vec3_t maxs) +hull_t * +SV_HullForBox (vec3_t mins, vec3_t maxs) { box_planes[0].dist = maxs[0]; box_planes[1].dist = mins[0]; @@ -145,21 +147,21 @@ Offset is filled in to contain the adjustment that must be added to the testing object's origin to get a point to use with the returned hull. ================ */ -hull_t *SV_HullForEntity (edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset) +hull_t * +SV_HullForEntity (edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset) { - model_t *model; - vec3_t size; - vec3_t hullmins, hullmaxs; - hull_t *hull; + model_t *model; + vec3_t size; + vec3_t hullmins, hullmaxs; + hull_t *hull; // decide which clipping hull to use, based on the size - if (ent->v.solid == SOLID_BSP) - { + if (ent->v.solid == SOLID_BSP) { // explicit hulls in the BSP model if (ent->v.movetype != MOVETYPE_PUSH) SV_Error ("SOLID_BSP without MOVETYPE_PUSH"); - model = sv.models[ (int)ent->v.modelindex ]; + model = sv.models[(int) ent->v.modelindex]; if (!model || model->type != mod_brush) SV_Error ("SOLID_BSP with a non bsp model"); @@ -175,14 +177,13 @@ hull_t *SV_HullForEntity (edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset) // calculate an offset value to center the origin VectorSubtract (hull->clip_mins, mins, offset); VectorAdd (offset, ent->v.origin, offset); - } - else - { // create a temp hull from bounding box sizes + } else { // create a temp hull from bounding + // box sizes VectorSubtract (ent->v.mins, maxs, hullmins); VectorSubtract (ent->v.maxs, mins, hullmaxs); hull = SV_HullForBox (hullmins, hullmaxs); - + VectorCopy (ent->v.origin, offset); } @@ -199,8 +200,8 @@ ENTITY AREA CHECKING */ -areanode_t sv_areanodes[AREA_NODES]; -int sv_numareanodes; +areanode_t sv_areanodes[AREA_NODES]; +int sv_numareanodes; /* =============== @@ -208,41 +209,41 @@ SV_CreateAreaNode =============== */ -areanode_t *SV_CreateAreaNode (int depth, vec3_t mins, vec3_t maxs) +areanode_t * +SV_CreateAreaNode (int depth, vec3_t mins, vec3_t maxs) { - areanode_t *anode; - vec3_t size; - vec3_t mins1, maxs1, mins2, maxs2; + areanode_t *anode; + vec3_t size; + vec3_t mins1, maxs1, mins2, maxs2; anode = &sv_areanodes[sv_numareanodes]; sv_numareanodes++; ClearLink (&anode->trigger_edicts); ClearLink (&anode->solid_edicts); - - if (depth == AREA_DEPTH) - { + + if (depth == AREA_DEPTH) { anode->axis = -1; anode->children[0] = anode->children[1] = NULL; return anode; } - + VectorSubtract (maxs, mins, size); if (size[0] > size[1]) anode->axis = 0; else anode->axis = 1; - + anode->dist = 0.5 * (maxs[anode->axis] + mins[anode->axis]); - VectorCopy (mins, mins1); - VectorCopy (mins, mins2); - VectorCopy (maxs, maxs1); - VectorCopy (maxs, maxs2); - + VectorCopy (mins, mins1); + VectorCopy (mins, mins2); + VectorCopy (maxs, maxs1); + VectorCopy (maxs, maxs2); + maxs1[anode->axis] = mins2[anode->axis] = anode->dist; - - anode->children[0] = SV_CreateAreaNode (depth+1, mins2, maxs2); - anode->children[1] = SV_CreateAreaNode (depth+1, mins1, maxs1); + + anode->children[0] = SV_CreateAreaNode (depth + 1, mins2, maxs2); + anode->children[1] = SV_CreateAreaNode (depth + 1, mins1, maxs1); return anode; } @@ -253,11 +254,12 @@ SV_ClearWorld =============== */ -void SV_ClearWorld (void) +void +SV_ClearWorld (void) { SV_InitBoxHull (); - - memset (sv_areanodes, 0, sizeof(sv_areanodes)); + + memset (sv_areanodes, 0, sizeof (sv_areanodes)); sv_numareanodes = 0; SV_CreateAreaNode (0, sv.worldmodel->mins, sv.worldmodel->maxs); } @@ -269,10 +271,11 @@ SV_UnlinkEdict =============== */ -void SV_UnlinkEdict (edict_t *ent) +void +SV_UnlinkEdict (edict_t *ent) { if (!ent->area.prev) - return; // not linked in anywhere + return; // not linked in anywhere RemoveLink (&ent->area); ent->area.prev = ent->area.next = NULL; } @@ -283,49 +286,49 @@ void SV_UnlinkEdict (edict_t *ent) SV_TouchLinks ==================== */ -void SV_TouchLinks ( edict_t *ent, areanode_t *node ) +void +SV_TouchLinks (edict_t *ent, areanode_t *node) { - link_t *l, *next; - edict_t *touch; - int old_self, old_other; + link_t *l, *next; + edict_t *touch; + int old_self, old_other; // touch linked edicts - for (l = node->trigger_edicts.next ; l != &node->trigger_edicts ; l = next) - { + for (l = node->trigger_edicts.next; l != &node->trigger_edicts; l = next) { next = l->next; - touch = EDICT_FROM_AREA(l); + touch = EDICT_FROM_AREA (l); if (touch == ent) continue; if (!touch->v.touch || touch->v.solid != SOLID_TRIGGER) continue; if (ent->v.absmin[0] > touch->v.absmax[0] - || ent->v.absmin[1] > touch->v.absmax[1] - || ent->v.absmin[2] > touch->v.absmax[2] - || ent->v.absmax[0] < touch->v.absmin[0] - || ent->v.absmax[1] < touch->v.absmin[1] - || ent->v.absmax[2] < touch->v.absmin[2] ) + || ent->v.absmin[1] > touch->v.absmax[1] + || ent->v.absmin[2] > touch->v.absmax[2] + || ent->v.absmax[0] < touch->v.absmin[0] + || ent->v.absmax[1] < touch->v.absmin[1] + || ent->v.absmax[2] < touch->v.absmin[2]) continue; - + old_self = pr_global_struct->self; old_other = pr_global_struct->other; - pr_global_struct->self = EDICT_TO_PROG(touch); - pr_global_struct->other = EDICT_TO_PROG(ent); + pr_global_struct->self = EDICT_TO_PROG (touch); + pr_global_struct->other = EDICT_TO_PROG (ent); pr_global_struct->time = sv.time; PR_ExecuteProgram (touch->v.touch); pr_global_struct->self = old_self; pr_global_struct->other = old_other; } - + // recurse down both sides if (node->axis == -1) return; - - if ( ent->v.absmax[node->axis] > node->dist ) - SV_TouchLinks ( ent, node->children[0] ); - if ( ent->v.absmin[node->axis] < node->dist ) - SV_TouchLinks ( ent, node->children[1] ); + + if (ent->v.absmax[node->axis] > node->dist) + SV_TouchLinks (ent, node->children[0]); + if (ent->v.absmin[node->axis] < node->dist) + SV_TouchLinks (ent, node->children[1]); } @@ -335,40 +338,39 @@ SV_FindTouchedLeafs =============== */ -void SV_FindTouchedLeafs (edict_t *ent, mnode_t *node) +void +SV_FindTouchedLeafs (edict_t *ent, mnode_t *node) { - mplane_t *splitplane; - mleaf_t *leaf; - int sides; - int leafnum; + mplane_t *splitplane; + mleaf_t *leaf; + int sides; + int leafnum; if (node->contents == CONTENTS_SOLID) return; - + // add an efrag if the node is a leaf - if ( node->contents < 0) - { + if (node->contents < 0) { if (ent->num_leafs == MAX_ENT_LEAFS) return; - leaf = (mleaf_t *)node; + leaf = (mleaf_t *) node; leafnum = leaf - sv.worldmodel->leafs - 1; ent->leafnums[ent->num_leafs] = leafnum; - ent->num_leafs++; + ent->num_leafs++; return; } - // NODE_MIXED splitplane = node->plane; - sides = BOX_ON_PLANE_SIDE(ent->v.absmin, ent->v.absmax, splitplane); - + sides = BOX_ON_PLANE_SIDE (ent->v.absmin, ent->v.absmax, splitplane); + // recurse down the contacted sides if (sides & 1) SV_FindTouchedLeafs (ent, node->children[0]); - + if (sides & 2) SV_FindTouchedLeafs (ent, node->children[1]); } @@ -379,36 +381,35 @@ SV_LinkEdict =============== */ -void SV_LinkEdict (edict_t *ent, qboolean touch_triggers) +void +SV_LinkEdict (edict_t *ent, qboolean touch_triggers) { - areanode_t *node; - + areanode_t *node; + if (ent->area.prev) - SV_UnlinkEdict (ent); // unlink from old position - + SV_UnlinkEdict (ent); // unlink from old position + if (ent == sv.edicts) - return; // don't add the world + return; // don't add the world if (ent->free) return; // set the abs box - VectorAdd (ent->v.origin, ent->v.mins, ent->v.absmin); + VectorAdd (ent->v.origin, ent->v.mins, ent->v.absmin); VectorAdd (ent->v.origin, ent->v.maxs, ent->v.absmax); // // to make items easier to pick up and allow them to be grabbed off // of shelves, the abs sizes are expanded // - if ((int)ent->v.flags & FL_ITEM) - { + if ((int) ent->v.flags & FL_ITEM) { ent->v.absmin[0] -= 15; ent->v.absmin[1] -= 15; ent->v.absmax[0] += 15; ent->v.absmax[1] += 15; - } - else - { // because movement is clipped an epsilon away from an actual edge, + } else { // because movement is clipped an + // epsilon away from an actual edge, // we must fully check even when bounding boxes don't quite touch ent->v.absmin[0] -= 1; ent->v.absmin[1] -= 1; @@ -417,7 +418,7 @@ void SV_LinkEdict (edict_t *ent, qboolean touch_triggers) ent->v.absmax[1] += 1; ent->v.absmax[2] += 1; } - + // link to PVS leafs ent->num_leafs = 0; if (ent->v.modelindex) @@ -428,8 +429,7 @@ void SV_LinkEdict (edict_t *ent, qboolean touch_triggers) // find the first node that the ent's box crosses node = sv_areanodes; - while (1) - { + while (1) { if (node->axis == -1) break; if (ent->v.absmin[node->axis] > node->dist) @@ -437,19 +437,19 @@ void SV_LinkEdict (edict_t *ent, qboolean touch_triggers) else if (ent->v.absmax[node->axis] < node->dist) node = node->children[1]; else - break; // crosses the node + break; // crosses the node } - -// link it in + +// link it in if (ent->v.solid == SOLID_TRIGGER) InsertLinkBefore (&ent->area, &node->trigger_edicts); else InsertLinkBefore (&ent->area, &node->solid_edicts); - + // if touch_triggers, touch all entities at this node and decend for more if (touch_triggers) - SV_TouchLinks ( ent, sv_areanodes ); + SV_TouchLinks (ent, sv_areanodes); } @@ -470,20 +470,20 @@ SV_HullPointContents ================== */ -int SV_HullPointContents (hull_t *hull, int num, vec3_t p) +int +SV_HullPointContents (hull_t *hull, int num, vec3_t p) { - float d; - dclipnode_t *node; - mplane_t *plane; + float d; + dclipnode_t *node; + mplane_t *plane; - while (num >= 0) - { + while (num >= 0) { if (num < hull->firstclipnode || num > hull->lastclipnode) SV_Error ("SV_HullPointContents: bad node number"); - + node = hull->clipnodes + num; plane = hull->planes + node->planenum; - + if (plane->type < 3) d = p[plane->type] - plane->dist; else @@ -493,11 +493,11 @@ int SV_HullPointContents (hull_t *hull, int num, vec3_t p) else num = node->children[0]; } - + return num; } -#endif // !USE_INTEL_ASM +#endif // !USE_INTEL_ASM /* @@ -506,7 +506,8 @@ SV_PointContents ================== */ -int SV_PointContents (vec3_t p) +int +SV_PointContents (vec3_t p) { return SV_HullPointContents (&sv.worldmodel->hulls[0], 0, p); } @@ -521,15 +522,18 @@ A small wrapper around SV_BoxInSolidEntity that never clips against the supplied entity. ============ */ -edict_t *SV_TestEntityPosition (edict_t *ent) +edict_t * +SV_TestEntityPosition (edict_t *ent) { - trace_t trace; + trace_t trace; + + trace = + SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, ent->v.origin, 0, + ent); - trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, ent->v.origin, 0, ent); - if (trace.startsolid) return sv.edicts; - + return NULL; } @@ -550,31 +554,30 @@ SV_RecursiveHullCheck ================== */ -qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace) +qboolean +SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, + vec3_t p2, trace_t *trace) { - dclipnode_t *node; - mplane_t *plane; - float t1, t2; - float frac; - int i; - vec3_t mid; - int side; - float midf; + dclipnode_t *node; + mplane_t *plane; + float t1, t2; + float frac; + int i; + vec3_t mid; + int side; + float midf; // check for empty - if (num < 0) - { - if (num != CONTENTS_SOLID) - { + if (num < 0) { + if (num != CONTENTS_SOLID) { trace->allsolid = false; if (num == CONTENTS_EMPTY) trace->inopen = true; else trace->inwater = true; - } - else + } else trace->startsolid = true; - return true; // empty + return true; // empty } if (num < hull->firstclipnode || num > hull->lastclipnode) @@ -586,94 +589,91 @@ qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec node = hull->clipnodes + num; plane = hull->planes + node->planenum; - if (plane->type < 3) - { + if (plane->type < 3) { t1 = p1[plane->type] - plane->dist; t2 = p2[plane->type] - plane->dist; - } - else - { + } else { t1 = DotProduct (plane->normal, p1) - plane->dist; t2 = DotProduct (plane->normal, p2) - plane->dist; } - + #if 1 if (t1 >= 0 && t2 >= 0) - return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace); + return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, + trace); if (t1 < 0 && t2 < 0) - return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace); + return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, + trace); #else - if ( (t1 >= DIST_EPSILON && t2 >= DIST_EPSILON) || (t2 > t1 && t1 >= 0) ) - return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace); - if ( (t1 <= -DIST_EPSILON && t2 <= -DIST_EPSILON) || (t2 < t1 && t1 <= 0) ) - return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace); + if ((t1 >= DIST_EPSILON && t2 >= DIST_EPSILON) || (t2 > t1 && t1 >= 0)) + return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, + trace); + if ((t1 <= -DIST_EPSILON && t2 <= -DIST_EPSILON) || (t2 < t1 && t1 <= 0)) + return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, + trace); #endif // put the crosspoint DIST_EPSILON pixels on the near side if (t1 < 0) - frac = (t1 + DIST_EPSILON)/(t1-t2); + frac = (t1 + DIST_EPSILON) / (t1 - t2); else - frac = (t1 - DIST_EPSILON)/(t1-t2); + frac = (t1 - DIST_EPSILON) / (t1 - t2); if (frac < 0) frac = 0; if (frac > 1) frac = 1; - - midf = p1f + (p2f - p1f)*frac; - for (i=0 ; i<3 ; i++) - mid[i] = p1[i] + frac*(p2[i] - p1[i]); + + midf = p1f + (p2f - p1f) * frac; + for (i = 0; i < 3; i++) + mid[i] = p1[i] + frac * (p2[i] - p1[i]); side = (t1 < 0); // move up to the node - if (!SV_RecursiveHullCheck (hull, node->children[side], p1f, midf, p1, mid, trace) ) - return false; + if (!SV_RecursiveHullCheck + (hull, node->children[side], p1f, midf, p1, mid, trace)) return false; #ifdef PARANOID if (SV_HullPointContents (sv_hullmodel, mid, node->children[side]) - == CONTENTS_SOLID) - { + == CONTENTS_SOLID) { Con_Printf ("mid PointInHullSolid\n"); return false; } #endif - - if (SV_HullPointContents (hull, node->children[side^1], mid) - != CONTENTS_SOLID) + + if (SV_HullPointContents (hull, node->children[side ^ 1], mid) + != CONTENTS_SOLID) // go past the node - return SV_RecursiveHullCheck (hull, node->children[side^1], midf, p2f, mid, p2, trace); - + return SV_RecursiveHullCheck (hull, node->children[side ^ 1], midf, p2f, + mid, p2, trace); + if (trace->allsolid) - return false; // never got out of the solid area - + return false; // never got out of the solid area + //================== // the other side of the node is solid, this is the impact point //================== - if (!side) - { + if (!side) { VectorCopy (plane->normal, trace->plane.normal); trace->plane.dist = plane->dist; - } - else - { + } else { VectorSubtract (vec3_origin, plane->normal, trace->plane.normal); trace->plane.dist = -plane->dist; } while (SV_HullPointContents (hull, hull->firstclipnode, mid) - == CONTENTS_SOLID) - { // shouldn't really happen, but does occasionally + == CONTENTS_SOLID) { // shouldn't really happen, but does + // occasionally frac -= 0.1; - if (frac < 0) - { + if (frac < 0) { trace->fraction = midf; VectorCopy (mid, trace->endpos); Con_Printf ("backup past 0\n"); return false; } - midf = p1f + (p2f - p1f)*frac; - for (i=0 ; i<3 ; i++) - mid[i] = p1[i] + frac*(p2[i] - p1[i]); + midf = p1f + (p2f - p1f) * frac; + for (i = 0; i < 3; i++) + mid[i] = p1[i] + frac * (p2[i] - p1[i]); } trace->fraction = midf; @@ -691,15 +691,18 @@ Handles selection or creation of a clipping hull, and offseting (and eventually rotation) of the end points ================== */ -trace_t SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end) +trace_t +SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, + vec3_t end) { - trace_t trace; - vec3_t offset; - vec3_t start_l, end_l; - hull_t *hull; + trace_t trace; + vec3_t offset; + vec3_t start_l, end_l; + hull_t *hull; // fill in a default trace - memset (&trace, 0, sizeof(trace_t)); + memset (&trace, 0, sizeof (trace_t)); + trace.fraction = 1; trace.allsolid = true; VectorCopy (end, trace.endpos); @@ -711,14 +714,15 @@ trace_t SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t max VectorSubtract (end, offset, end_l); // trace a line through the apropriate clipping hull - SV_RecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, &trace); + SV_RecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, + &trace); // fix trace up by the offset if (trace.fraction != 1) VectorAdd (trace.endpos, offset, trace.endpos); // did we clip the move? - if (trace.fraction < 1 || trace.startsolid ) + if (trace.fraction < 1 || trace.startsolid) trace.ent = ent; return trace; @@ -733,17 +737,17 @@ SV_ClipToLinks Mins and maxs enclose the entire area swept by the move ==================== */ -void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) +void +SV_ClipToLinks (areanode_t *node, moveclip_t * clip) { - link_t *l, *next; - edict_t *touch; - trace_t trace; + link_t *l, *next; + edict_t *touch; + trace_t trace; // touch linked edicts - for (l = node->solid_edicts.next ; l != &node->solid_edicts ; l = next) - { + for (l = node->solid_edicts.next; l != &node->solid_edicts; l = next) { next = l->next; - touch = EDICT_FROM_AREA(l); + touch = EDICT_FROM_AREA (l); if (touch->v.solid == SOLID_NOT) continue; if (touch == clip->passedict) @@ -755,55 +759,54 @@ void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) continue; if (clip->boxmins[0] > touch->v.absmax[0] - || clip->boxmins[1] > touch->v.absmax[1] - || clip->boxmins[2] > touch->v.absmax[2] - || clip->boxmaxs[0] < touch->v.absmin[0] - || clip->boxmaxs[1] < touch->v.absmin[1] - || clip->boxmaxs[2] < touch->v.absmin[2] ) + || clip->boxmins[1] > touch->v.absmax[1] + || clip->boxmins[2] > touch->v.absmax[2] + || clip->boxmaxs[0] < touch->v.absmin[0] + || clip->boxmaxs[1] < touch->v.absmin[1] + || clip->boxmaxs[2] < touch->v.absmin[2]) continue; - if (clip->passedict!=0 && clip->passedict->v.size[0] && !touch->v.size[0]) - continue; // points never interact + if (clip->passedict != 0 && clip->passedict->v.size[0] + && !touch->v.size[0]) continue; // points never interact - // might intersect, so do an exact clip + // might intersect, so do an exact clip if (clip->trace.allsolid) return; - if (clip->passedict) - { - if (PROG_TO_EDICT(touch->v.owner) == clip->passedict) - continue; // don't clip against own missiles - if (PROG_TO_EDICT(clip->passedict->v.owner) == touch) - continue; // don't clip against owner + if (clip->passedict) { + if (PROG_TO_EDICT (touch->v.owner) == clip->passedict) + continue; // don't clip against own missiles + if (PROG_TO_EDICT (clip->passedict->v.owner) == touch) + continue; // don't clip against owner } - if ((int)touch->v.flags & FL_MONSTER) - trace = SV_ClipMoveToEntity (touch, clip->start, clip->mins2, clip->maxs2, clip->end); + if ((int) touch->v.flags & FL_MONSTER) + trace = + SV_ClipMoveToEntity (touch, clip->start, clip->mins2, + clip->maxs2, clip->end); else - trace = SV_ClipMoveToEntity (touch, clip->start, clip->mins, clip->maxs, clip->end); - if (trace.allsolid || trace.startsolid || - trace.fraction < clip->trace.fraction) - { + trace = + SV_ClipMoveToEntity (touch, clip->start, clip->mins, clip->maxs, + clip->end); + if (trace.allsolid || trace.startsolid + || trace.fraction < clip->trace.fraction) { trace.ent = touch; - if (clip->trace.startsolid) - { + if (clip->trace.startsolid) { clip->trace = trace; clip->trace.startsolid = true; - } - else + } else clip->trace = trace; - } - else if (trace.startsolid) + } else if (trace.startsolid) clip->trace.startsolid = true; } - + // recurse down both sides if (node->axis == -1) return; - if ( clip->boxmaxs[node->axis] > node->dist ) - SV_ClipToLinks ( node->children[0], clip ); - if ( clip->boxmins[node->axis] < node->dist ) - SV_ClipToLinks ( node->children[1], clip ); + if (clip->boxmaxs[node->axis] > node->dist) + SV_ClipToLinks (node->children[0], clip); + if (clip->boxmins[node->axis] < node->dist) + SV_ClipToLinks (node->children[1], clip); } @@ -812,24 +815,22 @@ void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) SV_MoveBounds ================== */ -void SV_MoveBounds (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, vec3_t boxmins, vec3_t boxmaxs) +void +SV_MoveBounds (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, + vec3_t boxmins, vec3_t boxmaxs) { #if 0 // debug to test against everything -boxmins[0] = boxmins[1] = boxmins[2] = -9999; -boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999; + boxmins[0] = boxmins[1] = boxmins[2] = -9999; + boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999; #else - int i; - - for (i=0 ; i<3 ; i++) - { - if (end[i] > start[i]) - { + int i; + + for (i = 0; i < 3; i++) { + if (end[i] > start[i]) { boxmins[i] = start[i] + mins[i] - 1; boxmaxs[i] = end[i] + maxs[i] + 1; - } - else - { + } else { boxmins[i] = end[i] + mins[i] - 1; boxmaxs[i] = start[i] + maxs[i] + 1; } @@ -842,15 +843,17 @@ boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999; SV_Move ================== */ -trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, edict_t *passedict) +trace_t +SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, + edict_t *passedict) { - moveclip_t clip; - int i; + moveclip_t clip; + int i; - memset ( &clip, 0, sizeof ( moveclip_t ) ); + memset (&clip, 0, sizeof (moveclip_t)); // clip to world - clip.trace = SV_ClipMoveToEntity ( sv.edicts, start, mins, maxs, end ); + clip.trace = SV_ClipMoveToEntity (sv.edicts, start, mins, maxs, end); clip.start = start; clip.end = end; @@ -859,25 +862,22 @@ trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, e clip.type = type; clip.passedict = passedict; - if (type == MOVE_MISSILE) - { - for (i=0 ; i<3 ; i++) - { + if (type == MOVE_MISSILE) { + for (i = 0; i < 3; i++) { clip.mins2[i] = -15; clip.maxs2[i] = 15; } - } - else - { + } else { VectorCopy (mins, clip.mins2); VectorCopy (maxs, clip.maxs2); } - + // create the bounding box of the entire move - SV_MoveBounds ( start, clip.mins2, clip.maxs2, end, clip.boxmins, clip.boxmaxs ); + SV_MoveBounds (start, clip.mins2, clip.maxs2, end, clip.boxmins, + clip.boxmaxs); // clip to entities - SV_ClipToLinks ( sv_areanodes, &clip ); + SV_ClipToLinks (sv_areanodes, &clip); return clip.trace; } @@ -890,55 +890,52 @@ SV_TestPlayerPosition ============ */ -edict_t *SV_TestPlayerPosition (edict_t *ent, vec3_t origin) +edict_t * +SV_TestPlayerPosition (edict_t *ent, vec3_t origin) { - hull_t *hull; - edict_t *check; - vec3_t boxmins, boxmaxs; - vec3_t offset; - int e; - + hull_t *hull; + edict_t *check; + vec3_t boxmins, boxmaxs; + vec3_t offset; + int e; + // check world first hull = &sv.worldmodel->hulls[1]; - if ( SV_HullPointContents (hull, hull->firstclipnode, origin) != CONTENTS_EMPTY ) - return sv.edicts; + if (SV_HullPointContents (hull, hull->firstclipnode, origin) != + CONTENTS_EMPTY) return sv.edicts; // check all entities VectorAdd (origin, ent->v.mins, boxmins); VectorAdd (origin, ent->v.maxs, boxmaxs); - - check = NEXT_EDICT(sv.edicts); - for (e=1 ; efree) continue; if (check->v.solid != SOLID_BSP && - check->v.solid != SOLID_BBOX && - check->v.solid != SOLID_SLIDEBOX) + check->v.solid != SOLID_BBOX && check->v.solid != SOLID_SLIDEBOX) continue; if (boxmins[0] > check->v.absmax[0] - || boxmins[1] > check->v.absmax[1] - || boxmins[2] > check->v.absmax[2] - || boxmaxs[0] < check->v.absmin[0] - || boxmaxs[1] < check->v.absmin[1] - || boxmaxs[2] < check->v.absmin[2] ) + || boxmins[1] > check->v.absmax[1] + || boxmins[2] > check->v.absmax[2] + || boxmaxs[0] < check->v.absmin[0] + || boxmaxs[1] < check->v.absmin[1] + || boxmaxs[2] < check->v.absmin[2]) continue; if (check == ent) continue; - // get the clipping hull + // get the clipping hull hull = SV_HullForEntity (check, ent->v.mins, ent->v.maxs, offset); - + VectorSubtract (origin, offset, offset); - - // test the point - if ( SV_HullPointContents (hull, hull->firstclipnode, offset) != CONTENTS_EMPTY ) - return check; + + // test the point + if (SV_HullPointContents (hull, hull->firstclipnode, offset) != + CONTENTS_EMPTY) return check; } return NULL; } - - diff --git a/source/zone.c b/source/zone.c index 099f1bc..d79ba96 100644 --- a/source/zone.c +++ b/source/zone.c @@ -27,7 +27,7 @@ */ #ifdef HAVE_CONFIG_H -# include +# include "config.h" #endif #include "sys.h" #include "qtypes.h" @@ -45,8 +45,8 @@ #define MINFRAGMENT 64 -void Cache_FreeLow (int new_low_hunk); -void Cache_FreeHigh (int new_high_hunk); +void Cache_FreeLow (int new_low_hunk); +void Cache_FreeHigh (int new_high_hunk); /* @@ -59,23 +59,23 @@ all big things are allocated on the hunk. //============================================================================ -typedef struct -{ - int sentinal; - int size; // including sizeof(hunk_t), -1 = not allocated - char name[8]; +typedef struct { + int sentinal; + int size; // including sizeof(hunk_t), -1 = not + // allocated + char name[8]; } hunk_t; -byte *hunk_base; -int hunk_size; +byte *hunk_base; +int hunk_size; -int hunk_low_used; -int hunk_high_used; +int hunk_low_used; +int hunk_high_used; -qboolean hunk_tempactive; -int hunk_tempmark; +qboolean hunk_tempactive; +int hunk_tempmark; -void R_FreeTextures (void); +void R_FreeTextures (void); /* ============== @@ -84,17 +84,17 @@ Hunk_Check Run consistancy and sentinal trahing checks ============== */ -void Hunk_Check (void) +void +Hunk_Check (void) { - hunk_t *h; - - for (h = (hunk_t *)hunk_base ; (byte *)h != hunk_base + hunk_low_used ; ) - { + hunk_t *h; + + for (h = (hunk_t *) hunk_base; (byte *) h != hunk_base + hunk_low_used;) { if (h->sentinal != HUNK_SENTINAL) Sys_Error ("Hunk_Check: trashed sentinal"); - if (h->size < 16 || h->size + (byte *)h - hunk_base > hunk_size) + if (h->size < 16 || h->size + (byte *) h - hunk_base > hunk_size) Sys_Error ("Hunk_Check: bad size"); - h = (hunk_t *)((byte *)h+h->size); + h = (hunk_t *) ((byte *) h + h->size); } } @@ -106,73 +106,71 @@ If "all" is specified, every single allocation is printed. Otherwise, allocations with the same name will be totaled up before printing. ============== */ -void Hunk_Print (qboolean all) +void +Hunk_Print (qboolean all) { - hunk_t *h, *next, *endlow, *starthigh, *endhigh; - int count, sum; - int totalblocks; - char name[9]; + hunk_t *h, *next, *endlow, *starthigh, *endhigh; + int count, sum; + int totalblocks; + char name[9]; name[8] = 0; count = 0; sum = 0; totalblocks = 0; - - h = (hunk_t *)hunk_base; - endlow = (hunk_t *)(hunk_base + hunk_low_used); - starthigh = (hunk_t *)(hunk_base + hunk_size - hunk_high_used); - endhigh = (hunk_t *)(hunk_base + hunk_size); + + h = (hunk_t *) hunk_base; + endlow = (hunk_t *) (hunk_base + hunk_low_used); + starthigh = (hunk_t *) (hunk_base + hunk_size - hunk_high_used); + endhigh = (hunk_t *) (hunk_base + hunk_size); Con_Printf (" :%8i total hunk size\n", hunk_size); Con_Printf ("-------------------------\n"); - while (1) - { - // - // skip to the high hunk if done with low hunk - // - if ( h == endlow ) - { + while (1) { + // + // skip to the high hunk if done with low hunk + // + if (h == endlow) { Con_Printf ("-------------------------\n"); - Con_Printf (" :%8i REMAINING\n", hunk_size - hunk_low_used - hunk_high_used); + Con_Printf (" :%8i REMAINING\n", + hunk_size - hunk_low_used - hunk_high_used); Con_Printf ("-------------------------\n"); h = starthigh; } - - // - // if totally done, break - // - if ( h == endhigh ) + // + // if totally done, break + // + if (h == endhigh) break; - // - // run consistancy checks - // + // + // run consistancy checks + // if (h->sentinal != HUNK_SENTINAL) Sys_Error ("Hunk_Check: trahsed sentinal"); - if (h->size < 16 || h->size + (byte *)h - hunk_base > hunk_size) + if (h->size < 16 || h->size + (byte *) h - hunk_base > hunk_size) Sys_Error ("Hunk_Check: bad size"); - - next = (hunk_t *)((byte *)h+h->size); + + next = (hunk_t *) ((byte *) h + h->size); count++; totalblocks++; sum += h->size; - // - // print the single block - // + // + // print the single block + // memcpy (name, h->name, 8); if (all) - Con_Printf ("%8p :%8i %8s\n",h, h->size, name); - - // - // print the total - // - if (next == endlow || next == endhigh || - strncmp (h->name, next->name, 8) ) - { + Con_Printf ("%8p :%8i %8s\n", h, h->size, name); + + // + // print the total + // + if (next == endlow || next == endhigh || + strncmp (h->name, next->name, 8)) { if (!all) - Con_Printf (" :%8i %8s (TOTAL)\n",sum, name); + Con_Printf (" :%8i %8s (TOTAL)\n", sum, name); count = 0; sum = 0; } @@ -182,7 +180,7 @@ void Hunk_Print (qboolean all) Con_Printf ("-------------------------\n"); Con_Printf ("%8i total blocks\n", totalblocks); - + } /* @@ -190,39 +188,44 @@ void Hunk_Print (qboolean all) Hunk_AllocName =================== */ -void *Hunk_AllocName (int size, char *name) +void * +Hunk_AllocName (int size, char *name) { - hunk_t *h; - + hunk_t *h; + #ifdef PARANOID Hunk_Check (); #endif if (size < 0) Sys_Error ("Hunk_Alloc: bad size: %i", size); - - size = sizeof(hunk_t) + ((size+15)&~15); - + + size = sizeof (hunk_t) + ((size + 15) & ~15); + if (hunk_size - hunk_low_used - hunk_high_used < size) -// Sys_Error ("Hunk_Alloc: failed on %i bytes",size); +// Sys_Error ("Hunk_Alloc: failed on %i bytes",size); #ifdef _WIN32 - Sys_Error ("Not enough RAM allocated. Try starting using \"-heapsize 16000\" on the %s command line.", PROGRAM); + Sys_Error + ("Not enough RAM allocated. Try starting using \"-heapsize 16000\" on the %s command line.", + PROGRAM); #else - Sys_Error ("Not enough RAM allocated. Try starting using \"-mem 16\" on the %s command line.", PROGRAM); + Sys_Error + ("Not enough RAM allocated. Try starting using \"-mem 16\" on the %s command line.", + PROGRAM); #endif - - h = (hunk_t *)(hunk_base + hunk_low_used); + + h = (hunk_t *) (hunk_base + hunk_low_used); hunk_low_used += size; Cache_FreeLow (hunk_low_used); memset (h, 0, size); - + h->size = size; h->sentinal = HUNK_SENTINAL; strncpy (h->name, name, 8); - - return (void *)(h+1); + + return (void *) (h + 1); } /* @@ -230,17 +233,20 @@ void *Hunk_AllocName (int size, char *name) Hunk_Alloc =================== */ -void *Hunk_Alloc (int size) +void * +Hunk_Alloc (int size) { return Hunk_AllocName (size, "unknown"); } -int Hunk_LowMark (void) +int +Hunk_LowMark (void) { return hunk_low_used; } -void Hunk_FreeToLowMark (int mark) +void +Hunk_FreeToLowMark (int mark) { if (mark < 0 || mark > hunk_low_used) Sys_Error ("Hunk_FreeToLowMark: bad mark %i", mark); @@ -248,10 +254,10 @@ void Hunk_FreeToLowMark (int mark) hunk_low_used = mark; } -int Hunk_HighMark (void) +int +Hunk_HighMark (void) { - if (hunk_tempactive) - { + if (hunk_tempactive) { hunk_tempactive = false; Hunk_FreeToHighMark (hunk_tempmark); } @@ -259,10 +265,10 @@ int Hunk_HighMark (void) return hunk_high_used; } -void Hunk_FreeToHighMark (int mark) +void +Hunk_FreeToHighMark (int mark) { - if (hunk_tempactive) - { + if (hunk_tempactive) { hunk_tempactive = false; Hunk_FreeToHighMark (hunk_tempmark); } @@ -278,42 +284,40 @@ void Hunk_FreeToHighMark (int mark) Hunk_HighAllocName =================== */ -void *Hunk_HighAllocName (int size, char *name) +void * +Hunk_HighAllocName (int size, char *name) { - hunk_t *h; + hunk_t *h; if (size < 0) Sys_Error ("Hunk_HighAllocName: bad size: %i", size); - if (hunk_tempactive) - { + if (hunk_tempactive) { Hunk_FreeToHighMark (hunk_tempmark); hunk_tempactive = false; } - #ifdef PARANOID Hunk_Check (); #endif - size = sizeof(hunk_t) + ((size+15)&~15); + size = sizeof (hunk_t) + ((size + 15) & ~15); - if (hunk_size - hunk_low_used - hunk_high_used < size) - { - Con_Printf ("Hunk_HighAlloc: failed on %i bytes\n",size); + if (hunk_size - hunk_low_used - hunk_high_used < size) { + Con_Printf ("Hunk_HighAlloc: failed on %i bytes\n", size); return NULL; } hunk_high_used += size; Cache_FreeHigh (hunk_high_used); - h = (hunk_t *)(hunk_base + hunk_size - hunk_high_used); + h = (hunk_t *) (hunk_base + hunk_size - hunk_high_used); memset (h, 0, size); h->size = size; h->sentinal = HUNK_SENTINAL; strncpy (h->name, name, 8); - return (void *)(h+1); + return (void *) (h + 1); } @@ -324,18 +328,18 @@ Hunk_TempAlloc Return space from the top of the hunk ================= */ -void *Hunk_TempAlloc (int size) +void * +Hunk_TempAlloc (int size) { - void *buf; + void *buf; - size = (size+15)&~15; - - if (hunk_tempactive) - { + size = (size + 15) & ~15; + + if (hunk_tempactive) { Hunk_FreeToHighMark (hunk_tempmark); hunk_tempactive = false; } - + hunk_tempmark = Hunk_HighMark (); buf = Hunk_HighAllocName (size, "temp"); @@ -353,45 +357,42 @@ CACHE MEMORY =============================================================================== */ -typedef struct cache_system_s -{ - int size; // including this header - cache_user_t *user; - char name[16]; - struct cache_system_s *prev, *next; - struct cache_system_s *lru_prev, *lru_next; // for LRU flushing +typedef struct cache_system_s { + int size; // including this header + cache_user_t *user; + char name[16]; + struct cache_system_s *prev, *next; + struct cache_system_s *lru_prev, *lru_next; // for LRU flushing } cache_system_t; cache_system_t *Cache_TryAlloc (int size, qboolean nobottom); -cache_system_t cache_head; +cache_system_t cache_head; /* =========== Cache_Move =========== */ -void Cache_Move ( cache_system_t *c) +void +Cache_Move (cache_system_t * c) { - cache_system_t *new; + cache_system_t *new; // we are clearing up space at the bottom, so only allocate it late new = Cache_TryAlloc (c->size, true); - if (new) - { -// Con_Printf ("cache_move ok\n"); + if (new) { +// Con_Printf ("cache_move ok\n"); - memcpy ( new+1, c+1, c->size - sizeof(cache_system_t) ); + memcpy (new + 1, c + 1, c->size - sizeof (cache_system_t)); new->user = c->user; - memcpy (new->name, c->name, sizeof(new->name)); + memcpy (new->name, c->name, sizeof (new->name)); Cache_Free (c->user); - new->user->data = (void *)(new+1); - } - else - { -// Con_Printf ("cache_move failed\n"); + new->user->data = (void *) (new + 1); + } else { +// Con_Printf ("cache_move failed\n"); - Cache_Free (c->user); // tough luck... + Cache_Free (c->user); // tough luck... } } @@ -402,18 +403,18 @@ Cache_FreeLow Throw things out until the hunk can be expanded to the given point ============ */ -void Cache_FreeLow (int new_low_hunk) +void +Cache_FreeLow (int new_low_hunk) { - cache_system_t *c; - - while (1) - { + cache_system_t *c; + + while (1) { c = cache_head.next; if (c == &cache_head) - return; // nothing in cache at all - if ((byte *)c >= hunk_base + new_low_hunk) - return; // there is space to grow the hunk - Cache_Move ( c ); // reclaim the space + return; // nothing in cache at all + if ((byte *) c >= hunk_base + new_low_hunk) + return; // there is space to grow the hunk + Cache_Move (c); // reclaim the space } } @@ -424,40 +425,41 @@ Cache_FreeHigh Throw things out until the hunk can be expanded to the given point ============ */ -void Cache_FreeHigh (int new_high_hunk) +void +Cache_FreeHigh (int new_high_hunk) { - cache_system_t *c, *prev; - + cache_system_t *c, *prev; + prev = NULL; - while (1) - { + while (1) { c = cache_head.prev; if (c == &cache_head) - return; // nothing in cache at all - if ( (byte *)c + c->size <= hunk_base + hunk_size - new_high_hunk) - return; // there is space to grow the hunk + return; // nothing in cache at all + if ((byte *) c + c->size <= hunk_base + hunk_size - new_high_hunk) + return; // there is space to grow the hunk if (c == prev) - Cache_Free (c->user); // didn't move out of the way - else - { - Cache_Move (c); // try to move it + Cache_Free (c->user); // didn't move out of the way + else { + Cache_Move (c); // try to move it prev = c; } } } -void Cache_UnlinkLRU (cache_system_t *cs) +void +Cache_UnlinkLRU (cache_system_t * cs) { if (!cs->lru_next || !cs->lru_prev) Sys_Error ("Cache_UnlinkLRU: NULL link"); cs->lru_next->lru_prev = cs->lru_prev; cs->lru_prev->lru_next = cs->lru_next; - + cs->lru_prev = cs->lru_next = NULL; } -void Cache_MakeLRU (cache_system_t *cs) +void +Cache_MakeLRU (cache_system_t * cs) { if (cs->lru_next || cs->lru_prev) Sys_Error ("Cache_MakeLRU: active link"); @@ -476,76 +478,70 @@ Looks for a free block of memory between the high and low hunk marks Size should already include the header and padding ============ */ -cache_system_t *Cache_TryAlloc (int size, qboolean nobottom) +cache_system_t * +Cache_TryAlloc (int size, qboolean nobottom) { - cache_system_t *cs, *new; - + cache_system_t *cs, *new; + // is the cache completely empty? - if (!nobottom && cache_head.prev == &cache_head) - { + if (!nobottom && cache_head.prev == &cache_head) { if (hunk_size - hunk_high_used - hunk_low_used < size) Sys_Error ("Cache_TryAlloc: %i is greater then free hunk", size); new = (cache_system_t *) (hunk_base + hunk_low_used); - memset (new, 0, sizeof(*new)); + memset (new, 0, sizeof (*new)); new->size = size; cache_head.prev = cache_head.next = new; new->prev = new->next = &cache_head; - + Cache_MakeLRU (new); return new; } - // search from the bottom up for space new = (cache_system_t *) (hunk_base + hunk_low_used); cs = cache_head.next; - - do - { - if (!nobottom || cs != cache_head.next) - { - if ( (byte *)cs - (byte *)new >= size) - { // found space - memset (new, 0, sizeof(*new)); + + do { + if (!nobottom || cs != cache_head.next) { + if ((byte *) cs - (byte *) new >= size) { // found space + memset (new, 0, sizeof (*new)); new->size = size; - + new->next = cs; new->prev = cs->prev; cs->prev->next = new; cs->prev = new; - + Cache_MakeLRU (new); - + return new; } } - - // continue looking - new = (cache_system_t *)((byte *)cs + cs->size); + // continue looking + new = (cache_system_t *) ((byte *) cs + cs->size); cs = cs->next; } while (cs != &cache_head); - + // try to allocate one at the very end - if ( hunk_base + hunk_size - hunk_high_used - (byte *)new >= size) - { - memset (new, 0, sizeof(*new)); + if (hunk_base + hunk_size - hunk_high_used - (byte *) new >= size) { + memset (new, 0, sizeof (*new)); new->size = size; - + new->next = &cache_head; new->prev = cache_head.prev; cache_head.prev->next = new; cache_head.prev = new; - + Cache_MakeLRU (new); return new; } - - return NULL; // couldn't allocate + + return NULL; // couldn't allocate } /* @@ -555,10 +551,11 @@ Cache_Flush Throw everything out, so new data will be demand cached ============ */ -void Cache_Flush (void) +void +Cache_Flush (void) { while (cache_head.next != &cache_head) - Cache_Free ( cache_head.next->user ); // reclaim the space + Cache_Free (cache_head.next->user); // reclaim the space } @@ -568,12 +565,12 @@ Cache_Print ============ */ -void Cache_Print (void) +void +Cache_Print (void) { - cache_system_t *cd; + cache_system_t *cd; - for (cd = cache_head.next ; cd != &cache_head ; cd = cd->next) - { + for (cd = cache_head.next; cd != &cache_head; cd = cd->next) { Con_Printf ("%8i : %s\n", cd->size, cd->name); } } @@ -584,9 +581,12 @@ Cache_Report ============ */ -void Cache_Report (void) +void +Cache_Report (void) { - Con_DPrintf ("%4.1f megabyte data cache\n", (hunk_size - hunk_high_used - hunk_low_used) / (float)(1024*1024) ); + Con_DPrintf ("%4.1f megabyte data cache\n", + (hunk_size - hunk_high_used - + hunk_low_used) / (float) (1024 * 1024)); } /* @@ -595,7 +595,8 @@ Cache_Compact ============ */ -void Cache_Compact (void) +void +Cache_Compact (void) { } @@ -605,7 +606,8 @@ Cache_Init ============ */ -void Cache_Init (void) +void +Cache_Init (void) { cache_head.next = cache_head.prev = &cache_head; cache_head.lru_next = cache_head.lru_prev = &cache_head; @@ -620,14 +622,15 @@ Cache_Free Frees the memory and removes it from the LRU list ============== */ -void Cache_Free (cache_user_t *c) +void +Cache_Free (cache_user_t *c) { - cache_system_t *cs; + cache_system_t *cs; if (!c->data) Sys_Error ("Cache_Free: not allocated"); - cs = ((cache_system_t *)c->data) - 1; + cs = ((cache_system_t *) c->data) - 1; cs->prev->next = cs->next; cs->next->prev = cs->prev; @@ -645,19 +648,20 @@ void Cache_Free (cache_user_t *c) Cache_Check ============== */ -void *Cache_Check (cache_user_t *c) +void * +Cache_Check (cache_user_t *c) { - cache_system_t *cs; + cache_system_t *cs; if (!c->data) return NULL; - cs = ((cache_system_t *)c->data) - 1; + cs = ((cache_system_t *) c->data) - 1; // move to head of LRU Cache_UnlinkLRU (cs); Cache_MakeLRU (cs); - + return c->data; } @@ -667,37 +671,35 @@ void *Cache_Check (cache_user_t *c) Cache_Alloc ============== */ -void *Cache_Alloc (cache_user_t *c, int size, char *name) +void * +Cache_Alloc (cache_user_t *c, int size, char *name) { - cache_system_t *cs; + cache_system_t *cs; if (c->data) Sys_Error ("Cache_Alloc: allready allocated"); - + if (size <= 0) Sys_Error ("Cache_Alloc: size %i", size); - size = (size + sizeof(cache_system_t) + 15) & ~15; + size = (size + sizeof (cache_system_t) + 15) & ~15; -// find memory for it - while (1) - { +// find memory for it + while (1) { cs = Cache_TryAlloc (size, false); - if (cs) - { - strncpy (cs->name, name, sizeof(cs->name)-1); - c->data = (void *)(cs+1); + if (cs) { + strncpy (cs->name, name, sizeof (cs->name) - 1); + c->data = (void *) (cs + 1); cs->user = c; break; } - - // free the least recently used cahedat + // free the least recently used cahedat if (cache_head.lru_prev == &cache_head) Sys_Error ("Cache_Alloc: out of memory"); - // not enough memory at all - Cache_Free ( cache_head.lru_prev->user ); - } - + // not enough memory at all + Cache_Free (cache_head.lru_prev->user); + } + return Cache_Check (c); } @@ -709,13 +711,13 @@ void *Cache_Alloc (cache_user_t *c, int size, char *name) Memory_Init ======================== */ -void Memory_Init (void *buf, int size) +void +Memory_Init (void *buf, int size) { hunk_base = buf; hunk_size = size; hunk_low_used = 0; hunk_high_used = 0; - + Cache_Init (); } -