From 6f159fb39c48cbacc08e15090a4fe2ba73af0e02 Mon Sep 17 00:00:00 2001 From: "wagic.the.homebrew@gmail.com" Date: Tue, 13 Oct 2009 14:16:30 +0000 Subject: [PATCH] Erwan - cache fixes - Code review highly appreciated, please criticize my code! - fix issue 65 (quads when no image load slowly in shop/deck editor) - Possibly fix issue 92, please let me know if it reproduces - Fix issue 97 (Deck editor: weird behavior of deck display) - Fix issue 39 - please verify - Issue 56 can probably be closed as well - Fix issue 86 --- JGE/include/JRenderer.h | 6 +- JGE/lib/win/jge.lib | Bin 4070520 -> 4070520 bytes projects/mtg/include/GameOptions.h | 3 +- projects/mtg/include/Logger.h | 1 - projects/mtg/include/WCachedResource.h | 6 +- projects/mtg/include/WResourceManager.h | 32 +- projects/mtg/src/AIPlayer.cpp | 6 +- projects/mtg/src/ActionStack.cpp | 10 +- projects/mtg/src/Credits.cpp | 10 +- projects/mtg/src/GameApp.cpp | 10 +- projects/mtg/src/GameOptions.cpp | 3 +- projects/mtg/src/GameStateDeckViewer.cpp | 15 +- projects/mtg/src/GameStateMenu.cpp | 20 +- projects/mtg/src/GameStateOptions.cpp | 1 - projects/mtg/src/GameStateShop.cpp | 2 +- projects/mtg/src/GuiAvatars.cpp | 1 + projects/mtg/src/GuiCombat.cpp | 4 +- projects/mtg/src/GuiPhaseBar.cpp | 2 +- projects/mtg/src/GuiPlay.cpp | 1 - projects/mtg/src/MTGGameZones.cpp | 2 + projects/mtg/src/PlayGuiObject.cpp | 2 +- projects/mtg/src/Player.cpp | 5 +- projects/mtg/src/ShopItem.cpp | 21 +- projects/mtg/src/WCachedResource.cpp | 60 ++-- projects/mtg/src/WResourceManager.cpp | 440 ++++++++--------------- 25 files changed, 231 insertions(+), 432 deletions(-) diff --git a/JGE/include/JRenderer.h b/JGE/include/JRenderer.h index 1d74a1184..b11d14922 100644 --- a/JGE/include/JRenderer.h +++ b/JGE/include/JRenderer.h @@ -72,6 +72,11 @@ protected: public: +#if defined (WIN32) || defined (LINUX) +#else + int PixelSize(int textureMode); +#endif + ////////////////////////////////////////////////////////////////////////// /// Get the singleton instance /// @@ -540,7 +545,6 @@ private: int mCurrentTex; int mCurrentBlend; int mCurrentTextureFormat; - int PixelSize(int textureMode); #endif bool mVsync; diff --git a/JGE/lib/win/jge.lib b/JGE/lib/win/jge.lib index 0d857218646eabcc5fae37c6611f129806269bd0..ab9895e66938971ba98ec06a663e5c220c454a61 100644 GIT binary patch delta 2000 zcmZvceN0nV7{^gL6znK*^lcp<;w(nSf-F zJK{`0*^Xp>WXs4RbD@&4gDi89#ck-eSX_*mGt=OjY;G!4h*dS1Equ)+vQ=1VSm{_9D3QG&st|tc zwNeaiT!5v<(qJvbT7gzdKWfj`-OihT{$Qz&)Zp_K6`uj1C*aM=0uy}8MB34{ zQl0wcRN%~jZlFp8(vNftE%SlZCXzR_%S1lfkb1s3MmBE{&v%ZIwtdq1%P(3fc)_jL zafXg332;&c_u?th1GnDYo5Et~^Lj*|f9mlj%sc2-H>3A6Gyj^Bc;mn4P;exf$@5%y z0N76OyxYl4%bu+NhXue$I`lS@2DEZ>)`8bWsAVeasE}IN3$aNf<)?#Q3;xt;))PC3 z>o`7NHvxWvw-l5ass70t*)0PHM|q>@=)ulU%cZ052*i zEqATg6;xZl3~bH>_3m5)dgC~?;!hz?W^IoVD+jIZF;yLvfZU#p+RWUwFqdp*bjg+* zOV3Ole+%r1krY$w%EelOwG`F5mfa{6l3<4Gm!aW$3-!0a_Ood?)K~EQ>jv5R&rZ82 zWY}UI?oPd|YtvSAZF;%QBIeqpvJG#PNZ2K1qzeN9Hdij#5x|09y$67j1)I_S&9<}8 z%VaU6h1+Hw2DIUfEzmDyftHlpwd*B1w_59t*mX+GL|c#8+qTJo;sQwdz^_zPrB${6m38o$l`X z)cH3aa-Xav(hz=hPA%gxxH;S&p3!(nB`ys5LgR_awPel=C)f&Bz2@0iE;gie+_T0i z`C-R4`T`M}+ZDEhLx6SG)kc7ed_9g z!*^%EZE4u_iMVgac9DM~)Bovze0Ecfg&}WP!avL5U+Dw@!6p-FMjr(I=Sowrzj436 zc(nj!qGNun09FtygcU~7vBDu{emdG{gj8bp$Qq55&@#+@kq!rDvd=u%1oUQqqDHfozyaZL2KeOWM Ezd}DEhyVZp delta 1892 zcmZvdeN0L*xTg!r?>C# zJkNXHw|8xFjab9#(?iFkD!Pm6p@<$z&_f9)DAAc{_DgyxT7(sWCB~AVrRZ&L0sE+* z+D21aMp7&p)^@BNSdoa*$}4ul%GSsTxO6L03omBMNg?sxE%ZgEe7uRgvDtBVs$ZO0 z=Z~-~H(a=fIzN)vHNsAtv<)^}t-H{PXoWv1r2a&Xf|TLE>PRzM z%uz^R3J0!^C`L*-VAT}<8MUFqyQ}qmJAt4zF+Zk*&pSJ;L?-j)s(eZBuey z&ISl@UId$mBGu@jO=;^7!_d^U5>eAnJvzXl-dCyqTHsLA_hMq;L_npG0UXP^0zeJH zp?(dh3`e5=-y#4e#L#(|RHNNxQO957c!q_jQ%THa#B1GdD%EMgpDNjYqK=SbsH>L% zKf`5#Mvp}QL`^jDFb9-yxt>(h{)TAeZ&0tqKzn+68)REn->u%$@t;{Oye`m?LTncO zB+zsW^T0NBP-%-*qu0-BQvM9~o-XLqV#T0>K3(al5a6Uq&jRV2COx`oiuH+A;i(V8 zJ|C%}E3L6uaai%F(wcB5gXPoXwFzjv)}Z-21RHq4NJ^QeK68=Df7x%4BzG^SY4;lTO8T&qC&`ONc=@O31H@E8*>gXAMJ`B z&Wn_4RFO+PxEf+MAa+*xxWH8{PEy9;IuQV#t(Fb8IC~m-+~q2{o8EKBS^sPZZ*Q`T zGO|2f8bzh0F|pZyl|z6*k6Z^Jehd9gq3e?udC)cqtd77|&yBh2YC_QGRPN6>G;B_F zlWg*ry8%G3MMvt<2dVBWIpLRk_?SCuZ;(RgO}Vi=SgBZPSm`KlDr1!9njp{fa<^{G z^JY^#xTD^#L=MMHHhN>&n{^;~*>LH1FE@9Rasjx8UtsuMgQD(xXBT*q#v5SQ_dC?| Z57^0QG<{?jS9{{@m10&oBT diff --git a/projects/mtg/include/GameOptions.h b/projects/mtg/include/GameOptions.h index c2f984369..621553a05 100644 --- a/projects/mtg/include/GameOptions.h +++ b/projects/mtg/include/GameOptions.h @@ -60,7 +60,6 @@ public: MOMIR_MODE_UNLOCKED, EVILTWIN_MODE_UNLOCKED, RANDOMDECK_MODE_UNLOCKED, - CACHESIZE, //Theme metrics. These will be phased out fairly soon. THEME_METRICS, //Start of theme metrics. LOADING_TC = THEME_METRICS, @@ -151,7 +150,7 @@ public: string str; //All calls to asColor should include a fallback color for people without a theme. PIXEL_TYPE asColor(PIXEL_TYPE fallback = ARGB(255,255,255,255)); - bool isDefault(); //Returns true when number is 0 abd string is "" or "default" + bool isDefault(); //Returns true when number is 0 abd string is "" or "Default" GameOption(int value = 0); GameOption(string); GameOption(int, string); diff --git a/projects/mtg/include/Logger.h b/projects/mtg/include/Logger.h index 9c3297f72..dc316fd66 100644 --- a/projects/mtg/include/Logger.h +++ b/projects/mtg/include/Logger.h @@ -1,7 +1,6 @@ #ifndef _LOGGER_H #define _LOGGER_H_ - #ifdef DOLOG #define LOG(x) Logger::Log(x); #else diff --git a/projects/mtg/include/WCachedResource.h b/projects/mtg/include/WCachedResource.h index a17b7fe68..2d0e616b4 100644 --- a/projects/mtg/include/WCachedResource.h +++ b/projects/mtg/include/WCachedResource.h @@ -52,9 +52,8 @@ public: ~WTrackedQuad(); void Nullify(); void Trash(); - unsigned long size(); bool isGood(); - + unsigned long size(); string resname; JQuad * quad; }; @@ -100,7 +99,8 @@ public: void Nullify(); void Trash(); void Refresh(string filename); - unsigned long size(); + unsigned long size(); + bool isGood(); bool Attempt(string filename, int submode, int & error); bool compare(hgeParticleSystemInfo * p) {return (p == particles);}; diff --git a/projects/mtg/include/WResourceManager.h b/projects/mtg/include/WResourceManager.h index 4e5cf17f7..c9c62e60a 100644 --- a/projects/mtg/include/WResourceManager.h +++ b/projects/mtg/include/WResourceManager.h @@ -7,24 +7,20 @@ #include "MTGCard.h" #include "WCachedResource.h" -//Soft limits. -#define HUGE_CACHE_LIMIT 10000000 -#define HUGE_CACHE_ITEMS 300 - -#define LARGE_CACHE_LIMIT 5000000 -#define LARGE_CACHE_ITEMS 200 - -#define SMALL_CACHE_LIMIT 3000000 -#define SMALL_CACHE_ITEMS 150 - +#define HUGE_CACHE_LIMIT 6000000 // Size of the cache for Windows and Linux +#define SAMPLES_CACHE_SIZE 1000000 // Size in bytes of the cached samples +#define PSI_CACHE_SIZE 500000 // Size in bytes of the cahed particles +#define TEXTURES_CACHE_MINSIZE 2000000 // Minimum size of the cache on the PSP. The program should complain if the cache ever gets smaller than this +#define OPERATIONAL_SIZE 5000000 // Size required by Wagic for operational stuff. 3MB is not enough. The cache will usually try to take (Total Ram - Operational size) //Hard Limits. -#define MAX_CACHE_OBJECTS HUGE_CACHE_ITEMS +#define MAX_CACHE_OBJECTS 300 #define MAX_CACHE_ATTEMPTS 10 #define MAX_CACHE_MISSES 200 -#define MAX_CACHED_SAMPLES 4 +#define MAX_CACHED_SAMPLES 10 #define MAX_CACHE_GARBAGE 10 + enum ENUM_WRES_INFO{ WRES_UNLOCKED = 0, //Resource is unlocked. WRES_MAX_LOCK = 250, //Maximum number of locks for a resource. @@ -38,7 +34,6 @@ enum ENUM_RETRIEVE_STYLE{ RETRIEVE_LOCK, //As above, locks cached resource. Not for quads. RETRIEVE_UNLOCK, //As above, unlocks cached resource. Not for quads. RETRIEVE_RESOURCE, //Only retrieves a managed resource. Does not make a new one. - RETRIEVE_VRAM, //Retrieve it, and use vram if have to we create it. Must still remove it. RETRIEVE_MANAGE, //Makes resource permanent. RETRIEVE_THUMB, //Retrieve it as a thumbnail. CACHE_THUMB = RETRIEVE_THUMB, //Backwords compatibility. @@ -51,10 +46,9 @@ enum ENUM_CACHE_SUBTYPE{ //Because these bits only modify how a cached resource's Attempt() is called, //We can use them over and over for each resource type. TEXTURE_SUB_CARD = (1<<2), //Retrieve using cardFile, not graphicsFile. - TEXTURE_SUB_AVATAR = (1<<6), //Retrieve using avatarFile, not graphicsFile. + TEXTURE_SUB_AVATAR = (1<<5), //Retrieve using avatarFile, not graphicsFile. TEXTURE_SUB_THUMB = (1<<3),//Retrieve prepending "thumbnails\" to the filename. - TEXTURE_SUB_VRAM = (1<<4), //For textures. If we have to allocate, do it in VRAM. - TEXTURE_SUB_5551 = (1<<5), //For textures. If we have to allocate, use RGBA5551. + TEXTURE_SUB_5551 = (1<<4), //For textures. If we have to allocate, use RGBA5551. }; @@ -94,14 +88,12 @@ protected: bool Delete(cacheItem * item); //SAFE_DELETE and garbage collect. If maxCached == 0, nullify first. (This means you have to free that cacheActual later!) cacheItem* Get(string id, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); //Subordinate to Retrieve. cacheItem* AttemptNew(string filename, int submode); //Attempts a new cache item, progressively clearing cache if it fails. - cacheItem* Recycle(); //Returns a cache item from the trash. string makeID(string filename, int submode); //Makes an ID appropriate to the submode. string makeFilename(string id, int submode); //Makes a filename from an ID. map cache; map managed; //Cache can be arbitrarily large, so managed items are seperate. - vector garbage; //Garbage collection. unsigned long totalSize; unsigned long cacheSize; @@ -126,7 +118,7 @@ public: WResourceManager(); ~WResourceManager(); - JQuad * RetrieveCard(MTGCard * card, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); //RetrieveCard is reversed to match current use. + JQuad * RetrieveCard(MTGCard * card, int style = RETRIEVE_NORMAL,int submode = CACHE_NORMAL); JSample * RetrieveSample(string filename, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); JTexture * RetrieveTexture(string filename, int style = RETRIEVE_NORMAL, int submode = CACHE_NORMAL); JQuad * RetrieveQuad(string filename, float offX=0.0f, float offY=0.0f, float width=0.0f, float height=0.0f, string resname="", int style = RETRIEVE_LOCK, int submode = CACHE_NORMAL); @@ -177,7 +169,7 @@ public: //Wrapped from JSoundSystem. TODO: Privatize. JMusic * ssLoadMusic(const char *fileName); - void CacheForState(int state); + void autoResize(); //Recreates the cache size. void DebugRender(); diff --git a/projects/mtg/src/AIPlayer.cpp b/projects/mtg/src/AIPlayer.cpp index 7557263b8..d72d4110d 100644 --- a/projects/mtg/src/AIPlayer.cpp +++ b/projects/mtg/src/AIPlayer.cpp @@ -638,15 +638,15 @@ MTGCardInstance * AIPlayerBaka::FindCardToPlay(ManaCost * pMana, const char * ty } AIPlayerBaka::AIPlayerBaka(MTGPlayerCards * deck, string file, string fileSmall, string avatarFile) : AIPlayer(deck, file, fileSmall) { - mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); + mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_LOCK,TEXTURE_SUB_AVATAR); if(!mAvatarTex){ avatarFile = "baka.jpg"; - mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); + mAvatarTex = resources.RetrieveTexture(avatarFile,RETRIEVE_LOCK,TEXTURE_SUB_AVATAR); } if(mAvatarTex) - mAvatar = resources.RetrieveQuad(avatarFile, 0, 0, 35, 50,"bakaAvatar",RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); + mAvatar = resources.RetrieveQuad(avatarFile, 0, 0, 35, 50,"bakaAvatar",RETRIEVE_NORMAL,TEXTURE_SUB_AVATAR); else mAvatar = NULL; diff --git a/projects/mtg/src/ActionStack.cpp b/projects/mtg/src/ActionStack.cpp index c33784534..26c7f7d67 100644 --- a/projects/mtg/src/ActionStack.cpp +++ b/projects/mtg/src/ActionStack.cpp @@ -726,11 +726,11 @@ void ActionStack::Fizzle(Interruptible * action){ } void ActionStack::Render(){ - int x0 = 250; - int y0 = 30; - int width = 200; - int height = 90; - int currenty = y0 + 5 ; + float x0 = 250; + float y0 = 30; + float width = 200; + float height = 90; + float currenty = y0 + 5 ; if (mode == ACTIONSTACK_STANDARD){ if (!askIfWishesToInterrupt || !askIfWishesToInterrupt->displayStack()) return; diff --git a/projects/mtg/src/Credits.cpp b/projects/mtg/src/Credits.cpp index dc74c6f2b..029d5691a 100644 --- a/projects/mtg/src/Credits.cpp +++ b/projects/mtg/src/Credits.cpp @@ -81,27 +81,27 @@ void Credits::compute(Player * _p1, Player * _p2, GameApp * _app){ if (unlocked == -1){ unlocked = isDifficultyUnlocked(); if (unlocked){ - unlockedTex = resources.RetrieveTexture("unlocked.png", RETRIEVE_VRAM); + unlockedTex = resources.RetrieveTexture("unlocked.png"); unlockedQuad = resources.RetrieveQuad("unlocked.png", 2, 2, 396, 96); options[Options::DIFFICULTY_MODE_UNLOCKED] = GameOption(1); options.save(); } else if ((unlocked = isMomirUnlocked())) { - unlockedTex = resources.RetrieveTexture("momir_unlocked.png", RETRIEVE_VRAM); + unlockedTex = resources.RetrieveTexture("momir_unlocked.png"); unlockedQuad = resources.RetrieveQuad("momir_unlocked.png", 2, 2, 396, 96); options[Options::MOMIR_MODE_UNLOCKED] = GameOption(1); options.save(); } else if ((unlocked = isEvilTwinUnlocked())) { - unlockedTex = resources.RetrieveTexture("eviltwin_unlocked.png", RETRIEVE_VRAM); + unlockedTex = resources.RetrieveTexture("eviltwin_unlocked.png"); unlockedQuad = resources.RetrieveQuad("eviltwin_unlocked.png", 2, 2, 396, 96); options[Options::EVILTWIN_MODE_UNLOCKED] = GameOption(1); options.save(); }else if((unlocked = isRandomDeckUnlocked())) { - unlockedTex = resources.RetrieveTexture("randomdeck_unlocked.png", RETRIEVE_VRAM); + unlockedTex = resources.RetrieveTexture("randomdeck_unlocked.png"); unlockedQuad = resources.RetrieveQuad("randomdeck_unlocked.png", 2, 2, 396, 96); options[Options::RANDOMDECK_MODE_UNLOCKED] = GameOption(1); options.save(); }else if((unlocked = unlockRandomSet())) { - unlockedTex = resources.RetrieveTexture("set_unlocked.png", RETRIEVE_VRAM); + unlockedTex = resources.RetrieveTexture("set_unlocked.png"); unlockedQuad = resources.RetrieveQuad("set_unlocked.png", 2, 2, 396, 96); options[Options::optionSet(unlocked - 1)] = GameOption(1); options.save(); diff --git a/projects/mtg/src/GameApp.cpp b/projects/mtg/src/GameApp.cpp index 5cb5ec3c1..48242dd0b 100644 --- a/projects/mtg/src/GameApp.cpp +++ b/projects/mtg/src/GameApp.cpp @@ -250,19 +250,11 @@ void GameApp::Update() mCurrentState->End(); mCurrentState = mNextState; - - //Automate cache resizing. - for(int x=0;xRemove(card); - //loadIndexes(currentCard); return result; } @@ -233,7 +231,6 @@ void GameStateDeckViewer::Update(float dt) //Prevent screen from updating. return; } - // mParent->effect->UpdateBig(dt); hudAlpha = 255-(last_user_activity * 500); if (hudAlpha < 0) hudAlpha = 0; if (sellMenu){ @@ -419,9 +416,9 @@ void GameStateDeckViewer::renderOnScreenBasicInfo(){ void GameStateDeckViewer::renderSlideBar(){ int total = displayed_deck->getCount(colorFilter); - int filler = 15; - int y = SCREEN_HEIGHT-25; - int bar_size = SCREEN_WIDTH - 2*filler; + float filler = 15; + float y = SCREEN_HEIGHT_F-25; + float bar_size = SCREEN_WIDTH_F - 2*filler; JRenderer * r = JRenderer::GetInstance(); typedef map::reverse_iterator rit; @@ -436,7 +433,7 @@ void GameStateDeckViewer::renderSlideBar(){ for (; it != end; ++it) if (it->first->hasColor(colorFilter)) currentPos += it->second; } - int cursor_pos = bar_size * currentPos / total; + float cursor_pos = bar_size * currentPos / total; r->FillRoundRect(filler + 5,y+5,bar_size,0,3,ARGB(hudAlpha/2,0,0,0)); r->DrawLine(filler+cursor_pos + 5 ,y+5,filler+cursor_pos + 5,y+10,ARGB(hudAlpha/2,0,0,0)); @@ -603,7 +600,7 @@ void GameStateDeckViewer::renderOnScreenMenu(){ font->DrawString(buffer, 10+leftTransition, 10); int nb_letters = 0; - int posX, posY; + float posX, posY; DWORD graphColor; graphColor = ARGB(200, 155, 155, 155); diff --git a/projects/mtg/src/GameStateMenu.cpp b/projects/mtg/src/GameStateMenu.cpp index 3dd2dc315..059a17874 100644 --- a/projects/mtg/src/GameStateMenu.cpp +++ b/projects/mtg/src/GameStateMenu.cpp @@ -144,8 +144,8 @@ void GameStateMenu::Start(){ if (options[Options::MOMIR_MODE_UNLOCKED].number) hasChosenGameType = 0; if (options[Options::RANDOMDECK_MODE_UNLOCKED].number) hasChosenGameType = 0; - bgTexture = resources.RetrieveTexture("menutitle.png", RETRIEVE_VRAM); - movingWTexture = resources.RetrieveTexture("movingW.png", RETRIEVE_VRAM); + bgTexture = resources.RetrieveTexture("menutitle.png", RETRIEVE_LOCK); + movingWTexture = resources.RetrieveTexture("movingW.png", RETRIEVE_LOCK); mBg = resources.RetrieveQuad("menutitle.png", 0, 0, 256, 166); // Create background quad for rendering. mMovingW = resources.RetrieveQuad("movingW.png", 2, 2, 84, 62); @@ -162,20 +162,6 @@ void GameStateMenu::Start(){ SAFE_DELETE(playerdata); -#if defined DEBUG_CACHE - /*resources.ClearUnlocked(); //So we can tell if we've any extra locks. - - if(!resources.menuCached) - resources.menuCached = resources.CountCached(); - - if(resources.CountCached() != resources.menuCached){ - char buf[512]; - unsigned int i = resources.CountCached()-resources.menuCached; - sprintf(buf,"Warning: %u leftover locked items.",i); - resources.debugMessage = buf; - } - */ -#endif } @@ -336,6 +322,8 @@ void GameStateMenu::Update(float dt) sprintf(nbcardsStr, "Database: %i cards", mParent->collection->totalCards()); SAFE_DELETE(playerdata); resetDirectory(); + //All major things have been loaded, resize the cache to use it as efficiently as possible + resources.autoResize(); } break; case MENU_STATE_MAJOR_FIRST_TIME : diff --git a/projects/mtg/src/GameStateOptions.cpp b/projects/mtg/src/GameStateOptions.cpp index c3c686461..e714580e5 100644 --- a/projects/mtg/src/GameStateOptions.cpp +++ b/projects/mtg/src/GameStateOptions.cpp @@ -37,7 +37,6 @@ void GameStateOptions::Start() optionsList->Add(NEW OptionInteger(Options::INTERRUPT_SECONDS, "Seconds to pause for an Interrupt", 20, 1)); optionsList->Add(NEW OptionInteger(Options::INTERRUPTMYSPELLS, "Interrupt my spells")); optionsList->Add(NEW OptionInteger(Options::INTERRUPTMYABILITIES, "Interrupt my abilities")); - optionsList->Add(NEW OptionInteger(Options::CACHESIZE, "Use large cache")); optionsTabs = NEW OptionsMenu(); optionsTabs->Add(optionsList); diff --git a/projects/mtg/src/GameStateShop.cpp b/projects/mtg/src/GameStateShop.cpp index e24a49a88..415513297 100644 --- a/projects/mtg/src/GameStateShop.cpp +++ b/projects/mtg/src/GameStateShop.cpp @@ -30,7 +30,7 @@ void GameStateShop::Start() mStage = STAGE_SHOP_SHOP; - bgTexture = resources.RetrieveTexture("shop.jpg", RETRIEVE_VRAM); + bgTexture = resources.RetrieveTexture("shop.jpg"); //alternateRender doesn't lock, so lock our thumbnails for hgeDistort. altThumb[0] = resources.RetrieveTexture("artifact_thumb.jpg", RETRIEVE_LOCK); diff --git a/projects/mtg/src/GuiAvatars.cpp b/projects/mtg/src/GuiAvatars.cpp index 9b26a4aec..c2bb311af 100644 --- a/projects/mtg/src/GuiAvatars.cpp +++ b/projects/mtg/src/GuiAvatars.cpp @@ -96,4 +96,5 @@ void GuiAvatars::Render() r->FillRect(self->actX - w * self->actZ, self->actY - h * self->actZ, w * self->actZ , h * self->actZ, ARGB(200,0,0,0)); } GuiLayer::Render(); + } diff --git a/projects/mtg/src/GuiCombat.cpp b/projects/mtg/src/GuiCombat.cpp index 1b4147bb0..82871cb2a 100644 --- a/projects/mtg/src/GuiCombat.cpp +++ b/projects/mtg/src/GuiCombat.cpp @@ -28,8 +28,10 @@ GuiCombat::GuiCombat(GameObserver* go) : GuiLayer(), go(go), active(false), acti GuiCombat::~GuiCombat() { - if(ok_tex) + if(ok_tex){ resources.Release(ok_tex); + ok_tex = NULL; + } for (inner_iterator it = attackers.begin(); it != attackers.end(); ++it) { diff --git a/projects/mtg/src/GuiPhaseBar.cpp b/projects/mtg/src/GuiPhaseBar.cpp index da6c63a7e..5babbd710 100644 --- a/projects/mtg/src/GuiPhaseBar.cpp +++ b/projects/mtg/src/GuiPhaseBar.cpp @@ -46,7 +46,7 @@ void GuiPhaseBar::Update(float dt) void GuiPhaseBar::Render() { static const float ICONSCALE = 1.5; - static const unsigned CENTER = SCREEN_HEIGHT / 2 + 10; + static const float CENTER = SCREEN_HEIGHT_F / 2 + 10; JRenderer* renderer = JRenderer::GetInstance(); GameObserver * g = GameObserver::GetInstance(); unsigned p = (phase->id + Phases - 4) * (Width+1); diff --git a/projects/mtg/src/GuiPlay.cpp b/projects/mtg/src/GuiPlay.cpp index a24028881..d98427bd9 100644 --- a/projects/mtg/src/GuiPlay.cpp +++ b/projects/mtg/src/GuiPlay.cpp @@ -42,7 +42,6 @@ void GuiPlay::VertStack::reset(unsigned total, float x, float y) { GuiPlay::CardStack::reset(total, x - CARD_WIDTH, y); count = 0; - cout << "reset" << endl; } void GuiPlay::HorzStack::Render(CardView* card, iterator begin, iterator end) diff --git a/projects/mtg/src/MTGGameZones.cpp b/projects/mtg/src/MTGGameZones.cpp index bdf1e05f1..3b29c62b7 100644 --- a/projects/mtg/src/MTGGameZones.cpp +++ b/projects/mtg/src/MTGGameZones.cpp @@ -4,6 +4,7 @@ #include "../include/GameOptions.h" #include "../include/WEvent.h" #include "../include/MTGDeck.h" +#include #if defined (WIN32) || defined (LINUX) #include @@ -192,6 +193,7 @@ void MTGGameZone::setOwner(Player * player){ } MTGCardInstance * MTGGameZone::removeCard(MTGCardInstance * card, int createCopy){ + assert(nb_cards < 10000); int i; cardsMap.erase(card); for (i=0; i<(nb_cards); i++) { diff --git a/projects/mtg/src/PlayGuiObject.cpp b/projects/mtg/src/PlayGuiObject.cpp index 070d07242..167a50a48 100644 --- a/projects/mtg/src/PlayGuiObject.cpp +++ b/projects/mtg/src/PlayGuiObject.cpp @@ -35,7 +35,7 @@ void PlayGuiObject::Update(float dt){ if (mHeight < defaultHeight) mHeight = defaultHeight; } - wave = (wave +2) % 255; + wave = (wave +2 * (int) (100 * dt) ) % 255; for (vector::iterator it = effects.begin(); it != effects.end(); ++it) (*it)->Update(dt); Pos::Update(dt); diff --git a/projects/mtg/src/Player.cpp b/projects/mtg/src/Player.cpp index d80cac984..3733a9ed7 100644 --- a/projects/mtg/src/Player.cpp +++ b/projects/mtg/src/Player.cpp @@ -24,7 +24,6 @@ void Player::End(){ Player::~Player(){ SAFE_DELETE(manaPool); - resources.Release(mAvatar); resources.Release(mAvatarTex); mAvatar = NULL; mAvatarTex = NULL; @@ -59,9 +58,9 @@ Player * Player::opponent(){ } HumanPlayer::HumanPlayer(MTGPlayerCards * deck, string file, string fileSmall) : Player(deck, file, fileSmall) { - mAvatarTex = resources.RetrieveTexture("avatar.jpg",RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); + mAvatarTex = resources.RetrieveTexture("avatar.jpg",RETRIEVE_LOCK,TEXTURE_SUB_AVATAR); if (mAvatarTex) - mAvatar = resources.RetrieveQuad("avatar.jpg",0,0,35,50,"playerAvatar",RETRIEVE_VRAM,TEXTURE_SUB_AVATAR); + mAvatar = resources.RetrieveQuad("avatar.jpg",0,0,35,50,"playerAvatar",RETRIEVE_NORMAL,TEXTURE_SUB_AVATAR); else mAvatar = NULL; } diff --git a/projects/mtg/src/ShopItem.cpp b/projects/mtg/src/ShopItem.cpp index 5b7d92327..1effd29fb 100644 --- a/projects/mtg/src/ShopItem.cpp +++ b/projects/mtg/src/ShopItem.cpp @@ -139,30 +139,11 @@ void ShopItem::Render(){ } JRenderer * renderer = JRenderer::GetInstance(); - //float x0 = mX; - //float y0 = mY - (mScale > 1 ? 4 : 0); - /* if (GetId()%2){ - float xs[] = {mX, mX, mX+230,mX+230}; - float ys[] = {mY-5+17,mY-5+19,mY-5+35,mY-5} ; - - renderer->FillPolygon(xs,ys,4,ARGB(200,0,0,0)); - x0 = mX + 230 -30; - mFont->DrawString(mText.c_str(), x0, mY + 8,JGETEXT_RIGHT); - - }else{ - float xs[] = {mX-5, mX-5, mX-5+230,mX-5+230,}; - float ys[] = {mY-5,mY-5+35,mY-5+17,mY-5+19} ; - renderer->FillPolygon(xs,ys,4,ARGB(128,0,0,0)); - mFont->DrawString(mText.c_str(), mX + 30, mY + 8); - }*/ - //renderer->FillRect(mX-5, mY-5,230,35, ); - if (mesh){ mesh->Render(0,0); - //renderer->RenderQuad(thumb,x0,y0,0,mScale * 0.45,mScale * 0.45); }else{ - //NOTHING + //ERROR Management } if (mHasFocus){ if (card) quad = resources.RetrieveCard(card); diff --git a/projects/mtg/src/WCachedResource.cpp b/projects/mtg/src/WCachedResource.cpp index 0088d16aa..f13648953 100644 --- a/projects/mtg/src/WCachedResource.cpp +++ b/projects/mtg/src/WCachedResource.cpp @@ -128,15 +128,13 @@ bool WCachedTexture::ReleaseQuad(JQuad* quad){ } WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float width, float height,string resname){ - if(texture == NULL) - return NULL; + if(!texture) return NULL; bool allocated = false; WTrackedQuad * tq = NULL; JQuad * quad = NULL; vector::iterator it; - std::transform(resname.begin(),resname.end(),resname.begin(),::tolower); if(width == 0.0f || width > texture->mWidth) width = texture->mWidth; @@ -150,24 +148,15 @@ WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float widt } } - if(tq == NULL){ + if(!tq){ allocated = true; - vector::iterator gtq = WCachedTexture::garbageTQs.begin(); - if(gtq != WCachedTexture::garbageTQs.end()) - { - tq = *gtq; - garbageTQs.erase(gtq); - } - else - tq = NEW WTrackedQuad(resname); + tq = NEW WTrackedQuad(resname); + if(!tq) return NULL; } - if(tq == NULL) - return NULL; - quad = tq->quad; - if(quad == NULL){ + if(!quad){ quad = NEW JQuad(texture,offX,offY,width,height); if(!quad) { //Probably out of memory. Try again. @@ -178,20 +167,19 @@ WTrackedQuad * WCachedTexture::GetTrackedQuad(float offX, float offY, float widt if(!quad){ if(allocated && tq) SAFE_DELETE(tq); + fprintf(stderr, "WCACHEDRESOURCE:GetTrackedQuad - Quad is null\n"); return NULL; //Probably a crash. } tq->quad = quad; - trackedQuads.push_back(tq); - return tq; - } - else{ - //Update JQ's values to what we called this with. - quad->SetTextureRect(offX,offY,width,height); + if (allocated) trackedQuads.push_back(tq); return tq; } - return NULL; + //Update JQ's values to what we called this with. + quad->SetTextureRect(offX,offY,width,height); + return tq; + } JQuad * WCachedTexture::GetQuad(float offX, float offY, float width, float height,string resname){ @@ -206,7 +194,6 @@ JQuad * WCachedTexture::GetQuad(float offX, float offY, float width, float heigh JQuad * WCachedTexture::GetQuad(string resname){ vector::iterator it; - std::transform(resname.begin(),resname.end(),resname.begin(),::tolower); for(it = trackedQuads.begin();it!=trackedQuads.end();it++){ if((*it) && (*it)->resname == resname){ @@ -225,17 +212,20 @@ JQuad * WCachedTexture::GetCard(float offX, float offY, float width, float heigh } unsigned long WCachedTexture::size(){ - if(!texture) - return 0; - return texture->mTexHeight*texture->mTexWidth; + if(!texture) return 0; + + unsigned int pixel_size = 4; +#if defined WIN32 || defined LINUX +#else + pixel_size = JRenderer::GetInstance()->PixelSize(texture->mTextureFormat); +#endif + return texture->mTexHeight*texture->mTexWidth*pixel_size; } bool WCachedTexture::isGood(){ - if(!texture) - return false; - - return true; + return (texture != NULL); } + void WCachedTexture::Refresh(string filename){ int error = 0; JTexture* old = texture; @@ -287,12 +277,8 @@ bool WCachedTexture::Attempt(string filename, int submode, int & error){ if(submode & TEXTURE_SUB_5551) format = GU_PSM_5551; - //Use Vram? - if(submode & TEXTURE_SUB_VRAM){ - texture = JRenderer::GetInstance()->LoadTexture(realname.c_str(),TEX_TYPE_USE_VRAM,format); - } - else - texture = JRenderer::GetInstance()->LoadTexture(realname.c_str(),TEX_TYPE_NORMAL,format); + + texture = JRenderer::GetInstance()->LoadTexture(realname.c_str(),TEX_TYPE_USE_VRAM,format); //Failure. if(!texture){ diff --git a/projects/mtg/src/WResourceManager.cpp b/projects/mtg/src/WResourceManager.cpp index 5b86f6761..571bd93a8 100644 --- a/projects/mtg/src/WResourceManager.cpp +++ b/projects/mtg/src/WResourceManager.cpp @@ -9,6 +9,7 @@ #include #include "../include/WResourceManager.h" + WResourceManager resources; unsigned int vTime = 0; int WResourceManager::RetrieveError(){ @@ -36,12 +37,8 @@ void WResourceManager::DebugRender(){ font->SetScale(DEFAULT_MAIN_FONT_SCALE); renderer->FillRect(0,0,SCREEN_WIDTH,20,ARGB(128,155,0,0)); -#ifdef DEBUG_CACHE - if(debugMessage.size()) - renderer->FillRect(0,SCREEN_HEIGHT-30,SCREEN_WIDTH,40,ARGB(128,155,0,0)); - else -#endif - renderer->FillRect(0,SCREEN_HEIGHT-20,SCREEN_WIDTH,40,ARGB(128,155,0,0)); + + renderer->FillRect(0,SCREEN_HEIGHT-20,SCREEN_WIDTH,40,ARGB(128,155,0,0)); char buf[512]; @@ -167,9 +164,9 @@ WResourceManager::WResourceManager(){ mFontList.reserve(4); mFontMap.clear(); - psiWCache.Resize(SMALL_CACHE_LIMIT,6); //Plenty of room for mana symbols, or whatever. - sampleWCache.Resize(SMALL_CACHE_LIMIT,MAX_CACHED_SAMPLES); - textureWCache.Resize(LARGE_CACHE_LIMIT,MAX_CACHE_OBJECTS); + psiWCache.Resize(PSI_CACHE_SIZE,20); + sampleWCache.Resize(SAMPLES_CACHE_SIZE,MAX_CACHED_SAMPLES); + textureWCache.Resize(TEXTURES_CACHE_MINSIZE,MAX_CACHE_OBJECTS); lastTime = 0; lastError = CACHE_ERROR_NONE; } @@ -192,32 +189,33 @@ WResourceManager::~WResourceManager(){ LOG("==Successfully Destroyed WResourceManager=="); } -JQuad * WResourceManager::RetrieveCard(MTGCard * card, int style, int submode){ - //Cards are never, ever resource managed, so just check cache. - if(!card || options[Options::DISABLECARDS].number) - return NULL; +JQuad * WResourceManager::RetrieveCard(MTGCard * card, int style, int submode){ + //Cards are never, ever resource managed, so just check cache. + if(!card || options[Options::DISABLECARDS].number) + return NULL; + + submode = submode | TEXTURE_SUB_CARD; + + + string filename = card->getSetName(); + filename += "/"; + filename += card->getImageName(); + JQuad * jq = RetrieveQuad(filename,0,0,0,0,"",style,submode|TEXTURE_SUB_5551); + lastError = textureWCache.mError; + if(jq){ + jq->SetHotSpot(jq->mTex->mWidth / 2, jq->mTex->mHeight / 2); + return jq; + } + + return NULL; +} - submode = submode | TEXTURE_SUB_CARD; - - string filename = card->getSetName(); - filename += "/"; - filename += card->getImageName(); - JQuad * jq = RetrieveQuad(filename,0,0,0,0,"",style,submode|TEXTURE_SUB_5551); - lastError = textureWCache.mError; - if(jq){ - jq->SetHotSpot(jq->mTex->mWidth / 2, jq->mTex->mHeight / 2); - return jq; - } - - return NULL; -} int WResourceManager::CreateQuad(const string &quadName, const string &textureName, float x, float y, float width, float height){ if(!quadName.size() || !textureName.size()) return INVALID_ID; string resname = quadName; - std::transform(resname.begin(),resname.end(),resname.begin(),::tolower); vector::iterator it; int pos = 0; @@ -253,7 +251,6 @@ int WResourceManager::CreateQuad(const string &quadName, const string &textureNa JQuad * WResourceManager::GetQuad(const string &quadName){ string lookup = quadName; - std::transform(lookup.begin(),lookup.end(),lookup.begin(),::tolower); for(vector::iterator it=managedQuads.begin();it!=managedQuads.end();it++){ if((*it)->resname == lookup) @@ -289,11 +286,7 @@ JQuad * WResourceManager::RetrieveQuad(string filename, float offX, float offY, } //Aliases. - if(style == RETRIEVE_VRAM){ - submode = submode | TEXTURE_SUB_VRAM; - style = RETRIEVE_LOCK; - } - else if(style == RETRIEVE_THUMB){ + if(style == RETRIEVE_THUMB){ submode = submode | TEXTURE_SUB_THUMB; style = RETRIEVE_NORMAL; } @@ -319,8 +312,7 @@ JQuad * WResourceManager::RetrieveQuad(string filename, float offX, float offY, if(jtex){ WTrackedQuad * tq = jtex->GetTrackedQuad(offX,offY,width,height,resname); - if(tq == NULL) - return NULL; + if(!tq) return NULL; if(style == RETRIEVE_MANAGE && resname != ""){ WManagedQuad * mq = NEW WManagedQuad(); @@ -398,11 +390,7 @@ JTexture * WResourceManager::RetrieveTexture(string filename, int style, int sub WCachedTexture * res = NULL; //Aliases. - if(style == RETRIEVE_VRAM){ - submode = submode | TEXTURE_SUB_VRAM; - style = RETRIEVE_LOCK; - } - else if(style == RETRIEVE_THUMB){ + if(style == RETRIEVE_THUMB){ submode = submode | TEXTURE_SUB_THUMB; style = RETRIEVE_NORMAL; } @@ -521,9 +509,8 @@ string WResourceManager::graphicsFile(const string filename, const string specif //Check the theme folder. string theme = options[Options::ACTIVE_THEME].str; - std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); - if(theme != "" && theme != "default"){ + if(theme != "" && theme != "Default"){ sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -531,9 +518,8 @@ string WResourceManager::graphicsFile(const string filename, const string specif //Failure. Check mode graphics string mode = options[Options::ACTIVE_MODE].str; - std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); - if(mode != "" && mode != "defualt"){ + if(mode != "" && mode != "Default"){ sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -567,8 +553,8 @@ string WResourceManager::avatarFile(const string filename, const string specific //Check the profile folder. string profile = options[Options::ACTIVE_PROFILE].str; - std::transform(profile.begin(), profile.end(), profile.begin(), ::tolower); - if(profile != "" && profile != "default"){ + + if(profile != "" && profile != "Default"){ sprintf(buf,"profiles/%s/%s",profile.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -580,9 +566,8 @@ string WResourceManager::avatarFile(const string filename, const string specific //Check the theme folder. string theme = options[Options::ACTIVE_THEME].str; - std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); - if(theme != "" && theme != "default"){ + if(theme != "" && theme != "Default"){ sprintf(buf,"themes/%s/%s",theme.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -590,9 +575,8 @@ string WResourceManager::avatarFile(const string filename, const string specific //Failure. Check mode graphics string mode = options[Options::ACTIVE_MODE].str; - std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); - if(mode != "" && mode != "defualt"){ + if(mode != "" && mode != "Default"){ sprintf(buf,"modes/%s/graphics/%s",mode.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -615,9 +599,12 @@ string WResourceManager::avatarFile(const string filename, const string specific string WResourceManager::cardFile(const string filename, const string specific){ JFileSystem* fs = JFileSystem::GetInstance(); + + + //PUT Back the following when we have an actual usage for it (theme, or whatever) + //Right now I'm removing this for performance +/* char buf[512]; - - //Check the specific location, if any. if(specific != ""){ sprintf(buf,"%s/sets/%s",specific.c_str(),filename.c_str()); @@ -627,9 +614,8 @@ string WResourceManager::cardFile(const string filename, const string specific){ //Check the theme folder. string theme = options[Options::ACTIVE_THEME].str; - std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); - if(theme != "" && theme != "default"){ + if(theme != "" && theme != "Default"){ sprintf(buf,"themes/%s/sets/%s",theme.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -637,14 +623,14 @@ string WResourceManager::cardFile(const string filename, const string specific){ //Failure. Check mode string mode = options[Options::ACTIVE_MODE].str; - std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); - if(mode != "" && mode != "defualt"){ + if(mode != "" && mode != "Default"){ sprintf(buf,"modes/%s/sets/%s",mode.c_str(),filename.c_str()); - if(fileOK(buf,true)) + if(fileOK(buf,true)) return buf; } - + +*/ //Failure. Check sets char defdir[512]; sprintf(defdir,"sets/%s",filename.c_str()); @@ -687,9 +673,8 @@ string WResourceManager::musicFile(const string filename, const string specific) //Check the theme folder. string theme = options[Options::ACTIVE_THEME].str; - std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); - if(theme != "" && theme != "default"){ + if(theme != "" && theme != "Default"){ sprintf(buf,"themes/%s/sound/%s",theme.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -697,9 +682,8 @@ string WResourceManager::musicFile(const string filename, const string specific) //Failure. Check mode string mode = options[Options::ACTIVE_MODE].str; - std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); - if(mode != "" && mode != "defualt"){ + if(mode != "" && mode != "Default"){ sprintf(buf,"modes/%s/sound/%s",mode.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -727,9 +711,8 @@ string WResourceManager::sfxFile(const string filename, const string specific){ //Check the theme folder. string theme = options[Options::ACTIVE_THEME].str; - std::transform(theme.begin(), theme.end(), theme.begin(), ::tolower); - if(theme != "" && theme != "default"){ + if(theme != "" && theme != "Default"){ sprintf(buf,"themes/%s/sound/sfx/%s",theme.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -737,8 +720,7 @@ string WResourceManager::sfxFile(const string filename, const string specific){ //Failure. Check mode string mode = options[Options::ACTIVE_MODE].str; - std::transform(mode.begin(), mode.end(), mode.begin(), ::tolower); - if(mode != "" && mode != "defualt"){ + if(mode != "" && mode != "Default"){ sprintf(buf,"modes/%s/sound/sfx/%s",mode.c_str(),filename.c_str()); if(fileOK(buf,true)) return buf; @@ -793,40 +775,20 @@ int WResourceManager::LoadJLBFont(const string &fontName, int height){ else return itr->second; } -void WResourceManager::CacheForState(int state){ -#if (defined WIN32 || defined LINUX) && !defined DEBUG_CACHE - textureWCache.Resize(HUGE_CACHE_LIMIT,HUGE_CACHE_ITEMS); - return; -#else - switch(state){ - //Default is not to change cache sizes. - case GAME_STATE_MENU: - case GAME_STATE_OPTIONS: - break; - //Duels use a smaller cache, so there's more room for game stuff. - case GAME_STATE_DUEL: - if (options[Options::CACHESIZE].number) - textureWCache.Resize(LARGE_CACHE_LIMIT,LARGE_CACHE_ITEMS); - else - textureWCache.Resize(SMALL_CACHE_LIMIT,SMALL_CACHE_ITEMS); - sampleWCache.Resize(SMALL_CACHE_LIMIT,MAX_CACHED_SAMPLES); - break; - //Deck editor and shop are entirely cache safe, so give it near infinite resources. - case GAME_STATE_SHOP: - case GAME_STATE_DECK_VIEWER: - textureWCache.Resize(HUGE_CACHE_LIMIT,HUGE_CACHE_ITEMS); - break; - //Anything unknown, use large cache. - default: - textureWCache.Resize(LARGE_CACHE_LIMIT,LARGE_CACHE_ITEMS); - break; - } - - //Switching game states clears the cache on PSP. - ClearUnlocked(); +void WResourceManager::autoResize(){ +#if defined WIN32 || defined LINUX + textureWCache.Resize(HUGE_CACHE_LIMIT,MAX_CACHE_OBJECTS); +#else + unsigned int ram = ramAvailable(); + unsigned int myNewSize = ram - OPERATIONAL_SIZE + textureWCache.totalSize; + if (myNewSize < TEXTURES_CACHE_MINSIZE){ + fprintf(stderr, "Error, Not enough RAM for Cache: %i - total Ram: %i\n", myNewSize, ram); + } + textureWCache.Resize(myNewSize,MAX_CACHE_OBJECTS); #endif + return; } JMusic * WResourceManager::ssLoadMusic(const char *fileName){ @@ -993,17 +955,6 @@ void WCache::Resize(unsigned long size, int items){ maxCached = items; } -template -cacheItem* WCache::Recycle(){ - typename vector::iterator it = garbage.begin(); - if(it == garbage.end()) - return NULL; - - cacheItem * item = (*it); - garbage.erase(it); - - return item; -} template cacheItem* WCache::AttemptNew(string filename, int submode){ @@ -1012,70 +963,49 @@ cacheItem* WCache::AttemptNew(string filename, int submo return NULL; } - cacheItem* item = NULL; - - item = Recycle(); - - //There was nothing to recycle. Make absolutely certain we have an item. - if(item == NULL){ - item = NEW cacheItem; - if(item) - mError = CACHE_ERROR_NONE; - else{ - //Try a few times to get an item. - for(int attempt=0;attemptAttempt(filename,submode,mError) || !item->isGood()) + if(!item->Attempt(filename,submode,mError) || !item->isGood()) { + //No such file. Fail on first try. + if(mError == CACHE_ERROR_404){ + SAFE_DELETE(item); + return NULL; + } throw std::bad_alloc(); + } } catch(std::bad_alloc){ RemoveOldest(); } - //No such file. Fail on first try. - if(item && mError == CACHE_ERROR_404){ - if(garbage.size() < MAX_CACHE_GARBAGE){ - item->Trash(); - garbage.push_back(item); - } - else - SAFE_DELETE(item); - - return NULL; - } - - //Succeeded, so enforce limits and return. - if(item->isGood()){ - mError = CACHE_ERROR_NONE; - item->lock(); - Cleanup(); - item->unlock(); - return item; - } + //Succeeded + if(item->isGood()) + break; } //Still no result, so clear local cache, then try again. @@ -1089,23 +1019,18 @@ cacheItem* WCache::AttemptNew(string filename, int submo //Failed, so clear every cache we've got in prep for the next try. resources.ClearUnlocked(); } - - try{ - if(!item->Attempt(filename,submode,mError) || !item->isGood()) - throw std::bad_alloc(); - } - catch(std::bad_alloc){ - //Complete failure. Trash this object and return NULL. - if(item && !item->isGood()){ - if(garbage.size() < MAX_CACHE_GARBAGE){ - item->Trash(); - garbage.push_back(item); - } - else + if(!item->isGood()){ + try{ + if(!item->Attempt(filename,submode,mError) || !item->isGood()) + throw std::bad_alloc(); + } + catch(std::bad_alloc){ + //Complete failure. Trash this object and return NULL. + if(!item->isGood()){ SAFE_DELETE(item); - - mError = CACHE_ERROR_BAD; - return NULL; + mError = CACHE_ERROR_BAD; + return NULL; + } } } } @@ -1136,15 +1061,19 @@ cacheItem * WCache::Retrieve(string filename, int style, //Perform lock or unlock on entry. if(tc){ - if(style == RETRIEVE_LOCK) tc->lock(); - else if(style == RETRIEVE_UNLOCK) tc->unlock(); - else if(style == RETRIEVE_MANAGE && !tc->isPermanent()) { - //Unlink the managed resource from the cache. - UnlinkCache(tc); - - //Post it in managed resources. - managed[makeID(filename,submode)] = tc; - tc->deadbolt(); + switch(style){ + case RETRIEVE_LOCK: tc->lock(); break; + case RETRIEVE_UNLOCK: tc->unlock(); break; + case RETRIEVE_MANAGE: + if (!tc->isPermanent()) { + //Unlink the managed resource from the cache. + UnlinkCache(tc); + + //Post it in managed resources. + managed[makeID(filename,submode)] = tc; + tc->deadbolt(); + } + break; } } @@ -1154,10 +1083,8 @@ cacheItem * WCache::Retrieve(string filename, int style, tc->hit(); return tc; //Everything fine. } - else{ - //Something went wrong. - RemoveItem(tc); - } + //Something went wrong. + RemoveItem(tc); } //Record managed failure. Cache failure is recorded in Get(). @@ -1196,113 +1123,62 @@ cacheItem * WCache::Get(string id, int style, int submod //Something is managed. if(it != managed.end()) { - if(!it->second && style == RETRIEVE_RESOURCE) - return NULL; //A miss. - else - return it->second; //A hit. + return it->second; //A hit. } + //Failed to find managed resource and won't create one. Record a miss. - else if(style == RETRIEVE_RESOURCE){ + if(style == RETRIEVE_RESOURCE){ managed[lookup] = NULL; return NULL; } //Not managed, so look in cache. - if(it == managed.end() && style != RETRIEVE_MANAGE && style != RETRIEVE_RESOURCE ){ + if(style != RETRIEVE_MANAGE){ it = cache.find(lookup); //Well, we've found something... if(it != cache.end()) { if(!it->second && (submode & CACHE_EXISTING)){ mError = CACHE_ERROR_404; - return NULL; //A miss. } - else - return it->second; //A hit. + return it->second; //A hit. } } - cacheItem * item = NULL; - - if(style != RETRIEVE_MANAGE) - item = cache[lookup]; //We don't know about this one yet. - - //Found something. - if(item){ - //Item went bad? - if(!item->isGood()){ - - //If we're allowed, attempt to revive it. - if(!(submode & CACHE_EXISTING)) - item->Attempt(id,submode,mError); - - //Still bad, so remove it and return NULL - if(submode & CACHE_EXISTING || !item->isGood()){ - if(!item->isLocked()){ - RemoveItem(item); //Delete it. - mError = CACHE_ERROR_BAD; - } - //Worst case scenerio. Hopefully never happens.... hasn't so far. - else{ - item->Nullify(); //We're giving up on anything allocated here. - mError = CACHE_ERROR_LOST; //This is a potential memory leak, but might prevent a crash. - } - return NULL; - } - } - - //Alright, everythings fine! - mError = CACHE_ERROR_NONE; - return item; - } - //Didn't exist in cache. if(submode & CACHE_EXISTING ){ - RemoveMiss(lookup); mError = CACHE_ERROR_NOT_CACHED; return NULL; } - else{ - //Space in cache, make new texture - item = AttemptNew(id,submode); - //Couldn't make GOOD new item. - if(item && !item->isGood()) - { - if(garbage.size() < MAX_CACHE_GARBAGE){ - item->Trash(); - garbage.push_back(item); - } - else - SAFE_DELETE(item); - } - } - + //Space in cache, make new texture + cacheItem * item = AttemptNew(id,submode); + if(style == RETRIEVE_MANAGE){ - managed[lookup] = item; //Record hit or miss - if(item) + if(item){ + managed[lookup] = item; //Record a hit. item->deadbolt(); //Make permanent. - } - else{ - //Record it, hit or miss. - cache[lookup] = item; - } - - //Succeeded in making a new item. - if(item){ - unsigned long isize = item->size(); - totalSize += isize; - - mError = CACHE_ERROR_NONE; - if(style != RETRIEVE_MANAGE){ - cacheItems++; - cacheSize += isize; } - - return item; + else if(mError == CACHE_ERROR_404) + managed[lookup] = NULL; //File not found. Record a miss + } + else { + if(item || mError == CACHE_ERROR_404) + cache[lookup] = item; } - //Failure. - return NULL; + if (!item) return NULL; //Failure + + //Succeeded in making a new item. + unsigned long isize = item->size(); + totalSize += isize; + + mError = CACHE_ERROR_NONE; + if(style != RETRIEVE_MANAGE){ + cacheItems++; + cacheSize += isize; + } + + return item; } template @@ -1327,7 +1203,7 @@ WCache::WCache(){ cacheSize = 0; totalSize = 0; - maxCacheSize = SMALL_CACHE_LIMIT; + maxCacheSize = TEXTURES_CACHE_MINSIZE; maxCached = MAX_CACHE_OBJECTS; cacheItems = 0; @@ -1340,24 +1216,13 @@ WCache::~WCache(){ //Delete from cache & managed for(it=cache.begin();it!=cache.end();it++){ - if(!it->second) - continue; - SAFE_DELETE(it->second); } for(it=managed.begin();it!=managed.end();it++){ - if(!it->second) - continue; - SAFE_DELETE(it->second); } - //Clean up all the garbage - typename vector::iterator g; - for(g=garbage.begin();g!=garbage.end();g++){ - SAFE_DELETE(*g); - } } @@ -1462,24 +1327,17 @@ bool WCache::Delete(cacheItem * item){ if(maxCached == 0) item->Nullify(); - unsigned long isize = item->size(); - totalSize -= isize; - cacheSize -= isize; + unsigned long isize = item->size(); + totalSize -= isize; + cacheSize -= isize; #ifdef DEBUG_CACHE - if(cacheItems == 0) - OutputDebugString("cacheItems out of sync.\n"); + if(cacheItems == 0) + OutputDebugString("cacheItems out of sync.\n"); #endif - cacheItems--; + cacheItems--; - if(garbage.size() > MAX_CACHE_GARBAGE) - SAFE_DELETE(item); - else{ - item->Trash(); - item->lastTime = 0; - item->loadedMode = 0; - garbage.push_back(item); - } + SAFE_DELETE(item); return true; }