Browse Source

Merge remote-tracking branch 'origin/master' into plString

Conflicts:
	Sources/Plasma/CoreLib/hsStream.h
	Sources/Plasma/FeatureLib/pfAudio/plListener.cpp
	Sources/Plasma/FeatureLib/pfConsole/pfConsoleCommands.cpp
	Sources/Plasma/FeatureLib/pfConsole/pfDispatchLog.cpp
	Sources/Plasma/FeatureLib/pfJournalBook/pfJournalBook.cpp
	Sources/Plasma/FeatureLib/pfPython/cyMisc.cpp
	Sources/Plasma/FeatureLib/pfPython/cyMisc.h
	Sources/Plasma/FeatureLib/pfPython/cyMiscGlue4.cpp
	Sources/Plasma/FeatureLib/pfPython/plPythonFileMod.cpp
	Sources/Plasma/FeatureLib/pfPython/plPythonFileMod.h
	Sources/Plasma/FeatureLib/pfPython/pyImage.cpp
	Sources/Plasma/FeatureLib/pfPython/pyJournalBook.cpp
	Sources/Plasma/FeatureLib/pfPython/pyNetServerSessionInfo.h
	Sources/Plasma/NucleusLib/pnKeyedObject/plFixedKey.cpp
	Sources/Plasma/NucleusLib/pnKeyedObject/plKeyImp.cpp
	Sources/Plasma/NucleusLib/pnKeyedObject/plUoid.cpp
	Sources/Plasma/NucleusLib/pnKeyedObject/plUoid.h
	Sources/Plasma/NucleusLib/pnMessage/plMessage.h
	Sources/Plasma/NucleusLib/pnNetCommon/plNetApp.h
	Sources/Plasma/PubUtilLib/plAvatar/plCoopCoordinator.cpp
	Sources/Plasma/PubUtilLib/plDrawable/plDrawableSpansExport.cpp
	Sources/Plasma/PubUtilLib/plDrawable/plDynaDecalMgr.cpp
	Sources/Plasma/PubUtilLib/plDrawable/plWaveSet7.cpp
	Sources/Plasma/PubUtilLib/plInputCore/plInputDevice.h
	Sources/Plasma/PubUtilLib/plNetClient/plNetClientMgr.h
	Sources/Plasma/PubUtilLib/plNetCommon/plClientGuid.h
	Sources/Plasma/PubUtilLib/plNetMessage/plNetMessage.cpp
	Sources/Plasma/PubUtilLib/plNetMessage/plNetMsgHelpers.h
	Sources/Plasma/PubUtilLib/plNetTransport/plNetTransportMember.h
	Sources/Plasma/PubUtilLib/plPhysX/plSimulationMgr.cpp
	Sources/Plasma/PubUtilLib/plPipeline/plDXPipeline.cpp
	Sources/Plasma/PubUtilLib/plPipeline/plPlates.cpp
	Sources/Plasma/PubUtilLib/plResMgr/plKeyFinder.cpp
	Sources/Plasma/PubUtilLib/plResMgr/plKeyFinder.h
	Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.cpp
	Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.h
	Sources/Plasma/PubUtilLib/plScene/plRelevanceMgr.cpp
	Sources/Plasma/PubUtilLib/plScene/plRelevanceMgr.h
	Sources/Plasma/PubUtilLib/plSurface/plGrassShaderMod.cpp
Michael Hansen 13 years ago
parent
commit
c339f947ba
  1. 13
      CMakeLists.txt
  2. 1
      Sources/Plasma/Apps/plClient/CMakeLists.txt
  3. 2
      Sources/Plasma/Apps/plClient/plAllCreatables.cpp
  4. 126
      Sources/Plasma/Apps/plClient/plClient.cpp
  5. 16
      Sources/Plasma/Apps/plClient/plClient.h
  6. 6
      Sources/Plasma/Apps/plClient/plClientUpdateFormat.h
  7. 90
      Sources/Plasma/Apps/plClient/winmain.cpp
  8. 7
      Sources/Plasma/Apps/plClientKey/plClientKey.cpp
  9. 4
      Sources/Plasma/Apps/plClientKey/plClientKey.h
  10. 98
      Sources/Plasma/Apps/plClientPatcher/UruPlayer.cpp
  11. 2
      Sources/Plasma/Apps/plClientPatcher/UruPlayer.h
  12. 2
      Sources/Plasma/Apps/plFileEncrypt/CMakeLists.txt
  13. 4
      Sources/Plasma/Apps/plFileEncrypt/main.cpp
  14. 2
      Sources/Plasma/Apps/plFileSecure/CMakeLists.txt
  15. 22
      Sources/Plasma/Apps/plFileSecure/main.cpp
  16. 2
      Sources/Plasma/Apps/plLogDecrypt/CMakeLists.txt
  17. 16
      Sources/Plasma/Apps/plLogDecrypt/plLogDecrypt.cpp
  18. 2
      Sources/Plasma/Apps/plPageInfo/CMakeLists.txt
  19. 2
      Sources/Plasma/Apps/plPageInfo/plAllCreatables.cpp
  20. 8
      Sources/Plasma/Apps/plPageInfo/plPageInfo.cpp
  21. 4
      Sources/Plasma/Apps/plPageOptimizer/main.cpp
  22. 36
      Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.cpp
  23. 2
      Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.h
  24. 1
      Sources/Plasma/Apps/plPlasmaUpdate/main.cpp
  25. 2
      Sources/Plasma/Apps/plPlasmaUpdate/plFileGrabber.cpp
  26. 21
      Sources/Plasma/Apps/plPlasmaUpdate/plManifest.cpp
  27. 10
      Sources/Plasma/Apps/plPlasmaUpdate/plManifest.h
  28. 1
      Sources/Plasma/Apps/plPlasmaUpdate/plPlasmaServers.cpp
  29. 2
      Sources/Plasma/Apps/plPlasmaUpdate/plPlasmaServers.h
  30. 7
      Sources/Plasma/Apps/plPlasmaUpdate/plPlasmaUpdate.cpp
  31. 2
      Sources/Plasma/Apps/plPythonPack/CMakeLists.txt
  32. 2
      Sources/Plasma/Apps/plPythonPack/PythonInterface.cpp
  33. 4
      Sources/Plasma/Apps/plPythonPack/PythonInterface.h
  34. 18
      Sources/Plasma/Apps/plPythonPack/main.cpp
  35. 1
      Sources/Plasma/Apps/plUruLauncher/CMakeLists.txt
  36. 54
      Sources/Plasma/Apps/plUruLauncher/Main.cpp
  37. 30
      Sources/Plasma/Apps/plUruLauncher/SelfPatcher.cpp
  38. 4
      Sources/Plasma/Apps/plUruLauncher/plLauncherInfo.h
  39. 1
      Sources/Plasma/CMakeLists.txt
  40. 10
      Sources/Plasma/CoreLib/CMakeLists.txt
  41. 61
      Sources/Plasma/CoreLib/HS_POINT2.inc
  42. 107
      Sources/Plasma/CoreLib/HeadSpin.cpp
  43. 10
      Sources/Plasma/CoreLib/HeadSpin.h
  44. 124
      Sources/Plasma/CoreLib/hsBiExpander.h
  45. 20
      Sources/Plasma/CoreLib/hsBitVector.cpp
  46. 76
      Sources/Plasma/CoreLib/hsBitVector.h
  47. 464
      Sources/Plasma/CoreLib/hsBounds.cpp
  48. 48
      Sources/Plasma/CoreLib/hsBounds.h
  49. 43
      Sources/Plasma/CoreLib/hsColorRGBA.h
  50. 128
      Sources/Plasma/CoreLib/hsConfig.h
  51. 9
      Sources/Plasma/CoreLib/hsExceptionStack.h
  52. 2
      Sources/Plasma/CoreLib/hsExceptions.h
  53. 21
      Sources/Plasma/CoreLib/hsFastMath.cpp
  54. 52
      Sources/Plasma/CoreLib/hsFastMath.h
  55. 120
      Sources/Plasma/CoreLib/hsFixedTypes.h
  56. 34
      Sources/Plasma/CoreLib/hsGeometry3.cpp
  57. 164
      Sources/Plasma/CoreLib/hsGeometry3.h
  58. 46
      Sources/Plasma/CoreLib/hsHashTable.h
  59. 105
      Sources/Plasma/CoreLib/hsMMIOStream.cpp
  60. 72
      Sources/Plasma/CoreLib/hsMMIOStream.h
  61. 56
      Sources/Plasma/CoreLib/hsMalloc.cpp
  62. 205
      Sources/Plasma/CoreLib/hsMalloc.h
  63. 2
      Sources/Plasma/CoreLib/hsMatrix33.cpp
  64. 2
      Sources/Plasma/CoreLib/hsMatrix33.h
  65. 215
      Sources/Plasma/CoreLib/hsMatrix44.cpp
  66. 54
      Sources/Plasma/CoreLib/hsMatrix44.h
  67. 96
      Sources/Plasma/CoreLib/hsMemory.cpp
  68. 57
      Sources/Plasma/CoreLib/hsMemory.h
  69. 162
      Sources/Plasma/CoreLib/hsPoint2.h
  70. 82
      Sources/Plasma/CoreLib/hsQuat.cpp
  71. 32
      Sources/Plasma/CoreLib/hsQuat.h
  72. 369
      Sources/Plasma/CoreLib/hsQueue.h
  73. 56
      Sources/Plasma/CoreLib/hsSTLStream.cpp
  74. 42
      Sources/Plasma/CoreLib/hsSTLStream.h
  75. 200
      Sources/Plasma/CoreLib/hsScalar.h
  76. 4
      Sources/Plasma/CoreLib/hsStlUtils.cpp
  77. 8
      Sources/Plasma/CoreLib/hsStlUtils.h
  78. 390
      Sources/Plasma/CoreLib/hsStream.cpp
  79. 318
      Sources/Plasma/CoreLib/hsStream.h
  80. 30
      Sources/Plasma/CoreLib/hsStringTokenizer.cpp
  81. 30
      Sources/Plasma/CoreLib/hsStringTokenizer.h
  82. 174
      Sources/Plasma/CoreLib/hsTempPointer.h
  83. 14
      Sources/Plasma/CoreLib/hsTemplates.cpp
  84. 150
      Sources/Plasma/CoreLib/hsTemplates.h
  85. 2
      Sources/Plasma/CoreLib/hsThread.cpp
  86. 18
      Sources/Plasma/CoreLib/hsThread.h
  87. 2
      Sources/Plasma/CoreLib/hsThread_Mac.cpp
  88. 8
      Sources/Plasma/CoreLib/hsThread_Unix.cpp
  89. 2
      Sources/Plasma/CoreLib/hsThread_Win.cpp
  90. 274
      Sources/Plasma/CoreLib/hsTypes.h
  91. 59
      Sources/Plasma/CoreLib/hsUtils.cpp
  92. 88
      Sources/Plasma/CoreLib/hsUtils.h
  93. 104
      Sources/Plasma/CoreLib/hsWide.cpp
  94. 79
      Sources/Plasma/CoreLib/hsWide.h
  95. 54
      Sources/Plasma/CoreLib/hsWindowHndl.h
  96. 35
      Sources/Plasma/CoreLib/hsWindows.h
  97. 2
      Sources/Plasma/CoreLib/pcSmallRect.cpp
  98. 16
      Sources/Plasma/CoreLib/pcSmallRect.h
  99. 4
      Sources/Plasma/CoreLib/plGeneric.cpp
  100. 22
      Sources/Plasma/CoreLib/plLoadMask.cpp
  101. Some files were not shown because too many files have changed in this diff Show More

13
CMakeLists.txt

@ -1,6 +1,15 @@
project(Plasma) project(Plasma)
cmake_minimum_required(VERSION 2.8) cmake_minimum_required(VERSION 2.8)
# HeadSpin Configuration
if(WIN32 AND NOT CYGWIN)
add_definitions(-DHS_BUILD_FOR_WIN32)
endif(WIN32 AND NOT CYGWIN)
if(UNIX)
add_definitions(-DHS_BUILD_FOR_UNIX)
endif(UNIX)
# End HeadSpin Configuration
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${Plasma_BINARY_DIR}/bin) SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${Plasma_BINARY_DIR}/bin)
@ -42,6 +51,10 @@ set(PLASMA_TARGETS "Client"
set_property(CACHE PLASMA_TARGETS PROPERTY STRINGS set_property(CACHE PLASMA_TARGETS PROPERTY STRINGS
"Client" "Server" "Patcher" "Ethereal" "NoAvMsgs") "Client" "Server" "Patcher" "Ethereal" "NoAvMsgs")
if(PLASMA_TARGETS STREQUAL "Client")
add_definitions(-DCLIENT)
endif(PLASMA_TARGETS STREQUAL "Client")
if(PLASMA_TARGETS STREQUAL "Patcher") if(PLASMA_TARGETS STREQUAL "Patcher")
add_definitions(-DPATCHER) add_definitions(-DPATCHER)
endif(PLASMA_TARGETS STREQUAL "Patcher") endif(PLASMA_TARGETS STREQUAL "Patcher")

1
Sources/Plasma/Apps/plClient/CMakeLists.txt

@ -71,7 +71,6 @@ if(PLASMA_EXTERNAL_RELEASE)
set_target_properties(plClient PROPERTIES OUTPUT_NAME "UruExplorer") set_target_properties(plClient PROPERTIES OUTPUT_NAME "UruExplorer")
endif(PLASMA_EXTERNAL_RELEASE) endif(PLASMA_EXTERNAL_RELEASE)
target_link_libraries(plClient CoreLib) target_link_libraries(plClient CoreLib)
target_link_libraries(plClient CoreLibExe)
target_link_libraries(plClient pfAnimation) target_link_libraries(plClient pfAnimation)
target_link_libraries(plClient pfAudio) target_link_libraries(plClient pfAudio)
target_link_libraries(plClient pfCamera) target_link_libraries(plClient pfCamera)

2
Sources/Plasma/Apps/plClient/plAllCreatables.cpp

@ -39,5 +39,5 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "hsWindows.h"
#include "plAllCreatables.h" #include "plAllCreatables.h"

126
Sources/Plasma/Apps/plClient/plClient.cpp

@ -41,8 +41,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#pragma warning(disable: 4284) #pragma warning(disable: 4284)
#include "HeadSpin.h" #include "HeadSpin.h"
#include "hsTypes.h"
#include "hsWindowHndl.h"
#include "plClient.h" #include "plClient.h"
#include "hsStream.h" #include "hsStream.h"
#include "plResMgr/plResManager.h" #include "plResMgr/plResManager.h"
@ -164,7 +162,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#define MSG_LOADING_BAR #define MSG_LOADING_BAR
// static hsVector3 gAbsDown(0,0,-hsScalar1); // static hsVector3 gAbsDown(0,0,-1.f);
static plDispatchBase* gDisp = nil; static plDispatchBase* gDisp = nil;
static plTimerCallbackManager* gTimerMgr = nil; static plTimerCallbackManager* gTimerMgr = nil;
@ -224,14 +222,14 @@ plClient::plClient()
/// allow console commands to start working early /// allow console commands to start working early
// Create the console engine // Create the console engine
fConsoleEngine = TRACKED_NEW pfConsoleEngine(); fConsoleEngine = new pfConsoleEngine();
// create network mgr before console runs // create network mgr before console runs
plNetClientMgr::SetInstance(TRACKED_NEW plNetClientMgr); plNetClientMgr::SetInstance(new plNetClientMgr);
plAgeLoader::SetInstance(TRACKED_NEW plAgeLoader); plAgeLoader::SetInstance(new plAgeLoader);
// Use it to parse the init directory // Use it to parse the init directory
wchar initFolder[MAX_PATH]; wchar_t initFolder[MAX_PATH];
PathGetInitDirectory(initFolder, arrsize(initFolder)); PathGetInitDirectory(initFolder, arrsize(initFolder));
pfConsoleDirSrc dirSrc( fConsoleEngine, initFolder, L"*.ini" ); pfConsoleDirSrc dirSrc( fConsoleEngine, initFolder, L"*.ini" );
@ -276,7 +274,7 @@ hsBool plClient::Shutdown()
plBinkPlayer::DeInit(); plBinkPlayer::DeInit();
// //
// Get any proxies to commit suicide. // Get any proxies to commit suicide.
plProxyDrawMsg* nuke = TRACKED_NEW plProxyDrawMsg(plProxyDrawMsg::kAllTypes plProxyDrawMsg* nuke = new plProxyDrawMsg(plProxyDrawMsg::kAllTypes
| plProxyDrawMsg::kDestroy); | plProxyDrawMsg::kDestroy);
plgDispatch::MsgSend(nuke); plgDispatch::MsgSend(nuke);
@ -449,17 +447,17 @@ void plClient::InitAuxInits()
void plClient::InitInputs() void plClient::InitInputs()
{ {
hsStatusMessage("InitInputs client\n"); hsStatusMessage("InitInputs client\n");
fInputManager = TRACKED_NEW plInputManager( fWindowHndl ); fInputManager = new plInputManager( fWindowHndl );
fInputManager->CreateInterfaceMod(fPipeline); fInputManager->CreateInterfaceMod(fPipeline);
fInputManager->RegisterAs( kInput_KEY ); fInputManager->RegisterAs( kInput_KEY );
plgDispatch::Dispatch()->RegisterForExactType(plIMouseXEventMsg::Index(), fInputManager->GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plIMouseXEventMsg::Index(), fInputManager->GetKey());
plgDispatch::Dispatch()->RegisterForExactType(plIMouseYEventMsg::Index(), fInputManager->GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plIMouseYEventMsg::Index(), fInputManager->GetKey());
plgDispatch::Dispatch()->RegisterForExactType(plIMouseBEventMsg::Index(), fInputManager->GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plIMouseBEventMsg::Index(), fInputManager->GetKey());
plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), fInputManager->GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), fInputManager->GetKey());
plInputDevice* pKeyboard = TRACKED_NEW plKeyboardDevice(); plInputDevice* pKeyboard = new plKeyboardDevice();
fInputManager->AddInputDevice(pKeyboard); fInputManager->AddInputDevice(pKeyboard);
plInputDevice* pMouse = TRACKED_NEW plMouseDevice(); plInputDevice* pMouse = new plMouseDevice();
fInputManager->AddInputDevice(pMouse); fInputManager->AddInputDevice(pMouse);
if( fWindowActive ) if( fWindowActive )
@ -469,7 +467,7 @@ void plClient::InitInputs()
void plClient::ISetGraphicsDefaults() void plClient::ISetGraphicsDefaults()
{ {
// couldn't find display mode set defaults write to ini file // couldn't find display mode set defaults write to ini file
wchar graphicsIniFile[MAX_PATH]; wchar_t graphicsIniFile[MAX_PATH];
PathGetInitDirectory(graphicsIniFile, arrsize(graphicsIniFile)); PathGetInitDirectory(graphicsIniFile, arrsize(graphicsIniFile));
PathAddFilename(graphicsIniFile, graphicsIniFile, L"graphics.ini", arrsize(graphicsIniFile)); PathAddFilename(graphicsIniFile, graphicsIniFile, L"graphics.ini", arrsize(graphicsIniFile));
IWriteDefaultGraphicsSettings(graphicsIniFile); IWriteDefaultGraphicsSettings(graphicsIniFile);
@ -571,7 +569,7 @@ hsBool plClient::InitPipeline()
float yon = 500.0f; float yon = 500.0f;
pipe->SetFOV( 60.f, hsIntToScalar( 60.f * pipe->Height() / pipe->Width() ) ); pipe->SetFOV( 60.f, int32_t( 60.f * pipe->Height() / pipe->Width() ) );
pipe->SetDepth( 0.3f, yon ); pipe->SetDepth( 0.3f, yon );
hsMatrix44 id; hsMatrix44 id;
@ -793,7 +791,7 @@ hsBool plClient::MsgReceive(plMessage* msg)
plAudible* aud = plAudible::ConvertNoRef(callback->GetSender()->ObjectIsLoaded()); plAudible* aud = plAudible::ConvertNoRef(callback->GetSender()->ObjectIsLoaded());
if( simpMod ) if( simpMod )
{ {
plAnimCmdMsg* cmd = TRACKED_NEW plAnimCmdMsg; plAnimCmdMsg* cmd = new plAnimCmdMsg;
cmd->AddReceiver(simpMod->GetKey()); cmd->AddReceiver(simpMod->GetKey());
cmd->SetCmd(plAnimCmdMsg::kRemoveCallbacks); cmd->SetCmd(plAnimCmdMsg::kRemoveCallbacks);
cmd->AddCallback(callback); cmd->AddCallback(callback);
@ -802,7 +800,7 @@ hsBool plClient::MsgReceive(plMessage* msg)
} }
else if( aud ) else if( aud )
{ {
plSoundMsg* cmd = TRACKED_NEW plSoundMsg; plSoundMsg* cmd = new plSoundMsg;
cmd->AddReceiver(aud->GetKey()); cmd->AddReceiver(aud->GetKey());
cmd->SetCmd(plSoundMsg::kRemoveCallbacks); cmd->SetCmd(plSoundMsg::kRemoveCallbacks);
cmd->AddCallback(callback); cmd->AddCallback(callback);
@ -892,7 +890,7 @@ hsBool plClient::IHandleMovieMsg(plMovieMsg* mov)
if( i == fMovies.GetCount() ) if( i == fMovies.GetCount() )
{ {
fMovies.Append(TRACKED_NEW plBinkPlayer); fMovies.Append(new plBinkPlayer);
fMovies[i]->SetFileName(mov->GetFileName()); fMovies[i]->SetFileName(mov->GetFileName());
} }
@ -989,7 +987,7 @@ void plClient::IQueueRoomLoad(const std::vector<plLocation>& locs, bool hold)
bool allSameAge = true; bool allSameAge = true;
const char* lastAgeName = nil; const char* lastAgeName = nil;
UInt32 numRooms = 0; uint32_t numRooms = 0;
for (int i = 0; i < locs.size(); i++) for (int i = 0; i < locs.size(); i++)
{ {
const plLocation& loc = locs[i]; const plLocation& loc = locs[i];
@ -1011,7 +1009,7 @@ void plClient::IQueueRoomLoad(const std::vector<plLocation>& locs, bool hold)
continue; continue;
} }
fLoadRooms.push_back(TRACKED_NEW LoadRequest(loc, hold)); fLoadRooms.push_back(new LoadRequest(loc, hold));
if (!lastAgeName || hsStrEQ(info->GetAge(), lastAgeName)) if (!lastAgeName || hsStrEQ(info->GetAge(), lastAgeName))
lastAgeName = info->GetAge(); lastAgeName = info->GetAge();
@ -1051,7 +1049,7 @@ void plClient::ILoadNextRoom()
if (req) if (req)
{ {
plClientRefMsg* pRefMsg = TRACKED_NEW plClientRefMsg(GetKey(), plClientRefMsg* pRefMsg = new plClientRefMsg(GetKey(),
plRefMsg::kOnCreate, -1, plRefMsg::kOnCreate, -1,
req->hold ? plClientRefMsg::kLoadRoomHold : plClientRefMsg::kLoadRoom); req->hold ? plClientRefMsg::kLoadRoomHold : plClientRefMsg::kLoadRoom);
@ -1063,7 +1061,7 @@ void plClient::ILoadNextRoom()
delete req; delete req;
plClientMsg* nextRoom = TRACKED_NEW plClientMsg(plClientMsg::kLoadNextRoom); plClientMsg* nextRoom = new plClientMsg(plClientMsg::kLoadNextRoom);
nextRoom->Send(GetKey()); nextRoom->Send(GetKey());
} }
} }
@ -1108,7 +1106,7 @@ void plClient::IUnloadRooms(const std::vector<plLocation>& locs)
} }
GetKey()->Release(nodeKey); // release notify interest in scene node GetKey()->Release(nodeKey); // release notify interest in scene node
UInt32 recFlags = 0; uint32_t recFlags = 0;
if (roomIdx != -1) if (roomIdx != -1)
{ {
recFlags = fRooms[roomIdx].fFlags; recFlags = fRooms[roomIdx].fFlags;
@ -1237,7 +1235,7 @@ void plClient::IRoomLoaded(plSceneNode* node, bool hold)
// now tell all those who are interested that a room was loaded // now tell all those who are interested that a room was loaded
if (!hold) if (!hold)
{ {
plRoomLoadNotifyMsg* loadmsg = TRACKED_NEW plRoomLoadNotifyMsg; plRoomLoadNotifyMsg* loadmsg = new plRoomLoadNotifyMsg;
loadmsg->SetRoom(pRmKey); loadmsg->SetRoom(pRmKey);
loadmsg->SetWhatHappen(plRoomLoadNotifyMsg::kLoaded); loadmsg->SetWhatHappen(plRoomLoadNotifyMsg::kLoaded);
plgDispatch::MsgSend(loadmsg); plgDispatch::MsgSend(loadmsg);
@ -1273,7 +1271,7 @@ void plClient::IRoomUnloaded(plSceneNode* node)
plAgeLoader::GetInstance()->FinishedPagingOutRoom(&pRmKey, 1); plAgeLoader::GetInstance()->FinishedPagingOutRoom(&pRmKey, 1);
// tell all those who are interested that a room was unloaded // tell all those who are interested that a room was unloaded
plRoomLoadNotifyMsg* loadmsg = TRACKED_NEW plRoomLoadNotifyMsg; plRoomLoadNotifyMsg* loadmsg = new plRoomLoadNotifyMsg;
loadmsg->SetRoom(pRmKey); loadmsg->SetRoom(pRmKey);
loadmsg->SetWhatHappen(plRoomLoadNotifyMsg::kUnloaded); loadmsg->SetWhatHappen(plRoomLoadNotifyMsg::kUnloaded);
plgDispatch::MsgSend(loadmsg); plgDispatch::MsgSend(loadmsg);
@ -1295,7 +1293,7 @@ void plClient::IProgressMgrCallbackProc(plOperationProgress * progress)
} }
//============================================================================ //============================================================================
void plClient::IIncProgress (hsScalar byHowMuch, const char * text) void plClient::IIncProgress (float byHowMuch, const char * text)
{ {
if (fProgressBar) { if (fProgressBar) {
#ifndef PLASMA_EXTERNAL_RELEASE #ifndef PLASMA_EXTERNAL_RELEASE
@ -1306,7 +1304,7 @@ void plClient::IIncProgress (hsScalar byHowMuch, const char * text)
} }
//============================================================================ //============================================================================
void plClient::IStartProgress( const char *title, hsScalar len ) void plClient::IStartProgress( const char *title, float len )
{ {
if (fProgressBar) if (fProgressBar)
{ {
@ -1375,11 +1373,11 @@ public:
LoginNetClientCommCallback() : plNetClientComm::Callback(), fNumCurrentOps(0) LoginNetClientCommCallback() : plNetClientComm::Callback(), fNumCurrentOps(0)
{} {}
virtual void OperationStarted( UInt32 context ) virtual void OperationStarted( uint32_t context )
{ {
fNumCurrentOps++; fNumCurrentOps++;
} }
virtual void OperationComplete( UInt32 context, int resultCode ) virtual void OperationComplete( uint32_t context, int resultCode )
{ {
if (context == kAuth) if (context == kAuth)
{ {
@ -1392,14 +1390,14 @@ public:
{ {
if ( hsSucceeded( resultCode ) ) if ( hsSucceeded( resultCode ) )
{ {
UInt32 numPlayers = fCbArgs.GetInt(0); uint32_t numPlayers = fCbArgs.GetInt(0);
UInt32 pId = -1; uint32_t pId = -1;
std::string pName; std::string pName;
for (UInt32 i = 0; i < numPlayers; i++) for (uint32_t i = 0; i < numPlayers; i++)
{ {
pId = fCbArgs.GetInt((UInt16)(i*3+1)); pId = fCbArgs.GetInt((uint16_t)(i*3+1));
pName = fCbArgs.GetString((UInt16)(i*3+2)); pName = fCbArgs.GetString((uint16_t)(i*3+2));
if (pName == plClient::GetInstance()->fUsername) if (pName == plClient::GetInstance()->fUsername)
{ {
@ -1473,7 +1471,7 @@ hsBool plClient::StartInit()
InitDLLs(); InitDLLs();
plGlobalVisMgr::Init(); plGlobalVisMgr::Init();
fPageMgr = TRACKED_NEW plPageTreeMgr; fPageMgr = new plPageTreeMgr;
plVisLOSMgr::Init(fPipeline, fPageMgr); plVisLOSMgr::Init(fPipeline, fPageMgr);
@ -1493,32 +1491,32 @@ hsBool plClient::StartInit()
/// Note: this can be done last because the console engine was inited first, and /// Note: this can be done last because the console engine was inited first, and
/// everything in code that works with the console does so through the console engine /// everything in code that works with the console does so through the console engine
fConsole = TRACKED_NEW pfConsole(); fConsole = new pfConsole();
pfConsole::SetPipeline( fPipeline ); pfConsole::SetPipeline( fPipeline );
fConsole->RegisterAs( kConsoleObject_KEY ); // fixedKey from plFixedKey.h fConsole->RegisterAs( kConsoleObject_KEY ); // fixedKey from plFixedKey.h
fConsole->Init( fConsoleEngine ); fConsole->Init( fConsoleEngine );
/// Init the font cache /// Init the font cache
fFontCache = TRACKED_NEW plFontCache(); fFontCache = new plFontCache();
/// Init the transition manager /// Init the transition manager
fTransitionMgr = TRACKED_NEW plTransitionMgr(); fTransitionMgr = new plTransitionMgr();
fTransitionMgr->RegisterAs( kTransitionMgr_KEY ); // fixedKey from plFixedKey.h fTransitionMgr->RegisterAs( kTransitionMgr_KEY ); // fixedKey from plFixedKey.h
fTransitionMgr->Init(); fTransitionMgr->Init();
// Init the Age Linking effects manager // Init the Age Linking effects manager
fLinkEffectsMgr = TRACKED_NEW plLinkEffectsMgr(); fLinkEffectsMgr = new plLinkEffectsMgr();
fLinkEffectsMgr->RegisterAs( kLinkEffectsMgr_KEY ); // fixedKey from plFixedKey.h fLinkEffectsMgr->RegisterAs( kLinkEffectsMgr_KEY ); // fixedKey from plFixedKey.h
fLinkEffectsMgr->Init(); fLinkEffectsMgr->Init();
/// Init the in-game GUI manager /// Init the in-game GUI manager
fGameGUIMgr = TRACKED_NEW pfGameGUIMgr(); fGameGUIMgr = new pfGameGUIMgr();
fGameGUIMgr->RegisterAs( kGameGUIMgr_KEY ); fGameGUIMgr->RegisterAs( kGameGUIMgr_KEY );
fGameGUIMgr->Init(); fGameGUIMgr->Init();
plgAudioSys::Activate(true); plgAudioSys::Activate(true);
plConst(hsScalar) delay(2.f); plConst(float) delay(2.f);
//commenting out publisher splash for MORE //commenting out publisher splash for MORE
//IPlayIntroBink("avi/intro0.bik", delay, 0.f, 0.f, 1.f, 1.f, 0.75); //IPlayIntroBink("avi/intro0.bik", delay, 0.f, 0.f, 1.f, 1.f, 0.75);
//if( GetDone() ) return false; //if( GetDone() ) return false;
@ -1534,14 +1532,14 @@ hsBool plClient::StartInit()
plAgeLoader::GetInstance()->Init(); plAgeLoader::GetInstance()->Init();
pfSecurePreloader::GetInstance()->Init(); pfSecurePreloader::GetInstance()->Init();
plCmdIfaceModMsg* pModMsg2 = TRACKED_NEW plCmdIfaceModMsg; plCmdIfaceModMsg* pModMsg2 = new plCmdIfaceModMsg;
pModMsg2->SetBCastFlag(plMessage::kBCastByExactType); pModMsg2->SetBCastFlag(plMessage::kBCastByExactType);
pModMsg2->SetSender(fConsole->GetKey()); pModMsg2->SetSender(fConsole->GetKey());
pModMsg2->SetCmd(plCmdIfaceModMsg::kAdd); pModMsg2->SetCmd(plCmdIfaceModMsg::kAdd);
plgDispatch::MsgSend(pModMsg2); plgDispatch::MsgSend(pModMsg2);
// create new the virtual camera // create new the virtual camera
fNewCamera = TRACKED_NEW plVirtualCam1; fNewCamera = new plVirtualCam1;
fNewCamera->RegisterAs( kVirtualCamera1_KEY ); fNewCamera->RegisterAs( kVirtualCamera1_KEY );
fNewCamera->Init(); fNewCamera->Init();
fNewCamera->SetPipeline( GetPipeline() ); fNewCamera->SetPipeline( GetPipeline() );
@ -1555,7 +1553,7 @@ hsBool plClient::StartInit()
plInputManager::SetRecenterMouse(false); plInputManager::SetRecenterMouse(false);
// create the listener for the audio system: // create the listener for the audio system:
plListener* pLMod = TRACKED_NEW plListener; plListener* pLMod = new plListener;
pLMod->RegisterAs(kListenerMod_KEY ); pLMod->RegisterAs(kListenerMod_KEY );
plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), pLMod->GetKey()); plgDispatch::Dispatch()->RegisterForExactType(plEvalMsg::Index(), pLMod->GetKey());
@ -1565,7 +1563,7 @@ hsBool plClient::StartInit()
if (StrCmp(NetCommGetStartupAge()->ageDatasetName, "StartUp") == 0) if (StrCmp(NetCommGetStartupAge()->ageDatasetName, "StartUp") == 0)
{ {
plNetCommAuthMsg * msg = NEW(plNetCommAuthMsg); plNetCommAuthMsg * msg = new plNetCommAuthMsg();
msg->result = kNetSuccess; msg->result = kNetSuccess;
msg->param = nil; msg->param = nil;
msg->Send(); msg->Send();
@ -1730,7 +1728,7 @@ hsBool plClient::IUpdate()
// Time may have been clamped in IncSysSeconds, depending on hsTimer's current mode. // Time may have been clamped in IncSysSeconds, depending on hsTimer's current mode.
double currTime = hsTimer::GetSysSeconds(); double currTime = hsTimer::GetSysSeconds();
hsScalar delSecs = hsTimer::GetDelSysSeconds(); float delSecs = hsTimer::GetDelSysSeconds();
// do not change this ordering // do not change this ordering
@ -1749,18 +1747,18 @@ hsBool plClient::IUpdate()
// starting trouble during their update. So to get rid of this message, some // starting trouble during their update. So to get rid of this message, some
// other way of flushing the dispatch after NegClientMgr's update is needed. mf // other way of flushing the dispatch after NegClientMgr's update is needed. mf
plProfile_BeginTiming(TimeMsg); plProfile_BeginTiming(TimeMsg);
plTimeMsg* msg = TRACKED_NEW plTimeMsg(nil, nil, nil, nil); plTimeMsg* msg = new plTimeMsg(nil, nil, nil, nil);
plgDispatch::MsgSend(msg); plgDispatch::MsgSend(msg);
plProfile_EndTiming(TimeMsg); plProfile_EndTiming(TimeMsg);
plProfile_BeginTiming(EvalMsg); plProfile_BeginTiming(EvalMsg);
plEvalMsg* eval = TRACKED_NEW plEvalMsg(nil, nil, nil, nil); plEvalMsg* eval = new plEvalMsg(nil, nil, nil, nil);
plgDispatch::MsgSend(eval); plgDispatch::MsgSend(eval);
plProfile_EndTiming(EvalMsg); plProfile_EndTiming(EvalMsg);
char *xFormLap1 = "Main"; char *xFormLap1 = "Main";
plProfile_BeginLap(TransformMsg, xFormLap1); plProfile_BeginLap(TransformMsg, xFormLap1);
plTransformMsg* xform = TRACKED_NEW plTransformMsg(nil, nil, nil, nil); plTransformMsg* xform = new plTransformMsg(nil, nil, nil, nil);
plgDispatch::MsgSend(xform); plgDispatch::MsgSend(xform);
plProfile_EndLap(TransformMsg, xFormLap1); plProfile_EndLap(TransformMsg, xFormLap1);
@ -1778,7 +1776,7 @@ hsBool plClient::IUpdate()
{ {
char *xFormLap2 = "Simulation"; char *xFormLap2 = "Simulation";
plProfile_BeginLap(TransformMsg, xFormLap2); plProfile_BeginLap(TransformMsg, xFormLap2);
xform = TRACKED_NEW plTransformMsg(nil, nil, nil, nil); xform = new plTransformMsg(nil, nil, nil, nil);
plgDispatch::MsgSend(xform); plgDispatch::MsgSend(xform);
plProfile_EndLap(TransformMsg, xFormLap2); plProfile_EndLap(TransformMsg, xFormLap2);
} }
@ -1786,7 +1784,7 @@ hsBool plClient::IUpdate()
{ {
char *xFormLap3 = "Delayed"; char *xFormLap3 = "Delayed";
plProfile_BeginLap(TransformMsg, xFormLap3); plProfile_BeginLap(TransformMsg, xFormLap3);
xform = TRACKED_NEW plDelayedTransformMsg(nil, nil, nil, nil); xform = new plDelayedTransformMsg(nil, nil, nil, nil);
plgDispatch::MsgSend(xform); plgDispatch::MsgSend(xform);
plProfile_EndLap(TransformMsg, xFormLap3); plProfile_EndLap(TransformMsg, xFormLap3);
} }
@ -1794,7 +1792,7 @@ hsBool plClient::IUpdate()
plCoordinateInterface::SetTransformPhase(plCoordinateInterface::kTransformPhaseNormal); plCoordinateInterface::SetTransformPhase(plCoordinateInterface::kTransformPhaseNormal);
plProfile_BeginTiming(CameraMsg); plProfile_BeginTiming(CameraMsg);
plCameraMsg* cameras = TRACKED_NEW plCameraMsg; plCameraMsg* cameras = new plCameraMsg;
cameras->SetCmd(plCameraMsg::kUpdateCameras); cameras->SetCmd(plCameraMsg::kUpdateCameras);
cameras->SetBCastFlag(plMessage::kBCastByExactType); cameras->SetBCastFlag(plMessage::kBCastByExactType);
plgDispatch::MsgSend(cameras); plgDispatch::MsgSend(cameras);
@ -1867,11 +1865,11 @@ hsBool plClient::IDraw()
plProfile_EndTiming(VisEval); plProfile_EndTiming(VisEval);
plProfile_BeginTiming(RenderMsg); plProfile_BeginTiming(RenderMsg);
plRenderMsg* rendMsg = TRACKED_NEW plRenderMsg(fPipeline); plRenderMsg* rendMsg = new plRenderMsg(fPipeline);
plgDispatch::MsgSend(rendMsg); plgDispatch::MsgSend(rendMsg);
plProfile_EndTiming(RenderMsg); plProfile_EndTiming(RenderMsg);
plPreResourceMsg* preMsg = TRACKED_NEW plPreResourceMsg(fPipeline); plPreResourceMsg* preMsg = new plPreResourceMsg(fPipeline);
plgDispatch::MsgSend(preMsg); plgDispatch::MsgSend(preMsg);
// This might not be the ideal place for this, but it // This might not be the ideal place for this, but it
@ -1970,7 +1968,7 @@ void plClient::IKillMovies()
fMovies.Reset(); fMovies.Reset();
} }
hsBool plClient::IPlayIntroBink(const char* movieName, hsScalar endDelay, hsScalar posX, hsScalar posY, hsScalar scaleX, hsScalar scaleY, hsScalar volume /* = 1.0 */) hsBool plClient::IPlayIntroBink(const char* movieName, float endDelay, float posX, float posY, float scaleX, float scaleY, float volume /* = 1.0 */)
{ {
SetQuitIntro(false); SetQuitIntro(false);
plBinkPlayer player; plBinkPlayer player;
@ -2113,7 +2111,7 @@ hsG3DDeviceModeRecord plClient::ILoadDevMode(const char* devModeFile)
/// Read the rest in /// Read the rest in
selMode.Read(&stream); selMode.Read(&stream);
UInt16 performance = stream.ReadLE16(); uint16_t performance = stream.ReadLE16();
if( performance < 25 ) if( performance < 25 )
plBitmap::SetGlobalLevelChopCount( 2 ); plBitmap::SetGlobalLevelChopCount( 2 );
@ -2147,7 +2145,7 @@ hsG3DDeviceModeRecord plClient::ILoadDevMode(const char* devModeFile)
{ {
dmr.GetDevice()->Write(&stream); dmr.GetDevice()->Write(&stream);
dmr.GetMode()->Write(&stream); dmr.GetMode()->Write(&stream);
stream.WriteLE16((UInt16)(0*100)); stream.WriteLE16((uint16_t)(0*100));
stream.Close(); stream.Close();
} }
@ -2179,7 +2177,7 @@ void plClient::ResizeDisplayDevice(int Width, int Height, hsBool Windowed)
pfGameGUIMgr::GetInstance()->SetAspectRatio( aspectratio ); pfGameGUIMgr::GetInstance()->SetAspectRatio( aspectratio );
UInt32 winStyle, winExStyle; uint32_t winStyle, winExStyle;
if( Windowed ) if( Windowed )
{ {
winStyle = WS_OVERLAPPEDWINDOW; winStyle = WS_OVERLAPPEDWINDOW;
@ -2192,8 +2190,8 @@ void plClient::ResizeDisplayDevice(int Width, int Height, hsBool Windowed)
SetWindowLong(fWindowHndl, GWL_EXSTYLE, winExStyle); SetWindowLong(fWindowHndl, GWL_EXSTYLE, winExStyle);
UInt32 flags = SWP_NOCOPYBITS | SWP_SHOWWINDOW | SWP_FRAMECHANGED; uint32_t flags = SWP_NOCOPYBITS | SWP_SHOWWINDOW | SWP_FRAMECHANGED;
UInt32 OutsideWidth, OutsideHeight; uint32_t OutsideWidth, OutsideHeight;
HWND insertAfter; HWND insertAfter;
if( Windowed ) if( Windowed )
{ {
@ -2312,7 +2310,7 @@ void plClient::IDetectAudioVideoSettings()
int val = 0; int val = 0;
hsStream *stream = nil; hsStream *stream = nil;
hsUNIXStream s; hsUNIXStream s;
wchar audioIniFile[MAX_PATH], graphicsIniFile[MAX_PATH]; wchar_t audioIniFile[MAX_PATH], graphicsIniFile[MAX_PATH];
PathGetInitDirectory(audioIniFile, arrsize(audioIniFile)); PathGetInitDirectory(audioIniFile, arrsize(audioIniFile));
StrCopy(graphicsIniFile, audioIniFile, arrsize(audioIniFile)); StrCopy(graphicsIniFile, audioIniFile, arrsize(audioIniFile));
PathAddFilename(audioIniFile, audioIniFile, L"audio.ini", arrsize(audioIniFile)); PathAddFilename(audioIniFile, audioIniFile, L"audio.ini", arrsize(audioIniFile));
@ -2371,7 +2369,7 @@ void plClient::IDetectAudioVideoSettings()
} }
} }
void plClient::IWriteDefaultGraphicsSettings(const wchar* destFile) void plClient::IWriteDefaultGraphicsSettings(const wchar_t* destFile)
{ {
hsStream *stream = plEncryptedStream::OpenEncryptedFileWrite(destFile); hsStream *stream = plEncryptedStream::OpenEncryptedFileWrite(destFile);
@ -2445,11 +2443,11 @@ void plClient::IOnAsyncInitComplete () {
pfMarkerMgr::Instance(); pfMarkerMgr::Instance();
fAnimDebugList = TRACKED_NEW plAnimDebugList(); fAnimDebugList = new plAnimDebugList();
/// Now parse final init files (*.fni). These are files just like ini files, only to be run /// Now parse final init files (*.fni). These are files just like ini files, only to be run
/// after all hell has broken loose in the client. /// after all hell has broken loose in the client.
wchar initFolder[MAX_PATH]; wchar_t initFolder[MAX_PATH];
PathGetInitDirectory(initFolder, arrsize(initFolder)); PathGetInitDirectory(initFolder, arrsize(initFolder));
pfConsoleDirSrc dirSrc( fConsoleEngine, initFolder, L"net*.fni" ); // connect to net first pfConsoleDirSrc dirSrc( fConsoleEngine, initFolder, L"net*.fni" ); // connect to net first
#ifndef PLASMA_EXTERNAL_RELEASE #ifndef PLASMA_EXTERNAL_RELEASE
@ -2477,7 +2475,7 @@ void plClient::IOnAsyncInitComplete () {
// Tell the transition manager to start faded out. This is so we don't // Tell the transition manager to start faded out. This is so we don't
// get a frame or two of non-faded drawing before we do our initial fade in // get a frame or two of non-faded drawing before we do our initial fade in
(void)(TRACKED_NEW plTransitionMsg( plTransitionMsg::kFadeOut, 0.0f, true ))->Send(); (void)(new plTransitionMsg( plTransitionMsg::kFadeOut, 0.0f, true ))->Send();
fFlags.SetBit(kFlagAsyncInitComplete); fFlags.SetBit(kFlagAsyncInitComplete);
if (fFlags.IsBitSet(kFlagGlobalDataLoaded)) if (fFlags.IsBitSet(kFlagGlobalDataLoaded))
@ -2495,7 +2493,7 @@ void plClient::ICompleteInit () {
hsStatusMessage("Client init complete."); hsStatusMessage("Client init complete.");
// Tell everyone we're ready to rock. // Tell everyone we're ready to rock.
plClientMsg* clientMsg = TRACKED_NEW plClientMsg(plClientMsg::kInitComplete); plClientMsg* clientMsg = new plClientMsg(plClientMsg::kInitComplete);
clientMsg->SetBCastFlag(plMessage::kBCastByType); clientMsg->SetBCastFlag(plMessage::kBCastByType);
clientMsg->Send(); clientMsg->Send();

16
Sources/Plasma/Apps/plClient/plClient.h

@ -47,10 +47,10 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
//#define NEW_CAMERA_CODE //#define NEW_CAMERA_CODE
#include "hsWindowHndl.h" #include "HeadSpin.h"
#include "hsBitVector.h" #include "hsBitVector.h"
#include "hsTemplates.h" #include "hsTemplates.h"
#include "hsUtils.h"
#include "hsStlUtils.h" #include "hsStlUtils.h"
#include "pnKeyedObject/hsKeyedObject.h" #include "pnKeyedObject/hsKeyedObject.h"
#include "pnKeyedObject/plUoid.h" #include "pnKeyedObject/plUoid.h"
@ -94,10 +94,10 @@ protected:
{ {
public: public:
plSceneNode *fNode; plSceneNode *fNode;
UInt32 fFlags; uint32_t fFlags;
plRoomRec() { fNode = nil; fFlags = 0; } plRoomRec() { fNode = nil; fFlags = 0; }
plRoomRec( plSceneNode *n, UInt32 f ) : fNode( n ), fFlags( f ) {} plRoomRec( plSceneNode *n, uint32_t f ) : fNode( n ), fFlags( f ) {}
enum Flags enum Flags
{ {
@ -189,13 +189,13 @@ protected:
void IProcessRenderRequests(hsTArray<plRenderRequest*>& reqs); void IProcessRenderRequests(hsTArray<plRenderRequest*>& reqs);
void IAddRenderRequest(plRenderRequest* req); void IAddRenderRequest(plRenderRequest* req);
hsBool IPlayIntroBink(const char* movieName, hsScalar endDelay, hsScalar posX, hsScalar posY, hsScalar scaleX, hsScalar scaleY, hsScalar volume = 1.0); hsBool IPlayIntroBink(const char* movieName, float endDelay, float posX, float posY, float scaleX, float scaleY, float volume = 1.0);
hsBool IHandleMovieMsg(plMovieMsg* mov); hsBool IHandleMovieMsg(plMovieMsg* mov);
void IKillMovies(); void IKillMovies();
void IServiceMovies(); void IServiceMovies();
void IStartProgress( const char *title, hsScalar len ); void IStartProgress( const char *title, float len );
void IIncProgress( hsScalar byHowMuch, const char *text ); void IIncProgress( float byHowMuch, const char *text );
void IStopProgress( void ); void IStopProgress( void );
static void IDispatchMsgReceiveCallback(); static void IDispatchMsgReceiveCallback();
@ -293,7 +293,7 @@ public:
void ResetDisplayDevice(int Width, int Height, int ColorDepth, hsBool Windowed, int NumAASamples, int MaxAnisotropicSamples, hsBool VSync = false); void ResetDisplayDevice(int Width, int Height, int ColorDepth, hsBool Windowed, int NumAASamples, int MaxAnisotropicSamples, hsBool VSync = false);
void ResizeDisplayDevice(int Width, int Height, hsBool Windowed); void ResizeDisplayDevice(int Width, int Height, hsBool Windowed);
void IDetectAudioVideoSettings(); void IDetectAudioVideoSettings();
void IWriteDefaultGraphicsSettings(const wchar* destFile); void IWriteDefaultGraphicsSettings(const wchar_t* destFile);
plAnimDebugList *fAnimDebugList; plAnimDebugList *fAnimDebugList;

6
Sources/Plasma/Apps/plClient/plClientUpdateFormat.h

@ -54,13 +54,13 @@ namespace ClientUpdate
// //
// Format of the update stream // Format of the update stream
// //
// UInt8 - type (kUpdate, kShutdown) // uint8_t - type (kUpdate, kShutdown)
// //
// If type is kUpdate: // If type is kUpdate:
// UInt32 - number of deleted keys // uint32_t - number of deleted keys
// plUoid - uoid of deleted key (* num) // plUoid - uoid of deleted key (* num)
// //
// UInt32 - number of new creatables // uint32_t - number of new creatables
// plCreatable - new creatable (* num) // plCreatable - new creatable (* num)
// //

90
Sources/Plasma/Apps/plClient/winmain.cpp

@ -53,7 +53,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "HeadSpin.h" #include "HeadSpin.h"
#include "hsStream.h" #include "hsStream.h"
#include "hsUtils.h"
#include "plClient.h" #include "plClient.h"
#include "plClientResMgr/plClientResMgr.h" #include "plClientResMgr/plClientResMgr.h"
#include "plNetClient/plNetClientMgr.h" #include "plNetClient/plNetClientMgr.h"
@ -133,14 +133,14 @@ static const unsigned AUTH_FAILED_TIMER = 2;
//============================================================================ //============================================================================
#ifdef PLASMA_EXTERNAL_RELEASE #ifdef PLASMA_EXTERNAL_RELEASE
static wchar s_patcherExeName[] = L"UruLauncher.exe"; static wchar_t s_patcherExeName[] = L"UruLauncher.exe";
#endif // PLASMA_EXTERNAL_RELEASE #endif // PLASMA_EXTERNAL_RELEASE
//============================================================================ //============================================================================
// PhysX installer // PhysX installer
//============================================================================ //============================================================================
static wchar s_physXSetupExeName[] = L"PhysX_Setup.exe"; static wchar_t s_physXSetupExeName[] = L"PhysX_Setup.exe";
//============================================================================ //============================================================================
// TRANSGAMING detection & dialog replacement // TRANSGAMING detection & dialog replacement
@ -178,12 +178,12 @@ struct LoginDialogParam {
}; };
static bool AuthenticateNetClientComm(ENetError* result, HWND parentWnd); static bool AuthenticateNetClientComm(ENetError* result, HWND parentWnd);
static void GetCryptKey(UInt32* cryptKey, unsigned size); static void GetCryptKey(uint32_t* cryptKey, unsigned size);
static void SaveUserPass (LoginDialogParam *pLoginParam, char *password); static void SaveUserPass (LoginDialogParam *pLoginParam, char *password);
static void LoadUserPass (LoginDialogParam *pLoginParam); static void LoadUserPass (LoginDialogParam *pLoginParam);
static void AuthFailedStrings (ENetError authError, static void AuthFailedStrings (ENetError authError,
const char **ppStr1, const char **ppStr2, const char **ppStr1, const char **ppStr2,
const wchar **ppWStr); const wchar_t **ppWStr);
// Detect whether we're running under TRANSGAMING Cider // Detect whether we're running under TRANSGAMING Cider
@ -290,7 +290,7 @@ static bool TGRunLoginDialog (LoginDialogParam *pLoginParam)
if (!cancelled) if (!cancelled)
{ {
const char *pStr1, *pStr2; const char *pStr1, *pStr2;
const wchar *pWStr; const wchar_t *pWStr;
unsigned int Len; unsigned int Len;
char *pTmpStr; char *pTmpStr;
@ -302,7 +302,7 @@ static bool TGRunLoginDialog (LoginDialogParam *pLoginParam)
if (pWStr) if (pWStr)
Len += StrLen (pWStr) + 2; Len += StrLen (pWStr) + 2;
pTmpStr = TRACKED_NEW char[Len]; pTmpStr = new char[Len];
StrCopy (pTmpStr, pStr1, StrLen (pStr1)); StrCopy (pTmpStr, pStr1, StrLen (pStr1));
if (pStr2) if (pStr2)
{ {
@ -361,7 +361,7 @@ void DebugMsgF(const char* format, ...);
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{ {
static bool gDragging = false; static bool gDragging = false;
static UInt32 keyState=0; static uint32_t keyState=0;
// Handle messages // Handle messages
switch (message) { switch (message) {
@ -661,8 +661,8 @@ bool InitPhysX()
// launch the PhysX installer // launch the PhysX installer
STARTUPINFOW startupInfo; STARTUPINFOW startupInfo;
PROCESS_INFORMATION processInfo; PROCESS_INFORMATION processInfo;
ZERO(startupInfo); memset(&startupInfo, 0, sizeof(startupInfo));
ZERO(processInfo); memset(&processInfo, 0, sizeof(processInfo));
startupInfo.cb = sizeof(startupInfo); startupInfo.cb = sizeof(startupInfo);
if(!CreateProcessW(NULL, s_physXSetupExeName, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo)) if(!CreateProcessW(NULL, s_physXSetupExeName, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo))
{ {
@ -702,7 +702,7 @@ bool InitPhysX()
bool InitClient( HWND hWnd ) bool InitClient( HWND hWnd )
{ {
plResManager *resMgr = TRACKED_NEW plResManager; plResManager *resMgr = new plResManager;
resMgr->SetDataPath("dat"); resMgr->SetDataPath("dat");
hsgResMgr::Init(resMgr); hsgResMgr::Init(resMgr);
@ -713,7 +713,7 @@ bool InitClient( HWND hWnd )
} }
plClientResMgr::Instance().ILoadResources("resource.dat"); plClientResMgr::Instance().ILoadResources("resource.dat");
gClient = TRACKED_NEW plClient; gClient = new plClient;
if( gClient == nil ) if( gClient == nil )
return false; return false;
@ -773,7 +773,7 @@ BOOL WinInit(HINSTANCE hInst, int nCmdShow)
/// else, use our normal styles /// else, use our normal styles
char windowName[256]; char windowName[256];
wchar productString[256]; wchar_t productString[256];
StrCopy(productString, ProductLongName(), arrsize(productString)); StrCopy(productString, ProductLongName(), arrsize(productString));
StrToAnsi(windowName, productString, arrsize(windowName)); StrToAnsi(windowName, productString, arrsize(windowName));
@ -837,7 +837,7 @@ void DebugMsgF(const char* format, ...)
static void AuthFailedStrings (ENetError authError, static void AuthFailedStrings (ENetError authError,
const char **ppStr1, const char **ppStr2, const char **ppStr1, const char **ppStr2,
const wchar **ppWStr) const wchar_t **ppWStr)
{ {
*ppStr1 = NULL; *ppStr1 = NULL;
*ppStr2 = NULL; *ppStr2 = NULL;
@ -895,7 +895,7 @@ BOOL CALLBACK AuthFailedDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPAR
{ {
LoginDialogParam* loginParam = (LoginDialogParam*)lParam; LoginDialogParam* loginParam = (LoginDialogParam*)lParam;
const char *pStr1, *pStr2; const char *pStr1, *pStr2;
const wchar *pWStr; const wchar_t *pWStr;
AuthFailedStrings (loginParam->authError, AuthFailedStrings (loginParam->authError,
&pStr1, &pStr2, &pWStr); &pStr1, &pStr2, &pWStr);
@ -939,7 +939,7 @@ BOOL CALLBACK UruTOSDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM l
char* eulaData = NULL; char* eulaData = NULL;
unsigned dataLen = stream.GetSizeLeft(); unsigned dataLen = stream.GetSizeLeft();
eulaData = TRACKED_NEW char[dataLen + 1]; eulaData = new char[dataLen + 1];
ZeroMemory(eulaData, dataLen + 1); ZeroMemory(eulaData, dataLen + 1);
stream.Read(dataLen, eulaData); stream.Read(dataLen, eulaData);
@ -970,12 +970,12 @@ BOOL CALLBACK UruTOSDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM l
static void SaveUserPass (LoginDialogParam *pLoginParam, char *password) static void SaveUserPass (LoginDialogParam *pLoginParam, char *password)
{ {
UInt32 cryptKey[4]; uint32_t cryptKey[4];
ZeroMemory(cryptKey, sizeof(cryptKey)); ZeroMemory(cryptKey, sizeof(cryptKey));
GetCryptKey(cryptKey, arrsize(cryptKey)); GetCryptKey(cryptKey, arrsize(cryptKey));
wchar wusername[kMaxAccountNameLength]; wchar_t wusername[kMaxAccountNameLength];
wchar wpassword[kMaxPasswordLength]; wchar_t wpassword[kMaxPasswordLength];
StrToUnicode(wusername, pLoginParam->username, arrsize(wusername)); StrToUnicode(wusername, pLoginParam->username, arrsize(wusername));
@ -985,7 +985,7 @@ static void SaveUserPass (LoginDialogParam *pLoginParam, char *password)
{ {
StrToUnicode(wpassword, password, arrsize(wpassword)); StrToUnicode(wpassword, password, arrsize(wpassword));
wchar domain[15]; wchar_t domain[15];
PathSplitEmail(wusername, nil, 0, domain, arrsize(domain), nil, 0, nil, 0, 0); PathSplitEmail(wusername, nil, 0, domain, arrsize(domain), nil, 0, nil, 0, 0);
if (StrLen(domain) == 0 || StrCmpI(domain, L"gametap") == 0) { if (StrLen(domain) == 0 || StrCmpI(domain, L"gametap") == 0) {
@ -1012,12 +1012,12 @@ static void SaveUserPass (LoginDialogParam *pLoginParam, char *password)
else else
NetCommSetAuthTokenAndOS(nil, L"win"); NetCommSetAuthTokenAndOS(nil, L"win");
wchar fileAndPath[MAX_PATH]; wchar_t fileAndPath[MAX_PATH];
PathGetInitDirectory(fileAndPath, arrsize(fileAndPath)); PathGetInitDirectory(fileAndPath, arrsize(fileAndPath));
PathAddFilename(fileAndPath, fileAndPath, L"login.dat", arrsize(fileAndPath)); PathAddFilename(fileAndPath, fileAndPath, L"login.dat", arrsize(fileAndPath));
#ifndef PLASMA_EXTERNAL_RELEASE #ifndef PLASMA_EXTERNAL_RELEASE
// internal builds can use the local init directory // internal builds can use the local init directory
wchar localFileAndPath[MAX_PATH]; wchar_t localFileAndPath[MAX_PATH];
StrCopy(localFileAndPath, L"init\\login.dat", arrsize(localFileAndPath)); StrCopy(localFileAndPath, L"init\\login.dat", arrsize(localFileAndPath));
if (PathDoesFileExist(localFileAndPath)) if (PathDoesFileExist(localFileAndPath))
StrCopy(fileAndPath, localFileAndPath, arrsize(localFileAndPath)); StrCopy(fileAndPath, localFileAndPath, arrsize(localFileAndPath));
@ -1038,7 +1038,7 @@ static void SaveUserPass (LoginDialogParam *pLoginParam, char *password)
static void LoadUserPass (LoginDialogParam *pLoginParam) static void LoadUserPass (LoginDialogParam *pLoginParam)
{ {
UInt32 cryptKey[4]; uint32_t cryptKey[4];
ZeroMemory(cryptKey, sizeof(cryptKey)); ZeroMemory(cryptKey, sizeof(cryptKey));
GetCryptKey(cryptKey, arrsize(cryptKey)); GetCryptKey(cryptKey, arrsize(cryptKey));
@ -1046,12 +1046,12 @@ static void LoadUserPass (LoginDialogParam *pLoginParam)
pLoginParam->remember = false; pLoginParam->remember = false;
pLoginParam->username[0] = '\0'; pLoginParam->username[0] = '\0';
wchar fileAndPath[MAX_PATH]; wchar_t fileAndPath[MAX_PATH];
PathGetInitDirectory(fileAndPath, arrsize(fileAndPath)); PathGetInitDirectory(fileAndPath, arrsize(fileAndPath));
PathAddFilename(fileAndPath, fileAndPath, L"login.dat", arrsize(fileAndPath)); PathAddFilename(fileAndPath, fileAndPath, L"login.dat", arrsize(fileAndPath));
#ifndef PLASMA_EXTERNAL_RELEASE #ifndef PLASMA_EXTERNAL_RELEASE
// internal builds can use the local init directory // internal builds can use the local init directory
wchar localFileAndPath[MAX_PATH]; wchar_t localFileAndPath[MAX_PATH];
StrCopy(localFileAndPath, L"init\\login.dat", arrsize(localFileAndPath)); StrCopy(localFileAndPath, L"init\\login.dat", arrsize(localFileAndPath));
if (PathDoesFileExist(localFileAndPath)) if (PathDoesFileExist(localFileAndPath))
StrCopy(fileAndPath, localFileAndPath, arrsize(localFileAndPath)); StrCopy(fileAndPath, localFileAndPath, arrsize(localFileAndPath));
@ -1059,7 +1059,7 @@ static void LoadUserPass (LoginDialogParam *pLoginParam)
hsStream* stream = plEncryptedStream::OpenEncryptedFile(fileAndPath, true, cryptKey); hsStream* stream = plEncryptedStream::OpenEncryptedFile(fileAndPath, true, cryptKey);
if (stream && !stream->AtEnd()) if (stream && !stream->AtEnd())
{ {
UInt32 savedKey[4]; uint32_t savedKey[4];
stream->Read(sizeof(savedKey), savedKey); stream->Read(sizeof(savedKey), savedKey);
if (memcmp(cryptKey, savedKey, sizeof(savedKey)) == 0) if (memcmp(cryptKey, savedKey, sizeof(savedKey)) == 0)
@ -1166,7 +1166,7 @@ BOOL CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM
} }
char windowName[256]; char windowName[256];
wchar productString[256]; wchar_t productString[256];
ProductString(productString, arrsize(productString)); ProductString(productString, arrsize(productString));
StrToAnsi(windowName, productString, arrsize(windowName)); StrToAnsi(windowName, productString, arrsize(windowName));
SendMessage(GetDlgItem(hwndDlg, IDC_PRODUCTSTRING), WM_SETTEXT, 0, (LPARAM) windowName); SendMessage(GetDlgItem(hwndDlg, IDC_PRODUCTSTRING), WM_SETTEXT, 0, (LPARAM) windowName);
@ -1218,7 +1218,7 @@ BOOL CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM
SaveUserPass (pLoginParam, password); SaveUserPass (pLoginParam, password);
MemSet(&pLoginParam->authError, 0, sizeof(pLoginParam->authError)); memset(&pLoginParam->authError, 0, sizeof(pLoginParam->authError));
bool cancelled = AuthenticateNetClientComm(&pLoginParam->authError, hwndDlg); bool cancelled = AuthenticateNetClientComm(&pLoginParam->authError, hwndDlg);
if (IS_NET_SUCCESS(pLoginParam->authError) && !cancelled) if (IS_NET_SUCCESS(pLoginParam->authError) && !cancelled)
@ -1251,7 +1251,7 @@ BOOL CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM
} }
else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_URULOGIN_GAMETAPLINK) else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_URULOGIN_GAMETAPLINK)
{ {
const wchar *signupurl = GetServerSignupUrl(); const wchar_t *signupurl = GetServerSignupUrl();
ShellExecuteW(NULL, L"open", signupurl, NULL, NULL, SW_SHOWNORMAL); ShellExecuteW(NULL, L"open", signupurl, NULL, NULL, SW_SHOWNORMAL);
return TRUE; return TRUE;
@ -1380,7 +1380,7 @@ LONG WINAPI plCustomUnhandledExceptionFilter( struct _EXCEPTION_POINTERS *Except
} }
char prodName[256]; char prodName[256];
wchar productString[256]; wchar_t productString[256];
ProductString(productString, arrsize(productString)); ProductString(productString, arrsize(productString));
StrToAnsi(prodName, productString, arrsize(prodName)); StrToAnsi(prodName, productString, arrsize(prodName));
@ -1390,7 +1390,7 @@ LONG WINAPI plCustomUnhandledExceptionFilter( struct _EXCEPTION_POINTERS *Except
/// Print the info out to a log file as well /// Print the info out to a log file as well
hsUNIXStream log; hsUNIXStream log;
wchar fileAndPath[MAX_PATH]; wchar_t fileAndPath[MAX_PATH];
PathGetLogDirectory(fileAndPath, arrsize(fileAndPath)); PathGetLogDirectory(fileAndPath, arrsize(fileAndPath));
PathAddFilename(fileAndPath, fileAndPath, L"stackDump.log", arrsize(fileAndPath)); PathAddFilename(fileAndPath, fileAndPath, L"stackDump.log", arrsize(fileAndPath));
if( log.Open( fileAndPath, L"wt" ) ) if( log.Open( fileAndPath, L"wt" ) )
@ -1430,7 +1430,7 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
gDataServerLocal = true; gDataServerLocal = true;
#endif #endif
const wchar *serverIni = L"server.ini"; const wchar_t *serverIni = L"server.ini";
if (cmdParser.IsSpecified(kArgServerIni)) if (cmdParser.IsSpecified(kArgServerIni))
serverIni = cmdParser.GetString(kArgServerIni); serverIni = cmdParser.GetString(kArgServerIni);
@ -1455,11 +1455,11 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
// if the client was started directly, run the patcher, and shutdown // if the client was started directly, run the patcher, and shutdown
STARTUPINFOW si; STARTUPINFOW si;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
ZERO(si); memset(&si, 0, sizeof(si));
ZERO(pi); memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si); si.cb = sizeof(si);
wchar cmdLine[MAX_PATH]; wchar_t cmdLine[MAX_PATH];
const wchar ** addrs; const wchar_t ** addrs;
if (!eventExists) // if it is missing, assume patcher wasn't launched if (!eventExists) // if it is missing, assume patcher wasn't launched
{ {
@ -1487,7 +1487,7 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
#endif #endif
// Load an optional general.ini // Load an optional general.ini
wchar gipath[MAX_PATH]; wchar_t gipath[MAX_PATH];
PathGetInitDirectory(gipath, arrsize(gipath)); PathGetInitDirectory(gipath, arrsize(gipath));
PathAddFilename(gipath, gipath, L"general.ini", arrsize(gipath)); PathAddFilename(gipath, gipath, L"general.ini", arrsize(gipath));
FILE *generalini = _wfopen(gipath, L"rb"); FILE *generalini = _wfopen(gipath, L"rb");
@ -1547,13 +1547,13 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
bool needExit = false; bool needExit = false;
LoginDialogParam loginParam; LoginDialogParam loginParam;
MemSet(&loginParam, 0, sizeof(loginParam)); memset(&loginParam, 0, sizeof(loginParam));
LoadUserPass(&loginParam); LoadUserPass(&loginParam);
if (!doIntroDialogs && loginParam.remember) { if (!doIntroDialogs && loginParam.remember) {
ENetError auth; ENetError auth;
wchar wusername[kMaxAccountNameLength]; wchar_t wusername[kMaxAccountNameLength];
StrToUnicode(wusername, loginParam.username, arrsize(wusername)); StrToUnicode(wusername, loginParam.username, arrsize(wusername));
NetCommSetAccountUsernamePassword(wusername, loginParam.namePassHash); NetCommSetAccountUsernamePassword(wusername, loginParam.namePassHash);
bool cancelled = AuthenticateNetClientComm(&auth, NULL); bool cancelled = AuthenticateNetClientComm(&auth, NULL);
@ -1616,7 +1616,7 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
gDebugFile = NULL; gDebugFile = NULL;
if ( !plStatusLog::fLoggingOff ) if ( !plStatusLog::fLoggingOff )
{ {
wchar fileAndPath[MAX_PATH]; wchar_t fileAndPath[MAX_PATH];
PathGetLogDirectory(fileAndPath, arrsize(fileAndPath)); PathGetLogDirectory(fileAndPath, arrsize(fileAndPath));
PathAddFilename(fileAndPath, fileAndPath, L"plasmalog.txt", arrsize(fileAndPath)); PathAddFilename(fileAndPath, fileAndPath, L"plasmalog.txt", arrsize(fileAndPath));
gDebugFile = _wfopen(fileAndPath, L"wt"); gDebugFile = _wfopen(fileAndPath, L"wt");
@ -1625,7 +1625,7 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
if (gDebugFile != NULL) if (gDebugFile != NULL)
{ {
char prdName[256]; char prdName[256];
wchar prdString[256]; wchar_t prdString[256];
ProductString(prdString, arrsize(prdString)); ProductString(prdString, arrsize(prdString));
StrToAnsi(prdName, prdString, arrsize(prdName)); StrToAnsi(prdName, prdString, arrsize(prdName));
fprintf(gDebugFile, "%s\n", prdName); fprintf(gDebugFile, "%s\n", prdName);
@ -1635,10 +1635,10 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
// log stackdump.log text if the log exists // log stackdump.log text if the log exists
char stackDumpText[1024]; char stackDumpText[1024];
wchar stackDumpTextW[1024]; wchar_t stackDumpTextW[1024];
memset(stackDumpText, 0, arrsize(stackDumpText)); memset(stackDumpText, 0, arrsize(stackDumpText));
memset(stackDumpTextW, 0, arrsize(stackDumpTextW) * sizeof(wchar)); memset(stackDumpTextW, 0, arrsize(stackDumpTextW) * sizeof(wchar_t));
wchar fileAndPath[MAX_PATH]; wchar_t fileAndPath[MAX_PATH];
PathGetLogDirectory(fileAndPath, arrsize(fileAndPath)); PathGetLogDirectory(fileAndPath, arrsize(fileAndPath));
PathAddFilename(fileAndPath, fileAndPath, L"stackDump.log", arrsize(fileAndPath)); PathAddFilename(fileAndPath, fileAndPath, L"stackDump.log", arrsize(fileAndPath));
FILE *stackDumpLog = _wfopen(fileAndPath, L"r"); FILE *stackDumpLog = _wfopen(fileAndPath, L"r");
@ -1758,7 +1758,7 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nC
return PARABLE_NORMAL_EXIT; return PARABLE_NORMAL_EXIT;
} }
static void GetCryptKey(UInt32* cryptKey, unsigned numElements) static void GetCryptKey(uint32_t* cryptKey, unsigned numElements)
{ {
char volName[] = "C:\\"; char volName[] = "C:\\";
int index = 0; int index = 0;

7
Sources/Plasma/Apps/plClientKey/plClientKey.cpp

@ -40,11 +40,10 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "plClientKey.h" #include "plClientKey.h"
#include "hsWindows.h"
typedef const UInt32* (*GETKEY)(); typedef const uint32_t* (*GETKEY)();
const UInt32* plClientKey::GetKey() const uint32_t* plClientKey::GetKey()
{ {
HMODULE hDll = LoadLibrary("sp.dll"); HMODULE hDll = LoadLibrary("sp.dll");
if (hDll) if (hDll)
@ -52,7 +51,7 @@ const UInt32* plClientKey::GetKey()
GETKEY getKey = (GETKEY)GetProcAddress(hDll, "GetKey"); GETKEY getKey = (GETKEY)GetProcAddress(hDll, "GetKey");
if (getKey) if (getKey)
{ {
static UInt32 key[4]; static uint32_t key[4];
memcpy(key, getKey(), sizeof(key)); memcpy(key, getKey(), sizeof(key));
FreeLibrary(hDll); FreeLibrary(hDll);
return key; return key;

4
Sources/Plasma/Apps/plClientKey/plClientKey.h

@ -42,7 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef plClientKey_h_inc #ifndef plClientKey_h_inc
#define plClientKey_h_inc #define plClientKey_h_inc
#include "hsTypes.h" #include "HeadSpin.h"
// //
// For getting the "SafeDisc protected" encryption key in single player mode // For getting the "SafeDisc protected" encryption key in single player mode
@ -53,7 +53,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// //
namespace plClientKey namespace plClientKey
{ {
const UInt32* GetKey(); const uint32_t* GetKey();
} }
#endif // plClientKey_h_inc #endif // plClientKey_h_inc

98
Sources/Plasma/Apps/plClientPatcher/UruPlayer.cpp

@ -55,19 +55,19 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
* *
***/ ***/
#ifndef PLASMA_EXTERNAL_RELEASE #ifndef PLASMA_EXTERNAL_RELEASE
static const wchar s_manifest[] = L"Internal"; static const wchar_t s_manifest[] = L"Internal";
static const wchar s_macmanifest[] = L"macInternal"; static const wchar_t s_macmanifest[] = L"macInternal";
static const wchar s_thinmanifest[] = L"ThinInternal"; static const wchar_t s_thinmanifest[] = L"ThinInternal";
#else #else
static const wchar s_manifest[] = L"External"; static const wchar_t s_manifest[] = L"External";
static const wchar s_macmanifest[] = L"macExternal"; static const wchar_t s_macmanifest[] = L"macExternal";
static const wchar s_thinmanifest[] = L"ThinExternal"; static const wchar_t s_thinmanifest[] = L"ThinExternal";
#endif #endif
struct ManifestFile struct ManifestFile
{ {
LINK(ManifestFile) link; LINK(ManifestFile) link;
ManifestFile(const wchar clientName[], const wchar downloadName[], const wchar md5val[], int flags, plLauncherInfo *info) ManifestFile(const wchar_t clientName[], const wchar_t downloadName[], const wchar_t md5val[], int flags, plLauncherInfo *info)
{ {
StrCopy(filename, clientName, arrsize(filename)); StrCopy(filename, clientName, arrsize(filename));
StrCopy(zipName, downloadName, arrsize(zipName)); StrCopy(zipName, downloadName, arrsize(zipName));
@ -77,9 +77,9 @@ struct ManifestFile
md5failed = false; md5failed = false;
} }
wchar filename[MAX_PATH]; wchar_t filename[MAX_PATH];
wchar zipName[MAX_PATH]; wchar_t zipName[MAX_PATH];
wchar md5[MAX_PATH]; wchar_t md5[MAX_PATH];
int flags; int flags;
bool md5failed; bool md5failed;
plLauncherInfo *info; plLauncherInfo *info;
@ -88,13 +88,13 @@ struct ManifestFile
class ProgressStream : public plZlibStream { class ProgressStream : public plZlibStream {
public: public:
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
static plLauncherInfo *info; static plLauncherInfo *info;
static long totalBytes; static long totalBytes;
static unsigned progress; static unsigned progress;
// for updating bytes per second // for updating bytes per second
static dword startTime; static uint32_t startTime;
}; };
struct ProcessManifestEntryParam { struct ProcessManifestEntryParam {
@ -107,7 +107,7 @@ struct ProcessManifestEntryParam {
}; };
struct ManifestResult { struct ManifestResult {
wchar group[MAX_PATH]; wchar_t group[MAX_PATH];
ARRAY(NetCliFileManifestEntry) manifest; ARRAY(NetCliFileManifestEntry) manifest;
long * indicator; long * indicator;
plLauncherInfo * info; plLauncherInfo * info;
@ -120,7 +120,7 @@ struct ManifestResult {
static void DownloadCallback ( static void DownloadCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar filename[], const wchar_t filename[],
hsStream * writer hsStream * writer
); );
@ -165,7 +165,7 @@ static long s_perf[kNumPerf];
long ProgressStream::totalBytes; long ProgressStream::totalBytes;
unsigned ProgressStream::progress; unsigned ProgressStream::progress;
plLauncherInfo * ProgressStream::info; plLauncherInfo * ProgressStream::info;
dword ProgressStream::startTime = 0; uint32_t ProgressStream::startTime = 0;
long ProcessManifestEntryParam::progress = 0; long ProcessManifestEntryParam::progress = 0;
long ProcessManifestEntryParam::totalSize = 0; long ProcessManifestEntryParam::totalSize = 0;
double ProcessManifestEntryParam::startTime = 0; double ProcessManifestEntryParam::startTime = 0;
@ -181,9 +181,9 @@ double ProcessManifestEntryParam::startTime = 0;
// leaving clients with older patchers "dead in the water", without // leaving clients with older patchers "dead in the water", without
// a way to play Uru. // a way to play Uru.
#ifdef PLASMA_EXTERNAL_RELEASE #ifdef PLASMA_EXTERNAL_RELEASE
const wchar kPatcherExeFilename[] = L"UruLauncher.exe"; const wchar_t kPatcherExeFilename[] = L"UruLauncher.exe";
#else #else
const wchar kPatcherExeFilename[] = L"plUruLauncher.exe"; const wchar_t kPatcherExeFilename[] = L"plUruLauncher.exe";
#endif #endif
@ -192,9 +192,9 @@ const wchar kPatcherExeFilename[] = L"plUruLauncher.exe";
//============================================================================ //============================================================================
#ifdef PLASMA_EXTERNAL_RELEASE #ifdef PLASMA_EXTERNAL_RELEASE
#ifdef HS_DEBUGGING #ifdef HS_DEBUGGING
static wchar s_clientExeName[] = L"plClient_dbg.exe"; static wchar_t s_clientExeName[] = L"plClient_dbg.exe";
#else #else
static wchar s_clientExeName[] = L"UruExplorer.exe"; static wchar_t s_clientExeName[] = L"UruExplorer.exe";
#endif // HS_DEBUGGING #endif // HS_DEBUGGING
//============================================================================ //============================================================================
@ -202,9 +202,9 @@ static wchar s_clientExeName[] = L"UruExplorer.exe";
//============================================================================ //============================================================================
#else #else
#ifdef HS_DEBUGGING #ifdef HS_DEBUGGING
static wchar s_clientExeName[] = L"plClient_dbg.exe"; static wchar_t s_clientExeName[] = L"plClient_dbg.exe";
#else #else
static wchar s_clientExeName[] = L"plClient.exe"; static wchar_t s_clientExeName[] = L"plClient.exe";
#endif // HS_DEBUGGING #endif // HS_DEBUGGING
#endif // PLASMA_EXTERNAL_RELEASE #endif // PLASMA_EXTERNAL_RELEASE
@ -216,14 +216,14 @@ static wchar s_clientExeName[] = L"plClient.exe";
***/ ***/
//============================================================================ //============================================================================
static void LogHandler (ELogSeverity severity, const wchar msg[]) { static void LogHandler (ELogSeverity severity, const wchar_t msg[]) {
AsyncLogWriteMsg(L"UruPlayer", severity, msg); AsyncLogWriteMsg(L"UruPlayer", severity, msg);
} }
//============================================================================ //============================================================================
static void NetErrorHandler (ENetProtocol protocol, ENetError error) { static void NetErrorHandler (ENetProtocol protocol, ENetError error) {
const wchar * srv; const wchar_t * srv;
switch (protocol) { switch (protocol) {
case kNetProtocolNil: srv = L"Notify"; break; case kNetProtocolNil: srv = L"Notify"; break;
case kNetProtocolCli2File: srv = L"File"; break; case kNetProtocolCli2File: srv = L"File"; break;
@ -287,7 +287,7 @@ static void WaitUruExitProc (void * param) {
*/ */
//============================================================================ //============================================================================
static bool MD5Check (const char filename[], const wchar md5[]) { static bool MD5Check (const char filename[], const wchar_t md5[]) {
// Do md5 check // Do md5 check
char md5copy[MAX_PATH]; char md5copy[MAX_PATH];
plMD5Checksum existingMD5(filename); plMD5Checksum existingMD5(filename);
@ -315,7 +315,7 @@ static void DecompressOgg (ManifestFile *mf) {
break; break;
} }
UInt32 size = reader->GetDataSize(); uint32_t size = reader->GetDataSize();
delete reader; delete reader;
ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, neededBytes; ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, neededBytes;
@ -355,13 +355,13 @@ static void RequestNextManifestFile () {
return; return;
s_manifestQueue.Unlink(nextfile); s_manifestQueue.Unlink(nextfile);
char path[MAX_PATH]; char path[MAX_PATH];
wchar basePath[MAX_PATH]; wchar_t basePath[MAX_PATH];
StrPrintf(path, arrsize(path), "%s%S", s_workingDir, nextfile->filename); StrPrintf(path, arrsize(path), "%s%S", s_workingDir, nextfile->filename);
StrToUnicode(basePath, path, arrsize(basePath)); StrToUnicode(basePath, path, arrsize(basePath));
PathRemoveFilename(basePath, basePath, arrsize(basePath)); PathRemoveFilename(basePath, basePath, arrsize(basePath));
PathCreateDirectory(basePath, kPathCreateDirFlagEntireTree); PathCreateDirectory(basePath, kPathCreateDirFlagEntireTree);
ProgressStream *writer = NEW(ProgressStream); // optimization: dont delete and recreate. Doesn't seem to be working currently, ZLibStream is breaking ProgressStream *writer = new ProgressStream(); // optimization: dont delete and recreate. Doesn't seem to be working currently, ZLibStream is breaking
if(!writer->Open(path, "wb")) if(!writer->Open(path, "wb"))
{ {
writer->Close(); writer->Close();
@ -384,7 +384,7 @@ static void RequestNextManifestFile () {
static void DownloadCallback ( static void DownloadCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar filename[], const wchar_t filename[],
hsStream * writer hsStream * writer
) { ) {
s_numConnectFailures = 0; s_numConnectFailures = 0;
@ -435,7 +435,7 @@ static void DownloadCallback (
#endif // PLASMA_EXTERNAL_RELEASE #endif // PLASMA_EXTERNAL_RELEASE
Shutdown(mf->info); Shutdown(mf->info);
} }
writer = NEW(ProgressStream); writer = new ProgressStream();
if (!writer->Open(path, "wb")) { if (!writer->Open(path, "wb")) {
#ifdef PLASMA_EXTERNAL_RELEASE #ifdef PLASMA_EXTERNAL_RELEASE
MessageBox(nil, s_fileOpenError, "URU Launcher", MB_ICONERROR); MessageBox(nil, s_fileOpenError, "URU Launcher", MB_ICONERROR);
@ -457,7 +457,7 @@ static void DownloadCallback (
if(s_running) if(s_running)
{ {
wchar ext[MAX_EXT]; wchar_t ext[MAX_EXT];
PathSplitPath(mf->filename, nil, nil, nil, ext); PathSplitPath(mf->filename, nil, nil, nil, ext);
if(!StrCmpI(L".ogg", ext)) if(!StrCmpI(L".ogg", ext))
{ {
@ -497,7 +497,7 @@ static void ProcessManifestEntry (void * param, ENetError error) {
s_workingDir, s_workingDir,
p->mr->manifest[p->index].clientName p->mr->manifest[p->index].clientName
); );
dword start = (dword)(TimeGetTime() / kTimeIntervalsPerMs); uint32_t start = (uint32_t)(TimeGetTime() / kTimeIntervalsPerMs);
if(!MD5Check(path, p->mr->manifest[p->index].md5)) { if(!MD5Check(path, p->mr->manifest[p->index].md5)) {
p->mr->critsect.Enter(); p->mr->critsect.Enter();
p->mr->indices.Add(p->index); p->mr->indices.Add(p->index);
@ -506,7 +506,7 @@ static void ProcessManifestEntry (void * param, ENetError error) {
} }
// if we have a file that was cached the MD5 check will be really fast throwing off our approx time remaining. // if we have a file that was cached the MD5 check will be really fast throwing off our approx time remaining.
dword t = (dword)(TimeGetTime() / kTimeIntervalsPerMs - start); uint32_t t = (uint32_t)(TimeGetTime() / kTimeIntervalsPerMs - start);
if(t < 25) if(t < 25)
{ {
// cached file // cached file
@ -542,7 +542,7 @@ static void ProcessManifestEntry (void * param, ENetError error) {
//============================================================================ //============================================================================
static void ProcessManifest (void * param) { static void ProcessManifest (void * param) {
wchar basePath[MAX_PATH]; wchar_t basePath[MAX_PATH];
char path[MAX_PATH]; char path[MAX_PATH];
AtomicAdd(&s_perf[kPerfThreadTaskCount], 1); AtomicAdd(&s_perf[kPerfThreadTaskCount], 1);
@ -617,7 +617,7 @@ static void ProcessManifest (void * param) {
PathRemoveFilename(basePath, basePath, arrsize(basePath)); PathRemoveFilename(basePath, basePath, arrsize(basePath));
PathCreateDirectory(basePath, kPathCreateDirFlagEntireTree); PathCreateDirectory(basePath, kPathCreateDirFlagEntireTree);
ManifestFile * mf = NEW(ManifestFile)( ManifestFile * mf = new ManifestFile(
manifest[index].clientName, manifest[index].clientName,
manifest[index].downloadName, manifest[index].downloadName,
manifest[index].md5, manifest[index].md5,
@ -654,7 +654,7 @@ static void ProcessManifest (void * param) {
} }
} }
} }
DEL(mr); delete mr;
AtomicAdd(&s_perf[kPerfThreadTaskCount], -1); AtomicAdd(&s_perf[kPerfThreadTaskCount], -1);
} }
@ -662,7 +662,7 @@ static void ProcessManifest (void * param) {
static void ManifestCallback ( static void ManifestCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar group[], const wchar_t group[],
const NetCliFileManifestEntry manifest[], const NetCliFileManifestEntry manifest[],
unsigned entryCount unsigned entryCount
){ ){
@ -689,7 +689,7 @@ static void ManifestCallback (
return; return;
} }
ManifestResult * mr = NEW(ManifestResult); ManifestResult * mr = new ManifestResult();
StrCopy(mr->group, group, arrsize(mr->group)); StrCopy(mr->group, group, arrsize(mr->group));
mr->manifest.Set(manifest, entryCount); mr->manifest.Set(manifest, entryCount);
mr->info = info; mr->info = info;
@ -725,7 +725,7 @@ static void ManifestCallback (
static void ThinManifestCallback ( static void ThinManifestCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar group[], const wchar_t group[],
const NetCliFileManifestEntry manifest[], const NetCliFileManifestEntry manifest[],
unsigned entryCount unsigned entryCount
){ ){
@ -788,7 +788,7 @@ static void ThinManifestCallback (
***/ ***/
//============================================================================ //============================================================================
UInt32 ProgressStream::Write(UInt32 byteCount, const void* buffer) { uint32_t ProgressStream::Write(uint32_t byteCount, const void* buffer) {
if(!s_running || s_patchError) if(!s_running || s_patchError)
return 0; return 0;
if(!startTime) { if(!startTime) {
@ -814,7 +814,7 @@ UInt32 ProgressStream::Write(UInt32 byteCount, const void* buffer) {
info->SetBytesRemaining(totalBytes - progress); info->SetBytesRemaining(totalBytes - progress);
if(TimeGetSecondsSince2001Utc() != startTime) if(TimeGetSecondsSince2001Utc() != startTime)
{ {
dword bytesPerSec = (progress ) / (TimeGetSecondsSince2001Utc() - startTime); uint32_t bytesPerSec = (progress ) / (TimeGetSecondsSince2001Utc() - startTime);
info->SetTimeRemaining(bytesPerSec ? (totalBytes - progress) / bytesPerSec : 0); info->SetTimeRemaining(bytesPerSec ? (totalBytes - progress) / bytesPerSec : 0);
} }
} }
@ -826,7 +826,7 @@ UInt32 ProgressStream::Write(UInt32 byteCount, const void* buffer) {
static void FileSrvIpAddressCallback ( static void FileSrvIpAddressCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar addr[] const wchar_t addr[]
) { ) {
NetCliGateKeeperDisconnect(); NetCliGateKeeperDisconnect();
@ -866,7 +866,7 @@ void InitAsyncCore () {
AsyncCoreInitialize(); AsyncCoreInitialize();
AsyncLogInitialize(L"Log", false); AsyncLogInitialize(L"Log", false);
wchar productString[256]; wchar_t productString[256];
ProductString(productString, arrsize(productString)); ProductString(productString, arrsize(productString));
LogMsg(kLogPerf, L"Patcher: %s", productString); LogMsg(kLogPerf, L"Patcher: %s", productString);
} }
@ -902,7 +902,7 @@ void UruPrepProc (void * param) {
s_patchComplete = false; s_patchComplete = false;
s_patchError = false; s_patchError = false;
const wchar ** addrs; const wchar_t ** addrs;
unsigned count; unsigned count;
count = GetGateKeeperSrvHostnames(&addrs); count = GetGateKeeperSrvHostnames(&addrs);
@ -920,7 +920,7 @@ void UruPrepProc (void * param) {
while(ManifestFile *mf = s_manifestQueue.Head()) while(ManifestFile *mf = s_manifestQueue.Head())
{ {
DEL(mf); delete mf;
} }
// If s_patchError, we don't wait around for s_numFiles // If s_patchError, we don't wait around for s_numFiles
// to drop to zero because it never does for reasons // to drop to zero because it never does for reasons
@ -974,11 +974,11 @@ void UruStartProc (void * param) {
plLauncherInfo *info = (plLauncherInfo *) param; plLauncherInfo *info = (plLauncherInfo *) param;
wchar workDir[MAX_PATH]; wchar_t workDir[MAX_PATH];
StrPrintf(workDir, arrsize(workDir), L"%s", info->path); StrPrintf(workDir, arrsize(workDir), L"%s", info->path);
//fprintf(stderr, "URUPlayer StartProc gamePath is:%ws\n", workDir); //fprintf(stderr, "URUPlayer StartProc gamePath is:%ws\n", workDir);
wchar cmdLine[MAX_PATH]; wchar_t cmdLine[MAX_PATH];
StrPrintf(cmdLine, arrsize(cmdLine), L"%s%s %s", workDir, s_clientExeName, info->cmdLine); StrPrintf(cmdLine, arrsize(cmdLine), L"%s%s %s", workDir, s_clientExeName, info->cmdLine);
// Create the named event so the client won't restart us (Windows will clean it up when we exit) // Create the named event so the client won't restart us (Windows will clean it up when we exit)
@ -991,8 +991,8 @@ void UruStartProc (void * param) {
fprintf(stderr, "URUPlayer StartProc, running game process at dir:%ws, cmd:%ws for application:%ws\n", workDir, cmdLine, s_clientExeName); fprintf(stderr, "URUPlayer StartProc, running game process at dir:%ws, cmd:%ws for application:%ws\n", workDir, cmdLine, s_clientExeName);
STARTUPINFOW si; STARTUPINFOW si;
ZERO(si); memset(&si, 0, sizeof(si));
ZERO(s_pi); memset(&s_pi, 0, sizeof(s_pi));
si.cb = sizeof(si); si.cb = sizeof(si);
info->SetText("Launching URU..."); info->SetText("Launching URU...");
@ -1030,4 +1030,4 @@ void UruStartProc (void * param) {
{ {
info->startCallback(kStatusError, nil); info->startCallback(kStatusError, nil);
} }
} }

2
Sources/Plasma/Apps/plClientPatcher/UruPlayer.h

@ -64,4 +64,4 @@ void UruStartProc (void * param);
void PlayerTerminateProc (void * param); void PlayerTerminateProc (void * param);
void PlayerStopProc (void * param); void PlayerStopProc (void * param);
extern const wchar kPatcherExeFilename[]; extern const wchar_t kPatcherExeFilename[];

2
Sources/Plasma/Apps/plFileEncrypt/CMakeLists.txt

@ -12,6 +12,6 @@ set(plFileEncrypt_SOURCES
) )
add_executable(plFileEncrypt ${plFileEncrypt_SOURCES}) add_executable(plFileEncrypt ${plFileEncrypt_SOURCES})
target_link_libraries(plFileEncrypt CoreLib CoreLibExe pnProduct plFile) target_link_libraries(plFileEncrypt CoreLib pnProduct plFile)
source_group("Source Files" FILES ${plFileEncrypt_SOURCES}) source_group("Source Files" FILES ${plFileEncrypt_SOURCES})

4
Sources/Plasma/Apps/plFileEncrypt/main.cpp

@ -42,12 +42,12 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "plFile/hsFiles.h" #include "plFile/hsFiles.h"
#include "plFile/plEncryptedStream.h" #include "plFile/plEncryptedStream.h"
#include "pnProduct/pnProduct.h" #include "pnProduct/pnProduct.h"
#include "hsUtils.h"
void EncryptFiles(const char* dir, const char* ext, bool encrypt); void EncryptFiles(const char* dir, const char* ext, bool encrypt);
void print_version(){ void print_version(){
wchar productString[256]; wchar_t productString[256];
ProductString(productString, arrsize(productString)); ProductString(productString, arrsize(productString));
printf("%S\n\n", productString); printf("%S\n\n", productString);
} }

2
Sources/Plasma/Apps/plFileSecure/CMakeLists.txt

@ -12,6 +12,6 @@ set(plFileSecure_SOURCES
) )
add_executable(plFileSecure ${plFileSecure_SOURCES}) add_executable(plFileSecure ${plFileSecure_SOURCES})
target_link_libraries(plFileSecure CoreLib CoreLibExe pnProduct plFile) target_link_libraries(plFileSecure CoreLib pnProduct plFile)
source_group("Source Files" FILES ${plFileSecure_SOURCES}) source_group("Source Files" FILES ${plFileSecure_SOURCES})

22
Sources/Plasma/Apps/plFileSecure/main.cpp

@ -43,13 +43,13 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "plFile/plFileUtils.h" #include "plFile/plFileUtils.h"
#include "plFile/plSecureStream.h" #include "plFile/plSecureStream.h"
#include "pnProduct/pnProduct.h" #include "pnProduct/pnProduct.h"
#include "hsUtils.h"
#include <time.h> #include <time.h>
#include <string> #include <string>
void print_version() { void print_version() {
wchar productString[256]; wchar_t productString[256];
ProductString(productString, arrsize(productString)); ProductString(productString, arrsize(productString));
printf("%S\n\n", productString); printf("%S\n\n", productString);
} }
@ -75,40 +75,40 @@ void print_help() {
void GenerateKey(bool useDefault) void GenerateKey(bool useDefault)
{ {
UInt32 key[4]; uint32_t key[4];
if (useDefault) if (useDefault)
{ {
unsigned memSize = min(arrsize(key), arrsize(plSecureStream::kDefaultKey)); unsigned memSize = min(arrsize(key), arrsize(plSecureStream::kDefaultKey));
memSize *= sizeof(UInt32); memSize *= sizeof(uint32_t);
memcpy(key, plSecureStream::kDefaultKey, memSize); memcpy(key, plSecureStream::kDefaultKey, memSize);
} }
else else
{ {
srand((unsigned)time(nil)); srand((unsigned)time(nil));
double randNum = (double)rand() / (double)RAND_MAX; // converts to 0..1 double randNum = (double)rand() / (double)RAND_MAX; // converts to 0..1
UInt32 keyNum = (UInt32)(randNum * (double)0xFFFFFFFF); // multiply it by the max unsigned 32-bit int uint32_t keyNum = (uint32_t)(randNum * (double)0xFFFFFFFF); // multiply it by the max unsigned 32-bit int
key[0] = keyNum; key[0] = keyNum;
randNum = (double)rand() / (double)RAND_MAX; randNum = (double)rand() / (double)RAND_MAX;
keyNum = (UInt32)(randNum * (double)0xFFFFFFFF); keyNum = (uint32_t)(randNum * (double)0xFFFFFFFF);
key[1] = keyNum; key[1] = keyNum;
randNum = (double)rand() / (double)RAND_MAX; randNum = (double)rand() / (double)RAND_MAX;
keyNum = (UInt32)(randNum * (double)0xFFFFFFFF); keyNum = (uint32_t)(randNum * (double)0xFFFFFFFF);
key[2] = keyNum; key[2] = keyNum;
randNum = (double)rand() / (double)RAND_MAX; randNum = (double)rand() / (double)RAND_MAX;
keyNum = (UInt32)(randNum * (double)0xFFFFFFFF); keyNum = (uint32_t)(randNum * (double)0xFFFFFFFF);
key[3] = keyNum; key[3] = keyNum;
} }
hsUNIXStream out; hsUNIXStream out;
out.Open(plFileUtils::kKeyFilename, "wb"); out.Open(plFileUtils::kKeyFilename, "wb");
out.Write(sizeof(UInt32) * arrsize(key), (void*)key); out.Write(sizeof(uint32_t) * arrsize(key), (void*)key);
out.Close(); out.Close();
} }
void SecureFiles(std::string dir, std::string ext, UInt32* key) void SecureFiles(std::string dir, std::string ext, uint32_t* key)
{ {
char filePath[256]; char filePath[256];
@ -203,7 +203,7 @@ int main(int argc, char *argv[])
SecureFiles(directory, ext, nil); SecureFiles(directory, ext, nil);
else else
{ {
UInt32 key[4]; uint32_t key[4];
plFileUtils::GetSecureEncryptionKey(plFileUtils::kKeyFilename, key, arrsize(key)); plFileUtils::GetSecureEncryptionKey(plFileUtils::kKeyFilename, key, arrsize(key));
SecureFiles(directory, ext, key); SecureFiles(directory, ext, key);
} }

2
Sources/Plasma/Apps/plLogDecrypt/CMakeLists.txt

@ -12,6 +12,6 @@ set(plLogDecrypt_SOURCES
) )
add_executable(plLogDecrypt ${plLogDecrypt_SOURCES}) add_executable(plLogDecrypt ${plLogDecrypt_SOURCES})
target_link_libraries(plLogDecrypt CoreLib CoreLibExe plStatusLog pnProduct) target_link_libraries(plLogDecrypt CoreLib plStatusLog pnProduct)
source_group("Source Files" FILES ${plLogDecrypt_SOURCES}) source_group("Source Files" FILES ${plLogDecrypt_SOURCES})

16
Sources/Plasma/Apps/plLogDecrypt/plLogDecrypt.cpp

@ -47,8 +47,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsUtils.h"
#include "plStatusLog/plEncryptLogLine.h" #include "plStatusLog/plEncryptLogLine.h"
void IProcessFile(const char *path) void IProcessFile(const char *path)
@ -62,16 +62,16 @@ void IProcessFile(const char *path)
if( fpIn != nil && fpOut != nil) if( fpIn != nil && fpOut != nil)
{ {
UInt8 line[ 2048 ]; uint8_t line[ 2048 ];
while( !feof( fpIn ) ) while( !feof( fpIn ) )
{ {
// Read next string // Read next string
long pos = ftell(fpIn); long pos = ftell(fpIn);
if( pos == -1L ) if( pos == -1L )
break; break;
UInt8 hint = (UInt8)pos; uint8_t hint = (uint8_t)pos;
UInt16 sizeHint = (UInt16)pos; uint16_t sizeHint = (uint16_t)pos;
UInt16 size; uint16_t size;
if( stricmp( path + strlen( path ) - 4, ".log" ) == 0 ) if( stricmp( path + strlen( path ) - 4, ".log" ) == 0 )
{ {
@ -81,14 +81,14 @@ void IProcessFile(const char *path)
int c = fgetc( fpIn ); int c = fgetc( fpIn );
if( c == EOF || c == hint ) if( c == EOF || c == hint )
break; break;
line[ i ] = (UInt8)c; line[ i ] = (uint8_t)c;
} }
line[ i ] = 0; line[ i ] = 0;
size = i; size = i;
} }
else else
{ {
// UInt16 line length is encoded first // uint16_t line length is encoded first
int c = fgetc( fpIn ); int c = fgetc( fpIn );
if( c == EOF ) if( c == EOF )
break; break;

2
Sources/Plasma/Apps/plPageInfo/CMakeLists.txt

@ -13,6 +13,6 @@ set(plPageInfo_SOURCES
) )
add_executable(plPageInfo ${plPageInfo_SOURCES}) add_executable(plPageInfo ${plPageInfo_SOURCES})
target_link_libraries(plPageInfo CoreLib CoreLibExe pnProduct plResMgr plAudioCore) target_link_libraries(plPageInfo CoreLib pnProduct plResMgr plAudioCore)
source_group("Source Files" FILES ${plPageInfo_SOURCES}) source_group("Source Files" FILES ${plPageInfo_SOURCES})

2
Sources/Plasma/Apps/plPageInfo/plAllCreatables.cpp

@ -39,7 +39,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "hsTypes.h" #include "HeadSpin.h"
#include "pnFactory/plCreator.h" #include "pnFactory/plCreator.h"

8
Sources/Plasma/Apps/plPageInfo/plPageInfo.cpp

@ -39,7 +39,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "hsUtils.h"
#include "hsTimer.h" #include "hsTimer.h"
#include "plFile/hsFiles.h" #include "plFile/hsFiles.h"
#include "plFile/plFileUtils.h" #include "plFile/plFileUtils.h"
@ -67,7 +67,7 @@ bool DumpSounds();
//// PrintVersion /////////////////////////////////////////////////////////////// //// PrintVersion ///////////////////////////////////////////////////////////////
void PrintVersion() void PrintVersion()
{ {
wchar productString[256]; wchar_t productString[256];
ProductString(productString, arrsize(productString)); ProductString(productString, arrsize(productString));
printf("%S\n\n", productString); printf("%S\n\n", productString);
} }
@ -129,7 +129,7 @@ int main(int argc, char* argv[])
plResMgrSettings::Get().SetFilterNewerPageVersions(false); plResMgrSettings::Get().SetFilterNewerPageVersions(false);
plResMgrSettings::Get().SetFilterOlderPageVersions(false); plResMgrSettings::Get().SetFilterOlderPageVersions(false);
plResMgrSettings::Get().SetLoadPagesOnInit(false); plResMgrSettings::Get().SetLoadPagesOnInit(false);
gResMgr = TRACKED_NEW plResManager; gResMgr = new plResManager;
hsgResMgr::Init(gResMgr); hsgResMgr::Init(gResMgr);
gResMgr->AddSinglePage(pageFile); gResMgr->AddSinglePage(pageFile);
@ -185,7 +185,7 @@ bool DumpSounds()
const char* filename = buffer->GetFileName(); const char* filename = buffer->GetFileName();
if (filename) if (filename)
{ {
UInt32 flags = 0; uint32_t flags = 0;
if (stricmp(plFileUtils::GetFileExt(filename), "wav") != 0) if (stricmp(plFileUtils::GetFileExt(filename), "wav") != 0)
{ {

4
Sources/Plasma/Apps/plPageOptimizer/main.cpp

@ -63,12 +63,12 @@ int main(int argc, char* argv[])
try try
{ {
#endif #endif
plResManager* resMgr = TRACKED_NEW plResManager; plResManager* resMgr = new plResManager;
hsgResMgr::Init(resMgr); hsgResMgr::Init(resMgr);
// Setup all the crap that needs to be around to load // Setup all the crap that needs to be around to load
plSimulationMgr::Init(); plSimulationMgr::Init();
fontCache = TRACKED_NEW plFontCache; fontCache = new plFontCache;
plPythonFileMod::SetAtConvertTime(); plPythonFileMod::SetAtConvertTime();
#ifndef _DEBUG #ifndef _DEBUG
} catch (...) } catch (...)

36
Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.cpp

@ -135,8 +135,8 @@ void plPageOptimizer::Optimize()
if (loaded) if (loaded)
IRewritePage(); IRewritePage();
UInt32 oldSize = plFileUtils::GetFileSize(fPagePath); uint32_t oldSize = plFileUtils::GetFileSize(fPagePath);
UInt32 newSize = plFileUtils::GetFileSize(fTempPagePath); uint32_t newSize = plFileUtils::GetFileSize(fTempPagePath);
if (!loaded) if (!loaded)
{ {
@ -190,19 +190,19 @@ void plPageOptimizer::IWriteKeyData(hsStream* oldPage, hsStream* newPage, plKey
class plUpdateKeyImp : public plKeyImp class plUpdateKeyImp : public plKeyImp
{ {
public: public:
void SetStartPos(UInt32 startPos) { fStartPos = startPos; } void SetStartPos(uint32_t startPos) { fStartPos = startPos; }
}; };
plUpdateKeyImp* keyImp = (plUpdateKeyImp*)(plKeyImp*)key; plUpdateKeyImp* keyImp = (plUpdateKeyImp*)(plKeyImp*)key;
UInt32 startPos = keyImp->GetStartPos(); uint32_t startPos = keyImp->GetStartPos();
UInt32 len = keyImp->GetDataLen(); uint32_t len = keyImp->GetDataLen();
oldPage->SetPosition(startPos); oldPage->SetPosition(startPos);
if (len > fBuf.size()) if (len > fBuf.size())
fBuf.resize(len); fBuf.resize(len);
oldPage->Read(len, &fBuf[0]); oldPage->Read(len, &fBuf[0]);
UInt32 newStartPos = newPage->GetPosition(); uint32_t newStartPos = newPage->GetPosition();
// If we move any buffers, this page wasn't optimized already // If we move any buffers, this page wasn't optimized already
if (newStartPos != startPos) if (newStartPos != startPos)
@ -223,7 +223,7 @@ void plPageOptimizer::IRewritePage()
const plPageInfo& pageInfo = fPageNode->GetPageInfo(); const plPageInfo& pageInfo = fPageNode->GetPageInfo();
UInt32 dataStart = pageInfo.GetDataStart(); uint32_t dataStart = pageInfo.GetDataStart();
fBuf.resize(dataStart); fBuf.resize(dataStart);
@ -243,31 +243,31 @@ void plPageOptimizer::IRewritePage()
IWriteKeyData(&oldPage, &newPage, fAllKeys[i]); IWriteKeyData(&oldPage, &newPage, fAllKeys[i]);
} }
UInt32 newKeyStart = newPage.GetPosition(); uint32_t newKeyStart = newPage.GetPosition();
UInt32 oldKeyStart = pageInfo.GetIndexStart(); uint32_t oldKeyStart = pageInfo.GetIndexStart();
oldPage.SetPosition(oldKeyStart); oldPage.SetPosition(oldKeyStart);
UInt32 numTypes = oldPage.ReadSwap32(); uint32_t numTypes = oldPage.ReadSwap32();
newPage.WriteSwap32(numTypes); newPage.WriteSwap32(numTypes);
for (UInt32 i = 0; i < numTypes; i++) for (uint32_t i = 0; i < numTypes; i++)
{ {
UInt16 classType = oldPage.ReadSwap16(); uint16_t classType = oldPage.ReadSwap16();
UInt32 len = oldPage.ReadSwap32(); uint32_t len = oldPage.ReadSwap32();
UInt8 flags = oldPage.ReadByte(); uint8_t flags = oldPage.ReadByte();
UInt32 numKeys = oldPage.ReadSwap32(); uint32_t numKeys = oldPage.ReadSwap32();
newPage.WriteSwap16(classType); newPage.WriteSwap16(classType);
newPage.WriteSwap32(len); newPage.WriteSwap32(len);
newPage.WriteByte(flags); newPage.WriteByte(flags);
newPage.WriteSwap32(numKeys); newPage.WriteSwap32(numKeys);
for (UInt32 j = 0; j < numKeys; j++) for (uint32_t j = 0; j < numKeys; j++)
{ {
plUoid uoid; plUoid uoid;
uoid.Read(&oldPage); uoid.Read(&oldPage);
UInt32 startPos = oldPage.ReadSwap32(); uint32_t startPos = oldPage.ReadSwap32();
UInt32 dataLen = oldPage.ReadSwap32(); uint32_t dataLen = oldPage.ReadSwap32();
// Get the new start pos // Get the new start pos
plKeyImp* key = (plKeyImp*)fResMgr->FindKey(uoid); plKeyImp* key = (plKeyImp*)fResMgr->FindKey(uoid);

2
Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.h

@ -59,7 +59,7 @@ protected:
KeyVec fKeyLoadOrder; // The order objects were loaded in KeyVec fKeyLoadOrder; // The order objects were loaded in
KeySet fLoadedKeys; // Keys we've loaded objects for, for quick lookup KeySet fLoadedKeys; // Keys we've loaded objects for, for quick lookup
KeyVec fAllKeys; // All the keys in the page KeyVec fAllKeys; // All the keys in the page
std::vector<UInt8> fBuf; std::vector<uint8_t> fBuf;
bool fOptimized; // True after optimization if the page was already optimized bool fOptimized; // True after optimization if the page was already optimized

1
Sources/Plasma/Apps/plPlasmaUpdate/main.cpp

@ -42,7 +42,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "HeadSpin.h" #include "HeadSpin.h"
#include "plPlasmaUpdate.h" #include "plPlasmaUpdate.h"
#include "jvCoreUtil.h" #include "jvCoreUtil.h"
#include "hsUtils.h"
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{ {

2
Sources/Plasma/Apps/plPlasmaUpdate/plFileGrabber.cpp

@ -126,7 +126,7 @@ bool plNetShareFileGrabber::FileToStream(const char* path, hsStream* stream)
if (fileStream.Open(filePath.c_str())) if (fileStream.Open(filePath.c_str()))
{ {
char* buffer = new char[BUFFER_SIZE]; char* buffer = new char[BUFFER_SIZE];
UInt32 streamSize = fileStream.GetSizeLeft(); uint32_t streamSize = fileStream.GetSizeLeft();
while (streamSize > (BUFFER_SIZE)) while (streamSize > (BUFFER_SIZE))
{ {
fileStream.Read(BUFFER_SIZE, buffer); fileStream.Read(BUFFER_SIZE, buffer);

21
Sources/Plasma/Apps/plPlasmaUpdate/plManifest.cpp

@ -40,7 +40,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "HeadSpin.h" #include "HeadSpin.h"
#include "hsUtils.h"
#include "plManifest.h" #include "plManifest.h"
#include "../plEncryption/plChecksum.h" #include "../plEncryption/plChecksum.h"
@ -55,9 +54,9 @@ public:
char* fFilename; char* fFilename;
plMD5Checksum fSum; plMD5Checksum fSum;
plMD5Checksum fLocalSum; plMD5Checksum fLocalSum;
UInt32 fSize; uint32_t fSize;
UInt32 fCompressedSize; uint32_t fCompressedSize;
UInt32 fFlags; uint32_t fFlags;
}; };
plManifest::plManifest(LogFunc log) : plManifest::plManifest(LogFunc log) :
@ -175,8 +174,8 @@ void plManifest::DownloadUpdates(ProgressFunc progress, plFileGrabber* grabber)
if (localStream.Open(file->fFilename, "wb")) if (localStream.Open(file->fFilename, "wb"))
{ {
char dataBuf[1024]; char dataBuf[1024];
UInt32 sizeLeft = serverStream.GetSizeLeft(); uint32_t sizeLeft = serverStream.GetSizeLeft();
while (UInt32 amtRead = serverStream.Read( (sizeof(dataBuf) > sizeLeft) ? sizeLeft : sizeof(dataBuf), dataBuf)) while (uint32_t amtRead = serverStream.Read( (sizeof(dataBuf) > sizeLeft) ? sizeLeft : sizeof(dataBuf), dataBuf))
{ {
progress(file->fFilename, amtRead); progress(file->fFilename, amtRead);
@ -228,7 +227,7 @@ void plManifest::IWriteCache()
bool openedFile = false; bool openedFile = false;
UInt32 numFiles = 0; uint32_t numFiles = 0;
for (int i = 0; i < fFiles.size(); i++) for (int i = 0; i < fFiles.size(); i++)
{ {
plManifestFile* file = fFiles[i]; plManifestFile* file = fFiles[i];
@ -278,8 +277,8 @@ void plManifest::IReadCache(ProgressFunc progress)
if (s) if (s)
{ {
UInt32 numCached = s->ReadSwap32(); uint32_t numCached = s->ReadSwap32();
UInt32 cacheFileVersion = s->ReadSwap32(); uint32_t cacheFileVersion = s->ReadSwap32();
if (cacheFileVersion != kCacheFileVersion) if (cacheFileVersion != kCacheFileVersion)
{ {
@ -294,7 +293,7 @@ void plManifest::IReadCache(ProgressFunc progress)
{ {
char* name = s->ReadSafeString(); char* name = s->ReadSafeString();
UInt8 checksumBuf[MD5_DIGEST_LENGTH]; uint8_t checksumBuf[MD5_DIGEST_LENGTH];
s->Read(sizeof(checksumBuf), checksumBuf); s->Read(sizeof(checksumBuf), checksumBuf);
plMD5Checksum checksum; plMD5Checksum checksum;
checksum.SetValue(checksumBuf); checksum.SetValue(checksumBuf);
@ -349,7 +348,7 @@ bool plManifest::IDecompressSound(plManifestFile* file)
plAudioFileReader* reader = plAudioFileReader::CreateReader(file->fFilename, plAudioCore::kAll, plAudioFileReader::kStreamNative); plAudioFileReader* reader = plAudioFileReader::CreateReader(file->fFilename, plAudioCore::kAll, plAudioFileReader::kStreamNative);
if (!reader) if (!reader)
return false; return false;
UInt32 size = reader->GetDataSize(); uint32_t size = reader->GetDataSize();
delete reader; delete reader;
if (hsCheckBits(file->fFlags, kSndFlagCacheSplit)) if (hsCheckBits(file->fFlags, kSndFlagCacheSplit))

10
Sources/Plasma/Apps/plPlasmaUpdate/plManifest.h

@ -42,7 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef plManifest_h_inc #ifndef plManifest_h_inc
#define plManifest_h_inc #define plManifest_h_inc
#include "hsTypes.h" #include "HeadSpin.h"
#include "plFileGrabber.h" #include "plFileGrabber.h"
#include <vector> #include <vector>
#include <string> #include <string>
@ -61,8 +61,8 @@ protected:
typedef std::vector<plManifestFile*> FileVec; typedef std::vector<plManifestFile*> FileVec;
FileVec fFiles; FileVec fFiles;
UInt32 fDownloadFiles; uint32_t fDownloadFiles;
UInt32 fDownloadBytes; uint32_t fDownloadBytes;
bool fDirtySums; bool fDirtySums;
@ -86,8 +86,8 @@ public:
void DownloadUpdates(ProgressFunc progress, plFileGrabber* grabber); void DownloadUpdates(ProgressFunc progress, plFileGrabber* grabber);
int NumFiles() { return fFiles.size(); } int NumFiles() { return fFiles.size(); }
UInt32 NumDownloadFiles() { return fDownloadFiles; } uint32_t NumDownloadFiles() { return fDownloadFiles; }
UInt32 DownloadSize() { return fDownloadBytes; } uint32_t DownloadSize() { return fDownloadBytes; }
}; };
#endif // plManifest_h_inc #endif // plManifest_h_inc

1
Sources/Plasma/Apps/plPlasmaUpdate/plPlasmaServers.cpp

@ -41,7 +41,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "plPlasmaServers.h" #include "plPlasmaServers.h"
#include "hsStream.h" #include "hsStream.h"
#include "hsUtils.h"
bool plPlasmaServers::GetServerInfo() bool plPlasmaServers::GetServerInfo()
{ {

2
Sources/Plasma/Apps/plPlasmaUpdate/plPlasmaServers.h

@ -42,7 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef plPlasmaServers_h_inc #ifndef plPlasmaServers_h_inc
#define plPlasmaServers_h_inc #define plPlasmaServers_h_inc
#include "hsTypes.h" #include "HeadSpin.h"
#include <vector> #include <vector>
class plPlasmaServers class plPlasmaServers

7
Sources/Plasma/Apps/plPlasmaUpdate/plPlasmaUpdate.cpp

@ -53,7 +53,6 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "../plUnifiedTime/plUnifiedTime.h" #include "../plUnifiedTime/plUnifiedTime.h"
#include "hsStream.h" #include "hsStream.h"
#include "plManifest.h" #include "plManifest.h"
#include "hsUtils.h"
#include "../plStatusLog/plStatusLog.h" #include "../plStatusLog/plStatusLog.h"
static plPlasmaUpdate* gInst = nil; static plPlasmaUpdate* gInst = nil;
@ -360,7 +359,7 @@ void plPlasmaUpdate::IUpdateServer()
// Get the manifests // Get the manifests
// //
bool gotManifests = IGetManifests(serverRoot, external); bool gotManifests = IGetManifests(serverRoot, external);
UInt32 dlSize = 0; uint32_t dlSize = 0;
fProgressType = kValidating; fProgressType = kValidating;
@ -368,7 +367,7 @@ void plPlasmaUpdate::IUpdateServer()
{ {
int i; int i;
UInt32 numFiles = 0; uint32_t numFiles = 0;
for (i = 0; i < fManifests.size(); i++) for (i = 0; i < fManifests.size(); i++)
numFiles += fManifests[i]->NumFiles(); numFiles += fManifests[i]->NumFiles();
@ -413,7 +412,7 @@ void plPlasmaUpdate::IDownloadUpdates()
int i; int i;
UInt32 dlSize = 0; uint32_t dlSize = 0;
for (i = 0; i < fManifests.size(); i++) for (i = 0; i < fManifests.size(); i++)
dlSize += fManifests[i]->DownloadSize(); dlSize += fManifests[i]->DownloadSize();

2
Sources/Plasma/Apps/plPythonPack/CMakeLists.txt

@ -13,7 +13,7 @@ set(plPythonPack_HEADERS
) )
add_executable(plPythonPack ${plPythonPack_SOURCES} ${plPythonPack_HEADERS}) add_executable(plPythonPack ${plPythonPack_SOURCES} ${plPythonPack_HEADERS})
target_link_libraries(plPythonPack CoreLib CoreLibExe plFile) target_link_libraries(plPythonPack CoreLib plFile)
if(PYTHON_DEBUG_LIBRARY) if(PYTHON_DEBUG_LIBRARY)
target_link_libraries(plPythonPack debug ${PYTHON_DEBUG_LIBRARY}) target_link_libraries(plPythonPack debug ${PYTHON_DEBUG_LIBRARY})

2
Sources/Plasma/Apps/plPythonPack/PythonInterface.cpp

@ -152,7 +152,7 @@ PyObject* PythonInterface::CompileString(const char *command, const char* filena
// //
// PURPOSE : marshals an object into a char string // PURPOSE : marshals an object into a char string
// //
hsBool PythonInterface::DumpObject(PyObject* pyobj, char** pickle, Int32* size) hsBool PythonInterface::DumpObject(PyObject* pyobj, char** pickle, int32_t* size)
{ {
PyObject *s; // the python string object where the marsalled object wil go PyObject *s; // the python string object where the marsalled object wil go
// convert object to a marshalled string python object // convert object to a marshalled string python object

4
Sources/Plasma/Apps/plPythonPack/PythonInterface.h

@ -40,7 +40,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include <Python.h> #include <Python.h>
#include "hsTypes.h" #include "HeadSpin.h"
#include <string> #include <string>
@ -52,7 +52,7 @@ namespace PythonInterface
void addPythonPath(std::string dir); void addPythonPath(std::string dir);
PyObject* CompileString(const char *command, const char* filename); PyObject* CompileString(const char *command, const char* filename);
hsBool DumpObject(PyObject* pyobj, char** pickle, Int32* size); hsBool DumpObject(PyObject* pyobj, char** pickle, int32_t* size);
int getOutputAndReset(char** line=nil); int getOutputAndReset(char** line=nil);
PyObject* CreateModule(const char* module); PyObject* CreateModule(const char* module);
hsBool RunPYC(PyObject* code, PyObject* module); hsBool RunPYC(PyObject* code, PyObject* module);

18
Sources/Plasma/Apps/plPythonPack/main.cpp

@ -91,18 +91,18 @@ void WritePythonFile(std::string fileName, std::string path, hsStream *s)
printf("==Packing %s, ",fileName.c_str()); printf("==Packing %s, ",fileName.c_str());
pyStream.FastFwd(); pyStream.FastFwd();
UInt32 pyFileSize = pyStream.GetPosition(); uint32_t pyFileSize = pyStream.GetPosition();
pyStream.Rewind(); pyStream.Rewind();
glueStream.FastFwd(); glueStream.FastFwd();
UInt32 glueFileSize = glueStream.GetPosition(); uint32_t glueFileSize = glueStream.GetPosition();
glueStream.Rewind(); glueStream.Rewind();
UInt32 totalSize = pyFileSize + glueFileSize + 2; uint32_t totalSize = pyFileSize + glueFileSize + 2;
char *code = new char[totalSize]; char *code = new char[totalSize];
UInt32 amountRead = pyStream.Read(pyFileSize, code); uint32_t amountRead = pyStream.Read(pyFileSize, code);
hsAssert(amountRead == pyFileSize, "Bad read"); hsAssert(amountRead == pyFileSize, "Bad read");
code[pyFileSize] = '\n'; code[pyFileSize] = '\n';
@ -189,7 +189,7 @@ void WritePythonFile(std::string fileName, std::string path, hsStream *s)
// make sure that we have code to save // make sure that we have code to save
if (pythonCode) if (pythonCode)
{ {
Int32 size; int32_t size;
char* pycode; char* pycode;
PythonInterface::DumpObject(pythonCode,&pycode,&size); PythonInterface::DumpObject(pythonCode,&pycode,&size);
@ -420,21 +420,21 @@ void PackDirectory(std::string dir, std::string rootPath, std::string pakName, s
// set to maximum optimization (includes removing __doc__ strings) // set to maximum optimization (includes removing __doc__ strings)
Py_OptimizeFlag = 2; Py_OptimizeFlag = 2;
std::vector<UInt32> filePositions; std::vector<uint32_t> filePositions;
filePositions.resize(fileNames.size()); filePositions.resize(fileNames.size());
for (i = 0; i < fileNames.size(); i++) for (i = 0; i < fileNames.size(); i++)
{ {
// strip '.py' from the file name // strip '.py' from the file name
std::string properFileName = fileNames[i].substr(0, fileNames[i].size()-3); std::string properFileName = fileNames[i].substr(0, fileNames[i].size()-3);
UInt32 initialPos = s.GetPosition(); uint32_t initialPos = s.GetPosition();
WritePythonFile(properFileName, pathNames[i], &s); WritePythonFile(properFileName, pathNames[i], &s);
UInt32 endPos = s.GetPosition(); uint32_t endPos = s.GetPosition();
filePositions[i] = initialPos; filePositions[i] = initialPos;
} }
s.SetPosition(sizeof(UInt32)); s.SetPosition(sizeof(uint32_t));
for (i = 0; i < fileNames.size(); i++) for (i = 0; i < fileNames.size(); i++)
{ {
s.WriteSafeString(fileNames[i].c_str()); s.WriteSafeString(fileNames[i].c_str());

1
Sources/Plasma/Apps/plUruLauncher/CMakeLists.txt

@ -33,7 +33,6 @@ if(PLASMA_EXTERNAL_RELEASE)
set_target_properties(plUruLauncher PROPERTIES OUTPUT_NAME UruLauncher) set_target_properties(plUruLauncher PROPERTIES OUTPUT_NAME UruLauncher)
endif(PLASMA_EXTERNAL_RELEASE) endif(PLASMA_EXTERNAL_RELEASE)
target_link_libraries(plUruLauncher CoreLib) target_link_libraries(plUruLauncher CoreLib)
target_link_libraries(plUruLauncher CoreLibExe)
target_link_libraries(plUruLauncher pfConsoleCore) target_link_libraries(plUruLauncher pfConsoleCore)
target_link_libraries(plUruLauncher plAudioCore) target_link_libraries(plUruLauncher plAudioCore)
target_link_libraries(plUruLauncher plClientPatcher) target_link_libraries(plUruLauncher plClientPatcher)

54
Sources/Plasma/Apps/plUruLauncher/Main.cpp

@ -151,7 +151,7 @@ static CEvent s_dialogCreateEvent(kEventManualReset);
static CCritSect s_critsect; static CCritSect s_critsect;
static LISTDECL(WndEvent, link) s_eventQ; static LISTDECL(WndEvent, link) s_eventQ;
static CEvent s_shutdownEvent(kEventManualReset); static CEvent s_shutdownEvent(kEventManualReset);
static wchar s_workingDir[MAX_PATH]; static wchar_t s_workingDir[MAX_PATH];
static CEvent s_statusEvent(kEventManualReset); static CEvent s_statusEvent(kEventManualReset);
static char s_curlError[CURL_ERROR_SIZE]; static char s_curlError[CURL_ERROR_SIZE];
@ -202,8 +202,8 @@ static void PostEvent (WndEvent *event) {
} }
//============================================================================ //============================================================================
static void LogV (ELogSev sev, const wchar fmt[], va_list args) { static void LogV (ELogSev sev, const wchar_t fmt[], va_list args) {
static struct { FILE * file; const wchar * pre; } s_log[] = { static struct { FILE * file; const wchar_t * pre; } s_log[] = {
{ stdout, L"Inf" }, { stdout, L"Inf" },
{ stderr, L"Err" }, { stderr, L"Err" },
}; };
@ -218,7 +218,7 @@ static void LogV (ELogSev sev, const wchar fmt[], va_list args) {
} }
//============================================================================ //============================================================================
static void Log (ELogSev sev, const wchar fmt[], ...) { static void Log (ELogSev sev, const wchar_t fmt[], ...) {
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
LogV(sev, fmt, args); LogV(sev, fmt, args);
@ -227,7 +227,7 @@ static void Log (ELogSev sev, const wchar fmt[], ...) {
//============================================================================ //============================================================================
// NOTE: Must use LocalFree() on the return value of this function when finished with the string // NOTE: Must use LocalFree() on the return value of this function when finished with the string
static wchar *TranslateErrorCode(DWORD errorCode) { static wchar_t *TranslateErrorCode(DWORD errorCode) {
LPVOID lpMsgBuf; LPVOID lpMsgBuf;
FormatMessageW( FormatMessageW(
@ -236,11 +236,11 @@ static wchar *TranslateErrorCode(DWORD errorCode) {
NULL, NULL,
errorCode, errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(wchar *) &lpMsgBuf, (wchar_t *) &lpMsgBuf,
0, 0,
NULL NULL
); );
return (wchar *)lpMsgBuf; return (wchar_t *)lpMsgBuf;
} }
//============================================================================ //============================================================================
@ -409,7 +409,7 @@ static void DispatchEvents (HWND hwnd) {
DISPATCH(SetBytesRemaining); DISPATCH(SetBytesRemaining);
DEFAULT_FATAL(event->type); DEFAULT_FATAL(event->type);
} }
DEL(event); // unlinks from list delete event; // unlinks from list
} }
#undef DISPATCH #undef DISPATCH
} }
@ -531,7 +531,7 @@ static void WindowThreadProc(void *) {
SetTimer(s_dialog, kEventTimer, 250, 0); SetTimer(s_dialog, kEventTimer, 250, 0);
char productString[256]; char productString[256];
wchar productStringW[256]; wchar_t productStringW[256];
ProductString(productStringW, arrsize(productStringW)); ProductString(productStringW, arrsize(productStringW));
StrToAnsi(productString, productStringW, arrsize(productString)); StrToAnsi(productString, productStringW, arrsize(productString));
SendMessage(GetDlgItem(s_dialog, IDC_PRODUCTSTRING), WM_SETTEXT, 0, (LPARAM) productString); SendMessage(GetDlgItem(s_dialog, IDC_PRODUCTSTRING), WM_SETTEXT, 0, (LPARAM) productString);
@ -740,8 +740,8 @@ int __stdcall WinMain (
){ ){
PF_CONSOLE_INITIALIZE(Core) PF_CONSOLE_INITIALIZE(Core)
wchar token[256]; wchar_t token[256];
const wchar *appCmdLine = AppGetCommandLine(); const wchar_t *appCmdLine = AppGetCommandLine();
StrTokenize(&appCmdLine, token, arrsize(token), WHITESPACE); StrTokenize(&appCmdLine, token, arrsize(token), WHITESPACE);
while(!StrStr(token, L".exe") && !StrStr(token, L".tmp")) while(!StrStr(token, L".exe") && !StrStr(token, L".tmp"))
{ {
@ -750,8 +750,8 @@ int __stdcall WinMain (
while (*appCmdLine == L' ') while (*appCmdLine == L' ')
++appCmdLine; ++appCmdLine;
wchar curPatcherFile[MAX_PATH]; wchar_t curPatcherFile[MAX_PATH];
wchar newPatcherFile[MAX_PATH]; wchar_t newPatcherFile[MAX_PATH];
bool isTempPatcher = false; bool isTempPatcher = false;
PathGetProgramName(curPatcherFile, arrsize(curPatcherFile)); PathGetProgramName(curPatcherFile, arrsize(curPatcherFile));
@ -774,13 +774,13 @@ int __stdcall WinMain (
TGDoCiderDetection (); TGDoCiderDetection ();
s_hInstance = hInstance; s_hInstance = hInstance;
ZERO(s_launcherInfo); memset(&s_launcherInfo, 0, sizeof(s_launcherInfo));
StrPrintf(s_launcherInfo.cmdLine, arrsize(s_launcherInfo.cmdLine), appCmdLine); StrPrintf(s_launcherInfo.cmdLine, arrsize(s_launcherInfo.cmdLine), appCmdLine);
s_launcherInfo.returnCode = 0; s_launcherInfo.returnCode = 0;
curl_global_init(CURL_GLOBAL_ALL); curl_global_init(CURL_GLOBAL_ALL);
const wchar *serverIni = L"server.ini"; const wchar_t *serverIni = L"server.ini";
if(cmdParser.IsSpecified(kArgServerIni)) if(cmdParser.IsSpecified(kArgServerIni))
serverIni = cmdParser.GetString(kArgServerIni); serverIni = cmdParser.GetString(kArgServerIni);
@ -835,9 +835,9 @@ int __stdcall WinMain (
Sleep(1000); Sleep(1000);
if (!PathDeleteFile(newPatcherFile)) { if (!PathDeleteFile(newPatcherFile)) {
wchar error[256]; wchar_t error[256];
DWORD errorCode = GetLastError(); DWORD errorCode = GetLastError();
wchar *msg = TranslateErrorCode(errorCode); wchar_t *msg = TranslateErrorCode(errorCode);
StrPrintf(error, arrsize(error), L"Failed to delete old patcher executable. %s", msg); StrPrintf(error, arrsize(error), L"Failed to delete old patcher executable. %s", msg);
MessageBoxW(GetTopWindow(nil), error, L"Error", MB_OK); MessageBoxW(GetTopWindow(nil), error, L"Error", MB_OK);
@ -845,9 +845,9 @@ int __stdcall WinMain (
break; break;
} }
if (!PathMoveFile(curPatcherFile, newPatcherFile)) { if (!PathMoveFile(curPatcherFile, newPatcherFile)) {
wchar error[256]; wchar_t error[256];
DWORD errorCode = GetLastError(); DWORD errorCode = GetLastError();
wchar *msg = TranslateErrorCode(errorCode); wchar_t *msg = TranslateErrorCode(errorCode);
StrPrintf(error, arrsize(error), L"Failed to replace old patcher executable. %s", msg); StrPrintf(error, arrsize(error), L"Failed to replace old patcher executable. %s", msg);
MessageBoxW(GetTopWindow(nil), error, L"Error", MB_OK); MessageBoxW(GetTopWindow(nil), error, L"Error", MB_OK);
@ -860,11 +860,11 @@ int __stdcall WinMain (
// launch new patcher // launch new patcher
STARTUPINFOW si; STARTUPINFOW si;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
ZERO(si); memset(&si, 0, sizeof(si));
ZERO(pi); memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si); si.cb = sizeof(si);
wchar cmdline[MAX_PATH]; wchar_t cmdline[MAX_PATH];
StrPrintf(cmdline, arrsize(cmdline), L"%s %s", newPatcherFile, s_launcherInfo.cmdLine); StrPrintf(cmdline, arrsize(cmdline), L"%s %s", newPatcherFile, s_launcherInfo.cmdLine);
// we have only successfully patched if we actually launch the new version of the patcher // we have only successfully patched if we actually launch the new version of the patcher
@ -891,7 +891,7 @@ int __stdcall WinMain (
// Clean up old temp files // Clean up old temp files
ARRAY(PathFind) paths; ARRAY(PathFind) paths;
wchar fileSpec[MAX_PATH]; wchar_t fileSpec[MAX_PATH];
PathGetProgramDirectory(fileSpec, arrsize(fileSpec)); PathGetProgramDirectory(fileSpec, arrsize(fileSpec));
PathAddFilename(fileSpec, fileSpec, L"*.tmp", arrsize(fileSpec)); PathAddFilename(fileSpec, fileSpec, L"*.tmp", arrsize(fileSpec));
PathFindFiles(&paths, fileSpec, kPathFlagFile); PathFindFiles(&paths, fileSpec, kPathFlagFile);
@ -937,7 +937,7 @@ int __stdcall WinMain (
// Self-patch failed // Self-patch failed
SetText("Self-patch failed. Exiting..."); SetText("Self-patch failed. Exiting...");
if (!s_shutdown) { if (!s_shutdown) {
wchar str[256]; wchar_t str[256];
StrPrintf(str, arrsize(str), L"Patcher update failed. Error %u, %s", selfPatchResult, NetErrorToString(selfPatchResult)); StrPrintf(str, arrsize(str), L"Patcher update failed. Error %u, %s", selfPatchResult, NetErrorToString(selfPatchResult));
MessageBoxW(GetTopWindow(nil), str, L"Error", MB_OK); MessageBoxW(GetTopWindow(nil), str, L"Error", MB_OK);
} }
@ -990,7 +990,7 @@ void SetReturnCode (DWORD retCode) {
//============================================================================ //============================================================================
void SetProgress (unsigned progress) { void SetProgress (unsigned progress) {
SetProgressEvent *event = NEW(SetProgressEvent); SetProgressEvent *event = new SetProgressEvent();
event->type = kEventSetProgress; event->type = kEventSetProgress;
event->progress = progress; event->progress = progress;
PostEvent(event); PostEvent(event);
@ -998,7 +998,7 @@ void SetProgress (unsigned progress) {
//============================================================================ //============================================================================
void SetText (const char text[]) { void SetText (const char text[]) {
SetTextEvent *event = NEW(SetTextEvent); SetTextEvent *event = new SetTextEvent();
event->type = kEventSetText; event->type = kEventSetText;
StrCopy(event->text, text, arrsize(event->text)); StrCopy(event->text, text, arrsize(event->text));
PostEvent(event); PostEvent(event);
@ -1006,7 +1006,7 @@ void SetText (const char text[]) {
//============================================================================ //============================================================================
void SetStatusText (const char text[]) { void SetStatusText (const char text[]) {
SetTextEvent *event = NEW(SetTextEvent); SetTextEvent *event = new SetTextEvent();
event->type = kEventSetStatusText; event->type = kEventSetStatusText;
StrCopy(event->text, text, arrsize(event->text)); StrCopy(event->text, text, arrsize(event->text));
PostEvent(event); PostEvent(event);

30
Sources/Plasma/Apps/plUruLauncher/SelfPatcher.cpp

@ -56,14 +56,14 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
***/ ***/
#ifndef PLASMA_EXTERNAL_RELEASE #ifndef PLASMA_EXTERNAL_RELEASE
static const wchar s_manifest[] = L"InternalPatcher"; static const wchar_t s_manifest[] = L"InternalPatcher";
#else #else
static const wchar s_manifest[] = L"ExternalPatcher"; static const wchar_t s_manifest[] = L"ExternalPatcher";
#endif #endif
class SelfPatcherStream : public plZlibStream { class SelfPatcherStream : public plZlibStream {
public: public:
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
static plLauncherInfo *info; static plLauncherInfo *info;
static unsigned totalBytes; static unsigned totalBytes;
static unsigned progress; static unsigned progress;
@ -76,7 +76,7 @@ static bool s_downloadComplete;
static long s_numFiles; static long s_numFiles;
static ENetError s_patchResult; static ENetError s_patchResult;
static bool s_updated; static bool s_updated;
static wchar s_newPatcherFile[MAX_PATH]; static wchar_t s_newPatcherFile[MAX_PATH];
/***************************************************************************** /*****************************************************************************
@ -105,7 +105,7 @@ static void NetErrorHandler (ENetProtocol protocol, ENetError error) {
static void DownloadCallback ( static void DownloadCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar filename[], const wchar_t filename[],
hsStream * writer hsStream * writer
) { ) {
if(IS_NET_ERROR(result)) { if(IS_NET_ERROR(result)) {
@ -135,7 +135,7 @@ static void DownloadCallback (
} }
//============================================================================ //============================================================================
static bool MD5Check (const char filename[], const wchar md5[]) { static bool MD5Check (const char filename[], const wchar_t md5[]) {
// Do md5 check // Do md5 check
char md5copy[MAX_PATH]; char md5copy[MAX_PATH];
plMD5Checksum existingMD5(filename); plMD5Checksum existingMD5(filename);
@ -150,7 +150,7 @@ static bool MD5Check (const char filename[], const wchar md5[]) {
static void ManifestCallback ( static void ManifestCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar group[], const wchar_t group[],
const NetCliFileManifestEntry manifest[], const NetCliFileManifestEntry manifest[],
unsigned entryCount unsigned entryCount
) { ) {
@ -180,7 +180,7 @@ static void ManifestCallback (
// MD5 check current patcher against value in manifest // MD5 check current patcher against value in manifest
ASSERT(entryCount == 1); ASSERT(entryCount == 1);
wchar curPatcherFile[MAX_PATH]; wchar_t curPatcherFile[MAX_PATH];
PathGetProgramName(curPatcherFile, arrsize(curPatcherFile)); PathGetProgramName(curPatcherFile, arrsize(curPatcherFile));
StrToAnsi(ansi, curPatcherFile, arrsize(ansi)); StrToAnsi(ansi, curPatcherFile, arrsize(ansi));
if (!MD5Check(ansi, manifest[0].md5)) { if (!MD5Check(ansi, manifest[0].md5)) {
@ -193,7 +193,7 @@ static void ManifestCallback (
StrToAnsi(ansi, s_newPatcherFile, arrsize(ansi)); StrToAnsi(ansi, s_newPatcherFile, arrsize(ansi));
SelfPatcherStream * stream = NEWZERO(SelfPatcherStream); SelfPatcherStream * stream = NEWZERO(SelfPatcherStream);
if (!stream->Open(ansi, "wb")) if (!stream->Open(ansi, "wb"))
ErrorFatal(__LINE__, __FILE__, "Failed to create file: %s, errno: %u", ansi, errno); ErrorAssert(__LINE__, __FILE__, "Failed to create file: %s, errno: %u", ansi, errno);
NetCliFileDownloadRequest(manifest[0].downloadName, stream, DownloadCallback, nil); NetCliFileDownloadRequest(manifest[0].downloadName, stream, DownloadCallback, nil);
} }
@ -206,7 +206,7 @@ static void ManifestCallback (
static void FileSrvIpAddressCallback ( static void FileSrvIpAddressCallback (
ENetError result, ENetError result,
void * param, void * param,
const wchar addr[] const wchar_t addr[]
) { ) {
NetCliGateKeeperDisconnect(); NetCliGateKeeperDisconnect();
@ -236,7 +236,7 @@ static bool SelfPatcherProc (bool * abort, plLauncherInfo *info) {
NetClientInitialize(); NetClientInitialize();
NetClientSetErrorHandler(NetErrorHandler); NetClientSetErrorHandler(NetErrorHandler);
const wchar ** addrs; const wchar_t ** addrs;
unsigned count; unsigned count;
count = GetGateKeeperSrvHostnames(&addrs); count = GetGateKeeperSrvHostnames(&addrs);
@ -263,11 +263,11 @@ static bool SelfPatcherProc (bool * abort, plLauncherInfo *info) {
// launch new patcher // launch new patcher
STARTUPINFOW si; STARTUPINFOW si;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
ZERO(si); memset(&si, 0, sizeof(si));
ZERO(pi); memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si); si.cb = sizeof(si);
wchar cmdline[MAX_PATH]; wchar_t cmdline[MAX_PATH];
StrPrintf(cmdline, arrsize(cmdline), L"%s %s", s_newPatcherFile, info->cmdLine); StrPrintf(cmdline, arrsize(cmdline), L"%s %s", s_newPatcherFile, info->cmdLine);
// we have only successfully patched if we actually launch the new version of the patcher // we have only successfully patched if we actually launch the new version of the patcher
@ -300,7 +300,7 @@ static bool SelfPatcherProc (bool * abort, plLauncherInfo *info) {
***/ ***/
//============================================================================ //============================================================================
UInt32 SelfPatcherStream::Write(UInt32 byteCount, const void* buffer) { uint32_t SelfPatcherStream::Write(uint32_t byteCount, const void* buffer) {
progress += byteCount; progress += byteCount;
float p = (float)progress / (float)totalBytes * 100; // progress float p = (float)progress / (float)totalBytes * 100; // progress
SetProgress( (int)p ); SetProgress( (int)p );

4
Sources/Plasma/Apps/plUruLauncher/plLauncherInfo.h

@ -69,8 +69,8 @@ typedef void (*setTimeRemainingCallback)(unsigned seconds);
typedef void (*setBytesRemainingCallback)(unsigned bytes); typedef void (*setBytesRemainingCallback)(unsigned bytes);
struct plLauncherInfo { struct plLauncherInfo {
wchar path[MAX_PATH]; wchar_t path[MAX_PATH];
wchar cmdLine[512]; wchar_t cmdLine[512];
unsigned buildId; // buildId override unsigned buildId; // buildId override
launcherCallback prepCallback; launcherCallback prepCallback;
launcherCallback initCallback; launcherCallback initCallback;

1
Sources/Plasma/CMakeLists.txt

@ -1,6 +1,5 @@
add_subdirectory(Apps) add_subdirectory(Apps)
add_subdirectory(CoreLib) add_subdirectory(CoreLib)
add_subdirectory(CoreLibExe)
add_subdirectory(FeatureLib) add_subdirectory(FeatureLib)
add_subdirectory(NucleusLib) add_subdirectory(NucleusLib)
add_subdirectory(PubUtilLib) add_subdirectory(PubUtilLib)

10
Sources/Plasma/CoreLib/CMakeLists.txt

@ -19,11 +19,9 @@ set(CoreLib_SOURCES
hsExceptionStack.cpp hsExceptionStack.cpp
hsFastMath.cpp hsFastMath.cpp
hsGeometry3.cpp hsGeometry3.cpp
hsMalloc.cpp
hsMatrix33.cpp hsMatrix33.cpp
hsMatrix44.cpp hsMatrix44.cpp
hsMemory.cpp hsMemory.cpp
hsMMIOStream.cpp
hsQuat.cpp hsQuat.cpp
hsSafeRefCnt.cpp hsSafeRefCnt.cpp
hsSTLStream.cpp hsSTLStream.cpp
@ -59,35 +57,27 @@ set(CoreLib_HEADERS
hsBitVector.h hsBitVector.h
hsBounds.h hsBounds.h
hsColorRGBA.h hsColorRGBA.h
hsConfig.h
hsCritSect.h hsCritSect.h
hsExceptions.h hsExceptions.h
hsFastMath.h hsFastMath.h
hsFixedTypes.h
hsGeometry3.h hsGeometry3.h
hsHashTable.h hsHashTable.h
hsMalloc.h
hsMatrix44.h hsMatrix44.h
hsMemory.h hsMemory.h
hsMMIOStream.h
hsPoint2.h hsPoint2.h
hsQuat.h hsQuat.h
hsQueue.h
hsRefCnt.h hsRefCnt.h
hsSafeRefCnt.h hsSafeRefCnt.h
hsScalar.h
hsStlSortUtils.h hsStlSortUtils.h
hsSTLStream.h hsSTLStream.h
hsStlUtils.h hsStlUtils.h
hsStream.h hsStream.h
hsStringTokenizer.h hsStringTokenizer.h
hsTemplates.h hsTemplates.h
hsTempPointer.h
hsThread.h hsThread.h
hsTypes.h hsTypes.h
hsUtils.h hsUtils.h
hsWide.h hsWide.h
hsWindowHndl.h
hsWindows.h hsWindows.h
pcSmallRect.h pcSmallRect.h
plGeneric.h plGeneric.h

61
Sources/Plasma/CoreLib/HS_POINT2.inc

@ -1,61 +0,0 @@
struct HS_POINT2_NAME {
HS_POINT2_TYPE fX, fY;
HS_POINT2_NAME& Set(HS_POINT2_TYPE x, HS_POINT2_TYPE y)
{
fX = x;
fY = y;
return *this;
}
HS_POINT2_NAME& operator+=(const HS_POINT2_NAME& s)
{
this->fX += s.fX;
this->fY += s.fY;
return *this;
}
HS_POINT2_NAME& operator-=(const HS_POINT2_NAME& s)
{
this->fX -= s.fX;
this->fY -= s.fY;
return *this;
}
#if 0 // Havok reeks
friend int operator==(const HS_POINT2_NAME& s, const HS_POINT2_NAME& t)
{
return (s.fX == t.fX && s.fY == t.fY);
}
friend int operator!=(const HS_POINT2_NAME& s, const HS_POINT2_NAME& t)
{
return !(s == t);
}
#else // Havok reeks
int operator==(const HS_POINT2_NAME& ss) const
{
return (ss.fX == fX && ss.fY == fY);
}
int operator!=(const HS_POINT2_NAME& ss)
{
return !(ss == *this);
}
#endif // Havok reeks
friend HS_POINT2_NAME operator+(const HS_POINT2_NAME& s, const HS_POINT2_NAME& t)
{
HS_POINT2_NAME result;
result.Set(s.fX + t.fX, s.fY + t.fY);
return result;
}
friend HS_POINT2_NAME operator-(const HS_POINT2_NAME& s, const HS_POINT2_NAME& t)
{
HS_POINT2_NAME result;
result.Set(s.fX - t.fX, s.fY - t.fY);
return result;
}
friend HS_POINT2_NAME operator-(const HS_POINT2_NAME& s)
{
HS_POINT2_NAME result = { -s.fX, -s.fY };
return result;
}
#undef HS_POINT2_NAME
#undef HS_POINT2_TYPE

107
Sources/Plasma/CoreLib/HeadSpin.cpp

@ -41,18 +41,12 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "HeadSpin.h" #include "HeadSpin.h"
#include "hsRefCnt.h" #include "hsRefCnt.h"
#include "hsUtils.h"
#include "hsStlUtils.h" #include "hsStlUtils.h"
#include "hsExceptions.h" #include "hsExceptions.h"
#include <math.h>
#if HS_BUILD_FOR_WIN32
#ifdef _MSC_VER #ifdef _MSC_VER
# include <crtdbg.h> /* for _RPT_BASE */ # include <crtdbg.h>
#endif
# define WIN32_LEAN_AND_MEAN
# define WIN32_EXTRA_LEAN
# include <windows.h> // For OutputDebugString()
#endif #endif
@ -88,16 +82,10 @@ void hsDebugMessage (const char message[], long val)
{ {
char s[1024]; char s[1024];
#if HS_BUILD_FOR_WIN32
#define strfmt _snprintf
#else
#define strfmt snprintf
#endif
if (val) if (val)
s[0] = strfmt(&s[1], 1022, "%s: %ld", message, val); s[0] = snprintf(&s[1], 1022, "%s: %ld", message, val);
else else
s[0] = strfmt(&s[1], 1022, "%s", message); s[0] = snprintf(&s[1], 1022, "%s", message);
if (gHSDebugProc) if (gHSDebugProc)
gHSDebugProc(&s[1]); gHSDebugProc(&s[1]);
@ -116,6 +104,93 @@ void hsDebugMessage (const char message[], long val)
} }
#endif #endif
static bool s_GuiAsserts = true;
void ErrorEnableGui(bool enabled)
{
s_GuiAsserts = enabled;
}
void ErrorAssert(int line, const char file[], const char fmt[], ...)
{
#if defined(HS_DEBUGGING) || !defined(PLASMA_EXTERNAL_RELEASE)
char msg[1024];
va_list args;
va_start(args, fmt);
vsnprintf(msg, sizeof(msg), fmt, args);
#ifdef HS_DEBUGGING
if (s_GuiAsserts)
{
if(_CrtDbgReport(_CRT_ASSERT, file, line, NULL, msg))
DebugBreak();
} else
#endif // HS_DEBUGGING
if (DebugIsDebuggerPresent()) {
char str[] = "-------\nASSERTION FAILED:\nFile: %s Line: %i\nMessage: %s\n-------";
DebugMsg(str, file, line, msg);
}
#else
DebugBreakIfDebuggerPresent();
#endif // defined(HS_DEBUGGING) || !defined(PLASMA_EXTERNAL_RELEASE)
}
bool DebugIsDebuggerPresent()
{
#ifdef _MSC_VER
return IsDebuggerPresent();
#else
// FIXME
return false;
#endif
}
void DebugBreakIfDebuggerPresent()
{
#ifdef _MSC_VER
__try
{
__debugbreak();
} __except(EXCEPTION_EXECUTE_HANDLER) {
// Debugger not present or some such shwiz.
// Whatever. Don't crash here.
}
#endif // _MSC_VER
}
void DebugMsg(const char fmt[], ...)
{
char msg[1024];
va_list args;
va_start(args, fmt);
vsnprintf(msg, sizeof(msg), fmt, args);
if (DebugIsDebuggerPresent())
{
#ifdef _MSC_VER
OutputDebugStringA(msg);
OutputDebugStringA("\n");
#endif
} else {
fprintf(stderr, msg);
fprintf(stderr, "\n");
}
}
void ErrorMinimizeAppWindow ()
{
#ifdef HS_BUILD_FOR_WIN32
// If the application's topmost window is a fullscreen
// popup window, minimize it before displaying an error
HWND appWindow = GetActiveWindow();
if ( ((GetWindowLong(appWindow, GWL_STYLE) & WS_POPUP) != 0) )
SetWindowPos(
appWindow,
HWND_NOTOPMOST,
0, 0, // position
0, 0, // size
SWP_HIDEWINDOW | SWP_NOMOVE | SWP_NOSIZE
);
#endif
}
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////

10
Sources/Plasma/CoreLib/HeadSpin.h

@ -42,10 +42,14 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef HeadSpinHDefined #ifndef HeadSpinHDefined
#define HeadSpinHDefined #define HeadSpinHDefined
#include "hsConfig.h" #if (defined(_DEBUG) || defined(UNIX_DEBUG))
// Winsock2 compatibility; winsock2.h must always be included before windows.h =( # define HS_DEBUGGING
#endif // defined(_DEBUG) || defined(UNIX_DENUG)
// Internal Headers
// These are only ever included here :)
#include "hsWindows.h" #include "hsWindows.h"
#include "hsTypes.h" #include "hsTypes.h"
#include "hsMalloc.h" #include "hsUtils.h"
#endif #endif

124
Sources/Plasma/CoreLib/hsBiExpander.h

@ -51,14 +51,14 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <class T> class hsExpander { template <class T> class hsExpander {
private: private:
Int32 fNumPost; int32_t fNumPost;
Int32 fNumPostAlloc; int32_t fNumPostAlloc;
T* fArray; T* fArray;
Int32 fGrowBy; // default = 0, to double int32_t fGrowBy; // default = 0, to double
Int32 fMinSize; // default = 1, min == 1 int32_t fMinSize; // default = 1, min == 1
Int32 fCurrent; int32_t fCurrent;
hsExpander(const hsExpander& x); // make it passed as ref or pointer hsExpander(const hsExpander& x); // make it passed as ref or pointer
@ -66,29 +66,29 @@ private:
public: public:
enum { kMissingIndex = -1 }; enum { kMissingIndex = -1 };
hsExpander(Int32 minSize = 1, Int32 growBy = 0); hsExpander(int32_t minSize = 1, int32_t growBy = 0);
virtual ~hsExpander(); virtual ~hsExpander();
hsExpander<T>& operator=(const hsExpander<T>&orig) { return Copy(orig); } hsExpander<T>& operator=(const hsExpander<T>&orig) { return Copy(orig); }
hsExpander<T>& Copy(const hsExpander<T>& orig); hsExpander<T>& Copy(const hsExpander<T>& orig);
void SetCount(int cnt) { if( cnt >= fNumPostAlloc )IExpand(cnt); fNumPost = cnt; } void SetCount(int cnt) { if( cnt >= fNumPostAlloc )IExpand(cnt); fNumPost = cnt; }
Int32 GetCount() const { return fNumPost; } int32_t GetCount() const { return fNumPost; }
hsBool Empty() const { return GetCount() == 0; } hsBool Empty() const { return GetCount() == 0; }
const T& Get(Int32 index) const; const T& Get(int32_t index) const;
Int32 Get(Int32 index, Int32 count, T data[]) const; int32_t Get(int32_t index, int32_t count, T data[]) const;
Int32 Find(const T&) const; // returns kMissingIndex if not found int32_t Find(const T&) const; // returns kMissingIndex if not found
void SetArray(T* a, Int32 cnt); void SetArray(T* a, int32_t cnt);
T* GetArray() { return fArray; } T* GetArray() { return fArray; }
T& operator[]( Int32 index ); T& operator[]( int32_t index );
Int32 Append(const T&); // returns t's index int32_t Append(const T&); // returns t's index
T* Append(); T* Append();
Int32 Push(const T& t) { return Append(t); } int32_t Push(const T& t) { return Append(t); }
T* Push() { return Append(); } T* Push() { return Append(); }
T* Top() { return fNumPost ? fArray + fNumPost-1 : nil; } T* Top() { return fNumPost ? fArray + fNumPost-1 : nil; }
Int32 Pop(T* t); // returns count of remaining int32_t Pop(T* t); // returns count of remaining
Int32 Pop(); int32_t Pop();
void Reset(); // clears out everything void Reset(); // clears out everything
T& Head() { return fArray[0]; } T& Head() { return fArray[0]; }
@ -111,7 +111,7 @@ hsExpander<T>& hsExpander<T>::Copy(const hsExpander<T>& orig)
} }
template <class T> template <class T>
void hsExpander<T>::SetArray(T* a, Int32 cnt) void hsExpander<T>::SetArray(T* a, int32_t cnt)
{ {
delete [] fArray; delete [] fArray;
if( a ) if( a )
@ -122,12 +122,12 @@ void hsExpander<T>::SetArray(T* a, Int32 cnt)
template <class T> template <class T>
void hsExpander<T>::IExpand(int newSize) void hsExpander<T>::IExpand(int newSize)
{ {
Int32 newPostAlloc = fNumPostAlloc; int32_t newPostAlloc = fNumPostAlloc;
if( !newPostAlloc ) if( !newPostAlloc )
newPostAlloc++; newPostAlloc++;
while( newPostAlloc <= newSize ) while( newPostAlloc <= newSize )
newPostAlloc = fGrowBy ? newPostAlloc + fGrowBy : newPostAlloc << 1; newPostAlloc = fGrowBy ? newPostAlloc + fGrowBy : newPostAlloc << 1;
T* newArray = TRACKED_NEW T[newPostAlloc]; T* newArray = new T[newPostAlloc];
int i; int i;
for( i = 0; i < fNumPost; i++ ) for( i = 0; i < fNumPost; i++ )
newArray[i] = fArray[i]; newArray[i] = fArray[i];
@ -137,7 +137,7 @@ void hsExpander<T>::IExpand(int newSize)
} }
template <class T> template <class T>
hsExpander<T>::hsExpander(Int32 minSize, Int32 growBy) hsExpander<T>::hsExpander(int32_t minSize, int32_t growBy)
{ {
hsThrowIfBadParam(minSize < 0); hsThrowIfBadParam(minSize < 0);
hsThrowIfBadParam(growBy < 0); hsThrowIfBadParam(growBy < 0);
@ -145,7 +145,7 @@ hsExpander<T>::hsExpander(Int32 minSize, Int32 growBy)
fMinSize = minSize+1; fMinSize = minSize+1;
fGrowBy = growBy; fGrowBy = growBy;
fArray = TRACKED_NEW T[fMinSize]; fArray = new T[fMinSize];
fNumPostAlloc = fMinSize; fNumPostAlloc = fMinSize;
fNumPost = 0; fNumPost = 0;
@ -170,7 +170,7 @@ void hsExpander<T>::Last()
} }
template <class T> template <class T>
T& hsExpander<T>::operator[]( Int32 index ) T& hsExpander<T>::operator[]( int32_t index )
{ {
hsDebugCode(hsThrowIfBadParam((index < 0)||(index >= fNumPost));) hsDebugCode(hsThrowIfBadParam((index < 0)||(index >= fNumPost));)
@ -178,7 +178,7 @@ T& hsExpander<T>::operator[]( Int32 index )
} }
template <class T> template <class T>
const T& hsExpander<T>::Get( Int32 index ) const const T& hsExpander<T>::Get( int32_t index ) const
{ {
hsDebugCode(hsThrowIfBadParam((index < 0)||(index >= fNumPost));) hsDebugCode(hsThrowIfBadParam((index < 0)||(index >= fNumPost));)
@ -186,7 +186,7 @@ const T& hsExpander<T>::Get( Int32 index ) const
} }
template <class T> template <class T>
Int32 hsExpander<T>::Get(Int32 index, Int32 count, T data[]) const int32_t hsExpander<T>::Get(int32_t index, int32_t count, T data[]) const
{ {
if( count > 0 ) if( count > 0 )
{ hsThrowIfNilParam(data); { hsThrowIfNilParam(data);
@ -201,7 +201,7 @@ Int32 hsExpander<T>::Get(Int32 index, Int32 count, T data[]) const
} }
template <class T> template <class T>
Int32 hsExpander<T>::Find(const T& obj) const int32_t hsExpander<T>::Find(const T& obj) const
{ {
for (int i = 0; i < fNumPost; i++) for (int i = 0; i < fNumPost; i++)
if (fArray[i] == obj) if (fArray[i] == obj)
@ -210,7 +210,7 @@ Int32 hsExpander<T>::Find(const T& obj) const
} }
template <class T> template <class T>
Int32 hsExpander<T>::Append(const T& obj) int32_t hsExpander<T>::Append(const T& obj)
{ {
hsAssert(!(fNumPost >= fNumPostAlloc), "Must be less"); hsAssert(!(fNumPost >= fNumPostAlloc), "Must be less");
if( fNumPost == fNumPostAlloc-1 ) if( fNumPost == fNumPostAlloc-1 )
@ -229,7 +229,7 @@ T* hsExpander<T>::Append()
} }
template <class T> template <class T>
Int32 hsExpander<T>::Pop(T*t) int32_t hsExpander<T>::Pop(T*t)
{ {
hsThrowIfBadParam(Empty()); hsThrowIfBadParam(Empty());
--fNumPost; --fNumPost;
@ -239,7 +239,7 @@ Int32 hsExpander<T>::Pop(T*t)
} }
template <class T> template <class T>
Int32 hsExpander<T>::Pop() int32_t hsExpander<T>::Pop()
{ {
hsThrowIfBadParam(Empty()); hsThrowIfBadParam(Empty());
--fNumPost; --fNumPost;
@ -257,16 +257,16 @@ void hsExpander<T>::Reset()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <class T> class hsBiExpander { template <class T> class hsBiExpander {
private: private:
Int32 fNumPre; int32_t fNumPre;
Int32 fNumPost; int32_t fNumPost;
Int32 fNumPreAlloc; int32_t fNumPreAlloc;
Int32 fNumPostAlloc; int32_t fNumPostAlloc;
T* fArray; T* fArray;
Int32 fGrowBy; // default = 0, to double int32_t fGrowBy; // default = 0, to double
Int32 fMinSize; // default = 1, min == 1 int32_t fMinSize; // default = 1, min == 1
Int32 fCurrent; int32_t fCurrent;
hsBiExpander<T>& operator=(const hsBiExpander<T>&); // don't allow assignment hsBiExpander<T>& operator=(const hsBiExpander<T>&); // don't allow assignment
hsBiExpander(const hsBiExpander<T>&); // make it passed as ref or pointer hsBiExpander(const hsBiExpander<T>&); // make it passed as ref or pointer
@ -275,26 +275,26 @@ private:
public: public:
enum { kMissingIndex = -1 }; enum { kMissingIndex = -1 };
hsBiExpander(Int32 minSize = 1, Int32 growBy = 0); hsBiExpander(int32_t minSize = 1, int32_t growBy = 0);
virtual ~hsBiExpander(); virtual ~hsBiExpander();
Int32 GetFirst() const { return -fNumPre; } int32_t GetFirst() const { return -fNumPre; }
Int32 GetCount() const { return fNumPre + fNumPost; } int32_t GetCount() const { return fNumPre + fNumPost; }
hsBool Empty() const { return GetCount() == 0; } hsBool Empty() const { return GetCount() == 0; }
const T& Get(Int32 index) const; const T& Get(int32_t index) const;
Int32 Get(Int32 index, Int32 count, T data[]) const; int32_t Get(int32_t index, int32_t count, T data[]) const;
Int32 Find(const T&) const; // returns kMissingIndex if not found int32_t Find(const T&) const; // returns kMissingIndex if not found
void SetArray(T* a, Int32 cnt, Int32 numPre=0); void SetArray(T* a, int32_t cnt, int32_t numPre=0);
T** GetArray() { return fArray - fNumPre; } T** GetArray() { return fArray - fNumPre; }
T& operator[]( Int32 index ); T& operator[]( int32_t index );
T* Append(); // returns t's index T* Append(); // returns t's index
T* Push(); // returns t's index T* Push(); // returns t's index
Int32 Append(const T&); // returns t's index int32_t Append(const T&); // returns t's index
Int32 Push(const T&); // returns t's index int32_t Push(const T&); // returns t's index
Int32 Pop(T*t = nil) { return PopHead(t); } // returns count of remaining int32_t Pop(T*t = nil) { return PopHead(t); } // returns count of remaining
Int32 PopHead(T*t = nil); // returns count of remaining int32_t PopHead(T*t = nil); // returns count of remaining
Int32 PopTail(T*t = nil); // returns count of remaining int32_t PopTail(T*t = nil); // returns count of remaining
void Reset(); // clears out everything void Reset(); // clears out everything
T& Head() { return fArray[-fNumPre]; } T& Head() { return fArray[-fNumPre]; }
@ -308,7 +308,7 @@ public:
}; };
template <class T> template <class T>
void hsBiExpander<T>::SetArray(T* a, Int32 cnt, Int32 numPre) void hsBiExpander<T>::SetArray(T* a, int32_t cnt, int32_t numPre)
{ {
if( !numPre ) if( !numPre )
Reset(); Reset();
@ -323,8 +323,8 @@ void hsBiExpander<T>::SetArray(T* a, Int32 cnt, Int32 numPre)
template <class T> template <class T>
void hsBiExpander<T>::IExpand(int newSize, hsBool towardEnd) void hsBiExpander<T>::IExpand(int newSize, hsBool towardEnd)
{ {
Int32 newPreAlloc = fNumPreAlloc; int32_t newPreAlloc = fNumPreAlloc;
Int32 newPostAlloc = fNumPostAlloc; int32_t newPostAlloc = fNumPostAlloc;
if( towardEnd ) if( towardEnd )
{ {
if( !newPostAlloc ) if( !newPostAlloc )
@ -339,7 +339,7 @@ void hsBiExpander<T>::IExpand(int newSize, hsBool towardEnd)
while( newPreAlloc <= newSize ) while( newPreAlloc <= newSize )
newPreAlloc = fGrowBy ? newPreAlloc + fGrowBy : newPreAlloc << 1; newPreAlloc = fGrowBy ? newPreAlloc + fGrowBy : newPreAlloc << 1;
} }
T* newArray = TRACKED_NEW T[newPreAlloc + newPostAlloc]; T* newArray = new T[newPreAlloc + newPostAlloc];
newArray += newPreAlloc; newArray += newPreAlloc;
int i; int i;
for( i = -fNumPre; i < fNumPost; i++ ) for( i = -fNumPre; i < fNumPost; i++ )
@ -353,7 +353,7 @@ void hsBiExpander<T>::IExpand(int newSize, hsBool towardEnd)
} }
template <class T> template <class T>
hsBiExpander<T>::hsBiExpander(Int32 minSize, Int32 growBy) hsBiExpander<T>::hsBiExpander(int32_t minSize, int32_t growBy)
{ {
hsThrowIfBadParam(minSize < 0); hsThrowIfBadParam(minSize < 0);
hsThrowIfBadParam(growBy < 0); hsThrowIfBadParam(growBy < 0);
@ -361,7 +361,7 @@ hsBiExpander<T>::hsBiExpander(Int32 minSize, Int32 growBy)
fMinSize = minSize+1; fMinSize = minSize+1;
fGrowBy = growBy; fGrowBy = growBy;
fArray = TRACKED_NEW T[fMinSize << 1]; fArray = new T[fMinSize << 1];
fNumPreAlloc = fNumPostAlloc = fMinSize; fNumPreAlloc = fNumPostAlloc = fMinSize;
fArray += fNumPreAlloc; fArray += fNumPreAlloc;
@ -387,7 +387,7 @@ void hsBiExpander<T>::Last()
} }
template <class T> template <class T>
T& hsBiExpander<T>::operator[]( Int32 index ) T& hsBiExpander<T>::operator[]( int32_t index )
{ {
hsDebugCode(hsThrowIfBadParam((index < -fNumPre)||(index >= fNumPost));) hsDebugCode(hsThrowIfBadParam((index < -fNumPre)||(index >= fNumPost));)
@ -395,7 +395,7 @@ T& hsBiExpander<T>::operator[]( Int32 index )
} }
template <class T> template <class T>
const T& hsBiExpander<T>::Get( Int32 index ) const const T& hsBiExpander<T>::Get( int32_t index ) const
{ {
hsDebugCode(hsThrowIfBadParam((index < -fNumPre)||(index >= fNumPost));) hsDebugCode(hsThrowIfBadParam((index < -fNumPre)||(index >= fNumPost));)
@ -403,7 +403,7 @@ const T& hsBiExpander<T>::Get( Int32 index ) const
} }
template <class T> template <class T>
Int32 hsBiExpander<T>::Get(Int32 index, Int32 count, T data[]) const int32_t hsBiExpander<T>::Get(int32_t index, int32_t count, T data[]) const
{ {
if( count > 0 ) if( count > 0 )
{ hsThrowIfNilParam(data); { hsThrowIfNilParam(data);
@ -418,7 +418,7 @@ Int32 hsBiExpander<T>::Get(Int32 index, Int32 count, T data[]) const
} }
template <class T> template <class T>
Int32 hsBiExpander<T>::Find(const T& obj) const int32_t hsBiExpander<T>::Find(const T& obj) const
{ {
for (int i = -fNumPre; i < fNumPost; i++) for (int i = -fNumPre; i < fNumPost; i++)
if (fArray[i] == obj) if (fArray[i] == obj)
@ -445,7 +445,7 @@ T* hsBiExpander<T>::Push()
} }
template <class T> template <class T>
Int32 hsBiExpander<T>::Append(const T& obj) int32_t hsBiExpander<T>::Append(const T& obj)
{ {
hsAssert(!(fNumPost >= fNumPostAlloc), "Must be less"); hsAssert(!(fNumPost >= fNumPostAlloc), "Must be less");
if( fNumPost == fNumPostAlloc-1 ) if( fNumPost == fNumPostAlloc-1 )
@ -455,7 +455,7 @@ Int32 hsBiExpander<T>::Append(const T& obj)
} }
template <class T> template <class T>
Int32 hsBiExpander<T>::Push(const T& obj) int32_t hsBiExpander<T>::Push(const T& obj)
{ {
hsAssert(!(fNumPre >= fNumPreAlloc), "Must be less"); hsAssert(!(fNumPre >= fNumPreAlloc), "Must be less");
if( ++fNumPre == fNumPreAlloc ) if( ++fNumPre == fNumPreAlloc )
@ -465,7 +465,7 @@ Int32 hsBiExpander<T>::Push(const T& obj)
} }
template <class T> template <class T>
Int32 hsBiExpander<T>::PopHead(T*t) int32_t hsBiExpander<T>::PopHead(T*t)
{ {
hsThrowIfBadParam(Empty()); hsThrowIfBadParam(Empty());
if( t ) if( t )
@ -475,7 +475,7 @@ Int32 hsBiExpander<T>::PopHead(T*t)
} }
template <class T> template <class T>
Int32 hsBiExpander<T>::PopTail(T*t) int32_t hsBiExpander<T>::PopTail(T*t)
{ {
hsThrowIfBadParam(Empty()); hsThrowIfBadParam(Empty());
--fNumPost; --fNumPost;

20
Sources/Plasma/CoreLib/hsBitVector.cpp

@ -40,7 +40,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsStream.h" #include "hsStream.h"
#include "hsBitVector.h" #include "hsBitVector.h"
#include "hsTemplates.h" #include "hsTemplates.h"
@ -62,18 +62,18 @@ hsBitVector::hsBitVector(int b, ...)
va_end( vl ); va_end( vl );
} }
hsBitVector::hsBitVector(const hsTArray<Int16>& src) hsBitVector::hsBitVector(const hsTArray<int16_t>& src)
: fBitVectors(nil), : fBitVectors(nil),
fNumBitVectors(0) fNumBitVectors(0)
{ {
FromList(src); FromList(src);
} }
void hsBitVector::IGrow(UInt32 newNumBitVectors) void hsBitVector::IGrow(uint32_t newNumBitVectors)
{ {
hsAssert(newNumBitVectors > fNumBitVectors, "Growing smaller"); hsAssert(newNumBitVectors > fNumBitVectors, "Growing smaller");
UInt32 *old = fBitVectors; uint32_t *old = fBitVectors;
fBitVectors = TRACKED_NEW UInt32[newNumBitVectors]; fBitVectors = new uint32_t[newNumBitVectors];
int i; int i;
for( i = 0; i < fNumBitVectors; i++ ) for( i = 0; i < fNumBitVectors; i++ )
fBitVectors[i] = old[i]; fBitVectors[i] = old[i];
@ -95,8 +95,8 @@ hsBitVector& hsBitVector::Compact()
for( hiVec = fNumBitVectors-1; (hiVec >= 0)&& !fBitVectors[hiVec]; --hiVec ); for( hiVec = fNumBitVectors-1; (hiVec >= 0)&& !fBitVectors[hiVec]; --hiVec );
if( hiVec >= 0 ) if( hiVec >= 0 )
{ {
UInt32 *old = fBitVectors; uint32_t *old = fBitVectors;
fBitVectors = TRACKED_NEW UInt32[++hiVec]; fBitVectors = new uint32_t[++hiVec];
int i; int i;
for( i = 0; i < hiVec; i++ ) for( i = 0; i < hiVec; i++ )
fBitVectors[i] = old[i]; fBitVectors[i] = old[i];
@ -119,7 +119,7 @@ void hsBitVector::Read(hsStream* s)
if( fNumBitVectors ) if( fNumBitVectors )
{ {
delete [] fBitVectors; delete [] fBitVectors;
fBitVectors = TRACKED_NEW UInt32[fNumBitVectors]; fBitVectors = new uint32_t[fNumBitVectors];
int i; int i;
for( i = 0; i < fNumBitVectors; i++ ) for( i = 0; i < fNumBitVectors; i++ )
s->LogReadLE(&fBitVectors[i],"BitVector"); s->LogReadLE(&fBitVectors[i],"BitVector");
@ -135,7 +135,7 @@ void hsBitVector::Write(hsStream* s) const
s->WriteLE32(fBitVectors[i]); s->WriteLE32(fBitVectors[i]);
} }
hsTArray<Int16>& hsBitVector::Enumerate(hsTArray<Int16>& dst) const hsTArray<int16_t>& hsBitVector::Enumerate(hsTArray<int16_t>& dst) const
{ {
dst.SetCount(0); dst.SetCount(0);
hsBitIterator iter(*this); hsBitIterator iter(*this);
@ -148,7 +148,7 @@ hsTArray<Int16>& hsBitVector::Enumerate(hsTArray<Int16>& dst) const
return dst; return dst;
} }
hsBitVector& hsBitVector::FromList(const hsTArray<Int16>& src) hsBitVector& hsBitVector::FromList(const hsTArray<int16_t>& src)
{ {
Clear(); Clear();
int i; int i;

76
Sources/Plasma/CoreLib/hsBitVector.h

@ -43,7 +43,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsBitVector_inc #ifndef hsBitVector_inc
#define hsBitVector_inc #define hsBitVector_inc
#include "hsTypes.h" #include "HeadSpin.h"
template <class T> class hsTArray; template <class T> class hsTArray;
class hsStream; class hsStream;
@ -51,17 +51,17 @@ class hsStream;
class hsBitVector { class hsBitVector {
protected: protected:
UInt32* fBitVectors; uint32_t* fBitVectors;
UInt32 fNumBitVectors; uint32_t fNumBitVectors;
void IGrow(UInt32 newNumBitVectors); void IGrow(uint32_t newNumBitVectors);
friend class hsBitIterator; friend class hsBitIterator;
public: public:
hsBitVector(const hsBitVector& other); hsBitVector(const hsBitVector& other);
hsBitVector(UInt32 which) : fBitVectors(nil), fNumBitVectors(0) { SetBit(which); } hsBitVector(uint32_t which) : fBitVectors(nil), fNumBitVectors(0) { SetBit(which); }
hsBitVector(int b, ...); // list of one or more integer bits to set. -1 (or any negative) terminates the list (e.g. hsBitVector(0,1,4,-1); hsBitVector(int b, ...); // list of one or more integer bits to set. -1 (or any negative) terminates the list (e.g. hsBitVector(0,1,4,-1);
hsBitVector(const hsTArray<Int16>& list); // sets bit for each int in list hsBitVector(const hsTArray<int16_t>& list); // sets bit for each int in list
hsBitVector() : fBitVectors(nil), fNumBitVectors(0) {} hsBitVector() : fBitVectors(nil), fNumBitVectors(0) {}
virtual ~hsBitVector() { Reset(); } virtual ~hsBitVector() { Reset(); }
@ -73,17 +73,17 @@ public:
int operator!=(const hsBitVector& other) const { return !(*this == other); } int operator!=(const hsBitVector& other) const { return !(*this == other); }
hsBitVector& operator=(const hsBitVector& other); // will wind up identical hsBitVector& operator=(const hsBitVector& other); // will wind up identical
hsBool ClearBit(UInt32 which) { return SetBit(which, 0); } // returns previous state hsBool ClearBit(uint32_t which) { return SetBit(which, 0); } // returns previous state
hsBool SetBit(UInt32 which, hsBool on = true); // returns previous state hsBool SetBit(uint32_t which, hsBool on = true); // returns previous state
hsBool IsBitSet(UInt32 which) const; // returns current state hsBool IsBitSet(uint32_t which) const; // returns current state
hsBool ToggleBit(UInt32 which); // returns previous state hsBool ToggleBit(uint32_t which); // returns previous state
hsBitVector& RemoveBit(UInt32 which); // removes bit, sliding higher bits down to fill the gap. hsBitVector& RemoveBit(uint32_t which); // removes bit, sliding higher bits down to fill the gap.
friend inline int Overlap(const hsBitVector& lhs, const hsBitVector& rhs) { return lhs.Overlap(rhs); } friend inline int Overlap(const hsBitVector& lhs, const hsBitVector& rhs) { return lhs.Overlap(rhs); }
hsBool Overlap(const hsBitVector& other) const; hsBool Overlap(const hsBitVector& other) const;
hsBool Empty() const; hsBool Empty() const;
hsBool operator[](UInt32 which) const { return IsBitSet(which); } hsBool operator[](uint32_t which) const { return IsBitSet(which); }
friend inline hsBitVector operator&(const hsBitVector& lhs, const hsBitVector& rhs); // See Overlap() friend inline hsBitVector operator&(const hsBitVector& lhs, const hsBitVector& rhs); // See Overlap()
friend inline hsBitVector operator|(const hsBitVector& lhs, const hsBitVector& rhs); friend inline hsBitVector operator|(const hsBitVector& lhs, const hsBitVector& rhs);
@ -96,19 +96,19 @@ public:
hsBitVector& operator-=(const hsBitVector& other); // return me w/ other's bits turned off hsBitVector& operator-=(const hsBitVector& other); // return me w/ other's bits turned off
hsBitVector& Compact(); hsBitVector& Compact();
hsBitVector& SetSize(UInt32 numBits) { ClearBit(numBits+1); return *this; } hsBitVector& SetSize(uint32_t numBits) { ClearBit(numBits+1); return *this; }
UInt32 GetSize() { return fNumBitVectors << 5; } uint32_t GetSize() { return fNumBitVectors << 5; }
// integer level access // integer level access
UInt32 GetNumBitVectors() const { return fNumBitVectors; } uint32_t GetNumBitVectors() const { return fNumBitVectors; }
UInt32 GetBitVector(int i) const { return fBitVectors[i]; } uint32_t GetBitVector(int i) const { return fBitVectors[i]; }
void SetNumBitVectors(UInt32 n) { Reset(); fNumBitVectors=n; fBitVectors = TRACKED_NEW UInt32[n]; } void SetNumBitVectors(uint32_t n) { Reset(); fNumBitVectors=n; fBitVectors = new uint32_t[n]; }
void SetBitVector(int i, UInt32 val) { fBitVectors[i]=val; } void SetBitVector(int i, uint32_t val) { fBitVectors[i]=val; }
// Do dst.SetCount(0), then add each set bit's index into dst, returning dst. // Do dst.SetCount(0), then add each set bit's index into dst, returning dst.
hsTArray<Int16>& Enumerate(hsTArray<Int16>& dst) const; hsTArray<int16_t>& Enumerate(hsTArray<int16_t>& dst) const;
// this->Clear(), then set all bits listed in src, returning *this. // this->Clear(), then set all bits listed in src, returning *this.
hsBitVector& FromList(const hsTArray<Int16>& src); hsBitVector& FromList(const hsTArray<int16_t>& src);
void Read(hsStream* s); void Read(hsStream* s);
void Write(hsStream* s) const; void Write(hsStream* s) const;
@ -118,7 +118,7 @@ inline hsBitVector::hsBitVector(const hsBitVector& other)
{ {
if( 0 != (fNumBitVectors = other.fNumBitVectors) ) if( 0 != (fNumBitVectors = other.fNumBitVectors) )
{ {
fBitVectors = TRACKED_NEW UInt32[fNumBitVectors]; fBitVectors = new uint32_t[fNumBitVectors];
int i; int i;
for( i = 0; i < fNumBitVectors; i++ ) for( i = 0; i < fNumBitVectors; i++ )
fBitVectors[i] = other.fBitVectors[i]; fBitVectors[i] = other.fBitVectors[i];
@ -160,7 +160,7 @@ inline hsBitVector& hsBitVector::operator=(const hsBitVector& other)
{ {
Reset(); Reset();
fNumBitVectors = other.fNumBitVectors; fNumBitVectors = other.fNumBitVectors;
fBitVectors = TRACKED_NEW UInt32[fNumBitVectors]; fBitVectors = new uint32_t[fNumBitVectors];
} }
else else
{ {
@ -295,12 +295,12 @@ inline hsBitVector& hsBitVector::Set(int upToBit)
{ {
if( upToBit >= 0 ) if( upToBit >= 0 )
{ {
UInt32 major = upToBit >> 5; uint32_t major = upToBit >> 5;
UInt32 minor = 1 << (upToBit & 0x1f); uint32_t minor = 1 << (upToBit & 0x1f);
if( major >= fNumBitVectors ) if( major >= fNumBitVectors )
IGrow(major+1); IGrow(major+1);
UInt32 i; uint32_t i;
for( i = 0; i < major; i++ ) for( i = 0; i < major; i++ )
fBitVectors[i] = 0xffffffff; fBitVectors[i] = 0xffffffff;
for( i = 1; i <= minor && i > 0; i <<= 1 ) for( i = 1; i <= minor && i > 0; i <<= 1 )
@ -315,18 +315,18 @@ inline hsBitVector& hsBitVector::Set(int upToBit)
return *this; return *this;
} }
inline hsBool hsBitVector::IsBitSet(UInt32 which) const inline hsBool hsBitVector::IsBitSet(uint32_t which) const
{ {
UInt32 major = which >> 5; uint32_t major = which >> 5;
return return
(major < fNumBitVectors) (major < fNumBitVectors)
&& (0 != (fBitVectors[major] & 1 << (which & 0x1f))); && (0 != (fBitVectors[major] & 1 << (which & 0x1f)));
} }
inline hsBool hsBitVector::SetBit(UInt32 which, hsBool on) inline hsBool hsBitVector::SetBit(uint32_t which, hsBool on)
{ {
UInt32 major = which >> 5; uint32_t major = which >> 5;
UInt32 minor = 1 << (which & 0x1f); uint32_t minor = 1 << (which & 0x1f);
if( major >= fNumBitVectors ) if( major >= fNumBitVectors )
IGrow(major+1); IGrow(major+1);
hsBool ret = 0 != (fBitVectors[major] & minor); hsBool ret = 0 != (fBitVectors[major] & minor);
@ -341,10 +341,10 @@ inline hsBool hsBitVector::SetBit(UInt32 which, hsBool on)
return ret; return ret;
} }
inline hsBool hsBitVector::ToggleBit(UInt32 which) inline hsBool hsBitVector::ToggleBit(uint32_t which)
{ {
UInt32 major = which >> 5; uint32_t major = which >> 5;
UInt32 minor = 1 << (which & 0x1f); uint32_t minor = 1 << (which & 0x1f);
if( major >= fNumBitVectors ) if( major >= fNumBitVectors )
IGrow(major); IGrow(major);
hsBool ret = 0 != (fBitVectors[major] & minor); hsBool ret = 0 != (fBitVectors[major] & minor);
@ -355,14 +355,14 @@ inline hsBool hsBitVector::ToggleBit(UInt32 which)
return ret; return ret;
} }
inline hsBitVector& hsBitVector::RemoveBit(UInt32 which) inline hsBitVector& hsBitVector::RemoveBit(uint32_t which)
{ {
UInt32 major = which >> 5; uint32_t major = which >> 5;
if( major >= fNumBitVectors ) if( major >= fNumBitVectors )
return *this; return *this;
UInt32 minor = 1 << (which & 0x1f); uint32_t minor = 1 << (which & 0x1f);
UInt32 lowMask = minor-1; uint32_t lowMask = minor-1;
UInt32 hiMask = ~(lowMask); uint32_t hiMask = ~(lowMask);
fBitVectors[major] = (fBitVectors[major] & lowMask) fBitVectors[major] = (fBitVectors[major] & lowMask)
| ((fBitVectors[major] >> 1) & hiMask); | ((fBitVectors[major] >> 1) & hiMask);

464
Sources/Plasma/CoreLib/hsBounds.cpp

File diff suppressed because it is too large Load Diff

48
Sources/Plasma/CoreLib/hsBounds.h

@ -68,7 +68,7 @@ class hsBounds
protected: protected:
hsBoundsType fType; hsBoundsType fType;
public: public:
static const hsScalar kRealSmall; static const float kRealSmall;
hsBounds() : fType(kBoundsUninitialized) { }; hsBounds() : fType(kBoundsUninitialized) { };
@ -98,7 +98,7 @@ public:
kIsSphere = 0x2 kIsSphere = 0x2
}; };
protected: protected:
mutable UInt32 fBounds3Flags; mutable uint32_t fBounds3Flags;
hsPoint3 fMins; hsPoint3 fMins;
hsPoint3 fMaxs; hsPoint3 fMaxs;
mutable hsPoint3 fCenter; mutable hsPoint3 fCenter;
@ -130,7 +130,7 @@ public:
virtual void GetCorners(hsPoint3 *b) const; virtual void GetCorners(hsPoint3 *b) const;
const hsPoint3& GetMins() const; const hsPoint3& GetMins() const;
const hsPoint3& GetMaxs() const; const hsPoint3& GetMaxs() const;
hsScalar GetMaxDim() const; // Computes the answer float GetMaxDim() const; // Computes the answer
const hsPoint3& GetCenter() const; // Computes the answer if not already there const hsPoint3& GetCenter() const; // Computes the answer if not already there
virtual hsBool IsInside(const hsPoint3* pos) const; // ok for full/empty virtual hsBool IsInside(const hsPoint3* pos) const; // ok for full/empty
virtual void TestPlane(const hsVector3 &n, hsPoint2 &depth) const; virtual void TestPlane(const hsVector3 &n, hsPoint2 &depth) const;
@ -139,10 +139,10 @@ public:
// Test according to my axes only, doesn't check other's axes // Test according to my axes only, doesn't check other's axes
// neg, pos, zero == disjoint, I contain other, overlap // neg, pos, zero == disjoint, I contain other, overlap
virtual Int32 TestBound(const hsBounds3& other) const; virtual int32_t TestBound(const hsBounds3& other) const;
static hsScalar ClosestPointToLine(const hsPoint3 *p, const hsPoint3 *v0, const hsPoint3 *v1, hsPoint3 *out); static float ClosestPointToLine(const hsPoint3 *p, const hsPoint3 *v0, const hsPoint3 *v1, hsPoint3 *out);
static hsScalar ClosestPointToInfiniteLine(const hsPoint3* p, const hsVector3* v, hsPoint3* out); static float ClosestPointToInfiniteLine(const hsPoint3* p, const hsVector3* v, hsPoint3* out);
virtual void Read(hsStream*); virtual void Read(hsStream*);
virtual void Write(hsStream*); virtual void Write(hsStream*);
@ -183,7 +183,7 @@ inline const hsPoint3& hsBounds3::GetCenter() const
return fCenter; return fCenter;
} }
inline hsScalar hsBounds3::GetMaxDim() const inline float hsBounds3::GetMaxDim() const
{ {
hsAssert(kBoundsNormal == fType, "Invalid type for GetMaxDim"); hsAssert(kBoundsNormal == fType, "Invalid type for GetMaxDim");
return hsMaximum(hsMaximum(fMaxs.fX-fMins.fX, fMaxs.fY-fMins.fY), fMaxs.fZ-fMins.fZ); return hsMaximum(hsMaximum(fMaxs.fX-fMins.fX, fMaxs.fY-fMins.fY), fMaxs.fZ-fMins.fZ);
@ -198,7 +198,7 @@ private:
hsBool fCenterValid; hsBool fCenterValid;
hsPoint3 fCenter; hsPoint3 fCenter;
hsPlane3 *fPlanes; hsPlane3 *fPlanes;
UInt32 fNumPlanes; uint32_t fNumPlanes;
public: public:
hsBoundsOriented() : fPlanes(nil),fNumPlanes(0),fCenterValid(false) {} hsBoundsOriented() : fPlanes(nil),fNumPlanes(0),fCenterValid(false) {}
virtual ~hsBoundsOriented() { if (fPlanes) delete [] fPlanes; } virtual ~hsBoundsOriented() { if (fPlanes) delete [] fPlanes; }
@ -209,7 +209,7 @@ public:
void SetCenter(const hsBoundsOriented* b) { fCenter=b->GetCenter(); fCenterValid = true; } void SetCenter(const hsBoundsOriented* b) { fCenter=b->GetCenter(); fCenterValid = true; }
hsPoint3 GetCenter() const; hsPoint3 GetCenter() const;
void SetNumberPlanes(UInt32 n); void SetNumberPlanes(uint32_t n);
hsPlane3* GetPlane(int i) { return &fPlanes[i]; } hsPlane3* GetPlane(int i) { return &fPlanes[i]; }
int GetNumPlanes() { return fNumPlanes; } int GetNumPlanes() { return fNumPlanes; }
@ -218,7 +218,7 @@ public:
// These set type to kBounds Normal // These set type to kBounds Normal
// //
virtual void Reset(const hsBounds3*); virtual void Reset(const hsBounds3*);
void SetPlane(UInt32 i, hsPlane3 *p); void SetPlane(uint32_t i, hsPlane3 *p);
// //
// Only valid for kBounds Normal // Only valid for kBounds Normal
@ -241,13 +241,13 @@ protected:
kAxisOneZero =(1<<21), kAxisOneZero =(1<<21),
kAxisTwoZero =(1<<22) kAxisTwoZero =(1<<22)
}; };
mutable UInt32 fExtFlags; mutable uint32_t fExtFlags;
hsPoint3 fCorner; hsPoint3 fCorner;
hsVector3 fAxes[3]; hsVector3 fAxes[3];
mutable hsPoint2 fDists[3]; mutable hsPoint2 fDists[3];
mutable hsScalar fRadius; mutable float fRadius;
hsBool IAxisIsZero(UInt32 i) const { return (fExtFlags & (1 << (20+i))) != 0; }; hsBool IAxisIsZero(uint32_t i) const { return (fExtFlags & (1 << (20+i))) != 0; };
void IMakeSphere() const; void IMakeSphere() const;
void IMakeDists() const; void IMakeDists() const;
void IMakeMinsMaxs(); void IMakeMinsMaxs();
@ -276,7 +276,7 @@ public:
virtual void Transform(const hsMatrix44 *m); virtual void Transform(const hsMatrix44 *m);
virtual void Translate(const hsVector3 &v); virtual void Translate(const hsVector3 &v);
virtual hsScalar GetRadius() const; virtual float GetRadius() const;
virtual void GetAxes(hsVector3 *fAxis0, hsVector3 *fAxis1, hsVector3 *fAxis2) const; virtual void GetAxes(hsVector3 *fAxis0, hsVector3 *fAxis1, hsVector3 *fAxis2) const;
virtual hsPoint3 *GetCorner(hsPoint3 *c) const { *c = (fExtFlags & kAxisAligned ? fMins : fCorner); return c; } virtual hsPoint3 *GetCorner(hsPoint3 *c) const { *c = (fExtFlags & kAxisAligned ? fMins : fCorner); return c; }
virtual void GetCorners(hsPoint3 *b) const; virtual void GetCorners(hsPoint3 *b) const;
@ -285,36 +285,36 @@ public:
virtual hsBool IsInside(const hsPoint3* pos) const; // ok for full/empty virtual hsBool IsInside(const hsPoint3* pos) const; // ok for full/empty
virtual void TestPlane(const hsVector3 &n, hsPoint2 &depth) const; virtual void TestPlane(const hsVector3 &n, hsPoint2 &depth) const;
virtual Int32 TestPoints(int n, const hsPoint3 *pList) const; // pos,neg,zero == allout, allin, cut virtual int32_t TestPoints(int n, const hsPoint3 *pList) const; // pos,neg,zero == allout, allin, cut
// Test according to my axes only, doesn't check other's axes // Test according to my axes only, doesn't check other's axes
// neg, pos, zero == disjoint, I contain other, overlap // neg, pos, zero == disjoint, I contain other, overlap
virtual Int32 TestBound(const hsBounds3Ext& other) const; virtual int32_t TestBound(const hsBounds3Ext& other) const;
virtual void TestPlane(const hsVector3 &n, const hsVector3 &myVel, hsPoint2 &depth) const; virtual void TestPlane(const hsVector3 &n, const hsVector3 &myVel, hsPoint2 &depth) const;
virtual void TestPlane(const hsPlane3 *p, const hsVector3 &myVel, hsPoint2 &depth) const; virtual void TestPlane(const hsPlane3 *p, const hsVector3 &myVel, hsPoint2 &depth) const;
virtual Int32 TestPoints(int n, const hsPoint3 *pList, const hsVector3 &ptVel) const; // pos,neg,zero == allout, allin, cut virtual int32_t TestPoints(int n, const hsPoint3 *pList, const hsVector3 &ptVel) const; // pos,neg,zero == allout, allin, cut
virtual hsBool ISectBB(const hsBounds3Ext &other, const hsVector3 &myVel) const; virtual hsBool ISectBB(const hsBounds3Ext &other, const hsVector3 &myVel) const;
virtual hsBool ISectBB(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const; virtual hsBool ISectBB(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const;
virtual hsBool ISectABB(const hsBounds3Ext &other, const hsVector3 &myVel) const; virtual hsBool ISectABB(const hsBounds3Ext &other, const hsVector3 &myVel) const;
virtual hsBool ISectBS(const hsBounds3Ext &other, const hsVector3 &myVel) const; virtual hsBool ISectBS(const hsBounds3Ext &other, const hsVector3 &myVel) const;
virtual Int32 IClosestISect(const hsBounds3Ext& other, const hsVector3& myVel, virtual int32_t IClosestISect(const hsBounds3Ext& other, const hsVector3& myVel,
hsScalar* tClose, hsScalar* tImpact) const; float* tClose, float* tImpact) const;
virtual hsBool ISectBoxBS(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const; virtual hsBool ISectBoxBS(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const;
virtual hsBool ISectBSBox(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const; virtual hsBool ISectBSBox(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const;
virtual hsBool ISectBoxBS(const hsBounds3Ext &other, const hsVector3 &myVel) const; virtual hsBool ISectBoxBS(const hsBounds3Ext &other, const hsVector3 &myVel) const;
virtual hsBool ISectBSBS(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const; virtual hsBool ISectBSBS(const hsBounds3Ext &other, const hsVector3 &myVel, hsHitInfoExt *hit) const;
virtual hsBool ISectLine(const hsPoint3* from, const hsPoint3* to) const; virtual hsBool ISectLine(const hsPoint3* from, const hsPoint3* to) const;
virtual hsBool ISectCone(const hsPoint3* from, const hsPoint3* to, hsScalar radius) const; virtual hsBool ISectCone(const hsPoint3* from, const hsPoint3* to, float radius) const;
virtual hsBool ISectRayBS(const hsPoint3& from, const hsPoint3& to, hsPoint3& at) const; virtual hsBool ISectRayBS(const hsPoint3& from, const hsPoint3& to, hsPoint3& at) const;
virtual void Read(hsStream *s); virtual void Read(hsStream *s);
virtual void Write(hsStream *s); virtual void Write(hsStream *s);
}; };
inline hsScalar hsBounds3Ext::GetRadius() const inline float hsBounds3Ext::GetRadius() const
{ {
if( !(fExtFlags & kSphereSet) ) if( !(fExtFlags & kSphereSet) )
IMakeSphere(); IMakeSphere();
@ -323,7 +323,7 @@ inline hsScalar hsBounds3Ext::GetRadius() const
class hsHitInfoExt { class hsHitInfoExt {
public: public:
hsScalar fDepth; float fDepth;
hsVector3 fNormal; hsVector3 fNormal;
hsVector3 fDelPos; hsVector3 fDelPos;
@ -333,9 +333,9 @@ public:
hsHitInfoExt(const hsPoint3 *ctr, const hsVector3& offset) { fRootCenter=ctr; fDelPos=offset; }; hsHitInfoExt(const hsPoint3 *ctr, const hsVector3& offset) { fRootCenter=ctr; fDelPos=offset; };
void Set(const hsBounds3Ext *m, const hsVector3* n, hsScalar d) void Set(const hsBounds3Ext *m, const hsVector3* n, float d)
{ fDepth = d; fBoxBnd = m; fNormal = *n; fOtherBoxBnd = nil; } { fDepth = d; fBoxBnd = m; fNormal = *n; fOtherBoxBnd = nil; }
void Set(const hsBounds3Ext *m, const hsBounds3Ext *o, const hsVector3 &norm, hsScalar d) void Set(const hsBounds3Ext *m, const hsBounds3Ext *o, const hsVector3 &norm, float d)
{ fDepth = d; fBoxBnd = m, fOtherBoxBnd = o; fNormal = norm; } { fDepth = d; fBoxBnd = m, fOtherBoxBnd = o; fNormal = norm; }
}; };
#endif // hsBounds_inc #endif // hsBounds_inc

43
Sources/Plasma/CoreLib/hsColorRGBA.h

@ -43,15 +43,14 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsColorRGBA_inc #ifndef hsColorRGBA_inc
#define hsColorRGBA_inc #define hsColorRGBA_inc
#include "hsScalar.h"
#include "hsStream.h" #include "hsStream.h"
struct hsColorRGBA { struct hsColorRGBA {
hsScalar r,g,b,a; float r,g,b,a;
hsRGBAColor32 ToRGBA32() const; hsRGBAColor32 ToRGBA32() const;
hsColorRGBA& Set(hsScalar red, hsScalar grn, hsScalar blu, hsScalar alp) { r = red; g = grn; b = blu; a = alp; return *this; } hsColorRGBA& Set(float red, float grn, float blu, float alp) { r = red; g = grn; b = blu; a = alp; return *this; }
hsBool operator==(const hsColorRGBA&c) const { return (r==c.r)&&(g==c.g)&&(b==c.b)&&(a==c.a); } hsBool operator==(const hsColorRGBA&c) const { return (r==c.r)&&(g==c.g)&&(b==c.b)&&(a==c.a); }
hsBool operator!=(const hsColorRGBA&c) const { return !(c == *this); } hsBool operator!=(const hsColorRGBA&c) const { return !(c == *this); }
@ -65,12 +64,12 @@ struct hsColorRGBA {
friend inline hsColorRGBA operator-(const hsColorRGBA& s, const hsColorRGBA& t); friend inline hsColorRGBA operator-(const hsColorRGBA& s, const hsColorRGBA& t);
hsColorRGBA& operator-=(const hsColorRGBA& s); hsColorRGBA& operator-=(const hsColorRGBA& s);
friend inline hsColorRGBA operator*(const hsColorRGBA& c, const hsScalar s); friend inline hsColorRGBA operator*(const hsColorRGBA& c, const float s);
friend inline hsColorRGBA operator*(const hsScalar s, const hsColorRGBA& c); friend inline hsColorRGBA operator*(const float s, const hsColorRGBA& c);
hsColorRGBA& operator*=(const hsScalar s); hsColorRGBA& operator*=(const float s);
hsColorRGBA& FromARGB32(UInt32 c); hsColorRGBA& FromARGB32(uint32_t c);
UInt32 ToARGB32() const; uint32_t ToARGB32() const;
void Read(hsStream *stream); void Read(hsStream *stream);
void Write(hsStream *stream) const; void Write(hsStream *stream) const;
@ -91,22 +90,22 @@ inline void hsColorRGBA::Write(hsStream *s) const
s->WriteLEScalar(a); s->WriteLEScalar(a);
} }
inline hsColorRGBA& hsColorRGBA::FromARGB32(UInt32 c) inline hsColorRGBA& hsColorRGBA::FromARGB32(uint32_t c)
{ {
const hsScalar oo255 = 1.f / 255.f; const float oo255 = 1.f / 255.f;
a = hsScalar((c >> 24) & 0xff) * oo255; a = float((c >> 24) & 0xff) * oo255;
r = hsScalar((c >> 16) & 0xff) * oo255; r = float((c >> 16) & 0xff) * oo255;
g = hsScalar((c >> 8) & 0xff) * oo255; g = float((c >> 8) & 0xff) * oo255;
b = hsScalar((c >> 0) & 0xff) * oo255; b = float((c >> 0) & 0xff) * oo255;
return *this; return *this;
} }
inline UInt32 hsColorRGBA::ToARGB32() const inline uint32_t hsColorRGBA::ToARGB32() const
{ {
return (UInt32(a * 255.99f) << 24) return (uint32_t(a * 255.99f) << 24)
| (UInt32(r * 255.99f) << 16) | (uint32_t(r * 255.99f) << 16)
| (UInt32(g * 255.99f) << 8) | (uint32_t(g * 255.99f) << 8)
| (UInt32(b * 255.99f) << 0); | (uint32_t(b * 255.99f) << 0);
} }
inline hsColorRGBA operator+(const hsColorRGBA& s, const hsColorRGBA& t) inline hsColorRGBA operator+(const hsColorRGBA& s, const hsColorRGBA& t)
@ -151,16 +150,16 @@ inline hsColorRGBA& hsColorRGBA::operator-=(const hsColorRGBA& s)
return *this; return *this;
} }
inline hsColorRGBA operator*(const hsColorRGBA& t, const hsScalar s) inline hsColorRGBA operator*(const hsColorRGBA& t, const float s)
{ {
hsColorRGBA res; hsColorRGBA res;
return res.Set(s * t.r, s * t.g, s * t.b, s * t.a); return res.Set(s * t.r, s * t.g, s * t.b, s * t.a);
} }
inline hsColorRGBA operator*(const hsScalar s, const hsColorRGBA&t) inline hsColorRGBA operator*(const float s, const hsColorRGBA&t)
{ {
return t * s; return t * s;
} }
inline hsColorRGBA& hsColorRGBA::operator*=(const hsScalar s) inline hsColorRGBA& hsColorRGBA::operator*=(const float s)
{ {
r *= s; r *= s;
g *= s; g *= s;

128
Sources/Plasma/CoreLib/hsConfig.h

@ -1,128 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#include "HeadSpin.h"
#ifndef hsConfigDefined
#define hsConfigDefined
#ifndef SERVER
# define CLIENT
#endif
//////////////////// Change the 1s and 0s //////////////////////
#define HS_CAN_USE_FLOAT 1
#define HS_SCALAR_IS_FLOAT 1
#define HS_PIN_MATH_OVERFLOW 0 // This forces hsWide versions of FixMath routines
#define HS_DEBUG_MATH_OVERFLOW 0 // This calls hsDebugMessage on k[Pos,Neg]Infinity
//////////////////// Specific Compiler Stuff This Section is computed ////////////
#if defined(_WIN32)
#define HS_BUILD_FOR_WIN32 1
#elif defined(__unix__)
#define HS_BUILD_FOR_UNIX 1
#endif
#define HS_SCALAR_IS_FIXED !(HS_SCALAR_IS_FLOAT)
#define HS_NEVER_USE_FLOAT !(HS_CAN_USE_FLOAT)
#if HS_DEBUG_MATH_OVERFLOW && !(HS_PIN_MATH_OVERFLOW)
#error "Can't debug overflow unless HS_PIN_MATH_OVERFLOW is ON"
#endif
///////////////////////Windows Specific Defines /////////////////////////////
#if HS_BUILD_FOR_WIN32
// 4244: Conversion
// 4305: Truncation
// 4503: 'identifier' : decorated name length exceeded, name was truncated
// 4018: signed/unsigned mismatch
// 4786: 255 character debug limit
// 4284: STL template defined operator-> for a class it doesn't make sense for (int, etc)
// 4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
#ifdef _MSC_VER
#pragma warning( disable : 4305 4503 4018 4786 4284 4800)
#endif
// VC++ version greater than 6.0, must be building for .NET
#if defined(_MSC_VER) && (_MSC_VER > 1200)
#define HS_BUILD_FOR_WIN32_NET
#endif
#pragma optimize( "y", off )
#endif
#ifdef HS_BUILD_FOR_WIN32
# ifndef CDECL
# define CDECL __cdecl
# endif
#else
# define CDECL
#endif
/////////////////////Debugging Defines ///////////////////////////////////
#if (defined(_DEBUG)||defined(UNIX_DEBUG)) && !defined(HS_DISABLE_ASSERT)
#define HS_DEBUGGING
#if (!defined(HS_NO_MEM_TRACKER))
#define HS_FIND_MEM_LEAKS
#endif
#endif
///////////////////// Required facilities ///////////////////////////////
#ifndef HeadSpinHDefined
#include "HeadSpin.h"
#endif
#endif // hsConfigDefined

9
Sources/Plasma/CoreLib/hsExceptionStack.h

@ -42,8 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsExceptionStack_inc #ifndef hsExceptionStack_inc
#define hsExceptionStack_inc #define hsExceptionStack_inc
#include "hsUtils.h" #include "HeadSpin.h"
#include "hsTypes.h"
#include "hsTemplates.h" #include "hsTemplates.h"
class hsExceptionStackDestroyer; class hsExceptionStackDestroyer;
@ -62,8 +61,8 @@ public:
static hsExceptionStack& Instance(); static hsExceptionStack& Instance();
Int32 GetNumEntries() const { return fEntries.Count(); } int32_t GetNumEntries() const { return fEntries.Count(); }
const char* GetEntry(Int32 i) const { return fEntries[i]; } const char* GetEntry(int32_t i) const { return fEntries[i]; }
void Push(const char* str); void Push(const char* str);
@ -84,7 +83,7 @@ inline hsExceptionStack& hsExceptionStack::Instance()
{ {
if (!fExceptionStack) if (!fExceptionStack)
{ {
fExceptionStack = TRACKED_NEW hsExceptionStack; fExceptionStack = new hsExceptionStack;
} }
return *fExceptionStack; return *fExceptionStack;

2
Sources/Plasma/CoreLib/hsExceptions.h

@ -42,7 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsExceptionDefined #ifndef hsExceptionDefined
#define hsExceptionDefined #define hsExceptionDefined
#include "hsTypes.h" #include "HeadSpin.h"
// #define HS_NO_EXCEPTIONS -- this will turn off execptions you might want // #define HS_NO_EXCEPTIONS -- this will turn off execptions you might want
// to do it with -D or equivalent instead of here since who knows who includes this. // to do it with -D or equivalent instead of here since who knows who includes this.

21
Sources/Plasma/CoreLib/hsFastMath.cpp

@ -40,14 +40,13 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsScalar.h"
#include "hsGeometry3.h" #include "hsGeometry3.h"
#include "hsFastMath.h" #include "hsFastMath.h"
const hsScalar hsFastMath::kSqrtTwo = hsSquareRoot(2.f); const float hsFastMath::kSqrtTwo = sqrt(2.f);
const hsScalar hsFastMath::kInvSqrtTwo = hsScalarInvert(hsFastMath::kSqrtTwo); const float hsFastMath::kInvSqrtTwo = hsInvert(hsFastMath::kSqrtTwo);
const hsScalar hsFastMath::kTwoPI = hsScalarPI * 2.f; const float hsFastMath::kTwoPI = M_PI * 2.f;
hsPoint2 statCosSinTable[9] = // must match length in inline hsPoint2 statCosSinTable[9] = // must match length in inline
{ {
@ -579,11 +578,11 @@ unsigned char statSeedTable[] = {
0x6a 0x6a
}; };
hsScalar hsFastMath::IATan2OverTwoPi(hsScalar y, hsScalar x) float hsFastMath::IATan2OverTwoPi(float y, float x)
{ {
const int tabSize = 16; // pad with one extra because hi can go hi const int tabSize = 16; // pad with one extra because hi can go hi
const int tabMax = tabSize-1; const int tabMax = tabSize-1;
static hsScalar tab[tabSize+1] = { static float tab[tabSize+1] = {
0.f, 0.f,
0.0105947f, 0.0105947f,
0.0210962f, 0.0210962f,
@ -609,14 +608,14 @@ hsScalar hsFastMath::IATan2OverTwoPi(hsScalar y, hsScalar x)
if((yNeg = (y < 0)))y = -y; if((yNeg = (y < 0)))y = -y;
if((xNeg = (x < 0)))x = -x; if((xNeg = (x < 0)))x = -x;
hsBool yBigger = y >= x; hsBool yBigger = y >= x;
hsScalar div = yBigger ? x / y : y / x; float div = yBigger ? x / y : y / x;
hsScalar fInd = div * tabMax; float fInd = div * tabMax;
int lo = int(fInd); int lo = int(fInd);
int hi = lo+1; int hi = lo+1;
hsScalar frac = fInd - lo; float frac = fInd - lo;
hsScalar res = tab[lo]; float res = tab[lo];
res += frac * (tab[hi] - res); res += frac * (tab[hi] - res);
// now move to proper half quadrant // now move to proper half quadrant

52
Sources/Plasma/CoreLib/hsFastMath.h

@ -51,27 +51,27 @@ protected:
static const hsPoint2* fCosSinTable; static const hsPoint2* fCosSinTable;
public: public:
static const hsScalar kSqrtTwo; static const float kSqrtTwo;
static const hsScalar kInvSqrtTwo; static const float kInvSqrtTwo;
static const hsScalar kTwoPI; static const float kTwoPI;
static hsScalar IATan2OverTwoPi(hsScalar y, hsScalar x); static float IATan2OverTwoPi(float y, float x);
static inline hsScalar InvSqrtAppr(hsScalar x); static inline float InvSqrtAppr(float x);
static inline hsScalar InvSqrt(hsScalar x); static inline float InvSqrt(float x);
static inline hsVector3& Normalize(hsVector3& v) { return (v *= InvSqrt(v.MagnitudeSquared())); } static inline hsVector3& Normalize(hsVector3& v) { return (v *= InvSqrt(v.MagnitudeSquared())); }
static inline hsVector3& NormalizeAppr(hsVector3& v) { return (v *= InvSqrtAppr(v.MagnitudeSquared())); } static inline hsVector3& NormalizeAppr(hsVector3& v) { return (v *= InvSqrtAppr(v.MagnitudeSquared())); }
static inline void SinCosAppr(hsScalar rads, hsScalar& sinRads, hsScalar& cosRads); static inline void SinCosAppr(float rads, float& sinRads, float& cosRads);
static inline void SinCosInRangeAppr(hsScalar rads, hsScalar& sinRads, hsScalar& cosRads); static inline void SinCosInRangeAppr(float rads, float& sinRads, float& cosRads);
static inline void SinCos(hsScalar rads, hsScalar& sinRads, hsScalar& cosRads); static inline void SinCos(float rads, float& sinRads, float& cosRads);
static inline void SinCosInRange(hsScalar ang, hsScalar& sinRads, hsScalar& cosRads); static inline void SinCosInRange(float ang, float& sinRads, float& cosRads);
static inline hsScalar Sin(hsScalar rads); static inline float Sin(float rads);
static inline hsScalar Cos(hsScalar rads); static inline float Cos(float rads);
static inline hsScalar SinInRange(hsScalar rads); static inline float SinInRange(float rads);
static inline hsScalar CosInRange(hsScalar rads); static inline float CosInRange(float rads);
}; };
@ -104,7 +104,7 @@ public:
#define SET_MANTSEED(a) (((unsigned long) (a)) << SEED_POS) #define SET_MANTSEED(a) (((unsigned long) (a)) << SEED_POS)
inline hsScalar hsFastMath::InvSqrtAppr(hsScalar x) inline float hsFastMath::InvSqrtAppr(float x)
{ {
register unsigned long a = *(long*)&x; register unsigned long a = *(long*)&x;
register float arg = x; register float arg = x;
@ -131,7 +131,7 @@ inline hsScalar hsFastMath::InvSqrtAppr(hsScalar x)
return r; return r;
} }
inline hsScalar hsFastMath::InvSqrt(hsScalar x) inline float hsFastMath::InvSqrt(float x)
{ {
register unsigned long a = *(long*)&x; register unsigned long a = *(long*)&x;
register float arg = x; register float arg = x;
@ -155,7 +155,7 @@ inline hsScalar hsFastMath::InvSqrt(hsScalar x)
} }
inline void hsFastMath::SinCosAppr(hsScalar rads, hsScalar& sinRads, hsScalar& cosRads) inline void hsFastMath::SinCosAppr(float rads, float& sinRads, float& cosRads)
{ {
rads = fmodf(rads, kTwoPI); rads = fmodf(rads, kTwoPI);
if( rads < 0 ) if( rads < 0 )
@ -163,11 +163,11 @@ inline void hsFastMath::SinCosAppr(hsScalar rads, hsScalar& sinRads, hsScalar& c
SinCosInRangeAppr(rads, sinRads, cosRads); SinCosInRangeAppr(rads, sinRads, cosRads);
} }
inline void hsFastMath::SinCosInRangeAppr(hsScalar rads, hsScalar& sinRads, hsScalar& cosRads) inline void hsFastMath::SinCosInRangeAppr(float rads, float& sinRads, float& cosRads)
{ {
const int kNumSinCosEntries = 8; const int kNumSinCosEntries = 8;
const hsScalar kNumEntriesOverTwoPI = kNumSinCosEntries * 0.5f / hsScalarPI; const float kNumEntriesOverTwoPI = kNumSinCosEntries * 0.5f / M_PI;
hsScalar t = rads * kNumEntriesOverTwoPI; float t = rads * kNumEntriesOverTwoPI;
int iLo = (int)t; int iLo = (int)t;
t -= iLo; t -= iLo;
@ -184,7 +184,7 @@ inline void hsFastMath::SinCosInRangeAppr(hsScalar rads, hsScalar& sinRads, hsSc
} }
inline hsScalar hsFastMath::Sin(hsScalar rads) inline float hsFastMath::Sin(float rads)
{ {
rads = fmodf(rads, kTwoPI); rads = fmodf(rads, kTwoPI);
if( rads < 0 ) if( rads < 0 )
@ -193,7 +193,7 @@ inline hsScalar hsFastMath::Sin(hsScalar rads)
return SinInRange(rads); return SinInRange(rads);
} }
inline hsScalar hsFastMath::Cos(hsScalar rads) inline float hsFastMath::Cos(float rads)
{ {
rads = fmodf(rads, kTwoPI); rads = fmodf(rads, kTwoPI);
if( rads < 0 ) if( rads < 0 )
@ -202,7 +202,7 @@ inline hsScalar hsFastMath::Cos(hsScalar rads)
return CosInRange(rads); return CosInRange(rads);
} }
inline hsScalar hsFastMath::SinInRange(hsScalar ang) inline float hsFastMath::SinInRange(float ang)
{ {
float sgn = 1.f; float sgn = 1.f;
@ -217,7 +217,7 @@ inline hsScalar hsFastMath::SinInRange(hsScalar ang)
return (ang - (ang*ang*ang) * (1.0f/6.0f) + (ang*ang*ang*ang*ang) / 120.0f) * sgn; return (ang - (ang*ang*ang) * (1.0f/6.0f) + (ang*ang*ang*ang*ang) / 120.0f) * sgn;
} }
inline hsScalar hsFastMath::CosInRange(hsScalar ang) inline float hsFastMath::CosInRange(float ang)
{ {
float sgn = 1.f; float sgn = 1.f;
@ -232,7 +232,7 @@ inline hsScalar hsFastMath::CosInRange(hsScalar ang)
return (1.0f - (ang*ang / 2.0f) + (ang*ang*ang*ang) / 24.0f) *sgn; return (1.0f - (ang*ang / 2.0f) + (ang*ang*ang*ang) / 24.0f) *sgn;
} }
inline void hsFastMath::SinCos(hsScalar rads, hsScalar& sinRads, hsScalar& cosRads) inline void hsFastMath::SinCos(float rads, float& sinRads, float& cosRads)
{ {
rads = fmodf(rads, kTwoPI); rads = fmodf(rads, kTwoPI);
if( rads < 0 ) if( rads < 0 )
@ -240,7 +240,7 @@ inline void hsFastMath::SinCos(hsScalar rads, hsScalar& sinRads, hsScalar& cosRa
SinCosInRange(rads, sinRads, cosRads); SinCosInRange(rads, sinRads, cosRads);
} }
inline void hsFastMath::SinCosInRange(hsScalar ang, hsScalar& sinRads, hsScalar& cosRads) inline void hsFastMath::SinCosInRange(float ang, float& sinRads, float& cosRads)
{ {
float sgn = 1.f; float sgn = 1.f;

120
Sources/Plasma/CoreLib/hsFixedTypes.h

@ -1,120 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef hsFixedTypesDefined
#define hsFixedTypesDefined
#include "hsTypes.h"
#ifdef __cplusplus
extern "C" {
#endif
#define hsIntToFixed(x) ((hsFixed)(x) << 16)
#define hsFixedToInt(x) ((x) >> 16)
#define hsFixedRound(x) (((x) + 0x8000) >> 16)
#define hsFixed1 hsIntToFixed(1)
#define hsFixedPI (0x3243F)
#define hsFixedPiOver2 (0x1921F)
#define hsFixedToFract(x) ((hsFract)(x) << 14)
#define hsFractToFixed(x) ((hsFixed)(x) >> 14)
#define hsFract1 hsFixedToFract(hsFixed1)
#define hsFractPiOver2 (0x6487ED34) /* needs some work */
#define hsFixFloor(x) \
(hsFixed)((x) < 0 ? -(hsFixed)((-(x) + 0xFFFF) & 0xFFFF0000) : (x) & 0xFFFF0000)
#define hsFixedToFloorInt(x) \
(int)((x) < 0 ? -(int)((-(x) + 0xFFFF) >> 16) : ((x) >> 16))
#define hsFixCeiling(x) \
(hsFixed)((x) < 0 ? -(hsFixed)(-(x) & 0xFFFF0000) : ((x) + 0xFFFF) & 0xFFFF0000)
#define hsFixedToCeilingInt(x) \
(int)((x) < 0 ? -(int)(-(x) >> 16) : (((x) + 0xFFFF) >> 16))
#if HS_CAN_USE_FLOAT
#define hsFixedToFloat(x) ((x) / float(hsFixed1))
#define hsFloatToFixed(x) hsFixed((x) * hsFixed1)
#define hsFractToFloat(x) ((x) / float(hsFract1))
#define hsFloatToFract(x) hsFract((x) * hsFract1)
#endif
hsFixed hsFixMul(hsFixed a, hsFixed b);
hsFract hsFixDiv(hsFixed a, hsFixed b);
hsFract hsFracMul(hsFract a, hsFract b);
hsFract hsFracDiv(hsFract a, hsFract b);
hsFract hsFracSqrt(hsFract value);
#define hsFixSqrt(value) (hsFracSqrt(value) >> 7)
hsFract hsFracCubeRoot(hsFract value);
hsFixed hsFixedSin(hsFixed s);
hsFixed hsFixedCos(hsFixed s);
hsFixed hsFixedASin(hsFixed s);
hsFixed hsFixedACos(hsFixed s);
UInt16 hsSqrt32(UInt32 value);
UInt16 hsCubeRoot32(UInt32 value);
Int32 hsMulDiv32(Int32 numer1, Int32 numer2, Int32 denom);
Int32 hsMagnitude32(Int32 x, Int32 y);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
struct hsFixedPlane {
hsFixed fA, fB, fC;
void Set(hsFixed a, hsFixed b, hsFixed c) { fA = a; fB = b; fC = c; }
hsFixed FixEval(hsFixed x, hsFixed y) const { return hsFixMul(fA, x) + hsFixMul(fB, y) + fC; }
Int32 IntEval(Int32 x, Int32 y) const { return fA * x + fB * y + fC; }
void ShiftDown(UInt32 i) { fA >>= i; fB >>= i; fC >>= i;}
};
#endif
#endif

34
Sources/Plasma/CoreLib/hsGeometry3.cpp

@ -41,14 +41,15 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "hsGeometry3.h" #include "hsGeometry3.h"
#include "hsStream.h" #include "hsStream.h"
#include <math.h>
hsVector3 operator%(const hsVector3& t, const hsVector3& s) hsVector3 operator%(const hsVector3& t, const hsVector3& s)
{ {
hsVector3 result; hsVector3 result;
return *result.Set( hsScalarMul(t.fY, s.fZ) - hsScalarMul(s.fY, t.fZ), return *result.Set((t.fY * s.fZ) - (s.fY * t.fZ),
-hsScalarMul(t.fX, s.fZ) + hsScalarMul(s.fX, t.fZ), -(t.fX * s.fZ) + (s.fX * t.fZ),
hsScalarMul(t.fX, s.fY) - hsScalarMul(s.fX, t.fY)); (t.fX * s.fY) - (s.fX * t.fY));
} }
@ -56,33 +57,10 @@ hsVector3 operator%(const hsVector3& t, const hsVector3& s)
////////////////////////////////// //////////////////////////////////
///////////////////////////////// /////////////////////////////////
#if HS_SCALAR_IS_FIXED float hsScalarTriple::Magnitude() const
hsScalar hsScalarTriple::Magnitude() const
{ {
hsWide result, temp; return sqrt(MagnitudeSquared());
result.Mul(fCoord[0], fCoord[0]);
temp.Mul(fCoord[1], fCoord[1]);
result.Add(&temp);
temp.Mul(fCoord[2], fCoord[2]);
result.Add(&temp);
return result.Sqrt();
}
hsScalar hsScalarTriple::MagnitudeSquared() const
{
hsWide result, temp;
result.Mul(fCoord[0], fCoord[0]);
temp.Mul(fCoord[1], fCoord[1]);
result.Add(&temp);
temp.Mul(fCoord[2], fCoord[2]);
result.Add(&temp);
return result.AsFixed();
} }
#endif
void hsScalarTriple::Read(hsStream *stream) void hsScalarTriple::Read(hsStream *stream)
{ {

164
Sources/Plasma/CoreLib/hsGeometry3.h

@ -42,26 +42,27 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsGGeometry3Defined #ifndef hsGGeometry3Defined
#define hsGGeometry3Defined #define hsGGeometry3Defined
#include "hsTypes.h" #include "HeadSpin.h"
struct hsVector3; struct hsVector3;
struct hsPoint3; struct hsPoint3;
struct hsScalarTriple; struct hsScalarTriple;
class hsStream; class hsStream;
/* /*
If value is already close to hsScalar1, then this is a good approx. of 1/sqrt(value) If value is already close to 1.f, then this is a good approx. of 1/sqrt(value)
*/ */
static inline hsScalar hsInvSqrt(hsScalar value) static inline float hsInvSqrt(float value)
{ {
hsScalar guess; float guess;
hsScalar threeOverTwo = hsScalar1 + hsScalarHalf; float threeOverTwo = 1.5f;
value = hsScalarDiv2(value); value /= 2.f;
guess = threeOverTwo - value; // with initial guess = 1.0 guess = threeOverTwo - value; // with initial guess = 1.0
// repeat this line for better approx // repeat this line for better approx
guess = hsScalarMul(guess, threeOverTwo - hsScalarMul(hsScalarMul(value, guess), guess)); guess = (guess * threeOverTwo - ((value * guess) * guess));
guess = hsScalarMul(guess, threeOverTwo - hsScalarMul(hsScalarMul(value, guess), guess)); guess = (guess * threeOverTwo - ((value * guess) * guess));
return guess; return guess;
} }
@ -71,12 +72,12 @@ struct hsScalarTriple
{ {
//protected: //protected:
// hsScalarTriple() : fX(privateData[0]), fY(privateData[1]), fZ(privateData[2]) {} // hsScalarTriple() : fX(privateData[0]), fY(privateData[1]), fZ(privateData[2]) {}
// hsScalarTriple(hsScalar x, hsScalar y, hsScalar z) // hsScalarTriple(float x, float y, float z)
// : fX(privateData[0]), fY(privateData[1]), fZ(privateData[2]) { fX = x, fY = y, fZ = z; } // : fX(privateData[0]), fY(privateData[1]), fZ(privateData[2]) { fX = x, fY = y, fZ = z; }
// //
// union { // union {
// u_long128 privateTemp; // u_long128 privateTemp;
// hsScalar privateData[4]; // float privateData[4];
// }; // };
//public: //public:
// //
@ -84,34 +85,29 @@ struct hsScalarTriple
// hsScalarTriple(const hsScalarTriple& o) : fX(privateData[0]), fY(privateData[1]), fZ(privateData[2]) // hsScalarTriple(const hsScalarTriple& o) : fX(privateData[0]), fY(privateData[1]), fZ(privateData[2])
// { *this = o; } // { *this = o; }
// //
// hsScalar& fX; // float& fX;
// hsScalar& fY; // float& fY;
// hsScalar& fZ; // float& fZ;
protected: protected:
hsScalarTriple() {} hsScalarTriple() {}
hsScalarTriple(hsScalar x, hsScalar y, hsScalar z) : fX(x), fY(y), fZ(z) {} hsScalarTriple(float x, float y, float z) : fX(x), fY(y), fZ(z) {}
public: public:
hsScalar fX, fY, fZ; float fX, fY, fZ;
hsScalarTriple* Set(hsScalar x, hsScalar y, hsScalar z) { fX= x; fY = y; fZ = z; return this;} hsScalarTriple* Set(float x, float y, float z) { fX= x; fY = y; fZ = z; return this;}
hsScalarTriple* Set(const hsScalarTriple *p) { fX = p->fX; fY = p->fY; fZ = p->fZ; return this;} hsScalarTriple* Set(const hsScalarTriple *p) { fX = p->fX; fY = p->fY; fZ = p->fZ; return this;}
hsScalar InnerProduct(const hsScalarTriple &p) const; float InnerProduct(const hsScalarTriple &p) const;
hsScalar InnerProduct(const hsScalarTriple *p) const; float InnerProduct(const hsScalarTriple *p) const;
// hsScalarTriple LERP(hsScalarTriple &other, hsScalar t); // hsScalarTriple LERP(hsScalarTriple &other, float t);
#if HS_SCALAR_IS_FIXED float Magnitude() const;
hsScalar Magnitude() const; float MagnitudeSquared() const { return (fX * fX + fY * fY + fZ * fZ); }
hsScalar MagnitudeSquared() const;
#else
hsScalar Magnitude() const { return hsSquareRoot(MagnitudeSquared()); }
hsScalar MagnitudeSquared() const { return (fX * fX + fY * fY + fZ * fZ); }
#endif
hsBool IsEmpty() const { return fX == 0 && fY == 0 && fZ == 0; } hsBool IsEmpty() const { return fX == 0 && fY == 0 && fZ == 0; }
hsScalar operator[](int i) const; float operator[](int i) const;
hsScalar& operator[](int i); float& operator[](int i);
void Read(hsStream *stream); void Read(hsStream *stream);
void Write(hsStream *stream) const; void Write(hsStream *stream) const;
@ -120,32 +116,32 @@ public:
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
inline hsScalar& hsScalarTriple::operator[] (int i) inline float& hsScalarTriple::operator[] (int i)
{ {
hsAssert(i >=0 && i <3, "Bad index for hsScalarTriple::operator[]"); hsAssert(i >=0 && i <3, "Bad index for hsScalarTriple::operator[]");
return *(&fX + i); return *(&fX + i);
} }
inline hsScalar hsScalarTriple::operator[] (int i) const inline float hsScalarTriple::operator[] (int i) const
{ {
hsAssert(i >=0 && i <3, "Bad index for hsScalarTriple::operator[]"); hsAssert(i >=0 && i <3, "Bad index for hsScalarTriple::operator[]");
return *(&fX + i); return *(&fX + i);
} }
inline hsScalar hsScalarTriple::InnerProduct(const hsScalarTriple &p) const inline float hsScalarTriple::InnerProduct(const hsScalarTriple &p) const
{ {
hsScalar tmp = fX*p.fX; float tmp = fX*p.fX;
tmp += fY*p.fY; tmp += fY*p.fY;
tmp += fZ*p.fZ; tmp += fZ*p.fZ;
return tmp; return tmp;
} }
inline hsScalar hsScalarTriple::InnerProduct(const hsScalarTriple *p) const inline float hsScalarTriple::InnerProduct(const hsScalarTriple *p) const
{ {
hsScalar tmp = fX*p->fX; float tmp = fX*p->fX;
tmp += fY*p->fY; tmp += fY*p->fY;
tmp += fZ*p->fZ; tmp += fZ*p->fZ;
return tmp; return tmp;
} }
//inline hsScalarTriple hsScalarTriple::LERP(hsScalarTriple &other, hsScalar t) //inline hsScalarTriple hsScalarTriple::LERP(hsScalarTriple &other, float t)
//{ //{
// hsScalarTriple p = other - this; // hsScalarTriple p = other - this;
// p = p / t; // p = p / t;
@ -157,26 +153,26 @@ inline hsScalar hsScalarTriple::InnerProduct(const hsScalarTriple *p) const
///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////
struct hsPoint3 : public hsScalarTriple { struct hsPoint3 : public hsScalarTriple {
hsPoint3() {}; hsPoint3() {};
hsPoint3(hsScalar x, hsScalar y, hsScalar z) : hsScalarTriple(x,y,z) {} hsPoint3(float x, float y, float z) : hsScalarTriple(x,y,z) {}
explicit hsPoint3(const hsScalarTriple& p) : hsScalarTriple(p) {} explicit hsPoint3(const hsScalarTriple& p) : hsScalarTriple(p) {}
hsPoint3* Set(hsScalar x, hsScalar y, hsScalar z) { return (hsPoint3*)this->hsScalarTriple::Set(x,y,z);} hsPoint3* Set(float x, float y, float z) { return (hsPoint3*)this->hsScalarTriple::Set(x,y,z);}
hsPoint3* Set(const hsScalarTriple* p) { return (hsPoint3*)this->hsScalarTriple::Set(p) ;} hsPoint3* Set(const hsScalarTriple* p) { return (hsPoint3*)this->hsScalarTriple::Set(p) ;}
friend inline hsPoint3 operator+(const hsPoint3& s, const hsPoint3& t); friend inline hsPoint3 operator+(const hsPoint3& s, const hsPoint3& t);
friend inline hsPoint3 operator+(const hsPoint3& s, const hsVector3& t); friend inline hsPoint3 operator+(const hsPoint3& s, const hsVector3& t);
friend inline hsPoint3 operator-(const hsPoint3& s, const hsPoint3& t); friend inline hsPoint3 operator-(const hsPoint3& s, const hsPoint3& t);
friend inline hsPoint3 operator-(const hsPoint3& s); friend inline hsPoint3 operator-(const hsPoint3& s);
friend inline hsPoint3 operator*(const hsScalar& s, const hsPoint3& t); friend inline hsPoint3 operator*(const float& s, const hsPoint3& t);
friend inline hsPoint3 operator*(const hsPoint3& t, const hsScalar& s); friend inline hsPoint3 operator*(const hsPoint3& t, const float& s);
friend inline hsPoint3 operator/(const hsPoint3& t, const hsScalar& s); friend inline hsPoint3 operator/(const hsPoint3& t, const float& s);
hsBool operator==(const hsPoint3& ss) const hsBool operator==(const hsPoint3& ss) const
{ {
return (ss.fX == fX && ss.fY == fY && ss.fZ == fZ); return (ss.fX == fX && ss.fY == fY && ss.fZ == fZ);
} }
hsBool operator!=(const hsPoint3& ss) const { return !(*this == ss); } hsBool operator!=(const hsPoint3& ss) const { return !(*this == ss); }
hsPoint3 &operator+=(const hsScalarTriple &s) { fX += s.fX; fY += s.fY; fZ += s.fZ; return *this; } hsPoint3 &operator+=(const hsScalarTriple &s) { fX += s.fX; fY += s.fY; fZ += s.fZ; return *this; }
hsPoint3 &operator*=(const hsScalar s) { fX *= s; fY *= s; fZ *= s; return *this; } hsPoint3 &operator*=(const float s) { fX *= s; fY *= s; fZ *= s; return *this; }
}; };
@ -185,38 +181,38 @@ struct hsPoint3 : public hsScalarTriple {
struct hsVector3 : public hsScalarTriple { struct hsVector3 : public hsScalarTriple {
hsVector3() {}; hsVector3() {};
hsVector3(hsScalar x, hsScalar y, hsScalar z) : hsScalarTriple(x,y,z) {} hsVector3(float x, float y, float z) : hsScalarTriple(x,y,z) {}
explicit hsVector3(const hsScalarTriple& p) : hsScalarTriple(p) { } explicit hsVector3(const hsScalarTriple& p) : hsScalarTriple(p) { }
hsVector3(const hsPoint3 *p1, const hsPoint3 *p2) { hsVector3(const hsPoint3 *p1, const hsPoint3 *p2) {
fX = p1->fX - p2->fX, fY= p1->fY - p2->fY, fZ = p1->fZ - p2->fZ; } fX = p1->fX - p2->fX, fY= p1->fY - p2->fY, fZ = p1->fZ - p2->fZ; }
hsVector3* Set(hsScalar x, hsScalar y, hsScalar z) { return (hsVector3*)hsScalarTriple::Set(x,y,z); } hsVector3* Set(float x, float y, float z) { return (hsVector3*)hsScalarTriple::Set(x,y,z); }
hsVector3* Set(const hsScalarTriple* p) { return (hsVector3*)hsScalarTriple::Set(p) ;} hsVector3* Set(const hsScalarTriple* p) { return (hsVector3*)hsScalarTriple::Set(p) ;}
hsVector3* Set(const hsScalarTriple* p1, const hsScalarTriple* p2) { return Set(p1->fX-p2->fX,p1->fY-p2->fY,p1->fZ-p2->fZ);} hsVector3* Set(const hsScalarTriple* p1, const hsScalarTriple* p2) { return Set(p1->fX-p2->fX,p1->fY-p2->fY,p1->fZ-p2->fZ);}
void Normalize() void Normalize()
{ {
hsScalar length = this->Magnitude(); float length = this->Magnitude();
// hsIfDebugMessage(length == 0, "Err: Normalizing hsVector3 of length 0", 0); // hsIfDebugMessage(length == 0, "Err: Normalizing hsVector3 of length 0", 0);
if (length == 0) if (length == 0)
return; return;
hsScalar invMag = hsScalarInvert(length); float invMag = hsInvert(length);
fX = hsScalarMul(fX, invMag); fX = (fX * invMag);
fY = hsScalarMul(fY, invMag); fY = (fY * invMag);
fZ = hsScalarMul(fZ, invMag); fZ = (fZ * invMag);
} }
inline void Renormalize() // if the vector is already close to unit length inline void Renormalize() // if the vector is already close to unit length
{ {
hsScalar mag2 = *this * *this; float mag2 = *this * *this;
hsIfDebugMessage(mag2 == 0, "Err: Renormalizing hsVector3 of length 0", 0); hsIfDebugMessage(mag2 == 0, "Err: Renormalizing hsVector3 of length 0", 0);
if (mag2 == 0) if (mag2 == 0)
return; return;
hsScalar invMag = hsInvSqrt(mag2); float invMag = hsInvSqrt(mag2);
fX = hsScalarMul(fX, invMag); fX = (fX * invMag);
fY = hsScalarMul(fY, invMag); fY = (fY * invMag);
fZ = hsScalarMul(fZ, invMag); fZ = (fZ * invMag);
} }
// hsVector3 &Sub(const hsPoint3& s, const hsPoint3& t) // hsVector3 &Sub(const hsPoint3& s, const hsPoint3& t)
@ -225,10 +221,10 @@ struct hsVector3 : public hsScalarTriple {
friend inline hsVector3 operator+(const hsVector3& s, const hsVector3& t); friend inline hsVector3 operator+(const hsVector3& s, const hsVector3& t);
friend inline hsVector3 operator-(const hsVector3& s, const hsVector3& t); friend inline hsVector3 operator-(const hsVector3& s, const hsVector3& t);
friend inline hsVector3 operator-(const hsVector3& s); friend inline hsVector3 operator-(const hsVector3& s);
friend inline hsVector3 operator*(const hsScalar& s, const hsVector3& t); friend inline hsVector3 operator*(const float& s, const hsVector3& t);
friend inline hsVector3 operator*(const hsVector3& t, const hsScalar& s); friend inline hsVector3 operator*(const hsVector3& t, const float& s);
friend inline hsVector3 operator/(const hsVector3& t, const hsScalar& s); friend inline hsVector3 operator/(const hsVector3& t, const float& s);
friend inline hsScalar operator*(const hsVector3& t, const hsVector3& s); friend inline float operator*(const hsVector3& t, const hsVector3& s);
friend hsVector3 operator%(const hsVector3& t, const hsVector3& s); friend hsVector3 operator%(const hsVector3& t, const hsVector3& s);
#if 0 // Havok reeks #if 0 // Havok reeks
friend hsBool32 operator==(const hsVector3& s, const hsVector3& t) friend hsBool32 operator==(const hsVector3& s, const hsVector3& t)
@ -243,20 +239,20 @@ struct hsVector3 : public hsScalarTriple {
#endif // Havok reeks #endif // Havok reeks
hsVector3 &operator+=(const hsScalarTriple &s) { fX += s.fX; fY += s.fY; fZ += s.fZ; return *this; } hsVector3 &operator+=(const hsScalarTriple &s) { fX += s.fX; fY += s.fY; fZ += s.fZ; return *this; }
hsVector3 &operator-=(const hsScalarTriple &s) { fX -= s.fX; fY -= s.fY; fZ -= s.fZ; return *this; } hsVector3 &operator-=(const hsScalarTriple &s) { fX -= s.fX; fY -= s.fY; fZ -= s.fZ; return *this; }
hsVector3 &operator*=(const hsScalar s) { fX *= s; fY *= s; fZ *= s; return *this; } hsVector3 &operator*=(const float s) { fX *= s; fY *= s; fZ *= s; return *this; }
hsVector3 &operator/=(const hsScalar s) { fX /= s; fY /= s; fZ /= s; return *this; } hsVector3 &operator/=(const float s) { fX /= s; fY /= s; fZ /= s; return *this; }
}; };
struct hsPoint4 { struct hsPoint4 {
hsScalar fX, fY, fZ, fW; float fX, fY, fZ, fW;
hsPoint4() {} hsPoint4() {}
hsPoint4(hsScalar x, hsScalar y, hsScalar z, hsScalar w) : fX(x), fY(y), fZ(z), fW(w) {} hsPoint4(float x, float y, float z, float w) : fX(x), fY(y), fZ(z), fW(w) {}
hsScalar& operator[](int i); float& operator[](int i);
hsScalar operator[](int i) const; float operator[](int i) const;
hsPoint4& operator=(const hsPoint3&p) { Set(p.fX, p.fY, p.fZ, hsScalar1); return *this; } hsPoint4& operator=(const hsPoint3&p) { Set(p.fX, p.fY, p.fZ, 1.f); return *this; }
hsPoint4* Set(hsScalar x, hsScalar y, hsScalar z, hsScalar w) hsPoint4* Set(float x, float y, float z, float w)
{ fX = x; fY = y; fZ = z; fW = w; return this; } { fX = x; fY = y; fZ = z; fW = w; return this; }
}; };
@ -282,28 +278,28 @@ inline hsVector3 operator-(const hsVector3& s)
return *result.Set(-s.fX, -s.fY, -s.fZ); return *result.Set(-s.fX, -s.fY, -s.fZ);
} }
inline hsVector3 operator*(const hsVector3& s, const hsScalar& t) inline hsVector3 operator*(const hsVector3& s, const float& t)
{ {
hsVector3 result; hsVector3 result;
return *result.Set(hsScalarMul(s.fX, t), hsScalarMul(s.fY, t), hsScalarMul(s.fZ, t)); return *result.Set(s.fX * t, s.fY * t, s.fZ * t);
} }
inline hsVector3 operator/(const hsVector3& s, const hsScalar& t) inline hsVector3 operator/(const hsVector3& s, const float& t)
{ {
hsVector3 result; hsVector3 result;
return *result.Set(hsScalarDiv(s.fX, t), hsScalarDiv(s.fY, t), hsScalarDiv(s.fZ, t)); return *result.Set(s.fX / t, s.fY / t, s.fZ / t);
} }
inline hsVector3 operator*(const hsScalar& t, const hsVector3& s) inline hsVector3 operator*(const float& t, const hsVector3& s)
{ {
hsVector3 result; hsVector3 result;
return *result.Set(hsScalarMul(s.fX, t), hsScalarMul(s.fY, t), hsScalarMul(s.fZ, t)); return *result.Set(s.fX * t, s.fY * t, s.fZ * t);
} }
inline hsScalar operator*(const hsVector3& t, const hsVector3& s) inline float operator*(const hsVector3& t, const hsVector3& s)
{ {
return hsScalarMul(t.fX, s.fX) + hsScalarMul(t.fY, s.fY) + hsScalarMul(t.fZ, s.fZ); return (t.fX * s.fX) + (t.fY * s.fY) + (t.fZ * s.fZ);
} }
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
@ -343,32 +339,32 @@ inline hsPoint3 operator-(const hsPoint3& s, const hsVector3& t)
return *result.Set(s.fX - t.fX, s.fY - t.fY, s.fZ - t.fZ); return *result.Set(s.fX - t.fX, s.fY - t.fY, s.fZ - t.fZ);
} }
inline hsPoint3 operator*(const hsPoint3& s, const hsScalar& t) inline hsPoint3 operator*(const hsPoint3& s, const float& t)
{ {
hsPoint3 result; hsPoint3 result;
return *result.Set(hsScalarMul(s.fX, t), hsScalarMul(s.fY, t), hsScalarMul(s.fZ, t)); return *result.Set((s.fX * t), (s.fY * t), (s.fZ * t));
} }
inline hsPoint3 operator/(const hsPoint3& s, const hsScalar& t) inline hsPoint3 operator/(const hsPoint3& s, const float& t)
{ {
hsPoint3 result; hsPoint3 result;
return *result.Set(hsScalarDiv(s.fX, t), hsScalarDiv(s.fY, t), hsScalarDiv(s.fZ, t)); return *result.Set((s.fX / t), (s.fY / t), (s.fZ / t));
} }
inline hsPoint3 operator*(const hsScalar& t, const hsPoint3& s) inline hsPoint3 operator*(const float& t, const hsPoint3& s)
{ {
hsPoint3 result; hsPoint3 result;
return *result.Set(hsScalarMul(s.fX, t), hsScalarMul(s.fY, t), hsScalarMul(s.fZ, t)); return *result.Set((s.fX * t), (s.fY * t), (s.fZ * t));
} }
inline hsScalar hsPoint4::operator[] (int i) const inline float hsPoint4::operator[] (int i) const
{ {
hsAssert(i >=0 && i <4, "Bad index for hsPoint4::operator[]"); hsAssert(i >=0 && i <4, "Bad index for hsPoint4::operator[]");
return *(&fX + i); return *(&fX + i);
} }
inline hsScalar& hsPoint4::operator[] (int i) inline float& hsPoint4::operator[] (int i)
{ {
hsAssert(i >=0 && i <4, "Bad index for hsPoint4::operator[]"); hsAssert(i >=0 && i <4, "Bad index for hsPoint4::operator[]");
return *(&fX + i); return *(&fX + i);
@ -389,10 +385,10 @@ struct hsPointNorm {
struct hsPlane3 { struct hsPlane3 {
hsVector3 fN; hsVector3 fN;
hsScalar fD; float fD;
hsPlane3() { } hsPlane3() { }
hsPlane3(const hsVector3* nrml, hsScalar d) hsPlane3(const hsVector3* nrml, float d)
{ fN = *nrml; fD=d; } { fN = *nrml; fD=d; }
hsPlane3(const hsPoint3* pt, const hsVector3* nrml) hsPlane3(const hsPoint3* pt, const hsVector3* nrml)
{ fN = *nrml; fD = -pt->InnerProduct(nrml); } { fN = *nrml; fD = -pt->InnerProduct(nrml); }

46
Sources/Plasma/CoreLib/hsHashTable.h

@ -51,7 +51,7 @@ class hsHashTableIterator
{ {
public: public:
hsHashTableIterator() : fList(nil), fIndex(-1) { } hsHashTableIterator() : fList(nil), fIndex(-1) { }
explicit hsHashTableIterator(hsTArray<T>* list, UInt32 idx) : fList(list), fIndex(idx) { } explicit hsHashTableIterator(hsTArray<T>* list, uint32_t idx) : fList(list), fIndex(idx) { }
T* operator->() const { return &((*fList)[fIndex]); } T* operator->() const { return &((*fList)[fIndex]); }
T& operator*() const { return (*fList)[fIndex]; } T& operator*() const { return (*fList)[fIndex]; }
@ -67,7 +67,7 @@ public:
private: private:
hsTArray<T>* fList; hsTArray<T>* fList;
UInt32 fIndex; uint32_t fIndex;
}; };
@ -75,7 +75,7 @@ template <class T>
class hsHashTable class hsHashTable
{ {
public: public:
hsHashTable(UInt32 size=150001, UInt32 step=1); hsHashTable(uint32_t size=150001, uint32_t step=1);
~hsHashTable(); ~hsHashTable();
typedef hsHashTableIterator<T> iterator; typedef hsHashTableIterator<T> iterator;
@ -84,25 +84,25 @@ public:
iterator end() { return iterator(&fItemList,0); } iterator end() { return iterator(&fItemList,0); }
void clear(); void clear();
UInt32 count() { return fItemList.Count()-1; } uint32_t count() { return fItemList.Count()-1; }
UInt32 size() { return fSize; } uint32_t size() { return fSize; }
UInt32 CollisionCount() { return fCollisionCount; } uint32_t CollisionCount() { return fCollisionCount; }
inline void insert(T& item); inline void insert(T& item);
inline void erase(T& item); inline void erase(T& item);
inline iterator find(const T& item); inline iterator find(const T& item);
iterator GetItem(UInt32 i); iterator GetItem(uint32_t i);
private: private:
hsTArray<T> fItemList; hsTArray<T> fItemList;
hsTArray<UInt32> fClearList; hsTArray<uint32_t> fClearList;
UInt32* fHashTable; uint32_t* fHashTable;
UInt32 fSize; uint32_t fSize;
UInt32 fCollisionStep; uint32_t fCollisionStep;
UInt32 fCollisionCount; uint32_t fCollisionCount;
// No copy or assignment // No copy or assignment
hsHashTable(const hsHashTable&); hsHashTable(const hsHashTable&);
@ -110,14 +110,14 @@ private:
}; };
template <class T> template <class T>
hsHashTable<T>::hsHashTable(UInt32 size, UInt32 step) : hsHashTable<T>::hsHashTable(uint32_t size, uint32_t step) :
fSize(size), fSize(size),
fCollisionStep(step), fCollisionStep(step),
fCollisionCount(0) fCollisionCount(0)
{ {
fItemList.SetCount(1); fItemList.SetCount(1);
fHashTable = TRACKED_NEW UInt32[fSize]; fHashTable = new uint32_t[fSize];
memset(fHashTable,0,fSize*sizeof(UInt32)); memset(fHashTable,0,fSize*sizeof(uint32_t));
} }
template <class T> template <class T>
@ -130,7 +130,7 @@ template <class T>
void hsHashTable<T>::clear() void hsHashTable<T>::clear()
{ {
fItemList.SetCount(1); fItemList.SetCount(1);
for (Int32 i=0; i<fClearList.Count(); i++) for (int32_t i=0; i<fClearList.Count(); i++)
fHashTable[ fClearList[i] ] = 0; fHashTable[ fClearList[i] ] = 0;
fClearList.Reset(); fClearList.Reset();
} }
@ -139,9 +139,9 @@ template <class T>
void hsHashTable<T>::insert(T& item) void hsHashTable<T>::insert(T& item)
{ {
hsAssert(fClearList.Count() < fSize,"Hash table overflow! Increase the table size."); hsAssert(fClearList.Count() < fSize,"Hash table overflow! Increase the table size.");
UInt32 h = item.GetHash(); uint32_t h = item.GetHash();
h %= fSize; h %= fSize;
while (UInt32 it = fHashTable[h]) while (uint32_t it = fHashTable[h])
{ {
if ( fItemList[it] == item) if ( fItemList[it] == item)
{ {
@ -160,9 +160,9 @@ void hsHashTable<T>::insert(T& item)
template <class T> template <class T>
void hsHashTable<T>::erase(T& item) void hsHashTable<T>::erase(T& item)
{ {
UInt32 h = item.GetHash(); uint32_t h = item.GetHash();
h %= fSize; h %= fSize;
while (UInt32 it = fHashTable[h]) while (uint32_t it = fHashTable[h])
{ {
if ( fItemList[it] == item ) if ( fItemList[it] == item )
{ {
@ -175,9 +175,9 @@ void hsHashTable<T>::erase(T& item)
template <class T> template <class T>
hsHashTableIterator<T> hsHashTable<T>::find(const T& item) hsHashTableIterator<T> hsHashTable<T>::find(const T& item)
{ {
UInt32 h = item.GetHash(); uint32_t h = item.GetHash();
h %= fSize; h %= fSize;
while (UInt32 it = fHashTable[h]) while (uint32_t it = fHashTable[h])
{ {
if ( fItemList[it] == item ) if ( fItemList[it] == item )
{ {
@ -191,7 +191,7 @@ hsHashTableIterator<T> hsHashTable<T>::find(const T& item)
} }
template <class T> template <class T>
hsHashTableIterator<T> hsHashTable<T>::GetItem(UInt32 i) hsHashTableIterator<T> hsHashTable<T>::GetItem(uint32_t i)
{ {
return iterator(&fItemList,i+1); return iterator(&fItemList,i+1);
} }

105
Sources/Plasma/CoreLib/hsMMIOStream.cpp

@ -1,105 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#include "hsMMIOStream.h"
//////////////////////////////////////////////////////////////////////////////////////
#if HS_BUILD_FOR_WIN32
#include "hsExceptions.h"
UInt32 hsMMIOStream::Read(UInt32 bytes, void* buffer)
{
fBytesRead += bytes;
fPosition += bytes;
int numItems = ::mmioRead(fHmfr, (char*)buffer, bytes);
if ((unsigned)numItems < bytes)
{
if (numItems>=0 && ::mmioSeek(fHmfr,0,SEEK_CUR)==::mmioSeek(fHmfr,0,SEEK_END)) {
// EOF ocurred
char str[128];
sprintf(str, "Hit EOF on MMIO Read, only read %d out of requested %d bytes\n", numItems, bytes);
hsDebugMessage(str, 0);
}
else
{
hsDebugMessage("Error on MMIO Read",0);
}
}
return numItems;
}
hsBool hsMMIOStream::AtEnd()
{
return (::mmioSeek(fHmfr,0,SEEK_CUR)==::mmioSeek(fHmfr,0,SEEK_END));
}
UInt32 hsMMIOStream::Write(UInt32 bytes, const void* buffer)
{
fPosition += bytes;
return ::mmioWrite(fHmfr,(const char*)buffer,bytes);
}
void hsMMIOStream::Skip(UInt32 delta)
{
fBytesRead += delta;
fPosition += delta;
(void)::mmioSeek(fHmfr, delta, SEEK_CUR);
}
void hsMMIOStream::Rewind()
{
fBytesRead = 0;
fPosition = 0;
(void)::mmioSeek(fHmfr, 0, SEEK_SET);
}
void hsMMIOStream::FastFwd()
{
fBytesRead = fPosition = ::mmioSeek(fHmfr, 0, SEEK_END);
}
void hsMMIOStream::Truncate()
{
hsThrow("Truncate unimplemented by subclass of stream");
}
#endif

72
Sources/Plasma/CoreLib/hsMMIOStream.h

@ -1,72 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef hsMMIOStream_inc
#define hsMMIOStream_inc
#include "hsWindows.h"
#include "hsStream.h"
#if HS_BUILD_FOR_WIN32
#include <mmsystem.h>
class hsMMIOStream: public hsStream
{
HMMIO fHmfr;
public:
virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsMMIOStream::Open NotImplemented"); return false; }
virtual hsBool Close() { hsAssert(0, "hsMMIOStream::Close NotImplemented"); return false; }
virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void* buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount);
virtual void Rewind();
virtual void FastFwd();
virtual void Truncate();
HMMIO GetHandle() { return fHmfr; }
void SetHandle(HMMIO handle) { fHmfr = handle; }
};
#endif
#endif // hsMMIOStream_inc

56
Sources/Plasma/CoreLib/hsMalloc.cpp

@ -1,56 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/CoreLib/hsMalloc.cpp
*
***/
#include "HeadSpin.h"
/*****************************************************************************
*
* Exports
*
***/

205
Sources/Plasma/CoreLib/hsMalloc.h

@ -1,205 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/CoreLib/hsMalloc.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_CORELIB_HSMALLOC_H
#define PLASMA20_SOURCES_PLASMA_CORELIB_HSMALLOC_H
/****************************************************************************
*
* Allocation functions
*
***/
#ifdef __cplusplus
extern "C" {
#endif
// MemAlloc flags
extern const unsigned kMemReallocInPlaceOnly; // use _expand when realloc'ing
extern const unsigned kMemZero; // fill allocated memory with zeros
extern const unsigned kMemIgnoreBlock; // don't track this allocation
void * MemAlloc (unsigned bytes, unsigned flags, const char file[], int line);
void * MemDup (const void * ptr, unsigned bytes, unsigned flags, const char file[], int line);
void MemFree (void * ptr, unsigned flags);
void * MemRealloc (void * ptr, unsigned bytes, unsigned flags, const char file[], int line);
unsigned MemSize (void * ptr);
/****************************************************************************
*
* Manipulation functions
*
***/
int MemCmp (const void * buf1, const void * buf2, unsigned bytes);
void MemCopy (void * dest, const void * source, unsigned bytes);
void MemMove (void * dest, const void * source, unsigned bytes);
void MemSet (void * dest, unsigned value, unsigned bytes);
void MemZero (void * dest, unsigned bytes);
/*****************************************************************************
*
* Debugging functions
*
***/
void MemDumpAllocReport ();
void MemDumpUsageReport ();
void MemValidateNow ();
void MemSetValidation (unsigned on);
void MemPushDisableTracking ();
void MemPopDisableTracking ();
void MemSetColor (unsigned short color);
#ifdef __cplusplus
}
#endif
/****************************************************************************
*
* C++ Operators
*
***/
#ifdef __cplusplus
#include <new>
#ifndef _MSC_VER
#define THROW(x) throw(x)
#define THROW_EMPTY throw()
#else
#define THROW(x)
#define THROW_EMPTY
#endif
// standard new and delete
inline void* CDECL operator new (size_t bytes) THROW(std::bad_alloc)
{ return MemAlloc((unsigned)bytes, 0, __FILE__, __LINE__); }
inline void* CDECL operator new [](size_t bytes) THROW(std::bad_alloc)
{ return MemAlloc((unsigned)bytes, 0, __FILE__, __LINE__); }
inline void CDECL operator delete (void * ptr) THROW_EMPTY
{ MemFree(ptr, 0); }
inline void CDECL operator delete [](void * ptr) THROW_EMPTY
{ MemFree(ptr, 0); }
// memcheck-friendly new
inline void* CDECL operator new (size_t bytes, const char file[], unsigned line)
{ return MemAlloc((unsigned)bytes, 0, file, line); }
inline void* CDECL operator new [](size_t bytes, const char file[], unsigned line)
{ return MemAlloc((unsigned)bytes, 0, file, line); }
inline void CDECL operator delete (void * ptr, const char [], unsigned)
{ return MemFree(ptr, 0); }
inline void CDECL operator delete [](void * ptr, const char [], unsigned)
{ return MemFree(ptr, 0); }
#define TRACKED_NEW new(__FILE__, __LINE__)
// placement new
#if defined(_MSC_VER) && !defined(__PLACEMENT_NEW_INLINE)
#define __PLACEMENT_NEW_INLINE
inline void* CDECL operator new (size_t, void * ptr) { return ptr; }
inline void CDECL operator delete (void *, void *) {}
#endif // ifndef __PLACEMENT_NEW_INLINE
#endif // ifdef __cplusplus
/****************************************************************************
*
* Macros
*
***/
#define ALLOC(b) MemAlloc(b, 0, __FILE__, __LINE__)
#define ALLOCZERO(b) MemAlloc(b, kMemZero, __FILE__, __LINE__)
#define ALLOCFLAGS(b, f) MemAlloc(b, (f), __FILE__, __LINE__)
#define FREE(p) MemFree(p, 0)
#define FREEFLAGS(p, f) MemFree(p, (f))
#define REALLOC(p, b) MemRealloc(p, b, 0, __FILE__, __LINE__)
#define REALLOCFLAGS(p, b, f) MemRealloc(p, b, (f), __FILE__, __LINE__)
#define CALLOC(n, s) MemAlloc((n)*(s), kMemZero, __FILE__, __LINE__)
#define MEMDUP(s, b) MemDup(s, b, 0, __FILE__, __LINE__)
#define ZERO(s) MemSet(&s, 0, sizeof(s))
#define ZEROPTR(p) MemSet(p, 0, sizeof(*p))
// Client must #include <malloc.h>
#define ALLOCA(t, n) (t *)_alloca((n) * sizeof(t))
#ifdef __cplusplus
#define NEW(t) new(MemAlloc(sizeof(t), 0, __FILE__, __LINE__)) t
#define NEWFLAGS(t, f) new(MemAlloc(sizeof(t), (f), __FILE__, __LINE__)) t
#define NEWZERO(t) new(MemAlloc(sizeof(t), kMemZero, __FILE__, __LINE__)) t
#define DEL(t) delete (t)
#endif // __cplusplus
/****************************************************************************
*
* TypeInfo
* (needed for memory leak reporting)
*
***/
#ifdef __cplusplus
#if !defined(HS_NO_TYPEINFO)
#include <typeinfo>
#endif
#endif // ifdef __cplusplus
#endif // PLASMA20_SOURCES_PLASMA_CORELIB_HSMALLOC_H

2
Sources/Plasma/CoreLib/hsMatrix33.cpp

@ -40,7 +40,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsMatrix33.h" #include "hsMatrix33.h"
#include "hsStream.h" #include "hsStream.h"

2
Sources/Plasma/CoreLib/hsMatrix33.h

@ -47,7 +47,7 @@ class hsStream;
struct hsMatrix33 struct hsMatrix33
{ {
hsScalar fMap[3][3]; float fMap[3][3];
hsMatrix33* Reset(); hsMatrix33* Reset();

215
Sources/Plasma/CoreLib/hsMatrix44.cpp

@ -34,7 +34,8 @@ work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at: or by snail mail at:
Cyan Worlds, Inc. Cyan Worlds, I
nc.
14617 N Newport Hwy 14617 N Newport Hwy
Mead, WA 99021 Mead, WA 99021
@ -44,6 +45,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "hsQuat.h" #include "hsQuat.h"
#include "hsMatrix44.h" #include "hsMatrix44.h"
#include "hsStream.h" #include "hsStream.h"
#include <math.h>
static hsMatrix44 myIdent = hsMatrix44().Reset(); static hsMatrix44 myIdent = hsMatrix44().Reset();
const hsMatrix44& hsMatrix44::IdentityMatrix() { return myIdent; } const hsMatrix44& hsMatrix44::IdentityMatrix() { return myIdent; }
@ -91,75 +93,6 @@ void hsMatrix44::DecompRigid(hsScalarTriple &translate, hsQuat &rotate) const
} }
#if 0
hsMatrix44& hsMatrix44::Reset()
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
fMap[i][j] = (i==j) ? hsScalar1 : 0;
}
}
return *this;
}
#endif
#if 0 // Havok reeks
hsMatrix44 operator*(const hsMatrix44& a, const hsMatrix44& b)
{
hsMatrix44 c;
if( a.fFlags & b.fFlags & hsMatrix44::kIsIdent )
{
c.Reset();
return c;
}
if( a.fFlags & hsMatrix44::kIsIdent )
return b;
if( b.fFlags & hsMatrix44::kIsIdent )
return a;
c.fMap[0][0] = hsScalarMul(a.fMap[0][0], b.fMap[0][0]) + hsScalarMul(a.fMap[0][1], b.fMap[1][0]) + hsScalarMul(a.fMap[0][2], b.fMap[2][0]) + hsScalarMul(a.fMap[0][3], b.fMap[3][0]);
c.fMap[0][1] = hsScalarMul(a.fMap[0][0], b.fMap[0][1]) + hsScalarMul(a.fMap[0][1], b.fMap[1][1]) + hsScalarMul(a.fMap[0][2], b.fMap[2][1]) + hsScalarMul(a.fMap[0][3], b.fMap[3][1]);
c.fMap[0][2] = hsScalarMul(a.fMap[0][0], b.fMap[0][2]) + hsScalarMul(a.fMap[0][1], b.fMap[1][2]) + hsScalarMul(a.fMap[0][2], b.fMap[2][2]) + hsScalarMul(a.fMap[0][3], b.fMap[3][2]);
c.fMap[0][3] = hsScalarMul(a.fMap[0][0], b.fMap[0][3]) + hsScalarMul(a.fMap[0][1], b.fMap[1][3]) + hsScalarMul(a.fMap[0][2], b.fMap[2][3]) + hsScalarMul(a.fMap[0][3], b.fMap[3][3]);
c.fMap[1][0] = hsScalarMul(a.fMap[1][0], b.fMap[0][0]) + hsScalarMul(a.fMap[1][1], b.fMap[1][0]) + hsScalarMul(a.fMap[1][2], b.fMap[2][0]) + hsScalarMul(a.fMap[1][3], b.fMap[3][0]);
c.fMap[1][1] = hsScalarMul(a.fMap[1][0], b.fMap[0][1]) + hsScalarMul(a.fMap[1][1], b.fMap[1][1]) + hsScalarMul(a.fMap[1][2], b.fMap[2][1]) + hsScalarMul(a.fMap[1][3], b.fMap[3][1]);
c.fMap[1][2] = hsScalarMul(a.fMap[1][0], b.fMap[0][2]) + hsScalarMul(a.fMap[1][1], b.fMap[1][2]) + hsScalarMul(a.fMap[1][2], b.fMap[2][2]) + hsScalarMul(a.fMap[1][3], b.fMap[3][2]);
c.fMap[1][3] = hsScalarMul(a.fMap[1][0], b.fMap[0][3]) + hsScalarMul(a.fMap[1][1], b.fMap[1][3]) + hsScalarMul(a.fMap[1][2], b.fMap[2][3]) + hsScalarMul(a.fMap[1][3], b.fMap[3][3]);
c.fMap[2][0] = hsScalarMul(a.fMap[2][0], b.fMap[0][0]) + hsScalarMul(a.fMap[2][1], b.fMap[1][0]) + hsScalarMul(a.fMap[2][2], b.fMap[2][0]) + hsScalarMul(a.fMap[2][3], b.fMap[3][0]);
c.fMap[2][1] = hsScalarMul(a.fMap[2][0], b.fMap[0][1]) + hsScalarMul(a.fMap[2][1], b.fMap[1][1]) + hsScalarMul(a.fMap[2][2], b.fMap[2][1]) + hsScalarMul(a.fMap[2][3], b.fMap[3][1]);
c.fMap[2][2] = hsScalarMul(a.fMap[2][0], b.fMap[0][2]) + hsScalarMul(a.fMap[2][1], b.fMap[1][2]) + hsScalarMul(a.fMap[2][2], b.fMap[2][2]) + hsScalarMul(a.fMap[2][3], b.fMap[3][2]);
c.fMap[2][3] = hsScalarMul(a.fMap[2][0], b.fMap[0][3]) + hsScalarMul(a.fMap[2][1], b.fMap[1][3]) + hsScalarMul(a.fMap[2][2], b.fMap[2][3]) + hsScalarMul(a.fMap[2][3], b.fMap[3][3]);
c.fMap[3][0] = hsScalarMul(a.fMap[3][0], b.fMap[0][0]) + hsScalarMul(a.fMap[3][1], b.fMap[1][0]) + hsScalarMul(a.fMap[3][2], b.fMap[2][0]) + hsScalarMul(a.fMap[3][3], b.fMap[3][0]);
c.fMap[3][1] = hsScalarMul(a.fMap[3][0], b.fMap[0][1]) + hsScalarMul(a.fMap[3][1], b.fMap[1][1]) + hsScalarMul(a.fMap[3][2], b.fMap[2][1]) + hsScalarMul(a.fMap[3][3], b.fMap[3][1]);
c.fMap[3][2] = hsScalarMul(a.fMap[3][0], b.fMap[0][2]) + hsScalarMul(a.fMap[3][1], b.fMap[1][2]) + hsScalarMul(a.fMap[3][2], b.fMap[2][2]) + hsScalarMul(a.fMap[3][3], b.fMap[3][2]);
c.fMap[3][3] = hsScalarMul(a.fMap[3][0], b.fMap[0][3]) + hsScalarMul(a.fMap[3][1], b.fMap[1][3]) + hsScalarMul(a.fMap[3][2], b.fMap[2][3]) + hsScalarMul(a.fMap[3][3], b.fMap[3][3]);
return c;
}
hsVector3 operator*(const hsMatrix44& m, const hsVector3& p)
{
if( m.fFlags & hsMatrix44::kIsIdent )
return p;
hsVector3 rVal;
rVal.fX = hsScalarMul(p.fX, m.fMap[0][0]) + hsScalarMul(p.fY, m.fMap[0][1]) + hsScalarMul(p.fZ, m.fMap[0][2]);
rVal.fY = hsScalarMul(p.fX, m.fMap[1][0]) + hsScalarMul(p.fY, m.fMap[1][1]) + hsScalarMul(p.fZ, m.fMap[1][2]);
rVal.fZ = hsScalarMul(p.fX, m.fMap[2][0]) + hsScalarMul(p.fY, m.fMap[2][1]) + hsScalarMul(p.fZ, m.fMap[2][2]);
return rVal;
}
#else // Havok reeks
hsMatrix44 hsMatrix44::operator*(const hsMatrix44& b) const hsMatrix44 hsMatrix44::operator*(const hsMatrix44& b) const
{ {
hsMatrix44 c; hsMatrix44 c;
@ -175,25 +108,25 @@ hsMatrix44 hsMatrix44::operator*(const hsMatrix44& b) const
if( b.fFlags & hsMatrix44::kIsIdent ) if( b.fFlags & hsMatrix44::kIsIdent )
return *this; return *this;
c.fMap[0][0] = hsScalarMul(fMap[0][0], b.fMap[0][0]) + hsScalarMul(fMap[0][1], b.fMap[1][0]) + hsScalarMul(fMap[0][2], b.fMap[2][0]) + hsScalarMul(fMap[0][3], b.fMap[3][0]); c.fMap[0][0] = (fMap[0][0] * b.fMap[0][0]) + (fMap[0][1] * b.fMap[1][0]) + (fMap[0][2] * b.fMap[2][0]) + (fMap[0][3] * b.fMap[3][0]);
c.fMap[0][1] = hsScalarMul(fMap[0][0], b.fMap[0][1]) + hsScalarMul(fMap[0][1], b.fMap[1][1]) + hsScalarMul(fMap[0][2], b.fMap[2][1]) + hsScalarMul(fMap[0][3], b.fMap[3][1]); c.fMap[0][1] = (fMap[0][0] * b.fMap[0][1]) + (fMap[0][1] * b.fMap[1][1]) + (fMap[0][2] * b.fMap[2][1]) + (fMap[0][3] * b.fMap[3][1]);
c.fMap[0][2] = hsScalarMul(fMap[0][0], b.fMap[0][2]) + hsScalarMul(fMap[0][1], b.fMap[1][2]) + hsScalarMul(fMap[0][2], b.fMap[2][2]) + hsScalarMul(fMap[0][3], b.fMap[3][2]); c.fMap[0][2] = (fMap[0][0] * b.fMap[0][2]) + (fMap[0][1] * b.fMap[1][2]) + (fMap[0][2] * b.fMap[2][2]) + (fMap[0][3] * b.fMap[3][2]);
c.fMap[0][3] = hsScalarMul(fMap[0][0], b.fMap[0][3]) + hsScalarMul(fMap[0][1], b.fMap[1][3]) + hsScalarMul(fMap[0][2], b.fMap[2][3]) + hsScalarMul(fMap[0][3], b.fMap[3][3]); c.fMap[0][3] = (fMap[0][0] * b.fMap[0][3]) + (fMap[0][1] * b.fMap[1][3]) + (fMap[0][2] * b.fMap[2][3]) + (fMap[0][3] * b.fMap[3][3]);
c.fMap[1][0] = hsScalarMul(fMap[1][0], b.fMap[0][0]) + hsScalarMul(fMap[1][1], b.fMap[1][0]) + hsScalarMul(fMap[1][2], b.fMap[2][0]) + hsScalarMul(fMap[1][3], b.fMap[3][0]); c.fMap[1][0] = (fMap[1][0] * b.fMap[0][0]) + (fMap[1][1] * b.fMap[1][0]) + (fMap[1][2] * b.fMap[2][0]) + (fMap[1][3] * b.fMap[3][0]);
c.fMap[1][1] = hsScalarMul(fMap[1][0], b.fMap[0][1]) + hsScalarMul(fMap[1][1], b.fMap[1][1]) + hsScalarMul(fMap[1][2], b.fMap[2][1]) + hsScalarMul(fMap[1][3], b.fMap[3][1]); c.fMap[1][1] = (fMap[1][0] * b.fMap[0][1]) + (fMap[1][1] * b.fMap[1][1]) + (fMap[1][2] * b.fMap[2][1]) + (fMap[1][3] * b.fMap[3][1]);
c.fMap[1][2] = hsScalarMul(fMap[1][0], b.fMap[0][2]) + hsScalarMul(fMap[1][1], b.fMap[1][2]) + hsScalarMul(fMap[1][2], b.fMap[2][2]) + hsScalarMul(fMap[1][3], b.fMap[3][2]); c.fMap[1][2] = (fMap[1][0] * b.fMap[0][2]) + (fMap[1][1] * b.fMap[1][2]) + (fMap[1][2] * b.fMap[2][2]) + (fMap[1][3] * b.fMap[3][2]);
c.fMap[1][3] = hsScalarMul(fMap[1][0], b.fMap[0][3]) + hsScalarMul(fMap[1][1], b.fMap[1][3]) + hsScalarMul(fMap[1][2], b.fMap[2][3]) + hsScalarMul(fMap[1][3], b.fMap[3][3]); c.fMap[1][3] = (fMap[1][0] * b.fMap[0][3]) + (fMap[1][1] * b.fMap[1][3]) + (fMap[1][2] * b.fMap[2][3]) + (fMap[1][3] * b.fMap[3][3]);
c.fMap[2][0] = hsScalarMul(fMap[2][0], b.fMap[0][0]) + hsScalarMul(fMap[2][1], b.fMap[1][0]) + hsScalarMul(fMap[2][2], b.fMap[2][0]) + hsScalarMul(fMap[2][3], b.fMap[3][0]); c.fMap[2][0] = (fMap[2][0] * b.fMap[0][0]) + (fMap[2][1] * b.fMap[1][0]) + (fMap[2][2] * b.fMap[2][0]) + (fMap[2][3] * b.fMap[3][0]);
c.fMap[2][1] = hsScalarMul(fMap[2][0], b.fMap[0][1]) + hsScalarMul(fMap[2][1], b.fMap[1][1]) + hsScalarMul(fMap[2][2], b.fMap[2][1]) + hsScalarMul(fMap[2][3], b.fMap[3][1]); c.fMap[2][1] = (fMap[2][0] * b.fMap[0][1]) + (fMap[2][1] * b.fMap[1][1]) + (fMap[2][2] * b.fMap[2][1]) + (fMap[2][3] * b.fMap[3][1]);
c.fMap[2][2] = hsScalarMul(fMap[2][0], b.fMap[0][2]) + hsScalarMul(fMap[2][1], b.fMap[1][2]) + hsScalarMul(fMap[2][2], b.fMap[2][2]) + hsScalarMul(fMap[2][3], b.fMap[3][2]); c.fMap[2][2] = (fMap[2][0] * b.fMap[0][2]) + (fMap[2][1] * b.fMap[1][2]) + (fMap[2][2] * b.fMap[2][2]) + (fMap[2][3] * b.fMap[3][2]);
c.fMap[2][3] = hsScalarMul(fMap[2][0], b.fMap[0][3]) + hsScalarMul(fMap[2][1], b.fMap[1][3]) + hsScalarMul(fMap[2][2], b.fMap[2][3]) + hsScalarMul(fMap[2][3], b.fMap[3][3]); c.fMap[2][3] = (fMap[2][0] * b.fMap[0][3]) + (fMap[2][1] * b.fMap[1][3]) + (fMap[2][2] * b.fMap[2][3]) + (fMap[2][3] * b.fMap[3][3]);
c.fMap[3][0] = hsScalarMul(fMap[3][0], b.fMap[0][0]) + hsScalarMul(fMap[3][1], b.fMap[1][0]) + hsScalarMul(fMap[3][2], b.fMap[2][0]) + hsScalarMul(fMap[3][3], b.fMap[3][0]); c.fMap[3][0] = (fMap[3][0] * b.fMap[0][0]) + (fMap[3][1] * b.fMap[1][0]) + (fMap[3][2] * b.fMap[2][0]) + (fMap[3][3] * b.fMap[3][0]);
c.fMap[3][1] = hsScalarMul(fMap[3][0], b.fMap[0][1]) + hsScalarMul(fMap[3][1], b.fMap[1][1]) + hsScalarMul(fMap[3][2], b.fMap[2][1]) + hsScalarMul(fMap[3][3], b.fMap[3][1]); c.fMap[3][1] = (fMap[3][0] * b.fMap[0][1]) + (fMap[3][1] * b.fMap[1][1]) + (fMap[3][2] * b.fMap[2][1]) + (fMap[3][3] * b.fMap[3][1]);
c.fMap[3][2] = hsScalarMul(fMap[3][0], b.fMap[0][2]) + hsScalarMul(fMap[3][1], b.fMap[1][2]) + hsScalarMul(fMap[3][2], b.fMap[2][2]) + hsScalarMul(fMap[3][3], b.fMap[3][2]); c.fMap[3][2] = (fMap[3][0] * b.fMap[0][2]) + (fMap[3][1] * b.fMap[1][2]) + (fMap[3][2] * b.fMap[2][2]) + (fMap[3][3] * b.fMap[3][2]);
c.fMap[3][3] = hsScalarMul(fMap[3][0], b.fMap[0][3]) + hsScalarMul(fMap[3][1], b.fMap[1][3]) + hsScalarMul(fMap[3][2], b.fMap[2][3]) + hsScalarMul(fMap[3][3], b.fMap[3][3]); c.fMap[3][3] = (fMap[3][0] * b.fMap[0][3]) + (fMap[3][1] * b.fMap[1][3]) + (fMap[3][2] * b.fMap[2][3]) + (fMap[3][3] * b.fMap[3][3]);
return c; return c;
} }
@ -205,34 +138,13 @@ hsVector3 hsMatrix44::operator*(const hsVector3& p) const
hsVector3 rVal; hsVector3 rVal;
rVal.fX = hsScalarMul(p.fX, fMap[0][0]) + hsScalarMul(p.fY, fMap[0][1]) + hsScalarMul(p.fZ, fMap[0][2]); rVal.fX = (p.fX * fMap[0][0]) + (p.fY * fMap[0][1]) + (p.fZ * fMap[0][2]);
rVal.fY = hsScalarMul(p.fX, fMap[1][0]) + hsScalarMul(p.fY, fMap[1][1]) + hsScalarMul(p.fZ, fMap[1][2]); rVal.fY = (p.fX * fMap[1][0]) + (p.fY * fMap[1][1]) + (p.fZ * fMap[1][2]);
rVal.fZ = hsScalarMul(p.fX, fMap[2][0]) + hsScalarMul(p.fY, fMap[2][1]) + hsScalarMul(p.fZ, fMap[2][2]); rVal.fZ = (p.fX * fMap[2][0]) + (p.fY * fMap[2][1]) + (p.fZ * fMap[2][2]);
return rVal; return rVal;
} }
#endif // Havok reeks
#if 0 // Havok reeks
int operator==(const hsMatrix44& s, const hsMatrix44& t)
{
if( s.fFlags & t.fFlags & hsMatrix44::kIsIdent )
{
return true;
}
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if (s.fMap[i][j] != t.fMap[i][j])
return false;
}
}
return true;
}
#else // Havok reeks
int hsMatrix44::operator==(const hsMatrix44& ss) const int hsMatrix44::operator==(const hsMatrix44& ss) const
{ {
if( ss.fFlags & fFlags & hsMatrix44::kIsIdent ) if( ss.fFlags & fFlags & hsMatrix44::kIsIdent )
@ -251,7 +163,6 @@ int hsMatrix44::operator==(const hsMatrix44& ss) const
return true; return true;
} }
#endif // Havok reeks
hsMatrix44& hsMatrix44::Scale(const hsVector3* scale) hsMatrix44& hsMatrix44::Scale(const hsVector3* scale)
{ {
@ -315,7 +226,7 @@ hsMatrix44& hsMatrix44::SetTranslate(const hsScalarTriple* pt)
NotIdentity(); NotIdentity();
return *this; return *this;
} }
hsMatrix44& hsMatrix44::MakeRotateMat(int axis, hsScalar radians) hsMatrix44& hsMatrix44::MakeRotateMat(int axis, float radians)
{ {
Reset(); Reset();
SetRotate(axis, radians); SetRotate(axis, radians);
@ -323,7 +234,7 @@ hsMatrix44& hsMatrix44::MakeRotateMat(int axis, hsScalar radians)
return *this; return *this;
} }
hsMatrix44& hsMatrix44::Rotate(int axis, hsScalar radians) hsMatrix44& hsMatrix44::Rotate(int axis, float radians)
{ {
hsMatrix44 rMat; hsMatrix44 rMat;
rMat.MakeRotateMat(axis, radians); rMat.MakeRotateMat(axis, radians);
@ -331,10 +242,10 @@ hsMatrix44& hsMatrix44::Rotate(int axis, hsScalar radians)
return *this; return *this;
} }
hsMatrix44& hsMatrix44::SetRotate(int axis, hsScalar radians) hsMatrix44& hsMatrix44::SetRotate(int axis, float radians)
{ {
hsScalar s = hsSine(radians); float s = sin(radians);
hsScalar c = hsCosine(radians); float c = cos(radians);
int c1,c2; int c1,c2;
switch (axis) switch (axis)
{ {
@ -361,11 +272,11 @@ hsMatrix44& hsMatrix44::SetRotate(int axis, hsScalar radians)
return *this; return *this;
} }
void hsMatrix44::MakeXRotation(hsScalar radians) void hsMatrix44::MakeXRotation(float radians)
{ {
Reset(); Reset();
hsScalar s = hsSine(radians); float s = sin(radians);
hsScalar c = hsCosine(radians); float c = cos(radians);
fMap[1][1] = c; fMap[1][1] = c;
fMap[2][2] = c; fMap[2][2] = c;
@ -374,11 +285,11 @@ void hsMatrix44::MakeXRotation(hsScalar radians)
NotIdentity(); NotIdentity();
} }
void hsMatrix44::MakeYRotation(hsScalar radians) void hsMatrix44::MakeYRotation(float radians)
{ {
Reset(); Reset();
hsScalar s = hsSine(radians); float s = sin(radians);
hsScalar c = hsCosine(radians); float c = cos(radians);
fMap[0][0] = c; fMap[0][0] = c;
fMap[2][2] = c; fMap[2][2] = c;
fMap[0][2] = -s; fMap[0][2] = -s;
@ -386,11 +297,11 @@ void hsMatrix44::MakeYRotation(hsScalar radians)
NotIdentity(); NotIdentity();
} }
void hsMatrix44::MakeZRotation(hsScalar radians) void hsMatrix44::MakeZRotation(float radians)
{ {
Reset(); Reset();
hsScalar s = hsSine(radians); float s = sin(radians);
hsScalar c = hsCosine(radians); float c = cos(radians);
fMap[0][0] = c; fMap[0][0] = c;
fMap[1][1] = c; fMap[1][1] = c;
fMap[0][1] = s; fMap[0][1] = s;
@ -630,14 +541,14 @@ hsMatrix44& hsMatrix44::MakeCameraUpPreserving(const hsPoint3* from, const hsPoi
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
static hsScalar GetDeterminant33(const hsMatrix44* mat) static float GetDeterminant33(const hsMatrix44* mat)
{ {
return hsScalarMul(hsScalarMul(mat->fMap[0][0], mat->fMap[1][1]), mat->fMap[2][2]) + return ((mat->fMap[0][0] * mat->fMap[1][1]) * mat->fMap[2][2]) +
hsScalarMul(hsScalarMul(mat->fMap[0][1], mat->fMap[1][2]), mat->fMap[2][0]) + ((mat->fMap[0][1] * mat->fMap[1][2]) * mat->fMap[2][0]) +
hsScalarMul(hsScalarMul(mat->fMap[0][2], mat->fMap[1][0]), mat->fMap[2][1]) - ((mat->fMap[0][2] * mat->fMap[1][0]) * mat->fMap[2][1]) -
hsScalarMul(hsScalarMul(mat->fMap[0][2], mat->fMap[1][1]), mat->fMap[2][0]) - ((mat->fMap[0][2] * mat->fMap[1][1]) * mat->fMap[2][0]) -
hsScalarMul(hsScalarMul(mat->fMap[0][1], mat->fMap[1][0]), mat->fMap[2][2]) - ((mat->fMap[0][1] * mat->fMap[1][0]) * mat->fMap[2][2]) -
hsScalarMul(hsScalarMul(mat->fMap[0][0], mat->fMap[1][2]), mat->fMap[2][1]); ((mat->fMap[0][0] * mat->fMap[1][2]) * mat->fMap[2][1]);
} }
hsMatrix44* hsMatrix44::GetTranspose(hsMatrix44* transp) const hsMatrix44* hsMatrix44::GetTranspose(hsMatrix44* transp) const
@ -649,21 +560,21 @@ hsMatrix44* hsMatrix44::GetTranspose(hsMatrix44* transp) const
} }
static inline hsScalar Determinant2(hsScalar a, hsScalar b,hsScalar c, hsScalar d) static inline float Determinant2(float a, float b,float c, float d)
{ {
return hsScalarMul(a,d) - hsScalarMul(c,b); return (a * d) - (c * b);
} }
static inline hsScalar Determinant3(hsScalar a, hsScalar b, hsScalar c, static inline float Determinant3(float a, float b, float c,
hsScalar d, hsScalar e, hsScalar f, float d, float e, float f,
hsScalar g, hsScalar h, hsScalar i) float g, float h, float i)
{ {
return hsScalarMul(a, Determinant2(e, f, h, i)) return (a * Determinant2(e, f, h, i))
- hsScalarMul(b, Determinant2(d, f, g, i)) - (b * Determinant2(d, f, g, i))
+ hsScalarMul(c, Determinant2(d, e, g, h)); + (c * Determinant2(d, e, g, h));
} }
hsScalar hsMatrix44::GetDeterminant() const float hsMatrix44::GetDeterminant() const
{ {
return (fMap[0][0]*Determinant3(fMap[1][1], fMap[2][1], fMap[3][1], return (fMap[0][0]*Determinant3(fMap[1][1], fMap[2][1], fMap[3][1],
fMap[1][2], fMap[2][2], fMap[3][2], fMap[1][2], fMap[2][2], fMap[3][2],
@ -753,7 +664,7 @@ hsMatrix44 *hsMatrix44::GetAdjoint(hsMatrix44 *adj) const
hsMatrix44* hsMatrix44::GetInverse(hsMatrix44* inverse) const hsMatrix44* hsMatrix44::GetInverse(hsMatrix44* inverse) const
{ {
hsScalar det = GetDeterminant(); float det = GetDeterminant();
int i,j; int i,j;
if (det == 0.0f) if (det == 0.0f)
@ -762,7 +673,7 @@ hsMatrix44* hsMatrix44::GetInverse(hsMatrix44* inverse) const
return inverse; return inverse;
} }
det = hsScalarInvert(det); det = hsInvert(det);
GetAdjoint(inverse); GetAdjoint(inverse);
for (i=0; i<4; i++) for (i=0; i<4; i++)
@ -840,7 +751,7 @@ hsBool hsMatrix44::IsIdentity(void)
#if 0 // IDENTITY_CRISIS #if 0 // IDENTITY_CRISIS
if( i == j) if( i == j)
{ {
if (fMap[i][j] != hsScalar1) if (fMap[i][j] != 1.f)
{ {
NotIdentity(); NotIdentity();
retVal = false; retVal = false;
@ -855,17 +766,17 @@ hsBool hsMatrix44::IsIdentity(void)
} }
} }
#else // IDENTITY_CRISIS #else // IDENTITY_CRISIS
const hsScalar kEPS = 1.e-5f; const float kEPS = 1.e-5f;
if( i == j) if( i == j)
{ {
if( (fMap[i][j] < hsScalar1-kEPS) || (fMap[i][j] > hsScalar1+kEPS) ) if( (fMap[i][j] < 1.f-kEPS) || (fMap[i][j] > 1.f+kEPS) )
{ {
NotIdentity(); NotIdentity();
retVal = false; retVal = false;
} }
else else
{ {
fMap[i][j] = hsScalar1; fMap[i][j] = 1.f;
} }
} }
else else
@ -909,12 +820,7 @@ void hsMatrix44::Read(hsStream *stream)
int i,j; int i,j;
for(i=0; i<4; i++) for(i=0; i<4; i++)
for(j=0; j<4; j++) for(j=0; j<4; j++)
#if HS_SCALAR_IS_FIXED
fMap[i][j] = stream->ReadLE32();
#endif
#if HS_SCALAR_IS_FLOAT
fMap[i][j] = stream->ReadLEFloat(); fMap[i][j] = stream->ReadLEFloat();
#endif
IsIdentity(); IsIdentity();
} }
else else
@ -930,11 +836,6 @@ void hsMatrix44::Write(hsStream *stream)
int i,j; int i,j;
for(i=0; i<4; i++) for(i=0; i<4; i++)
for(j=0; j<4; j++) for(j=0; j<4; j++)
#if HS_SCALAR_IS_FIXED
stream->WriteLE32(fMap[i][j]);
#endif
#if HS_SCALAR_IS_FLOAT
stream->WriteLEFloat(fMap[i][j]); stream->WriteLEFloat(fMap[i][j]);
#endif
} }
} }

54
Sources/Plasma/CoreLib/hsMatrix44.h

@ -42,7 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef HSMATRIX44_inc #ifndef HSMATRIX44_inc
#define HSMATRIX44_inc #define HSMATRIX44_inc
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsGeometry3.h" #include "hsGeometry3.h"
class hsQuat; class hsQuat;
@ -59,8 +59,8 @@ struct hsMatrix44 {
kUp, kUp,
kView kView
}; };
hsScalar fMap[4][4]; float fMap[4][4];
UInt32 fFlags; uint32_t fFlags;
hsMatrix44() : fFlags(0) {} hsMatrix44() : fFlags(0) {}
hsMatrix44(const hsScalarTriple &translate, const hsQuat &rotate); hsMatrix44(const hsScalarTriple &translate, const hsQuat &rotate);
@ -76,7 +76,7 @@ struct hsMatrix44 {
// Concat transform // Concat transform
hsMatrix44& Translate(const hsVector3 *); hsMatrix44& Translate(const hsVector3 *);
hsMatrix44& Scale(const hsVector3 *); hsMatrix44& Scale(const hsVector3 *);
hsMatrix44& Rotate(int axis, hsScalar radians); hsMatrix44& Rotate(int axis, float radians);
hsMatrix44& Reset(hsBool asIdent=true) hsMatrix44& Reset(hsBool asIdent=true)
{ {
@ -92,7 +92,7 @@ struct hsMatrix44 {
// Create matrix from scratch // Create matrix from scratch
hsMatrix44& MakeTranslateMat(const hsVector3 *trans); hsMatrix44& MakeTranslateMat(const hsVector3 *trans);
hsMatrix44& MakeScaleMat(const hsVector3 *scale); hsMatrix44& MakeScaleMat(const hsVector3 *scale);
hsMatrix44& MakeRotateMat(int axis, hsScalar radians); hsMatrix44& MakeRotateMat(int axis, float radians);
hsMatrix44& Make(const hsPoint3* from, const hsPoint3* at, hsMatrix44& Make(const hsPoint3* from, const hsPoint3* at,
const hsVector3* up); // Not a camera matrix const hsVector3* up); // Not a camera matrix
hsMatrix44& MakeUpPreserving(const hsPoint3* from, const hsPoint3* at, hsMatrix44& MakeUpPreserving(const hsPoint3* from, const hsPoint3* at,
@ -104,7 +104,7 @@ struct hsMatrix44 {
const hsVector3* up); const hsVector3* up);
hsBool GetParity() const; hsBool GetParity() const;
hsScalar GetDeterminant() const; float GetDeterminant() const;
hsMatrix44* GetInverse(hsMatrix44* inverse) const; hsMatrix44* GetInverse(hsMatrix44* inverse) const;
hsMatrix44* GetTranspose(hsMatrix44* inverse) const; hsMatrix44* GetTranspose(hsMatrix44* inverse) const;
hsMatrix44* GetAdjoint(hsMatrix44* adjoint) const; hsMatrix44* GetAdjoint(hsMatrix44* adjoint) const;
@ -120,67 +120,39 @@ struct hsMatrix44 {
// Change component of matrix // Change component of matrix
hsMatrix44& SetTranslate(const hsScalarTriple *); hsMatrix44& SetTranslate(const hsScalarTriple *);
hsMatrix44& SetScale(const hsVector3 *); hsMatrix44& SetScale(const hsVector3 *);
hsMatrix44& SetRotate(int axis, hsScalar radians); hsMatrix44& SetRotate(int axis, float radians);
hsVector3 RemoveScale(); // returns old scale hsVector3 RemoveScale(); // returns old scale
void MakeXRotation(hsScalar radians); void MakeXRotation(float radians);
void MakeYRotation(hsScalar radians); void MakeYRotation(float radians);
void MakeZRotation(hsScalar radians); void MakeZRotation(float radians);
#if 0 // Havok reeks
friend hsPoint3 operator*(const hsMatrix44& m, const hsPoint3& p)
{
if( m.fFlags & hsMatrix44::kIsIdent )
return p;
hsPoint3 rVal;
rVal.fX = hsScalarMul(p.fX, m.fMap[0][0]) + hsScalarMul(p.fY, m.fMap[0][1]) + hsScalarMul(p.fZ, m.fMap[0][2]) + m.fMap[0][3];
rVal.fY = hsScalarMul(p.fX, m.fMap[1][0]) + hsScalarMul(p.fY, m.fMap[1][1]) + hsScalarMul(p.fZ, m.fMap[1][2]) + m.fMap[1][3];
rVal.fZ = hsScalarMul(p.fX, m.fMap[2][0]) + hsScalarMul(p.fY, m.fMap[2][1]) + hsScalarMul(p.fZ, m.fMap[2][2]) + m.fMap[2][3];
return rVal;
}
friend hsVector3 operator*(const hsMatrix44& m, const hsVector3& p);
friend hsMatrix44 operator*(const hsMatrix44& a, const hsMatrix44& b);
#else // Havok reeks
hsPoint3 operator*(const hsPoint3& p) const hsPoint3 operator*(const hsPoint3& p) const
{ {
if( fFlags & hsMatrix44::kIsIdent ) if( fFlags & hsMatrix44::kIsIdent )
return p; return p;
hsPoint3 rVal; hsPoint3 rVal;
rVal.fX = hsScalarMul(p.fX, fMap[0][0]) + hsScalarMul(p.fY, fMap[0][1]) + hsScalarMul(p.fZ, fMap[0][2]) + fMap[0][3]; rVal.fX = (p.fX * fMap[0][0]) + (p.fY * fMap[0][1]) + (p.fZ * fMap[0][2]) + fMap[0][3];
rVal.fY = hsScalarMul(p.fX, fMap[1][0]) + hsScalarMul(p.fY, fMap[1][1]) + hsScalarMul(p.fZ, fMap[1][2]) + fMap[1][3]; rVal.fY = (p.fX * fMap[1][0]) + (p.fY * fMap[1][1]) + (p.fZ * fMap[1][2]) + fMap[1][3];
rVal.fZ = hsScalarMul(p.fX, fMap[2][0]) + hsScalarMul(p.fY, fMap[2][1]) + hsScalarMul(p.fZ, fMap[2][2]) + fMap[2][3]; rVal.fZ = (p.fX * fMap[2][0]) + (p.fY * fMap[2][1]) + (p.fZ * fMap[2][2]) + fMap[2][3];
return rVal; return rVal;
} }
hsVector3 operator*(const hsVector3& p) const; hsVector3 operator*(const hsVector3& p) const;
hsMatrix44 operator*(const hsMatrix44& b) const; hsMatrix44 operator*(const hsMatrix44& b) const;
#endif // Havok reeks
hsPoint3* MapPoints(long count, hsPoint3 points[]) const; hsPoint3* MapPoints(long count, hsPoint3 points[]) const;
hsBool IsIdentity(void); hsBool IsIdentity(void);
void NotIdentity() { fFlags &= ~kIsIdent; } void NotIdentity() { fFlags &= ~kIsIdent; }
#if 0 // Havok reeks
friend int operator==(const hsMatrix44& s, const hsMatrix44& t);
friend int operator!=(const hsMatrix44& s, const hsMatrix44& t);
#else // Havok reeks
hsBool operator==(const hsMatrix44& ss) const; hsBool operator==(const hsMatrix44& ss) const;
hsBool operator!=(const hsMatrix44& ss) const { return !(ss == *this); } hsBool operator!=(const hsMatrix44& ss) const { return !(ss == *this); }
#endif // Havok reeks
void Read(hsStream *stream); void Read(hsStream *stream);
void Write(hsStream *stream); void Write(hsStream *stream);
}; };
#if 0 // Havok reeks
inline int operator!=(const hsMatrix44& s, const hsMatrix44& t)
{
return (!(s==t));
}
#endif // Havok reeks
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
#endif #endif

96
Sources/Plasma/CoreLib/hsMemory.cpp

@ -49,15 +49,15 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
void HSMemory::BlockMove(const void* src, void* dst, UInt32 length) void HSMemory::BlockMove(const void* src, void* dst, uint32_t length)
{ {
memmove(dst, src, length); memmove(dst, src, length);
} }
hsBool HSMemory::EqualBlocks(const void* block1, const void* block2, UInt32 length) hsBool HSMemory::EqualBlocks(const void* block1, const void* block2, uint32_t length)
{ {
const Byte* byte1 = (Byte*)block1; const uint8_t* byte1 = (uint8_t*)block1;
const Byte* byte2 = (Byte*)block2; const uint8_t* byte2 = (uint8_t*)block2;
while (length--) while (length--)
if (*byte1++ != *byte2++) if (*byte1++ != *byte2++)
@ -65,17 +65,17 @@ hsBool HSMemory::EqualBlocks(const void* block1, const void* block2, UInt32 leng
return true; return true;
} }
void* HSMemory::New(UInt32 size) void* HSMemory::New(uint32_t size)
{ {
return TRACKED_NEW UInt32[(size + 3) >> 2]; return new uint32_t[(size + 3) >> 2];
} }
void HSMemory::Delete(void* block) void HSMemory::Delete(void* block)
{ {
delete[] (UInt32*)block; delete[] (uint32_t*)block;
} }
void* HSMemory::Copy(UInt32 length, const void* source) void* HSMemory::Copy(uint32_t length, const void* source)
{ {
void* destination = HSMemory::New(length); void* destination = HSMemory::New(length);
@ -83,22 +83,22 @@ void* HSMemory::Copy(UInt32 length, const void* source)
return destination; return destination;
} }
void HSMemory::Clear(void* m, UInt32 byteLen) void HSMemory::Clear(void* m, uint32_t byteLen)
{ {
UInt8* mem = (UInt8*)m; uint8_t* mem = (uint8_t*)m;
UInt8* memStop = mem + byteLen; uint8_t* memStop = mem + byteLen;
if (byteLen > 8) if (byteLen > 8)
{ while (unsigned_ptr(mem) & 3) { while (uintptr_t(mem) & 3)
*mem++ = 0; *mem++ = 0;
UInt32* mem32 = (UInt32*)mem; uint32_t* mem32 = (uint32_t*)mem;
UInt32* mem32Stop = (UInt32*)(unsigned_ptr(memStop) & ~3); uint32_t* mem32Stop = (uint32_t*)(uintptr_t(memStop) & ~3);
do { do {
*mem32++ = 0; *mem32++ = 0;
} while (mem32 < mem32Stop); } while (mem32 < mem32Stop);
mem = (UInt8*)mem32; mem = (uint8_t*)mem32;
// fall through to finish any remaining bytes (0..3) // fall through to finish any remaining bytes (0..3)
} }
while (mem < memStop) while (mem < memStop)
@ -113,7 +113,7 @@ void HSMemory::Clear(void* m, UInt32 byteLen)
template <class T> T* hsSoftNew(T*& obj) template <class T> T* hsSoftNew(T*& obj)
{ {
try { try {
obj = TRACKED_NEW T; obj = new T;
} }
catch (...) { catch (...) {
obj = nil; obj = nil;
@ -124,7 +124,7 @@ template <class T> T* hsSoftNew(T*& obj)
inline template <class T> T* hsSoftNew(T*& obj, unsigned count) inline template <class T> T* hsSoftNew(T*& obj, unsigned count)
{ {
try { try {
obj = TRACKED_NEW T[count]; obj = new T[count];
} }
catch (...) { catch (...) {
obj = nil; obj = nil;
@ -133,12 +133,12 @@ inline template <class T> T* hsSoftNew(T*& obj, unsigned count)
} }
#endif #endif
void* HSMemory::SoftNew(UInt32 size) void* HSMemory::SoftNew(uint32_t size)
{ {
UInt32* p; uint32_t* p;
hsTry { hsTry {
p = TRACKED_NEW UInt32[(size + 3) >> 2]; p = new uint32_t[(size + 3) >> 2];
} hsCatch(...) { } hsCatch(...) {
p = nil; p = nil;
} }
@ -150,15 +150,15 @@ void* HSMemory::SoftNew(UInt32 size)
struct hsPrivateChunk { struct hsPrivateChunk {
hsPrivateChunk* fNext; hsPrivateChunk* fNext;
char* fAvailableAddr; char* fAvailableAddr;
UInt32 fAvailableSize; uint32_t fAvailableSize;
hsDebugCode(UInt32 fSize;) hsDebugCode(uint32_t fSize;)
hsDebugCode(UInt32 fCount;) hsDebugCode(uint32_t fCount;)
static hsPrivateChunk* NewPrivateChunk(hsPrivateChunk* next, UInt32 chunkSize); static hsPrivateChunk* NewPrivateChunk(hsPrivateChunk* next, uint32_t chunkSize);
}; };
hsPrivateChunk* hsPrivateChunk::NewPrivateChunk(hsPrivateChunk* next, UInt32 chunkSize) hsPrivateChunk* hsPrivateChunk::NewPrivateChunk(hsPrivateChunk* next, uint32_t chunkSize)
{ {
hsPrivateChunk* chunk = (hsPrivateChunk*)HSMemory::New(sizeof(hsPrivateChunk) + chunkSize); hsPrivateChunk* chunk = (hsPrivateChunk*)HSMemory::New(sizeof(hsPrivateChunk) + chunkSize);
@ -171,7 +171,7 @@ hsPrivateChunk* hsPrivateChunk::NewPrivateChunk(hsPrivateChunk* next, UInt32 chu
return chunk; return chunk;
} }
hsChunkAllocator::hsChunkAllocator(UInt32 chunkSize) : fChunkSize(chunkSize), fChunk(nil) hsChunkAllocator::hsChunkAllocator(uint32_t chunkSize) : fChunkSize(chunkSize), fChunk(nil)
{ {
hsDebugCode(fChunkCount = 0;) hsDebugCode(fChunkCount = 0;)
} }
@ -194,12 +194,12 @@ void hsChunkAllocator::Reset()
hsDebugCode(fChunkCount = 0;) hsDebugCode(fChunkCount = 0;)
} }
void hsChunkAllocator::SetChunkSize(UInt32 chunkSize) void hsChunkAllocator::SetChunkSize(uint32_t chunkSize)
{ {
fChunkSize = chunkSize; fChunkSize = chunkSize;
} }
void* hsChunkAllocator::Allocate(UInt32 size, const void* data) void* hsChunkAllocator::Allocate(uint32_t size, const void* data)
{ {
void* addr; void* addr;
@ -221,7 +221,7 @@ void* hsChunkAllocator::Allocate(UInt32 size, const void* data)
return addr; return addr;
} }
void* hsChunkAllocator::SoftAllocate(UInt32 size, const void* data) void* hsChunkAllocator::SoftAllocate(uint32_t size, const void* data)
{ {
void* addr; void* addr;
@ -248,22 +248,22 @@ struct hsAppenderHead {
void* GetStop() const { return fStop; } void* GetStop() const { return fStop; }
void* GetFirst() const { return fFirst; } void* GetFirst() const { return fFirst; }
void* GetLast(UInt32 elemSize) const { return (char*)fStop - elemSize; } void* GetLast(uint32_t elemSize) const { return (char*)fStop - elemSize; }
UInt32 GetSize() const { return (char*)fStop - (char*)fFirst; } uint32_t GetSize() const { return (char*)fStop - (char*)fFirst; }
hsBool CanPrepend() const { return fFirst != this->GetTop(); } hsBool CanPrepend() const { return fFirst != this->GetTop(); }
int PrependSize() const { return (char*)fFirst - (char*)this->GetTop(); } int PrependSize() const { return (char*)fFirst - (char*)this->GetTop(); }
hsBool CanAppend() const { return fStop != this->GetBottom(); } hsBool CanAppend() const { return fStop != this->GetBottom(); }
int AppendSize() const { return (char*)this->GetBottom() - (char*)fStop; } int AppendSize() const { return (char*)this->GetBottom() - (char*)fStop; }
void* Prepend(UInt32 elemSize) void* Prepend(uint32_t elemSize)
{ {
hsAssert(this->CanPrepend(), "bad prepend"); hsAssert(this->CanPrepend(), "bad prepend");
fFirst = (char*)fFirst - elemSize; fFirst = (char*)fFirst - elemSize;
hsAssert((char*)fFirst >= (char*)this->GetTop(), "bad elemSize"); hsAssert((char*)fFirst >= (char*)this->GetTop(), "bad elemSize");
return fFirst; return fFirst;
} }
void* Append(UInt32 elemSize) void* Append(uint32_t elemSize)
{ {
hsAssert(this->CanAppend(), "bad append"); hsAssert(this->CanAppend(), "bad append");
void* data = fStop; void* data = fStop;
@ -271,7 +271,7 @@ struct hsAppenderHead {
hsAssert((char*)fStop <= (char*)fBottom, "bad elemSize"); hsAssert((char*)fStop <= (char*)fBottom, "bad elemSize");
return data; return data;
} }
hsBool PopHead(UInt32 elemSize, void* data) hsBool PopHead(uint32_t elemSize, void* data)
{ {
hsAssert(fFirst != fStop, "Empty"); hsAssert(fFirst != fStop, "Empty");
if( data ) if( data )
@ -279,7 +279,7 @@ struct hsAppenderHead {
fFirst = (char*)fFirst + elemSize; fFirst = (char*)fFirst + elemSize;
return fFirst == fStop; return fFirst == fStop;
} }
hsBool PopTail(UInt32 elemSize, void* data) hsBool PopTail(uint32_t elemSize, void* data)
{ {
hsAssert(fFirst != fStop, "Empty"); hsAssert(fFirst != fStop, "Empty");
fStop = (char*)fStop - elemSize; fStop = (char*)fStop - elemSize;
@ -288,9 +288,9 @@ struct hsAppenderHead {
return fFirst == fStop; return fFirst == fStop;
} }
static hsAppenderHead* NewAppend(UInt32 elemSize, UInt32 elemCount, hsAppenderHead* prev) static hsAppenderHead* NewAppend(uint32_t elemSize, uint32_t elemCount, hsAppenderHead* prev)
{ {
UInt32 dataSize = elemSize * elemCount; uint32_t dataSize = elemSize * elemCount;
hsAppenderHead* head = (hsAppenderHead*)HSMemory::New(sizeof(hsAppenderHead) + dataSize); hsAppenderHead* head = (hsAppenderHead*)HSMemory::New(sizeof(hsAppenderHead) + dataSize);
head->fNext = nil; head->fNext = nil;
@ -300,9 +300,9 @@ struct hsAppenderHead {
head->fBottom = (char*)head->fFirst + dataSize; head->fBottom = (char*)head->fFirst + dataSize;
return head; return head;
} }
static hsAppenderHead* NewPrepend(UInt32 elemSize, UInt32 elemCount, hsAppenderHead* next) static hsAppenderHead* NewPrepend(uint32_t elemSize, uint32_t elemCount, hsAppenderHead* next)
{ {
UInt32 dataSize = elemSize * elemCount; uint32_t dataSize = elemSize * elemCount;
hsAppenderHead* head = (hsAppenderHead*)HSMemory::New(sizeof(hsAppenderHead) + dataSize); hsAppenderHead* head = (hsAppenderHead*)HSMemory::New(sizeof(hsAppenderHead) + dataSize);
head->fNext = next; head->fNext = next;
@ -316,7 +316,7 @@ struct hsAppenderHead {
//////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////
hsAppender::hsAppender(UInt32 elemSize, UInt32 elemCount) hsAppender::hsAppender(uint32_t elemSize, uint32_t elemCount)
: fFirstBlock(nil), fElemSize(elemSize), fElemCount(elemCount), fCount(0) : fFirstBlock(nil), fElemSize(elemSize), fElemCount(elemCount), fCount(0)
{ {
} }
@ -326,14 +326,14 @@ hsAppender::~hsAppender()
this->Reset(); this->Reset();
} }
UInt32 hsAppender::CopyInto(void* data) const uint32_t hsAppender::CopyInto(void* data) const
{ {
if (data) if (data)
{ const hsAppenderHead* head = fFirstBlock; { const hsAppenderHead* head = fFirstBlock;
hsDebugCode(UInt32 totalSize = 0;) hsDebugCode(uint32_t totalSize = 0;)
while (head != nil) while (head != nil)
{ UInt32 size = head->GetSize(); { uint32_t size = head->GetSize();
HSMemory::BlockMove(head->GetFirst(), data, size); HSMemory::BlockMove(head->GetFirst(), data, size);
data = (char*)data + size; data = (char*)data + size;
@ -721,7 +721,7 @@ void SortNDumpUnfreedMemory(const char *nm, bool full) // file name base, and FU
_CrtMemState heap_state; _CrtMemState heap_state;
static UInt32 GrandTotal =0; static uint32_t GrandTotal =0;
static _CrtMemBlockHeader *cmbh_last; // Remember this header for next incremental check DANGER this static _CrtMemBlockHeader *cmbh_last; // Remember this header for next incremental check DANGER this
// could break if this is freed...(gives bad report) // could break if this is freed...(gives bad report)
_CrtMemBlockHeader *cmbh_last_good; _CrtMemBlockHeader *cmbh_last_good;
@ -736,7 +736,7 @@ static _CrtMemBlockHeader *cmbh_last; // Remember this header for next increme
long totsize= 0; // Track Total Bytes long totsize= 0; // Track Total Bytes
long normsize = 0; // Track total of NORMAL Blocks long normsize = 0; // Track total of NORMAL Blocks
looktbl *ltb = TRACKED_NEW looktbl[LTBLMAX]; looktbl *ltb = new looktbl[LTBLMAX];
long tblEnd=1; // first is "NULL"; long tblEnd=1; // first is "NULL";
memset((void *)ltb,0,sizeof(looktbl) * LTBLMAX); // clear table area memset((void *)ltb,0,sizeof(looktbl) * LTBLMAX); // clear table area
@ -821,7 +821,7 @@ static _CrtMemBlockHeader *cmbh_last; // Remember this header for next increme
for(int x=len; x < 25; x++) for(int x=len; x < 25; x++)
fputc(' ',DumpLogFile); // make even columns fputc(' ',DumpLogFile); // make even columns
fprintf(DumpLogFile,"%5ld K\n",(UInt32)( ltb[i].fBytes+500)/1000);//,ltb[i].fAllocs); fprintf(DumpLogFile,"%5ld K\n",(uint32_t)( ltb[i].fBytes+500)/1000);//,ltb[i].fAllocs);
//allocs += ltb[i].fAllocs; //allocs += ltb[i].fAllocs;
} }
@ -847,11 +847,11 @@ static _CrtMemBlockHeader *cmbh_last; // Remember this header for next increme
if( DumpLogFile) if( DumpLogFile)
{ fprintf(DumpLogFile,"%s ",nm); { fprintf(DumpLogFile,"%s ",nm);
int len = strlen(nm); int len = strlen(nm);
GrandTotal += (UInt32)(normsize+500)/1000; GrandTotal += (uint32_t)(normsize+500)/1000;
for(int x=len; x < 25; x++) for(int x=len; x < 25; x++)
fputc(' ',DumpLogFile); // make even columns fputc(' ',DumpLogFile); // make even columns
fprintf(DumpLogFile,"%5ld K %5ld %s\n",(UInt32)(normsize+500)/1000,GrandTotal,errStr);//, allocs); fprintf(DumpLogFile,"%5ld K %5ld %s\n",(uint32_t)(normsize+500)/1000,GrandTotal,errStr);//, allocs);
fclose(DumpLogFile); fclose(DumpLogFile);
} }
} }

57
Sources/Plasma/CoreLib/hsMemory.h

@ -42,30 +42,29 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsMemoryDefined #ifndef hsMemoryDefined
#define hsMemoryDefined #define hsMemoryDefined
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsMalloc.h"
//#include "hsTemplates.h" //#include "hsTemplates.h"
class HSMemory { class HSMemory {
public: public:
static void BlockMove(const void* src, void* dst, UInt32 length); static void BlockMove(const void* src, void* dst, uint32_t length);
static void Clear(void *m, UInt32 byteLen); static void Clear(void *m, uint32_t byteLen);
static void ClearMemory(void *m, UInt32 byteLen) { HSMemory::Clear(m, byteLen); } static void ClearMemory(void *m, uint32_t byteLen) { HSMemory::Clear(m, byteLen); }
static hsBool EqualBlocks(const void* block1, const void* block2, UInt32 length); static hsBool EqualBlocks(const void* block1, const void* block2, uint32_t length);
static void* New(UInt32 size); static void* New(uint32_t size);
static void Delete(void* block); static void Delete(void* block);
static void* Copy(UInt32 length, const void* source); static void* Copy(uint32_t length, const void* source);
static void* SoftNew(UInt32 size); // returns nil if can't allocate static void* SoftNew(uint32_t size); // returns nil if can't allocate
}; };
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
class hsAllocator { class hsAllocator {
public: public:
virtual void* Alloc(UInt32 size) = 0; virtual void* Alloc(uint32_t size) = 0;
virtual void Free(void* addr) = 0; virtual void Free(void* addr) = 0;
}; };
@ -73,9 +72,9 @@ class hsScratchMem {
enum { enum {
kBufferSize = 32 kBufferSize = 32
}; };
UInt8* fMem; uint8_t* fMem;
UInt8 fMemBuffer[kBufferSize]; uint8_t fMemBuffer[kBufferSize];
UInt32 fLength; uint32_t fLength;
public: public:
hsScratchMem() : fLength(kBufferSize) hsScratchMem() : fLength(kBufferSize)
{ {
@ -86,12 +85,12 @@ public:
if (fMem != fMemBuffer) if (fMem != fMemBuffer)
delete[] fMem; delete[] fMem;
} }
UInt8* GetMem(UInt32 length) uint8_t* GetMem(uint32_t length)
{ {
if (length > fLength) if (length > fLength)
{ if (fMem != fMemBuffer) { if (fMem != fMemBuffer)
delete[] fMem; delete[] fMem;
fMem = TRACKED_NEW UInt8[length]; fMem = new uint8_t[length];
fLength = length; fLength = length;
} }
return fMem; return fMem;
@ -102,36 +101,36 @@ class hsChunkAllocator {
enum { enum {
kDefaultChunkSize = 4096 kDefaultChunkSize = 4096
}; };
UInt32 fChunkSize; uint32_t fChunkSize;
struct hsPrivateChunk* fChunk; struct hsPrivateChunk* fChunk;
hsDebugCode(UInt32 fChunkCount;) hsDebugCode(uint32_t fChunkCount;)
public: public:
hsChunkAllocator(UInt32 chunkSize = kDefaultChunkSize); hsChunkAllocator(uint32_t chunkSize = kDefaultChunkSize);
~hsChunkAllocator(); ~hsChunkAllocator();
void Reset(); void Reset();
void SetChunkSize(UInt32 size); void SetChunkSize(uint32_t size);
void* Allocate(UInt32 size, const void* data = nil); // throws if fails void* Allocate(uint32_t size, const void* data = nil); // throws if fails
void* SoftAllocate(UInt32 size, const void* data = nil); // returns nil if fails void* SoftAllocate(uint32_t size, const void* data = nil); // returns nil if fails
}; };
/////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////
class hsAppender { class hsAppender {
struct hsAppenderHead* fFirstBlock, *fLastBlock; struct hsAppenderHead* fFirstBlock, *fLastBlock;
UInt32 fElemSize, fElemCount, fCount; uint32_t fElemSize, fElemCount, fCount;
friend class hsAppenderIterator; friend class hsAppenderIterator;
public: public:
hsAppender(UInt32 elemSize, UInt32 minCount = 16); hsAppender(uint32_t elemSize, uint32_t minCount = 16);
~hsAppender(); ~hsAppender();
UInt32 ElemSize() const { return fElemSize; } uint32_t ElemSize() const { return fElemSize; }
UInt32 Count() const { return fCount; } uint32_t Count() const { return fCount; }
hsBool IsEmpty() const { return fCount == 0; } hsBool IsEmpty() const { return fCount == 0; }
void Reset(); void Reset();
UInt32 CopyInto(void* data = nil) const; // return size of data array in bytes uint32_t CopyInto(void* data = nil) const; // return size of data array in bytes
void* PushHead(); void* PushHead();
void PushHead(const void* data); void PushHead(const void* data);
@ -185,16 +184,16 @@ public:
template <class T> class hsTAppender : hsAppender { template <class T> class hsTAppender : hsAppender {
public: public:
hsTAppender() : hsAppender(sizeof(T)) {} hsTAppender() : hsAppender(sizeof(T)) {}
hsTAppender(UInt32 minCount) : hsAppender(sizeof(T), minCount) {} hsTAppender(uint32_t minCount) : hsAppender(sizeof(T), minCount) {}
hsAppender* GetAppender() { return this; } hsAppender* GetAppender() { return this; }
const hsAppender* GetAppender() const { return this; } const hsAppender* GetAppender() const { return this; }
UInt32 Count() const { return hsAppender::Count(); } uint32_t Count() const { return hsAppender::Count(); }
hsBool IsEmpty() const { return hsAppender::IsEmpty(); } hsBool IsEmpty() const { return hsAppender::IsEmpty(); }
void Reset() { hsAppender::Reset(); } void Reset() { hsAppender::Reset(); }
UInt32 CopyInto(T copy[]) const { return hsAppender::CopyInto(copy); } uint32_t CopyInto(T copy[]) const { return hsAppender::CopyInto(copy); }
T* PushHead() { return (T*)hsAppender::PushHead(); } T* PushHead() { return (T*)hsAppender::PushHead(); }
void PushHead(const T& item) { *this->PushHead() = item; } void PushHead(const T& item) { *this->PushHead() = item; }

162
Sources/Plasma/CoreLib/hsPoint2.h

@ -42,90 +42,92 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsPoint2_Defined #ifndef hsPoint2_Defined
#define hsPoint2_Defined #define hsPoint2_Defined
#include "hsScalar.h" #include <cmath>
#define HS_POINT2_NAME hsIntPoint2 struct hsPolar {
#define HS_POINT2_TYPE Int32 float fRadius;
#include "HS_POINT2.inc" float fAngle;
}; };
#define HS_POINT2_NAME hsFixedPoint2 struct hsPoint2 {
#define HS_POINT2_TYPE hsFixed float fX, fY;
#include "HS_POINT2.inc"
hsPoint2& Set(float x, float y)
hsFixedPoint2& operator=(const hsIntPoint2& src) {
{ fX = x;
this->fX = hsIntToFixed(src.fX); fY = y;
this->fY = hsIntToFixed(src.fY); return *this;
return *this; }
} hsPoint2& operator+=(const hsPoint2& s)
{
hsFixed Magnitude() const { return hsMagnitude32(fX, fY); } this->fX += s.fX;
this->fY += s.fY;
static hsFixed Magnitude(hsFixed x, hsFixed y) return *this;
{ }
return hsMagnitude32(x, y); hsPoint2& operator-=(const hsPoint2& s)
} {
static hsFixed Distance(const hsFixedPoint2& p1, const hsFixedPoint2& p2) this->fX -= s.fX;
{ this->fY -= s.fY;
return hsMagnitude32(p2.fX - p1.fX, p2.fY - p1.fY); return *this;
} }
int operator==(const hsPoint2& ss) const
{
return (ss.fX == fX && ss.fY == fY);
}
int operator!=(const hsPoint2& ss)
{
return !(ss == *this);
}
friend hsPoint2 operator+(const hsPoint2& s, const hsPoint2& t)
{
hsPoint2 result;
result.Set(s.fX + t.fX, s.fY + t.fY);
return result;
}
friend hsPoint2 operator-(const hsPoint2& s, const hsPoint2& t)
{
hsPoint2 result;
result.Set(s.fX - t.fX, s.fY - t.fY);
return result;
}
friend hsPoint2 operator-(const hsPoint2& s)
{
hsPoint2 result = { -s.fX, -s.fY };
return result;
}
friend hsPoint2 operator*(const hsPoint2& s, float t)
{
hsPoint2 result;
result.Set(s.fX * t, s.fY * t);
return result;
}
friend hsPoint2 operator*(float t, const hsPoint2& s)
{
hsPoint2 result;
result.Set(s.fX * t, s.fY * t);
return result;
}
hsPoint2* Grid(float period);
hsBool CloseEnough(const hsPoint2* p, float tolerance) const;
float MagnitudeSquared() const { return fX * fX + fY * fY; }
float Magnitude() const { return Magnitude(fX, fY); }
hsPolar* ToPolar(hsPolar* polar) const;
static float Magnitude(float x, float y) { return sqrt(x * x + y * y); }
static float Distance(const hsPoint2& p1, const hsPoint2& p2);
static hsPoint2 Average(const hsPoint2& a, const hsPoint2& b)
{
hsPoint2 result;
result.Set((a.fX + b.fX) * float(0.5), (a.fY + b.fY) * float(0.5));
return result;
}
static float ComputeAngle(const hsPoint2& a, const hsPoint2& b, const hsPoint2& c);
}; };
#if HS_CAN_USE_FLOAT
struct hsPolar {
float fRadius;
float fAngle;
};
#define HS_POINT2_NAME hsFloatPoint2
#define HS_POINT2_TYPE float
#include "HS_POINT2.inc"
hsFloatPoint2& operator=(const hsIntPoint2& src)
{
this->fX = float(src.fX);
this->fY = float(src.fY);
return *this;
}
friend hsFloatPoint2 operator*(const hsFloatPoint2& s, float t)
{
hsFloatPoint2 result;
result.Set(s.fX * t, s.fY * t);
return result;
}
friend hsFloatPoint2 operator*(float t, const hsFloatPoint2& s)
{
hsFloatPoint2 result;
result.Set(s.fX * t, s.fY * t);
return result;
}
hsFloatPoint2* Grid(float period);
hsBool CloseEnough(const hsFloatPoint2* p, float tolerance) const;
float Magnitude() const { return hsFloatPoint2::Magnitude(fX, fY); }
float MagnitudeSquared() const { return fX * fX + fY * fY; }
hsPolar* ToPolar(hsPolar* polar) const;
static float Magnitude(float x, float y) { return hsSquareRoot(x * x + y * y); }
static hsScalar Distance(const hsFloatPoint2& p1, const hsFloatPoint2& p2);
static hsFloatPoint2 Average(const hsFloatPoint2& a, const hsFloatPoint2& b)
{
hsFloatPoint2 result;
result.Set((a.fX + b.fX) * float(0.5), (a.fY + b.fY) * float(0.5));
return result;
}
static hsScalar ComputeAngle(const hsFloatPoint2& a, const hsFloatPoint2& b, const hsFloatPoint2& c);
};
#endif
#if HS_SCALAR_IS_FIXED
typedef hsFixedPoint2 hsPoint2;
#else
typedef hsFloatPoint2 hsPoint2;
#endif
#endif // hsPoint2_Defined #endif // hsPoint2_Defined

82
Sources/Plasma/CoreLib/hsQuat.cpp

@ -53,13 +53,13 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// //
// Construct quat from angle (in radians) and axis of rotation // Construct quat from angle (in radians) and axis of rotation
// //
hsQuat::hsQuat(hsScalar rad, const hsVector3* axis) hsQuat::hsQuat(float rad, const hsVector3* axis)
{ {
// hsAssert(rad >= -hsScalarPI && rad <= hsScalarPI, "Quat: Angle should be between -PI and PI"); // hsAssert(rad >= -M_PI && rad <= M_PI, "Quat: Angle should be between -PI and PI");
fW = hsCosine(rad*0.5f); fW = cos(rad*0.5f);
hsScalar s = hsSine(rad*0.5f); float s = sin(rad*0.5f);
fX = axis->fX*s; fX = axis->fX*s;
fY = axis->fY*s; fY = axis->fY*s;
fZ = axis->fZ*s; fZ = axis->fZ*s;
@ -68,7 +68,7 @@ hsQuat::hsQuat(hsScalar rad, const hsVector3* axis)
hsQuat hsQuat::Inverse() hsQuat hsQuat::Inverse()
{ {
hsQuat q2 = Conjugate(); hsQuat q2 = Conjugate();
hsScalar msInv = 1.0f/q2.MagnitudeSquared(); float msInv = 1.0f/q2.MagnitudeSquared();
return (q2 * msInv); return (q2 * msInv);
} }
@ -82,11 +82,11 @@ hsPoint3 hsQuat::Rotate(const hsScalarTriple* v)
return hsPoint3(res.fX, res.fY, res.fZ); return hsPoint3(res.fX, res.fY, res.fZ);
} }
void hsQuat::SetAngleAxis(const hsScalar rad, const hsVector3 &axis) void hsQuat::SetAngleAxis(const float rad, const hsVector3 &axis)
{ {
fW = hsCosine(rad*0.5f); fW = cos(rad*0.5f);
hsScalar s = hsSine(rad*0.5f); float s = sin(rad*0.5f);
fX = axis.fX*s; fX = axis.fX*s;
fY = axis.fY*s; fY = axis.fY*s;
fZ = axis.fZ*s; fZ = axis.fZ*s;
@ -95,16 +95,16 @@ void hsQuat::SetAngleAxis(const hsScalar rad, const hsVector3 &axis)
// //
// Might want to Normalize before calling this // Might want to Normalize before calling this
// //
void hsQuat::GetAngleAxis(hsScalar *rad, hsVector3 *axis) const void hsQuat::GetAngleAxis(float *rad, hsVector3 *axis) const
{ {
hsAssert((fW >= -1) && (fW <= 1), "Invalid acos argument"); hsAssert((fW >= -1) && (fW <= 1), "Invalid acos argument");
hsScalar ac = hsACosine(fW); float ac = acos(fW);
*rad = 2.0f * ac; *rad = 2.0f * ac;
hsScalar s = hsSine(ac); float s = sin(ac);
if (s != 0.0f) if (s != 0.0f)
{ {
hsScalar invS = 1.0f/s; float invS = 1.0f/s;
axis->Set(fX*invS, fY*invS, fZ*invS); axis->Set(fX*invS, fY*invS, fZ*invS);
} }
else else
@ -114,7 +114,7 @@ void hsQuat::GetAngleAxis(hsScalar *rad, hsVector3 *axis) const
// //
// //
// //
hsScalar hsQuat::MagnitudeSquared() float hsQuat::MagnitudeSquared()
{ {
return (fX*fX + fY*fY + fZ*fZ + fW*fW); return (fX*fX + fY*fY + fZ*fZ + fW*fW);
} }
@ -122,9 +122,9 @@ hsScalar hsQuat::MagnitudeSquared()
// //
// //
// //
hsScalar hsQuat::Magnitude() float hsQuat::Magnitude()
{ {
return hsSquareRoot(MagnitudeSquared()); return sqrt(MagnitudeSquared());
} }
// //
@ -132,7 +132,7 @@ hsScalar hsQuat::Magnitude()
// //
void hsQuat::Normalize() void hsQuat::Normalize()
{ {
hsScalar invMag = 1.0f/Magnitude(); float invMag = 1.0f/Magnitude();
fX *= invMag; fX *= invMag;
fY *= invMag; fY *= invMag;
fZ *= invMag; fZ *= invMag;
@ -145,11 +145,11 @@ void hsQuat::Normalize()
void hsQuat::NormalizeIfNeeded() void hsQuat::NormalizeIfNeeded()
{ {
hsScalar magSquared = MagnitudeSquared(); float magSquared = MagnitudeSquared();
if (magSquared == 1.0f) if (magSquared == 1.0f)
return; return;
hsScalar invMag = 1.0f/hsSquareRoot(magSquared); float invMag = 1.0f/sqrt(magSquared);
fX *= invMag; fX *= invMag;
fY *= invMag; fY *= invMag;
fZ *= invMag; fZ *= invMag;
@ -259,17 +259,17 @@ void hsQuat::Write(hsStream *stream)
// //
// Interpolate on a sphere. // Interpolate on a sphere.
// //
void hsQuat::SetFromSlerp(hsQuat *q1, hsQuat *q2, hsScalar t) void hsQuat::SetFromSlerp(hsQuat *q1, hsQuat *q2, float t)
{ {
hsAssert(t>=0.0 && t<= 1.0, "Quat slerp param must be between 0 an 1"); hsAssert(t>=0.0 && t<= 1.0, "Quat slerp param must be between 0 an 1");
hsScalar theta = hsACosine(q1->Dot(*q2)); float theta = acos(q1->Dot(*q2));
hsScalar st = hsSine(theta); float st = sin(theta);
assert(st != 0.0); assert(st != 0.0);
hsScalar s1 = hsSine(1.0-t)*theta / st; float s1 = sin(1.0-t)*theta / st;
hsScalar s2 = hsSine(t)*theta / st; float s2 = sin(t)*theta / st;
*this = (*q1) * s1 + (*q2) * s2; *this = (*q1) * s1 + (*q2) * s2;
} }
@ -280,15 +280,15 @@ void hsQuat::SetFromSlerp(hsQuat *q1, hsQuat *q2, hsScalar t)
#define EPSILON 1.0E-6 /* a tiny number */ #define EPSILON 1.0E-6 /* a tiny number */
void hsQuat::SetFromSlerp(const hsQuat &a, const hsQuat &b, hsScalar alpha, int spin) void hsQuat::SetFromSlerp(const hsQuat &a, const hsQuat &b, float alpha, int spin)
// double alpha; /* interpolation parameter (0 to 1) */ // double alpha; /* interpolation parameter (0 to 1) */
// Quaternion *a, *b; /* start and end unit quaternions */ // Quaternion *a, *b; /* start and end unit quaternions */
// int spin; /* number of extra spin rotations */ // int spin; /* number of extra spin rotations */
{ {
hsScalar beta; /* complementary interp parameter */ float beta; /* complementary interp parameter */
hsScalar theta; /* angle between A and B */ float theta; /* angle between A and B */
hsScalar sin_t, cos_t; /* sine, cosine of theta */ float sin_t, cos_t; /* sine, cosine of theta */
hsScalar phi; /* theta plus spins */ float phi; /* theta plus spins */
int bflip; /* use negation of B? */ int bflip; /* use negation of B? */
/* cosine theta = dot product of A and B */ /* cosine theta = dot product of A and B */
@ -313,12 +313,12 @@ void hsQuat::SetFromSlerp(const hsQuat &a, const hsQuat &b, hsScalar alpha, int
} else } else
{ /* normal case */ { /* normal case */
// hsAssert((cos_t >= -1) && (cos_t <= 1), "Invalid acos argument"); // hsAssert((cos_t >= -1) && (cos_t <= 1), "Invalid acos argument");
theta = hsACosine(cos_t); theta = acos(cos_t);
phi = theta + spin * hsScalarPI; phi = theta + spin * M_PI;
sin_t = hsSine(theta); sin_t = sin(theta);
hsAssert(sin_t != 0.0, "Invalid sin value in quat slerp"); hsAssert(sin_t != 0.0, "Invalid sin value in quat slerp");
beta = hsSine(theta - alpha*phi) / sin_t; beta = sin(theta - alpha*phi) / sin_t;
alpha = hsSine(alpha*phi) / sin_t; alpha = sin(alpha*phi) / sin_t;
} }
if (bflip) if (bflip)
@ -337,11 +337,11 @@ void hsQuat::SetFromSlerp(const hsQuat &a, const hsQuat &b, hsScalar alpha, int
// //
void hsQuat::SetFromMatrix(const hsMatrix44* mat) void hsQuat::SetFromMatrix(const hsMatrix44* mat)
{ {
hsScalar wSq = 0.25f*(1 + mat->fMap[0][0] + mat->fMap[1][1] + mat->fMap[2][2]); float wSq = 0.25f*(1 + mat->fMap[0][0] + mat->fMap[1][1] + mat->fMap[2][2]);
if (wSq > EPSILON) if (wSq > EPSILON)
{ {
fW = hsSquareRoot(wSq); fW = sqrt(wSq);
hsScalar iw4 = 1.0f/(4.0f*fW); float iw4 = 1.0f/(4.0f*fW);
fX = (mat->fMap[2][1] - mat->fMap[1][2]) * iw4; fX = (mat->fMap[2][1] - mat->fMap[1][2]) * iw4;
fY = (mat->fMap[0][2] - mat->fMap[2][0]) * iw4; fY = (mat->fMap[0][2] - mat->fMap[2][0]) * iw4;
fZ = (mat->fMap[1][0] - mat->fMap[0][1]) * iw4; fZ = (mat->fMap[1][0] - mat->fMap[0][1]) * iw4;
@ -349,21 +349,21 @@ void hsQuat::SetFromMatrix(const hsMatrix44* mat)
} }
fW = 0; fW = 0;
hsScalar xSq = -0.5f*(mat->fMap[1][1] + mat->fMap[2][2]); float xSq = -0.5f*(mat->fMap[1][1] + mat->fMap[2][2]);
if (xSq > EPSILON) if (xSq > EPSILON)
{ {
fX = hsSquareRoot(xSq); fX = sqrt(xSq);
hsScalar ix2 = 1.0f/(2.0f*fX); float ix2 = 1.0f/(2.0f*fX);
fY = mat->fMap[1][0] * ix2; fY = mat->fMap[1][0] * ix2;
fZ = mat->fMap[2][0] * ix2; fZ = mat->fMap[2][0] * ix2;
return; return;
} }
fX = 0; fX = 0;
hsScalar ySq = 0.5f * (1 - mat->fMap[2][2]); float ySq = 0.5f * (1 - mat->fMap[2][2]);
if (ySq > EPSILON) if (ySq > EPSILON)
{ {
fY = hsSquareRoot(ySq); fY = sqrt(ySq);
fZ = mat->fMap[2][1] / (2.0f*fY); fZ = mat->fMap[2][1] / (2.0f*fY);
return; return;
} }

32
Sources/Plasma/CoreLib/hsQuat.h

@ -53,29 +53,29 @@ struct hsMatrix44;
class hsQuat { class hsQuat {
public: public:
hsScalar fX,fY,fZ,fW; float fX,fY,fZ,fW;
// Constructors // Constructors
hsQuat(){} hsQuat(){}
hsQuat(hsScalar X, hsScalar Y, hsScalar Z, hsScalar W) : hsQuat(float X, float Y, float Z, float W) :
fX(X), fY(Y), fZ(Z), fW(W) {} fX(X), fY(Y), fZ(Z), fW(W) {}
hsQuat(const hsQuat& a) { fX = a.fX; fY = a.fY; fZ = a.fZ; fW = a.fW; } hsQuat(const hsQuat& a) { fX = a.fX; fY = a.fY; fZ = a.fZ; fW = a.fW; }
hsQuat(hsScalar af[4]) { fX = af[0]; fY = af[1]; fZ = af[2]; fW = af[3]; } hsQuat(float af[4]) { fX = af[0]; fY = af[1]; fZ = af[2]; fW = af[3]; }
hsQuat(hsScalar rad, const hsVector3* axis); hsQuat(float rad, const hsVector3* axis);
static hsQuat QuatFromMatrix44(const hsMatrix44& mat); static hsQuat QuatFromMatrix44(const hsMatrix44& mat);
hsQuat& SetFromMatrix44(const hsMatrix44& mat); hsQuat& SetFromMatrix44(const hsMatrix44& mat);
void SetFromMatrix(const hsMatrix44 *mat); void SetFromMatrix(const hsMatrix44 *mat);
void SetFromSlerp(const hsQuat &q1, const hsQuat &q2, hsScalar t, int spin=0); void SetFromSlerp(const hsQuat &q1, const hsQuat &q2, float t, int spin=0);
void Set(hsScalar X, hsScalar Y, hsScalar Z, hsScalar W) void Set(float X, float Y, float Z, float W)
{ fX = X; fY = Y; fZ = Z; fW = W; } { fX = X; fY = Y; fZ = Z; fW = W; }
void GetAngleAxis(hsScalar *rad, hsVector3 *axis) const; void GetAngleAxis(float *rad, hsVector3 *axis) const;
void SetAngleAxis(const hsScalar rad, const hsVector3 &axis); void SetAngleAxis(const float rad, const hsVector3 &axis);
hsPoint3 Rotate(const hsScalarTriple* v); hsPoint3 Rotate(const hsScalarTriple* v);
// Access operators // Access operators
hsScalar& operator[](int i) { return (&fX)[i]; } float& operator[](int i) { return (&fX)[i]; }
const hsScalar& operator[](int i) const { return (&fX)[i]; } const float& operator[](int i) const { return (&fX)[i]; }
// Unary operators // Unary operators
hsQuat operator-() const { return(hsQuat(-fX,-fY,-fZ,-fW)); } hsQuat operator-() const { return(hsQuat(-fX,-fY,-fZ,-fW)); }
@ -84,14 +84,14 @@ public:
// Comparison // Comparison
int operator==(const hsQuat& a) const int operator==(const hsQuat& a) const
{ return (fX==a.fX && fY==a.fY && fZ==a.fZ && fW==a.fW); } { return (fX==a.fX && fY==a.fY && fZ==a.fZ && fW==a.fW); }
void Identity() { fX = fY = fZ = (hsScalar)0.0; fW = (hsScalar) 1.0; } void Identity() { fX = fY = fZ = (float)0.0; fW = (float) 1.0; }
int IsIdentity() const int IsIdentity() const
{ return (fX==0.0 && fY==0.0 && fZ==0.0 && fW==1.0); } { return (fX==0.0 && fY==0.0 && fZ==0.0 && fW==1.0); }
void Normalize(); void Normalize();
void NormalizeIfNeeded(); void NormalizeIfNeeded();
void MakeMatrix(hsMatrix44 *mat) const; void MakeMatrix(hsMatrix44 *mat) const;
hsScalar Magnitude(); float Magnitude();
hsScalar MagnitudeSquared(); float MagnitudeSquared();
hsQuat Conjugate() const hsQuat Conjugate() const
{ return hsQuat(-fX,-fY,-fZ,fW); } { return hsQuat(-fX,-fY,-fZ,fW); }
hsQuat Inverse(); hsQuat Inverse();
@ -99,13 +99,13 @@ public:
hsQuat operator-(const hsQuat&) const; hsQuat operator-(const hsQuat&) const;
hsQuat operator+(const hsQuat&) const; hsQuat operator+(const hsQuat&) const;
hsQuat operator*(const hsQuat&) const; hsQuat operator*(const hsQuat&) const;
hsQuat operator*(hsScalar f) const hsQuat operator*(float f) const
{ return hsQuat(fX*f,fY*f,fZ*f,fW*f); } { return hsQuat(fX*f,fY*f,fZ*f,fW*f); }
hsQuat operator/(hsScalar f) const hsQuat operator/(float f) const
{ return hsQuat(fX/f,fY/f,fZ/f,fW/f); } { return hsQuat(fX/f,fY/f,fZ/f,fW/f); }
hsQuat operator/(const hsQuat&) const; hsQuat operator/(const hsQuat&) const;
hsScalar Dot(const hsQuat &q2) const float Dot(const hsQuat &q2) const
{ return (fX*q2.fX + fY*q2.fY + fZ*q2.fZ + fW*q2.fW); } { return (fX*q2.fX + fY*q2.fY + fZ*q2.fZ + fW*q2.fW); }
// I/O // I/O

369
Sources/Plasma/CoreLib/hsQueue.h

@ -1,369 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef hsQueue_Defined
#define hsQueue_Defined
#include "hsTypes.h"
template <class T> class hsQueue {
private:
int fArraySize;
T *fArray;
int fHead; // Index of first element in the queue
int fTail; // Index of next free spot in the queue
int fLook; // Index of look pointer
hsBool fFull; // Is queue full?
hsBool fEmpty; // Is queue empty?
void Inc(int *index);
int Inc(int index);
void Dec(int *index);
int Dec(int index);
public:
hsQueue( int size );
~hsQueue();
hsBool Append(const T &newTail); // Add to end of line
hsBool Remove(const T &someElement); // Find and remove element in the line
hsBool Pop(T *headElement); // Remove and return the head of the line
hsBool StartLook(T *headElement); // Return the head of the line w/out removing it
hsBool NextLook(T *nextElement); // Return the head of the line w/out removing it
hsBool IsEmpty(void) { return fEmpty; }
hsBool IsFull(void) { return fFull; }
};
//
// Constructor
// Allocate array, init head/tail indices
//
template <class T> hsQueue<T>::hsQueue( int size )
{
fArraySize = size;
fArray = TRACKED_NEW T[ size ];
fHead = -1;
fTail = -1;
fLook = -1;
fEmpty = true;
fFull = false;
}
//
// Destructor. free array
//
template <class T> hsQueue<T>::~hsQueue()
{
delete [] fArray;
}
//
// Wrap index on increment
//
template <class T> void hsQueue<T>::Inc( int *index )
{
(*index) ++;
if ((*index) == fArraySize) {
*index = 0;
}
}
//
// Wrap index on increment
//
template <class T> int hsQueue<T>::Inc( int index )
{
(index) ++;
if ((index) == fArraySize) {
index = 0;
}
return index;
}
//
// Wrap index on decrement
//
template <class T> void hsQueue<T>::Dec( int *index )
{
(*index) --;
if ((*index) < 0) {
*index = fArraySize-1;
}
}
//
// Wrap index on decrement
//
template <class T> int hsQueue<T>::Dec( int index )
{
(index) --;
if ((index) < 0) {
index = fArraySize-1;
}
return index;
}
//
// Add copy of item to the array.
//
template <class T> hsBool hsQueue<T>::Append(const T &thing)
{
if (fHead == -1 && fTail == -1) {
// init case
fHead = 0;
fTail = 0;
}
if (fFull) {
// Queue is full
return false;
}
if ( (fHead<0 || fHead>=fArraySize) ) {
hsIfDebugMessage( (fHead<0 || fHead>=fArraySize), "Append: Illegal head pointer", fHead);
}
hsIfDebugMessage( (fTail<0 || fTail>=fArraySize), "Append: Illegal tail pointer", fTail);
// Copy
fArray[fTail] = thing;
fEmpty = false;
// increment tail pointer
Inc(&fTail);
if (fTail == fHead) {
fFull = true;
}
return true;
}
//
// Get a copy of the head of the array
//
template <class T> hsBool hsQueue<T>::Pop(T *thing)
{
if (fEmpty) {
return false;
}
hsIfDebugMessage( (fHead<0 || fHead>=fArraySize), "Pop: Illegal head pointer", fHead);
hsIfDebugMessage( (fTail<0 || fTail>=fArraySize), "Pop: Illegal tail pointer", fTail);
// Copy
*thing = fArray[fHead];
fFull = false;
// Increment head pointer
Inc(&fHead);
if (fHead == fTail) {
fEmpty = true;
}
return true;
}
//
// Remove item from list
//
template <class T> hsBool hsQueue<T>::Remove(const T &thing)
{
if (fEmpty) {
return false;
}
hsIfDebugMessage( (fHead<0 || fHead>=fArraySize), "Remove: Illegal head pointer", fHead);
hsIfDebugMessage( (fTail<0 || fTail>=fArraySize), "Remove: Illegal tail pointer", fTail);
// loop through list, find item
int i = fHead;
do {
if (fArray[i] == thing) {
// Found it - now remove it by sliding everything down 1
int j=Inc(i);
while(j!= fTail) {
if (fLook==j)
Dec(&fLook);
fArray[Dec(j)] = fArray[j];
Inc(&j);
}
if (fLook==fTail)
Dec(&fLook);
Dec(&fTail);
if (fTail == fHead) {
fEmpty = true;
}
return true;
}
Inc(&i);
if (i==fTail) {
return false;
}
} while(true);
}
//
// Return pointer to first item in list, without popping it.
// Return false if nothing there.
//
template <class T> hsBool hsQueue<T>::StartLook(T *thing)
{
if (fEmpty) {
return false;
}
hsIfDebugMessage( (fHead<0 || fHead>=fArraySize), "StartLook: Illegal head pointer", fHead);
hsIfDebugMessage( (fTail<0 || fTail>=fArraySize), "StartLook: Illegal tail pointer", fTail);
fLook = fHead;
*thing = fArray[fLook];
// inc look pointer
Inc(&fLook);
// success
return true;
}
//
// Return pointer to next item in list, without popping it. Doesn't change head or tail.
// Should be called immediately after StartLook.
// Return false when at end of list.
//
template <class T> hsBool hsQueue<T>::NextLook(T *thing)
{
if (fEmpty || fLook == fTail) {
return false;
}
hsAssert(fLook != -1, "Must call StartLook first\n");
hsIfDebugMessage( (fHead<0 || fHead>=fArraySize), "NextLook: Illegal head pointer", fHead);
hsIfDebugMessage( (fTail<0 || fTail>=fArraySize), "NextLook: Illegal tail pointer", fTail);
// Return copy of item without removing it
*thing = fArray[fLook];
Inc(&fLook);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Code for threaded message queues - move to another file
//
#ifdef MQUEUE
#include "hsThread.h"
#if HS_BUILD_FOR_UNIX
#include <mqueue.h>
#endif
class hsListQue {
public:
struct Elem {
Elem* fNext;
};
private:
Elem* fHead;
Elem* fTail;
int fCount;
public:
hsListQue();
virtual ~hsListQue();
virtual int Count();
virtual void Enqueue(Elem* newItem);
virtual Elem* Dequeue();
};
class hsMutexQueue : public hsListQue {
hsMutex fMutex;
public:
hsMutexQueue() {}
virtual int Count();
virtual void Enqueue(Elem* newItem);
virtual Elem* Dequeue(); // will return nil if the queue is empty
};
class hsSemaphoreQueue : public hsMutexQueue {
hsSemaphore fSema;
public:
hsSemaphoreQueue() {}
virtual void Enqueue(Elem* newItem);
virtual Elem* Dequeue(); // never returns nil, it just waits
};
class hsMsgQueue {
int fMaxSize;
#if HS_BUILD_FOR_UNIX
mqd_t fMQ;
#else
class hsPrivateMQ* fMQ;
UInt32 fAccess;
#endif
public:
enum {
kRead = 0x0001,
kWrite = 0x0002,
kBlock = 0x0004
};
hsMsgQueue();
virtual ~hsMsgQueue();
hsBool Create(const char name[], int maxSize, UInt32 access);
hsBool Open(const char name[], UInt32 access);
void Close();
int GetMaxSize() const { return fMaxSize; }
hsBool Send(const void* data, int size = 0);
int Receive(void* data); // returns actual size or 0
static void Delete(const char name[]);
};
#endif // MQUEUE
#endif

56
Sources/Plasma/CoreLib/hsSTLStream.cpp

@ -45,7 +45,7 @@ hsVectorStream::hsVectorStream() : fEnd(0)
{ {
} }
hsVectorStream::hsVectorStream(UInt32 chunkSize) hsVectorStream::hsVectorStream(uint32_t chunkSize)
{ {
fVector.reserve(chunkSize); fVector.reserve(chunkSize);
} }
@ -59,7 +59,7 @@ hsBool hsVectorStream::AtEnd()
return (fBytesRead >= fEnd); return (fBytesRead >= fEnd);
} }
UInt32 hsVectorStream::Read(UInt32 byteCount, void *buffer) uint32_t hsVectorStream::Read(uint32_t byteCount, void *buffer)
{ {
if (fBytesRead + byteCount > fEnd) if (fBytesRead + byteCount > fEnd)
{ {
@ -75,18 +75,18 @@ UInt32 hsVectorStream::Read(UInt32 byteCount, void *buffer)
return byteCount; return byteCount;
} }
UInt32 hsVectorStream::Write(UInt32 byteCount, const void* buffer) uint32_t hsVectorStream::Write(uint32_t byteCount, const void* buffer)
{ {
// If we are at the end of the vector, we can just do a block insert of the data // If we are at the end of the vector, we can just do a block insert of the data
if (fPosition == fVector.size()) if (fPosition == fVector.size())
fVector.insert(fVector.end(), (Byte*)buffer, (Byte*)buffer+byteCount); fVector.insert(fVector.end(), (uint8_t*)buffer, (uint8_t*)buffer+byteCount);
// If we are in the middle, I don't know how to just overwrite a block of the vector. // If we are in the middle, I don't know how to just overwrite a block of the vector.
// So, we make sure there is enough space and copy the elements one by one // So, we make sure there is enough space and copy the elements one by one
else else
{ {
fVector.reserve(fPosition+byteCount); fVector.reserve(fPosition+byteCount);
for (UInt32 i = 0; i < byteCount; i++) for (uint32_t i = 0; i < byteCount; i++)
fVector[fPosition+i] = ((Byte*)buffer)[i]; fVector[fPosition+i] = ((uint8_t*)buffer)[i];
} }
fPosition += byteCount; fPosition += byteCount;
@ -97,7 +97,7 @@ UInt32 hsVectorStream::Write(UInt32 byteCount, const void* buffer)
return byteCount; return byteCount;
} }
void hsVectorStream::Skip(UInt32 deltaByteCount) void hsVectorStream::Skip(uint32_t deltaByteCount)
{ {
fBytesRead += deltaByteCount; fBytesRead += deltaByteCount;
fPosition += deltaByteCount; fPosition += deltaByteCount;
@ -120,7 +120,7 @@ void hsVectorStream::Truncate()
fEnd = fPosition-1; fEnd = fPosition-1;
} }
UInt32 hsVectorStream::GetEOF() uint32_t hsVectorStream::GetEOF()
{ {
return fEnd; return fEnd;
} }
@ -130,7 +130,7 @@ void hsVectorStream::CopyToMem(void* mem)
memcpy(mem, &fVector[0], fEnd); memcpy(mem, &fVector[0], fEnd);
} }
void hsVectorStream::Erase(UInt32 bytes) void hsVectorStream::Erase(uint32_t bytes)
{ {
hsAssert(fPosition+bytes <= fEnd, "Erasing past end of stream"); hsAssert(fPosition+bytes <= fEnd, "Erasing past end of stream");
@ -158,7 +158,7 @@ const void *hsVectorStream::GetData()
#ifdef HS_BUILD_FOR_WIN32 #ifdef HS_BUILD_FOR_WIN32
hsNamedPipeStream::hsNamedPipeStream(UInt8 flags, UInt32 timeout) : hsNamedPipeStream::hsNamedPipeStream(uint8_t flags, uint32_t timeout) :
fFlags(flags), fFlags(flags),
fPipe(INVALID_HANDLE_VALUE), fPipe(INVALID_HANDLE_VALUE),
fReadMode(false), fReadMode(false),
@ -203,15 +203,15 @@ hsBool hsNamedPipeStream::WaitForClientConnect()
hsBool hsNamedPipeStream::Open(const char *name, const char *mode) hsBool hsNamedPipeStream::Open(const char *name, const char *mode)
{ {
wchar* wName = hsStringToWString(name); wchar_t* wName = hsStringToWString(name);
wchar* wMode = hsStringToWString(mode); wchar_t* wMode = hsStringToWString(mode);
hsBool ret = Open(wName, wMode); hsBool ret = Open(wName, wMode);
delete [] wName; delete [] wName;
delete [] wMode; delete [] wMode;
return ret; return ret;
} }
hsBool hsNamedPipeStream::Open(const wchar *name, const wchar *mode) hsBool hsNamedPipeStream::Open(const wchar_t *name, const wchar_t *mode)
{ {
if (wcschr(mode, L'w')) if (wcschr(mode, L'w'))
{ {
@ -270,7 +270,7 @@ hsBool hsNamedPipeStream::Close()
return true; return true;
} }
hsBool hsNamedPipeStream::ICheckOverlappedResult(BOOL result, UInt32 &numTransferred) hsBool hsNamedPipeStream::ICheckOverlappedResult(BOOL result, uint32_t &numTransferred)
{ {
// Read/Write succeeded, return now // Read/Write succeeded, return now
if (result) if (result)
@ -294,7 +294,7 @@ hsBool hsNamedPipeStream::ICheckOverlappedResult(BOOL result, UInt32 &numTransfe
return false; return false;
} }
hsBool hsNamedPipeStream::IRead(UInt32 byteCount, void *buffer, UInt32 &numRead) hsBool hsNamedPipeStream::IRead(uint32_t byteCount, void *buffer, uint32_t &numRead)
{ {
numRead = 0; numRead = 0;
@ -312,7 +312,7 @@ hsBool hsNamedPipeStream::IRead(UInt32 byteCount, void *buffer, UInt32 &numRead)
return false; return false;
} }
hsBool hsNamedPipeStream::IWrite(UInt32 byteCount, const void *buffer, UInt32 &numWritten) hsBool hsNamedPipeStream::IWrite(uint32_t byteCount, const void *buffer, uint32_t &numWritten)
{ {
numWritten = 0; numWritten = 0;
@ -330,13 +330,13 @@ hsBool hsNamedPipeStream::IWrite(UInt32 byteCount, const void *buffer, UInt32 &n
return false; return false;
} }
UInt32 hsNamedPipeStream::Read(UInt32 byteCount, void *buffer) uint32_t hsNamedPipeStream::Read(uint32_t byteCount, void *buffer)
{ {
UInt32 totalRead = 0; uint32_t totalRead = 0;
// Read until we get all our data or an error // Read until we get all our data or an error
UInt32 numRead = 0; uint32_t numRead = 0;
while (IRead(byteCount-totalRead, (void*)((UInt32)buffer+totalRead), numRead)) while (IRead(byteCount-totalRead, (void*)((uint32_t)buffer+totalRead), numRead))
{ {
totalRead += numRead; totalRead += numRead;
@ -347,13 +347,13 @@ UInt32 hsNamedPipeStream::Read(UInt32 byteCount, void *buffer)
return totalRead; return totalRead;
} }
UInt32 hsNamedPipeStream::Write(UInt32 byteCount, const void *buffer) uint32_t hsNamedPipeStream::Write(uint32_t byteCount, const void *buffer)
{ {
UInt32 totalWritten = 0; uint32_t totalWritten = 0;
// Write until we get all our data or an error // Write until we get all our data or an error
UInt32 numWritten = 0; uint32_t numWritten = 0;
while (IWrite(byteCount-totalWritten, (const void*)((UInt32)buffer+totalWritten), numWritten)) while (IWrite(byteCount-totalWritten, (const void*)((uint32_t)buffer+totalWritten), numWritten))
{ {
totalWritten += numWritten; totalWritten += numWritten;
@ -368,14 +368,14 @@ UInt32 hsNamedPipeStream::Write(UInt32 byteCount, const void *buffer)
using std::min; using std::min;
#endif #endif
void hsNamedPipeStream::Skip(UInt32 deltaByteCount) void hsNamedPipeStream::Skip(uint32_t deltaByteCount)
{ {
char buf[256]; char buf[256];
// Read until we get all our data or an error // Read until we get all our data or an error
UInt32 totalRead = 0; uint32_t totalRead = 0;
UInt32 numRead = 0; uint32_t numRead = 0;
while (IRead(min((UInt32)256L, deltaByteCount-totalRead), buf, numRead)) while (IRead(min((uint32_t)256L, deltaByteCount-totalRead), buf, numRead))
{ {
totalRead += numRead; totalRead += numRead;

42
Sources/Plasma/CoreLib/hsSTLStream.h

@ -49,43 +49,43 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
class hsVectorStream : public hsStream class hsVectorStream : public hsStream
{ {
protected: protected:
std::vector<Byte> fVector; std::vector<uint8_t> fVector;
UInt32 fEnd; // End of file (one past the last byte) uint32_t fEnd; // End of file (one past the last byte)
public: public:
hsVectorStream(); hsVectorStream();
hsVectorStream(UInt32 chunkSize); hsVectorStream(uint32_t chunkSize);
virtual ~hsVectorStream(); virtual ~hsVectorStream();
virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsVectorStream::Open Not Implemented"); return false; } virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsVectorStream::Open Not Implemented"); return false; }
virtual hsBool Open(const wchar *, const wchar *) { hsAssert(0, "hsVectorStream::Open Not Implemented"); return false; } virtual hsBool Open(const wchar_t *, const wchar_t *) { hsAssert(0, "hsVectorStream::Open Not Implemented"); return false; }
virtual hsBool Close() { hsAssert(0, "hsVectorStream::Close Not Implemented"); return false; } virtual hsBool Close() { hsAssert(0, "hsVectorStream::Close Not Implemented"); return false; }
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void * buffer); virtual uint32_t Read(uint32_t byteCount, void * buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void FastFwd(); virtual void FastFwd();
virtual void Truncate(); virtual void Truncate();
virtual UInt32 GetEOF(); virtual uint32_t GetEOF();
virtual void CopyToMem(void* mem); virtual void CopyToMem(void* mem);
virtual void Reset(); // clears the buffers virtual void Reset(); // clears the buffers
// Erase number of bytes at the current position // Erase number of bytes at the current position
virtual void Erase(UInt32 bytes); virtual void Erase(uint32_t bytes);
// A pointer to the beginning of the data in the stream. This is only valid // A pointer to the beginning of the data in the stream. This is only valid
// until someone modifies the stream. // until someone modifies the stream.
const void *GetData(); const void *GetData();
// In case you want to try and be efficient with your memory allocations // In case you want to try and be efficient with your memory allocations
void Reserve(UInt32 bytes) { fVector.reserve(bytes); } void Reserve(uint32_t bytes) { fVector.reserve(bytes); }
}; };
#ifdef HS_BUILD_FOR_WIN32 #ifdef HS_BUILD_FOR_WIN32
#include "hsWindows.h"
class hsNamedPipeStream : public hsStream class hsNamedPipeStream : public hsStream
{ {
@ -93,17 +93,17 @@ protected:
HANDLE fPipe; HANDLE fPipe;
OVERLAPPED fOverlap; OVERLAPPED fOverlap;
hsBool fReadMode; // True for read, false for write hsBool fReadMode; // True for read, false for write
UInt8 fFlags; uint8_t fFlags;
UInt32 fTimeout; uint32_t fTimeout;
hsBool ICheckOverlappedResult(BOOL result, UInt32 &numTransferred); hsBool ICheckOverlappedResult(BOOL result, uint32_t &numTransferred);
hsBool IRead(UInt32 byteCount, void *buffer, UInt32 &numRead); hsBool IRead(uint32_t byteCount, void *buffer, uint32_t &numRead);
hsBool IWrite(UInt32 byteCount, const void *buffer, UInt32 &numWritten); hsBool IWrite(uint32_t byteCount, const void *buffer, uint32_t &numWritten);
public: public:
enum { kThrowOnError = 1 }; // Throws if a read or write operation fails enum { kThrowOnError = 1 }; // Throws if a read or write operation fails
hsNamedPipeStream(UInt8 flags=0, UInt32 timeout=INFINITE); hsNamedPipeStream(uint8_t flags=0, uint32_t timeout=INFINITE);
virtual ~hsNamedPipeStream(); virtual ~hsNamedPipeStream();
// The server (writer) and client (reader) need to open the same file. // The server (writer) and client (reader) need to open the same file.
@ -111,12 +111,12 @@ public:
// computer name to do it over the network. 'pipeName' is whatever you // computer name to do it over the network. 'pipeName' is whatever you
// want. // want.
virtual hsBool Open(const char *name, const char *mode); virtual hsBool Open(const char *name, const char *mode);
virtual hsBool Open(const wchar *name, const wchar *mode); virtual hsBool Open(const wchar_t *name, const wchar_t *mode);
virtual hsBool Close(); virtual hsBool Close();
virtual UInt32 Read(UInt32 byteCount, void *buffer); virtual uint32_t Read(uint32_t byteCount, void *buffer);
virtual UInt32 Write(UInt32 byteCount, const void *buffer); virtual uint32_t Write(uint32_t byteCount, const void *buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
// - For the server (writer) only - // - For the server (writer) only -

200
Sources/Plasma/CoreLib/hsScalar.h

@ -1,200 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef hsScalarMacrosDefined
#define hsScalarMacrosDefined
#include "hsFixedTypes.h"
#ifndef HS_SCALAR_IS_FLOAT
#define HS_SCALAR_IS_FIXED 0
#define HS_SCALAR_IS_FLOAT 1
#define HS_NEVER_USE_FLOAT 0
#endif
#if HS_SCALAR_IS_FLOAT && HS_NEVER_USE_FLOAT
#error "can't define HS_SCALAR_IS_FLOAT and HS_NEVER_USE_FLOAT"
#endif
#if HS_SCALAR_IS_FLOAT
#include <math.h>
#endif
#define hsScalarDegToRad(deg) hsScalarMul(deg, hsScalarPI / 180)
#define hsScalarRadToDeg(rad) hsScalarMul(rad, 180 / hsScalarPI)
#if HS_SCALAR_IS_FIXED
typedef hsFixed hsScalar;
#define hsScalar1 hsFixed1
#define hsScalarHalf (hsFixed1 >> 1)
#define hsScalarPI (hsFixedPI)
#define hsScalarMax (0x7fffffff)
#if HS_CAN_USE_FLOAT
#define hsFloatToScalar(x) hsFixed((x) * float(hsFixed1))
#define hsScalarToFloat(x) ((x) / float(hsFixed1))
#endif
#define hsIntToScalar(x) hsIntToFixed(x)
#define hsScalarToInt(x) hsFixedToInt(x)
#define hsScalarRound(x) hsFixedRound(x)
#define hsFixedToScalar(x) (x)
#define hsScalarToFixed(x) (x)
#define hsFractToScalar(x) hsFractToFixed(x)
#define hsScalarToFract(x) hsFixedToFract(x)
#define hsScalarMul(a, b) hsFixMul(a, b)
#define hsScalarMul2(a) ((a) << 1)
#define hsScalarDiv(a, b) hsFixDiv(a, b)
#define hsScalarDiv2(a) ((a) >> 1)
#define hsScalarInvert(a) hsFixDiv(hsFixed1, a)
#define hsScalarMod(a,b) ((a) % (b))
#define hsScalarMulDiv(n1, n2, d) hsMulDiv32(n1, n2, d)
#define hsScalarMulAdd(a, b, c) (hsFixMul(a, b) + (c))
#define hsSquareRoot(scalar) hsFixSqrt(scalar)
#define hsSine(angle) hsFixedSin(angle)
#define hsCosine(angle) hsFixedCos(angle)
#define hsTan(angle) (hsSine(angle)/hsCosine(angle))
#define hsASine(value) hsFixedASin(value)
#define hsACosine(value) hsFixedACos(value)
#ifdef __cplusplus
inline hsScalar hsScalarAverage(hsScalar a, hsScalar b) { return a + b >> 1; }
inline hsScalar hsScalarAverage(hsScalar a, hsScalar b, hsScalar t)
{
return a + hsFixMul(t, b - a);
}
#if HS_CAN_USE_FLOAT
inline hsScalar hsPow(hsScalar base, hsScalar exponent)
{
return hsFloatToScalar(powf(hsScalarToFloat(base), hsScalarToFloat(exponent)));
}
inline hsScalar hsATan2(hsScalar y, hsScalar x)
{
return hsFloatToScalar(atan2f(hsScalarToFloat(y), hsScalarToFloat(x)));
}
#endif
inline hsScalar hsCeil(hsScalar x) { return (x + 0xFFFF) & 0xFFFF0000; }
inline hsScalar hsFloor(hsScalar x) { return x & 0xFFFF0000; }
#endif
#endif
#if HS_SCALAR_IS_FLOAT
typedef float hsScalar;
#define hsScalar1 float(1)
#define hsScalarHalf float(0.5)
#define hsScalarPI float(HS_PI)
#define hsScalarMax float(3.402823466e+38F)
#define hsFloatToScalar(x) float(x)
#define hsScalarToFloat(x) float(x)
#define hsIntToScalar(x) float(x)
#define hsScalarToInt(x) Int32(x)
#define hsFixedToScalar(x) ((hsScalar)(x) / float(hsFixed1))
#define hsScalarToFixed(x) hsFixed((x) * float(hsFixed1))
#define hsFractToScalar(x) ((x) / float(hsFract1))
#define hsScalarToFract(x) hsFract((x) * float(hsFract1))
#ifdef __cplusplus
#define hsScalarMod(a,b) fmodf(a, b)
#define hsScalarMulAdd(a, b, c) ((a) * (b) + (c))
#define hsScalarMul(a,b) ((a) * (b))
#define hsScalarMul2(a) ((a) * 2)
#define hsScalarDiv(a,b) ((a) / (b))
#define hsScalarDiv2(a) ((a) * float(0.5))
#define hsScalarInvert(a) (float(1) / (a))
#define hsScalarMulDiv(n1,n2,d) ((n1) * (n2) / (d))
#ifndef HS_DEBUGGING /* mf horse testing defines vs inlines for VC++5.0 performance */
#define hsScalarRound(x) Int32((x) + ((x) < 0 ? -hsScalarHalf : hsScalarHalf))
#else /* HS_DEBUGGING - use inlines for type-checking etc...and all */
inline Int32 hsScalarRound(float x)
{
float half = hsScalarHalf;
if (x < 0)
half = -half;
return Int32(x + half);
}
#endif /* HS_DEBUGGING - use inlines for type-checking etc...and all */
inline float hsScalarAverage(float a, float b) { return (a + b) * float(0.5); }
inline float hsScalarAverage(float a, float b, float t) { return a + t * (b - a); }
inline hsScalar hsSquareRoot(hsScalar scalar) { return sqrtf(scalar); }
inline hsScalar hsSine(hsScalar angle) { return sinf(angle); }
inline hsScalar hsCosine(hsScalar angle) { return cosf(angle); }
inline hsScalar hsTan(hsScalar rads) { return tanf(rads); }
inline hsScalar hsASine(hsScalar value) { return asinf(value); }
inline hsScalar hsACosine(hsScalar value) { return acosf(value); }
inline hsScalar hsPow(hsScalar base, hsScalar exponent) { return powf(base, exponent); }
inline hsScalar hsATan2(hsScalar y, hsScalar x) { return atan2f(y, x); }
inline hsScalar hsCeil(hsScalar x) { return ceilf(x); }
inline hsScalar hsFloor(hsScalar x) { return floorf(x); }
#endif /* HS_SCALAR_IS_FLOAT */
#endif /* __CPLUSPLUS */
//
// Macros for enabling double precision math ops
// require #include <float.h>
//
#if HS_BUILD_FOR_WIN32
#define hsDoublePrecBegin \
unsigned int fpc=_controlfp( 0, 0); \
_controlfp( _PC_64, MCW_PC );
#define hsDoublePrecEnd \
_controlfp( fpc, 0xfffff );
#else
#define hsDoublePrecBegin
#define hsDoublePrecEnd
#endif
#endif

4
Sources/Plasma/CoreLib/hsStlUtils.cpp

@ -262,7 +262,7 @@ bool formatv(std::string & out, const char * fmt, va_list args)
{ {
if (pbuf!=buf) if (pbuf!=buf)
delete [] pbuf; delete [] pbuf;
pbuf = TRACKED_NEW char[kBufSz+kBufSz*attempts]; pbuf = new char[kBufSz+kBufSz*attempts];
} }
} }
while (!success && attempts<kMaxAttempts); while (!success && attempts<kMaxAttempts);
@ -314,7 +314,7 @@ bool formatv(std::wstring & out, const wchar_t * fmt, va_list args)
{ {
if (pbuf!=buf) if (pbuf!=buf)
delete [] pbuf; delete [] pbuf;
pbuf = TRACKED_NEW wchar_t[kBufSz+kBufSz*attempts]; pbuf = new wchar_t[kBufSz+kBufSz*attempts];
} }
} }
while (!success && attempts<kMaxAttempts); while (!success && attempts<kMaxAttempts);

8
Sources/Plasma/CoreLib/hsStlUtils.h

@ -42,8 +42,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsStlUtils_h_inc #ifndef hsStlUtils_h_inc
#define hsStlUtils_h_inc #define hsStlUtils_h_inc
#include "hsUtils.h"
//#include <xmemory> #include "HeadSpin.h"
#include <functional> #include <functional>
#include <algorithm> #include <algorithm>
#include <string> #include <string>
@ -114,12 +114,12 @@ public:
void deallocate(pointer _Ptr, size_type) void deallocate(pointer _Ptr, size_type)
{ // deallocate object at _Ptr, ignore size { // deallocate object at _Ptr, ignore size
FREE(_Ptr); free(_Ptr);
} }
pointer allocate(size_type _Count) pointer allocate(size_type _Count)
{ // allocate array of _Count elements { // allocate array of _Count elements
return (pointer)ALLOC(_Count * sizeof(_Ty)); return (pointer)malloc(_Count * sizeof(_Ty));
} }
pointer allocate(size_type _Count, const void*) pointer allocate(size_type _Count, const void*)

390
Sources/Plasma/CoreLib/hsStream.cpp

File diff suppressed because it is too large Load Diff

318
Sources/Plasma/CoreLib/hsStream.h

@ -44,7 +44,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include <stdarg.h> // Included for GCC 3.2.2+ #include <stdarg.h> // Included for GCC 3.2.2+
#include "hsTypes.h" #include "HeadSpin.h"
#include "hsMemory.h" #include "hsMemory.h"
#include "plString.h" #include "plString.h"
@ -82,8 +82,8 @@ enum VDB_Type {// Virtual Database type
kVDB_Mesh kVDB_Mesh
}; };
protected: protected:
UInt32 fBytesRead; uint32_t fBytesRead;
UInt32 fPosition; uint32_t fPosition;
hsBool IsTokenSeparator(char c); hsBool IsTokenSeparator(char c);
public: public:
@ -91,25 +91,25 @@ public:
virtual ~hsStream(); virtual ~hsStream();
virtual hsBool Open(const char *, const char * = "rb")=0; virtual hsBool Open(const char *, const char * = "rb")=0;
virtual hsBool Open(const wchar *, const wchar * = L"rb")=0; virtual hsBool Open(const wchar_t *, const wchar_t * = L"rb")=0;
virtual hsBool Close()=0; virtual hsBool Close()=0;
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void * buffer) = 0; virtual uint32_t Read(uint32_t byteCount, void * buffer) = 0;
virtual UInt32 Write(UInt32 byteCount, const void* buffer) = 0; virtual uint32_t Write(uint32_t byteCount, const void* buffer) = 0;
virtual void Skip(UInt32 deltaByteCount) = 0; virtual void Skip(uint32_t deltaByteCount) = 0;
virtual void Rewind() = 0; virtual void Rewind() = 0;
virtual void FastFwd(); virtual void FastFwd();
virtual UInt32 GetPosition() const; virtual uint32_t GetPosition() const;
virtual void SetPosition(UInt32 position); virtual void SetPosition(uint32_t position);
virtual void Truncate(); virtual void Truncate();
virtual void Flush() {} virtual void Flush() {}
#ifdef STREAM_LOGGER #ifdef STREAM_LOGGER
// Logging Reads & Skips // Logging Reads & Skips
virtual UInt32 LogRead(UInt32 byteCount, void * buffer, const char* desc) { return Read(byteCount,buffer); } virtual uint32_t LogRead(uint32_t byteCount, void * buffer, const char* desc) { return Read(byteCount,buffer); }
virtual char* LogReadSafeString() { return ReadSafeString(); } virtual char* LogReadSafeString() { return ReadSafeString(); }
virtual char* LogReadSafeStringLong() { return ReadSafeStringLong(); } virtual char* LogReadSafeStringLong() { return ReadSafeStringLong(); }
virtual void LogSkip(UInt32 deltaByteCount, const char* desc) { Skip(deltaByteCount); } virtual void LogSkip(uint32_t deltaByteCount, const char* desc) { Skip(deltaByteCount); }
// Stream Notes for Logging // Stream Notes for Logging
virtual void LogStringString(const char* s) { } virtual void LogStringString(const char* s) { }
@ -120,120 +120,119 @@ public:
void LogVoidFunc() { } void LogVoidFunc() { }
// Optimization for small Reads // Optimization for small Reads
virtual UInt8 ReadByte(); virtual uint8_t ReadByte();
virtual hsBool Read4Bytes(void *buffer); // Reads 4 bytes, return true if success virtual hsBool Read4Bytes(void *buffer); // Reads 4 bytes, return true if success
virtual hsBool Read8Bytes(void *buffer); // Reads 8 bytes, return true if success virtual hsBool Read8Bytes(void *buffer); // Reads 8 bytes, return true if success
virtual hsBool Read12Bytes(void *buffer); // Reads 12 bytes, return true if success virtual hsBool Read12Bytes(void *buffer); // Reads 12 bytes, return true if success
virtual UInt32 GetEOF(); virtual uint32_t GetEOF();
UInt32 GetSizeLeft(); uint32_t GetSizeLeft();
virtual void CopyToMem(void* mem); virtual void CopyToMem(void* mem);
virtual hsBool IsCompressed() { return false; } virtual hsBool IsCompressed() { return false; }
UInt32 WriteString(const char cstring[]); uint32_t WriteString(const char cstring[]);
UInt32 WriteString_TEMP(const plString & string) { return WriteString(string.c_str()); } uint32_t WriteString_TEMP(const plString & string) { return WriteString(string.c_str()); }
UInt32 WriteFmt(const char * fmt, ...); uint32_t WriteFmt(const char * fmt, ...);
UInt32 WriteFmtV(const char * fmt, va_list av); uint32_t WriteFmtV(const char * fmt, va_list av);
UInt32 WriteSafeStringLong(const char *string); // uses 4 bytes for length uint32_t WriteSafeStringLong(const char *string); // uses 4 bytes for length
UInt32 WriteSafeWStringLong(const wchar_t *string); uint32_t WriteSafeWStringLong(const wchar_t *string);
char * ReadSafeStringLong(); char * ReadSafeStringLong();
wchar_t * ReadSafeWStringLong(); wchar_t * ReadSafeWStringLong();
UInt32 WriteSafeString(const char *string); // uses 2 bytes for length uint32_t WriteSafeString(const char *string); // uses 2 bytes for length
UInt32 WriteSafeWString(const wchar_t *string); uint32_t WriteSafeWString(const wchar_t *string);
char * ReadSafeString(); char * ReadSafeString();
wchar_t * ReadSafeWString(); wchar_t * ReadSafeWString();
UInt32 WriteSafeString_TEMP(const plString &string); // uses 2 bytes for length uint32_t WriteSafeString_TEMP(const plString &string); // uses 2 bytes for length
UInt32 WriteSafeWString_TEMP(const plString &string); uint32_t WriteSafeWString_TEMP(const plString &string);
plString ReadSafeString_TEMP(); plString ReadSafeString_TEMP();
plString ReadSafeWString_TEMP(); plString ReadSafeWString_TEMP();
hsBool GetToken(char *s, UInt32 maxLen=UInt32(-1), const char beginComment=kComment, const char endComment=kEolnCode); hsBool GetToken(char *s, uint32_t maxLen=uint32_t(-1), const char beginComment=kComment, const char endComment=kEolnCode);
hsBool ReadLn(char* s, UInt32 maxLen=UInt32(-1), const char beginComment=kComment, const char endComment=kEolnCode); hsBool ReadLn(char* s, uint32_t maxLen=uint32_t(-1), const char beginComment=kComment, const char endComment=kEolnCode);
bool Readbool(); bool Readbool();
hsBool ReadBool(); hsBool ReadBool();
void ReadBool(int count, hsBool values[]); void ReadBool(int count, hsBool values[]);
UInt16 ReadLE16(); uint16_t ReadLE16();
void ReadLE16(int count, UInt16 values[]); void ReadLE16(int count, uint16_t values[]);
UInt32 ReadLE32(); uint32_t ReadLE32();
void ReadLE32(int count, UInt32 values[]); void ReadLE32(int count, uint32_t values[]);
UInt32 ReadBE32(); uint32_t ReadBE32();
void Writebool(bool value); void Writebool(bool value);
void WriteBool(hsBool value); void WriteBool(hsBool value);
void WriteBool(int count, const hsBool values[]); void WriteBool(int count, const hsBool values[]);
void WriteByte(UInt8 value); void WriteByte(uint8_t value);
void WriteLE16(UInt16 value); void WriteLE16(uint16_t value);
void WriteLE16(int count, const UInt16 values[]); void WriteLE16(int count, const uint16_t values[]);
void WriteLE32(UInt32 value); void WriteLE32(uint32_t value);
void WriteLE32(int count, const UInt32 values[]); void WriteLE32(int count, const uint32_t values[]);
void WriteBE32(UInt32 value); void WriteBE32(uint32_t value);
/* Overloaded Begin (8 & 16 & 32 int)*/ /* Overloaded Begin (8 & 16 & 32 int)*/
/* yes, swapping an 8 bit value does nothing, just useful*/ /* yes, swapping an 8 bit value does nothing, just useful*/
void ReadLE(bool* value) { *value = this->ReadByte() ? true : false; } void ReadLE(bool* value) { *value = this->ReadByte() ? true : false; }
void ReadLE(UInt8* value) { *value = this->ReadByte(); } void ReadLE(uint8_t* value) { *value = this->ReadByte(); }
void ReadLE(int count, UInt8 values[]) { this->Read(count, values); } void ReadLE(int count, uint8_t values[]) { this->Read(count, values); }
void ReadLE(UInt16* value) { *value = this->ReadLE16(); } void ReadLE(uint16_t* value) { *value = this->ReadLE16(); }
void ReadLE(int count, UInt16 values[]) { this->ReadLE16(count, values); } void ReadLE(int count, uint16_t values[]) { this->ReadLE16(count, values); }
void ReadLE(UInt32* value) { *value = this->ReadLE32(); } void ReadLE(uint32_t* value) { *value = this->ReadLE32(); }
void ReadLE(int count, UInt32 values[]) { this->ReadLE32(count, values); } void ReadLE(int count, uint32_t values[]) { this->ReadLE32(count, values); }
#ifdef STREAM_LOGGER #ifdef STREAM_LOGGER
// Begin LogReadLEs // Begin LogReadLEs
virtual void LogReadLE(bool* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(bool* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLE(UInt8* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(uint8_t* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, UInt8 values[], const char* desc) { this->ReadLE(count, values); } virtual void LogReadLEArray(int count, uint8_t values[], const char* desc) { this->ReadLE(count, values); }
virtual void LogReadLE(UInt16* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(uint16_t* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, UInt16 values[], const char* desc) { this->ReadLE(count, values); } virtual void LogReadLEArray(int count, uint16_t values[], const char* desc) { this->ReadLE(count, values); }
virtual void LogReadLE(UInt32* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(uint32_t* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, UInt32 values[], const char* desc) { this->ReadLE(count, values); } virtual void LogReadLEArray(int count, uint32_t values[], const char* desc) { this->ReadLE(count, values); }
// End LogReadLEs // End LogReadLEs
#endif #endif
void WriteLE(bool value) { this->Write(1,&value); } void WriteLE(bool value) { this->Write(1,&value); }
void WriteLE(UInt8 value) { this->Write(1,&value); } void WriteLE(uint8_t value) { this->Write(1,&value); }
void WriteLE(int count, const UInt8 values[]) { this->Write(count, values); } void WriteLE(int count, const uint8_t values[]) { this->Write(count, values); }
void WriteLE(UInt16 value) { this->WriteLE16(value); } void WriteLE(uint16_t value) { this->WriteLE16(value); }
void WriteLE(int count, const UInt16 values[]) { this->WriteLE16(count, values); } void WriteLE(int count, const uint16_t values[]) { this->WriteLE16(count, values); }
void WriteLE(UInt32 value) { this->WriteLE32(value); } void WriteLE(uint32_t value) { this->WriteLE32(value); }
void WriteLE(int count, const UInt32 values[]) { this->WriteLE32(count, values); } void WriteLE(int count, const uint32_t values[]) { this->WriteLE32(count, values); }
void ReadLE(Int8* value) { *value = this->ReadByte(); } void ReadLE(int8_t* value) { *value = this->ReadByte(); }
void ReadLE(int count, Int8 values[]) { this->Read(count, values); } void ReadLE(int count, int8_t values[]) { this->Read(count, values); }
void ReadLE(char* value) { *value = (char)this->ReadByte(); } void ReadLE(char* value) { *value = (char)this->ReadByte(); }
void ReadLE(int count, char values[]) { this->Read(count, values); } void ReadLE(int count, char values[]) { this->Read(count, values); }
void ReadLE(Int16* value) { *value = (Int16)this->ReadLE16(); } void ReadLE(int16_t* value) { *value = (int16_t)this->ReadLE16(); }
void ReadLE(int count, Int16 values[]) { this->ReadLE16(count, (UInt16*)values); } void ReadLE(int count, int16_t values[]) { this->ReadLE16(count, (uint16_t*)values); }
void ReadLE(Int32* value) { *value = (Int32)this->ReadLE32(); } void ReadLE(int32_t* value) { *value = (int32_t)this->ReadLE32(); }
void ReadLE(int count, Int32 values[]) { this->ReadLE32(count, (UInt32*)values); } void ReadLE(int count, int32_t values[]) { this->ReadLE32(count, (uint32_t*)values); }
#ifdef STREAM_LOGGER #ifdef STREAM_LOGGER
// Begin LogReadLEs // Begin LogReadLEs
virtual void LogReadLE(Int8* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(int8_t* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, Int8 values[], const char* desc) { this->ReadLE(count, values); } virtual void LogReadLEArray(int count, int8_t values[], const char* desc) { this->ReadLE(count, values); }
virtual void LogReadLE(char* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(char* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, char values[], const char* desc) { this->ReadLE(count, values); } virtual void LogReadLEArray(int count, char values[], const char* desc) { this->ReadLE(count, values); }
virtual void LogReadLE(Int16* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(int16_t* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, Int16 values[], const char* desc) { this->ReadLE(count, (UInt16*)values); } virtual void LogReadLEArray(int count, int16_t values[], const char* desc) { this->ReadLE(count, (uint16_t*)values); }
virtual void LogReadLE(Int32* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(int32_t* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, Int32 values[], const char* desc) { this->ReadLE(count, (UInt32*)values); } virtual void LogReadLEArray(int count, int32_t values[], const char* desc) { this->ReadLE(count, (uint32_t*)values); }
virtual void LogReadLE(int* value, const char* desc) { this->ReadLE(value); } virtual void LogReadLE(int* value, const char* desc) { this->ReadLE(value); }
virtual void LogReadLEArray(int count, int values[], const char* desc) { this->ReadLE(count, (UInt32*)values); } virtual void LogReadLEArray(int count, int values[], const char* desc) { this->ReadLE(count, (uint32_t*)values); }
// End LogReadLEs // End LogReadLEs
#endif #endif
void WriteLE(Int8 value) { this->Write(1,&value); } void WriteLE(int8_t value) { this->Write(1,&value); }
void WriteLE(int count, const Int8 values[]) { this->Write(count, values); } void WriteLE(int count, const int8_t values[]) { this->Write(count, values); }
void WriteLE(char value) { this->Write(1,(UInt8*)&value); } void WriteLE(char value) { this->Write(1,(uint8_t*)&value); }
void WriteLE(int count, const char values[]) { this->Write(count, (UInt8*)values); } void WriteLE(int count, const char values[]) { this->Write(count, (uint8_t*)values); }
void WriteLE(Int16 value) { this->WriteLE16((UInt16)value); } void WriteLE(int16_t value) { this->WriteLE16((uint16_t)value); }
void WriteLE(int count, const Int16 values[]) { this->WriteLE16(count, (UInt16*)values); } void WriteLE(int count, const int16_t values[]) { this->WriteLE16(count, (uint16_t*)values); }
void WriteLE(Int32 value) { this->WriteLE32((UInt32)value); } void WriteLE(int32_t value) { this->WriteLE32((uint32_t)value); }
void WriteLE(int count, const Int32 values[]) { this->WriteLE32(count, (UInt32*)values); } void WriteLE(int count, const int32_t values[]) { this->WriteLE32(count, (uint32_t*)values); }
/* Overloaded End */ /* Overloaded End */
#if HS_CAN_USE_FLOAT
float ReadLEFloat(); float ReadLEFloat();
void ReadLEFloat(int count, float values[]); void ReadLEFloat(int count, float values[]);
double ReadLEDouble(); double ReadLEDouble();
@ -264,33 +263,7 @@ public:
void WriteLE(double value) { WriteLEDouble(value); } void WriteLE(double value) { WriteLEDouble(value); }
void WriteLE(int count, const double values[]) { WriteLEDouble(count, values); } void WriteLE(int count, const double values[]) { WriteLEDouble(count, values); }
/* Overloaded End */ /* Overloaded End */
#endif
#if HS_SCALAR_IS_FIXED
hsFixed ReadLEScalar() { return (hsFixed)this->ReadLE32(); }
void ReadLEScalar(int count, hsFixed values[])
{
this->ReadLE32(count, (UInt32*)values);
}
hsFixed ReadBEScalar() { return (hsFixed)this->ReadBE32(); }
void WriteLEScalar(hsFixed value) { this->WriteLE32(value); }
void WriteLEScalar(int count, const hsFixed values[])
{
this->WriteLE32(count, (UInt32*)values);
}
void WriteBEScalar(hsFixed value) { this->WriteBE32(value); }
/* Overloaded Begin (Scalar) */
void ReadLE(hsFixed* value) { this->ReadLE((UInt32*)value); }
void ReadLE(int count, hsFixed values[]) { this->ReadLE(count, (UInt32*)values); }
void WriteLE(hsFixed value) { this->WriteLE((UInt32)value); }
void WriteLE(int count, const hsFixed values[]) { this->WriteLE(count, (UInt32*)values); }
/* Overloaded End */
#else
float ReadLEScalar() { return (float)this->ReadLEFloat(); } float ReadLEScalar() { return (float)this->ReadLEFloat(); }
void ReadLEScalar(int count, float values[]) void ReadLEScalar(int count, float values[])
{ {
@ -303,17 +276,16 @@ public:
this->WriteLEFloat(count, (float*)values); this->WriteLEFloat(count, (float*)values);
} }
void WriteBEScalar(float value) { this->WriteBEFloat(value); } void WriteBEScalar(float value) { this->WriteBEFloat(value); }
#endif
void WriteLEAtom(UInt32 tag, UInt32 size); void WriteLEAtom(uint32_t tag, uint32_t size);
UInt32 ReadLEAtom(UInt32* size); uint32_t ReadLEAtom(uint32_t* size);
/* Overloaded Begin (Atom)*/ /* Overloaded Begin (Atom)*/
void WriteLE(UInt32* tag, UInt32 size) { WriteLEAtom(*tag, size); } void WriteLE(uint32_t* tag, uint32_t size) { WriteLEAtom(*tag, size); }
void ReadLE(UInt32* tag, UInt32 *size) { *tag = ReadLEAtom(size); } void ReadLE(uint32_t* tag, uint32_t *size) { *tag = ReadLEAtom(size); }
/* Overloaded End */ /* Overloaded End */
virtual void VirtualSetPosition(UInt32 pos, VDB_Type ){ SetPosition(pos); }; virtual void VirtualSetPosition(uint32_t pos, VDB_Type ){ SetPosition(pos); };
virtual hsPackFileSys::FileEntry *GetFileEntry() { return nil; } // Streams from Packfiles can return a FileEntry virtual hsPackFileSys::FileEntry *GetFileEntry() { return nil; } // Streams from Packfiles can return a FileEntry
}; };
@ -322,29 +294,29 @@ class hsStreamable {
public: public:
virtual void Read(hsStream* stream) = 0; virtual void Read(hsStream* stream) = 0;
virtual void Write(hsStream* stream) = 0; virtual void Write(hsStream* stream) = 0;
virtual UInt32 GetStreamSize() = 0; virtual uint32_t GetStreamSize() = 0;
}; };
class hsFileStream: public hsStream class hsFileStream: public hsStream
{ {
UInt32 fRef; uint32_t fRef;
public: public:
hsFileStream(); hsFileStream();
virtual ~hsFileStream(); virtual ~hsFileStream();
virtual hsBool Open(const char *name, const char *mode = "rb"); virtual hsBool Open(const char *name, const char *mode = "rb");
virtual hsBool Open(const wchar *name, const wchar *mode = L"rb"); virtual hsBool Open(const wchar_t *name, const wchar_t *mode = L"rb");
virtual hsBool Close(); virtual hsBool Close();
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void* buffer); virtual uint32_t Read(uint32_t byteCount, void* buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void Truncate(); virtual void Truncate();
virtual UInt32 GetFileRef(); virtual uint32_t GetFileRef();
virtual void SetFileRef(UInt32 refNum); virtual void SetFileRef(uint32_t refNum);
}; };
class hsUNIXStream: public hsStream class hsUNIXStream: public hsStream
@ -356,14 +328,14 @@ public:
hsUNIXStream(): fRef(0), fBuff(nil) {} hsUNIXStream(): fRef(0), fBuff(nil) {}
~hsUNIXStream(); ~hsUNIXStream();
virtual hsBool Open(const char* name, const char* mode = "rb"); virtual hsBool Open(const char* name, const char* mode = "rb");
virtual hsBool Open(const wchar *name, const wchar *mode = L"rb"); virtual hsBool Open(const wchar_t *name, const wchar_t *mode = L"rb");
virtual hsBool Close(); virtual hsBool Close();
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void* buffer); virtual uint32_t Read(uint32_t byteCount, void* buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void SetPosition(UInt32 position); virtual void SetPosition(uint32_t position);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void FastFwd(); virtual void FastFwd();
virtual void Truncate(); virtual void Truncate();
@ -372,7 +344,7 @@ public:
FILE* GetFILE() { return fRef; } FILE* GetFILE() { return fRef; }
void SetFILE(FILE* file) { fRef = file; } void SetFILE(FILE* file) { fRef = file; }
virtual UInt32 GetEOF(); virtual uint32_t GetEOF();
}; };
// Small substream class: give it a base stream, an offset and a length, and it'll // Small substream class: give it a base stream, an offset and a length, and it'll
@ -382,7 +354,7 @@ public:
class plReadOnlySubStream: public hsStream class plReadOnlySubStream: public hsStream
{ {
hsStream *fBase; hsStream *fBase;
UInt32 fOffset, fLength; uint32_t fOffset, fLength;
void IFixPosition( void ); void IFixPosition( void );
@ -391,18 +363,18 @@ public:
~plReadOnlySubStream(); ~plReadOnlySubStream();
virtual hsBool Open(const char *, const char *) { hsAssert(0, "plReadOnlySubStream::Open NotImplemented"); return false; } virtual hsBool Open(const char *, const char *) { hsAssert(0, "plReadOnlySubStream::Open NotImplemented"); return false; }
virtual hsBool Open(const wchar *, const wchar *) { hsAssert(0, "plReadOnlySubStream::Open NotImplemented"); return false; } virtual hsBool Open(const wchar_t *, const wchar_t *) { hsAssert(0, "plReadOnlySubStream::Open NotImplemented"); return false; }
void Open( hsStream *base, UInt32 offset, UInt32 length ); void Open( hsStream *base, uint32_t offset, uint32_t length );
virtual hsBool Close() { fBase = nil; fOffset = 0; fLength = 0; return true; } virtual hsBool Close() { fBase = nil; fOffset = 0; fLength = 0; return true; }
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void* buffer); virtual uint32_t Read(uint32_t byteCount, void* buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void FastFwd(); virtual void FastFwd();
virtual void Truncate(); virtual void Truncate();
virtual UInt32 GetEOF(); virtual uint32_t GetEOF();
}; };
class hsRAMStream : public hsStream { class hsRAMStream : public hsStream {
@ -410,22 +382,22 @@ class hsRAMStream : public hsStream {
hsAppenderIterator fIter; hsAppenderIterator fIter;
public: public:
hsRAMStream(); hsRAMStream();
hsRAMStream(UInt32 chunkSize); hsRAMStream(uint32_t chunkSize);
virtual ~hsRAMStream(); virtual ~hsRAMStream();
virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsRAMStream::Open NotImplemented"); return false; } virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsRAMStream::Open NotImplemented"); return false; }
virtual hsBool Open(const wchar *, const wchar *) { hsAssert(0, "hsRAMStream::Open NotImplemented"); return false; } virtual hsBool Open(const wchar_t *, const wchar_t *) { hsAssert(0, "hsRAMStream::Open NotImplemented"); return false; }
virtual hsBool Close() { hsAssert(0, "hsRAMStream::Close NotImplemented"); return false; } virtual hsBool Close() { hsAssert(0, "hsRAMStream::Close NotImplemented"); return false; }
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void * buffer); virtual uint32_t Read(uint32_t byteCount, void * buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void Truncate(); virtual void Truncate();
virtual UInt32 GetEOF(); virtual uint32_t GetEOF();
virtual void CopyToMem(void* mem); virtual void CopyToMem(void* mem);
void Reset(); // clears the buffers void Reset(); // clears the buffers
@ -435,16 +407,16 @@ class hsNullStream : public hsStream {
public: public:
virtual hsBool Open(const char *, const char *) { return true; } virtual hsBool Open(const char *, const char *) { return true; }
virtual hsBool Open(const wchar *, const wchar *) { return true; } virtual hsBool Open(const wchar_t *, const wchar_t *) { return true; }
virtual hsBool Close() { return true; } virtual hsBool Close() { return true; }
virtual UInt32 Read(UInt32 byteCount, void * buffer); // throw's exception virtual uint32_t Read(uint32_t byteCount, void * buffer); // throw's exception
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void Truncate(); virtual void Truncate();
UInt32 GetBytesWritten() const { return fBytesRead; } uint32_t GetBytesWritten() const { return fBytesRead; }
void Reset( ) { fBytesRead = 0; } void Reset( ) { fBytesRead = 0; }
}; };
@ -460,16 +432,16 @@ public:
virtual void Init(int size, const void* data) { fStart=((char*)data); fData=((char*)data); fStop=((char*)data + size); } virtual void Init(int size, const void* data) { fStart=((char*)data); fData=((char*)data); fStop=((char*)data + size); }
virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsReadOnlyStream::Open NotImplemented"); return false; } virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsReadOnlyStream::Open NotImplemented"); return false; }
virtual hsBool Open(const wchar *, const wchar *) { hsAssert(0, "hsReadOnlyStream::Open NotImplemented"); return false; } virtual hsBool Open(const wchar_t *, const wchar_t *) { hsAssert(0, "hsReadOnlyStream::Open NotImplemented"); return false; }
virtual hsBool Close() { hsAssert(0, "hsReadOnlyStream::Close NotImplemented"); return false; } virtual hsBool Close() { hsAssert(0, "hsReadOnlyStream::Close NotImplemented"); return false; }
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void * buffer); virtual uint32_t Read(uint32_t byteCount, void * buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); // throws exception virtual uint32_t Write(uint32_t byteCount, const void* buffer); // throws exception
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void Truncate(); virtual void Truncate();
virtual UInt32 GetBytesRead() const { return fBytesRead; } virtual uint32_t GetBytesRead() const { return fBytesRead; }
virtual UInt32 GetEOF() { return (UInt32)(fStop-fStart); } virtual uint32_t GetEOF() { return (uint32_t)(fStop-fStart); }
virtual void CopyToMem(void* mem); virtual void CopyToMem(void* mem);
}; };
@ -480,61 +452,61 @@ public:
hsWriteOnlyStream() {} hsWriteOnlyStream() {}
virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsWriteOnlyStream::Open NotImplemented"); return false; } virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsWriteOnlyStream::Open NotImplemented"); return false; }
virtual hsBool Open(const wchar *, const wchar *) { hsAssert(0, "hsWriteOnlyStream::Open NotImplemented"); return false; } virtual hsBool Open(const wchar_t *, const wchar_t *) { hsAssert(0, "hsWriteOnlyStream::Open NotImplemented"); return false; }
virtual hsBool Close() { hsAssert(0, "hsWriteOnlyStream::Close NotImplemented"); return false; } virtual hsBool Close() { hsAssert(0, "hsWriteOnlyStream::Close NotImplemented"); return false; }
virtual UInt32 Read(UInt32 byteCount, void * buffer); // throws exception virtual uint32_t Read(uint32_t byteCount, void * buffer); // throws exception
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual UInt32 GetBytesRead() const { return 0; } virtual uint32_t GetBytesRead() const { return 0; }
virtual UInt32 GetBytesWritten() const { return fBytesRead; } virtual uint32_t GetBytesWritten() const { return fBytesRead; }
}; };
// circular queue stream // circular queue stream
class hsQueueStream : public hsStream { class hsQueueStream : public hsStream {
private: private:
char* fQueue; char* fQueue;
UInt32 fReadCursor; uint32_t fReadCursor;
UInt32 fWriteCursor; uint32_t fWriteCursor;
UInt32 fSize; uint32_t fSize;
public: public:
hsQueueStream(Int32 size); hsQueueStream(int32_t size);
~hsQueueStream(); ~hsQueueStream();
virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsQueueStream::Open NotImplemented"); return false; } virtual hsBool Open(const char *, const char *) { hsAssert(0, "hsQueueStream::Open NotImplemented"); return false; }
virtual hsBool Open(const wchar *, const wchar *) { hsAssert(0, "hsQueueStream::Open NotImplemented"); return false; } virtual hsBool Open(const wchar_t *, const wchar_t *) { hsAssert(0, "hsQueueStream::Open NotImplemented"); return false; }
virtual hsBool Close() { hsAssert(0, "hsQueueStream::Close NotImplemented"); return false; } virtual hsBool Close() { hsAssert(0, "hsQueueStream::Close NotImplemented"); return false; }
virtual UInt32 Read(UInt32 byteCount, void * buffer); virtual uint32_t Read(uint32_t byteCount, void * buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void FastFwd(); virtual void FastFwd();
virtual hsBool AtEnd(); virtual hsBool AtEnd();
UInt32 GetSize() { return fSize; } uint32_t GetSize() { return fSize; }
const char* GetQueue() { return fQueue; } const char* GetQueue() { return fQueue; }
UInt32 GetReadCursor() { return fReadCursor; } uint32_t GetReadCursor() { return fReadCursor; }
UInt32 GetWriteCursor() { return fWriteCursor; } uint32_t GetWriteCursor() { return fWriteCursor; }
}; };
class hsBufferedStream : public hsStream class hsBufferedStream : public hsStream
{ {
FILE* fRef; FILE* fRef;
UInt32 fFileSize; uint32_t fFileSize;
enum { kBufferSize = 2*1024 }; enum { kBufferSize = 2*1024 };
char fBuffer[kBufferSize]; char fBuffer[kBufferSize];
// If the buffer is empty, this is zero. Otherwise it is the size of the // If the buffer is empty, this is zero. Otherwise it is the size of the
// buffer (if we read a full block), or something less than that if we read // buffer (if we read a full block), or something less than that if we read
// a partial block at the end of the file. // a partial block at the end of the file.
UInt32 fBufferLen; uint32_t fBufferLen;
hsBool fWriteBufferUsed; hsBool fWriteBufferUsed;
#ifdef HS_DEBUGGING #ifdef HS_DEBUGGING
// For doing statistics on how efficient we are // For doing statistics on how efficient we are
int fBufferHits, fBufferMisses; int fBufferHits, fBufferMisses;
UInt32 fBufferReadIn, fBufferReadOut, fReadDirect, fLastReadPos; uint32_t fBufferReadIn, fBufferReadOut, fReadDirect, fLastReadPos;
char* fFilename; char* fFilename;
const char* fCloseReason; const char* fCloseReason;
#endif #endif
@ -544,16 +516,16 @@ public:
virtual ~hsBufferedStream(); virtual ~hsBufferedStream();
virtual hsBool Open(const char* name, const char* mode = "rb"); virtual hsBool Open(const char* name, const char* mode = "rb");
virtual hsBool Open(const wchar* name, const wchar* mode = L"rb"); virtual hsBool Open(const wchar_t* name, const wchar_t* mode = L"rb");
virtual hsBool Close(); virtual hsBool Close();
virtual hsBool AtEnd(); virtual hsBool AtEnd();
virtual UInt32 Read(UInt32 byteCount, void* buffer); virtual uint32_t Read(uint32_t byteCount, void* buffer);
virtual UInt32 Write(UInt32 byteCount, const void* buffer); virtual uint32_t Write(uint32_t byteCount, const void* buffer);
virtual void Skip(UInt32 deltaByteCount); virtual void Skip(uint32_t deltaByteCount);
virtual void Rewind(); virtual void Rewind();
virtual void Truncate(); virtual void Truncate();
virtual UInt32 GetEOF(); virtual uint32_t GetEOF();
FILE* GetFileRef(); FILE* GetFileRef();
void SetFileRef(FILE* file); void SetFileRef(FILE* file);

30
Sources/Plasma/CoreLib/hsStringTokenizer.cpp

@ -42,7 +42,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
// hsStringTokenizer.cpp // hsStringTokenizer.cpp
#include "hsStringTokenizer.h" #include "hsStringTokenizer.h"
#include "hsUtils.h"
// String Tokenizer routines // String Tokenizer routines
hsStringTokenizer::hsStringTokenizer(const char *string, const char *seps) : hsStringTokenizer::hsStringTokenizer(const char *string, const char *seps) :
@ -72,7 +72,7 @@ inline hsBool hsStringTokenizer::IsSep(char c)
{ {
if ( fCheckAlphaNum || !isalnum(c) ) if ( fCheckAlphaNum || !isalnum(c) )
{ {
for (Int32 i=0; i<fNumSeps; i++) for (int32_t i=0; i<fNumSeps; i++)
{ {
if (fSeps[i] == c) if (fSeps[i] == c)
return true; return true;
@ -111,7 +111,7 @@ char *hsStringTokenizer::next()
} }
// Slightly more loop-friendly version of next // Slightly more loop-friendly version of next
hsBool hsStringTokenizer::Next( char *token, UInt32 maxTokLen ) hsBool hsStringTokenizer::Next( char *token, uint32_t maxTokLen )
{ {
char *t = next(); char *t = next();
if( t == nil ) if( t == nil )
@ -142,7 +142,7 @@ void hsStringTokenizer::Reset(const char *string, const char *seps)
fSeps = seps ? hsStrcpy(seps) : nil; fSeps = seps ? hsStrcpy(seps) : nil;
fNumSeps = fSeps ? strlen(fSeps) : 0; fNumSeps = fSeps ? strlen(fSeps) : 0;
fCheckAlphaNum = false; fCheckAlphaNum = false;
for (Int32 i=0; i<fNumSeps; i++) for (int32_t i=0; i<fNumSeps; i++)
{ {
if (isalnum(fSeps[i])) if (isalnum(fSeps[i]))
{ {
@ -169,7 +169,7 @@ void hsStringTokenizer::ParseQuotes(hsBool qAsTok)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// String Tokenizer routines // String Tokenizer routines
hsWStringTokenizer::hsWStringTokenizer(const wchar *string, const wchar *seps) : hsWStringTokenizer::hsWStringTokenizer(const wchar_t *string, const wchar_t *seps) :
fQAsTok(true), fQAsTok(true),
fInQuote(false), fInQuote(false),
fString(nil), fString(nil),
@ -190,13 +190,13 @@ hsBool hsWStringTokenizer::HasMoreTokens()
return (*fTok != L'\0'); return (*fTok != L'\0');
} }
inline hsBool hsWStringTokenizer::IsSep(wchar c) inline hsBool hsWStringTokenizer::IsSep(wchar_t c)
{ {
if (!fQAsTok || !fInQuote) if (!fQAsTok || !fInQuote)
{ {
if ( fCheckAlphaNum || !iswalnum(c) ) if ( fCheckAlphaNum || !iswalnum(c) )
{ {
for (Int32 i=0; i<fNumSeps; i++) for (int32_t i=0; i<fNumSeps; i++)
{ {
if (fSeps[i] == c) if (fSeps[i] == c)
return true; return true;
@ -211,12 +211,12 @@ inline hsBool hsWStringTokenizer::IsSep(wchar c)
return false; return false;
} }
wchar *hsWStringTokenizer::next() wchar_t *hsWStringTokenizer::next()
{ {
if (*fTok == L'\0') if (*fTok == L'\0')
return nil; return nil;
wchar *cur = fTok; wchar_t *cur = fTok;
while (*fTok != L'\0' && !IsSep(*fTok)) while (*fTok != L'\0' && !IsSep(*fTok))
fTok++; fTok++;
@ -235,9 +235,9 @@ wchar *hsWStringTokenizer::next()
} }
// Slightly more loop-friendly version of next // Slightly more loop-friendly version of next
hsBool hsWStringTokenizer::Next( wchar *token, UInt32 maxTokLen ) hsBool hsWStringTokenizer::Next( wchar_t *token, uint32_t maxTokLen )
{ {
wchar *t = next(); wchar_t *t = next();
if( t == nil ) if( t == nil )
return false; return false;
@ -256,14 +256,14 @@ void hsWStringTokenizer::RestoreLastTerminator( void )
} }
} }
void hsWStringTokenizer::Reset(const wchar *string, const wchar *seps) void hsWStringTokenizer::Reset(const wchar_t *string, const wchar_t *seps)
{ {
if (fString) if (fString)
delete[] fString; delete[] fString;
if (string) if (string)
{ {
int count = wcslen(string); int count = wcslen(string);
fString = new wchar[count + 1]; fString = new wchar_t[count + 1];
wcscpy(fString, string); wcscpy(fString, string);
fString[count] = L'\0'; fString[count] = L'\0';
} }
@ -275,7 +275,7 @@ void hsWStringTokenizer::Reset(const wchar *string, const wchar *seps)
if (seps) if (seps)
{ {
int count = wcslen(seps); int count = wcslen(seps);
fSeps = new wchar[count + 1]; fSeps = new wchar_t[count + 1];
wcscpy(fSeps, seps); wcscpy(fSeps, seps);
fSeps[count] = L'\0'; fSeps[count] = L'\0';
} }
@ -284,7 +284,7 @@ void hsWStringTokenizer::Reset(const wchar *string, const wchar *seps)
fNumSeps = fSeps ? wcslen(fSeps) : 0; fNumSeps = fSeps ? wcslen(fSeps) : 0;
fCheckAlphaNum = false; fCheckAlphaNum = false;
for (Int32 i=0; i<fNumSeps; i++) for (int32_t i=0; i<fNumSeps; i++)
{ {
if (iswalnum(fSeps[i])) if (iswalnum(fSeps[i]))
{ {

30
Sources/Plasma/CoreLib/hsStringTokenizer.h

@ -43,7 +43,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef _hsStringTokenizer_Included_ #ifndef _hsStringTokenizer_Included_
#define _hsStringTokenizer_Included_ #define _hsStringTokenizer_Included_
#include "hsTypes.h" #include "HeadSpin.h"
#ifndef HS_BUILD_FOR_WIN32 #ifndef HS_BUILD_FOR_WIN32
#include <wchar.h> #include <wchar.h>
@ -58,7 +58,7 @@ private:
char *fLastTerminator; char *fLastTerminator;
char fLastRep; char fLastRep;
Int32 fNumSeps; int32_t fNumSeps;
hsBool fQAsTok; hsBool fQAsTok;
hsBool fInQuote; hsBool fInQuote;
hsBool fCheckAlphaNum; hsBool fCheckAlphaNum;
@ -66,7 +66,7 @@ public:
hsStringTokenizer(const char *string=nil, const char *seps=nil); hsStringTokenizer(const char *string=nil, const char *seps=nil);
~hsStringTokenizer(); ~hsStringTokenizer();
char *next(); char *next();
hsBool Next( char *token, UInt32 maxTokLen ); hsBool Next( char *token, uint32_t maxTokLen );
hsBool HasMoreTokens(); hsBool HasMoreTokens();
void Reset(const char *string, const char *seps); void Reset(const char *string, const char *seps);
void ParseQuotes(hsBool qAsTok); void ParseQuotes(hsBool qAsTok);
@ -84,32 +84,32 @@ private:
class hsWStringTokenizer class hsWStringTokenizer
{ {
private: private:
wchar *fSeps; wchar_t *fSeps;
wchar *fTok; wchar_t *fTok;
wchar *fLastTerminator; wchar_t *fLastTerminator;
wchar fLastRep; wchar_t fLastRep;
Int32 fNumSeps; int32_t fNumSeps;
hsBool fQAsTok; hsBool fQAsTok;
hsBool fInQuote; hsBool fInQuote;
hsBool fCheckAlphaNum; hsBool fCheckAlphaNum;
public: public:
hsWStringTokenizer(const wchar *string=nil, const wchar *seps=nil); hsWStringTokenizer(const wchar_t *string=nil, const wchar_t *seps=nil);
~hsWStringTokenizer(); ~hsWStringTokenizer();
wchar *next(); wchar_t *next();
hsBool Next( wchar *token, UInt32 maxTokLen ); hsBool Next( wchar_t *token, uint32_t maxTokLen );
hsBool HasMoreTokens(); hsBool HasMoreTokens();
void Reset(const wchar *string, const wchar *seps); void Reset(const wchar_t *string, const wchar_t *seps);
void ParseQuotes(hsBool qAsTok); void ParseQuotes(hsBool qAsTok);
wchar *GetRestOfString( void ) const { return fTok; } wchar_t *GetRestOfString( void ) const { return fTok; }
wchar *fString; wchar_t *fString;
void RestoreLastTerminator( void ); void RestoreLastTerminator( void );
private: private:
hsBool IsSep(wchar c); hsBool IsSep(wchar_t c);
}; };
#endif // _hsStringTokenizer_Included_ #endif // _hsStringTokenizer_Included_

174
Sources/Plasma/CoreLib/hsTempPointer.h

@ -1,174 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef hsTempPointer_inc
#define hsTempPointer_inc
#include "hsMemory.h"
#include "hsExceptions.h"
template <class T> class hsTempPointer {
private:
T** fArray;
UInt32 fCurrBlock;
UInt32 fNumBlockAlloc;
UInt32 fCurrElem;
UInt32 fNumElemAlloc;
UInt32 fGrowBy; // def = 0, to double
UInt32 fMinSize; // def = 1
hsTempPointer<T>& operator=(const hsTempPointer<T>&);
void IConsolidate();
void IGrow();
public:
hsTempPointer(UInt32 minSize = 1, UInt32 growBy = 0);
~hsTempPointer();
void Reset();
T* Next();
T* Array(int n);
};
template <class T>
hsTempPointer<T>::~hsTempPointer()
{
int i;
for( i = 0; i <= fCurrBlock; i++ )
delete [] fArray[i];
delete [] fArray;
}
template <class T>
hsTempPointer<T>::hsTempPointer(UInt32 minSize, UInt32 growBy)
{
fGrowBy = growBy;
fMinSize = minSize;
fArray = TRACKED_NEW T*[2];
fNumBlockAlloc = 2;
fCurrBlock = 0;
fArray[fCurrBlock] = TRACKED_NEW T[fMinSize];
fNumElemAlloc = minSize;
fCurrElem = 0;
}
template <class T>
void hsTempPointer<T>::IConsolidate()
{
hsAssert(fCurrBlock > 0, "Shouldn't consolidate when nothing to do");
UInt32 numUsed = fCurrBlock * fNumElemAlloc + fCurrElem;
UInt32 newSize = fNumElemAlloc;
if( !fGrowBy )
{
while( newSize <= numUsed )
newSize <<= 1;
}
else
{
while( newSize <= numUsed )
newSize += fGrowBy;
}
int i;
for( i = 0; i <= fCurrBlock; i++ )
delete [] fArray[i];
fArray[0] = TRACKED_NEW T[newSize];
fNumElemAlloc = newSize;
fCurrElem = 0;
fCurrBlock = 0;
}
template <class T>
void hsTempPointer<T>::IGrow()
{
if( ++fCurrBlock >= fNumBlockAlloc )
{
T** newBlockArray = TRACKED_NEW T*[fNumBlockAlloc <<= 1];
HSMemory::BlockMove(fArray, newBlockArray, fCurrBlock * sizeof(*fArray));
delete [] fArray;
fArray = newBlockArray;
}
fArray[fCurrBlock] = TRACKED_NEW T[fNumElemAlloc];
fCurrElem = 0;
}
template <class T>
T* hsTempPointer<T>::Next()
{
if( fCurrElem >= fNumElemAlloc )
IGrow();
return fArray[fCurrBlock] + fCurrElem++;
}
template <class T>
T* hsTempPointer<T>::Array(int n)
{
// minSize (on constructor) should be greater than max n
hsDebugCode(hsThrowIfBadParam((UInt32)n > (UInt32)fNumElemAlloc);)
if( fCurrElem + n >= fNumElemAlloc )
IGrow();
int idx = fCurrElem;
fCurrElem += n;
return fArray[fCurrBlock] + idx;
}
template <class T>
void hsTempPointer<T>::Reset()
{
if( fCurrBlock > 0 )
IConsolidate();
fCurrElem = 0;
}
#endif // hsTempPointer_inc

14
Sources/Plasma/CoreLib/hsTemplates.cpp

@ -40,7 +40,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "hsTemplates.h" #include "hsTemplates.h"
#include "hsUtils.h"
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@ -83,8 +83,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
hsDlistNode *hsDlistNode::fpFirst=0; hsDlistNode *hsDlistNode::fpFirst=0;
hsDlistNode *hsDlistNode::fpLast=0; hsDlistNode *hsDlistNode::fpLast=0;
UInt32 hsDlistNode::fcreated=0; uint32_t hsDlistNode::fcreated=0;
UInt32 hsDlistNode::fdestroyed=0; uint32_t hsDlistNode::fdestroyed=0;
static int NodeKnt = 0; static int NodeKnt = 0;
void RemoveNode(void *pthing) void RemoveNode(void *pthing)
@ -261,7 +261,7 @@ int hsTArrayBase::GetSizeOf(void) { return 0; }
hsTArrayBase::hsTArrayBase():fUseCount(0), fTotalCount(0) hsTArrayBase::hsTArrayBase():fUseCount(0), fTotalCount(0)
{ {
self = TRACKED_NEW hsDlistNode(this); self = new hsDlistNode(this);
} }
hsTArrayBase::~hsTArrayBase() hsTArrayBase::~hsTArrayBase()
@ -280,7 +280,7 @@ int hsLargeArrayBase::GetSizeOf(void) { return 0; }
hsLargeArrayBase::hsLargeArrayBase():fUseCount(0), fTotalCount(0) hsLargeArrayBase::hsLargeArrayBase():fUseCount(0), fTotalCount(0)
{ {
self = TRACKED_NEW hsDlistNode(this); self = new hsDlistNode(this);
} }
hsLargeArrayBase::~hsLargeArrayBase() hsLargeArrayBase::~hsLargeArrayBase()
@ -302,7 +302,7 @@ void LargeArrayStats() {}
void hsTArrayBase::GrowArraySize(UInt16 newCount) void hsTArrayBase::GrowArraySize(uint16_t newCount)
{ {
#if 1 #if 1
if (newCount < 8) if (newCount < 8)
@ -321,7 +321,7 @@ void hsTArrayBase::GrowArraySize(UInt16 newCount)
#endif #endif
} }
void hsLargeArrayBase::GrowArraySize(UInt32 newCount) void hsLargeArrayBase::GrowArraySize(uint32_t newCount)
{ {
#if 1 #if 1
if (newCount < 8) if (newCount < 8)

150
Sources/Plasma/CoreLib/hsTemplates.h

@ -45,7 +45,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#include "hsExceptions.h" #include "hsExceptions.h"
#include "hsMemory.h" #include "hsMemory.h"
#include "hsRefCnt.h" #include "hsRefCnt.h"
#include "hsUtils.h"
#include <stdarg.h> #include <stdarg.h>
@ -62,8 +62,8 @@ class hsDlistNode
public: public:
static hsDlistNode *fpFirst; static hsDlistNode *fpFirst;
static hsDlistNode *fpLast; static hsDlistNode *fpLast;
static UInt32 fcreated; static uint32_t fcreated;
static UInt32 fdestroyed; static uint32_t fdestroyed;
void *fpThing; void *fpThing;
hsDlistNode *fpPrev; hsDlistNode *fpPrev;
@ -127,13 +127,13 @@ public:
// Use this for an array of objects of class T allocated with new[] // Use this for an array of objects of class T allocated with new[]
template <class T> class hsTempArray { template <class T> class hsTempArray {
T* fArray; T* fArray;
UInt32 fCount; uint32_t fCount;
hsTempArray<T>& operator=(const hsTempArray<T>&); hsTempArray<T>& operator=(const hsTempArray<T>&);
public: public:
hsTempArray(long count) : fArray(TRACKED_NEW T[count]), fCount(count) hsTempArray(long count) : fArray(new T[count]), fCount(count)
{ {
} }
hsTempArray(long count, T initValue) : fArray(TRACKED_NEW T[count]), fCount(count) hsTempArray(long count, T initValue) : fArray(new T[count]), fCount(count)
{ {
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
fArray[i] = initValue; fArray[i] = initValue;
@ -151,12 +151,12 @@ public:
operator T*() const { return fArray; } operator T*() const { return fArray; }
T* GetArray() const { return fArray; } T* GetArray() const { return fArray; }
void Accomodate(UInt32 count) void Accomodate(uint32_t count)
{ {
if (count > fCount) if (count > fCount)
{ delete[] fArray; { delete[] fArray;
fCount = count; fCount = count;
fArray = TRACKED_NEW T[count]; fArray = new T[count];
} }
} }
}; };
@ -224,29 +224,29 @@ public:
template <class T> class hsDynamicArray { template <class T> class hsDynamicArray {
private: private:
Int32 fCount; int32_t fCount;
T* fArray; T* fArray;
hsDynamicArray<T>& operator=(const hsDynamicArray<T>&); // don't allow assignment hsDynamicArray<T>& operator=(const hsDynamicArray<T>&); // don't allow assignment
public: public:
enum { kMissingIndex = -1 }; enum { kMissingIndex = -1 };
hsDynamicArray(Int32 count = 0); hsDynamicArray(int32_t count = 0);
virtual ~hsDynamicArray(); virtual ~hsDynamicArray();
Int32 GetCount() const { return fCount; } int32_t GetCount() const { return fCount; }
hsBool IsEmpty() const { return fCount == 0; } hsBool IsEmpty() const { return fCount == 0; }
const T& Get(Int32 index) const; const T& Get(int32_t index) const;
Int32 Get(Int32 index, Int32 count, T data[]) const; int32_t Get(int32_t index, int32_t count, T data[]) const;
Int32 Find(const T&) const; // returns kMissingIndex if not found int32_t Find(const T&) const; // returns kMissingIndex if not found
void SetCount(Int32 count); void SetCount(int32_t count);
T& operator[]( Int32 index ); T& operator[]( int32_t index );
Int32 Append(const T&); int32_t Append(const T&);
Int32 InsertAtIndex(UInt32 index, const T& obj); int32_t InsertAtIndex(uint32_t index, const T& obj);
Int32 Push(const T&); int32_t Push(const T&);
Int32 Pop(T*); int32_t Pop(T*);
void Remove(Int32); void Remove(int32_t);
void Reset(); // clears out everything void Reset(); // clears out everything
T* AcquireArray() { return fArray; } T* AcquireArray() { return fArray; }
@ -254,9 +254,9 @@ public:
void ReleaseArray(T*) {} void ReleaseArray(T*) {}
hsDynamicArray<T>* Copy(hsDynamicArray<T>* dst = nil) const; hsDynamicArray<T>* Copy(hsDynamicArray<T>* dst = nil) const;
T* ForEach(Boolean (*proc)(T&)); T* ForEach(bool (*proc)(T&));
T* ForEach(Boolean (*proc)(T&, void* p1), void* p1); T* ForEach(bool (*proc)(T&, void* p1), void* p1);
T* ForEach(Boolean (*proc)(T&, void* p1, void* p2), void* p1, void* p2); T* ForEach(bool (*proc)(T&, void* p1, void* p2), void* p1, void* p2);
}; };
// Use this for block of memory allocated with HSMemory::New() // Use this for block of memory allocated with HSMemory::New()
@ -274,12 +274,12 @@ public:
template <class T> template <class T>
hsDynamicArray<T>::hsDynamicArray(Int32 count) hsDynamicArray<T>::hsDynamicArray(int32_t count)
{ {
fCount = count; fCount = count;
fArray = nil; fArray = nil;
if (count) if (count)
fArray = TRACKED_NEW T[ count ]; fArray = new T[ count ];
} }
template <class T> template <class T>
@ -289,13 +289,13 @@ hsDynamicArray<T>::~hsDynamicArray()
} }
template <class T> template <class T>
void hsDynamicArray<T>::SetCount(Int32 count) void hsDynamicArray<T>::SetCount(int32_t count)
{ {
if (fCount != count) if (fCount != count)
{ if (count == 0) { if (count == 0)
this->Reset(); this->Reset();
else else
{ T* newArray = TRACKED_NEW T[count]; { T* newArray = new T[count];
if (fArray) if (fArray)
{ int copyCount = hsMinimum(count, fCount); { int copyCount = hsMinimum(count, fCount);
@ -310,26 +310,26 @@ void hsDynamicArray<T>::SetCount(Int32 count)
} }
} }
template <class T> T& hsDynamicArray<T>::operator[]( Int32 index ) template <class T> T& hsDynamicArray<T>::operator[]( int32_t index )
{ {
hsDebugCode(hsThrowIfBadParam((UInt32)index >= (UInt32)fCount);) hsDebugCode(hsThrowIfBadParam((uint32_t)index >= (uint32_t)fCount);)
return fArray[index]; return fArray[index];
} }
template <class T> const T& hsDynamicArray<T>::Get( Int32 index ) const template <class T> const T& hsDynamicArray<T>::Get( int32_t index ) const
{ {
hsDebugCode(hsThrowIfBadParam((UInt32)index >= (UInt32)fCount);) hsDebugCode(hsThrowIfBadParam((uint32_t)index >= (uint32_t)fCount);)
return fArray[index]; return fArray[index];
} }
template <class T> template <class T>
Int32 hsDynamicArray<T>::Get(Int32 index, Int32 count, T data[]) const int32_t hsDynamicArray<T>::Get(int32_t index, int32_t count, T data[]) const
{ {
if (count > 0) if (count > 0)
{ hsThrowIfNilParam(data); { hsThrowIfNilParam(data);
hsThrowIfBadParam((UInt32)index >= fCount); hsThrowIfBadParam((uint32_t)index >= fCount);
if (index + count > fCount) if (index + count > fCount)
count = fCount - index; count = fCount - index;
@ -340,7 +340,7 @@ Int32 hsDynamicArray<T>::Get(Int32 index, Int32 count, T data[]) const
} }
template <class T> template <class T>
Int32 hsDynamicArray<T>::Find(const T& obj) const int32_t hsDynamicArray<T>::Find(const T& obj) const
{ {
for (int i = 0; i < fCount; i++) for (int i = 0; i < fCount; i++)
if (fArray[i] == obj) if (fArray[i] == obj)
@ -349,16 +349,16 @@ Int32 hsDynamicArray<T>::Find(const T& obj) const
} }
template <class T> template <class T>
void hsDynamicArray<T>::Remove(Int32 index) void hsDynamicArray<T>::Remove(int32_t index)
{ {
hsThrowIfBadParam((UInt32)index >= (UInt32)fCount); hsThrowIfBadParam((uint32_t)index >= (uint32_t)fCount);
T rVal = fArray[index]; T rVal = fArray[index];
if (--fCount > 0) if (--fCount > 0)
{ {
int i; int i;
T* newList = TRACKED_NEW T[fCount]; T* newList = new T[fCount];
for(i = 0 ; i < index;i++) for(i = 0 ; i < index;i++)
newList[i] = fArray[i]; newList[i] = fArray[i];
for (i = index; i < fCount; i++) for (i = index; i < fCount; i++)
@ -373,7 +373,7 @@ void hsDynamicArray<T>::Remove(Int32 index)
} }
template <class T> template <class T>
Int32 hsDynamicArray<T>::Pop(T *obj) int32_t hsDynamicArray<T>::Pop(T *obj)
{ {
hsThrowIfBadParam(this->IsEmpty()); hsThrowIfBadParam(this->IsEmpty());
@ -384,11 +384,11 @@ Int32 hsDynamicArray<T>::Pop(T *obj)
template <class T> template <class T>
Int32 hsDynamicArray<T>::Push(const T& obj) int32_t hsDynamicArray<T>::Push(const T& obj)
{ {
if (fArray) if (fArray)
{ {
T* newList = TRACKED_NEW T[fCount+1]; T* newList = new T[fCount+1];
for(int i = 0 ; i < fCount; i++) for(int i = 0 ; i < fCount; i++)
newList[i+1] = fArray[i]; newList[i+1] = fArray[i];
newList[0] = obj; newList[0] = obj;
@ -397,17 +397,17 @@ Int32 hsDynamicArray<T>::Push(const T& obj)
} }
else else
{ hsAssert(fCount == 0, "mismatch"); { hsAssert(fCount == 0, "mismatch");
fArray = TRACKED_NEW T[1]; fArray = new T[1];
fArray[0] = obj; fArray[0] = obj;
} }
return ++fCount; return ++fCount;
} }
template <class T> template <class T>
Int32 hsDynamicArray<T>::Append(const T& obj) int32_t hsDynamicArray<T>::Append(const T& obj)
{ {
if (fArray) if (fArray)
{ T* newList = TRACKED_NEW T[fCount + 1]; { T* newList = new T[fCount + 1];
for (int i = 0; i < fCount; i++) for (int i = 0; i < fCount; i++)
newList[i] = fArray[i]; newList[i] = fArray[i];
@ -417,7 +417,7 @@ Int32 hsDynamicArray<T>::Append(const T& obj)
} }
else else
{ hsAssert(fCount == 0, "mismatch"); { hsAssert(fCount == 0, "mismatch");
fArray = TRACKED_NEW T[1]; fArray = new T[1];
fArray[0] = obj; fArray[0] = obj;
} }
return ++fCount; return ++fCount;
@ -425,17 +425,17 @@ Int32 hsDynamicArray<T>::Append(const T& obj)
template <class T> template <class T>
Int32 hsDynamicArray<T>::InsertAtIndex(UInt32 index, const T& obj) int32_t hsDynamicArray<T>::InsertAtIndex(uint32_t index, const T& obj)
{ {
if (fArray) if (fArray)
{ {
hsAssert(UInt32(fCount) >= index, "Index too large for array"); hsAssert(uint32_t(fCount) >= index, "Index too large for array");
T* newList = TRACKED_NEW T[fCount + 1]; T* newList = new T[fCount + 1];
unsigned i; unsigned i;
for ( i = 0; i < index; i++) for ( i = 0; i < index; i++)
newList[i] = fArray[i]; newList[i] = fArray[i];
newList[index] = obj; newList[index] = obj;
for ( i = index; i < UInt32(fCount); i++) for ( i = index; i < uint32_t(fCount); i++)
newList[i+1] = fArray[i]; newList[i+1] = fArray[i];
delete [] fArray; delete [] fArray;
@ -445,7 +445,7 @@ Int32 hsDynamicArray<T>::InsertAtIndex(UInt32 index, const T& obj)
{ {
hsAssert(fCount == 0, "mismatch"); hsAssert(fCount == 0, "mismatch");
hsAssert(index ==0,"Can't insert at non zero index in empty array"); hsAssert(index ==0,"Can't insert at non zero index in empty array");
fArray = TRACKED_NEW T[1]; fArray = new T[1];
fArray[0] = obj; fArray[0] = obj;
} }
return ++fCount; return ++fCount;
@ -464,7 +464,7 @@ template <class T>
hsDynamicArray<T>* hsDynamicArray<T>::Copy(hsDynamicArray<T>* dst) const hsDynamicArray<T>* hsDynamicArray<T>::Copy(hsDynamicArray<T>* dst) const
{ {
if (dst == nil) if (dst == nil)
dst = TRACKED_NEW hsDynamicArray<T>; dst = new hsDynamicArray<T>;
else else
dst->Reset(); dst->Reset();
@ -475,7 +475,7 @@ hsDynamicArray<T>* hsDynamicArray<T>::Copy(hsDynamicArray<T>* dst) const
return dst; return dst;
} }
template <class T> T* hsDynamicArray<T>::ForEach(Boolean (*proc)(T&)) template <class T> T* hsDynamicArray<T>::ForEach(bool (*proc)(T&))
{ {
for (int i = 0; i < fCount; i++) for (int i = 0; i < fCount; i++)
if (proc(fArray[i])) if (proc(fArray[i]))
@ -483,7 +483,7 @@ template <class T> T* hsDynamicArray<T>::ForEach(Boolean (*proc)(T&))
return nil; return nil;
} }
template <class T> T* hsDynamicArray<T>::ForEach(Boolean (*proc)(T&, void* p1), void * p1) template <class T> T* hsDynamicArray<T>::ForEach(bool (*proc)(T&, void* p1), void * p1)
{ {
for (int i = 0; i < fCount; i++) for (int i = 0; i < fCount; i++)
if (proc(fArray[i], p1)) if (proc(fArray[i], p1))
@ -491,7 +491,7 @@ template <class T> T* hsDynamicArray<T>::ForEach(Boolean (*proc)(T&, void* p1),
return nil; return nil;
} }
template <class T> T* hsDynamicArray<T>::ForEach(Boolean (*proc)(T&, void* p1, void* p2), void *p1, void *p2) template <class T> T* hsDynamicArray<T>::ForEach(bool (*proc)(T&, void* p1, void* p2), void *p1, void *p2)
{ {
for (int i = 0; i < fCount; i++) for (int i = 0; i < fCount; i++)
if (proc(fArray[i], p1, p2)) if (proc(fArray[i], p1, p2))
@ -504,10 +504,10 @@ template <class T> T* hsDynamicArray<T>::ForEach(Boolean (*proc)(T&, void* p1, v
class hsTArrayBase class hsTArrayBase
{ {
protected: protected:
UInt16 fUseCount; uint16_t fUseCount;
UInt16 fTotalCount; uint16_t fTotalCount;
void GrowArraySize(UInt16 nSize); void GrowArraySize(uint16_t nSize);
#ifdef HS_DEBUGTARRAY #ifdef HS_DEBUGTARRAY
hsTArrayBase(); hsTArrayBase();
@ -521,7 +521,7 @@ protected:
#endif #endif
public: public:
UInt16 GetNumAlloc() const { return fTotalCount; } uint16_t GetNumAlloc() const { return fTotalCount; }
}; };
template <class T> void hsTArray_CopyForward(const T src[], T dst[], int count); template <class T> void hsTArray_CopyForward(const T src[], T dst[], int count);
@ -659,7 +659,7 @@ template <class T> hsTArray<T>::hsTArray(int count) : fArray(nil)
hsTArray_ValidateCount(count); hsTArray_ValidateCount(count);
fUseCount = fTotalCount = count; fUseCount = fTotalCount = count;
if (count > 0) if (count > 0)
fArray = TRACKED_NEW T[count]; fArray = new T[count];
} }
template <class T> hsTArray<T>::hsTArray(const hsTArray<T>& src) : fArray(nil) template <class T> hsTArray<T>::hsTArray(const hsTArray<T>& src) : fArray(nil)
@ -669,7 +669,7 @@ template <class T> hsTArray<T>::hsTArray(const hsTArray<T>& src) : fArray(nil)
if (count > 0) if (count > 0)
{ {
fArray = TRACKED_NEW T[count]; fArray = new T[count];
hsTArray_CopyForward(src.fArray, fArray, count); hsTArray_CopyForward(src.fArray, fArray, count);
} }
} }
@ -708,7 +708,7 @@ bool hsTArray<T>::operator==(const hsTArray<T>& src) const
template <class T> void hsTArray<T>::Swap( hsTArray<T>& src ) template <class T> void hsTArray<T>::Swap( hsTArray<T>& src )
{ {
UInt16 use, tot; uint16_t use, tot;
T *array; T *array;
@ -759,7 +759,7 @@ template <class T> void hsTArray<T>::SetCount(int count)
{ {
if (fArray) if (fArray)
delete[] fArray; delete[] fArray;
fArray = TRACKED_NEW T[count]; fArray = new T[count];
fUseCount = fTotalCount = count; fUseCount = fTotalCount = count;
} }
fUseCount = count; fUseCount = count;
@ -770,7 +770,7 @@ template <class T> void hsTArray<T>::Expand(int NewCount) // New Count is Absolu
hsTArray_ValidateCount(NewCount); hsTArray_ValidateCount(NewCount);
if (NewCount > fTotalCount) // This is Expand not Shrink if (NewCount > fTotalCount) // This is Expand not Shrink
{ {
T* newArray = TRACKED_NEW T[NewCount]; T* newArray = new T[NewCount];
if (fArray != nil) if (fArray != nil)
{ hsTArray_CopyForward(fArray, newArray, fUseCount); { hsTArray_CopyForward(fArray, newArray, fUseCount);
@ -846,7 +846,7 @@ template <class T> void hsTArray<T>::IncCount(int index, int count)
fTotalCount = newCount; fTotalCount = newCount;
GrowArraySize(newCount); // Sets new fTotalCount GrowArraySize(newCount); // Sets new fTotalCount
T* newArray = TRACKED_NEW T[fTotalCount]; T* newArray = new T[fTotalCount];
if (fArray != nil) if (fArray != nil)
{ hsTArray_CopyForward(fArray, newArray, index); { hsTArray_CopyForward(fArray, newArray, index);
@ -903,10 +903,10 @@ template <class T> T* hsTArray<T>::ForEach(hsBool (*proc)(T&, void* p1, void* p2
class hsLargeArrayBase class hsLargeArrayBase
{ {
protected: protected:
UInt32 fUseCount; uint32_t fUseCount;
UInt32 fTotalCount; uint32_t fTotalCount;
void GrowArraySize(UInt32 nSize); void GrowArraySize(uint32_t nSize);
#ifdef HS_DEBUGTARRAY #ifdef HS_DEBUGTARRAY
hsLargeArrayBase(); hsLargeArrayBase();
@ -920,7 +920,7 @@ protected:
#endif #endif
public: public:
UInt32 GetNumAlloc() const { return fTotalCount; } uint32_t GetNumAlloc() const { return fTotalCount; }
}; };
@ -1056,7 +1056,7 @@ template <class T> hsLargeArray<T>::hsLargeArray(int count) : fArray(nil)
hsLargeArray_ValidateCount(count); hsLargeArray_ValidateCount(count);
fUseCount = fTotalCount = count; fUseCount = fTotalCount = count;
if (count > 0) if (count > 0)
fArray = TRACKED_NEW T[count]; fArray = new T[count];
} }
template <class T> hsLargeArray<T>::hsLargeArray(const hsLargeArray<T>& src) : fArray(nil) template <class T> hsLargeArray<T>::hsLargeArray(const hsLargeArray<T>& src) : fArray(nil)
@ -1066,7 +1066,7 @@ template <class T> hsLargeArray<T>::hsLargeArray(const hsLargeArray<T>& src) : f
if (count > 0) if (count > 0)
{ {
fArray = TRACKED_NEW T[count]; fArray = new T[count];
hsLargeArray_CopyForward(src.fArray, fArray, count); hsLargeArray_CopyForward(src.fArray, fArray, count);
} }
} }
@ -1081,7 +1081,7 @@ template <class T> hsLargeArray<T>& hsLargeArray<T>::operator=(const hsLargeArra
template <class T> void hsLargeArray<T>::Swap( hsLargeArray<T>& src ) template <class T> void hsLargeArray<T>::Swap( hsLargeArray<T>& src )
{ {
UInt32 use, tot; uint32_t use, tot;
T *array; T *array;
@ -1128,7 +1128,7 @@ template <class T> void hsLargeArray<T>::SetCount(int count)
{ {
if (fArray) if (fArray)
delete[] fArray; delete[] fArray;
fArray = TRACKED_NEW T[count]; fArray = new T[count];
fUseCount = fTotalCount = count; fUseCount = fTotalCount = count;
} }
fUseCount = count; fUseCount = count;
@ -1139,7 +1139,7 @@ template <class T> void hsLargeArray<T>::Expand(int NewCount) // New Count is Ab
hsLargeArray_ValidateCount(NewCount); hsLargeArray_ValidateCount(NewCount);
if (NewCount > fTotalCount) // This is Expand not Shrink if (NewCount > fTotalCount) // This is Expand not Shrink
{ {
T* newArray = TRACKED_NEW T[NewCount]; T* newArray = new T[NewCount];
if (fArray != nil) if (fArray != nil)
{ hsLargeArray_CopyForward(fArray, newArray, fUseCount); { hsLargeArray_CopyForward(fArray, newArray, fUseCount);
@ -1215,7 +1215,7 @@ template <class T> void hsLargeArray<T>::IncCount(int index, int count)
fTotalCount = newCount; fTotalCount = newCount;
GrowArraySize(newCount); // Sets new fTotalCount GrowArraySize(newCount); // Sets new fTotalCount
T* newArray = TRACKED_NEW T[fTotalCount]; T* newArray = new T[fTotalCount];
if (fArray != nil) if (fArray != nil)
{ hsLargeArray_CopyForward(fArray, newArray, index); { hsLargeArray_CopyForward(fArray, newArray, index);

2
Sources/Plasma/CoreLib/hsThread.cpp

@ -43,7 +43,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#define CoreLib_Thread #define CoreLib_Thread
#include "hsThread.h" #include "hsThread.h"
#include "hsUtils.h"
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////

18
Sources/Plasma/CoreLib/hsThread.h

@ -42,14 +42,12 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsThread_Defined #ifndef hsThread_Defined
#define hsThread_Defined #define hsThread_Defined
#include "hsTypes.h" #include "HeadSpin.h"
typedef UInt32 hsMilliseconds; typedef uint32_t hsMilliseconds;
#if HS_BUILD_FOR_WIN32 #ifdef HS_BUILD_FOR_UNIX
#include "hsWindows.h"
#elif HS_BUILD_FOR_UNIX
#include <pthread.h> #include <pthread.h>
#include <semaphore.h> #include <semaphore.h>
// We can't wait with a timeout with semas // We can't wait with a timeout with semas
@ -71,7 +69,7 @@ public:
#endif #endif
private: private:
hsBool fQuit; hsBool fQuit;
UInt32 fStackSize; uint32_t fStackSize;
#if HS_BUILD_FOR_WIN32 #if HS_BUILD_FOR_WIN32
ThreadId fThreadId; ThreadId fThreadId;
HANDLE fThreadH; HANDLE fThreadH;
@ -85,7 +83,7 @@ protected:
hsBool GetQuit() const { return hsBool(fQuit); } hsBool GetQuit() const { return hsBool(fQuit); }
void SetQuit(hsBool value) { fQuit = value; } void SetQuit(hsBool value) { fQuit = value; }
public: public:
hsThread(UInt32 stackSize = 0); hsThread(uint32_t stackSize = 0);
virtual ~hsThread(); // calls Stop() virtual ~hsThread(); // calls Stop()
#if HS_BUILD_FOR_WIN32 #if HS_BUILD_FOR_WIN32
ThreadId GetThreadId() { return fThreadId; } ThreadId GetThreadId() { return fThreadId; }
@ -155,7 +153,7 @@ class hsSemaphore {
#else #else
pthread_mutex_t fPMutex; pthread_mutex_t fPMutex;
pthread_cond_t fPCond; pthread_cond_t fPCond;
Int32 fCounter; int32_t fCounter;
#endif #endif
#endif #endif
public: public:
@ -200,10 +198,10 @@ class hsSleep
{ {
public: public:
#if HS_BUILD_FOR_UNIX #if HS_BUILD_FOR_UNIX
static void Sleep(UInt32 millis); static void Sleep(uint32_t millis);
#elif HS_BUILD_FOR_WIN32 #elif HS_BUILD_FOR_WIN32
static void Sleep(UInt32 millis) { ::Sleep(millis); } static void Sleep(uint32_t millis) { ::Sleep(millis); }
#endif #endif
}; };

2
Sources/Plasma/CoreLib/hsThread_Mac.cpp

@ -49,7 +49,7 @@ extern "C" {
} }
} }
hsThread::hsThread(UInt32 stackSize) : fTaskId(0), fStackSize(stackSize), fQuit(false) hsThread::hsThread(uint32_t stackSize) : fTaskId(0), fStackSize(stackSize), fQuit(false)
{ {
if (MPLibraryIsLoaded() == false) if (MPLibraryIsLoaded() == false)
throw "MPLibraryIsLoaded() returned false"; throw "MPLibraryIsLoaded() returned false";

8
Sources/Plasma/CoreLib/hsThread_Unix.cpp

@ -79,9 +79,9 @@ extern "C" {
} }
} }
#define kInvalidStackSize UInt32(~0) #define kInvalidStackSize uint32_t(~0)
hsThread::hsThread(UInt32 stackSize) : fStackSize(stackSize), fQuit(false) hsThread::hsThread(uint32_t stackSize) : fStackSize(stackSize), fQuit(false)
{ {
fIsValid = false; fIsValid = false;
pthread_mutex_init(&fMutex,nil); pthread_mutex_init(&fMutex,nil);
@ -541,9 +541,9 @@ void hsEvent::Signal()
#endif #endif
void hsSleep::Sleep(UInt32 millis) void hsSleep::Sleep(uint32_t millis)
{ {
UInt32 secs = millis / 1000; uint32_t secs = millis / 1000;
if (secs > 0) if (secs > 0)
{ {
millis %= 1000; millis %= 1000;

2
Sources/Plasma/CoreLib/hsThread_Win.cpp

@ -58,7 +58,7 @@ static unsigned int __stdcall gEntryPointBT(void* param)
return ((hsThread*)param)->WinRun(); return ((hsThread*)param)->WinRun();
} }
hsThread::hsThread(UInt32 stackSize) : fStackSize(stackSize), fQuit(false), fThreadH(nil), fQuitSemaH(nil) hsThread::hsThread(uint32_t stackSize) : fStackSize(stackSize), fQuit(false), fThreadH(nil), fQuitSemaH(nil)
{ {
} }

274
Sources/Plasma/CoreLib/hsTypes.h

@ -39,19 +39,17 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "HeadSpin.h"
#ifndef hsTypes_Defined #ifdef _HSTYPES_H
#define hsTypes_Defined # error "Do not include hsTypes.h directly--use HeadSpin.h"
#endif // _HSTYPES_H
#define _HSTYPES_H
/************************** Other Includes *****************************/ /************************** Other Includes *****************************/
#include <cstdlib> #include <cstdlib>
#include <cstdio> #include <cstdio>
#include <cstddef>
#if HS_CAN_USE_FLOAT
#include <math.h>
#endif
/************************** Basic Macros *****************************/ /************************** Basic Macros *****************************/
@ -62,63 +60,38 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#define hsCTypeDefStruct(foo) typedef struct foo foo; #define hsCTypeDefStruct(foo) typedef struct foo foo;
#endif #endif
#ifdef HS_BUILD_FOR_WIN32
# ifndef CDECL
# define CDECL __cdecl
# endif
#else
# define CDECL
#endif
/************************** Basic Types *****************************/ /************************** Basic Types *****************************/
#ifdef _MSC_VER #if defined(_MSC_VER) && _MSC_VER < 1600
typedef signed __int8 int8_t; typedef signed char int8_t;
typedef unsigned __int8 uint8_t; typedef unsigned char uint8_t;
typedef signed __int16 int16_t; typedef signed short int int16_t;
typedef unsigned __int16 uint16_t; typedef unsigned short int uint16_t;
typedef signed __int32 int32_t; typedef signed int int32_t;
typedef unsigned __int32 uint32_t; typedef unsigned int uint32_t;
typedef signed __int64 int64_t; typedef signed long long int64_t;
typedef unsigned __int64 uint64_t; typedef unsigned long long uint64_t;
#else #else
#include <stdint.h> #include <stdint.h>
#endif #endif
typedef uint8_t byte;
typedef uint16_t word;
typedef uint32_t dword;
typedef uint64_t qword;
typedef uintptr_t unsigned_ptr;
typedef wchar_t wchar;
#define kPosInfinity16 (32767) #define kPosInfinity16 (32767)
#define kNegInfinity16 (-32768) #define kNegInfinity16 (-32768)
#define kPosInfinity32 (0x7fffffff) #define kPosInfinity32 (0x7fffffff)
#define kNegInfinity32 (0x80000000) #define kNegInfinity32 (0x80000000)
typedef int8_t Int8; #ifndef M_PI
typedef int16_t Int16; # define M_PI 3.14159265358979323846
typedef int32_t Int32;
typedef int64_t Int64;
typedef uint8_t UInt8;
typedef uint16_t UInt16;
typedef uint32_t UInt32;
typedef uint64_t UInt64;
#ifndef Byte
typedef uint8_t Byte;
#endif
#ifndef false
#define false 0
#endif #endif
#ifndef true
#define true 1
#endif
#ifndef Boolean
typedef uint8_t Boolean;
#endif
typedef Int32 hsFixed;
typedef Int32 hsFract;
#ifdef __cplusplus #ifdef __cplusplus
@ -126,18 +99,12 @@ typedef int hsBool;
#endif #endif
#include "hsScalar.h"
#if HS_CAN_USE_FLOAT
#define HS_PI 3.1415927
#endif
#ifndef nil #ifndef nil
#define nil (0) #define nil (0)
#endif #endif
typedef Int32 hsError; typedef int32_t hsError;
typedef UInt32 hsGSeedValue; typedef uint32_t hsGSeedValue;
#define hsOK 0 #define hsOK 0
#define hsFail -1 #define hsFail -1
@ -153,24 +120,23 @@ typedef UInt32 hsGSeedValue;
#define hsBitTst2Bool(value, mask) (((value) & (mask)) != 0) #define hsBitTst2Bool(value, mask) (((value) & (mask)) != 0)
#define hsFourByteTag(a, b, c, d) (((UInt32)(a) << 24) | ((UInt32)(b) << 16) | ((UInt32)(c) << 8) | (d)) #define hsFourByteTag(a, b, c, d) (((uint32_t)(a) << 24) | ((uint32_t)(b) << 16) | ((uint32_t)(c) << 8) | (d))
/************************** Swap Macros *****************************/ /************************** Swap Macros *****************************/
#ifdef __cplusplus inline uint16_t hsSwapEndian16(uint16_t value)
inline UInt16 hsSwapEndian16(UInt16 value)
{ {
return (value >> 8) | (value << 8); return (value >> 8) | (value << 8);
} }
inline UInt32 hsSwapEndian32(UInt32 value) inline uint32_t hsSwapEndian32(uint32_t value)
{ {
return ((value) << 24) | return ((value) << 24) |
((value & 0x0000ff00) << 8) | ((value & 0x0000ff00) << 8) |
((value & 0x00ff0000) >> 8) | ((value & 0x00ff0000) >> 8) |
((value) >> 24); ((value) >> 24);
} }
inline UInt64 hsSwapEndian64(UInt64 value) inline uint64_t hsSwapEndian64(uint64_t value)
{ {
return ((value) << 56) | return ((value) << 56) |
((value & 0x000000000000ff00) << 40) | ((value & 0x000000000000ff00) << 40) |
@ -181,20 +147,18 @@ typedef UInt32 hsGSeedValue;
((value & 0x00ff000000000000) >> 40) | ((value & 0x00ff000000000000) >> 40) |
((value) >> 56); ((value) >> 56);
} }
#if HS_CAN_USE_FLOAT
inline float hsSwapEndianFloat(float fvalue) inline float hsSwapEndianFloat(float fvalue)
{ {
UInt32 value = *(UInt32*)&fvalue; uint32_t value = *(uint32_t*)&fvalue;
value = hsSwapEndian32(value); value = hsSwapEndian32(value);
return *(float*)&value; return *(float*)&value;
} }
inline double hsSwapEndianDouble(double dvalue) inline double hsSwapEndianDouble(double dvalue)
{ {
UInt64 value = *(UInt64*)&dvalue; uint64_t value = *(uint64_t*)&dvalue;
value = hsSwapEndian64(value); value = hsSwapEndian64(value);
return *(double*)&value; return *(double*)&value;
} }
#endif
#if LITTLE_ENDIAN #if LITTLE_ENDIAN
#define hsToBE16(n) hsSwapEndian16(n) #define hsToBE16(n) hsSwapEndian16(n)
@ -220,66 +184,53 @@ typedef UInt32 hsGSeedValue;
#define hsToLEDouble(n) hsSwapEndianDouble(n) #define hsToLEDouble(n) hsSwapEndianDouble(n)
#endif #endif
inline void hsSwap(Int32& a, Int32& b) inline void hsSwap(int32_t& a, int32_t& b)
{ {
Int32 c = a; int32_t c = a;
a = b; a = b;
b = c; b = c;
} }
inline void hsSwap(UInt32& a, UInt32& b) inline void hsSwap(uint32_t& a, uint32_t& b)
{ {
UInt32 c = a; uint32_t c = a;
a = b; a = b;
b = c; b = c;
} }
#if HS_CAN_USE_FLOAT
inline void hsSwap(float& a, float& b) inline void hsSwap(float& a, float& b)
{ {
float c = a; float c = a;
a = b; a = b;
b = c; b = c;
} }
#endif
#endif
/************************** Color32 Type *****************************/ /************************** Color32 Type *****************************/
struct hsColor32 { struct hsColor32 {
UInt8 b, g, r, a; uint8_t b, g, r, a;
#ifdef __cplusplus void SetARGB(uint8_t aa, uint8_t rr, uint8_t gg, uint8_t bb)
void SetARGB(UInt8 aa, UInt8 rr, UInt8 gg, UInt8 bb)
{ {
this->a = aa; this->r = rr; this->g = gg; this->b = bb; this->a = aa; this->r = rr; this->g = gg; this->b = bb;
} }
// Compatibility inlines, should be depricated // Compatibility inlines, should be depricated
void Set(UInt8 rr, UInt8 gg, UInt8 bb) void Set(uint8_t rr, uint8_t gg, uint8_t bb)
{ {
this->r = rr; this->g = gg; this->b = bb; this->r = rr; this->g = gg; this->b = bb;
} }
void Set(UInt8 aa, UInt8 rr, UInt8 gg, UInt8 bb) void Set(uint8_t aa, uint8_t rr, uint8_t gg, uint8_t bb)
{ {
this->SetARGB(aa, rr, gg, bb); this->SetARGB(aa, rr, gg, bb);
} }
#if 0
friend int operator==(const hsColor32& a, const hsColor32& b)
{
return *(UInt32*)&a == *(UInt32*)&b;
}
friend int operator!=(const hsColor32& a, const hsColor32& b) { return !(a == b); }
#else
int operator==(const hsColor32& aa) const int operator==(const hsColor32& aa) const
{ {
return *(UInt32*)&aa == *(UInt32*)this; return *(uint32_t*)&aa == *(uint32_t*)this;
} }
int operator!=(const hsColor32& aa) { return !(aa == *this); } int operator!=(const hsColor32& aa) { return !(aa == *this); }
#endif
#endif
}; };
hsCTypeDefStruct(hsColor32) hsCTypeDefStruct(hsColor32)
@ -298,7 +249,8 @@ typedef hsColor32 hsRGBAColor32;
* *
***/ ***/
#if _MSC_VER >= 7
#ifdef _MSC_VER
# define NULL_STMT __noop # define NULL_STMT __noop
#else #else
# define NULL_STMT ((void)0) # define NULL_STMT ((void)0)
@ -427,23 +379,8 @@ void SWAP (T & a, T & b) {
/**************************************************************************** /****************************************************************************
* *
* Calculate the address to the base of a structure given its type, and the * arrsize
* address of a field within the structure.
*
* Example:
*
* CONTAINING_STRUCT(trans, INetTrans, m_trans);
*
***/
#define CONTAINING_STRUCT(a, t, f) ((t *) ((byte *)(a) - (unsigned_ptr)(&((t *)0)->f)))
/****************************************************************************
*
* arrsize/marrsize
* arrsize returns the number of elements in an array variable * arrsize returns the number of elements in an array variable
* marrsize returns the number of elements in an array field in a structure
* *
* Example: * Example:
* *
@ -452,54 +389,6 @@ void SWAP (T & a, T & b) {
***/ ***/
#define arrsize(a) (sizeof(a) / sizeof((a)[0])) #define arrsize(a) (sizeof(a) / sizeof((a)[0]))
#define marrsize(c,a) (arrsize(((c *)0)->a))
/****************************************************************************
*
* offsetof/moffsetof
* offsetof returns the offset in bytes of a field inside a structure based on a type
* moffsetof returns the offset in bytes of a field inside a structure based on a variable
*
***/
#include <stddef.h>
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif // ifndef offsetof
#define moffsetof(v,f) (((byte *) &((v)->f)) - ((byte *) v))
/****************************************************************************
*
* msizeof
* Returns the size of a field in a structure
*
* Example:
*
* unsigned bufferSize = msizeof(CommandStruct, buffer);
*
***/
#define msizeof(c,a) (sizeof(((c *)0)->a))
/****************************************************************************
*
* ONCE
* Shortcut to create a 'for' loop that executes only once
*
* for (ONCE) {
* ...
* }
*
***/
#ifndef ONCE
#define ONCE bool UNIQUE_SYMBOL(ONCE) = true; UNIQUE_SYMBOL(ONCE); UNIQUE_SYMBOL(ONCE) = false
#endif
/**************************************************************************** /****************************************************************************
@ -510,75 +399,6 @@ void SWAP (T & a, T & b) {
#define IS_POW2(val) (!((val) & ((val) - 1))) #define IS_POW2(val) (!((val) & ((val) - 1)))
/************************ Debug/Error Macros **************************/
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*hsDebugMessageProc)(const char message[]);
extern hsDebugMessageProc gHSDebugProc;
#define HSDebugProc(m) { if (gHSDebugProc) gHSDebugProc(m); }
hsDebugMessageProc hsSetDebugMessageProc(hsDebugMessageProc newProc);
extern hsDebugMessageProc gHSStatusProc;
hsDebugMessageProc hsSetStatusMessageProc(hsDebugMessageProc newProc);
void CDECL ErrorAssert (int line, const char file[], const char fmt[], ...);
void CDECL ErrorFatal (int line, const char file[], const char fmt[], ...);
void ErrorMinimizeAppWindow ();
enum EErrorOption {
kErrOptNonGuiAsserts,
kErrOptDisableMemLeakChecking,
kNumErrorOptions
};
bool ErrorSetOption (EErrorOption option, bool on);
bool ErrorGetOption (EErrorOption option);
bool DebugIsDebuggerPresent ();
void DebugBreakIfDebuggerPresent ();
void DebugMsg (const char fmt[], ...);
void DebugMsgV (const char fmt[], va_list args);
#ifdef HS_DEBUGGING
void hsDebugMessage(const char message[], long refcon);
#define hsDebugCode(code) code
#define hsIfDebugMessage(expr, msg, ref) (void)( ((expr) != 0) || (hsDebugMessage(msg, ref), 0) )
#define hsAssert(expr, msg) (void)( ((expr) != 0) || (ErrorAssert(__LINE__, __FILE__, msg), 0) )
#define ASSERT(expr) (void)( ((expr) != 0) || (ErrorAssert(__LINE__, __FILE__, #expr), 0) )
#define ASSERTMSG(expr, msg) (void)( ((expr) != 0) || (ErrorAssert(__LINE__, __FILE__, msg), 0) )
#define FATAL(msg) ErrorAssert(__LINE__, __FILE__, msg)
#define DEBUG_MSG DebugMsg
#define DEBUG_MSGV DebugMsgV
#define DEBUG_BREAK_IF_DEBUGGER_PRESENT DebugBreakIfDebuggerPresent
#else /* Not debugging */
#define hsDebugMessage(message, refcon) NULL_STMT
#define hsDebugCode(code) /* empty */
#define hsIfDebugMessage(expr, msg, ref) NULL_STMT
#define hsAssert(expr, msg) NULL_STMT
#define ASSERT(expr) NULL_STMT
#define ASSERTMSG(expr, msg) NULL_STMT
#define FATAL(msg) NULL_STMT
#define DEBUG_MSG (void)
#define DEBUG_MSGV NULL_STMT
#define DEBUG_BREAK_IF_DEBUGGER_PRESENT NULL_STMT
#endif // HS_DEBUGGING
#ifdef _MSC_VER
#define DEFAULT_FATAL(var) default: FATAL("No valid case for switch variable '" #var "'"); __assume(0); break;
#else
#define DEFAULT_FATAL(var) default: FATAL("No valid case for switch variable '" #var "'"); break;
#endif
#ifdef PLASMA_EXTERNAL_RELEASE #ifdef PLASMA_EXTERNAL_RELEASE
#define hsStatusMessage(x) NULL_STMT #define hsStatusMessage(x) NULL_STMT
@ -591,9 +411,3 @@ void DebugMsgV (const char fmt[], va_list args);
#endif // PLASMA_EXTERNAL_RELEASE #endif // PLASMA_EXTERNAL_RELEASE
#ifdef __cplusplus
}
#endif
#endif

59
Sources/Plasma/CoreLib/hsUtils.cpp

@ -39,22 +39,11 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "hsUtils.h"
#if HS_BUILD_FOR_WIN32
extern "C" {
#endif
#include <stdio.h>
#include <stdarg.h>
#if HS_BUILD_FOR_WIN32
};
#endif
#if HS_BUILD_FOR_WIN32 #include "HeadSpin.h"
#include <winsock2.h>
#include <windows.h>
#endif
#include "hsStlUtils.h" #include "hsStlUtils.h"
#include "hsTemplates.h" #include "hsTemplates.h"
#include <math.h>
char * hsFormatStr(const char * fmt, ...) char * hsFormatStr(const char * fmt, ...)
@ -75,16 +64,9 @@ char * hsFormatStrV(const char * fmt, va_list args)
static char hsStrBuf[100]; static char hsStrBuf[100];
char *hsScalarToStr(hsScalar s) char *hsScalarToStr(float s)
{ {
if (s == hsIntToScalar(hsScalarToInt(s))) sprintf(hsStrBuf, "%f", s);
sprintf(hsStrBuf, "%d", hsScalarToInt(s));
else
#if HS_CAN_USE_FLOAT
sprintf(hsStrBuf, "%f", hsScalarToFloat(s));
#else
sprintf(hsStrBuf, "%d:%lu", hsFixedToInt(s), (UInt16)s);
#endif
return hsStrBuf; return hsStrBuf;
} }
@ -96,7 +78,7 @@ int hsMessageBoxWithOwner(void * owner, const char message[], const char caption
return hsMBoxOk; return hsMBoxOk;
#if HS_BUILD_FOR_WIN32 #if HS_BUILD_FOR_WIN32
UInt32 flags = 0; uint32_t flags = 0;
if (kind == hsMessageBoxNormal) if (kind == hsMessageBoxNormal)
flags |= MB_OK; flags |= MB_OK;
@ -150,7 +132,7 @@ int hsMessageBoxWithOwner(void * owner, const wchar_t message[], const wchar_t c
return hsMBoxOk; return hsMBoxOk;
#if HS_BUILD_FOR_WIN32 #if HS_BUILD_FOR_WIN32
UInt32 flags = 0; uint32_t flags = 0;
if (kind == hsMessageBoxNormal) if (kind == hsMessageBoxNormal)
flags |= MB_OK; flags |= MB_OK;
@ -216,6 +198,11 @@ int hsMessageBox(const wchar_t message[], const wchar_t caption[], int kind, int
#endif #endif
} }
inline hsBool hsCompare(float a, float b, float delta)
{
return (fabs(a - b) < delta);
}
/* Generic psuedo RNG used in ANSI C. */ /* Generic psuedo RNG used in ANSI C. */
static unsigned long SEED = 1; static unsigned long SEED = 1;
@ -250,13 +237,13 @@ char* hsStrcpy(char dst[], const char src[])
if (dst == nil) if (dst == nil)
{ {
int count = hsStrlen(src); int count = hsStrlen(src);
dst = (char *)ALLOC(count + 1); dst = (char *)malloc(count + 1);
memcpy(dst, src, count); memcpy(dst, src, count);
dst[count] = 0; dst[count] = 0;
return dst; return dst;
} }
Int32 i; int32_t i;
for (i = 0; src[i] != 0; i++) for (i = 0; src[i] != 0; i++)
dst[i] = src[i]; dst[i] = src[i];
dst[i] = 0; dst[i] = 0;
@ -265,7 +252,7 @@ char* hsStrcpy(char dst[], const char src[])
return dst; return dst;
} }
hsBool hsStrEQ(const char s1[], const char s2[]) bool hsStrEQ(const char s1[], const char s2[])
{ {
if (s1 && s2) if (s1 && s2)
{ {
@ -278,7 +265,7 @@ hsBool hsStrEQ(const char s1[], const char s2[])
return (!s1 && !s2); return (!s1 && !s2);
} }
hsBool hsStrCaseEQ(const char* s1, const char* s2) bool hsStrCaseEQ(const char* s1, const char* s2)
{ {
if (s1 && s2) if (s1 && s2)
{ {
@ -312,10 +299,10 @@ void hsStrLower(char *s)
} }
} }
char* hsP2CString(const UInt8 pstring[], char cstring[]) char* hsP2CString(const uint8_t pstring[], char cstring[])
{ {
char* cstr = cstring; char* cstr = cstring;
const UInt8* stop = &pstring[1] + pstring[0]; const uint8_t* stop = &pstring[1] + pstring[0];
pstring += 1; // skip length byte pstring += 1; // skip length byte
while (pstring < stop) while (pstring < stop)
@ -324,7 +311,7 @@ char* hsP2CString(const UInt8 pstring[], char cstring[])
return cstring; return cstring;
} }
UInt8* hsC2PString(const char cstring[], UInt8 pstring[]) uint8_t* hsC2PString(const char cstring[], uint8_t pstring[])
{ {
int i; int i;
@ -341,7 +328,7 @@ wchar_t *hsStringToWString( const char *str )
{ {
// convert the char string to a wchar_t string // convert the char string to a wchar_t string
int len = strlen(str); int len = strlen(str);
wchar_t *wideString = TRACKED_NEW wchar_t[len+1]; wchar_t *wideString = new wchar_t[len+1];
for (int i=0; i<len; i++) for (int i=0; i<len; i++)
wideString[i] = btowc(str[i]); wideString[i] = btowc(str[i]);
wideString[len] = L'\0'; wideString[len] = L'\0';
@ -355,7 +342,7 @@ char *hsWStringToString( const wchar_t *str )
{ {
// convert the wchar_t string to a char string // convert the wchar_t string to a char string
int len = wcslen(str); int len = wcslen(str);
char *sStr = TRACKED_NEW char[len+1]; char *sStr = new char[len+1];
int i; int i;
for (i = 0; i < len; i++) for (i = 0; i < len; i++)
@ -394,7 +381,7 @@ void hsCPathToMacPath(char* dst, char* fname)
else if(strstr(fname, "\\\\")) else if(strstr(fname, "\\\\"))
{ {
prefix = 0; prefix = 0;
offset = 2; // copy fname from 2-bytes in. This removes offset = 2; // copy fname from 2-Bytes in. This removes
// the first two chars... // the first two chars...
} }
@ -423,7 +410,7 @@ int hsRemove(const char * fname)
} }
UInt32 hsPhysicalMemory() uint32_t hsPhysicalMemory()
{ {
#define HS_ONE_MEGABYTE 1048576 // 1024 * 1024 #define HS_ONE_MEGABYTE 1048576 // 1024 * 1024
@ -436,7 +423,7 @@ UInt32 hsPhysicalMemory()
MemSpec hsMemorySpec() MemSpec hsMemorySpec()
{ {
UInt32 mem = hsPhysicalMemory(); uint32_t mem = hsPhysicalMemory();
// Currently adding a little margin of error here // Currently adding a little margin of error here
// due to the fact that Windows doesn't seem to // due to the fact that Windows doesn't seem to

88
Sources/Plasma/CoreLib/hsUtils.h

@ -39,21 +39,22 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#ifndef hsUtils_Defined
#define hsUtils_Defined
#include "HeadSpin.h" #ifdef _HSUTILS_H
# error "Do not include hsUtils.h directly--use HeadSpin.h"
#endif // _HSUTILS_H
#define _HSUTILS_H
#include <string.h> #include "HeadSpin.h"
#include <ctype.h> #include <ctype.h>
#include <stdarg.h> #include <stdarg.h>
int hsStrlen(const char src[]); int hsStrlen(const char src[]);
char* hsStrcpy(char dstOrNil[], const char src[]); char* hsStrcpy(char dstOrNil[], const char src[]);
void hsStrcat(char dst[], const char src[]); void hsStrcat(char dst[], const char src[]);
hsBool hsStrEQ(const char s1[], const char s2[]); bool hsStrEQ(const char s1[], const char s2[]);
hsBool hsStrCaseEQ(const char* s1, const char* s2); bool hsStrCaseEQ(const char* s1, const char* s2);
char* hsScalarToStr(hsScalar); char* hsScalarToStr(float);
int hsRemove(const char* filename); int hsRemove(const char* filename);
void hsCPathToMacPath(char* dst, char* fname); void hsCPathToMacPath(char* dst, char* fname);
void hsStrLower(char *s); void hsStrLower(char *s);
@ -76,9 +77,9 @@ char * hsFormatStrV(const char * fmt, va_list args); // You are responsible f
#endif #endif
// A pstring has a length byte at the beginning, and no trailing 0 // A pstring has a length uint8_t at the beginning, and no trailing 0
char* hsP2CString(const UInt8 pstring[], char cstring[]); char* hsP2CString(const uint8_t pstring[], char cstring[]);
UInt8* hsC2PString(const char cstring[], UInt8 pstring[]); uint8_t* hsC2PString(const char cstring[], uint8_t pstring[]);
inline char* hsStrcpy(const char src[]) inline char* hsStrcpy(const char src[])
{ {
@ -127,10 +128,7 @@ int hsMessageBox(const wchar_t message[], const wchar_t caption[], int kind, int
int hsMessageBoxWithOwner(void* owner, const char message[], const char caption[], int kind, int icon=hsMessageBoxIconAsterisk); int hsMessageBoxWithOwner(void* owner, const char message[], const char caption[], int kind, int icon=hsMessageBoxIconAsterisk);
int hsMessageBoxWithOwner(void* owner, const wchar_t message[], const wchar_t caption[], int kind, int icon=hsMessageBoxIconAsterisk); int hsMessageBoxWithOwner(void* owner, const wchar_t message[], const wchar_t caption[], int kind, int icon=hsMessageBoxIconAsterisk);
inline hsBool hsCompare(hsScalar a, hsScalar b, hsScalar delta=0.0001) inline hsBool hsCompare(float a, float b, float delta=0.0001);
{
return (fabs(a - b) < delta);
}
// flag testing / clearing // flag testing / clearing
#define hsCheckBits(f,c) ((f & c)==c) #define hsCheckBits(f,c) ((f & c)==c)
@ -167,6 +165,13 @@ inline hsBool hsCompare(hsScalar a, hsScalar b, hsScalar delta=0.0001)
# define hsWFopen(name, mode) fopen(hsWStringToString(name), hsWStringToString(mode)) # define hsWFopen(name, mode) fopen(hsWStringToString(name), hsWStringToString(mode))
#endif #endif
// Useful floating point utilities
inline float hsDegreesToRadians(float deg) { return float(deg * (M_PI / 180)); }
inline float hsRadiansToDegrees(float rad) { return float(rad * (180 / M_PI)); }
#define hsInvert(a) (1 / (a))
#include <new>
#define NEWZERO(t) new(calloc(sizeof(t), 1)) t
///////////////////////////// /////////////////////////////
// Physical memory functions // Physical memory functions
@ -178,7 +183,7 @@ enum MemSpec
kOptimal // 256 or greater kOptimal // 256 or greater
}; };
UInt32 hsPhysicalMemory(); uint32_t hsPhysicalMemory();
MemSpec hsMemorySpec(); MemSpec hsMemorySpec();
inline int hsRandMax() { return 32767; } inline int hsRandMax() { return 32767; }
@ -190,5 +195,54 @@ void hsRandSeed(int seed);
char** DisplaySystemVersion(); char** DisplaySystemVersion();
#endif // hsUtils_Defined /************************ Debug/Error Macros **************************/
typedef void (*hsDebugMessageProc)(const char message[]);
extern hsDebugMessageProc gHSDebugProc;
#define HSDebugProc(m) { if (gHSDebugProc) gHSDebugProc(m); }
hsDebugMessageProc hsSetDebugMessageProc(hsDebugMessageProc newProc);
extern hsDebugMessageProc gHSStatusProc;
hsDebugMessageProc hsSetStatusMessageProc(hsDebugMessageProc newProc);
void ErrorEnableGui (bool enabled);
void ErrorAssert (int line, const char file[], const char fmt[], ...);
void ErrorMinimizeAppWindow ();
bool DebugIsDebuggerPresent ();
void DebugBreakIfDebuggerPresent ();
void DebugMsg(const char fmt[], ...);
#ifdef HS_DEBUGGING
void hsDebugMessage(const char message[], long refcon);
#define hsDebugCode(code) code
#define hsIfDebugMessage(expr, msg, ref) (void)( ((expr) != 0) || (hsDebugMessage(msg, ref), 0) )
#define hsAssert(expr, msg) (void)( ((expr) != 0) || (ErrorAssert(__LINE__, __FILE__, msg), 0) )
#define ASSERT(expr) (void)( ((expr) != 0) || (ErrorAssert(__LINE__, __FILE__, #expr), 0) )
#define ASSERTMSG(expr, msg) (void)( ((expr) != 0) || (ErrorAssert(__LINE__, __FILE__, msg), 0) )
#define FATAL(msg) ErrorAssert(__LINE__, __FILE__, msg)
#define DEBUG_MSG DebugMsg
#define DEBUG_BREAK_IF_DEBUGGER_PRESENT DebugBreakIfDebuggerPresent
#else /* Not debugging */
#define hsDebugMessage(message, refcon) NULL_STMT
#define hsDebugCode(code) /* empty */
#define hsIfDebugMessage(expr, msg, ref) NULL_STMT
#define hsAssert(expr, msg) NULL_STMT
#define ASSERT(expr) NULL_STMT
#define ASSERTMSG(expr, msg) NULL_STMT
#define FATAL(msg) NULL_STMT
#define DEBUG_MSG (void)
#define DEBUG_MSGV NULL_STMT
#define DEBUG_BREAK_IF_DEBUGGER_PRESENT NULL_STMT
#endif // HS_DEBUGGING
#ifdef _MSC_VER
#define DEFAULT_FATAL(var) default: FATAL("No valid case for switch variable '" #var "'"); __assume(0); break;
#else
#define DEFAULT_FATAL(var) default: FATAL("No valid case for switch variable '" #var "'"); break;
#endif

104
Sources/Plasma/CoreLib/hsWide.cpp

@ -43,7 +43,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
inline hsBool OverflowAdd(UInt32* sum, UInt32 a, UInt32 b) inline hsBool OverflowAdd(uint32_t* sum, uint32_t a, uint32_t b)
{ {
*sum = a + b; *sum = a + b;
@ -55,19 +55,19 @@ inline hsBool OverflowAdd(UInt32* sum, UInt32 a, UInt32 b)
wide = (high << 32) + (middle << 16) + low wide = (high << 32) + (middle << 16) + low
*/ */
inline hsBool SetWide3(hsWide* target, Int32 high, UInt32 middle, UInt32 low) inline hsBool SetWide3(hsWide* target, int32_t high, uint32_t middle, uint32_t low)
{ {
hsAssert(high >= 0, "high is neg"); hsAssert(high >= 0, "high is neg");
target->fLo = low + (middle << 16); target->fLo = low + (middle << 16);
target->fHi = high + (middle >> 16) + (((low >> 16) + (UInt16)middle) >> 16); target->fHi = high + (middle >> 16) + (((low >> 16) + (uint16_t)middle) >> 16);
return target->fHi < 0; // true if overflow return target->fHi < 0; // true if overflow
} }
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
hsWide* hsWide::Mul(Int32 src1, Int32 src2) hsWide* hsWide::Mul(int32_t src1, int32_t src2)
{ {
int neg = 0; int neg = 0;
@ -80,10 +80,10 @@ hsWide* hsWide::Mul(Int32 src1, Int32 src2)
neg = ~neg; neg = ~neg;
} }
UInt32 a = src1 >> 16; uint32_t a = src1 >> 16;
UInt32 b = (UInt16)src1; uint32_t b = (uint16_t)src1;
UInt32 c = src2 >> 16; uint32_t c = src2 >> 16;
UInt32 d = (UInt16)src2; uint32_t d = (uint16_t)src2;
(void)SetWide3(this, a * c, a * d + c * b, b * d); (void)SetWide3(this, a * c, a * d + c * b, b * d);
@ -92,13 +92,13 @@ hsWide* hsWide::Mul(Int32 src1, Int32 src2)
return this; return this;
} }
hsWide* hsWide::Mul(Int32 A) hsWide* hsWide::Mul(int32_t A)
{ {
int neg = 0; int neg = 0;
UInt32 B = fLo; uint32_t B = fLo;
Int32 C = fHi; int32_t C = fHi;
Int32 tmp; int32_t tmp;
UInt32 clo,blo,bhi,alo; uint32_t clo,blo,bhi,alo;
if (A < 0) if (A < 0)
{ A = -A; { A = -A;
@ -109,37 +109,37 @@ hsWide* hsWide::Mul(Int32 A)
neg = ~neg; neg = ~neg;
} }
UInt32 ahi = A >> 16; uint32_t ahi = A >> 16;
UInt32 chi = C >> 16; uint32_t chi = C >> 16;
if (ahi != 0 && chi != 0) if (ahi != 0 && chi != 0)
goto OVER_FLOW; goto OVER_FLOW;
alo = (UInt16)A; alo = (uint16_t)A;
bhi = B >> 16; bhi = B >> 16;
blo = (UInt16)B; blo = (uint16_t)B;
clo = (UInt16)C; clo = (uint16_t)C;
tmp = alo * clo; tmp = alo * clo;
if (tmp < 0 || SetWide3(this, tmp, alo * bhi, alo * blo)) if (tmp < 0 || SetWide3(this, tmp, alo * bhi, alo * blo))
goto OVER_FLOW; goto OVER_FLOW;
if (chi != 0) if (chi != 0)
{ UInt32 Vh = alo * chi; { uint32_t Vh = alo * chi;
if (Vh >> 15) if (Vh >> 15)
goto OVER_FLOW; goto OVER_FLOW;
if (((this->fHi >> 16) + (UInt16)Vh) >> 15) if (((this->fHi >> 16) + (uint16_t)Vh) >> 15)
goto OVER_FLOW; goto OVER_FLOW;
this->fHi += Vh << 16; this->fHi += Vh << 16;
} }
else // ahi != 0 && chi == 0 else // ahi != 0 && chi == 0
{ hsWide w; { hsWide w;
UInt32 Vh = ahi * clo; uint32_t Vh = ahi * clo;
if (Vh >> 16) if (Vh >> 16)
goto OVER_FLOW; goto OVER_FLOW;
tmp = ahi * bhi; tmp = ahi * bhi;
if (tmp < 0 || SetWide3(&w, tmp, ahi * blo, 0)) if (tmp < 0 || SetWide3(&w, tmp, ahi * blo, 0))
goto OVER_FLOW; goto OVER_FLOW;
if (((w.fHi >> 16) + (UInt16)Vh) >> 15) if (((w.fHi >> 16) + (uint16_t)Vh) >> 15)
goto OVER_FLOW; goto OVER_FLOW;
w.fHi += Vh << 16; w.fHi += Vh << 16;
this->Add(&w); this->Add(&w);
@ -154,7 +154,7 @@ OVER_FLOW:
return this; return this;
} }
hsWide* hsWide::Div(Int32 denom) hsWide* hsWide::Div(int32_t denom)
{ {
if (denom == 0) if (denom == 0)
{ if (this->IsNeg()) { if (this->IsNeg())
@ -169,10 +169,10 @@ hsWide* hsWide::Div(Int32 denom)
} }
int neg = 0; int neg = 0;
Int32 resultH = 0; int32_t resultH = 0;
UInt32 resultL = 0; uint32_t resultL = 0;
Int32 numerH = this->fHi; int32_t numerH = this->fHi;
UInt32 numerL = this->fLo; uint32_t numerL = this->fLo;
if (denom < 0) if (denom < 0)
{ denom = -denom; { denom = -denom;
@ -185,18 +185,18 @@ hsWide* hsWide::Div(Int32 denom)
WIDE_ADDPOS(numerH, numerL, denom >> 1); // add denom/2 to get a round result WIDE_ADDPOS(numerH, numerL, denom >> 1); // add denom/2 to get a round result
UInt32 curr = (UInt32)numerH >> 31; uint32_t curr = (uint32_t)numerH >> 31;
for (int i = 0; i < 64; i++) for (int i = 0; i < 64; i++)
{ {
WIDE_SHIFTLEFT(resultH, resultL, resultH, resultL, 1); WIDE_SHIFTLEFT(resultH, resultL, resultH, resultL, 1);
if (UInt32(denom) <= curr) if (uint32_t(denom) <= curr)
{ {
resultL |= 1; resultL |= 1;
curr -= denom; curr -= denom;
} }
WIDE_SHIFTLEFT(numerH, numerL, numerH, numerL, 1); WIDE_SHIFTLEFT(numerH, numerL, numerH, numerL, 1);
curr = (curr << 1) | ((UInt32)numerH >> 31); curr = (curr << 1) | ((uint32_t)numerH >> 31);
} }
if (neg) if (neg)
@ -223,7 +223,7 @@ hsWide* hsWide::Div(const hsWide* denom)
inline int MaxLeftShift(const hsWide* w) inline int MaxLeftShift(const hsWide* w)
{ {
Int32 hi = w->fHi; int32_t hi = w->fHi;
if (hi == 0) if (hi == 0)
return 31; return 31;
@ -240,7 +240,7 @@ inline int MaxLeftShift(const hsWide* w)
} }
} }
hsFixed hsWide::FixDiv(const hsWide* denom) const int32_t hsWide::FixDiv(const hsWide* denom) const
{ {
hsWide num = *this; hsWide num = *this;
hsWide den = *denom; hsWide den = *denom;
@ -256,7 +256,7 @@ hsFixed hsWide::FixDiv(const hsWide* denom) const
return num.Div(&den)->AsLong(); return num.Div(&den)->AsLong();
} }
hsFract hsWide::FracDiv(const hsWide* denom) const int32_t hsWide::FracDiv(const hsWide* denom) const
{ {
hsWide num = *this; hsWide num = *this;
hsWide den = *denom; hsWide den = *denom;
@ -274,15 +274,15 @@ hsFract hsWide::FracDiv(const hsWide* denom) const
//////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////
Int32 hsWide::Sqrt() const int32_t hsWide::Sqrt() const
{ {
int bits = 32; int bits = 32;
UInt32 root = 0; uint32_t root = 0;
UInt32 valueH = (UInt32)fHi; uint32_t valueH = (uint32_t)fHi;
UInt32 valueL = fLo; uint32_t valueL = fLo;
UInt32 currH = 0; uint32_t currH = 0;
UInt32 currL = 0; uint32_t currL = 0;
UInt32 guessH, guessL; uint32_t guessH, guessL;
do { do {
WIDE_SHIFTLEFT(currH, currL, currH, currL, 2); WIDE_SHIFTLEFT(currH, currL, currH, currL, 2);
@ -297,21 +297,17 @@ Int32 hsWide::Sqrt() const
} }
} while (--bits); } while (--bits);
#if HS_PIN_MATH_OVERFLOW return (int32_t)root;
if ((Int32)root < 0)
return kPosInfinity32;
#endif
return (Int32)root;
} }
Int32 hsWide::CubeRoot() const int32_t hsWide::CubeRoot() const
{ {
int bits = 21; int bits = 21;
UInt32 root = 0; uint32_t root = 0;
UInt32 valueH = (UInt32)fHi; uint32_t valueH = (uint32_t)fHi;
UInt32 valueL = fLo; uint32_t valueL = fLo;
UInt32 currH, currL; uint32_t currH, currL;
UInt32 guessH, guessL; uint32_t guessH, guessL;
hsBool neg = false; hsBool neg = false;
if (WIDE_ISNEG(valueH, valueL)) if (WIDE_ISNEG(valueH, valueL))
@ -336,7 +332,7 @@ Int32 hsWide::CubeRoot() const
hsWide w2 = w; hsWide w2 = w;
w.ShiftLeft(1)->Add(&w2); w.ShiftLeft(1)->Add(&w2);
#endif #endif
guessH = (UInt32)w.fHi; guessH = (uint32_t)w.fHi;
guessL = w.fLo; guessL = w.fLo;
if (WIDE_LESSTHAN(guessH, guessL, currH, currL)) if (WIDE_LESSTHAN(guessH, guessL, currH, currL))
@ -347,7 +343,7 @@ Int32 hsWide::CubeRoot() const
} while (--bits); } while (--bits);
if (neg) if (neg)
root = -Int32(root); root = -int32_t(root);
return (Int32)root; return (int32_t)root;
} }

79
Sources/Plasma/CoreLib/hsWide.h

@ -42,14 +42,14 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef hsWideDefined #ifndef hsWideDefined
#define hsWideDefined #define hsWideDefined
#include "hsTypes.h" #include "HeadSpin.h"
struct hsWide { struct hsWide {
Int32 fHi; int32_t fHi;
UInt32 fLo; uint32_t fLo;
hsWide* Set(Int32 lo) { fLo = lo; if (lo < 0) fHi = -1L; else fHi = 0; return this; } hsWide* Set(int32_t lo) { fLo = lo; if (lo < 0) fHi = -1L; else fHi = 0; return this; }
hsWide* Set(Int32 hi, UInt32 lo) { fHi = hi; fLo = lo; return this; } hsWide* Set(int32_t hi, uint32_t lo) { fHi = hi; fLo = lo; return this; }
inline hsBool IsNeg() const { return fHi < 0; } inline hsBool IsNeg() const { return fHi < 0; }
inline hsBool IsPos() const { return fHi > 0 || (fHi == 0 && fLo != 0); } inline hsBool IsPos() const { return fHi > 0 || (fHi == 0 && fLo != 0); }
@ -65,37 +65,35 @@ struct hsWide {
hsBool operator>=(const hsWide& b) const { return !(*this < b); } hsBool operator>=(const hsWide& b) const { return !(*this < b); }
inline hsWide* Negate(); inline hsWide* Negate();
inline hsWide* Add(Int32 scaler); inline hsWide* Add(int32_t scaler);
inline hsWide* Add(const hsWide* a); inline hsWide* Add(const hsWide* a);
inline hsWide* Sub(const hsWide* a); inline hsWide* Sub(const hsWide* a);
inline hsWide* ShiftLeft(unsigned shift); inline hsWide* ShiftLeft(unsigned shift);
inline hsWide* ShiftRight(unsigned shift); inline hsWide* ShiftRight(unsigned shift);
inline hsWide* RoundRight(unsigned shift); inline hsWide* RoundRight(unsigned shift);
inline Int32 AsLong() const; // return bits 31-0, checking for over/under flow inline int32_t AsLong() const; // return bits 31-0, checking for over/under flow
inline hsFixed AsFixed() const; // return bits 47-16, checking for over/under flow inline int32_t AsFixed() const; // return bits 47-16, checking for over/under flow
inline hsFract AsFract() const; // return bits 61-30, checking for over/under flow inline int32_t AsFract() const; // return bits 61-30, checking for over/under flow
hsWide* Mul(Int32 a); // this updates the wide hsWide* Mul(int32_t a); // this updates the wide
hsWide* Mul(Int32 a, Int32 b); // this sets the wide hsWide* Mul(int32_t a, int32_t b); // this sets the wide
hsWide* Div(Int32 denom); // this updates the wide hsWide* Div(int32_t denom); // this updates the wide
hsWide* Div(const hsWide* denom); // this updates the wide hsWide* Div(const hsWide* denom); // this updates the wide
hsFixed FixDiv(const hsWide* denom) const; int32_t FixDiv(const hsWide* denom) const;
hsFract FracDiv(const hsWide* denom) const; int32_t FracDiv(const hsWide* denom) const;
Int32 Sqrt() const; int32_t Sqrt() const;
Int32 CubeRoot() const; int32_t CubeRoot() const;
#if HS_CAN_USE_FLOAT
double AsDouble() const { return fHi * double(65536) * double(65536) + fLo; } double AsDouble() const { return fHi * double(65536) * double(65536) + fLo; }
hsWide* Set(double d) hsWide* Set(double d)
{ {
Int32 hi = Int32(d / double(65536) / double(65536)); int32_t hi = int32_t(d / double(65536) / double(65536));
Int32 lo = Int32(d - double(hi)); int32_t lo = int32_t(d - double(hi));
return Set(hi, lo); return Set(hi, lo);
} }
#endif
}; };
@ -104,22 +102,17 @@ const hsWide kNegInfinity64 = { kNegInfinity32, 0 };
/////////////////////// Inline implementations /////////////////////// /////////////////////// Inline implementations ///////////////////////
#define TOP2BITS(n) (UInt32(n) >> 30) #define TOP2BITS(n) (uint32_t(n) >> 30)
#define TOP3BITS(n) (UInt32(n) >> 29) #define TOP3BITS(n) (uint32_t(n) >> 29)
#if HS_PIN_MATH_OVERFLOW && HS_DEBUG_MATH_OVERFLOW
#define hsSignalMathOverflow() hsDebugMessage("Math overflow", 0)
#define hsSignalMathUnderflow() hsDebugMessage("Math underflow", 0)
#else
#define hsSignalMathOverflow() #define hsSignalMathOverflow()
#define hsSignalMathUnderflow() #define hsSignalMathUnderflow()
#endif
#define WIDE_ISNEG(hi, lo) (Int32(hi) < 0) #define WIDE_ISNEG(hi, lo) (int32_t(hi) < 0)
#define WIDE_LESSTHAN(hi, lo, hi2, lo2) ((hi) < (hi2) || (hi) == (hi2) && (lo) < (lo2)) #define WIDE_LESSTHAN(hi, lo, hi2, lo2) ((hi) < (hi2) || (hi) == (hi2) && (lo) < (lo2))
#define WIDE_SHIFTLEFT(outH, outL, inH, inL, shift) do { (outH) = ((inH) << (shift)) | ((inL) >> (32 - (shift))); (outL) = (inL) << (shift); } while (0) #define WIDE_SHIFTLEFT(outH, outL, inH, inL, shift) do { (outH) = ((inH) << (shift)) | ((inL) >> (32 - (shift))); (outL) = (inL) << (shift); } while (0)
#define WIDE_NEGATE(hi, lo) do { (hi) = ~(hi); if (((lo) = -Int32(lo)) == 0) (hi) += 1; } while (0) #define WIDE_NEGATE(hi, lo) do { (hi) = ~(hi); if (((lo) = -int32_t(lo)) == 0) (hi) += 1; } while (0)
#define WIDE_ADDPOS(hi, lo, scaler) do { UInt32 tmp = (lo) + (scaler); if (tmp < (lo)) (hi) += 1; (lo) = tmp; } while (0) #define WIDE_ADDPOS(hi, lo, scaler) do { uint32_t tmp = (lo) + (scaler); if (tmp < (lo)) (hi) += 1; (lo) = tmp; } while (0)
#define WIDE_SUBWIDE(hi, lo, subhi, sublo) do { (hi) -= (subhi); if ((lo) < (sublo)) (hi) -= 1; (lo) -= (sublo); } while (0) #define WIDE_SUBWIDE(hi, lo, subhi, sublo) do { (hi) -= (subhi); if ((lo) < (sublo)) (hi) -= 1; (lo) -= (sublo); } while (0)
/////////////////////// Inline implementations /////////////////////// /////////////////////// Inline implementations ///////////////////////
@ -131,13 +124,13 @@ inline hsWide* hsWide::Negate()
return this; return this;
} }
inline hsWide* hsWide::Add(Int32 scaler) inline hsWide* hsWide::Add(int32_t scaler)
{ {
if (scaler >= 0) if (scaler >= 0)
WIDE_ADDPOS(fHi, fLo, scaler); WIDE_ADDPOS(fHi, fLo, scaler);
else else
{ scaler = -scaler; { scaler = -scaler;
if (fLo < UInt32(scaler)) if (fLo < uint32_t(scaler))
fHi--; fHi--;
fLo -= scaler; fLo -= scaler;
} }
@ -147,7 +140,7 @@ inline hsWide* hsWide::Add(Int32 scaler)
inline hsWide* hsWide::Add(const hsWide* a) inline hsWide* hsWide::Add(const hsWide* a)
{ {
UInt32 newLo = fLo + a->fLo; uint32_t newLo = fLo + a->fLo;
fHi += a->fHi; fHi += a->fHi;
if (newLo < (fLo | a->fLo)) if (newLo < (fLo | a->fLo))
@ -184,34 +177,24 @@ inline hsWide* hsWide::RoundRight(unsigned shift)
return this->Add(1L << (shift - 1))->ShiftRight(shift); return this->Add(1L << (shift - 1))->ShiftRight(shift);
} }
inline Int32 hsWide::AsLong() const inline int32_t hsWide::AsLong() const
{ {
#if HS_PIN_MATH_OVERFLOW return (int32_t)fLo;
if (fHi > 0 || (fHi == 0 && (Int32)fLo < 0))
{ hsSignalMathOverflow();
return kPosInfinity32;
}
if (fHi < -1L || (fHi == -1L && (Int32)fLo >= 0))
{ hsSignalMathOverflow();
return kNegInfinity32;
}
#endif
return (Int32)fLo;
} }
inline hsBool hsWide::IsWide() const inline hsBool hsWide::IsWide() const
{ {
return (fHi > 0 || (fHi == 0 && (Int32)fLo < 0)) || (fHi < -1L || (fHi == -1L && (Int32)fLo >= 0)); return (fHi > 0 || (fHi == 0 && (int32_t)fLo < 0)) || (fHi < -1L || (fHi == -1L && (int32_t)fLo >= 0));
} }
inline hsFixed hsWide::AsFixed() const inline int32_t hsWide::AsFixed() const
{ {
hsWide tmp = *this; hsWide tmp = *this;
return tmp.RoundRight(16)->AsLong(); return tmp.RoundRight(16)->AsLong();
} }
inline hsFract hsWide::AsFract() const inline int32_t hsWide::AsFract() const
{ {
hsWide tmp = *this; hsWide tmp = *this;

54
Sources/Plasma/CoreLib/hsWindowHndl.h

@ -1,54 +0,0 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#ifndef HSWINDOWHNDL_inc
#define HSWINDOWHNDL_inc
#include "HeadSpin.h"
// decide what hsWindowHndl is
#if HS_BUILD_FOR_WIN32
typedef struct HWND__ * hsWindowHndl;
#elif HS_BUILD_FOR_UNIX
typedef int* hsWindowHndl;
#endif
#endif

35
Sources/Plasma/CoreLib/hsWindows.h

@ -39,16 +39,35 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "hsConfig.h"
#if HS_BUILD_FOR_WIN32 #ifdef _HSWINDOWS_H
# error "Do not include hsWindows.h directly--use HeadSpin.h"
#endif // _HSWINDOWS_H
#define _HSWINDOWS_H
#ifndef __AFX_H__ // MFC apps won't let us include windows from here. =( #if HS_BUILD_FOR_WIN32
#ifndef MAXPLUGINCODE
#include <WinSock2.h>
#endif // MAXPLUGINCODE
#include <Windows.h> // 4244: Conversion
#endif // __AFX_H__ // 4305: Truncation
// 4503: 'identifier' : decorated name length exceeded, name was truncated
// 4018: signed/unsigned mismatch
// 4786: 255 character debug limit
// 4284: STL template defined operator-> for a class it doesn't make sense for (int, etc)
// 4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
# ifdef _MSC_VER
# pragma warning( disable : 4305 4503 4018 4786 4284 4800)
# endif // _MSC_VER
// Windows.h includes winsock.h (winsocks 1), so we need to manually include winsock2
// and tell Windows.h to only bring in modern headers
# ifndef MAXPLUGINCODE
# include <WinSock2.h>
# include <ws2tcpip.h>
# endif // MAXPLUGINCODE
# define WIN32_LEAN_AND_MEAN
# include <Windows.h>
typedef HWND hsWindowHndl;
#else
typedef int32_t* hsWindowHndl;
#endif // HS_BUILD_FOR_WIN32 #endif // HS_BUILD_FOR_WIN32

2
Sources/Plasma/CoreLib/pcSmallRect.cpp

@ -41,7 +41,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// // // //
// pcSmallRect - A tiny Int16-based 2D rectangle class // // pcSmallRect - A tiny int16_t-based 2D rectangle class //
// // // //
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

16
Sources/Plasma/CoreLib/pcSmallRect.h

@ -41,7 +41,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// // // //
// pcSmallRect - A tiny Int16-based 2D rectangle class // // pcSmallRect - A tiny int16_t-based 2D rectangle class //
// // // //
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -53,27 +53,27 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
#ifndef _pcSmallRect_h #ifndef _pcSmallRect_h
#define _pcSmallRect_h #define _pcSmallRect_h
#include "hsTypes.h" #include "HeadSpin.h"
class hsStream; class hsStream;
class pcSmallRect class pcSmallRect
{ {
public: public:
Int16 fX, fY, fWidth, fHeight; int16_t fX, fY, fWidth, fHeight;
pcSmallRect() { Empty(); } pcSmallRect() { Empty(); }
pcSmallRect( Int16 x, Int16 y, Int16 w, Int16 h ) { Set( x, y, w, h ); } pcSmallRect( int16_t x, int16_t y, int16_t w, int16_t h ) { Set( x, y, w, h ); }
void Set( Int16 x, Int16 y, Int16 w, Int16 h ) { fX = x; fY = y; fWidth = w; fHeight = h; } void Set( int16_t x, int16_t y, int16_t w, int16_t h ) { fX = x; fY = y; fWidth = w; fHeight = h; }
void Empty( void ) { fX = fY = fWidth = fHeight = 0; } void Empty( void ) { fX = fY = fWidth = fHeight = 0; }
Int16 GetRight( void ) const { return fX + fWidth; } int16_t GetRight( void ) const { return fX + fWidth; }
Int16 GetBottom( void ) const { return fY + fHeight; } int16_t GetBottom( void ) const { return fY + fHeight; }
void Read( hsStream *s ); void Read( hsStream *s );
void Write( hsStream *s ); void Write( hsStream *s );
hsBool Contains( Int16 x, Int16 y ) { if( x >= fX && x <= fX + fWidth && y >= fY && y <= fY + fHeight ) return true; return false; } hsBool Contains( int16_t x, int16_t y ) { if( x >= fX && x <= fX + fWidth && y >= fY && y <= fY + fHeight ) return true; return false; }
}; };

4
Sources/Plasma/CoreLib/plGeneric.cpp

@ -39,7 +39,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
Mead, WA 99021 Mead, WA 99021
*==LICENSE==*/ *==LICENSE==*/
#include "hsUtils.h"
#include "plGeneric.h" #include "plGeneric.h"
plGeneric::plGeneric(): fType(kNull), fBoolVal(false), fIntVal(0), fFloatVal(0.0) {} plGeneric::plGeneric(): fType(kNull), fBoolVal(false), fIntVal(0), fFloatVal(0.0) {}
@ -141,7 +141,7 @@ plGeneric& plGeneric::operator=(const std::wstring& val)
int plGeneric::Write(hsStream* stream) int plGeneric::Write(hsStream* stream)
{ {
stream->WriteByte((UInt8)fType); stream->WriteByte((uint8_t)fType);
switch (fType) switch (fType)
{ {

22
Sources/Plasma/CoreLib/plLoadMask.cpp

@ -40,7 +40,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com
*==LICENSE==*/ *==LICENSE==*/
#include "hsTypes.h" #include "HeadSpin.h"
#include "plLoadMask.h" #include "plLoadMask.h"
#include "hsStream.h" #include "hsStream.h"
#include "hsTemplates.h" #include "hsTemplates.h"
@ -75,13 +75,13 @@ void plQuality::SetCapability(int c)
const plLoadMask plLoadMask::kAlways; const plLoadMask plLoadMask::kAlways;
UInt8 plLoadMask::fGlobalQuality = UInt8(1); uint8_t plLoadMask::fGlobalQuality = uint8_t(1);
UInt8 plLoadMask::fGlobalCapability = UInt8(0); uint8_t plLoadMask::fGlobalCapability = uint8_t(0);
void plLoadMask::Read(hsStream* s) void plLoadMask::Read(hsStream* s)
{ {
// read as packed byte // read as packed byte
UInt8 qc; uint8_t qc;
s->LogReadLE(&qc,"Quality|Capabilty"); s->LogReadLE(&qc,"Quality|Capabilty");
fQuality[0] = (qc & 0xf0) >> 4; fQuality[0] = (qc & 0xf0) >> 4;
@ -95,13 +95,13 @@ void plLoadMask::Read(hsStream* s)
void plLoadMask::Write(hsStream* s) const void plLoadMask::Write(hsStream* s) const
{ {
// write packed into 1 byte // write packed into 1 byte
UInt8 qc = (fQuality[0]<<4) | (fQuality[1] & 0xf); uint8_t qc = (fQuality[0]<<4) | (fQuality[1] & 0xf);
s->WriteLE(qc); s->WriteLE(qc);
} }
UInt32 plLoadMask::ValidateReps(int num, const int quals[], const int caps[]) uint32_t plLoadMask::ValidateReps(int num, const int quals[], const int caps[])
{ {
UInt32 retVal = 0; uint32_t retVal = 0;
int i; int i;
for( i = 1; i < num; i++ ) for( i = 1; i < num; i++ )
{ {
@ -118,9 +118,9 @@ UInt32 plLoadMask::ValidateReps(int num, const int quals[], const int caps[])
return retVal; return retVal;
} }
UInt32 plLoadMask::ValidateMasks(int num, plLoadMask masks[]) uint32_t plLoadMask::ValidateMasks(int num, plLoadMask masks[])
{ {
UInt32 retVal = 0; uint32_t retVal = 0;
int i; int i;
for( i = 0; i < num; i++ ) for( i = 0; i < num; i++ )
{ {
@ -160,12 +160,12 @@ hsBool plLoadMask::ComputeRepMasks(
{ {
// Q starts off the bits higher than or equal to 1 << qual. // Q starts off the bits higher than or equal to 1 << qual.
// I.e. we just turned off all lower quality bits. // I.e. we just turned off all lower quality bits.
UInt8 q = ~( (1 << quals[i]) - 1 ); uint8_t q = ~( (1 << quals[i]) - 1 );
// For this cap level, if we require higher caps, // For this cap level, if we require higher caps,
// turn off our quality (i.e. we won't load at this // turn off our quality (i.e. we won't load at this
// cap for any quality setting. // cap for any quality setting.
UInt8 c = caps[i] > kMaxCap ? kMaxCap : caps[i]; uint8_t c = caps[i] > kMaxCap ? kMaxCap : caps[i];
if( c > k ) if( c > k )
q = 0; q = 0;

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save