diff --git a/sc2/src/options.c b/sc2/src/options.c index 907f03659..9881aaae2 100644 --- a/sc2/src/options.c +++ b/sc2/src/options.c @@ -28,6 +28,7 @@ #include "libs/compiler.h" #include "libs/uio.h" #include "libs/strlib.h" +#include "libs/log.h" #include #include @@ -93,8 +94,8 @@ findFileInDirs (const char *locs[], int numLocs, const char *file) if (locLen + (needSlash ? 1 : 0) + fileLen + 1 >= sizeof path) { // This dir plus the file name is too long. - fprintf (stderr, "Warning: path '%s' is ignored because it is " - "too long.\n", loc); + log_add (log_Warning, "Warning: path '%s' is ignored" + " because it is too long.", loc); continue; } @@ -134,20 +135,19 @@ prepareContentDir (const char *contentDirName, const char **addons) } if (loc == NULL) { - fprintf (stderr, "Fatal error: Could not find content.\n"); + log_add (log_Always, "Fatal error: Could not find content."); exit (EXIT_FAILURE); } - if (expandPath(path, sizeof path, loc, EP_ALL_SYSTEM) == -1) + if (expandPath (path, sizeof path, loc, EP_ALL_SYSTEM) == -1) { - fprintf (stderr, "Fatal error: Could not expand path to content " - "directory: %s\n", strerror (errno)); + log_add (log_Always, "Fatal error: Could not expand path to content " + "directory: %s", strerror (errno)); exit (EXIT_FAILURE); } -#ifdef DEBUG - fprintf (stderr, "Using '%s' as base content dir.\n", path); -#endif + log_add (log_Debug, "Using '%s' as base content dir.", path); + mountContentDir (repository, path, addons); } @@ -157,7 +157,8 @@ prepareConfigDir (const char *configDirName) { static uio_AutoMount *autoMount[] = { NULL }; uio_MountHandle *contentHandle; - if (configDirName == NULL) { + if (configDirName == NULL) + { configDirName = getenv("UQM_CONFIG_DIR"); if (configDirName == NULL) @@ -169,14 +170,12 @@ prepareConfigDir (const char *configDirName) { { // Doesn't have to be fatal, but might mess up things when saving // config files. - fprintf (stderr, "Fatal error: Invalid path to config files.\n"); + log_add (log_Always, "Fatal error: Invalid path to config files."); exit (EXIT_FAILURE); } configDirName = buf; -#ifdef DEBUG - fprintf (stderr, "Using config dir '%s'\n", configDirName); -#endif + log_add (log_Debug, "Using config dir '%s'", configDirName); // Set the environment variable UQM_CONFIG_DIR so UQM_MELEE_DIR // and UQM_SAVE_DIR can refer to it. @@ -189,15 +188,17 @@ prepareConfigDir (const char *configDirName) { contentHandle = uio_mountDir (repository, "/", uio_FSTYPE_STDIO, NULL, NULL, configDirName, autoMount, uio_MOUNT_TOP, NULL); - if (contentHandle == NULL) { - fprintf (stderr, "Fatal error: Could not mount config dir: %s\n", + if (contentHandle == NULL) + { + log_add (log_Always, "Fatal error: Could not mount config dir: %s", strerror (errno)); exit (EXIT_FAILURE); } configDir = uio_openDir (repository, "/", 0); - if (configDir == NULL) { - fprintf (stderr, "Fatal error: Could not open config dir: %s\n", + if (configDir == NULL) + { + log_add (log_Always, "Fatal error: Could not open config dir: %s", strerror (errno)); exit (EXIT_FAILURE); } @@ -216,7 +217,7 @@ prepareSaveDir (void) { { // Doesn't have to be fatal, but might mess up things when saving // config files. - fprintf (stderr, "Fatal error: Invalid path to config files.\n"); + log_add (log_Always, "Fatal error: Invalid path to config files."); exit (EXIT_FAILURE); } @@ -226,15 +227,15 @@ prepareSaveDir (void) { // Create the path upto the save dir, if not already existing. if (mkdirhier (saveDirName) == -1) exit (EXIT_FAILURE); -#ifdef DEBUG - fprintf(stderr, "Saved games are kept in %s.\n", saveDirName); -#endif + + log_add (log_Debug, "Saved games are kept in %s.", saveDirName); saveDir = uio_openDirRelative (configDir, "save", 0); // TODO: this doesn't work if the save dir is not // "save" in the config dir. - if (saveDir == NULL) { - fprintf (stderr, "Fatal error: Could not open save dir: %s\n", + if (saveDir == NULL) + { + log_add (log_Always, "Fatal error: Could not open save dir: %s", strerror (errno)); exit (EXIT_FAILURE); } @@ -253,7 +254,7 @@ prepareMeleeDir (void) { { // Doesn't have to be fatal, but might mess up things when saving // config files. - fprintf (stderr, "Fatal error: Invalid path to config files.\n"); + log_add (log_Always, "Fatal error: Invalid path to config files."); exit (EXIT_FAILURE); } @@ -267,8 +268,9 @@ prepareMeleeDir (void) { meleeDir = uio_openDirRelative (configDir, "teams", 0); // TODO: this doesn't work if the save dir is not // "teams" in the config dir. - if (meleeDir == NULL) { - fprintf (stderr, "Fatal error: Could not open melee teams dir: %s\n", + if (meleeDir == NULL) + { + log_add (log_Always, "Fatal error: Could not open melee teams dir: %s", strerror (errno)); exit (EXIT_FAILURE); } @@ -285,28 +287,30 @@ mountContentDir (uio_Repository *repository, const char *contentPath, contentHandle = uio_mountDir (repository, "/", uio_FSTYPE_STDIO, NULL, NULL, contentPath, autoMount, uio_MOUNT_TOP | uio_MOUNT_RDONLY, NULL); - if (contentHandle == NULL) { - fprintf (stderr, "Fatal error: Could not mount content dir: %s\n", + if (contentHandle == NULL) + { + log_add (log_Always, "Fatal error: Could not mount content dir: %s", strerror (errno)); exit (EXIT_FAILURE); } contentDir = uio_openDir (repository, "/", 0); - if (contentDir == NULL) { - fprintf (stderr, "Fatal error: Could not open content dir: %s\n", + if (contentDir == NULL) + { + log_add (log_Always, "Fatal error: Could not open content dir: %s", strerror (errno)); exit (EXIT_FAILURE); } packagesDir = uio_openDir (repository, "/packages", 0); - if (packagesDir == NULL) { - // No packages dir means no packages to load. - if (addons[0] != NULL) { - // addons were specified, but there's no /packages dir, + if (packagesDir == NULL) + { // No packages dir means no packages to load. + if (addons[0] != NULL) + { // addons were specified, but there's no /packages dir, // let alone a /packages/addons dir. - fprintf (stderr, "Warning: There's no 'packages/addons' " + log_add (log_Always, "Warning: There's no 'packages/addons' " "directory in the 'content' directory;\n\t'--addon' " - "options are ignored.\n"); + "options are ignored."); } return; } @@ -317,11 +321,11 @@ mountContentDir (uio_Repository *repository, const char *contentPath, // the former is the dir 'packages/addons', the latter a directory // in that dir. addonsDir = uio_openDirRelative (packagesDir, "addons", 0); - if (addonsDir == NULL) { - // No addon dir found. - fprintf (stderr, "Warning: There's no 'packages/addons' " + if (addonsDir == NULL) + { // No addon dir found. + log_add (log_Always, "Warning: There's no 'packages/addons' " "directory in the 'content' directory;\n\t'--addon' " - "options are ignored.\n"); + "options are ignored."); uio_closeDir (packagesDir); return; } @@ -329,31 +333,37 @@ mountContentDir (uio_Repository *repository, const char *contentPath, uio_closeDir (packagesDir); availableAddons = uio_getDirList (addonsDir, "", "", match_MATCH_PREFIX); - if (availableAddons != NULL) { + if (availableAddons != NULL) + { int i, count; count = availableAddons->numNames; if (count != 1) { - fprintf (stderr, "%d available addon packs.\n", count); + log_add (log_Always, "%d available addon packs.", count); } else { - fprintf (stderr, "1 available addon pack.\n"); + log_add (log_Always, "1 available addon pack."); } - for (i = 0; i < count; i++) { - fprintf (stderr, " %d. %s\n", i+1, availableAddons->names[i]); + for (i = 0; i < count; i++) + { + log_add (log_Always, " %d. %s", i+1, + availableAddons->names[i]); } - } else { - fprintf (stderr, "0 available addon packs.\n"); + } + else + { + log_add (log_Always, "0 available addon packs."); } for (; *addons != NULL; addons++) { addonDir = uio_openDirRelative (addonsDir, *addons, 0); - if (addonDir == NULL) { - fprintf (stderr, "Warning: directory 'packages/addons/%s' " - "not found; addon skipped.\n", *addons); + if (addonDir == NULL) + { + log_add (log_Always, "Warning: directory 'packages/addons/%s' " + "not found; addon skipped.", *addons); continue; } @@ -373,15 +383,18 @@ mountDirZips (uio_MountHandle *contentHandle, uio_DirHandle *dirHandle) dirList = uio_getDirList (dirHandle, "", ".(zip|uqm)$", match_MATCH_REGEX); - if (dirList != NULL) { + if (dirList != NULL) + { int i; - for (i = 0; i < dirList->numNames; i++) { + for (i = 0; i < dirList->numNames; i++) + { if (uio_mountDir (repository, "/", uio_FSTYPE_ZIP, dirHandle, dirList->names[i], "/", autoMount, uio_MOUNT_BELOW | uio_MOUNT_RDONLY, - contentHandle) == NULL) { - fprintf (stderr, "Warning: Could not mount '%s': %s.\n", + contentHandle) == NULL) + { + log_add (log_Always, "Warning: Could not mount '%s': %s.", dirList->names[i], strerror (errno)); } } diff --git a/sc2/src/port.h b/sc2/src/port.h index dbfa76b7b..c065e59a8 100644 --- a/sc2/src/port.h +++ b/sc2/src/port.h @@ -112,6 +112,7 @@ typedef unsigned short mode_t; // Printf #ifdef _MSC_VER #define snprintf _snprintf +#define vsnprintf _vsnprintf #endif // setenv() diff --git a/sc2/src/sc2code/clock.c b/sc2/src/sc2code/clock.c index f0585ce2b..3d2fd2898 100644 --- a/sc2/src/sc2code/clock.c +++ b/sc2/src/sc2code/clock.c @@ -24,7 +24,7 @@ #include "libs/gfxlib.h" #include "libs/tasklib.h" #include "libs/threadlib.h" - +#include "libs/log.h" // the running of the game-clock is based on game framerates // *not* on the system (or translated) timer @@ -225,7 +225,8 @@ SuspendGameClock (void) { if (!clock_mutex) { - fprintf (stderr, "BUG: Attempted to suspend non-existent game clock\n"); + log_add (log_Always, "BUG: " + "Attempted to suspend non-existent game clock"); #ifdef DEBUG abort(); #endif @@ -245,7 +246,8 @@ ResumeGameClock (void) { if (!clock_mutex) { - fprintf (stderr, "BUG: Attempted to resume non-existent game clock\n"); + log_add (log_Always, "BUG: " + "Attempted to resume non-existent game clock\n"); #ifdef DEBUG abort(); #endif @@ -271,7 +273,6 @@ SetGameClockRate (COUNT seconds_per_day) { SIZE new_day_in_ticks, new_tick_count; -//if (GLOBAL (GameClock.clock_sem)) fprintf (stderr, "%u\n", GLOBAL (GameClock.clock_sem)); SetSemaphore (GLOBAL (GameClock.clock_sem)); new_day_in_ticks = (SIZE)(seconds_per_day * CLOCK_BASE_FRAMERATE); if (GLOBAL (GameClock.day_in_ticks) == 0) diff --git a/sc2/src/sc2code/collide.c b/sc2/src/sc2code/collide.c index 80e7ff300..6956e3c58 100644 --- a/sc2/src/sc2code/collide.c +++ b/sc2/src/sc2code/collide.c @@ -21,6 +21,7 @@ #include "races.h" #include "units.h" #include "libs/mathlib.h" +#include "libs/log.h" //#define DEBUG_COLLIDE @@ -61,10 +62,10 @@ collide (ELEMENTPTR ElementPtr0, ELEMENTPTR ElementPtr1) } #ifdef DEBUG_COLLIDE - fprintf (stderr, "Centers: <%d, %d> <%d, %d>\n", + log_add (log_Debug, "Centers: <%d, %d> <%d, %d>", ElementPtr0->next.location.x, ElementPtr0->next.location.y, ElementPtr1->next.location.x, ElementPtr1->next.location.y); - fprintf (stderr, "RelTravelAngle : %d, ImpactAngles <%d, %d>\n", + log_add (log_Debug, "RelTravelAngle : %d, ImpactAngles <%d, %d>", RelTravelAngle, ImpactAngle0, ImpactAngle1); #endif /* DEBUG_COLLIDE */ @@ -83,8 +84,10 @@ collide (ELEMENTPTR ElementPtr0, ELEMENTPTR ElementPtr1) ElementPtr0->state_flags |= (DEFY_PHYSICS | COLLISION); ElementPtr1->state_flags |= (DEFY_PHYSICS | COLLISION); #ifdef DEBUG_COLLIDE - fprintf (stderr, "No movement before collision -- <(%d, %d) = %d, (%d, %d) = %d>\n", - dx0, dy0, ImpactAngle0 - OCTANT, dx1, dy1, ImpactAngle1 - OCTANT); + log_add (log_Debug, "No movement before collision -- " + "<(%d, %d) = %d, (%d, %d) = %d>", + dx0, dy0, ImpactAngle0 - OCTANT, dx1, dy1, + ImpactAngle1 - OCTANT); #endif /* DEBUG_COLLIDE */ } @@ -172,7 +175,7 @@ collide (ELEMENTPTR ElementPtr0, ELEMENTPTR ElementPtr1) #ifdef DEBUG_COLLIDE GetCurrentVelocityComponents (&ElementPtr0->velocity, &dx0, &dy0); GetCurrentVelocityComponents (&ElementPtr1->velocity, &dx1, &dy1); - fprintf (stderr, "After: <%d, %d> <%d, %d>\n\n", + log_add (log_Debug, "After: <%d, %d> <%d, %d>\n", dx0, dy0, dx1, dy1); #endif /* DEBUG_COLLIDE */ } diff --git a/sc2/src/sc2code/comm.c b/sc2/src/sc2code/comm.c index 4b8d912d1..214093f97 100644 --- a/sc2/src/sc2code/comm.c +++ b/sc2/src/sc2code/comm.c @@ -40,6 +40,7 @@ #include "libs/sound/trackplayer.h" #include "libs/sound/trackint.h" #include "libs/strlib.h" +#include "libs/log.h" #include @@ -1579,10 +1580,10 @@ DoCommunication (PENCOUNTER_STATE pES) } if ((unsigned)space_index >= sizeof (buffer)) { - fprintf (stderr, "DoCommunication() BUG: buffer[%u] " - "too small to fit %d bytes\n", + log_add (log_Always, "DoCommunication() BUG: " + "buffer[%u] too small to fit %d bytes\n", sizeof (buffer), space_index); - abort (); + exit (EXIT_FAILURE); } strncpy (buffer, temp, space_index); buffer[space_index] = '\0'; @@ -2251,7 +2252,6 @@ do_subtitles (UNICODE *pStr) } subtitle_state = READ_SUBTITLE; ClearSubtitle = TRUE; -// fprintf (stderr, "changed page to: %d\n", cur_page); } last_page = pStr; diff --git a/sc2/src/sc2code/comm/zoqfot/zoqfotc.c b/sc2/src/sc2code/comm/zoqfot/zoqfotc.c index 4ac0ef651..33f08f427 100644 --- a/sc2/src/sc2code/comm/zoqfot/zoqfotc.c +++ b/sc2/src/sc2code/comm/zoqfot/zoqfotc.c @@ -337,9 +337,6 @@ ZoqFotIntro (RESPONSE_REF R) DISABLE_PHRASE (what_look_like); } -// fprintf (stderr, "yr = 0x%x wf = 0x%x\n", alien_text[your_race][0], alien_text[where_from][0]); -// fprintf (stderr, "we = 0x%x tl = 0x%x\n", alien_text[what_emergency][0], alien_text[tough_luck][0]); -// fprintf (stderr, "wll = 0x%x\n", what_look_like); if (PHRASE_ENABLED (your_race) || PHRASE_ENABLED (where_from) || PHRASE_ENABLED (what_emergency)) diff --git a/sc2/src/sc2code/commglue.c b/sc2/src/sc2code/commglue.c index f47d058b3..7b856aea2 100644 --- a/sc2/src/sc2code/commglue.c +++ b/sc2/src/sc2code/commglue.c @@ -24,6 +24,7 @@ #include #include #include +#include "libs/log.h" int NPCNumberPhrase (int number, UNICODE **ptrack); @@ -285,9 +286,9 @@ construct_response (UNICODE *buf, int R /* promoted from RESPONSE_REF */, ...) if ((buf_start == shared_phrase_buf) && (buf > shared_phrase_buf + sizeof (shared_phrase_buf))) { - fprintf (stderr, "Error: shared_phrase_buf size exceeded," + log_add (log_Always, "Error: shared_phrase_buf size exceeded," " please increase!\n"); - abort (); + exit (EXIT_FAILURE); } } diff --git a/sc2/src/sc2code/confirm.c b/sc2/src/sc2code/confirm.c index cf008c4bf..a1db3d817 100644 --- a/sc2/src/sc2code/confirm.c +++ b/sc2/src/sc2code/confirm.c @@ -27,6 +27,7 @@ #include "libs/graphics/widgets.h" #include "libs/inplib.h" #include "libs/sound/trackplayer.h" +#include "libs/log.h" #include @@ -86,7 +87,7 @@ DoConfirmExit (void) { BOOLEAN result; static BOOLEAN in_confirm = FALSE; - fprintf (stderr, "Confirming Exit!\n"); + log_add (log_Info, "Confirming Exit!\n"); if (LOBYTE (GLOBAL (CurrentActivity)) != SUPER_MELEE && LOBYTE (GLOBAL (CurrentActivity)) != WON_LAST_BATTLE && !(LastActivity & CHECK_RESTART)) @@ -189,7 +190,7 @@ DoConfirmExit (void) do_subtitles ((void *)~0); } - fprintf (stderr, "Exit was %sconfirmed.\n", result ? "" : "NOT "); + log_add (log_Info, "Exit was %sconfirmed.\n", result ? "" : "NOT "); in_confirm = FALSE; return (result); } diff --git a/sc2/src/sc2code/cyborg.c b/sc2/src/sc2code/cyborg.c index 628f927bf..9caebb944 100644 --- a/sc2/src/sc2code/cyborg.c +++ b/sc2/src/sc2code/cyborg.c @@ -26,7 +26,7 @@ #include "units.h" #include "libs/inplib.h" #include "libs/mathlib.h" - +#include "libs/log.h" //#define DEBUG_CYBORG @@ -308,7 +308,7 @@ InitCyborg (STARSHIPPTR StarShipPtr) char buf[40]; GetStringContents (StarShipPtr->RaceDescPtr->ship_data.race_strings, buf, FALSE); - fprintf (stderr, "MI(%s) -- <%u:%u> = %u\n", buf, + log_add (log_Debug, "MI(%s) -- <%u:%u> = %u", buf, StarShipPtr->RaceDescPtr->characteristics.max_thrust * StarShipPtr->RaceDescPtr->characteristics.thrust_increment, Divisor, Index); diff --git a/sc2/src/sc2code/displist.c b/sc2/src/sc2code/displist.c index feed474f2..d8c0887e1 100644 --- a/sc2/src/sc2code/displist.c +++ b/sc2/src/sc2code/displist.c @@ -17,6 +17,7 @@ */ #include "displist.h" +#include "libs/log.h" /* * This file contains code for generic doubly linked lists. @@ -35,7 +36,10 @@ InitQueue (PQUEUE pq, COUNT num_elements, OBJ_SIZE size) return (TRUE); #else /* QUEUE_TABLE */ SetFreeList (pq, NULL_HANDLE); -// fprintf (stderr, "num_elements = %d (%d)\n", num_elements, (BYTE)num_elements); +#if 0 + log_add (log_Debug, "InitQueue(): num_elements = %d (%d)", + num_elements, (BYTE)num_elements); +#endif if (AllocQueueTab (pq, num_elements) && LockQueueTab (pq)) { do @@ -111,10 +115,9 @@ AllocLink (PQUEUE pq) SetFreeList (pq, _GetSuccLink (LinkPtr)); UnlockLink (pq, hLink); } -/* else - fprintf (stderr, "No more elements\n"); -*/ + log_add (log_Debug, "AllocLink(): No more elements"); + return (hLink); } diff --git a/sc2/src/sc2code/dummy.c b/sc2/src/sc2code/dummy.c index e6d2015c5..126bfa931 100644 --- a/sc2/src/sc2code/dummy.c +++ b/sc2/src/sc2code/dummy.c @@ -28,6 +28,7 @@ #include "races.h" #include "libs/compiler.h" +#include "libs/log.h" #include @@ -356,7 +357,7 @@ CaptureCodeRes (MEM_HANDLE hCode, PVOID pData, PVOID *ppLocData) if (hCode == 0) { - fprintf(stderr, "Ack! dummy.c::CaptureCodeRes() hCode==0! FATAL!\n"); + log_add (log_Always, "dummy.c::CaptureCodeRes() hCode==0! FATAL!"); return(0); } diff --git a/sc2/src/sc2code/galaxy.c b/sc2/src/sc2code/galaxy.c index a2f09c050..7c03529d2 100644 --- a/sc2/src/sc2code/galaxy.c +++ b/sc2/src/sc2code/galaxy.c @@ -27,7 +27,7 @@ #include "libs/gfxlib.h" #include "libs/graphics/gfx_common.h" #include "libs/mathlib.h" - +#include "libs/log.h" extern COUNT zoom_out; extern PRIM_LINKS DisplayLinks; @@ -238,7 +238,9 @@ InitGalaxy (void) PPOINT ppt; PRIM_LINKS Links; -// fprintf (stderr, "transition_width = %d transition_height = %d\n", TRANSITION_WIDTH, TRANSITION_HEIGHT); + log_add (log_Debug, "InitGalaxy(): transition_width = %d, " + "transition_height = %d", + TRANSITION_WIDTH, TRANSITION_HEIGHT); Links = MakeLinks (END_OF_LIST, END_OF_LIST); factor = ONE_SHIFT + MAX_REDUCTION + (BACKGROUND_SHIFT - 3); diff --git a/sc2/src/sc2code/getchar.c b/sc2/src/sc2code/getchar.c index 1b61bac68..acdd94a62 100644 --- a/sc2/src/sc2code/getchar.c +++ b/sc2/src/sc2code/getchar.c @@ -20,6 +20,7 @@ #include "controls.h" #include "libs/inplib.h" #include "libs/misc.h" +#include "libs/log.h" #include "globdata.h" #include "sounds.h" #include "settings.h" @@ -163,8 +164,8 @@ DoTextEntry (PTEXTENTRY_STATE pTES) { if (lwlen < pTES->JoyRegLength) pTES->JoyRegLength = lwlen; - fprintf (stderr, "Warning: Joystick upper-lower registers size " - "mismatch; using the smallest subset (%d)\n", + log_add (log_Warning, "Warning: Joystick upper-lower registers" + " size mismatch; using the smallest subset (%d)", pTES->JoyRegLength); } diff --git a/sc2/src/sc2code/globdata.c b/sc2/src/sc2code/globdata.c index e366a27a6..ffe699a55 100644 --- a/sc2/src/sc2code/globdata.c +++ b/sc2/src/sc2code/globdata.c @@ -29,7 +29,7 @@ #include #ifdef STATE_DEBUG -# include +# include "libs/log.h" #endif @@ -73,7 +73,7 @@ setGameState (int startBit, int endBit, BYTE val | (BYTE)((val) >> (endBit - startBit - (endBit & 7))); } #ifdef STATE_DEBUG - fprintf (stderr, "State '%s' set to %d.\n", name, val); + log_add (log_Debug, "State '%s' set to %d.", name, val); #endif } diff --git a/sc2/src/sc2code/gravity.c b/sc2/src/sc2code/gravity.c index a773774ef..33ebcd6b6 100644 --- a/sc2/src/sc2code/gravity.c +++ b/sc2/src/sc2code/gravity.c @@ -19,7 +19,7 @@ #include "collide.h" #include "races.h" #include "units.h" - +#include "libs/log.h" //#define DEBUG_GRAVITY @@ -64,15 +64,15 @@ CalculateGravity (PELEMENT ElementPtr) #ifdef DEBUG_GRAVITY if (TestElementPtr->state_flags & PLAYER_SHIP) { - fprintf (stderr, "CalculateGravity:\n"); - fprintf (stderr, "\tdx = %d, dy = %d\n", dx, dy); + log_add (log_Debug, "CalculateGravity:"); + log_add (log_Debug, "\tdx = %d, dy = %d", dx, dy); } #endif /* DEBUG_GRAVITY */ dx = WRAP_DELTA_X (dx); dy = WRAP_DELTA_Y (dy); #ifdef DEBUG_GRAVITY if (TestElementPtr->state_flags & PLAYER_SHIP) - fprintf (stderr, "\twrap_dx = %d, wrap_dy = %d\n", dx, dy); + log_add (log_Debug, "\twrap_dx = %d, wrap_dy = %d", dx, dy); #endif /* DEBUG_GRAVITY */ abs_dx = dx >= 0 ? dx : -dx; abs_dy = dy >= 0 ? dy : -dy; @@ -80,7 +80,8 @@ CalculateGravity (PELEMENT ElementPtr) abs_dy = WORLD_TO_DISPLAY (abs_dy); #ifdef DEBUG_GRAVITY if (TestElementPtr->state_flags & PLAYER_SHIP) - fprintf (stderr, "\tdisplay_dx = %d, display_dy = %d\n", abs_dx, abs_dy); + log_add (log_Debug, "\tdisplay_dx = %d, display_dy = %d", + abs_dx, abs_dy); #endif /* DEBUG_GRAVITY */ if (abs_dx <= GRAVITY_THRESHOLD && abs_dy <= GRAVITY_THRESHOLD) @@ -106,12 +107,12 @@ CalculateGravity (PELEMENT ElementPtr) #define MAX_MAGNITUDE 6 else if (magnitude > MAX_MAGNITUDE) magnitude = MAX_MAGNITUDE; - fprintf (stderr, "magnitude = %u ", magnitude); + log_add (log_Debug, "magnitude = %u", magnitude); #endif /* NEVER */ #ifdef DEBUG_GRAVITY if (TestElementPtr->state_flags & PLAYER_SHIP) - fprintf (stderr, "dist_squared = %lu\n", dist_squared); + log_add (log_Debug, "dist_squared = %lu", dist_squared); #endif /* DEBUG_GRAVITY */ if (TestHasGravity) { diff --git a/sc2/src/sc2code/grpinfo.c b/sc2/src/sc2code/grpinfo.c index 2fc268c55..2d350a95b 100644 --- a/sc2/src/sc2code/grpinfo.c +++ b/sc2/src/sc2code/grpinfo.c @@ -25,6 +25,7 @@ #include "state.h" #include "libs/mathlib.h" +#include "libs/log.h" #ifdef HAVE_UNISTD_H #include @@ -302,8 +303,8 @@ FlushGroupInfo (GROUP_HEADER *pGH, DWORD offset, BYTE which_group, PVOID fp) SeekStateFile (fp, offset, SEEK_SET); WriteStateFile (pGH, sizeof (*pGH), 1, fp); #ifdef DEBUG_GROUPS - fprintf (stderr, "1)FlushGroupInfo(%lu): WG = %u(%lu), NG = %u, " - "SI = %u\n", offset, which_group, pGH->GroupOffset[which_group], + log_add (log_Debug, "1)FlushGroupInfo(%lu): WG = %u(%lu), NG = %u, " + "SI = %u", offset, which_group, pGH->GroupOffset[which_group], pGH->NumGroups, pGH->star_index); #endif /* DEBUG_GROUPS */ @@ -336,7 +337,7 @@ FlushGroupInfo (GROUP_HEADER *pGH, DWORD offset, BYTE which_group, PVOID fp) #ifdef DEBUG_GROUPS if (which_group == 0) - fprintf (stderr, "F) type %u, loc %u<%d, %d>, task 0x%02x:%u\n", + log_add (log_Debug, "F) type %u, loc %u<%d, %d>, task 0x%02x:%u", RaceType, GET_GROUP_LOC (FragPtr), FragPtr->ShipInfo.loc.x, @@ -370,7 +371,7 @@ GetGroupInfo (DWORD offset, BYTE which_group) SeekStateFile (fp, offset, SEEK_SET); ReadStateFile (&GH, sizeof (GH), 1, fp); #ifdef DEBUG_GROUPS - fprintf (stderr, "GetGroupInfo(%lu): %u(%lu) out of %u\n", offset, + log_add (log_Debug, "GetGroupInfo(%lu): %u(%lu) out of %u", offset, which_group, GH.GroupOffset[which_group], GH.NumGroups); #endif /* DEBUG_GROUPS */ if (which_group == (BYTE)~0) @@ -379,7 +380,7 @@ GetGroupInfo (DWORD offset, BYTE which_group) ReinitQueue (&GLOBAL (npc_built_ship_q)); #ifdef DEBUG_GROUPS - fprintf (stderr, "%u == %u\n", GH.star_index, + log_add (log_Debug, "%u == %u", GH.star_index, (COUNT)(CurStarDescPtr - star_array)); #endif /* DEBUG_GROUPS */ day_index = GH.day_index; @@ -394,8 +395,8 @@ GetGroupInfo (DWORD offset, BYTE which_group) #ifdef DEBUG_GROUPS if (GH.star_index == (COUNT)(CurStarDescPtr - star_array)) - fprintf (stderr, "GetGroupInfo: battle groups out of " - "date %u/%u/%u!\n", month_index, day_index, + log_add (log_Debug, "GetGroupInfo: battle groups out of " + "date %u/%u/%u!", month_index, day_index, year_index); #endif /* DEBUG_GROUPS */ fp = OpenStateFile (RANDGRPINFO_FILE, "wb"); @@ -478,8 +479,8 @@ GetGroupInfo (DWORD offset, BYTE which_group) SET_GROUP_LOC (FragPtr, group_loc); #ifdef DEBUG_GROUPS - fprintf (stderr, "battle group %u(0x%04x) strength " - "%u, type %u, loc %u<%d, %d>, task %u\n", + log_add (log_Debug, "battle group %u(0x%04x) strength " + "%u, type %u, loc %u<%d, %d>, task %u", which_group, hStarShip, NumShips, @@ -558,8 +559,8 @@ GetGroupInfo (DWORD offset, BYTE which_group) #ifdef DEBUG_GROUPS if (which_group == 0) - fprintf (stderr, "G) type %u, loc %u<%d, %d>, " - "task 0x%02x:%u\n", + log_add (log_Debug, "G) type %u, loc %u<%d, %d>, " + "task 0x%02x:%u", RaceType, GET_GROUP_LOC (FragPtr), FragPtr->ShipInfo.loc.x, @@ -572,7 +573,7 @@ GetGroupInfo (DWORD offset, BYTE which_group) || ShipsLeft) { #ifdef DEBUG_GROUPS - fprintf (stderr, "\n"); + log_add (log_Debug, "\n"); #endif /* DEBUG_GROUPS */ if (RaceType == SHOFIXTI_SHIP && which_group @@ -593,7 +594,7 @@ GetGroupInfo (DWORD offset, BYTE which_group) else { #ifdef DEBUG_GROUPS - fprintf (stderr, " -- REMOVING\n"); + log_add (log_Debug, " -- REMOVING"); #endif /* DEBUG_GROUPS */ UnlockStarShip (&GLOBAL (npc_built_ship_q), hStarShip); RemoveQueue (&GLOBAL (npc_built_ship_q), hStarShip); @@ -660,7 +661,7 @@ PutGroupInfo (DWORD offset, BYTE which_group) } GH.star_index = CurStarDescPtr - star_array; #ifdef DEBUG_GROUPS - fprintf (stderr, "PutGroupInfo(%lu): %u out of %u -- %u/%u/%u\n", + log_add (log_Debug, "PutGroupInfo(%lu): %u out of %u -- %u/%u/%u", offset, which_group, GH.NumGroups, GH.month_index, GH.day_index, GH.year_index); #endif /* DEBUG_GROUPS */ diff --git a/sc2/src/sc2code/intel.c b/sc2/src/sc2code/intel.c index 2b46e2afe..f55cf7bb4 100644 --- a/sc2/src/sc2code/intel.c +++ b/sc2/src/sc2code/intel.c @@ -21,6 +21,7 @@ #include "controls.h" #include "globdata.h" #include "setup.h" +#include "libs/log.h" #include @@ -62,7 +63,7 @@ computer_intelligence (void) } default: // Should not happen. Satisfying compiler. - fprintf (stderr, "Warning: Unexpected state in " + log_add (log_Warning, "Warning: Unexpected state in " "computer_intelligence()."); InputState = 0; break; diff --git a/sc2/src/sc2code/intro.c b/sc2/src/sc2code/intro.c index f29fe2420..2dcc5886b 100644 --- a/sc2/src/sc2code/intro.c +++ b/sc2/src/sc2code/intro.c @@ -28,6 +28,7 @@ #include "libs/sound/sound.h" //#include "libs/vidlib.h" #include "libs/inplib.h" +#include "libs/log.h" #include @@ -576,7 +577,7 @@ DoPresentation (PVOID pIS) if (cargs < 1) { - fprintf (stderr, "Bad DRAW command '%s'\n", pStr); + log_add (log_Warning, "Bad DRAW command '%s'", pStr); continue; } if (cargs < 5) diff --git a/sc2/src/sc2code/libs/file/dirs.c b/sc2/src/sc2code/libs/file/dirs.c index 48b0ad02c..6fee8df69 100644 --- a/sc2/src/sc2code/libs/file/dirs.c +++ b/sc2/src/sc2code/libs/file/dirs.c @@ -27,6 +27,7 @@ #include "filintrn.h" #include "compiler.h" #include "misc.h" +#include "libs/log.h" #ifdef WIN32 # include @@ -105,7 +106,7 @@ mkdirhier (const char *path) { if (errno != ENOENT) { - fprintf (stderr, "Can't stat %s: %s\n", buf, + log_add (log_Always, "Can't stat %s: %s", buf, strerror (errno)); return -1; } @@ -131,7 +132,7 @@ mkdirhier (const char *path) { if (createDirectory (buf, 0777) == -1) { - fprintf (stderr, "Error: Can't create %s: %s\n", buf, + log_add (log_Always, "Error: Can't create %s: %s", buf, strerror (errno)); return -1; } @@ -264,9 +265,9 @@ expandPath (char *dest, size_t len, const char *src, int what) // fallback for when the APPDATA env var is not set // Using SHGetFolderPath or SHGetSpecialFolderPath // is problematic (not everywhere available). - fprintf(stderr, "Warning: %%APPDATA%% is not set. " + log_add (log_Warning, "Warning: %%APPDATA%% is not set. " "Falling back to \"%%USERPROFILE%%\\Application " - "Data\"\n"); + "Data\""); envVar = getenv ("USERPROFILE"); if (envVar != NULL) { @@ -284,8 +285,9 @@ expandPath (char *dest, size_t len, const char *src, int what) // fallback to "./userdata" #define APPDATA_FALLBACK_STRING ".\\userdata" - fprintf(stderr, "Warning: %%USERPROFILE%% is not set. " - "Falling back to \"%s\" for %%APPDATA%%\n", + log_add (log_Warning, + "Warning: %%USERPROFILE%% is not set. " + "Falling back to \"%s\" for %%APPDATA%%", APPDATA_FALLBACK_STRING); CHECKLEN (buf, sizeof (APPDATA_FALLBACK_STRING) - 1); strcpy (bufptr, APPDATA_FALLBACK_STRING); diff --git a/sc2/src/sc2code/libs/file/files.c b/sc2/src/sc2code/libs/file/files.c index 60a100851..ffe952fbb 100644 --- a/sc2/src/sc2code/libs/file/files.c +++ b/sc2/src/sc2code/libs/file/files.c @@ -27,6 +27,7 @@ #include "types.h" #include "filintrn.h" #include "misc.h" +#include "libs/log.h" static int copyError(uio_Handle *srcHandle, uio_Handle *dstHandle, uio_DirHandle *unlinkHandle, const char *unlinkPath, uint8 *buf); @@ -144,9 +145,7 @@ copyError(uio_Handle *srcHandle, uio_Handle *dstHandle, savedErrno = errno; -#ifdef DEBUG - fprintf (stderr, "Error while copying: %s\n", strerror (errno)); -#endif + log_add (log_Debug, "Error while copying: %s", strerror (errno)); if (srcHandle != NULL) uio_close (srcHandle); diff --git a/sc2/src/sc2code/libs/file/temp.c b/sc2/src/sc2code/libs/file/temp.c index 589268b3c..d22b7d6e4 100644 --- a/sc2/src/sc2code/libs/file/temp.c +++ b/sc2/src/sc2code/libs/file/temp.c @@ -28,6 +28,7 @@ #include "timelib.h" #include "port.h" #include "libs/compiler.h" +#include "libs/log.h" #include "misc.h" static char *tempDirName; @@ -99,8 +100,8 @@ getTempDir (char *buf, size_t buflen) { tryTempDir (buf, buflen, "/tmp/") && tryTempDir (buf, buflen, getcwd (cwd, sizeof cwd))) { - fprintf (stderr, "Fatal Error: Cannot find a suitable location " - "to store temporary files.\n"); + log_add (log_Always, "Fatal Error: Cannot find a suitable location " + "to store temporary files."); exit (EXIT_FAILURE); } } @@ -117,8 +118,8 @@ mountTempDir(const char *name) { uio_MOUNT_TOP, NULL); if (tempHandle == NULL) { int saveErrno = errno; - fprintf (stderr, "Fatal error: Couldn't mount temp dir '%s': " - "%s\n", name, strerror (errno)); + log_add (log_Always, "Fatal error: Couldn't mount temp dir '%s': " + "%s", name, strerror (errno)); errno = saveErrno; return -1; } @@ -126,7 +127,7 @@ mountTempDir(const char *name) { tempDir = uio_openDir (repository, "/tmp", 0); if (tempDir == NULL) { int saveErrno = errno; - fprintf (stderr, "Fatal error: Could not open temp dir: %s\n", + log_add (log_Always, "Fatal error: Could not open temp dir: %s", strerror (errno)); errno = saveErrno; return -1; @@ -168,9 +169,9 @@ initTempDir (void) { } // Failure, could not make a temporary directory. - fprintf(stderr, "Fatal error: Cannot get a name for a temporary " - "directory.\n"); - exit(EXIT_FAILURE); + log_add (log_Always, "Fatal error: Cannot get a name for a temporary " + "directory."); + exit (EXIT_FAILURE); } void @@ -186,7 +187,7 @@ tempFilePath (const char *filename) { static char file[PATH_MAX]; if (snprintf (file, PATH_MAX, "%s/%s", tempDirName, filename) == -1) { - fprintf (stderr, "Path to temp file too long.\n"); + log_add (log_Always, "Path to temp file too long."); exit (EXIT_FAILURE); } return file; diff --git a/sc2/src/sc2code/libs/graphics/cmap.c b/sc2/src/sc2code/libs/graphics/cmap.c index 731304b27..0bf8e0ad0 100644 --- a/sc2/src/sc2code/libs/graphics/cmap.c +++ b/sc2/src/sc2code/libs/graphics/cmap.c @@ -18,6 +18,7 @@ #include "gfx_common.h" #include "libs/tasklib.h" +#include "libs/log.h" #include @@ -129,14 +130,15 @@ clone_colormap (TFB_ColorMap *from, int index) if (!from) { - fprintf (stderr, "FATAL: clone_colormap(): no maps available\n"); - abort (); + log_add (log_Warning, "FATAL: clone_colormap(): " + "no maps available"); + exit (EXIT_FAILURE); } Now = GetTimeCounter (); if (Now >= NextTime) { - fprintf (stderr, "clone_colormap(): static pool exhausted\n"); + log_add (log_Warning, "clone_colormap(): static pool exhausted"); NextTime = Now + ONE_SECOND; } @@ -160,7 +162,7 @@ free_colormap (TFB_ColorMap *map) { if (!map) { - fprintf (stderr, "free_colormap(): tried to free a NULL map\n"); + log_add (log_Warning, "free_colormap(): tried to free a NULL map"); return; } @@ -176,8 +178,8 @@ get_colormap (int index) map = colormaps[index]; if (!map) { - fprintf (stderr, "BUG: get_colormap(): map not present\n"); - abort (); + log_add (log_Always, "BUG: get_colormap(): map not present"); + exit (EXIT_FAILURE); } map->refcount++; @@ -192,7 +194,7 @@ release_colormap (TFB_ColorMap *map) if (map->refcount <= 0) { - fprintf (stderr, "BUG: release_colormap(): refcount not >0\n"); + log_add (log_Warning, "BUG: release_colormap(): refcount not >0"); return; } @@ -231,8 +233,8 @@ TFB_ColorMapToRGB (TFB_Palette *pal, int index) if (!map) { - fprintf (stderr, "TFB_ColorMapToRGB(): " - "requested non-present colormap %d\n", index); + log_add (log_Warning, "TFB_ColorMapToRGB(): " + "requested non-present colormap %d", index); return; } @@ -254,21 +256,21 @@ SetColorMap (COLORMAPPTR map) end = *colors++; if (start > end) { - fprintf (stderr, "ERROR: SetColorMap(): " - "starting map (%d) not less or eq ending (%d)\n", + log_add (log_Warning, "ERROR: SetColorMap(): " + "starting map (%d) not less or eq ending (%d)", start, end); return FALSE; } if (start >= MAX_COLORMAPS) { - fprintf (stderr, "ERROR: SetColorMap(): " - "starting map (%d) beyond range (0-%d)\n", + log_add (log_Warning, "ERROR: SetColorMap(): " + "starting map (%d) beyond range (0-%d)", start, (int)MAX_COLORMAPS - 1); return FALSE; } if (end >= MAX_COLORMAPS) { - fprintf (stderr, "SetColorMap(): " + log_add (log_Warning, "SetColorMap(): " "ending map (%d) beyond range (0-%d)\n", end, (int)MAX_COLORMAPS - 1); end = MAX_COLORMAPS - 1; @@ -305,7 +307,6 @@ SetColorMap (COLORMAPPTR map) UnlockMutex (maplock); - //fprintf (stderr, "SetColorMap(): vp %x map %x bytes %d, start %d end %d\n", vp, map, bytes, start, end); return TRUE; } @@ -338,7 +339,7 @@ fade_xform_task (void *data) TDelta = TTotal; FadeAmount += (FadeEnd - FadeAmount) * TDelta / TTotal; - //fprintf (stderr, "fade_xform_task FadeAmount %d\n", FadeAmount); + //log_add (log_Debug, "fade_xform_task FadeAmount %d\n", FadeAmount); } while ((TTotal -= TDelta) && (!Task_ReadState (task, TASK_EXIT))); } @@ -452,7 +453,7 @@ XFormColorMap_step (void) if (!curmap) { UnlockMutex (maplock); - fprintf (stderr, "BUG: XFormColorMap_step(): no current map\n"); + log_add (log_Always, "BUG: XFormColorMap_step(): no current map"); finish_colormap_xform (x); continue; } @@ -561,9 +562,7 @@ XFormPLUT (COLORMAPPTR ColorMapPtr, SIZE TimeInterval) } else if (x >= MAX_XFORMS) { // flush some xforms if the queue is full -#ifdef DEBUG - fprintf (stderr, "WARNING: XFormPLUT(): no slots available\n"); -#endif + log_add (log_Debug, "WARNING: XFormPLUT(): no slots available"); x = XFormControl.Highest; finish_colormap_xform (x); } @@ -579,7 +578,7 @@ XFormPLUT (COLORMAPPTR ColorMapPtr, SIZE TimeInterval) { UnlockMutex (maplock); UnlockMutex (XFormControl.Lock); - fprintf (stderr, "BUG: XFormPLUT(): no current map\n"); + log_add (log_Warning, "BUG: XFormPLUT(): no current map"); return (0); } memcpy (control->OldCMap, map->colors, sizeof (map->colors)); diff --git a/sc2/src/sc2code/libs/graphics/font.c b/sc2/src/sc2code/libs/graphics/font.c index bcd2dd04d..b0b945fd6 100644 --- a/sc2/src/sc2code/libs/graphics/font.c +++ b/sc2/src/sc2code/libs/graphics/font.c @@ -19,7 +19,7 @@ #include "gfxintrn.h" #include "tfb_prim.h" #include "gfxother.h" - +#include "libs/log.h" extern void FixContextFontEffect (void); static inline TFB_Char *getCharFrame (FONT_DESC *fontPtr, wchar_t ch); @@ -333,9 +333,7 @@ getCharFrame (FONT_DESC *fontPtr, wchar_t ch) } else { -#ifdef DEBUG - fprintf (stderr, "Character %u not present\n", (unsigned int) ch); -#endif + log_add (log_Debug, "Character %u not present", (unsigned int) ch); return NULL; } } diff --git a/sc2/src/sc2code/libs/graphics/gfx_common.c b/sc2/src/sc2code/libs/graphics/gfx_common.c index 0cdbd52a7..9db1bf66e 100644 --- a/sc2/src/sc2code/libs/graphics/gfx_common.c +++ b/sc2/src/sc2code/libs/graphics/gfx_common.c @@ -39,7 +39,7 @@ int TFB_DEBUG_HALT = 0; void SetGraphicUseOtherExtra (int other) //Could this possibly be more cryptic?!? :) { - //fprintf(stderr, "SetGraphicUseOtherExtra %d\n", other); + //log_add (log_Debug, "SetGraphicUseOtherExtra %d", other); (void)other; /* lint */ } @@ -47,7 +47,7 @@ SetGraphicUseOtherExtra (int other) //Could this possibly be more cryptic?!? :) void SetGraphicGrabOther (int grab_other) { - //fprintf(stderr, "SetGraphicGrabOther %d\n", grab_other); + //log_add (log_Debug, "SetGraphicGrabOther %d", grab_other); (void)grab_other; /* lint */ } diff --git a/sc2/src/sc2code/libs/graphics/intersec.c b/sc2/src/sc2code/libs/graphics/intersec.c index ff1d12515..1fe890c02 100644 --- a/sc2/src/sc2code/libs/graphics/intersec.c +++ b/sc2/src/sc2code/libs/graphics/intersec.c @@ -17,6 +17,7 @@ */ #include "gfxintrn.h" +#include "libs/log.h" //#define DEBUG_INTERSEC @@ -334,12 +335,14 @@ DrawablesIntersect (PINTERSECT_CONTROL pControl0, ++time_x_1; #ifdef DEBUG_INTERSEC - fprintf (stderr, "FramePtr0<%d, %d> --> <%d, %d>\nFramePtr1<%d, %d> --> <%d, %d>\n", + log_add (log_Debug, "FramePtr0<%d, %d> --> <%d, %d>", GetFrameWidth (FramePtr0), GetFrameHeight (FramePtr0), - r0.corner.x, r0.corner.y, + r0.corner.x, r0.corner.y); + log_add (log_Debug, "FramePtr1<%d, %d> --> <%d, %d>", GetFrameWidth (FramePtr1), GetFrameHeight (FramePtr1), r1.corner.x, r1.corner.y); - fprintf (stderr, "time_x(%d, %d)-%d, time_y(%d, %d)-%d\n", time_x_0, time_x_1, dx, time_y_0, time_y_1, dy); + log_add (log_Debug, "time_x(%d, %d)-%d, time_y(%d, %d)-%d", + time_x_0, time_x_1, dx, time_y_0, time_y_1, dy); #endif /* DEBUG_INTERSEC */ if (dx == 0) { @@ -382,7 +385,8 @@ DrawablesIntersect (PINTERSECT_CONTROL pControl0, } #ifdef DEBUG_INTERSEC - fprintf (stderr, "start_time = %d, end_time = %d\n", time_y_0, time_y_1); + log_add (log_Debug, "start_time = %d, end_time = %d", + time_y_0, time_y_1); #endif /* DEBUG_INTERSEC */ if (time_y_0 <= time_y_1 && (intersect_time = frame_intersect ( diff --git a/sc2/src/sc2code/libs/graphics/sdl/3do_blt.c b/sc2/src/sc2code/libs/graphics/sdl/3do_blt.c index 022b6f734..9c6e895e7 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/3do_blt.c +++ b/sc2/src/sc2code/libs/graphics/sdl/3do_blt.c @@ -20,6 +20,7 @@ #include "sdl_common.h" #include "graphics/tfb_draw.h" +#include "libs/log.h" static int gscale = GSCALE_IDENTITY; @@ -44,7 +45,7 @@ read_screen (PRECT lpRect, FRAMEPTR DstFramePtr) ->FlagsAndIndex) & ((DWORD) MAPPED_TO_DISPLAY << FTYPE_SHIFT))) { - fprintf (stderr, "Unimplemented function activated: read_screen()\n"); + log_add (log_Warning, "Unimplemented function activated: read_screen()"); } else { diff --git a/sc2/src/sc2code/libs/graphics/sdl/3do_getbody.c b/sc2/src/sc2code/libs/graphics/sdl/3do_getbody.c index b6eb5a573..5384a2e16 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/3do_getbody.c +++ b/sc2/src/sc2code/libs/graphics/sdl/3do_getbody.c @@ -29,6 +29,7 @@ #include "sdluio.h" #include "libs/file.h" #include "libs/reslib.h" +#include "libs/log.h" #include "../font.h" #include "primitives.h" @@ -415,15 +416,15 @@ _GetCelData (uio_Stream *fp, DWORD length) const char *err; err = SDL_GetError(); - fprintf (stderr, "_GetCelData: Unable to load image!\n"); + log_add (log_Warning, "_GetCelData: Unable to load image!"); if (err != NULL) - fprintf (stderr, "SDL reports: %s\n", err); + log_add (log_Warning, "SDL reports: %s", err); SDL_FreeSurface (img[cel_ct]); } else if (img[cel_ct]->w < 0 || img[cel_ct]->h < 0 || img[cel_ct]->format->BitsPerPixel < 8) { - fprintf (stderr, "_GetCelData: Bad file!\n"); + log_add (log_Warning, "_GetCelData: Bad file!"); SDL_FreeSurface (img[cel_ct]); } else @@ -466,7 +467,7 @@ _GetCelData (uio_Stream *fp, DWORD length) } if (Drawable == 0) - fprintf (stderr, "Couldn't get cel data for '%s'\n", + log_add (log_Warning, "Couldn't get cel data for '%s'", _cur_resfile_name); return (GetDrawableHandle (Drawable)); } @@ -638,11 +639,9 @@ _GetFontData (uio_Stream *fp, DWORD length) if (destChar->data != NULL) { // There's already an image for this character. -#ifdef DEBUG - fprintf (stderr, "Duplicate image for character %d " - "for font %s.\n", (int) bcd->index, + log_add (log_Debug, "Duplicate image for character %d " + "for font %s.", (int) bcd->index, _cur_resfile_name); -#endif SDL_FreeSurface (bcd->surface); continue; } diff --git a/sc2/src/sc2code/libs/graphics/sdl/canvas.c b/sc2/src/sc2code/libs/graphics/sdl/canvas.c index 98ad96595..9607c4894 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/canvas.c +++ b/sc2/src/sc2code/libs/graphics/sdl/canvas.c @@ -4,6 +4,7 @@ #include "libs/graphics/gfx_common.h" #include "libs/graphics/sdl/primitives.h" #include "libs/graphics/tfb_draw.h" +#include "libs/log.h" #include "rotozoom.h" #include "options.h" #include "types.h" @@ -70,7 +71,7 @@ TFB_DrawCanvas_Image (TFB_Image *img, int x, int y, int scale, if (img == 0) { - fprintf (stderr, "ERROR: TFB_DrawCanvas_Image passed null image ptr\n"); + log_add (log_Warning, "ERROR: TFB_DrawCanvas_Image passed null image ptr"); return; } @@ -154,8 +155,8 @@ TFB_DrawCanvas_Fill (TFB_Canvas source, int width, int height, if (srcfmt->BytesPerPixel != 4 || dstfmt->BytesPerPixel != 4) { - fprintf (stderr, "TFB_DrawCanvas_Fill: Unsupported surface formats: " - "%d bytes/pixel source, %d bytes/pixel destination\n", + log_add (log_Warning, "TFB_DrawCanvas_Fill: Unsupported surface " + "formats: %d bytes/pixel source, %d bytes/pixel destination", (int)srcfmt->BytesPerPixel, (int)dstfmt->BytesPerPixel); return; } @@ -207,8 +208,8 @@ TFB_DrawCanvas_Fill (TFB_Canvas source, int width, int height, } else { - fprintf (stderr, "TFB_DrawCanvas_Fill: Unsupported source surface " - "format\n"); + log_add (log_Warning, "TFB_DrawCanvas_Fill: Unsupported source" + "surface format\n"); } SDL_UnlockSurface(dst); @@ -232,7 +233,7 @@ TFB_DrawCanvas_FilledImage (TFB_Image *img, int x, int y, int scale, int r, int if (img == 0) { - fprintf (stderr, "ERROR: TFB_DrawCanvas_FilledImage passed null image ptr\n"); + log_add (log_Warning, "ERROR: TFB_DrawCanvas_FilledImage passed null image ptr"); return; } @@ -327,14 +328,14 @@ TFB_DrawCanvas_FontChar (TFB_Char *fontChar, TFB_Image *backing, if (fontChar == 0) { - fprintf (stderr, "ERROR: " - "TFB_DrawCanvas_FontChar passed null char ptr\n"); + log_add (log_Warning, "ERROR: " + "TFB_DrawCanvas_FontChar passed null char ptr"); return; } if (backing == 0) { - fprintf (stderr, "ERROR: " - "TFB_DrawCanvas_FontChar passed null backing ptr\n"); + log_add (log_Warning, "ERROR: " + "TFB_DrawCanvas_FontChar passed null backing ptr"); return; } @@ -347,9 +348,9 @@ TFB_DrawCanvas_FontChar (TFB_Char *fontChar, TFB_Image *backing, if (surf->format->BytesPerPixel != 4 || surf->w < w || surf->h < h) { - fprintf (stderr, "ERROR: " + log_add (log_Warning, "ERROR: " "TFB_DrawCanvas_FontChar bad backing surface: %dx%dx%d; " - "char: %dx%d\n", + "char: %dx%d", surf->w, surf->h, (int)surf->format->BytesPerPixel, w, h); UnlockMutex (backing->mutex); return; @@ -397,9 +398,11 @@ TFB_DrawCanvas_New_TrueColor (int w, int h, BOOLEAN hasalpha) new_surf = SDL_CreateRGBSurface (SDL_SWSURFACE, w, h, fmt->BitsPerPixel, fmt->Rmask, fmt->Gmask, fmt->Bmask, hasalpha ? fmt->Amask : 0); - if (!new_surf) { - fprintf(stderr, "INTERNAL PANIC: Failed to create TFB_Canvas: %s", SDL_GetError()); - exit(-1); + if (!new_surf) + { + log_add (log_Always, "INTERNAL PANIC: Failed to create TFB_Canvas: %s", + SDL_GetError()); + exit (EXIT_FAILURE); } return new_surf; } @@ -412,7 +415,7 @@ TFB_DrawCanvas_New_ForScreen (int w, int h, BOOLEAN withalpha) if (fmt->palette) { - fprintf(stderr, "TFB_DrawCanvas_New_ForScreen() WARNING:" + log_add (log_Warning, "TFB_DrawCanvas_New_ForScreen() WARNING:" "Paletted display format will be slow"); new_surf = TFB_DrawCanvas_New_TrueColor (w, h, withalpha); @@ -429,9 +432,9 @@ TFB_DrawCanvas_New_ForScreen (int w, int h, BOOLEAN withalpha) if (!new_surf) { - fprintf(stderr, "TFB_DrawCanvas_New_ForScreen() INTERNAL PANIC:" + log_add (log_Always, "TFB_DrawCanvas_New_ForScreen() INTERNAL PANIC:" "Failed to create TFB_Canvas: %s", SDL_GetError()); - exit (-1); + exit (EXIT_FAILURE); } return new_surf; } @@ -441,9 +444,11 @@ TFB_DrawCanvas_New_Paletted (int w, int h, TFB_Palette *palette, int transparent { SDL_Surface *new_surf; new_surf = SDL_CreateRGBSurface (SDL_SWSURFACE, w, h, 8, 0, 0, 0, 0); - if (!new_surf) { - fprintf(stderr, "INTERNAL PANIC: Failed to create TFB_Canvas: %s\n", SDL_GetError()); - exit(-1); + if (!new_surf) + { + log_add (log_Always, "INTERNAL PANIC: Failed to create TFB_Canvas: %s", + SDL_GetError()); + exit (EXIT_FAILURE); } if (palette != NULL) { @@ -530,9 +535,10 @@ TFB_DrawCanvas_New_RotationTarget (TFB_Canvas src_canvas, int angle) src->format->Amask); if (!newsurf) { - fprintf(stderr, "TFB_DrawCanvas_New_RotationTarget() INTERNAL PANIC:" - "Failed to create TFB_Canvas: %s", SDL_GetError()); - exit (-1); + log_add (log_Always, "TFB_DrawCanvas_New_RotationTarget()" + " INTERNAL PANIC: Failed to create TFB_Canvas: %s", + SDL_GetError()); + exit (EXIT_FAILURE); } if (src->format->palette) TFB_DrawCanvas_SetTransparentIndex (newsurf, TFB_DrawCanvas_GetTransparentIndex (src), FALSE); @@ -551,7 +557,8 @@ TFB_DrawCanvas_Delete (TFB_Canvas canvas) { if (!canvas) { - fprintf(stderr, "INTERNAL PANIC: Attempted to delete a NULL canvas!\n"); + log_add (log_Warning, "INTERNAL PANIC: Attempted" + " to delete a NULL canvas!"); /* Should we actually die here? */ } else @@ -590,7 +597,8 @@ TFB_DrawCanvas_ToScreenFormat (TFB_Canvas canvas) SDL_Surface *result = TFB_DisplayFormatAlpha ((SDL_Surface *)canvas); if (result == NULL) { - fprintf (stderr, "WARNING: Could not convert sprite-canvas to display format.\n"); + log_add (log_Always, "WARNING: Could not convert" + " sprite-canvas to display format."); return canvas; } else if (result == canvas) @@ -743,13 +751,16 @@ TFB_DrawCanvas_Rescale_Nearest (TFB_Canvas src_canvas, TFB_Canvas dest_canvas, E if (size.width + size.height > NNS_MAX_DIMS) { - fprintf (stderr, "TFB_DrawCanvas_Scale: Tried to zoom an image to unreasonable size! Failing.\n"); + log_add (log_Warning, "TFB_DrawCanvas_Scale: Tried to zoom" + " an image to unreasonable size! Failing."); return; } if (size.width > dst->w || size.height > dst->h) { - fprintf (stderr, "TFB_DrawCanvas_Scale: Tried to scale image to size %d %d when dest_canvas has only dimensions of %d %d! Failing.\n", - size.width, size.height, dst->w, dst->h); + log_add (log_Warning, "TFB_DrawCanvas_Scale: Tried to scale" + " image to size %d %d when dest_canvas has only" + " dimensions of %d %d! Failing.", + size.width, size.height, dst->w, dst->h); return; } @@ -836,7 +847,8 @@ TFB_DrawCanvas_Rescale_Nearest (TFB_Canvas src_canvas, TFB_Canvas dest_canvas, E } else { - fprintf (stderr, "Tried to deal with unknown BPP: %d -> %d\n", src->format->BitsPerPixel, dst->format->BitsPerPixel); + log_add (log_Warning, "Tried to deal with unknown BPP: %d -> %d", + src->format->BitsPerPixel, dst->format->BitsPerPixel); } SDL_UnlockSurface (dst); SDL_UnlockSurface (src); @@ -985,8 +997,10 @@ TFB_DrawCanvas_Rescale_Trilinear (TFB_Canvas src_canvas, if (size.width > dst->w || size.height > dst->h) { - fprintf (stderr, "TFB_DrawCanvas_Rescale_Trilinear: Tried to scale image to size %d %d when dest_canvas has only dimensions of %d %d! Failing.\n", - size.width, size.height, dst->w, dst->h); + log_add (log_Warning, "TFB_DrawCanvas_Rescale_Trilinear: " + "Tried to scale image to size %d %d when dest_canvas" + " has only dimensions of %d %d! Failing.", + size.width, size.height, dst->w, dst->h); return; } @@ -994,8 +1008,11 @@ TFB_DrawCanvas_Rescale_Trilinear (TFB_Canvas src_canvas, (mmfmt->BytesPerPixel != 1 && mmfmt->BytesPerPixel != 4) || (dst->format->BytesPerPixel != 4)) { - fprintf (stderr, "Tried to deal with unknown BPP: %d -> %d, mipmap %d\n", - srcfmt->BitsPerPixel, dst->format->BitsPerPixel, mmfmt->BitsPerPixel); + log_add (log_Warning, "TFB_DrawCanvas_Rescale_Trilinear: " + "Tried to deal with unknown BPP: %d -> %d, mipmap %d", + srcfmt->BitsPerPixel, dst->format->BitsPerPixel, + mmfmt->BitsPerPixel); + return; } // use colorkeys where appropriate @@ -1230,7 +1247,7 @@ TFB_DrawCanvas_GetScreenFormat (TFB_PixelFormat *fmt) if (sdl->palette) { - fprintf(stderr, "TFB_DrawCanvas_GetScreenFormat() WARNING:" + log_add (log_Warning, "TFB_DrawCanvas_GetScreenFormat() WARNING:" "Paletted display format will be slow"); fmt->BitsPerPixel = 32; @@ -1282,8 +1299,10 @@ TFB_DrawCanvas_Rotate (TFB_Canvas src_canvas, TFB_Canvas dst_canvas, int angle, if (size.width > dst->w || size.height > dst->h) { - fprintf (stderr, "TFB_DrawCanvas_Rotate: Tried to rotate image to size %d %d when dst_canvas has only dimensions of %d %d! Failing.\n", - size.width, size.height, dst->w, dst->h); + log_add (log_Warning, "TFB_DrawCanvas_Rotate: Tried to rotate" + " image to size %d %d when dst_canvas has only dimensions" + " of %d %d! Failing.", + size.width, size.height, dst->w, dst->h); return; } @@ -1297,7 +1316,8 @@ TFB_DrawCanvas_Rotate (TFB_Canvas src_canvas, TFB_Canvas dst_canvas, int angle, ret = rotateSurface (src, dst, angle, 0); if (ret != 0) { - fprintf (stderr, "TFB_DrawCanvas_Rotate: WARNING: actual rotation func returned failure\n"); + log_add (log_Warning, "TFB_DrawCanvas_Rotate: WARNING:" + " actual rotation func returned failure\n"); } } diff --git a/sc2/src/sc2code/libs/graphics/sdl/dcqueue.c b/sc2/src/sc2code/libs/graphics/sdl/dcqueue.c index bf33a0b3a..39ffa3239 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/dcqueue.c +++ b/sc2/src/sc2code/libs/graphics/sdl/dcqueue.c @@ -24,6 +24,7 @@ #include SDL_INCLUDE(SDL_thread.h) #include "libs/graphics/drawcmd.h" #include "libs/graphics/sdl/dcqueue.h" +#include "libs/log.h" static RecursiveMutex DCQ_Mutex; @@ -39,8 +40,8 @@ static void TFB_WaitForSpace (int requested_slots) { int old_depth, i; - fprintf (stderr, "DCQ overload (Size = %d, FullSize = %d, " - "Requested = %d). Sleeping until renderer is done.\n", + log_add (log_Debug, "DCQ overload (Size = %d, FullSize = %d, " + "Requested = %d). Sleeping until renderer is done.", DrawCommandQueue.Size, DrawCommandQueue.FullSize, requested_slots); // Restore the DCQ locking level. I *think* this is @@ -52,7 +53,7 @@ TFB_WaitForSpace (int requested_slots) WaitCondVar (RenderingCond); for (i = 0; i < old_depth; i++) LockRecursiveMutex (DCQ_Mutex); - fprintf (stderr, "DCQ clear (Size = %d, FullSize = %d). Continuing.\n", + log_add (log_Debug, "DCQ clear (Size = %d, FullSize = %d). Continuing.", DrawCommandQueue.Size, DrawCommandQueue.FullSize); } @@ -173,8 +174,8 @@ TFB_DrawCommandQueue_Pop (TFB_DrawCommand *target) if (DrawCommandQueue.Front == DrawCommandQueue.Back && DrawCommandQueue.Size != DCQ_MAX) { - fprintf (stderr, "Augh! Assertion failure in DCQ! Front == Back, " - "Size != DCQ_MAX\n"); + log_add (log_Debug, "Augh! Assertion failure in DCQ! " + "Front == Back, Size != DCQ_MAX"); DrawCommandQueue.Size = 0; Unlock_DCQ (); return (0); diff --git a/sc2/src/sc2code/libs/graphics/sdl/opengl.c b/sc2/src/sc2code/libs/graphics/sdl/opengl.c index 1eca99a5f..575621098 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/opengl.c +++ b/sc2/src/sc2code/libs/graphics/sdl/opengl.c @@ -21,6 +21,7 @@ #include "libs/graphics/sdl/opengl.h" #include "bbox.h" #include "scalers.h" +#include "libs/log.h" static SDL_Surface *scaled_display = NULL; static SDL_Surface *scaled_transition = NULL; @@ -53,7 +54,7 @@ Create_Screen (SDL_Surface *template, int w, int h) template->format->Rmask, template->format->Gmask, template->format->Bmask, 0); if (newsurf == 0) { - fprintf (stderr, "Couldn't create screen buffers: %s\n", + log_add (log_Always, "Couldn't create screen buffers: %s", SDL_GetError()); } return newsurf; @@ -117,19 +118,20 @@ AttemptColorDepth (int flags, int width, int height, int bpp) bpp, videomode_flags); if (SDL_Video == NULL) { - fprintf (stderr, "Couldn't set OpenGL %ix%ix%i video mode: %s\n", + log_add (log_Always, "Couldn't set OpenGL %ix%ix%i video mode: %s", ScreenWidthActual, ScreenHeightActual, bpp, SDL_GetError ()); return -1; } else { - fprintf (stderr, "Set the resolution to: %ix%ix%i (surface reports %ix%ix%i)\n", + log_add (log_Always, "Set the resolution to: %ix%ix%i" + " (surface reports %ix%ix%i)", width, height, bpp, SDL_GetVideoSurface()->w, SDL_GetVideoSurface()->h, SDL_GetVideoSurface()->format->BitsPerPixel); - fprintf (stderr, "OpenGL renderer: %s version: %s\n", + log_add (log_Always, "OpenGL renderer: %s version: %s", glGetString (GL_RENDERER), glGetString (GL_VERSION)); } return 0; @@ -145,7 +147,7 @@ TFB_GL_ConfigureVideo (int driver, int flags, int width, int height) AttemptColorDepth (flags, width, height, 24) && AttemptColorDepth (flags, width, height, 16)) { - fprintf (stderr, "Couldn't set any OpenGL %ix%i video mode!\n", + log_add (log_Always, "Couldn't set any OpenGL %ix%i video mode!", width, height); return -1; } @@ -156,7 +158,7 @@ TFB_GL_ConfigureVideo (int driver, int flags, int width, int height) R_MASK, G_MASK, B_MASK, A_MASK); if (format_conv_surf == NULL) { - fprintf (stderr, "Couldn't create format_conv_surf: %s\n", + log_add (log_Always, "Couldn't create format_conv_surf: %s", SDL_GetError()); return -1; } @@ -231,21 +233,21 @@ TFB_GL_InitGraphics (int driver, int flags, int width, int height) { char VideoName[256]; - fprintf (stderr, "Initializing SDL with OpenGL support.\n"); + log_add (log_Always, "Initializing SDL with OpenGL support."); SDL_VideoDriverName (VideoName, sizeof (VideoName)); - fprintf (stderr, "SDL driver used: %s\n", VideoName); - fprintf (stderr, "SDL initialized.\n"); - fprintf (stderr, "Initializing Screen.\n"); + log_add (log_Always, "SDL driver used: %s", VideoName); + log_add (log_Always, "SDL initialized."); + log_add (log_Always, "Initializing Screen."); ScreenWidth = 320; ScreenHeight = 240; if (TFB_GL_ConfigureVideo (driver, flags, width, height)) { - fprintf (stderr, "Could not initialize video: " - "no fallback at start of program!\n"); - exit (-1); + log_add (log_Always, "Could not initialize video: " + "no fallback at start of program!"); + exit (EXIT_FAILURE); } // Initialize scalers (let them precompute whatever) diff --git a/sc2/src/sc2code/libs/graphics/sdl/pure.c b/sc2/src/sc2code/libs/graphics/sdl/pure.c index c541f1d6d..78d8055fc 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/pure.c +++ b/sc2/src/sc2code/libs/graphics/sdl/pure.c @@ -20,6 +20,7 @@ #include "pure.h" #include "bbox.h" #include "scalers.h" +#include "libs/log.h" static SDL_Surface *fade_black = NULL; static SDL_Surface *fade_white = NULL; @@ -36,7 +37,7 @@ Create_Screen (SDL_Surface *template, int w, int h) template->format->Rmask, template->format->Gmask, template->format->Bmask, 0); if (newsurf == 0) { - fprintf (stderr, "Couldn't create screen buffers: %s\n", + log_add (log_Always, "Couldn't create screen buffers: %s", SDL_GetError()); } return newsurf; @@ -75,8 +76,8 @@ TFB_Pure_ConfigureVideo (int driver, int flags, int width, int height) ScreenHeightActual = 480; if (width != 640 || height != 480) - fprintf (stderr, "Screen resolution of %dx%d not supported " - "under pure SDL, using 640x480\n", width, height); + log_add (log_Always, "Screen resolution of %dx%d not supported " + "under pure SDL, using 640x480", width, height); } videomode_flags |= SDL_ANYFORMAT; @@ -90,14 +91,14 @@ TFB_Pure_ConfigureVideo (int driver, int flags, int width, int height) if (SDL_Video == NULL) { - fprintf (stderr, "Couldn't set %ix%i video mode: %s\n", + log_add (log_Always, "Couldn't set %ix%i video mode: %s", ScreenWidthActual, ScreenHeightActual, SDL_GetError ()); return -1; } else { - fprintf (stderr, "Set the resolution to: %ix%ix%i\n", + log_add (log_Always, "Set the resolution to: %ix%ix%i", SDL_GetVideoSurface()->w, SDL_GetVideoSurface()->h, SDL_GetVideoSurface()->format->BitsPerPixel); ScreenColorDepth = SDL_GetVideoSurface()->format->BitsPerPixel; @@ -125,7 +126,7 @@ TFB_Pure_ConfigureVideo (int driver, int flags, int width, int height) } if (!format_conv_surf) { - fprintf (stderr, "Couldn't create format_conv_surf: %s\n", + log_add (log_Always, "Couldn't create format_conv_surf: %s", SDL_GetError()); return -1; } @@ -178,27 +179,26 @@ TFB_Pure_InitGraphics (int driver, int flags, int width, int height) { char VideoName[256]; - fprintf (stderr, "Initializing Pure-SDL graphics.\n"); + log_add (log_Always, "Initializing Pure-SDL graphics."); SDL_VideoDriverName (VideoName, sizeof (VideoName)); - fprintf (stderr, "SDL driver used: %s\n", VideoName); + log_add (log_Always, "SDL driver used: %s", VideoName); // Set the environment variable SDL_VIDEODRIVER to override // For Linux: x11 (default), dga, fbcon, directfb, svgalib, // ggi, aalib // For Windows: directx (default), windib - fprintf (stderr, "SDL initialized.\n"); - - fprintf (stderr, "Initializing Screen.\n"); + log_add (log_Always, "SDL initialized."); + log_add (log_Always, "Initializing Screen."); ScreenWidth = 320; ScreenHeight = 240; if (TFB_Pure_ConfigureVideo (driver, flags, width, height)) { - fprintf (stderr, "Could not initialize video: " - "no fallback at start of program!\n"); - exit (-1); + log_add (log_Always, "Could not initialize video: " + "no fallback at start of program!"); + exit (EXIT_FAILURE); } // Initialize scalers (let them precompute whatever) @@ -369,14 +369,14 @@ Scale_PerfTest (void) if (!scaler) { - fprintf (stderr, "No scaler configured! " - "Run with larger resolution, please\n"); + log_add (log_Always, "No scaler configured! " + "Run with larger resolution, please"); return; } if (!scaled_display) { - fprintf (stderr, "Run scaler performance tests " - "in Pure mode, please\n"); + log_add (log_Always, "Run scaler performance tests " + "in Pure mode, please"); return; } @@ -395,13 +395,13 @@ Scale_PerfTest (void) if (i % 100 == 0) { Now = SDL_GetTicks (); - fprintf(stderr, "%03ld(%04ld) ", 100*1000 / (Now - TimeIn), + log_add (log_Debug, "%03ld(%04ld) ", 100*1000 / (Now - TimeIn), Now - TimeIn); TimeIn = Now; } } - fprintf (stderr, "Full frames scaled: %d; over %ld ms; %ld fps\n", + log_add (log_Always, "Full frames scaled: %d; over %ld ms; %ld fps\n", (i - 1), Now - TimeStart, i * 1000 / (Now - TimeStart)); SDL_UnlockSurface (scaled_display); diff --git a/sc2/src/sc2code/libs/graphics/sdl/rndzoom.c b/sc2/src/sc2code/libs/graphics/sdl/rndzoom.c index 1b4c29210..f6261b2d1 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/rndzoom.c +++ b/sc2/src/sc2code/libs/graphics/sdl/rndzoom.c @@ -37,8 +37,6 @@ #define R0 0.8 #define RANDOM_METHOD 3 -#define RND_BLUR_PROFILE - #ifdef GFXMODULE_SDL #ifdef WIN32 @@ -48,10 +46,7 @@ #include "sdl_common.h" #include "primitives.h" - -#ifdef RND_BLUR_PROFILE -#include -#endif +#include "libs/log.h" #ifndef MAX #define MAX(x,y) ((x) < (y) ? (y) : (x)) @@ -81,9 +76,6 @@ void blurSurface32 (SDL_Surface *src) Uint32 *ptr; int y, x, yy, xx; Uint32 i, offset, ypos, yof; -#ifdef RND_BLUR_PROFILE - clock_t t1 = clock (); -#endif #if BLUR_TYPE == 1 #define MWID 3 #define ARRAY_SIZE 4 @@ -172,7 +164,7 @@ void blurSurface32 (SDL_Surface *src) if (src->format->BitsPerPixel != 32) { - fprintf(stderr, "blurSurface32 requires a 32bit Surface, but surface is %d bits!\n", + log_add (log_Debug, "blurSurface32 requires a 32bit Surface, but surface is %d bits!\n", src->format->BitsPerPixel); return; } @@ -256,9 +248,6 @@ void blurSurface32 (SDL_Surface *src) SDL_UnlockSurface (src); for(i = 0; i < ARRAY_SIZE; i++) HFree (blur_array[i]); -#ifdef RND_BLUR_PROFILE - fprintf(stderr, "Blur took %f seconds\n",(float)(clock() - t1) / CLOCKS_PER_SEC); -#endif } /* the rZF_nearestneighbor method fills the 'dst' image with the 'src' image @@ -520,10 +509,6 @@ void rZF_continuous (SDL_Surface *src, SDL_Surface *dst) /* perform a 16x zoom, and then apply a blur filter to the result */ void random16xZoomSurfaceRGBA (SDL_Surface *src, SDL_Surface *dst) { -#ifdef RND_BLUR_PROFILE - clock_t t1 = clock(); -#endif - /* * Alloc space to completely contain the zoomed surface */ @@ -543,9 +528,6 @@ void random16xZoomSurfaceRGBA (SDL_Surface *src, SDL_Surface *dst) SDL_UnlockSurface (src); SDL_UnlockSurface (dst); SDL_SetAlpha(dst, SDL_SRCALPHA, 255); -#ifdef RND_BLUR_PROFILE - fprintf(stderr, "Randomize took %f seconds\n",(float)(clock() - t1) / CLOCKS_PER_SEC); -#endif blurSurface32 (dst); } diff --git a/sc2/src/sc2code/libs/graphics/sdl/scalers.c b/sc2/src/sc2code/libs/graphics/sdl/scalers.c index 85d2f9fc6..2e4459fbf 100755 --- a/sc2/src/sc2code/libs/graphics/sdl/scalers.c +++ b/sc2/src/sc2code/libs/graphics/sdl/scalers.c @@ -19,6 +19,7 @@ #include "types.h" #include "libs/graphics/sdl/sdl_common.h" #include "libs/platform.h" +#include "libs/log.h" #include "scalers.h" #include "scaleint.h" #include "2xscalers.h" @@ -214,7 +215,7 @@ Scale_PrepPlatform (int flags, const SDL_PixelFormat* fmt) if ( (!force_platform && (SDL_HasSSE () || SDL_HasMMXExt ())) || force_platform == SCALEPLAT_SSE) { - fprintf (stderr, "Screen scalers are using SSE/MMX-Ext/MMX code\n"); + log_add (log_Always, "Screen scalers are using SSE/MMX-Ext/MMX code"); Scale_Platform = SCALEPLAT_SSE; Scale_SSE_PrepPlatform (fmt); @@ -223,15 +224,15 @@ Scale_PrepPlatform (int flags, const SDL_PixelFormat* fmt) if ( (!force_platform && SDL_HasAltiVec ()) || force_platform == SCALEPLAT_ALTIVEC) { - fprintf (stderr, "Screen scalers would use AltiVec code " - "if someone actually wrote it\n"); + log_add (log_Always, "Screen scalers would use AltiVec code " + "if someone actually wrote it"); //Scale_Platform = SCALEPLAT_ALTIVEC; } else if ( (!force_platform && SDL_Has3DNow ()) || force_platform == SCALEPLAT_3DNOW) { - fprintf (stderr, "Screen scalers are using 3DNow/MMX code\n"); + log_add (log_Always, "Screen scalers are using 3DNow/MMX code"); Scale_Platform = SCALEPLAT_3DNOW; Scale_3DNow_PrepPlatform (fmt); @@ -240,7 +241,7 @@ Scale_PrepPlatform (int flags, const SDL_PixelFormat* fmt) if ( (!force_platform && SDL_HasMMX ()) || force_platform == SCALEPLAT_MMX) { - fprintf (stderr, "Screen scalers are using MMX code\n"); + log_add (log_Always, "Screen scalers are using MMX code"); Scale_Platform = SCALEPLAT_MMX; Scale_MMX_PrepPlatform (fmt); @@ -259,15 +260,15 @@ Scale_PrepPlatform (int flags, const SDL_PixelFormat* fmt) Scale_Platform = SCALEPLAT_C_ABGR; else { // use slowest default - fprintf (stderr, "Scale_PrepPlatform(): " - "unknown Red mask (0x%08x)\n", fmt->Rmask); + log_add (log_Warning, "Scale_PrepPlatform(): " + "unknown Red mask (0x%08x)", fmt->Rmask); Scale_Platform = SCALEPLAT_C; } if (Scale_Platform == SCALEPLAT_C) - fprintf (stderr, "Screen scalers are using slow generic C code\n"); + log_add (log_Always, "Screen scalers are using slow generic C code"); else - fprintf (stderr, "Screen scalers are using optimized C code\n"); + log_add (log_Always, "Screen scalers are using optimized C code"); } // Lookup the scaling function diff --git a/sc2/src/sc2code/libs/graphics/sdl/sdl_common.c b/sc2/src/sc2code/libs/graphics/sdl/sdl_common.c index 92caf36a1..530b8d15c 100644 --- a/sc2/src/sc2code/libs/graphics/sdl/sdl_common.c +++ b/sc2/src/sc2code/libs/graphics/sdl/sdl_common.c @@ -30,6 +30,7 @@ #include "bbox.h" #include "port.h" #include "libs/uio.h" +#include "libs/log.h" #include "controls.h" // XXX: Should not be included from here. #include "uqmdebug.h" @@ -63,15 +64,15 @@ TFB_Abort (void) void TFB_PreInit (void) { - fprintf (stderr, "Initializing base SDL functionality.\n"); - fprintf (stderr, "Using SDL version %d.%d.%d (compiled with " - "%d.%d.%d)\n", SDL_Linked_Version ()->major, + log_add (log_Always, "Initializing base SDL functionality."); + log_add (log_Always, "Using SDL version %d.%d.%d (compiled with " + "%d.%d.%d)", SDL_Linked_Version ()->major, SDL_Linked_Version ()->minor, SDL_Linked_Version ()->patch, SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL); if ((SDL_Init (SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) == -1)) { - fprintf (stderr, "Could not initialize SDL: %s.\n", SDL_GetError()); - exit(-1); + log_add (log_Always, "Could not initialize SDL: %s.", SDL_GetError()); + exit (EXIT_FAILURE); } } @@ -89,8 +90,8 @@ TFB_ReInitGraphics (int driver, int flags, int width, int height) result = TFB_GL_ConfigureVideo (driver, flags, width, height); #else driver = TFB_GFXDRIVER_SDL_PURE; - fprintf (stderr, "OpenGL support not compiled in, so using pure " - "sdl driver\n"); + log_add (log_Always, "OpenGL support not compiled in," + " so using pure SDL driver"); result = TFB_Pure_ConfigureVideo (driver, flags, width, height); #endif } @@ -126,8 +127,8 @@ TFB_InitGraphics (int driver, int flags, int width, int height) result = TFB_GL_InitGraphics (driver, flags, width, height); #else driver = TFB_GFXDRIVER_SDL_PURE; - fprintf (stderr, "OpenGL support not compiled in, so using pure " - "sdl driver\n"); + log_add (log_Always, "OpenGL support not compiled in," + " so using pure SDL driver"); result = TFB_Pure_InitGraphics (driver, flags, width, height); #endif } @@ -178,7 +179,8 @@ TFB_ProcessEvents () // TODO break; case SDL_QUIT: - exit (0); + log_showBox (false, false); + exit (EXIT_SUCCESS); break; case SDL_VIDEORESIZE: /* User resized video mode */ // TODO @@ -191,7 +193,10 @@ TFB_ProcessEvents () } } if (ImmediateInputState.menu[KEY_ABORT] || abortFlag) - exit (0); + { + log_showBox (false, false); + exit (EXIT_SUCCESS); + } #if defined(DEBUG) || defined(USE_DEBUG_KEY) if (ImmediateInputState.menu[KEY_DEBUG]) { @@ -262,7 +267,7 @@ void TFB_BlitSurface (SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, { // normal blit: dst = src - // fprintf(stderr, "normal blit\n"); + // log_add (log_Debug, "normal blit\n"); SDL_BlitSurface (src, srcrect, dst, dstrect); return; } @@ -369,9 +374,11 @@ void TFB_BlitSurface (SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, if (blend_denom < 0) { // additive blit: dst = src + dst - - // fprintf(stderr, "additive blit %d %d, src %d %d %d %d dst %d %d, srcbpp %d\n",blend_numer, blend_denom, x1, y1, x2, y2, dstrect->x, dstrect->y, src->format->BitsPerPixel); - +#if 0 + log_add (log_Debug, "additive blit %d %d, src %d %d %d %d dst %d %d," + " srcbpp %d", blend_numer, blend_denom, x1, y1, x2, y2, + dstrect->x, dstrect->y, src->format->BitsPerPixel); +#endif for (y = y1; y < y2; ++y) { dst_y2 = dstrect->y + (y - y1); @@ -407,9 +414,12 @@ void TFB_BlitSurface (SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, else if (blend_numer < 0) { // subtractive blit: dst = src - dst - - // fprintf(stderr, "subtractive blit %d %d, src %d %d %d %d dst %d %d, srcbpp %d\n",blend_numer, blend_denom, x1, y1, x2, y2, dstrect->x, dstrect->y, src->format->BitsPerPixel); - +#if 0 + log_add (log_Debug, "subtractive blit %d %d, src %d %d %d %d" + " dst %d %d, srcbpp %d", blend_numer, blend_denom, + x1, y1, x2, y2, dstrect->x, dstrect->y, + src->format->BitsPerPixel); +#endif for (y = y1; y < y2; ++y) { dst_y2 = dstrect->y + (y - y1); @@ -447,9 +457,12 @@ void TFB_BlitSurface (SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, // modulated blit: dst = src * (blend_numer / blend_denom) float f = blend_numer / (float)blend_denom; - - // fprintf(stderr, "modulated blit %d %d, f %f, src %d %d %d %d dst %d %d, srcbpp %d\n",blend_numer, blend_denom, f, x1, y1, x2, y2, dstrect->x, dstrect->y, src->format->BitsPerPixel); - +#if 0 + log_add (log_Debug, "modulated blit %d %d, f %f, src %d %d %d %d" + " dst %d %d, srcbpp %d\n", blend_numer, blend_denom, f, + x1, y1, x2, y2, dstrect->x, dstrect->y, + src->format->BitsPerPixel); +#endif for (y = y1; y < y2; ++y) { dst_y2 = dstrect->y + (y - y1); @@ -494,7 +507,7 @@ TFB_ComputeFPS (void) fps_counter += delta_time; if (fps_counter > FPS_PERIOD) { - fprintf (stderr, "fps %.2f, effective %.2f\n", + log_add (log_Always, "fps %.2f, effective %.2f", 1000.0 / delta_time, 1000.0 * RenderedFrames / fps_counter); @@ -573,7 +586,7 @@ TFB_FlushGraphics () // Only call from main thread!! if (!livelock_deterrence && commands_handled + DrawCommandQueue.Size > DCQ_LIVELOCK_MAX) { - // fprintf (stderr, "Initiating livelock deterrence!\n"); + // log_add (log_Debug, "Initiating livelock deterrence!"); livelock_deterrence = TRUE; Lock_DCQ (-1); @@ -586,7 +599,7 @@ TFB_FlushGraphics () // Only call from main thread!! int index = DC.data.setpalette.index; if (index < 0 || index > 255) { - fprintf(stderr, "DCQ panic: Tried to set palette #%i", + log_add (log_Debug, "DCQ panic: Tried to set palette #%i", index); } else @@ -731,8 +744,8 @@ TFB_FlushGraphics () // Only call from main thread!! if (DC_image == 0) { - fprintf (stderr, "DCQ ERROR: COPYTOIMAGE passed null " - "image ptr\n"); + log_add (log_Debug, "DCQ ERROR: COPYTOIMAGE passed null " + "image ptr"); break; } LockMutex (DC_image->mutex); @@ -788,12 +801,14 @@ TFB_FlushGraphics () // Only call from main thread!! if (TFB_ReInitGraphics (DC.data.reinitvideo.driver, DC.data.reinitvideo.flags, DC.data.reinitvideo.width, DC.data.reinitvideo.height)) { - fprintf (stderr, "Could not provide requested mode: reverting to last known driver.\n"); + log_add (log_Always, "Could not provide requested mode: " + "reverting to last known driver."); if (TFB_ReInitGraphics (oldDriver, DC.data.reinitvideo.flags, DC.data.reinitvideo.width, DC.data.reinitvideo.height)) { - fprintf (stderr, "Couldn't reinit at that point either. Your video has been somehow tied in knots.\n"); - exit (-1); + log_add (log_Always, "Couldn't reinit at that point either." + " Your video has been somehow tied in knots."); + exit (EXIT_FAILURE); } } break; @@ -816,11 +831,11 @@ TFB_SetGamma (float gamma) { if (SDL_SetGamma (gamma, gamma, gamma) == -1) { - fprintf (stderr, "Unable to set gamma correction.\n"); + log_add (log_Warning, "Unable to set gamma correction."); } else { - fprintf (stderr, "Gamma correction set to %1.4f.\n", gamma); + log_add (log_Info, "Gamma correction set to %1.4f.", gamma); } } diff --git a/sc2/src/sc2code/libs/graphics/tfb_draw.c b/sc2/src/sc2code/libs/graphics/tfb_draw.c index dd6581c7c..234d39e25 100644 --- a/sc2/src/sc2code/libs/graphics/tfb_draw.c +++ b/sc2/src/sc2code/libs/graphics/tfb_draw.c @@ -18,6 +18,7 @@ #include "tfb_draw.h" #include "drawcmd.h" #include "units.h" +#include "libs/log.h" static const HOT_SPOT NullHs = {0, 0}; @@ -340,8 +341,8 @@ TFB_DrawImage_New_Rotated (TFB_Image *img, int angle) /* sanity check */ if (!img->NormalImg) { - fprintf (stderr, "TFB_DrawImage_New_Rotated: " - "source canvas is NULL! Failing.\n"); + log_add (log_Warning, "TFB_DrawImage_New_Rotated: " + "source canvas is NULL! Failing."); return NULL; } @@ -349,8 +350,8 @@ TFB_DrawImage_New_Rotated (TFB_Image *img, int angle) dst = TFB_DrawCanvas_New_RotationTarget (img->NormalImg, angle); if (!dst) { - fprintf (stderr, "TFB_DrawImage_New_Rotated: " - "rotation target canvas not created! Failing.\n"); + log_add (log_Warning, "TFB_DrawImage_New_Rotated: " + "rotation target canvas not created! Failing."); return NULL; } TFB_DrawCanvas_Rotate (img->NormalImg, dst, angle, size); @@ -364,7 +365,7 @@ TFB_DrawImage_Delete (TFB_Image *image) { if (image == 0) { - fprintf (stderr, "INTERNAL ERROR: Tried to delete a null image!\n"); + log_add (log_Warning, "INTERNAL ERROR: Tried to delete a null image!"); /* Should we die here? */ return; } diff --git a/sc2/src/sc2code/libs/graphics/tfb_prim.c b/sc2/src/sc2code/libs/graphics/tfb_prim.c index f1a0d33e5..d65714434 100644 --- a/sc2/src/sc2code/libs/graphics/tfb_prim.c +++ b/sc2/src/sc2code/libs/graphics/tfb_prim.c @@ -26,6 +26,7 @@ #include "tfb_draw.h" #include "tfb_prim.h" #include "cmap.h" +#include "libs/log.h" void TFB_Prim_Point (PPOINT p, TFB_Palette *color) @@ -125,7 +126,8 @@ TFB_Prim_Stamp (PSTAMP stmp) SrcFramePtr = (PFRAME_DESC)stmp->frame; if (!SrcFramePtr) { - fprintf (stderr, "TFB_Prim_Stamp: Tried to draw a NULL frame (Stamp address = %p)\n", stmp); + log_add (log_Warning, "TFB_Prim_Stamp: Tried to draw a NULL frame" + " (Stamp address = %p)", stmp); return; } img = SrcFramePtr->image; @@ -133,7 +135,7 @@ TFB_Prim_Stamp (PSTAMP stmp) if (!img) { - fprintf (stderr, "Non-existent image to TFB_Prim_Stamp()\n"); + log_add (log_Warning, "Non-existent image to TFB_Prim_Stamp()"); return; } @@ -173,7 +175,8 @@ TFB_Prim_StampFill (PSTAMP stmp, TFB_Palette *color) SrcFramePtr = (PFRAME_DESC)stmp->frame; if (!SrcFramePtr) { - fprintf (stderr, "TFB_Prim_StampFill: Tried to draw a NULL frame (Stamp address = %p)\n", stmp); + log_add (log_Warning, "TFB_Prim_StampFill: Tried to draw a NULL frame" + " (Stamp address = %p)", stmp); return; } img = SrcFramePtr->image; @@ -181,7 +184,7 @@ TFB_Prim_StampFill (PSTAMP stmp, TFB_Palette *color) if (!img) { - fprintf (stderr, "Non-existent image to TFB_Prim_StampFill()\n"); + log_add (log_Warning, "Non-existent image to TFB_Prim_StampFill()"); return; } diff --git a/sc2/src/sc2code/libs/input/sdl/input.c b/sc2/src/sc2code/libs/input/sdl/input.c index ceb3f060d..a366374d5 100644 --- a/sc2/src/sc2code/libs/input/sdl/input.c +++ b/sc2/src/sc2code/libs/input/sdl/input.c @@ -25,6 +25,7 @@ #include "libs/input/sdl/vcontrol.h" #include "controls.h" #include "libs/file.h" +#include "libs/log.h" #include "options.h" @@ -109,7 +110,8 @@ static VControl_NameBinding control_names[] = { static void -initKeyConfig(void) { +initKeyConfig (void) +{ uio_Stream *fp; int i, errors; @@ -120,16 +122,16 @@ initKeyConfig(void) { if (copyFile (contentDir, "starcon.key", configDir, "keys.cfg") == -1) { - fprintf (stderr, "Error: Could not copy default key config " - "to user config dir: %s.\n", strerror (errno)); + log_add (log_Always, "Error: Could not copy default key config " + "to user config dir: %s.", strerror (errno)); exit (EXIT_FAILURE); } - fprintf(stderr, "Copying default key config file to user " - "config dir.\n"); + log_add (log_Info, "Copying default key config file to user " + "config dir."); if ((fp = res_OpenResFile (configDir, "keys.cfg", "rt")) == NULL) { - fprintf (stderr, "Error: Could not open keys.cfg\n"); + log_add (log_Always, "Error: Could not open keys.cfg"); exit (EXIT_FAILURE); } } @@ -141,45 +143,45 @@ initKeyConfig(void) { { bool do_rename = false; if (errors) - fprintf (stderr, "%d errors encountered in key configuration file.\n", errors); + log_add (log_Warning, "%d errors encountered in key configuration file.", errors); if (VControl_GetValidCount () == 0) { - fprintf (stderr, "\nI didn't understand a single line in your configuration file.\n"); - fprintf (stderr, "This is likely because you're still using a 0.2 era or earlier keys.cfg.\n"); + log_add (log_Always, "\nI didn't understand a single line in your configuration file."); + log_add (log_Always, "This is likely because you're still using a 0.2 era or earlier keys.cfg."); do_rename = true; } if (VControl_GetConfigFileVersion () != VCONTROL_VERSION) { - fprintf (stderr, "\nThe control scheme for UQM has changed since you last updated keys.cfg.\n"); - fprintf (stderr, "(I'm using control scheme version %d, while your config file appears to be\nfor version %d.)\n", VCONTROL_VERSION, VControl_GetConfigFileVersion ()); + log_add (log_Always, "\nThe control scheme for UQM has changed since you last updated keys.cfg."); + log_add (log_Always, "(I'm using control scheme version %d, while your config file appears to be\nfor version %d.)", VCONTROL_VERSION, VControl_GetConfigFileVersion ()); do_rename = true; } if (do_rename) { - fprintf (stderr, "\nRenaming keys.cfg to keys.old and retrying.\n"); + log_add (log_Always, "\nRenaming keys.cfg to keys.old and retrying."); if (fileExists2 (configDir, "keys.old")) uio_unlink (configDir, "keys.old"); if ((uio_rename (configDir, "keys.cfg", configDir, "keys.old")) == -1) { - fprintf (stderr, "Error: Renaming failed!\n"); - fprintf (stderr, "You must delete keys.cfg manually before you can run the game.\n"); + log_add (log_Always, "Error: Renaming failed!"); + log_add (log_Always, "You must delete keys.cfg manually before you can run the game."); exit (EXIT_FAILURE); } continue; } - fprintf (stderr, "\nRepair your keys.cfg file to continue.\n"); + log_add (log_Always, "\nRepair your keys.cfg file to continue."); exit (EXIT_FAILURE); } return; } - fprintf (stderr, "Error: Something went wrong and we were looping again and again so aborting.\n"); - fprintf (stderr, "Possible cause is your content dir not being up-to-date.\n"); + log_add (log_Always, "Error: Something went wrong and we were looping again and again so aborting."); + log_add (log_Always, "Possible cause is your content dir not being up-to-date."); exit (EXIT_FAILURE); } @@ -204,19 +206,20 @@ TFB_InitInput (int driver, int flags) if ((SDL_InitSubSystem(SDL_INIT_JOYSTICK)) == -1) { - fprintf (stderr, "Couldn't initialize joystick subsystem: %s\n", SDL_GetError()); - exit(-1); + log_add (log_Always, "Couldn't initialize joystick subsystem: %s", + SDL_GetError()); + exit (EXIT_FAILURE); } - fprintf (stderr, "%i joysticks were found.\n", SDL_NumJoysticks ()); + log_add (log_Info, "%i joysticks were found.", SDL_NumJoysticks ()); nJoysticks = SDL_NumJoysticks (); if (nJoysticks > 0) { - fprintf (stderr, "The names of the joysticks are:\n"); - for(i = 0; i < nJoysticks; i++) + log_add (log_Info, "The names of the joysticks are:"); + for (i = 0; i < nJoysticks; i++) { - fprintf (stderr, " %s\n", SDL_JoystickName (i)); + log_add (log_Info, " %s", SDL_JoystickName (i)); } SDL_JoystickEventState (SDL_ENABLE); } diff --git a/sc2/src/sc2code/libs/input/sdl/vcontrol.c b/sc2/src/sc2code/libs/input/sdl/vcontrol.c index 2c288784a..eb137c2f8 100644 --- a/sc2/src/sc2code/libs/input/sdl/vcontrol.c +++ b/sc2/src/sc2code/libs/input/sdl/vcontrol.c @@ -6,6 +6,7 @@ #include "vcontrol.h" #include "vcontrol_malloc.h" #include "keynames.h" +#include "libs/log.h" /* How many binding slots are allocated at once. */ #define POOL_CHUNK_SIZE 64 @@ -97,7 +98,7 @@ create_joystick (int index) int axes, buttons, hats; if (index >= joycount) { - fprintf (stderr, "VControl warning: Tried to open a non-existent joystick!"); + log_add (log_Warning, "VControl warning: Tried to open a non-existent joystick!"); return; } if (joysticks[index].stick) @@ -110,11 +111,11 @@ create_joystick (int index) { joystick *x = &joysticks[index]; int j; - fprintf (stderr, "VControl opened joystick: %s\n", SDL_JoystickName (index)); + log_add (log_Info, "VControl opened joystick: %s", SDL_JoystickName (index)); axes = SDL_JoystickNumAxes (stick); buttons = SDL_JoystickNumButtons (stick); hats = SDL_JoystickNumHats (stick); - fprintf (stderr, "%d axes, %d buttons, %d hats.\n", axes, buttons, hats); + log_add (log_Info, "%d axes, %d buttons, %d hats.", axes, buttons, hats); x->numaxes = axes; x->numbuttons = buttons; x->numhats = hats; @@ -139,7 +140,7 @@ create_joystick (int index) } else { - fprintf (stderr, "VControl: Could not initialize joystick #%d\n", index); + log_add (log_Warning, "VControl: Could not initialize joystick #%d", index); } } @@ -238,7 +239,7 @@ VControl_SetJoyThreshold (int port, int threshold) } else { - // fprintf (stderr, "VControl_SetJoyThreshold passed illegal port %d\n", port); + // log_add (log_Warning, "VControl_SetJoyThreshold passed illegal port %d", port); return -1; } } @@ -293,7 +294,7 @@ add_binding (keybinding **newptr, int *target) /* Sanity check. */ if (!newbinding) { - fprintf (stderr, "add_binding failed to find a free binding slot!\n"); + log_add (log_Warning, "add_binding failed to find a free binding slot!"); return; } @@ -378,7 +379,7 @@ VControl_AddBinding (SDL_Event *e, int *target) result = VControl_AddJoyButtonBinding (e->jbutton.which, e->jbutton.button, target); break; default: - fprintf (stderr, "VControl_AddBinding didn't understand argument event\n"); + log_add (log_Warning, "VControl_AddBinding didn't understand argument event"); result = -1; break; } @@ -403,7 +404,7 @@ VControl_RemoveBinding (SDL_Event *e, int *target) VControl_RemoveJoyButtonBinding (e->jbutton.which, e->jbutton.button, target); break; default: - fprintf (stderr, "VControl_RemoveBinding didn't understand argument event\n"); + log_add (log_Warning, "VControl_RemoveBinding didn't understand argument event"); break; } } @@ -412,7 +413,7 @@ int VControl_AddKeyBinding (SDLKey symbol, int *target) { if ((symbol < 0) || (symbol >= SDLK_LAST)) { - fprintf (stderr, "VControl: Illegal key index %d\n", symbol); + log_add (log_Warning, "VControl: Illegal key index %d", symbol); return -1; } add_binding(&bindings[symbol], target); @@ -423,7 +424,7 @@ void VControl_RemoveKeyBinding (SDLKey symbol, int *target) { if ((symbol < 0) || (symbol >= SDLK_LAST)) { - fprintf (stderr, "VControl: Illegal key index %d\n", symbol); + log_add (log_Warning, "VControl: Illegal key index %d", symbol); return; } remove_binding (&bindings[symbol], target); @@ -449,19 +450,19 @@ VControl_AddJoyAxisBinding (int port, int axis, int polarity, int *target) } else { - // fprintf (stderr, "VControl: Attempted to bind to polarity zero\n"); + log_add (log_Debug, "VControl: Attempted to bind to polarity zero"); return -1; } } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal axis %d\n", axis); + // log_add (log_Debug, "VControl: Attempted to bind to illegal axis %d", axis); return -1; } } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal port %d\n", port); + // log_add (log_Debug, "VControl: Attempted to bind to illegal port %d", port); return -1; } return 0; @@ -487,17 +488,17 @@ VControl_RemoveJoyAxisBinding (int port, int axis, int polarity, int *target) } else { - fprintf (stderr, "VControl: Attempted to unbind from polarity zero\n"); + log_add (log_Debug, "VControl: Attempted to unbind from polarity zero"); } } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal axis %d\n", axis); + log_add (log_Debug, "VControl: Attempted to unbind from illegal axis %d", axis); } } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal port %d\n", port); + log_add (log_Debug, "VControl: Attempted to unbind from illegal port %d", port); } } @@ -516,13 +517,13 @@ VControl_AddJoyButtonBinding (int port, int button, int *target) } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal button %d\n", button); + // log_add (log_Debug, "VControl: Attempted to bind to illegal button %d", button); return -1; } } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal port %d\n", port); + // log_add (log_Debug, "VControl: Attempted to bind to illegal port %d", port); return -1; } } @@ -541,12 +542,12 @@ VControl_RemoveJoyButtonBinding (int port, int button, int *target) } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal button %d\n", button); + log_add (log_Debug, "VControl: Attempted to unbind from illegal button %d", button); } } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal port %d\n", port); + log_add (log_Debug, "VControl: Attempted to unbind from illegal port %d", port); } } @@ -578,20 +579,20 @@ VControl_AddJoyHatBinding (int port, int which, Uint8 dir, int *target) } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal direction\n"); + // log_add (log_Debug, "VControl: Attempted to bind to illegal direction"); return -1; } return 0; } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal hat %d\n", which); + // log_add (log_Debug, "VControl: Attempted to bind to illegal hat %d", which); return -1; } } else { - // fprintf (stderr, "VControl: Attempted to bind to illegal port %d\n", port); + // log_add (log_Debug, "VControl: Attempted to bind to illegal port %d", port); return -1; } } @@ -624,17 +625,17 @@ VControl_RemoveJoyHatBinding (int port, int which, Uint8 dir, int *target) } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal direction\n"); + log_add (log_Debug, "VControl: Attempted to unbind from illegal direction"); } } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal hat %d\n", which); + log_add (log_Debug, "VControl: Attempted to unbind from illegal hat %d", which); } } else { - fprintf (stderr, "VControl: Attempted to unbind from illegal port %d\n", port); + log_add (log_Debug, "VControl: Attempted to unbind from illegal port %d", port); } } @@ -1213,7 +1214,8 @@ next_line (parse_state *state, uio_Stream *in) static void expected_error (parse_state *state, char *expected) { - fprintf (stderr, "VControl: Expected '%s' on config file line %d\n", expected, state->linenum); + log_add (log_Warning, "VControl: Expected '%s' on config file line %d", + expected, state->linenum); state->error = 1; } @@ -1233,7 +1235,8 @@ consume_keyname (parse_state *state) int keysym = VControl_name2code (state->token); if (!keysym) { - fprintf (stderr, "VControl: Illegal key name '%s' on config file line %d\n", state->token, state->linenum); + log_add (log_Warning, "VControl: Illegal key name '%s' on config file line %d", + state->token, state->linenum); state->error = 1; } next_token (state); @@ -1252,7 +1255,8 @@ consume_idname (parse_state *state) if (index == 0) { - fprintf (stderr, "VControl: Can't happen: blank token to consume_idname (line %d)\n", state->linenum); + log_add (log_Debug, "VControl: Can't happen: blank token to consume_idname (line %d)", + state->linenum); state->error = 1; return NULL; } @@ -1270,7 +1274,8 @@ consume_idname (parse_state *state) if (!result) { - fprintf (stderr, "VControl: Illegal command type '%s' on config file line %d\n", state->token, state->linenum); + log_add (log_Warning, "VControl: Illegal command type '%s' on config file line %d", + state->token, state->linenum); state->error = 1; } next_token (state); @@ -1284,7 +1289,8 @@ consume_num (parse_state *state) int result = strtol (state->token, &end, 10); if (*end != '\0') { - fprintf (stderr, "VControl: Expected integer on config line %d\n", state->linenum); + log_add (log_Warning, "VControl: Expected integer on config line %d", + state->linenum); state->error = 1; } next_token (state); @@ -1490,7 +1496,7 @@ VControl_ReadConfiguration (uio_Stream *in) parse_state ps; if (!in) { - fprintf (stderr, "VControl: Invalid configuration file stream\n"); + log_add (log_Warning, "VControl: Invalid configuration file stream"); return 1; } ps.linenum = 0; @@ -1542,7 +1548,7 @@ VControl_TokenizeFile (FILE *in) parse_state ps; if (!in) { - fprintf (stderr, "VControl: Invalid configuration file stream\n"); + log_add (log_Warning, "VControl: Invalid configuration file stream"); return; } ps.linenum = 0; diff --git a/sc2/src/sc2code/libs/memory/w_memlib.c b/sc2/src/sc2code/libs/memory/w_memlib.c index 4dc04b395..07da023d5 100644 --- a/sc2/src/sc2code/libs/memory/w_memlib.c +++ b/sc2/src/sc2code/libs/memory/w_memlib.c @@ -27,6 +27,7 @@ #include "compiler.h" #include "libs/threadlib.h" #include "libs/memlib.h" +#include "libs/log.h" #define GetToolFrame() 1 @@ -64,55 +65,6 @@ typedef struct _szMemoryNode { static szMemoryNode extents[MAX_EXTENTS]; static szMemoryNode *freeListHead = NULL; -/*****************************************************************************/ -/*FUNCTION -** -** SYNOPSIS -** Message(format, parms) -** -** DESCRIPTION -** Presents a windows message box to the user and echoes the -** message with printf(). -** -** INPUT -** As for printf(). -** -** OUTPUT -** -** HISTORY -** 10-Jul-96:AKL Creation. -** -** ASSUMPTIONS -**END*/ - -static void Message(char *fmt, ...) -{ - va_list ap; - char buffer[256]; - - - va_start(ap, fmt); - vsprintf(buffer, fmt, ap); - va_end(ap); - -#ifndef FINAL - fprintf (stderr, "%s\n", buffer); - //fflush (stderr); -#endif - -#if 0 - if (GetToolFrame ()) - { - ShowWindow(GetToolFrame (),SW_HIDE); - } - MessageBox(NULL, buffer, "Message From Programmer Dude", MB_OK); - - if (GetToolFrame ()) - { - ShowWindow(GetToolFrame (),SW_NORMAL); - } -#endif -} #if 0 /*****************************************************************************/ @@ -151,10 +103,8 @@ static int MessageWithRetry(char *fmt, ...) vsprintf(buffer, fmt, ap); va_end(ap); -#ifndef FINAL - fprintf (stderr, "%s\n", buffer); + log_add (log_Always, "%s", buffer); // fflush(stderr); -#endif #if 0 if (GetToolFrame ()) @@ -258,12 +208,10 @@ MallocWithRetry(int bytes, char *diagStr) ptr = malloc (bytes); if (ptr) return (ptr); -#ifndef FINAL - fprintf (stderr, "Malloc failed for %s. #Bytes %d.\n", diagStr, bytes); -// fflush (stderr); -#endif - abort(); + log_add (log_Always, "Malloc failed for %s. #Bytes %d.", diagStr, bytes); + fflush (stderr); + abort (); #if 0 /* The user gets a chance to close other applications and try again. */ if (!MessageWithRetry ("I'm out of memory! " @@ -272,8 +220,9 @@ MallocWithRetry(int bytes, char *diagStr) if (MessageWithRetry ("Really OK to stop tfbtool?")) { /* User says "die". */ - fprintf (stderr, "Killed by the user (%s).\n", diagStr); - exit (0); + log_add (log_Always, "Killed by the user (%s).", diagStr); + log_showBox (false, false); + exit (EXIT_SUCCESS); } } #endif @@ -293,10 +242,11 @@ mem_allocate (MEM_SIZE coreSize, MEM_FLAGS flags, MEM_PRIORITY priority, #endif if ((node = freeListHead) == NULL) - Message ("mem_allocate: out of extents."); + log_add (log_Always, "mem_allocate: out of extents."); else if ((node->memory = MallocWithRetry (coreSize, "mem_allocate:")) == 0 && coreSize) - Message ("mem_allocate: couldn't allocate %u bytes.", coreSize); + log_add (log_Always, "mem_allocate: couldn't allocate %u bytes.", + coreSize); else { freeListHead = node->next; @@ -309,10 +259,10 @@ mem_allocate (MEM_SIZE coreSize, MEM_FLAGS flags, MEM_PRIORITY priority, #ifdef LEAK_DEBUG if (leak_debug) { - fprintf (stderr, "alloc %d: %p, %lu\n", (int) node->handle, + log_add (log_Debug, "alloc %d: %p, %lu", (int) node->handle, (void *) node->memory, node->size); // Prefered form: - //fprintf (stderr, "alloc %d: %#8" PRIxPTR ", %lu\n", + //log_add (log_Debug, "alloc %d: %#8" PRIxPTR ", %lu", // (int) node->handle, (intptr_t) node->memory, node->size); } if (node->handle == leak_idx && node->size == leak_size) @@ -445,12 +395,12 @@ mem_uninit(void) { if (extents[i].handle != -1) { - fprintf (stderr, "LEAK: unreleased extent %d: %p, %lu\n", + log_add (log_Debug, "LEAK: unreleased extent %d: %p, %lu", extents[i].handle, (void *) extents[i].memory, extents[i].size); // Prefered form: - //fprintf (stderr, "LEAK: unreleased extent %d: %#8" PRIxPTR - // ", %lu\n", extents[i].handle, + //log_add (log_Debug, "LEAK: unreleased extent %d: %#8" PRIxPTR + // ", %lu", extents[i].handle, // (intptr_t) extents[i].memory, extents[i].size); fflush (stderr); extents[i].handle = -1; @@ -501,18 +451,18 @@ mem_release(MEM_HANDLE h) --h; if (h < 0 || h >= MAX_EXTENTS) - fprintf (stderr, "LEAK: attempt to release invalid extent %d\n", h); + log_add (log_Debug, "LEAK: attempt to release invalid extent %d", h); else if (extents[h].handle == -1) - fprintf (stderr, "LEAK: attempt to release unallocated extent %d\n",h); + log_add (log_Debug, "LEAK: attempt to release unallocated extent %d",h); else if (extents[h].refcount == 0) { #ifdef LEAK_DEBUG if (leak_debug) { - fprintf (stderr, "free %d: %p\n", + log_add (log_Debug, "free %d: %p", extents[h].handle, (void *) extents[h].memory); // Prefered form: - //fprintf (stderr, "free %d: %#8" PRIxPTR "\n", + //log_add (log_Debug, "free %d: %#8" PRIxPTR, // extents[h].handle, (intptr_t) extents[h].memory); } #endif @@ -635,12 +585,9 @@ HMalloc (int size) if (size == 0) return (0); if ((p = _alloc_mem(size)) == NULL) { - fprintf(stderr, "Fatal Error: HMalloc(): out of memory.\n"); -#ifdef DEBUG - abort(); -#else - exit(1); -#endif /* #ifdef DEBUG */ + log_add (log_Always, "Fatal Error: HMalloc(): out of memory."); + fflush (stderr); + abort (); } return (p); } diff --git a/sc2/src/sc2code/libs/resource/alist.c b/sc2/src/sc2code/libs/resource/alist.c index 57a703216..606f51bfb 100644 --- a/sc2/src/sc2code/libs/resource/alist.c +++ b/sc2/src/sc2code/libs/resource/alist.c @@ -20,6 +20,7 @@ #include #include #include "libs/reslib.h" +#include "libs/log.h" #include "alist.h" alist_entry * @@ -161,12 +162,12 @@ Alist_New_FromString (char *d) while ((i < len) && (d[i] != '=') && (d[i] != '\n') && (d[i] != '#')) i++; if (i >= len) { /* Bare key at EOF */ - fprintf (stderr, "Warning: Bare keyword at EOF\n"); + log_add (log_Warning, "Warning: Bare keyword at EOF"); break; } /* Comments here mean incomplete line too */ if (d[i] != '=') { - fprintf (stderr, "Warning: Key without value\n"); + log_add (log_Warning, "Warning: Key without value"); while ((i < len) && (d[i] != '\n')) i++; if (i >= len) break; continue; /* Back to keyword search */ diff --git a/sc2/src/sc2code/libs/resource/getres.c b/sc2/src/sc2code/libs/resource/getres.c index 60d9acfd9..b4b0ee5c9 100644 --- a/sc2/src/sc2code/libs/resource/getres.c +++ b/sc2/src/sc2code/libs/resource/getres.c @@ -20,6 +20,7 @@ #include "port.h" #include "resintrn.h" #include "libs/misc.h" +#include "libs/log.h" const char *_cur_resfile_name; @@ -75,8 +76,8 @@ loadResourceDesc (ResourceIndex *idx, ResourceDesc *desc) if (resType >= idx->typeInfo.numTypes || idx->typeInfo.handlers[resType].loadFun == NULL) { - fprintf (stderr, "Warning: Unable to load '%s'; no handler " - "for type %d defined.\n", desc->path, resType); + log_add (log_Warning, "Warning: Unable to load '%s'; no handler " + "for type %d defined.", desc->path, resType); return NULL_HANDLE; } @@ -95,19 +96,16 @@ loadResource(const char *path, ResourceLoadFun *loadFun) stream = res_OpenResFile (contentDir, path, "rb"); if (stream == NULL) { - fprintf (stderr, "Warning: Can't open '%s'\n", path); + log_add (log_Warning, "Warning: Can't open '%s'", path); return NULL_HANDLE; } dataLen = LengthResFile (stream); -//#ifdef DEBUG -#if 1 - fprintf (stderr, "\t'%s' -- %lu bytes\n", path, dataLen); -#endif + log_add (log_Info, "\t'%s' -- %lu bytes", path, dataLen); if (dataLen == 0) { - fprintf (stderr, "Warning: Trying to load empty file '%s'.\n", path); + log_add (log_Warning, "Warning: Trying to load empty file '%s'.", path); goto err; } @@ -140,7 +138,7 @@ res_GetResource (RESOURCE res) desc = lookupResourceDesc (resourceIndex, res); if (desc == NULL) { - fprintf (stderr, "Trying to get undefined resource %08lx\n", + log_add (log_Warning, "Trying to get undefined resource %08lx", (DWORD) res); return NULL_HANDLE; } @@ -166,19 +164,15 @@ res_FreeResource (RESOURCE res) desc = lookupResourceDesc (_get_current_index_header(), res); if (desc == NULL) { -#ifdef DEBUG - fprintf (stderr, "Warning: trying to free an unrecognised " - "resource.\n"); -#endif + log_add (log_Debug, "Warning: trying to free an unrecognised " + "resource."); return; } if (desc->handle == NULL_HANDLE) { -#ifdef DEBUG - fprintf (stderr, "Warning: trying to free not loaded " - "resource.\n"); -#endif + log_add (log_Debug, "Warning: trying to free not loaded " + "resource."); return; } @@ -201,19 +195,15 @@ res_DetachResource (RESOURCE res) desc = lookupResourceDesc (_get_current_index_header(), res); if (desc == NULL) { -#ifdef DEBUG - fprintf (stderr, "Warning: trying to detach from an unrecognised " - "resource.\n"); -#endif + log_add (log_Debug, "Warning: trying to detach from an unrecognised " + "resource."); return NULL_HANDLE; } if (desc->handle == NULL_HANDLE) { -#ifdef DEBUG - fprintf (stderr, "Warning: trying to detach from a not loaded " - "resource.\n"); -#endif + log_add (log_Debug, "Warning: trying to detach from a not loaded " + "resource."); return NULL_HANDLE; } diff --git a/sc2/src/sc2code/libs/resource/resinit.c b/sc2/src/sc2code/libs/resource/resinit.c index 847458583..29280944b 100644 --- a/sc2/src/sc2code/libs/resource/resinit.c +++ b/sc2/src/sc2code/libs/resource/resinit.c @@ -21,6 +21,7 @@ #include "options.h" #include "types.h" #include "libs/list.h" +#include "libs/log.h" #include #include @@ -165,7 +166,7 @@ loadResourceIndex (uio_Stream *stream, const char *fileName) { if (sscanf (ptr, "%i %i %i %n", &resPackage, &resInstance, &resType, &numParsed) != 3) { - fprintf (stderr, "Resource index '%s': Invalid line %d.\n", + log_add (log_Warning, "Resource index '%s': Invalid line %d.", fileName, lineNum); continue; } @@ -179,7 +180,7 @@ loadResourceIndex (uio_Stream *stream, const char *fileName) { if (*path == '\0') { // No path supplied. - fprintf (stderr, "Resource index '%s': Invalid line %d.\n", + log_add (log_Warning, "Resource index '%s': Invalid line %d.", fileName, lineNum); continue; } @@ -188,9 +189,9 @@ loadResourceIndex (uio_Stream *stream, const char *fileName) { // We need the list to be sorted, as we binary search through it. if (res <= lastResource) { - fprintf (stderr, "Fatal: resource index '%s' is not sorted " + log_add (log_Always, "Fatal: resource index '%s' is not sorted " "on the resource number, or contains a double entry. " - "Problem encountered on line %d.\n", fileName, lineNum); + "Problem encountered on line %d.", fileName, lineNum); abort (); } lastResource = res; @@ -231,11 +232,9 @@ loadResourceIndex (uio_Stream *stream, const char *fileName) { descs = newDescs; } -#ifdef DEBUG if (numRes == 0) - fprintf (stderr, "Warning: Resource index '%s' contains no valid " - "entries.\n", fileName); -#endif + log_add (log_Debug, "Warning: Resource index '%s' contains no valid " + "entries.", fileName); indexHandle = allocResourceIndex (); if (indexHandle == NULL_HANDLE) diff --git a/sc2/src/sc2code/libs/sound/audiocore.c b/sc2/src/sc2code/libs/sound/audiocore.c index f73c91dab..28ba11d37 100644 --- a/sc2/src/sc2code/libs/sound/audiocore.c +++ b/sc2/src/sc2code/libs/sound/audiocore.c @@ -20,6 +20,7 @@ #include #include #include "audiocore.h" +#include "libs/log.h" static audio_Driver audiodrv; @@ -56,7 +57,7 @@ initAudio (sint32 driver, sint32 flags) #else if (driver == audio_DRIVER_OPENAL) { - fprintf (stderr, "OpenAL driver not compiled in, so using MixSDL\n"); + log_add (log_Always, "OpenAL driver not compiled in, so using MixSDL"); driver = audio_DRIVER_MIXSDL; } if (driver == audio_DRIVER_MIXSDL) @@ -67,10 +68,10 @@ initAudio (sint32 driver, sint32 flags) if (ret != 0) { - fprintf (stderr, "Sound driver initialization failed.\n" + log_add (log_Always, "Sound driver initialization failed.\n" "This may happen when a soundcard is " "not present or not available.\n" - "NOTICE: Try running UQM with '--sound=none' option\n"); + "NOTICE: Try running UQM with '--sound=none' option"); exit (EXIT_FAILURE); } return ret; diff --git a/sc2/src/sc2code/libs/sound/decoders/decoder.c b/sc2/src/sc2code/libs/sound/decoders/decoder.c index 7fa503ef0..454438568 100644 --- a/sc2/src/sc2code/libs/sound/decoders/decoder.c +++ b/sc2/src/sc2code/libs/sound/decoders/decoder.c @@ -23,6 +23,7 @@ #include "port.h" #include "libs/misc.h" #include "libs/file.h" +#include "libs/log.h" #include "decoder.h" #include "wav.h" #include "dukaud.h" @@ -177,7 +178,7 @@ SoundDecoder_Init (int flags, TFB_DecoderFormats *formats) if (!formats) { - fprintf (stderr, "SoundDecoder_Init(): missing decoder formats\n"); + log_add (log_Always, "SoundDecoder_Init(): missing decoder formats"); return 1; } decoder_formats = *formats; @@ -187,8 +188,8 @@ SoundDecoder_Init (int flags, TFB_DecoderFormats *formats) { if (!info->funcs->InitModule (flags, &decoder_formats)) { - fprintf (stderr, "SoundDecoder_Init(): " - "%s audio decoder init failed\n", + log_add (log_Always, "SoundDecoder_Init(): " + "%s audio decoder init failed", info->funcs->GetName ()); ret = 1; } @@ -227,12 +228,12 @@ SoundDecoder_Register (const char* fileext, TFB_SoundDecoderFuncs* decvtbl) if (!decvtbl) { - fprintf (stderr, "SoundDecoder_Register(): Null decoder table\n"); + log_add (log_Warning, "SoundDecoder_Register(): Null decoder table"); return NULL; } if (!fileext) { - fprintf (stderr, "SoundDecoder_Register(): Bad file type for %s\n", + log_add (log_Warning, "SoundDecoder_Register(): Bad file type for %s", decvtbl->GetName ()); return NULL; } @@ -249,20 +250,20 @@ SoundDecoder_Register (const char* fileext, TFB_SoundDecoderFuncs* decvtbl) if (info >= sd_decoders + MAX_REG_DECODERS) { - fprintf (stderr, "SoundDecoder_Register(): Decoders limit reached\n"); + log_add (log_Warning, "SoundDecoder_Register(): Decoders limit reached"); return NULL; } else if (info->ext) { - fprintf (stderr, "SoundDecoder_Register(): " - "'%s' decoder already registered (%s denied)\n", + log_add (log_Warning, "SoundDecoder_Register(): " + "'%s' decoder already registered (%s denied)", fileext, decvtbl->GetName ()); return NULL; } if (!decvtbl->InitModule (sd_flags, &decoder_formats)) { - fprintf (stderr, "SoundDecoder_Register(): %s decoder init failed\n", + log_add (log_Warning, "SoundDecoder_Register(): %s decoder init failed", decvtbl->GetName ()); return NULL; } @@ -289,8 +290,8 @@ SoundDecoder_Unregister (TFB_RegSoundDecoder* regdec) if (regdec < sd_decoders || regdec >= sd_decoders + MAX_REG_DECODERS || !regdec->ext || !regdec->funcs) { - fprintf (stderr, "SoundDecoder_Unregister(): " - "Invalid or expired decoder passed\n"); + log_add (log_Warning, "SoundDecoder_Unregister(): " + "Invalid or expired decoder passed"); return; } @@ -324,7 +325,7 @@ SoundDecoder_Load (uio_DirHandle *dir, char *filename, pext = strrchr (filename, '.'); if (!pext) { - fprintf (stderr, "SoundDecoder_Load(): Unknown file type (%s)\n", + log_add (log_Warning, "SoundDecoder_Load(): Unknown file type (%s)", filename); return NULL; } @@ -336,7 +337,7 @@ SoundDecoder_Load (uio_DirHandle *dir, char *filename, ; if (!info->ext) { - fprintf (stderr, "SoundDecoder_Load(): Unsupported file type (%s)\n", + log_add (log_Warning, "SoundDecoder_Load(): Unsupported file type (%s)", filename); return NULL; } @@ -352,7 +353,7 @@ SoundDecoder_Load (uio_DirHandle *dir, char *filename, } else { - fprintf (stderr, "SoundDecoder_Load(): %s does not exist\n", + log_add (log_Warning, "SoundDecoder_Load(): %s does not exist", filename); return NULL; } @@ -366,8 +367,8 @@ SoundDecoder_Load (uio_DirHandle *dir, char *filename, decoder->funcs = funcs; if (!decoder->funcs->Init (decoder)) { - fprintf (stderr, "SoundDecoder_Load(): " - "%s decoder instance failed init\n", + log_add (log_Warning, "SoundDecoder_Load(): " + "%s decoder instance failed init", decoder->funcs->GetName ()); HFree (decoder); return NULL; @@ -375,8 +376,8 @@ SoundDecoder_Load (uio_DirHandle *dir, char *filename, if (!decoder->funcs->Open (decoder, dir, filename)) { - fprintf (stderr, "SoundDecoder_Load(): " - "%s decoder could not load %s\n", + log_add (log_Warning, "SoundDecoder_Load(): " + "%s decoder could not load %s", decoder->funcs->GetName (), filename); decoder->funcs->Term (decoder); HFree (decoder); @@ -431,7 +432,7 @@ SoundDecoder_Decode (TFB_SoundDecoder *decoder) if (!decoder || !decoder->funcs) { - fprintf (stderr, "SoundDecoder_Decode(): null or bad decoder\n"); + log_add (log_Warning, "SoundDecoder_Decode(): null or bad decoder"); return 0; } @@ -456,8 +457,8 @@ SoundDecoder_Decode (TFB_SoundDecoder *decoder) buffer_size - decoded_bytes); if (rc < 0) { - fprintf (stderr, "SoundDecoder_Decode(): " - "error decoding %s, code %ld\n", + log_add (log_Warning, "SoundDecoder_Decode(): " + "error decoding %s, code %ld", decoder->filename, rc); } else if (rc == 0) @@ -467,21 +468,21 @@ SoundDecoder_Decode (TFB_SoundDecoder *decoder) SoundDecoder_Rewind (decoder); if (decoder->error) { - fprintf (stderr, "SoundDecoder_Decode(): " + log_add (log_Warning, "SoundDecoder_Decode(): " "tried to loop %s but couldn't rewind, " - "error code %d\n", + "error code %d", decoder->filename, decoder->error); } else { - fprintf (stderr, "SoundDecoder_Decode(): " - "looping %s\n", decoder->filename); + log_add (log_Info, "SoundDecoder_Decode(): " + "looping %s", decoder->filename); rc = 1; // prime the loop again } } else { - fprintf (stderr, "SoundDecoder_Decode(): eof for %s\n", + log_add (log_Info, "SoundDecoder_Decode(): eof for %s", decoder->filename); } } @@ -518,7 +519,7 @@ SoundDecoder_DecodeAll (TFB_SoundDecoder *decoder) if (!decoder || !decoder->funcs) { - fprintf (stderr, "SoundDecoder_DecodeAll(): null or bad decoder\n"); + log_add (log_Warning, "SoundDecoder_DecodeAll(): null or bad decoder"); return 0; } @@ -526,19 +527,17 @@ SoundDecoder_DecodeAll (TFB_SoundDecoder *decoder) if (decoder->looping) { - fprintf (stderr, "SoundDecoder_DecodeAll(): " - "called for %s with looping\n", decoder->filename); + log_add (log_Warning, "SoundDecoder_DecodeAll(): " + "called for %s with looping", decoder->filename); return 0; } if (reqbufsize < 4096) reqbufsize = 4096; -#ifdef DEBUG if (reqbufsize < 16384) - fprintf (stderr, "SoundDecoder_DecodeAll(): WARNING, " - "called with a small buffer (%u)\n", reqbufsize); -#endif + log_add (log_Debug, "SoundDecoder_DecodeAll(): WARNING, " + "called with a small buffer (%u)", reqbufsize); for (decoded_bytes = 0, rc = 1; rc > 0; ) { @@ -570,8 +569,8 @@ SoundDecoder_DecodeAll (TFB_SoundDecoder *decoder) if (rc < 0) { decoder->error = SOUNDDECODER_ERROR; - fprintf (stderr, "SoundDecoder_DecodeAll(): " - "error decoding %s, code %ld\n", + log_add (log_Warning, "SoundDecoder_DecodeAll(): " + "error decoding %s, code %ld", decoder->filename, rc); return decoded_bytes; } @@ -605,7 +604,7 @@ SoundDecoder_Seek (TFB_SoundDecoder *decoder, uint32 seekTime) return; if (!decoder->funcs) { - fprintf (stderr, "SoundDecoder_Seek(): bad decoder passed\n"); + log_add (log_Warning, "SoundDecoder_Seek(): bad decoder passed"); return; } @@ -623,7 +622,7 @@ SoundDecoder_Free (TFB_SoundDecoder *decoder) return; if (!decoder->funcs) { - fprintf (stderr, "SoundDecoder_Free(): bad decoder passed\n"); + log_add (log_Warning, "SoundDecoder_Free(): bad decoder passed"); return; } @@ -642,7 +641,7 @@ SoundDecoder_GetTime (TFB_SoundDecoder *decoder) return 0.0f; if (!decoder->funcs) { - fprintf (stderr, "SoundDecoder_GetTime(): bad decoder passed\n"); + log_add (log_Warning, "SoundDecoder_GetTime(): bad decoder passed"); return 0.0f; } @@ -659,7 +658,7 @@ SoundDecoder_GetFrame (TFB_SoundDecoder *decoder) return 0; if (!decoder->funcs) { - fprintf (stderr, "SoundDecoder_GetFrame(): bad decoder passed\n"); + log_add (log_Warning, "SoundDecoder_GetFrame(): bad decoder passed"); return 0; } @@ -679,7 +678,7 @@ static bool bufa_InitModule (int flags, const TFB_DecoderFormats* fmts) { // this should never be called - fprintf (stderr, "bufa_InitModule(): dead function called\n"); + log_add (log_Debug, "bufa_InitModule(): dead function called"); return false; (void)flags; (void)fmts; // laugh at compiler warning @@ -689,7 +688,7 @@ static void bufa_TermModule (void) { // this should never be called - fprintf (stderr, "bufa_TermModule(): dead function called\n"); + log_add (log_Debug, "bufa_TermModule(): dead function called"); } static uint32 @@ -731,7 +730,7 @@ static bool bufa_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) { // this should never be called - fprintf (stderr, "bufa_Open(): dead function called\n"); + log_add (log_Debug, "bufa_Open(): dead function called"); return false; // laugh at compiler warnings @@ -807,7 +806,7 @@ static bool nula_InitModule (int flags, const TFB_DecoderFormats* fmts) { // this should never be called - fprintf (stderr, "nula_InitModule(): dead function called\n"); + log_add (log_Debug, "nula_InitModule(): dead function called"); return false; (void)flags; (void)fmts; // laugh at compiler warning @@ -817,7 +816,7 @@ static void nula_TermModule (void) { // this should never be called - fprintf (stderr, "nula_TermModule(): dead function called\n"); + log_add (log_Debug, "nula_TermModule(): dead function called"); } static uint32 diff --git a/sc2/src/sc2code/libs/sound/decoders/modaud.c b/sc2/src/sc2code/libs/sound/decoders/modaud.c index dadbca0cc..f80f65f2e 100644 --- a/sc2/src/sc2code/libs/sound/decoders/modaud.c +++ b/sc2/src/sc2code/libs/sound/decoders/modaud.c @@ -29,6 +29,7 @@ #include "mikmod/mikmod.h" #include "mikmod/drv_openal.h" #include "libs/sound/audiocore.h" +#include "libs/log.h" #include "modaud.h" #define THIS_PTR TFB_SoundDecoder* This @@ -174,7 +175,7 @@ moda_InitModule (int flags, const TFB_DecoderFormats* fmts) if (MikMod_Init ("")) { - fprintf (stderr, "MikMod_Init() failed, %s\n", + log_add (log_Always, "MikMod_Init() failed, %s", MikMod_strerror (MikMod_errno)); return false; } @@ -251,7 +252,7 @@ moda_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) uio_fclose (fp); if (!mod) { - fprintf (stderr, "moda_Open(): could not load %s\n", filename); + log_add (log_Warning, "moda_Open(): could not load %s", filename); return false; } @@ -305,8 +306,8 @@ moda_Seek (THIS_PTR, uint32 pcm_pos) Player_Start (moda->module); if (pcm_pos) - fprintf (stderr, "moda_Seek(): " - "non-zero seek positions not supported for mod\n"); + log_add (log_Debug, "moda_Seek(): " + "non-zero seek positions not supported for mod"); Player_SetPosition (0); return 0; diff --git a/sc2/src/sc2code/libs/sound/decoders/oggaud.c b/sc2/src/sc2code/libs/sound/decoders/oggaud.c index 07a8162c0..a4920091c 100644 --- a/sc2/src/sc2code/libs/sound/decoders/oggaud.c +++ b/sc2/src/sc2code/libs/sound/decoders/oggaud.c @@ -21,6 +21,7 @@ #include #include #include "libs/misc.h" +#include "libs/log.h" #include "port.h" #include "types.h" #include "uio.h" @@ -174,15 +175,15 @@ ova_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) fp = uio_fopen (dir, filename, "rb"); if (fp == NULL) { - fprintf (stderr, "ova_Open(): could not open %s\n", filename); + log_add (log_Warning, "ova_Open(): could not open %s", filename); return false; } rc = ov_open_callbacks (fp, &ova->vf, NULL, 0, ogg_callbacks); if (rc != 0) { - fprintf (stderr, "ova_Open(): " - "ov_open_callbacks failed for %s, error code %d\n", + log_add (log_Warning, "ova_Open(): " + "ov_open_callbacks failed for %s, error code %d", filename, rc); uio_fclose (fp); return false; @@ -191,8 +192,8 @@ ova_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) vinfo = ov_info (&ova->vf, -1); if (!vinfo) { - fprintf (stderr, "ova_Open(): " - "failed to retrieve ogg bitstream info for %s\n", + log_add (log_Warning, "ova_Open(): " + "failed to retrieve ogg bitstream info for %s", filename); ov_clear (&ova->vf); return false; diff --git a/sc2/src/sc2code/libs/sound/decoders/wav.c b/sc2/src/sc2code/libs/sound/decoders/wav.c index 231d342c3..258c41b95 100644 --- a/sc2/src/sc2code/libs/sound/decoders/wav.c +++ b/sc2/src/sc2code/libs/sound/decoders/wav.c @@ -25,6 +25,7 @@ #include "uio.h" #include "endian_uqm.h" #include "libs/misc.h" +#include "libs/log.h" #include "wav.h" #define RIFF 0x46464952 /* "RIFF" */ @@ -234,8 +235,8 @@ wava_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) } if (FileHdr.Id != RIFF || FileHdr.Type != WAVE) { - fprintf (stderr, "wava_Open(): " - "not a wave file, ID 0x%08x, Type 0x%08x\n", + log_add (log_Warning, "wava_Open(): " + "not a wave file, ID 0x%08x, Type 0x%08x", FileHdr.Id, FileHdr.Type); wava_Close (This); return false; @@ -276,7 +277,8 @@ wava_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) if (!wava->data_size || !wava->data_ofs) { - fprintf (stderr, "wava_Open(): bad wave file, no DATA chunk found\n"); + log_add (log_Warning, "wava_Open(): bad wave file," + " no DATA chunk found"); wava_Close (This); return false; } @@ -294,7 +296,8 @@ wava_Open (THIS_PTR, uio_DirHandle *dir, const char *filename) } else { - fprintf (stderr, "wava_Open(): unsupported format %x\n", wava->FmtHdr.Format); + log_add (log_Warning, "wava_Open(): unsupported format %x", + wava->FmtHdr.Format); wava_Close (This); return false; } diff --git a/sc2/src/sc2code/libs/sound/mixer/mixer.c b/sc2/src/sc2code/libs/sound/mixer/mixer.c index 95ad04ede..02423c803 100644 --- a/sc2/src/sc2code/libs/sound/mixer/mixer.c +++ b/sc2/src/sc2code/libs/sound/mixer/mixer.c @@ -24,6 +24,7 @@ #include "mixerint.h" #include "libs/misc.h" #include "libs/threadlib.h" +#include "libs/log.h" static uint32 mixer_initialized = 0; static uint32 mixer_format; @@ -249,9 +250,7 @@ mixer_GenSources (uint32 n, mixer_Object *psrcobj) if (!psrcobj) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GenSources() called with null ptr\n"); -#endif + log_add (log_Debug, "mixer_GenSources() called with null ptr"); return; } for (; n; n--, psrcobj++) @@ -290,9 +289,7 @@ mixer_DeleteSources (uint32 n, mixer_Object *psrcobj) if (!psrcobj) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_DeleteSources() called with null ptr\n"); -#endif + log_add (log_Debug, "mixer_DeleteSources() called with null ptr"); return; } @@ -313,9 +310,7 @@ mixer_DeleteSources (uint32 n, mixer_Object *psrcobj) if (i) { /* some source failed */ mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_DeleteSources(): not a source\n"); -#endif + log_add (log_Debug, "mixer_DeleteSources(): not a source"); } else { /* all sources checked out */ @@ -371,9 +366,7 @@ mixer_Sourcei (mixer_Object srcobj, mixer_SourceProp pname, if (!src) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_Sourcei() called with null source\n"); -#endif + log_add (log_Debug, "mixer_Sourcei() called with null source"); return; } @@ -382,9 +375,7 @@ mixer_Sourcei (mixer_Object srcobj, mixer_SourceProp pname, if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_Sourcei(): not a source\n"); -#endif + log_add (log_Debug, "mixer_Sourcei(): not a source"); } else { @@ -419,14 +410,14 @@ mixer_Sourcei (mixer_Object srcobj, mixer_SourceProp pname, } else { - fprintf (stderr, "mixer_Sourcei(MIX_SOURCE_STATE): " - "unsupported state, call ignored\n"); + log_add (log_Debug, "mixer_Sourcei(MIX_SOURCE_STATE): " + "unsupported state, call ignored"); } break; default: mixer_SetError (MIX_INVALID_ENUM); - fprintf (stderr, "mixer_Sourcei() called " - "with unsupported property %u\n", pname); + log_add (log_Debug, "mixer_Sourcei() called " + "with unsupported property %u", pname); } } @@ -442,9 +433,7 @@ mixer_Sourcef (mixer_Object srcobj, mixer_SourceProp pname, float value) if (!src) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_Sourcef() called with null source\n"); -#endif + log_add (log_Debug, "mixer_Sourcef() called with null source"); return; } @@ -453,9 +442,7 @@ mixer_Sourcef (mixer_Object srcobj, mixer_SourceProp pname, float value) if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_Sourcef(): not a source\n"); -#endif + log_add (log_Debug, "mixer_Sourcef(): not a source"); } else { @@ -465,8 +452,8 @@ mixer_Sourcef (mixer_Object srcobj, mixer_SourceProp pname, float value) src->gain = value * MIX_GAIN_ADJ; break; default: - fprintf (stderr, "mixer_Sourcei() called " - "with unsupported property %u\n", pname); + log_add (log_Debug, "mixer_Sourcei() called " + "with unsupported property %u", pname); } } @@ -492,9 +479,7 @@ mixer_GetSourcei (mixer_Object srcobj, mixer_SourceProp pname, if (!src || !value) { mixer_SetError (src ? MIX_INVALID_VALUE : MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GetSourcei() called with null param\n"); -#endif + log_add (log_Debug, "mixer_GetSourcei() called with null param"); return; } @@ -503,9 +488,7 @@ mixer_GetSourcei (mixer_Object srcobj, mixer_SourceProp pname, if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GetSourcei(): not a source\n"); -#endif + log_add (log_Debug, "mixer_GetSourcei(): not a source"); } else { @@ -528,8 +511,8 @@ mixer_GetSourcei (mixer_Object srcobj, mixer_SourceProp pname, break; default: mixer_SetError (MIX_INVALID_ENUM); - fprintf (stderr, "mixer_GetSourcei() called " - "with unsupported property %u\n", pname); + log_add (log_Debug, "mixer_GetSourcei() called " + "with unsupported property %u", pname); } } @@ -546,9 +529,7 @@ mixer_GetSourcef (mixer_Object srcobj, mixer_SourceProp pname, if (!src || !value) { mixer_SetError (src ? MIX_INVALID_VALUE : MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GetSourcef() called with null param\n"); -#endif + log_add (log_Debug, "mixer_GetSourcef() called with null param"); return; } @@ -557,9 +538,7 @@ mixer_GetSourcef (mixer_Object srcobj, mixer_SourceProp pname, if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GetSourcef(): not a source\n"); -#endif + log_add (log_Debug, "mixer_GetSourcef(): not a source"); } else { @@ -569,8 +548,8 @@ mixer_GetSourcef (mixer_Object srcobj, mixer_SourceProp pname, *value = src->gain / MIX_GAIN_ADJ; break; default: - fprintf (stderr, "mixer_GetSourcef() called " - "with unsupported property %u\n", pname); + log_add (log_Debug, "mixer_GetSourcef() called " + "with unsupported property %u", pname); } } @@ -586,9 +565,7 @@ mixer_SourcePlay (mixer_Object srcobj) if (!src) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourcePlay() called with null source\n"); -#endif + log_add (log_Debug, "mixer_SourcePlay() called with null source"); return; } @@ -597,9 +574,7 @@ mixer_SourcePlay (mixer_Object srcobj) if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourcePlay(): not a source\n"); -#endif + log_add (log_Debug, "mixer_SourcePlay(): not a source"); } else /* should make the source active */ { @@ -624,9 +599,7 @@ mixer_SourceRewind (mixer_Object srcobj) if (!src) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceRewind() called with null source\n"); -#endif + log_add (log_Debug, "mixer_SourceRewind() called with null source"); return; } @@ -635,9 +608,7 @@ mixer_SourceRewind (mixer_Object srcobj) if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourcePlay(): not a source\n"); -#endif + log_add (log_Debug, "mixer_SourcePlay(): not a source"); } else { @@ -656,9 +627,7 @@ mixer_SourcePause (mixer_Object srcobj) if (!src) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourcePause() called with null source\n"); -#endif + log_add (log_Debug, "mixer_SourcePause() called with null source"); return; } @@ -667,9 +636,7 @@ mixer_SourcePause (mixer_Object srcobj) if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourcePause(): not a source\n"); -#endif + log_add (log_Debug, "mixer_SourcePause(): not a source"); } else /* should keep all buffers and offsets */ { @@ -692,9 +659,7 @@ mixer_SourceStop (mixer_Object srcobj) if (!src) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceStop() called with null source\n"); -#endif + log_add (log_Debug, "mixer_SourceStop() called with null source"); return; } @@ -703,9 +668,7 @@ mixer_SourceStop (mixer_Object srcobj) if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceStop(): not a source\n"); -#endif + log_add (log_Debug, "mixer_SourceStop(): not a source"); } else /* should remove queued buffers */ { @@ -730,10 +693,8 @@ mixer_SourceQueueBuffers (mixer_Object srcobj, uint32 n, if (!src || !pbufobj) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceQueueBuffers() called " - "with null param\n"); -#endif + log_add (log_Debug, "mixer_SourceQueueBuffers() called " + "with null param"); return; } @@ -758,9 +719,7 @@ mixer_SourceQueueBuffers (mixer_Object srcobj, uint32 n, if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceQueueBuffers(): not a source\n"); -#endif + log_add (log_Debug, "mixer_SourceQueueBuffers(): not a source"); } else { @@ -801,10 +760,8 @@ mixer_SourceUnqueueBuffers (mixer_Object srcobj, uint32 n, if (!src || !pbufobj) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceUnqueueBuffers() called " - "with null source\n"); -#endif + log_add (log_Debug, "mixer_SourceUnqueueBuffers() called " + "with null source"); return; } @@ -813,9 +770,7 @@ mixer_SourceUnqueueBuffers (mixer_Object srcobj, uint32 n, if (src->magic != mixer_srcMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceUnqueueBuffers(): not a source\n"); -#endif + log_add (log_Debug, "mixer_SourceUnqueueBuffers(): not a source"); } else if (n > src->cqueued) { @@ -834,10 +789,8 @@ mixer_SourceUnqueueBuffers (mixer_Object srcobj, uint32 n, if (i) { mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "mixer_SourceUnqueueBuffers(): " - "active buffer attempted\n"); -#endif + log_add (log_Debug, "mixer_SourceUnqueueBuffers(): " + "active buffer attempted"); } else { /* all buffers checked out */ @@ -882,10 +835,8 @@ mixer_SourceUnqueueAll (mixer_Source *src) if (!src) { -#ifdef DEBUG - fprintf (stderr, "mixer_SourceUnqueueAll() called " - "with null source\n"); -#endif + log_add (log_Debug, "mixer_SourceUnqueueAll() called " + "with null source"); return; } @@ -893,13 +844,11 @@ mixer_SourceUnqueueAll (mixer_Source *src) for (buf = src->firstqueued; buf; buf = nextbuf) { -#ifdef DEBUG if (buf->state == MIX_BUF_PLAYING) { - fprintf (stderr, "mixer_SourceUnqueueAll(): " - "attempted on active buffer\n"); + log_add (log_Debug, "mixer_SourceUnqueueAll(): " + "attempted on active buffer"); } -#endif nextbuf = buf->next; buf->state = MIX_BUF_FILLED; buf->next = 0; @@ -925,18 +874,16 @@ mixer_SourceActivate (mixer_Source* src) LockRecursiveMutex (act_mutex); -#ifdef DEBUG /* check active sources, see if this source is there already */ for (i = 0; i < MAX_SOURCES && active_sources[i] != src; i++) ; if (i < MAX_SOURCES) { /* source found */ - fprintf (stderr, "mixer_SourceActivate(): " - "source already active in slot %u\n", i); + log_add (log_Debug, "mixer_SourceActivate(): " + "source already active in slot %u", i); UnlockRecursiveMutex (act_mutex); return; } -#endif /* find an empty slot */ for (i = 0; i < MAX_SOURCES && active_sources[i] != 0; i++) @@ -945,13 +892,11 @@ mixer_SourceActivate (mixer_Source* src) { /* slot found */ active_sources[i] = src; } -#ifdef DEBUG else { - fprintf (stderr, "mixer_SourceActivate(): " - "no more slots available (max=%d)\n", MAX_SOURCES); + log_add (log_Debug, "mixer_SourceActivate(): " + "no more slots available (max=%d)", MAX_SOURCES); } -#endif UnlockRecursiveMutex (act_mutex); } @@ -971,12 +916,10 @@ mixer_SourceDeactivate (mixer_Source* src) { /* source found */ active_sources[i] = 0; } -#ifdef DEBUG else { /* source not found */ - fprintf (stderr, "mixer_SourceDeactivate(): source not active\n"); + log_add (log_Debug, "mixer_SourceDeactivate(): source not active"); } -#endif UnlockRecursiveMutex (act_mutex); } @@ -990,15 +933,15 @@ mixer_SourceStop_internal (mixer_Source *src) if (!src->firstqueued) return; -#ifdef DEBUG /* assert the source buffers state */ if (!src->lastqueued) { - fprintf (stderr, "mixer_SourceStop_internal(): " - "desynced source state\n"); - return; - } + log_add (log_Debug, "mixer_SourceStop_internal(): " + "desynced source state"); +#ifdef DEBUG + abort (); #endif + } LockRecursiveMutex (buf_mutex); @@ -1211,9 +1154,7 @@ mixer_GenBuffers (uint32 n, mixer_Object *pbufobj) if (!pbufobj) { mixer_SetError (MIX_INVALID_VALUE); -#ifdef DEBUG - fprintf (stderr, "mixer_GenBuffers() called with null ptr\n"); -#endif + log_add (log_Debug, "mixer_GenBuffers() called with null ptr"); return; } for (; n; n--, pbufobj++) @@ -1250,9 +1191,7 @@ mixer_DeleteBuffers (uint32 n, mixer_Object *pbufobj) if (!pbufobj) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_DeleteBuffers() called with null ptr\n"); -#endif + log_add (log_Debug, "mixer_DeleteBuffers() called with null ptr"); return; } @@ -1269,26 +1208,20 @@ mixer_DeleteBuffers (uint32 n, mixer_Object *pbufobj) if (buf->magic != mixer_bufMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_DeleteBuffers(): not a buffer\n"); -#endif + log_add (log_Debug, "mixer_DeleteBuffers(): not a buffer"); break; } else if (buf->locked) { mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "mixer_DeleteBuffers(): locked buffer\n"); -#endif + log_add (log_Debug, "mixer_DeleteBuffers(): locked buffer"); break; } else if (buf->state >= MIX_BUF_QUEUED) { mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "mixer_DeleteBuffers(): " - "attempted on queued/active buffer\n"); -#endif + log_add (log_Debug, "mixer_DeleteBuffers(): " + "attempted on queued/active buffer"); break; } } @@ -1340,9 +1273,7 @@ mixer_GetBufferi (mixer_Object bufobj, mixer_BufferProp pname, if (!buf || !value) { mixer_SetError (buf ? MIX_INVALID_VALUE : MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GetBufferi() called with null param\n"); -#endif + log_add (log_Debug, "mixer_GetBufferi() called with null param"); return; } @@ -1352,18 +1283,14 @@ mixer_GetBufferi (mixer_Object bufobj, mixer_BufferProp pname, { UnlockRecursiveMutex (buf_mutex); mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "mixer_GetBufferi() called with locked buffer\n"); -#endif + log_add (log_Debug, "mixer_GetBufferi() called with locked buffer"); return; } if (buf->magic != mixer_bufMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_GetBufferi(): not a buffer\n"); -#endif + log_add (log_Debug, "mixer_GetBufferi(): not a buffer"); } else { @@ -1388,8 +1315,8 @@ mixer_GetBufferi (mixer_Object bufobj, mixer_BufferProp pname, break; default: mixer_SetError (MIX_INVALID_ENUM); - fprintf (stderr, "mixer_GetBufferi() called " - "with invalid property %u\n", pname); + log_add (log_Debug, "mixer_GetBufferi() called " + "with invalid property %u", pname); } } @@ -1408,9 +1335,7 @@ mixer_BufferData (mixer_Object bufobj, uint32 format, void* data, if (!buf || !data || !size) { mixer_SetError (buf ? MIX_INVALID_VALUE : MIX_INVALID_NAME); -#ifdef DEBUG -// fprintf (stderr, "mixer_BufferData() called with bad param\n"); -#endif + log_add (log_Debug, "mixer_BufferData() called with bad param"); return; } @@ -1420,27 +1345,21 @@ mixer_BufferData (mixer_Object bufobj, uint32 format, void* data, { UnlockRecursiveMutex (buf_mutex); mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "mixer_BufferData() called " - "with locked buffer\n"); -#endif + log_add (log_Debug, "mixer_BufferData() called " + "with locked buffer"); return; } if (buf->magic != mixer_bufMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "mixer_BufferData(): not a buffer\n"); -#endif + log_add (log_Debug, "mixer_BufferData(): not a buffer"); } else if (buf->state > MIX_BUF_FILLED) { mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "mixer_BufferData() attempted " - "on in-use buffer\n"); -#endif + log_add (log_Debug, "mixer_BufferData() attempted " + "on in-use buffer"); } else { @@ -1551,27 +1470,21 @@ mixer_CheckBufferState (mixer_Buffer *buf, const char* FuncName) if (buf->magic != mixer_bufMagic) { mixer_SetError (MIX_INVALID_NAME); -#ifdef DEBUG - fprintf (stderr, "%s(): not a buffer\n", FuncName); -#endif + log_add (log_Debug, "%s(): not a buffer", FuncName); return false; } if (buf->locked) { mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "%s(): locked buffer attempted\n", FuncName); -#endif + log_add (log_Debug, "%s(): locked buffer attempted", FuncName); return false; } if (buf->state != MIX_BUF_FILLED) { mixer_SetError (MIX_INVALID_OPERATION); -#ifdef DEBUG - fprintf (stderr, "%s: invalid buffer attempted\n", FuncName); -#endif + log_add (log_Debug, "%s: invalid buffer attempted", FuncName); return false; } return true; diff --git a/sc2/src/sc2code/libs/sound/mixer/nosound/audiodrv_nosound.c b/sc2/src/sc2code/libs/sound/mixer/nosound/audiodrv_nosound.c index ae5d6f330..f7ceb29a8 100644 --- a/sc2/src/sc2code/libs/sound/mixer/nosound/audiodrv_nosound.c +++ b/sc2/src/sc2code/libs/sound/mixer/nosound/audiodrv_nosound.c @@ -21,6 +21,7 @@ #include "audiodrv_nosound.h" #include "libs/tasklib.h" +#include "libs/log.h" #include @@ -109,26 +110,26 @@ noSound_Init (audio_Driver *driver, sint32 flags) audio_FORMAT_MONO16, audio_FORMAT_STEREO16 }; - fprintf (stderr, "Using nosound audio driver.\n"); - fprintf (stderr, "Initializing mixer.\n"); + log_add (log_Always, "Using nosound audio driver."); + log_add (log_Always, "Initializing mixer."); if (!mixer_Init (nosound_freq, MIX_FORMAT_MAKE (1, 1), MIX_QUALITY_LOW, MIX_FAKE_DATA)) { - fprintf (stderr, "Mixer initialization failed: %x\n", + log_add (log_Always, "Mixer initialization failed: %x", mixer_GetError ()); return -1; } - fprintf (stderr, "Mixer initialized.\n"); + log_add (log_Always, "Mixer initialized."); - fprintf (stderr, "Initializing sound decoders.\n"); + log_add (log_Always, "Initializing sound decoders."); if (SoundDecoder_Init (flags, &formats)) { - fprintf (stderr, "Sound decoders initialization failed.\n"); + log_add (log_Always, "Sound decoders initialization failed."); mixer_Uninit (); return -1; } - fprintf (stderr, "Sound decoders initialized.\n"); + log_add (log_Always, "Sound decoders initialized."); *driver = noSound_Driver; for (i = 0; i < NUM_SOUNDSOURCES; ++i) @@ -250,7 +251,7 @@ noSound_GetError (void) case MIX_OUT_OF_MEMORY: return audio_OUT_OF_MEMORY; default: - fprintf (stderr, "noSound_GetError: unknown value %x\n", + log_add (log_Debug, "noSound_GetError: unknown value %x", value); return audio_DRIVER_FAILURE; break; @@ -326,7 +327,7 @@ noSound_GetSourcei (audio_Object srcobj, audio_SourceProp pname, *value = audio_PAUSED; break; default: - fprintf (stderr, "noSound_GetSourcei(): unknown value %lx\n", + log_add (log_Debug, "noSound_GetSourcei(): unknown value %lx", (long int) *value); *value = audio_DRIVER_FAILURE; } diff --git a/sc2/src/sc2code/libs/sound/mixer/sdl/audiodrv_sdl.c b/sc2/src/sc2code/libs/sound/mixer/sdl/audiodrv_sdl.c index 24c32682d..ddcc96adc 100644 --- a/sc2/src/sc2code/libs/sound/mixer/sdl/audiodrv_sdl.c +++ b/sc2/src/sc2code/libs/sound/mixer/sdl/audiodrv_sdl.c @@ -21,6 +21,7 @@ #include "audiodrv_sdl.h" #include "libs/tasklib.h" +#include "libs/log.h" #include @@ -110,13 +111,14 @@ mixSDL_Init (audio_Driver *driver, sint32 flags) audio_FORMAT_MONO16, audio_FORMAT_STEREO16 }; - fprintf (stderr, "Initializing SDL audio subsystem.\n"); + log_add (log_Always, "Initializing SDL audio subsystem."); if ((SDL_InitSubSystem(SDL_INIT_AUDIO)) == -1) { - fprintf (stderr, "Couldn't initialize audio subsystem: %s\n", SDL_GetError()); + log_add (log_Always, "Couldn't initialize audio subsystem: %s", + SDL_GetError()); return -1; } - fprintf (stderr, "SDL audio subsystem initialized.\n"); + log_add (log_Always, "SDL audio subsystem initialized."); if (flags & audio_QUALITY_HIGH) { @@ -141,49 +143,52 @@ mixSDL_Init (audio_Driver *driver, sint32 flags) desired.channels = 2; desired.callback = mixer_MixChannels; - fprintf (stderr, "Opening SDL audio device.\n"); + log_add (log_Always, "Opening SDL audio device."); if (SDL_OpenAudio (&desired, &obtained) < 0) { - fprintf (stderr, "Unable to open audio device: %s\n", SDL_GetError ()); + log_add (log_Always, "Unable to open audio device: %s", + SDL_GetError ()); SDL_QuitSubSystem (SDL_INIT_AUDIO); return -1; } if (obtained.format != desired.format || (obtained.channels != 1 && obtained.channels != 2)) { - fprintf (stderr, "Unable to obtain desired audio format.\n"); + log_add (log_Always, "Unable to obtain desired audio format."); SDL_CloseAudio (); SDL_QuitSubSystem (SDL_INIT_AUDIO); return -1; } SDL_AudioDriverName (devicename, sizeof (devicename)); - fprintf (stderr, " using %s at %d Hz 16 bit %s, %d samples audio buffer\n", - devicename, obtained.freq, obtained.channels > 1 ? "stereo" : "mono", + log_add (log_Always, " using %s at %d Hz 16 bit %s, " + "%d samples audio buffer", + devicename, obtained.freq, + obtained.channels > 1 ? "stereo" : "mono", obtained.samples); - fprintf (stderr, "Initializing mixer.\n"); + log_add (log_Always, "Initializing mixer."); if (!mixer_Init (obtained.freq, MIX_FORMAT_MAKE (2, obtained.channels), quality, 0)) { - fprintf (stderr, "Mixer initialization failed: %x\n", + log_add (log_Always, "Mixer initialization failed: %x", mixer_GetError ()); SDL_CloseAudio (); SDL_QuitSubSystem (SDL_INIT_AUDIO); return -1; } - fprintf (stderr, "Mixer initialized.\n"); + log_add (log_Always, "Mixer initialized."); - fprintf (stderr, "Initializing sound decoders.\n"); + log_add (log_Always, "Initializing sound decoders."); if (SoundDecoder_Init (flags, &formats)) { - fprintf (stderr, "Sound decoders initialization failed.\n"); + log_add (log_Always, "Sound decoders initialization failed."); SDL_CloseAudio (); mixer_Uninit (); SDL_QuitSubSystem (SDL_INIT_AUDIO); return -1; } - fprintf (stderr, "Sound decoders initialized.\n"); + log_add (log_Always, "Sound decoders initialized."); *driver = mixSDL_Driver; for (i = 0; i < NUM_SOUNDSOURCES; ++i) @@ -270,7 +275,7 @@ mixSDL_GetError (void) case MIX_OUT_OF_MEMORY: return audio_OUT_OF_MEMORY; default: - fprintf (stderr, "mixSDL_GetError: unknown value %x\n", value); + log_add (log_Debug, "mixSDL_GetError: unknown value %x", value); return audio_DRIVER_FAILURE; break; } diff --git a/sc2/src/sc2code/libs/sound/music.c b/sc2/src/sc2code/libs/sound/music.c index 14aca8b10..15681e3f7 100644 --- a/sc2/src/sc2code/libs/sound/music.c +++ b/sc2/src/sc2code/libs/sound/music.c @@ -18,6 +18,7 @@ #include "options.h" #include "sound.h" #include "libs/reslib.h" +#include "libs/log.h" static MUSIC_REF curMusicRef; @@ -139,7 +140,7 @@ CheckMusicResName (char* fileName) if (fileExists2 (contentDir, otherName)) strcpy (fileName, otherName); else - fprintf (stderr, "Requested track '%s' not found!\n", otherName); + log_add (log_Warning, "Requested track '%s' not found.", otherName); } return fileName; @@ -171,11 +172,11 @@ _GetMusicData (uio_Stream *fp, DWORD length) filename[sizeof(filename) - 1] = '\0'; CheckMusicResName (filename); - fprintf (stderr, "_GetMusicData(): loading %s\n", filename); + log_add (log_Info, "_GetMusicData(): loading %s", filename); if (((*pmus)->decoder = SoundDecoder_Load (contentDir, filename, 4096, 0, 0)) == 0) { - fprintf (stderr, "_GetMusicData(): couldn't load %s\n", filename); + log_add (log_Warning, "_GetMusicData(): couldn't load %s", filename); UnlockMusicData (h); mem_release (h); @@ -183,7 +184,7 @@ _GetMusicData (uio_Stream *fp, DWORD length) } else { - fprintf (stderr, " decoder: %s, rate %d format %x\n", + log_add (log_Info, " decoder: %s, rate %d format %x", SoundDecoder_GetName ((*pmus)->decoder), (*pmus)->decoder->frequency, (*pmus)->decoder->format); diff --git a/sc2/src/sc2code/libs/sound/openal/audiodrv_openal.c b/sc2/src/sc2code/libs/sound/openal/audiodrv_openal.c index 601514349..de4d872c7 100644 --- a/sc2/src/sc2code/libs/sound/openal/audiodrv_openal.c +++ b/sc2/src/sc2code/libs/sound/openal/audiodrv_openal.c @@ -22,7 +22,7 @@ #include "audiodrv_openal.h" #include "libs/tasklib.h" - +#include "libs/log.h" #include @@ -115,7 +115,7 @@ openAL_Init (audio_Driver *driver, sint32 flags) audio_FORMAT_MONO16, audio_FORMAT_STEREO16 }; - fprintf (stderr, "Initializing OpenAL.\n"); + log_add (log_Always, "Initializing OpenAL."); #ifdef WIN32 alcDevice = alcOpenDevice ((ALubyte*)"DirectSound3D"); #else @@ -124,7 +124,8 @@ openAL_Init (audio_Driver *driver, sint32 flags) if (!alcDevice) { - fprintf (stderr,"Couldn't initialize OpenAL: %d\n", alcGetError (NULL)); + log_add (log_Always, "Couldn't initialize OpenAL: %d", + alcGetError (NULL)); return -1; } @@ -134,22 +135,37 @@ openAL_Init (audio_Driver *driver, sint32 flags) alcContext = alcCreateContext (alcDevice, NULL); if (!alcContext) { - fprintf (stderr, "Couldn't create OpenAL context: %d\n", alcGetError (alcDevice)); + log_add (log_Always, "Couldn't create OpenAL context: %d", + alcGetError (alcDevice)); + alcCloseDevice (alcDevice); + alcDevice = NULL; + return -1; } alcMakeContextCurrent (alcContext); - fprintf (stderr, "OpenAL initialized.\n"); - fprintf (stderr, " version: %s\n", alGetString (AL_VERSION)); - fprintf (stderr, " vendor: %s\n", alGetString (AL_VENDOR)); - fprintf (stderr, " renderer: %s\n", alGetString (AL_RENDERER)); - fprintf (stderr, " device: %s\n", - alcGetString (alcDevice, ALC_DEFAULT_DEVICE_SPECIFIER)); - //fprintf (stderr, " extensions: %s\n", alGetString (AL_EXTENSIONS)); + log_add (log_Always, "OpenAL initialized.\n" + " version: %s\n", + " vendor: %s\n", + " renderer: %s\n", + " device: %s", + alGetString (AL_VERSION), alGetString (AL_VENDOR), + alGetString (AL_RENDERER), + alcGetString (alcDevice, ALC_DEFAULT_DEVICE_SPECIFIER)); + //log_add (log_Info, " extensions: %s", alGetString (AL_EXTENSIONS)); - fprintf (stderr, "Initializing sound decoders.\n"); - SoundDecoder_Init (flags, &formats); - fprintf (stderr, "Sound decoders initialized.\n"); + log_add (log_Always, "Initializing sound decoders."); + if (SoundDecoder_Init (flags, &formats)) + { + log_add (log_Always, "Sound decoders initialization failed."); + alcMakeContextCurrent (NULL); + alcDestroyContext (alcContext); + alcContext = NULL; + alcCloseDevice (alcDevice); + alcDevice = NULL; + return -1; + } + log_add (log_Always, "Sound decoders initialized."); alListenerfv (AL_POSITION, listenerPos); alListenerfv (AL_VELOCITY, listenerVel); @@ -250,7 +266,7 @@ openAL_GetError (void) case AL_OUT_OF_MEMORY: return audio_OUT_OF_MEMORY; default: - fprintf (stderr, "openAL_GetError: unknown value %x\n", value); + log_add (log_Debug, "openAL_GetError: unknown value %x", value); return audio_DRIVER_FAILURE; break; } @@ -323,7 +339,7 @@ openAL_GetSourcei (audio_Object srcobj, audio_SourceProp pname, *value = audio_PAUSED; break; default: - fprintf (stderr, "openAL_GetSourcei(): unknown value %x\n", + log_add (log_Debug, "openAL_GetSourcei(): unknown value %x", *value); *value = audio_DRIVER_FAILURE; } diff --git a/sc2/src/sc2code/libs/sound/sfx.c b/sc2/src/sc2code/libs/sound/sfx.c index de7f2738a..8fc9fdc23 100644 --- a/sc2/src/sc2code/libs/sound/sfx.c +++ b/sc2/src/sc2code/libs/sound/sfx.c @@ -17,6 +17,7 @@ #include "options.h" #include "sound.h" #include "libs/reslib.h" +#include "libs/log.h" #include @@ -121,7 +122,7 @@ UpdateSoundPosition (COUNT channel, SoundPosition pos) } audio_Sourcefv (soundSource[channel].handle, audio_POSITION, fpos); - //fprintf (stderr, "UpdateSoundPosition(): channel %d, pos %d %d, posobj %x\n", + //log_add (log_Debug, "UpdateSoundPosition(): channel %d, pos %d %d, posobj %x", // channel, pos.x, pos.y, (unsigned int)soundSource[channel].positional_object); } else @@ -210,7 +211,7 @@ _GetSoundBankData (uio_Stream *fp, DWORD length) { if (sscanf(CurrentLine, "%s", &filename[n]) == 1) { - fprintf (stderr, "_GetSoundBankData(): loading %s\n", filename); + log_add (log_Info, "_GetSoundBankData(): loading %s", filename); sndfx[snd_ct] = (TFB_SoundSample *) HCalloc (sizeof (TFB_SoundSample)); @@ -218,7 +219,7 @@ _GetSoundBankData (uio_Stream *fp, DWORD length) filename, 4096, 0, 0); if (!sndfx[snd_ct]->decoder) { - fprintf (stderr, "_GetSoundBankData(): couldn't load %s\n", filename); + log_add (log_Warning, "_GetSoundBankData(): couldn't load %s", filename); HFree (sndfx[snd_ct]); } else @@ -226,7 +227,7 @@ _GetSoundBankData (uio_Stream *fp, DWORD length) uint32 decoded_bytes; decoded_bytes = SoundDecoder_DecodeAll (sndfx[snd_ct]->decoder); - //fprintf (stderr, "_GetSoundBankData(): decoded_bytes %d\n", decoded_bytes); + log_add (log_Info, "_GetSoundBankData(): decoded_bytes %d", decoded_bytes); sndfx[snd_ct]->num_buffers = 1; sndfx[snd_ct]->buffer = (audio_Object *) HMalloc ( @@ -244,7 +245,7 @@ _GetSoundBankData (uio_Stream *fp, DWORD length) } else { - fprintf (stderr, "_GetSoundBankData: Bad file!\n"); + log_add (log_Warning, "_GetSoundBankData: Bad file!"); } // pkunk insult fix 2002/11/12 (ftell shouldn't be needed for loop to terminate) diff --git a/sc2/src/sc2code/libs/sound/stream.c b/sc2/src/sc2code/libs/sound/stream.c index fee574fc6..08d2bd81d 100644 --- a/sc2/src/sc2code/libs/sound/stream.c +++ b/sc2/src/sc2code/libs/sound/stream.c @@ -16,7 +16,8 @@ #include #include "sound.h" -#include "../tasklib.h" +#include "libs/tasklib.h" +#include "libs/log.h" void @@ -58,9 +59,11 @@ PlayStream (TFB_SoundSample *sample, uint32 source, bool looping, bool scope, uint32 decoded_bytes; decoded_bytes = SoundDecoder_Decode (sample->decoder); - //fprintf (stderr, "PlayStream(): source %d filename:%s start: %d position:%d bytes %d\n", source, - // sample->decoder->filename, sample->decoder->start_sample, - // sample->decoder->pos, decoded_bytes); +#if 0 + log_add (log_Debug, "PlayStream(): source:%d filename:%s start:%d position:%d bytes:%d\n", + source, sample->decoder->filename, sample->decoder->start_sample, + sample->decoder->pos, decoded_bytes); +#endif if (decoded_bytes == 0) break; @@ -245,8 +248,8 @@ StreamDecoderTaskFunc (void *data) if (queued == 0 && soundSource[i].sample->decoder->error == SOUNDDECODER_EOF) { - fprintf (stderr, "StreamDecoderTaskFunc(): " - "finished playing %s, source %d\n", + log_add (log_Info, "StreamDecoderTaskFunc(): " + "finished playing %s, source %d", soundSource[i].sample->decoder->filename, i); soundSource[i].stream_should_be_playing = FALSE; if (soundSource[i].sample->callbacks.OnEndStream) @@ -255,15 +258,18 @@ StreamDecoderTaskFunc (void *data) } else { - fprintf (stderr, "StreamDecoderTaskFunc(): buffer " - "underrun when playing %s, source %d\n", + log_add (log_Warning, "StreamDecoderTaskFunc(): buffer " + "underrun when playing %s, source %d", soundSource[i].sample->decoder->filename, i); audio_SourcePlay (soundSource[i].handle); } } } - //fprintf (stderr, "StreamDecoderTaskFunc(): source %d, processed %d queued %d\n", i, processed, queued); +#if 0 + log_add (log_Debug, "StreamDecoderTaskFunc(): source %d, processed %d queued %d", + i, processed, queued); +#endif while (processed) { @@ -278,9 +284,9 @@ StreamDecoderTaskFunc (void *data) error = audio_GetError(); if (error != audio_NO_ERROR) { - fprintf (stderr, "StreamDecoderTaskFunc(): OpenAL " + log_add (log_Warning, "StreamDecoderTaskFunc(): OpenAL " "error after alSourceUnqueueBuffers: %x, " - "file %s, source %d\n", error, + "file %s, source %d", error, soundSource[i].sample->decoder->filename, i); break; } @@ -315,14 +321,21 @@ StreamDecoderTaskFunc (void *data) !soundSource[i].sample->callbacks.OnEndChunk ( soundSource[i].sample, last_buffer[i])) { - //fprintf (stderr, "StreamDecoderTaskFunc(): decoder->error is eof for %s\n", soundSource[i].sample->decoder->filename); +#if 0 + log_add (log_Debug, "StreamDecoderTaskFunc(): decoder->error is eof for %s", + soundSource[i].sample->decoder->filename); +#endif processed--; continue; } } else { - //fprintf (stderr, "StreamDecoderTaskFunc(): decoder->error is %d for %s\n", soundSource[i].sample->decoder->error, soundSource[i].sample->decoder->filename); +#if 0 + log_add (log_Debug, "StreamDecoderTaskFunc(): decoder->error is %d for %s", + soundSource[i].sample->decoder->error, + soundSource[i].sample->decoder->filename); +#endif processed--; continue; } @@ -333,9 +346,9 @@ StreamDecoderTaskFunc (void *data) if (soundSource[i].sample->decoder->error == SOUNDDECODER_ERROR) { - fprintf (stderr, "StreamDecoderTaskFunc(): " + log_add (log_Warning, "StreamDecoderTaskFunc(): " "SoundDecoder_Decode error %d, file %s, " - "source %d\n", + "source %d", soundSource[i].sample->decoder->error, soundSource[i].sample->decoder->filename, i); soundSource[i].stream_should_be_playing = FALSE; @@ -354,9 +367,9 @@ StreamDecoderTaskFunc (void *data) error = audio_GetError(); if (error != audio_NO_ERROR) { - fprintf (stderr, "StreamDecoderTaskFunc(): " + log_add (log_Warning, "StreamDecoderTaskFunc(): " "TFBSound error after audio_BufferData: " - "%x, file %s, source %d, decoded_bytes %d\n", + "%x, file %s, source %d, decoded_bytes %d", error, soundSource[i].sample->decoder->filename, i, decoded_bytes); } @@ -393,7 +406,6 @@ StreamDecoderTaskFunc (void *data) if (j - soundSource[i].sbuf_start >= 1) { - //fprintf (stderr, "copying_a to %d - %d, %d bytes\n", soundSource[i].sbuf_start, j, j - soundSource[i].sbuf_start); memcpy (&sbuffer[soundSource[i].sbuf_start], decoder_buffer, j - soundSource[i].sbuf_start); @@ -401,7 +413,6 @@ StreamDecoderTaskFunc (void *data) if (remaining_bytes) { - //fprintf (stderr, "copying_b to 0 - %d\n", remaining_bytes); memcpy (sbuffer, &decoder_buffer[ j - soundSource[i].sbuf_start], remaining_bytes); @@ -416,10 +427,10 @@ StreamDecoderTaskFunc (void *data) error = audio_GetError(); if (error != audio_NO_ERROR) { - fprintf (stderr, "StreamDecoderTaskFunc(): " + log_add (log_Warning, "StreamDecoderTaskFunc(): " "TFBSound error after " "audio_SourceQueueBuffers: %x, file %s, " - "source %d, decoded_bytes %d\n", error, + "source %d, decoded_bytes %d", error, soundSource[i].sample->decoder->filename, i, decoded_bytes); } diff --git a/sc2/src/sc2code/libs/sound/trackplayer.c b/sc2/src/sc2code/libs/sound/trackplayer.c index e83c9dc99..325a93708 100644 --- a/sc2/src/sc2code/libs/sound/trackplayer.c +++ b/sc2/src/sc2code/libs/sound/trackplayer.c @@ -17,6 +17,7 @@ #include "sound.h" #include "libs/sound/trackplayer.h" #include "libs/sound/trackint.h" +#include "libs/log.h" #include "comm.h" #include "sis.h" #include "options.h" @@ -267,7 +268,7 @@ OnChunkEnd (TFB_SoundSample* sample, audio_Object buffer) scd->read_chain_ptr = scd->read_chain_ptr->next; sample->decoder = scd->read_chain_ptr->decoder; SoundDecoder_Rewind (sample->decoder); - fprintf (stderr, "Switching to stream %s at pos %d\n", + log_add (log_Info, "Switching to stream %s at pos %d", sample->decoder->filename, sample->decoder->start_sample); if (sample->buffer_tag && scd->read_chain_ptr->tag_me) @@ -414,33 +415,31 @@ SpliceMultiTrack (UNICODE *TrackNames[], UNICODE *TrackText) if (!TrackText) { -#ifdef DEBUG - fprintf (stderr, "SpliceMultiTrack(): no track text\n"); -#endif + log_add (log_Debug, "SpliceMultiTrack(): no track text"); return; } if (tct >= MAX_CLIPS) { - fprintf (stderr, "SpliceMultiTrack(): no more clip slots (%d)\n", + log_add (log_Warning, "SpliceMultiTrack(): no more clip slots (%d)", MAX_CLIPS); return; } if (! sound_sample) { - fprintf (stderr, "SpliceMultiTrack(): Cannot be called before SpliceTrack()\n"); + log_add (log_Warning, "SpliceMultiTrack(): Cannot be called before SpliceTrack()"); return; } - fprintf (stderr, "SpliceMultiTrack(): loading...\n"); + log_add (log_Info, "SpliceMultiTrack(): loading..."); for (tracks = 0; *TrackNames && tracks < MAX_MULTI_TRACKS; TrackNames++, tracks++) { track_decs[tracks] = SoundDecoder_Load (contentDir, *TrackNames, 32768, 0, - 3 * TEXT_SPEED); if (track_decs[tracks]) { - fprintf (stderr, " track: %s, decoder: %s, rate %d format %x\n", + log_add (log_Info, " track: %s, decoder: %s, rate %d format %x", *TrackNames, SoundDecoder_GetName (track_decs[tracks]), track_decs[tracks]->frequency, @@ -455,7 +454,8 @@ SpliceMultiTrack (UNICODE *TrackNames[], UNICODE *TrackText) } else { - fprintf (stderr, " couldn't load %s\n", *TrackNames); + log_add (log_Warning, "SpliceMultiTrack(): couldn't load %s\n", + *TrackNames); tracks--; } } @@ -463,7 +463,7 @@ SpliceMultiTrack (UNICODE *TrackNames[], UNICODE *TrackText) if (tracks == 0) { - fprintf (stderr, " no tracks loaded\n"); + log_add (log_Warning, "SpliceMultiTrack(): no tracks loaded"); return; } @@ -486,12 +486,6 @@ SpliceMultiTrack (UNICODE *TrackNames[], UNICODE *TrackText) } no_page_break = 1; - if (tracks > 0) - return; - else - { - fprintf (stderr, " no tracks loaded\n"); - } } void @@ -512,14 +506,14 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra if (!last_ts_chain || !last_ts_chain->text) { - fprintf (stderr, - "SpliceTrack(): Tried to append a subtitle to a NULL string\n"); + log_add (log_Warning, "SpliceTrack(): Tried to append" + " a subtitle to a NULL string"); return; } split_text = SplitSubPages (TrackText, time_stamps, &num_pages); if (! split_text) { - fprintf (stderr, "SpliceTrack(): Failed to parse sutitles\n"); + log_add (log_Warning, "SpliceTrack(): Failed to parse sutitles"); return; } oTT = (UNICODE *)last_ts_chain->text; @@ -532,7 +526,7 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra { if (! last_ts_chain->next) { - fprintf (stderr, "SpliceTrack(): More text pages than timestamps!\n"); + log_add (log_Warning, "SpliceTrack(): More text pages than timestamps!"); break; } last_ts_chain = last_ts_chain->next; @@ -552,7 +546,7 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra split_text = SplitSubPages (TrackText, time_stamps, &num_pages); if (! split_text) { - fprintf (stderr, "SpliceTrack(): Failed to parse sutitles\n"); + log_add (log_Warning, "SpliceTrack(): Failed to parse sutitles"); return; } if (no_page_break && tct) @@ -570,13 +564,14 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra else tct++; - fprintf (stderr, "SpliceTrack(): loading %s\n", TrackName); + log_add (log_Info, "SpliceTrack(): loading %s", TrackName); if (TimeStamp) { num_timestamps = GetTimeStamps (TimeStamp, time_stamps) + 1; if (num_timestamps < num_pages) - fprintf (stderr, "SpliceTrack(): number of timestamps doesn't match number of pages!\n"); + log_add (log_Warning, "SpliceTrack(): number of timestamps" + " doesn't match number of pages!"); } else num_timestamps = num_pages; @@ -615,7 +610,11 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra } startTime += abs (time_stamps[page_counter]); - // fprintf (stderr, "page (%d of %d): %d ts: %d\n",page_counter, num_pages, startTime, time_stamps[page_counter]); +#if 0 + log_add (log_Debug, "page (%d of %d): %d ts: %d", + page_counter, num_pages, + startTime, time_stamps[page_counter]); +#endif if (last_chain->decoder) { static float old_volume = 0.0f; @@ -627,13 +626,14 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra ensure proper operation of oscilloscope and music fading */ old_volume = speechVolumeScale; speechVolumeScale = 0.0f; - fprintf (stderr, "SpliceTrack(): no voice ogg available so setting speech volume to zero\n"); + log_add (log_Warning, "SpliceTrack(): no voice ogg" + " available so setting speech volume to zero"); } } else if (old_volume != 0.0f && speechVolumeScale != old_volume) { /* This time voice ogg is there */ - fprintf (stderr, "SpliceTrack(): restoring speech volume\n"); + log_add (log_Warning, "SpliceTrack(): restoring speech volume"); speechVolumeScale = old_volume; old_volume = 0.0f; } @@ -656,7 +656,7 @@ SpliceTrack (UNICODE *TrackName, UNICODE *TrackText, UNICODE *TimeStamp, TFB_Tra } else { - fprintf (stderr, "SpliceTrack(): couldn't load %s\n", TrackName); + log_add (log_Warning, "SpliceTrack(): couldn't load %s", TrackName); audio_DeleteBuffers (sound_sample->num_buffers, sound_sample->buffer); destroy_soundchain (first_chain); first_chain = NULL; @@ -848,17 +848,23 @@ GetSoundData (void *data) if (delta < 0) { - fprintf (stderr, "GetSoundData(): something's messed with timing, delta %ld\n", delta); + log_add (log_Debug, "GetSoundData(): something's messed" + " with timing, delta %ld", delta); delta = 0; } else if (delta > (int)(soundSource[SPEECH_SOURCE].sbuf_size * 2)) { - //fprintf (stderr, "GetSoundData(): something's messed with timing, delta %d\n", delta); +#if 0 + log_add (log_Debug, "GetSoundData(): something's messed" + " with timing, delta %d", delta); +#endif delta = 0; } - - //fprintf (stderr, "played_data %d total_decoded %d delta %d\n", played_data, soundSource[SPEECH_SOURCE].total_decoded, delta); - +#if 0 + log_add (log_Debug, "played_data %d total_decoded %d delta %d", + played_data, soundSource[SPEECH_SOURCE].total_decoded, + delta); +#endif pos = soundSource[SPEECH_SOURCE].sbuf_offset + delta; if (pos % 2 == 1) pos++; @@ -921,17 +927,25 @@ GetSoundData (void *data) if (delta < 0) { - //fprintf (stderr, "GetSoundData(): something's messed with timing, delta %d\n", delta); +#if 0 + log_add (log_Debug, "GetSoundData(): something's messed" + " with timing, delta %d", delta); +#endif delta = 0; } else if (delta > (int)(soundSource[MUSIC_SOURCE].sbuf_size * 2)) { - //fprintf (stderr, "GetSoundData(): something's messed with timing, delta %d\n", delta); +#if 0 + log_add (log_Debug, "GetSoundData(): something's messed" + " with timing, delta %d", delta); +#endif delta = 0; } - - //fprintf (stderr, "played_data %d total_decoded %d delta %d\n", played_data, soundSource[MUSIC_SOURCE].total_decoded, delta); - +#if 0 + log_add (log_Debug, "played_data %d total_decoded %d delta %d", + played_data, soundSource[MUSIC_SOURCE].total_decoded, + delta); +#endif pos = soundSource[MUSIC_SOURCE].sbuf_offset + delta; if (pos % 2 == 1) pos++; diff --git a/sc2/src/sc2code/libs/strings/getstr.c b/sc2/src/sc2code/libs/strings/getstr.c index 7385c145b..3cb3aeea2 100644 --- a/sc2/src/sc2code/libs/strings/getstr.c +++ b/sc2/src/sc2code/libs/strings/getstr.c @@ -20,6 +20,7 @@ #include "strintrn.h" #include "libs/graphics/gfx_common.h" #include "libs/reslib.h" +#include "libs/log.h" static void @@ -97,7 +98,7 @@ _GetStringData (uio_Stream *fp, DWORD length) if ((timestamp_fp = uio_fopen (contentDir, ts_file_name, "rb"))) { - fprintf (stderr, "Found timestamp file: %s\n", ts_file_name); + log_add (log_Info, "Found timestamp file: %s", ts_file_name); if ((ts_data = HMalloc (tot_ts_size = POOL_SIZE)) == 0) return (0); } @@ -166,8 +167,8 @@ _GetStringData (uio_Stream *fp, DWORD length) if (!ts_ok) { // timestamp data is invalid, remove all of it - fprintf (stderr, "Invalid timestamp data " - "for '%s'. Disabling timestamps\n", s); + log_add (log_Warning, "Invalid timestamp data " + "for '%s'. Disabling timestamps", s); HFree (ts_data); ts_data = NULL; uio_fclose (timestamp_fp); diff --git a/sc2/src/sc2code/libs/strings/unicode.c b/sc2/src/sc2code/libs/strings/unicode.c index 2aeda5d09..f3e9b5d7c 100644 --- a/sc2/src/sc2code/libs/strings/unicode.c +++ b/sc2/src/sc2code/libs/strings/unicode.c @@ -21,6 +21,7 @@ #include #include #include "strlib.h" +#include "libs/log.h" // Resynchronise (skip everything starting with 0x10xxxxxx): @@ -117,7 +118,7 @@ getCharFromString(const unsigned char **ptr) { } err: - fprintf(stderr, "Warning: Invalid UTF8 sequence.\n"); + log_add(log_Warning, "Warning: Invalid UTF8 sequence."); // Resynchronise (skip everything starting with 0x10xxxxxx): resyncUTF8(ptr); @@ -416,7 +417,7 @@ getStringFromChar(unsigned char *ptr, size_t size, wchar_t ch) ; if (def->mask == 0) { // invalid or unsupported char - fprintf(stderr, "Warning: Invalid or unsupported wide char (%lu)\n", + log_add(log_Warning, "Warning: Invalid or unsupported wide char (%lu)", (unsigned long)ch); return 0; } diff --git a/sc2/src/sc2code/libs/task/tasklib.c b/sc2/src/sc2code/libs/task/tasklib.c index 0a014a623..da543ba94 100644 --- a/sc2/src/sc2code/libs/task/tasklib.c +++ b/sc2/src/sc2code/libs/task/tasklib.c @@ -20,6 +20,7 @@ #include #include #include "libs/tasklib.h" +#include "libs/log.h" #define TASK_MAX 64 @@ -33,7 +34,7 @@ AssignTask (ThreadFunction task_func, SDWORD stackSize, const char *name) { if (!Task_SetState (task_array+i, TASK_INUSE)) { - // fprintf (stderr, "Assigning Task #%i: %s\n", i+1, name); + // log_add (log_Debug, "Assigning Task #%i: %s", i+1, name); Task_ClearState (task_array+i, ~TASK_INUSE); task_array[i].name = name; task_array[i].thread = CreateThread (task_func, task_array+i, @@ -41,19 +42,19 @@ AssignTask (ThreadFunction task_func, SDWORD stackSize, const char *name) return task_array+i; } } - fprintf (stderr, "Task error! Task array exhausted. Check for thread leaks.\n"); + log_add (log_Always, "Task error! Task array exhausted. Check for thread leaks."); return NULL; } void FinishTask (Task task) { - // fprintf (stderr, "Releasing Task: %s\n", task->name); + // log_add (log_Debug, "Releasing Task: %s", task->name); task->thread = 0; if (!Task_ClearState (task, TASK_INUSE)) { - fprintf (stderr, "Task error! Attempted to FinishTask \"%s\"... " - "but it was already done!\n", task->name); + log_add (log_Debug, "Task error! Attempted to FinishTask '%s'... " + "but it was already done!", task->name); } } @@ -62,7 +63,7 @@ void ConcludeTask (Task task) { Thread old = task->thread; - // fprintf (stderr, "Awaiting conclusion of %s\n", task->name); + // log_add (log_Debug, "Awaiting conclusion of %s", task->name); if (old) { Task_SetState (task, TASK_EXIT); diff --git a/sc2/src/sc2code/libs/threads/sdl/sdlthreads.c b/sc2/src/sc2code/libs/threads/sdl/sdlthreads.c index c68eb1dea..e930401d3 100644 --- a/sc2/src/sc2code/libs/threads/sdl/sdlthreads.c +++ b/sc2/src/sc2code/libs/threads/sdl/sdlthreads.c @@ -24,6 +24,7 @@ #include #include #endif +#include "libs/log.h" #if defined(PROFILE_THREADS) && !defined(WIN32) #include @@ -151,8 +152,8 @@ UnQueueThread (TrueThread thread) if (*ptr == NULL) { // Should not happen. - fprintf (stderr, "Error: Trying to remove non-present thread " - "from thread queue.\n"); + log_add (log_Debug, "Error: Trying to remove non-present thread " + "from thread queue."); fflush (stderr); abort(); } @@ -213,7 +214,7 @@ ThreadHelper (void *startInfo) { result = (*func) (data); #ifdef DEBUG_THREADS - fprintf (stderr, "Thread '%s' done (returned %d).\n", + log_add (log_Debug, "Thread '%s' done (returned %d).", thread->name, result); fflush (stderr); #endif @@ -271,8 +272,10 @@ CreateThread_SDL (ThreadFunction func, void *data, SDWORD stackSize QueueThread (thread); #ifdef DEBUG_THREADS -// fprintf (stderr, "Thread '%s' created.\n", ThreadName (thread)); -// fflush (stderr); +#if 0 + log_add (log_Debug, "Thread '%s' created.", ThreadName (thread)); + fflush (stderr); +#endif #endif // Signal to the new thread that the thread structure is ready @@ -358,11 +361,15 @@ CreateMutex_SDL (void) if ((mutex == NULL) || (mutex->mutex == NULL)) { #ifdef NAMED_SYNCHRO - fprintf (stderr, "Could not initialize mutex '%s': aborting.\n", name); + /* logging depends on Mutexes, so we have to use the + * non-threaded version instead */ + log_add_nothread (log_Always, "Could not initialize mutex '%s':" + "aborting.", name); #else - fprintf (stderr, "Could not initialize mutex: aborting.\n"); + log_add_nothread (log_Always, "Could not initialize mutex:" + "aborting."); #endif - abort (); + exit (EXIT_FAILURE); } return mutex; @@ -391,8 +398,10 @@ LockMutex_SDL (Mutex m) * CrossThreadMutex code). This almost-measure is being added * because for the most part it should suffice. */ if (mutex->owner && (mutex->syncClass & TRACK_CONTENTION_CLASSES)) - { - fprintf (stderr, "Thread '%s' blocking on mutex '%s'\n", MyThreadName (), mutex->name); + { /* logging depends on Mutexes, so we have to use the + * non-threaded version instead */ + log_add_nothread (log_Debug, "Thread '%s' blocking on mutex '%s'", + MyThreadName (), mutex->name); } #endif while (SDL_mutexP (mutex->mutex) != 0) @@ -443,11 +452,13 @@ CreateSemaphore_SDL (DWORD initial if (sem->sem == NULL) { #ifdef NAMED_SYNCHRO - fprintf (stderr, "Could not initialize semaphore '%s': aborting.\n", name); + log_add (log_Always, "Could not initialize semaphore '%s':" + " aborting.", name); #else - fprintf (stderr, "Could not initialize semaphore: aborting.\n"); + log_add (log_Always, "Could not initialize semaphore:" + " aborting."); #endif - abort (); + exit (EXIT_FAILURE); } return sem; } @@ -468,7 +479,8 @@ SetSemaphore_SDL (Semaphore s) BOOLEAN contention = !(SDL_SemValue (sem->sem)); if (contention && (sem->syncClass & TRACK_CONTENTION_CLASSES)) { - fprintf (stderr, "Thread '%s' blocking on semaphore '%s'\n", MyThreadName (), sem->name); + log_add (log_Debug, "Thread '%s' blocking on semaphore '%s'", + MyThreadName (), sem->name); } #endif while (SDL_SemWait (sem->sem) == -1) @@ -478,7 +490,8 @@ SetSemaphore_SDL (Semaphore s) #ifdef TRACK_CONTENTION if (contention && (sem->syncClass & TRACK_CONTENTION_CLASSES)) { - fprintf (stderr, "Thread '%s' awakens, released from semaphore '%s'\n", MyThreadName (), sem->name); + log_add (log_Debug, "Thread '%s' awakens," + " released from semaphore '%s'", MyThreadName (), sem->name); } #endif } @@ -520,11 +533,13 @@ CreateRecursiveMutex_SDL (void) if (mtx->mutex == NULL) { #ifdef NAMED_SYNCHRO - fprintf (stderr, "Could not initialize recursive mutex '%s': aborting.\n", name); + log_add (log_Always, "Could not initialize recursive " + "mutex '%s': aborting.", name); #else - fprintf (stderr, "Could not initialize recursive mutex: aborting.\n"); + log_add (log_Always, "Could not initialize recursive " + "mutex: aborting."); #endif - abort (); + exit (EXIT_FAILURE); } #ifdef NAMED_SYNCHRO mtx->name = name; @@ -552,7 +567,8 @@ LockRecursiveMutex_SDL (RecursiveMutex val) #ifdef TRACK_CONTENTION if (mtx->thread_id && (mtx->syncClass & TRACK_CONTENTION_CLASSES)) { - fprintf (stderr, "Thread '%s' blocking on '%s'\n", MyThreadName (), mtx->name); + log_add (log_Debug, "Thread '%s' blocking on '%s'", + MyThreadName (), mtx->name); } #endif while (SDL_mutexP (mtx->mutex)) @@ -570,7 +586,8 @@ UnlockRecursiveMutex_SDL (RecursiveMutex val) if (!mtx->locks || mtx->thread_id != thread_id) { #ifdef NAMED_SYNCHRO - fprintf (stderr, "'%s' attempted to unlock %s when it didn't hold it\n", MyThreadName (), mtx->name); + log_add (log_Debug, "'%s' attempted to unlock %s when it " + "didn't hold it", MyThreadName (), mtx->name); #endif } else @@ -613,11 +630,13 @@ CreateCondVar_SDL (void) if ((cv->cond == NULL) || (cv->mutex == NULL)) { #ifdef NAMED_SYNCHRO - fprintf (stderr, "Could not initialize condition variable '%s': aborting.\n", name); + log_add (log_Always, "Could not initialize condition variable '%s':" + " aborting.", name); #else - fprintf (stderr, "Could not initialize condition variable: aborting.\n"); + log_add (log_Always, "Could not initialize condition variable:" + " aborting."); #endif - abort (); + exit (EXIT_FAILURE); } #ifdef NAMED_SYNCHRO cv->name = name; @@ -643,7 +662,8 @@ WaitCondVar_SDL (CondVar c) #ifdef TRACK_CONTENTION if (cv->syncClass & TRACK_CONTENTION_CLASSES) { - fprintf (stderr, "Thread '%s' waiting for signal from '%s'\n", MyThreadName (), cv->name); + log_add (log_Debug, "Thread '%s' waiting for signal from '%s'", + MyThreadName (), cv->name); } #endif while (SDL_CondWait (cv->cond, cv->mutex) != 0) @@ -653,7 +673,8 @@ WaitCondVar_SDL (CondVar c) #ifdef TRACK_CONTENTION if (cv->syncClass & TRACK_CONTENTION_CLASSES) { - fprintf (stderr, "Thread '%s' received signal from '%s', awakening.\n", MyThreadName (), cv->name); + log_add (log_Debug, "Thread '%s' received signal from '%s'," + " awakening.", MyThreadName (), cv->name); } #endif SDL_mutexV (cv->mutex); diff --git a/sc2/src/sc2code/libs/threads/thrcommon.c b/sc2/src/sc2code/libs/threads/thrcommon.c index 255299b32..6acd586db 100644 --- a/sc2/src/sc2code/libs/threads/thrcommon.c +++ b/sc2/src/sc2code/libs/threads/thrcommon.c @@ -22,6 +22,7 @@ #include "libs/threadlib.h" #include "libs/timelib.h" #include "libs/misc.h" +#include "libs/log.h" #include "thrcommon.h" #define LIFECYCLE_SIZE 8 @@ -85,8 +86,8 @@ FlagStartThread (SpawnRequest s) return NULL; } } - fprintf (stderr, "Thread Lifecycle array filled. This is a fatal error! Make LIFECYCLE_SIZE something larger than %d.\n", LIFECYCLE_SIZE); - exit (-1); + log_add (log_Always, "Thread Lifecycle array filled. This is a fatal error! Make LIFECYCLE_SIZE something larger than %d.", LIFECYCLE_SIZE); + exit (EXIT_FAILURE); } void @@ -103,8 +104,8 @@ FinishThread (Thread thread) return; } } - fprintf (stderr, "Thread Lifecycle array filled. This is a fatal error! Make LIFECYCLE_SIZE something larger than %d.\n", LIFECYCLE_SIZE); - exit (-1); + log_add (log_Always, "Thread Lifecycle array filled. This is a fatal error! Make LIFECYCLE_SIZE something larger than %d.", LIFECYCLE_SIZE); + exit (EXIT_FAILURE); } /* Only call from main thread! */ diff --git a/sc2/src/sc2code/libs/video/videodec.c b/sc2/src/sc2code/libs/video/videodec.c index 377633c56..31e626fff 100644 --- a/sc2/src/sc2code/libs/video/videodec.c +++ b/sc2/src/sc2code/libs/video/videodec.c @@ -17,6 +17,7 @@ #include "video.h" #include "videodec.h" #include "dukvid.h" +#include "libs/log.h" #define MAX_REG_DECODERS 31 @@ -57,15 +58,15 @@ VideoDecoder_Init (int flags, int depth, uint32 Rmask, uint32 Gmask, if (depth < 15 || depth > 32) { - fprintf (stderr, "VideoDecoder_Init: " - "Unsupported video depth %d\n", depth); + log_add (log_Always, "VideoDecoder_Init: " + "Unsupported video depth %d", depth); return false; } if ((Rmask & Gmask) || (Rmask & Bmask) || (Rmask & Amask) || (Gmask & Bmask) || (Gmask & Amask) || (Bmask & Amask)) { - fprintf (stderr, "VideoDecoder_Init: Invalid channel masks\n"); + log_add (log_Always, "VideoDecoder_Init: Invalid channel masks"); return false; } @@ -87,8 +88,8 @@ VideoDecoder_Init (int flags, int depth, uint32 Rmask, uint32 Gmask, { if (!info->funcs->InitModule (flags)) { - fprintf (stderr, "VideoDecoder_Init(): " - "%s video decoder init failed\n", + log_add (log_Always, "VideoDecoder_Init(): " + "%s video decoder init failed", info->funcs->GetName ()); } } @@ -129,12 +130,12 @@ VideoDecoder_Register (const char* fileext, TFB_VideoDecoderFuncs* decvtbl) if (!decvtbl) { - fprintf (stderr, "VideoDecoder_Register(): Null decoder table\n"); + log_add (log_Warning, "VideoDecoder_Register(): Null decoder table"); return NULL; } if (!fileext) { - fprintf (stderr, "VideoDecoder_Register(): Bad file type for %s\n", + log_add (log_Warning, "VideoDecoder_Register(): Bad file type for %s", decvtbl->GetName ()); return NULL; } @@ -151,20 +152,20 @@ VideoDecoder_Register (const char* fileext, TFB_VideoDecoderFuncs* decvtbl) if (info >= vd_decoders + MAX_REG_DECODERS) { - fprintf (stderr, "VideoDecoder_Register(): Decoders limit reached\n"); + log_add (log_Warning, "VideoDecoder_Register(): Decoders limit reached"); return NULL; } else if (info->ext) { - fprintf (stderr, "VideoDecoder_Register(): " - "'%s' decoder already registered (%s denied)\n", + log_add (log_Warning, "VideoDecoder_Register(): " + "'%s' decoder already registered (%s denied)", fileext, decvtbl->GetName ()); return NULL; } if (!decvtbl->InitModule (vd_flags)) { - fprintf (stderr, "VideoDecoder_Register(): %s decoder init failed\n", + log_add (log_Warning, "VideoDecoder_Register(): %s decoder init failed", decvtbl->GetName ()); return NULL; } @@ -191,8 +192,8 @@ VideoDecoder_Unregister (TFB_RegVideoDecoder* regdec) if (regdec < vd_decoders || regdec >= vd_decoders + MAX_REG_DECODERS || !regdec->ext || !regdec->funcs) { - fprintf (stderr, "VideoDecoder_Unregister(): " - "Invalid or expired decoder passed\n"); + log_add (log_Warning, "VideoDecoder_Unregister(): " + "Invalid or expired decoder passed"); return; } @@ -227,7 +228,7 @@ VideoDecoder_Load (uio_DirHandle *dir, const char *filename) pext = strrchr (filename, '.'); if (!pext) { - fprintf (stderr, "VideoDecoder_Load: Unknown file type\n"); + log_add (log_Warning, "VideoDecoder_Load: Unknown file type"); return NULL; } ++pext; @@ -238,7 +239,7 @@ VideoDecoder_Load (uio_DirHandle *dir, const char *filename) ; if (!info->ext) { - fprintf (stderr, "VideoDecoder_Load: Unsupported file type\n"); + log_add (log_Warning, "VideoDecoder_Load: Unsupported file type"); return NULL; } @@ -246,8 +247,8 @@ VideoDecoder_Load (uio_DirHandle *dir, const char *filename) decoder->funcs = info->funcs; if (!decoder->funcs->Init (decoder, &vd_vidfmt)) { - fprintf (stderr, "VideoDecoder_Load: " - "Cannot init '%s' decoder, code %d\n", + log_add (log_Warning, "VideoDecoder_Load: " + "Cannot init '%s' decoder, code %d", decoder->funcs->GetName (), decoder->funcs->GetError (decoder)); HFree (decoder); @@ -261,8 +262,8 @@ VideoDecoder_Load (uio_DirHandle *dir, const char *filename) if (!decoder->funcs->Open (decoder, dir, filename)) { - fprintf (stderr, "VideoDecoder_Load: " - "'%s' decoder did not load %s, code %d\n", + log_add (log_Warning, "VideoDecoder_Load: " + "'%s' decoder did not load %s, code %d", decoder->funcs->GetName (), filename, decoder->funcs->GetError (decoder)); diff --git a/sc2/src/sc2code/libs/video/vidplayer.c b/sc2/src/sc2code/libs/video/vidplayer.c index 73deacd9b..8f7a8ab4b 100644 --- a/sc2/src/sc2code/libs/video/vidplayer.c +++ b/sc2/src/sc2code/libs/video/vidplayer.c @@ -22,7 +22,7 @@ #include "sounds.h" #include "libs/graphics/gfx_common.h" #include "libs/graphics/tfb_draw.h" - +#include "libs/log.h" // video callbacks static void* vp_GetCanvasLine (TFB_VideoDecoder*, uint32 line); @@ -324,8 +324,8 @@ TFB_PlayVideo (VIDEO_REF VidRef, uint32 x, uint32 y) if (!vid->hAudio) { - fprintf (stderr, "TFB_PlayVideo: " - "Cannot load sound-track for audio-synced video\n"); + log_add (log_Warning, "TFB_PlayVideo: " + "Cannot load sound-track for audio-synced video"); return false; } diff --git a/sc2/src/sc2code/load.c b/sc2/src/sc2code/load.c index ea3ffebbb..83bc15d09 100644 --- a/sc2/src/sc2code/load.c +++ b/sc2/src/sc2code/load.c @@ -29,7 +29,7 @@ #include "state.h" #include "libs/tasklib.h" - +#include "libs/log.h" //#define DEBUG_LOAD @@ -172,8 +172,8 @@ LoadGame (COUNT which_game, SUMMARY_DESC *summary_desc) 1 /* time to destroy all races, plenty */ + 25 /* for cheaters */) { - fprintf (stderr, "Warning: Savegame corrupt or from an " - "an incompatible platform.\n"); + log_add (log_Always, "Warning: Savegame corrupt or from an " + "an incompatible platform."); res_CloseResFile (in_fp); return FALSE; } @@ -218,7 +218,7 @@ LoadGame (COUNT which_game, SUMMARY_DESC *summary_desc) // But if it does happen, it needs to be reset to 0, since on load // the clock semaphore is gauranteed to be 0 if (GLOBAL (GameClock.TimeCounter) != 0) - fprintf (stderr, "Warning: Game clock wasn't stopped during " + log_add (log_Always, "Warning: Game clock wasn't stopped during " "save, Savegame may be corrupt!\n"); GLOBAL (GameClock.TimeCounter) = 0; @@ -230,7 +230,7 @@ LoadGame (COUNT which_game, SUMMARY_DESC *summary_desc) cread ((PBYTE)&num_links, sizeof (num_links), 1, fh); { #ifdef DEBUG_LOAD - fprintf (stderr, "EVENTS:\n"); + log_add (log_Debug, "EVENTS:"); #endif /* DEBUG_LOAD */ while (num_links--) { @@ -243,7 +243,7 @@ LoadGame (COUNT which_game, SUMMARY_DESC *summary_desc) cread ((PBYTE)EventPtr, sizeof (*EventPtr), 1, fh); #ifdef DEBUG_LOAD - fprintf (stderr, "\t%u/%u/%u -- %u\n", + log_add (log_Debug, "\t%u/%u/%u -- %u", EventPtr->month_index, EventPtr->day_index, EventPtr->year_index, diff --git a/sc2/src/sc2code/melee.c b/sc2/src/sc2code/melee.c index 9bb98c6a5..82b04cbea 100644 --- a/sc2/src/sc2code/melee.c +++ b/sc2/src/sc2code/melee.c @@ -40,6 +40,7 @@ #include "libs/gfxlib.h" #include "libs/inplib.h" #include "libs/mathlib.h" +#include "libs/log.h" #include @@ -1061,14 +1062,14 @@ GetNewList: { BOOLEAN deleteStatus; - fprintf (stderr, "Could not load '%s'\n", file); + log_add (log_Always, "Could not load '%s'", file); deleteStatus = DeleteResFile (meleeDir, file); if (deleteStatus == FALSE) { // XXX: see bug #823 - fprintf (stderr, "FATAL: Could not delete '%s'\n", file); - abort (); + log_add (log_Always, "FATAL: Could not delete '%s'", file); + exit (EXIT_FAILURE); } goto GetNewList; } diff --git a/sc2/src/sc2code/menu.c b/sc2/src/sc2code/menu.c index 2413a6036..f8e9b6bed 100644 --- a/sc2/src/sc2code/menu.c +++ b/sc2/src/sc2code/menu.c @@ -23,7 +23,7 @@ #include "gamestr.h" #include "libs/graphics/gfx_common.h" #include "libs/tasklib.h" - +#include "libs/log.h" extern Task flash_task; extern RECT flash_rect; @@ -79,7 +79,7 @@ DrawPCMenu (BYTE beg_index, BYTE end_index, BYTE NewState, BYTE hilite, RECT *r) r->extent.width += 1; DrawFilledRectangle (r); if (num_items * PC_MENU_HEIGHT > r->extent.height) - fprintf (stderr, "Warning, no room for all menu items!\n"); + log_add (log_Always, "Warning, no room for all menu items!"); else r->corner.y += (r->extent.height - num_items * PC_MENU_HEIGHT) / 2; r->extent.height = num_items * PC_MENU_HEIGHT + 4; @@ -284,7 +284,8 @@ GetAlternateMenu (BYTE *BaseState, BYTE *CurState) *CurState = PM_ALT_EXITMENU0 - PM_ALT_CARGO; return (TRUE); } - fprintf (stderr, "Unknown state combination: %d, %d\n",*BaseState, *CurState); + log_add (log_Always, "Unknown state combination: %d, %d", + *BaseState, *CurState); return (FALSE); } else diff --git a/sc2/src/sc2code/planets/calc.c b/sc2/src/sc2code/planets/calc.c index acc5d312d..4abcf57e4 100644 --- a/sc2/src/sc2code/planets/calc.c +++ b/sc2/src/sc2code/planets/calc.c @@ -19,6 +19,7 @@ /* ----------------------------- INCLUDES ---------------------------- */ #include "encount.h" #include "libs/mathlib.h" +#include "libs/log.h" /* -------------------------------- DATA -------------------------------- */ /* -------------------------------- CODE -------------------------------- */ @@ -259,10 +260,10 @@ DoPlanetaryAnalysis (SYSTEM_INFOPTR SysInfoPtr, PPLANET_DESC "Supergiant", }; - fprintf (stderr, "%s %s\n", + log_add (log_Debug, "%s %s", ColorClass[SysInfoPtr->StarIntensity], SizeName[SysInfoPtr->StarSize]); - fprintf (stderr, "Stellar Energy: %d (sol = 3)\n", + log_add (log_Debug, "Stellar Energy: %d (sol = 3)", SysInfoPtr->StarEnergy); } #endif /* DEBUG_PLANET_CALC */ @@ -344,62 +345,62 @@ DoPlanetaryAnalysis (SYSTEM_INFOPTR SysInfoPtr, PPLANET_DESC #ifdef DEBUG_PLANET_CALC radius = (SIZE)((DWORD)UNSCALE_RADIUS (radius) * 100 / UNSCALE_RADIUS (EARTH_RADIUS)); - fprintf (stderr, "\tOrbital Distance : %d.%02d AU\n", radius / 100, radius % 100); - //fprintf (stderr, "\tPlanetary Mass : %d.%02d Earth masses\n", + log_add (log_Debug, "\tOrbital Distance : %d.%02d AU", radius / 100, radius % 100); + //log_add (log_Debug, "\tPlanetary Mass : %d.%02d Earth masses", // SysInfoPtr->PlanetInfo.PlanetMass / 100, // SysInfoPtr->PlanetInfo.PlanetMass % 100); - fprintf (stderr, "\tPlanetary Radius : %d.%02d Earth radii\n", + log_add (log_Debug, "\tPlanetary Radius : %d.%02d Earth radii", SysInfoPtr->PlanetInfo.PlanetRadius / 100, SysInfoPtr->PlanetInfo.PlanetRadius % 100); - fprintf (stderr, "\tSurface Gravity: %d.%02d gravities\n", + log_add (log_Debug, "\tSurface Gravity: %d.%02d gravities", SysInfoPtr->PlanetInfo.SurfaceGravity / 100, SysInfoPtr->PlanetInfo.SurfaceGravity % 100); - fprintf (stderr, "\tSurface Temperature: %d degrees C\n", + log_add (log_Debug, "\tSurface Temperature: %d degrees C", SysInfoPtr->PlanetInfo.SurfaceTemperature ); - fprintf (stderr, "\tAxial Tilt : %d degrees\n", + log_add (log_Debug, "\tAxial Tilt : %d degrees", abs (SysInfoPtr->PlanetInfo.AxialTilt)); - fprintf (stderr, "\tTectonics : Class %u\n", + log_add (log_Debug, "\tTectonics : Class %u", SysInfoPtr->PlanetInfo.Tectonics + 1); - fprintf (stderr, "\tAtmospheric Density: %u.%02u ", + log_add (log_Debug, "\tAtmospheric Density: %u.%02u", SysInfoPtr->PlanetInfo.AtmoDensity / EARTH_ATMOSPHERE, (SysInfoPtr->PlanetInfo.AtmoDensity * 100 / EARTH_ATMOSPHERE) % 100); if (SysInfoPtr->PlanetInfo.AtmoDensity == 0) { - fprintf (stderr, "(Vacuum)\n"); + log_add (log_Debug, "\tAtmosphere: (Vacuum)"); } else if (SysInfoPtr->PlanetInfo.AtmoDensity < THIN_ATMOSPHERE) { - fprintf (stderr, "(Thin)\n"); + log_add (log_Debug, "\tAtmosphere: (Thin)"); } else if (SysInfoPtr->PlanetInfo.AtmoDensity < NORMAL_ATMOSPHERE) { - fprintf (stderr, "(Normal)\n"); + log_add (log_Debug, "\tAtmosphere: (Normal)"); } else if (SysInfoPtr->PlanetInfo.AtmoDensity < THICK_ATMOSPHERE) { - fprintf (stderr, "(Thick)\n"); + log_add (log_Debug, "\tAtmosphere: (Thick)"); } else if (SysInfoPtr->PlanetInfo.AtmoDensity < SUPER_THICK_ATMOSPHERE) { - fprintf (stderr, "(Super thick)\n"); + log_add (log_Debug, "\tAtmosphere: (Super thick)"); } else { - fprintf (stderr, "(Gas Giant atmosphere)\n"); + log_add (log_Debug, "\tAtmosphere: (Gas Giant)"); } - fprintf (stderr, "\tWeather : Class %u\n", + log_add (log_Debug, "\tWeather : Class %u", SysInfoPtr->PlanetInfo.Weather + 1); if (SysInfoPtr->PlanetInfo.RotationPeriod >= 480) { - fprintf (stderr, "\tLength of day : %d.%d Earth days\n", + log_add (log_Debug, "\tLength of day : %d.%d Earth days", SysInfoPtr->PlanetInfo.RotationPeriod / 240, SysInfoPtr->PlanetInfo.RotationPeriod % 240); } else { - fprintf (stderr, "\tLength of day : %d.%d Earth hours\n", + log_add (log_Debug, "\tLength of day : %d.%d Earth hours", SysInfoPtr->PlanetInfo.RotationPeriod / 10, SysInfoPtr->PlanetInfo.RotationPeriod % 10); } diff --git a/sc2/src/sc2code/planets/orbits.c b/sc2/src/sc2code/planets/orbits.c index e254bbf31..7cc683168 100644 --- a/sc2/src/sc2code/planets/orbits.c +++ b/sc2/src/sc2code/planets/orbits.c @@ -20,6 +20,7 @@ #include "planets/planets.h" #include "libs/compiler.h" #include "libs/mathlib.h" +#include "libs/log.h" //#define DEBUG_ORBITS @@ -506,7 +507,7 @@ char scolor[] = {'B', 'G', 'O', 'R', 'W', 'Y'}; #ifdef DEBUG_ORBITS GetClusterName (CurStarDescPtr, buf); - fprintf (stderr, "cluster name = %s color = %c type = %c\n", buf, + log_add (log_Debug, "cluster name = %s color = %c type = %c", buf, scolor[STAR_COLOR (CurStarDescPtr->Type)], stype[STAR_TYPE (CurStarDescPtr->Type)]); #endif /* DEBUG_ORBITS */ diff --git a/sc2/src/sc2code/planets/plangen.c b/sc2/src/sc2code/planets/plangen.c index b5febc30e..eaffd3e6d 100644 --- a/sc2/src/sc2code/planets/plangen.c +++ b/sc2/src/sc2code/planets/plangen.c @@ -25,12 +25,12 @@ #include "libs/graphics/gfx_common.h" #include "libs/graphics/drawable.h" #include "libs/mathlib.h" - +#include "libs/log.h" #include #include -#define PROFILE 1 +#define PROFILE_ROTATION 1 #define ROTATION_TIME 12 // The initial size of the planet when zooming. MUST BE ODD @@ -748,7 +748,7 @@ RenderLevelMasks (FRAME MaskFrame, int offset, BOOLEAN doThrob) SBYTE *elevs; int shLevel; -#if PROFILE +#if PROFILE_ROTATION static clock_t t = 0; static int frames_done = 1; clock_t t1; @@ -851,11 +851,12 @@ RenderLevelMasks (FRAME MaskFrame, int offset, BOOLEAN doThrob) process_rgb_bmp (MaskFrame, rgba, DIAMETER, DIAMETER); SetFrameHot (MaskFrame, MAKE_HOT_SPOT (RADIUS + 1, RADIUS + 1)); -#if PROFILE +#if PROFILE_ROTATION t += clock() - t1; if (frames_done == MAP_WIDTH) { - fprintf (stderr, "frames/sec: %d/%ld(msec)=%f\n", frames_done, + log_add (log_Debug, "Rotation frames/sec: %d/%ld(msec)=%f", + frames_done, (long int) (((double)t / CLOCKS_PER_SEC) * 1000.0 + 0.5), frames_done / ((double)t / CLOCKS_PER_SEC + 0.5)); frames_done = 1; @@ -2121,8 +2122,8 @@ rotate_planet_task (void *data) frame_num++; if (frame_num > zoom_frames) { - fprintf (stderr, "rotate_planet_task() : zoom frame " - "out of bounds!\n"); + log_add (log_Warning, "rotate_planet_task() : zoom frame" + " out of bounds!"); frame_num = zoom_frames; } zoom_amt = zoom_arr[frame_num]; diff --git a/sc2/src/sc2code/planets/solarsys.c b/sc2/src/sc2code/planets/solarsys.c index 973d44562..07537ed32 100644 --- a/sc2/src/sc2code/planets/solarsys.c +++ b/sc2/src/sc2code/planets/solarsys.c @@ -34,6 +34,7 @@ #include "libs/graphics/gfx_common.h" #include "libs/mathlib.h" #include "libs/inplib.h" +#include "libs/log.h" //#define DEBUG_SOLARSYS @@ -390,7 +391,8 @@ FreeSolarSys (void) { if (pSolarSysState->MenuState.flash_task != (Task)(~0)) { - fprintf (stderr, "DIAGNOSTIC: FreeSolarSys cancels a flash_task that wasn't the placeholder for IP flight\n"); + log_add (log_Warning, "DIAGNOSTIC: FreeSolarSys cancels a " + "flash_task that wasn't the placeholder for IP flight"); ConcludeTask (pSolarSysState->MenuState.flash_task); } pSolarSysState->MenuState.flash_task = 0; @@ -445,7 +447,10 @@ CheckIntersect (BOOLEAN just_checking) { PlanetOffset = pCurDesc - pSolarSysState->PlanetDesc + 1; MoonOffset = 1; -//fprintf (stderr, "0: Planet %d, Moon %d\n", PlanetOffset, MoonOffset); +#ifdef DEBUG_SOLARSYS + log_add (log_Debug, "0: Planet %d, Moon %d", PlanetOffset, + MoonOffset); +#endif /* DEBUG_SOLARSYS */ NewWaitPlanet = MAKE_WORD (PlanetOffset, MoonOffset); if (pSolarSysState->WaitIntersect != (COUNT)~0 && pSolarSysState->WaitIntersect != NewWaitPlanet) @@ -461,7 +466,7 @@ ShowPlanet: } #ifdef DEBUG_SOLARSYS - fprintf (stderr, "Star index = %d, Planet index = %d, <%d, %d>\n", + log_add (log_Debug, "Star index = %d, Planet index = %d, <%d, %d>", CurStarDescPtr - star_array, pCurDesc - pSolarSysState->PlanetDesc, pSolarSysState->SunDesc[0].location.x, @@ -499,7 +504,10 @@ ShowPlanet: if (DrawablesIntersect (&ShipIntersect, &PlanetIntersect, MAX_TIME_VALUE)) { -// fprintf (stderr, "1: Planet %d, Moon %d\n", PlanetOffset, MoonOffset); +#ifdef DEBUG_SOLARSYS + log_add (log_Debug, "1: Planet %d, Moon %d", PlanetOffset, + MoonOffset); +#endif /* DEBUG_SOLARSYS */ NewWaitPlanet = MAKE_WORD (PlanetOffset, MoonOffset); if (pSolarSysState->WaitIntersect == (COUNT)~0) @@ -1594,11 +1602,11 @@ GenerateRandomIP (BYTE control) #ifdef DEBUG_SOLARSYS if (pSolarSysState->pOrbitalDesc->pPrevDesc == pSolarSysState->SunDesc) - fprintf (stderr, "Planet index = %d\n", + log_add (log_Debug, "Planet index = %d", pSolarSysState->pOrbitalDesc - pSolarSysState->PlanetDesc); else - fprintf (stderr, "Planet index = %d, Moon index = %d\n", + log_add (log_Debug, "Planet index = %d, Moon index = %d", pSolarSysState->pOrbitalDesc->pPrevDesc - pSolarSysState->PlanetDesc, pSolarSysState->pOrbitalDesc - diff --git a/sc2/src/sc2code/planets/surface.c b/sc2/src/sc2code/planets/surface.c index 453449c60..efe6a6506 100644 --- a/sc2/src/sc2code/planets/surface.c +++ b/sc2/src/sc2code/planets/surface.c @@ -19,6 +19,7 @@ #include "lifeform.h" #include "planets.h" #include "libs/mathlib.h" +#include "libs/log.h" //#define DEBUG_SURFACE @@ -77,7 +78,7 @@ CalcMineralDeposits (SYSTEM_INFOPTR SysInfoPtr, COUNT which_deposit) ); SysInfoPtr->PlanetInfo.CurType = eptr->ElementType; #ifdef DEBUG_SURFACE - fprintf (stderr, "\t\t%d units of %Fs\n", + log_add (log_Debug, "\t\t%d units of %Fs", SysInfoPtr->PlanetInfo.CurDensity, Elements[eptr->ElementType].name); #endif /* DEBUG_SURFACE */ @@ -241,7 +242,7 @@ CalcLifeForms (SYSTEM_INFOPTR SysInfoPtr, COUNT which_life) } #ifdef DEBUG_SURFACE else - fprintf (stderr, "It's dead, Jim! (%d >= %d)\n", life_var, + log_add (log_Debug, "It's dead, Jim! (%d >= %d)", life_var, SysInfoPtr->PlanetInfo.LifeChance); #endif /* DEBUG_SURFACE */ } diff --git a/sc2/src/sc2code/process.c b/sc2/src/sc2code/process.c index b66358aef..14edd9a11 100644 --- a/sc2/src/sc2code/process.c +++ b/sc2/src/sc2code/process.c @@ -27,7 +27,7 @@ #include "libs/graphics/drawable.h" #include "libs/graphics/drawcmd.h" #include "libs/graphics/gfx_common.h" - +#include "libs/log.h" //#define DEBUG_PROCESS @@ -198,7 +198,7 @@ CalcReduction (SIZE dx, SIZE dy) COUNT next_reduction; #ifdef KDEBUG - fprintf (stderr, "CalcReduction:\n"); + log_add (log_Debug, "CalcReduction:"); #endif if (optMeleeScale == TFB_SCALE_STEP) @@ -263,7 +263,7 @@ CalcReduction (SIZE dx, SIZE dy) } #ifdef KDEBUG - fprintf (stderr, "CalcReduction: exit\n"); + log_add (log_Debug, "CalcReduction: exit"); #endif return (next_reduction); @@ -277,7 +277,7 @@ CalcView (PPOINT pNewScrollPt, SIZE next_reduction, VIEW_STATE view_state; #ifdef KDEBUG - fprintf (stderr, "CalcView:\n"); + log_add (log_Debug, "CalcView:"); #endif dx = ((COORD)(LOG_SPACE_WIDTH >> 1) - pNewScrollPt->x); dy = ((COORD)(LOG_SPACE_HEIGHT >> 1) - pNewScrollPt->y); @@ -340,7 +340,7 @@ CalcView (PPOINT pNewScrollPt, SIZE next_reduction, *pdy = dy; #ifdef KDEBUG - fprintf (stderr, "CalcView: exit\n"); + log_add (log_Debug, "CalcView: exit"); #endif return (view_state); } @@ -388,7 +388,7 @@ ProcessCollisions (HELEMENT hSuccElement, ELEMENTPTR ElementPtr, && !((state_flags | test_state_flags) & FINITE_LIFE)) { #ifdef DEBUG_PROCESS - fprintf (stderr, "BAD NEWS 0x%x <--> 0x%x\n", ElementPtr, + log_add (log_Debug, "BAD NEWS 0x%x <--> 0x%x", ElementPtr, TestElementPtr); #endif /* DEBUG_PROCESS */ if (state_flags & COLLISION) @@ -510,7 +510,7 @@ ProcessCollisions (HELEMENT hSuccElement, ELEMENTPTR ElementPtr, POINT SavePt, TestSavePt; #ifdef DEBUG_PROCESS - fprintf (stderr, "0x%x <--> 0x%x at %u\n", ElementPtr, + log_add (log_Debug, "0x%x <--> 0x%x at %u", ElementPtr, TestElementPtr, time_val); #endif /* DEBUG_PROCESS */ SavePt = ElementPtr->IntersectControl.EndPoint; @@ -532,7 +532,7 @@ ProcessCollisions (HELEMENT hSuccElement, ELEMENTPTR ElementPtr, test_state_flags = TestElementPtr->state_flags; #ifdef DEBUG_PROCESS - fprintf (stderr, "PROCESSING 0x%x <--> 0x%x at %u\n", + log_add (log_Debug, "PROCESSING 0x%x <--> 0x%x at %u", ElementPtr, TestElementPtr, time_val); #endif /* DEBUG_PROCESS */ if (test_state_flags & PLAYER_SHIP) @@ -625,7 +625,7 @@ PreProcessQueue (PSIZE pscroll_x, PSIZE pscroll_y) COUNT ships_alive; #ifdef KDEBUG - fprintf (stderr, "PreProcess:\n"); + log_add (log_Debug, "PreProcess:"); #endif num_ships = (LOBYTE (battle_counter) ? 1 : 0) + (HIBYTE (battle_counter) ? 1 : 0); @@ -710,7 +710,7 @@ PreProcessQueue (PSIZE pscroll_x, PSIZE pscroll_y) || reduction < min_reduction) min_reduction = reduction; } -// fprintf (stderr, "dx = %d dy = %d min_red = %d max_red = %d\n", +// log_add (log_Debug, "dx = %d dy = %d min_red = %d max_red = %d", // dx, dy, min_reduction, max_reduction); } @@ -729,7 +729,7 @@ PreProcessQueue (PSIZE pscroll_x, PSIZE pscroll_y) } #ifdef KDEBUG - fprintf (stderr, "PreProcess: exit\n"); + log_add (log_Debug, "PreProcess: exit"); #endif return (CalcView (&Origin, min_reduction, pscroll_x, pscroll_y, ships_alive)); } @@ -793,7 +793,7 @@ PostProcessQueue (VIEW_STATE view_state, SIZE scroll_x, HELEMENT hElement; #ifdef KDEBUG - fprintf (stderr, "PostProcess:\n"); + log_add (log_Debug, "PostProcess:"); #endif if (optMeleeScale == TFB_SCALE_STEP) reduction = zoom_out + ONE_SHIFT; @@ -976,7 +976,7 @@ PostProcessQueue (VIEW_STATE view_state, SIZE scroll_x, hElement = hNextElement; } #ifdef KDEBUG - fprintf (stderr, "PostProcess: exit\n"); + log_add (log_Debug, "PostProcess: exit"); #endif } diff --git a/sc2/src/sc2code/save.c b/sc2/src/sc2code/save.c index 9b413a7b9..9276821a5 100644 --- a/sc2/src/sc2code/save.c +++ b/sc2/src/sc2code/save.c @@ -32,6 +32,7 @@ #include "state.h" #include "util.h" #include "libs/inplib.h" +#include "libs/log.h" static void @@ -321,11 +322,13 @@ RetrySave: mem_release (h); FreeSC2Data (); -// fprintf (stderr, "Insufficient room for save buffers -- RETRYING\n"); + log_add (log_Debug, "Insufficient room for save buffers" + " -- RETRYING"); goto RetrySave; } -// else -// fprintf (stderr, "Insufficient room for save buffers -- GIVING UP!\n"); + else + log_add (log_Debug, "Insufficient room for save buffers" + " -- GIVING UP!"); } else { @@ -481,7 +484,8 @@ RetrySave: // Write the memory file to the actual savegame file. sprintf (file, "starcon2.%02u", which_game); -// fprintf (stderr, "'%s' is %lu bytes long\n", file, flen + sizeof (*summary_desc)); + log_add (log_Debug, "'%s' is %lu bytes long", file, + flen + sizeof (*summary_desc)); if (flen && (out_fp = (PVOID)res_OpenResFile (saveDir, file, "wb"))) { PrepareSummary (summary_desc); diff --git a/sc2/src/sc2code/setup.c b/sc2/src/sc2code/setup.c index b7bf44b52..8616d01db 100644 --- a/sc2/src/sc2code/setup.c +++ b/sc2/src/sc2code/setup.c @@ -32,6 +32,7 @@ #include "libs/graphics/gfx_common.h" #include "libs/threadlib.h" #include "libs/vidlib.h" +#include "libs/log.h" #include #include @@ -238,8 +239,9 @@ initIO (void) repository = uio_openRepository (0); rootDir = uio_openDir (repository, "/", 0); - if (rootDir == NULL) { - fprintf(stderr, "Could not open '/' dir.\n"); + if (rootDir == NULL) + { + log_add (log_Always, "Could not open '/' dir."); return -1; } return 0; @@ -253,5 +255,3 @@ uninitIO (void) uio_unInit (); } - - diff --git a/sc2/src/sc2code/setupmenu.c b/sc2/src/sc2code/setupmenu.c index f18cb0d33..589afbcc7 100644 --- a/sc2/src/sc2code/setupmenu.c +++ b/sc2/src/sc2code/setupmenu.c @@ -30,6 +30,7 @@ #include "libs/reslib.h" #include "libs/sound/sound.h" #include "libs/resource/stringbank.h" +#include "libs/log.h" #include "resinst.h" #include "nameref.h" @@ -425,8 +426,8 @@ init_widgets (void) if (count < 3) { - fprintf (stderr, "PANIC: Setup string table too short to even hold all indices!\n"); - exit (1); + log_add (log_Always, "PANIC: Setup string table too short to even hold all indices!"); + exit (EXIT_FAILURE); } /* Menus */ @@ -434,8 +435,8 @@ init_widgets (void) if (SplitString (GetStringAddress (SetAbsStringTableIndex (SetupTab, 1)), '\n', 100, buffer, bank) != MENU_COUNT) { /* TODO: Ignore extras instead of dying. */ - fprintf (stderr, "PANIC: Incorrect number of Menu Subtitles\n"); - exit (1); + log_add (log_Always, "PANIC: Incorrect number of Menu Subtitles"); + exit (EXIT_FAILURE); } for (i = 0; i < MENU_COUNT; i++) @@ -460,8 +461,8 @@ init_widgets (void) if (SplitString (GetStringAddress (SetAbsStringTableIndex (SetupTab, 2)), '\n', 100, buffer, bank) != CHOICE_COUNT) { /* TODO: Ignore extras instead of dying. */ - fprintf (stderr, "PANIC: Incorrect number of Choice Options\n"); - exit (1); + log_add (log_Always, "PANIC: Incorrect number of Choice Options"); + exit (EXIT_FAILURE); } for (i = 0; i < CHOICE_COUNT; i++) @@ -488,8 +489,8 @@ init_widgets (void) if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading choices\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading choices"); + exit (EXIT_FAILURE); } str = GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)); optcount = SplitString (str, '\n', 100, buffer, bank); @@ -508,8 +509,8 @@ init_widgets (void) if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading choices\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading choices"); + exit (EXIT_FAILURE); } str = GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)); tipcount = SplitString (str, '\n', 100, buffer, bank); @@ -530,15 +531,15 @@ init_widgets (void) /* Sliders */ if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading sliders\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading sliders"); + exit (EXIT_FAILURE); } if (SplitString (GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)), '\n', 100, buffer, bank) != SLIDER_COUNT) { /* TODO: Ignore extras instead of dying. */ - fprintf (stderr, "PANIC: Incorrect number of Slider Options\n"); - exit (1); + log_add (log_Always, "PANIC: Incorrect number of Slider Options"); + exit (EXIT_FAILURE); } for (i = 0; i < SLIDER_COUNT; i++) @@ -566,8 +567,8 @@ init_widgets (void) if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading sliders\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading sliders"); + exit (EXIT_FAILURE); } str = GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)); tipcount = SplitString (str, '\n', 100, buffer, bank); @@ -584,15 +585,15 @@ init_widgets (void) /* Buttons */ if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading buttons\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading buttons"); + exit (EXIT_FAILURE); } if (SplitString (GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)), '\n', 100, buffer, bank) != BUTTON_COUNT) { /* TODO: Ignore extras instead of dying. */ - fprintf (stderr, "PANIC: Incorrect number of Button Options\n"); - exit (1); + log_add (log_Always, "PANIC: Incorrect number of Button Options"); + exit (EXIT_FAILURE); } for (i = 0; i < BUTTON_COUNT; i++) @@ -615,8 +616,8 @@ init_widgets (void) if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading buttons\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading buttons"); + exit (EXIT_FAILURE); } str = GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)); tipcount = SplitString (str, '\n', 100, buffer, bank); @@ -633,15 +634,15 @@ init_widgets (void) /* Labels */ if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading labels\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading labels"); + exit (EXIT_FAILURE); } if (SplitString (GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)), '\n', 100, buffer, bank) != LABEL_COUNT) { /* TODO: Ignore extras instead of dying. */ - fprintf (stderr, "PANIC: Incorrect number of Label Options\n"); - exit (1); + log_add (log_Always, "PANIC: Incorrect number of Label Options"); + exit (EXIT_FAILURE); } for (i = 0; i < LABEL_COUNT; i++) @@ -662,8 +663,8 @@ init_widgets (void) if (index >= count) { - fprintf (stderr, "PANIC: String table cut short while reading labels\n"); - exit (1); + log_add (log_Always, "PANIC: String table cut short while reading labels"); + exit (EXIT_FAILURE); } str = GetStringAddress (SetAbsStringTableIndex (SetupTab, index++)); linecount = SplitString (str, '\n', 100, buffer, bank); @@ -678,7 +679,8 @@ init_widgets (void) /* Check for garbage at the end */ if (index < count) { - fprintf (stderr, "WARNING: Setup strings had %d garbage entries at the end.\n", count - index); + log_add (log_Warning, "WARNING: Setup strings had %d garbage entries at the end.", + count - index); } } @@ -737,8 +739,8 @@ SetupMenu (void) } else { - fprintf (stderr, "PANIC: Could not find strings for the setup menu!\n"); - exit (1); + log_add (log_Always, "PANIC: Could not find strings for the setup menu!"); + exit (EXIT_FAILURE); } done = FALSE; diff --git a/sc2/src/sc2code/sis.c b/sc2/src/sc2code/sis.c index e5d237fd7..f63f225db 100644 --- a/sc2/src/sc2code/sis.c +++ b/sc2/src/sc2code/sis.c @@ -26,6 +26,7 @@ #include "state.h" #include "libs/graphics/gfx_common.h" #include "libs/tasklib.h" +#include "libs/log.h" #include @@ -1542,7 +1543,7 @@ SetFlashRect (PRECT pRect, FRAME f) flash_screen_frame = 0; } else - fprintf (stderr, "couldn't locate flash_screen_rect\n"); + log_add (log_Always, "Couldn't locate flash_screen_rect"); } if (flash_rect.extent.width) diff --git a/sc2/src/sc2code/starcon.c b/sc2/src/sc2code/starcon.c index e5105a170..fe7586043 100644 --- a/sc2/src/sc2code/starcon.c +++ b/sc2/src/sc2code/starcon.c @@ -33,6 +33,7 @@ #include "starcon.h" #include "uqmdebug.h" #include "libs/tasklib.h" +#include "libs/log.h" // Open or close the periodically occuring QuasiSpace portal. @@ -140,7 +141,7 @@ while (--ac > 0) if (LoadKernel (0,0)) { - fprintf (stderr, "We've loaded the Kernel\n"); + log_add (log_Info, "We've loaded the Kernel"); Logo (); @@ -274,7 +275,7 @@ while (--ac > 0) } else { - fprintf (stderr, "Kernel failed to load!\n"); + log_add (log_Always, "Kernel failed to load!"); } FreeKernel (); diff --git a/sc2/src/sc2code/state.c b/sc2/src/sc2code/state.c index 333eacc7f..d9003a878 100644 --- a/sc2/src/sc2code/state.c +++ b/sc2/src/sc2code/state.c @@ -20,6 +20,7 @@ #include "encount.h" #include "libs/misc.h" +#include "libs/log.h" #ifdef HAVE_UNISTD_H #include #endif @@ -58,8 +59,8 @@ OpenStateFile (int stateFile, const char *mode) fp = &state_files[stateFile]; fp->open_count++; if (fp->open_count > 1) - fprintf (stderr, "WARNING: " - "State file %s open count is %d after open()\n", + log_add (log_Warning, "WARNING: " + "State file %s open count is %d after open()", fp->symname, fp->open_count); if (!fp->data) @@ -85,8 +86,8 @@ OpenStateFile (int stateFile, const char *mode) } else { - fprintf (stderr, "WARNING: " - "State file %s opened with unsupported mode '%s'\n", + log_add (log_Warning, "WARNING: " + "State file %s opened with unsupported mode '%s'", fp->symname, mode); } fp->ptr = 0; @@ -100,8 +101,8 @@ CloseStateFile (GAME_STATE_FILE *fp) fp->ptr = 0; fp->open_count--; if (fp->open_count < 0) - fprintf (stderr, "WARNING: " - "State file %s open count is %d after close()\n", + log_add (log_Warning, "WARNING: " + "State file %s open count is %d after close()", fp->symname, fp->open_count); // Erm, Ok, it's closed! Honest! } @@ -116,8 +117,8 @@ DeleteStateFile (int stateFile) fp = &state_files[stateFile]; if (fp->open_count != 0) - fprintf (stderr, "WARNING: " - "State file %s open count is %d during delete()\n", + log_add (log_Warning, "WARNING: " + "State file %s open count is %d during delete()", fp->symname, fp->open_count); fp->used = 0; diff --git a/sc2/src/starcon2.c b/sc2/src/starcon2.c index c493fb15e..1d6ea9815 100644 --- a/sc2/src/starcon2.c +++ b/sc2/src/starcon2.c @@ -34,6 +34,7 @@ #include "file.h" #include "port.h" #include "libs/platform.h" +#include "libs/log.h" #include "options.h" #include "uqmversion.h" #include "comm.h" @@ -127,8 +128,10 @@ main (int argc, char *argv[]) /* .sfxVolumeScale = */ 1.0f, /* .speechVolumeScale = */ 1.0f, }; - int optionsResult; + + log_init (15); + optionsResult = preParseOptions(argc, argv, &options); if (optionsResult != 0) { @@ -141,19 +144,20 @@ main (int argc, char *argv[]) int i; freopen (options.logFile, "w", stderr); for (i = 0; i < argc; ++i) - fprintf (stderr, "argv[%d] = [%s]\n", i, argv[i]); + log_add (log_Always, "argv[%d] = [%s]", i, argv[i]); } if (options.runMode == runMode_version) { printf ("%d.%d.%d%s\n", UQM_MAJOR_VERSION, UQM_MINOR_VERSION, UQM_PATCH_VERSION, UQM_EXTRA_VERSION); + log_showBox (false, false); return EXIT_SUCCESS; } - fprintf (stderr, "The Ur-Quan Masters v%d.%d.%d%s (compiled %s %s)\n" + log_add (log_Always, "The Ur-Quan Masters v%d.%d.%d%s (compiled %s %s)\n" "This software comes with ABSOLUTELY NO WARRANTY;\n" - "for details see the included 'COPYING' file.\n\n", + "for details see the included 'COPYING' file.\n", UQM_MAJOR_VERSION, UQM_MINOR_VERSION, UQM_PATCH_VERSION, UQM_EXTRA_VERSION, __DATE__, __TIME__); @@ -161,6 +165,7 @@ main (int argc, char *argv[]) if (options.runMode == runMode_usage) { usage (stdout, &options); + log_showBox (true, false); return EXIT_SUCCESS; } @@ -171,6 +176,7 @@ main (int argc, char *argv[]) TFB_PreInit (); mem_init (); InitThreadSystem (); + log_initThreads (); initIO (); prepareConfigDir (options.configDir); @@ -319,7 +325,7 @@ main (int argc, char *argv[]) /* This is an unsigned, so no < 0 check is necessary */ if (PlayerOne >= NUM_TEMPLATES) { - fprintf (stderr, "Illegal control template '%d' for Player One.\n", PlayerOne); + log_add (log_Always, "Illegal control template '%d' for Player One.", PlayerOne); PlayerOne = CONTROL_TEMPLATE_KB_1; } } @@ -329,7 +335,7 @@ main (int argc, char *argv[]) PlayerTwo = res_GetInteger ("config.player2control"); if (PlayerTwo >= NUM_TEMPLATES) { - fprintf (stderr, "Illegal control template '%d' for Player Two.\n", PlayerTwo); + log_add (log_Always, "Illegal control template '%d' for Player Two.", PlayerTwo); PlayerTwo = CONTROL_TEMPLATE_KB_2; } } @@ -415,7 +421,8 @@ main (int argc, char *argv[]) unInitTempDir (); uninitIO (); - exit (EXIT_SUCCESS); + + return EXIT_SUCCESS; } enum @@ -511,7 +518,7 @@ preParseOptions(int argc, char *argv[], struct options_struct *options) static int parseOptions(int argc, char *argv[], struct options_struct *options) { - int optionIndex = 0; + int optionIndex; BOOLEAN badArg = FALSE; options->addons = HMalloc(1 * sizeof (const char *)); @@ -520,13 +527,14 @@ parseOptions(int argc, char *argv[], struct options_struct *options) if (argc == 0) { - fprintf (stderr, "Error: Bad command line.\n"); + log_add (log_Always, "Error: Bad command line."); return EXIT_FAILURE; } while (!badArg) { int c; + optionIndex = -1; c = getopt_long(argc, argv, optString, longOptions, &optionIndex); if (c == -1) break; @@ -537,8 +545,8 @@ parseOptions(int argc, char *argv[], struct options_struct *options) int width, height; if (sscanf (optarg, "%dx%d", &width, &height) != 2) { - fprintf (stderr, "Error: invalid argument specified " - "as resolution.\n"); + log_add (log_Always, "Error: invalid argument specified " + "as resolution."); badArg = TRUE; break; } @@ -646,7 +654,7 @@ parseOptions(int argc, char *argv[], struct options_struct *options) case 'm': { if (Check_PC_3DO_opt (optarg, OPT_PC | OPT_3DO, - longOptions[optionIndex].name, + optionIndex >= 0 ? longOptions[optionIndex].name : "m", &options->whichMusic) == -1) badArg = TRUE; break; @@ -668,7 +676,7 @@ parseOptions(int argc, char *argv[], struct options_struct *options) case 'i': { if (Check_PC_3DO_opt (optarg, OPT_PC | OPT_3DO, - longOptions[optionIndex].name, + optionIndex >= 0 ? longOptions[optionIndex].name : "i", &options->whichIntro) == -1) badArg = TRUE; break; @@ -715,8 +723,8 @@ parseOptions(int argc, char *argv[], struct options_struct *options) } else { - fprintf (stderr, "Error: Invalid sound driver " - "specified.\n"); + log_add (log_Always, "Error: Invalid sound driver " + "specified."); badArg = TRUE; } break; @@ -747,7 +755,7 @@ parseOptions(int argc, char *argv[], struct options_struct *options) } break; default: - fprintf (stderr, "Error: Invalid option '%s' not found.\n", + log_add (log_Always, "Error: Invalid option '%s' not found.", longOptions[optionIndex].name); badArg = TRUE; break; @@ -756,14 +764,14 @@ parseOptions(int argc, char *argv[], struct options_struct *options) if (optind != argc) { - fprintf (stderr, "\nError: Extra arguments found on the command " - "line.\n"); + log_add (log_Always, "\nError: Extra arguments found on the command " + "line."); badArg = TRUE; } if (badArg) { - fprintf (stderr, "Run with -h to see the allowed arguments.\n"); + log_add (log_Always, "Run with -h to see the allowed arguments."); return EXIT_FAILURE; } @@ -778,14 +786,14 @@ parseVolume (const char *str, float *vol, const char *optName) if (str[0] == '\0') { - fprintf (stderr, "Error: Invalid value for '%s'.\n", optName); + log_add (log_Always, "Error: Invalid value for '%s'.", optName); return -1; } intVol = (int) strtol(str, &endPtr, 10); if (*endPtr != '\0') { - fprintf (stderr, "Error: Junk characters in volume specified " - "for '%s'.\n", optName); + log_add (log_Always, "Error: Junk characters in volume specified " + "for '%s'.", optName); return -1; } @@ -813,13 +821,13 @@ parseIntOption (const char *str, int *result, const char *optName) if (str[0] == '\0') { - fprintf (stderr, "Error: Invalid value for '%s'.\n", optName); + log_add (log_Always, "Error: Invalid value for '%s'.", optName); return -1; } temp = (int) strtol(str, &endPtr, 10); if (*endPtr != '\0') { - fprintf (stderr, "Error: Junk characters in argument '%s'.\n", + log_add (log_Always, "Error: Junk characters in argument '%s'.", optName); return -1; } @@ -836,13 +844,13 @@ parseFloatOption (const char *str, float *f, const char *optName) if (str[0] == '\0') { - fprintf (stderr, "Error: Invalid value for '%s'.\n", optName); + log_add (log_Always, "Error: Invalid value for '%s'.", optName); return -1; } temp = (float) strtod(str, &endPtr); if (*endPtr != '\0') { - fprintf (stderr, "Error: Junk characters in argument '%s'.\n", + log_add (log_Always, "Error: Junk characters in argument '%s'.", optName); return -1; } @@ -854,62 +862,67 @@ parseFloatOption (const char *str, float *f, const char *optName) static void usage (FILE *out, const struct options_struct *defaultOptions) { - fprintf (out, "Options:\n"); - fprintf (out, " -r, --res=WIDTHxHEIGHT (default 640x480, bigger " - "works only with --opengl)\n"); - fprintf (out, " -f, --fullscreen (default off)\n"); - fprintf (out, " -o, --opengl (default off)\n"); - fprintf (out, " -c, --scale=MODE (bilinear, biadapt, biadv, triscan, " - "hq or none (default) )\n"); - fprintf (out, " -b, --meleezoom=MODE (step, aka pc, or smooth, aka 3do; " - "default is 3do)\n"); - fprintf (out, " -s, --scanlines (default off)\n"); - fprintf (out, " -p, --fps (default off)\n"); - fprintf (out, " -g, --gamma=CORRECTIONVALUE (default 1.0, which " - "causes no change)\n"); - fprintf (out, " -C, --configdir=CONFIGDIR\n"); - fprintf (out, " -n, --contentdir=CONTENTDIR\n"); - fprintf (out, " -M, --musicvol=VOLUME (0-100, default 100)\n"); - fprintf (out, " -S, --sfxvol=VOLUME (0-100, default 100)\n"); - fprintf (out, " -T, --speechvol=VOLUME (0-100, default 100)\n"); - fprintf (out, " -q, --audioquality=QUALITY (high, medium or low, " - "default medium)\n"); - fprintf (out, " -u, --nosubtitles\n"); - fprintf (out, " -l, --logfile=FILE (sends console output to logfile " - "FILE)\n"); - fprintf (out, " --addon ADDON (using a specific addon; " - "may be specified multiple times)\n"); - fprintf (out, " --sound=DRIVER (openal, mixsdl, none; default " - "mixsdl)\n"); - fprintf (out, " --stereosfx (enables positional sound effects, " - "currently only for openal)\n"); - fprintf (out, "The following options can take either '3do' or 'pc' " - "as an option:\n"); - fprintf (out, " -m, --music : Music version (default %s)\n", + FILE *old = log_setOutput (out); + log_captureLines (LOG_CAPTURE_ALL); + + log_add (log_Always, "Options:"); + log_add (log_Always, " -r, --res=WIDTHxHEIGHT (default 640x480, bigger " + "works only with --opengl)"); + log_add (log_Always, " -f, --fullscreen (default off)"); + log_add (log_Always, " -o, --opengl (default off)"); + log_add (log_Always, " -c, --scale=MODE (bilinear, biadapt, biadv, triscan, " + "hq or none (default) )"); + log_add (log_Always, " -b, --meleezoom=MODE (step, aka pc, or smooth, aka 3do; " + "default is 3do)"); + log_add (log_Always, " -s, --scanlines (default off)"); + log_add (log_Always, " -p, --fps (default off)"); + log_add (log_Always, " -g, --gamma=CORRECTIONVALUE (default 1.0, which " + "causes no change)"); + log_add (log_Always, " -C, --configdir=CONFIGDIR"); + log_add (log_Always, " -n, --contentdir=CONTENTDIR"); + log_add (log_Always, " -M, --musicvol=VOLUME (0-100, default 100)"); + log_add (log_Always, " -S, --sfxvol=VOLUME (0-100, default 100)"); + log_add (log_Always, " -T, --speechvol=VOLUME (0-100, default 100)"); + log_add (log_Always, " -q, --audioquality=QUALITY (high, medium or low, " + "default medium)"); + log_add (log_Always, " -u, --nosubtitles"); + log_add (log_Always, " -l, --logfile=FILE (sends console output to logfile " + "FILE)"); + log_add (log_Always, " --addon ADDON (using a specific addon; " + "may be specified multiple times)"); + log_add (log_Always, " --sound=DRIVER (openal, mixsdl, none; default " + "mixsdl)"); + log_add (log_Always, " --stereosfx (enables positional sound effects, " + "currently only for openal)"); + log_add (log_Always, "The following options can take either '3do' or 'pc' " + "as an option:"); + log_add (log_Always, " -m, --music : Music version (default %s)", PC_3DO_optString(defaultOptions->whichMusic)); - fprintf (out, " -i, --intro : Intro/ending version (default %s)\n", + log_add (log_Always, " -i, --intro : Intro/ending version (default %s)", PC_3DO_optString(defaultOptions->whichIntro)); - fprintf (out, " --cscan : coarse-scan display, pc=text, " - "3do=hieroglyphs (default %s)\n", + log_add (log_Always, " --cscan : coarse-scan display, pc=text, " + "3do=hieroglyphs (default %s)", PC_3DO_optString(defaultOptions->whichCoarseScan)); - fprintf (out, " --menu : menu type, pc=text, 3do=graphical " - "(default %s)\n", PC_3DO_optString(defaultOptions->whichMenu)); - fprintf (out, " --font : font types and colors (default %s)\n", + log_add (log_Always, " --menu : menu type, pc=text, 3do=graphical " + "(default %s)", PC_3DO_optString(defaultOptions->whichMenu)); + log_add (log_Always, " --font : font types and colors (default %s)", PC_3DO_optString(defaultOptions->whichFonts)); - fprintf (out, " --shield : slave shield type; pc=static, " - "3do=throbbing (default %s)\n", + log_add (log_Always, " --shield : slave shield type; pc=static, " + "3do=throbbing (default %s)", PC_3DO_optString(defaultOptions->whichShield)); - fprintf (out, " --scroll : ff/frev during comm. pc=per-page, " - "3do=smooth (default %s)\n", + log_add (log_Always, " --scroll : ff/frev during comm. pc=per-page, " + "3do=smooth (default %s)", PC_3DO_optString(defaultOptions->smoothScroll)); + + log_setOutput (old); } static int -InvalidArgument(const char *supplied, const char *opt_name) +InvalidArgument (const char *supplied, const char *opt_name) { - fprintf(stderr, "Invalid argument '%s' to option %s.\n", + log_add (log_Always, "Invalid argument '%s' to option %s.", supplied, opt_name); - fprintf (stderr, "Use -h to see the allowed arguments.\n"); + log_add (log_Always, "Use -h to see the allowed arguments."); return EXIT_FAILURE; } @@ -919,7 +932,8 @@ Check_PC_3DO_opt (const char *value, DWORD mask, const char *optName, { if (value == NULL) { - fprintf (stderr, "Error: option '%s' requires a value.\n", optName); + log_add (log_Always, "Error: option '%s' requires a value.", + optName); return -1; } @@ -933,12 +947,14 @@ Check_PC_3DO_opt (const char *value, DWORD mask, const char *optName, *result = OPT_PC; return 0; } - fprintf (stderr, "Error: Invalid option '%s %s' found.", optName, value); + log_add (log_Always, "Error: Invalid option '%s %s' found.", + optName, value); return -1; } static const char * -PC_3DO_optString(DWORD optMask) { +PC_3DO_optString (DWORD optMask) +{ if (optMask & OPT_3DO) { if (optMask & OPT_PC)