code
stringlengths
1
2.06M
language
stringclasses
1 value
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // vid_win.c -- Win32 video driver #include "quakedef.h" #include "winquake.h" #include "d_local.h" #include "resource.h" #define MAX_MODE_LIST 30 #define VID_ROW_SIZE 3 qboolean dibonly; extern int Minimized; HWND mainwindow; HWND WINAPI InitializeWindow (HINSTANCE hInstance, int nCmdShow); 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; static DEVMODE gdevmode; static qboolean startwindowed = 0, windowed_mode_set; 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; viddef_t vid; // global video state #define MODE_WINDOWED 0 #define MODE_SETTABLE_WINDOW 2 #define NO_MODE (MODE_WINDOWED - 1) #define MODE_FULLSCREEN_DEFAULT (MODE_WINDOWED + 3) // Note that 0 is MODE_WINDOWED cvar_t vid_mode = {"vid_mode","0", false}; // Note that 0 is MODE_WINDOWED cvar_t _vid_default_mode = {"_vid_default_mode","0", true}; // Note that 3 is MODE_FULLSCREEN_DEFAULT cvar_t _vid_default_mode_win = {"_vid_default_mode_win","3", true}; cvar_t vid_wait = {"vid_wait","0"}; cvar_t vid_nopageflip = {"vid_nopageflip","0", true}; cvar_t _vid_wait_override = {"_vid_wait_override", "0", true}; cvar_t vid_config_x = {"vid_config_x","800", true}; cvar_t vid_config_y = {"vid_config_y","600", true}; cvar_t vid_stretch_by_2 = {"vid_stretch_by_2","1", true}; cvar_t _windowed_mouse = {"_windowed_mouse","0", true}; cvar_t vid_fullscreen_mode = {"vid_fullscreen_mode","3", true}; cvar_t vid_windowed_mode = {"vid_windowed_mode","0", true}; cvar_t block_switch = {"block_switch","0", true}; cvar_t vid_window_x = {"vid_window_x", "0", true}; cvar_t vid_window_y = {"vid_window_y", "0", true}; typedef struct { int width; int height; } lmode_t; 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; modestate_t modestate = MS_UNINIT; static byte *vid_surfcache; static int vid_surfcachesize; static int VID_highhunkmark; unsigned char vid_curpal[256*3]; unsigned short d_8to16table[256]; unsigned d_8to24table[256]; int driver = grDETECT,mode; bool 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]; } vmode_t; static vmode_t modelist[MAX_MODE_LIST]; static int nummodes; static vmode_t *pcurrentmode; 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 byte backingbuf[48*24]; 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); /* ================ VID_RememberWindowPos ================ */ void VID_RememberWindowPos (void) { RECT rect; if (GetWindowRect (mainwindow, &rect)) { if ((rect.left < GetSystemMetrics (SM_CXSCREEN)) && (rect.top < GetSystemMetrics (SM_CYSCREEN)) && (rect.right > 0) && (rect.bottom > 0)) { Cvar_SetValue ("vid_window_x", (float)rect.left); Cvar_SetValue ("vid_window_y", (float)rect.top); } } } /* ================ VID_CheckWindowXY ================ */ void VID_CheckWindowXY (void) { if (((int)vid_window_x.value > (GetSystemMetrics (SM_CXSCREEN) - 160)) || ((int)vid_window_y.value > (GetSystemMetrics (SM_CYSCREEN) - 120)) || ((int)vid_window_x.value < 0) || ((int)vid_window_y.value < 0)) { Cvar_SetValue ("vid_window_x", 0.0); Cvar_SetValue ("vid_window_y", 0.0 ); } } /* ================ VID_UpdateWindowStatus ================ */ void VID_UpdateWindowStatus (void) { window_rect.left = window_x; window_rect.top = window_y; window_rect.right = window_x + window_width; window_rect.bottom = window_y + window_height; window_center_x = (window_rect.left + window_rect.right) / 2; window_center_y = (window_rect.top + window_rect.bottom) / 2; IN_UpdateClipCursor (); } /* ================ ClearAllStates ================ */ void ClearAllStates (void) { int i; // send an up event for each key, to make sure the server clears them all for (i=0 ; i<256 ; i++) { Key_Event (i, false); } Key_ClearStates (); IN_ClearStates (); } /* ================ VID_CheckAdequateMem ================ */ qboolean VID_CheckAdequateMem (int width, int height) { int tbuffersize; tbuffersize = width * height * sizeof (*d_pzbuffer); tbuffersize += D_SurfaceCacheForRes (width, height); // see if there's enough memory, allowing for the normal mode 0x13 pixel, // z, and surface buffers if ((host_parms.memsize - tbuffersize + SURFCACHE_SIZE_AT_320X200 + 0x10000 * 3) < minimum_memory) { return false; // not enough memory for mode } return true; } /* ================ VID_AllocBuffers ================ */ qboolean VID_AllocBuffers (int width, int height) { int tsize, tbuffersize; tbuffersize = width * height * sizeof (*d_pzbuffer); tsize = D_SurfaceCacheForRes (width, height); tbuffersize += tsize; // see if there's enough memory, allowing for the normal mode 0x13 pixel, // z, and surface buffers if ((host_parms.memsize - tbuffersize + SURFCACHE_SIZE_AT_320X200 + 0x10000 * 3) < minimum_memory) { Con_SafePrintf ("Not enough memory for video mode\n"); return false; // not enough memory for mode } vid_surfcachesize = tsize; if (d_pzbuffer) { D_FlushCaches (); Hunk_FreeToHighMark (VID_highhunkmark); d_pzbuffer = NULL; } VID_highhunkmark = Hunk_HighMark (); d_pzbuffer = Hunk_HighAllocName (tbuffersize, "video"); vid_surfcache = (byte *)d_pzbuffer + width * height * sizeof (*d_pzbuffer); return true; } void initFatalError(void) { MGL_exit(); MGL_fatalError(MGL_errorMsg(MGL_result())); exit(EXIT_FAILURE); } int VID_Suspend (MGLDC *dc,m_int flags) { if (flags & MGL_DEACTIVATE) { // FIXME: this doesn't currently work on NT if (block_switch.value && !WinNT) { return MGL_NO_DEACTIVATE; } S_BlockSound (); S_ClearBuffer (); IN_RestoreOriginalMouseState (); CDAudio_Pause (); // keep WM_PAINT from trying to redraw in_mode_set = true; block_drawing = true; // so we don't try to draw while switched away return MGL_NO_SUSPEND_APP; } else if (flags & MGL_REACTIVATE) { IN_SetQuakeMouseState (); // fix the leftover Alt from any Alt-Tab or the like that switched us away ClearAllStates (); CDAudio_Resume (); S_UnblockSound (); in_mode_set = false; vid.recalc_refdef = 1; block_drawing = false; return MGL_NO_SUSPEND_APP; } } 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); /* 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 (!COM_CheckParm ("-novbeaf")) MGL_registerDriver(MGL_ACCEL8NAME,ACCEL8_driver); } if (useDirectDraw) { MGL_registerDriver(MGL_DDRAW8NAME,DDRAW8_driver); } } void registerAllMemDrivers(void) { /* Register memory context drivers */ MGL_registerDriver(MGL_PACKED8NAME,PACKED8_driver); } void VID_InitMGLFull (HINSTANCE hInstance) { int i, xRes, yRes, bits, vMode, lowres, curmode, temp; int lowstretchedres, stretchedmode, 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) { useWinDirect = false; } 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(); 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); if ((bits == 8) && (xRes <= MAXWIDTH) && (yRes <= MAXHEIGHT) && (curmode < MAX_MODE_LIST)) { if (m[i] == grVGA_320x200x256) is_mode0x13 = true; if (!COM_CheckParm("-noforcevga")) { if (m[i] == grVGA_320x200x256) { mode = i; break; } } if (xRes < lowres) { lowres = xRes; mode = i; } if ((xRes < lowstretchedres) && ((xRes >> 1) >= 320)) { lowstretchedres = xRes >> 1; stretchedmode = i; } } 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) { 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 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) { stretchedmode = nummodes; curmode = nummodes++; } else { curmode = MODE_FULLSCREEN_DEFAULT; } } else { curmode = nummodes++; } modelist[curmode].type = MS_FULLSCREEN; modelist[curmode].width = xRes; modelist[curmode].height = yRes; sprintf (modelist[curmode].modedesc, "%dx%d", xRes, yRes); if (m[i] == grVGA_320x200x256) modelist[curmode].mode13 = 1; else modelist[curmode].mode13 = 0; modelist[curmode].modenum = m[i]; modelist[curmode].stretched = 0; modelist[curmode].dib = 0; modelist[curmode].fullscreen = 1; modelist[curmode].halfscreen = 0; modelist[curmode].bpp = 8; } } 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; sprintf (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(); } } MGL_setSuspendAppCallback(VID_Suspend); } MGLDC *createDisplayDC(int forcemem) /**************************************************************************** * * Function: createDisplayDC * Returns: Pointer to the MGL device context to use for the application * * Description: Initialises the MGL and creates an appropriate display * device context to be used by the GUI. This creates and * apropriate device context depending on the system being * compile for, and should be the only place where system * specific code is required. * ****************************************************************************/ { MGLDC *dc; pixel_format_t pf; int npages; // Start the specified video mode if (!MGL_changeDisplayMode(mode)) initFatalError(); npages = MGL_availablePages(mode); if (npages > 3) npages = 3; if (!COM_CheckParm ("-notriplebuf")) { if (npages > 2) { npages = 2; } } if ((dc = MGL_createDisplayDC(npages)) == NULL) return NULL; if (!forcemem && (MGL_surfaceAccessType(dc)) == MGL_LINEAR_ACCESS && (dc->mi.maxPage > 0)) { MGL_makeCurrentDC(dc); memdc = NULL; } 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); } // Enable page flipping even for even for blitted surfaces if (forcemem) { vid.numpages = 1; } else { vid.numpages = dc->mi.maxPage + 1; if (vid.numpages > 1) { // Set up for page flipping MGL_setActivePage(dc, aPage = 1); MGL_setVisualPage(dc, vPage = 0, false); } if (vid.numpages > 3) vid.numpages = 3; } if (vid.numpages == 2) waitVRT = true; else waitVRT = false; return dc; } void VID_InitMGLDIB (HINSTANCE hInstance) { WNDCLASS wc; HDC hdc; int i; hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON2)); /* 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.hbrBackground = NULL; wc.lpszMenuName = 0; wc.lpszClassName = "WinQuake"; 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(""); modelist[0].type = MS_WINDOWED; modelist[0].width = 320; modelist[0].height = 240; strcpy (modelist[0].modedesc, "320x240"); modelist[0].mode13 = 0; modelist[0].modenum = MODE_WINDOWED; modelist[0].stretched = 0; modelist[0].dib = 1; modelist[0].fullscreen = 0; modelist[0].halfscreen = 0; modelist[0].bpp = 8; modelist[1].type = MS_WINDOWED; modelist[1].width = 640; modelist[1].height = 480; strcpy (modelist[1].modedesc, "640x480"); modelist[1].mode13 = 0; modelist[1].modenum = MODE_WINDOWED + 1; modelist[1].stretched = 1; modelist[1].dib = 1; modelist[1].fullscreen = 0; modelist[1].halfscreen = 0; modelist[1].bpp = 8; modelist[2].type = MS_WINDOWED; modelist[2].width = 800; modelist[2].height = 600; strcpy (modelist[2].modedesc, "800x600"); modelist[2].mode13 = 0; modelist[2].modenum = MODE_WINDOWED + 2; modelist[2].stretched = 1; modelist[2].dib = 1; modelist[2].fullscreen = 0; modelist[2].halfscreen = 0; modelist[2].bpp = 8; // automatically stretch the default mode up if > 640x480 desktop resolution hdc = GetDC(NULL); if ((GetDeviceCaps(hdc, HORZRES) > 640) && !COM_CheckParm("-noautostretch")) { vid_default = MODE_WINDOWED + 1; } else { vid_default = MODE_WINDOWED; } windowed_default = vid_default; ReleaseDC(NULL,hdc); nummodes = 3; // reserve space for windowed mode DDActive = 0; } /* ================= VID_InitFullDIB ================= */ void VID_InitFullDIB (HINSTANCE hInstance) { DEVMODE devmode; int i, j, modenum, cmodes, existingmode, originalnummodes, lowestres; int numlowresmodes, bpp, done; int cstretch, istretch, mstretch; BOOL stat; // enumerate 8 bpp modes originalnummodes = nummodes; modenum = 0; lowestres = 99999; 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; 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; modelist[nummodes].modenum = 0; modelist[nummodes].mode13 = 0; modelist[nummodes].stretched = 0; modelist[nummodes].halfscreen = 0; modelist[nummodes].dib = 1; modelist[nummodes].fullscreen = 1; modelist[nummodes].bpp = devmode.dmBitsPerPel; sprintf (modelist[nummodes].modedesc, "%dx%d", 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)) { modelist[nummodes].width >>= 1; modelist[nummodes].halfscreen = 1; sprintf (modelist[nummodes].modedesc, "%dx%d", modelist[nummodes].width, modelist[nummodes].height); } } for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++) { if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height)) { existingmode = 1; break; } } if (!existingmode) { if (modelist[nummodes].width < lowestres) lowestres = modelist[nummodes].width; nummodes++; } } } modenum++; } while (stat); // see if any of them were actually settable; if so, this is our mode list, // else enumerate all modes; our mode list is whichever ones are settable // with > 8 bpp if (nummodes == originalnummodes) { modenum = 0; lowestres = 99999; Con_SafePrintf ("No 8-bpp fullscreen DIB modes found\n"); 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; 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; modelist[nummodes].modenum = 0; modelist[nummodes].mode13 = 0; modelist[nummodes].stretched = 0; modelist[nummodes].halfscreen = 0; modelist[nummodes].dib = 1; modelist[nummodes].fullscreen = 1; modelist[nummodes].bpp = devmode.dmBitsPerPel; sprintf (modelist[nummodes].modedesc, "%dx%d", 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)) { modelist[nummodes].width >>= 1; modelist[nummodes].halfscreen = 1; sprintf (modelist[nummodes].modedesc, "%dx%d", modelist[nummodes].width, modelist[nummodes].height); } } for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++) { if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height)) { // pick the lowest available bpp if (modelist[nummodes].bpp < modelist[i].bpp) modelist[i] = modelist[nummodes]; existingmode = 1; break; } } if (!existingmode) { if (modelist[nummodes].width < lowestres) lowestres = modelist[nummodes].width; nummodes++; } } } modenum++; } while (stat); } // see if there are any low-res modes that aren't being reported numlowresmodes = sizeof(lowresmodes) / sizeof(lowresmodes[0]); bpp = 8; done = 0; // first make sure the driver doesn't just answer yes to all tests devmode.dmBitsPerPel = 8; devmode.dmPelsWidth = 42; devmode.dmPelsHeight = 37; devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings (&devmode, CDS_TEST | CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL) { done = 1; } while (!done) { for (j=0 ; (j<numlowresmodes) && (nummodes < MAX_MODE_LIST) ; j++) { devmode.dmBitsPerPel = bpp; devmode.dmPelsWidth = lowresmodes[j].width; devmode.dmPelsHeight = lowresmodes[j].height; devmode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; 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; modelist[nummodes].modenum = 0; modelist[nummodes].mode13 = 0; modelist[nummodes].stretched = 0; modelist[nummodes].halfscreen = 0; modelist[nummodes].dib = 1; modelist[nummodes].fullscreen = 1; modelist[nummodes].bpp = devmode.dmBitsPerPel; sprintf (modelist[nummodes].modedesc, "%dx%d", devmode.dmPelsWidth, devmode.dmPelsHeight); // we only want the lowest-bpp version of each mode for (i=originalnummodes, existingmode = 0 ; i<nummodes ; i++) { if ((modelist[nummodes].width == modelist[i].width) && (modelist[nummodes].height == modelist[i].height) && (modelist[nummodes].bpp >= modelist[i].bpp)) { existingmode = 1; break; } } if (!existingmode) { if (modelist[nummodes].width < lowestres) lowestres = modelist[nummodes].width; nummodes++; } } } switch (bpp) { case 8: bpp = 16; break; case 16: bpp = 32; break; case 32: done = 1; break; } } // 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<nummodes ; i++) { if (((modelist[i].width >> 1) < lowestres) && ((modelist[i].width >> 1) >= 320)) { lowestres = modelist[i].width >> 1; cstretch = 1; mstretch = i; } } 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]; nummodes += cstretch; istretch = originalnummodes; modelist[istretch] = modelist[mstretch]; modelist[istretch].width >>= 1; modelist[istretch].height >>= 1; modelist[istretch].stretched = 1; sprintf (modelist[istretch].modedesc, "%dx%d", modelist[istretch].width, modelist[istretch].height); } } if (nummodes != originalnummodes) vid_default = MODE_FULLSCREEN_DEFAULT; else Con_SafePrintf ("No fullscreen DIB modes found\n"); } /* ================= VID_NumModes ================= */ int VID_NumModes (void) { return nummodes; } /* ================= VID_GetModePtr ================= */ vmode_t *VID_GetModePtr (int modenum) { if ((modenum >= 0) && (modenum < nummodes)) return &modelist[modenum]; else return &badmode; } /* ================= VID_CheckModedescFixup ================= */ void VID_CheckModedescFixup (int mode) { int x, y, stretch; if (mode == MODE_SETTABLE_WINDOW) { modelist[mode].stretched = (int)vid_stretch_by_2.value; stretch = modelist[mode].stretched; if (vid_config_x.value < (320 << stretch)) vid_config_x.value = 320 << stretch; if (vid_config_y.value < (200 << stretch)) vid_config_y.value = 200 << stretch; x = (int)vid_config_x.value; y = (int)vid_config_y.value; sprintf (modelist[mode].modedesc, "%dx%d", x, y); modelist[mode].width = x; modelist[mode].height = y; } } /* ================= VID_GetModeDescriptionMemCheck ================= */ char *VID_GetModeDescriptionMemCheck (int mode) { char *pinfo; vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; VID_CheckModedescFixup (mode); pv = VID_GetModePtr (mode); pinfo = pv->modedesc; if (VID_CheckAdequateMem (pv->width, pv->height)) { return pinfo; } else { return NULL; } } /* ================= VID_GetModeDescription ================= */ char *VID_GetModeDescription (int mode) { char *pinfo; vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; VID_CheckModedescFixup (mode); pv = VID_GetModePtr (mode); pinfo = pv->modedesc; return pinfo; } /* ================= VID_GetModeDescription2 Tacks on "windowed" or "fullscreen" ================= */ char *VID_GetModeDescription2 (int mode) { static char pinfo[40]; vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; VID_CheckModedescFixup (mode); pv = VID_GetModePtr (mode); if (modelist[mode].type == MS_FULLSCREEN) { sprintf(pinfo,"%s fullscreen", pv->modedesc); } else if (modelist[mode].type == MS_FULLDIB) { sprintf(pinfo,"%s fullscreen", pv->modedesc); } else { sprintf(pinfo, "%s windowed", pv->modedesc); } return pinfo; } // KJB: Added this to return the mode driver name in description for console char *VID_GetExtModeDescription (int mode) { static char pinfo[40]; vmode_t *pv; if ((mode < 0) || (mode >= nummodes)) return NULL; VID_CheckModedescFixup (mode); pv = VID_GetModePtr (mode); if (modelist[mode].type == MS_FULLSCREEN) { sprintf(pinfo,"%s fullscreen %s",pv->modedesc, MGL_modeDriverName(pv->modenum)); } else if (modelist[mode].type == MS_FULLDIB) { sprintf(pinfo,"%s fullscreen DIB", pv->modedesc); } else { sprintf(pinfo, "%s windowed", pv->modedesc); } return pinfo; } void DestroyDIBWindow (void) { if (modestate == MS_WINDOWED) { // destroy the associated MGL DC's; the window gets reused if (windc) MGL_destroyDC(windc); if (dibdc) MGL_destroyDC(dibdc); windc = dibdc = NULL; } } void DestroyFullscreenWindow (void) { if (modestate == MS_FULLSCREEN) { // destroy the existing fullscreen mode and DC's if (mgldc) MGL_destroyDC (mgldc); if (memdc) MGL_destroyDC (memdc); mgldc = memdc = NULL; } } void DestroyFullDIBWindow (void) { if (modestate == MS_FULLDIB) { ChangeDisplaySettings (NULL, CDS_FULLSCREEN); // Destroy the fullscreen DIB window and associated MGL DC's if (windc) MGL_destroyDC(windc); if (dibdc) MGL_destroyDC(dibdc); windc = dibdc = NULL; } } qboolean VID_SetWindowedMode (int modenum) { HDC hdc; pixel_format_t pf; qboolean stretched; int lastmodestate; LONG wlong; if (!windowed_mode_set) { if (COM_CheckParm ("-resetwinpos")) { Cvar_SetValue ("vid_window_x", 0.0); Cvar_SetValue ("vid_window_y", 0.0); } windowed_mode_set; } VID_CheckModedescFixup (modenum); DDActive = 0; lastmodestate = modestate; DestroyFullscreenWindow (); DestroyFullDIBWindow (); if (windc) MGL_destroyDC(windc); if (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(); WindowRect.top = WindowRect.left = 0; WindowRect.right = modelist[modenum].width; WindowRect.bottom = modelist[modenum].height; stretched = modelist[modenum].stretched; DIBWidth = modelist[modenum].width; DIBHeight = modelist[modenum].height; if (stretched) { DIBWidth >>= 1; DIBHeight >>= 1; } WindowStyle = WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; ExWindowStyle = 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", "WinQuake", 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 MGL_registerFullScreenWindow (mainwindow); vid_mode_set = true; } 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"); } if (hide_window) return true; // position and show the DIB window VID_CheckWindowXY (); SetWindowPos (mainwindow, NULL, (int)vid_window_x.value, (int)vid_window_y.value, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME); if (force_minimized) ShowWindow (mainwindow, SW_MINIMIZE); else ShowWindow (mainwindow, SW_SHOWDEFAULT); UpdateWindow (mainwindow); modestate = MS_WINDOWED; vid_fulldib_on_focus_mode = 0; // because we have set the background brush for the window to NULL // (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); /* Create the MGL window DC and the MGL memory 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!"); MGL_makeCurrentDC(dibdc); vid.buffer = vid.conbuffer = vid.direct = dibdc->surface; vid.rowbytes = vid.conrowbytes = dibdc->mi.bytesPerLine; vid.numpages = 1; vid.maxwarpwidth = WARP_WIDTH; 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_stretched = stretched; SendMessage (mainwindow, WM_SETICON, (WPARAM)TRUE, (LPARAM)hIcon); SendMessage (mainwindow, WM_SETICON, (WPARAM)FALSE, (LPARAM)hIcon); return true; } qboolean VID_SetFullscreenMode (int modenum) { DDActive = 1; DestroyDIBWindow (); DestroyFullDIBWindow (); mode = modelist[modenum].modenum; // Destroy old DC's, resetting back to fullscreen mode if (mgldc) MGL_destroyDC (mgldc); if (memdc) MGL_destroyDC (memdc); mgldc = memdc = NULL; if ((mgldc = createDisplayDC (modelist[modenum].stretched || (int)vid_nopageflip.value)) == NULL) { return false; } modestate = MS_FULLSCREEN; vid_fulldib_on_focus_mode = 0; vid.buffer = vid.conbuffer = vid.direct = NULL; vid.maxwarpwidth = WARP_WIDTH; 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_stretched = modelist[modenum].stretched; // needed because we're not getting WM_MOVE messages fullscreen on NT window_x = 0; 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); // shouldn't be needed, but Kendall needs to let us get the activation // message for this not to be needed on NT AppActivate (true, false); return true; } qboolean VID_SetFullDIBMode (int modenum) { HDC hdc; pixel_format_t pf; int lastmodestate; DDActive = 0; DestroyFullscreenWindow (); DestroyDIBWindow (); if (windc) MGL_destroyDC(windc); if (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(); 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.dmSize = sizeof (gdevmode); if (ChangeDisplaySettings (&gdevmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) Sys_Error ("Couldn't set fullscreen DIB mode"); lastmodestate = modestate; modestate = MS_FULLDIB; vid_fulldib_on_focus_mode = modenum; WindowRect.top = WindowRect.left = 0; hdc = GetDC(NULL); WindowRect.right = modelist[modenum].width << modelist[modenum].stretched; WindowRect.bottom = modelist[modenum].height << modelist[modenum].stretched; 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); 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"); } // position and show the DIB window SetWindowPos (mainwindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW | SWP_DRAWFRAME); ShowWindow (mainwindow, SW_SHOWDEFAULT); UpdateWindow (mainwindow); // Because we have set the background brush for the window to NULL // (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); /* 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 ((dibdc = MGL_createMemoryDC(DIBWidth,DIBHeight,8,&pf)) == NULL) MGL_fatalError("Unable to create Memory DC!"); MGL_makeCurrentDC(dibdc); vid.buffer = vid.conbuffer = vid.direct = dibdc->surface; vid.rowbytes = vid.conrowbytes = dibdc->mi.bytesPerLine; vid.numpages = 1; vid.maxwarpwidth = WARP_WIDTH; 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_stretched = modelist[modenum].stretched; // needed because we're not getting WM_MOVE messages fullscreen on NT window_x = 0; window_y = 0; return true; } void VID_RestoreOldMode (int original_mode) { static qboolean inerror = false; if (inerror) return; in_mode_set = false; inerror = true; // make sure mode set happens (video mode changes) vid_modenum = original_mode - 1; if (!VID_SetMode (original_mode, vid_curpal)) { vid_modenum = MODE_WINDOWED - 1; if (!VID_SetMode (windowed_default, vid_curpal)) Sys_Error ("Can't set any video mode"); } inerror = false; } void VID_SetDefaultMode (void) { if (vid_initialized) VID_SetMode (0, vid_curpal); IN_DeactivateMouse (); } int VID_SetMode (int modenum, unsigned char *palette) { int original_mode, temp, dummy; qboolean stat; MSG msg; HDC hdc; while ((modenum >= nummodes) || (modenum < 0)) { if (vid_modenum == NO_MODE) { if (modenum == vid_default) { modenum = windowed_default; } else { modenum = vid_default; } Cvar_SetValue ("vid_mode", (float)modenum); } else { Cvar_SetValue ("vid_mode", (float)vid_modenum); return 0; } } if (!force_mode_set && (modenum == vid_modenum)) return true; // so Con_Printfs don't mess us up by forcing vid and snd updates temp = scr_disabled_for_loading; scr_disabled_for_loading = true; in_mode_set = true; CDAudio_Pause (); S_ClearBuffer (); if (vid_modenum == NO_MODE) original_mode = windowed_default; else original_mode = vid_modenum; // Set either the fullscreen or windowed mode if (modelist[modenum].type == MS_WINDOWED) { if (_windowed_mouse.value) { stat = VID_SetWindowedMode(modenum); IN_ActivateMouse (); IN_HideMouse (); } else { IN_DeactivateMouse (); IN_ShowMouse (); stat = VID_SetWindowedMode(modenum); } } else if (modelist[modenum].type == MS_FULLDIB) { stat = VID_SetFullDIBMode(modenum); IN_ActivateMouse (); IN_HideMouse (); } else { stat = VID_SetFullscreenMode(modenum); IN_ActivateMouse (); IN_HideMouse (); } window_width = vid.width << vid_stretched; window_height = vid.height << vid_stretched; VID_UpdateWindowStatus (); CDAudio_Resume (); scr_disabled_for_loading = temp; if (!stat) { VID_RestoreOldMode (original_mode); return false; } if (hide_window) return true; // 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 // to let messages finish bouncing around the system, then we put // ourselves at the top of the z order, then grab the foreground again, // Who knows if it helps, but it probably doesn't hurt if (!force_minimized) SetForegroundWindow (mainwindow); hdc = GetDC(NULL); if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) vid_palettized = true; else vid_palettized = false; VID_SetPalette (palette); ReleaseDC(NULL,hdc); vid_modenum = modenum; Cvar_SetValue ("vid_mode", (float)vid_modenum); 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); while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage (&msg); DispatchMessage (&msg); } Sleep (100); if (!force_minimized) { SetWindowPos (mainwindow, HWND_TOP, 0, 0, 0, 0, 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_SafePrintf ("%s\n", VID_GetModeDescription (vid_modenum)); VID_SetPalette (palette); in_mode_set = false; vid.recalc_refdef = 1; return true; } void VID_LockBuffer (void) { if (dibdc) return; lockcount++; if (lockcount > 1) return; MGL_beginDirectAccess(); 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) { // Update surface pointer for linear access modes vid.buffer = vid.conbuffer = vid.direct = mgldc->surface; vid.rowbytes = vid.conrowbytes = mgldc->mi.bytesPerLine; } if (r_dowarp) d_viewbuffer = r_warpbuffer; else d_viewbuffer = (void *)(byte *)vid.buffer; if (r_dowarp) screenwidth = WARP_WIDTH; else screenwidth = vid.rowbytes; if (lcd_x.value) screenwidth <<= 1; } void VID_UnlockBuffer (void) { if (dibdc) return; lockcount--; if (lockcount > 0) return; if (lockcount < 0) Sys_Error ("Unbalanced unlock"); MGL_endDirectAccess(); // to turn up any unlocked accesses vid.buffer = vid.conbuffer = vid.direct = d_viewbuffer = NULL; } int VID_ForceUnlockedAndReturnState (void) { int lk; if (!lockcount) return 0; lk = lockcount; if (dibdc) { lockcount = 0; } else { lockcount = 1; VID_UnlockBuffer (); } return lk; } void VID_ForceLockState (int lk) { if (!dibdc && lk) { lockcount = 0; VID_LockBuffer (); } lockcount = lk; } void VID_SetPalette (unsigned char *palette) { INT i; palette_t pal[256]; HDC hdc; if (!Minimized) { palette_changed = true; // 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); syscolchg = true; pal_is_nostatic = true; } } 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]; } if (DDActive) { if (!mgldc) return; MGL_setPalette(mgldc,pal,256,0); MGL_realizePalette(mgldc,256,0,false); if (memdc) 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); } } } memcpy (vid_curpal, palette, sizeof(vid_curpal)); if (syscolchg) { PostMessage (HWND_BROADCAST, WM_SYSCOLORCHANGE, (WPARAM)0, (LPARAM)0); syscolchg = false; } } void VID_ShiftPalette (unsigned char *palette) { VID_SetPalette (palette); } /* ================= VID_DescribeCurrentMode_f ================= */ void VID_DescribeCurrentMode_f (void) { Con_Printf ("%s\n", VID_GetExtModeDescription (vid_modenum)); } /* ================= VID_NumModes_f ================= */ void VID_NumModes_f (void) { if (nummodes == 1) Con_Printf ("%d video mode is available\n", nummodes); else Con_Printf ("%d video modes are available\n", nummodes); } /* ================= VID_DescribeMode_f ================= */ void VID_DescribeMode_f (void) { int modenum; modenum = Q_atoi (Cmd_Argv(1)); Con_Printf ("%s\n", VID_GetExtModeDescription (modenum)); } /* ================= VID_DescribeModes_f ================= */ void VID_DescribeModes_f (void) { int i, lnummodes; char *pinfo; qboolean na; vmode_t *pv; na = false; lnummodes = VID_NumModes (); for (i=0 ; i<lnummodes ; i++) { pv = VID_GetModePtr (i); pinfo = VID_GetExtModeDescription (i); if (VID_CheckAdequateMem (pv->width, pv->height)) { Con_Printf ("%2d: %s\n", i, pinfo); } else { Con_Printf ("**: %s\n", pinfo); na = true; } } if (na) { Con_Printf ("\n[**: not enough system RAM for mode]\n"); } } /* ================= VID_TestMode_f ================= */ void VID_TestMode_f (void) { int modenum; double testduration; if (!vid_testingmode) { modenum = Q_atoi (Cmd_Argv(1)); if (VID_SetMode (modenum, vid_curpal)) { vid_testingmode = 1; testduration = Q_atof (Cmd_Argv(2)); if (testduration == 0) testduration = 5.0; vid_testendtime = realtime + testduration; } } } /* ================= VID_Windowed_f ================= */ void VID_Windowed_f (void) { VID_SetMode ((int)vid_windowed_mode.value, vid_curpal); } /* ================= VID_Fullscreen_f ================= */ void VID_Fullscreen_f (void) { VID_SetMode ((int)vid_fullscreen_mode.value, vid_curpal); } /* ================= VID_Minimize_f ================= */ void VID_Minimize_f (void) { // we only support minimizing windows; if you're fullscreen, // switch to windowed first if (modestate == MS_WINDOWED) ShowWindow (mainwindow, SW_MINIMIZE); } /* ================= VID_ForceMode_f ================= */ void VID_ForceMode_f (void) { int modenum; double testduration; if (!vid_testingmode) { modenum = Q_atoi (Cmd_Argv(1)); force_mode_set = 1; VID_SetMode (modenum, vid_curpal); force_mode_set = 0; } } void VID_Init (unsigned char *palette) { int i, bestmatch, bestmatchmetric, t, dr, dg, db; int basenummodes; byte *ptmp; Cvar_RegisterVariable (&vid_mode); Cvar_RegisterVariable (&vid_wait); Cvar_RegisterVariable (&vid_nopageflip); Cvar_RegisterVariable (&_vid_wait_override); Cvar_RegisterVariable (&_vid_default_mode); Cvar_RegisterVariable (&_vid_default_mode_win); Cvar_RegisterVariable (&vid_config_x); Cvar_RegisterVariable (&vid_config_y); Cvar_RegisterVariable (&vid_stretch_by_2); Cvar_RegisterVariable (&_windowed_mouse); Cvar_RegisterVariable (&vid_fullscreen_mode); Cvar_RegisterVariable (&vid_windowed_mode); Cvar_RegisterVariable (&block_switch); Cvar_RegisterVariable (&vid_window_x); Cvar_RegisterVariable (&vid_window_y); Cmd_AddCommand ("vid_testmode", VID_TestMode_f); Cmd_AddCommand ("vid_nummodes", VID_NumModes_f); Cmd_AddCommand ("vid_describecurrentmode", VID_DescribeCurrentMode_f); Cmd_AddCommand ("vid_describemode", VID_DescribeMode_f); Cmd_AddCommand ("vid_describemodes", VID_DescribeModes_f); Cmd_AddCommand ("vid_forcemode", VID_ForceMode_f); Cmd_AddCommand ("vid_windowed", VID_Windowed_f); Cmd_AddCommand ("vid_fullscreen", VID_Fullscreen_f); Cmd_AddCommand ("vid_minimize", VID_Minimize_f); if (COM_CheckParm ("-dibonly")) dibonly = true; VID_InitMGLDIB (global_hInstance); basenummodes = nummodes; if (!dibonly) VID_InitMGLFull (global_hInstance); // if there are no non-windowed modes, or only windowed and mode 0x13, then use // fullscreen DIBs as well 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_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; 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) { bestmatchmetric = t; bestmatch = i; if (t == 0) break; } } for (i=0, ptmp = vid.colormap ; i<(1<<(VID_CBITS+8)) ; i++, ptmp++) { if (*ptmp == 0) *ptmp = bestmatch; } if (COM_CheckParm("-startwindowed")) { startwindowed = 1; vid_default = windowed_default; } if (hwnd_dialog) DestroyWindow (hwnd_dialog); // sound initialization has to go here, preceded by a windowed mode set, // so there's a window for DirectSound to work with but we're not yet // fullscreen so the "hardware already in use" dialog is visible if it // gets displayed // keep the window minimized until we're ready for the first real mode set hide_window = true; VID_SetMode (MODE_WINDOWED, palette); hide_window = false; S_Init (); vid_initialized = true; force_mode_set = true; VID_SetMode (vid_default, palette); force_mode_set = false; vid_realmode = vid_modenum; VID_SetPalette (palette); vid_menudrawfn = VID_MenuDraw; vid_menukeyfn = VID_MenuKey; strcpy (badmode.modedesc, "Bad mode"); } void VID_Shutdown (void) { HDC hdc; int dummy; 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); AppActivate(false, false); DestroyDIBWindow (); DestroyFullscreenWindow (); DestroyFullDIBWindow (); if (hwnd_dialog) DestroyWindow (hwnd_dialog); if (mainwindow) DestroyWindow(mainwindow); MGL_exit(); vid_testingmode = 0; vid_initialized = 0; } } /* ================ FlipScreen ================ */ void FlipScreen(vrect_t *rects) { HRESULT ddrval; // 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); } rects = rects->pnext; } } 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); } } } else { HDC hdcScreen; hdcScreen = GetDC(mainwindow); 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); } rects = rects->pnext; } } ReleaseDC(mainwindow, hdcScreen); } } void VID_Update (vrect_t *rects) { vrect_t rect; RECT trect; if (!vid_palettized && palette_changed) { palette_changed = false; rect.x = 0; rect.y = 0; rect.width = vid.width; rect.height = vid.height; rect.pnext = NULL; rects = &rect; } if (firstupdate) { if (modestate == MS_WINDOWED) { GetWindowRect (mainwindow, &trect); if ((trect.left != (int)vid_window_x.value) || (trect.top != (int)vid_window_y.value)) { if (COM_CheckParm ("-resetwinpos")) { Cvar_SetValue ("vid_window_x", 0.0); Cvar_SetValue ("vid_window_y", 0.0); } VID_CheckWindowXY (); SetWindowPos (mainwindow, NULL, (int)vid_window_x.value, (int)vid_window_y.value, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME); } } if ((_vid_default_mode_win.value != vid_default) && (!startwindowed || (_vid_default_mode_win.value < MODE_FULLSCREEN_DEFAULT))) { firstupdate = 0; if (COM_CheckParm ("-resetwinpos")) { Cvar_SetValue ("vid_window_x", 0.0); Cvar_SetValue ("vid_window_y", 0.0); } if ((_vid_default_mode_win.value < 0) || (_vid_default_mode_win.value >= nummodes)) { Cvar_SetValue ("_vid_default_mode_win", windowed_default); } Cvar_SetValue ("vid_mode", _vid_default_mode_win.value); } } // We've drawn the frame; copy it to the screen FlipScreen (rects); if (vid_testingmode) { if (realtime >= vid_testendtime) { VID_SetMode (vid_realmode, vid_curpal); vid_testingmode = 0; } } else { if ((int)vid_mode.value != vid_realmode) { VID_SetMode ((int)vid_mode.value, vid_curpal); Cvar_SetValue ("vid_mode", (float)vid_modenum); // 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 ((int)_windowed_mouse.value != windowed_mouse) { if (_windowed_mouse.value) { IN_ActivateMouse (); IN_HideMouse (); } else { IN_DeactivateMouse (); IN_ShowMouse (); } windowed_mouse = (int)_windowed_mouse.value; } } } /* ================ D_BeginDirectRect ================ */ void D_BeginDirectRect (int x, int y, byte *pbitmap, int width, int height) { int i, j, reps, repshift; vrect_t rect; if (!vid_initialized) return; if (vid.aspect > 1.5) { reps = 2; repshift = 1; } else { reps = 1; repshift = 0; } 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<reps ; j++) { memcpy (&backingbuf[(i + j) * 24], 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); } } VID_UnlockBuffer (); rect.x = x; rect.y = y; rect.width = width; rect.height = height << repshift; rect.pnext = NULL; FlipScreen (&rect); } else { // unlock if locked if (lockcount > 0) MGL_endDirectAccess(); // set the active page to the displayed page MGL_setActivePage (mgldc, vPage); // lock the screen MGL_beginDirectAccess (); // save from and draw to screen for (i=0 ; i<(height << repshift) ; i += reps) { for (j=0 ; j<reps ; j++) { memcpy (&backingbuf[(i + j) * 24], (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 MGL_endDirectAccess (); // restore the original active page MGL_setActivePage (mgldc, aPage); // relock the screen if it was locked if (lockcount > 0) MGL_beginDirectAccess(); } } /* ================ D_EndDirectRect ================ */ void D_EndDirectRect (int x, int y, int width, int height) { int i, j, reps, repshift; vrect_t rect; if (!vid_initialized) return; if (vid.aspect > 1.5) { reps = 2; repshift = 1; } else { reps = 1; repshift = 0; } 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<reps ; j++) { memcpy (vid.direct + x + ((y << repshift) + i + j) * vid.rowbytes, &backingbuf[(i + j) * 24], width); } } VID_UnlockBuffer (); rect.x = x; rect.y = y; rect.width = width; rect.height = height << repshift; rect.pnext = NULL; FlipScreen (&rect); } else { // unlock if locked if (lockcount > 0) MGL_endDirectAccess(); // set the active page to the displayed page MGL_setActivePage (mgldc, vPage); // lock the screen MGL_beginDirectAccess (); // 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 MGL_endDirectAccess (); // restore the original active page MGL_setActivePage (mgldc, aPage); // relock the screen if it was locked if (lockcount > 0) MGL_beginDirectAccess(); } } //========================================================================== 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,'*', K_ALT,' ', 0 , K_F1, K_F2, K_F3, K_F4, K_F5, // 3 K_F6, K_F7, K_F8, K_F9, K_F10, K_PAUSE, 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, // 6 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0, 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 // 7 }; /* ======= MapKey Map from windows to quake keynums ======= */ int MapKey (int key) { key = (key>>16)&255; if (key > 127) return 0; return scantokey[key]; } void AppActivate(BOOL fActive, BOOL minimize) /**************************************************************************** * * Function: AppActivate * Parameters: fActive - True if app is activating * * Description: If the application is activating, then swap the system * into SYSPAL_NOSTATIC mode so that our palettes will display * correctly. * ****************************************************************************/ { 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 (Minimized) ActiveApp = false; } MGL_appActivate(windc, ActiveApp); 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; 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); syscolchg = true; } pal_is_nostatic = false; } } if (!Minimized) VID_SetPalette (vid_curpal); scr_fullupdate = 0; ReleaseDC(NULL,hdc); } // enable/disable sound on focus gain/loss if (!ActiveApp && sound_active) { S_BlockSound (); S_ClearBuffer (); sound_active = false; } 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 VID_SetMode (vid_fulldib_on_focus_mode, vid_curpal); msg_suppress_1 = false; t = in_mode_set; in_mode_set = true; AppActivate (true, false); in_mode_set = t; } IN_ActivateMouse (); IN_HideMouse (); } else if ((modestate == MS_WINDOWED) && _windowed_mouse.value) { IN_ActivateMouse (); IN_HideMouse (); } } 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 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 t = in_mode_set; in_mode_set = true; AppActivate (false, true); in_mode_set = t; } IN_DeactivateMouse (); IN_ShowMouse (); } else if ((modestate == MS_WINDOWED) && _windowed_mouse.value) { IN_DeactivateMouse (); IN_ShowMouse (); } } } } /* ================ VID_HandlePause ================ */ void VID_HandlePause (qboolean pause) { if ((modestate == MS_WINDOWED) && _windowed_mouse.value) { if (pause) { IN_DeactivateMouse (); IN_ShowMouse (); } else { IN_ActivateMouse (); IN_HideMouse (); } } } /* =================================================================== MAIN WINDOW =================================================================== */ 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 lRet = 0; int fwKeys, xPos, yPos, fActive, fMinimized, temp; HDC hdc; PAINTSTRUCT ps; static int recursiveflag; switch (uMsg) { case WM_CREATE: break; case WM_SYSCOMMAND: // 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) { force_mode_set = true; VID_SetMode (vid_modenum, vid_curpal); force_mode_set = false; } VID_SetMode ((int)vid_fullscreen_mode.value, 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 break; } // fall through windowed and allow the screen saver to start default: if (!in_mode_set) { S_BlockSound (); S_ClearBuffer (); } lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); if (!in_mode_set) { S_UnblockSound (); } } break; case WM_MOVE: window_x = (int) LOWORD(lParam); window_y = (int) HIWORD(lParam); VID_UpdateWindowStatus (); if ((modestate == MS_WINDOWED) && !in_mode_set && !Minimized) VID_RememberWindowPos (); break; case WM_SIZE: Minimized = false; if (!(wParam & SIZE_RESTORED)) { if (wParam & SIZE_MINIMIZED) Minimized = true; } break; case WM_SYSCHAR: // keep Alt-Space from happening break; case WM_ACTIVATE: 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 ClearAllStates (); if (!in_mode_set) { if (windc) MGL_activatePalette(windc,true); VID_SetPalette(vid_curpal); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); if (!in_mode_set && host_initialized) SCR_UpdateWholeScreen (); EndPaint(hWnd, &ps); break; case WM_KEYDOWN: case WM_SYSKEYDOWN: if (!in_mode_set) Key_Event (MapKey(lParam), true); break; case WM_KEYUP: case WM_SYSKEYUP: if (!in_mode_set) Key_Event (MapKey(lParam), 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 case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MOUSEMOVE: if (!in_mode_set) { temp = 0; if (wParam & MK_LBUTTON) temp |= 1; if (wParam & MK_RBUTTON) temp |= 2; if (wParam & MK_MBUTTON) temp |= 4; 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, true); Key_Event(K_MWHEELUP, false); } else { Key_Event(K_MWHEELDOWN, true); Key_Event(K_MWHEELDOWN, false); } break; // KJB: Added these new palette functions case WM_PALETTECHANGED: if ((HWND)wParam == hWnd) break; /* Fall through to WM_QUERYNEWPALETTE */ case WM_QUERYNEWPALETTE: hdc = GetDC(NULL); if (GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) vid_palettized = true; else vid_palettized = false; ReleaseDC(NULL,hdc); scr_fullupdate = 0; 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 lRet = TRUE; } break; case WM_DISPLAYCHANGE: 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) { Sys_Quit (); } } break; case MM_MCINOTIFY: lRet = CDAudio_MessageHandler (hWnd, uMsg, wParam, lParam); break; default: /* pass all unhandled messages to DefWindowProc */ lRet = DefWindowProc (hWnd, uMsg, wParam, lParam); break; } /* return 0 if handled message, 1 if not */ return lRet; } extern void M_Menu_Options_f (void); extern void M_Print (int cx, int cy, char *str); extern void M_PrintWhite (int cx, int cy, char *str); 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; 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]; /* ================ VID_MenuDraw ================ */ void VID_MenuDraw (void) { qpic_t *p; char *ptr; int lnummodes, i, j, k, column, row, dup, dupmode; char temp[100]; vmode_t *pv; modedesc_t tmodedesc; p = Draw_CachePic ("gfx/vidmodes.lmp"); M_DrawPic ( (320-p->width)/2, 4, p); for (i=0 ; i<3 ; i++) { ptr = VID_GetModeDescriptionMemCheck (i); modedescs[i].modenum = modelist[i].modenum; modedescs[i].desc = ptr; modedescs[i].ismode13 = 0; modedescs[i].iscur = 0; if (vid_modenum == i) modedescs[i].iscur = 1; } vid_wmodes = 3; lnummodes = VID_NumModes (); for (i=3 ; i<lnummodes ; i++) { ptr = VID_GetModeDescriptionMemCheck (i); pv = VID_GetModePtr (i); // 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<vid_wmodes ; j++) { if (!strcmp (modedescs[j].desc, ptr)) { dup = 1; dupmode = j; break; } } if (dup || (vid_wmodes < MAX_MODEDESCS)) { if (!dup || !modedescs[dupmode].ismode13 || COM_CheckParm("-noforcevga")) { if (dup) { k = dupmode; } else { k = vid_wmodes; } modedescs[k].modenum = i; modedescs[k].desc = ptr; modedescs[k].ismode13 = pv->mode13; modedescs[k].iscur = 0; modedescs[k].width = pv->width; if (i == vid_modenum) modedescs[k].iscur = 1; if (!dup) vid_wmodes++; } } } } // sort the modes on width (to handle picking up oddball dibonly modes // after all the others) 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; } } } M_Print (13*8, 36, "Windowed Modes"); column = 16; row = 36+2*8; 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; } if (vid_wmodes > 3) { M_Print (12*8, 36+4*8, "Fullscreen Modes"); column = 16; row = 36+6*8; for (i=3 ; i<vid_wmodes ; i++) { if (modedescs[i].iscur) M_PrintWhite (column, row, modedescs[i].desc); else M_Print (column, row, modedescs[i].desc); column += 13*8; if (((i - 3) % VID_ROW_SIZE) == (VID_ROW_SIZE - 1)) { column = 16; row += 8; } } } // line cursor if (vid_testingmode) { sprintf (temp, "TESTING %s", modedescs[vid_line].desc); M_Print (13*8, 36 + MODE_AREA_HEIGHT * 8 + 8*4, temp); M_Print (9*8, 36 + MODE_AREA_HEIGHT * 8 + 8*6, "Please wait 5 seconds..."); } else { M_Print (9*8, 36 + MODE_AREA_HEIGHT * 8 + 8, "Press Enter to set mode"); M_Print (6*8, 36 + MODE_AREA_HEIGHT * 8 + 8*3, "T to test mode for 5 seconds"); ptr = VID_GetModeDescription2 (vid_modenum); if (ptr) { sprintf (temp, "D to set default: %s", ptr); M_Print (2*8, 36 + MODE_AREA_HEIGHT * 8 + 8*5, temp); } ptr = VID_GetModeDescription2 ((int)_vid_default_mode_win.value); if (ptr) { sprintf (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"); 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; M_DrawCharacter (column, row, 12+((int)(realtime*4)&1)); } } /* ================ VID_MenuKey ================ */ void VID_MenuKey (int key) { if (vid_testingmode) return; switch (key) { case K_ESCAPE: S_LocalSound ("misc/menu1.wav"); M_Menu_Options_f (); break; case K_LEFTARROW: 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; 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; 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; while (vid_line >= vid_wmodes) vid_line -= VID_ROW_SIZE; } break; 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; 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 '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; case 'D': case 'd': S_LocalSound ("misc/menu1.wav"); firstupdate = 0; Cvar_SetValue ("_vid_default_mode_win", vid_modenum); break; default: break; } }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // net_comx.c #include <dos.h> #include <dpmi.h> #define NUM_COM_PORTS 2 #define ERR_TTY_LINE_STATUS -1 #define ERR_TTY_MODEM_STATUS -2 #define ERR_TTY_NODATA -3 #define QUEUESIZE 8192 #define QUEUEMASK (QUEUESIZE - 1) typedef struct { volatile int head; volatile int tail; volatile byte data[QUEUESIZE]; } queue; #define FULL(q) (q.head == ((q.tail-1) & QUEUEMASK)) #define EMPTY(q) (q.tail == q.head) #define ENQUEUE(q,b) (q.data[q.head] = b, q.head = (q.head + 1) & QUEUEMASK) #define DEQUEUE(q,b) (b = q.data[q.tail], q.tail = (q.tail + 1) & QUEUEMASK) extern cvar_t config_com_port; extern cvar_t config_com_irq; extern cvar_t config_com_baud; extern cvar_t config_com_modem; extern cvar_t config_modem_dialtype; extern cvar_t config_modem_clear; extern cvar_t config_modem_init; extern cvar_t config_modem_hangup; extern int m_return_state; extern int m_state; extern qboolean m_return_onerror; extern char m_return_reason[32]; // 8250, 16550 definitions #define TRANSMIT_HOLDING_REGISTER 0x00 #define RECEIVE_BUFFER_REGISTER 0x00 #define INTERRUPT_ENABLE_REGISTER 0x01 #define IER_RX_DATA_READY 0x01 #define IER_TX_HOLDING_REGISTER_EMPTY 0x02 #define IER_LINE_STATUS 0x04 #define IER_MODEM_STATUS 0x08 #define INTERRUPT_ID_REGISTER 0x02 #define IIR_MODEM_STATUS_INTERRUPT 0x00 #define IIR_TX_HOLDING_REGISTER_INTERRUPT 0x02 #define IIR_RX_DATA_READY_INTERRUPT 0x04 #define IIR_LINE_STATUS_INTERRUPT 0x06 #define IIR_FIFO_TIMEOUT 0x0c #define IIR_FIFO_ENABLED 0xc0 #define FIFO_CONTROL_REGISTER 0x02 #define FCR_FIFO_ENABLE 0x01 #define FCR_RCVR_FIFO_RESET 0x02 #define FCR_XMIT_FIFO_RESET 0x04 #define FCR_TRIGGER_01 0x00 #define FCR_TRIGGER_04 0x40 #define FCR_TRIGGER_08 0x80 #define FCR_TRIGGER_16 0xc0 #define LINE_CONTROL_REGISTER 0x03 #define LCR_DATA_BITS_5 0x00 #define LCR_DATA_BITS_6 0x01 #define LCR_DATA_BITS_7 0x02 #define LCR_DATA_BITS_8 0x03 #define LCR_STOP_BITS_1 0x00 #define LCR_STOP_BITS_2 0x04 #define LCR_PARITY_NONE 0x00 #define LCR_PARITY_ODD 0x08 #define LCR_PARITY_EVEN 0x18 #define LCR_PARITY_MARK 0x28 #define LCR_PARITY_SPACE 0x38 #define LCR_SET_BREAK 0x40 #define LCR_DLAB 0x80 #define MODEM_CONTROL_REGISTER 0x04 #define MCR_DTR 0x01 #define MCR_RTS 0x02 #define MCR_OUT1 0x04 #define MCR_OUT2 0x08 #define MCR_LOOPBACK 0x10 #define LINE_STATUS_REGISTER 0x05 #define LSR_DATA_READY 0x01 #define LSR_OVERRUN_ERROR 0x02 #define LSR_PARITY_ERROR 0x04 #define LSR_FRAMING_ERROR 0x08 #define LSR_BREAK_DETECT 0x10 #define LSR_TRANSMITTER_BUFFER_EMPTY 0x20 #define LSR_TRANSMITTER_EMPTY 0x40 #define LSR_FIFO_DIRTY 0x80 #define MODEM_STATUS_REGISTER 0x06 #define MSR_DELTA_CTS 0x01 #define MSR_DELTA_DSR 0x02 #define MSR_DELTA_RI 0x04 #define MSR_DELTA_CD 0x08 #define MSR_CTS 0x10 #define MSR_DSR 0x20 #define MSR_RI 0x40 #define MSR_CD 0x80 #define DIVISOR_LATCH_LOW 0x00 #define DIVISOR_LATCH_HIGH 0x01 #define MODEM_STATUS_MASK (MSR_CTS | MSR_DSR | MSR_CD) #define UART_AUTO 0 #define UART_8250 1 #define UART_16550 2 static int ISA_uarts[] = {0x3f8,0x2f8,0x3e8,0x2e8}; static int ISA_IRQs[] = {4,3,4,3}; typedef struct ComPort_s { struct ComPort_s *next; _go32_dpmi_seginfo protectedModeInfo; _go32_dpmi_seginfo protectedModeSaveInfo; int uart; volatile byte modemStatus; byte modemStatusIgnore; byte lineStatus; byte bufferUsed; qboolean enabled; volatile qboolean statusUpdated; qboolean useModem; qboolean modemInitialized; qboolean modemRang; qboolean modemConnected; queue inputQueue; queue outputQueue; char clear[16]; char startup[32]; char shutdown[16]; char buffer[128]; PollProcedure poll; double timestamp; byte uartType; byte irq; byte baudBits; byte lineControl; byte portNumber; char dialType; char name[4]; } ComPort; ComPort *portList = NULL; ComPort *handleToPort [NUM_COM_PORTS]; static int Modem_Command(ComPort *p, char *commandString); static char *Modem_Response(ComPort *p); static void Modem_Hangup(ComPort *p); int TTY_Init(void); void TTY_Shutdown(void); int TTY_Open(int serialPortNumber); void TTY_Close(int handle); int TTY_ReadByte(int handle); int TTY_WriteByte(int handle, byte data); void TTY_Flush(int handle); int TTY_Connect(int handle, char *host); void TTY_Disconnect(int handle); qboolean TTY_CheckForConnection(int handle); qboolean TTY_IsEnabled(int serialPortNumber); qboolean TTY_IsModem(int serialPortNumber); qboolean TTY_OutputQueueIsEmpty(int handle); static void ISR_8250 (ComPort *p) { byte source = 0; byte b; disable(); while((source = inportb (p->uart + INTERRUPT_ID_REGISTER) & 0x07) != 1) { switch (source) { case IIR_RX_DATA_READY_INTERRUPT: b = inportb (p->uart + RECEIVE_BUFFER_REGISTER); if (! FULL(p->inputQueue)) { ENQUEUE (p->inputQueue, b); } else { p->lineStatus |= LSR_OVERRUN_ERROR; p->statusUpdated = true; } break; case IIR_TX_HOLDING_REGISTER_INTERRUPT: if (! EMPTY(p->outputQueue)) { DEQUEUE (p->outputQueue, b); outportb (p->uart + TRANSMIT_HOLDING_REGISTER, b); } break; case IIR_MODEM_STATUS_INTERRUPT: p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore; p->statusUpdated = true; break; case IIR_LINE_STATUS_INTERRUPT: p->lineStatus = inportb (p->uart + LINE_STATUS_REGISTER); p->statusUpdated = true; break; } source = inportb (p->uart + INTERRUPT_ID_REGISTER) & 0x07; } outportb (0x20, 0x20); } static void COM1_ISR_8250 (void) { ISR_8250 (handleToPort[0]); } static void COM2_ISR_8250 (void) { ISR_8250 (handleToPort[1]); } static void ISR_16550 (ComPort *p) { int count; byte source; byte b; disable(); while((source = inportb (p->uart + INTERRUPT_ID_REGISTER) & 0x07) != 1) { switch (source) { case IIR_RX_DATA_READY_INTERRUPT: do { b = inportb (p->uart + RECEIVE_BUFFER_REGISTER); if (!FULL(p->inputQueue)) { ENQUEUE (p->inputQueue, b); } else { p->lineStatus |= LSR_OVERRUN_ERROR; p->statusUpdated = true; } } while (inportb (p->uart + LINE_STATUS_REGISTER) & LSR_DATA_READY); break; case IIR_TX_HOLDING_REGISTER_INTERRUPT: count = 16; while ((! EMPTY(p->outputQueue)) && count--) { DEQUEUE (p->outputQueue, b); outportb (p->uart + TRANSMIT_HOLDING_REGISTER, b); } break; case IIR_MODEM_STATUS_INTERRUPT: p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore; p->statusUpdated = true; break; case IIR_LINE_STATUS_INTERRUPT: p->lineStatus = inportb (p->uart + LINE_STATUS_REGISTER); p->statusUpdated = true; break; } source = inportb (p->uart + INTERRUPT_ID_REGISTER) & 0x07; } // check for lost IIR_TX_HOLDING_REGISTER_INTERRUPT on 16550a! if (inportb (p->uart + LINE_STATUS_REGISTER ) & LSR_TRANSMITTER_EMPTY) { count = 16; while ((! EMPTY(p->outputQueue)) && count--) { DEQUEUE (p->outputQueue, b); outportb (p->uart + TRANSMIT_HOLDING_REGISTER, b); } } outportb (0x20, 0x20); } static void COM1_ISR_16550 (void) { ISR_16550 (handleToPort[0]); } static void COM2_ISR_16550 (void) { ISR_16550 (handleToPort[1]); } void TTY_GetComPortConfig (int portNumber, int *port, int *irq, int *baud, qboolean *useModem) { ComPort *p; p = handleToPort[portNumber]; *port = p->uart; *irq = p->irq; *baud = 115200 / p->baudBits; *useModem = p->useModem; } void TTY_SetComPortConfig (int portNumber, int port, int irq, int baud, qboolean useModem) { ComPort *p; float temp; if (useModem) { if (baud == 14400) baud = 19200; if (baud == 28800) baud = 38400; } p = handleToPort[portNumber]; p->uart = port; p->irq = irq; p->baudBits = 115200 / baud; p->useModem = useModem; if (useModem) temp = 1.0; else temp = 0.0; Cvar_SetValue ("_config_com_port", (float)port); Cvar_SetValue ("_config_com_irq", (float)irq); Cvar_SetValue ("_config_com_baud", (float)baud); Cvar_SetValue ("_config_com_modem", temp); } void TTY_GetModemConfig (int portNumber, char *dialType, char *clear, char *init, char *hangup) { ComPort *p; p = handleToPort[portNumber]; *dialType = p->dialType; Q_strcpy(clear, p->clear); Q_strcpy(init, p->startup); Q_strcpy(hangup, p->shutdown); } void TTY_SetModemConfig (int portNumber, char *dialType, char *clear, char *init, char *hangup) { ComPort *p; p = handleToPort[portNumber]; p->dialType = dialType[0]; Q_strcpy(p->clear, clear); Q_strcpy(p->startup, init); Q_strcpy(p->shutdown, hangup); p->modemInitialized = false; Cvar_Set ("_config_modem_dialtype", dialType); Cvar_Set ("_config_modem_clear", clear); Cvar_Set ("_config_modem_init", init); Cvar_Set ("_config_modem_hangup", hangup); } static void ResetComPortConfig (ComPort *p) { p->useModem = false; p->uartType = UART_AUTO; p->uart = ISA_uarts[p->portNumber]; p->irq = ISA_IRQs[p->portNumber]; p->modemStatusIgnore = MSR_CD | MSR_CTS | MSR_DSR; p->baudBits = 115200 / 57600; p->lineControl = LCR_DATA_BITS_8 | LCR_STOP_BITS_1 | LCR_PARITY_NONE; Q_strcpy(p->clear, "ATZ"); Q_strcpy(p->startup, ""); Q_strcpy(p->shutdown, "AT H"); p->modemRang = false; p->modemConnected = false; p->statusUpdated = false; p->outputQueue.head = p->outputQueue.tail = 0; p->inputQueue.head = p->inputQueue.tail = 0; } static void ComPort_Enable(ComPort *p) { void (*isr)(void); int n; byte b; if (p->enabled) { Con_Printf("Already enabled\n"); return; } // disable all UART interrupts outportb (p->uart + INTERRUPT_ENABLE_REGISTER, 0); // clear out any buffered uncoming data while((inportb (p->uart + LINE_STATUS_REGISTER)) & LSR_DATA_READY) inportb (p->uart + RECEIVE_BUFFER_REGISTER); // get the current line and modem status p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore; p->lineStatus = inportb (p->uart + LINE_STATUS_REGISTER); // clear any UART interrupts do { n = inportb (p->uart + INTERRUPT_ID_REGISTER) & 7; if (n == IIR_RX_DATA_READY_INTERRUPT) inportb (p->uart + RECEIVE_BUFFER_REGISTER); } while (!(n & 1)); if (p->uartType == UART_AUTO) { outportb (p->uart + FIFO_CONTROL_REGISTER, FCR_FIFO_ENABLE); b = inportb (p->uart + INTERRUPT_ID_REGISTER); if ((b & IIR_FIFO_ENABLED) == IIR_FIFO_ENABLED) p->uartType = UART_16550; else p->uartType = UART_8250; } // save the old interrupt handler _go32_dpmi_get_protected_mode_interrupt_vector(p->irq + 8, &p->protectedModeSaveInfo); if (p->uartType == UART_8250) { outportb (p->uart + FIFO_CONTROL_REGISTER, 0); if (p == handleToPort[0]) isr = COM1_ISR_8250; else isr = COM2_ISR_8250; } else { outportb (p->uart + FIFO_CONTROL_REGISTER, FCR_FIFO_ENABLE | FCR_RCVR_FIFO_RESET | FCR_XMIT_FIFO_RESET | FCR_TRIGGER_08); if (p == handleToPort[0]) isr = COM1_ISR_16550; else isr = COM2_ISR_16550; } p->protectedModeInfo.pm_offset = (int)isr; n = _go32_dpmi_allocate_iret_wrapper(&p->protectedModeInfo); if (n) { Con_Printf("serial: protected mode callback allocation failed\n"); return; } // disable interrupts at the processor disable(); // install our interrupt handlers now _go32_dpmi_set_protected_mode_interrupt_vector(p->irq + 8, &p->protectedModeInfo); // enable our interrupt at the PIC outportb (0x21, inportb (0x21) & ~(1<<p->irq)); // enable interrupts at the processor enable(); // enable interrupts at the PIC outportb (0x20, 0xc2); // set baud rate & line control outportb (p->uart + LINE_CONTROL_REGISTER, LCR_DLAB | p->lineControl); outportb (p->uart, p->baudBits); outportb (p->uart + 1, 0); outportb (p->uart + LINE_CONTROL_REGISTER, p->lineControl); // set modem control register & enable uart interrupt generation outportb(p->uart + MODEM_CONTROL_REGISTER, MCR_OUT2 | MCR_RTS | MCR_DTR); // enable the individual interrupts at the uart outportb (p->uart + INTERRUPT_ENABLE_REGISTER, IER_RX_DATA_READY | IER_TX_HOLDING_REGISTER_EMPTY | IER_LINE_STATUS | IER_MODEM_STATUS); p->enabled = true; } static void ComPort_Disable(ComPort *p) { if (!p->enabled) { Con_Printf("Already disabled\n"); return; } // disable interrupts at the uart outportb (p->uart + INTERRUPT_ENABLE_REGISTER, 0); // disable our interrupt at the PIC outportb (0x21, inportb (0x21) | (1<<p->irq)); // disable interrupts at the processor disable(); // restore the old interrupt handler _go32_dpmi_set_protected_mode_interrupt_vector(p->irq + 8, &p->protectedModeSaveInfo); _go32_dpmi_free_iret_wrapper(&p->protectedModeInfo); // enable interrupts at the processor enable(); p->enabled = false; } static int CheckStatus (ComPort *p) { int ret = 0; if (p->statusUpdated) { p->statusUpdated = false; if (p->lineStatus & (LSR_OVERRUN_ERROR | LSR_PARITY_ERROR | LSR_FRAMING_ERROR | LSR_BREAK_DETECT)) { if (p->lineStatus & LSR_OVERRUN_ERROR) Con_DPrintf ("Serial overrun error\n"); if (p->lineStatus & LSR_PARITY_ERROR) Con_DPrintf ("Serial parity error\n"); if (p->lineStatus & LSR_FRAMING_ERROR) Con_DPrintf ("Serial framing error\n"); if (p->lineStatus & LSR_BREAK_DETECT) Con_DPrintf ("Serial break detect\n"); ret = ERR_TTY_LINE_STATUS; } if ((p->modemStatus & MODEM_STATUS_MASK) != MODEM_STATUS_MASK) { if (!(p->modemStatus & MSR_CTS)) Con_Printf ("Serial lost CTS\n"); if (!(p->modemStatus & MSR_DSR)) Con_Printf ("Serial lost DSR\n"); if (!(p->modemStatus & MSR_CD)) Con_Printf ("Serial lost Carrier\n"); ret = ERR_TTY_MODEM_STATUS; } } return ret; } static void Modem_Init(ComPort *p) { double start; char *response; Con_Printf ("Initializing modem...\n"); // write 0 to MCR, wait 1/2 sec, then write the real value back again // I got this from the guys at head-to-head who say it's necessary. outportb(p->uart + MODEM_CONTROL_REGISTER, 0); start = Sys_FloatTime(); while ((Sys_FloatTime() - start) < 0.5) ; outportb(p->uart + MODEM_CONTROL_REGISTER, MCR_OUT2 | MCR_RTS | MCR_DTR); start = Sys_FloatTime(); while ((Sys_FloatTime() - start) < 0.25) ; if (*p->clear) { Modem_Command (p, p->clear); start = Sys_FloatTime(); while(1) { if ((Sys_FloatTime() - start) > 3.0) { Con_Printf("No response - clear failed\n"); p->enabled = false; goto failed; } response = Modem_Response(p); if (!response) continue; if (Q_strncmp(response, "OK", 2) == 0) break; if (Q_strncmp(response, "ERROR", 5) == 0) { p->enabled = false; goto failed; } } } if (*p->startup) { Modem_Command (p, p->startup); start = Sys_FloatTime(); while(1) { if ((Sys_FloatTime() - start) > 3.0) { Con_Printf("No response - init failed\n"); p->enabled = false; goto failed; } response = Modem_Response(p); if (!response) continue; if (Q_strncmp(response, "OK", 2) == 0) break; if (Q_strncmp(response, "ERROR", 5) == 0) { p->enabled = false; goto failed; } } } p->modemInitialized = true; return; failed: if (m_return_onerror) { key_dest = key_menu; m_state = m_return_state; m_return_onerror = false; Q_strcpy(m_return_reason, "Initialization Failed"); } return; } void TTY_Enable(int handle) { ComPort *p; p = handleToPort [handle]; if (p->enabled) return; ComPort_Enable(p); if (p->useModem && !p->modemInitialized) Modem_Init (p); } int TTY_Open(int serialPortNumber) { return serialPortNumber; } void TTY_Close(int handle) { ComPort *p; double startTime; p = handleToPort [handle]; startTime = Sys_FloatTime(); while ((Sys_FloatTime() - startTime) < 1.0) if (EMPTY(p->outputQueue)) break; if (p->useModem) { if (p->modemConnected) Modem_Hangup(p); } } int TTY_ReadByte(int handle) { int ret; ComPort *p; p = handleToPort [handle]; if ((ret = CheckStatus (p)) != 0) return ret; if (EMPTY (p->inputQueue)) return ERR_TTY_NODATA; DEQUEUE (p->inputQueue, ret); return (ret & 0xff); } int TTY_WriteByte(int handle, byte data) { ComPort *p; p = handleToPort [handle]; if (FULL(p->outputQueue)) return -1; ENQUEUE (p->outputQueue, data); return 0; } void TTY_Flush(int handle) { byte b; ComPort *p; p = handleToPort [handle]; if (inportb (p->uart + LINE_STATUS_REGISTER ) & LSR_TRANSMITTER_EMPTY) { DEQUEUE (p->outputQueue, b); outportb(p->uart, b); } } int TTY_Connect(int handle, char *host) { double start; ComPort *p; char *response = NULL; keydest_t save_key_dest; byte dialstring[64]; byte b; p = handleToPort[handle]; if ((p->modemStatus & MODEM_STATUS_MASK) != MODEM_STATUS_MASK) { Con_Printf ("Serial: line not ready ("); if ((p->modemStatus & MSR_CTS) == 0) Con_Printf(" CTS"); if ((p->modemStatus & MSR_DSR) == 0) Con_Printf(" DSR"); if ((p->modemStatus & MSR_CD) == 0) Con_Printf(" CD"); Con_Printf(" )"); return -1; } // discard any scraps in the input buffer while (! EMPTY (p->inputQueue)) DEQUEUE (p->inputQueue, b); CheckStatus (p); if (p->useModem) { save_key_dest = key_dest; key_dest = key_console; key_count = -2; Con_Printf ("Dialing...\n"); sprintf(dialstring, "AT D%c %s\r", p->dialType, host); Modem_Command (p, dialstring); start = Sys_FloatTime(); while(1) { if ((Sys_FloatTime() - start) > 60.0) { Con_Printf("Dialing failure!\n"); break; } Sys_SendKeyEvents (); if (key_count == 0) { if (key_lastpress != K_ESCAPE) { key_count = -2; continue; } Con_Printf("Aborting...\n"); while ((Sys_FloatTime() - start) < 5.0) ; disable(); p->outputQueue.head = p->outputQueue.tail = 0; p->inputQueue.head = p->inputQueue.tail = 0; outportb(p->uart + MODEM_CONTROL_REGISTER, inportb(p->uart + MODEM_CONTROL_REGISTER) & ~MCR_DTR); enable(); start = Sys_FloatTime(); while ((Sys_FloatTime() - start) < 0.75) ; outportb(p->uart + MODEM_CONTROL_REGISTER, inportb(p->uart + MODEM_CONTROL_REGISTER) | MCR_DTR); response = "Aborted"; break; } response = Modem_Response(p); if (!response) continue; if (Q_strncmp(response, "CONNECT", 7) == 0) { disable(); p->modemRang = true; p->modemConnected = true; p->outputQueue.head = p->outputQueue.tail = 0; p->inputQueue.head = p->inputQueue.tail = 0; enable(); key_dest = save_key_dest; key_count = 0; m_return_onerror = false; return 0; } if (Q_strncmp(response, "NO CARRIER", 10) == 0) break; if (Q_strncmp(response, "NO DIALTONE", 11) == 0) break; if (Q_strncmp(response, "NO DIAL TONE", 12) == 0) break; if (Q_strncmp(response, "NO ANSWER", 9) == 0) break; if (Q_strncmp(response, "BUSY", 4) == 0) break; if (Q_strncmp(response, "ERROR", 5) == 0) break; } key_dest = save_key_dest; key_count = 0; if (m_return_onerror) { key_dest = key_menu; m_state = m_return_state; m_return_onerror = false; Q_strncpy(m_return_reason, response, 31); } return -1; } m_return_onerror = false; return 0; } void TTY_Disconnect(int handle) { ComPort *p; p = handleToPort[handle]; if (p->useModem && p->modemConnected) Modem_Hangup(p); } qboolean TTY_CheckForConnection(int handle) { ComPort *p; p = handleToPort[handle]; CheckStatus (p); if (p->useModem) { if (!p->modemRang) { if (!Modem_Response(p)) return false; if (Q_strncmp(p->buffer, "RING", 4) == 0) { Modem_Command (p, "ATA"); p->modemRang = true; p->timestamp = net_time; } return false; } if (!p->modemConnected) { if ((net_time - p->timestamp) > 35.0) { Con_Printf("Unable to establish modem connection\n"); p->modemRang = false; return false; } if (!Modem_Response(p)) return false; if (Q_strncmp (p->buffer, "CONNECT", 7) != 0) return false; disable(); p->modemConnected = true; p->outputQueue.head = p->outputQueue.tail = 0; p->inputQueue.head = p->inputQueue.tail = 0; enable(); Con_Printf("Modem Connect\n"); return true; } return true; } // direct connect case if (EMPTY (p->inputQueue)) return false; return true; } qboolean TTY_IsEnabled(int serialPortNumber) { return handleToPort[serialPortNumber]->enabled; } qboolean TTY_IsModem(int serialPortNumber) { return handleToPort[serialPortNumber]->useModem; } qboolean TTY_OutputQueueIsEmpty(int handle) { return EMPTY(handleToPort[handle]->outputQueue); } void Com_f (void) { ComPort *p; int portNumber; int i; int n; // first, determine which port they're messing with portNumber = Q_atoi(Cmd_Argv (0) + 3) - 1; if (portNumber > 1) return; p = handleToPort[portNumber]; if (Cmd_Argc() == 1) { Con_Printf("Settings for COM%i\n", portNumber + 1); Con_Printf("enabled: %s\n", p->enabled ? "true" : "false"); Con_Printf("uart: "); if (p->uartType == UART_AUTO) Con_Printf("auto\n"); else if (p->uartType == UART_8250) Con_Printf("8250\n"); else Con_Printf("16550\n"); Con_Printf("port: %x\n", p->uart); Con_Printf("irq: %i\n", p->irq); Con_Printf("baud: %i\n", 115200 / p->baudBits); Con_Printf("CTS: %s\n", (p->modemStatusIgnore & MSR_CTS) ? "ignored" : "honored"); Con_Printf("DSR: %s\n", (p->modemStatusIgnore & MSR_DSR) ? "ignored" : "honored"); Con_Printf("CD: %s\n", (p->modemStatusIgnore & MSR_CD) ? "ignored" : "honored"); if (p->useModem) { Con_Printf("type: Modem\n"); Con_Printf("clear: %s\n", p->clear); Con_Printf("startup: %s\n", p->startup); Con_Printf("shutdown: %s\n", p->shutdown); } else Con_Printf("type: Direct connect\n"); return; } if (Cmd_CheckParm ("disable")) { if (p->enabled) ComPort_Disable(p); p->modemInitialized = false; return; } if (Cmd_CheckParm ("reset")) { ComPort_Disable(p); ResetComPortConfig (p); return; } if ((i = Cmd_CheckParm ("port")) != 0) { if (p->enabled) { Con_Printf("COM port must be disabled to change port\n"); return; } p->uart = Q_atoi (Cmd_Argv (i+1)); } if ((i = Cmd_CheckParm ("irq")) != 0) { if (p->enabled) { Con_Printf("COM port must be disabled to change irq\n"); return; } p->irq = Q_atoi (Cmd_Argv (i+1)); } if ((i = Cmd_CheckParm ("baud")) != 0) { if (p->enabled) { Con_Printf("COM port must be disabled to change baud\n"); return; } n = Q_atoi (Cmd_Argv (i+1)); if (n == 0) Con_Printf("Invalid baud rate specified\n"); else p->baudBits = 115200 / n; } if (Cmd_CheckParm ("8250")) { if (p->enabled) { Con_Printf("COM port must be disabled to change uart\n"); return; } p->uartType = UART_8250; } if (Cmd_CheckParm ("16550")) { if (p->enabled) { Con_Printf("COM port must be disabled to change uart\n"); return; } p->uartType = UART_16550; } if (Cmd_CheckParm ("auto")) { if (p->enabled) { Con_Printf("COM port must be disabled to change uart\n"); return; } p->uartType = UART_AUTO; } if (Cmd_CheckParm ("pulse")) p->dialType = 'P'; if (Cmd_CheckParm ("tone")) p->dialType = 'T'; if (Cmd_CheckParm ("direct")) p->useModem = false; if (Cmd_CheckParm ("modem")) p->useModem = true; if ((i = Cmd_CheckParm ("clear")) != 0) { Q_strncpy (p->clear, Cmd_Argv (i+1), 16); } if ((i = Cmd_CheckParm ("startup")) != 0) { Q_strncpy (p->startup, Cmd_Argv (i+1), 32); p->modemInitialized = false; } if ((i = Cmd_CheckParm ("shutdown")) != 0) { Q_strncpy (p->shutdown, Cmd_Argv (i+1), 16); } if (Cmd_CheckParm ("-cts")) { p->modemStatusIgnore |= MSR_CTS; p->modemStatus |= MSR_CTS; } if (Cmd_CheckParm ("+cts")) { p->modemStatusIgnore &= (~MSR_CTS); p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore; } if (Cmd_CheckParm ("-dsr")) { p->modemStatusIgnore |= MSR_DSR; p->modemStatus |= MSR_DSR; } if (Cmd_CheckParm ("+dsr")) { p->modemStatusIgnore &= (~MSR_DSR); p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore; } if (Cmd_CheckParm ("-cd")) { p->modemStatusIgnore |= MSR_CD; p->modemStatus |= MSR_CD; } if (Cmd_CheckParm ("+cd")) { p->modemStatusIgnore &= (~MSR_CD); p->modemStatus = (inportb (p->uart + MODEM_STATUS_REGISTER) & MODEM_STATUS_MASK) | p->modemStatusIgnore; } if (Cmd_CheckParm ("enable")) { if (!p->enabled) ComPort_Enable(p); if (p->useModem && !p->modemInitialized) Modem_Init (p); } } int TTY_Init(void) { int n; ComPort *p; for (n = 0; n < NUM_COM_PORTS; n++) { p = (ComPort *)Hunk_AllocName(sizeof(ComPort), "comport"); if (p == NULL) Sys_Error("Hunk alloc failed for com port\n"); p->next = portList; portList = p; handleToPort[n] = p; p->portNumber = n; p->dialType = 'T'; sprintf(p->name, "com%u", n+1); Cmd_AddCommand (p->name, Com_f); ResetComPortConfig (p); } GetComPortConfig = TTY_GetComPortConfig; SetComPortConfig = TTY_SetComPortConfig; GetModemConfig = TTY_GetModemConfig; SetModemConfig = TTY_SetModemConfig; return 0; } void TTY_Shutdown(void) { int n; ComPort *p; for (n = 0; n < NUM_COM_PORTS; n++) { p = handleToPort[n]; if (p->enabled) { while (p->modemConnected) NET_Poll(); ComPort_Disable (p); } } } static int Modem_Command(ComPort *p, char *commandString) { byte b; if (CheckStatus (p)) return -1; disable(); p->outputQueue.head = p->outputQueue.tail = 0; p->inputQueue.head = p->inputQueue.tail = 0; enable(); p->bufferUsed = 0; while (*commandString) ENQUEUE (p->outputQueue, *commandString++); ENQUEUE (p->outputQueue, '\r'); // get the transmit rolling DEQUEUE (p->outputQueue, b); outportb(p->uart, b); return 0; } static char *Modem_Response(ComPort *p) { byte b; if (CheckStatus (p)) return NULL; while (! EMPTY(p->inputQueue)) { DEQUEUE (p->inputQueue, b); if (p->bufferUsed == (sizeof(p->buffer) - 1)) b = '\r'; if (b == '\r' && p->bufferUsed) { p->buffer[p->bufferUsed] = 0; Con_Printf("%s\n", p->buffer); SCR_UpdateScreen (); p->bufferUsed = 0; return p->buffer; } if (b < ' ' || b > 'z') continue; p->buffer[p->bufferUsed] = b; p->bufferUsed++; } return NULL; } static void Modem_Hangup2(ComPort *p); static void Modem_Hangup3(ComPort *p); static void Modem_Hangup4(ComPort *p); static void Modem_Hangup(ComPort *p) { Con_Printf("Hanging up modem...\n"); disable(); p->modemRang = false; p->outputQueue.head = p->outputQueue.tail = 0; p->inputQueue.head = p->inputQueue.tail = 0; outportb(p->uart + MODEM_CONTROL_REGISTER, inportb(p->uart + MODEM_CONTROL_REGISTER) & ~MCR_DTR); enable(); p->poll.procedure = Modem_Hangup2; p->poll.arg = p; SchedulePollProcedure(&p->poll, 1.5); } static void Modem_Hangup2(ComPort *p) { outportb(p->uart + MODEM_CONTROL_REGISTER, inportb(p->uart + MODEM_CONTROL_REGISTER) | MCR_DTR); Modem_Command(p, "+++"); p->poll.procedure = Modem_Hangup3; SchedulePollProcedure(&p->poll, 1.5); } static void Modem_Hangup3(ComPort *p) { Modem_Command(p, p->shutdown); p->poll.procedure = Modem_Hangup4; SchedulePollProcedure(&p->poll, 1.5); } static void Modem_Hangup4(ComPort *p) { Modem_Response(p); Con_Printf("Hangup complete\n"); p->modemConnected = false; }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sys_sun.h -- Sun system driver #include "quakedef.h" #include "errno.h" #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/param.h> #include <fcntl.h> #include <stddef.h> #include <sys/types.h> #include <fcntl.h> #include <sys/mman.h> #include <stdio.h> qboolean isDedicated; /* =============================================================================== FILE IO =============================================================================== */ #define MAX_HANDLES 10 typedef struct { FILE *hFile; char *pMap; int nLen; int nPos; } MEMFILE; MEMFILE sys_handles[MAX_HANDLES]; int findhandle (void) { int i; for (i=1 ; i<MAX_HANDLES ; i++) if (!sys_handles[i].hFile) return i; Sys_Error ("out of handles"); return -1; } /* ================ filelength ================ */ int filelength (FILE *f) { int pos; int end; pos = ftell (f); fseek (f, 0, SEEK_END); end = ftell (f); fseek (f, pos, SEEK_SET); return end; } int Sys_FileOpenRead (char *path, int *hndl) { FILE *f; int i; i = findhandle (); f = fopen(path, "rb"); if (!f) { *hndl = -1; return -1; } sys_handles[i].hFile = f; sys_handles[i].nLen = filelength(f); sys_handles[i].nPos = 0; sys_handles[i].pMap = mmap( 0, sys_handles[i].nLen, PROT_READ, MAP_SHARED, fileno( sys_handles[i].hFile ), 0 ); if (!sys_handles[i].pMap || (sys_handles[i].pMap == (char *)-1)) { printf( "mmap %s failed!", path ); sys_handles[i].pMap = NULL; } *hndl = i; return( sys_handles[i].nLen ); } int Sys_FileOpenWrite (char *path) { FILE *f; int i; i = findhandle (); f = fopen(path, "wb"); if (!f) Sys_Error ("Error opening %s: %s", path,strerror(errno)); sys_handles[i].hFile = f; sys_handles[i].nLen = 0; sys_handles[i].nPos = 0; sys_handles[i].pMap = NULL; return i; } void Sys_FileClose (int handle) { if (sys_handles[handle].pMap) if (munmap( sys_handles[handle].pMap, sys_handles[handle].nLen ) != 0) printf( "failed to unmap handle %d\n", handle ); fclose (sys_handles[handle].hFile); sys_handles[handle].hFile = NULL; } void Sys_FileSeek (int handle, int position) { if (sys_handles[handle].pMap) { sys_handles[handle].nPos = position; } else fseek (sys_handles[handle].hFile, position, SEEK_SET); } int Sys_FileRead (int handle, void *dest, int count) { if (sys_handles[handle].pMap) { int nPos = sys_handles[handle].nPos; if (count < 0) count = 0; if (nPos + count > sys_handles[handle].nLen) count = sys_handles[handle].nLen - nPos; memcpy( dest, &sys_handles[handle].pMap[nPos], count ); sys_handles[handle].nPos = nPos + count; return( count ); } else return fread (dest, 1, count, sys_handles[handle].hFile); } int Sys_FileWrite (int handle, void *data, int count) { if (sys_handles[handle].pMap) Sys_Error( "Attempted to write to read-only file %d!\n", handle ); return fwrite (data, 1, count, sys_handles[handle].hFile); } int Sys_FileTime (char *path) { FILE *f; f = fopen(path, "rb"); if (f) { fclose(f); return 1; } return -1; } void Sys_mkdir (char *path) { mkdir( path, 0777 ); } /* =============================================================================== SYSTEM IO =============================================================================== */ void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length) { int r; unsigned long addr; int psize = getpagesize(); addr = (startaddr & ~(psize-1)) - psize; // fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr, // addr, startaddr+length, length); r = mprotect((char*)addr, length + startaddr - addr + psize, 7); if (r < 0) Sys_Error("Protection change failed\n"); } void Sys_Error (char *error, ...) { va_list argptr; printf ("Sys_Error: "); va_start (argptr,error); vprintf (error,argptr); va_end (argptr); printf ("\n"); Host_Shutdown(); exit (1); } void Sys_Printf (char *fmt, ...) { va_list argptr; va_start (argptr,fmt); vprintf (fmt,argptr); va_end (argptr); } void Sys_Quit (void) { Host_Shutdown(); exit (0); } double Sys_FloatTime (void) { struct timeval tp; struct timezone tzp; static int secbase; gettimeofday(&tp, &tzp); if (!secbase) { secbase = tp.tv_sec; return tp.tv_usec/1000000.0; } return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0; } char *Sys_ConsoleInput (void) { static char text[256]; int len; fd_set readfds; int ready; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; FD_ZERO(&readfds); FD_SET(0, &readfds); ready = select(1, &readfds, 0, 0, &timeout); if (ready>0) { len = read (0, text, sizeof(text)); if (len >= 1) { text[len-1] = 0; // rip off the /n and terminate return text; } } return 0; } void Sys_Sleep (void) { } #if !id386 void Sys_HighFPPrecision (void) { } void Sys_LowFPPrecision (void) { } #endif void Sys_Init(void) { #if id386 Sys_SetFPCW(); #endif } //============================================================================= int main (int argc, char **argv) { static quakeparms_t parms; float time, oldtime, newtime; parms.memsize = 16*1024*1024; parms.membase = malloc (parms.memsize); parms.basedir = "."; parms.cachedir = NULL; COM_InitArgv (argc, argv); parms.argc = com_argc; parms.argv = com_argv; printf ("Host_Init\n"); Host_Init (&parms); Sys_Init(); // unroll the simulation loop to give the video side a chance to see _vid_default_mode Host_Frame( 0.1 ); VID_SetDefaultMode(); oldtime = Sys_FloatTime(); while (1) { newtime = Sys_FloatTime(); Host_Frame (newtime - oldtime); oldtime = newtime; } return 0; }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // d_part.c: software driver module for drawing particles #include "quakedef.h" #include "d_local.h" /* ============== D_EndParticles ============== */ void D_EndParticles (void) { // not used by software driver } /* ============== D_StartParticles ============== */ void D_StartParticles (void) { // not used by software driver } #if !id386 /* ============== D_DrawParticle ============== */ void D_DrawParticle (particle_t *pparticle) { 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); if (transformed[2] < PARTICLE_Z_CLIP) return; // 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); 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); pix = izi >> d_pix_shift; if (pix < d_pix_min) pix = d_pix_min; else if (pix > d_pix_max) pix = d_pix_max; 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 ; i<pix ; i++) { if (pz[i] <= izi) { pz[i] = izi; pdest[i] = pparticle->color; } } } break; } } #endif // !id386
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // cl_main.c -- client main loop #include "quakedef.h" // we need to declare some mouse variables here, because the menu system // references them even when on a unix system. // these two are not intended to be set directly cvar_t cl_name = CVAR3("_cl_name", "player", true); cvar_t cl_color = CVAR3("_cl_color", "0", true); cvar_t cl_shownet = CVAR2("cl_shownet","0"); // can be 0, 1, or 2 cvar_t cl_nolerp = CVAR2("cl_nolerp","0"); cvar_t lookspring = CVAR3("lookspring","0", true); cvar_t lookstrafe = CVAR3("lookstrafe","0", true); cvar_t sensitivity = CVAR3("sensitivity","3", true); cvar_t m_pitch = CVAR3("m_pitch","0.022", true); cvar_t m_yaw = CVAR3("m_yaw","0.022", true); cvar_t m_forward = CVAR3("m_forward","1", true); cvar_t m_side = CVAR3("m_side","0.8", true); client_static_t cls; client_state_t cl; // FIXME: put these on hunk? efrag_t cl_efrags[MAX_EFRAGS]; entity_t cl_entities[MAX_EDICTS]; entity_t cl_static_entities[MAX_STATIC_ENTITIES]; lightstyle_t cl_lightstyle[MAX_LIGHTSTYLES]; dlight_t cl_dlights[MAX_DLIGHTS]; int cl_numvisedicts; entity_t *cl_visedicts[MAX_VISEDICTS]; /* ===================== CL_ClearState ===================== */ void CL_ClearState (void) { int i; if (!sv.active) Host_ClearMemory (); // wipe the entire cl structure memset (&cl, 0, sizeof(cl)); SZ_Clear (&cls.message); // clear other arrays memset (cl_efrags, 0, sizeof(cl_efrags)); memset (cl_entities, 0, sizeof(cl_entities)); memset (cl_dlights, 0, sizeof(cl_dlights)); memset (cl_lightstyle, 0, sizeof(cl_lightstyle)); memset (cl_temp_entities, 0, sizeof(cl_temp_entities)); memset (cl_beams, 0, sizeof(cl_beams)); // // allocate the efrags and chain together into a free list // cl.free_efrags = cl_efrags; for (i=0 ; i<MAX_EFRAGS-1 ; i++) cl.free_efrags[i].entnext = &cl.free_efrags[i+1]; cl.free_efrags[i].entnext = NULL; } /* ===================== CL_Disconnect Sends a disconnect message to the server This is also called on Host_Error, so it shouldn't cause any errors ===================== */ void CL_Disconnect (void) { // stop sounds (especially looping!) S_StopAllSounds (true); // bring the console down and fade the colors back to normal // SCR_BringDownConsole (); // if running a local server, shut it down if (cls.demoplayback) CL_StopPlayback (); else if (cls.state == ca_connected) { if (cls.demorecording) CL_Stop_f (); Con_DPrintf ("Sending clc_disconnect\n"); SZ_Clear (&cls.message); MSG_WriteByte (&cls.message, clc_disconnect); NET_SendUnreliableMessage (cls.netcon, &cls.message); SZ_Clear (&cls.message); NET_Close (cls.netcon); cls.state = ca_disconnected; if (sv.active) Host_ShutdownServer(false); } cls.demoplayback = cls.timedemo = false; cls.signon = 0; } void CL_Disconnect_f (void) { CL_Disconnect (); if (sv.active) Host_ShutdownServer (false); } /* ===================== CL_EstablishConnection Host should be either "local" or a net address to be passed on ===================== */ void CL_EstablishConnection (const char *host) { if (cls.state == ca_dedicated) return; if (cls.demoplayback) return; CL_Disconnect (); cls.netcon = NET_Connect (host); if (!cls.netcon) Host_Error ("CL_Connect: connect failed\n"); Con_DPrintf ("CL_EstablishConnection: connected to %s\n", host); cls.demonum = -1; // not in the demo loop now cls.state = ca_connected; cls.signon = 0; // need all the signon messages before playing } /* ===================== CL_SignonReply An svc_signonnum has been received, perform a client side setup ===================== */ void CL_SignonReply (void) { char str[8192]; Con_DPrintf ("CL_SignonReply: %i\n", cls.signon); switch (cls.signon) { case 1: MSG_WriteByte (&cls.message, clc_stringcmd); MSG_WriteString (&cls.message, "prespawn"); break; case 2: MSG_WriteByte (&cls.message, clc_stringcmd); MSG_WriteString (&cls.message, va("name \"%s\"\n", cl_name.string)); MSG_WriteByte (&cls.message, clc_stringcmd); MSG_WriteString (&cls.message, va("color %i %i\n", ((int)cl_color.value)>>4, ((int)cl_color.value)&15)); MSG_WriteByte (&cls.message, clc_stringcmd); sprintf (str, "spawn %s", cls.spawnparms); MSG_WriteString (&cls.message, str); break; case 3: MSG_WriteByte (&cls.message, clc_stringcmd); MSG_WriteString (&cls.message, "begin"); Cache_Report (); // print remaining memory break; case 4: SCR_EndLoadingPlaque (); // allow normal screen updates break; } } /* ===================== CL_NextDemo Called to play the next demo in the demo loop ===================== */ void CL_NextDemo (void) { char str[1024]; if (cls.demonum == -1) return; // don't play demos SCR_BeginLoadingPlaque (); if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) { cls.demonum = 0; if (!cls.demos[cls.demonum][0]) { Con_Printf ("No demos listed with startdemos\n"); cls.demonum = -1; return; } } sprintf (str,"playdemo %s\n", cls.demos[cls.demonum]); Cbuf_InsertText (str); cls.demonum++; } /* ============== CL_PrintEntities_f ============== */ void CL_PrintEntities_f (void) { entity_t *ent; int i; for (i=0,ent=cl_entities ; i<cl.num_entities ; i++,ent++) { Con_Printf ("%3i:",i); if (!ent->model) { Con_Printf ("EMPTY\n"); continue; } Con_Printf ("%s:%2i (%5.1f,%5.1f,%5.1f) [%5.1f %5.1f %5.1f]\n" ,ent->model->name,ent->frame, ent->origin[0], ent->origin[1], ent->origin[2], ent->angles[0], ent->angles[1], ent->angles[2]); } } /* =============== SetPal Debugging tool, just flashes the screen =============== */ void SetPal (int i) { #if 0 static int old; byte pal[768]; int c; if (i == old) return; old = i; if (i==0) VID_SetPalette (host_basepal); else if (i==1) { for (c=0 ; c<768 ; c+=3) { pal[c] = 0; pal[c+1] = 255; pal[c+2] = 0; } VID_SetPalette (pal); } else { for (c=0 ; c<768 ; c+=3) { pal[c] = 0; pal[c+1] = 0; pal[c+2] = 255; } VID_SetPalette (pal); } #endif } /* =============== CL_AllocDlight =============== */ dlight_t *CL_AllocDlight (int key) { int i; dlight_t *dl; // first look for an exact key match if (key) { dl = cl_dlights; for (i=0 ; i<MAX_DLIGHTS ; i++, dl++) { if (dl->key == key) { memset (dl, 0, sizeof(*dl)); dl->key = key; return dl; } } } // then look for anything else dl = cl_dlights; for (i=0 ; i<MAX_DLIGHTS ; i++, dl++) { if (dl->die < cl.time) { memset (dl, 0, sizeof(*dl)); dl->key = key; return dl; } } dl = &cl_dlights[0]; memset (dl, 0, sizeof(*dl)); dl->key = key; return dl; } /* =============== CL_DecayLights =============== */ void CL_DecayLights (void) { int i; dlight_t *dl; float time; time = cl.time - cl.oldtime; dl = cl_dlights; for (i=0 ; i<MAX_DLIGHTS ; i++, dl++) { if (dl->die < cl.time || !dl->radius) continue; dl->radius -= time*dl->decay; if (dl->radius < 0) dl->radius = 0; } } /* =============== CL_LerpPoint Determines the fraction between the last two messages that the objects should be put at. =============== */ float CL_LerpPoint (void) { float f, frac; f = cl.mtime[0] - cl.mtime[1]; if (!f || cl_nolerp.value || cls.timedemo || sv.active) { cl.time = cl.mtime[0]; return 1; } if (f > 0.1) { // dropped packet, or start of demo cl.mtime[1] = cl.mtime[0] - 0.1; f = 0.1; } frac = (cl.time - cl.mtime[1]) / f; //Con_Printf ("frac: %f\n",frac); if (frac < 0) { if (frac < -0.01) { SetPal(1); cl.time = cl.mtime[1]; // Con_Printf ("low frac\n"); } frac = 0; } else if (frac > 1) { if (frac > 1.01) { SetPal(2); cl.time = cl.mtime[0]; // Con_Printf ("high frac\n"); } frac = 1; } else SetPal(0); return frac; } /* =============== CL_RelinkEntities =============== */ void CL_RelinkEntities (void) { entity_t *ent; int i, j; float frac, f, d; vec3_t delta; float bobjrotate; vec3_t oldorg; dlight_t *dl; // determine partial update time frac = CL_LerpPoint (); cl_numvisedicts = 0; // // interpolate player info // for (i=0 ; i<3 ; i++) cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]); if (cls.demoplayback) { // interpolate the angles for (j=0 ; j<3 ; j++) { d = cl.mviewangles[0][j] - cl.mviewangles[1][j]; if (d > 180) d -= 360; else if (d < -180) d += 360; cl.viewangles[j] = cl.mviewangles[1][j] + frac*d; } } bobjrotate = anglemod(100*cl.time); // start on the entity after the world for (i=1,ent=cl_entities+1 ; i<cl.num_entities ; i++,ent++) { if (!ent->model) { // empty slot if (ent->forcelink) R_RemoveEfrags (ent); // just became empty continue; } // if the object wasn't included in the last packet, remove it if (ent->msgtime != cl.mtime[0]) { ent->model = NULL; continue; } VectorCopy (ent->origin, oldorg); if (ent->forcelink) { // the entity was not updated in the last message // so move to the final spot VectorCopy (ent->msg_origins[0], ent->origin); VectorCopy (ent->msg_angles[0], ent->angles); } else { // if the delta is large, assume a teleport and don't lerp f = frac; for (j=0 ; j<3 ; j++) { delta[j] = ent->msg_origins[0][j] - ent->msg_origins[1][j]; if (delta[j] > 100 || delta[j] < -100) f = 1; // assume a teleportation, not a motion } // interpolate the origin and angles for (j=0 ; j<3 ; j++) { ent->origin[j] = ent->msg_origins[1][j] + f*delta[j]; d = ent->msg_angles[0][j] - ent->msg_angles[1][j]; if (d > 180) d -= 360; else if (d < -180) d += 360; ent->angles[j] = ent->msg_angles[1][j] + f*d; } } // rotate binary objects locally if (ent->model->flags & EF_ROTATE) ent->angles[1] = bobjrotate; if (ent->effects & EF_BRIGHTFIELD) R_EntityParticles (ent); #ifdef QUAKE2 if (ent->effects & EF_DARKFIELD) R_DarkFieldParticles (ent); #endif if (ent->effects & EF_MUZZLEFLASH) { vec3_t fv, rv, uv; dl = CL_AllocDlight (i); VectorCopy (ent->origin, dl->origin); dl->origin[2] += 16; AngleVectors (ent->angles, fv, rv, uv); VectorMA (dl->origin, 18, fv, dl->origin); dl->radius = 200 + (rand()&31); dl->minlight = 32; dl->die = cl.time + 0.1; } if (ent->effects & EF_BRIGHTLIGHT) { dl = CL_AllocDlight (i); VectorCopy (ent->origin, dl->origin); dl->origin[2] += 16; dl->radius = 400 + (rand()&31); dl->die = cl.time + 0.001; } if (ent->effects & EF_DIMLIGHT) { dl = CL_AllocDlight (i); VectorCopy (ent->origin, dl->origin); dl->radius = 200 + (rand()&31); dl->die = cl.time + 0.001; } #ifdef QUAKE2 if (ent->effects & EF_DARKLIGHT) { dl = CL_AllocDlight (i); VectorCopy (ent->origin, dl->origin); dl->radius = 200.0 + (rand()&31); dl->die = cl.time + 0.001; dl->dark = true; } if (ent->effects & EF_LIGHT) { dl = CL_AllocDlight (i); VectorCopy (ent->origin, dl->origin); dl->radius = 200; dl->die = cl.time + 0.001; } #endif if (ent->model->flags & EF_GIB) R_RocketTrail (oldorg, ent->origin, 2); else if (ent->model->flags & EF_ZOMGIB) R_RocketTrail (oldorg, ent->origin, 4); else if (ent->model->flags & EF_TRACER) R_RocketTrail (oldorg, ent->origin, 3); else if (ent->model->flags & EF_TRACER2) R_RocketTrail (oldorg, ent->origin, 5); else if (ent->model->flags & EF_ROCKET) { R_RocketTrail (oldorg, ent->origin, 0); dl = CL_AllocDlight (i); VectorCopy (ent->origin, dl->origin); dl->radius = 200; dl->die = cl.time + 0.01; } else if (ent->model->flags & EF_GRENADE) R_RocketTrail (oldorg, ent->origin, 1); else if (ent->model->flags & EF_TRACER3) R_RocketTrail (oldorg, ent->origin, 6); ent->forcelink = false; if (i == cl.viewentity && !chase_active.value) continue; #ifdef QUAKE2 if ( ent->effects & EF_NODRAW ) continue; #endif if (cl_numvisedicts < MAX_VISEDICTS) { cl_visedicts[cl_numvisedicts] = ent; cl_numvisedicts++; } } } /* =============== CL_ReadFromServer Read all incoming data from the server =============== */ int CL_ReadFromServer (void) { int ret; cl.oldtime = cl.time; cl.time += host_frametime; do { ret = CL_GetMessage (); if (ret == -1) Host_Error ("CL_ReadFromServer: lost server connection"); if (!ret) break; cl.last_received_message = realtime; CL_ParseServerMessage (); } while (ret && cls.state == ca_connected); if (cl_shownet.value) Con_Printf ("\n"); CL_RelinkEntities (); CL_UpdateTEnts (); // // bring the links up to date // return 0; } /* ================= CL_SendCmd ================= */ void CL_SendCmd (void) { usercmd_t cmd; if (cls.state != ca_connected) return; if (cls.signon == SIGNONS) { // get basic movement from keyboard CL_BaseMove (&cmd); // allow mice or other external controllers to add to the move IN_Move (&cmd); // send the unreliable message CL_SendMove (&cmd); } if (cls.demoplayback) { SZ_Clear (&cls.message); return; } // send the reliable message if (!cls.message.cursize) return; // no message at all if (!NET_CanSendMessage (cls.netcon)) { Con_DPrintf ("CL_WriteToServer: can't send\n"); return; } if (NET_SendMessage (cls.netcon, &cls.message) == -1) Host_Error ("CL_WriteToServer: lost server connection"); SZ_Clear (&cls.message); } /* ================= CL_Init ================= */ void CL_Init (void) { SZ_Alloc (&cls.message, 1024); CL_InitInput (); CL_InitTEnts (); // // register our commands // Cvar_RegisterVariable (&cl_name); Cvar_RegisterVariable (&cl_color); Cvar_RegisterVariable (&cl_upspeed); Cvar_RegisterVariable (&cl_forwardspeed); Cvar_RegisterVariable (&cl_backspeed); Cvar_RegisterVariable (&cl_sidespeed); Cvar_RegisterVariable (&cl_movespeedkey); Cvar_RegisterVariable (&cl_yawspeed); Cvar_RegisterVariable (&cl_pitchspeed); Cvar_RegisterVariable (&cl_anglespeedkey); Cvar_RegisterVariable (&cl_shownet); Cvar_RegisterVariable (&cl_nolerp); Cvar_RegisterVariable (&lookspring); Cvar_RegisterVariable (&lookstrafe); Cvar_RegisterVariable (&sensitivity); Cvar_RegisterVariable (&m_pitch); Cvar_RegisterVariable (&m_yaw); Cvar_RegisterVariable (&m_forward); Cvar_RegisterVariable (&m_side); // Cvar_RegisterVariable (&cl_autofire); Cmd_AddCommand ("entities", CL_PrintEntities_f); Cmd_AddCommand ("disconnect", CL_Disconnect_f); Cmd_AddCommand ("record", CL_Record_f); Cmd_AddCommand ("stop", CL_Stop_f); Cmd_AddCommand ("playdemo", CL_PlayDemo_f); Cmd_AddCommand ("timedemo", CL_TimeDemo_f); }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_surf.c: surface-related refresh code #include "quakedef.h" #include "r_local.h" drawsurf_t r_drawsurf; int lightleft, sourcesstep, blocksize, sourcetstep; int lightdelta, lightdeltastep; int lightright, lightleftstep, lightrightstep, blockdivshift; unsigned blockdivmask; void *prowdestbase; unsigned char *pbasesource; int surfrowbytes; // used by ASM files unsigned *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); static void (*surfmiptable[4])(void) = { R_DrawSurfaceBlock8_mip0, R_DrawSurfaceBlock8_mip1, R_DrawSurfaceBlock8_mip2, R_DrawSurfaceBlock8_mip3 }; unsigned blocklights[18*18]; /* =============== R_AddDynamicLights =============== */ void R_AddDynamicLights (void) { msurface_t *surf; int lnum; int sd, td; float dist, rad, minlight; vec3_t impact, local; 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; tex = surf->texinfo; for (lnum=0 ; lnum<MAX_DLIGHTS ; lnum++) { if ( !(surf->dlightbits & (1<<lnum) ) ) continue; // not lit by this light rad = cl_dlights[lnum].radius; dist = DotProduct (cl_dlights[lnum].origin, surf->plane->normal) - 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] = cl_dlights[lnum].origin[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<tmax ; t++) { td = local[1] - t*16; if (td < 0) td = -td; for (s=0 ; s<smax ; s++) { sd = local[0] - s*16; if (sd < 0) sd = -sd; if (sd > td) dist = sd + (td>>1); else dist = td + (sd>>1); if (dist < minlight) #ifdef QUAKE2 { unsigned temp; temp = (rad - dist)*256; i = t*smax + s; if (!cl_dlights[lnum].dark) blocklights[i] += temp; else { if (blocklights[i] > temp) blocklights[i] -= temp; else blocklights[i] = 0; } } #else blocklights[t*smax + s] += (rad - dist)*256; #endif } } } } /* =============== R_BuildLightMap Combine and scale multiple lightmaps into the 8.8 format in blocklights =============== */ void R_BuildLightMap (void) { int smax, tmax; int t; int i, size; byte *lightmap; unsigned 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; lightmap = surf->samples; if (r_fullbright.value || !cl.worldmodel->lightdata) { for (i=0 ; i<size ; i++) blocklights[i] = 0; return; } // clear to ambient for (i=0 ; i<size ; i++) blocklights[i] = r_refdef.ambientlight<<8; // add all the lightmaps if (lightmap) for (maps = 0 ; maps < MAXLIGHTMAPS && surf->styles[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 } // add all the dynamic lights if (surf->dlightframe == r_framecount) R_AddDynamicLights (); // bound, invert, and shift for (i=0 ; i<size ; i++) { t = (255*256 - (int)blocklights[i]) >> (8 - VID_CBITS); if (t < (1 << 6)) t = (1 << 6); blocklights[i] = t; } } /* =============== R_TextureAnimation Returns the proper texture for a given time and base texture =============== */ texture_t *R_TextureAnimation (texture_t *base) { int reletive; int count; 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; count = 0; while (base->anim_min > reletive || base->anim_max <= reletive) { base = base->anim_next; if (!base) Sys_Error ("R_TextureAnimation: broken cycle"); if (++count > 100) Sys_Error ("R_TextureAnimation: infinite cycle"); } return base; } /* =============== R_DrawSurface =============== */ 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; // calculate the lightings R_BuildLightMap (); surfrowbytes = r_drawsurf.rowbytes; mt = r_drawsurf.texture; 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_numhblocks = r_drawsurf.surfwidth >> blockdivshift; r_numvblocks = r_drawsurf.surfheight >> blockdivshift; //============================== if (r_pixbytes == 1) { pblockdrawer = surfmiptable[r_drawsurf.surfmip]; // TODO: only needs to be set when there is a display settings change horzblockstep = blocksize; } else { pblockdrawer = R_DrawSurfaceBlock16; // TODO: only needs to be set when there is a display settings change horzblockstep = blocksize << 1; } smax = mt->width >> r_drawsurf.surfmip; twidth = texwidth; tmax = mt->height >> r_drawsurf.surfmip; sourcetstep = texwidth; r_stepback = tmax * twidth; r_sourcemax = r_source + (tmax * smax); soffset = r_drawsurf.surf->texturemins[0]; basetoffset = r_drawsurf.surf->texturemins[1]; // << 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)]; pcolumndest = r_drawsurf.surfdat; for (u=0 ; u<r_numhblocks; u++) { r_lightptr = blocklights + u; prowdestbase = pcolumndest; pbasesource = basetptr + soffset; (*pblockdrawer)(); soffset = soffset + blocksize; if (soffset >= smax) soffset = 0; pcolumndest += horzblockstep; } } //============================================================================= #if !id386 /* ================ R_DrawSurfaceBlock8_mip0 ================ */ void R_DrawSurfaceBlock8_mip0 (void) { int v, i, b, lightstep, lighttemp, light; unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; for (v=0 ; v<r_numvblocks ; v++) { // FIXME: make these locals? // FIXME: use delta rather than both right and left, like ASM? lightleft = r_lightptr[0]; lightright = r_lightptr[1]; r_lightptr += r_lightwidth; lightleftstep = (r_lightptr[0] - lightleft) >> 4; lightrightstep = (r_lightptr[1] - lightright) >> 4; for (i=0 ; i<16 ; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 4; light = lightright; for (b=15; b>=0; b--) { pix = psource[b]; prowdest[b] = ((unsigned char *)vid.colormap) [(light & 0xFF00) + pix]; light += lightstep; } psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; prowdest += surfrowbytes; } if (psource >= r_sourcemax) psource -= r_stepback; } } /* ================ R_DrawSurfaceBlock8_mip1 ================ */ void R_DrawSurfaceBlock8_mip1 (void) { int v, i, b, lightstep, lighttemp, light; unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; for (v=0 ; v<r_numvblocks ; v++) { // FIXME: make these locals? // FIXME: use delta rather than both right and left, like ASM? lightleft = r_lightptr[0]; lightright = r_lightptr[1]; r_lightptr += r_lightwidth; lightleftstep = (r_lightptr[0] - lightleft) >> 3; lightrightstep = (r_lightptr[1] - lightright) >> 3; for (i=0 ; i<8 ; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 3; light = lightright; for (b=7; b>=0; b--) { pix = psource[b]; prowdest[b] = ((unsigned char *)vid.colormap) [(light & 0xFF00) + pix]; light += lightstep; } psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; prowdest += surfrowbytes; } if (psource >= r_sourcemax) psource -= r_stepback; } } /* ================ R_DrawSurfaceBlock8_mip2 ================ */ void R_DrawSurfaceBlock8_mip2 (void) { int v, i, b, lightstep, lighttemp, light; unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; for (v=0 ; v<r_numvblocks ; v++) { // FIXME: make these locals? // FIXME: use delta rather than both right and left, like ASM? lightleft = r_lightptr[0]; lightright = r_lightptr[1]; r_lightptr += r_lightwidth; lightleftstep = (r_lightptr[0] - lightleft) >> 2; lightrightstep = (r_lightptr[1] - lightright) >> 2; for (i=0 ; i<4 ; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 2; light = lightright; for (b=3; b>=0; b--) { pix = psource[b]; prowdest[b] = ((unsigned char *)vid.colormap) [(light & 0xFF00) + pix]; light += lightstep; } psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; prowdest += surfrowbytes; } if (psource >= r_sourcemax) psource -= r_stepback; } } /* ================ R_DrawSurfaceBlock8_mip3 ================ */ void R_DrawSurfaceBlock8_mip3 (void) { int v, i, b, lightstep, lighttemp, light; unsigned char pix, *psource, *prowdest; psource = pbasesource; prowdest = prowdestbase; for (v=0 ; v<r_numvblocks ; v++) { // FIXME: make these locals? // FIXME: use delta rather than both right and left, like ASM? lightleft = r_lightptr[0]; lightright = r_lightptr[1]; r_lightptr += r_lightwidth; lightleftstep = (r_lightptr[0] - lightleft) >> 1; lightrightstep = (r_lightptr[1] - lightright) >> 1; for (i=0 ; i<2 ; i++) { lighttemp = lightleft - lightright; lightstep = lighttemp >> 1; light = lightright; for (b=1; b>=0; b--) { pix = psource[b]; prowdest[b] = ((unsigned char *)vid.colormap) [(light & 0xFF00) + pix]; light += lightstep; } psource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; prowdest += surfrowbytes; } if (psource >= r_sourcemax) psource -= r_stepback; } } /* ================ R_DrawSurfaceBlock16 FIXME: make this work ================ */ void R_DrawSurfaceBlock16 (void) { int k; unsigned char *psource; int lighttemp, lightstep, light; unsigned short *prowdest; prowdest = (unsigned short *)prowdestbase; for (k=0 ; k<blocksize ; k++) { unsigned short *pdest; unsigned char pix; int b; psource = pbasesource; lighttemp = lightright - lightleft; lightstep = lighttemp >> blockdivshift; light = lightleft; pdest = prowdest; for (b=0; b<blocksize; b++) { pix = *psource; *pdest = vid.colormap16[(light & 0xFF00) + pix]; psource += sourcesstep; pdest++; light += lightstep; } pbasesource += sourcetstep; lightright += lightrightstep; lightleft += lightleftstep; prowdest = (unsigned short *)((long)prowdest + surfrowbytes); } prowdestbase = prowdest; } #endif //============================================================================ /* ================ R_GenTurbTile ================ */ void R_GenTurbTile (pixel_t *pbasetex, void *pdest) { int *turb; int i, j, s, t; byte *pd; 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); } } } /* ================ R_GenTurbTile16 ================ */ void R_GenTurbTile16 (pixel_t *pbasetex, void *pdest) { int *turb; int i, j, s, t; unsigned short *pd; turb = sintable + ((int)(cl.time*SPEED)&(CYCLE-1)); pd = (unsigned short *)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++ = d_8to16table[*(pbasetex + (t<<6) + s)]; } } } /* ================ R_GenTile ================ */ void R_GenTile (msurface_t *psurf, void *pdest) { if (psurf->flags & SURF_DRAWTURB) { if (r_pixbytes == 1) { R_GenTurbTile ((pixel_t *) ((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); } } else if (psurf->flags & SURF_DRAWSKY) { if (r_pixbytes == 1) { R_GenSkyTile (pdest); } else { R_GenSkyTile16 (pdest); } } else { Sys_Error ("Unknown tile type"); } }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // d_edge.c #include "quakedef.h" #include "d_local.h" static int miplevel; float scale_for_mip; int screenwidth; int ubasestep, errorterm, erroradjustup, erroradjustdown; int vstartscan; // FIXME: should go away extern void R_RotateBmodel (void); extern void R_TransformFrustum (void); vec3_t transformed_modelorg; /* ============== D_DrawPoly ============== */ void D_DrawPoly (void) { // this driver takes spans, not polygons } /* ============= D_MipLevelForScale ============= */ int D_MipLevelForScale (float scale) { int lmiplevel; if (scale >= d_scalemip[0] ) lmiplevel = 0; else if (scale >= d_scalemip[1] ) lmiplevel = 1; else if (scale >= d_scalemip[2] ) lmiplevel = 2; else lmiplevel = 3; if (lmiplevel < d_minmip) lmiplevel = d_minmip; return lmiplevel; } /* ============== D_DrawSolidSurface ============== */ // FIXME: clean this up 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; u = span->u; u2 = span->u + span->count - 1; ((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; u2 += 4; for ( ; u <= u2 ; u++) ((byte *)pdest)[u] = pix; } } } /* ============== D_CalcGradients ============== */ void D_CalcGradients (msurface_t *pface) { 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); TransformVector (pface->texinfo->vecs[0], p_saxis); TransformVector (pface->texinfo->vecs[1], p_taxis); t = xscaleinv * mipscale; d_sdivzstepu = p_saxis[0] * t; d_tdivzstepu = p_taxis[0] * t; t = yscaleinv * mipscale; d_sdivzstepv = -p_saxis[1] * t; d_tdivzstepv = -p_taxis[1] * t; d_sdivzorigin = p_saxis[2] * mipscale - xcenter * d_sdivzstepu - ycenter * d_sdivzstepv; d_tdivzorigin = p_taxis[2] * mipscale - xcenter * d_tdivzstepu - 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; // // -1 (-epsilon) so we never wander off the edge of the texture // bbextents = ((pface->extents[0] << 16) >> miplevel) - 1; bbextentt = ((pface->extents[1] << 16) >> miplevel) - 1; } /* ============== D_DrawSurfaces ============== */ void D_DrawSurfaces (void) { surf_t *s; msurface_t *pface; surfcache_t *pcurrentcache; vec3_t world_transformed_modelorg; vec3_t local_modelorg; currententity = &cl_entities[0]; TransformVector (modelorg, transformed_modelorg); VectorCopy (transformed_modelorg, world_transformed_modelorg); // TODO: could preset a lot of this at mode set time if (r_drawflat.value) { for (s = &surfaces[1] ; s<surface_p ; s++) { if (!s->spans) continue; d_zistepu = s->d_zistepu; d_zistepv = s->d_zistepv; d_ziorigin = s->d_ziorigin; D_DrawSolidSurface (s, (int)s->data & 0xFF); D_DrawZSpans (s->spans); } } else { for (s = &surfaces[1] ; s<surface_p ; s++) { if (!s->spans) continue; r_drawnpolycount++; d_zistepu = s->d_zistepu; d_zistepv = s->d_zistepv; d_ziorigin = s->d_ziorigin; 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 d_zistepu = 0; d_zistepv = 0; d_ziorigin = -0.9; D_DrawSolidSurface (s, (int)r_clearcolor.value & 0xFF); D_DrawZSpans (s->spans); } else if (s->flags & SURF_DRAWTURB) { pface = s->data; miplevel = 0; cacheblock = (pixel_t *) ((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 () 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 } D_CalcGradients (pface); 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 // currententity = &cl_entities[0]; VectorCopy (world_transformed_modelorg, transformed_modelorg); VectorCopy (base_vpn, vpn); VectorCopy (base_vup, vup); VectorCopy (base_vright, vright); 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); TransformVector (local_modelorg, transformed_modelorg); 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); // FIXME: make this passed in to D_CacheSurface pcurrentcache = D_CacheSurface (pface, miplevel); cacheblock = (pixel_t *)pcurrentcache->data; cachewidth = pcurrentcache->width; D_CalcGradients (pface); (*d_drawspans) (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 // currententity = &cl_entities[0]; VectorCopy (world_transformed_modelorg, transformed_modelorg); VectorCopy (base_vpn, vpn); VectorCopy (base_vup, vup); VectorCopy (base_vright, vright); VectorCopy (base_modelorg, modelorg); R_TransformFrustum (); } } } } }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // in_null.c -- for systems without a mouse #include "quakedef.h" void IN_Init (void) { } void IN_Shutdown (void) { } void IN_Commands (void) { } void IN_Move (usercmd_t *cmd) { }
C++
/* * snd_android.c * Android-specific sound interface * */ #include "quakedef.h" #include <pthread.h> #include <time.h> #include <math.h> #include <stdlib.h> #include <utils/Log.h> #include <media/AudioTrack.h> using namespace android; static AudioTrack gAudioTrack; // Written by the callback function running in an audio thread. // index in bytes of where we last read. static volatile size_t gDMAByteIndex; // Written by main thread static size_t gAvailableBytes; static bool gSoundMixingStarted; // The condition is "new data is now available" static pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; /* ================== SNDDMA_Init Try to find a sound device to mix for. Returns false if nothing is found. ================== */ const size_t SAMPLE_RATE = 11025; const size_t BYTES_PER_SAMPLE = 2; const size_t CHANNEL_COUNT = 2; const size_t BITS_PER_SAMPLE = 8 * BYTES_PER_SAMPLE; const size_t TOTAL_BUFFER_SIZE = 16 * 1024; static size_t min(size_t a, size_t b) { return a < b ? a : b; } static size_t mod(size_t value, size_t mod) { return value % mod; } static size_t next(size_t value, size_t mod) { value = value + 1; if ( value >= mod ) { value = 0; } return value; } static size_t prev(size_t value, size_t mod) { if ( value <= 0 ) { value = mod; } return value - 1; } static bool enableSound() { if (COM_CheckParm("-nosound")) return false; return true; } // Choose one: // #define GENERATE_SINE_WAVE #define NORMAL_SOUND #ifdef GENERATE_SINE_WAVE static const float p = 2 * M_PI * 440.0f / SAMPLE_RATE; static float left = 0.0f; static float right = 0.0f; static float sinef(float x) { const float A = 1.0f / (2.0f*M_PI); const float B = -16.0f; const float C = 8.0f; // scale angle for easy argument reduction x *= A; if (fabsf(x) >= 0.5f) { // Argument reduction x = x - ceilf(x + 0.5f) + 1.0f; } const float y = B*x*fabsf(x) + C*x; return 0.2215f * (y*fabsf(y) - y) + y; } static void AndroidQuakeSoundCallback(int event, void* user, void *info) { if (event != AudioTrack::EVENT_MORE_DATA) return; const AudioTrack::Buffer *buffer = static_cast<const AudioTrack::Buffer *>(info); size_t bytesToCopy = buffer->size; size_t framesToCopy = buffer->size / (BYTES_PER_SAMPLE * CHANNEL_COUNT); short* pData = buffer->i16; for(size_t frame = 0; frame < framesToCopy; frame++) { short leftSample = (short) (32767.0f * sinef(left)); left += p; if (left > 2*M_PI) { left -= 2*M_PI; } pData[frame * CHANNEL_COUNT] = leftSample; short rightSample = (short) (32767.0f * sinef(right)); right += 2 * p; if (right > 2*M_PI) { right -= 2*M_PI; } pData[1 + frame * CHANNEL_COUNT] = rightSample; } gDMAByteIndex = mod(gDMAByteIndex + bytesToCopy, TOTAL_BUFFER_SIZE); asm volatile ("":::"memory"); } #endif #ifdef NORMAL_SOUND static bool gWaitingForMixerToRestart; // Assumes the mutex is acquired. // Waits until audio is available or a time period has elapsed. static bool shouldMixSilence() { if (!gSoundMixingStarted) { return true; } while (gAvailableBytes == 0) { if (gWaitingForMixerToRestart) { return true; } timeval tp; if (gettimeofday(&tp, NULL)) { return true; } const long WAIT_NS = 40 * 1000 * 1000; const long NS_PER_SECOND = 1000 * 1000 * 1000; timespec ts; ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000 + WAIT_NS; if (ts.tv_nsec >= NS_PER_SECOND) { ts.tv_nsec -= NS_PER_SECOND; ts.tv_sec += 1; } if (ETIMEDOUT == pthread_cond_timedwait( &condition_cond, &condition_mutex, &ts)) { gWaitingForMixerToRestart = true; return true; } } gWaitingForMixerToRestart = false; return false; } static void AndroidQuakeSoundCallback(int event, void* user, void *info) { if (event != AudioTrack::EVENT_MORE_DATA) return; const AudioTrack::Buffer *buffer = static_cast<const AudioTrack::Buffer *>(info); size_t dmaByteIndex = gDMAByteIndex; size_t size = buffer->size; unsigned char* pDestBuffer = (unsigned char*) buffer->raw; if (size == 0) return; if ( ! shm ) { memset(pDestBuffer, 0, size); return; } const unsigned char* pSrcBuffer = shm->buffer; while(size > 0) { pthread_mutex_lock( &condition_mutex ); if (shouldMixSilence()) { memset(pDestBuffer, 0, size); pthread_mutex_unlock( &condition_mutex ); return; } size_t chunkSize = min(gAvailableBytes, min(TOTAL_BUFFER_SIZE-dmaByteIndex, size)); gAvailableBytes -= chunkSize; pthread_mutex_unlock( &condition_mutex ); memcpy(pDestBuffer, pSrcBuffer + dmaByteIndex, chunkSize); size -= chunkSize; pDestBuffer += chunkSize; dmaByteIndex += chunkSize; if (dmaByteIndex >= TOTAL_BUFFER_SIZE) { dmaByteIndex = 0; } } gDMAByteIndex = dmaByteIndex; asm volatile ("":::"memory"); } #endif qboolean SNDDMA_Init(void) { if ( ! enableSound() ) { return false; } gDMAByteIndex = 0; // Initialize the AudioTrack. status_t result = gAudioTrack.set( AudioSystem::DEFAULT, // stream type SAMPLE_RATE, // sample rate BITS_PER_SAMPLE == 16 ? AudioSystem::PCM_16_BIT : AudioSystem::PCM_8_BIT, // format (8 or 16) (CHANNEL_COUNT > 1) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO, // channel mask 0, // default buffer size 0, // flags AndroidQuakeSoundCallback, // callback 0, // user 0); // default notification size LOGI("AudioTrack status = %d (%s)\n", result, result == NO_ERROR ? "success" : "error"); if ( result == NO_ERROR ) { LOGI("AudioTrack latency = %u ms\n", gAudioTrack.latency()); LOGI("AudioTrack format = %u bits\n", gAudioTrack.format() == AudioSystem::PCM_16_BIT ? 16 : 8); LOGI("AudioTrack sample rate = %u Hz\n", gAudioTrack.getSampleRate()); LOGI("AudioTrack frame count = %d\n", int(gAudioTrack.frameCount())); LOGI("AudioTrack channel count = %d\n", gAudioTrack.channelCount()); // Initialize Quake's idea of a DMA buffer. shm = &sn; memset((void*)&sn, 0, sizeof(sn)); shm->splitbuffer = false; // Not used. shm->samplebits = gAudioTrack.format() == AudioSystem::PCM_16_BIT ? 16 : 8; shm->speed = gAudioTrack.getSampleRate(); shm->channels = gAudioTrack.channelCount(); shm->samples = TOTAL_BUFFER_SIZE / BYTES_PER_SAMPLE; shm->samplepos = 0; // Not used. shm->buffer = (unsigned char*) Hunk_AllocName(TOTAL_BUFFER_SIZE, (char*) "shmbuf"); shm->submission_chunk = 1; // Not used. shm->soundalive = true; if ( (shm->samples & 0x1ff) != 0 ) { LOGE("SNDDDMA_Init: samples must be power of two."); return false; } if ( shm->buffer == 0 ) { LOGE("SNDDDMA_Init: Could not allocate sound buffer."); return false; } gAudioTrack.setVolume(1.0f, 1.0f); gAudioTrack.start(); } return result == NO_ERROR; } /* ============== SNDDMA_GetDMAPos return the current sample position (in mono samples read) 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 dmaPos = gDMAByteIndex / BYTES_PER_SAMPLE; asm volatile ("":::"memory"); return dmaPos; } /* =============== SNDDMA_ReportWrite Report valid data being written into the DMA buffer by the sound mixing code. This is an Android specific API. ================ */ void SNDDMA_ReportWrite(size_t lengthBytes) { pthread_mutex_lock( &condition_mutex ); gSoundMixingStarted = true; if (gAvailableBytes == 0) { pthread_cond_signal( &condition_cond ); } gAvailableBytes += lengthBytes; pthread_mutex_unlock( &condition_mutex ); } /* ============== SNDDMA_Submit Send sound to device if buffer isn't really the dma buffer =============== */ void SNDDMA_Submit(void) { } /* ============== SNDDMA_Shutdown Reset the sound device for exiting =============== */ void SNDDMA_Shutdown(void) { gAudioTrack.stop(); }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_vars.c: global refresh variables #if !id386 #include "quakedef.h" // all global and static refresh variables are collected in a contiguous block // to avoid cache conflicts. //------------------------------------------------------- // global refresh variables //------------------------------------------------------- // 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; 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 // !id386
C++
/* Copyright (C) 2007 The Android Open Source Project */ #include "quakedef.h" unsigned short d_8to16table[256]; unsigned d_8to24table[256]; #ifdef SUPPORT_8BIT_MIPMAPGENERATION unsigned char d_15to8table[65536]; #endif cvar_t mouse_button_commands[3] = { CVAR2("mouse1","+attack"), CVAR2("mouse2","+strafe"), CVAR2("mouse3","+forward"), }; static const int MOUSE_LEFTBUTTON = 1; static const int MOUSE_MIDDLEBUTTON = 2; static const int MOUSE_RIGHTBUTTON = 4; bool mouse_tap; float mouse_x, mouse_y; float old_mouse_x, old_mouse_y; int mx, my; bool mouse_buttonstate; bool mouse_oldbuttonstate; cvar_t m_filter = CVAR2("m_filter","1"); int scr_width, scr_height; cvar_t _windowed_mouse = CVAR3("_windowed_mouse","0", true); /*-----------------------------------------------------------------------*/ //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_extension_number = 1; float gldepthmin, gldepthmax; cvar_t gl_ztrick = CVAR2("gl_ztrick","0"); const char *gl_vendor; const char *gl_renderer; const char *gl_version; const char *gl_extensions; qboolean is8bit = false; qboolean isPermedia = false; qboolean gl_mtexable = false; /*-----------------------------------------------------------------------*/ 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 VID_Shutdown(void) { } void VID_ShiftPalette(unsigned char *p) { // VID_SetPalette(p); } void VID_SetPalette (unsigned char *palette) { byte *pal; unsigned r,g,b; unsigned v; int r1,g1,b1; int k; unsigned short i; unsigned *table; FILE *f; char s[255]; int dist, bestdist; static qboolean palflag = false; PMPBEGIN(("VID_SetPalette")); // // 8 8 8 encoding // Con_Printf("Converting 8to24\n"); pal = palette; table = d_8to24table; 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); *table++ = v; } d_8to24table[255] &= 0xffffff; // 255 is transparent #ifdef SUPPORT_8BIT_MIPMAPGENERATION // JACK: 3D distance calcs - k is last closest, l is the distance. // FIXME: Precalculate this and cache to disk. if (palflag) return; palflag = true; COM_FOpenFile("glquake/15to8.pal", &f); if (f) { fread(d_15to8table, 1<<15, 1, f); fclose(f); } else { PMPBEGIN(("Creating 15to8 palette")); for (i=0; i < (1<<15); i++) { /* Maps 0000.0000.0000.0000 0000.0000.0001.1111 = Red = 0x001F 0000.0011.1110.0000 = Green = 0x03E0 0111.1100.0000.0000 = Blue = 0x7C00 */ r = ((i & 0x1F) << 3)+4; g = ((i & 0x03E0) >> (5-3)) +4; b = ((i & 0x7C00) >> (10-3))+4; pal = (unsigned char *)d_8to24table; for (v=0,k=0,bestdist=0x7FFFFFFF; v<256; v++,pal+=4) { r1 = (int)r - (int)pal[0]; g1 = (int)g - (int)pal[1]; b1 = (int)b - (int)pal[2]; dist = ((r1*r1)+(g1*g1)+(b1*b1)); if (dist < bestdist) { k=v; bestdist = dist; } } d_15to8table[i]=k; } PMPEND(("Creating 15to8 palette")); sprintf(s, "%s/glquake", com_gamedir); Sys_mkdir (s); sprintf(s, "%s/glquake/15to8.pal", com_gamedir); if ((f = fopen(s, "wb")) != NULL) { fwrite(d_15to8table, 1<<15, 1, f); fclose(f); } else { Con_Printf("Could not write %s\n", s); } } #endif // SUPPORT_8BIT_MIPMAPGENERATION PMPEND(("VID_SetPalette")); } /* =============== GL_Init =============== */ void GL_Init (void) { gl_vendor = (char*) glGetString (GL_VENDOR); Con_Printf ("GL_VENDOR: %s\n", gl_vendor); GLCHECK("glGetString"); gl_renderer = (char*) glGetString (GL_RENDERER); Con_Printf ("GL_RENDERER: %s\n", gl_renderer); GLCHECK("glGetString"); gl_version = (char*) glGetString (GL_VERSION); Con_Printf ("GL_VERSION: %s\n", gl_version); GLCHECK("glGetString"); gl_extensions = (char*) glGetString (GL_EXTENSIONS); Con_Printf ("GL_EXTENSIONS: %s\n", gl_extensions); GLCHECK("glGetString"); // Con_Printf ("%s %s\n", gl_renderer, gl_version); // Enable/disable multitexture: gl_mtexable = true; glClearColor (1,0,0,0); glCullFace(GL_FRONT); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.666); #ifdef USE_OPENGLES #else glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); #endif glShadeModel(GL_FLAT); glDisable(GL_DITHER); // perspective correction don't work well currently glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); 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_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 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_REPLACE); #ifdef USE_OPENGLES glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); #endif } /* ================= GL_BeginRendering ================= */ void GL_BeginRendering (int *x, int *y, int *width, int *height) { extern cvar_t gl_clear; *x = *y = 0; *width = scr_width; *height = scr_height; // if (!wglMakeCurrent( maindc, baseRC )) // Sys_Error ("wglMakeCurrent failed"); // glViewport (*x, *y, *width, *height); } void GL_EndRendering (void) { //glFlush(); // !!! Swap buffers. } void Init_KBD(void) { } // This function controls whether or not 8-bit paletted textures are used: qboolean VID_Is8bit(void) { return 0; } static void Check_Gamma (unsigned char *pal) { float vid_gamma; float f, inf; unsigned char palette[768]; int i; if ((i = COM_CheckParm("-gamma")) == 0) { vid_gamma = 0.5; // brighten up game. } else vid_gamma = Q_atof(com_argv[i+1]); if(vid_gamma != 1) { for (i=0 ; i<768 ; i++) { f = pow ( (pal[i]+1)/256.0 , vid_gamma ); inf = f*255 + 0.5; if (inf < 0) inf = 0; if (inf > 255) inf = 255; palette[i] = (unsigned char) inf; } } memcpy (pal, palette, sizeof(palette)); } void VID_Init(unsigned char *palette) { int i; GLint attribs[32]; char gldir[MAX_OSPATH]; int width = scr_width, height = scr_height; S_Init(); Init_KBD(); Cvar_RegisterVariable (&gl_ztrick); vid.maxwarpwidth = scr_width; vid.maxwarpheight = height; vid.colormap = host_colormap; vid.fullbright = 0xffff; vid.aspect = (float) scr_width / (float) scr_height; vid.numpages = 2; vid.rowbytes = 2 * scr_width; vid.width = scr_width; vid.height = scr_height; vid.conwidth = scr_width; vid.conheight = scr_height; // interpret command-line params // set vid parameters GL_Init(); sprintf (gldir, "%s/glquake", com_gamedir); Sys_mkdir (gldir); Check_Gamma(palette); VID_SetPalette(palette); Con_SafePrintf ("Video mode %dx%d initialized.\n", width, height); vid.recalc_refdef = 1; // force a surface cache flush } // Android Key event codes. Some of these are // only generated from the simulator. // Not all Android devices can generate all codes. byte scantokey[] = { '$', K_ESCAPE, '$', '$', K_ESCAPE, '$', '$', '0', // 0.. 7 '1', '2', '3', '4', '5', '6', '7', '8', // 8..15 '9', '$', '$', K_UPARROW, K_DOWNARROW, K_LEFTARROW, K_RIGHTARROW, K_ENTER, // 16..23 '$', '$', '$', '$', '$', 'a', 'b', 'c', // 24..31 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', // 32..39 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', // 40..47 't', 'u', 'v', 'w', 'x', 'y', 'z', ',', // 48..55 '.', K_CTRL, K_SHIFT, K_TAB, ' ', '$', '$', '$', // 56..63 '$', '$', K_ENTER, K_BACKSPACE, '`', '-', '=', '[', // 64..71 ']', '\\', ';', '\'', '/', '@', '#', '$', // 72..79 '$', '$', K_ESCAPE, '$' // 80..83 }; byte scantokeyAlt[] = { 0, 0, 0, 0, 0, 0, 0, 0, // 0.. 7 0, 0, 0, 0, 0, 0, 0, 0, // 8..15 0, 0, 0, 0, 0, 0, 0, 0, // 16..23 0, 0, 0, 0, 0, '%', '=', '8', // 24..31 '5', '2', '6', '-', '[', '$', ']', '"', // 32..39 '\'', '>', '<', '(', ')', '*', '3', '4', // 40..47 '+', '&', '9', '1', '7', '!', '#', ';', // 48..55 ':', 0, 0, 0, K_TAB, 0, 0, 0, // 56..63 0, 0, 0, 0, 0, 0, 0, 0, // 64..71 0, 0, '?', '0', 0, 0, 0, 0, // 72..79 0, 0, K_ESCAPE, 0 // 80..83 }; #if 0 byte scantokeyCap[] = { 0, 0, 0, 0, 0, 0, 0, 0, // 0.. 7 0, 0, 0, 0, 0, 0, 0, 0, // 8..15 0, 0, 0, 0, 0, 0, 0, 0, // 16..23 0, 0, 0, 0, 0, 'A', 'B', 'C', // 24..31 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', // 32..39 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', // 40..47 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0, // 48..55 0, 0, 0, 0, 0, 0, 0, 0, // 56..63 0, 0, 0, 0, 0, 0, 0, 0, // 64..71 0, 0, 0, 0, 0, 0, 0, 0, // 72..79 0, 0, K_ESCAPE, 0 // 80..83 }; #endif byte scantokeySym[] = { 0, 0, 0, 0, 0, 0, 0, 0, // 0.. 7 0, 0, 0, 0, 0, 0, 0, 0, // 8..15 0, 0, 0, 0, 0, 0, 0, 0, // 16..23 0, 0, 0, 0, 0, 0, 0, K_F8, // 24..31 K_F5, K_F2, K_F6, '_', 0, 0, 0, 0, // 32..39 0, 0, 0, 0, 0, 0, K_F3, K_F4, // 40..47 K_F11, 0, K_F9, K_F1, K_F7, K_F12, K_PAUSE, 0, // 48..55 0, 0, 0, 0, 0, 0, 0, 0, // 56..63 0, 0, 0, 0, 0, 0, 0, 0, // 64..71 0, 0, '`', K_F10, 0, 0, 0, 0, // 72..79 0, 0, K_ESCAPE, 0 // 80..83 }; #define ALT_KEY_VALUE 57 // #define CAPS_KEY_VALUE 58 #define SYM_KEY_VALUE 61 byte modifierKeyInEffect; qboolean symKeyDown; byte symKeyCode; // Called from stand-alone main() function to process an event. // Return non-zero if the event is handled. int AndroidEvent(int type, int value) { if(value >= 0 && value < (int) sizeof(scantokey)) { byte key; qboolean isPress = type != 0; qboolean isModifier = value == ALT_KEY_VALUE || value == SYM_KEY_VALUE; if(isModifier) { if(isPress) { if(modifierKeyInEffect == value) { // Press modifier twice to cancel modifier modifierKeyInEffect = 0; } else { // Most recent modifier key wins modifierKeyInEffect = value; } } return 1; } else { switch(modifierKeyInEffect) { default: key = scantokey[value]; break; case ALT_KEY_VALUE: key = scantokeyAlt[value]; break; // case CAP_KEY_VALUE: key = scantokeyCap[value]; break; case SYM_KEY_VALUE: key = scantokeySym[value]; break; } if(!key) { key = scantokey[value]; } // Hack: Remap @ and / to K_CTRL in game mode if(key_dest == key_game && ! modifierKeyInEffect && (key == '@' || key == '/')) { key = K_CTRL; } if(!isPress) { modifierKeyInEffect = 0; } } Key_Event(key, type); // PMPLOG(("type: %d, value: %d -> %d '%c'\n", type, value, key, key)); return 1; } else { PMPWARNING(("unexpected event type: %d, value: %d\n", type, value)); } return 0; } // Called from Java to process an event. // Return non-zero if the event is handled. int AndroidEvent2(int type, int value) { Key_Event(value, type); return 0; } static const int MOTION_DOWN = 0; static const int MOTION_UP = 1; static const int MOTION_MOVE = 2; static const int MOTION_CANCEL = 3; class GestureDetector { private: bool mIsScroll; bool mIsTap; bool mIsDoubleTap; float mScrollX; float mScrollY; static const unsigned long long TAP_TIME_MS = 200; static const unsigned long long DOUBLE_TAP_TIME_MS = 400; static const int TAP_REGION_MANHATTAN_DISTANCE = 10; bool mAlwaysInTapRegion; float mDownX; float mDownY; unsigned long long mDownTime; unsigned long long mPreviousDownTime; /** * Position of the last motion event. */ float mLastMotionY; float mLastMotionX; public: /** * Analyze a motion event. Call this once for each motion event * that is received by a view. * @param ev the motion event to analyze. */ void analyze(unsigned long long eventTime, int action, float x, float y, float pressure, float size, int deviceId) { mIsScroll = false; mIsTap = false; mIsDoubleTap = false; switch (action) { case MOTION_DOWN: printf("Down"); // Remember where the motion event started mLastMotionX = x; mLastMotionY = y; mDownX = x; mDownY = y; mPreviousDownTime = mDownTime; mDownTime = eventTime; mAlwaysInTapRegion = true; break; case MOTION_MOVE: { mIsScroll = true; mScrollX = mLastMotionX - x; mScrollY = mLastMotionY - y; mLastMotionX = x; mLastMotionY = y; int manhattanTapDistance = (int) (absf(x - mDownX) + absf(y - mDownY)); if (manhattanTapDistance > TAP_REGION_MANHATTAN_DISTANCE) { mAlwaysInTapRegion = false; } } break; case MOTION_UP: { unsigned long long doubleTapDelta = eventTime - mPreviousDownTime; unsigned long long singleTapDelta = eventTime - mDownTime; if (mAlwaysInTapRegion) { if (doubleTapDelta < DOUBLE_TAP_TIME_MS) { mIsDoubleTap = true; } else if (singleTapDelta < TAP_TIME_MS) { mIsTap = true; } } } break; } } /** * @return true if the current motion event is a scroll * event. */ bool isScroll() { return mIsScroll; } /** * This value is only defined if {@link #isScroll} is true. * @return the X position of the current scroll event. * event. */ float scrollX() { return mScrollX; } /** * This value is only defined if {@link #isScroll} is true. * @return the Y position of the current scroll event. * event. */ float scrollY() { return mScrollY; } /** * @return true if the current motion event is a single-tap * event. */ bool isTap() { return mIsTap; } /** * This value is only defined if either {@link #isTap} or * {@link #isDoubleTap} is true. * @return the X position of the current tap event. * event. */ float tapX() { return mDownX; } /** * This value is only defined if either {@link #isTap} or * {@link #isDoubleTap} is true. * @return the Y position of the current tap event. * event. */ float tapY() { return mDownY; } /** * @return true if the current motion event is a double-tap * event. */ bool isDoubleTap() { return mIsDoubleTap; } private: inline float absf(float a) { return a >= 0.0f ? a : -a; } }; GestureDetector gGestureDetector; int AndroidMotionEvent(unsigned long long eventTime, int action, float x, float y, float pressure, float size, int deviceId) { gGestureDetector.analyze(eventTime, action, x, y, pressure, size, deviceId); if (gGestureDetector.isTap()) { mouse_tap = true; } else if (gGestureDetector.isScroll()) { mx += (int) gGestureDetector.scrollX(); my += (int) gGestureDetector.scrollY(); } return true; } int AndroidTrackballEvent(unsigned long long eventTime, int action, float x, float y) { switch (action ) { case MOTION_DOWN: mouse_buttonstate = true; break; case MOTION_UP: mouse_buttonstate = false; break; case MOTION_MOVE: mx += (int) (20.0f * x); my += (int) (20.0f * y); break; } return true; } void Sys_SendKeyEvents(void) { // Used to poll keyboards on systems that need to poll keyboards. } void Force_CenterView_f (void) { cl.viewangles[PITCH] = 0; } void IN_Init(void) { Cvar_RegisterVariable (&mouse_button_commands[0]); Cvar_RegisterVariable (&mouse_button_commands[1]); Cvar_RegisterVariable (&mouse_button_commands[2]); Cmd_AddCommand ("force_centerview", Force_CenterView_f); } void IN_Shutdown(void) { } /* =========== IN_Commands =========== */ void IN_Commands (void) { // perform button actions if (mouse_tap) { Key_Event (K_MOUSE1, true); Key_Event (K_MOUSE1, false); mouse_tap = false; } if (mouse_buttonstate != mouse_oldbuttonstate) { Key_Event (K_MOUSE1, mouse_buttonstate ? true : false); mouse_oldbuttonstate = mouse_buttonstate; } } /* =========== IN_Move =========== */ void IN_MouseMove (usercmd_t *cmd) { #if 0 if (m_filter.value) { mouse_x = (mx + old_mouse_x) * 0.5; mouse_y = (my + old_mouse_y) * 0.5; } else #endif { mouse_x = mx; mouse_y = my; } old_mouse_x = mx; old_mouse_y = my; mx = my = 0; // clear for next update mouse_x *= 5.0f * sensitivity.value; mouse_y *= 5.0f * sensitivity.value; // add mouse X/Y movement to cmd 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; if (in_mlook.state & 1) V_StopPitchDrift (); if ( (in_mlook.state & 1) && !(in_strafe.state & 1)) { cl.viewangles[PITCH] += m_pitch.value * mouse_y; if (cl.viewangles[PITCH] > 80) cl.viewangles[PITCH] = 80; if (cl.viewangles[PITCH] < -70) cl.viewangles[PITCH] = -70; } else { if ((in_strafe.state & 1) && noclip_anglehack) cmd->upmove -= m_forward.value * mouse_y; else cmd->forwardmove -= m_forward.value * mouse_y; } } void IN_Move (usercmd_t *cmd) { IN_MouseMove(cmd); }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // view.c -- player eye positioning #include "quakedef.h" #include "r_local.h" /* The view is allowed to move slightly from it's true position for bobbing, but if it exceeds 8 pixels linear distance (spherical, not box), the list of entities sent from the server may not include everything in the pvs, especially when crossing a water boudnary. */ cvar_t lcd_x = CVAR2("lcd_x","0"); cvar_t lcd_yaw = CVAR2("lcd_yaw","0"); cvar_t scr_ofsx = CVAR3("scr_ofsx","0", false); cvar_t scr_ofsy = CVAR3("scr_ofsy","0", false); cvar_t scr_ofsz = CVAR3("scr_ofsz","0", false); cvar_t cl_rollspeed = CVAR2("cl_rollspeed", "200"); cvar_t cl_rollangle = CVAR2("cl_rollangle", "2.0"); cvar_t cl_bob = CVAR3("cl_bob","0.02", false); cvar_t cl_bobcycle = CVAR3("cl_bobcycle","0.6", false); cvar_t cl_bobup = CVAR3("cl_bobup","0.5", false); cvar_t v_kicktime = CVAR3("v_kicktime", "0.5", false); cvar_t v_kickroll = CVAR3("v_kickroll", "0.6", false); cvar_t v_kickpitch = CVAR3("v_kickpitch", "0.6", false); cvar_t v_iyaw_cycle = CVAR3("v_iyaw_cycle", "2", false); cvar_t v_iroll_cycle = CVAR3("v_iroll_cycle", "0.5", false); cvar_t v_ipitch_cycle = CVAR3("v_ipitch_cycle", "1", false); cvar_t v_iyaw_level = CVAR3("v_iyaw_level", "0.3", false); cvar_t v_iroll_level = CVAR3("v_iroll_level", "0.1", false); cvar_t v_ipitch_level = CVAR3("v_ipitch_level", "0.3", false); cvar_t v_idlescale = CVAR3("v_idlescale", "0", false); cvar_t crosshair = CVAR3("crosshair", "0", true); cvar_t cl_crossx = CVAR3("cl_crossx", "0", false); cvar_t cl_crossy = CVAR3("cl_crossy", "0", false); cvar_t gl_cshiftpercent = CVAR3("gl_cshiftpercent", "100", false); float v_dmg_time, v_dmg_roll, v_dmg_pitch; extern int in_forward, in_forward2, in_back; /* =============== V_CalcRoll Used by view and sv_user =============== */ vec3_t forward, right, up; float V_CalcRoll (vec3_t angles, vec3_t velocity) { float sign; float side; float value; AngleVectors (angles, forward, right, up); side = DotProduct (velocity, right); sign = side < 0 ? -1 : 1; side = fabs(side); value = cl_rollangle.value; // if (cl.inwater) // value *= 6; if (side < cl_rollspeed.value) side = side * value / cl_rollspeed.value; else side = value; return side*sign; } /* =============== V_CalcBob =============== */ float V_CalcBob (void) { float bob; float cycle; cycle = cl.time - (int)(cl.time/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); // bob is proportional to velocity in the xy plane // (don't count Z, or jumping messes it up) bob = sqrt(cl.velocity[0]*cl.velocity[0] + cl.velocity[1]*cl.velocity[1]) * cl_bob.value; //Con_Printf ("speed: %5.1f\n", Length(cl.velocity)); 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 = CVAR3("v_centermove", "0.15", false); cvar_t v_centerspeed = CVAR2("v_centerspeed","500"); void V_StartPitchDrift (void) { #if 1 if (cl.laststop == cl.time) { return; // something else is keeping it from drifting } #endif if (cl.nodrift || !cl.pitchvel) { cl.pitchvel = v_centerspeed.value; cl.nodrift = false; cl.driftmove = 0; } } void V_StopPitchDrift (void) { cl.laststop = cl.time; cl.nodrift = true; cl.pitchvel = 0; } /* =============== V_DriftPitch Moves the client pitch angle towards cl.idealpitch sent by the server. If the user is adjusting pitch manually, either with lookup/lookdown, mlook and mouse, or klook and keyboard, pitch drifting is constantly stopped. Drifting is enabled when the center view key is hit, mlook is released and lookspring is non 0, or when =============== */ void V_DriftPitch (void) { float delta, move; if (noclip_anglehack || !cl.onground || cls.demoplayback ) { cl.driftmove = 0; cl.pitchvel = 0; return; } // don't count small mouse motion if (cl.nodrift) { if ( fabs(cl.cmd.forwardmove) < cl_forwardspeed.value) cl.driftmove = 0; else cl.driftmove += host_frametime; if ( cl.driftmove > v_centermove.value) { V_StartPitchDrift (); } return; } delta = cl.idealpitch - cl.viewangles[PITCH]; 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) { cl.pitchvel = 0; move = delta; } cl.viewangles[PITCH] += move; } else if (delta < 0) { if (move > -delta) { cl.pitchvel = 0; move = -delta; } cl.viewangles[PITCH] -= move; } } /* ============================================================================== PALETTE FLASHES ============================================================================== */ 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 v_gamma = CVAR3("gamma", "1", true); byte gammatable[256]; // palette is sent through this #ifdef GLQUAKE byte ramps[3][256]; float v_blend[4]; // rgba 0.0 - 1.0 #endif // GLQUAKE void BuildGammaTable (float g) { int i, inf; if (g == 1.0) { for (i=0 ; i<256 ; i++) gammatable[i] = i; return; } for (i=0 ; i<256 ; i++) { inf = (int) (255 * pow ( (i+0.5)/255.5 , g ) + 0.5); if (inf < 0) inf = 0; if (inf > 255) inf = 255; gammatable[i] = inf; } } /* ================= V_CheckGamma ================= */ qboolean V_CheckGamma (void) { static float oldgammavalue; if (v_gamma.value == oldgammavalue) return false; oldgammavalue = v_gamma.value; BuildGammaTable (v_gamma.value); vid.recalc_refdef = 1; // force a surface cache flush return true; } /* =============== V_ParseDamage =============== */ void V_ParseDamage (void) { int armor, blood; vec3_t from; int i; vec3_t forward, right, up; entity_t *ent; float side; float count; armor = MSG_ReadByte (); blood = MSG_ReadByte (); for (i=0 ; i<3 ; i++) from[i] = MSG_ReadCoord (); 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.cshifts[CSHIFT_DAMAGE].percent += (int) (3*count); if (cl.cshifts[CSHIFT_DAMAGE].percent < 0) cl.cshifts[CSHIFT_DAMAGE].percent = 0; if (cl.cshifts[CSHIFT_DAMAGE].percent > 150) cl.cshifts[CSHIFT_DAMAGE].percent = 150; if (armor > blood) { cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 200; cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 100; cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 100; } else if (armor) { cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 220; cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 50; cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 50; } else { cl.cshifts[CSHIFT_DAMAGE].destcolor[0] = 255; cl.cshifts[CSHIFT_DAMAGE].destcolor[1] = 0; cl.cshifts[CSHIFT_DAMAGE].destcolor[2] = 0; } // // calculate view angle kicks // ent = &cl_entities[cl.viewentity]; VectorSubtract (from, ent->origin, from); VectorNormalize (from); AngleVectors (ent->angles, forward, right, up); side = DotProduct (from, right); v_dmg_roll = count*side*v_kickroll.value; side = DotProduct (from, forward); v_dmg_pitch = count*side*v_kickpitch.value; v_dmg_time = v_kicktime.value; } /* ================== V_cshift_f ================== */ 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)); } /* ================== V_BonusFlash_f When you run over an item, the server sends this command ================== */ void V_BonusFlash_f (void) { cl.cshifts[CSHIFT_BONUS].destcolor[0] = 215; cl.cshifts[CSHIFT_BONUS].destcolor[1] = 186; cl.cshifts[CSHIFT_BONUS].destcolor[2] = 69; cl.cshifts[CSHIFT_BONUS].percent = 50; } /* ============= V_SetContentsColor Underwater, lava, etc each has a color shift ============= */ void V_SetContentsColor (int contents) { switch (contents) { case CONTENTS_EMPTY: case CONTENTS_SOLID: cl.cshifts[CSHIFT_CONTENTS] = cshift_empty; break; case CONTENTS_LAVA: cl.cshifts[CSHIFT_CONTENTS] = cshift_lava; break; case CONTENTS_SLIME: cl.cshifts[CSHIFT_CONTENTS] = cshift_slime; break; default: cl.cshifts[CSHIFT_CONTENTS] = cshift_water; } } /* ============= V_CalcPowerupCshift ============= */ void V_CalcPowerupCshift (void) { if (cl.items & IT_QUAD) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 255; cl.cshifts[CSHIFT_POWERUP].percent = 30; } else if (cl.items & IT_SUIT) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 0; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; cl.cshifts[CSHIFT_POWERUP].percent = 20; } else if (cl.items & IT_INVISIBILITY) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 100; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 100; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 100; cl.cshifts[CSHIFT_POWERUP].percent = 100; } else if (cl.items & IT_INVULNERABILITY) { cl.cshifts[CSHIFT_POWERUP].destcolor[0] = 255; cl.cshifts[CSHIFT_POWERUP].destcolor[1] = 255; cl.cshifts[CSHIFT_POWERUP].destcolor[2] = 0; cl.cshifts[CSHIFT_POWERUP].percent = 30; } else cl.cshifts[CSHIFT_POWERUP].percent = 0; } /* ============= V_CalcBlend ============= */ #ifdef GLQUAKE void V_CalcBlend (void) { float r, g, b, a, a2; int j; r = 0; g = 0; b = 0; a = 0; for (j=0 ; j<NUM_CSHIFTS ; j++) { if (!gl_cshiftpercent.value) continue; a2 = ((cl.cshifts[j].percent * gl_cshiftpercent.value) / 100.0) / 255.0; // a2 = cl.cshifts[j].percent/255.0; if (!a2) continue; a = a + a2*(1-a); //Con_Printf ("j:%i a:%f\n", j, a); a2 = a2/a; r = r*(1-a2) + cl.cshifts[j].destcolor[0]*a2; g = g*(1-a2) + cl.cshifts[j].destcolor[1]*a2; b = b*(1-a2) + cl.cshifts[j].destcolor[2]*a2; } v_blend[0] = r/255.0; v_blend[1] = g/255.0; v_blend[2] = b/255.0; v_blend[3] = a; if (v_blend[3] > 1) v_blend[3] = 1; if (v_blend[3] < 0) v_blend[3] = 0; } #endif /* ============= V_UpdatePalette ============= */ #ifdef GLQUAKE void V_UpdatePalette (void) { int i, j; qboolean newb; byte *basepal, *newpal; byte pal[768]; float r,g,b,a; int ir, ig, ib; qboolean force; V_CalcPowerupCshift (); newb = false; for (i=0 ; i<NUM_CSHIFTS ; i++) { if (cl.cshifts[i].percent != cl.prev_cshifts[i].percent) { newb = true; cl.prev_cshifts[i].percent = cl.cshifts[i].percent; } for (j=0 ; j<3 ; j++) if (cl.cshifts[i].destcolor[j] != cl.prev_cshifts[i].destcolor[j]) { newb = true; cl.prev_cshifts[i].destcolor[j] = cl.cshifts[i].destcolor[j]; } } // drop the damage value cl.cshifts[CSHIFT_DAMAGE].percent -= (int)(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 -= (int)(host_frametime*100); if (cl.cshifts[CSHIFT_BONUS].percent <= 0) cl.cshifts[CSHIFT_BONUS].percent = 0; force = V_CheckGamma (); if (!newb && !force) return; V_CalcBlend (); a = v_blend[3]; r = 255*v_blend[0]*a; g = 255*v_blend[1]*a; b = 255*v_blend[2]*a; a = 1-a; for (i=0 ; i<256 ; i++) { ir = (int) (i*a + r); ig = (int) (i*a + g); ib = (int) (i*a + b); if (ir > 255) ir = 255; if (ig > 255) ig = 255; if (ib > 255) ib = 255; ramps[0][i] = gammatable[ir]; ramps[1][i] = gammatable[ig]; ramps[2][i] = gammatable[ib]; } basepal = host_basepal; newpal = pal; for (i=0 ; i<256 ; i++) { ir = basepal[0]; ig = basepal[1]; ib = basepal[2]; basepal += 3; newpal[0] = ramps[0][ir]; newpal[1] = ramps[1][ig]; newpal[2] = ramps[2][ib]; newpal += 3; } VID_ShiftPalette (pal); } #else // !GLQUAKE void V_UpdatePalette (void) { 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++) { if (cl.cshifts[i].percent != cl.prev_cshifts[i].percent) { new = true; cl.prev_cshifts[i].percent = cl.cshifts[i].percent; } for (j=0 ; j<3 ; j++) if (cl.cshifts[i].destcolor[j] != cl.prev_cshifts[i].destcolor[j]) { new = true; cl.prev_cshifts[i].destcolor[j] = cl.cshifts[i].destcolor[j]; } } // drop the damage value 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; if (cl.cshifts[CSHIFT_BONUS].percent <= 0) cl.cshifts[CSHIFT_BONUS].percent = 0; force = V_CheckGamma (); if (!new && !force) return; basepal = host_basepal; newpal = pal; for (i=0 ; i<256 ; i++) { r = basepal[0]; g = basepal[1]; b = basepal[2]; basepal += 3; 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]; newpal[1] = gammatable[g]; newpal[2] = gammatable[b]; newpal += 3; } VID_ShiftPalette (pal); } #endif // !GLQUAKE /* ============================================================================== VIEW RENDERING ============================================================================== */ float angledelta (float a) { a = anglemod(a); if (a > 180) a -= 360; return a; } /* ================== CalcGunAngle ================== */ 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; if (yaw > 10) yaw = 10; if (yaw < -10) yaw = -10; pitch = angledelta(-pitch - r_refdef.viewangles[PITCH]) * 0.4; if (pitch > 10) pitch = 10; if (pitch < -10) pitch = -10; move = host_frametime*20; if (yaw > oldyaw) { if (oldyaw + move < yaw) yaw = oldyaw + move; } else { if (oldyaw - move > yaw) yaw = oldyaw - move; } if (pitch > oldpitch) { if (oldpitch + move < pitch) pitch = oldpitch + move; } 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[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; } /* ============== V_BoundOffsets ============== */ void V_BoundOffsets (void) { entity_t *ent; ent = &cl_entities[cl.viewentity]; // absolutely bound refresh reletive to entity clipping hull // so the view can never be inside a solid wall if (r_refdef.vieworg[0] < ent->origin[0] - 14) r_refdef.vieworg[0] = ent->origin[0] - 14; else if (r_refdef.vieworg[0] > ent->origin[0] + 14) r_refdef.vieworg[0] = ent->origin[0] + 14; if (r_refdef.vieworg[1] < ent->origin[1] - 14) r_refdef.vieworg[1] = ent->origin[1] - 14; else if (r_refdef.vieworg[1] > ent->origin[1] + 14) r_refdef.vieworg[1] = ent->origin[1] + 14; if (r_refdef.vieworg[2] < ent->origin[2] - 22) r_refdef.vieworg[2] = ent->origin[2] - 22; else if (r_refdef.vieworg[2] > ent->origin[2] + 30) r_refdef.vieworg[2] = ent->origin[2] + 30; } /* ============== V_AddIdle Idle swaying ============== */ 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; } /* ============== V_CalcViewRoll Roll is induced by movement and damage ============== */ void V_CalcViewRoll (void) { float side; side = V_CalcRoll (cl_entities[cl.viewentity].angles, cl.velocity); 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; v_dmg_time -= host_frametime; } if (cl.stats[STAT_HEALTH] <= 0) { r_refdef.viewangles[ROLL] = 80; // dead view angle return; } } /* ================== V_CalcIntermissionRefdef ================== */ void V_CalcIntermissionRefdef (void) { entity_t *ent, *view; float old; // ent is the player model (visible when out of body) ent = &cl_entities[cl.viewentity]; // view is the weapon model (only visible from inside body) view = &cl.viewent; VectorCopy (ent->origin, r_refdef.vieworg); VectorCopy (ent->angles, r_refdef.viewangles); view->model = NULL; // allways idle in intermission old = v_idlescale.value; v_idlescale.value = 1; V_AddIdle (); v_idlescale.value = old; } /* ================== V_CalcRefdef ================== */ void V_CalcRefdef (void) { entity_t *ent, *view; int i; vec3_t forward, right, up; vec3_t angles; float bob; static float oldz = 0; V_DriftPitch (); // ent is the player model (visible when out of body) ent = &cl_entities[cl.viewentity]; // view is the weapon model (only visible from inside body) view = &cl.viewent; // transform the view offset by the model's matrix to get the offset from // model origin for the view ent->angles[YAW] = cl.viewangles[YAW]; // the model should face // the view dir ent->angles[PITCH] = -cl.viewangles[PITCH]; // the model should face // the view dir bob = V_CalcBob (); // refresh position VectorCopy (ent->origin, r_refdef.vieworg); r_refdef.vieworg[2] += cl.viewheight + bob; // 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/16 pixel, so add 1/32 in each axis r_refdef.vieworg[0] += 1.0/32; r_refdef.vieworg[1] += 1.0/32; r_refdef.vieworg[2] += 1.0/32; VectorCopy (cl.viewangles, r_refdef.viewangles); V_CalcViewRoll (); V_AddIdle (); // offsets angles[PITCH] = -ent->angles[PITCH]; // because entity pitches are // actually backward angles[YAW] = ent->angles[YAW]; angles[ROLL] = ent->angles[ROLL]; AngleVectors (angles, forward, right, up); for (i=0 ; i<3 ; i++) r_refdef.vieworg[i] += scr_ofsx.value*forward[i] + scr_ofsy.value*right[i] + scr_ofsz.value*up[i]; V_BoundOffsets (); // set up gun position VectorCopy (cl.viewangles, view->angles); CalcGunAngle (); VectorCopy (ent->origin, view->origin); view->origin[2] += cl.viewheight; 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; // fudge position around to keep amount of weapon visible // roughly equal with different FOV #if 0 if (cl.model_precache[cl.stats[STAT_WEAPON]] && strcmp (cl.model_precache[cl.stats[STAT_WEAPON]]->name, "progs/v_shot2.mdl")) #endif if (scr_viewsize.value == 110) view->origin[2] += 1; else if (scr_viewsize.value == 100) view->origin[2] += 2; else if (scr_viewsize.value == 90) view->origin[2] += 1; else if (scr_viewsize.value == 80) view->origin[2] += 0.5; view->model = cl.model_precache[cl.stats[STAT_WEAPON]]; view->frame = cl.stats[STAT_WEAPONFRAME]; view->colormap = vid.colormap; // set up the refresh position VectorAdd (r_refdef.viewangles, cl.punchangle, r_refdef.viewangles); // smooth out stair step ups if (cl.onground && ent->origin[2] - oldz > 0) { float steptime; steptime = cl.time - cl.oldtime; if (steptime < 0) //FIXME I_Error ("steptime < 0"); steptime = 0; oldz += steptime * 80; if (oldz > ent->origin[2]) oldz = ent->origin[2]; if (ent->origin[2] - oldz > 12) oldz = ent->origin[2] - 12; r_refdef.vieworg[2] += oldz - ent->origin[2]; view->origin[2] += oldz - ent->origin[2]; } else oldz = ent->origin[2]; if (chase_active.value) Chase_Update (); } /* ================== V_RenderView The player's clipping box goes from (-16 -16 -24) to (16 16 32) from the entity origin, so any view position inside that will be valid ================== */ extern vrect_t scr_vrect; void V_RenderView (void) { if (con_forcedup) return; // don't allow cheats in multiplayer if (cl.maxclients > 1) { Cvar_Set ("scr_ofsx", "0"); Cvar_Set ("scr_ofsy", "0"); Cvar_Set ("scr_ofsz", "0"); } if (cl.intermission) { // intermission / finale rendering V_CalcIntermissionRefdef (); } else { if (!cl.paused /* && (sv.maxclients > 1 || key_dest == key_game) */ ) V_CalcRefdef (); } R_PushDlights (); if (lcd_x.value) { // // render two interleaved views // int i; vid.rowbytes <<= 1; vid.aspect *= 0.5; r_refdef.viewangles[YAW] -= lcd_yaw.value; for (i=0 ; i<3 ; i++) r_refdef.vieworg[i] -= right[i]*lcd_x.value; R_RenderView (); vid.buffer += vid.rowbytes>>1; R_PushDlights (); r_refdef.viewangles[YAW] += lcd_yaw.value*2; for (i=0 ; i<3 ; i++) r_refdef.vieworg[i] += 2*right[i]*lcd_x.value; R_RenderView (); vid.buffer -= vid.rowbytes>>1; r_refdef.vrect.height <<= 1; vid.rowbytes >>= 1; vid.aspect *= 2; } else { R_RenderView (); } #ifndef GLQUAKE if (crosshair.value) Draw_Character (scr_vrect.x + scr_vrect.width/2 + cl_crossx.value, scr_vrect.y + scr_vrect.height/2 + cl_crossy.value, '+'); #endif } //============================================================================ /* ============= V_Init ============= */ void V_Init (void) { Cmd_AddCommand ("v_cshift", V_cshift_f); Cmd_AddCommand ("bf", V_BonusFlash_f); Cmd_AddCommand ("centerview", V_StartPitchDrift); Cvar_RegisterVariable (&lcd_x); Cvar_RegisterVariable (&lcd_yaw); Cvar_RegisterVariable (&v_centermove); Cvar_RegisterVariable (&v_centerspeed); Cvar_RegisterVariable (&v_iyaw_cycle); Cvar_RegisterVariable (&v_iroll_cycle); Cvar_RegisterVariable (&v_ipitch_cycle); Cvar_RegisterVariable (&v_iyaw_level); Cvar_RegisterVariable (&v_iroll_level); Cvar_RegisterVariable (&v_ipitch_level); Cvar_RegisterVariable (&v_idlescale); Cvar_RegisterVariable (&crosshair); Cvar_RegisterVariable (&cl_crossx); Cvar_RegisterVariable (&cl_crossy); Cvar_RegisterVariable (&gl_cshiftpercent); Cvar_RegisterVariable (&scr_ofsx); Cvar_RegisterVariable (&scr_ofsy); Cvar_RegisterVariable (&scr_ofsz); Cvar_RegisterVariable (&cl_rollspeed); Cvar_RegisterVariable (&cl_rollangle); Cvar_RegisterVariable (&cl_bob); Cvar_RegisterVariable (&cl_bobcycle); Cvar_RegisterVariable (&cl_bobup); Cvar_RegisterVariable (&v_kicktime); Cvar_RegisterVariable (&v_kickroll); Cvar_RegisterVariable (&v_kickpitch); BuildGammaTable (1.0); // no gamma yet Cvar_RegisterVariable (&v_gamma); }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "quakedef.h" /* */ typedef struct { int s; dfunction_t *f; } prstack_t; #define MAX_STACK_DEPTH 32 prstack_t pr_stack[MAX_STACK_DEPTH]; int pr_depth; #define LOCALSTACK_SIZE 2048 int localstack[LOCALSTACK_SIZE]; int localstack_used; qboolean pr_trace; dfunction_t *pr_xfunction; int pr_xstatement; int pr_argc; const char *pr_opnames[] = { "DONE", "MUL_F", "MUL_V", "MUL_FV", "MUL_VF", "DIV", "ADD_F", "ADD_V", "SUB_F", "SUB_V", "EQ_F", "EQ_V", "EQ_S", "EQ_E", "EQ_FNC", "NE_F", "NE_V", "NE_S", "NE_E", "NE_FNC", "LE", "GE", "LT", "GT", "INDIRECT", "INDIRECT", "INDIRECT", "INDIRECT", "INDIRECT", "INDIRECT", "ADDRESS", "STORE_F", "STORE_V", "STORE_S", "STORE_ENT", "STORE_FLD", "STORE_FNC", "STOREP_F", "STOREP_V", "STOREP_S", "STOREP_ENT", "STOREP_FLD", "STOREP_FNC", "RETURN", "NOT_F", "NOT_V", "NOT_S", "NOT_ENT", "NOT_FNC", "IF", "IFNOT", "CALL0", "CALL1", "CALL2", "CALL3", "CALL4", "CALL5", "CALL6", "CALL7", "CALL8", "STATE", "GOTO", "AND", "OR", "BITAND", "BITOR" }; char *PR_GlobalString (int ofs); char *PR_GlobalStringNoContents (int ofs); //============================================================================= /* ================= PR_PrintStatement ================= */ void PR_PrintStatement (dstatement_t *s) { int i; if ( (unsigned)s->op < sizeof(pr_opnames)/sizeof(pr_opnames[0])) { Con_Printf ("%s ", pr_opnames[s->op]); i = strlen(pr_opnames[s->op]); for ( ; i<10 ; i++) Con_Printf (" "); } if (s->op == OP_IF || s->op == OP_IFNOT) Con_Printf ("%sbranch %i",PR_GlobalString(s->a),s->b); else if (s->op == OP_GOTO) { Con_Printf ("branch %i",s->a); } else if ( (unsigned)(s->op - OP_STORE_F) < 6) { Con_Printf ("%s",PR_GlobalString(s->a)); Con_Printf ("%s", PR_GlobalStringNoContents(s->b)); } else { if (s->a) Con_Printf ("%s",PR_GlobalString(s->a)); if (s->b) Con_Printf ("%s",PR_GlobalString(s->b)); if (s->c) Con_Printf ("%s", PR_GlobalStringNoContents(s->c)); } Con_Printf ("\n"); } /* ============ PR_StackTrace ============ */ void PR_StackTrace (void) { dfunction_t *f; int i; if (pr_depth == 0) { Con_Printf ("<NO STACK>\n"); return; } pr_stack[pr_depth].f = pr_xfunction; for (i=pr_depth ; i>=0 ; i--) { f = pr_stack[i].f; if (!f) { Con_Printf ("<NO FUNCTION>\n"); } else Con_Printf ("%12s : %s\n", pr_strings + f->s_file, pr_strings + f->s_name); } } /* ============ PR_Profile_f ============ */ void PR_Profile_f (void) { dfunction_t *f, *best; int max; int num; int i; num = 0; do { max = 0; best = NULL; for (i=0 ; i<progs->numfunctions ; i++) { f = &pr_functions[i]; if (f->profile > max) { max = f->profile; best = f; } } if (best) { if (num < 10) Con_Printf ("%7i %s\n", best->profile, pr_strings+best->s_name); num++; best->profile = 0; } } while (best); } /* ============ PR_RunError Aborts the currently executing function ============ */ void PR_RunError (const char *error, ...) { va_list argptr; char string[1024]; va_start (argptr,error); vsprintf (string,error,argptr); va_end (argptr); PR_PrintStatement (pr_statements + pr_xstatement); PR_StackTrace (); Con_Printf ("%s\n", string); pr_depth = 0; // dump the stack so host_error can shutdown functions Host_Error ("Program error"); } /* ============================================================================ PR_ExecuteProgram The interpretation main loop ============================================================================ */ /* ==================== PR_EnterFunction Returns the new program statement counter ==================== */ int PR_EnterFunction (dfunction_t *f) { int i, j, c, o; pr_stack[pr_depth].s = pr_xstatement; pr_stack[pr_depth].f = pr_xfunction; pr_depth++; if (pr_depth >= MAX_STACK_DEPTH) PR_RunError ("stack overflow"); // save off any locals that the new function steps on c = f->locals; if (localstack_used + c > LOCALSTACK_SIZE) PR_RunError ("PR_ExecuteProgram: locals stack overflow\n"); for (i=0 ; i < c ; i++) localstack[localstack_used+i] = ((int *)pr_globals)[f->parm_start + i]; localstack_used += c; // copy parameters o = f->parm_start; for (i=0 ; i<f->numparms ; i++) { for (j=0 ; j<f->parm_size[i] ; j++) { ((int *)pr_globals)[o] = ((int *)pr_globals)[OFS_PARM0+i*3+j]; o++; } } pr_xfunction = f; return f->first_statement - 1; // offset the s++ } /* ==================== PR_LeaveFunction ==================== */ int PR_LeaveFunction (void) { int i, c; if (pr_depth <= 0) Sys_Error ("prog stack underflow"); // restore locals from the stack c = pr_xfunction->locals; localstack_used -= c; if (localstack_used < 0) PR_RunError ("PR_ExecuteProgram: locals stack underflow\n"); for (i=0 ; i < c ; i++) ((int *)pr_globals)[pr_xfunction->parm_start + i] = localstack[localstack_used+i]; // up stack pr_depth--; pr_xfunction = pr_stack[pr_depth].f; return pr_stack[pr_depth].s; } /* ==================== PR_ExecuteProgram ==================== */ void PR_ExecuteProgram (func_t fnum) { eval_t *a, *b, *c; int s; dstatement_t *st; dfunction_t *f, *newf; int runaway; int i; edict_t *ed; int exitdepth; eval_t *ptr; if (!fnum || fnum >= progs->numfunctions) { if (pr_global_struct->self) ED_Print (PROG_TO_EDICT(pr_global_struct->self)); Host_Error ("PR_ExecuteProgram: NULL function"); } f = &pr_functions[fnum]; runaway = 100000; pr_trace = false; // make a stack frame exitdepth = pr_depth; s = PR_EnterFunction (f); while (1) { s++; // next statement st = &pr_statements[s]; a = (eval_t *)&pr_globals[st->a]; b = (eval_t *)&pr_globals[st->b]; c = (eval_t *)&pr_globals[st->c]; if (!--runaway) PR_RunError ("runaway loop error"); pr_xfunction->profile++; pr_xstatement = s; if (pr_trace) PR_PrintStatement (st); switch (st->op) { case OP_ADD_F: c->_float = a->_float + b->_float; break; case OP_ADD_V: c->vector[0] = a->vector[0] + b->vector[0]; c->vector[1] = a->vector[1] + b->vector[1]; c->vector[2] = a->vector[2] + b->vector[2]; break; case OP_SUB_F: c->_float = a->_float - b->_float; break; case OP_SUB_V: c->vector[0] = a->vector[0] - b->vector[0]; c->vector[1] = a->vector[1] - b->vector[1]; c->vector[2] = a->vector[2] - b->vector[2]; break; case OP_MUL_F: c->_float = a->_float * b->_float; break; case OP_MUL_V: c->_float = a->vector[0]*b->vector[0] + a->vector[1]*b->vector[1] + a->vector[2]*b->vector[2]; break; case OP_MUL_FV: c->vector[0] = a->_float * b->vector[0]; c->vector[1] = a->_float * b->vector[1]; c->vector[2] = a->_float * b->vector[2]; break; case OP_MUL_VF: c->vector[0] = b->_float * a->vector[0]; c->vector[1] = b->_float * a->vector[1]; c->vector[2] = b->_float * a->vector[2]; break; case OP_DIV_F: c->_float = a->_float / b->_float; break; case OP_BITAND: c->_float = (int)a->_float & (int)b->_float; break; case OP_BITOR: c->_float = (int)a->_float | (int)b->_float; break; case OP_GE: c->_float = a->_float >= b->_float; break; case OP_LE: c->_float = a->_float <= b->_float; break; case OP_GT: c->_float = a->_float > b->_float; break; case OP_LT: c->_float = a->_float < b->_float; break; case OP_AND: c->_float = a->_float && b->_float; break; case OP_OR: c->_float = a->_float || b->_float; break; case OP_NOT_F: c->_float = !a->_float; break; case OP_NOT_V: c->_float = !a->vector[0] && !a->vector[1] && !a->vector[2]; break; case OP_NOT_S: c->_float = !a->string || !pr_strings[a->string]; break; case OP_NOT_FNC: c->_float = !a->function; break; case OP_NOT_ENT: c->_float = (PROG_TO_EDICT(a->edict) == sv.edicts); break; case OP_EQ_F: c->_float = a->_float == b->_float; break; case OP_EQ_V: c->_float = (a->vector[0] == b->vector[0]) && (a->vector[1] == b->vector[1]) && (a->vector[2] == b->vector[2]); break; case OP_EQ_S: c->_float = !strcmp(pr_strings+a->string,pr_strings+b->string); break; case OP_EQ_E: c->_float = a->_int == b->_int; break; case OP_EQ_FNC: c->_float = a->function == b->function; break; case OP_NE_F: c->_float = a->_float != b->_float; break; case OP_NE_V: c->_float = (a->vector[0] != b->vector[0]) || (a->vector[1] != b->vector[1]) || (a->vector[2] != b->vector[2]); break; case OP_NE_S: c->_float = strcmp(pr_strings+a->string,pr_strings+b->string); break; case OP_NE_E: c->_float = a->_int != b->_int; break; case OP_NE_FNC: c->_float = a->function != b->function; break; //================== case OP_STORE_F: case OP_STORE_ENT: case OP_STORE_FLD: // integers case OP_STORE_S: case OP_STORE_FNC: // pointers b->_int = a->_int; break; case OP_STORE_V: b->vector[0] = a->vector[0]; b->vector[1] = a->vector[1]; b->vector[2] = a->vector[2]; break; case OP_STOREP_F: case OP_STOREP_ENT: case OP_STOREP_FLD: // integers case OP_STOREP_S: case OP_STOREP_FNC: // pointers ptr = (eval_t *)((byte *)sv.edicts + b->_int); ptr->_int = a->_int; break; case OP_STOREP_V: ptr = (eval_t *)((byte *)sv.edicts + b->_int); ptr->vector[0] = a->vector[0]; ptr->vector[1] = a->vector[1]; ptr->vector[2] = a->vector[2]; break; case OP_ADDRESS: ed = PROG_TO_EDICT(a->edict); #ifdef PARANOID NUM_FOR_EDICT(ed); // make sure it's in range #endif if (ed == (edict_t *)sv.edicts && sv.state == ss_active) PR_RunError ("assignment to world entity"); c->_int = (byte *)(ed->u.i + b->_int) - (byte *)sv.edicts; break; case OP_LOAD_F: case OP_LOAD_FLD: case OP_LOAD_ENT: case OP_LOAD_S: case OP_LOAD_FNC: ed = PROG_TO_EDICT(a->edict); #ifdef PARANOID NUM_FOR_EDICT(ed); // make sure it's in range #endif a = (eval_t *)(ed->u.i + b->_int); c->_int = a->_int; break; case OP_LOAD_V: ed = PROG_TO_EDICT(a->edict); #ifdef PARANOID NUM_FOR_EDICT(ed); // make sure it's in range #endif a = (eval_t *)(ed->u.i + b->_int); c->vector[0] = a->vector[0]; c->vector[1] = a->vector[1]; c->vector[2] = a->vector[2]; break; //================== case OP_IFNOT: if (!a->_int) s += st->b - 1; // offset the s++ break; case OP_IF: if (a->_int) s += st->b - 1; // offset the s++ break; case OP_GOTO: s += st->a - 1; // offset the s++ break; 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: pr_argc = st->op - OP_CALL0; if (!a->function) PR_RunError ("NULL function"); newf = &pr_functions[a->function]; if (newf->first_statement < 0) { // negative statements are built in functions i = -newf->first_statement; if (i >= pr_numbuiltins) PR_RunError ("Bad builtin call number"); pr_builtins[i] (); break; } s = PR_EnterFunction (newf); break; case OP_DONE: case OP_RETURN: pr_globals[OFS_RETURN] = pr_globals[st->a]; pr_globals[OFS_RETURN+1] = pr_globals[st->a+1]; pr_globals[OFS_RETURN+2] = pr_globals[st->a+2]; s = PR_LeaveFunction (); if (pr_depth == exitdepth) return; // all done break; case OP_STATE: ed = PROG_TO_EDICT(pr_global_struct->self); #ifdef FPS_20 ed->u.v.nextthink = pr_global_struct->time + 0.05; #else ed->u.v.nextthink = pr_global_struct->time + 0.1; #endif if (a->_float != ed->u.v.frame) { ed->u.v.frame = a->_float; } ed->u.v.think = b->function; break; default: PR_RunError ("Bad opcode %i", st->op); } } }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All // rights reserved. #include <dpmi.h> #include "quakedef.h" #include "dosisms.h" extern cvar_t bgmvolume; #define ADDRESS_MODE_HSG 0 #define ADDRESS_MODE_RED_BOOK 1 #define STATUS_ERROR_BIT 0x8000 #define STATUS_BUSY_BIT 0x0200 #define STATUS_DONE_BIT 0x0100 #define STATUS_ERROR_MASK 0x00ff #define ERROR_WRITE_PROTECT 0 #define ERROR_UNKNOWN_UNIT 1 #define ERROR_DRIVE_NOT_READY 2 #define ERROR_UNKNOWN_COMMAND 3 #define ERROR_CRC_ERROR 4 #define ERROR_BAD_REQUEST_LEN 5 #define ERROR_SEEK_ERROR 6 #define ERROR_UNKNOWN_MEDIA 7 #define ERROR_SECTOR_NOT_FOUND 8 #define ERROR_OUT_OF_PAPER 9 #define ERROR_WRITE_FAULT 10 #define ERROR_READ_FAULT 11 #define ERROR_GENERAL_FAILURE 12 #define ERROR_RESERVED_13 13 #define ERROR_RESERVED_14 14 #define ERROR_BAD_DISK_CHANGE 15 #define COMMAND_READ 3 #define COMMAND_WRITE 12 #define COMMAND_PLAY_AUDIO 132 #define COMMAND_STOP_AUDIO 133 #define COMMAND_RESUME_AUDIO 136 #define READ_REQUEST_AUDIO_CHANNEL_INFO 4 #define READ_REQUEST_DEVICE_STATUS 6 #define READ_REQUEST_MEDIA_CHANGE 9 #define READ_REQUEST_AUDIO_DISK_INFO 10 #define READ_REQUEST_AUDIO_TRACK_INFO 11 #define READ_REQUEST_AUDIO_STATUS 15 #define WRITE_REQUEST_EJECT 0 #define WRITE_REQUEST_RESET 2 #define WRITE_REQUEST_AUDIO_CHANNEL_INFO 3 #define STATUS_DOOR_OPEN 0x00000001 #define STATUS_DOOR_UNLOCKED 0x00000002 #define STATUS_RAW_SUPPORT 0x00000004 #define STATUS_READ_WRITE 0x00000008 #define STATUS_AUDIO_SUPPORT 0x00000010 #define STATUS_INTERLEAVE_SUPPORT 0x00000020 #define STATUS_BIT_6_RESERVED 0x00000040 #define STATUS_PREFETCH_SUPPORT 0x00000080 #define STATUS_AUDIO_MANIPLUATION_SUPPORT 0x00000100 #define STATUS_RED_BOOK_ADDRESS_SUPPORT 0x00000200 #define MEDIA_NOT_CHANGED 1 #define MEDIA_STATUS_UNKNOWN 0 #define MEDIA_CHANGED -1 #define AUDIO_CONTROL_MASK 0xd0 #define AUDIO_CONTROL_DATA_TRACK 0x40 #define AUDIO_CONTROL_AUDIO_2_TRACK 0x00 #define AUDIO_CONTROL_AUDIO_2P_TRACK 0x10 #define AUDIO_CONTROL_AUDIO_4_TRACK 0x80 #define AUDIO_CONTROL_AUDIO_4P_TRACK 0x90 #define AUDIO_STATUS_PAUSED 0x0001 #pragma pack(1) struct playAudioRequest { char addressingMode; int startLocation; int sectors; }; 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 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 deviceStatus_s { char code; int status; }; struct mediaChange_s { char code; char status; }; struct audioDiskInfo_s { char code; char lowTrack; char highTrack; int leadOutStart; }; struct audioTrackInfo_s { char code; char track; int start; char control; }; struct audioStatus_s { char code; short status; int PRstartLocation; int PRendLocation; }; 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; }; #pragma pack() #define MAXIMUM_TRACKS 100 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; } cd_info; 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 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 int RedBookToSector(int rb) { byte minute; byte second; byte frame; minute = (rb >> 16) & 0xff; second = (rb >> 8) & 0xff; frame = rb & 0xff; return minute * 60 * 75 + second * 75 + frame; } static void CDAudio_Reset(void) { cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_WRITE; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.write.volumeID = 0; readInfo->reset.code = WRITE_REQUEST_RESET; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); } static void CDAudio_Eject(void) { cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_WRITE; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.write.volumeID = 0; readInfo->reset.code = WRITE_REQUEST_EJECT; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); } static int CDAudio_GetAudioTrackInfo(byte track, int *start) { byte control; cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_READ; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.read.volumeID = 0; readInfo->audioTrackInfo.code = READ_REQUEST_AUDIO_TRACK_INFO; readInfo->audioTrackInfo.track = track; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); if (cdRequest->status & STATUS_ERROR_BIT) { Con_DPrintf("CDAudio_GetAudioTrackInfo %04x\n", cdRequest->status & 0xffff); return -1; } *start = readInfo->audioTrackInfo.start; control = readInfo->audioTrackInfo.control & AUDIO_CONTROL_MASK; return (control & AUDIO_CONTROL_DATA_TRACK); } static int CDAudio_GetAudioDiskInfo(void) { int n; cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_READ; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.read.volumeID = 0; readInfo->audioDiskInfo.code = READ_REQUEST_AUDIO_DISK_INFO; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); if (cdRequest->status & STATUS_ERROR_BIT) { Con_DPrintf("CDAudio_GetAudioDiskInfo %04x\n", cdRequest->status & 0xffff); return -1; } cd.valid = true; cd.lowTrack = readInfo->audioDiskInfo.lowTrack; cd.highTrack = readInfo->audioDiskInfo.highTrack; cd.leadOutAddress = readInfo->audioDiskInfo.leadOutStart; 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.highTrack) cd.track[n].length = RedBookToSector(cd.leadOutAddress) - RedBookToSector(cd.track[n].start); } } return 0; } static int CDAudio_GetAudioStatus(void) { cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_READ; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.read.volumeID = 0; readInfo->audioDiskInfo.code = READ_REQUEST_AUDIO_STATUS; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); if (cdRequest->status & STATUS_ERROR_BIT) return -1; return 0; } static int CDAudio_MediaChange(void) { cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_READ; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.read.volumeID = 0; readInfo->mediaChange.code = READ_REQUEST_MEDIA_CHANGE; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); return readInfo->mediaChange.status; } // 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) { if (!initialized || !enabled) return; cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_WRITE; cdRequest->status = 0; 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.startSector = 0; cdRequest->x.read.volumeID = 0; readInfo->audioChannelInfo.code = WRITE_REQUEST_AUDIO_CHANNEL_INFO; readInfo->audioChannelInfo.channel0input = 0; readInfo->audioChannelInfo.channel0volume = 0; readInfo->audioChannelInfo.channel1input = 1; readInfo->audioChannelInfo.channel1volume = 0; readInfo->audioChannelInfo.channel2input = 2; readInfo->audioChannelInfo.channel2volume = 0; readInfo->audioChannelInfo.channel3input = 3; readInfo->audioChannelInfo.channel3volume = 0; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); readInfo->audioChannelInfo.channel0volume = volume; readInfo->audioChannelInfo.channel1volume = volume; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); cdvolume = volume; } void CDAudio_Play(byte track, qboolean looping) { int volume; if (!initialized || !enabled) return; if (!cd.valid) return; track = remap[track]; if (playing) { if (playTrack == track) return; CDAudio_Stop(); } playLooping = looping; 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"); return; } volume = (int)(bgmvolume.value * 255.0); if (volume < 0) { Cvar_SetValue ("bgmvolume", 0.0); volume = 0; } else if (volume > 255) { Cvar_SetValue ("bgmvolume", 1.0); volume = 255; } CDAudio_SetVolume (volume); cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_PLAY_AUDIO; cdRequest->status = 0; cdRequest->x.playAudio.addressingMode = ADDRESS_MODE_RED_BOOK; cdRequest->x.playAudio.startLocation = cd.track[track].start; cdRequest->x.playAudio.sectors = cd.track[track].length; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); if (cdRequest->status & STATUS_ERROR_BIT) { Con_DPrintf("CDAudio_Play: track %u failed\n", track); cd.valid = false; playing = false; return; } playing = true; } void CDAudio_Stop(void) { if (!initialized || !enabled) return; cdRequest->headerLength = 13; cdRequest->unit = 0; cdRequest->command = COMMAND_STOP_AUDIO; cdRequest->status = 0; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); wasPlaying = playing; playing = false; } void CDAudio_Pause(void) { CDAudio_Stop(); } 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; cdRequest->status = 0; regs.x.ax = 0x1510; regs.x.cx = cdrom; regs.x.es = cdRequestSegment; regs.x.bx = cdRequestOffset; dos_int86 (0x2f); playing = true; } static void CD_f (void) { char *command; int ret; int n; int startAddress; if (Cmd_Argc() < 2) return; command = Cmd_Argv (1); if (Q_strcasecmp(command, "on") == 0) { enabled = true; return; } if (Q_strcasecmp(command, "off") == 0) { if (playing) CDAudio_Stop(); enabled = false; return; } if (Q_strcasecmp(command, "reset") == 0) { enabled = true; if (playing) CDAudio_Stop(); for (n = 0; n < 256; n++) remap[n] = n; CDAudio_Reset(); CDAudio_GetAudioDiskInfo(); return; } 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]); return; } for (n = 1; n <= ret; n++) remap[n] = Q_atoi(Cmd_Argv (n+1)); return; } 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); return; } if (Q_strcasecmp(command, "loop") == 0) { CDAudio_Play(Q_atoi(Cmd_Argv (2)), true); return; } if (Q_strcasecmp(command, "stop") == 0) { CDAudio_Stop(); return; } if (Q_strcasecmp(command, "pause") == 0) { CDAudio_Pause(); return; } if (Q_strcasecmp(command, "resume") == 0) { CDAudio_Resume(); return; } if (Q_strcasecmp(command, "eject") == 0) { if (playing) 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++) { ret = CDAudio_GetAudioTrackInfo (n, &startAddress); 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); return; } } void CDAudio_Update(void) { int ret; int newVolume; static double lastUpdate; if (!initialized || !enabled) return; if ((realtime - lastUpdate) < 0.25) return; lastUpdate = realtime; 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"); playing = false; wasPlaying = false; cd.valid = false; CDAudio_GetAudioDiskInfo(); return; } } newVolume = (int)(bgmvolume.value * 255.0); if (newVolume != cdvolume) { if (newVolume < 0) { Cvar_SetValue ("bgmvolume", 0.0); newVolume = 0; } else if (newVolume > 255) { Cvar_SetValue ("bgmvolume", 1.0); newVolume = 255; } CDAudio_SetVolume (newVolume); } if (playing) { CDAudio_GetAudioStatus(); if ((cdRequest->status & STATUS_BUSY_BIT) == 0) { playing = false; if (playLooping) CDAudio_Play(playTrack, true); } } } int CDAudio_Init(void) { char *memory; int n; if (cls.state == ca_dedicated) return -1; if (COM_CheckParm("-nocdaudio")) return -1; if (COM_CheckParm("-cdmediacheck")) mediaCheck = true; regs.x.ax = 0x1500; regs.x.bx = 0; dos_int86 (0x2f); if (regs.x.bx == 0) { Con_NotifyBox ( "MSCDEX not loaded, music is\n" "disabled. Use \"-nocdaudio\" if you\n" "wish to avoid this message in the\n" "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"); cdrom = regs.x.cx; regs.x.ax = 0x150c; regs.x.bx = 0; dos_int86 (0x2f); if (regs.x.bx == 0) { Con_NotifyBox ( "MSCDEX version 2.00 or later\n" "required for music. See README.TXT\n" "for help.\n" ); Con_DPrintf("CDAudio_Init: MSCDEX version 2.00 or later required.\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"); return -1; } 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; 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"); enabled = false; } Cmd_AddCommand ("cd", CD_f); Con_Printf("CD Audio Initialized\n"); return 0; } void CDAudio_Shutdown(void) { if (!initialized) return; CDAudio_Stop(); }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // // vid_ext.c: extended video modes // in this implementation, VESA-specific DOS video stuff // // TODO: make dependencies on vid_vga.c explicit or eliminate them #include <stdlib.h> #include <dos.h> #include "quakedef.h" #include "d_local.h" #include "dosisms.h" #include "vid_dos.h" #include <dpmi.h> #define MODE_SUPPORTED_IN_HW 0x0001 #define COLOR_MODE 0x0008 #define GRAPHICS_MODE 0x0010 #define VGA_INCOMPATIBLE 0x0020 #define LINEAR_FRAME_BUFFER 0x0080 #define LINEAR_MODE 0x4000 #define VESA_DONT_WAIT_VSYNC 0 // when page flipping #define VESA_WAIT_VSYNC 0x80 #define MAX_VESA_MODES 30 // we'll just take the first 30 if there // are more typedef struct { int pages[3]; // either 2 or 3 is valid int vesamode; // LINEAR_MODE set if linear mode void *plinearmem; // linear address of start of frame buffer qboolean vga_incompatible; } vesa_extra_t; static vmode_t vesa_modes[MAX_VESA_MODES] = {{NULL, NULL, " ********* VESA modes ********* "}}; static vesa_extra_t vesa_extra[MAX_VESA_MODES]; static char names[MAX_VESA_MODES][10]; extern regs_t regs; static int VID_currentpage; static int VID_displayedpage; static int *VID_pagelist; static byte *VID_membase; static int VID_banked; typedef struct { int modenum; int mode_attributes; int winasegment; int winbsegment; int bytes_per_scanline; // bytes per logical scanline (+16) int win; // window number (A=0, B=1) int win_size; // window size (+6) int granularity; // how finely i can set the window in vid mem (+4) int width, height; // displayed width and height (+18, +20) int bits_per_pixel; // er, better be 8, 15, 16, 24, or 32 (+25) int bytes_per_pixel; // er, better be 1, 2, or 4 int memory_model; // and better be 4 or 6, packed or direct color (+27) int num_pages; // number of complete frame buffer pages (+29) int red_width; // the # of bits in the red component (+31) int red_pos; // the bit position of the red component (+32) int green_width; // etc.. (+33) int green_pos; // (+34) int blue_width; // (+35) int blue_pos; // (+36) int pptr; int pagesize; int numpages; } modeinfo_t; static modeinfo_t modeinfo; // all bytes to avoid problems with compiler field packing typedef struct vbeinfoblock_s { byte VbeSignature[4]; byte VbeVersion[2]; byte OemStringPtr[4]; byte Capabilities[4]; byte VideoModePtr[4]; byte TotalMemory[2]; byte OemSoftwareRev[2]; byte OemVendorNamePtr[4]; byte OemProductNamePtr[4]; byte OemProductRevPtr[4]; byte Reserved[222]; byte OemData[256]; } vbeinfoblock_t; static int totalvidmem; static byte *ppal; qboolean vsync_exists, de_exists; qboolean VID_ExtraGetModeInfo(int modenum); int VID_ExtraInitMode (viddef_t *vid, vmode_t *pcurrentmode); void VID_ExtraSwapBuffers (viddef_t *vid, vmode_t *pcurrentmode, vrect_t *rects); /* ================ VGA_BankedBeginDirectRect ================ */ void VGA_BankedBeginDirectRect (viddef_t *lvid, struct vmode_s *pcurrentmode, int x, int y, byte *pbitmap, int width, int height) { if (!lvid->direct) return; regs.x.ax = 0x4f05; regs.x.bx = 0; regs.x.dx = VID_displayedpage; dos_int86(0x10); VGA_BeginDirectRect (lvid, pcurrentmode, x, y, pbitmap, width, height); regs.x.ax = 0x4f05; regs.x.bx = 0; regs.x.dx = VID_currentpage; dos_int86(0x10); } /* ================ VGA_BankedEndDirectRect ================ */ void VGA_BankedEndDirectRect (viddef_t *lvid, struct vmode_s *pcurrentmode, int x, int y, int width, int height) { if (!lvid->direct) return; regs.x.ax = 0x4f05; regs.x.bx = 0; regs.x.dx = VID_displayedpage; dos_int86(0x10); VGA_EndDirectRect (lvid, pcurrentmode, x, y, width, height); regs.x.ax = 0x4f05; regs.x.bx = 0; regs.x.dx = VID_currentpage; dos_int86(0x10); } /* ================ VID_SetVESAPalette ================ */ void VID_SetVESAPalette (viddef_t *lvid, vmode_t *pcurrentmode, unsigned char *pal) { int i; byte *pp; UNUSED(lvid); UNUSED(pcurrentmode); pp = ppal; for (i=0 ; i<256 ; i++) { pp[2] = pal[0] >> 2; pp[1] = pal[1] >> 2; pp[0] = pal[2] >> 2; pp += 4; pal += 3; } regs.x.ax = 0x4F09; regs.x.bx = 0; regs.x.cx = 256; regs.x.dx = 0; regs.x.es = ptr2real(ppal) >> 4; regs.x.di = ptr2real(ppal) & 0xf; dos_int86(0x10); if (regs.x.ax != 0x4f) Sys_Error ("Unable to load VESA palette\n"); } /* ================ VID_ExtraFarToLinear ================ */ void *VID_ExtraFarToLinear (void *ptr) { int temp; temp = (int)ptr; return real2ptr(((temp & 0xFFFF0000) >> 12) + (temp & 0xFFFF)); } /* ================ VID_ExtraWaitDisplayEnable ================ */ void VID_ExtraWaitDisplayEnable () { while ((inportb (0x3DA) & 0x01) == 1) ; } /* ================ VID_ExtraVidLookForState ================ */ qboolean VID_ExtraVidLookForState (unsigned state, unsigned mask) { int i; double starttime, time; starttime = Sys_FloatTime (); do { for (i=0 ; i<100000 ; i++) { if ((inportb (0x3DA) & mask) == state) return true; } time = Sys_FloatTime (); } while ((time - starttime) < 0.1); return false; } /* ================ VID_ExtraStateFound ================ */ qboolean VID_ExtraStateFound (unsigned state) { int i, workingstate; workingstate = 0; for (i=0 ; i<10 ; i++) { if (!VID_ExtraVidLookForState(workingstate, state)) { return false; } workingstate ^= state; } return true; } /* ================ VID_InitExtra ================ */ void VID_InitExtra (void) { int nummodes; short *pmodenums; vbeinfoblock_t *pinfoblock; __dpmi_meminfo phys_mem_info; pinfoblock = dos_getmemory(sizeof(vbeinfoblock_t)); *(long *)pinfoblock->VbeSignature = 'V' + ('B'<<8) + ('E'<<16) + ('2'<<24); // see if VESA support is available regs.x.ax = 0x4f00; regs.x.es = ptr2real(pinfoblock) >> 4; regs.x.di = ptr2real(pinfoblock) & 0xf; dos_int86(0x10); if (regs.x.ax != 0x4f) return; // no VESA support if (pinfoblock->VbeVersion[1] < 0x02) return; // not VESA 2.0 or greater Con_Printf ("VESA 2.0 compliant adapter:\n%s\n", VID_ExtraFarToLinear (*(byte **)&pinfoblock->OemStringPtr[0])); totalvidmem = *(unsigned short *)&pinfoblock->TotalMemory[0] << 16; pmodenums = (short *) VID_ExtraFarToLinear (*(byte **)&pinfoblock->VideoModePtr[0]); // find 8 bit modes until we either run out of space or run out of modes nummodes = 0; while ((*pmodenums != -1) && (nummodes < MAX_VESA_MODES)) { if (VID_ExtraGetModeInfo (*pmodenums)) { vesa_modes[nummodes].pnext = &vesa_modes[nummodes+1]; if (modeinfo.width > 999) { if (modeinfo.height > 999) { sprintf (&names[nummodes][0], "%4dx%4d", modeinfo.width, modeinfo.height); names[nummodes][9] = 0; } else { sprintf (&names[nummodes][0], "%4dx%3d", modeinfo.width, modeinfo.height); names[nummodes][8] = 0; } } else { if (modeinfo.height > 999) { sprintf (&names[nummodes][0], "%3dx%4d", modeinfo.width, modeinfo.height); names[nummodes][8] = 0; } else { sprintf (&names[nummodes][0], "%3dx%3d", modeinfo.width, modeinfo.height); names[nummodes][7] = 0; } } vesa_modes[nummodes].name = &names[nummodes][0]; vesa_modes[nummodes].width = modeinfo.width; vesa_modes[nummodes].height = modeinfo.height; vesa_modes[nummodes].aspect = ((float)modeinfo.height / (float)modeinfo.width) * (320.0 / 240.0); vesa_modes[nummodes].rowbytes = modeinfo.bytes_per_scanline; vesa_modes[nummodes].planar = 0; vesa_modes[nummodes].pextradata = &vesa_extra[nummodes]; vesa_modes[nummodes].setmode = VID_ExtraInitMode; vesa_modes[nummodes].swapbuffers = VID_ExtraSwapBuffers; vesa_modes[nummodes].setpalette = VID_SetVESAPalette; if (modeinfo.mode_attributes & LINEAR_FRAME_BUFFER) { // add linear bit to mode for linear modes vesa_extra[nummodes].vesamode = modeinfo.modenum | LINEAR_MODE; vesa_extra[nummodes].pages[0] = 0; vesa_extra[nummodes].pages[1] = modeinfo.pagesize; vesa_extra[nummodes].pages[2] = modeinfo.pagesize * 2; vesa_modes[nummodes].numpages = modeinfo.numpages; vesa_modes[nummodes].begindirectrect = VGA_BeginDirectRect; vesa_modes[nummodes].enddirectrect = VGA_EndDirectRect; phys_mem_info.address = (int)modeinfo.pptr; phys_mem_info.size = 0x400000; if (__dpmi_physical_address_mapping(&phys_mem_info)) goto NextMode; vesa_extra[nummodes].plinearmem = real2ptr (phys_mem_info.address); } else { // banked at 0xA0000 vesa_extra[nummodes].vesamode = modeinfo.modenum; vesa_extra[nummodes].pages[0] = 0; vesa_extra[nummodes].plinearmem = real2ptr(modeinfo.winasegment<<4); vesa_modes[nummodes].begindirectrect = VGA_BankedBeginDirectRect; vesa_modes[nummodes].enddirectrect = VGA_BankedEndDirectRect; vesa_extra[nummodes].pages[1] = modeinfo.pagesize; vesa_extra[nummodes].pages[2] = modeinfo.pagesize * 2; vesa_modes[nummodes].numpages = modeinfo.numpages; } vesa_extra[nummodes].vga_incompatible = modeinfo.mode_attributes & VGA_INCOMPATIBLE; nummodes++; } NextMode: pmodenums++; } // add the VESA modes at the start of the mode list (if there are any) if (nummodes) { vesa_modes[nummodes-1].pnext = pvidmodes; pvidmodes = &vesa_modes[0]; numvidmodes += nummodes; ppal = dos_getmemory(256*4); } dos_freememory(pinfoblock); } /* ================ VID_ExtraGetModeInfo ================ */ qboolean VID_ExtraGetModeInfo(int modenum) { char *infobuf; int numimagepages; infobuf = dos_getmemory(256); regs.x.ax = 0x4f01; regs.x.cx = modenum; regs.x.es = ptr2real(infobuf) >> 4; regs.x.di = ptr2real(infobuf) & 0xf; dos_int86(0x10); if (regs.x.ax != 0x4f) { return false; } else { modeinfo.modenum = modenum; modeinfo.bits_per_pixel = *(char*)(infobuf+25); modeinfo.bytes_per_pixel = (modeinfo.bits_per_pixel+1)/8; modeinfo.width = *(short*)(infobuf+18); modeinfo.height = *(short*)(infobuf+20); // we do only 8-bpp in software if ((modeinfo.bits_per_pixel != 8) || (modeinfo.bytes_per_pixel != 1) || (modeinfo.width > MAXWIDTH) || (modeinfo.height > MAXHEIGHT)) { return false; } modeinfo.mode_attributes = *(short*)infobuf; // we only want color graphics modes that are supported by the hardware if ((modeinfo.mode_attributes & (MODE_SUPPORTED_IN_HW | COLOR_MODE | GRAPHICS_MODE)) != (MODE_SUPPORTED_IN_HW | COLOR_MODE | GRAPHICS_MODE)) { return false; } // we only work with linear frame buffers, except for 320x200, which can // effectively be linear when banked at 0xA000 if (!(modeinfo.mode_attributes & LINEAR_FRAME_BUFFER)) { if ((modeinfo.width != 320) || (modeinfo.height != 200)) return false; } modeinfo.bytes_per_scanline = *(short*)(infobuf+16); modeinfo.pagesize = modeinfo.bytes_per_scanline * modeinfo.height; if (modeinfo.pagesize > totalvidmem) return false; // force to one page if the adapter reports it doesn't support more pages // than that, no matter how much memory it has--it may not have hardware // support for page flipping numimagepages = *(unsigned char *)(infobuf+29); if (numimagepages <= 0) { // wrong, but there seems to be an ATI VESA driver that reports 0 modeinfo.numpages = 1; } else if (numimagepages < 3) { modeinfo.numpages = numimagepages; } else { modeinfo.numpages = 3; } if (*(char*)(infobuf+2) & 5) { modeinfo.winasegment = *(unsigned short*)(infobuf+8); modeinfo.win = 0; } else if (*(char*)(infobuf+3) & 5) { modeinfo.winbsegment = *(unsigned short*)(infobuf+8); modeinfo.win = 1; } modeinfo.granularity = *(short*)(infobuf+4) * 1024; modeinfo.win_size = *(short*)(infobuf+6) * 1024; modeinfo.bits_per_pixel = *(char*)(infobuf+25); modeinfo.bytes_per_pixel = (modeinfo.bits_per_pixel+1)/8; modeinfo.memory_model = *(unsigned char*)(infobuf+27); modeinfo.num_pages = *(char*)(infobuf+29) + 1; modeinfo.red_width = *(char*)(infobuf+31); modeinfo.red_pos = *(char*)(infobuf+32); modeinfo.green_width = *(char*)(infobuf+33); modeinfo.green_pos = *(char*)(infobuf+34); modeinfo.blue_width = *(char*)(infobuf+35); modeinfo.blue_pos = *(char*)(infobuf+36); modeinfo.pptr = *(long *)(infobuf+40); #if 0 printf("VID: (VESA) info for mode 0x%x\n", modeinfo.modenum); printf(" mode attrib = 0x%0x\n", modeinfo.mode_attributes); printf(" win a attrib = 0x%0x\n", *(unsigned char*)(infobuf+2)); printf(" win b attrib = 0x%0x\n", *(unsigned char*)(infobuf+3)); printf(" win a seg 0x%0x\n", (int) modeinfo.winasegment); printf(" win b seg 0x%0x\n", (int) modeinfo.winbsegment); printf(" bytes per scanline = %d\n", modeinfo.bytes_per_scanline); printf(" width = %d, height = %d\n", modeinfo.width, modeinfo.height); printf(" win = %c\n", 'A' + modeinfo.win); printf(" win granularity = %d\n", modeinfo.granularity); printf(" win size = %d\n", modeinfo.win_size); printf(" bits per pixel = %d\n", modeinfo.bits_per_pixel); printf(" bytes per pixel = %d\n", modeinfo.bytes_per_pixel); printf(" memory model = 0x%x\n", modeinfo.memory_model); printf(" num pages = %d\n", modeinfo.num_pages); printf(" red width = %d\n", modeinfo.red_width); printf(" red pos = %d\n", modeinfo.red_pos); printf(" green width = %d\n", modeinfo.green_width); printf(" green pos = %d\n", modeinfo.green_pos); printf(" blue width = %d\n", modeinfo.blue_width); printf(" blue pos = %d\n", modeinfo.blue_pos); printf(" phys mem = %x\n", modeinfo.pptr); #endif } dos_freememory(infobuf); return true; } /* ================ VID_ExtraInitMode ================ */ int VID_ExtraInitMode (viddef_t *lvid, vmode_t *pcurrentmode) { vesa_extra_t *pextra; int pageoffset; pextra = pcurrentmode->pextradata; if (vid_nopageflip.value) lvid->numpages = 1; else lvid->numpages = pcurrentmode->numpages; // clean up any old vid buffer lying around, alloc new if needed if (!VGA_FreeAndAllocVidbuffer (lvid, lvid->numpages == 1)) return -1; // memory alloc failed // clear the screen and wait for the next frame. VGA_pcurmode, which // VGA_ClearVideoMem relies on, is guaranteed to be set because mode 0 is // always the first mode set in a session if (VGA_pcurmode) VGA_ClearVideoMem (VGA_pcurmode->planar); // set the mode regs.x.ax = 0x4f02; regs.x.bx = pextra->vesamode; dos_int86(0x10); if (regs.x.ax != 0x4f) return 0; VID_banked = !(pextra->vesamode & LINEAR_MODE); VID_membase = pextra->plinearmem; VGA_width = lvid->width; VGA_height = lvid->height; VGA_rowbytes = lvid->rowbytes; lvid->colormap = host_colormap; VID_pagelist = &pextra->pages[0]; // wait for display enable by default only when triple-buffering on a VGA- // compatible machine that actually has a functioning display enable status vsync_exists = VID_ExtraStateFound (0x08); de_exists = VID_ExtraStateFound (0x01); if (!pextra->vga_incompatible && (lvid->numpages == 3) && de_exists && (_vid_wait_override.value == 0.0)) { Cvar_SetValue ("vid_wait", (float)VID_WAIT_DISPLAY_ENABLE); VID_displayedpage = 0; VID_currentpage = 1; } else { if ((lvid->numpages == 1) && (_vid_wait_override.value == 0.0)) { Cvar_SetValue ("vid_wait", (float)VID_WAIT_NONE); VID_displayedpage = VID_currentpage = 0; } else { Cvar_SetValue ("vid_wait", (float)VID_WAIT_VSYNC); VID_displayedpage = 0; if (lvid->numpages > 1) VID_currentpage = 1; else VID_currentpage = 0; } } // TODO: really should be a call to a function pageoffset = VID_pagelist[VID_displayedpage]; regs.x.ax = 0x4f07; regs.x.bx = 0x80; // wait for vsync so we know page 0 is visible regs.x.cx = pageoffset % VGA_rowbytes; regs.x.dx = pageoffset / VGA_rowbytes; dos_int86(0x10); if (VID_banked) { regs.x.ax = 0x4f05; regs.x.bx = 0; regs.x.dx = VID_currentpage; dos_int86(0x10); VGA_pagebase = VID_membase; } else { VGA_pagebase = VID_membase + VID_pagelist[VID_currentpage]; } if (lvid->numpages > 1) { lvid->buffer = VGA_pagebase; lvid->conbuffer = lvid->buffer; } else { lvid->rowbytes = lvid->width; } lvid->direct = VGA_pagebase; lvid->conrowbytes = lvid->rowbytes; lvid->conwidth = lvid->width; lvid->conheight = lvid->height; lvid->maxwarpwidth = WARP_WIDTH; lvid->maxwarpheight = WARP_HEIGHT; VGA_pcurmode = pcurrentmode; D_InitCaches (vid_surfcache, vid_surfcachesize); return 1; } /* ================ VID_ExtraSwapBuffers ================ */ void VID_ExtraSwapBuffers (viddef_t *lvid, vmode_t *pcurrentmode, vrect_t *rects) { int pageoffset; UNUSED(rects); UNUSED(pcurrentmode); pageoffset = VID_pagelist[VID_currentpage]; // display the newly finished page if (lvid->numpages > 1) { // page flipped regs.x.ax = 0x4f07; if (vid_wait.value != VID_WAIT_VSYNC) { if ((vid_wait.value == VID_WAIT_DISPLAY_ENABLE) && de_exists) VID_ExtraWaitDisplayEnable (); regs.x.bx = VESA_DONT_WAIT_VSYNC; } else { regs.x.bx = VESA_WAIT_VSYNC; // double buffered has to wait } regs.x.cx = pageoffset % VGA_rowbytes; regs.x.dx = pageoffset / VGA_rowbytes; dos_int86(0x10); VID_displayedpage = VID_currentpage; if (++VID_currentpage >= lvid->numpages) VID_currentpage = 0; // // set the new write window if this is a banked mode; otherwise, set the // new address to which to write // if (VID_banked) { regs.x.ax = 0x4f05; regs.x.bx = 0; regs.x.dx = VID_currentpage; dos_int86(0x10); } else { lvid->direct = lvid->buffer; // direct drawing goes to the // currently displayed page lvid->buffer = VID_membase + VID_pagelist[VID_currentpage]; lvid->conbuffer = lvid->buffer; } VGA_pagebase = lvid->buffer; } else { // non-page-flipped if (vsync_exists && (vid_wait.value == VID_WAIT_VSYNC)) { VGA_WaitVsync (); } while (rects) { VGA_UpdateLinearScreen ( lvid->buffer + rects->x + (rects->y * lvid->rowbytes), VGA_pagebase + rects->x + (rects->y * VGA_rowbytes), rects->width, rects->height, lvid->rowbytes, VGA_rowbytes); rects = rects->pnext; } } }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // net_dgrm.c // This is enables a simple IP banning mechanism #define BAN_TEST #ifdef BAN_TEST #if defined(_WIN32) #include <windows.h> #elif defined (NeXT) #include <sys/socket.h> #include <arpa/inet.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif #endif // BAN_TEST #include "quakedef.h" #include "net_dgrm.h" // these two macros are to make the code more readable #define sfunc net_landrivers[sock->landriver] #define dfunc net_landrivers[net_landriverlevel] static int net_landriverlevel; /* statistic counters */ int packetsSent = 0; int packetsReSent = 0; int packetsReceived = 0; int receivedDuplicateCount = 0; int shortPacketCount = 0; int droppedDatagrams; static int myDriverLevel; struct packetBuffer_t { unsigned int length; unsigned int sequence; byte data[MAX_DATAGRAM]; } packetBuffer; extern int m_return_state; extern int m_state; extern qboolean m_return_onerror; extern char m_return_reason[32]; #ifdef DEBUG char *StrAddr (struct qsockaddr *addr) { static char buf[34]; byte *p = (byte *)addr; int n; for (n = 0; n < 16; n++) sprintf (buf + n * 2, "%02x", *p++); return buf; } #endif #ifdef BAN_TEST typedef union { unsigned long ul; struct in_addr addr; } ulongaddr; typedef union { qsockaddr q; sockaddr_in i; } qsockaddr2sockaddr_in; unsigned long banAddr = 0x00000000; unsigned long banMask = 0xffffffff; void NET_Ban_f (void) { char addrStr [32]; char maskStr [32]; void (*print) (const char *fmt, ...); if (cmd_source == src_command) { if (!sv.active) { Cmd_ForwardToServer (); return; } print = Con_Printf; } else { if (pr_global_struct->deathmatch && !host_client->privileged) return; print = SV_ClientPrintf; } switch (Cmd_Argc ()) { case 1: { ulongaddr addrTemp; addrTemp.ul = banAddr; ulongaddr maskTemp; maskTemp.ul - banMask; if (addrTemp.addr.s_addr) { Q_strcpy(addrStr, inet_ntoa(addrTemp.addr)); Q_strcpy(maskStr, inet_ntoa(maskTemp.addr)); print("Banning %s [%s]\n", addrStr, maskStr); } else print("Banning not active\n"); } break; case 2: if (Q_strcasecmp(Cmd_Argv(1), "off") == 0) banAddr = 0x00000000; else banAddr = inet_addr(Cmd_Argv(1)); banMask = 0xffffffff; break; case 3: banAddr = inet_addr(Cmd_Argv(1)); banMask = inet_addr(Cmd_Argv(2)); break; default: print("BAN ip_address [mask]\n"); break; } } #endif int Datagram_SendMessage (qsocket_t *sock, sizebuf_t *data) { unsigned int packetLen; unsigned int dataLen; unsigned int eom; #ifdef DEBUG if (data->cursize == 0) Sys_Error("Datagram_SendMessage: zero length message\n"); if (data->cursize > NET_MAXMESSAGE) Sys_Error("Datagram_SendMessage: message too big %u\n", data->cursize); if (sock->canSend == false) Sys_Error("SendMessage: called with canSend == false\n"); #endif Q_memcpy(sock->sendMessage, data->data, data->cursize); sock->sendMessageLength = data->cursize; if (data->cursize <= MAX_DATAGRAM) { dataLen = data->cursize; eom = NETFLAG_EOM; } else { dataLen = MAX_DATAGRAM; eom = 0; } packetLen = NET_HEADERSIZE + dataLen; packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence++); Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); sock->canSend = false; if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; sock->lastSendTime = net_time; packetsSent++; return 1; } int SendMessageNext (qsocket_t *sock) { unsigned int packetLen; unsigned int dataLen; unsigned int eom; if (sock->sendMessageLength <= MAX_DATAGRAM) { dataLen = sock->sendMessageLength; eom = NETFLAG_EOM; } else { dataLen = MAX_DATAGRAM; eom = 0; } packetLen = NET_HEADERSIZE + dataLen; packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence++); Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); sock->sendNext = false; if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; sock->lastSendTime = net_time; packetsSent++; return 1; } int ReSendMessage (qsocket_t *sock) { unsigned int packetLen; unsigned int dataLen; unsigned int eom; if (sock->sendMessageLength <= MAX_DATAGRAM) { dataLen = sock->sendMessageLength; eom = NETFLAG_EOM; } else { dataLen = MAX_DATAGRAM; eom = 0; } packetLen = NET_HEADERSIZE + dataLen; packetBuffer.length = BigLong(packetLen | (NETFLAG_DATA | eom)); packetBuffer.sequence = BigLong(sock->sendSequence - 1); Q_memcpy (packetBuffer.data, sock->sendMessage, dataLen); sock->sendNext = false; if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; sock->lastSendTime = net_time; packetsReSent++; return 1; } qboolean Datagram_CanSendMessage (qsocket_t *sock) { if (sock->sendNext) SendMessageNext (sock); return sock->canSend; } qboolean Datagram_CanSendUnreliableMessage (qsocket_t *sock) { return true; } int Datagram_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *data) { int packetLen; #ifdef DEBUG if (data->cursize == 0) Sys_Error("Datagram_SendUnreliableMessage: zero length message\n"); if (data->cursize > MAX_DATAGRAM) Sys_Error("Datagram_SendUnreliableMessage: message too big %u\n", data->cursize); #endif packetLen = NET_HEADERSIZE + data->cursize; packetBuffer.length = BigLong(packetLen | NETFLAG_UNRELIABLE); packetBuffer.sequence = BigLong(sock->unreliableSendSequence++); Q_memcpy (packetBuffer.data, data->data, data->cursize); if (sfunc.Write (sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1) return -1; packetsSent++; return 1; } int Datagram_GetMessage (qsocket_t *sock) { unsigned int length; unsigned int flags; int ret = 0; struct qsockaddr readaddr; unsigned int sequence; unsigned int count; if (!sock->canSend) if ((net_time - sock->lastSendTime) > 1.0) ReSendMessage (sock); while(1) { length = sfunc.Read (sock->socket, (byte *)&packetBuffer, NET_DATAGRAMSIZE, &readaddr); // if ((rand() & 255) > 220) // continue; if (length == 0) break; if (length == (unsigned int) -1) { Con_Printf("Read error\n"); return -1; } if (sfunc.AddrCompare(&readaddr, &sock->addr) != 0) { #ifdef DEBUG Con_DPrintf("Forged packet received\n"); Con_DPrintf("Expected: %s\n", StrAddr (&sock->addr)); Con_DPrintf("Received: %s\n", StrAddr (&readaddr)); #endif continue; } if (length < NET_HEADERSIZE) { shortPacketCount++; continue; } length = BigLong(packetBuffer.length); flags = length & (~NETFLAG_LENGTH_MASK); length &= NETFLAG_LENGTH_MASK; if (flags & NETFLAG_CTL) continue; sequence = BigLong(packetBuffer.sequence); packetsReceived++; if (flags & NETFLAG_UNRELIABLE) { if (sequence < sock->unreliableReceiveSequence) { Con_DPrintf("Got a stale datagram\n"); ret = 0; break; } if (sequence != sock->unreliableReceiveSequence) { count = sequence - sock->unreliableReceiveSequence; droppedDatagrams += count; Con_DPrintf("Dropped %u datagram(s)\n", count); } sock->unreliableReceiveSequence = sequence + 1; length -= NET_HEADERSIZE; SZ_Clear (&net_message); SZ_Write (&net_message, packetBuffer.data, length); ret = 2; break; } if (flags & NETFLAG_ACK) { if (sequence != (sock->sendSequence - 1)) { Con_DPrintf("Stale ACK received\n"); continue; } if (sequence == sock->ackSequence) { sock->ackSequence++; if (sock->ackSequence != sock->sendSequence) Con_DPrintf("ack sequencing error\n"); } else { Con_DPrintf("Duplicate ACK received\n"); continue; } sock->sendMessageLength -= MAX_DATAGRAM; if (sock->sendMessageLength > 0) { Q_memcpy(sock->sendMessage, sock->sendMessage+MAX_DATAGRAM, sock->sendMessageLength); sock->sendNext = true; } else { sock->sendMessageLength = 0; sock->canSend = true; } continue; } if (flags & NETFLAG_DATA) { packetBuffer.length = BigLong(NET_HEADERSIZE | NETFLAG_ACK); packetBuffer.sequence = BigLong(sequence); sfunc.Write (sock->socket, (byte *)&packetBuffer, NET_HEADERSIZE, &readaddr); if (sequence != sock->receiveSequence) { receivedDuplicateCount++; continue; } sock->receiveSequence++; length -= NET_HEADERSIZE; if (flags & NETFLAG_EOM) { SZ_Clear(&net_message); SZ_Write(&net_message, sock->receiveMessage, sock->receiveMessageLength); SZ_Write(&net_message, packetBuffer.data, length); sock->receiveMessageLength = 0; ret = 1; break; } Q_memcpy(sock->receiveMessage + sock->receiveMessageLength, packetBuffer.data, length); sock->receiveMessageLength += length; continue; } } if (sock->sendNext) SendMessageNext (sock); return ret; } void PrintStats(qsocket_t *s) { Con_Printf("canSend = %4u \n", s->canSend); Con_Printf("sendSeq = %4u ", s->sendSequence); Con_Printf("recvSeq = %4u \n", s->receiveSequence); Con_Printf("\n"); } void NET_Stats_f (void) { qsocket_t *s; if (Cmd_Argc () == 1) { Con_Printf("unreliable messages sent = %i\n", unreliableMessagesSent); Con_Printf("unreliable messages recv = %i\n", unreliableMessagesReceived); Con_Printf("reliable messages sent = %i\n", messagesSent); Con_Printf("reliable messages received = %i\n", messagesReceived); Con_Printf("packetsSent = %i\n", packetsSent); Con_Printf("packetsReSent = %i\n", packetsReSent); Con_Printf("packetsReceived = %i\n", packetsReceived); Con_Printf("receivedDuplicateCount = %i\n", receivedDuplicateCount); Con_Printf("shortPacketCount = %i\n", shortPacketCount); Con_Printf("droppedDatagrams = %i\n", droppedDatagrams); } else if (Q_strcmp(Cmd_Argv(1), "*") == 0) { for (s = net_activeSockets; s; s = s->next) PrintStats(s); for (s = net_freeSockets; s; s = s->next) PrintStats(s); } else { for (s = net_activeSockets; s; s = s->next) if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0) break; if (s == NULL) for (s = net_freeSockets; s; s = s->next) if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0) break; if (s == NULL) return; PrintStats(s); } } static qboolean testInProgress = false; static int testPollCount; static int testDriver; static int testSocket; static void Test_Poll(void* arg); PollProcedure testPollProcedure = {NULL, 0.0, Test_Poll, NULL}; static void Test_Poll(void* /* arg */) { struct qsockaddr clientaddr; int control; int len; char name[32]; char address[64]; int colors; int frags; int connectTime; byte playerNumber; net_landriverlevel = testDriver; while (1) { len = dfunc.Read (testSocket, net_message.data, net_message.maxsize, &clientaddr); if (len < (int) sizeof(int)) break; net_message.cursize = len; MSG_BeginReading (); control = BigLong(*((int *)net_message.data)); MSG_ReadLong(); if (control == -1) break; if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) break; if ((control & NETFLAG_LENGTH_MASK) != len) break; if (MSG_ReadByte() != CCREP_PLAYER_INFO) Sys_Error("Unexpected repsonse to Player Info request\n"); playerNumber = MSG_ReadByte(); Q_strcpy(name, MSG_ReadString()); colors = MSG_ReadLong(); frags = MSG_ReadLong(); connectTime = MSG_ReadLong(); Q_strcpy(address, MSG_ReadString()); Con_Printf("%s\n frags:%3i colors:%u %u time:%u\n %s\n", name, frags, colors >> 4, colors & 0x0f, connectTime / 60, address); } testPollCount--; if (testPollCount) { SchedulePollProcedure(&testPollProcedure, 0.1); } else { dfunc.CloseSocket(testSocket); testInProgress = false; } } static void Test_f (void) { char *host; int n; int max = MAX_SCOREBOARD; struct qsockaddr sendaddr; if (testInProgress) return; host = Cmd_Argv (1); if (host && hostCacheCount) { for (n = 0; n < hostCacheCount; n++) if (Q_strcasecmp (host, hostcache[n].name) == 0) { if (hostcache[n].driver != myDriverLevel) continue; net_landriverlevel = hostcache[n].ldriver; max = hostcache[n].maxusers; Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); break; } if (n < hostCacheCount) goto JustDoIt; } for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { if (!net_landrivers[net_landriverlevel].initialized) continue; // see if we can resolve the host name if (dfunc.GetAddrFromName(host, &sendaddr) != -1) break; } if (net_landriverlevel == net_numlandrivers) return; JustDoIt: testSocket = dfunc.OpenSocket(0); if (testSocket == -1) return; testInProgress = true; testPollCount = 20; testDriver = net_landriverlevel; for (n = 0; n < max; n++) { SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREQ_PLAYER_INFO); MSG_WriteByte(&net_message, n); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (testSocket, net_message.data, net_message.cursize, &sendaddr); } SZ_Clear(&net_message); SchedulePollProcedure(&testPollProcedure, 0.1); } static qboolean test2InProgress = false; static int test2Driver; static int test2Socket; static void Test2_Poll(void*); PollProcedure test2PollProcedure = {NULL, 0.0, Test2_Poll, NULL}; static void Test2_Poll(void* /* arg */) { struct qsockaddr clientaddr; int control; int len; char name[256]; char value[256]; net_landriverlevel = test2Driver; name[0] = 0; len = dfunc.Read (test2Socket, net_message.data, net_message.maxsize, &clientaddr); if (len < (int) sizeof(int)) goto Reschedule; net_message.cursize = len; MSG_BeginReading (); control = BigLong(*((int *)net_message.data)); MSG_ReadLong(); if (control == -1) goto Error; if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) goto Error; if ((control & NETFLAG_LENGTH_MASK) != len) goto Error; if (MSG_ReadByte() != CCREP_RULE_INFO) goto Error; Q_strcpy(name, MSG_ReadString()); if (name[0] == 0) goto Done; Q_strcpy(value, MSG_ReadString()); Con_Printf("%-16.16s %-16.16s\n", name, value); SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREQ_RULE_INFO); MSG_WriteString(&net_message, name); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (test2Socket, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); Reschedule: SchedulePollProcedure(&test2PollProcedure, 0.05); return; Error: Con_Printf("Unexpected repsonse to Rule Info request\n"); Done: dfunc.CloseSocket(test2Socket); test2InProgress = false; return; } static void Test2_f (void) { char *host; int n; struct qsockaddr sendaddr; if (test2InProgress) return; host = Cmd_Argv (1); if (host && hostCacheCount) { for (n = 0; n < hostCacheCount; n++) if (Q_strcasecmp (host, hostcache[n].name) == 0) { if (hostcache[n].driver != myDriverLevel) continue; net_landriverlevel = hostcache[n].ldriver; Q_memcpy(&sendaddr, &hostcache[n].addr, sizeof(struct qsockaddr)); break; } if (n < hostCacheCount) goto JustDoIt; } for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { if (!net_landrivers[net_landriverlevel].initialized) continue; // see if we can resolve the host name if (dfunc.GetAddrFromName(host, &sendaddr) != -1) break; } if (net_landriverlevel == net_numlandrivers) return; JustDoIt: test2Socket = dfunc.OpenSocket(0); if (test2Socket == -1) return; test2InProgress = true; test2Driver = net_landriverlevel; SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREQ_RULE_INFO); MSG_WriteString(&net_message, ""); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (test2Socket, net_message.data, net_message.cursize, &sendaddr); SZ_Clear(&net_message); SchedulePollProcedure(&test2PollProcedure, 0.05); } int Datagram_Init (void) { int i; int csock; myDriverLevel = net_driverlevel; Cmd_AddCommand ("net_stats", NET_Stats_f); if (COM_CheckParm("-nolan")) return -1; for (i = 0; i < net_numlandrivers; i++) { csock = net_landrivers[i].Init (); if (csock == -1) continue; net_landrivers[i].initialized = true; net_landrivers[i].controlSock = csock; } #ifdef BAN_TEST Cmd_AddCommand ("ban", NET_Ban_f); #endif Cmd_AddCommand ("test", Test_f); Cmd_AddCommand ("test2", Test2_f); return 0; } void Datagram_Shutdown (void) { int i; // // shutdown the lan drivers // for (i = 0; i < net_numlandrivers; i++) { if (net_landrivers[i].initialized) { net_landrivers[i].Shutdown (); net_landrivers[i].initialized = false; } } } void Datagram_Close (qsocket_t *sock) { sfunc.CloseSocket(sock->socket); } void Datagram_Listen (qboolean state) { int i; for (i = 0; i < net_numlandrivers; i++) if (net_landrivers[i].initialized) net_landrivers[i].Listen (state); } static qsocket_t *_Datagram_CheckNewConnections (void) { struct qsockaddr clientaddr; struct qsockaddr newaddr; int newsock; int acceptsock; qsocket_t *sock; qsocket_t *s; int len; int command; int control; int ret; acceptsock = dfunc.CheckNewConnections(); if (acceptsock == -1) return NULL; SZ_Clear(&net_message); len = dfunc.Read (acceptsock, net_message.data, net_message.maxsize, &clientaddr); if (len < (int) sizeof(int)) return NULL; net_message.cursize = len; MSG_BeginReading (); control = BigLong(*((int *)net_message.data)); MSG_ReadLong(); if (control == -1) return NULL; if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) return NULL; if ((control & NETFLAG_LENGTH_MASK) != len) return NULL; command = MSG_ReadByte(); if (command == CCREQ_SERVER_INFO) { if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_SERVER_INFO); dfunc.GetSocketAddr(acceptsock, &newaddr); MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); MSG_WriteString(&net_message, hostname.string); MSG_WriteString(&net_message, sv.name); MSG_WriteByte(&net_message, net_activeconnections); MSG_WriteByte(&net_message, svs.maxclients); MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } if (command == CCREQ_PLAYER_INFO) { int playerNumber; int activeNumber; int clientNumber; client_t *client; playerNumber = MSG_ReadByte(); activeNumber = -1; for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++) { if (client->active) { activeNumber++; if (activeNumber == playerNumber) break; } } if (clientNumber == svs.maxclients) return NULL; SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_PLAYER_INFO); MSG_WriteByte(&net_message, playerNumber); MSG_WriteString(&net_message, client->name); MSG_WriteLong(&net_message, client->colors); MSG_WriteLong(&net_message, (int)client->edict->u.v.frags); MSG_WriteLong(&net_message, (int)(net_time - client->netconnection->connecttime)); MSG_WriteString(&net_message, client->netconnection->address); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } if (command == CCREQ_RULE_INFO) { char *prevCvarName; cvar_t *var; // find the search start location prevCvarName = MSG_ReadString(); if (*prevCvarName) { var = Cvar_FindVar (prevCvarName); if (!var) return NULL; var = var->next; } else var = cvar_vars; // search for the next server cvar while (var) { if (var->server) break; var = var->next; } // send the response SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_RULE_INFO); if (var) { MSG_WriteString(&net_message, var->name); MSG_WriteString(&net_message, var->string); } *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } if (command != CCREQ_CONNECT) return NULL; if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_REJECT); MSG_WriteString(&net_message, "Incompatible version.\n"); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } #ifdef BAN_TEST // check for a ban if (clientaddr.sa_family == AF_INET) { qsockaddr2sockaddr_in temp; temp.q = clientaddr; unsigned long testAddr = temp.i.sin_addr.s_addr; if ((testAddr & banMask) == banAddr) { SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_REJECT); MSG_WriteString(&net_message, "You have been banned.\n"); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } } #endif // see if this guy is already connected for (s = net_activeSockets; s; s = s->next) { if (s->driver != net_driverlevel) continue; ret = dfunc.AddrCompare(&clientaddr, &s->addr); if (ret >= 0) { // is this a duplicate connection reqeust? if (ret == 0 && net_time - s->connecttime < 2.0) { // yes, so send a duplicate reply SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_ACCEPT); dfunc.GetSocketAddr(s->socket, &newaddr); MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } // it's somebody coming back in from a crash/disconnect // so close the old qsocket and let their retry get them back in NET_Close(s); return NULL; } } // allocate a QSocket sock = NET_NewQSocket (); if (sock == NULL) { // no room; try to let him know SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_REJECT); MSG_WriteString(&net_message, "Server is full.\n"); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return NULL; } // allocate a network socket newsock = dfunc.OpenSocket(0); if (newsock == -1) { NET_FreeQSocket(sock); return NULL; } // connect to the client if (dfunc.Connect (newsock, &clientaddr) == -1) { dfunc.CloseSocket(newsock); NET_FreeQSocket(sock); return NULL; } // everything is allocated, just fill in the details sock->socket = newsock; sock->landriver = net_landriverlevel; sock->addr = clientaddr; Q_strcpy(sock->address, dfunc.AddrToString(&clientaddr)); // send him back the info about the server connection he has been allocated SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREP_ACCEPT); dfunc.GetSocketAddr(newsock, &newaddr); MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr)); // MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr)); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr); SZ_Clear(&net_message); return sock; } qsocket_t *Datagram_CheckNewConnections (void) { qsocket_t *ret = NULL; for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) if (net_landrivers[net_landriverlevel].initialized) if ((ret = _Datagram_CheckNewConnections ()) != NULL) break; return ret; } static void _Datagram_SearchForHosts (qboolean xmit) { int ret; int n; int i; struct qsockaddr readaddr; struct qsockaddr myaddr; int control; dfunc.GetSocketAddr (dfunc.controlSock, &myaddr); if (xmit) { SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREQ_SERVER_INFO); MSG_WriteString(&net_message, "QUAKE"); MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Broadcast(dfunc.controlSock, net_message.data, net_message.cursize); SZ_Clear(&net_message); } while ((ret = dfunc.Read (dfunc.controlSock, net_message.data, net_message.maxsize, &readaddr)) > 0) { if (ret < (int) sizeof(int)) continue; net_message.cursize = ret; // don't answer our own query if (dfunc.AddrCompare(&readaddr, &myaddr) >= 0) continue; // is the cache full? if (hostCacheCount == HOSTCACHESIZE) continue; MSG_BeginReading (); control = BigLong(*((int *)net_message.data)); MSG_ReadLong(); if (control == -1) continue; if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) continue; if ((control & NETFLAG_LENGTH_MASK) != ret) continue; if (MSG_ReadByte() != CCREP_SERVER_INFO) continue; dfunc.GetAddrFromName(MSG_ReadString(), &readaddr); // search the cache for this server for (n = 0; n < hostCacheCount; n++) if (dfunc.AddrCompare(&readaddr, &hostcache[n].addr) == 0) break; // is it already there? if (n < hostCacheCount) continue; // add it hostCacheCount++; Q_strcpy(hostcache[n].name, MSG_ReadString()); Q_strcpy(hostcache[n].map, MSG_ReadString()); hostcache[n].users = MSG_ReadByte(); hostcache[n].maxusers = MSG_ReadByte(); if (MSG_ReadByte() != NET_PROTOCOL_VERSION) { Q_strcpy(hostcache[n].cname, hostcache[n].name); hostcache[n].cname[14] = 0; Q_strcpy(hostcache[n].name, "*"); Q_strcat(hostcache[n].name, hostcache[n].cname); } Q_memcpy(&hostcache[n].addr, &readaddr, sizeof(struct qsockaddr)); hostcache[n].driver = net_driverlevel; hostcache[n].ldriver = net_landriverlevel; Q_strcpy(hostcache[n].cname, dfunc.AddrToString(&readaddr)); // check for a name conflict for (i = 0; i < hostCacheCount; i++) { if (i == n) continue; if (Q_strcasecmp (hostcache[n].name, hostcache[i].name) == 0) { i = Q_strlen(hostcache[n].name); if (i < 15 && hostcache[n].name[i-1] > '8') { hostcache[n].name[i] = '0'; hostcache[n].name[i+1] = 0; } else hostcache[n].name[i-1]++; i = -1; } } } } void Datagram_SearchForHosts (qboolean xmit) { for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) { if (hostCacheCount == HOSTCACHESIZE) break; if (net_landrivers[net_landriverlevel].initialized) _Datagram_SearchForHosts (xmit); } } static qsocket_t *_Datagram_Connect (const char *host) { struct qsockaddr sendaddr; struct qsockaddr readaddr; qsocket_t *sock; int newsock; int ret; int reps; double start_time; int control; const char *reason; // see if we can resolve the host name if (dfunc.GetAddrFromName(host, &sendaddr) == -1) return NULL; newsock = dfunc.OpenSocket (0); if (newsock == -1) return NULL; sock = NET_NewQSocket (); if (sock == NULL) goto ErrorReturn2; sock->socket = newsock; sock->landriver = net_landriverlevel; // connect to the host if (dfunc.Connect (newsock, &sendaddr) == -1) goto ErrorReturn; // send the connection request Con_Printf("trying...\n"); SCR_UpdateScreen (); start_time = net_time; for (reps = 0; reps < 3; reps++) { SZ_Clear(&net_message); // save space for the header, filled in later MSG_WriteLong(&net_message, 0); MSG_WriteByte(&net_message, CCREQ_CONNECT); MSG_WriteString(&net_message, "QUAKE"); MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION); *((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK)); dfunc.Write (newsock, net_message.data, net_message.cursize, &sendaddr); SZ_Clear(&net_message); do { ret = dfunc.Read (newsock, net_message.data, net_message.maxsize, &readaddr); // if we got something, validate it if (ret > 0) { // is it from the right place? if (sfunc.AddrCompare(&readaddr, &sendaddr) != 0) { #ifdef DEBUG Con_Printf("wrong reply address\n"); Con_Printf("Expected: %s\n", StrAddr (&sendaddr)); Con_Printf("Received: %s\n", StrAddr (&readaddr)); SCR_UpdateScreen (); #endif ret = 0; continue; } if (ret < (int) sizeof(int)) { ret = 0; continue; } net_message.cursize = ret; MSG_BeginReading (); control = BigLong(*((int *)net_message.data)); MSG_ReadLong(); if (control == -1) { ret = 0; continue; } if ((control & (~NETFLAG_LENGTH_MASK)) != (int) NETFLAG_CTL) { ret = 0; continue; } if ((control & NETFLAG_LENGTH_MASK) != ret) { ret = 0; continue; } } } while (ret == 0 && (SetNetTime() - start_time) < 2.5); if (ret) break; Con_Printf("still trying...\n"); SCR_UpdateScreen (); start_time = SetNetTime(); } if (ret == 0) { reason = "No Response"; Con_Printf("%s\n", reason); Q_strcpy(m_return_reason, reason); goto ErrorReturn; } if (ret == -1) { reason = "Network Error"; Con_Printf("%s\n", reason); Q_strcpy(m_return_reason, reason); goto ErrorReturn; } ret = MSG_ReadByte(); if (ret == CCREP_REJECT) { reason = MSG_ReadString(); Con_Printf(reason); Q_strncpy(m_return_reason, reason, 31); goto ErrorReturn; } if (ret == CCREP_ACCEPT) { Q_memcpy(&sock->addr, &sendaddr, sizeof(struct qsockaddr)); dfunc.SetSocketPort (&sock->addr, MSG_ReadLong()); } else { reason = "Bad Response"; Con_Printf("%s\n", reason); Q_strcpy(m_return_reason, reason); goto ErrorReturn; } dfunc.GetNameFromAddr (&sendaddr, sock->address); Con_Printf ("Connection accepted\n"); sock->lastMessageTime = SetNetTime(); // switch the connection to the specified address if (dfunc.Connect (newsock, &sock->addr) == -1) { reason = "Connect to Game failed"; Con_Printf("%s\n", reason); Q_strcpy(m_return_reason, reason); goto ErrorReturn; } m_return_onerror = false; return sock; ErrorReturn: NET_FreeQSocket(sock); ErrorReturn2: dfunc.CloseSocket(newsock); if (m_return_onerror) { key_dest = key_menu; m_state = m_return_state; m_return_onerror = false; } return NULL; } qsocket_t *Datagram_Connect (const char *host) { qsocket_t *ret = NULL; for (net_landriverlevel = 0; net_landriverlevel < net_numlandrivers; net_landriverlevel++) if (net_landrivers[net_landriverlevel].initialized) if ((ret = _Datagram_Connect (host)) != NULL) break; return ret; }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // net_wipx.c #include "quakedef.h" #include "winquake.h" #include <wsipx.h> #include "net_wipx.h" extern cvar_t hostname; #define MAXHOSTNAMELEN 256 static int net_acceptsocket = -1; // socket for fielding new connections static int net_controlsocket; static struct qsockaddr broadcastaddr; extern qboolean winsock_initialized; extern WSADATA winsockdata; #define IPXSOCKETS 18 static int ipxsocket[IPXSOCKETS]; static int sequence[IPXSOCKETS]; //============================================================================= int WIPX_Init (void) { int i; char buff[MAXHOSTNAMELEN]; struct qsockaddr addr; char *p; int r; WORD wVersionRequested; if (COM_CheckParm ("-noipx")) return -1; // make sure LoadLibrary has happened successfully if (!winsock_lib_initialized) return -1; if (winsock_initialized == 0) { wVersionRequested = MAKEWORD(1, 1); r = pWSAStartup (MAKEWORD(1, 1), &winsockdata); if (r) { Con_Printf ("Winsock initialization failed.\n"); return -1; } } winsock_initialized++; for (i = 0; i < IPXSOCKETS; i++) ipxsocket[i] = 0; // determine my name & address if (pgethostname(buff, MAXHOSTNAMELEN) == 0) { // if the quake hostname isn't set, set it to the machine name if (Q_strcmp(hostname.string, "UNNAMED") == 0) { // see if it's a text IP address (well, close enough) for (p = buff; *p; p++) if ((*p < '0' || *p > '9') && *p != '.') break; // if it is a real name, strip off the domain; we only want the host if (*p) { for (i = 0; i < 15; i++) if (buff[i] == '.') break; buff[i] = 0; } Cvar_Set ("hostname", buff); } } if ((net_controlsocket = WIPX_OpenSocket (0)) == -1) { Con_Printf("WIPX_Init: Unable to open control socket\n"); if (--winsock_initialized == 0) pWSACleanup (); return -1; } ((struct sockaddr_ipx *)&broadcastaddr)->sa_family = AF_IPX; memset(((struct sockaddr_ipx *)&broadcastaddr)->sa_netnum, 0, 4); memset(((struct sockaddr_ipx *)&broadcastaddr)->sa_nodenum, 0xff, 6); ((struct sockaddr_ipx *)&broadcastaddr)->sa_socket = htons((unsigned short)net_hostport); WIPX_GetSocketAddr (net_controlsocket, &addr); Q_strcpy(my_ipx_address, WIPX_AddrToString (&addr)); p = Q_strrchr (my_ipx_address, ':'); if (p) *p = 0; Con_Printf("Winsock IPX Initialized\n"); ipxAvailable = true; return net_controlsocket; } //============================================================================= void WIPX_Shutdown (void) { WIPX_Listen (false); WIPX_CloseSocket (net_controlsocket); if (--winsock_initialized == 0) pWSACleanup (); } //============================================================================= void WIPX_Listen (qboolean state) { // enable listening if (state) { if (net_acceptsocket != -1) return; if ((net_acceptsocket = WIPX_OpenSocket (net_hostport)) == -1) Sys_Error ("WIPX_Listen: Unable to open accept socket\n"); return; } // disable listening if (net_acceptsocket == -1) return; WIPX_CloseSocket (net_acceptsocket); net_acceptsocket = -1; } //============================================================================= int WIPX_OpenSocket (int port) { int handle; int newsocket; struct sockaddr_ipx address; u_long _true = 1; for (handle = 0; handle < IPXSOCKETS; handle++) if (ipxsocket[handle] == 0) break; if (handle == IPXSOCKETS) return -1; if ((newsocket = psocket (AF_IPX, SOCK_DGRAM, NSPROTO_IPX)) == INVALID_SOCKET) return -1; if (pioctlsocket (newsocket, FIONBIO, &_true) == -1) goto ErrorReturn; if (psetsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&_true, sizeof(_true)) < 0) goto ErrorReturn; address.sa_family = AF_IPX; memset(address.sa_netnum, 0, 4); memset(address.sa_nodenum, 0, 6);; address.sa_socket = htons((unsigned short)port); if( bind (newsocket, (void *)&address, sizeof(address)) == 0) { ipxsocket[handle] = newsocket; sequence[handle] = 0; return handle; } Sys_Error ("Winsock IPX bind failed\n"); ErrorReturn: pclosesocket (newsocket); return -1; } //============================================================================= int WIPX_CloseSocket (int handle) { int socket = ipxsocket[handle]; int ret; ret = pclosesocket (socket); ipxsocket[handle] = 0; return ret; } //============================================================================= int WIPX_Connect (int handle, struct qsockaddr *addr) { return 0; } //============================================================================= int WIPX_CheckNewConnections (void) { unsigned long available; if (net_acceptsocket == -1) return -1; if (pioctlsocket (ipxsocket[net_acceptsocket], FIONREAD, &available) == -1) Sys_Error ("WIPX: ioctlsocket (FIONREAD) failed\n"); if (available) return net_acceptsocket; return -1; } //============================================================================= static byte packetBuffer[NET_DATAGRAMSIZE + 4]; int WIPX_Read (int handle, byte *buf, int len, struct qsockaddr *addr) { int addrlen = sizeof (struct qsockaddr); int socket = ipxsocket[handle]; int ret; ret = precvfrom (socket, packetBuffer, len+4, 0, (struct sockaddr *)addr, &addrlen); if (ret == -1) { int errno = pWSAGetLastError(); if (errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED) return 0; } if (ret < 4) return 0; // remove sequence number, it's only needed for DOS IPX ret -= 4; memcpy(buf, packetBuffer+4, ret); return ret; } //============================================================================= int WIPX_Broadcast (int handle, byte *buf, int len) { return WIPX_Write (handle, buf, len, &broadcastaddr); } //============================================================================= int WIPX_Write (int handle, byte *buf, int len, struct qsockaddr *addr) { int socket = ipxsocket[handle]; int ret; // build packet with sequence number *(int *)(&packetBuffer[0]) = sequence[handle]; sequence[handle]++; memcpy(&packetBuffer[4], buf, len); len += 4; ret = psendto (socket, packetBuffer, len, 0, (struct sockaddr *)addr, sizeof(struct qsockaddr)); if (ret == -1) if (pWSAGetLastError() == WSAEWOULDBLOCK) return 0; return ret; } //============================================================================= char *WIPX_AddrToString (struct qsockaddr *addr) { static char buf[28]; sprintf(buf, "%02x%02x%02x%02x:%02x%02x%02x%02x%02x%02x:%u", ((struct sockaddr_ipx *)addr)->sa_netnum[0] & 0xff, ((struct sockaddr_ipx *)addr)->sa_netnum[1] & 0xff, ((struct sockaddr_ipx *)addr)->sa_netnum[2] & 0xff, ((struct sockaddr_ipx *)addr)->sa_netnum[3] & 0xff, ((struct sockaddr_ipx *)addr)->sa_nodenum[0] & 0xff, ((struct sockaddr_ipx *)addr)->sa_nodenum[1] & 0xff, ((struct sockaddr_ipx *)addr)->sa_nodenum[2] & 0xff, ((struct sockaddr_ipx *)addr)->sa_nodenum[3] & 0xff, ((struct sockaddr_ipx *)addr)->sa_nodenum[4] & 0xff, ((struct sockaddr_ipx *)addr)->sa_nodenum[5] & 0xff, ntohs(((struct sockaddr_ipx *)addr)->sa_socket) ); return buf; } //============================================================================= int WIPX_StringToAddr (char *string, struct qsockaddr *addr) { int val; char buf[3]; buf[2] = 0; Q_memset(addr, 0, sizeof(struct qsockaddr)); addr->sa_family = AF_IPX; #define DO(src,dest) \ buf[0] = string[src]; \ buf[1] = string[src + 1]; \ if (sscanf (buf, "%x", &val) != 1) \ return -1; \ ((struct sockaddr_ipx *)addr)->dest = val DO(0, sa_netnum[0]); DO(2, sa_netnum[1]); DO(4, sa_netnum[2]); DO(6, sa_netnum[3]); DO(9, sa_nodenum[0]); DO(11, sa_nodenum[1]); DO(13, sa_nodenum[2]); DO(15, sa_nodenum[3]); DO(17, sa_nodenum[4]); DO(19, sa_nodenum[5]); #undef DO sscanf (&string[22], "%u", &val); ((struct sockaddr_ipx *)addr)->sa_socket = htons((unsigned short)val); return 0; } //============================================================================= int WIPX_GetSocketAddr (int handle, struct qsockaddr *addr) { int socket = ipxsocket[handle]; int addrlen = sizeof(struct qsockaddr); unsigned int a; Q_memset(addr, 0, sizeof(struct qsockaddr)); if(pgetsockname(socket, (struct sockaddr *)addr, &addrlen) != 0) { int errno = pWSAGetLastError(); } return 0; } //============================================================================= int WIPX_GetNameFromAddr (struct qsockaddr *addr, char *name) { Q_strcpy(name, WIPX_AddrToString(addr)); return 0; } //============================================================================= int WIPX_GetAddrFromName(char *name, struct qsockaddr *addr) { int n; char buf[32]; n = Q_strlen(name); if (n == 12) { sprintf(buf, "00000000:%s:%u", name, net_hostport); return WIPX_StringToAddr (buf, addr); } if (n == 21) { sprintf(buf, "%s:%u", name, net_hostport); return WIPX_StringToAddr (buf, addr); } if (n > 21 && n <= 27) return WIPX_StringToAddr (name, addr); return -1; } //============================================================================= int WIPX_AddrCompare (struct qsockaddr *addr1, struct qsockaddr *addr2) { if (addr1->sa_family != addr2->sa_family) return -1; if (*((struct sockaddr_ipx *)addr1)->sa_netnum && *((struct sockaddr_ipx *)addr2)->sa_netnum) if (memcmp(((struct sockaddr_ipx *)addr1)->sa_netnum, ((struct sockaddr_ipx *)addr2)->sa_netnum, 4) != 0) return -1; if (memcmp(((struct sockaddr_ipx *)addr1)->sa_nodenum, ((struct sockaddr_ipx *)addr2)->sa_nodenum, 6) != 0) return -1; if (((struct sockaddr_ipx *)addr1)->sa_socket != ((struct sockaddr_ipx *)addr2)->sa_socket) return 1; return 0; } //============================================================================= int WIPX_GetSocketPort (struct qsockaddr *addr) { return ntohs(((struct sockaddr_ipx *)addr)->sa_socket); } int WIPX_SetSocketPort (struct qsockaddr *addr, int port) { ((struct sockaddr_ipx *)addr)->sa_socket = htons((unsigned short)port); return 0; } //=============================================================================
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* crc.c */ #include "quakedef.h" #include "crc.h" // this is a 16 bit, non-reflected CRC using the polynomial 0x1021 // and the initial and final xor values shown below... in other words, the // CCITT standard CRC used by XMODEM #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 }; void CRC_Init(unsigned short *crcvalue) { *crcvalue = CRC_INIT_VALUE; } void CRC_ProcessByte(unsigned short *crcvalue, byte data) { *crcvalue = (*crcvalue << 8) ^ crctable[(*crcvalue >> 8) ^ data]; } unsigned short CRC_Value(unsigned short crcvalue) { return crcvalue ^ CRC_XOR_VALUE; }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // net_ser.c #include "quakedef.h" #include "net_ser.h" #include "dosisms.h" #include "crc.h" #include "net_comx.c" // serial protocol #define SERIAL_PROTOCOL_VERSION 3 // The serial protocol is message oriented. The high level message format is // a one byte message type (MTYPE_xxx), data, and a 16-bit checksum. All // multi-byte fields are sent in network byte order. There are currently 4 // MTYPEs defined. Their formats are as follows: // // MTYPE_RELIABLE sequence data_length data checksum eom // MTYPE_UNRELIABLE sequence data_length data checksum eom // MTYPE_ACK sequence checksum eom // MTYPE_CONTROL data_length data checksum eom // // sequence is an 8-bit unsigned value starting from 0 // data_length is a 16-bit unsigned value; it is the length of the data only // the checksum is a 16-bit value. the CRC formula used is defined in crc.h. // the checksum covers the entire messages, excluding itself // eom is a special 2 byte sequence used to mark the End Of Message. This is // needed for error recovery. // // A lot of behavior is based on knowledge of the upper level Quake network // layer. For example, only one reliable message can be outstanding (pending // reception of an MTYPE_ACK) at a time. // // The low level routines used to communicate with the modem are not part of // this protocol. // // The CONTROL messages are only used for session establishment. They are // not reliable or sequenced. #define MTYPE_RELIABLE 0x01 #define MTYPE_UNRELIABLE 0x02 #define MTYPE_CONTROL 0x03 #define MTYPE_ACK 0x04 #define MTYPE_CLIENT 0x80 #define ESCAPE_COMMAND 0xe0 #define ESCAPE_EOM 0x19 static qboolean listening = false; typedef struct SerialLine_s { struct SerialLine_s *next; qsocket_t *sock; int lengthStated; int lengthFound; int tty; qboolean connected; qboolean connecting; qboolean client; double connect_time; unsigned short crcStated; unsigned short crcValue; byte currState; byte prevState; byte mtype; byte sequence; } SerialLine; #define STATE_READY 0 #define STATE_SEQUENCE 1 #define STATE_LENGTH1 2 #define STATE_LENGTH2 3 #define STATE_DATA 4 #define STATE_CRC1 5 #define STATE_CRC2 6 #define STATE_EOM 7 #define STATE_ESCAPE 8 #define STATE_ABORT 9 SerialLine serialLine[NUM_COM_PORTS]; int myDriverLevel; static void Serial_SendACK (SerialLine *p, byte sequence); static void ResetSerialLineProtocol (SerialLine *p) { p->connected = false; p->connecting = false; p->currState = STATE_READY; p->prevState = STATE_READY; p->lengthFound = 0; } static int ProcessInQueue(SerialLine *p) { int b; while (1) { b = TTY_ReadByte(p->tty); if (b == ERR_TTY_NODATA) break; if (b == ERR_TTY_LINE_STATUS) { p->currState = STATE_ABORT; continue; } if (b == ERR_TTY_MODEM_STATUS) { p->currState = STATE_ABORT; return -1; } if (b == ESCAPE_COMMAND) if (p->currState != STATE_ESCAPE) { p->prevState = p->currState; p->currState = STATE_ESCAPE; continue; } if (p->currState == STATE_ESCAPE) { if (b == ESCAPE_EOM) { if (p->prevState == STATE_ABORT) { p->currState = STATE_READY; p->lengthFound = 0; continue; } if (p->prevState != STATE_EOM) { p->currState = STATE_READY; p->lengthFound = 0; Con_DPrintf("Serial: premature EOM\n"); continue; } switch (p->mtype) { case MTYPE_RELIABLE: Con_DPrintf("Serial: sending ack %u\n", p->sequence); Serial_SendACK (p, p->sequence); if (p->sequence == p->sock->receiveSequence) { p->sock->receiveSequence = (p->sequence + 1) & 0xff; p->sock->receiveMessageLength += p->lengthFound; } else Con_DPrintf("Serial: reliable out of order; got %u wanted %u\n", p->sequence, p->sock->receiveSequence); break; case MTYPE_UNRELIABLE: p->sock->unreliableReceiveSequence = (p->sequence + 1) & 0xff; p->sock->receiveMessageLength += p->lengthFound; break; case MTYPE_ACK: Con_DPrintf("Serial: got ack %u\n", p->sequence); if (p->sequence == p->sock->sendSequence) { p->sock->sendSequence = (p->sock->sendSequence + 1) & 0xff; p->sock->canSend = true; } else Con_DPrintf("Serial: ack out of order; got %u wanted %u\n",p->sequence, p->sock->sendSequence); break; case MTYPE_CONTROL: p->sock->receiveMessageLength += p->lengthFound; break; } p->currState = STATE_READY; p->lengthFound = 0; continue; } if (b != ESCAPE_COMMAND) { p->currState = STATE_ABORT; Con_DPrintf("Serial: Bad escape sequence\n"); continue; } // b == ESCAPE_COMMAND p->currState = p->prevState; } p->prevState = p->currState; //DEBUG if (p->sock->receiveMessageLength + p->lengthFound > NET_MAXMESSAGE) { Con_DPrintf("Serial blew out receive buffer: %u\n", p->sock->receiveMessageLength + p->lengthFound); p->currState = STATE_ABORT; } if (p->sock->receiveMessageLength + p->lengthFound == NET_MAXMESSAGE) { Con_DPrintf("Serial hit receive buffer limit: %u\n", p->sock->receiveMessageLength + p->lengthFound); p->currState = STATE_ABORT; } //end DEBUG switch (p->currState) { case STATE_READY: CRC_Init(&p->crcValue); CRC_ProcessByte(&p->crcValue, b); if (p->client) { if ((b & MTYPE_CLIENT) != 0) { p->currState = STATE_ABORT; Con_DPrintf("Serial: client got own message\n"); break; } } else { if ((b & MTYPE_CLIENT) == 0) { p->currState = STATE_ABORT; Con_DPrintf("Serial: server got own message\n"); break; } b &= 0x7f; } p->mtype = b; if (b != MTYPE_CONTROL) p->currState = STATE_SEQUENCE; else p->currState = STATE_LENGTH1; if (p->mtype < MTYPE_ACK) { p->sock->receiveMessage[p->sock->receiveMessageLength] = b; p->lengthFound++; } break; case STATE_SEQUENCE: p->sequence = b; CRC_ProcessByte(&p->crcValue, b); if (p->mtype != MTYPE_ACK) p->currState = STATE_LENGTH1; else p->currState = STATE_CRC1; break; case STATE_LENGTH1: p->lengthStated = b * 256; CRC_ProcessByte(&p->crcValue, b); p->currState = STATE_LENGTH2; break; case STATE_LENGTH2: p->lengthStated += b; CRC_ProcessByte(&p->crcValue, b); if (p->mtype == MTYPE_RELIABLE && p->lengthStated > MAX_MSGLEN) { p->currState = STATE_ABORT; Con_DPrintf("Serial: bad reliable message length %u\n", p->lengthStated); } else if (p->mtype == MTYPE_UNRELIABLE && p->lengthStated > MAX_DATAGRAM) { p->currState = STATE_ABORT; Con_DPrintf("Serial: bad unreliable message length %u\n", p->lengthStated); } else { p->currState = STATE_DATA; if (p->mtype < MTYPE_ACK) { *(short *)&p->sock->receiveMessage [p->sock->receiveMessageLength + 1] = p->lengthStated; p->lengthFound += 2; } } break; case STATE_DATA: p->sock->receiveMessage[p->sock->receiveMessageLength + p->lengthFound] = b; p->lengthFound++; CRC_ProcessByte(&p->crcValue, b); if (p->lengthFound == p->lengthStated + 3) p->currState = STATE_CRC1; break; case STATE_CRC1: p->crcStated = b * 256; p->currState = STATE_CRC2; break; case STATE_CRC2: p->crcStated += b; if (p->crcStated == CRC_Value(p->crcValue)) { p->currState = STATE_EOM; } else { p->currState = STATE_ABORT; Con_DPrintf("Serial: Bad crc\n"); } break; case STATE_EOM: p->currState = STATE_ABORT; Con_DPrintf("Serial: Bad message format\n"); break; case STATE_ABORT: break; } } return 0; } int Serial_Init (void) { int n; // LATER do Win32 serial support #ifdef _WIN32 return -1; #endif if (COM_CheckParm("-nolan")) return -1; if (COM_CheckParm ("-noserial")) return -1; myDriverLevel = net_driverlevel; if (TTY_Init()) return -1; for (n = 0; n < NUM_COM_PORTS; n++) { serialLine[n].tty = TTY_Open(n); ResetSerialLineProtocol (&serialLine[n]); } Con_Printf("Serial driver initialized\n"); serialAvailable = true; return 0; } void Serial_Shutdown (void) { int n; for (n = 0; n < NUM_COM_PORTS; n++) { if (serialLine[n].connected) Serial_Close(serialLine[n].sock); } TTY_Shutdown(); } void Serial_Listen (qboolean state) { listening = state; } qboolean Serial_CanSendMessage (qsocket_t *sock) { return sock->canSend; } qboolean Serial_CanSendUnreliableMessage (qsocket_t *sock) { return TTY_OutputQueueIsEmpty(((SerialLine *)sock->driverdata)->tty); } int Serial_SendMessage (qsocket_t *sock, sizebuf_t *message) { SerialLine *p; int n; unsigned short crc; byte b; p = (SerialLine *)sock->driverdata; CRC_Init (&crc); // message type b = MTYPE_RELIABLE; if (p->client) b |= MTYPE_CLIENT; TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // sequence b = p->sock->sendSequence; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // data length b = message->cursize >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); b = message->cursize & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // data for (n = 0; n < message->cursize; n++) { b = message->data[n]; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); } // checksum b = CRC_Value (crc) >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); b = CRC_Value (crc) & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); // end of message TTY_WriteByte(p->tty, ESCAPE_COMMAND); TTY_WriteByte(p->tty, ESCAPE_EOM); TTY_Flush(p->tty); // mark sock as busy and save the message for possible retransmit sock->canSend = false; Q_memcpy(sock->sendMessage, message->data, message->cursize); sock->sendMessageLength = message->cursize; sock->lastSendTime = net_time; return 1; } static void ReSendMessage (qsocket_t *sock) { sizebuf_t temp; Con_DPrintf("Serial: re-sending reliable\n"); temp.data = sock->sendMessage; temp.maxsize = sock->sendMessageLength; temp.cursize = sock->sendMessageLength; Serial_SendMessage (sock, &temp); } int Serial_SendUnreliableMessage (qsocket_t *sock, sizebuf_t *message) { SerialLine *p; int n; unsigned short crc; byte b; p = (SerialLine *)sock->driverdata; if (!TTY_OutputQueueIsEmpty(p->tty)) { TTY_Flush(p->tty); return 1; } CRC_Init (&crc); // message type b = MTYPE_UNRELIABLE; if (p->client) b |= MTYPE_CLIENT; TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // sequence b = p->sock->unreliableSendSequence; p->sock->unreliableSendSequence = (b + 1) & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // data length b = message->cursize >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); b = message->cursize & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // data for (n = 0; n < message->cursize; n++) { b = message->data[n]; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); } // checksum b = CRC_Value (crc) >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); b = CRC_Value (crc) & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); // end of message TTY_WriteByte(p->tty, ESCAPE_COMMAND); TTY_WriteByte(p->tty, ESCAPE_EOM); TTY_Flush(p->tty); return 1; } static void Serial_SendACK (SerialLine *p, byte sequence) { unsigned short crc; byte b; CRC_Init (&crc); // message type b = MTYPE_ACK; if (p->client) b |= MTYPE_CLIENT; TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // sequence b = sequence; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // checksum b = CRC_Value (crc) >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); b = CRC_Value (crc) & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); // end of message TTY_WriteByte(p->tty, ESCAPE_COMMAND); TTY_WriteByte(p->tty, ESCAPE_EOM); TTY_Flush(p->tty); } static void Serial_SendControlMessage (SerialLine *p, sizebuf_t *message) { unsigned short crc; int n; byte b; CRC_Init (&crc); // message type b = MTYPE_CONTROL; if (p->client) b |= MTYPE_CLIENT; TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // data length b = message->cursize >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); b = message->cursize & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); // data for (n = 0; n < message->cursize; n++) { b = message->data[n]; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); CRC_ProcessByte (&crc, b); } // checksum b = CRC_Value (crc) >> 8; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); b = CRC_Value (crc) & 0xff; TTY_WriteByte(p->tty, b); if (b == ESCAPE_COMMAND) TTY_WriteByte(p->tty, b); // end of message TTY_WriteByte(p->tty, ESCAPE_COMMAND); TTY_WriteByte(p->tty, ESCAPE_EOM); TTY_Flush(p->tty); } static int _Serial_GetMessage (SerialLine *p) { byte ret; short length; if (ProcessInQueue(p)) return -1; if (p->sock->receiveMessageLength == 0) return 0; ret = p->sock->receiveMessage[0]; length = *(short *)&p->sock->receiveMessage[1]; if (ret == MTYPE_CONTROL) ret = 1; SZ_Clear (&net_message); SZ_Write (&net_message, &p->sock->receiveMessage[3], length); length += 3; p->sock->receiveMessageLength -= length; if (p->sock->receiveMessageLength + p->lengthFound) Q_memcpy(p->sock->receiveMessage, &p->sock->receiveMessage[length], p->sock->receiveMessageLength + p->lengthFound); return ret; } int Serial_GetMessage (qsocket_t *sock) { SerialLine *p; int ret; p = (SerialLine *)sock->driverdata; ret = _Serial_GetMessage (p); if (ret == 1) messagesReceived++; if (!sock->canSend) if ((net_time - sock->lastSendTime) > 1.0) { ReSendMessage (sock); sock->lastSendTime = net_time; } return ret; } void Serial_Close (qsocket_t *sock) { SerialLine *p = (SerialLine *)sock->driverdata; TTY_Close(p->tty); ResetSerialLineProtocol (p); } char *com_types[] = {"direct", "modem"}; unsigned com_bauds[] = {9600, 14400, 19200, 28800, 57600}; void Serial_SearchForHosts (qboolean xmit) { int n; SerialLine *p; if (sv.active) return; if (hostCacheCount == HOSTCACHESIZE) return; // see if we've already answered for (n = 0; n < hostCacheCount; n++) if (Q_strcmp (hostcache[n].cname, "#") == 0) return; for (n = 0; n < NUM_COM_PORTS; n++) if (TTY_IsEnabled(n)) break; if (n == NUM_COM_PORTS) return; p = &serialLine[n]; if (TTY_IsModem(p->tty)) return; sprintf(hostcache[hostCacheCount].name, "COM%u", n+1); Q_strcpy(hostcache[hostCacheCount].map, ""); hostcache[hostCacheCount].users = 0; hostcache[hostCacheCount].maxusers = 0; hostcache[hostCacheCount].driver = net_driverlevel; Q_strcpy(hostcache[hostCacheCount].cname, "#"); hostCacheCount++; return; } static qsocket_t *_Serial_Connect (char *host, SerialLine *p) { int ret; double start_time; double last_time; p->client = true; if (TTY_Connect(p->tty, host)) return NULL; p->sock = NET_NewQSocket (); p->sock->driver = myDriverLevel; if (p->sock == NULL) { Con_Printf("No sockets available\n"); return NULL; } p->sock->driverdata = p; // send the connection request start_time = SetNetTime(); last_time = 0.0; SZ_Clear(&net_message); MSG_WriteByte(&net_message, CCREQ_CONNECT); MSG_WriteString(&net_message, "QUAKE"); do { SetNetTime(); if ((net_time - last_time) >= 1.0) { Serial_SendControlMessage (p, &net_message); last_time = net_time; Con_Printf("trying...\n"); SCR_UpdateScreen (); } ret = _Serial_GetMessage (p); } while (ret == 0 && (net_time - start_time) < 5.0); if (ret == 0) { Con_Printf("Unable to connect, no response\n"); goto ErrorReturn; } if (ret == -1) { Con_Printf("Connection request error\n"); goto ErrorReturn; } MSG_BeginReading (); ret = MSG_ReadByte(); if (ret == CCREP_REJECT) { Con_Printf(MSG_ReadString()); goto ErrorReturn; } if (ret != CCREP_ACCEPT) { Con_Printf("Unknown connection response\n"); goto ErrorReturn; } p->connected = true; p->sock->lastMessageTime = net_time; Con_Printf ("Connection accepted\n"); return p->sock; ErrorReturn: TTY_Disconnect(p->tty); return NULL; } qsocket_t *Serial_Connect (char *host) { int n; qsocket_t *ret = NULL; // see if this looks like a phone number if (*host == '#') host++; for (n = 0; n < Q_strlen(host); n++) if (host[n] == '.' || host[n] == ':') return NULL; for (n = 0; n < NUM_COM_PORTS; n++) if (TTY_IsEnabled(n) && !serialLine[n].connected) if ((ret = _Serial_Connect (host, &serialLine[n]))) break; return ret; } static qsocket_t *_Serial_CheckNewConnections (SerialLine *p) { int command; p->client = false; if (!TTY_CheckForConnection(p->tty)) return NULL; if (TTY_IsModem(p->tty)) { if (!p->connecting) { p->connecting = true; p->connect_time = net_time; } else if ((net_time - p->connect_time) > 15.0) { p->connecting = false; TTY_Disconnect(p->tty); return NULL; } } p->sock = NET_NewQSocket (); p->sock->driver = myDriverLevel; if (p->sock == NULL) { Con_Printf("No sockets available\n"); return NULL; } p->sock->driverdata = p; SZ_Clear(&net_message); if (_Serial_GetMessage(p) != 1) { NET_FreeQSocket(p->sock); return NULL; } MSG_BeginReading (); command = MSG_ReadByte(); if (command == CCREQ_SERVER_INFO) { if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; if (MSG_ReadByte() != SERIAL_PROTOCOL_VERSION) return NULL; SZ_Clear(&net_message); MSG_WriteByte(&net_message, CCREP_SERVER_INFO); MSG_WriteString(&net_message, hostname.string); MSG_WriteString(&net_message, sv.name); MSG_WriteByte(&net_message, net_activeconnections); MSG_WriteByte(&net_message, svs.maxclients); Serial_SendControlMessage (p, &net_message); SZ_Clear(&net_message); return NULL; } if (command != CCREQ_CONNECT) return NULL; if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0) return NULL; // send him back the info about the server connection he has been allocated SZ_Clear(&net_message); MSG_WriteByte(&net_message, CCREP_ACCEPT); Serial_SendControlMessage (p, &net_message); SZ_Clear(&net_message); p->connected = true; p->connecting = false; p->sock->lastMessageTime = net_time; sprintf(p->sock->address, "COM%u", (int)((p - serialLine) + 1)); return p->sock; } qsocket_t *Serial_CheckNewConnections (void) { int n; qsocket_t *ret = NULL; for (n = 0; n < NUM_COM_PORTS; n++) if (TTY_IsEnabled(n) && !serialLine[n].connected) if ((ret = _Serial_CheckNewConnections (&serialLine[n]))) break; return ret; }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_main.c #include "quakedef.h" #include "r_local.h" //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; qboolean r_dowarp, r_dowarpold, r_viewchanged; 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; byte *r_warpbuffer; byte *r_stack_start; qboolean r_fov_greater_than_90; // // view 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; int screenwidth; float pixelAspect; float screenAspect; float verticalFieldOfView; float xOrigin, yOrigin; 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; #define VIEWMODNAME_LENGTH 256 char viewmodname[VIEWMODNAME_LENGTH+1]; int modcount; int *pfrustum_indexes[4]; int r_frustum_indexes[4*6]; int reinit_surfcache = 1; // if 1, surface cache is currently empty and // must be reinitialized for current cache size mleaf_t *r_viewleaf, *r_oldviewleaf; texture_t *r_notexture_mip; float r_aliastransition, r_resfudge; int d_lightstylevalue[256]; // 8.8 fraction of base light value 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; void R_MarkLeaves (void); cvar_t r_draworder = {"r_draworder","0"}; cvar_t r_speeds = {"r_speeds","0"}; cvar_t r_timegraph = {"r_timegraph","0"}; cvar_t r_graphheight = {"r_graphheight","10"}; cvar_t r_clearcolor = {"r_clearcolor","2"}; cvar_t r_waterwarp = {"r_waterwarp","1"}; cvar_t r_fullbright = {"r_fullbright","0"}; cvar_t r_drawentities = {"r_drawentities","1"}; cvar_t r_drawviewmodel = {"r_drawviewmodel","1"}; cvar_t r_aliasstats = {"r_polymodelstats","0"}; cvar_t r_dspeeds = {"r_dspeeds","0"}; cvar_t r_drawflat = {"r_drawflat", "0"}; cvar_t r_ambient = {"r_ambient", "0"}; cvar_t r_reportsurfout = {"r_reportsurfout", "0"}; cvar_t r_maxsurfs = {"r_maxsurfs", "0"}; cvar_t r_numsurfs = {"r_numsurfs", "0"}; cvar_t r_reportedgeout = {"r_reportedgeout", "0"}; cvar_t r_maxedges = {"r_maxedges", "0"}; cvar_t r_numedges = {"r_numedges", "0"}; cvar_t r_aliastransbase = {"r_aliastransbase", "200"}; cvar_t r_aliastransadj = {"r_aliastransadj", "100"}; extern cvar_t scr_fov; void CreatePassages (void); void SetVisibilityByPassages (void); /* ================== R_InitTextures ================== */ void R_InitTextures (void) { 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->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) ) ) *dest++ = 0; else *dest++ = 0xff; } } } /* =============== R_Init =============== */ void R_Init (void) { int dummy; // get stack position so we can guess if we are going to overflow r_stack_start = (byte *)&dummy; R_InitTurb (); Cmd_AddCommand ("timerefresh", R_TimeRefresh_f); Cmd_AddCommand ("pointfile", R_ReadPointFile_f); Cvar_RegisterVariable (&r_draworder); Cvar_RegisterVariable (&r_speeds); Cvar_RegisterVariable (&r_timegraph); Cvar_RegisterVariable (&r_graphheight); Cvar_RegisterVariable (&r_drawflat); Cvar_RegisterVariable (&r_ambient); Cvar_RegisterVariable (&r_clearcolor); Cvar_RegisterVariable (&r_waterwarp); Cvar_RegisterVariable (&r_fullbright); Cvar_RegisterVariable (&r_drawentities); Cvar_RegisterVariable (&r_drawviewmodel); Cvar_RegisterVariable (&r_aliasstats); Cvar_RegisterVariable (&r_dspeeds); Cvar_RegisterVariable (&r_reportsurfout); Cvar_RegisterVariable (&r_maxsurfs); Cvar_RegisterVariable (&r_numsurfs); Cvar_RegisterVariable (&r_reportedgeout); Cvar_RegisterVariable (&r_maxedges); Cvar_RegisterVariable (&r_numedges); Cvar_RegisterVariable (&r_aliastransbase); Cvar_RegisterVariable (&r_aliastransadj); 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[0].rightedge = view_clipplanes[2].rightedge = view_clipplanes[3].rightedge = false; r_refdef.xOrigin = XCENTERING; r_refdef.yOrigin = YCENTERING; R_InitParticles (); // TODO: collect 386-specific code in one place #if id386 Sys_MakeCodeWriteable ((long)R_EdgeCodeStart, (long)R_EdgeCodeEnd - (long)R_EdgeCodeStart); #endif // id386 D_Init (); } /* =============== R_NewMap =============== */ void R_NewMap (void) { int i; // clear out efrags in case the level hasn't been reloaded // FIXME: is this one short? for (i=0 ; i<cl.worldmodel->numleafs ; i++) cl.worldmodel->leafs[i].efrags = NULL; r_viewleaf = NULL; R_ClearParticles (); r_cnumsurfs = r_maxsurfs.value; if (r_cnumsurfs <= MINSURFACES) r_cnumsurfs = MINSURFACES; 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 surfaces--; R_SurfacePatch (); } else { r_surfsonstack = true; } r_maxedgesseen = 0; r_maxsurfsseen = 0; r_numallocatededges = r_maxedges.value; if (r_numallocatededges < MINEDGES) r_numallocatededges = MINEDGES; if (r_numallocatededges <= NUMSTACKEDGES) { auxedges = NULL; } else { auxedges = Hunk_AllocName (r_numallocatededges * sizeof(edge_t), "edges"); } r_dowarpold = false; r_viewchanged = false; #ifdef PASSAGES CreatePassages (); #endif } /* =============== R_SetVrect =============== */ void R_SetVrect (vrect_t *pvrectin, vrect_t *pvrect, int lineadj) { int h; float size; size = scr_viewsize.value > 100 ? 100 : scr_viewsize.value; if (cl.intermission) { size = 100; lineadj = 0; } size /= 100; h = pvrectin->height - lineadj; pvrect->width = pvrectin->width * size; if (pvrect->width < 96) { size = 96.0 / pvrectin->width; pvrect->width = 96; // min for icons } pvrect->width &= ~7; pvrect->height = pvrectin->height * size; if (pvrect->height > pvrectin->height - lineadj) pvrect->height = pvrectin->height - lineadj; pvrect->height &= ~1; pvrect->x = (pvrectin->width - pvrect->width)/2; pvrect->y = (h - pvrect->height)/2; { if (lcd_x.value) { pvrect->y >>= 1; pvrect->height >>= 1; } } } /* =============== R_ViewChanged 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) { 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.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.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.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.aliasvrectbottom = r_refdef.aliasvrect.y + r_refdef.aliasvrect.height; pixelAspect = aspect; xOrigin = r_refdef.xOrigin; yOrigin = r_refdef.yOrigin; 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 verticalFieldOfView = r_refdef.horizontalFieldOfView / screenAspect; // values for perspective projection // if math were exact, the values would range from 0.5 to to range+0.5 // hopefully they wll be in the 0.000001 to range+.999999 and truncate // 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; aliasxcenter = xcenter * r_aliasuvscale; 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; aliasxscale = xscale * r_aliasuvscale; xscaleinv = 1.0 / xscale; yscale = xscale * pixelAspect; aliasyscale = yscale * r_aliasuvscale; yscaleinv = 1.0 / yscale; 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[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); 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[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].type = PLANE_ANYZ; 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); r_aliastransition = r_aliastransbase.value * res_scale; r_resfudge = r_aliastransadj.value * res_scale; if (scr_fov.value <= 90.0) r_fov_greater_than_90 = false; else r_fov_greater_than_90 = true; // TODO: collect 386-specific code in one place #if id386 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); colormap = vid.colormap16; R_Surf16Patch (); } #endif // id386 D_ViewChanged (); } /* =============== R_MarkLeaves =============== */ void R_MarkLeaves (void) { 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 ; 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; node = node->parent; } while (node); } } } /* ============= R_DrawEntitiesOnList ============= */ void R_DrawEntitiesOnList (void) { 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; if (!r_drawentities.value) return; for (i=0 ; i<cl_numvisedicts ; i++) { currententity = cl_visedicts[i]; if (currententity == &cl_entities[cl.viewentity]) continue; // don't draw the player 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); // 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; 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); } break; default: break; } } } /* ============= R_DrawViewModel ============= */ 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.value || r_fov_greater_than_90) return; if (cl.items & IT_INVISIBILITY) return; if (cl.stats[STAT_HEALTH] <= 0) return; currententity = &cl.viewent; if (!currententity->model) return; VectorCopy (currententity->origin, r_entorigin); VectorSubtract (r_origin, r_entorigin, modelorg); VectorCopy (vup, viewlightvec); VectorInverse (viewlightvec); j = R_LightPoint (currententity->origin); if (j < 24) j = 24; // allways give some light on gun r_viewlighting.ambientlight = j; r_viewlighting.shadelight = j; // add dynamic lights for (lnum=0 ; lnum<MAX_DLIGHTS ; lnum++) { dl = &cl_dlights[lnum]; if (!dl->radius) continue; if (!dl->radius) continue; if (dl->die < cl.time) continue; VectorSubtract (currententity->origin, dl->origin, dist); add = dl->radius - Length(dist); if (add > 0) r_viewlighting.ambientlight += add; } // clamp lighting so it doesn't overbright as much if (r_viewlighting.ambientlight > 128) r_viewlighting.ambientlight = 128; if (r_viewlighting.ambientlight + r_viewlighting.shadelight > 192) r_viewlighting.shadelight = 192 - r_viewlighting.ambientlight; r_viewlighting.plightvec = lightvec; #ifdef QUAKE2 cl.light_level = r_viewlighting.ambientlight; #endif R_AliasDrawModel (&r_viewlighting); } /* ============= R_BmodelCheckBBox ============= */ int R_BmodelCheckBBox (model_t *clmodel, float *minmaxs) { 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++) { d = DotProduct (currententity->origin, view_clipplanes[i].normal); d -= view_clipplanes[i].dist; if (d <= -clmodel->radius) return BMODEL_FULLY_CLIPPED; if (d <= clmodel->radius) clipflags |= (1<<i); } } else { for (i=0 ; i<4 ; i++) { // generate accept and reject points // FIXME: do with fast look-ups or integer tests based on the sign bit // of the floating point values pindex = pfrustum_indexes[i]; rejectpt[0] = minmaxs[pindex[0]]; rejectpt[1] = minmaxs[pindex[1]]; rejectpt[2] = minmaxs[pindex[2]]; d = DotProduct (rejectpt, view_clipplanes[i].normal); d -= view_clipplanes[i].dist; if (d <= 0) return BMODEL_FULLY_CLIPPED; acceptpt[0] = minmaxs[pindex[3+0]]; acceptpt[1] = minmaxs[pindex[3+1]]; acceptpt[2] = minmaxs[pindex[3+2]]; d = DotProduct (acceptpt, view_clipplanes[i].normal); d -= view_clipplanes[i].dist; if (d <= 0) clipflags |= (1<<i); } } return clipflags; } /* ============= R_DrawBEntitiesOnList ============= */ void R_DrawBEntitiesOnList (void) { int i, j, k, clipflags; vec3_t oldorigin; model_t *clmodel; float minmaxs[6]; if (!r_drawentities.value) return; VectorCopy (modelorg, oldorigin); insubmodel = true; r_dlightframecount = r_framecount; for (i=0 ; i<cl_numvisedicts ; i++) { currententity = cl_visedicts[i]; switch (currententity->model->type) { case mod_brush: 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] + 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) { for (k=0 ; k<MAX_DLIGHTS ; k++) { if ((cl_dlights[k].die < cl.time) || (!cl_dlights[k].radius)) { continue; } R_MarkLights (&cl_dlights[k], 1<<k, clmodel->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; 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 (); } break; default: break; } } insubmodel = false; } /* ================ R_EdgeDrawing ================ */ 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]; if (auxedges) { r_edges = auxedges; } 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)); 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 surfaces--; R_SurfacePatch (); } R_BeginEdgeFrame (); if (r_dspeeds.value) { rw_time1 = Sys_FloatTime (); } R_RenderWorld (); if (r_drawculledpolys) R_ScanEdges (); // only the world can be drawn back to front with no z reads or compares, just // z writes, so have the driver turn z compares on now D_TurnZOn (); if (r_dspeeds.value) { rw_time2 = Sys_FloatTime (); db_time1 = rw_time2; } R_DrawBEntitiesOnList (); if (r_dspeeds.value) { db_time2 = Sys_FloatTime (); se_time1 = db_time2; } if (!r_dspeeds.value) { VID_UnlockBuffer (); S_ExtraUpdate (); // don't let sound get messed up if going slow VID_LockBuffer (); } if (!(r_drawpolys | r_drawculledpolys)) R_ScanEdges (); } /* ================ R_RenderView r_refdef must be set before the first call ================ */ void R_RenderView_ (void) { byte warpbuffer[WARP_WIDTH * WARP_HEIGHT]; r_warpbuffer = warpbuffer; if (r_timegraph.value || r_speeds.value || r_dspeeds.value) r_time1 = Sys_FloatTime (); R_SetupFrame (); #ifdef PASSAGES SetVisibilityByPassages (); #else 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 // while, so we don't do it globally. This also sets chop mode, and we do it // here so that setup stuff like the refresh area calculations match what's // done in screen.c Sys_LowFPPrecision (); if (!cl_entities[0].model || !cl.worldmodel) Sys_Error ("R_RenderView: NULL worldmodel"); if (!r_dspeeds.value) { VID_UnlockBuffer (); S_ExtraUpdate (); // don't let sound get messed up if going slow VID_LockBuffer (); } R_EdgeDrawing (); if (!r_dspeeds.value) { VID_UnlockBuffer (); S_ExtraUpdate (); // don't let sound get messed up if going slow VID_LockBuffer (); } if (r_dspeeds.value) { se_time2 = Sys_FloatTime (); de_time1 = se_time2; } R_DrawEntitiesOnList (); if (r_dspeeds.value) { de_time2 = Sys_FloatTime (); dv_time1 = de_time2; } R_DrawViewModel (); if (r_dspeeds.value) { dv_time2 = Sys_FloatTime (); dp_time1 = Sys_FloatTime (); } R_DrawParticles (); if (r_dspeeds.value) dp_time2 = Sys_FloatTime (); if (r_dowarp) D_WarpScreen (); V_SetContentsColor (r_viewleaf->contents); if (r_timegraph.value) R_TimeGraph (); if (r_aliasstats.value) R_PrintAliasStats (); if (r_speeds.value) R_PrintTimes (); if (r_dspeeds.value) R_PrintDSpeeds (); if (r_reportsurfout.value && r_outofsurfaces) Con_Printf ("Short %d surfaces\n", r_outofsurfaces); if (r_reportedgeout.value && r_outofedges) Con_Printf ("Short roughly %d edges\n", r_outofedges * 2 / 3); // back to high floating-point precision Sys_HighFPPrecision (); } void R_RenderView (void) { 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 ) Sys_Error ("Hunk is missaligned"); if ( (long)(&dummy) & 3 ) Sys_Error ("Stack is missaligned"); if ( (long)(&r_warpbuffer) & 3 ) Sys_Error ("Globals are missaligned"); R_RenderView_ (); } /* ================ R_InitTurb ================ */ void R_InitTurb (void) { int i; for (i=0 ; i<(SIN_BUFFER_SIZE) ; i++) { sintable[i] = AMP + sin(i*3.14159*2/CYCLE)*AMP; intsintable[i] = AMP2 + sin(i*3.14159*2/CYCLE)*AMP2; // AMP2, not 20 } }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_misc.c #include "quakedef.h" #include "r_local.h" /* =============== R_CheckVariables =============== */ void R_CheckVariables (void) { static float oldbright; if (r_fullbright.value != oldbright) { oldbright = r_fullbright.value; D_FlushCaches (); // so all lighting changes } } /* ============ Show Debugging use ============ */ void Show (void) { vrect_t vr; vr.x = vr.y = 0; vr.width = vid.width; vr.height = vid.height; vr.pnext = NULL; VID_Update (&vr); } /* ==================== R_TimeRefresh_f For program optimization ==================== */ void R_TimeRefresh_f (void) { int i; float start, stop, time; int startangle; vrect_t vr; startangle = r_refdef.viewangles[1]; start = Sys_FloatTime (); for (i=0 ; i<128 ; i++) { r_refdef.viewangles[1] = i/128.0*360.0; VID_LockBuffer (); R_RenderView (); VID_UnlockBuffer (); vr.x = r_refdef.vrect.x; vr.y = r_refdef.vrect.y; vr.width = r_refdef.vrect.width; vr.height = r_refdef.vrect.height; vr.pnext = NULL; VID_Update (&vr); } stop = Sys_FloatTime (); time = stop-start; Con_Printf ("%f seconds (%f fps)\n", time, 128/time); r_refdef.viewangles[1] = startangle; } /* ================ R_LineGraph Only called by R_DisplayTime ================ */ void R_LineGraph (int x, int y, int h) { int i; byte *dest; int s; // 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; s = r_graphheight.value; if (h>s) h = s; for (i=0 ; i<h ; i++, dest -= vid.rowbytes*2) { dest[0] = 0xff; *(dest-vid.rowbytes) = 0x30; } for ( ; i<s ; i++, dest -= vid.rowbytes*2) { dest[0] = 0x30; *(dest-vid.rowbytes) = 0x30; } } /* ============== R_TimeGraph Performance monitoring tool ============== */ #define MAX_TIMINGS 100 extern float mouse_x, mouse_y; void R_TimeGraph (void) { static int timex; int a; float r_time2; static byte r_timings[MAX_TIMINGS]; int x; r_time2 = Sys_FloatTime (); a = (r_time2-r_time1)/0.01; //a = fabs(mouse_y * 0.05); //a = (int)((r_refdef.vieworg[2] + 1024)/1)%(int)r_graphheight.value; //a = fabs(velocity[0])/20; //a = ((int)fabs(origin[0])/8)%20; //a = (cl.idealpitch + 30)/5; r_timings[timex] = a; a = timex; if (r_refdef.vrect.width <= MAX_TIMINGS) 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--; a--; if (a == -1) a = MAX_TIMINGS-1; } while (a != timex); timex = (timex+1)%MAX_TIMINGS; } /* ============= R_PrintTimes ============= */ void R_PrintTimes (void) { float r_time2; float ms; r_time2 = Sys_FloatTime (); ms = 1000* (r_time2 - r_time1); Con_Printf ("%5.1f ms %3i/%3i/%3i poly %3i surf\n", ms, c_faceclip, r_polycount, r_drawnpolycount, c_surf); c_surf = 0; } /* ============= R_PrintDSpeeds ============= */ void R_PrintDSpeeds (void) { float ms, dp_time, r_time2, rw_time, db_time, se_time, de_time, dv_time; r_time2 = Sys_FloatTime (); dp_time = (dp_time2 - dp_time1) * 1000; rw_time = (rw_time2 - rw_time1) * 1000; db_time = (db_time2 - db_time1) * 1000; se_time = (se_time2 - se_time1) * 1000; de_time = (de_time2 - de_time1) * 1000; dv_time = (dv_time2 - dv_time1) * 1000; ms = (r_time2 - r_time1) * 1000; Con_Printf ("%3i %4.1fp %3iw %4.1fb %3is %4.1fe %4.1fv\n", (int)ms, dp_time, (int)rw_time, db_time, (int)se_time, de_time, dv_time); } /* ============= R_PrintAliasStats ============= */ void R_PrintAliasStats (void) { Con_Printf ("%3i polygon model drawn\n", r_amodels_drawn); } void WarpPalette (void) { int i,j; byte newpalette[768]; int basecolor[3]; basecolor[0] = 130; basecolor[1] = 80; basecolor[2] = 50; // pull the colors halfway to bright brown for (i=0 ; i<256 ; i++) { for (j=0 ; j<3 ; j++) { newpalette[i*3+j] = (host_basepal[i*3+j] + basecolor[j])/2; } } VID_ShiftPalette (newpalette); } /* =================== R_TransformFrustum =================== */ void R_TransformFrustum (void) { int i; vec3_t v, v2; for (i=0 ; i<4 ; i++) { v[0] = screenedge[i].normal[2]; v[1] = -screenedge[i].normal[0]; v[2] = screenedge[i].normal[1]; v2[0] = v[1]*vright[0] + v[2]*vup[0] + v[0]*vpn[0]; v2[1] = v[1]*vright[1] + v[2]*vup[1] + v[0]*vpn[1]; v2[2] = v[1]*vright[2] + v[2]*vup[2] + v[0]*vpn[2]; VectorCopy (v2, view_clipplanes[i].normal); view_clipplanes[i].dist = DotProduct (modelorg, v2); } } #if !id386 /* ================ TransformVector ================ */ void TransformVector (vec3_t in, vec3_t out) { out[0] = DotProduct(in,vright); out[1] = DotProduct(in,vup); out[2] = DotProduct(in,vpn); } #endif /* ================ R_TransformPlane ================ */ void R_TransformPlane (mplane_t *p, float *normal, float *dist) { float d; d = DotProduct (r_origin, p->normal); *dist = p->dist - d; // TODO: when we have rotating entities, this will need to use the view matrix TransformVector (p->normal, normal); } /* =============== R_SetUpFrustumIndexes =============== */ void R_SetUpFrustumIndexes (void) { 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) { pindex[j] = j; pindex[j+3] = j+3; } else { pindex[j] = j+3; pindex[j+3] = j; } } // FIXME: do just once at start pfrustum_indexes[i] = pindex; pindex += 6; } } /* =============== R_SetupFrame =============== */ void R_SetupFrame (void) { int edgecount; vrect_t vrect; float w, h; // don't allow cheats in multiplayer if (cl.maxclients > 1) { Cvar_Set ("r_draworder", "0"); Cvar_Set ("r_fullbright", "0"); Cvar_Set ("r_ambient", "0"); Cvar_Set ("r_drawflat", "0"); } if (r_numsurfs.value) { 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); } if (r_numedges.value) { edgecount = edge_p - r_edges; if (edgecount > r_maxedgesseen) r_maxedgesseen = edgecount; Con_Printf ("Used %d of %d edges; %d max\n", edgecount, r_numallocatededges, r_maxedgesseen); } r_refdef.ambientlight = r_ambient.value; if (r_refdef.ambientlight < 0) r_refdef.ambientlight = 0; if (!sv.active) r_draworder.value = 0; // don't let cheaters look behind walls R_CheckVariables (); R_AnimateLight (); r_framecount++; numbtofpolys = 0; // debugging #if 0 r_refdef.vieworg[0]= 80; r_refdef.vieworg[1]= 64; r_refdef.vieworg[2]= 40; r_refdef.viewangles[0]= 0; r_refdef.viewangles[1]= 46.763641357; r_refdef.viewangles[2]= 0; #endif // build the transformation matrix for the given view angles VectorCopy (r_refdef.vieworg, modelorg); VectorCopy (r_refdef.vieworg, r_origin); AngleVectors (r_refdef.viewangles, vpn, vright, vup); // current viewleaf r_oldviewleaf = r_viewleaf; r_viewleaf = Mod_PointInLeaf (r_origin, cl.worldmodel); r_dowarpold = r_dowarp; r_dowarp = r_waterwarp.value && (r_viewleaf->contents <= CONTENTS_WATER); if ((r_dowarp != r_dowarpold) || r_viewchanged || lcd_x.value) { if (r_dowarp) { if ((vid.width <= vid.maxwarpwidth) && (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 { w = vid.width; h = vid.height; if (w > vid.maxwarpwidth) { h *= (float)vid.maxwarpwidth / w; w = vid.maxwarpwidth; } if (h > vid.maxwarpheight) { h = vid.maxwarpheight; w *= (float)vid.maxwarpheight / h; } vrect.x = 0; vrect.y = 0; 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)); } } else { vrect.x = 0; vrect.y = 0; vrect.width = vid.width; vrect.height = vid.height; R_ViewChanged (&vrect, sb_lines, vid.aspect); } r_viewchanged = false; } // start off with just the four screen edge clip planes R_TransformFrustum (); // save base values VectorCopy (vpn, base_vpn); VectorCopy (vright, base_vright); VectorCopy (vup, base_vup); VectorCopy (modelorg, base_modelorg); R_SetSkyFrame (); R_SetUpFrustumIndexes (); r_cache_thrash = false; // clear frame counts c_faceclip = 0; d_spanpixcount = 0; r_polycount = 0; r_drawnpolycount = 0; r_wholepolycount = 0; r_amodels_drawn = 0; r_outofsurfaces = 0; r_outofedges = 0; D_SetupFrame (); }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "quakedef.h" extern int desired_speed; extern int desired_bits; qboolean SNDDMA_Init(void) { int size; size = 16384 + sizeof(dma_t); shm = malloc (size); memset((void*)shm, 0, size); shm->buffer = (char*)shm + sizeof(dma_t); shm->channels = 2; shm->speed = desired_speed; shm->samplebits = desired_bits; shm->samples = 16384 / (desired_bits / 8); shm->submission_chunk = 1; return true; } // return the current sample position (in mono samples read) // inside the recirculating dma buffer int SNDDMA_GetDMAPos(void) { shm->samplepos = (int)(realtime*shm->speed*shm->channels) & (shm->samples-1); return shm->samplepos; } void SNDDMA_Shutdown(void) { }
C++
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // r_efrag.c #include "quakedef.h" #include "r_local.h" mnode_t *r_pefragtopnode; //=========================================================================== /* =============================================================================== ENTITY FRAGMENT FUNCTIONS =============================================================================== */ efrag_t **lastlink; vec3_t r_emins, r_emaxs; entity_t *r_addent; /* ================ R_RemoveEfrags Call when removing an object from the world or moving it to another position ================ */ void R_RemoveEfrags (entity_t *ent) { efrag_t *ef, *old, *walk, **prev; ef = ent->efrag; while (ef) { prev = &ef->leaf->efrags; while (1) { walk = *prev; if (!walk) break; if (walk == ef) { // remove this fragment *prev = ef->leafnext; break; } else prev = &walk->leafnext; } old = ef; ef = ef->entnext; // put it on the free list old->entnext = cl.free_efrags; cl.free_efrags = old; } ent->efrag = NULL; } /* =================== R_SplitEntityOnNode =================== */ void R_SplitEntityOnNode (mnode_t *node) { 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 (!r_pefragtopnode) r_pefragtopnode = node; leaf = (mleaf_t *)node; // grab an efrag off the free list ef = cl.free_efrags; if (!ef) { Con_Printf ("Too many efrags!\n"); return; // no free fragments... } cl.free_efrags = cl.free_efrags->entnext; ef->entity = r_addent; // 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 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]); } /* =================== R_SplitEntityOnNode2 =================== */ void R_SplitEntityOnNode2 (mnode_t *node) { mplane_t *splitplane; int sides; if (node->visframe != r_visframecount) return; 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 return; } splitplane = node->plane; 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]); else R_SplitEntityOnNode2 (node->children[1]); } /* =========== R_AddEfrags =========== */ void R_AddEfrags (entity_t *ent) { model_t *entmodel; int i; if (!ent->model) return; if (ent == cl_entities) return; // never add the world r_addent = ent; lastlink = &ent->efrag; r_pefragtopnode = NULL; entmodel = ent->model; for (i=0 ; i<3 ; i++) { r_emins[i] = ent->origin[i] + entmodel->mins[i]; r_emaxs[i] = ent->origin[i] + entmodel->maxs[i]; } R_SplitEntityOnNode (cl.worldmodel->nodes); ent->topnode = r_pefragtopnode; } /* ================ R_StoreEfrags // FIXME: a lot of this goes away with edge-based ================ */ void R_StoreEfrags (efrag_t **ppefrag) { entity_t *pent; model_t *clmodel; efrag_t *pefrag; 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; 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; } ppefrag = &pefrag->leafnext; break; default: Sys_Error ("R_StoreEfrags: Bad entity type %d\n", clmodel->type); } } }
C++
// LibDepthSmoother.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include <stdlib.h> #include <Windows.h> #define DllExport extern "C" __declspec(dllexport) #define MaxDepthDistance 4000 #define MinDepthDistance 800 #define MaxDepthDistanceOffset 3150 static int InnerBandThreshold = 1; static int OuterBandThreshold = 1; static inline short CalculateDistanceFromDepth(unsigned char first, unsigned char second) { // Please note that this would be different if you use Depth and User tracking rather than just depth return (first | second << 8); } static inline unsigned char CalculateIntensityFromDistance(int distance) { // This will map a distance value to a 0 - 255 range // for the purposes of applying the resulting value // to RGB pixels. int newMax = distance - MinDepthDistance; if (newMax > 0) return (unsigned char)(255 - (255 * newMax / ( MaxDepthDistanceOffset ))); else return (unsigned char)255; } DllExport void _cdecl CreateDepthArray(unsigned char * depthFrame, short * depthArray) { // When creating a depth array, it will have half the number of indexes than the original depth image // This is because the depth image uses two bytes to represent depth. These values must then be // transformed to a single value per pixel of the final image that represents depth // for purposes of smoothing prior to rendering. for (int depthImageRowIndex = 0; depthImageRowIndex < 240; depthImageRowIndex++) { for (int depthImageColumnIndex = 0; depthImageColumnIndex < 640; depthImageColumnIndex += 2) { int depthIndex = depthImageColumnIndex + (depthImageRowIndex * 640); depthArray[depthIndex / 2] = CalculateDistanceFromDepth(depthFrame[depthIndex], depthFrame[depthIndex + 1]); } } } int* filterCollection = new int[24, 3]; DllExport void _cdecl CreateFilteredDepthArray(short *depthArray, short *filteredDepthArray) { int width = 320, height = 240; // We will be using these numbers for constraints on indexes int widthBound = width - 1; int heightBound = height - 1; // Process each row for(int depthArrayRowIndex = 0; depthArrayRowIndex < height; depthArrayRowIndex++) { int x, y, innerBandCount, depthIndex, outerBandCount, row, xi, yi, xSearch, ySearch, index, depth, frequency, i; // Process each pixel in the row for (int depthArrayColumnIndex = 0; depthArrayColumnIndex < width; depthArrayColumnIndex++) { for(row = 0; row < 24; row++) { filterCollection[row, 0] = 0; filterCollection[row, 1] = 0; filterCollection[row, 2] = 0; } depthIndex = depthArrayColumnIndex + (depthArrayRowIndex * width); // We are only concerned with eliminating 'white' noise from the data. // We consider any pixel with a depth of 0 as a possible candidate for filtering. if (depthArray[depthIndex] == 0) { // From the depth index, we can determine the X and Y coordinates that the index // will appear in the image. We use this to help us define our filter matrix. x = depthIndex % width; y = (depthIndex - x) / width; // The inner and outer band counts are used later to compare against the threshold // values set in the UI to identify a positive filter result. innerBandCount = 0; outerBandCount = 0; // The following loops will loop through a 5 X 5 matrix of pixels surrounding the // candidate pixel. This defines 2 distinct 'bands' around the candidate pixel. // If any of the pixels in this matrix are non-0, we will accumulate them and count // how many non-0 pixels are in each band. If the number of non-0 pixels breaks the // threshold in either band, then the average of all non-0 pixels in the matrix is applied // to the candidate pixel. for (yi = -2; yi < 3; yi++) { for (xi = -2; xi < 3; xi++) { // yi and xi are modifiers that will be subtracted from and added to the // candidate pixel's x and y coordinates that we calculated earlier. From the // resulting coordinates, we can calculate the index to be addressed for processing. // We do not want to consider the candidate pixel (xi = 0, yi = 0) in our process at this point. // We already know that it's 0 if (xi != 0 || yi != 0) { // We then create our modified coordinates for each pass xSearch = x + xi; ySearch = y + yi; // While the modified coordinates may in fact calculate out to an actual index, it // might not be the one we want. Be sure to check to make sure that the modified coordinates // match up with our image bounds. if (xSearch >= 0 && xSearch <= widthBound && ySearch >= 0 && ySearch <= heightBound) { index = xSearch + (ySearch * width); // We only want to look for non-0 values if (depthArray[index] != 0) { // We want to find count the frequency of each depth for (i = 0; i < 24; i++) { if (filterCollection[i, 0] == depthArray[index]) { // When the depth is already in the filter collection // we will just increment the frequency. filterCollection[i, 1]++; break; } else if (filterCollection[i, 0] == 0) { // When we encounter a 0 depth in the filter collection // this means we have reached the end of values already counted. // We will then add the new depth and start it's frequency at 1. filterCollection[i, 0] = depthArray[index]; filterCollection[i, 1]++; break; } } // We will then determine which band the non-0 pixel // was found in, and increment the band counters. if (yi != 2 && yi != -2 && xi != 2 && xi != -2) innerBandCount++; else outerBandCount++; } } } } } // Once we have determined our inner and outer band non-zero counts, and accumulated all of those values, // we can compare it against the threshold to determine if our candidate pixel will be changed to the // statistical mode of the non-zero surrounding pixels. if (innerBandCount >= InnerBandThreshold || outerBandCount >= OuterBandThreshold) { frequency = 0; depth = 0; // This loop will determine the statistical mode // of the surrounding pixels for assignment to // the candidate. for (i = 0; i < 24; i++) { // This means we have reached the end of our // frequency distribution and can break out of the // loop to save time. if (filterCollection[i, 0] == 0) break; if (filterCollection[i, 1] > frequency) { depth = filterCollection[i, 0]; frequency = filterCollection[i, 1]; } } filteredDepthArray[depthIndex] = depth; } } else { // If the pixel is not zero, we will keep the original depth. short tmp = depthArray[depthIndex]; filteredDepthArray[depthIndex] = tmp; } } } } DllExport void _cdecl SetParams(int innerBand, int outerBand) { InnerBandThreshold = innerBand; OuterBandThreshold = outerBand; }
C++
// stdafx.cpp : source file that includes just the standard includes // LibDepthSmoother.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
C++
// dllmain.cpp : Defines the entry point for the DLL application. #include "stdafx.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
C++
// list.cc // Routines to manage a singly-linked list of integers. // // A "ListElement" is allocated for each item to be put on the // list; it is de-allocated when the item is removed. This means // we don't need to keep a "next" pointer in every object we // want to put on a list. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. extern "C" { #include <assert.h> #define ASSERT(expression) assert(expression) } #include "copyright.h" #include "list.h" const int NULL = 0; // The following class defines a "list element" -- which is // used to keep track of one item on a list. It is equivalent to a // LISP cell, with a "car" ("next") pointing to the next element on the list, // and a "cdr" ("item") containing the item on the list. // // Class defined in list.cc, because only the List class can be allocating // and accessing ListElements. class ListElement { public: ListElement(int value) { item = value; next = NULL;}; // constructor for list element ListElement *next; // next element on list, // NULL if this is the last int item; // value of this element }; //---------------------------------------------------------------------- // List::List // Initialize a list, empty to start with. // Elements can now be added to the list. //---------------------------------------------------------------------- List::List() { first = last = NULL; } //---------------------------------------------------------------------- // List::~List // Prepare a list for deallocation. If the list still contains any // ListElements, de-allocate them. //---------------------------------------------------------------------- List::~List() { while (!Empty()) (void) Remove(); // delete all the list elements } //---------------------------------------------------------------------- // List::Prepend // Put an integer on the front of the list. // // Allocate a ListElement to keep track of the integer. // If the list is empty, then this will be the only element. // Otherwise, put it at the beginning. // // "value" is the integer to be put on the list. //---------------------------------------------------------------------- void List::Prepend(int value) { ListElement *element = new ListElement(value); if (Empty()) { // list is empty first = element; last = element; } else { // else put it before first element->next = first; first = element; } } //---------------------------------------------------------------------- // List::Remove // Remove the first integer from the front of the list. // Error if nothing on the list. // // Returns: // The removed integer. //---------------------------------------------------------------------- int List::Remove() { ListElement *element = first; int value; ASSERT(!Empty()); element = first; value = first->item; if (first == last) { // list had one item, now has none first = NULL; last = NULL; } else { first = element->next; } delete element; // deallocate list element -- no longer needed return value; } //---------------------------------------------------------------------- // List::Empty // Returns TRUE if the list is empty (has no items). //---------------------------------------------------------------------- bool List::Empty() { return (first == NULL); }
C++
// inheritstack.cc // Routines for two implementions of a LIFO stack of integers, // one as an array, the other as a list. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. extern "C" { #include <assert.h> #define ASSERT(expression) assert(expression) } const bool FALSE = false; const bool TRUE = true; #include <iostream.h> #include "copyright.h" #include "list.h" #include "inheritstack.h" //---------------------------------------------------------------------- // Stack::Stack, Stack::~Stack // constructor and destructor for the Stack class; no data // to initialize! //---------------------------------------------------------------------- Stack::Stack() {} Stack::~Stack() {} // IMPLEMENTATION #1: AS AN ARRAY //---------------------------------------------------------------------- // ArrayStack::ArrayStack // The constructor for the ArrayStack class. // // "sz" -- maximum number of elements on the ArrayStack at any time //---------------------------------------------------------------------- ArrayStack::ArrayStack(int sz) : Stack() { ASSERT(sz >= 1); // Initialize the data members of the stack object. size = sz; top = 0; stack = new int[size]; // allocate an array of integers. } //---------------------------------------------------------------------- // ArrayStack::~ArrayStack // The destructor for the ArrayStack class. Just get rid of the array we // allocated in the constructor. //---------------------------------------------------------------------- ArrayStack::~ArrayStack() { delete [] stack; } //---------------------------------------------------------------------- // ArrayStack::Push // Put an integer on the top of the stack; error on overflow. // // "value" -- the value to put on the stack //---------------------------------------------------------------------- void ArrayStack::Push(int value) { ASSERT(!Full()); stack[top++] = value; } //---------------------------------------------------------------------- // ArrayStack::Pop // Remove an integer from the top of the stack, returning its value. // Error if the stack is empty. //---------------------------------------------------------------------- int ArrayStack::Pop() { ASSERT(!Empty()); return (stack[--top]); } //---------------------------------------------------------------------- // ArrayStack::Full // Return TRUE if the stack has no more room. //---------------------------------------------------------------------- bool ArrayStack::Full() { return (top == size); } //---------------------------------------------------------------------- // ArrayStack::Empty // Return TRUE if the stack has nothing on it. //---------------------------------------------------------------------- bool ArrayStack::Empty() { return (top == 0); } // IMPLEMENTATION #2: AS A LIST //---------------------------------------------------------------------- // ListStack::ListStack // The constructor for the ListStack class. //---------------------------------------------------------------------- ListStack::ListStack() : Stack() { stack = new List; // allocate an empty list of integers. } //---------------------------------------------------------------------- // ListStack::~ListStack // The destructor for the ListStack class. Just get rid of the list we // allocated in the constructor. //---------------------------------------------------------------------- ListStack::~ListStack() { delete stack; } //---------------------------------------------------------------------- // ListStack::Push // Put an integer on the top of the stack. // // "value" -- the value to put on the stack //---------------------------------------------------------------------- void ListStack::Push(int value) { stack->Prepend(value); } //---------------------------------------------------------------------- // ListStack::Pop // Remove an integer from the top of the stack, returning its value. // Error if the stack is empty. //---------------------------------------------------------------------- int ListStack::Pop() { ASSERT(!Empty()); return stack->Remove(); } //---------------------------------------------------------------------- // ListStack::Full // Return FALSE, because a liststack can never overflow //---------------------------------------------------------------------- bool ListStack::Full() { return FALSE; } //---------------------------------------------------------------------- // ListStack::Empty // Return TRUE if the stack has nothing on it. //---------------------------------------------------------------------- bool ListStack::Empty() { return stack->Empty(); } //---------------------------------------------------------------------- // Stack::SelfTest // Test our stack implementation by pushing 10 numbers onto the // stack, and then print them as it pops them off. // // Note this code is generic between the two versions -- // it doesn't matter whether this is an ArrayStack or a ListStack! // // "numToPush" is the number of items to put on the stack in the // selftest. //---------------------------------------------------------------------- void Stack::SelfTest(int numToPush) { int count = 17; // Put a bunch of stuff in the stack... for (int i = 0; i < numToPush; i++) { ASSERT(!Full()); cout << "pushing " << count << "\n"; Push(count++); } // ... and take it out again. while (!Empty()) { cout << "popping " << Pop() << "\n"; } } //---------------------------------------------------------------------- // main // Run the test code for the stack implementation. //---------------------------------------------------------------------- int main() { Stack *s1 = new ArrayStack(10); // Constructor with an argument. Stack *s2 = new ListStack(); cout << "Testing ArrayStack\n"; s1->SelfTest(10); cout << "Testing ListStack\n"; s2->SelfTest(10); delete s1; // always delete what you allocate delete s2; // always delete what you allocate return 0; }
C++
// stack.cc // Routines to implement a LIFO stack of integers. // // The stack is represented as an array; we return an error // if the caller tries to push more things onto the stack than we have // room for. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. extern "C" { #include <assert.h> #define ASSERT(expression) assert(expression) } #include <iostream.h> #include "copyright.h" #include "stack.h" //---------------------------------------------------------------------- // Stack::Stack // The constructor for the Stack class. Note that it doesn't have a // return type. // // "sz" -- maximum number of elements on the Stack at any time //---------------------------------------------------------------------- Stack::Stack(int sz) { ASSERT(sz >= 1); // Initialize the data members of the stack object. size = sz; top = 0; stack = new int[size]; // allocate an array of integers. } //---------------------------------------------------------------------- // Stack::~Stack // The destructor for the Stack class. Just get rid of the array we // allocated in the constructor. //---------------------------------------------------------------------- Stack::~Stack() { delete [] stack; } //---------------------------------------------------------------------- // Stack::Push // Put an integer on the top of the stack; error on overflow. // // "value" -- the value to put on the stack //---------------------------------------------------------------------- void Stack::Push(int value) { ASSERT(!Full()); stack[top++] = value; } //---------------------------------------------------------------------- // Stack::Pop // Remove an integer from the top of the stack, returning its value. // Error if the stack is empty. //---------------------------------------------------------------------- int Stack::Pop() { ASSERT(!Empty()); return (stack[--top]); } //---------------------------------------------------------------------- // Stack::Full // Return TRUE if the stack has no more room. //---------------------------------------------------------------------- bool Stack::Full() { return (top == size); } //---------------------------------------------------------------------- // Stack::Empty // Return TRUE if the stack has nothing on it. //---------------------------------------------------------------------- bool Stack::Empty() { return (top == 0); } //---------------------------------------------------------------------- // Stack::SelfTest // Test our stack implementation by pushing 10 numbers onto the // stack, and then print them as it pops them off. //---------------------------------------------------------------------- void Stack::SelfTest() { int count = 17; // Put a bunch of stuff in the stack... while (!Full()) { cout << "pushing " << count << "\n"; Push(count++); } // ... and take it out again. while (!Empty()) { cout << "popping " << Pop() << "\n"; } } //---------------------------------------------------------------------- // main // Run the test code for the stack implementation. //---------------------------------------------------------------------- int main() { Stack *stack = new Stack(10); // Constructor with an argument. stack->SelfTest(); delete stack; // always delete what you allocate return 0; }
C++
// templatestack.h // Data structures for a stack" -- a Last-In-First-Out list -- // of arbitrary things. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef TEMPLATESTACK_H // to prevent recursive includes #define TEMPLATESTACK_H #include "copyright.h" // The following defines the Stack class. The functions are // implemented in the file templatestack.cc. // // T is the type of the thing we want to put on the stack. template <class T> class Stack { public: Stack(int sz); // Constructor ~Stack(); // Destructor void Push(T value); // Push a T on the stack T Pop(); // Pop a T off the stack bool Full(); // Returns TRUE if the stack is full bool Empty(); // Returns TRUE if the stack is empty void SelfTest(T start); // Test whether the implementation works. private: int size; // The maximum capacity of the stack. int top; // Index of the next position to be used. T *stack; // A pointer to an array that holds the contents. }; #endif // TEMPLATESTACK_H
C++
// inheritstack.h // Data structures for a "stack" -- a Last-In-First-Out list of integers. // // We define two separate implementations of stacks, to // illustrate C++ inheritance. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef INHERITSTACK_H // to prevent recursive includes #define INHERITSTACK_H #include "copyright.h" #include "list.h" // The following defines an "abstract" stack of integers. // This class is abstract because no one is allowed to create // instances of it; instead, you make instances of the derived // classes that inherit from it. class Stack { public: virtual ~Stack(); // Destructor virtual void Push(int value) = 0; // Push an integer on the stack virtual int Pop() = 0; // Pop an integer off the stack virtual bool Full() = 0; // Returns TRUE if the stack is full virtual bool Empty() = 0; // Returns TRUE if the stack is empty void SelfTest(int numToPush); // Test whether the implementation works. // Note that the test routine is shared among // all derived classes because it shouldn't // matter to the test code which version we're using! protected: Stack(); // Constructor is protected to prevent anyone but // derived classes from calling constructor. }; // The following defines an implementation of Stack using arrays. // This is the same as the original implementation in stack.h, // except we don't need a SelfTest() because that's defined above by Stack! class ArrayStack : public Stack { public: ArrayStack(int sz); // Constructor: initialize variables, allocate space. ~ArrayStack(); // Destructor: deallocate space allocated above. void Push(int value); // Push an integer on the stack int Pop(); // Pop an integer off the stack bool Full(); // Returns TRUE if the stack is full bool Empty(); // Returns TRUE if the stack is empty private: int size; // The maximum capacity of the stack. int top; // Index of the next position to be used. int *stack; // A pointer to an array that holds the contents. }; // The following defines an implementation of Stack using lists. // // Note that a list implementation can't overflow, so we don't // need to pass a maximum size into the constructor. class ListStack : public Stack { public: ListStack(); // Constructor: initialize variables, allocate space. ~ListStack(); // Destructor: deallocate space allocated above. void Push(int value); // Push an integer on the stack int Pop(); // Pop an integer off the stack bool Full(); // Always return FALSE, this implementation never overflows bool Empty(); // Returns TRUE if the stack is empty private: List *stack; }; #endif INHERITSTACK_H
C++
// stack.h // Data structures for a "stack" -- a Last-In-First-Out list of integers. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef STACK_H // to prevent recursive includes #define STACK_H #include "copyright.h" // The following defines the Stack class. The functions are // implemented in the file stack.cc. // // The constructor (initializer) for the Stack is passed the number // of elements (integers) in the stack. class Stack { public: Stack(int sz); // Constructor: initialize variables, allocate space. ~Stack(); // Destructor: deallocate space allocated above. void Push(int value); // Push an integer on the stack, checking for overflow int Pop(); // Pop an integer off the stack, checking for underflow. bool Full(); // Returns TRUE if the stack is full, FALSE otherwise. bool Empty(); // Returns TRUE if the stack is empty, FALSE otherwise. void SelfTest(); // Test whether the implementation works. private: int size; // The maximum capacity of the stack. int top; // Index of the next position to be used. int *stack; // A pointer to an array that holds the contents. }; #endif // STACK_H
C++
// templatestack.cc // Routines to implement a LIFO stack of arbitrary things. // // The stack is represented as an array; we return an error // if the caller tries to push more things onto the stack than we have // room for. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. extern "C" { #include <assert.h> #define ASSERT(expression) assert(expression) } #include <iostream.h> #include "copyright.h" #include "templatestack.h" //---------------------------------------------------------------------- // Stack<T>::Stack // The constructor for the Stack class. Note that it doesn't have a // return type. // // "sz" -- maximum number of elements on the Stack at any time //---------------------------------------------------------------------- template <class T> Stack<T>::Stack(int sz) { ASSERT(sz >= 1); // Initialize the data members of the stack object. size = sz; top = 0; stack = new T[size]; // allocate an array of integers. } //---------------------------------------------------------------------- // Stack<T>::~Stack // The destructor for the Stack class. Just get rid of the array we // allocated in the constructor. //---------------------------------------------------------------------- template <class T> Stack<T>::~Stack() { delete [] stack; } //---------------------------------------------------------------------- // Stack<T>::Push // Put a T on the top of the stack; error on overflow. // // "value" -- the value to put on the stack //---------------------------------------------------------------------- template <class T> void Stack<T>::Push(T value) { ASSERT(!Full()); stack[top++] = value; } //---------------------------------------------------------------------- // Stack<T>::Pop // Remove a T from the top of the stack, returning its value. // Error if the stack is empty. //---------------------------------------------------------------------- template <class T> T Stack<T>::Pop() { ASSERT(!Empty()); return (stack[--top]); } //---------------------------------------------------------------------- // Stack<T>::Full // Return TRUE if the stack has no more room. //---------------------------------------------------------------------- template <class T> bool Stack<T>::Full() { return (top == size); } //---------------------------------------------------------------------- // Stack<T>::Empty // Return TRUE if the stack has nothing on it. //---------------------------------------------------------------------- template <class T> bool Stack<T>::Empty() { return (top == 0); } //---------------------------------------------------------------------- // Stack<T>::SelfTest // Test our stack implementation by pushing 10 T's onto the // stack, and then print them as it pops them off. //---------------------------------------------------------------------- template <class T> void Stack<T>::SelfTest(T start) { T count = start; // Put a bunch of stuff in the stack... while (!Full()) { cout << "pushing " << count << "\n"; Push(count++); } // ... and take it out again. while (!Empty()) { cout << "popping " << Pop() << "\n"; } } //---------------------------------------------------------------------- // main // Run the test code for the stack implementation. //---------------------------------------------------------------------- int main() { Stack<int> *s1 = new Stack<int>(10); Stack<char> *s2 = new Stack<char>(10); cout << "Testing Stack<int>\n"; s1->SelfTest(17); cout << "Testing Stack<char>\n"; s2->SelfTest('a'); delete s1; // always delete what you allocate delete s2; // always delete what you allocate return 0; }
C++
// list.h // Data structures to manage LISP-like lists. // // Copyright (c) 1992,1993,1995 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef LIST_H #define LIST_H #include "copyright.h" class ListElement; // The following class defines a "list" -- a singly linked list of // list elements, each of which contains an integer. class List { public: List(); // initialize the list ~List(); // de-allocate the list void Prepend(int value); // Put item at the beginning of the list int Remove(); // Take item off the front of the list bool Empty(); // is the list empty? void SelfTest(); private: ListElement *first; // Head of the list, NULL if list is empty ListElement *last; // Last element of list }; #endif // LIST_H
C++
/* * VMManager.cc * * Created on: Dec 28, 2009 * Author: qi * Modified by Hyper: Dec 29 2009 */ #include "system.h" #include "vmmanager.h" VirtualMemoryManager::VirtualMemoryManager() : bitMap(SWAP_SIZE) { fileSystem->Create("SWAP", PageSize * SWAP_SIZE); swapFile = fileSystem->Open("SWAP"); pageInfos = new PhysicalPageInfo[NumPhysPages]; shareInfos = new DiskPageInfo[SWAP_SIZE]; position = 0;//the clock pointer starting position } VirtualMemoryManager::~VirtualMemoryManager() { fileSystem->Remove("SWAP"); delete swapFile; delete pageInfos; delete shareInfos; } int VirtualMemoryManager::GetStoreLocation() { return bitMap.Find() * PageSize; } void VirtualMemoryManager::BackStore(char * from, int size, int location) { swapFile->WriteAt(from, size, location); } void VirtualMemoryManager::ClearSpace(AddrSpace * space) { int emptyIndex = NumPhysPages; for (int i = 0; i < NumPhysPages; i++) { if (pageInfos[i].space == space) { TranslationEntry* entry = space->GetTranslationEntry(pageInfos[i].pageTableIndex); this->ChangeRepresentee(space,pageInfos[i].pageTableIndex*PageSize); } if(pageInfos[i].space == NULL) emptyIndex=min(i,emptyIndex); } for (int i = 0; i < NumPhysPages; i++) { if (pageInfos[i].space != NULL && i > emptyIndex) { pageInfos[emptyIndex] = pageInfos[i]; pageInfos[i].space = NULL; emptyIndex++; } } for (int i = 0; i < space->GetNumPages(); i++) { TranslationEntry* entry = space->GetTranslationEntry(i); DiskPageInfo* shareInfo = shareInfos+entry->diskLoc/PageSize; shareInfo->Remove(entry); if(entry->readOnly == FALSE){ if (entry->valid == TRUE){ memManager->ClearPage(entry->physicalPage); printf("E %d: %d\n",entry->space->pcb->pid,entry->virtualPage); } bitMap.Clear(entry->diskLoc / PageSize); } } } void VirtualMemoryManager::LoadToMemory(char * to, int size, int location) { swapFile->ReadAt(to, size, location); } TranslationEntry* VirtualMemoryManager::GetTranslationEntry( PhysicalPageInfo * info) { return info->space->GetTranslationEntry(info->pageTableIndex); } /** * Choose a page and put it to the disk, and load the demanding page to the physical memory. */ void VirtualMemoryManager::ReplacePage(int vitualAddr) { TranslationEntry* entry; while (true) { PhysicalPageInfo& info = pageInfos[position];//The space group occupying the page if (info.space == NULL) { info.space = currentThread->space; info.pageTableIndex = vitualAddr / PageSize; entry = GetTranslationEntry(&pageInfos[position]); entry->physicalPage = memManager->GetPage(); break; } entry = GetTranslationEntry(&info);//The represent entry DiskPageInfo * shareInfo = &shareInfos[entry->diskLoc / PageSize]; if (entry->use == FALSE) { if (entry->dirty == TRUE){ printf("S %d: %d\n",entry->space->pcb->pid,entry->virtualPage); this->BackStore(machine->mainMemory + entry->physicalPage * PageSize, PageSize, entry->diskLoc); } else printf("E %d: %d\n",entry->space->pcb->pid,entry->virtualPage); shareInfo->MarkValid(FALSE); shareInfo->MarkUse(FALSE); info.space = currentThread->space; info.pageTableIndex = vitualAddr / PageSize; GetTranslationEntry(&info)->physicalPage = entry->physicalPage; break; } else { shareInfo->MarkUse(FALSE); IncreasePosition(); } } IncreasePosition(); LoadPage(vitualAddr); } void VirtualMemoryManager::IncreasePosition() { position = (position + 1) % NumPhysPages; } void VirtualMemoryManager::LoadPage(int virtualAddr) { TranslationEntry* entry = currentThread->space->GetTranslationEntry( virtualAddr / PageSize); this->LoadToMemory(machine->mainMemory + entry->physicalPage * PageSize, PageSize, entry->diskLoc); DiskPageInfo * shareInfo = &shareInfos[entry->diskLoc / PageSize]; shareInfo->MarkValid(TRUE); shareInfo->SetMemPage(entry->physicalPage); } void VirtualMemoryManager::ChangeRepresentee(AddrSpace* space,int virAddr){ TranslationEntry* entry = space->GetTranslationEntry(virAddr/PageSize); DiskPageInfo* shareInfo = shareInfos+entry->diskLoc/PageSize; shareInfo->Remove(entry); PhysicalPageInfo* pageInfo = NULL; for(int i=0;i<NumPhysPages;i++){ pageInfo = pageInfos+i; if(pageInfo->space == space&&pageInfo->pageTableIndex == virAddr/PageSize) break; pageInfo = NULL; } if(pageInfo == NULL) return; TranslationEntry* newRep = shareInfo->GetAt(0); if(newRep == NULL) pageInfo->space = NULL; else{ pageInfo->space = newRep->space; pageInfo->pageTableIndex = newRep->space->GetTransEntryIndex(newRep); } } DiskPageInfo * VirtualMemoryManager::GetDiskPageInfo(int index) { return &shareInfos[index]; } DiskPageInfo::DiskPageInfo() { list = new List(); } void DiskPageInfo::Add(TranslationEntry *entry) { list->Append(entry); } void DiskPageInfo::MarkValid(bool flag) { TranslationEntry *entry; for (int i = 0; i < list->Size(); i++) { entry = (TranslationEntry *) (list->GetAt(i)); entry->valid = flag; } } void DiskPageInfo::MarkUse(bool flag) { TranslationEntry *entry; for (int i = 0; i < list->Size(); i++) { entry = (TranslationEntry *) (list->GetAt(i)); entry->use = flag; } } void DiskPageInfo::Remove(TranslationEntry *entry){ list->Remove(entry); if(list->Size() == 1) ((TranslationEntry *) list->Top())->readOnly = FALSE; } TranslationEntry* DiskPageInfo::GetAt(int index){ return (TranslationEntry*)this->list->GetAt(index); } void DiskPageInfo::SetMemPage(int page){ TranslationEntry *entry; for (int i = 0; i < list->Size(); i++) { entry = (TranslationEntry *) (list->GetAt(i)); entry->physicalPage=page; } } void DiskPageInfo::MarkDirty(bool flag){ TranslationEntry *entry; for (int i = 0; i < list->Size(); i++) { entry = (TranslationEntry *) (list->GetAt(i)); entry->dirty = flag; } }
C++
/* * VMManager.h * * Created on: Dec 28, 2009 * Author: qi */ #ifndef VMMANAGER_H_ #define VMMANAGER_H_ #include "bitmap.h" #include "addrspace.h" #include "list.h" #define SWAP_SIZE 512 class PhysicalPageInfo{ public : //time AddrSpace * space; int pageTableIndex; }; class DiskPageInfo{ public : DiskPageInfo(); void Add(TranslationEntry *); void MarkValid(bool); void MarkUse(bool); void MarkDirty(bool); void Remove(TranslationEntry *); TranslationEntry* GetAt(int index); void SetMemPage(int page); private: int index; //index in the swap file List * list; }; class VirtualMemoryManager{ public: VirtualMemoryManager(); ~VirtualMemoryManager(); int GetStoreLocation(); PhysicalPageInfo* GetPageInfo(int index); void ClearSpace(AddrSpace * space); void BackStore(char * from,int size,int location); void LoadToMemory(char * to,int size,int location); void ReplacePage(int vitualAddr); void LoadPage(int vitualAddr); void IncreasePosition(); DiskPageInfo *GetDiskPageInfo(int); void ChangeRepresentee(AddrSpace* space,int virAddr); private: TranslationEntry* GetTranslationEntry(PhysicalPageInfo *); private : BitMap bitMap; OpenFile *swapFile; //the backing store PhysicalPageInfo * pageInfos; DiskPageInfo * shareInfos; int position; }; #endif /* VMMANAGER_H_ */
C++
// threadtest.cc // Simple test case for the threads assignment. // // Create two threads, and have them context switch // back and forth between themselves by calling Thread::Yield, // to illustratethe inner workings of the thread system. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #if defined(CHANGED) && defined(THREADS) #include "synch.h" #if defined(HW1_ELEVATOR) #include "synchlist.h" //---------------------------------------------------------------------- // ElevatorObj // The following class defines an "Elevator". An elevator // represented as a thread. It is controllered by using semaphores // or condition variables.] // It simulates some people, also represented by threads, use the // elevator from A floor to B floor(A and B can be the same floor in // this elevator). //---------------------------------------------------------------------- class ElevatorObj { public: ElevatorObj(int numFloor);// initialize an elevator virtual ~ElevatorObj();// Deallocate elevator void RequestAndWait(int atFloor);// recieve calling from a person void Enter(int toFloor);// A person enter the elevator // and choose the floor to go. void Exit(); // A person go out of the elevator void Run(); // Starts the elevator private: void AddToRoute(int floor); //Sets a request to the controller for the elevator int currentFloor; //Records the floor where the elevator is. SynchList* currentRoute;// A list records floor to go for the elevator // in running direction SynchList* nextRoute;// A list records floor to go for the elevator // in negative direction int* personCount; //Records total number of people and the state of the elevator Lock* lock; //Realize the semaphore Condition* eleCondition;//Records elevator stops or runs Condition* perCondition;//Records person takes action or waits for elevator }; ElevatorObj* elevator; //Creates a elevator int num=0; int out = 0; #endif #endif // testnum is set in main.cc int testnum = 1; #if defined(CHANGED) && defined(THREADS) int SharedVariable; Barrier* barrier; #ifdef HW1_SEMAPHORES Semaphore sema("SimpleThread semaphore",1); #endif #ifdef HW1_LOCKS Lock lock("SimpleThread lock"); #endif void SimpleThread(int which) { int num, val; for(num = 0; num < 5; num++) { #ifdef HW1_SEMAPHORES sema.P(); #endif #ifdef HW1_LOCKS lock.Acquire(); #endif val = SharedVariable; printf("*** thread %d sees value %d\n", which, val); currentThread->Yield(); SharedVariable = val+1; #ifdef HW1_SEMAPHORES sema.V(); #endif #ifdef HW1_LOCKS lock.Release(); #endif currentThread->Yield(); } #if defined(HW1_SEMAPHORES) || defined(HW1_LOCKS) barrier->wait(); #endif val = SharedVariable; printf("Thread %d sees final value %d\n", which, val); } #else //---------------------------------------------------------------------- // SimpleThread // Loop 5 times, yielding the CPU to another ready thread // each iteration. // // "which" is simply a number identifying the thread, for debugging // purposes. //---------------------------------------------------------------------- void SimpleThread(int which) { int num; for (num = 0; num < 5; num++) { printf("*** thread %d looped %d times\n", which, num); currentThread->Yield(); } } #endif //---------------------------------------------------------------------- // ThreadTest1 // Set up a ping-pong between two threads, by forking a thread // to call SimpleThread, and then calling SimpleThread ourselves. //---------------------------------------------------------------------- void ThreadTest1() { DEBUG('t', "Entering ThreadTest1"); Thread *t = new Thread("forked thread"); t->Fork(SimpleThread, 1); SimpleThread(0); } #if defined(CHANGED) && defined(THREADS) void ThreadTestN(int n) { DEBUG('t',"Entering ThreadTestN"); if(n < 0) { printf("n must be 0 or positive!"); return; } barrier = new Barrier(n+1); for(int i = 0; i < n;i++) { Thread *t = new Thread("forked thread"); t->Fork(SimpleThread,i+1); } SimpleThread(0); } //---------------------------------------------------------------------- // ThreadTest // Invoke a test routine. //---------------------------------------------------------------------- void ThreadTest(int n) { DEBUG('t',"Entering ThreadTest n number version"); ThreadTestN(n); } #endif //---------------------------------------------------------------------- // ThreadTest // Invoke a test routine. //---------------------------------------------------------------------- void ThreadTest() { switch (testnum) { case 1: ThreadTest1(); break; default: printf("No test specified.\n"); break; } } #if defined(THREADS) && defined(CHANGED) &&defined(HW1_LOCKS) &&defined(HW1_ELEVATOR) //---------------------------------------------------------------------- // RunElevator // Starts the elevator. //---------------------------------------------------------------------- void RunElevator(int){ elevator->Run(); } //---------------------------------------------------------------------- // Elevator // This call starts the elevator thread that serves numFloor floors. // You can expect that the function is only called once and that // the argument is greater than zero. // Floors are numbered starting from 1 to the maximum number of floors // as defined by numFloors. // // "numFloors" is an int value stored the number of floors //---------------------------------------------------------------------- void Elevator(int numFloors) { elevator = new ElevatorObj(numFloors); Thread* t = new Thread("Elevator"); t->Fork(RunElevator,0); } //---------------------------------------------------------------------- // RunPerson // Simulates a person action and prints his behaviour. // // "infoPtr" is an int value stored person id, "atFloor" and // "toFloor". //---------------------------------------------------------------------- void RunPerson(int infoPtr) { int* info = (int *)infoPtr; printf("Person %d wants to go to floor %d from floor %d. \n", info[0], info[2], info[1]); elevator->RequestAndWait(info[1]); printf("Person %d got into the elevator. \n", info[0]); elevator->Enter(info[2]); printf("Person %d got out of the elevator. \n", info[0]); elevator->Exit(); delete info; #ifdef ELEVATOR_TEST printf("%d persons used the elevator. \nAnd %d persons reached their destination.\n", num,out); printf("The elevator operated normally.\n "); #endif } //---------------------------------------------------------------------- // FromTo // This creates a student/faculty thread. It wakes up the elevator // (when it is not already active), tells it the current floor // the person is on, and waits until the elevator arrives. // When the elevator arrives, it tells it which floor to go to. // The elevator is amazingly fast, but it is not instantaneous // - it takes 100 ticks to go from one floor to the next. // There's only one elevator and more than one person (there is no // upper limit ) can be in the elevator at a time. The trivial solution // of serving one person at a time and putting others on hold is not // acceptable. // // "atFloor" is an int value stored which floor a person requests. // "toFloor" is an int value stored which floor a person wants to go. //---------------------------------------------------------------------- void FromTo(int atFloor, int toFloor) { num++; int* info = new int[3]; info[0] = num; info[1] = atFloor; info[2] = toFloor; Thread* t = new Thread("Person"); t->Fork(RunPerson, (int)info); } //---------------------------------------------------------------------- // ElevatorObj::RequestAndWait // Initialize an elevator //---------------------------------------------------------------------- ElevatorObj::ElevatorObj(int numFloor) { currentFloor = 1; //Set first floor as the initial floor where // the elevator is personCount = new int[numFloor + 1]; //personCount[0] is used // to store the state // (stop/run) of the elevator. for (int i = 1; i <= numFloor; i++) { personCount[i] = 0; } lock = new Lock(""); currentRoute = new SynchList(); nextRoute = new SynchList(); eleCondition = new Condition("1"); perCondition = new Condition("2"); } //---------------------------------------------------------------------- // ElevatorObj::RequestAndWait // Deallocate elevator //---------------------------------------------------------------------- ElevatorObj::~ElevatorObj() { delete personCount; delete lock; delete eleCondition; delete perCondition; delete currentRoute; delete nextRoute; } //---------------------------------------------------------------------- // ElevatorObj::RequestAndWait // Simulates the elevator recieves a calling from a person at some // floor. // If the elevator is not at the floor, the person needs to wait // and requests the elevator. If not, the person enter the elevator // directly. // // "aoFloor" is an int value recorded the floor a person requests //---------------------------------------------------------------------- void ElevatorObj::RequestAndWait(int atFloor) { lock->Acquire(); if (currentFloor == atFloor&&personCount[0] == 0) {//Enter the // elevator // directly. personCount[atFloor]++; lock->Release(); return; } AddToRoute(atFloor);// Sets the floor the elevator needs to go while (currentFloor != atFloor || personCount[0] == 1) perCondition->Wait(lock);// Waits until the elevator // is at the floor. lock->Release(); } //---------------------------------------------------------------------- // ElevatorObj::Enter // Simulates a person enter the elevator and choose the floor to go. // // "toFloor" is an int value recorded the floor a person wants to go //---------------------------------------------------------------------- void ElevatorObj::Enter(int toFloor) { lock->Acquire(); AddToRoute(toFloor);// Sets the floor the elevator needs to go personCount[currentFloor]--;// Deletes the request number if (personCount[currentFloor] == 0){ eleCondition->Signal(lock);}//Tells the elevator can move while (currentFloor != toFloor||personCount[0] == 1) perCondition->Wait(lock);// Waits until the elevator // is at the floor. lock->Release(); } //---------------------------------------------------------------------- // ElevatorObj::Exit // Simulates a person go out of the elevator. // //---------------------------------------------------------------------- void ElevatorObj::Exit() { lock->Acquire();// enforce mutual exclusive access personCount[currentFloor]--; if (personCount[currentFloor] == 0)//Tells the elevator can move eleCondition->Signal(lock); lock->Release(); } //---------------------------------------------------------------------- // ElevatorObj::AddToRoute // Sets a request to the controller for the elevator. If the floor // to go is in running direction, adds it in the currentRote list. If // not, adds it in the nextRoute. // // "floor" is an int value stored which floor a person ask to use the // elevator. //---------------------------------------------------------------------- void ElevatorObj::AddToRoute(int floor) { if(!(lock->isHeldByCurrentThread())) lock->Acquire(); // enforce mutual exclusive access int* floorPtr = new int(floor); if (currentRoute->IsEmpty()) {//No requests and add request directly currentRoute->SortedInsert(floorPtr, floor); eleCondition->Signal(lock);//The lock must have been acquired } else { int * nextFloor = (int *) currentRoute->Top();//Shows next floor // the elevator to go. if(personCount[floor] == 0) //If the floor is in the list, // needn't be inserted. if (*nextFloor < currentFloor) { //Sets when the elevator moves down. if (floor >= currentFloor) { nextRoute->SortedInsert(floorPtr, floor); } else { currentRoute->SortedInsert(floorPtr, -floor); } } else { //Sets when the elevator moves up. if (floor <= currentFloor) { nextRoute->SortedInsert(floorPtr, -floor); } else { currentRoute->SortedInsert(floorPtr, floor); } } } personCount[floor]++;// Adds a person wants to use elevator on "floor" floor if(!(lock->isHeldByCurrentThread())) lock->Release(); } //---------------------------------------------------------------------- // ElevatorObj::Run // Move the elevator. // There are two route list, one list is the current route, when current // route is done, elevator will run the next route. // When the elevator is moving, currentFloor !=nextFloor, and when it's // stopped, currentFloor = nextFloor //---------------------------------------------------------------------- void ElevatorObj::Run() { while (true) { lock->Acquire(); if (currentRoute->IsEmpty()) {//No requests and no person in, wait eleCondition->Wait(lock); personCount[0] = 1; } lock->Release(); while (!currentRoute->IsEmpty()) {//Have a floor to move to, //a person wants in or out for (int i = 0; i < 10000; i++) {//The procedure of moving currentThread->Yield(); } lock->Acquire(); int nextFloor = *((int *) currentRoute->Top());//Find next floor to move to if (currentFloor > nextFloor) {//Move down currentFloor--; } else if (currentFloor < nextFloor) {//Move up currentFloor++; } printf("Elevator arrives on floor %d.\n",currentFloor); if(currentFloor == nextFloor)//The destination { personCount[0] = 0; perCondition->Broadcast(lock);//Let people out or in eleCondition->Wait(lock);//Wait till all people in and out int* temp_ptr = (int*)currentRoute->Remove(); delete temp_ptr; personCount[0] = 1; } lock->Release(); } lock->Acquire(); //Current route is done,exchange the two list, go to next route. SynchList * temp = currentRoute; currentRoute = nextRoute; nextRoute = temp; lock->Release(); } } #endif
C++
// main.cc // Bootstrap code to initialize the operating system kernel. // // Allows direct calls into internal operating system functions, // to simplify debugging and testing. In practice, the // bootstrap code would just initialize data structures, // and start a user program to print the login prompt. // // Most of this file is not needed until later assignments. // // Usage: nachos -d <debugflags> -rs <random seed #> // -s -x <nachos file> -c <consoleIn> <consoleOut> // -f -cp <unix file> <nachos file> // -p <nachos file> -r <nachos file> -l -D -t // -n <network reliability> -m <machine id> // -o <other machine id> // -z // // -d causes certain debugging messages to be printed (cf. utility.h) // -rs causes Yield to occur at random (but repeatable) spots // -z prints the copyright message // // USER_PROGRAM // -s causes user programs to be executed in single-step mode // -x runs a user program // -c tests the console // // FILESYS // -f causes the physical disk to be formatted // -cp copies a file from UNIX to Nachos // -p prints a Nachos file to stdout // -r removes a Nachos file from the file system // -l lists the contents of the Nachos directory // -D prints the contents of the entire file system // -t tests the performance of the Nachos file system // // NETWORK // -n sets the network reliability // -m sets this machine's host id (needed for the network) // -o runs a simple test of the Nachos network software // // NOTE -- flags are ignored until the relevant assignment. // Some of the flags are interpreted here; some in system.cc. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #define MAIN #include "copyright.h" #undef MAIN #include "utility.h" #include "system.h" #ifdef THREADS extern int testnum; #include "sysdep.h" #endif // External functions used by this file #if defined(CHANGED) && defined (THREADS) extern void ThreadTest(int n); #endif extern void ThreadTest(void), Copy(char *unixFile, char *nachosFile); extern void Print(char *file), PerformanceTest(void); extern void StartProcess(char *file), ConsoleTest(char *in, char *out); extern void MailTest(int networkID); extern void Elevator(int); extern void FromTo(int, int); //---------------------------------------------------------------------- // main // Bootstrap the operating system kernel. // // Check command line arguments // Initialize data structures // (optionally) Call test procedure // // "argc" is the number of command line arguments (including the name // of the command) -- ex: "nachos -d +" -> argc = 3 // "argv" is an array of strings, one for each command line argument // ex: "nachos -d +" -> argv = {"nachos", "-d", "+"} //---------------------------------------------------------------------- int main(int argc, char **argv) { int argCount; // the number of arguments // for a particular command #ifdef CHANGED//an error of the orgin program, the DEBUG is omitted (void) Initialize(argc,argv); DEBUG('t',"Entering main"); #else DEBUG('t', "Entering main"); (void) Initialize(argc, argv); #endif #ifdef THREADS for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount) { argCount = 1; switch (argv[0][1]) { case 'q': testnum = atoi(argv[1]); argCount++; break; #ifdef CHANGED case 'i': //test simple thread after changed testnum = atoi(argv[1]); argCount++; break; #endif default: testnum = 1; break; } } #ifdef CHANGED #if defined(THREADS) && defined(HW1_LOCKS) && defined(HW1_ELEVATOR) #ifdef ELEVATOR_TEST Elevator(100); //Creates an elevator thread int m,i,j,k; for(i=1;i<=10000;i++) //Creates 10000 people want to // go from j-th floor to k-th floor randomly { j=1+(int)(Random()%100); k=1+(int)(Random()%100); for(m = 0; m< (1+(Random()%200));m++) // Simulate some time currentThread->Yield(); // before each people wants to use the elevator FromTo(j,k); } #else Elevator(5); FromTo(1,4); FromTo(3,1); FromTo(2,4); FromTo(5,1); #endif #else ThreadTest(testnum); #endif #else ThreadTest(); #endif #endif for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount) { argCount = 1; if (!strcmp(*argv, "-z")) // print copyright printf (copyright); #ifdef USER_PROGRAM if (!strcmp(*argv, "-x")) { // run a user program ASSERT(argc > 1); StartProcess(*(argv + 1)); argCount = 2; } else if (!strcmp(*argv, "-c")) { // test the console if (argc == 1) ConsoleTest(NULL, NULL); else { ASSERT(argc > 2); ConsoleTest(*(argv + 1), *(argv + 2)); argCount = 3; } interrupt->Halt(); // once we start the console, then // Nachos will loop forever waiting // for console input } #endif // USER_PROGRAM #ifdef FILESYS if (!strcmp(*argv, "-cp")) { // copy from UNIX to Nachos ASSERT(argc > 2); Copy(*(argv + 1), *(argv + 2)); argCount = 3; } else if (!strcmp(*argv, "-p")) { // print a Nachos file ASSERT(argc > 1); Print(*(argv + 1)); argCount = 2; } else if (!strcmp(*argv, "-r")) { // remove Nachos file ASSERT(argc > 1); fileSystem->Remove(*(argv + 1)); argCount = 2; } else if (!strcmp(*argv, "-l")) { // list Nachos directory fileSystem->List(); } else if (!strcmp(*argv, "-D")) { // print entire filesystem fileSystem->Print(); } else if (!strcmp(*argv, "-t")) { // performance test PerformanceTest(); } #endif // FILESYS #ifdef NETWORK if (!strcmp(*argv, "-o")) { ASSERT(argc > 1); Delay(2); // delay for 2 seconds // to give the user time to // start up another nachos MailTest(atoi(*(argv + 1))); argCount = 2; } #endif // NETWORK } currentThread->Finish(); // NOTE: if the procedure "main" // returns, then the program "nachos" // will exit (as any other normal program // would). But there may be other // threads on the ready list. We switch // to those threads by saying that the // "main" thread is finished, preventing // it from returning. return(0); // Not reached... }
C++
// list.cc // // Routines to manage a singly-linked list of "things". // // A "ListElement" is allocated for each item to be put on the // list; it is de-allocated when the item is removed. This means // we don't need to keep a "next" pointer in every object we // want to put on a list. // // NOTE: Mutual exclusion must be provided by the caller. // If you want a synchronized list, you must use the routines // in synchlist.cc. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "list.h" //---------------------------------------------------------------------- // ListElement::ListElement // Initialize a list element, so it can be added somewhere on a list. // // "itemPtr" is the item to be put on the list. It can be a pointer // to anything. // "sortKey" is the priority of the item, if any. //---------------------------------------------------------------------- ListElement::ListElement(void *itemPtr, int sortKey) { item = itemPtr; key = sortKey; next = NULL; // assume we'll put it at the end of the list } //---------------------------------------------------------------------- // List::List // Initialize a list, empty to start with. // Elements can now be added to the list. //---------------------------------------------------------------------- List::List() { first = last = NULL; } //---------------------------------------------------------------------- // List::~List // Prepare a list for deallocation. If the list still contains any // ListElements, de-allocate them. However, note that we do *not* // de-allocate the "items" on the list -- this module allocates // and de-allocates the ListElements to keep track of each item, // but a given item may be on multiple lists, so we can't // de-allocate them here. //---------------------------------------------------------------------- List::~List() { while (Remove() != NULL) ; // delete all the list elements } //---------------------------------------------------------------------- // List::Append // Append an "item" to the end of the list. // // Allocate a ListElement to keep track of the item. // If the list is empty, then this will be the only element. // Otherwise, put it at the end. // // "item" is the thing to put on the list, it can be a pointer to // anything. //---------------------------------------------------------------------- void List::Append(void *item) { ListElement *element = new ListElement(item, 0); if (IsEmpty()) { // list is empty first = element; last = element; } else { // else put it after last last->next = element; last = element; } } //---------------------------------------------------------------------- // List::Prepend // Put an "item" on the front of the list. // // Allocate a ListElement to keep track of the item. // If the list is empty, then this will be the only element. // Otherwise, put it at the beginning. // // "item" is the thing to put on the list, it can be a pointer to // anything. //---------------------------------------------------------------------- void List::Prepend(void *item) { ListElement *element = new ListElement(item, 0); if (IsEmpty()) { // list is empty first = element; last = element; } else { // else put it before first element->next = first; first = element; } } //---------------------------------------------------------------------- // List::Remove // Remove the first "item" from the front of the list. // // Returns: // Pointer to removed item, NULL if nothing on the list. //---------------------------------------------------------------------- void * List::Remove() { return SortedRemove(NULL); // Same as SortedRemove, but ignore the key } //---------------------------------------------------------------------- // List::Mapcar // Apply a function to each item on the list, by walking through // the list, one element at a time. // // Unlike LISP, this mapcar does not return anything! // // "func" is the procedure to apply to each element of the list. //---------------------------------------------------------------------- void List::Mapcar(VoidFunctionPtr func) { for (ListElement *ptr = first; ptr != NULL; ptr = ptr->next) { DEBUG('l', "In mapcar, about to invoke %x(%x)\n", func, ptr->item); (*func)((int)ptr->item); } } //---------------------------------------------------------------------- // List::IsEmpty // Returns TRUE if the list is empty (has no items). //---------------------------------------------------------------------- bool List::IsEmpty() { if (first == NULL) return TRUE; else return FALSE; } //---------------------------------------------------------------------- // List::SortedInsert // Insert an "item" into a list, so that the list elements are // sorted in increasing order by "sortKey". // // Allocate a ListElement to keep track of the item. // If the list is empty, then this will be the only element. // Otherwise, walk through the list, one element at a time, // to find where the new item should be placed. // // "item" is the thing to put on the list, it can be a pointer to // anything. // "sortKey" is the priority of the item. //---------------------------------------------------------------------- void List::SortedInsert(void *item, int sortKey) { ListElement *element = new ListElement(item, sortKey); ListElement *ptr; // keep track if (IsEmpty()) { // if list is empty, put first = element; last = element; } else if (sortKey < first->key) { // item goes on front of list element->next = first; first = element; } else { // look for first elt in list bigger than item for (ptr = first; ptr->next != NULL; ptr = ptr->next) { if (sortKey < ptr->next->key) { element->next = ptr->next; ptr->next = element; return; } } last->next = element; // item goes at end of list last = element; } } //---------------------------------------------------------------------- // List::SortedRemove // Remove the first "item" from the front of a sorted list. // // Returns: // Pointer to removed item, NULL if nothing on the list. // Sets *keyPtr to the priority value of the removed item // (this is needed by interrupt.cc, for instance). // // "keyPtr" is a pointer to the location in which to store the // priority of the removed item. //---------------------------------------------------------------------- void * List::SortedRemove(int *keyPtr) { ListElement *element = first; void *thing; if (IsEmpty()) return NULL; thing = first->item; if (first == last) { // list had one item, now has none first = NULL; last = NULL; } else { first = element->next; } if (keyPtr != NULL) *keyPtr = element->key; delete element; return thing; } //---------------------------------------------------------------------- // List::Top // Show the first "item" from the front of a sorted list. // // Returns: // Pointer to the first item, NULL if nothing on the list. //---------------------------------------------------------------------- void *List::Top(){ if (IsEmpty()) return NULL; else return first->item; } void * List::GetAt(int num){ int i = 0; ListElement *element = first; while(element!=NULL){ if(i==num) return element->item; element = element->next; i++; } return NULL; } int List::Size(){ int count=0; ListElement *element = first; while(element != NULL){ count++; element=element->next; } return count; } void List::Remove( void * item){ List tem; void * i = this->Remove(); while(i!=NULL){ if(i!=item) tem.Append(i); i = this->Remove(); } i = tem.Remove(); while(i!=NULL){ this->Append(i); i = tem.Remove(); } }
C++
// scheduler.cc // Routines to choose the next thread to run, and to dispatch to // that thread. // // These routines assume that interrupts are already disabled. // If interrupts are disabled, we can assume mutual exclusion // (since we are on a uniprocessor). // // NOTE: We can't use Locks to provide mutual exclusion here, since // if we needed to wait for a lock, and the lock was busy, we would // end up calling FindNextToRun(), and that would put us in an // infinite loop. // // Very simple implementation -- no priorities, straight FIFO. // Might need to be improved in later assignments. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "scheduler.h" #include "system.h" //---------------------------------------------------------------------- // Scheduler::Scheduler // Initialize the list of ready but not running threads to empty. //---------------------------------------------------------------------- Scheduler::Scheduler() { readyList = new List; } //---------------------------------------------------------------------- // Scheduler::~Scheduler // De-allocate the list of ready threads. //---------------------------------------------------------------------- Scheduler::~Scheduler() { delete readyList; } //---------------------------------------------------------------------- // Scheduler::ReadyToRun // Mark a thread as ready, but not running. // Put it on the ready list, for later scheduling onto the CPU. // // "thread" is the thread to be put on the ready list. //---------------------------------------------------------------------- void Scheduler::ReadyToRun (Thread *thread) { DEBUG('t', "Putting thread %s on ready list.\n", thread->getName()); thread->setStatus(READY); readyList->Append((void *)thread); } //---------------------------------------------------------------------- // Scheduler::FindNextToRun // Return the next thread to be scheduled onto the CPU. // If there are no ready threads, return NULL. // Side effect: // Thread is removed from the ready list. //---------------------------------------------------------------------- Thread * Scheduler::FindNextToRun () { return (Thread *)readyList->Remove(); } //---------------------------------------------------------------------- // Scheduler::Run // Dispatch the CPU to nextThread. Save the state of the old thread, // and load the state of the new thread, by calling the machine // dependent context switch routine, SWITCH. // // Note: we assume the state of the previously running thread has // already been changed from running to blocked or ready (depending). // Side effect: // The global variable currentThread becomes nextThread. // // "nextThread" is the thread to be put into the CPU. //---------------------------------------------------------------------- void Scheduler::Run (Thread *nextThread) { Thread *oldThread = currentThread; #ifdef USER_PROGRAM // ignore until running user programs if (currentThread->space != NULL) { // if this thread is a user program, currentThread->SaveUserState(); // save the user's CPU registers currentThread->space->SaveState(); } #endif oldThread->CheckOverflow(); // check if the old thread // had an undetected stack overflow currentThread = nextThread; // switch to the next thread currentThread->setStatus(RUNNING); // nextThread is now running DEBUG('t', "Switching from thread \"%s\" to thread \"%s\"\n", oldThread->getName(), nextThread->getName()); // This is a machine-dependent assembly language routine defined // in switch.s. You may have to think // a bit to figure out what happens after this, both from the point // of view of the thread and from the perspective of the "outside world". SWITCH(oldThread, nextThread); DEBUG('t', "Now in thread \"%s\"\n", currentThread->getName()); // If the old thread gave up the processor because it was finishing, // we need to delete its carcass. Note we cannot delete the thread // before now (for example, in Thread::Finish()), because up to this // point, we were still running on the old thread's stack! if (threadToBeDestroyed != NULL) { delete threadToBeDestroyed; threadToBeDestroyed = NULL; } #ifdef USER_PROGRAM if (currentThread->space != NULL) { // if there is an address space currentThread->RestoreUserState(); // to restore, do it. currentThread->space->RestoreState(); } #endif } //---------------------------------------------------------------------- // Scheduler::Print // Print the scheduler state -- in other words, the contents of // the ready list. For debugging. //---------------------------------------------------------------------- void Scheduler::Print() { printf("Ready list contents:\n"); readyList->Mapcar((VoidFunctionPtr) ThreadPrint); }
C++
// synchlist.h // Data structures for synchronized access to a list. // // Implemented by surrounding the List abstraction // with synchronization routines. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef SYNCHLIST_H #define SYNCHLIST_H #include "copyright.h" #include "list.h" #include "synch.h" // The following class defines a "synchronized list" -- a list for which: // these constraints hold: // 1. Threads trying to remove an item from a list will // wait until the list has an element on it. // 2. One thread at a time can access list data structures class SynchList { public: SynchList(); // initialize a synchronized list ~SynchList(); // de-allocate a synchronized list void Append(void *item); // append item to the end of the list, // and wake up any thread waiting in remove void *Remove(); // remove the first item from the front of // the list, waiting if the list is empty // apply function to every item in the list void Mapcar(VoidFunctionPtr func); #if defined(CHANGED) && defined(THREADS) bool IsEmpty(); // is the list empty? // Routines to put/get items on/off list in order (sorted by key) void SortedInsert(void *item, int sortKey); // Put item into list void *SortedRemove(int *keyPtr); // Remove first item from list void *Top(); // Show the first "item" from the front of a sorted // synchronized list. #endif private: List *list; // the unsynchronized list Lock *lock; // enforce mutual exclusive access to the list Condition *listEmpty; // wait in Remove if the list is empty }; #endif // SYNCHLIST_H
C++
// synch.cc // Routines for synchronizing threads. Three kinds of // synchronization routines are defined here: semaphores, locks // and condition variables (the implementation of the last two // are left to the reader). // // Any implementation of a synchronization routine needs some // primitive atomic operation. We assume Nachos is running on // a uniprocessor, and thus atomicity can be provided by // turning off interrupts. While interrupts are disabled, no // context switch can occur, and thus the current thread is guaranteed // to hold the CPU throughout, until interrupts are reenabled. // // Because some of these routines might be called with interrupts // already disabled (Semaphore::V for one), instead of turning // on interrupts at the end of the atomic operation, we always simply // re-set the interrupt state back to its original value (whether // that be disabled or enabled). // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "synch.h" #include "system.h" //---------------------------------------------------------------------- // Semaphore::Semaphore // Initialize a semaphore, so that it can be used for synchronization. // // "debugName" is an arbitrary name, useful for debugging. // "initialValue" is the initial value of the semaphore. //---------------------------------------------------------------------- Semaphore::Semaphore(char* debugName, int initialValue) { name = debugName; value = initialValue; queue = new List; } //---------------------------------------------------------------------- // Semaphore::Semaphore // De-allocate semaphore, when no longer needed. Assume no one // is still waiting on the semaphore! //---------------------------------------------------------------------- Semaphore::~Semaphore() { delete queue; } //---------------------------------------------------------------------- // Semaphore::P // Wait until semaphore value > 0, then decrement. Checking the // value and decrementing must be done atomically, so we // need to disable interrupts before checking the value. // // Note that Thread::Sleep assumes that interrupts are disabled // when it is called. //---------------------------------------------------------------------- void Semaphore::P() { IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts while (value == 0) { // semaphore not available queue->Append((void *)currentThread); // so go to sleep currentThread->Sleep(); } value--; // semaphore available, // consume its value (void) interrupt->SetLevel(oldLevel); // re-enable interrupts } //---------------------------------------------------------------------- // Semaphore::V // Increment semaphore value, waking up a waiter if necessary. // As with P(), this operation must be atomic, so we need to disable // interrupts. Scheduler::ReadyToRun() assumes that threads // are disabled when it is called. //---------------------------------------------------------------------- void Semaphore::V() { Thread *thread; IntStatus oldLevel = interrupt->SetLevel(IntOff); thread = (Thread *)queue->Remove(); if (thread != NULL) // make thread ready, consuming the V immediately scheduler->ReadyToRun(thread); value++; (void) interrupt->SetLevel(oldLevel); } // Dummy functions -- so we can compile our later assignments // Note -- without a correct implementation of Condition::Wait(), // the test case in the network assignment won't work! //---------------------------------------------------------------------- // Lock::Lock // Initialize a lock, so that it can be used for synchronization. // the lock is initialized to be FREE // "debugName" is an arbitrary name, useful for debugging. //---------------------------------------------------------------------- Lock::Lock(char* debugName) { name = debugName; lockHolder = NULL; queue = new List; value = FREE; } //---------------------------------------------------------------------- // Lock::~Lock // De-allocate lock, when no longer needed. Assume no one // is still waiting on the lock! //---------------------------------------------------------------------- Lock::~Lock() { delete queue; } //---------------------------------------------------------------------- // Lock::Acquire() // wait until the lock is FREE, then set it to BUSY //---------------------------------------------------------------------- void Lock::Acquire() { IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts while (value == BUSY) { // lock is held by some thead queue->Append((void *) currentThread); // so go to sleep currentThread->Sleep(); } value = BUSY; // hold the lock lockHolder = currentThread; (void) interrupt->SetLevel(oldLevel); // re-enable interrupts } //---------------------------------------------------------------------- // Lock::Release() // set lock to be FREE, waking up a thread waiting // on the lock(if there are any) //---------------------------------------------------------------------- void Lock::Release() { if (isHeldByCurrentThread()) { // only the thread that acquired the lock can release it. value=FREE; //set the lock free lockHolder = NULL; Thread *thread; IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts thread = (Thread *) queue->Remove(); if (thread != NULL){ // make thread ready, scheduler->ReadyToRun(thread); } (void) interrupt->SetLevel(oldLevel); // re-enable interrupts } } //---------------------------------------------------------------------- // Lock::isHeldByCurrentThread() // return true if the current thread holds this lock. //---------------------------------------------------------------------- bool Lock::isHeldByCurrentThread(){ return lockHolder == currentThread; } //---------------------------------------------------------------------- // Condition::Condition //initialize condition to // "no one waiting" //---------------------------------------------------------------------- Condition::Condition(char* debugName) { this->name = debugName; queue = new List(); lock = NULL; } //---------------------------------------------------------------------- // Condition::~Condition //deallocate the condition //---------------------------------------------------------------------- Condition::~Condition() { delete queue; } //---------------------------------------------------------------------- // Condition:Wait // these are the 3 operations on // condition variables; releasing the // lock and going to sleep are // *atomic* in Wait() //---------------------------------------------------------------------- void Condition::Wait(Lock* conditionLock) { if(lock!=NULL&&lock!=conditionLock){ printf("The condition variable can't be used by two locks!"); return; } else lock = conditionLock; queue->Append(currentThread); IntStatus oldLevel = interrupt->SetLevel(IntOff); conditionLock->Release(); currentThread->Sleep(); (void) interrupt->SetLevel(oldLevel); conditionLock->Acquire(); } void Condition::Signal(Lock* conditionLock) { IntStatus oldLevel = interrupt->SetLevel(IntOff); Thread* thread = (Thread*)queue->Remove(); if(thread!=NULL) scheduler->ReadyToRun(thread); (void) interrupt->SetLevel(oldLevel); conditionLock->Release(); conditionLock->Acquire(); } void Condition::Broadcast(Lock* conditionLock) { Thread* thread; IntStatus oldLevel = interrupt->SetLevel(IntOff); while(!queue->IsEmpty()){ thread = (Thread*)queue->Remove(); if(thread!=NULL) scheduler->ReadyToRun(thread); } (void) interrupt->SetLevel(oldLevel); conditionLock->Release(); conditionLock->Acquire(); } #if defined(CHANGED) && defined(THREADS) Barrier::Barrier(int n){ this->goal = n; this->queue = new List; this->number = 0; } Barrier::~Barrier(){ delete queue; } void Barrier::wait(){ IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts number++; if (number != goal) { // semaphore not available queue->Append((void *)currentThread); // so go to sleep currentThread->Sleep(); } Thread* thread = (Thread *)queue->Remove(); if (thread != NULL) // make thread ready, consuming the V immediately {scheduler->ReadyToRun(thread); } if(queue->IsEmpty()) number = 0; (void) interrupt->SetLevel(oldLevel); // re-enable interrupts } #endif
C++
// scheduler.h // Data structures for the thread dispatcher and scheduler. // Primarily, the list of threads that are ready to run. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef SCHEDULER_H #define SCHEDULER_H #include "copyright.h" #include "list.h" #include "thread.h" // The following class defines the scheduler/dispatcher abstraction -- // the data structures and operations needed to keep track of which // thread is running, and which threads are ready but not running. class Scheduler { public: Scheduler(); // Initialize list of ready threads ~Scheduler(); // De-allocate ready list void ReadyToRun(Thread* thread); // Thread can be dispatched. Thread* FindNextToRun(); // Dequeue first thread on the ready // list, if any, and return thread. void Run(Thread* nextThread); // Cause nextThread to start running void Print(); // Print contents of ready list private: List *readyList; // queue of threads that are ready to run, // but not running }; #endif // SCHEDULER_H
C++
// synchlist.cc // Routines for synchronized access to a list. // // Implemented by surrounding the List abstraction // with synchronization routines. // // Implemented in "monitor"-style -- surround each procedure with a // lock acquire and release pair, using condition signal and wait for // synchronization. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "synchlist.h" //---------------------------------------------------------------------- // SynchList::SynchList // Allocate and initialize the data structures needed for a // synchronized list, empty to start with. // Elements can now be added to the list. //---------------------------------------------------------------------- SynchList::SynchList() { list = new List(); lock = new Lock("list lock"); listEmpty = new Condition("list empty cond"); } //---------------------------------------------------------------------- // SynchList::~SynchList // De-allocate the data structures created for synchronizing a list. //---------------------------------------------------------------------- SynchList::~SynchList() { delete list; delete lock; delete listEmpty; } //---------------------------------------------------------------------- // SynchList::Append // Append an "item" to the end of the list. Wake up anyone // waiting for an element to be appended. // // "item" is the thing to put on the list, it can be a pointer to // anything. //---------------------------------------------------------------------- void SynchList::Append(void *item) { lock->Acquire(); // enforce mutual exclusive access to the list list->Append(item); listEmpty->Signal(lock); // wake up a waiter, if any lock->Release(); } //---------------------------------------------------------------------- // SynchList::Remove // Remove an "item" from the beginning of the list. Wait if // the list is empty. // Returns: // The removed item. //---------------------------------------------------------------------- void * SynchList::Remove() { void *item; lock->Acquire(); // enforce mutual exclusion while (list->IsEmpty()) listEmpty->Wait(lock); // wait until list isn't empty item = list->Remove(); ASSERT(item != NULL); lock->Release(); return item; } //---------------------------------------------------------------------- // SynchList::Mapcar // Apply function to every item on the list. Obey mutual exclusion // constraints. // // "func" is the procedure to be applied. //---------------------------------------------------------------------- void SynchList::Mapcar(VoidFunctionPtr func) { lock->Acquire(); list->Mapcar(func); lock->Release(); } #if defined(THREADS) && defined(CHANGED) bool SynchList::IsEmpty(){ bool isEmpty; lock->Acquire(); isEmpty = list->IsEmpty(); lock->Release(); return isEmpty; } //---------------------------------------------------------------------- // SynchList::SortedInsert // Insert an "item" into a synchronized list, so that the list elements are // sorted in increasing order by "sortKey". // // "item" is the thing to put on the list, it can be a pointer to // anything. // "sortKey" is the priority of the item. //---------------------------------------------------------------------- void SynchList::SortedInsert(void *item, int sortKey){ lock->Acquire(); // enforce mutual exclusive access to the list list->SortedInsert(item,sortKey); listEmpty->Signal(lock); lock->Release(); } //---------------------------------------------------------------------- // SynchList::SortedRemove // Remove the first "item" from the front of a sorted synchronized list. // // Returns: // Pointer to removed item, NULL if nothing on the list. // Sets *keyPtr to the priority value of the removed item // (this is needed by interrupt.cc, for instance). // // "keyPtr" is a pointer to the location in which to store the // priority of the removed item. //---------------------------------------------------------------------- void* SynchList::SortedRemove(int *keyPtr){ void *item; lock->Acquire(); // enforce mutual exclusion while (list->IsEmpty()) listEmpty->Wait(lock); // wait until list isn't empty item = list->SortedRemove(keyPtr); ASSERT(item != NULL); lock->Release(); return item; } //---------------------------------------------------------------------- // List::Top // Show the first "item" from the front of a sorted synchronized list. // // Returns: // Pointer to the first item, NULL if nothing on the list. //---------------------------------------------------------------------- void* SynchList::Top(){ void *item; lock->Acquire(); // enforce mutual exclusion while (list->IsEmpty()) listEmpty->Wait(lock); // wait until list isn't empty item = list->Top(); ASSERT(item != NULL); lock->Release(); return item; } #endif
C++
// list.h // Data structures to manage LISP-like lists. // // As in LISP, a list can contain any type of data structure // as an item on the list: thread control blocks, // pending interrupts, etc. That is why each item is a "void *", // or in other words, a "pointers to anything". // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef LIST_H #define LIST_H #include "copyright.h" #include "utility.h" // The following class defines a "list element" -- which is // used to keep track of one item on a list. It is equivalent to a // LISP cell, with a "car" ("next") pointing to the next element on the list, // and a "cdr" ("item") pointing to the item on the list. // // Internal data structures kept public so that List operations can // access them directly. class ListElement { public: ListElement(void *itemPtr, int sortKey); // initialize a list element ListElement *next; // next element on list, // NULL if this is the last int key; // priority, for a sorted list void *item; // pointer to item on the list }; // The following class defines a "list" -- a singly linked list of // list elements, each of which points to a single item on the list. // // By using the "Sorted" functions, the list can be kept in sorted // in increasing order by "key" in ListElement. class List { public: List(); // initialize the list ~List(); // de-allocate the list void Prepend(void *item); // Put item at the beginning of the list void Append(void *item); // Put item at the end of the list void *Remove(); // Take item off the front of the list void Mapcar(VoidFunctionPtr func); // Apply "func" to every element // on the list bool IsEmpty(); // is the list empty? void * GetAt(int num); void Remove( void *); int Size(); // Routines to put/get items on/off list in order (sorted by key) void SortedInsert(void *item, int sortKey); // Put item into list void *SortedRemove(int *keyPtr); // Remove first item from list void *Top(); // Show the first "item" from the front of a sorted list private: ListElement *first; // Head of the list, NULL if list is empty ListElement *last; // Last element of list }; #endif // LIST_H
C++
// synch.h // Data structures for synchronizing threads. // // Three kinds of synchronization are defined here: semaphores, // locks, and condition variables. The implementation for // semaphores is given; for the latter two, only the procedure // interface is given -- they are to be implemented as part of // the first assignment. // // Note that all the synchronization objects take a "name" as // part of the initialization. This is solely for debugging purposes. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // synch.h -- synchronization primitives. #ifndef SYNCH_H #define SYNCH_H #include "copyright.h" #include "thread.h" #include "list.h" // The following class defines a "semaphore" whose value is a non-negative // integer. The semaphore has only two operations P() and V(): // // P() -- waits until value > 0, then decrement // // V() -- increment, waking up a thread waiting in P() if necessary // // Note that the interface does *not* allow a thread to read the value of // the semaphore directly -- even if you did read the value, the // only thing you would know is what the value used to be. You don't // know what the value is now, because by the time you get the value // into a register, a context switch might have occurred, // and some other thread might have called P or V, so the true value might // now be different. class Semaphore { public: Semaphore(char* debugName, int initialValue); // set initial value ~Semaphore(); // de-allocate semaphore char* getName() { return name;} // debugging assist void P(); // these are the only operations on a semaphore void V(); // they are both *atomic* private: char* name; // useful for debugging int value; // semaphore value, always >= 0 List *queue; // threads waiting in P() for the value to be > 0 }; // The following class defines a "lock". A lock can be BUSY or FREE. // There are only two operations allowed on a lock: // // Acquire -- wait until the lock is FREE, then set it to BUSY // // Release -- set lock to be FREE, waking up a thread waiting // in Acquire if necessary // // In addition, by convention, only the thread that acquired the lock // may release it. As with semaphores, you can't read the lock value // (because the value might change immediately after you read it). class Lock { const static int FREE = 1; const static int BUSY = 0; public: Lock(char* debugName); // initialize lock to be FREE ~Lock(); // deallocate lock char* getName() { return name; } // debugging assist void Acquire(); // these are the only operations on a lock void Release(); // they are both *atomic* bool isHeldByCurrentThread(); // true if the current thread // holds this lock. Useful for // checking in Release, and in // Condition variable ops below. private: char* name; Thread *lockHolder; //thread who holds the lock int value; // state of the lock List *queue; //threads waiting to process }; // The following class defines a "condition variable". A condition // variable does not have a value, but threads may be queued, waiting // on the variable. These are only operations on a condition variable: // // Wait() -- release the lock, relinquish the CPU until signaled, // then re-acquire the lock // // Signal() -- wake up a thread, if there are any waiting on // the condition // // Broadcast() -- wake up all threads waiting on the condition // // All operations on a condition variable must be made while // the current thread has acquired a lock. Indeed, all accesses // to a given condition variable must be protected by the same lock. // In other words, mutual exclusion must be enforced among threads calling // the condition variable operations. // // In Nachos, condition variables are assumed to obey *Mesa*-style // semantics. When a Signal or Broadcast wakes up another thread, // it simply puts the thread on the ready list, and it is the responsibility // of the woken thread to re-acquire the lock (this re-acquire is // taken care of within Wait()). By contrast, some define condition // variables according to *Hoare*-style semantics -- where the signalling // thread gives up control over the lock and the CPU to the woken thread, // which runs immediately and gives back control over the lock to the // signaller when the woken thread leaves the critical section. // // The consequence of using Mesa-style semantics is that some other thread // can acquire the lock, and change data structures, before the woken // thread gets a chance to run. class Condition { public: Condition(char* debugName); // initialize condition to // "no one waiting" ~Condition(); // deallocate the condition char* getName() { return (name); } void Wait(Lock *conditionLock); // these are the 3 operations on // condition variables; releasing the // lock and going to sleep are // *atomic* in Wait() void Signal(Lock *conditionLock); // conditionLock must be held by void Broadcast(Lock *conditionLock);// the currentThread for all of // these operations private: char* name; List* queue; Lock* lock; }; #if defined(CHANGED) && defined(THREADS) // The following class defines a "Barrier". A Barrier is intended // for a group of threads. // There are only one operation allowed on a Barrier: // // wait -- wait until all threads reach the barrier // class Barrier{ public: Barrier(int n);//Initialize a Barrier, so that it can be used //for synchronization. virtual ~Barrier();//deallocate the barrier void wait();//wait all threads reach the barrier private: int goal;//Record count of threads in the group int number;//Record number of thread approaching the barrier List* queue;//list for all threads }; #endif #endif // SYNCH_H
C++
// thread.h // Data structures for managing threads. A thread represents // sequential execution of code within a program. // So the state of a thread includes the program counter, // the processor registers, and the execution stack. // // Note that because we allocate a fixed size stack for each // thread, it is possible to overflow the stack -- for instance, // by recursing to too deep a level. The most common reason // for this occuring is allocating large data structures // on the stack. For instance, this will cause problems: // // void foo() { int buf[1000]; ...} // // Instead, you should allocate all data structures dynamically: // // void foo() { int *buf = new int[1000]; ...} // // // Bad things happen if you overflow the stack, and in the worst // case, the problem may not be caught explicitly. Instead, // the only symptom may be bizarre segmentation faults. (Of course, // other problems can cause seg faults, so that isn't a sure sign // that your thread stacks are too small.) // // One thing to try if you find yourself with seg faults is to // increase the size of thread stack -- ThreadStackSize. // // In this interface, forking a thread takes two steps. // We must first allocate a data structure for it: "t = new Thread". // Only then can we do the fork: "t->fork(f, arg)". // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef THREAD_H #define THREAD_H #include "copyright.h" #include "utility.h" #ifdef USER_PROGRAM #include "machine.h" #include "addrspace.h" #endif // CPU register state to be saved on context switch. // The SPARC and MIPS only need 10 registers, but the Snake needs 18. // For simplicity, this is just the max over all architectures. #define MachineStateSize 18 // Size of the thread's private execution stack. // WATCH OUT IF THIS ISN'T BIG ENOUGH!!!!! #define StackSize (4 * 1024) // in words // Thread state enum ThreadStatus { JUST_CREATED, RUNNING, READY, BLOCKED }; // external function, dummy routine whose sole job is to call Thread::Print extern void ThreadPrint(int arg); // The following class defines a "thread control block" -- which // represents a single thread of execution. // // Every thread has: // an execution stack for activation records ("stackTop" and "stack") // space to save CPU registers while not running ("machineState") // a "status" (running/ready/blocked) // // Some threads also belong to a user address space; threads // that only run in the kernel have a NULL address space. class Thread { private: // NOTE: DO NOT CHANGE the order of these first two members. // THEY MUST be in this position for SWITCH to work. int* stackTop; // the current stack pointer int machineState[MachineStateSize]; // all registers except for stackTop public: Thread(char* debugName); // initialize a Thread ~Thread(); // deallocate a Thread // NOTE -- thread being deleted // must not be running when delete // is called // basic thread operations void Fork(VoidFunctionPtr func, int arg); // Make thread run (*func)(arg) void Yield(); // Relinquish the CPU if any // other thread is runnable void Sleep(); // Put the thread to sleep and // relinquish the processor void Finish(); // The thread is done executing void CheckOverflow(); // Check if thread has // overflowed its stack void setStatus(ThreadStatus st) { status = st; } char* getName() { return (name); } void Print() { printf("%s, ", name); } private: // some of the private data for this class is listed above int* stack; // Bottom of the stack // NULL if this is the main thread // (If NULL, don't deallocate stack) ThreadStatus status; // ready, running or blocked char* name; void StackAllocate(VoidFunctionPtr func, int arg); // Allocate a stack for thread. // Used internally by Fork() #ifdef USER_PROGRAM // A thread running a user program actually has *two* sets of CPU registers -- // one for its state while executing user code, one for its state // while executing kernel code. int userRegisters[NumTotalRegs]; // user-level CPU register state public: void SaveUserState(); // save user-level register state void RestoreUserState(); // restore user-level register state AddrSpace *space; // User code this thread is running. #endif }; // Magical machine-dependent routines, defined in switch.s extern "C" { // First frame on thread execution stack; // enable interrupts // call "func" // (when func returns, if ever) call ThreadFinish() void ThreadRoot(); // Stop running oldThread and start running newThread void SWITCH(Thread *oldThread, Thread *newThread); } #endif // THREAD_H
C++
// utility.cc // Debugging routines. Allows users to control whether to // print DEBUG statements, based on a command line argument. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "utility.h" // this seems to be dependent on how the compiler is configured. // if you have problems with va_start, try both of these alternatives #ifdef HOST_SNAKE #include <stdarg.h> #else #ifdef HOST_SPARC #include <stdarg.h> #else #include "stdarg.h" #endif #endif static char *enableFlags = NULL; // controls which DEBUG messages are printed //---------------------------------------------------------------------- // DebugInit // Initialize so that only DEBUG messages with a flag in flagList // will be printed. // // If the flag is "+", we enable all DEBUG messages. // // "flagList" is a string of characters for whose DEBUG messages are // to be enabled. //---------------------------------------------------------------------- void DebugInit(char *flagList) { enableFlags = flagList; } //---------------------------------------------------------------------- // DebugIsEnabled // Return TRUE if DEBUG messages with "flag" are to be printed. //---------------------------------------------------------------------- bool DebugIsEnabled(char flag) { if (enableFlags != NULL) return (strchr(enableFlags, flag) != 0) || (strchr(enableFlags, '+') != 0); else return FALSE; } //---------------------------------------------------------------------- // DEBUG // Print a debug message, if flag is enabled. Like printf, // only with an extra argument on the front. //---------------------------------------------------------------------- void DEBUG(char flag, char *format, ...) { if (DebugIsEnabled(flag)) { va_list ap; // You will get an unused variable message here -- ignore it. va_start(ap, format); vfprintf(stdout, format, ap); va_end(ap); fflush(stdout); } }
C++
// system.cc // Nachos initialization and cleanup routines. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" // This defines *all* of the global data structures used by Nachos. // These are all initialized and de-allocated by this file. Thread *currentThread; // the thread we are running now Thread *threadToBeDestroyed; // the thread that just finished Scheduler *scheduler; // the ready list Interrupt *interrupt; // interrupt status Statistics *stats; // performance metrics Timer *timer; // the hardware timer device, // for invoking context switches #ifdef FILESYS_NEEDED FileSystem *fileSystem; #endif #ifdef FILESYS SynchDisk *synchDisk; #endif #ifdef USER_PROGRAM // requires either FILESYS or FILESYS_STUB Machine *machine; // user program memory and registers ProcessManager *pm; MemoryManager *memManager; SysOpenFileManager* fileManager; char diskBuffer[PageSize]; VirtualMemoryManager *vmmanager; /* int UserReadWrite(OpenFile *file, int size, int fileAddr, int type) { ASSERT(size<=PageSize); if (type == USER_READ) { return file->ReadAt(diskBuffer, size, fileAddr); } else if (type == USER_WRITE) { return file->WriteAt(diskBuffer, size, fileAddr); } } int ReadWrite(int virAddr, OpenFile *file, int size, int fileAddr, int type) { int bytesMoved = 0; int physicAddr; int bytesToCopy; int pageSizeLeft; if (type == USER_READ) { while (size > 0) { int toRead = min(size,PageSize); int bytes = UserReadWrite(file, toRead, fileAddr, USER_READ); int bytesCopied = 0; bytesToCopy = bytes; while (bytesToCopy > 0) { machine->Translate(virAddr, &physicAddr, bytesToCopy, FALSE); pageSizeLeft = PageSize - (physicAddr) % PageSize; int actualToCopy = min(pageSizeLeft,bytesToCopy); bcopy(diskBuffer+bytesCopied, machine->mainMemory + physicAddr, actualToCopy); bytesCopied+=actualToCopy; bytesToCopy -= actualToCopy; virAddr += actualToCopy; bytesMoved += actualToCopy; } size -= bytes; fileAddr += bytes; if (bytes < toRead) return bytesMoved; } } else if (type == USER_WRITE) { while (size > 0) { int bytesCopied = 0; bytesToCopy = min(size,PageSize); while (bytesCopied < bytesToCopy) { machine->Translate(virAddr, &physicAddr, bytesToCopy, FALSE); pageSizeLeft = PageSize - (physicAddr) % PageSize; int actualToCopy = min(pageSizeLeft,bytesToCopy-bytesCopied); bcopy(machine->mainMemory + physicAddr, diskBuffer+bytesCopied,actualToCopy); bytesCopied += actualToCopy; virAddr += actualToCopy; bytesMoved += actualToCopy; } int bytes = UserReadWrite(file, bytesToCopy, fileAddr, USER_WRITE); size -= bytes; fileAddr += bytes; if (bytes < bytesToCopy) return bytesMoved; } } return bytesMoved; } */ int ReadWrite(int virAddr, char* buffer, int size, int type) { int physicAddr; int pageSizeLeft; int bytesCopied = 0; ExceptionType exception; if (type == USER_READ) { while (size > 0) { do { exception = machine->Translate(virAddr, &physicAddr, size, FALSE); if (exception != NoException) { machine->RaiseException(exception, virAddr); } }while(exception != NoException); pageSizeLeft = PageSize - (physicAddr) % PageSize; int actualToCopy = min(pageSizeLeft,size); bcopy(buffer + bytesCopied, machine->mainMemory + physicAddr, actualToCopy); size -= actualToCopy; bytesCopied += actualToCopy; virAddr += actualToCopy; } } else if (type == USER_WRITE) { while (size > 0) { do { exception = machine->Translate(virAddr, &physicAddr, size, FALSE); if (exception != NoException) { machine->RaiseException(exception, virAddr); } }while(exception != NoException); pageSizeLeft = PageSize - (physicAddr) % PageSize; int actualToCopy = min(pageSizeLeft,size); bcopy( machine->mainMemory + physicAddr,buffer + bytesCopied,actualToCopy); size -= actualToCopy; bytesCopied += actualToCopy; virAddr += actualToCopy; } } return bytesCopied; } #endif #ifdef NETWORK PostOffice *postOffice; #endif // External definition, to allow us to take a pointer to this function extern void Cleanup(); //---------------------------------------------------------------------- // TimerInterruptHandler // Interrupt handler for the timer device. The timer device is // set up to interrupt the CPU periodically (once every TimerTicks). // This routine is called each time there is a timer interrupt, // with interrupts disabled. // // Note that instead of calling Yield() directly (which would // suspend the interrupt handler, not the interrupted thread // which is what we wanted to context switch), we set a flag // so that once the interrupt handler is done, it will appear as // if the interrupted thread called Yield at the point it is // was interrupted. // // "dummy" is because every interrupt handler takes one argument, // whether it needs it or not. //---------------------------------------------------------------------- static void TimerInterruptHandler(int dummy) { if (interrupt->getStatus() != IdleMode) interrupt->YieldOnReturn(); } //---------------------------------------------------------------------- // Initialize // Initialize Nachos global data structures. Interpret command // line arguments in order to determine flags for the initialization. // // "argc" is the number of command line arguments (including the name // of the command) -- ex: "nachos -d +" -> argc = 3 // "argv" is an array of strings, one for each command line argument // ex: "nachos -d +" -> argv = {"nachos", "-d", "+"} //---------------------------------------------------------------------- void Initialize(int argc, char **argv) { int argCount; char* debugArgs = ""; bool randomYield = FALSE; #ifdef USER_PROGRAM bool debugUserProg = FALSE; // single step user program #endif #ifdef FILESYS_NEEDED bool format = FALSE; // format disk #endif #ifdef NETWORK double rely = 1; // network reliability int netname = 0; // UNIX socket name #endif for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount) { argCount = 1; if (!strcmp(*argv, "-d")) { if (argc == 1) debugArgs = "+"; // turn on all debug flags else { debugArgs = *(argv + 1); argCount = 2; } } else if (!strcmp(*argv, "-rs")) { ASSERT(argc > 1); RandomInit(atoi(*(argv + 1))); // initialize pseudo-random // number generator randomYield = TRUE; argCount = 2; } #ifdef USER_PROGRAM if (!strcmp(*argv, "-s")) debugUserProg = TRUE; #endif #ifdef FILESYS_NEEDED if (!strcmp(*argv, "-f")) format = TRUE; #endif #ifdef NETWORK if (!strcmp(*argv, "-l")) { ASSERT(argc > 1); rely = atof(*(argv + 1)); argCount = 2; } else if (!strcmp(*argv, "-m")) { ASSERT(argc > 1); netname = atoi(*(argv + 1)); argCount = 2; } #endif } DebugInit(debugArgs); // initialize DEBUG messages stats = new Statistics(); // collect statistics interrupt = new Interrupt; // start up interrupt handling scheduler = new Scheduler(); // initialize the ready queue if (randomYield) // start the timer (if needed) timer = new Timer(TimerInterruptHandler, 0, randomYield); threadToBeDestroyed = NULL; // We didn't explicitly allocate the current thread we are running in. // But if it ever tries to give up the CPU, we better have a Thread // object to save its state. currentThread = new Thread("main"); currentThread->setStatus(RUNNING); interrupt->Enable(); CallOnUserAbort(Cleanup); // if user hits ctl-C #ifdef USER_PROGRAM machine = new Machine(debugUserProg); // this must come first pm = new ProcessManager(); memManager = new MemoryManager(); fileManager = new SysOpenFileManager(); #endif #ifdef FILESYS synchDisk = new SynchDisk("DISK"); #endif #ifdef FILESYS_NEEDED fileSystem = new FileSystem(format); #endif #ifdef NETWORK postOffice = new PostOffice(netname, rely, 10); #endif #ifdef USER_PROGRAM vmmanager = new VirtualMemoryManager(); #endif } //---------------------------------------------------------------------- // Cleanup // Nachos is halting. De-allocate global data structures. //---------------------------------------------------------------------- void Cleanup() { printf("\nCleaning up...\n"); #ifdef NETWORK delete postOffice; #endif #ifdef USER_PROGRAM delete machine; delete pm; delete memManager; delete fileManager; delete vmmanager; #endif #ifdef FILESYS_NEEDED delete fileSystem; #endif #ifdef FILESYS delete synchDisk; #endif delete timer; delete scheduler; delete interrupt; Exit(0); }
C++
// thread.cc // Routines to manage threads. There are four main operations: // // Fork -- create a thread to run a procedure concurrently // with the caller (this is done in two steps -- first // allocate the Thread object, then call Fork on it) // Finish -- called when the forked procedure finishes, to clean up // Yield -- relinquish control over the CPU to another ready thread // Sleep -- relinquish control over the CPU, but thread is now blocked. // In other words, it will not run again, until explicitly // put back on the ready queue. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "thread.h" #include "switch.h" #include "synch.h" #include "system.h" #define STACK_FENCEPOST 0xdeadbeef // this is put at the top of the // execution stack, for detecting // stack overflows //---------------------------------------------------------------------- // Thread::Thread // Initialize a thread control block, so that we can then call // Thread::Fork. // // "threadName" is an arbitrary string, useful for debugging. //---------------------------------------------------------------------- Thread::Thread(char* threadName) { name = threadName; stackTop = NULL; stack = NULL; status = JUST_CREATED; #ifdef USER_PROGRAM space = NULL; #endif } //---------------------------------------------------------------------- // Thread::~Thread // De-allocate a thread. // // NOTE: the current thread *cannot* delete itself directly, // since it is still running on the stack that we need to delete. // // NOTE: if this is the main thread, we can't delete the stack // because we didn't allocate it -- we got it automatically // as part of starting up Nachos. //---------------------------------------------------------------------- Thread::~Thread() { DEBUG('t', "Deleting thread \"%s\"\n", name); ASSERT(this != currentThread); if (stack != NULL) DeallocBoundedArray((char *) stack, StackSize * sizeof(int)); } //---------------------------------------------------------------------- // Thread::Fork // Invoke (*func)(arg), allowing caller and callee to execute // concurrently. // // NOTE: although our definition allows only a single integer argument // to be passed to the procedure, it is possible to pass multiple // arguments by making them fields of a structure, and passing a pointer // to the structure as "arg". // // Implemented as the following steps: // 1. Allocate a stack // 2. Initialize the stack so that a call to SWITCH will // cause it to run the procedure // 3. Put the thread on the ready queue // // "func" is the procedure to run concurrently. // "arg" is a single argument to be passed to the procedure. //---------------------------------------------------------------------- void Thread::Fork(VoidFunctionPtr func, int arg) { DEBUG('t', "Forking thread \"%s\" with func = 0x%x, arg = %d\n", name, (int) func, arg); StackAllocate(func, arg); IntStatus oldLevel = interrupt->SetLevel(IntOff); scheduler->ReadyToRun(this); // ReadyToRun assumes that interrupts // are disabled! (void) interrupt->SetLevel(oldLevel); } //---------------------------------------------------------------------- // Thread::CheckOverflow // Check a thread's stack to see if it has overrun the space // that has been allocated for it. If we had a smarter compiler, // we wouldn't need to worry about this, but we don't. // // NOTE: Nachos will not catch all stack overflow conditions. // In other words, your program may still crash because of an overflow. // // If you get bizarre results (such as seg faults where there is no code) // then you *may* need to increase the stack size. You can avoid stack // overflows by not putting large data structures on the stack. // Don't do this: void foo() { int bigArray[10000]; ... } //---------------------------------------------------------------------- void Thread::CheckOverflow() { if (stack != NULL) #ifdef HOST_SNAKE // Stacks grow upward on the Snakes ASSERT(stack[StackSize - 1] == STACK_FENCEPOST); #else ASSERT((int) *stack == (int) STACK_FENCEPOST); #endif } //---------------------------------------------------------------------- // Thread::Finish // Called by ThreadRoot when a thread is done executing the // forked procedure. // // NOTE: we don't immediately de-allocate the thread data structure // or the execution stack, because we're still running in the thread // and we're still on the stack! Instead, we set "threadToBeDestroyed", // so that Scheduler::Run() will call the destructor, once we're // running in the context of a different thread. // // NOTE: we disable interrupts, so that we don't get a time slice // between setting threadToBeDestroyed, and going to sleep. //---------------------------------------------------------------------- // void Thread::Finish () { (void) interrupt->SetLevel(IntOff); ASSERT(this == currentThread); DEBUG('t', "Finishing thread \"%s\"\n", getName()); threadToBeDestroyed = currentThread; Sleep(); // invokes SWITCH // not reached } //---------------------------------------------------------------------- // Thread::Yield // Relinquish the CPU if any other thread is ready to run. // If so, put the thread on the end of the ready list, so that // it will eventually be re-scheduled. // // NOTE: returns immediately if no other thread on the ready queue. // Otherwise returns when the thread eventually works its way // to the front of the ready list and gets re-scheduled. // // NOTE: we disable interrupts, so that looking at the thread // on the front of the ready list, and switching to it, can be done // atomically. On return, we re-set the interrupt level to its // original state, in case we are called with interrupts disabled. // // Similar to Thread::Sleep(), but a little different. //---------------------------------------------------------------------- void Thread::Yield () { Thread *nextThread; IntStatus oldLevel = interrupt->SetLevel(IntOff); ASSERT(this == currentThread); DEBUG('t', "Yielding thread \"%s\"\n", getName()); nextThread = scheduler->FindNextToRun(); if (nextThread != NULL) { scheduler->ReadyToRun(this); scheduler->Run(nextThread); } (void) interrupt->SetLevel(oldLevel); } //---------------------------------------------------------------------- // Thread::Sleep // Relinquish the CPU, because the current thread is blocked // waiting on a synchronization variable (Semaphore, Lock, or Condition). // Eventually, some thread will wake this thread up, and put it // back on the ready queue, so that it can be re-scheduled. // // NOTE: if there are no threads on the ready queue, that means // we have no thread to run. "Interrupt::Idle" is called // to signify that we should idle the CPU until the next I/O interrupt // occurs (the only thing that could cause a thread to become // ready to run). // // NOTE: we assume interrupts are already disabled, because it // is called from the synchronization routines which must // disable interrupts for atomicity. We need interrupts off // so that there can't be a time slice between pulling the first thread // off the ready list, and switching to it. //---------------------------------------------------------------------- void Thread::Sleep () { Thread *nextThread; ASSERT(this == currentThread); ASSERT(interrupt->getLevel() == IntOff); DEBUG('t', "Sleeping thread \"%s\"\n", getName()); status = BLOCKED; while ((nextThread = scheduler->FindNextToRun()) == NULL) interrupt->Idle(); // no one to run, wait for an interrupt scheduler->Run(nextThread); // returns when we've been signalled } //---------------------------------------------------------------------- // ThreadFinish, InterruptEnable, ThreadPrint // Dummy functions because C++ does not allow a pointer to a member // function. So in order to do this, we create a dummy C function // (which we can pass a pointer to), that then simply calls the // member function. //---------------------------------------------------------------------- static void ThreadFinish() { currentThread->Finish(); } static void InterruptEnable() { interrupt->Enable(); } void ThreadPrint(int arg){ Thread *t = (Thread *)arg; t->Print(); } //---------------------------------------------------------------------- // Thread::StackAllocate // Allocate and initialize an execution stack. The stack is // initialized with an initial stack frame for ThreadRoot, which: // enables interrupts // calls (*func)(arg) // calls Thread::Finish // // "func" is the procedure to be forked // "arg" is the parameter to be passed to the procedure //---------------------------------------------------------------------- void Thread::StackAllocate (VoidFunctionPtr func, int arg) { stack = (int *) AllocBoundedArray(StackSize * sizeof(int)); #ifdef HOST_SNAKE // HP stack works from low addresses to high addresses stackTop = stack + 16; // HP requires 64-byte frame marker stack[StackSize - 1] = STACK_FENCEPOST; #else // i386 & MIPS & SPARC stack works from high addresses to low addresses #ifdef HOST_SPARC // SPARC stack must contains at least 1 activation record to start with. stackTop = stack + StackSize - 96; #else // HOST_MIPS || HOST_i386 stackTop = stack + StackSize - 4; // -4 to be on the safe side! #ifdef HOST_i386 // the 80386 passes the return address on the stack. In order for // SWITCH() to go to ThreadRoot when we switch to this thread, the // return addres used in SWITCH() must be the starting address of // ThreadRoot. *(--stackTop) = (int)ThreadRoot; #endif #endif // HOST_SPARC *stack = STACK_FENCEPOST; #endif // HOST_SNAKE machineState[PCState] = (int) ThreadRoot; machineState[StartupPCState] = (int) InterruptEnable; machineState[InitialPCState] = (int) func; machineState[InitialArgState] = arg; machineState[WhenDonePCState] = (int) ThreadFinish; } #ifdef USER_PROGRAM #include "machine.h" //---------------------------------------------------------------------- // Thread::SaveUserState // Save the CPU state of a user program on a context switch. // // Note that a user program thread has *two* sets of CPU registers -- // one for its state while executing user code, one for its state // while executing kernel code. This routine saves the former. //---------------------------------------------------------------------- void Thread::SaveUserState() { for (int i = 0; i < NumTotalRegs; i++) userRegisters[i] = machine->ReadRegister(i); } //---------------------------------------------------------------------- // Thread::RestoreUserState // Restore the CPU state of a user program on a context switch. // // Note that a user program thread has *two* sets of CPU registers -- // one for its state while executing user code, one for its state // while executing kernel code. This routine restores the former. //---------------------------------------------------------------------- void Thread::RestoreUserState() { for (int i = 0; i < NumTotalRegs; i++) machine->WriteRegister(i, userRegisters[i]); } #endif
C++
// exception.cc // Entry point into the Nachos kernel from user programs. // There are two kinds of things that can cause control to // transfer back to here from user code: // // syscall -- The user code explicitly requests to call a procedure // in the Nachos kernel. Right now, the only function we support is // "Halt". // // exceptions -- The user code does something that the CPU can't handle. // For instance, accessing memory that doesn't exist, arithmetic errors, // etc. // // Interrupts (which can also cause control to transfer from user // code into the Nachos kernel) are handled elsewhere. #include "copyright.h" #include "system.h" #include "syscall.h" #include "list.h" const int FILE_NAME_SIZE = 128; //---------------------------------------------------------------------- // StringClone // Return copied string // // "old" is string to copy. //---------------------------------------------------------------------- char* StringClone(char* old) { char * newString = new char[FILE_NAME_SIZE]; for (int i = 0; i < FILE_NAME_SIZE; i++) { newString[i] = old[i]; if (old[i] == NULL) break; } return newString; } //---------------------------------------------------------------------- // AdjustPCRegs // Change register. //---------------------------------------------------------------------- void AdjustPCRegs() { int pc = machine->ReadRegister(PCReg); machine->WriteRegister(PrevPCReg, pc); pc = machine->ReadRegister(NextPCReg); machine->WriteRegister(PCReg, pc); machine->WriteRegister(NextPCReg, pc + 4); } //---------------------------------------------------------------------- // ReadFileName // Read file name from memory to a string // // "*fileName" is the point to file. //---------------------------------------------------------------------- void ReadFileName(char *fileName) { int pos = 0; int i; int arg1 = machine->ReadRegister(4); do { ReadWrite(arg1,fileName+pos, 1, USER_WRITE); arg1++; }while(fileName[pos++] != 0); fileName[pos]=0; } //---------------------------------------------------------------------- // HaltHandler // Halt current thread. //---------------------------------------------------------------------- void HaltHandler() { printf("System Call: %d invoked Halt\n", currentThread->space->pcb->pid); interrupt->Halt(); } //---------------------------------------------------------------------- // ForkHelper // ForkHelper is a dummy function that will copy back the machine registers, // PC and return registers saved from before the yield was performed. // // "funcAddr" is the function address. //---------------------------------------------------------------------- void ForkHelper(int funcAddr) { int* state = (int*)funcAddr; for(int i =0; i < NumTotalRegs;i++) machine->WriteRegister(i,state[i]); delete[] state; currentThread->space->RestoreState(); // load page table register machine->Run(); // jump to the user progam ASSERT(FALSE); // machine->Run never returns; } //---------------------------------------------------------------------- // ForkHandler // User-level thread operations: Fork. To allow multiple threads to run // within a user program. // Fork a thread to run a procedure in the *same* address space (virtualSpace) // as the current thread. // // Fork will create a new kernel thread and set it's AddrSpace to be a // duplicate of the CurrentThread's space. It sets then Yields(). // The new thread runs a dummy function that will copy back the // machine registers, PC and return registers saved from before the yield // was performed. // // "virtualSpace" is the CurrentThread's space. //---------------------------------------------------------------------- void ForkHandler(int virtualSpace) { int currentPid = currentThread->space->pcb->pid; printf("System Call: %d invoked Fork\n", currentPid); PCB *pcb = new PCB(); pcb->pid = pm->GetPID(); AddrSpace *space = currentThread->space->Clone(pcb); if(space==NULL){ printf("Process %d is unable to fork a new process\n",currentPid); return ; } Thread* thread = new Thread("Forked thread."); //set PCB pcb->thread = thread; pcb->status = PRUNNING; ASSERT(pcb->pid!=-1); pcb->parentPid = currentThread->space->pcb->pid; //parent ID thread->space = space; pm->AddProcessAt(pcb, pcb->pid); space->SaveState(); int* currentState = new int[NumTotalRegs]; for(int i =0; i < NumTotalRegs;i++) currentState[i] = machine->ReadRegister(i); currentState[PCReg] = virtualSpace; currentState[NextPCReg] = virtualSpace+4; printf("Process %d Fork %d: start at address 0x%X with %d pages memory\n",currentPid,pcb->pid,virtualSpace,space->GetNumPages()); thread->Fork(ForkHelper, (int)currentState); currentThread->Yield(); } //---------------------------------------------------------------------- // ExitHandler // Exit takes "status" of currently executing process. The currently // executing process is terminated. // // "status" is an integer status value as in Unix. //---------------------------------------------------------------------- void ExitHandler(int status) { printf("System Call: %d invoked Exit\n", currentThread->space->pcb->pid); printf("Process %d exists with %d\n", currentThread->space->pcb->pid,status); int pid = currentThread->space->pcb->pid; currentThread->space->pcb->status = status; pm->Broadcast(pid); delete currentThread->space; currentThread->space = NULL; pm->ClearPID(pid); currentThread->Finish(); } //---------------------------------------------------------------------- // YieldHandler // User-level thread operations: Yield. To allow multiple threads to run // within a user program. Yield the CPU to another runnable thread, // whether in this address space or not. // // Yield is used by a process executing in user mode to temporarily // relinquish the CPU to another process. //---------------------------------------------------------------------- void YieldHandler() { printf("System Call: %d invoked Yield\n", currentThread->space->pcb->pid); currentThread->Yield(); } //---------------------------------------------------------------------- // NewProcess // Create new process in register. //---------------------------------------------------------------------- void NewProcess(int arg) { currentThread->space->InitRegisters(); // set the initial register values currentThread->space->SaveState(); currentThread->space->RestoreState(); // load page table register machine->Run(); // jump to the user progam } //---------------------------------------------------------------------- // ExecHandler // Run the executable, stored in the Nachos file "filename". // Exec call spawns a new user-level thread (process), but creates a // new address space and begins executing a new program given by the // object code in the Nachos file whose name is supplied as an argument // to the call. It should return to the parent a SpaceId which can be // used to uniquely identify the newly created process. // // Return the address space identifier. // // "filename" is the name of the file stored in the Nachos //---------------------------------------------------------------------- SpaceId ExecHandler(char * filename) { printf("System Call: %d invoked Exec\n", currentThread->space->pcb->pid); printf("Exec Program: %d loading %s\n", currentThread->space->pcb->pid,filename); int spaceId; OpenFile *executable = fileSystem->Open(filename); if (executable == NULL) { printf("Unable to open file %s\n", filename); return -1; } PCB* pcb = new PCB(); pcb->pid = pm->GetPID(); AddrSpace *space; space = new AddrSpace(executable,pcb); if(!space->IsValid()){ delete space; return -1; } Thread *t = new Thread("forked process"); spaceId = pcb->pid; ASSERT(pcb->pid!=-1); pcb->status = PRUNNING; pcb->parentPid = currentThread->space->pcb->pid; pcb->thread = t; t->space = space; pm->AddProcessAt(pcb, pcb->pid); delete executable; // close file t->Fork(NewProcess, NULL); currentThread->Yield(); return spaceId; } //---------------------------------------------------------------------- // JoinHandler // Only return once the the user program "id" has finished. // Join call waits and returns only after a process with the specified ID // (supplied as an arguemnt to that call) has finished. // // Return the exit status. // // "id" is the specified ID of the process //---------------------------------------------------------------------- int JoinHandler(int id) { printf("System Call: %d invoked Join\n", currentThread->space->pcb->pid); currentThread->space->pcb->status = PBLOCKED; if(pm->GetStatus(id)<0) return pm->GetStatus(id); pm->Join(id); currentThread->space->pcb->status = PRUNNING; return pm->GetStatus(id); } //---------------------------------------------------------------------- // CreateHandler // Create a Nachos file, with "fileName". // This is a straight forward call that should simply get the fileName // from user space then use fileSystem->Create(fileName,0) to create a // new instance of an OpenFile object. // // "fileName" is the name of file to create. //---------------------------------------------------------------------- void CreateHandler(char *fileName) { printf("System Call: %d invoked Create\n", currentThread->space->pcb->pid); bool success = fileSystem->Create(fileName, 0); ASSERT(success); } //---------------------------------------------------------------------- // OpenHandler // Open the Nachos file "fileName". // This function will use an OpenFile object created previously by // fileSystem->Open(fileName). Once you have this object, check to see // if it is already open by some other process in the global array of // SysOpenFiles. If so, increment the userOpens count. If not, store // the OpenFile object in the global table at the next open slot. // // Then find an open slot in the currentThread's PCB's UserOpenFile array // and let UserOpenFile index to the global array of SysOpenFiles. Finally, // return the OpenFileID (index to PCB's UserOpenFile array) to the user. // // Note that 0 and 1 are for console input and output, respectively. // // Return an "OpenFileId" that can be used to read and write to the file. // // "fileName" is the name of file to open. //---------------------------------------------------------------------- OpenFileId OpenHandler(char *fileName) { printf("System Call: %d invoked Open\n", currentThread->space->pcb->pid); int index=0; SysOpenFile * sysFile = fileManager->Get(fileName, index); if (sysFile == NULL) { OpenFile * openFile = fileSystem->Open(fileName); if (openFile == NULL) { //printf("Unable to open file %s\n", fileName); //ASSERT(FALSE); return -1; } SysOpenFile sysFile; sysFile.file = openFile; sysFile.userOpens = 1; sysFile.fileName = StringClone(fileName); index = fileManager->Add(sysFile); } else{ sysFile->userOpens++; } UserOpenFile userFile; userFile.fileIndex = index; userFile.offset = 0; OpenFileId openFileId = currentThread->space->pcb->Add(userFile); return openFileId; } //---------------------------------------------------------------------- // CloseHandler // Close the file, we're done reading and writing to it. // // "id" is the id of the openFile //---------------------------------------------------------------------- void CloseHandler(OpenFileId id) { printf("System Call: %d invoked Close\n", currentThread->space->pcb->pid); UserOpenFile* userFile = currentThread->space->pcb->Get(id); if(userFile == NULL){ return ; } SysOpenFile * sysFile=fileManager->Get(userFile->fileIndex); sysFile->closeOne(); currentThread->space->pcb->Remove(id); } //---------------------------------------------------------------------- // ReadHandler // Read "size" bytes from the open file into "buffer". // If the open file isn't long enough, or if it is an I/O device, and // there aren't enough characters to read, return whatever is available // (for I/O devices, you should always wait until you can return at // least one character). // // Get the arguments from the user in the same way as WriteHandler(). // If the OpenFileID == ConsoleInput (syscall.h), use a routine to read // into a buffer of size 'size+1' one character at a time using getchar(). // Otherwise, grab a handle to the OpenFile object in the same way you // did for WriteHandler() and use OpenFileObject->ReadAt(myOwnBuffer,size,pos) // to put n characters into your buffer. pos is the position listed in // the UserOpenFile object that represents the place in the current file // you are writing to. With this method, you must explictly put a null byte // after the last character read. The number read is returned from ReadAt(). // // Write that buffer into the user's memory using the ReadWrite() function. // Finally, return the number of bytes written. // // Return the number of bytes actually read // // "bufferAddr" is the address of the buffer to read. // "size" is the size of bytes to read. // "id" is the id for the open file. //---------------------------------------------------------------------- int ReadHandler(int bufferAddr, int size, OpenFileId id) { printf("System Call: %d invoked Read\n", currentThread->space->pcb->pid); char *buffer = new char[size + 1]; int actualSize = size; if (id == ConsoleInput) { int count = 0; while (count < size) { buffer[count]=getchar(); count++; } } else { UserOpenFile* userFile = currentThread->space->pcb->Get(id); if(userFile == NULL) return 0; SysOpenFile * sysFile=fileManager->Get(userFile->fileIndex); actualSize = sysFile->file->ReadAt(buffer,size,userFile->offset); userFile->offset+=actualSize; } ReadWrite(bufferAddr,buffer,actualSize,USER_READ); delete[] buffer; return actualSize; } //---------------------------------------------------------------------- // WriteHandler // Write "size" bytes from "buffer" to the open file. // First you will need to get the arguments from the user by reading // registers 4-6. If the OpenFileID is == ConsoleOutput (syscall.h), // then simply printf(buffer). Otherwise, grab a handle to the OpenFile // object from the user's openfile list pointing to the global file list. // The user may not have opened that file before trying to write to it. // // Fill up a buffer created of size 'size+1' using your ReadWrite() function. // Then simply call OpenFileObject->Write(myOwnBuffer, size) // // "bufferAddr" is the address of the buffer to write. // "size" is the size of bytes to read. // "id" is the id for the open file. //---------------------------------------------------------------------- void WriteHandler(int bufferAddr, int size, OpenFileId id) { printf("System Call: %d invoked Write\n", currentThread->space->pcb->pid); char* buffer = new char[size+1]; if (id == ConsoleOutput) { ReadWrite(bufferAddr,buffer,size,USER_WRITE); buffer[size]=0; printf("%s",buffer); } else { buffer = new char[size]; int writeSize = ReadWrite(bufferAddr,buffer,size,USER_WRITE); UserOpenFile* userFile = currentThread->space->pcb->Get(id); if(userFile == NULL) return ; SysOpenFile * sysFile=fileManager->Get(userFile->fileIndex); int bytes = sysFile->file->WriteAt(buffer,size,userFile->offset); userFile->offset+=bytes; } delete[] buffer; } void PageFaultHandler() { int faultAddr = machine->ReadRegister(BadVAddrReg); vmmanager->ReplacePage(faultAddr); printf("L %d: %d -> %d\n",currentThread->space->pcb->pid,faultAddr/PageSize,currentThread->space->GetTranslationEntry(faultAddr/PageSize)->physicalPage); } void ReadOnlyHandler(){ int faultAddr = machine->ReadRegister(BadVAddrReg); vmmanager->ChangeRepresentee(currentThread->space,faultAddr); TranslationEntry* entry = currentThread->space->GetTranslationEntry(faultAddr/PageSize); printf("D %d: %d\n%",currentThread->space->pcb->pid,entry->diskLoc/PageSize); entry->diskLoc = vmmanager->GetStoreLocation(); int oriPhyPage = entry->physicalPage; vmmanager->BackStore(machine->mainMemory+entry->physicalPage*PageSize,PageSize,entry->diskLoc); vmmanager->GetDiskPageInfo(entry->diskLoc/PageSize)->Add(entry); entry->dirty = FALSE; entry->readOnly = FALSE; entry->valid = FALSE; vmmanager->ReplacePage(faultAddr); } //---------------------------------------------------------------------- // ExceptionHandler // Entry point into the Nachos kernel. Called when a user program // is executing, and either does a syscall, or generates an addressing // or arithmetic exception. // // For system calls, the following is the calling convention: // // system call code -- r2 // arg1 -- r4 // arg2 -- r5 // arg3 -- r6 // arg4 -- r7 // // The result of the system call, if any, must be put back into r2. // // And don't forget to increment the pc before returning. (Or else you'll // loop making the same system call forever! // // "which" is the kind of exception. The list of possible exceptions // are in machine.h. //---------------------------------------------------------------------- void ExceptionHandler(ExceptionType which) { int type = machine->ReadRegister(2); int arg1, arg2, arg3, result; char* fileName = new char[FILE_NAME_SIZE];// file name int pos = 0; if (which == SyscallException) { switch (type) { case SC_Halt: DEBUG('a', "Shutdown, initiated by user program.\n"); HaltHandler(); break; case SC_Fork: arg1 = machine->ReadRegister(4); ForkHandler(arg1); break; case SC_Exit: arg1 = machine->ReadRegister(4); ExitHandler(arg1); break; case SC_Exec: ReadFileName(fileName); result = ExecHandler(fileName); machine->WriteRegister(2, result); break; case SC_Yield: YieldHandler(); break; case SC_Join: arg1 = machine->ReadRegister(4); result = JoinHandler(arg1); machine->WriteRegister(2, result); break; case SC_Create: ReadFileName(fileName); CreateHandler(fileName); break; case SC_Open: ReadFileName(fileName); StringClone(fileName); result = OpenHandler(fileName); machine->WriteRegister(2, result); break; case SC_Close: arg1 = machine->ReadRegister(4); CloseHandler(arg1); break; case SC_Read: arg1 = machine->ReadRegister(4); arg2 = machine->ReadRegister(5); arg3 = machine->ReadRegister(6); result = ReadHandler(arg1, arg2, arg3); machine->WriteRegister(2, result); break; case SC_Write: arg1 = machine->ReadRegister(4); arg2 = machine->ReadRegister(5); arg3 = machine->ReadRegister(6); WriteHandler(arg1, arg2, arg3); break; default: printf("No such function.\n"); } AdjustPCRegs(); delete[] fileName; } else if (which == PageFaultException) { PageFaultHandler(); } else if(which== ReadOnlyException){ ReadOnlyHandler(); }else { printf("Unexpected user mode exception %d %d\n", which, type); ASSERT(FALSE); } }
C++
// processmanager.h // Defines PCB class -- Data structures to keep necessary information about a process, // Such as PID, parent PID, Thread*, and thread status. // // Defines ProcessManager class -- like memory manager function, return an unused process // id, clear a process id respectively by using a bitmap, store PCBs in an array of PCB*. // // Created on: 2009-12-9 // Author: hyper #ifndef PROCESSMANAGER_H_ #define PROCESSMANAGER_H_ #define MAX_PROCESS PageSize #define MAX_FILE_OPEN 25 #include "bitmap.h" #include "thread.h" #include "synch.h" #include "useropenfile.h" // Definitions thread status #define PRUNNING 2; #define PBLOCKED 3; #define GOOD 0; #define BAD 1; // The following class defines a "PCB" -- an class of procese // stored necessary information class PCB { public: int pid; // pid information int parentPid; // parent's pid information Thread* thread; // thread information int status; // the process status PCB(); // Initialize a PCB ~PCB(); // De-allocate a PCB int Add(UserOpenFile uoFile); // Add a UserOpenFile in PCB bool Remove(int fileId); // Remove a UserOpenFile by file id UserOpenFile* Get(int fileId); // Return the UserOpenFile by file id private: UserOpenFile userOpenFileTable[MAX_FILE_OPEN]; // UserOpenFile in PCB BitMap bitMap; // a BitMap for PCB methods }; // The following class defines a "ProcessManager" -- an class to manage // process like the memory manager for physical memory class ProcessManager { public: ProcessManager(); // Initialize a process manager ~ProcessManager(); // De-allocate a process manager int GetPID(); // Return an unused process id void ClearPID(int pid); // Clear a process id respectively void AddProcessAt(PCB *pcb,int pid); // Add a process with exact pid void Join(int pid); // keep track of who is waiting for who using a condition variable for each PCB void Broadcast(int pid); // Broadcast the "pid" process in Exit int GetStatus(int pid); // Get process's status by pid private: BitMap bitMap; // a BitMap for process manager methods PCB** pcbs; // an array of PCB* to store the PCBs Condition **conditions; //condition for PCBs join and exit Lock ** locks; // Lock for join and exit int pcbStatus[MAX_PROCESS]; // array of PCB's status int joinProNum[MAX_PROCESS]; // array of }; #endif /* PROCESSMANAGER_H_ */
C++
// addrspace.cc // Routines to manage address spaces (executing user programs). // // In order to run a user program, you must: // // 1. link with the -N -T 0 option // 2. run coff2noff to convert the object file to Nachos format // (Nachos object code format is essentially just a simpler // version of the UNIX executable object code format) // 3. load the NOFF file into the Nachos file system // (if you haven't implemented the file system yet, you // don't need to do this last step) // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "addrspace.h" #include "noff.h" #ifdef HOST_SPARC #include <strings.h> #endif //---------------------------------------------------------------------- // SwapHeader // Do little endian to big endian conversion on the bytes in the // object file header, in case the file was generated on a little // endian machine, and we're now running on a big endian machine. //---------------------------------------------------------------------- static void SwapHeader(NoffHeader *noffH) { noffH->noffMagic = WordToHost(noffH->noffMagic); noffH->code.size = WordToHost(noffH->code.size); noffH->code.virtualAddr = WordToHost(noffH->code.virtualAddr); noffH->code.inFileAddr = WordToHost(noffH->code.inFileAddr); noffH->initData.size = WordToHost(noffH->initData.size); noffH->initData.virtualAddr = WordToHost(noffH->initData.virtualAddr); noffH->initData.inFileAddr = WordToHost(noffH->initData.inFileAddr); noffH->uninitData.size = WordToHost(noffH->uninitData.size); noffH->uninitData.virtualAddr = WordToHost(noffH->uninitData.virtualAddr); noffH->uninitData.inFileAddr = WordToHost(noffH->uninitData.inFileAddr); } //---------------------------------------------------------------------- // AddrSpace::AddrSpace // Create an address space to run a user program. // Load the program from a file "executable", and set everything // up so that we can start executing user instructions. // // Assumes that the object code file is in NOFF format. // // First, set up the translation from program memory to physical // memory. For now, this is really simple (1:1), since we are // only uniprogramming, and we have a single unsegmented page table // // "executable" is the file containing the object code to load into memory //---------------------------------------------------------------------- AddrSpace::AddrSpace(OpenFile *executable,PCB* pcb) { this->pcb = pcb; NoffHeader noffH; unsigned int i, size; executable->ReadAt((char *) &noffH, sizeof(noffH), 0); if ((noffH.noffMagic != NOFFMAGIC) && (WordToHost(noffH.noffMagic) == NOFFMAGIC)) SwapHeader(&noffH); ASSERT(noffH.noffMagic == NOFFMAGIC); // how big is address space? size = noffH.code.size + noffH.initData.size + noffH.uninitData.size + UserStackSize; // we need to increase the size // to leave room for the stack numPages = divRoundUp(size, PageSize); size = numPages * PageSize; // to run anything too big -- // at least until we have // virtual memory DEBUG('a', "Initializing address space, num pages %d, size %d\n", numPages, size); // first, set up the translation pageTable = new TranslationEntry[numPages]; for (i = 0; i < numPages; i++) { pageTable[i].virtualPage = i; //use pages allocated by your memory manager for the physical page index pageTable[i].physicalPage = -1; pageTable[i].diskLoc = vmmanager->GetStoreLocation(); char blank[PageSize]; bzero(blank,PageSize); vmmanager->BackStore(blank,PageSize,pageTable[i].diskLoc); // zero out the address space of physical page // and the stack segment pageTable[i].valid = FALSE; pageTable[i].use = FALSE; pageTable[i].dirty = FALSE; pageTable[i].readOnly = FALSE; // if the code segment was entirely on // a separate page, we could set its // pages to be read-only printf("z %d: %d\n",pcb->pid,pageTable[i].diskLoc/PageSize); DiskPageInfo * info = vmmanager->GetDiskPageInfo(pageTable[i].diskLoc/PageSize); pageTable[i].space = this; info->Add(&pageTable[i]); } // then, copy in the code and data segments into memory if (noffH.code.size > 0) { DEBUG('a', "Initializing code segment, at 0x%x, size %d\n", noffH.code.virtualAddr, noffH.code.size); ReadFile(noffH.code.virtualAddr, executable, noffH.code.size, noffH.code.inFileAddr); // executable->ReadAt(&(machine->mainMemory[noffH.code.virtualAddr]), // noffH.code.size, noffH.code.inFileAddr); } if (noffH.initData.size > 0) { DEBUG('a', "Initializing data segment, at 0x%x, size %d\n", noffH.initData.virtualAddr, noffH.initData.size); ReadFile(noffH.initData.virtualAddr, executable, noffH.initData.size, noffH.initData.inFileAddr); // executable->ReadAt(&(machine->mainMemory[noffH.initData.virtualAddr]), // noffH.initData.size, noffH.initData.inFileAddr); } printf("Loaded Program: %d code | %d data | %d bss\n", noffH.code.size, noffH.initData.size, noffH.uninitData.size); } AddrSpace::AddrSpace() { }//Do nothing //---------------------------------------------------------------------- // AddrSpace::~AddrSpace // Dealloate an address space. Nothing for now! //---------------------------------------------------------------------- AddrSpace::~AddrSpace() { if (this->IsValid()) { vmmanager->ClearSpace(this); delete [] pageTable; delete pcb; } } //---------------------------------------------------------------------- // AddrSpace::InitRegisters // Set the initial values for the user-level register set. // // We write these directly into the "machine" registers, so // that we can immediately jump to user code. Note that these // will be saved/restored into the currentThread->userRegisters // when this thread is context switched out. //---------------------------------------------------------------------- void AddrSpace::InitRegisters() { int i; for (i = 0; i < NumTotalRegs; i++) machine->WriteRegister(i, 0); // Initial program counter -- must be location of "Start" machine->WriteRegister(PCReg, 0); // Need to also tell MIPS where next instruction is, because // of branch delay possibility machine->WriteRegister(NextPCReg, 4); // Set the stack register to the end of the address space, where we // allocated the stack; but subtract off a bit, to make sure we don't // accidentally reference off the end! machine->WriteRegister(StackReg, numPages * PageSize - 16); DEBUG('a', "Initializing stack register to %d\n", numPages * PageSize - 16); } //---------------------------------------------------------------------- // AddrSpace::SaveState // On a context switch, save any machine state, specific // to this address space, that needs saving. // // For now, nothing! //---------------------------------------------------------------------- void AddrSpace::SaveState() { } //---------------------------------------------------------------------- // AddrSpace::RestoreState // On a context switch, restore the machine state so that // this address space can run. // // For now, tell the machine where to find the page table. //---------------------------------------------------------------------- void AddrSpace::RestoreState() { machine->pageTable = pageTable; machine->pageTableSize = numPages; } //---------------------------------------------------------------------- // AddrSpace::Translate // Convert a virtual address to a physical address. It does so by breaking // the virtual address into a page table index and an offset. It then looks // up the physical page in the page table entry given by the page table // index and obtains the final physical address by combining the physical // page address with the page offset. It might help to pass a pointer to // the space you would like the physical address to be stored in as a // paramter. // // Return a boolean TRUE or FALSE depending on whether or not the virtual // address was valid. // // "virtAddr" is the virtual address to be translated. // "physAddr" is the physical address to be stored. //---------------------------------------------------------------------- bool AddrSpace::Translate(int virtAddr, int* physAddr) { int i; unsigned int vpn, offset; unsigned int pageFrame; TranslationEntry entry; DEBUG('a', "\tTranslate 0x%x: ", virtAddr); // we must have either a TLB or a page table, but not both! ASSERT(pageTable != NULL); // calculate the virtual page number, and offset within the page, // from the virtual address vpn = (unsigned) virtAddr / PageSize; offset = (unsigned) virtAddr % PageSize; if (vpn >= numPages) { DEBUG('a', "virtual page # %d too large for page table size %d!\n", virtAddr, numPages); return false; } else if (!pageTable[vpn].valid) { DEBUG('a', "virtual page # %d invalid %d!\n", virtAddr, numPages); return false; } entry = pageTable[vpn]; pageFrame = entry.physicalPage; // if the pageFrame is too big, there is something really wrong! if (pageFrame >= NumPhysPages) { DEBUG('a', "*** frame %d > %d!\n", pageFrame, NumPhysPages); return false; } //store the physical address *physAddr = pageFrame * PageSize + offset; ASSERT((*physAddr >= 0)); DEBUG('a', "phys addr = 0x%x\n", *physAddr); return true; } //---------------------------------------------------------------------- // AddrSpace::ReadFile // Load the code and data segments into the translated memory, instead // of at position 0 like the code in the AddrSpace constructor already // does. This is needed not only for Exec() but for the initial startup // of the machine when executing any test program with virtual memory. // // ReadFile tries to read "size" bytes from "file" at offset "fileAddr" // and then store them at virtual memory address beginning at "virtAddr". // Then, buffer user file reads in a disk buffer called diskBuffer // (declare it in system.h). All of user-level file I/O must go through // the diskBuffer. It will try to read as many bytes as possible. It will // also use the functions: File::ReadAt(buff,size,addr) and bcopy(src,dst,num) // as well as the memory locations at machine->mainMemory[physAddr]. // // Return the number of bytes actually read, but has // no side effects (except that Write modifies the file, of course). // // "virtAddr" is the beginning virtual address of the bytes to be read. // "file" is the file where some bytes are from. // "size" is the size of bytes need to be read. // "fileAddr" is the file address. //---------------------------------------------------------------------- int AddrSpace::ReadFile(int virtAddr, OpenFile *file, int size, int fileAddr) { char diskBuffer[size]; // store read bytes int availSize; // store the number of bytes actually read int actualSize = file->ReadAt(diskBuffer, size, fileAddr); size = actualSize; int bytesCopied = 0; int offset=0; //read bytes in the "file" while (size > 0) { int pageNum = virtAddr / PageSize; offset = virtAddr%PageSize; availSize = min(PageSize,size); vmmanager->BackStore(diskBuffer + bytesCopied, availSize, pageTable[pageNum].diskLoc+offset); size -= availSize; bytesCopied += availSize; virtAddr += availSize; } return actualSize; } //---------------------------------------------------------------------- // AddrSpace::Clone // Create a new address space that is an exact copy of the original. // Allocate additional physical memory for this copy, set up the page // tables properly for the new address space, and copy the data from // the old address space to the new. // // Return the clone space //---------------------------------------------------------------------- AddrSpace* AddrSpace::Clone(PCB *pcb) { //test if the SWAP file is enough AddrSpace* clone = new AddrSpace(); clone->pcb = pcb; clone->numPages = this->numPages; clone->pageTable = new TranslationEntry[numPages]; for (int i = 0; i < numPages; i++) { clone->pageTable[i].virtualPage = i; clone->pageTable[i].physicalPage = this->pageTable[i].physicalPage; clone->pageTable[i].valid = this->pageTable[i].valid; clone->pageTable[i].use = this->pageTable[i].use; clone->pageTable[i].dirty = this->pageTable[i].dirty; clone->pageTable[i].diskLoc = this->pageTable[i].diskLoc; clone->pageTable[i].readOnly = this->pageTable[i].readOnly = TRUE; printf("Z %d: %d\n",clone->pcb->pid,pageTable[i].diskLoc/PageSize); DiskPageInfo * info = vmmanager->GetDiskPageInfo(this->pageTable[i].diskLoc/PageSize); info->Add(&clone->pageTable[i]); clone->pageTable[i].space = clone; } return clone; } //---------------------------------------------------------------------- // AddrSpace::IsValid // Return TRUE if numPages != -1 //---------------------------------------------------------------------- bool AddrSpace::IsValid() { return numPages != -1; } //---------------------------------------------------------------------- // AddrSpace::GetNumPages // Return numPages //---------------------------------------------------------------------- int AddrSpace::GetNumPages() { return numPages; } TranslationEntry* AddrSpace::GetTranslationEntry(int pageNum) { return &pageTable[pageNum]; } int AddrSpace::GetTransEntryIndex(TranslationEntry* entry){ for(int i = 0;i < numPages;i++) if(entry==pageTable+i) return i; return -1; }
C++
// useropenfile.h // Defines UserOpenFile class contains an index into the global SysOpenFile table and // an integer offset represeting a process's current position in that file. // // Created on: Dec 10, 2009 // Author: qi #ifndef USEROPENFILE_H_ #define USEROPENFILE_H_ class UserOpenFile{ public: int fileIndex; //an index into the global SysOpenFile table int offset; //a process's current position in the pointing file. }; #endif /* USEROPENFILE_H_ */
C++
// SysOpenFile.h // Defines SysOpenFile class that contains a pointer to the file system's OpenFile object // and (char *)fileName for that file and the number of user processes currently accessing // it. Declare an array of SysOpenFile objects for use by all system calls implemented. // // Defines SysOpenFile Manager class that manage all SysOpenFile. // // Created on: Dec 10, 2009 // Author: qi #ifndef SYSOPENFILE_H_ #define SYSOPENFILE_H_ #define SOFILETABLE_SIZE 100 #include "filesys.h" #include "bitmap.h" // The following class defines a "SysOpenFile" class SysOpenFile{ public: OpenFile *file; // a pointer to the file system's OpenFile object char * fileName; // file name and the number of user processes accessing int userOpens; // Number of user processes accessing void closeOne(); //close a SysOpenFile and accessing processes void close(); //close all SysOpenFile and accessing processes }; // The following class defines a "SysOpenFileManager" class SysOpenFileManager{ public: SysOpenFileManager(); // Initialize a SysOpenFileManager ~SysOpenFileManager(); // De-allocate a SysOpenFileManager int Add(SysOpenFile newSysOpenFile); //Add a SysOpenFile to the array SysOpenFile* Get(char* fileName,int& index); // Get SysOpenFile by "fileName" SysOpenFile* Get(int index); // Get SysOpenFile by "index" of the array void closeOne(int index); // Close a SysOpenFile by "index" private: SysOpenFile sysOpenFileTable[SOFILETABLE_SIZE]; // array for all SysOpenFile BitMap bitMap; // a BitMap for SysOpenFile manager methods }; #endif /* SYSOPENFILE_H_ */
C++
// memorymanager.h // Methods defining in Memory Manager that will be used to facilitate contiguous virtual memory. // The amount of memory available to the user space is the same as the amount // of physical memory. // // Memory Manager allocates the first clear page, takes the index of a page // and frees it, and get the number of clear pages. // // Created on: 2009-12-7 // Author: hyper #ifndef MEMORYMANAGER_H_ #define MEMORYMANAGER_H_ #include "bitmap.h" // The following class defines a "Memory Manager", // which can allocate the first clear page, take the index of a page // and free it, and get the number of clear pages by using a bitmap (in code/userprog/bitmap.*) // with one bit per page to track allocation. class MemoryManager { private: BitMap bitMap; // a BitMap for memory manager methods public: MemoryManager(); // Initialize a Memory Manager ~MemoryManager(); // De-allocate Memory Manager int GetPage(); // Return the first clear page void ClearPage(int i); // Take the index "i" of a page // and free it int GetClearPages(); // Return the number of clear pages }; #endif /* MEMORYMANAGER_H_ */
C++
// addrspace.h // Data structures to keep track of executing user programs // (address spaces). // // For now, we don't keep any information about address spaces. // The user level CPU state is saved and restored in the thread // executing the user program (see thread.h). // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef ADDRSPACE_H #define ADDRSPACE_H #include "copyright.h" #include "filesys.h" #define UserStackSize 2048 // increase this as necessary! class PCB; class AddrSpace { public: AddrSpace(OpenFile *executable,PCB *pcb); // Create an address space, AddrSpace(); // initializing it with the program // stored in the file "executable" ~AddrSpace(); // De-allocate an address space void InitRegisters(); // Initialize user-level CPU registers, // before jumping to user code void SaveState(); // Save/restore address space-specific void RestoreState(); // info on a context switch bool Translate(int virtAddr, int* physAddr); //converts a virtual address to a physical address int ReadFile(int virtAddr, OpenFile* file, int size, int fileAddr); // Loads the code and data segments into the translated memory bool IsValid(); // Return TRUE if numPages != -1 AddrSpace* Clone(PCB *pcb); // Create a new address space, an exact copy of the original int GetNumPages(); // Return numPages TranslationEntry* GetTranslationEntry(int pageNum); int GetTransEntryIndex(TranslationEntry* entry); public : PCB *pcb; // store information of the process private: TranslationEntry *pageTable; // Assume linear page table translation // for now! unsigned int numPages; // Number of pages in the virtual // address space // int userRegisters[NumTotalRegs]; // user-level CPU register state }; #endif // ADDRSPACE_H
C++
// bitmap.c // Routines to manage a bitmap -- an array of bits each of which // can be either on or off. Represented as an array of integers. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "bitmap.h" //---------------------------------------------------------------------- // BitMap::BitMap // Initialize a bitmap with "nitems" bits, so that every bit is clear. // it can be added somewhere on a list. // // "nitems" is the number of bits in the bitmap. //---------------------------------------------------------------------- BitMap::BitMap(int nitems) { numBits = nitems; numWords = divRoundUp(numBits, BitsInWord); map = new unsigned int[numWords]; for (int i = 0; i < numBits; i++) Clear(i); } //---------------------------------------------------------------------- // BitMap::~BitMap // De-allocate a bitmap. //---------------------------------------------------------------------- BitMap::~BitMap() { delete map; } //---------------------------------------------------------------------- // BitMap::Set // Set the "nth" bit in a bitmap. // // "which" is the number of the bit to be set. //---------------------------------------------------------------------- void BitMap::Mark(int which) { ASSERT(which >= 0 && which < numBits); map[which / BitsInWord] |= 1 << (which % BitsInWord); } //---------------------------------------------------------------------- // BitMap::Clear // Clear the "nth" bit in a bitmap. // // "which" is the number of the bit to be cleared. //---------------------------------------------------------------------- void BitMap::Clear(int which) { ASSERT(which >= 0 && which < numBits); map[which / BitsInWord] &= ~(1 << (which % BitsInWord)); } //---------------------------------------------------------------------- // BitMap::Test // Return TRUE if the "nth" bit is set. // // "which" is the number of the bit to be tested. //---------------------------------------------------------------------- bool BitMap::Test(int which) { ASSERT(which >= 0 && which < numBits); if (map[which / BitsInWord] & (1 << (which % BitsInWord))) return TRUE; else return FALSE; } //---------------------------------------------------------------------- // BitMap::Find // Return the number of the first bit which is clear. // As a side effect, set the bit (mark it as in use). // (In other words, find and allocate a bit.) // // If no bits are clear, return -1. //---------------------------------------------------------------------- int BitMap::Find() { for (int i = 0; i < numBits; i++) if (!Test(i)) { Mark(i); return i; } return -1; } //---------------------------------------------------------------------- // BitMap::NumClear // Return the number of clear bits in the bitmap. // (In other words, how many bits are unallocated?) //---------------------------------------------------------------------- int BitMap::NumClear() { int count = 0; for (int i = 0; i < numBits; i++) if (!Test(i)) count++; return count; } //---------------------------------------------------------------------- // BitMap::Print // Print the contents of the bitmap, for debugging. // // Could be done in a number of ways, but we just print the #'s of // all the bits that are set in the bitmap. //---------------------------------------------------------------------- void BitMap::Print() { printf("Bitmap set:\n"); for (int i = 0; i < numBits; i++) if (Test(i)) printf("%d, ", i); printf("\n"); } // These aren't needed until the FILESYS assignment //---------------------------------------------------------------------- // BitMap::FetchFromFile // Initialize the contents of a bitmap from a Nachos file. // // "file" is the place to read the bitmap from //---------------------------------------------------------------------- void BitMap::FetchFrom(OpenFile *file) { file->ReadAt((char *)map, numWords * sizeof(unsigned), 0); } //---------------------------------------------------------------------- // BitMap::WriteBack // Store the contents of a bitmap to a Nachos file. // // "file" is the place to write the bitmap to //---------------------------------------------------------------------- void BitMap::WriteBack(OpenFile *file) { file->WriteAt((char *)map, numWords * sizeof(unsigned), 0); }
C++
// sysopenfile.cc // Defines SysOpenFile class that contains a pointer to the file system's OpenFile object // and (char *)fileName for that file and the number of user processes currently accessing // it. Declare an array of SysOpenFile objects for use by all system calls implemented. // // Defines SysOpenFile Manager class that manage all SysOpenFile. // // Created on: Dec 10, 2009 // Author: qi #include "sysopenfile.h" #include "myutilities.h" //---------------------------------------------------------------------- // SysOpenFile::closeOne // close a SysOpenFile and accessing processes //---------------------------------------------------------------------- void SysOpenFile::closeOne() { if (userOpens <= 0) return; userOpens--; if (userOpens == 0) { delete fileName; delete file; } } //---------------------------------------------------------------------- // SysOpenFile::close // close all SysOpenFile and accessing processes //---------------------------------------------------------------------- void SysOpenFile::close() { if (userOpens <= 0) return; userOpens = 0; delete fileName; delete file; } //---------------------------------------------------------------------- // SysOpenFileManager::SysOpenFileManager // Initialize a SysOpenFileManager with initialize a bitmap with // "SOFILETABLE_SIZE" //---------------------------------------------------------------------- SysOpenFileManager::SysOpenFileManager() : bitMap(SOFILETABLE_SIZE) { } //---------------------------------------------------------------------- // SysOpenFileManager::~SysOpenFileManager // De-allocate a SysOpenFileManager //---------------------------------------------------------------------- SysOpenFileManager::~SysOpenFileManager() { } //---------------------------------------------------------------------- // SysOpenFileManager::Add // Add a SysOpenFile to the array of all SysOpenFile. // // Return the index of the added SysOpenFile // // "soFile" is the SysOpenFile to be added. //---------------------------------------------------------------------- int SysOpenFileManager::Add(SysOpenFile soFile) { int i = bitMap.Find(); if (i < 0) return i;//Fail to add, full sysOpenFileTable[i] = soFile; return i; } //---------------------------------------------------------------------- // SysOpenFileManager::Get // Get SysOpenFile by "fileName" and stored its index. // // Return the added SysOpenFile // // "fileName" is the name of the SysOpenFile to get. // "index" is the index of the SysOpenFile to get in the array. //---------------------------------------------------------------------- SysOpenFile* SysOpenFileManager::Get(char* fileName, int& index) { for (int i = 2; i < SOFILETABLE_SIZE; i++){ if (bitMap.Test(i) && strcmp(fileName, sysOpenFileTable[i].fileName)) { index = i; return &sysOpenFileTable[i]; } } return NULL; } //---------------------------------------------------------------------- // SysOpenFileManager::Get(index) // Get SysOpenFile by "index" of the array // // Return the got SysOpenFile if existed, or // Return NULL // // "index" is the number of index in the array to get. //---------------------------------------------------------------------- SysOpenFile* SysOpenFileManager::Get(int index) { if (bitMap.Test(index)) { return sysOpenFileTable + index; } return NULL; } //---------------------------------------------------------------------- // SysOpenFileManager::closeOne // Close a SysOpenFile by "index" of the array // // "index" is the number of index in the array to get. //---------------------------------------------------------------------- void SysOpenFileManager::closeOne(int index) { ASSERT(bitMap.Test(index)); sysOpenFileTable[index].closeOne(); if (sysOpenFileTable[index].userOpens == 0) bitMap.Clear(index); }
C++
// myutilities.cc // Method for compare two buffer. // // Created on: 2009-12-11 // Author: hyper #include "myutilities.h" //---------------------------------------------------------------------- // strcmp // Do little endian to big endian conversion on the bytes in the // object file header, in case the file was generated on a little // endian machine, and we're now running on a big endian machine. // // Return TRUE if the "first" char is the same as the "second" char, or // Return FALSE if they are different. // // "first" is the pointer to the char to be compared. // "second" is the pointer to the char compared with. //---------------------------------------------------------------------- bool strcmp(char* first,char * second){ while((*first)!=0) { if(*first != *second) return false; first++; second++; } return *second == 0; }
C++
// processmanager.cc // Defines PCB class -- Data structures to keep necessary information about a process, // Such as PID, parent PID, Thread*, and thread status. // // Defines ProcessManager class -- like memory manager function, return an unused process // id, clear a process id respectively by using a bitmap, store PCBs in an array of PCB*. // // Created on: 2009-12-9 // Author: hyper #include "processmanager.h" //---------------------------------------------------------------------- // PCB::PCB // Initialize a PCB with initialize a bitmap with "MAX_FILE_OPEN" // bits, and set the bits in a bitmap //---------------------------------------------------------------------- PCB::PCB():bitMap(MAX_FILE_OPEN){ bitMap.Mark(0); bitMap.Mark(1); } //---------------------------------------------------------------------- // PCB::~PCB // De-allocate a PCB //---------------------------------------------------------------------- PCB::~PCB(){ } //---------------------------------------------------------------------- // PCB::Add // Add a UserOpenFile in PCB // // Return index of the added UserOpenFile // // "uoFile" is the UserOpenFile to be added. //---------------------------------------------------------------------- int PCB::Add(UserOpenFile uoFile){ int i = bitMap.Find(); if(i < 0) return i;//Fail, full this->userOpenFileTable[i] = uoFile; return i; } //---------------------------------------------------------------------- // PCB::Remove // Remove a UserOpenFile by file id // // Return TRUE if removed the UserOpenFile // // "fileId" is the index of the UserOpenFile to be removed. //---------------------------------------------------------------------- bool PCB::Remove(int fileId){ bitMap.Clear(fileId); return true; } //---------------------------------------------------------------------- // PCB::Get // Return the UserOpenFile by file id // // "fileId" is the index of the UserOpenFile to get. //---------------------------------------------------------------------- UserOpenFile* PCB::Get(int fileId){ if(bitMap.Test(fileId)) return userOpenFileTable+fileId; return NULL; } //---------------------------------------------------------------------- // ProcessManager::ProcessManager // Initialize a process manager with initialize a bitmap with "MAX_PROCESS" // bits,and set the PCBs array, conditions array and lock array //---------------------------------------------------------------------- ProcessManager::ProcessManager():bitMap(MAX_PROCESS){ pcbs = new PCB*[MAX_PROCESS]; conditions = new Condition*[MAX_PROCESS]; locks = new Lock*[MAX_PROCESS]; } //---------------------------------------------------------------------- // ProcessManager::~ProcessManager // De-allocate a process manager //---------------------------------------------------------------------- ProcessManager::~ProcessManager(){ delete pcbs; delete conditions; delete locks; } //---------------------------------------------------------------------- // ProcessManager::GetPID // Return an unused process id //---------------------------------------------------------------------- int ProcessManager::GetPID(){ int result = bitMap.Find(); this->joinProNum[result] = 0; this->joinProNum[result] ++; return result; } //---------------------------------------------------------------------- // ProcessManager::GetPID // Clear a process id respectively // // "pid" is the pid number of the process need to be cleared //---------------------------------------------------------------------- void ProcessManager::ClearPID(int pid){ this->joinProNum[pid]--; if(this->joinProNum[pid]==0) bitMap.Clear(pid); } //---------------------------------------------------------------------- // ProcessManager::AddProcessAt // Add a process with exact pid // // "*pcb" is the pointer to the PCB to be added // "pid" is the pid number of the process //---------------------------------------------------------------------- void ProcessManager::AddProcessAt(PCB *pcb,int pid){ pcbs[pid] = pcb; } //---------------------------------------------------------------------- // ProcessManager::Join // The PCB manager keep track of who is waiting for who using a condition // variable for each PCB. // // "pid" is the pid number of the process //---------------------------------------------------------------------- void ProcessManager::Join(int pid){ //ASSERT(bitMap.Test(pid)); Lock * lock = locks[pid]; if(lock == NULL){ lock = new Lock(""); locks[pid] = lock; } Condition* condition = conditions[pid]; if(condition == NULL){ condition = new Condition(""); conditions[pid] = condition; } lock->Acquire(); this->joinProNum[pid]++; condition->Wait(lock); this->joinProNum[pid]--; if(this->joinProNum[pid]==0) bitMap.Clear(pid); lock->Release(); } //---------------------------------------------------------------------- // ProcessManager::Broadcast // Broadcast the "pid" process in Exit // // "pid" is the pid number of the process //---------------------------------------------------------------------- void ProcessManager::Broadcast(int pid){ Lock * lock = locks[pid]; Condition* condition = conditions[pid]; pcbStatus[pid] = pcbs[pid]->status; if(condition != NULL){ lock->Acquire(); condition->Broadcast(lock); lock->Release(); } } //---------------------------------------------------------------------- // ProcessManager::GetStatus // Return process's status by pid // // "pid" is the pid number of the process to get //---------------------------------------------------------------------- int ProcessManager::GetStatus(int pid){ if(bitMap.Test(pid) == 0) return -1;//process already done return pcbStatus[pid]; }
C++
// progtest.cc // Test routines for demonstrating that Nachos can load // a user program and execute it. // // Also, routines for testing the Console hardware device. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "console.h" #include "addrspace.h" #include "synch.h" //---------------------------------------------------------------------- // StartProcess // Run a user program. Open the executable, load it into // memory, and jump to it. //---------------------------------------------------------------------- void StartProcess(char *filename) { OpenFile *executable = fileSystem->Open(filename); if (executable == NULL) { printf("Unable to open file %s\n", filename); return; } AddrSpace *space; PCB* pcb = new PCB(); pcb->pid = pm->GetPID(); space = new AddrSpace(executable,pcb); //set pcb pcb->parentPid = -1; pcb->thread = currentThread; pcb->status = PRUNNING; space->pcb = pcb; currentThread->space = space; pm->AddProcessAt(pcb,pcb->pid); delete executable; // close file space->InitRegisters(); // set the initial register values space->RestoreState(); // load page table register machine->Run(); // jump to the user progam ASSERT(FALSE); // machine->Run never returns; // the address space exits // by doing the syscall "exit" } // Data structures needed for the console test. Threads making // I/O requests wait on a Semaphore to delay until the I/O completes. static Console *console; static Semaphore *readAvail; static Semaphore *writeDone; //---------------------------------------------------------------------- // ConsoleInterruptHandlers // Wake up the thread that requested the I/O. //---------------------------------------------------------------------- static void ReadAvail(int arg) { readAvail->V(); } static void WriteDone(int arg) { writeDone->V(); } //---------------------------------------------------------------------- // ConsoleTest // Test the console by echoing characters typed at the input onto // the output. Stop when the user types a 'q'. //---------------------------------------------------------------------- void ConsoleTest (char *in, char *out) { char ch; console = new Console(in, out, ReadAvail, WriteDone, 0); readAvail = new Semaphore("read avail", 0); writeDone = new Semaphore("write done", 0); for (;;) { readAvail->P(); // wait for character to arrive ch = console->GetChar(); console->PutChar(ch); // echo it! writeDone->P() ; // wait for write to finish if (ch == 'q') return; // if q, quit } }
C++
// bitmap.h // Data structures defining a bitmap -- an array of bits each of which // can be either on or off. // // Represented as an array of unsigned integers, on which we do // modulo arithmetic to find the bit we are interested in. // // The bitmap can be parameterized with with the number of bits being // managed. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef BITMAP_H #define BITMAP_H #include "copyright.h" #include "utility.h" #include "openfile.h" // Definitions helpful for representing a bitmap as an array of integers #define BitsInByte 8 #define BitsInWord 32 // The following class defines a "bitmap" -- an array of bits, // each of which can be independently set, cleared, and tested. // // Most useful for managing the allocation of the elements of an array -- // for instance, disk sectors, or main memory pages. // Each bit represents whether the corresponding sector or page is // in use or free. class BitMap { public: BitMap(int nitems); // Initialize a bitmap, with "nitems" bits // initially, all bits are cleared. ~BitMap(); // De-allocate bitmap void Mark(int which); // Set the "nth" bit void Clear(int which); // Clear the "nth" bit bool Test(int which); // Is the "nth" bit set? int Find(); // Return the # of a clear bit, and as a side // effect, set the bit. // If no bits are clear, return -1. int NumClear(); // Return the number of clear bits void Print(); // Print contents of bitmap // These aren't needed until FILESYS, when we will need to read and // write the bitmap to a file void FetchFrom(OpenFile *file); // fetch contents from disk void WriteBack(OpenFile *file); // write contents to disk private: int numBits; // number of bits in the bitmap int numWords; // number of words of bitmap storage // (rounded up if numBits is not a // multiple of the number of bits in // a word) unsigned int *map; // bit storage }; #endif // BITMAP_H
C++
/* * useropenfile.cc * * Created on: Dec 10, 2009 * Author: qi */ #include "useropenfile.h"
C++
// memorymanager.cc // Routines to manage a memory manager -- that will be used to facilitate // contiguous virtual memory. The amount of memory available to the user // space is the same as the amount of physical memory. // // Memory Manager allocates the first clear page, takes the index of a page // and frees it, and get the number of clear pages. // // Created on: 2009-12-7 // Author: hyper #include "memorymanager.h" #include "machine.h" //---------------------------------------------------------------------- // MemoryManager::MemoryManager // Initialize a memory manager with initialize a bitmap with "NumPhysPages" // bits, so that every bit is clear. // it can be added somewhere on a list. //---------------------------------------------------------------------- MemoryManager::MemoryManager():bitMap(NumPhysPages){ } //---------------------------------------------------------------------- // MemoryManager::~MemoryManager // De-allocate a memory manager. //---------------------------------------------------------------------- MemoryManager::~MemoryManager() { } //---------------------------------------------------------------------- // MemoryManager::GetPage // Return the first clear page //---------------------------------------------------------------------- int MemoryManager::GetPage() { return bitMap.Find(); } //---------------------------------------------------------------------- // MemoryManager::ClearPage // Take the index "i" of a page and free it. // // "i" is the index of a page to be cleared and freed. //---------------------------------------------------------------------- void MemoryManager::ClearPage(int i) { bitMap.Clear(i); } //---------------------------------------------------------------------- // MemoryManager::GetClearPages // Return the number of clear pages //---------------------------------------------------------------------- int MemoryManager::GetClearPages() { return bitMap.NumClear(); }
C++
// nettest.cc // Test out message delivery between two "Nachos" machines, // using the Post Office to coordinate delivery. // // Two caveats: // 1. Two copies of Nachos must be running, with machine ID's 0 and 1: // ./nachos -m 0 -o 1 & // ./nachos -m 1 -o 0 & // // 2. You need an implementation of condition variables, // which is *not* provided as part of the baseline threads // implementation. The Post Office won't work without // a correct implementation of condition variables. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "network.h" #include "post.h" #include "interrupt.h" // Test out message delivery, by doing the following: // 1. send a message to the machine with ID "farAddr", at mail box #0 // 2. wait for the other machine's message to arrive (in our mailbox #0) // 3. send an acknowledgment for the other machine's message // 4. wait for an acknowledgement from the other machine to our // original message void MailTest(int farAddr) { PacketHeader outPktHdr, inPktHdr; MailHeader outMailHdr, inMailHdr; char *data = "Hello there!"; char *ack = "Got it!"; char buffer[MaxMailSize]; // construct packet, mail header for original message // To: destination machine, mailbox 0 // From: our machine, reply to: mailbox 1 outPktHdr.to = farAddr; outMailHdr.to = 0; outMailHdr.from = 1; outMailHdr.length = strlen(data) + 1; // Send the first message postOffice->Send(outPktHdr, outMailHdr, data); // Wait for the first message from the other machine postOffice->Receive(0, &inPktHdr, &inMailHdr, buffer); printf("Got \"%s\" from %d, box %d\n",buffer,inPktHdr.from,inMailHdr.from); fflush(stdout); // Send acknowledgement to the other machine (using "reply to" mailbox // in the message that just arrived outPktHdr.to = inPktHdr.from; outMailHdr.to = inMailHdr.from; outMailHdr.length = strlen(ack) + 1; postOffice->Send(outPktHdr, outMailHdr, ack); // Wait for the ack from the other machine to the first message we sent. postOffice->Receive(1, &inPktHdr, &inMailHdr, buffer); printf("Got \"%s\" from %d, box %d\n",buffer,inPktHdr.from,inMailHdr.from); fflush(stdout); // Then we're done! interrupt->Halt(); }
C++
// post.h // Data structures for providing the abstraction of unreliable, // ordered, fixed-size message delivery to mailboxes on other // (directly connected) machines. Messages can be dropped by // the network, but they are never corrupted. // // The US Post Office delivers mail to the addressed mailbox. // By analogy, our post office delivers packets to a specific buffer // (MailBox), based on the mailbox number stored in the packet header. // Mail waits in the box until a thread asks for it; if the mailbox // is empty, threads can wait for mail to arrive in it. // // Thus, the service our post office provides is to de-multiplex // incoming packets, delivering them to the appropriate thread. // // With each message, you get a return address, which consists of a "from // address", which is the id of the machine that sent the message, and // a "from box", which is the number of a mailbox on the sending machine // to which you can send an acknowledgement, if your protocol requires // this. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #ifndef POST_H #define POST_H #include "network.h" #include "synchlist.h" // Mailbox address -- uniquely identifies a mailbox on a given machine. // A mailbox is just a place for temporary storage for messages. typedef int MailBoxAddress; // The following class defines part of the message header. // This is prepended to the message by the PostOffice, before the message // is sent to the Network. class MailHeader { public: MailBoxAddress to; // Destination mail box MailBoxAddress from; // Mail box to reply to unsigned length; // Bytes of message data (excluding the // mail header) }; // Maximum "payload" -- real data -- that can included in a single message // Excluding the MailHeader and the PacketHeader #define MaxMailSize (MaxPacketSize - sizeof(MailHeader)) // The following class defines the format of an incoming/outgoing // "Mail" message. The message format is layered: // network header (PacketHeader) // post office header (MailHeader) // data class Mail { public: Mail(PacketHeader pktH, MailHeader mailH, char *msgData); // Initialize a mail message by // concatenating the headers to the data PacketHeader pktHdr; // Header appended by Network MailHeader mailHdr; // Header appended by PostOffice char data[MaxMailSize]; // Payload -- message data }; // The following class defines a single mailbox, or temporary storage // for messages. Incoming messages are put by the PostOffice into the // appropriate mailbox, and these messages can then be retrieved by // threads on this machine. class MailBox { public: MailBox(); // Allocate and initialize mail box ~MailBox(); // De-allocate mail box void Put(PacketHeader pktHdr, MailHeader mailHdr, char *data); // Atomically put a message into the mailbox void Get(PacketHeader *pktHdr, MailHeader *mailHdr, char *data); // Atomically get a message out of the // mailbox (and wait if there is no message // to get!) private: SynchList *messages; // A mailbox is just a list of arrived messages }; // The following class defines a "Post Office", or a collection of // mailboxes. The Post Office is a synchronization object that provides // two main operations: Send -- send a message to a mailbox on a remote // machine, and Receive -- wait until a message is in the mailbox, // then remove and return it. // // Incoming messages are put by the PostOffice into the // appropriate mailbox, waking up any threads waiting on Receive. class PostOffice { public: PostOffice(NetworkAddress addr, double reliability, int nBoxes); // Allocate and initialize Post Office // "reliability" is how many packets // get dropped by the underlying network ~PostOffice(); // De-allocate Post Office data void Send(PacketHeader pktHdr, MailHeader mailHdr, char *data); // Send a message to a mailbox on a remote // machine. The fromBox in the MailHeader is // the return box for ack's. void Receive(int box, PacketHeader *pktHdr, MailHeader *mailHdr, char *data); // Retrieve a message from "box". Wait if // there is no message in the box. void PostalDelivery(); // Wait for incoming messages, // and then put them in the correct mailbox void PacketSent(); // Interrupt handler, called when outgoing // packet has been put on network; next // packet can now be sent void IncomingPacket(); // Interrupt handler, called when incoming // packet has arrived and can be pulled // off of network (i.e., time to call // PostalDelivery) private: Network *network; // Physical network connection NetworkAddress netAddr; // Network address of this machine MailBox *boxes; // Table of mail boxes to hold incoming mail int numBoxes; // Number of mail boxes Semaphore *messageAvailable;// V'ed when message has arrived from network Semaphore *messageSent; // V'ed when next message can be sent to network Lock *sendLock; // Only one outgoing message at a time }; #endif
C++
// post.cc // Routines to deliver incoming network messages to the correct // "address" -- a mailbox, or a holding area for incoming messages. // This module operates just like the US postal service (in other // words, it works, but it's slow, and you can't really be sure if // your mail really got through!). // // Note that once we prepend the MailHdr to the outgoing message data, // the combination (MailHdr plus data) looks like "data" to the Network // device. // // The implementation synchronizes incoming messages with threads // waiting for those messages. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "post.h" #ifdef HOST_SPARC #include <strings.h> #endif //---------------------------------------------------------------------- // Mail::Mail // Initialize a single mail message, by concatenating the headers to // the data. // // "pktH" -- source, destination machine ID's // "mailH" -- source, destination mailbox ID's // "data" -- payload data //---------------------------------------------------------------------- Mail::Mail(PacketHeader pktH, MailHeader mailH, char *msgData) { ASSERT(mailH.length <= MaxMailSize); pktHdr = pktH; mailHdr = mailH; bcopy(msgData, data, mailHdr.length); } //---------------------------------------------------------------------- // MailBox::MailBox // Initialize a single mail box within the post office, so that it // can receive incoming messages. // // Just initialize a list of messages, representing the mailbox. //---------------------------------------------------------------------- MailBox::MailBox() { messages = new SynchList(); } //---------------------------------------------------------------------- // MailBox::~MailBox // De-allocate a single mail box within the post office. // // Just delete the mailbox, and throw away all the queued messages // in the mailbox. //---------------------------------------------------------------------- MailBox::~MailBox() { delete messages; } //---------------------------------------------------------------------- // PrintHeader // Print the message header -- the destination machine ID and mailbox // #, source machine ID and mailbox #, and message length. // // "pktHdr" -- source, destination machine ID's // "mailHdr" -- source, destination mailbox ID's //---------------------------------------------------------------------- static void PrintHeader(PacketHeader pktHdr, MailHeader mailHdr) { printf("From (%d, %d) to (%d, %d) bytes %d\n", pktHdr.from, mailHdr.from, pktHdr.to, mailHdr.to, mailHdr.length); } //---------------------------------------------------------------------- // MailBox::Put // Add a message to the mailbox. If anyone is waiting for message // arrival, wake them up! // // We need to reconstruct the Mail message (by concatenating the headers // to the data), to simplify queueing the message on the SynchList. // // "pktHdr" -- source, destination machine ID's // "mailHdr" -- source, destination mailbox ID's // "data" -- payload message data //---------------------------------------------------------------------- void MailBox::Put(PacketHeader pktHdr, MailHeader mailHdr, char *data) { Mail *mail = new Mail(pktHdr, mailHdr, data); messages->Append((void *)mail); // put on the end of the list of // arrived messages, and wake up // any waiters } //---------------------------------------------------------------------- // MailBox::Get // Get a message from a mailbox, parsing it into the packet header, // mailbox header, and data. // // The calling thread waits if there are no messages in the mailbox. // // "pktHdr" -- address to put: source, destination machine ID's // "mailHdr" -- address to put: source, destination mailbox ID's // "data" -- address to put: payload message data //---------------------------------------------------------------------- void MailBox::Get(PacketHeader *pktHdr, MailHeader *mailHdr, char *data) { DEBUG('n', "Waiting for mail in mailbox\n"); Mail *mail = (Mail *) messages->Remove(); // remove message from list; // will wait if list is empty *pktHdr = mail->pktHdr; *mailHdr = mail->mailHdr; if (DebugIsEnabled('n')) { printf("Got mail from mailbox: "); PrintHeader(*pktHdr, *mailHdr); } bcopy(mail->data, data, mail->mailHdr.length); // copy the message data into // the caller's buffer delete mail; // we've copied out the stuff we // need, we can now discard the message } //---------------------------------------------------------------------- // PostalHelper, ReadAvail, WriteDone // Dummy functions because C++ can't indirectly invoke member functions // The first is forked as part of the "postal worker thread; the // later two are called by the network interrupt handler. // // "arg" -- pointer to the Post Office managing the Network //---------------------------------------------------------------------- static void PostalHelper(int arg) { PostOffice* po = (PostOffice *) arg; po->PostalDelivery(); } static void ReadAvail(int arg) { PostOffice* po = (PostOffice *) arg; po->IncomingPacket(); } static void WriteDone(int arg) { PostOffice* po = (PostOffice *) arg; po->PacketSent(); } //---------------------------------------------------------------------- // PostOffice::PostOffice // Initialize a post office as a collection of mailboxes. // Also initialize the network device, to allow post offices // on different machines to deliver messages to one another. // // We use a separate thread "the postal worker" to wait for messages // to arrive, and deliver them to the correct mailbox. Note that // delivering messages to the mailboxes can't be done directly // by the interrupt handlers, because it requires a Lock. // // "addr" is this machine's network ID // "reliability" is the probability that a network packet will // be delivered (e.g., reliability = 1 means the network never // drops any packets; reliability = 0 means the network never // delivers any packets) // "nBoxes" is the number of mail boxes in this Post Office //---------------------------------------------------------------------- PostOffice::PostOffice(NetworkAddress addr, double reliability, int nBoxes) { // First, initialize the synchronization with the interrupt handlers messageAvailable = new Semaphore("message available", 0); messageSent = new Semaphore("message sent", 0); sendLock = new Lock("message send lock"); // Second, initialize the mailboxes netAddr = addr; numBoxes = nBoxes; boxes = new MailBox[nBoxes]; // Third, initialize the network; tell it which interrupt handlers to call network = new Network(addr, reliability, ReadAvail, WriteDone, (int) this); // Finally, create a thread whose sole job is to wait for incoming messages, // and put them in the right mailbox. Thread *t = new Thread("postal worker"); t->Fork(PostalHelper, (int) this); } //---------------------------------------------------------------------- // PostOffice::~PostOffice // De-allocate the post office data structures. //---------------------------------------------------------------------- PostOffice::~PostOffice() { delete network; delete [] boxes; delete messageAvailable; delete messageSent; delete sendLock; } //---------------------------------------------------------------------- // PostOffice::PostalDelivery // Wait for incoming messages, and put them in the right mailbox. // // Incoming messages have had the PacketHeader stripped off, // but the MailHeader is still tacked on the front of the data. //---------------------------------------------------------------------- void PostOffice::PostalDelivery() { PacketHeader pktHdr; MailHeader mailHdr; char *buffer = new char[MaxPacketSize]; for (;;) { // first, wait for a message messageAvailable->P(); pktHdr = network->Receive(buffer); mailHdr = *(MailHeader *)buffer; if (DebugIsEnabled('n')) { printf("Putting mail into mailbox: "); PrintHeader(pktHdr, mailHdr); } // check that arriving message is legal! ASSERT(0 <= mailHdr.to && mailHdr.to < numBoxes); ASSERT(mailHdr.length <= MaxMailSize); // put into mailbox boxes[mailHdr.to].Put(pktHdr, mailHdr, buffer + sizeof(MailHeader)); } } //---------------------------------------------------------------------- // PostOffice::Send // Concatenate the MailHeader to the front of the data, and pass // the result to the Network for delivery to the destination machine. // // Note that the MailHeader + data looks just like normal payload // data to the Network. // // "pktHdr" -- source, destination machine ID's // "mailHdr" -- source, destination mailbox ID's // "data" -- payload message data //---------------------------------------------------------------------- void PostOffice::Send(PacketHeader pktHdr, MailHeader mailHdr, char* data) { char* buffer = new char[MaxPacketSize]; // space to hold concatenated // mailHdr + data if (DebugIsEnabled('n')) { printf("Post send: "); PrintHeader(pktHdr, mailHdr); } ASSERT(mailHdr.length <= MaxMailSize); ASSERT(0 <= mailHdr.to && mailHdr.to < numBoxes); // fill in pktHdr, for the Network layer pktHdr.from = netAddr; pktHdr.length = mailHdr.length + sizeof(MailHeader); // concatenate MailHeader and data bcopy(&mailHdr, buffer, sizeof(MailHeader)); bcopy(data, buffer + sizeof(MailHeader), mailHdr.length); sendLock->Acquire(); // only one message can be sent // to the network at any one time network->Send(pktHdr, buffer); messageSent->P(); // wait for interrupt to tell us // ok to send the next message sendLock->Release(); delete [] buffer; // we've sent the message, so // we can delete our buffer } //---------------------------------------------------------------------- // PostOffice::Send // Retrieve a message from a specific box if one is available, // otherwise wait for a message to arrive in the box. // // Note that the MailHeader + data looks just like normal payload // data to the Network. // // // "box" -- mailbox ID in which to look for message // "pktHdr" -- address to put: source, destination machine ID's // "mailHdr" -- address to put: source, destination mailbox ID's // "data" -- address to put: payload message data //---------------------------------------------------------------------- void PostOffice::Receive(int box, PacketHeader *pktHdr, MailHeader *mailHdr, char* data) { ASSERT((box >= 0) && (box < numBoxes)); boxes[box].Get(pktHdr, mailHdr, data); ASSERT(mailHdr->length <= MaxMailSize); } //---------------------------------------------------------------------- // PostOffice::IncomingPacket // Interrupt handler, called when a packet arrives from the network. // // Signal the PostalDelivery routine that it is time to get to work! //---------------------------------------------------------------------- void PostOffice::IncomingPacket() { messageAvailable->V(); } //---------------------------------------------------------------------- // PostOffice::PacketSent // Interrupt handler, called when the next packet can be put onto the // network. // // The name of this routine is a misnomer; if "reliability < 1", // the packet could have been dropped by the network, so it won't get // through. //---------------------------------------------------------------------- void PostOffice::PacketSent() { messageSent->V(); }
C++
// directory.cc // Routines to manage a directory of file names. // // The directory is a table of fixed length entries; each // entry represents a single file, and contains the file name, // and the location of the file header on disk. The fixed size // of each directory entry means that we have the restriction // of a fixed maximum size for file names. // // The constructor initializes an empty directory of a certain size; // we use ReadFrom/WriteBack to fetch the contents of the directory // from disk, and to write back any modifications back to disk. // // Also, this implementation has the restriction that the size // of the directory cannot expand. In other words, once all the // entries in the directory are used, no more files can be created. // Fixing this is one of the parts to the assignment. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "utility.h" #include "filehdr.h" #include "directory.h" //---------------------------------------------------------------------- // Directory::Directory // Initialize a directory; initially, the directory is completely // empty. If the disk is being formatted, an empty directory // is all we need, but otherwise, we need to call FetchFrom in order // to initialize it from disk. // // "size" is the number of entries in the directory //---------------------------------------------------------------------- Directory::Directory(int size) { table = new DirectoryEntry[size]; tableSize = size; for (int i = 0; i < tableSize; i++) table[i].inUse = FALSE; } //---------------------------------------------------------------------- // Directory::~Directory // De-allocate directory data structure. //---------------------------------------------------------------------- Directory::~Directory() { delete [] table; } //---------------------------------------------------------------------- // Directory::FetchFrom // Read the contents of the directory from disk. // // "file" -- file containing the directory contents //---------------------------------------------------------------------- void Directory::FetchFrom(OpenFile *file) { (void) file->ReadAt((char *)table, tableSize * sizeof(DirectoryEntry), 0); } //---------------------------------------------------------------------- // Directory::WriteBack // Write any modifications to the directory back to disk // // "file" -- file to contain the new directory contents //---------------------------------------------------------------------- void Directory::WriteBack(OpenFile *file) { (void) file->WriteAt((char *)table, tableSize * sizeof(DirectoryEntry), 0); } //---------------------------------------------------------------------- // Directory::FindIndex // Look up file name in directory, and return its location in the table of // directory entries. Return -1 if the name isn't in the directory. // // "name" -- the file name to look up //---------------------------------------------------------------------- int Directory::FindIndex(char *name) { for (int i = 0; i < tableSize; i++) if (table[i].inUse && !strncmp(table[i].name, name, FileNameMaxLen)) return i; return -1; // name not in directory } //---------------------------------------------------------------------- // Directory::Find // Look up file name in directory, and return the disk sector number // where the file's header is stored. Return -1 if the name isn't // in the directory. // // "name" -- the file name to look up //---------------------------------------------------------------------- int Directory::Find(char *name) { int i = FindIndex(name); if (i != -1) return table[i].sector; return -1; } //---------------------------------------------------------------------- // Directory::Add // Add a file into the directory. Return TRUE if successful; // return FALSE if the file name is already in the directory, or if // the directory is completely full, and has no more space for // additional file names. // // "name" -- the name of the file being added // "newSector" -- the disk sector containing the added file's header //---------------------------------------------------------------------- bool Directory::Add(char *name, int newSector) { if (FindIndex(name) != -1) return FALSE; for (int i = 0; i < tableSize; i++) if (!table[i].inUse) { table[i].inUse = TRUE; strncpy(table[i].name, name, FileNameMaxLen); table[i].sector = newSector; return TRUE; } return FALSE; // no space. Fix when we have extensible files. } //---------------------------------------------------------------------- // Directory::Remove // Remove a file name from the directory. Return TRUE if successful; // return FALSE if the file isn't in the directory. // // "name" -- the file name to be removed //---------------------------------------------------------------------- bool Directory::Remove(char *name) { int i = FindIndex(name); if (i == -1) return FALSE; // name not in directory table[i].inUse = FALSE; return TRUE; } //---------------------------------------------------------------------- // Directory::List // List all the file names in the directory. //---------------------------------------------------------------------- void Directory::List() { for (int i = 0; i < tableSize; i++) if (table[i].inUse) printf("%s\n", table[i].name); } //---------------------------------------------------------------------- // Directory::Print // List all the file names in the directory, their FileHeader locations, // and the contents of each file. For debugging. //---------------------------------------------------------------------- void Directory::Print() { FileHeader *hdr = new FileHeader; printf("Directory contents:\n"); for (int i = 0; i < tableSize; i++) if (table[i].inUse) { printf("Name: %s, Sector: %d\n", table[i].name, table[i].sector); hdr->FetchFrom(table[i].sector); hdr->Print(); } printf("\n"); delete hdr; }
C++
// filehdr.cc // Routines for managing the disk file header (in UNIX, this // would be called the i-node). // // The file header is used to locate where on disk the // file's data is stored. We implement this as a fixed size // table of pointers -- each entry in the table points to the // disk sector containing that portion of the file data // (in other words, there are no indirect or doubly indirect // blocks). The table size is chosen so that the file header // will be just big enough to fit in one disk sector, // // Unlike in a real system, we do not keep track of file permissions, // ownership, last modification date, etc., in the file header. // // A file header can be initialized in two ways: // for a new file, by modifying the in-memory data structure // to point to the newly allocated data blocks // for a file already on disk, by reading the file header from disk // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "filehdr.h" //---------------------------------------------------------------------- // FileHeader::Allocate // Initialize a fresh file header for a newly created file. // Allocate data blocks for the file out of the map of free disk blocks. // Return FALSE if there are not enough free blocks to accomodate // the new file. // // "freeMap" is the bit map of free disk sectors // "fileSize" is the bit map of free disk sectors //---------------------------------------------------------------------- bool FileHeader::Allocate(BitMap *freeMap, int fileSize) { numBytes = fileSize; numSectors = divRoundUp(fileSize, SectorSize); if (freeMap->NumClear() < numSectors) return FALSE; // not enough space for (int i = 0; i < numSectors; i++) dataSectors[i] = freeMap->Find(); return TRUE; } //---------------------------------------------------------------------- // FileHeader::Deallocate // De-allocate all the space allocated for data blocks for this file. // // "freeMap" is the bit map of free disk sectors //---------------------------------------------------------------------- void FileHeader::Deallocate(BitMap *freeMap) { for (int i = 0; i < numSectors; i++) { ASSERT(freeMap->Test((int) dataSectors[i])); // ought to be marked! freeMap->Clear((int) dataSectors[i]); } } //---------------------------------------------------------------------- // FileHeader::FetchFrom // Fetch contents of file header from disk. // // "sector" is the disk sector containing the file header //---------------------------------------------------------------------- void FileHeader::FetchFrom(int sector) { synchDisk->ReadSector(sector, (char *)this); } //---------------------------------------------------------------------- // FileHeader::WriteBack // Write the modified contents of the file header back to disk. // // "sector" is the disk sector to contain the file header //---------------------------------------------------------------------- void FileHeader::WriteBack(int sector) { synchDisk->WriteSector(sector, (char *)this); } //---------------------------------------------------------------------- // FileHeader::ByteToSector // Return which disk sector is storing a particular byte within the file. // This is essentially a translation from a virtual address (the // offset in the file) to a physical address (the sector where the // data at the offset is stored). // // "offset" is the location within the file of the byte in question //---------------------------------------------------------------------- int FileHeader::ByteToSector(int offset) { return(dataSectors[offset / SectorSize]); } //---------------------------------------------------------------------- // FileHeader::FileLength // Return the number of bytes in the file. //---------------------------------------------------------------------- int FileHeader::FileLength() { return numBytes; } //---------------------------------------------------------------------- // FileHeader::Print // Print the contents of the file header, and the contents of all // the data blocks pointed to by the file header. //---------------------------------------------------------------------- void FileHeader::Print() { int i, j, k; char *data = new char[SectorSize]; printf("FileHeader contents. File size: %d. File blocks:\n", numBytes); for (i = 0; i < numSectors; i++) printf("%d ", dataSectors[i]); printf("\nFile contents:\n"); for (i = k = 0; i < numSectors; i++) { synchDisk->ReadSector(dataSectors[i], data); for (j = 0; (j < SectorSize) && (k < numBytes); j++, k++) { if ('\040' <= data[j] && data[j] <= '\176') // isprint(data[j]) printf("%c", data[j]); else printf("\\%x", (unsigned char)data[j]); } printf("\n"); } delete [] data; }
C++
// openfile.h // Data structures for opening, closing, reading and writing to // individual files. The operations supported are similar to // the UNIX ones -- type 'man open' to the UNIX prompt. // // There are two implementations. One is a "STUB" that directly // turns the file operations into the underlying UNIX operations. // (cf. comment in filesys.h). // // The other is the "real" implementation, that turns these // operations into read and write disk sector requests. // In this baseline implementation of the file system, we don't // worry about concurrent accesses to the file system // by different threads -- this is part of the assignment. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef OPENFILE_H #define OPENFILE_H #include "copyright.h" #include "utility.h" #ifdef FILESYS_STUB // Temporarily implement calls to // Nachos file system as calls to UNIX! // See definitions listed under #else class OpenFile { public: OpenFile(int f) { file = f; currentOffset = 0; } // open the file ~OpenFile() { Close(file); } // close the file int ReadAt(char *into, int numBytes, int position) { Lseek(file, position, 0); return ReadPartial(file, into, numBytes); } int WriteAt(char *from, int numBytes, int position) { Lseek(file, position, 0); WriteFile(file, from, numBytes); return numBytes; } int Read(char *into, int numBytes) { int numRead = ReadAt(into, numBytes, currentOffset); currentOffset += numRead; return numRead; } int Write(char *from, int numBytes) { int numWritten = WriteAt(from, numBytes, currentOffset); currentOffset += numWritten; return numWritten; } int Length() { Lseek(file, 0, 2); return Tell(file); } private: int file; int currentOffset; }; #else // FILESYS class FileHeader; class OpenFile { public: OpenFile(int sector); // Open a file whose header is located // at "sector" on the disk ~OpenFile(); // Close the file void Seek(int position); // Set the position from which to // start reading/writing -- UNIX lseek int Read(char *into, int numBytes); // Read/write bytes from the file, // starting at the implicit position. // Return the # actually read/written, // and increment position in file. int Write(char *from, int numBytes); int ReadAt(char *into, int numBytes, int position); // Read/write bytes from the file, // bypassing the implicit position. int WriteAt(char *from, int numBytes, int position); int Length(); // Return the number of bytes in the // file (this interface is simpler // than the UNIX idiom -- lseek to // end of file, tell, lseek back private: FileHeader *hdr; // Header for this file int seekPosition; // Current position within the file }; #endif // FILESYS #endif // OPENFILE_H
C++
// filehdr.h // Data structures for managing a disk file header. // // A file header describes where on disk to find the data in a file, // along with other information about the file (for instance, its // length, owner, etc.) // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #ifndef FILEHDR_H #define FILEHDR_H #include "disk.h" #include "bitmap.h" #define NumDirect ((SectorSize - 2 * sizeof(int)) / sizeof(int)) #define MaxFileSize (NumDirect * SectorSize) // The following class defines the Nachos "file header" (in UNIX terms, // the "i-node"), describing where on disk to find all of the data in the file. // The file header is organized as a simple table of pointers to // data blocks. // // The file header data structure can be stored in memory or on disk. // When it is on disk, it is stored in a single sector -- this means // that we assume the size of this data structure to be the same // as one disk sector. Without indirect addressing, this // limits the maximum file length to just under 4K bytes. // // There is no constructor; rather the file header can be initialized // by allocating blocks for the file (if it is a new file), or by // reading it from disk. class FileHeader { public: bool Allocate(BitMap *bitMap, int fileSize);// Initialize a file header, // including allocating space // on disk for the file data void Deallocate(BitMap *bitMap); // De-allocate this file's // data blocks void FetchFrom(int sectorNumber); // Initialize file header from disk void WriteBack(int sectorNumber); // Write modifications to file header // back to disk int ByteToSector(int offset); // Convert a byte offset into the file // to the disk sector containing // the byte int FileLength(); // Return the length of the file // in bytes void Print(); // Print the contents of the file. private: int numBytes; // Number of bytes in the file int numSectors; // Number of data sectors in the file int dataSectors[NumDirect]; // Disk sector numbers for each data // block in the file }; #endif // FILEHDR_H
C++
// openfile.cc // Routines to manage an open Nachos file. As in UNIX, a // file must be open before we can read or write to it. // Once we're all done, we can close it (in Nachos, by deleting // the OpenFile data structure). // // Also as in UNIX, for convenience, we keep the file header in // memory while the file is open. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "filehdr.h" #include "openfile.h" #include "system.h" #ifdef HOST_SPARC #include <strings.h> #endif //---------------------------------------------------------------------- // OpenFile::OpenFile // Open a Nachos file for reading and writing. Bring the file header // into memory while the file is open. // // "sector" -- the location on disk of the file header for this file //---------------------------------------------------------------------- OpenFile::OpenFile(int sector) { hdr = new FileHeader; hdr->FetchFrom(sector); seekPosition = 0; } //---------------------------------------------------------------------- // OpenFile::~OpenFile // Close a Nachos file, de-allocating any in-memory data structures. //---------------------------------------------------------------------- OpenFile::~OpenFile() { delete hdr; } //---------------------------------------------------------------------- // OpenFile::Seek // Change the current location within the open file -- the point at // which the next Read or Write will start from. // // "position" -- the location within the file for the next Read/Write //---------------------------------------------------------------------- void OpenFile::Seek(int position) { seekPosition = position; } //---------------------------------------------------------------------- // OpenFile::Read/Write // Read/write a portion of a file, starting from seekPosition. // Return the number of bytes actually written or read, and as a // side effect, increment the current position within the file. // // Implemented using the more primitive ReadAt/WriteAt. // // "into" -- the buffer to contain the data to be read from disk // "from" -- the buffer containing the data to be written to disk // "numBytes" -- the number of bytes to transfer //---------------------------------------------------------------------- int OpenFile::Read(char *into, int numBytes) { int result = ReadAt(into, numBytes, seekPosition); seekPosition += result; return result; } int OpenFile::Write(char *into, int numBytes) { int result = WriteAt(into, numBytes, seekPosition); seekPosition += result; return result; } //---------------------------------------------------------------------- // OpenFile::ReadAt/WriteAt // Read/write a portion of a file, starting at "position". // Return the number of bytes actually written or read, but has // no side effects (except that Write modifies the file, of course). // // There is no guarantee the request starts or ends on an even disk sector // boundary; however the disk only knows how to read/write a whole disk // sector at a time. Thus: // // For ReadAt: // We read in all of the full or partial sectors that are part of the // request, but we only copy the part we are interested in. // For WriteAt: // We must first read in any sectors that will be partially written, // so that we don't overwrite the unmodified portion. We then copy // in the data that will be modified, and write back all the full // or partial sectors that are part of the request. // // "into" -- the buffer to contain the data to be read from disk // "from" -- the buffer containing the data to be written to disk // "numBytes" -- the number of bytes to transfer // "position" -- the offset within the file of the first byte to be // read/written //---------------------------------------------------------------------- int OpenFile::ReadAt(char *into, int numBytes, int position) { int fileLength = hdr->FileLength(); int i, firstSector, lastSector, numSectors; char *buf; if ((numBytes <= 0) || (position >= fileLength)) return 0; // check request if ((position + numBytes) > fileLength) numBytes = fileLength - position; DEBUG('f', "Reading %d bytes at %d, from file of length %d.\n", numBytes, position, fileLength); firstSector = divRoundDown(position, SectorSize); lastSector = divRoundDown(position + numBytes - 1, SectorSize); numSectors = 1 + lastSector - firstSector; // read in all the full and partial sectors that we need buf = new char[numSectors * SectorSize]; for (i = firstSector; i <= lastSector; i++) synchDisk->ReadSector(hdr->ByteToSector(i * SectorSize), &buf[(i - firstSector) * SectorSize]); // copy the part we want bcopy(&buf[position - (firstSector * SectorSize)], into, numBytes); delete [] buf; return numBytes; } int OpenFile::WriteAt(char *from, int numBytes, int position) { int fileLength = hdr->FileLength(); int i, firstSector, lastSector, numSectors; bool firstAligned, lastAligned; char *buf; if ((numBytes <= 0) || (position >= fileLength)) return 0; // check request if ((position + numBytes) > fileLength) numBytes = fileLength - position; DEBUG('f', "Writing %d bytes at %d, from file of length %d.\n", numBytes, position, fileLength); firstSector = divRoundDown(position, SectorSize); lastSector = divRoundDown(position + numBytes - 1, SectorSize); numSectors = 1 + lastSector - firstSector; buf = new char[numSectors * SectorSize]; firstAligned = (position == (firstSector * SectorSize)); lastAligned = ((position + numBytes) == ((lastSector + 1) * SectorSize)); // read in first and last sector, if they are to be partially modified if (!firstAligned) ReadAt(buf, SectorSize, firstSector * SectorSize); if (!lastAligned && ((firstSector != lastSector) || firstAligned)) ReadAt(&buf[(lastSector - firstSector) * SectorSize], SectorSize, lastSector * SectorSize); // copy in the bytes we want to change bcopy(from, &buf[position - (firstSector * SectorSize)], numBytes); // write modified sectors back for (i = firstSector; i <= lastSector; i++) synchDisk->WriteSector(hdr->ByteToSector(i * SectorSize), &buf[(i - firstSector) * SectorSize]); delete [] buf; return numBytes; } //---------------------------------------------------------------------- // OpenFile::Length // Return the number of bytes in the file. //---------------------------------------------------------------------- int OpenFile::Length() { return hdr->FileLength(); }
C++
// filesys.cc // Routines to manage the overall operation of the file system. // Implements routines to map from textual file names to files. // // Each file in the file system has: // A file header, stored in a sector on disk // (the size of the file header data structure is arranged // to be precisely the size of 1 disk sector) // A number of data blocks // An entry in the file system directory // // The file system consists of several data structures: // A bitmap of free disk sectors (cf. bitmap.h) // A directory of file names and file headers // // Both the bitmap and the directory are represented as normal // files. Their file headers are located in specific sectors // (sector 0 and sector 1), so that the file system can find them // on bootup. // // The file system assumes that the bitmap and directory files are // kept "open" continuously while Nachos is running. // // For those operations (such as Create, Remove) that modify the // directory and/or bitmap, if the operation succeeds, the changes // are written immediately back to disk (the two files are kept // open during all this time). If the operation fails, and we have // modified part of the directory and/or bitmap, we simply discard // the changed version, without writing it back to disk. // // Our implementation at this point has the following restrictions: // // there is no synchronization for concurrent accesses // files have a fixed size, set when the file is created // files cannot be bigger than about 3KB in size // there is no hierarchical directory structure, and only a limited // number of files can be added to the system // there is no attempt to make the system robust to failures // (if Nachos exits in the middle of an operation that modifies // the file system, it may corrupt the disk) // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "disk.h" #include "bitmap.h" #include "directory.h" #include "filehdr.h" #include "filesys.h" // Sectors containing the file headers for the bitmap of free sectors, // and the directory of files. These file headers are placed in well-known // sectors, so that they can be located on boot-up. #define FreeMapSector 0 #define DirectorySector 1 // Initial file sizes for the bitmap and directory; until the file system // supports extensible files, the directory size sets the maximum number // of files that can be loaded onto the disk. #define FreeMapFileSize (NumSectors / BitsInByte) #define NumDirEntries 10 #define DirectoryFileSize (sizeof(DirectoryEntry) * NumDirEntries) //---------------------------------------------------------------------- // FileSystem::FileSystem // Initialize the file system. If format = TRUE, the disk has // nothing on it, and we need to initialize the disk to contain // an empty directory, and a bitmap of free sectors (with almost but // not all of the sectors marked as free). // // If format = FALSE, we just have to open the files // representing the bitmap and the directory. // // "format" -- should we initialize the disk? //---------------------------------------------------------------------- FileSystem::FileSystem(bool format) { DEBUG('f', "Initializing the file system.\n"); if (format) { BitMap *freeMap = new BitMap(NumSectors); Directory *directory = new Directory(NumDirEntries); FileHeader *mapHdr = new FileHeader; FileHeader *dirHdr = new FileHeader; DEBUG('f', "Formatting the file system.\n"); // First, allocate space for FileHeaders for the directory and bitmap // (make sure no one else grabs these!) freeMap->Mark(FreeMapSector); freeMap->Mark(DirectorySector); // Second, allocate space for the data blocks containing the contents // of the directory and bitmap files. There better be enough space! ASSERT(mapHdr->Allocate(freeMap, FreeMapFileSize)); ASSERT(dirHdr->Allocate(freeMap, DirectoryFileSize)); // Flush the bitmap and directory FileHeaders back to disk // We need to do this before we can "Open" the file, since open // reads the file header off of disk (and currently the disk has garbage // on it!). DEBUG('f', "Writing headers back to disk.\n"); mapHdr->WriteBack(FreeMapSector); dirHdr->WriteBack(DirectorySector); // OK to open the bitmap and directory files now // The file system operations assume these two files are left open // while Nachos is running. freeMapFile = new OpenFile(FreeMapSector); directoryFile = new OpenFile(DirectorySector); // Once we have the files "open", we can write the initial version // of each file back to disk. The directory at this point is completely // empty; but the bitmap has been changed to reflect the fact that // sectors on the disk have been allocated for the file headers and // to hold the file data for the directory and bitmap. DEBUG('f', "Writing bitmap and directory back to disk.\n"); freeMap->WriteBack(freeMapFile); // flush changes to disk directory->WriteBack(directoryFile); if (DebugIsEnabled('f')) { freeMap->Print(); directory->Print(); delete freeMap; delete directory; delete mapHdr; delete dirHdr; } } else { // if we are not formatting the disk, just open the files representing // the bitmap and directory; these are left open while Nachos is running freeMapFile = new OpenFile(FreeMapSector); directoryFile = new OpenFile(DirectorySector); } } //---------------------------------------------------------------------- // FileSystem::Create // Create a file in the Nachos file system (similar to UNIX create). // Since we can't increase the size of files dynamically, we have // to give Create the initial size of the file. // // The steps to create a file are: // Make sure the file doesn't already exist // Allocate a sector for the file header // Allocate space on disk for the data blocks for the file // Add the name to the directory // Store the new file header on disk // Flush the changes to the bitmap and the directory back to disk // // Return TRUE if everything goes ok, otherwise, return FALSE. // // Create fails if: // file is already in directory // no free space for file header // no free entry for file in directory // no free space for data blocks for the file // // Note that this implementation assumes there is no concurrent access // to the file system! // // "name" -- name of file to be created // "initialSize" -- size of file to be created //---------------------------------------------------------------------- bool FileSystem::Create(char *name, int initialSize) { Directory *directory; BitMap *freeMap; FileHeader *hdr; int sector; bool success; DEBUG('f', "Creating file %s, size %d\n", name, initialSize); directory = new Directory(NumDirEntries); directory->FetchFrom(directoryFile); if (directory->Find(name) != -1) success = FALSE; // file is already in directory else { freeMap = new BitMap(NumSectors); freeMap->FetchFrom(freeMapFile); sector = freeMap->Find(); // find a sector to hold the file header if (sector == -1) success = FALSE; // no free block for file header else if (!directory->Add(name, sector)) success = FALSE; // no space in directory else { hdr = new FileHeader; if (!hdr->Allocate(freeMap, initialSize)) success = FALSE; // no space on disk for data else { success = TRUE; // everthing worked, flush all changes back to disk hdr->WriteBack(sector); directory->WriteBack(directoryFile); freeMap->WriteBack(freeMapFile); } delete hdr; } delete freeMap; } delete directory; return success; } //---------------------------------------------------------------------- // FileSystem::Open // Open a file for reading and writing. // To open a file: // Find the location of the file's header, using the directory // Bring the header into memory // // "name" -- the text name of the file to be opened //---------------------------------------------------------------------- OpenFile * FileSystem::Open(char *name) { Directory *directory = new Directory(NumDirEntries); OpenFile *openFile = NULL; int sector; DEBUG('f', "Opening file %s\n", name); directory->FetchFrom(directoryFile); sector = directory->Find(name); if (sector >= 0) openFile = new OpenFile(sector); // name was found in directory delete directory; return openFile; // return NULL if not found } //---------------------------------------------------------------------- // FileSystem::Remove // Delete a file from the file system. This requires: // Remove it from the directory // Delete the space for its header // Delete the space for its data blocks // Write changes to directory, bitmap back to disk // // Return TRUE if the file was deleted, FALSE if the file wasn't // in the file system. // // "name" -- the text name of the file to be removed //---------------------------------------------------------------------- bool FileSystem::Remove(char *name) { Directory *directory; BitMap *freeMap; FileHeader *fileHdr; int sector; directory = new Directory(NumDirEntries); directory->FetchFrom(directoryFile); sector = directory->Find(name); if (sector == -1) { delete directory; return FALSE; // file not found } fileHdr = new FileHeader; fileHdr->FetchFrom(sector); freeMap = new BitMap(NumSectors); freeMap->FetchFrom(freeMapFile); fileHdr->Deallocate(freeMap); // remove data blocks freeMap->Clear(sector); // remove header block directory->Remove(name); freeMap->WriteBack(freeMapFile); // flush to disk directory->WriteBack(directoryFile); // flush to disk delete fileHdr; delete directory; delete freeMap; return TRUE; } //---------------------------------------------------------------------- // FileSystem::List // List all the files in the file system directory. //---------------------------------------------------------------------- void FileSystem::List() { Directory *directory = new Directory(NumDirEntries); directory->FetchFrom(directoryFile); directory->List(); delete directory; } //---------------------------------------------------------------------- // FileSystem::Print // Print everything about the file system: // the contents of the bitmap // the contents of the directory // for each file in the directory, // the contents of the file header // the data in the file //---------------------------------------------------------------------- void FileSystem::Print() { FileHeader *bitHdr = new FileHeader; FileHeader *dirHdr = new FileHeader; BitMap *freeMap = new BitMap(NumSectors); Directory *directory = new Directory(NumDirEntries); printf("Bit map file header:\n"); bitHdr->FetchFrom(FreeMapSector); bitHdr->Print(); printf("Directory file header:\n"); dirHdr->FetchFrom(DirectorySector); dirHdr->Print(); freeMap->FetchFrom(freeMapFile); freeMap->Print(); directory->FetchFrom(directoryFile); directory->Print(); delete bitHdr; delete dirHdr; delete freeMap; delete directory; }
C++
// directory.h // Data structures to manage a UNIX-like directory of file names. // // A directory is a table of pairs: <file name, sector #>, // giving the name of each file in the directory, and // where to find its file header (the data structure describing // where to find the file's data blocks) on disk. // // We assume mutual exclusion is provided by the caller. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #ifndef DIRECTORY_H #define DIRECTORY_H #include "openfile.h" #define FileNameMaxLen 9 // for simplicity, we assume // file names are <= 9 characters long // The following class defines a "directory entry", representing a file // in the directory. Each entry gives the name of the file, and where // the file's header is to be found on disk. // // Internal data structures kept public so that Directory operations can // access them directly. class DirectoryEntry { public: bool inUse; // Is this directory entry in use? int sector; // Location on disk to find the // FileHeader for this file char name[FileNameMaxLen + 1]; // Text name for file, with +1 for // the trailing '\0' }; // The following class defines a UNIX-like "directory". Each entry in // the directory describes a file, and where to find it on disk. // // The directory data structure can be stored in memory, or on disk. // When it is on disk, it is stored as a regular Nachos file. // // The constructor initializes a directory structure in memory; the // FetchFrom/WriteBack operations shuffle the directory information // from/to disk. class Directory { public: Directory(int size); // Initialize an empty directory // with space for "size" files ~Directory(); // De-allocate the directory void FetchFrom(OpenFile *file); // Init directory contents from disk void WriteBack(OpenFile *file); // Write modifications to // directory contents back to disk int Find(char *name); // Find the sector number of the // FileHeader for file: "name" bool Add(char *name, int newSector); // Add a file name into the directory bool Remove(char *name); // Remove a file from the directory void List(); // Print the names of all the files // in the directory void Print(); // Verbose print of the contents // of the directory -- all the file // names and their contents. private: int tableSize; // Number of directory entries DirectoryEntry *table; // Table of pairs: // <file name, file header location> int FindIndex(char *name); // Find the index into the directory // table corresponding to "name" }; #endif // DIRECTORY_H
C++
// synchdisk.h // Data structures to export a synchronous interface to the raw // disk device. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #ifndef SYNCHDISK_H #define SYNCHDISK_H #include "disk.h" #include "synch.h" // The following class defines a "synchronous" disk abstraction. // As with other I/O devices, the raw physical disk is an asynchronous device -- // requests to read or write portions of the disk return immediately, // and an interrupt occurs later to signal that the operation completed. // (Also, the physical characteristics of the disk device assume that // only one operation can be requested at a time). // // This class provides the abstraction that for any individual thread // making a request, it waits around until the operation finishes before // returning. class SynchDisk { public: SynchDisk(char* name); // Initialize a synchronous disk, // by initializing the raw Disk. ~SynchDisk(); // De-allocate the synch disk data void ReadSector(int sectorNumber, char* data); // Read/write a disk sector, returning // only once the data is actually read // or written. These call // Disk::ReadRequest/WriteRequest and // then wait until the request is done. void WriteSector(int sectorNumber, char* data); void RequestDone(); // Called by the disk device interrupt // handler, to signal that the // current disk operation is complete. private: Disk *disk; // Raw disk device Semaphore *semaphore; // To synchronize requesting thread // with the interrupt handler Lock *lock; // Only one read/write request // can be sent to the disk at a time }; #endif // SYNCHDISK_H
C++
// fstest.cc // Simple test routines for the file system. // // We implement: // Copy -- copy a file from UNIX to Nachos // Print -- cat the contents of a Nachos file // Perftest -- a stress test for the Nachos file system // read and write a really large file in tiny chunks // (won't work on baseline system!) // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "utility.h" #include "filesys.h" #include "system.h" #include "thread.h" #include "disk.h" #include "stats.h" #define TransferSize 10 // make it small, just to be difficult //---------------------------------------------------------------------- // Copy // Copy the contents of the UNIX file "from" to the Nachos file "to" //---------------------------------------------------------------------- void Copy(char *from, char *to) { FILE *fp; OpenFile* openFile; int amountRead, fileLength; char *buffer; // Open UNIX file if ((fp = fopen(from, "r")) == NULL) { printf("Copy: couldn't open input file %s\n", from); return; } // Figure out length of UNIX file fseek(fp, 0, 2); fileLength = ftell(fp); fseek(fp, 0, 0); // Create a Nachos file of the same length DEBUG('f', "Copying file %s, size %d, to file %s\n", from, fileLength, to); if (!fileSystem->Create(to, fileLength)) { // Create Nachos file printf("Copy: couldn't create output file %s\n", to); fclose(fp); return; } openFile = fileSystem->Open(to); ASSERT(openFile != NULL); // Copy the data in TransferSize chunks buffer = new char[TransferSize]; while ((amountRead = fread(buffer, sizeof(char), TransferSize, fp)) > 0) openFile->Write(buffer, amountRead); delete [] buffer; // Close the UNIX and the Nachos files delete openFile; fclose(fp); } //---------------------------------------------------------------------- // Print // Print the contents of the Nachos file "name". //---------------------------------------------------------------------- void Print(char *name) { OpenFile *openFile; int i, amountRead; char *buffer; if ((openFile = fileSystem->Open(name)) == NULL) { printf("Print: unable to open file %s\n", name); return; } buffer = new char[TransferSize]; while ((amountRead = openFile->Read(buffer, TransferSize)) > 0) for (i = 0; i < amountRead; i++) printf("%c", buffer[i]); delete [] buffer; delete openFile; // close the Nachos file return; } //---------------------------------------------------------------------- // PerformanceTest // Stress the Nachos file system by creating a large file, writing // it out a bit at a time, reading it back a bit at a time, and then // deleting the file. // // Implemented as three separate routines: // FileWrite -- write the file // FileRead -- read the file // PerformanceTest -- overall control, and print out performance #'s //---------------------------------------------------------------------- #define FileName "TestFile" #define Contents "1234567890" #define ContentSize strlen(Contents) #define FileSize ((int)(ContentSize * 5000)) static void FileWrite() { OpenFile *openFile; int i, numBytes; printf("Sequential write of %d byte file, in %d byte chunks\n", FileSize, ContentSize); if (!fileSystem->Create(FileName, 0)) { printf("Perf test: can't create %s\n", FileName); return; } openFile = fileSystem->Open(FileName); if (openFile == NULL) { printf("Perf test: unable to open %s\n", FileName); return; } for (i = 0; i < FileSize; i += ContentSize) { numBytes = openFile->Write(Contents, ContentSize); if (numBytes < 10) { printf("Perf test: unable to write %s\n", FileName); delete openFile; return; } } delete openFile; // close file } static void FileRead() { OpenFile *openFile; char *buffer = new char[ContentSize]; int i, numBytes; printf("Sequential read of %d byte file, in %d byte chunks\n", FileSize, ContentSize); if ((openFile = fileSystem->Open(FileName)) == NULL) { printf("Perf test: unable to open file %s\n", FileName); delete [] buffer; return; } for (i = 0; i < FileSize; i += ContentSize) { numBytes = openFile->Read(buffer, ContentSize); if ((numBytes < 10) || strncmp(buffer, Contents, ContentSize)) { printf("Perf test: unable to read %s\n", FileName); delete openFile; delete [] buffer; return; } } delete [] buffer; delete openFile; // close file } void PerformanceTest() { printf("Starting file system performance test:\n"); stats->Print(); FileWrite(); FileRead(); if (!fileSystem->Remove(FileName)) { printf("Perf test: unable to remove %s\n", FileName); return; } stats->Print(); }
C++
// filesys.h // Data structures to represent the Nachos file system. // // A file system is a set of files stored on disk, organized // into directories. Operations on the file system have to // do with "naming" -- creating, opening, and deleting files, // given a textual file name. Operations on an individual // "open" file (read, write, close) are to be found in the OpenFile // class (openfile.h). // // We define two separate implementations of the file system. // The "STUB" version just re-defines the Nachos file system // operations as operations on the native UNIX file system on the machine // running the Nachos simulation. This is provided in case the // multiprogramming and virtual memory assignments (which make use // of the file system) are done before the file system assignment. // // The other version is a "real" file system, built on top of // a disk simulator. The disk is simulated using the native UNIX // file system (in a file named "DISK"). // // In the "real" implementation, there are two key data structures used // in the file system. There is a single "root" directory, listing // all of the files in the file system; unlike UNIX, the baseline // system does not provide a hierarchical directory structure. // In addition, there is a bitmap for allocating // disk sectors. Both the root directory and the bitmap are themselves // stored as files in the Nachos file system -- this causes an interesting // bootstrap problem when the simulated disk is initialized. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef FS_H #define FS_H #include "copyright.h" #include "openfile.h" #ifdef FILESYS_STUB // Temporarily implement file system calls as // calls to UNIX, until the real file system // implementation is available class FileSystem { public: FileSystem(bool format) {} bool Create(char *name, int initialSize) { int fileDescriptor = OpenForWrite(name); if (fileDescriptor == -1) return FALSE; Close(fileDescriptor); return TRUE; } OpenFile* Open(char *name) { int fileDescriptor = OpenForReadWrite(name, FALSE); if (fileDescriptor == -1) return NULL; return new OpenFile(fileDescriptor); } bool Remove(char *name) { return Unlink(name) == 0; } }; #else // FILESYS class FileSystem { public: FileSystem(bool format); // Initialize the file system. // Must be called *after* "synchDisk" // has been initialized. // If "format", there is nothing on // the disk, so initialize the directory // and the bitmap of free blocks. bool Create(char *name, int initialSize); // Create a file (UNIX creat) OpenFile* Open(char *name); // Open a file (UNIX open) bool Remove(char *name); // Delete a file (UNIX unlink) void List(); // List all the files in the file system void Print(); // List all the files and their contents private: OpenFile* freeMapFile; // Bit map of free disk blocks, // represented as a file OpenFile* directoryFile; // "Root" directory -- list of // file names, represented as a file }; #endif // FILESYS #endif // FS_H
C++
// synchdisk.cc // Routines to synchronously access the disk. The physical disk // is an asynchronous device (disk requests return immediately, and // an interrupt happens later on). This is a layer on top of // the disk providing a synchronous interface (requests wait until // the request completes). // // Use a semaphore to synchronize the interrupt handlers with the // pending requests. And, because the physical disk can only // handle one operation at a time, use a lock to enforce mutual // exclusion. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "synchdisk.h" //---------------------------------------------------------------------- // DiskRequestDone // Disk interrupt handler. Need this to be a C routine, because // C++ can't handle pointers to member functions. //---------------------------------------------------------------------- static void DiskRequestDone (int arg) { SynchDisk* disk = (SynchDisk *)arg; disk->RequestDone(); } //---------------------------------------------------------------------- // SynchDisk::SynchDisk // Initialize the synchronous interface to the physical disk, in turn // initializing the physical disk. // // "name" -- UNIX file name to be used as storage for the disk data // (usually, "DISK") //---------------------------------------------------------------------- SynchDisk::SynchDisk(char* name) { semaphore = new Semaphore("synch disk", 0); lock = new Lock("synch disk lock"); disk = new Disk(name, DiskRequestDone, (int) this); } //---------------------------------------------------------------------- // SynchDisk::~SynchDisk // De-allocate data structures needed for the synchronous disk // abstraction. //---------------------------------------------------------------------- SynchDisk::~SynchDisk() { delete disk; delete lock; delete semaphore; } //---------------------------------------------------------------------- // SynchDisk::ReadSector // Read the contents of a disk sector into a buffer. Return only // after the data has been read. // // "sectorNumber" -- the disk sector to read // "data" -- the buffer to hold the contents of the disk sector //---------------------------------------------------------------------- void SynchDisk::ReadSector(int sectorNumber, char* data) { lock->Acquire(); // only one disk I/O at a time disk->ReadRequest(sectorNumber, data); semaphore->P(); // wait for interrupt lock->Release(); } //---------------------------------------------------------------------- // SynchDisk::WriteSector // Write the contents of a buffer into a disk sector. Return only // after the data has been written. // // "sectorNumber" -- the disk sector to be written // "data" -- the new contents of the disk sector //---------------------------------------------------------------------- void SynchDisk::WriteSector(int sectorNumber, char* data) { lock->Acquire(); // only one disk I/O at a time disk->WriteRequest(sectorNumber, data); semaphore->P(); // wait for interrupt lock->Release(); } //---------------------------------------------------------------------- // SynchDisk::RequestDone // Disk interrupt handler. Wake up any thread waiting for the disk // request to finish. //---------------------------------------------------------------------- void SynchDisk::RequestDone() { semaphore->V(); }
C++
// stats.h // Routines for managing statistics about Nachos performance. // // DO NOT CHANGE -- these stats are maintained by the machine emulation. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "utility.h" #include "stats.h" //---------------------------------------------------------------------- // Statistics::Statistics // Initialize performance metrics to zero, at system startup. //---------------------------------------------------------------------- Statistics::Statistics() { totalTicks = idleTicks = systemTicks = userTicks = 0; numDiskReads = numDiskWrites = 0; numConsoleCharsRead = numConsoleCharsWritten = 0; numPageFaults = numPacketsSent = numPacketsRecvd = 0; } //---------------------------------------------------------------------- // Statistics::Print // Print performance metrics, when we've finished everything // at system shutdown. //---------------------------------------------------------------------- void Statistics::Print() { printf("Ticks: total %d, idle %d, system %d, user %d\n", totalTicks, idleTicks, systemTicks, userTicks); printf("Disk I/O: reads %d, writes %d\n", numDiskReads, numDiskWrites); printf("Console I/O: reads %d, writes %d\n", numConsoleCharsRead, numConsoleCharsWritten); printf("Paging: faults %d\n", numPageFaults); printf("Network I/O: packets received %d, sent %d\n", numPacketsRecvd, numPacketsSent); }
C++
// timer.h // Data structures to emulate a hardware timer. // // A hardware timer generates a CPU interrupt every X milliseconds. // This means it can be used for implementing time-slicing, or for // having a thread go to sleep for a specific period of time. // // We emulate a hardware timer by scheduling an interrupt to occur // every time stats->totalTicks has increased by TimerTicks. // // In order to introduce some randomness into time-slicing, if "doRandom" // is set, then the interrupt comes after a random number of ticks. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef TIMER_H #define TIMER_H #include "copyright.h" #include "utility.h" // The following class defines a hardware timer. class Timer { public: Timer(VoidFunctionPtr timerHandler, int callArg, bool doRandom); // Initialize the timer, to call the interrupt // handler "timerHandler" every time slice. ~Timer() {} // Internal routines to the timer emulation -- DO NOT call these void TimerExpired(); // called internally when the hardware // timer generates an interrupt int TimeOfNextInterrupt(); // figure out when the timer will generate // its next interrupt private: bool randomize; // set if we need to use a random timeout delay VoidFunctionPtr handler; // timer interrupt handler int arg; // argument to pass to interrupt handler }; #endif // TIMER_H
C++
// translate.cc // Routines to translate virtual addresses to physical addresses. // Software sets up a table of legal translations. We look up // in the table on every memory reference to find the true physical // memory location. // // Two types of translation are supported here. // // Linear page table -- the virtual page # is used as an index // into the table, to find the physical page #. // // Translation lookaside buffer -- associative lookup in the table // to find an entry with the same virtual page #. If found, // this entry is used for the translation. // If not, it traps to software with an exception. // // In practice, the TLB is much smaller than the amount of physical // memory (16 entries is common on a machine that has 1000's of // pages). Thus, there must also be a backup translation scheme // (such as page tables), but the hardware doesn't need to know // anything at all about that. // // Note that the contents of the TLB are specific to an address space. // If the address space changes, so does the contents of the TLB! // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "machine.h" #include "addrspace.h" #include "system.h" // Routines for converting Words and Short Words to and from the // simulated machine's format of little endian. These end up // being NOPs when the host machine is also little endian (DEC and Intel). unsigned int WordToHost(unsigned int word) { #ifdef HOST_IS_BIG_ENDIAN register unsigned long result; result = (word >> 24) & 0x000000ff; result |= (word >> 8) & 0x0000ff00; result |= (word << 8) & 0x00ff0000; result |= (word << 24) & 0xff000000; return result; #else return word; #endif /* HOST_IS_BIG_ENDIAN */ } unsigned short ShortToHost(unsigned short shortword) { #ifdef HOST_IS_BIG_ENDIAN register unsigned short result; result = (shortword << 8) & 0xff00; result |= (shortword >> 8) & 0x00ff; return result; #else return shortword; #endif /* HOST_IS_BIG_ENDIAN */ } unsigned int WordToMachine(unsigned int word) { return WordToHost(word); } unsigned short ShortToMachine(unsigned short shortword) { return ShortToHost(shortword); } //---------------------------------------------------------------------- // Machine::ReadMem // Read "size" (1, 2, or 4) bytes of virtual memory at "addr" into // the location pointed to by "value". // // Returns FALSE if the translation step from virtual to physical memory // failed. // // "addr" -- the virtual address to read from // "size" -- the number of bytes to read (1, 2, or 4) // "value" -- the place to write the result //---------------------------------------------------------------------- bool Machine::ReadMem(int addr, int size, int *value) { int data; ExceptionType exception; int physicalAddress; DEBUG('a', "Reading VA 0x%x, size %d\n", addr, size); exception = Translate(addr, &physicalAddress, size, FALSE); if (exception != NoException) { machine->RaiseException(exception, addr); return FALSE; } switch (size) { case 1: data = machine->mainMemory[physicalAddress]; *value = data; break; case 2: data = *(unsigned short *) &machine->mainMemory[physicalAddress]; *value = ShortToHost(data); break; case 4: data = *(unsigned int *) &machine->mainMemory[physicalAddress]; *value = WordToHost(data); break; default: ASSERT(FALSE); } DEBUG('a', "\tvalue read = %8.8x\n", *value); return (TRUE); } //---------------------------------------------------------------------- // Machine::WriteMem // Write "size" (1, 2, or 4) bytes of the contents of "value" into // virtual memory at location "addr". // // Returns FALSE if the translation step from virtual to physical memory // failed. // // "addr" -- the virtual address to write to // "size" -- the number of bytes to be written (1, 2, or 4) // "value" -- the data to be written //---------------------------------------------------------------------- bool Machine::WriteMem(int addr, int size, int value) { ExceptionType exception; int physicalAddress; DEBUG('a', "Writing VA 0x%x, size %d, value 0x%x\n", addr, size, value); exception = Translate(addr, &physicalAddress, size, TRUE); if (exception != NoException) { machine->RaiseException(exception, addr); return FALSE; } switch (size) { case 1: machine->mainMemory[physicalAddress] = (unsigned char) (value & 0xff); break; case 2: *(unsigned short *) &machine->mainMemory[physicalAddress] = ShortToMachine((unsigned short) (value & 0xffff)); break; case 4: *(unsigned int *) &machine->mainMemory[physicalAddress] = WordToMachine((unsigned int) value); break; default: ASSERT(FALSE); } return TRUE; } //---------------------------------------------------------------------- // Machine::Translate // Translate a virtual address into a physical address, using // either a page table or a TLB. Check for alignment and all sorts // of other errors, and if everything is ok, set the use/dirty bits in // the translation table entry, and store the translated physical // address in "physAddr". If there was an error, returns the type // of the exception. // // "virtAddr" -- the virtual address to translate // "physAddr" -- the place to store the physical address // "size" -- the amount of memory being read or written // "writing" -- if TRUE, check the "read-only" bit in the TLB //---------------------------------------------------------------------- ExceptionType Machine::Translate(int virtAddr, int* physAddr, int size, bool writing) { int i; unsigned int vpn, offset; TranslationEntry *entry; unsigned int pageFrame; DEBUG('a', "\tTranslate 0x%x, %s: ", virtAddr, writing ? "write" : "read"); // check for alignment errors if (((size == 4) && (virtAddr & 0x3)) || ((size == 2) && (virtAddr & 0x1))){ DEBUG('a', "alignment problem at %d, size %d!\n", virtAddr, size); return AddressErrorException; } // we must have either a TLB or a page table, but not both! ASSERT(tlb == NULL || pageTable == NULL); ASSERT(tlb != NULL || pageTable != NULL); // calculate the virtual page number, and offset within the page, // from the virtual address vpn = (unsigned) virtAddr / PageSize; offset = (unsigned) virtAddr % PageSize; if (tlb == NULL) { // => page table => vpn is index into table if (vpn >= pageTableSize) { DEBUG('a', "virtual page # %d too large for page table size %d!\n", virtAddr, pageTableSize); return AddressErrorException; } else if (!pageTable[vpn].valid) { DEBUG('a', "virtual page # %d too large for page table size %d!\n", virtAddr, pageTableSize); return PageFaultException; } entry = &pageTable[vpn]; } else { for (entry = NULL, i = 0; i < TLBSize; i++) if (tlb[i].valid && (((unsigned int)tlb[i].virtualPage) == vpn)) { entry = &tlb[i]; // FOUND! break; } if (entry == NULL) { // not found DEBUG('a', "*** no valid TLB entry found for this virtual page!\n"); return PageFaultException; // really, this is a TLB fault, // the page may be in memory, // but not in the TLB } } if (entry->readOnly && writing) { // trying to write to a read-only page DEBUG('a', "%d mapped read-only at %d in TLB!\n", virtAddr, i); return ReadOnlyException; } pageFrame = entry->physicalPage; // if the pageFrame is too big, there is something really wrong! // An invalid translation was loaded into the page table or TLB. if (pageFrame >= NumPhysPages) { DEBUG('a', "*** frame %d > %d!\n", pageFrame, NumPhysPages); return BusErrorException; } entry->use = TRUE; // set the use, dirty bits DiskPageInfo* diskInfo = vmmanager->GetDiskPageInfo(entry->diskLoc/PageSize); diskInfo->MarkUse(TRUE); if (writing){ entry->dirty = TRUE; diskInfo->MarkDirty(TRUE); } *physAddr = pageFrame * PageSize + offset; ASSERT((*physAddr >= 0) && ((*physAddr + size) <= MemorySize)); DEBUG('a', "phys addr = 0x%x\n", *physAddr); return NoException; }
C++
// mipssim.cc -- simulate a MIPS R2/3000 processor // // This code has been adapted from Ousterhout's MIPSSIM package. // Byte ordering is little-endian, so we can be compatible with // DEC RISC systems. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "machine.h" #include "mipssim.h" #include "system.h" static void Mult(int a, int b, bool signedArith, int* hiPtr, int* loPtr); //---------------------------------------------------------------------- // Machine::Run // Simulate the execution of a user-level program on Nachos. // Called by the kernel when the program starts up; never returns. // // This routine is re-entrant, in that it can be called multiple // times concurrently -- one for each thread executing user code. //---------------------------------------------------------------------- void Machine::Run() { Instruction *instr = new Instruction; // storage for decoded instruction if(DebugIsEnabled('m')) printf("Starting thread \"%s\" at time %d\n", currentThread->getName(), stats->totalTicks); interrupt->setStatus(UserMode); for (;;) { OneInstruction(instr); interrupt->OneTick(); if (singleStep && (runUntilTime <= stats->totalTicks)) Debugger(); } } //---------------------------------------------------------------------- // TypeToReg // Retrieve the register # referred to in an instruction. //---------------------------------------------------------------------- static int TypeToReg(RegType reg, Instruction *instr) { switch (reg) { case RS: return instr->rs; case RT: return instr->rt; case RD: return instr->rd; case EXTRA: return instr->extra; default: return -1; } } //---------------------------------------------------------------------- // Machine::OneInstruction // Execute one instruction from a user-level program // // If there is any kind of exception or interrupt, we invoke the // exception handler, and when it returns, we return to Run(), which // will re-invoke us in a loop. This allows us to // re-start the instruction execution from the beginning, in // case any of our state has changed. On a syscall, // the OS software must increment the PC so execution begins // at the instruction immediately after the syscall. // // This routine is re-entrant, in that it can be called multiple // times concurrently -- one for each thread executing user code. // We get re-entrancy by never caching any data -- we always re-start the // simulation from scratch each time we are called (or after trapping // back to the Nachos kernel on an exception or interrupt), and we always // store all data back to the machine registers and memory before // leaving. This allows the Nachos kernel to control our behavior // by controlling the contents of memory, the translation table, // and the register set. //---------------------------------------------------------------------- void Machine::OneInstruction(Instruction *instr) { int raw; int nextLoadReg = 0; int nextLoadValue = 0; // record delayed load operation, to apply // in the future // Fetch instruction if (!machine->ReadMem(registers[PCReg], 4, &raw)) return; // exception occurred instr->value = raw; instr->Decode(); if (DebugIsEnabled('m')) { struct OpString *str = &opStrings[instr->opCode]; ASSERT(instr->opCode <= MaxOpcode); printf("At PC = 0x%x: ", registers[PCReg]); printf(str->string, TypeToReg(str->args[0], instr), TypeToReg(str->args[1], instr), TypeToReg(str->args[2], instr)); printf("\n"); } // Compute next pc, but don't install in case there's an error or branch. int pcAfter = registers[NextPCReg] + 4; int sum, diff, tmp, value; unsigned int rs, rt, imm; // Execute the instruction (cf. Kane's book) switch (instr->opCode) { case OP_ADD: sum = registers[instr->rs] + registers[instr->rt]; if (!((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT) && ((registers[instr->rs] ^ sum) & SIGN_BIT)) { RaiseException(OverflowException, 0); return; } registers[instr->rd] = sum; break; case OP_ADDI: sum = registers[instr->rs] + instr->extra; if (!((registers[instr->rs] ^ instr->extra) & SIGN_BIT) && ((instr->extra ^ sum) & SIGN_BIT)) { RaiseException(OverflowException, 0); return; } registers[instr->rt] = sum; break; case OP_ADDIU: registers[instr->rt] = registers[instr->rs] + instr->extra; break; case OP_ADDU: registers[instr->rd] = registers[instr->rs] + registers[instr->rt]; break; case OP_AND: registers[instr->rd] = registers[instr->rs] & registers[instr->rt]; break; case OP_ANDI: registers[instr->rt] = registers[instr->rs] & (instr->extra & 0xffff); break; case OP_BEQ: if (registers[instr->rs] == registers[instr->rt]) pcAfter = registers[NextPCReg] + IndexToAddr(instr->extra); break; case OP_BGEZAL: registers[R31] = registers[NextPCReg] + 4; case OP_BGEZ: if (!(registers[instr->rs] & SIGN_BIT)) pcAfter = registers[NextPCReg] + IndexToAddr(instr->extra); break; case OP_BGTZ: if (registers[instr->rs] > 0) pcAfter = registers[NextPCReg] + IndexToAddr(instr->extra); break; case OP_BLEZ: if (registers[instr->rs] <= 0) pcAfter = registers[NextPCReg] + IndexToAddr(instr->extra); break; case OP_BLTZAL: registers[R31] = registers[NextPCReg] + 4; case OP_BLTZ: if (registers[instr->rs] & SIGN_BIT) pcAfter = registers[NextPCReg] + IndexToAddr(instr->extra); break; case OP_BNE: if (registers[instr->rs] != registers[instr->rt]) pcAfter = registers[NextPCReg] + IndexToAddr(instr->extra); break; case OP_DIV: if (registers[instr->rt] == 0) { registers[LoReg] = 0; registers[HiReg] = 0; } else { registers[LoReg] = registers[instr->rs] / registers[instr->rt]; registers[HiReg] = registers[instr->rs] % registers[instr->rt]; } break; case OP_DIVU: rs = (unsigned int) registers[instr->rs]; rt = (unsigned int) registers[instr->rt]; if (rt == 0) { registers[LoReg] = 0; registers[HiReg] = 0; } else { tmp = rs / rt; registers[LoReg] = (int) tmp; tmp = rs % rt; registers[HiReg] = (int) tmp; } break; case OP_JAL: registers[R31] = registers[NextPCReg] + 4; case OP_J: pcAfter = (pcAfter & 0xf0000000) | IndexToAddr(instr->extra); break; case OP_JALR: registers[instr->rd] = registers[NextPCReg] + 4; case OP_JR: pcAfter = registers[instr->rs]; break; case OP_LB: case OP_LBU: tmp = registers[instr->rs] + instr->extra; if (!machine->ReadMem(tmp, 1, &value)) return; if ((value & 0x80) && (instr->opCode == OP_LB)) value |= 0xffffff00; else value &= 0xff; nextLoadReg = instr->rt; nextLoadValue = value; break; case OP_LH: case OP_LHU: tmp = registers[instr->rs] + instr->extra; if (tmp & 0x1) { RaiseException(AddressErrorException, tmp); return; } if (!machine->ReadMem(tmp, 2, &value)) return; if ((value & 0x8000) && (instr->opCode == OP_LH)) value |= 0xffff0000; else value &= 0xffff; nextLoadReg = instr->rt; nextLoadValue = value; break; case OP_LUI: DEBUG('m', "Executing: LUI r%d,%d\n", instr->rt, instr->extra); registers[instr->rt] = instr->extra << 16; break; case OP_LW: tmp = registers[instr->rs] + instr->extra; if (tmp & 0x3) { RaiseException(AddressErrorException, tmp); return; } if (!machine->ReadMem(tmp, 4, &value)) return; nextLoadReg = instr->rt; nextLoadValue = value; break; case OP_LWL: tmp = registers[instr->rs] + instr->extra; // ReadMem assumes all 4 byte requests are aligned on an even // word boundary. Also, the little endian/big endian swap code would // fail (I think) if the other cases are ever exercised. ASSERT((tmp & 0x3) == 0); if (!machine->ReadMem(tmp, 4, &value)) return; if (registers[LoadReg] == instr->rt) nextLoadValue = registers[LoadValueReg]; else nextLoadValue = registers[instr->rt]; switch (tmp & 0x3) { case 0: nextLoadValue = value; break; case 1: nextLoadValue = (nextLoadValue & 0xff) | (value << 8); break; case 2: nextLoadValue = (nextLoadValue & 0xffff) | (value << 16); break; case 3: nextLoadValue = (nextLoadValue & 0xffffff) | (value << 24); break; } nextLoadReg = instr->rt; break; case OP_LWR: tmp = registers[instr->rs] + instr->extra; // ReadMem assumes all 4 byte requests are aligned on an even // word boundary. Also, the little endian/big endian swap code would // fail (I think) if the other cases are ever exercised. ASSERT((tmp & 0x3) == 0); if (!machine->ReadMem(tmp, 4, &value)) return; if (registers[LoadReg] == instr->rt) nextLoadValue = registers[LoadValueReg]; else nextLoadValue = registers[instr->rt]; switch (tmp & 0x3) { case 0: nextLoadValue = (nextLoadValue & 0xffffff00) | ((value >> 24) & 0xff); break; case 1: nextLoadValue = (nextLoadValue & 0xffff0000) | ((value >> 16) & 0xffff); break; case 2: nextLoadValue = (nextLoadValue & 0xff000000) | ((value >> 8) & 0xffffff); break; case 3: nextLoadValue = value; break; } nextLoadReg = instr->rt; break; case OP_MFHI: registers[instr->rd] = registers[HiReg]; break; case OP_MFLO: registers[instr->rd] = registers[LoReg]; break; case OP_MTHI: registers[HiReg] = registers[instr->rs]; break; case OP_MTLO: registers[LoReg] = registers[instr->rs]; break; case OP_MULT: Mult(registers[instr->rs], registers[instr->rt], TRUE, &registers[HiReg], &registers[LoReg]); break; case OP_MULTU: Mult(registers[instr->rs], registers[instr->rt], FALSE, &registers[HiReg], &registers[LoReg]); break; case OP_NOR: registers[instr->rd] = ~(registers[instr->rs] | registers[instr->rt]); break; case OP_OR: registers[instr->rd] = registers[instr->rs] | registers[instr->rs]; break; case OP_ORI: registers[instr->rt] = registers[instr->rs] | (instr->extra & 0xffff); break; case OP_SB: if (!machine->WriteMem((unsigned) (registers[instr->rs] + instr->extra), 1, registers[instr->rt])) return; break; case OP_SH: if (!machine->WriteMem((unsigned) (registers[instr->rs] + instr->extra), 2, registers[instr->rt])) return; break; case OP_SLL: registers[instr->rd] = registers[instr->rt] << instr->extra; break; case OP_SLLV: registers[instr->rd] = registers[instr->rt] << (registers[instr->rs] & 0x1f); break; case OP_SLT: if (registers[instr->rs] < registers[instr->rt]) registers[instr->rd] = 1; else registers[instr->rd] = 0; break; case OP_SLTI: if (registers[instr->rs] < instr->extra) registers[instr->rt] = 1; else registers[instr->rt] = 0; break; case OP_SLTIU: rs = registers[instr->rs]; imm = instr->extra; if (rs < imm) registers[instr->rt] = 1; else registers[instr->rt] = 0; break; case OP_SLTU: rs = registers[instr->rs]; rt = registers[instr->rt]; if (rs < rt) registers[instr->rd] = 1; else registers[instr->rd] = 0; break; case OP_SRA: registers[instr->rd] = registers[instr->rt] >> instr->extra; break; case OP_SRAV: registers[instr->rd] = registers[instr->rt] >> (registers[instr->rs] & 0x1f); break; case OP_SRL: tmp = registers[instr->rt]; tmp >>= instr->extra; registers[instr->rd] = tmp; break; case OP_SRLV: tmp = registers[instr->rt]; tmp >>= (registers[instr->rs] & 0x1f); registers[instr->rd] = tmp; break; case OP_SUB: diff = registers[instr->rs] - registers[instr->rt]; if (((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT) && ((registers[instr->rs] ^ diff) & SIGN_BIT)) { RaiseException(OverflowException, 0); return; } registers[instr->rd] = diff; break; case OP_SUBU: registers[instr->rd] = registers[instr->rs] - registers[instr->rt]; break; case OP_SW: if (!machine->WriteMem((unsigned) (registers[instr->rs] + instr->extra), 4, registers[instr->rt])) return; break; case OP_SWL: tmp = registers[instr->rs] + instr->extra; // The little endian/big endian swap code would // fail (I think) if the other cases are ever exercised. ASSERT((tmp & 0x3) == 0); if (!machine->ReadMem((tmp & ~0x3), 4, &value)) return; switch (tmp & 0x3) { case 0: value = registers[instr->rt]; break; case 1: value = (value & 0xff000000) | ((registers[instr->rt] >> 8) & 0xffffff); break; case 2: value = (value & 0xffff0000) | ((registers[instr->rt] >> 16) & 0xffff); break; case 3: value = (value & 0xffffff00) | ((registers[instr->rt] >> 24) & 0xff); break; } if (!machine->WriteMem((tmp & ~0x3), 4, value)) return; break; case OP_SWR: tmp = registers[instr->rs] + instr->extra; // The little endian/big endian swap code would // fail (I think) if the other cases are ever exercised. ASSERT((tmp & 0x3) == 0); if (!machine->ReadMem((tmp & ~0x3), 4, &value)) return; switch (tmp & 0x3) { case 0: value = (value & 0xffffff) | (registers[instr->rt] << 24); break; case 1: value = (value & 0xffff) | (registers[instr->rt] << 16); break; case 2: value = (value & 0xff) | (registers[instr->rt] << 8); break; case 3: value = registers[instr->rt]; break; } if (!machine->WriteMem((tmp & ~0x3), 4, value)) return; break; case OP_SYSCALL: RaiseException(SyscallException, 0); return; case OP_XOR: registers[instr->rd] = registers[instr->rs] ^ registers[instr->rt]; break; case OP_XORI: registers[instr->rt] = registers[instr->rs] ^ (instr->extra & 0xffff); break; case OP_RES: case OP_UNIMP: RaiseException(IllegalInstrException, 0); return; default: ASSERT(FALSE); } // Now we have successfully executed the instruction. // Do any delayed load operation DelayedLoad(nextLoadReg, nextLoadValue); // Advance program counters. registers[PrevPCReg] = registers[PCReg]; // for debugging, in case we // are jumping into lala-land registers[PCReg] = registers[NextPCReg]; registers[NextPCReg] = pcAfter; } //---------------------------------------------------------------------- // Machine::DelayedLoad // Simulate effects of a delayed load. // // NOTE -- RaiseException/CheckInterrupts must also call DelayedLoad, // since any delayed load must get applied before we trap to the kernel. //---------------------------------------------------------------------- void Machine::DelayedLoad(int nextReg, int nextValue) { registers[registers[LoadReg]] = registers[LoadValueReg]; registers[LoadReg] = nextReg; registers[LoadValueReg] = nextValue; registers[0] = 0; // and always make sure R0 stays zero. } //---------------------------------------------------------------------- // Instruction::Decode // Decode a MIPS instruction //---------------------------------------------------------------------- void Instruction::Decode() { OpInfo *opPtr; rs = (value >> 21) & 0x1f; rt = (value >> 16) & 0x1f; rd = (value >> 11) & 0x1f; opPtr = &opTable[(value >> 26) & 0x3f]; opCode = opPtr->opCode; if (opPtr->format == IFMT) { extra = value & 0xffff; if (extra & 0x8000) { extra |= 0xffff0000; } } else if (opPtr->format == RFMT) { extra = (value >> 6) & 0x1f; } else { extra = value & 0x3ffffff; } if (opCode == SPECIAL) { opCode = specialTable[value & 0x3f]; } else if (opCode == BCOND) { int i = value & 0x1f0000; if (i == 0) { opCode = OP_BLTZ; } else if (i == 0x10000) { opCode = OP_BGEZ; } else if (i == 0x100000) { opCode = OP_BLTZAL; } else if (i == 0x110000) { opCode = OP_BGEZAL; } else { opCode = OP_UNIMP; } } } //---------------------------------------------------------------------- // Mult // Simulate R2000 multiplication. // The words at *hiPtr and *loPtr are overwritten with the // double-length result of the multiplication. //---------------------------------------------------------------------- static void Mult(int a, int b, bool signedArith, int* hiPtr, int* loPtr) { if ((a == 0) || (b == 0)) { *hiPtr = *loPtr = 0; return; } // Compute the sign of the result, then make everything positive // so unsigned computation can be done in the main loop. bool negative = FALSE; if (signedArith) { if (a < 0) { negative = !negative; a = -a; } if (b < 0) { negative = !negative; b = -b; } } // Compute the result in unsigned arithmetic (check a's bits one at // a time, and add in a shifted value of b). unsigned int bLo = b; unsigned int bHi = 0; unsigned int lo = 0; unsigned int hi = 0; for (int i = 0; i < 32; i++) { if (a & 1) { lo += bLo; if (lo < bLo) // Carry out of the low bits? hi += 1; hi += bHi; if ((a & 0xfffffffe) == 0) break; } bHi <<= 1; if (bLo & 0x80000000) bHi |= 1; bLo <<= 1; a >>= 1; } // If the result is supposed to be negative, compute the two's // complement of the double-word result. if (negative) { hi = ~hi; lo = ~lo; lo++; if (lo == 0) hi++; } *hiPtr = (int) hi; *loPtr = (int) lo; }
C++
// console.h // Data structures to simulate the behavior of a terminal // I/O device. A terminal has two parts -- a keyboard input, // and a display output, each of which produces/accepts // characters sequentially. // // The console hardware device is asynchronous. When a character is // written to the device, the routine returns immediately, and an // interrupt handler is called later when the I/O completes. // For reads, an interrupt handler is called when a character arrives. // // The user of the device can specify the routines to be called when // the read/write interrupts occur. There is a separate interrupt // for read and write, and the device is "duplex" -- a character // can be outgoing and incoming at the same time. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef CONSOLE_H #define CONSOLE_H #include "copyright.h" #include "utility.h" // The following class defines a hardware console device. // Input and output to the device is simulated by reading // and writing to UNIX files ("readFile" and "writeFile"). // // Since the device is asynchronous, the interrupt handler "readAvail" // is called when a character has arrived, ready to be read in. // The interrupt handler "writeDone" is called when an output character // has been "put", so that the next character can be written. class Console { public: Console(char *readFile, char *writeFile, VoidFunctionPtr readAvail, VoidFunctionPtr writeDone, int callArg); // initialize the hardware console device ~Console(); // clean up console emulation // external interface -- Nachos kernel code can call these void PutChar(char ch); // Write "ch" to the console display, // and return immediately. "writeHandler" // is called when the I/O completes. char GetChar(); // Poll the console input. If a char is // available, return it. Otherwise, return EOF. // "readHandler" is called whenever there is // a char to be gotten // internal emulation routines -- DO NOT call these. void WriteDone(); // internal routines to signal I/O completion void CheckCharAvail(); private: int readFileNo; // UNIX file emulating the keyboard int writeFileNo; // UNIX file emulating the display VoidFunctionPtr writeHandler; // Interrupt handler to call when // the PutChar I/O completes VoidFunctionPtr readHandler; // Interrupt handler to call when // a character arrives from the keyboard int handlerArg; // argument to be passed to the // interrupt handlers bool putBusy; // Is a PutChar operation in progress? // If so, you can't do another one! char incoming; // Contains the character to be read, // if there is one available. // Otherwise contains EOF. }; #endif // CONSOLE_H
C++
// interrupt.h // Data structures to emulate low-level interrupt hardware. // // The hardware provides a routine (SetLevel) to enable or disable // interrupts. // // In order to emulate the hardware, we need to keep track of all // interrupts the hardware devices would cause, and when they // are supposed to occur. // // This module also keeps track of simulated time. Time advances // only when the following occur: // interrupts are re-enabled // a user instruction is executed // there is nothing in the ready queue // // As a result, unlike real hardware, interrupts (and thus time-slice // context switches) cannot occur anywhere in the code where interrupts // are enabled, but rather only at those places in the code where // simulated time advances (so that it becomes time to invoke an // interrupt in the hardware simulation). // // NOTE: this means that incorrectly synchronized code may work // fine on this hardware simulation (even with randomized time slices), // but it wouldn't work on real hardware. (Just because we can't // always detect when your program would fail in real life, does not // mean it's ok to write incorrectly synchronized code!) // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef INTERRUPT_H #define INTERRUPT_H #include "copyright.h" #include "list.h" // Interrupts can be disabled (IntOff) or enabled (IntOn) enum IntStatus { IntOff, IntOn }; // Nachos can be running kernel code (SystemMode), user code (UserMode), // or there can be no runnable thread, because the ready list // is empty (IdleMode). enum MachineStatus {IdleMode, SystemMode, UserMode}; // IntType records which hardware device generated an interrupt. // In Nachos, we support a hardware timer device, a disk, a console // display and keyboard, and a network. enum IntType { TimerInt, DiskInt, ConsoleWriteInt, ConsoleReadInt, NetworkSendInt, NetworkRecvInt}; // The following class defines an interrupt that is scheduled // to occur in the future. The internal data structures are // left public to make it simpler to manipulate. class PendingInterrupt { public: PendingInterrupt(VoidFunctionPtr func, int param, int time, IntType kind); // initialize an interrupt that will // occur in the future VoidFunctionPtr handler; // The function (in the hardware device // emulator) to call when the interrupt occurs int arg; // The argument to the function. int when; // When the interrupt is supposed to fire IntType type; // for debugging }; // The following class defines the data structures for the simulation // of hardware interrupts. We record whether interrupts are enabled // or disabled, and any hardware interrupts that are scheduled to occur // in the future. class Interrupt { public: Interrupt(); // initialize the interrupt simulation ~Interrupt(); // de-allocate data structures IntStatus SetLevel(IntStatus level);// Disable or enable interrupts // and return previous setting. void Enable(); // Enable interrupts. IntStatus getLevel() {return level;}// Return whether interrupts // are enabled or disabled void Idle(); // The ready queue is empty, roll // simulated time forward until the // next interrupt void Halt(); // quit and print out stats void YieldOnReturn(); // cause a context switch on return // from an interrupt handler MachineStatus getStatus() { return status; } // idle, kernel, user void setStatus(MachineStatus st) { status = st; } void DumpState(); // Print interrupt state // NOTE: the following are internal to the hardware simulation code. // DO NOT call these directly. I should make them "private", // but they need to be public since they are called by the // hardware device simulators. void Schedule(VoidFunctionPtr handler,// Schedule an interrupt to occur int arg, int when, IntType type);// at time ``when''. This is called // by the hardware device simulators. void OneTick(); // Advance simulated time private: IntStatus level; // are interrupts enabled or disabled? List *pending; // the list of interrupts scheduled // to occur in the future bool inHandler; // TRUE if we are running an interrupt handler bool yieldOnReturn; // TRUE if we are to context switch // on return from the interrupt handler MachineStatus status; // idle, kernel mode, user mode // these functions are internal to the interrupt simulation code bool CheckIfDue(bool advanceClock); // Check if an interrupt is supposed // to occur now void ChangeLevel(IntStatus old, // SetLevel, without advancing the IntStatus now); // simulated time }; #endif // INTERRRUPT_H
C++
// network.cc // Routines to simulate a network interface, using UNIX sockets // to deliver packets between multiple invocations of nachos. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #ifdef HOST_SPARC #include <strings.h> #endif // Dummy functions because C++ can't call member functions indirectly static void NetworkReadPoll(int arg) { Network *net = (Network *)arg; net->CheckPktAvail(); } static void NetworkSendDone(int arg) { Network *net = (Network *)arg; net->SendDone(); } // Initialize the network emulation // addr is used to generate the socket name // reliability says whether we drop packets to emulate unreliable links // readAvail, writeDone, callArg -- analogous to console Network::Network(NetworkAddress addr, double reliability, VoidFunctionPtr readAvail, VoidFunctionPtr writeDone, int callArg) { ident = addr; if (reliability < 0) chanceToWork = 0; else if (reliability > 1) chanceToWork = 1; else chanceToWork = reliability; // set up the stuff to emulate asynchronous interrupts writeHandler = writeDone; readHandler = readAvail; handlerArg = callArg; sendBusy = FALSE; inHdr.length = 0; sock = OpenSocket(); sprintf(sockName, "SOCKET_%d", (int)addr); AssignNameToSocket(sockName, sock); // Bind socket to a filename // in the current directory. // start polling for incoming packets interrupt->Schedule(NetworkReadPoll, (int)this, NetworkTime, NetworkRecvInt); } Network::~Network() { CloseSocket(sock); DeAssignNameToSocket(sockName); } // if a packet is already buffered, we simply delay reading // the incoming packet. In real life, the incoming // packet might be dropped if we can't read it in time. void Network::CheckPktAvail() { // schedule the next time to poll for a packet interrupt->Schedule(NetworkReadPoll, (int)this, NetworkTime, NetworkRecvInt); if (inHdr.length != 0) // do nothing if packet is already buffered return; if (!PollSocket(sock)) // do nothing if no packet to be read return; // otherwise, read packet in char *buffer = new char[MaxWireSize]; ReadFromSocket(sock, buffer, MaxWireSize); // divide packet into header and data inHdr = *(PacketHeader *)buffer; ASSERT((inHdr.to == ident) && (inHdr.length <= MaxPacketSize)); bcopy(buffer + sizeof(PacketHeader), inbox, inHdr.length); delete []buffer ; DEBUG('n', "Network received packet from %d, length %d...\n", (int) inHdr.from, inHdr.length); stats->numPacketsRecvd++; // tell post office that the packet has arrived (*readHandler)(handlerArg); } // notify user that another packet can be sent void Network::SendDone() { sendBusy = FALSE; stats->numPacketsSent++; (*writeHandler)(handlerArg); } // send a packet by concatenating hdr and data, and schedule // an interrupt to tell the user when the next packet can be sent // // Note we always pad out a packet to MaxWireSize before putting it into // the socket, because it's simpler at the receive end. void Network::Send(PacketHeader hdr, char* data) { char toName[32]; sprintf(toName, "SOCKET_%d", (int)hdr.to); ASSERT((sendBusy == FALSE) && (hdr.length > 0) && (hdr.length <= MaxPacketSize) && (hdr.from == ident)); DEBUG('n', "Sending to addr %d, %d bytes... ", hdr.to, hdr.length); interrupt->Schedule(NetworkSendDone, (int)this, NetworkTime, NetworkSendInt); if (Random() % 100 >= chanceToWork * 100) { // emulate a lost packet DEBUG('n', "oops, lost it!\n"); return; } // concatenate hdr and data into a single buffer, and send it out char *buffer = new char[MaxWireSize]; *(PacketHeader *)buffer = hdr; bcopy(data, buffer + sizeof(PacketHeader), hdr.length); SendToSocket(sock, buffer, MaxWireSize, toName); delete []buffer; } // read a packet, if one is buffered PacketHeader Network::Receive(char* data) { PacketHeader hdr = inHdr; inHdr.length = 0; if (hdr.length != 0) bcopy(inbox, data, hdr.length); return hdr; }
C++
// network.h // Data structures to emulate a physical network connection. // The network provides the abstraction of ordered, unreliable, // fixed-size packet delivery to other machines on the network. // // You may note that the interface to the network is similar to // the console device -- both are full duplex channels. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef NETWORK_H #define NETWORK_H #include "copyright.h" #include "utility.h" // Network address -- uniquely identifies a machine. This machine's ID // is given on the command line. typedef int NetworkAddress; // The following class defines the network packet header. // The packet header is prepended to the data payload by the Network driver, // before the packet is sent over the wire. The format on the wire is: // packet header (PacketHeader) // data (containing MailHeader from the PostOffice!) class PacketHeader { public: NetworkAddress to; // Destination machine ID NetworkAddress from; // source machine ID unsigned length; // bytes of packet data, excluding the // packet header (but including the // MailHeader prepended by the post office) }; #define MaxWireSize 64 // largest packet that can go out on the wire #define MaxPacketSize (MaxWireSize - sizeof(struct PacketHeader)) // data "payload" of the largest packet // The following class defines a physical network device. The network // is capable of delivering fixed sized packets, in order but unreliably, // to other machines connected to the network. // // The "reliability" of the network can be specified to the constructor. // This number, between 0 and 1, is the chance that the network will lose // a packet. Note that you can change the seed for the random number // generator, by changing the arguments to RandomInit() in Initialize(). // The random number generator is used to choose which packets to drop. class Network { public: Network(NetworkAddress addr, double reliability, VoidFunctionPtr readAvail, VoidFunctionPtr writeDone, int callArg); // Allocate and initialize network driver ~Network(); // De-allocate the network driver data void Send(PacketHeader hdr, char* data); // Send the packet data to a remote machine, // specified by "hdr". Returns immediately. // "writeHandler" is invoked once the next // packet can be sent. Note that writeHandler // is called whether or not the packet is // dropped, and note that the "from" field of // the PacketHeader is filled in automatically // by Send(). PacketHeader Receive(char* data); // Poll the network for incoming messages. // If there is a packet waiting, copy the // packet into "data" and return the header. // If no packet is waiting, return a header // with length 0. void SendDone(); // Interrupt handler, called when message is // sent void CheckPktAvail(); // Check if there is an incoming packet private: NetworkAddress ident; // This machine's network address double chanceToWork; // Likelihood packet will be dropped int sock; // UNIX socket number for incoming packets char sockName[32]; // File name corresponding to UNIX socket VoidFunctionPtr writeHandler; // Interrupt handler, signalling next packet // can be sent. VoidFunctionPtr readHandler; // Interrupt handler, signalling packet has // arrived. int handlerArg; // Argument to be passed to interrupt handler // (pointer to post office) bool sendBusy; // Packet is being sent. bool packetAvail; // Packet has arrived, can be pulled off of // network PacketHeader inHdr; // Information about arrived packet char inbox[MaxPacketSize]; // Data for arrived packet }; #endif // NETWORK_H
C++
// disk.h // Data structures to emulate a physical disk. A physical disk // can accept (one at a time) requests to read/write a disk sector; // when the request is satisfied, the CPU gets an interrupt, and // the next request can be sent to the disk. // // Disk contents are preserved across machine crashes, but if // a file system operation (eg, create a file) is in progress when the // system shuts down, the file system may be corrupted. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef DISK_H #define DISK_H #include "copyright.h" #include "utility.h" // The following class defines a physical disk I/O device. The disk // has a single surface, split up into "tracks", and each track split // up into "sectors" (the same number of sectors on each track, and each // sector has the same number of bytes of storage). // // Addressing is by sector number -- each sector on the disk is given // a unique number: track * SectorsPerTrack + offset within a track. // // As with other I/O devices, the raw physical disk is an asynchronous device -- // requests to read or write portions of the disk return immediately, // and an interrupt is invoked later to signal that the operation completed. // // The physical disk is in fact simulated via operations on a UNIX file. // // To make life a little more realistic, the simulated time for // each operation reflects a "track buffer" -- RAM to store the contents // of the current track as the disk head passes by. The idea is that the // disk always transfers to the track buffer, in case that data is requested // later on. This has the benefit of eliminating the need for // "skip-sector" scheduling -- a read request which comes in shortly after // the head has passed the beginning of the sector can be satisfied more // quickly, because its contents are in the track buffer. Most // disks these days now come with a track buffer. // // The track buffer simulation can be disabled by compiling with -DNOTRACKBUF #define SectorSize 128 // number of bytes per disk sector #define SectorsPerTrack 32 // number of sectors per disk track #define NumTracks 32 // number of tracks per disk #define NumSectors (SectorsPerTrack * NumTracks) // total # of sectors per disk class Disk { public: Disk(char* name, VoidFunctionPtr callWhenDone, int callArg); // Create a simulated disk. // Invoke (*callWhenDone)(callArg) // every time a request completes. ~Disk(); // Deallocate the disk. void ReadRequest(int sectorNumber, char* data); // Read/write an single disk sector. // These routines send a request to // the disk and return immediately. // Only one request allowed at a time! void WriteRequest(int sectorNumber, char* data); void HandleInterrupt(); // Interrupt handler, invoked when // disk request finishes. int ComputeLatency(int newSector, bool writing); // Return how long a request to // newSector will take: // (seek + rotational delay + transfer) private: int fileno; // UNIX file number for simulated disk VoidFunctionPtr handler; // Interrupt handler, to be invoked // when any disk request finishes int handlerArg; // Argument to interrupt handler bool active; // Is a disk operation in progress? int lastSector; // The previous disk request int bufferInit; // When the track buffer started // being loaded int TimeToSeek(int newSector, int *rotate); // time to get to the new track int ModuloDiff(int to, int from); // # sectors between to and from void UpdateLast(int newSector); }; #endif // DISK_H
C++
// timer.cc // Routines to emulate a hardware timer device. // // A hardware timer generates a CPU interrupt every X milliseconds. // This means it can be used for implementing time-slicing. // // We emulate a hardware timer by scheduling an interrupt to occur // every time stats->totalTicks has increased by TimerTicks. // // In order to introduce some randomness into time-slicing, if "doRandom" // is set, then the interrupt is comes after a random number of ticks. // // Remember -- nothing in here is part of Nachos. It is just // an emulation for the hardware that Nachos is running on top of. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "timer.h" #include "system.h" // dummy function because C++ does not allow pointers to member functions static void TimerHandler(int arg) { Timer *p = (Timer *)arg; p->TimerExpired(); } //---------------------------------------------------------------------- // Timer::Timer // Initialize a hardware timer device. Save the place to call // on each interrupt, and then arrange for the timer to start // generating interrupts. // // "timerHandler" is the interrupt handler for the timer device. // It is called with interrupts disabled every time the // the timer expires. // "callArg" is the parameter to be passed to the interrupt handler. // "doRandom" -- if true, arrange for the interrupts to occur // at random, instead of fixed, intervals. //---------------------------------------------------------------------- Timer::Timer(VoidFunctionPtr timerHandler, int callArg, bool doRandom) { randomize = doRandom; handler = timerHandler; arg = callArg; // schedule the first interrupt from the timer device interrupt->Schedule(TimerHandler, (int) this, TimeOfNextInterrupt(), TimerInt); } //---------------------------------------------------------------------- // Timer::TimerExpired // Routine to simulate the interrupt generated by the hardware // timer device. Schedule the next interrupt, and invoke the // interrupt handler. //---------------------------------------------------------------------- void Timer::TimerExpired() { // schedule the next timer device interrupt interrupt->Schedule(TimerHandler, (int) this, TimeOfNextInterrupt(), TimerInt); // invoke the Nachos interrupt handler for this device (*handler)(arg); } //---------------------------------------------------------------------- // Timer::TimeOfNextInterrupt // Return when the hardware timer device will next cause an interrupt. // If randomize is turned on, make it a (pseudo-)random delay. //---------------------------------------------------------------------- int Timer::TimeOfNextInterrupt() { if (randomize) return 1 + (Random() % (TimerTicks * 2)); else return TimerTicks; }
C++
// disk.cc // Routines to simulate a physical disk device; reading and writing // to the disk is simulated as reading and writing to a UNIX file. // See disk.h for details about the behavior of disks (and // therefore about the behavior of this simulation). // // Disk operations are asynchronous, so we have to invoke an interrupt // handler when the simulated operation completes. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "disk.h" #include "system.h" // We put this at the front of the UNIX file representing the // disk, to make it less likely we will accidentally treat a useful file // as a disk (which would probably trash the file's contents). #define MagicNumber 0x456789ab #define MagicSize sizeof(int) #define DiskSize (MagicSize + (NumSectors * SectorSize)) // dummy procedure because we can't take a pointer of a member function static void DiskDone(int arg) { ((Disk *)arg)->HandleInterrupt(); } //---------------------------------------------------------------------- // Disk::Disk() // Initialize a simulated disk. Open the UNIX file (creating it // if it doesn't exist), and check the magic number to make sure it's // ok to treat it as Nachos disk storage. // // "name" -- text name of the file simulating the Nachos disk // "callWhenDone" -- interrupt handler to be called when disk read/write // request completes // "callArg" -- argument to pass the interrupt handler //---------------------------------------------------------------------- Disk::Disk(char* name, VoidFunctionPtr callWhenDone, int callArg) { int magicNum; int tmp = 0; DEBUG('d', "Initializing the disk, 0x%x 0x%x\n", callWhenDone, callArg); handler = callWhenDone; handlerArg = callArg; lastSector = 0; bufferInit = 0; fileno = OpenForReadWrite(name, FALSE); if (fileno >= 0) { // file exists, check magic number Read(fileno, (char *) &magicNum, MagicSize); ASSERT(magicNum == MagicNumber); } else { // file doesn't exist, create it fileno = OpenForWrite(name); magicNum = MagicNumber; WriteFile(fileno, (char *) &magicNum, MagicSize); // write magic number // need to write at end of file, so that reads will not return EOF Lseek(fileno, DiskSize - sizeof(int), 0); WriteFile(fileno, (char *)&tmp, sizeof(int)); } active = FALSE; } //---------------------------------------------------------------------- // Disk::~Disk() // Clean up disk simulation, by closing the UNIX file representing the // disk. //---------------------------------------------------------------------- Disk::~Disk() { Close(fileno); } //---------------------------------------------------------------------- // Disk::PrintSector() // Dump the data in a disk read/write request, for debugging. //---------------------------------------------------------------------- static void PrintSector (bool writing, int sector, char *data) { int *p = (int *) data; if (writing) printf("Writing sector: %d\n", sector); else printf("Reading sector: %d\n", sector); for (unsigned int i = 0; i < (SectorSize/sizeof(int)); i++) printf("%x ", p[i]); printf("\n"); } //---------------------------------------------------------------------- // Disk::ReadRequest/WriteRequest // Simulate a request to read/write a single disk sector // Do the read/write immediately to the UNIX file // Set up an interrupt handler to be called later, // that will notify the caller when the simulator says // the operation has completed. // // Note that a disk only allows an entire sector to be read/written, // not part of a sector. // // "sectorNumber" -- the disk sector to read/write // "data" -- the bytes to be written, the buffer to hold the incoming bytes //---------------------------------------------------------------------- void Disk::ReadRequest(int sectorNumber, char* data) { int ticks = ComputeLatency(sectorNumber, FALSE); ASSERT(!active); // only one request at a time ASSERT((sectorNumber >= 0) && (sectorNumber < NumSectors)); DEBUG('d', "Reading from sector %d\n", sectorNumber); Lseek(fileno, SectorSize * sectorNumber + MagicSize, 0); Read(fileno, data, SectorSize); if (DebugIsEnabled('d')) PrintSector(FALSE, sectorNumber, data); active = TRUE; UpdateLast(sectorNumber); stats->numDiskReads++; interrupt->Schedule(DiskDone, (int) this, ticks, DiskInt); } void Disk::WriteRequest(int sectorNumber, char* data) { int ticks = ComputeLatency(sectorNumber, TRUE); ASSERT(!active); ASSERT((sectorNumber >= 0) && (sectorNumber < NumSectors)); DEBUG('d', "Writing to sector %d\n", sectorNumber); Lseek(fileno, SectorSize * sectorNumber + MagicSize, 0); WriteFile(fileno, data, SectorSize); if (DebugIsEnabled('d')) PrintSector(TRUE, sectorNumber, data); active = TRUE; UpdateLast(sectorNumber); stats->numDiskWrites++; interrupt->Schedule(DiskDone, (int) this, ticks, DiskInt); } //---------------------------------------------------------------------- // Disk::HandleInterrupt() // Called when it is time to invoke the disk interrupt handler, // to tell the Nachos kernel that the disk request is done. //---------------------------------------------------------------------- void Disk::HandleInterrupt () { active = FALSE; (*handler)(handlerArg); } //---------------------------------------------------------------------- // Disk::TimeToSeek() // Returns how long it will take to position the disk head over the correct // track on the disk. Since when we finish seeking, we are likely // to be in the middle of a sector that is rotating past the head, // we also return how long until the head is at the next sector boundary. // // Disk seeks at one track per SeekTime ticks (cf. stats.h) // and rotates at one sector per RotationTime ticks //---------------------------------------------------------------------- int Disk::TimeToSeek(int newSector, int *rotation) { int newTrack = newSector / SectorsPerTrack; int oldTrack = lastSector / SectorsPerTrack; int seek = abs(newTrack - oldTrack) * SeekTime; // how long will seek take? int over = (stats->totalTicks + seek) % RotationTime; // will we be in the middle of a sector when // we finish the seek? *rotation = 0; if (over > 0) // if so, need to round up to next full sector *rotation = RotationTime - over; return seek; } //---------------------------------------------------------------------- // Disk::ModuloDiff() // Return number of sectors of rotational delay between target sector // "to" and current sector position "from" //---------------------------------------------------------------------- int Disk::ModuloDiff(int to, int from) { int toOffset = to % SectorsPerTrack; int fromOffset = from % SectorsPerTrack; return ((toOffset - fromOffset) + SectorsPerTrack) % SectorsPerTrack; } //---------------------------------------------------------------------- // Disk::ComputeLatency() // Return how long will it take to read/write a disk sector, from // the current position of the disk head. // // Latency = seek time + rotational latency + transfer time // Disk seeks at one track per SeekTime ticks (cf. stats.h) // and rotates at one sector per RotationTime ticks // // To find the rotational latency, we first must figure out where the // disk head will be after the seek (if any). We then figure out // how long it will take to rotate completely past newSector after // that point. // // The disk also has a "track buffer"; the disk continuously reads // the contents of the current disk track into the buffer. This allows // read requests to the current track to be satisfied more quickly. // The contents of the track buffer are discarded after every seek to // a new track. //---------------------------------------------------------------------- int Disk::ComputeLatency(int newSector, bool writing) { int rotation; int seek = TimeToSeek(newSector, &rotation); int timeAfter = stats->totalTicks + seek + rotation; #ifndef NOTRACKBUF // turn this on if you don't want the track buffer stuff // check if track buffer applies if ((writing == FALSE) && (seek == 0) && (((timeAfter - bufferInit) / RotationTime) > ModuloDiff(newSector, bufferInit / RotationTime))) { DEBUG('d', "Request latency = %d\n", RotationTime); return RotationTime; // time to transfer sector from the track buffer } #endif rotation += ModuloDiff(newSector, timeAfter / RotationTime) * RotationTime; DEBUG('d', "Request latency = %d\n", seek + rotation + RotationTime); return(seek + rotation + RotationTime); } //---------------------------------------------------------------------- // Disk::UpdateLast // Keep track of the most recently requested sector. So we can know // what is in the track buffer. //---------------------------------------------------------------------- void Disk::UpdateLast(int newSector) { int rotate; int seek = TimeToSeek(newSector, &rotate); if (seek != 0) bufferInit = stats->totalTicks + seek + rotate; lastSector = newSector; DEBUG('d', "Updating last sector = %d, %d\n", lastSector, bufferInit); }
C++
// interrupt.cc // Routines to simulate hardware interrupts. // // The hardware provides a routine (SetLevel) to enable or disable // interrupts. // // In order to emulate the hardware, we need to keep track of all // interrupts the hardware devices would cause, and when they // are supposed to occur. // // This module also keeps track of simulated time. Time advances // only when the following occur: // interrupts are re-enabled // a user instruction is executed // there is nothing in the ready queue // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "interrupt.h" #include "system.h" // String definitions for debugging messages static char *intLevelNames[] = { "off", "on"}; static char *intTypeNames[] = { "timer", "disk", "console write", "console read", "network send", "network recv"}; //---------------------------------------------------------------------- // PendingInterrupt::PendingInterrupt // Initialize a hardware device interrupt that is to be scheduled // to occur in the near future. // // "func" is the procedure to call when the interrupt occurs // "param" is the argument to pass to the procedure // "time" is when (in simulated time) the interrupt is to occur // "kind" is the hardware device that generated the interrupt //---------------------------------------------------------------------- PendingInterrupt::PendingInterrupt(VoidFunctionPtr func, int param, int time, IntType kind) { handler = func; arg = param; when = time; type = kind; } //---------------------------------------------------------------------- // Interrupt::Interrupt // Initialize the simulation of hardware device interrupts. // // Interrupts start disabled, with no interrupts pending, etc. //---------------------------------------------------------------------- Interrupt::Interrupt() { level = IntOff; pending = new List(); inHandler = FALSE; yieldOnReturn = FALSE; status = SystemMode; } //---------------------------------------------------------------------- // Interrupt::~Interrupt // De-allocate the data structures needed by the interrupt simulation. //---------------------------------------------------------------------- Interrupt::~Interrupt() { while (!pending->IsEmpty()) delete (PendingInterrupt *)pending->Remove(); delete pending; } //---------------------------------------------------------------------- // Interrupt::ChangeLevel // Change interrupts to be enabled or disabled, without advancing // the simulated time (normally, enabling interrupts advances the time). //---------------------------------------------------------------------- // Interrupt::ChangeLevel // Change interrupts to be enabled or disabled, without advancing // the simulated time (normally, enabling interrupts advances the time). // // Used internally. // // "old" -- the old interrupt status // "now" -- the new interrupt status //---------------------------------------------------------------------- void Interrupt::ChangeLevel(IntStatus old, IntStatus now) { level = now; DEBUG('i',"\tinterrupts: %s -> %s\n",intLevelNames[old],intLevelNames[now]); } //---------------------------------------------------------------------- // Interrupt::SetLevel // Change interrupts to be enabled or disabled, and if interrupts // are being enabled, advance simulated time by calling OneTick(). // // Returns: // The old interrupt status. // Parameters: // "now" -- the new interrupt status //---------------------------------------------------------------------- IntStatus Interrupt::SetLevel(IntStatus now) { IntStatus old = level; ASSERT((now == IntOff) || (inHandler == FALSE));// interrupt handlers are // prohibited from enabling // interrupts ChangeLevel(old, now); // change to new state if ((now == IntOn) && (old == IntOff)) OneTick(); // advance simulated time return old; } //---------------------------------------------------------------------- // Interrupt::Enable // Turn interrupts on. Who cares what they used to be? // Used in ThreadRoot, to turn interrupts on when first starting up // a thread. //---------------------------------------------------------------------- void Interrupt::Enable() { (void) SetLevel(IntOn); } //---------------------------------------------------------------------- // Interrupt::OneTick // Advance simulated time and check if there are any pending // interrupts to be called. // // Two things can cause OneTick to be called: // interrupts are re-enabled // a user instruction is executed //---------------------------------------------------------------------- void Interrupt::OneTick() { MachineStatus old = status; // advance simulated time if (status == SystemMode) { stats->totalTicks += SystemTick; stats->systemTicks += SystemTick; } else { // USER_PROGRAM stats->totalTicks += UserTick; stats->userTicks += UserTick; } DEBUG('i', "\n== Tick %d ==\n", stats->totalTicks); // check any pending interrupts are now ready to fire ChangeLevel(IntOn, IntOff); // first, turn off interrupts // (interrupt handlers run with // interrupts disabled) while (CheckIfDue(FALSE)) // check for pending interrupts ; ChangeLevel(IntOff, IntOn); // re-enable interrupts if (yieldOnReturn) { // if the timer device handler asked // for a context switch, ok to do it now yieldOnReturn = FALSE; status = SystemMode; // yield is a kernel routine currentThread->Yield(); status = old; } } //---------------------------------------------------------------------- // Interrupt::YieldOnReturn // Called from within an interrupt handler, to cause a context switch // (for example, on a time slice) in the interrupted thread, // when the handler returns. // // We can't do the context switch here, because that would switch // out the interrupt handler, and we want to switch out the // interrupted thread. //---------------------------------------------------------------------- void Interrupt::YieldOnReturn() { ASSERT(inHandler == TRUE); yieldOnReturn = TRUE; } //---------------------------------------------------------------------- // Interrupt::Idle // Routine called when there is nothing in the ready queue. // // Since something has to be running in order to put a thread // on the ready queue, the only thing to do is to advance // simulated time until the next scheduled hardware interrupt. // // If there are no pending interrupts, stop. There's nothing // more for us to do. //---------------------------------------------------------------------- void Interrupt::Idle() { DEBUG('i', "Machine idling; checking for interrupts.\n"); status = IdleMode; if (CheckIfDue(TRUE)) { // check for any pending interrupts while (CheckIfDue(FALSE)) // check for any other pending ; // interrupts yieldOnReturn = FALSE; // since there's nothing in the // ready queue, the yield is automatic status = SystemMode; return; // return in case there's now // a runnable thread } // if there are no pending interrupts, and nothing is on the ready // queue, it is time to stop. If the console or the network is // operating, there are *always* pending interrupts, so this code // is not reached. Instead, the halt must be invoked by the user program. DEBUG('i', "Machine idle. No interrupts to do.\n"); printf("No threads ready or runnable, and no pending interrupts.\n"); printf("Assuming the program completed.\n"); Halt(); } //---------------------------------------------------------------------- // Interrupt::Halt // Shut down Nachos cleanly, printing out performance statistics. //---------------------------------------------------------------------- void Interrupt::Halt() { printf("Machine halting!\n\n"); stats->Print(); Cleanup(); // Never returns. } //---------------------------------------------------------------------- // Interrupt::Schedule // Arrange for the CPU to be interrupted when simulated time // reaches "now + when". // // Implementation: just put it on a sorted list. // // NOTE: the Nachos kernel should not call this routine directly. // Instead, it is only called by the hardware device simulators. // // "handler" is the procedure to call when the interrupt occurs // "arg" is the argument to pass to the procedure // "fromNow" is how far in the future (in simulated time) the // interrupt is to occur // "type" is the hardware device that generated the interrupt //---------------------------------------------------------------------- void Interrupt::Schedule(VoidFunctionPtr handler, int arg, int fromNow, IntType type) { int when = stats->totalTicks + fromNow; PendingInterrupt *toOccur = new PendingInterrupt(handler, arg, when, type); DEBUG('i', "Scheduling interrupt handler the %s at time = %d\n", intTypeNames[type], when); ASSERT(fromNow > 0); pending->SortedInsert(toOccur, when); } //---------------------------------------------------------------------- // Interrupt::CheckIfDue // Check if an interrupt is scheduled to occur, and if so, fire it off. // // Returns: // TRUE, if we fired off any interrupt handlers // Params: // "advanceClock" -- if TRUE, there is nothing in the ready queue, // so we should simply advance the clock to when the next // pending interrupt would occur (if any). If the pending // interrupt is just the time-slice daemon, however, then // we're done! //---------------------------------------------------------------------- bool Interrupt::CheckIfDue(bool advanceClock) { MachineStatus old = status; int when; ASSERT(level == IntOff); // interrupts need to be disabled, // to invoke an interrupt handler if (DebugIsEnabled('i')) DumpState(); PendingInterrupt *toOccur = (PendingInterrupt *)pending->SortedRemove(&when); if (toOccur == NULL) // no pending interrupts return FALSE; if (advanceClock && when > stats->totalTicks) { // advance the clock stats->idleTicks += (when - stats->totalTicks); stats->totalTicks = when; } else if (when > stats->totalTicks) { // not time yet, put it back pending->SortedInsert(toOccur, when); return FALSE; } // Check if there is nothing more to do, and if so, quit if ((status == IdleMode) && (toOccur->type == TimerInt) && pending->IsEmpty()) { pending->SortedInsert(toOccur, when); return FALSE; } DEBUG('i', "Invoking interrupt handler for the %s at time %d\n", intTypeNames[toOccur->type], toOccur->when); #ifdef USER_PROGRAM if (machine != NULL) machine->DelayedLoad(0, 0); #endif inHandler = TRUE; status = SystemMode; // whatever we were doing, // we are now going to be // running in the kernel (*(toOccur->handler))(toOccur->arg); // call the interrupt handler status = old; // restore the machine status inHandler = FALSE; delete toOccur; return TRUE; } //---------------------------------------------------------------------- // PrintPending // Print information about an interrupt that is scheduled to occur. // When, where, why, etc. //---------------------------------------------------------------------- static void PrintPending(int arg) { PendingInterrupt *pend = (PendingInterrupt *)arg; printf("Interrupt handler %s, scheduled at %d\n", intTypeNames[pend->type], pend->when); } //---------------------------------------------------------------------- // DumpState // Print the complete interrupt state - the status, and all interrupts // that are scheduled to occur in the future. //---------------------------------------------------------------------- void Interrupt::DumpState() { printf("Time: %d, interrupts %s\n", stats->totalTicks, intLevelNames[level]); printf("Pending interrupts:\n"); fflush(stdout); pending->Mapcar(PrintPending); printf("End of pending interrupts\n"); fflush(stdout); }
C++
// translate.h // Data structures for managing the translation from // virtual page # -> physical page #, used for managing // physical memory on behalf of user programs. // // The data structures in this file are "dual-use" - they // serve both as a page table entry, and as an entry in // a software-managed translation lookaside buffer (TLB). // Either way, each entry is of the form: // <virtual page #, physical page #>. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef TLB_H #define TLB_H #include "copyright.h" #include "utility.h" // The following class defines an entry in a translation table -- either // in a page table or a TLB. Each entry defines a mapping from one // virtual page to one physical page. // In addition, there are some extra bits for access control (valid and // read-only) and some bits for usage information (use and dirty). class AddrSpace; class TranslationEntry { public: int virtualPage; // The page number in virtual memory. int physicalPage; // The page number in real memory (relative to the // start of "mainMemory" bool valid; // If this bit is set, the translation is ignored. // (In other words, the entry hasn't been initialized.) bool readOnly; // If this bit is set, the user program is not allowed // to modify the contents of the page. bool use; // This bit is set by the hardware every time the // page is referenced or modified. bool dirty; // This bit is set by the hardware every time the // page is modified. int diskLoc; AddrSpace* space; }; #endif
C++
// machine.h // Data structures for simulating the execution of user programs // running on top of Nachos. // // User programs are loaded into "mainMemory"; to Nachos, // this looks just like an array of bytes. Of course, the Nachos // kernel is in memory too -- but as in most machines these days, // the kernel is loaded into a separate memory region from user // programs, and accesses to kernel memory are not translated or paged. // // In Nachos, user programs are executed one instruction at a time, // by the simulator. Each memory reference is translated, checked // for errors, etc. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef MACHINE_H #define MACHINE_H #include "copyright.h" #include "utility.h" #include "translate.h" #include "disk.h" // Definitions related to the size, and format of user memory #define PageSize SectorSize // set the page size equal to // the disk sector size, for // simplicity #define NumPhysPages 32 #define MemorySize (NumPhysPages * PageSize) #define TLBSize 4 // if there is a TLB, make it small enum ExceptionType { NoException, // Everything ok! SyscallException, // A program executed a system call. PageFaultException, // No valid translation found ReadOnlyException, // Write attempted to page marked // "read-only" BusErrorException, // Translation resulted in an // invalid physical address AddressErrorException, // Unaligned reference or one that // was beyond the end of the // address space OverflowException, // Integer overflow in add or sub. IllegalInstrException, // Unimplemented or reserved instr. NumExceptionTypes }; // User program CPU state. The full set of MIPS registers, plus a few // more because we need to be able to start/stop a user program between // any two instructions (thus we need to keep track of things like load // delay slots, etc.) #define StackReg 29 // User's stack pointer #define RetAddrReg 31 // Holds return address for procedure calls #define NumGPRegs 32 // 32 general purpose registers on MIPS #define HiReg 32 // Double register to hold multiply result #define LoReg 33 #define PCReg 34 // Current program counter #define NextPCReg 35 // Next program counter (for branch delay) #define PrevPCReg 36 // Previous program counter (for debugging) #define LoadReg 37 // The register target of a delayed load. #define LoadValueReg 38 // The value to be loaded by a delayed load. #define BadVAddrReg 39 // The failing virtual address on an exception #define NumTotalRegs 40 // The following class defines an instruction, represented in both // undecoded binary form // decoded to identify // operation to do // registers to act on // any immediate operand value class Instruction { public: void Decode(); // decode the binary representation of the instruction unsigned int value; // binary representation of the instruction unsigned char opCode; // Type of instruction. This is NOT the same as the // opcode field from the instruction: see defs in mips.h unsigned char rs, rt, rd; // Three registers from instruction. int extra; // Immediate or target or shamt field or offset. // Immediates are sign-extended. }; // The following class defines the simulated host workstation hardware, as // seen by user programs -- the CPU registers, main memory, etc. // User programs shouldn't be able to tell that they are running on our // simulator or on the real hardware, except // we don't support floating point instructions // the system call interface to Nachos is not the same as UNIX // (10 system calls in Nachos vs. 200 in UNIX!) // If we were to implement more of the UNIX system calls, we ought to be // able to run Nachos on top of Nachos! // // The procedures in this class are defined in machine.cc, mipssim.cc, and // translate.cc. class Machine { public: Machine(bool debug); // Initialize the simulation of the hardware // for running user programs ~Machine(); // De-allocate the data structures // Routines callable by the Nachos kernel void Run(); // Run a user program int ReadRegister(int num); // read the contents of a CPU register void WriteRegister(int num, int value); // store a value into a CPU register // Routines internal to the machine simulation -- DO NOT call these void OneInstruction(Instruction *instr); // Run one instruction of a user program. void DelayedLoad(int nextReg, int nextVal); // Do a pending delayed load (modifying a reg) bool ReadMem(int addr, int size, int* value); bool WriteMem(int addr, int size, int value); // Read or write 1, 2, or 4 bytes of virtual // memory (at addr). Return FALSE if a // correct translation couldn't be found. ExceptionType Translate(int virtAddr, int* physAddr, int size,bool writing); // Translate an address, and check for // alignment. Set the use and dirty bits in // the translation entry appropriately, // and return an exception code if the // translation couldn't be completed. void RaiseException(ExceptionType which, int badVAddr); // Trap to the Nachos kernel, because of a // system call or other exception. void Debugger(); // invoke the user program debugger void DumpState(); // print the user CPU and memory state // Data structures -- all of these are accessible to Nachos kernel code. // "public" for convenience. // // Note that *all* communication between the user program and the kernel // are in terms of these data structures. char *mainMemory; // physical memory to store user program, // code and data, while executing int registers[NumTotalRegs]; // CPU registers, for executing user programs // NOTE: the hardware translation of virtual addresses in the user program // to physical addresses (relative to the beginning of "mainMemory") // can be controlled by one of: // a traditional linear page table // a software-loaded translation lookaside buffer (tlb) -- a cache of // mappings of virtual page #'s to physical page #'s // // If "tlb" is NULL, the linear page table is used // If "tlb" is non-NULL, the Nachos kernel is responsible for managing // the contents of the TLB. But the kernel can use any data structure // it wants (eg, segmented paging) for handling TLB cache misses. // // For simplicity, both the page table pointer and the TLB pointer are // public. However, while there can be multiple page tables (one per address // space, stored in memory), there is only one TLB (implemented in hardware). // Thus the TLB pointer should be considered as *read-only*, although // the contents of the TLB are free to be modified by the kernel software. TranslationEntry *tlb; // this pointer should be considered // "read-only" to Nachos kernel code TranslationEntry *pageTable; unsigned int pageTableSize; private: bool singleStep; // drop back into the debugger after each // simulated instruction int runUntilTime; // drop back into the debugger when simulated // time reaches this value }; extern void ExceptionHandler(ExceptionType which); // Entry point into Nachos for handling // user system calls and exceptions // Defined in exception.cc // Routines for converting Words and Short Words to and from the // simulated machine's format of little endian. If the host machine // is little endian (DEC and Intel), these end up being NOPs. // // What is stored in each format: // host byte ordering: // kernel data structures // user registers // simulated machine byte ordering: // contents of main memory unsigned int WordToHost(unsigned int word); unsigned short ShortToHost(unsigned short shortword); unsigned int WordToMachine(unsigned int word); unsigned short ShortToMachine(unsigned short shortword); #endif // MACHINE_H
C++
// console.cc // Routines to simulate a serial port to a console device. // A console has input (a keyboard) and output (a display). // These are each simulated by operations on UNIX files. // The simulated device is asynchronous, // so we have to invoke the interrupt handler (after a simulated // delay), to signal that a byte has arrived and/or that a written // byte has departed. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "console.h" #include "system.h" // Dummy functions because C++ is weird about pointers to member functions static void ConsoleReadPoll(int c) { Console *console = (Console *)c; console->CheckCharAvail(); } static void ConsoleWriteDone(int c) { Console *console = (Console *)c; console->WriteDone(); } //---------------------------------------------------------------------- // Console::Console // Initialize the simulation of a hardware console device. // // "readFile" -- UNIX file simulating the keyboard (NULL -> use stdin) // "writeFile" -- UNIX file simulating the display (NULL -> use stdout) // "readAvail" is the interrupt handler called when a character arrives // from the keyboard // "writeDone" is the interrupt handler called when a character has // been output, so that it is ok to request the next char be // output //---------------------------------------------------------------------- Console::Console(char *readFile, char *writeFile, VoidFunctionPtr readAvail, VoidFunctionPtr writeDone, int callArg) { if (readFile == NULL) readFileNo = 0; // keyboard = stdin else readFileNo = OpenForReadWrite(readFile, TRUE); // should be read-only if (writeFile == NULL) writeFileNo = 1; // display = stdout else writeFileNo = OpenForWrite(writeFile); // set up the stuff to emulate asynchronous interrupts writeHandler = writeDone; readHandler = readAvail; handlerArg = callArg; putBusy = FALSE; incoming = EOF; // start polling for incoming packets interrupt->Schedule(ConsoleReadPoll, (int)this, ConsoleTime, ConsoleReadInt); } //---------------------------------------------------------------------- // Console::~Console // Clean up console emulation //---------------------------------------------------------------------- Console::~Console() { if (readFileNo != 0) Close(readFileNo); if (writeFileNo != 1) Close(writeFileNo); } //---------------------------------------------------------------------- // Console::CheckCharAvail() // Periodically called to check if a character is available for // input from the simulated keyboard (eg, has it been typed?). // // Only read it in if there is buffer space for it (if the previous // character has been grabbed out of the buffer by the Nachos kernel). // Invoke the "read" interrupt handler, once the character has been // put into the buffer. //---------------------------------------------------------------------- void Console::CheckCharAvail() { char c; // schedule the next time to poll for a packet interrupt->Schedule(ConsoleReadPoll, (int)this, ConsoleTime, ConsoleReadInt); // do nothing if character is already buffered, or none to be read if ((incoming != EOF) || !PollFile(readFileNo)) return; // otherwise, read character and tell user about it Read(readFileNo, &c, sizeof(char)); incoming = c ; stats->numConsoleCharsRead++; (*readHandler)(handlerArg); } //---------------------------------------------------------------------- // Console::WriteDone() // Internal routine called when it is time to invoke the interrupt // handler to tell the Nachos kernel that the output character has // completed. //---------------------------------------------------------------------- void Console::WriteDone() { putBusy = FALSE; stats->numConsoleCharsWritten++; (*writeHandler)(handlerArg); } //---------------------------------------------------------------------- // Console::GetChar() // Read a character from the input buffer, if there is any there. // Either return the character, or EOF if none buffered. //---------------------------------------------------------------------- char Console::GetChar() { char ch = incoming; incoming = EOF; return ch; } //---------------------------------------------------------------------- // Console::PutChar() // Write a character to the simulated display, schedule an interrupt // to occur in the future, and return. //---------------------------------------------------------------------- void Console::PutChar(char ch) { ASSERT(putBusy == FALSE); WriteFile(writeFileNo, &ch, sizeof(char)); putBusy = TRUE; interrupt->Schedule(ConsoleWriteDone, (int)this, ConsoleTime, ConsoleWriteInt); }
C++
// sysdep.cc // Implementation of system-dependent interface. Nachos uses the // routines defined here, rather than directly calling the UNIX library, // to simplify porting between versions of UNIX, and even to // other systems, such as MSDOS. // // On UNIX, almost all of these routines are simple wrappers // for the underlying UNIX system calls. // // NOTE: all of these routines refer to operations on the underlying // host machine (e.g., the DECstation, SPARC, etc.), supporting the // Nachos simulation code. Nachos implements similar operations, // (such as opening a file), but those are implemented in terms // of hardware devices, which are simulated by calls to the underlying // routines in the host workstation OS. // // This file includes lots of calls to C routines. C++ requires // us to wrap all C definitions with a "extern "C" block". // This prevents the internal forms of the names from being // changed by the C++ compiler. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" extern "C" { #include <stdio.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <sys/time.h> #include <sys/socket.h> #include <sys/file.h> #include <sys/un.h> #include <sys/mman.h> #ifdef HOST_i386 #include <unistd.h> #include <sys/time.h> #include <errno.h> #endif #ifdef HOST_SPARC #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #endif // UNIX routines called by procedures in this file #ifdef HOST_SNAKE // int creat(char *name, unsigned short mode); // int open(const char *name, int flags, ...); #else //int creat(const char *name, unsigned short mode); //int open(const char *name, int flags, ...); // void signal(int sig, VoidFunctionPtr func); -- this may work now! #ifdef HOST_i386 int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); #else #ifdef HOST_SPARC int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); #else int select(int numBits, void *readFds, void *writeFds, void *exceptFds, struct timeval *timeout); #endif #endif #endif //int unlink(char *name); //int read(int filedes, char *buf, int numBytes); //int write(int filedes, char *buf, int numBytes); //int lseek(int filedes, int offset, int whence); //int tell(int filedes); //int close(int filedes); //int unlink(char *name); // definition varies slightly from platform to platform, so don't // define unless gcc complains // extern int recvfrom(int s, void *buf, int len, int flags, void *from, int *fromlen); // extern int sendto(int s, void *msg, int len, int flags, void *to, int tolen); void srand(unsigned seed); int rand(void); unsigned sleep(unsigned); void abort(); void exit(int); //int mprotect(char *addr, int len, int prot); //int socket(int, int, int); //int bind (int, const void*, int); //int recvfrom (int, void*, int, int, void*, int *); //int sendto (int, const void*, int, int, void*, int); } #include "interrupt.h" #include "system.h" //---------------------------------------------------------------------- // PollFile // Check open file or open socket to see if there are any // characters that can be read immediately. If so, read them // in, and return TRUE. // // In the network case, if there are no threads for us to run, // and no characters to be read, // we need to give the other side a chance to get our host's CPU // (otherwise, we'll go really slowly, since UNIX time-slices // infrequently, and this would be like busy-waiting). So we // delay for a short fixed time, before allowing ourselves to be // re-scheduled (sort of like a Yield, but cast in terms of UNIX). // // "fd" -- the file descriptor of the file to be polled //---------------------------------------------------------------------- bool PollFile(int fd) { int rfd = (1 << fd), wfd = 0, xfd = 0, retVal; struct timeval pollTime; // decide how long to wait if there are no characters on the file pollTime.tv_sec = 0; if (interrupt->getStatus() == IdleMode) pollTime.tv_usec = 20000; // delay to let other nachos run else pollTime.tv_usec = 0; // no delay // poll file or socket #if (defined(HOST_i386) || defined(HOST_SPARC)) retVal = select(32, (fd_set*)&rfd, (fd_set*)&wfd, (fd_set*)&xfd, &pollTime); #else retVal = select(32, &rfd, &wfd, &xfd, &pollTime); #endif ASSERT((retVal == 0) || (retVal == 1)); if (retVal == 0) return FALSE; // no char waiting to be read return TRUE; } //---------------------------------------------------------------------- // OpenForWrite // Open a file for writing. Create it if it doesn't exist; truncate it // if it does already exist. Return the file descriptor. // // "name" -- file name //---------------------------------------------------------------------- int OpenForWrite(char *name) { int fd = open(name, O_RDWR|O_CREAT|O_TRUNC, 0666); ASSERT(fd >= 0); return fd; } //---------------------------------------------------------------------- // OpenForReadWrite // Open a file for reading or writing. // Return the file descriptor, or error if it doesn't exist. // // "name" -- file name //---------------------------------------------------------------------- int OpenForReadWrite(char *name, bool crashOnError) { int fd = open(name, O_RDWR, 0); ASSERT(!crashOnError || fd >= 0); return fd; } //---------------------------------------------------------------------- // Read // Read characters from an open file. Abort if read fails. //---------------------------------------------------------------------- void Read(int fd, char *buffer, int nBytes) { int retVal = read(fd, buffer, nBytes); ASSERT(retVal == nBytes); } //---------------------------------------------------------------------- // ReadPartial // Read characters from an open file, returning as many as are // available. //---------------------------------------------------------------------- int ReadPartial(int fd, char *buffer, int nBytes) { return read(fd, buffer, nBytes); } //---------------------------------------------------------------------- // WriteFile // Write characters to an open file. Abort if write fails. //---------------------------------------------------------------------- void WriteFile(int fd, char *buffer, int nBytes) { int retVal = write(fd, buffer, nBytes); ASSERT(retVal == nBytes); } //---------------------------------------------------------------------- // Lseek // Change the location within an open file. Abort on error. //---------------------------------------------------------------------- void Lseek(int fd, int offset, int whence) { int retVal = lseek(fd, offset, whence); ASSERT(retVal >= 0); } //---------------------------------------------------------------------- // Tell // Report the current location within an open file. //---------------------------------------------------------------------- int Tell(int fd) { #ifdef HOST_i386 return lseek(fd,0,SEEK_CUR); // 386BSD doesn't have the tell() system call #else return tell(fd); #endif } //---------------------------------------------------------------------- // Close // Close a file. Abort on error. //---------------------------------------------------------------------- void Close(int fd) { int retVal = close(fd); ASSERT(retVal >= 0); } //---------------------------------------------------------------------- // Unlink // Delete a file. //---------------------------------------------------------------------- bool Unlink(char *name) { return unlink(name); } //---------------------------------------------------------------------- // OpenSocket // Open an interprocess communication (IPC) connection. For now, // just open a datagram port where other Nachos (simulating // workstations on a network) can send messages to this Nachos. //---------------------------------------------------------------------- int OpenSocket() { int sockID; sockID = socket(AF_UNIX, SOCK_DGRAM, 0); ASSERT(sockID >= 0); return sockID; } //---------------------------------------------------------------------- // CloseSocket // Close the IPC connection. //---------------------------------------------------------------------- void CloseSocket(int sockID) { (void) close(sockID); } //---------------------------------------------------------------------- // InitSocketName // Initialize a UNIX socket address -- magical! //---------------------------------------------------------------------- static void InitSocketName(struct sockaddr_un *uname, char *name) { uname->sun_family = AF_UNIX; strcpy(uname->sun_path, name); } //---------------------------------------------------------------------- // AssignNameToSocket // Give a UNIX file name to the IPC port, so other instances of Nachos // can locate the port. //---------------------------------------------------------------------- void AssignNameToSocket(char *socketName, int sockID) { struct sockaddr_un uName; int retVal; (void) unlink(socketName); // in case it's still around from last time InitSocketName(&uName, socketName); retVal = bind(sockID, (struct sockaddr *) &uName, sizeof(uName)); ASSERT(retVal >= 0); DEBUG('n', "Created socket %s\n", socketName); } //---------------------------------------------------------------------- // DeAssignNameToSocket // Delete the UNIX file name we assigned to our IPC port, on cleanup. //---------------------------------------------------------------------- void DeAssignNameToSocket(char *socketName) { (void) unlink(socketName); } //---------------------------------------------------------------------- // PollSocket // Return TRUE if there are any messages waiting to arrive on the // IPC port. //---------------------------------------------------------------------- bool PollSocket(int sockID) { return PollFile(sockID); // on UNIX, socket ID's are just file ID's } //---------------------------------------------------------------------- // ReadFromSocket // Read a fixed size packet off the IPC port. Abort on error. //---------------------------------------------------------------------- void ReadFromSocket(int sockID, char *buffer, int packetSize) { int retVal; // extern int errno; errno sometimes defined as a macro struct sockaddr_un uName; #ifdef HOST_i386 unsigned int size = sizeof(uName); #else int size = sizeof(uName); #endif retVal = recvfrom(sockID, buffer, packetSize, 0, (struct sockaddr *) &uName, &size); if (retVal != packetSize) { perror("in recvfrom"); printf("called: %x, got back %d, %d\n", (unsigned int) buffer, retVal, errno); } ASSERT(retVal == packetSize); } //---------------------------------------------------------------------- // SendToSocket // Transmit a fixed size packet to another Nachos' IPC port. // Abort on error. //---------------------------------------------------------------------- void SendToSocket(int sockID, char *buffer, int packetSize, char *toName) { struct sockaddr_un uName; int retVal; InitSocketName(&uName, toName); retVal = sendto(sockID, buffer, packetSize, 0, (sockaddr*) &uName, sizeof(uName)); ASSERT(retVal == packetSize); } //---------------------------------------------------------------------- // CallOnUserAbort // Arrange that "func" will be called when the user aborts (e.g., by // hitting ctl-C. //---------------------------------------------------------------------- void CallOnUserAbort(VoidNoArgFunctionPtr func) { (void)signal(SIGINT, (VoidFunctionPtr) func); } //---------------------------------------------------------------------- // Sleep // Put the UNIX process running Nachos to sleep for x seconds, // to give the user time to start up another invocation of Nachos // in a different UNIX shell. //---------------------------------------------------------------------- void Delay(int seconds) { (void) sleep((unsigned) seconds); } //---------------------------------------------------------------------- // Abort // Quit and drop core. //---------------------------------------------------------------------- void Abort() { abort(); } //---------------------------------------------------------------------- // Exit // Quit without dropping core. //---------------------------------------------------------------------- void Exit(int exitCode) { exit(exitCode); } //---------------------------------------------------------------------- // RandomInit // Initialize the pseudo-random number generator. We use the // now obsolete "srand" and "rand" because they are more portable! //---------------------------------------------------------------------- void RandomInit(unsigned seed) { srand(seed); } //---------------------------------------------------------------------- // Random // Return a pseudo-random number. //---------------------------------------------------------------------- int Random() { return rand(); } //---------------------------------------------------------------------- // AllocBoundedArray // Return an array, with the two pages just before // and after the array unmapped, to catch illegal references off // the end of the array. Particularly useful for catching overflow // beyond fixed-size thread execution stacks. // // Note: Just return the useful part! // // "size" -- amount of useful space needed (in bytes) //---------------------------------------------------------------------- char * AllocBoundedArray(int size) { int pgSize = getpagesize(); char *ptr = new char[pgSize * 2 + size]; //mprotect(ptr, pgSize, 0); //mprotect(ptr + pgSize + size, pgSize, 0); return ptr + pgSize; } //---------------------------------------------------------------------- // DeallocBoundedArray // Deallocate an array of integers, unprotecting its two boundary pages. // // "ptr" -- the array to be deallocated // "size" -- amount of useful space in the array (in bytes) //---------------------------------------------------------------------- void DeallocBoundedArray(char *ptr, int size) { int pgSize = getpagesize(); mprotect(ptr - pgSize, pgSize, PROT_READ | PROT_WRITE | PROT_EXEC); mprotect(ptr + size, pgSize, PROT_READ | PROT_WRITE | PROT_EXEC); delete [] (ptr - pgSize); }
C++
// stats.h // Data structures for gathering statistics about Nachos performance. // // DO NOT CHANGE -- these stats are maintained by the machine emulation // // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef STATS_H #define STATS_H #include "copyright.h" // The following class defines the statistics that are to be kept // about Nachos behavior -- how much time (ticks) elapsed, how // many user instructions executed, etc. // // The fields in this class are public to make it easier to update. class Statistics { public: int totalTicks; // Total time running Nachos int idleTicks; // Time spent idle (no threads to run) int systemTicks; // Time spent executing system code int userTicks; // Time spent executing user code // (this is also equal to # of // user instructions executed) int numDiskReads; // number of disk read requests int numDiskWrites; // number of disk write requests int numConsoleCharsRead; // number of characters read from the keyboard int numConsoleCharsWritten; // number of characters written to the display int numPageFaults; // number of virtual memory page faults int numPacketsSent; // number of packets sent over the network int numPacketsRecvd; // number of packets received over the network Statistics(); // initialize everything to zero void Print(); // print collected statistics }; // Constants used to reflect the relative time an operation would // take in a real system. A "tick" is a just a unit of time -- if you // like, a microsecond. // // Since Nachos kernel code is directly executed, and the time spent // in the kernel measured by the number of calls to enable interrupts, // these time constants are none too exact. #define UserTick 1 // advance for each user-level instruction #define SystemTick 10 // advance each time interrupts are enabled #define RotationTime 500 // time disk takes to rotate one sector #define SeekTime 500 // time disk takes to seek past one track #define ConsoleTime 100 // time to read or write one character #define NetworkTime 100 // time to send or receive one packet #define TimerTicks 100 // (average) time between timer interrupts #endif // STATS_H
C++
/* Copyright 2011, Janne Kytömäki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * jni-soundpool-wrapper.cpp * * Created on: 30.9.2011 * Author: Janne Kytomaki */ #include <jni.h> #include <android/log.h> #include <stdio.h> #include "logging.h" #include "OpenSLSoundPool.h" #include <unistd.h> #include <iostream> #include "ios" #include <fstream> #include <stdlib.h> OpenSLSoundPool* pool; extern "C" { void Java_com_kytomaki_openslsoundpool_OpenSLSoundPool_createEngine(JNIEnv* env, jclass clazz, jint maxStreams){ LOGI("createEngine"); pool = new OpenSLSoundPool(maxStreams, SL_SAMPLINGRATE_44_1, SL_PCMSAMPLEFORMAT_FIXED_16); LOGI("createEngine done"); } void Java_com_kytomaki_openslsoundpool_OpenSLSoundPool_nativeRelease(JNIEnv* env, jclass clazz){ LOGI("release OpenSLSoundPool"); delete pool; LOGI("release OpenSLSoundPool done"); } int Java_com_kytomaki_openslsoundpool_OpenSLSoundPool_nativePlay(JNIEnv * env, jclass clazz, jint soundId, jfloat volume){ return pool->play(soundId, volume); } int Java_com_kytomaki_openslsoundpool_OpenSLSoundPool_load(JNIEnv * env, jclass clazz, jobject fd_sys, jint off, jint len){ LOGI("load(), off: %i, len: %i", off, len); int soundId = 0; jclass fdClass = env->FindClass("java/io/FileDescriptor"); if (fdClass != NULL){ jfieldID fdClassDescriptorFieldID = env->GetFieldID(fdClass, "descriptor", "I"); if (fdClassDescriptorFieldID != NULL && fd_sys != NULL){ jint fd = env->GetIntField(fd_sys, fdClassDescriptorFieldID); LOGI("Duplicating file descriptor"); int fileDescriptor = dup(fd); LOGI("Opening file"); FILE* file = fdopen(fileDescriptor, "rb"); if (file == NULL){ LOGI("File is null!"); exit(EXIT_FAILURE); } LOGI("Seeking"); int fsr = fseek(file, off, SEEK_SET); if (fsr!=0){ LOGI("Error in seek"); exit(EXIT_FAILURE); } LOGI("Reading"); char* buf; int indx = 0; int headersLength = 0; char* dataHdr = "data"; int dataHdrLength = 4; int dataHdrIndx = 0; bool readingRaw = false; int countdown = 0; for (int i = 0; i < len; i++){ char c = getc(file); if (readingRaw){ if (countdown == 0){ buf[indx] = c; indx++; }else{ countdown--; } }else{ headersLength++; if (dataHdr[dataHdrIndx] == c){ if (dataHdrIndx == dataHdrLength - 1){ readingRaw = true; buf = (char*) malloc (len - headersLength - 4); countdown = 4; }else{ dataHdrIndx++; } }else{ dataHdrIndx = 0; } } } LOGI("Load successful"); return pool->load(buf, (int)len - headersLength - 4); } } return 0; } }
C++
/* Copyright 2011, Janne Kytömäki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * MySoundPool.cpp * * Created on: 30.9.2011 * Author: Janne Kytomaki */ #include "OpenSLSoundPool.h" #include <dlfcn.h> #include <iostream> #include <stdlib.h> #include <assert.h> #include <string.h> #include <vector> #include "opensl_helpers.h" OpenSLSoundPool* OpenSLSoundPool::instance; BufferQueue::~BufferQueue(){ LOGI("Deleting BufferQueue"); (**player)->Destroy(*player); player = NULL; playerPlay = NULL; queue = NULL; volume = NULL; } ResourceBuffer::~ResourceBuffer(){ LOGI("Deleting ResourceBuffer"); free(buf); } OpenSLSoundPool::OpenSLSoundPool(int maxStreams, SLuint32 samplingRate, SLuint32 bitrate): engineObject(NULL), outputMixObject(NULL), maxStreams(maxStreams), samplingRate(samplingRate), bitrate(bitrate){ LOGI("MySoundPool"); if (OpenSLSoundPool::instance != NULL){ LOGI("Can only be instantiated once"); exit(EXIT_FAILURE); } OpenSLSoundPool::instance = this; // see if OpenSL library is available void* handle = dlopen("libOpenSLES.so", RTLD_LAZY); if (handle == NULL){ LOGI("OpenSLES not available"); exit(EXIT_FAILURE); } bufferQueues = new std::vector<BufferQueue*>(); samples = new std::vector<ResourceBuffer*>(); LOGI("OpenSLES available"); LOGI("Initializing"); createEngine(); createBufferQueueAudioPlayer(); minVolume = SL_MILLIBEL_MIN; maxVolume = 0; } int OpenSLSoundPool::load(char* buffer, int length){ ResourceBuffer* b = new ResourceBuffer(); b->buf = buffer; b->size = length; samples->push_back(b); return samples->size(); } void OpenSLSoundPool::createEngine(){ SLresult result; const SLInterfaceID engine_ids[] = {SL_IID_ENGINE}; const SLboolean engine_req[] = {SL_BOOLEAN_TRUE}; result = slCreateEngine(&engineObject, 0, NULL, 0, engine_ids, engine_req); check(result); // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); check(result); // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); check(result); // create output mix, with environmental reverb specified as a non-required interface const SLInterfaceID ids[1] = {SL_IID_NULL}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); check(result); // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); check(result); } // a static callback function called every time a buffer finishes playing, // delegates to the instance function void OpenSLSoundPool::staticBqPlayerCallback(SLBufferQueueItf bq, void *context){ LOGI("staticBqPlayerCallback"); // we might be already destroyed if release() has been called mid-playback OpenSLSoundPool* tmpInstance; if ( (tmpInstance = instance) != NULL){ tmpInstance->bqPlayerCallback(bq, context); } } // this callback handler is called every time a buffer finishes playing void OpenSLSoundPool::bqPlayerCallback(SLBufferQueueItf bq, void *context) { LOGI("bqPlayerCallback"); BufferQueue* avail = NULL; for (int i = 0; i < bufferQueues->size(); i++){ if (*bufferQueues->at(i)->queue == bq){ avail = bufferQueues->at(i); avail->playing = false; break; } } } // create buffer queue audio player void OpenSLSoundPool::createBufferQueueAudioPlayer(){ LOGI("createBufferQueueAudioPlayer"); SLresult result; // configure audio source SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 1, samplingRate, bitrate, bitrate, SL_SPEAKER_FRONT_CENTER, SL_BYTEORDER_LITTLEENDIAN}; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // create audio player const SLInterfaceID player_ids[] = {SL_IID_BUFFERQUEUE, SL_IID_PLAY, SL_IID_VOLUME}; const SLboolean player_req[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; LOGI("Creating %i streams", maxStreams); for (int i = 0; i < maxStreams; i++){ BufferQueue* bf = new BufferQueue(); bf->playing = false; bf->queue = new SLBufferQueueItf(); bf->player = new SLObjectItf(); bf->playerPlay = new SLPlayItf(); bf->volume = new SLVolumeItf(); // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; //SLVolumeItf volume; LOGI("Creating SLAndroidSimpleBufferQueueItf"); result = (*engineEngine)->CreateAudioPlayer(engineEngine, &*bf->player, &audioSrc, &audioSnk, 3, player_ids, player_req); check(result); // realize the player result = (**bf->player)->Realize(*bf->player, SL_BOOLEAN_FALSE); check(result); // get the play interface result = (**bf->player)->GetInterface(*bf->player, SL_IID_PLAY, &*bf->playerPlay); check(result); // get the buffer queue interface result = (**bf->player)->GetInterface(*bf->player, SL_IID_BUFFERQUEUE, &*bf->queue); check(result); // register callback on the buffer queue result = (**bf->queue)->RegisterCallback(*bf->queue, OpenSLSoundPool::staticBqPlayerCallback, NULL); check(result); result = (**bf->player)->GetInterface(*bf->player, SL_IID_VOLUME, &*bf->volume); check(result); if (i == 0){ result = (**bf->volume)->GetMaxVolumeLevel(*bf->volume, &maxVolume); check(result); } result = (**bf->playerPlay)->SetPlayState(*bf->playerPlay, SL_PLAYSTATE_PLAYING); check(result); bufferQueues->push_back(bf); LOGI("Created stream %i", i); } LOGI("Created %i streams", bufferQueues->size()); LOGI("createBufferQueueAudioPlayer done"); } __attribute__((constructor)) static void onDlOpen(void) { LOGI("onDlOpen"); } OpenSLSoundPool::~OpenSLSoundPool() { instance = NULL; // destroy all buffer queues for (int i = 0; i < bufferQueues->size(); i++){ delete bufferQueues->at(i); } delete bufferQueues; // destroy all samples for (int i = 0; i < samples->size(); i++){ delete samples->at(i); } delete samples; // destroy output mix object if (outputMixObject != NULL) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = NULL; } // destroy engine object, and invalidate all associated interfaces if (engineObject != NULL) { (*engineObject)->Destroy(engineObject); engineObject = NULL; engineEngine = NULL; } } int OpenSLSoundPool::play(int sampleId, float volume){ int streamId = 0; LOGI("Play sample %i at volume %f", sampleId, volume); // find first available buffer queue BufferQueue* avail = NULL; int i = 0; for (; i < bufferQueues->size(); i++){ if (!bufferQueues->at(i)->playing){ avail = bufferQueues->at(i); avail->playing = true; streamId = i + 1; break; } } if (avail != NULL){ LOGI("Playing on channel %i", streamId); // find the requested sample if (sampleId > samples->size() + 1 || samples->at(sampleId - 1) == NULL){ LOGI("No sample found"); return 0; } ResourceBuffer* buf = samples->at(sampleId - 1); SLresult result; // convert requested volume 0.0-1.0 to millibels // in range max(minVolume, MIN_VOL_MILLIBEL) - maxVolume SLmillibel minvol = minVolume; if (minvol < MIN_VOL_MILLIBEL){ minvol = MIN_VOL_MILLIBEL; } SLmillibel newVolume = ((minvol - maxVolume) * (1.0 - volume)) + maxVolume; //adjust volume for the buffer queue result = (**avail->volume)->SetVolumeLevel(*avail->volume, newVolume); check(result); //enqueue the sample result = (**avail->queue)->Enqueue(*avail->queue, (void*)(short*) buf->buf, buf->size); if (SL_RESULT_SUCCESS != result) { LOGI("Enqueue result not OK"); } }else{ LOGI("No channels available for playback"); } return streamId; }
C++
/* /** Copyright 2011, Janne Kytömäki Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * MySoundPool.h * * Created on: 30.9.2011 * Author: Janne Kytomaki */ #ifndef MYSOUNDPOOL_H_ #define MYSOUNDPOOL_H_ #include "SLES/OpenSLES.h" #include "SLES/OpenSLES_Android.h" #include "logging.h" #include "vector" #include "stdlib.h" #define NDKSP_MIN_VOLUME 0.0f #define NDKSP_MAX_VOLUME 1.0f #define MIN_VOL_MILLIBEL -500 void createEngine(); void createBufferQueueAudioPlayer(); void shutdown(); class ResourceBuffer { public: virtual ~ResourceBuffer(); char* buf; int size; }; class BufferQueue{ public: virtual ~BufferQueue(); SLBufferQueueItf* queue; SLObjectItf* player; SLPlayItf* playerPlay; SLVolumeItf* volume; bool playing; }; class OpenSLSoundPool { public: OpenSLSoundPool(int maxStreams, SLuint32 samplingRate, SLuint32 bitrate); virtual ~OpenSLSoundPool(); virtual int play(int sampleId, float volume); virtual int load(char* buffer, int length); static OpenSLSoundPool* instance; private: virtual void createEngine(); static void staticBqPlayerCallback(SLBufferQueueItf bq, void *context); virtual void bqPlayerCallback(SLBufferQueueItf bq, void *context); virtual void createBufferQueueAudioPlayer(); int maxStreams; SLuint32 samplingRate; SLuint32 bitrate; // device specific min and max volumes SLmillibel minVolume; SLmillibel maxVolume; // engine interfaces SLObjectItf engineObject; SLEngineItf engineEngine; // output mix interfaces SLObjectItf outputMixObject; //BufferQueue queues[]; // vector for BufferQueues (one for each channel) std::vector<BufferQueue*>* bufferQueues; // vector for samples std::vector<ResourceBuffer*>* samples; }; #endif /* MYSOUNDPOOL_H_ */
C++
/* * Visible snake objects, rendered by openGL/GLUT. */ #include <iostream> class SnakeObject { public: SnakeObject(int x, int y); SnakeObject(int x, int y, int z); void SnakeObjectDisplay(); int& X(); int& Y(); int& Z(); void setX(int x); void setY(int y); void setZ(int z); private: int x; int y; int z; };
C++