2
3
mirror of https://foundry.openuru.org/gitblit/r/CWE-ou-minkata.git synced 2025-07-14 02:27:40 -04:00

CWE Directory Reorganization

Rearrange directory structure of CWE to be loosely equivalent to
the H'uru Plasma repository.

Part 1: Movement of directories and files.
This commit is contained in:
rarified
2021-05-15 12:49:46 -06:00
parent c3f4a640a3
commit 96903e8dca
4002 changed files with 159 additions and 644 deletions

View File

@ -0,0 +1,41 @@
/*==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==*/

View File

@ -0,0 +1,389 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Addr.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
// hardcoded byte ordering -- Intel only
#ifdef _M_IX86
const unsigned kHostClassALoopbackAddr = 0x7f000001; // 127.0.0.1
const unsigned kHostClassALoopbackMask = 0x00ffffff;
const unsigned kNetClassALoopbackAddr = 0x0100007f; // 127.0.0.1
const unsigned kNetClassALoopbackMask = 0xffffff00;
const unsigned kHostClassANatAddr = 0x000000a0; // 10.0.0.0 - 10.255.255.255
const unsigned kHostClassANatMask = 0x000000ff;
const unsigned kNetClassANatAddr = 0x0a000000; // 10.0.0.0 - 10.255.255.255
const unsigned kNetClassANatMask = 0xff000000;
const unsigned kHostClassBNetAddr = 0x000010ac; // 172.16.0.0 - 172.31.255.255
const unsigned kHostClassBNetMask = 0x0000f0ff;
const unsigned kNetClassBNetAddr = 0xac100000; // 172.16.0.0 - 172.31.255.255
const unsigned kNetClassBNetMask = 0xfff00000;
const unsigned kHostClassCNatAddr = 0x0000a8c0; // 192.168.0.0 - 192.168.255.255
const unsigned kHostClassCNatMask = 0x0000ffff;
const unsigned kNetClassCNatAddr = 0xc0a80000; // 192.168.0.0 - 192.168.255.255
const unsigned kNetClassCNatMask = 0xffff0000;
#else
#error "Must implement for this architecture"
#endif // ifdef _M_IX86
/*****************************************************************************
*
* Internal functions
*
***/
//===========================================================================
// Address sort order:
// (highest)
// externally visible address
// 10.0.0.0 - 10.255.255.255
// 172.16.0.0 - 172.31.255.255
// 192.168.0.0 - 192.168.255.255
// 127.0.0.0 - 127.0.0.255
// (lowest)
static int NetAddressNodeSortValueNetOrder (NetAddressNode addr) {
REF(NetAddressNodeSortValueNetOrder);
// Loopback addresses
if ((addr & kNetClassALoopbackMask) == (kNetClassALoopbackAddr & kNetClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kNetClassCNatMask) == (kNetClassCNatAddr & kNetClassCNatMask))
return 3;
if ((addr & kNetClassBNetMask) == (kNetClassBNetAddr & kNetClassBNetMask))
return 2;
if ((addr & kNetClassANatMask) == (kNetClassANatAddr & kNetClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static int NetAddressNodeSortValueHostOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kHostClassALoopbackMask) == (kHostClassALoopbackAddr & kHostClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kHostClassCNatMask) == (kHostClassCNatAddr & kHostClassCNatMask))
return 3;
if ((addr & kHostClassBNetMask) == (kHostClassBNetAddr & kHostClassBNetMask))
return 2;
if ((addr & kHostClassANatMask) == (kHostClassANatAddr & kHostClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static NetAddressNode NodeFromString (const wchar * string[]) {
// skip leading whitespace
const wchar * str = *string;
while (iswspace(*str))
++str;
// This function handles partial ip addresses (61.33)
// as well as full dotted quads. The address can be
// terminated by whitespace or ':' as well as '\0'
byte data[4];
* (dword *) data = 0;
for (unsigned i = sizeof(data); i--; ) {
if (!iswdigit(*str))
return (unsigned)-1;
unsigned value = StrToUnsigned(str, &str, 10);
if (value >= 256)
return (unsigned)-1;
data[i] = (byte) value;
if (!*str || (*str == ':') || iswspace(*str))
break;
static const wchar s_separator[] = L"\0...";
if (*str++ != s_separator[i])
return (unsigned)-1;
}
*string = str;
return * (NetAddressNode *) &data[0];
}
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
int d = i1.sin_addr.S_un.S_addr - i2.sin_addr.S_un.S_addr;
return d ? d : i1.sin_port - i2.sin_port;
}
//===========================================================================
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
return i1.sin_addr.S_un.S_addr == i2.sin_addr.S_un.S_addr;
}
//===========================================================================
unsigned NetAddressHash (const NetAddress & addr) {
// by using only the node number as the hash value, users can safely use
// hash value to find addresses by either using either "SameSystem" or "Equal"
const sockaddr_in & iAddr = * (const sockaddr_in *) &addr;
return iAddr.sin_addr.S_un.S_addr;
}
//===========================================================================
void NetAddressToString (
const NetAddress & addr,
wchar * str,
unsigned chars,
ENetAddressFormat format
) {
ASSERT(str);
static const wchar * s_fmts[] = {
L"%S", // kNetAddressFormatNodeNumber
L"%S:%u", // kNetAddressFormatAll
};
ASSERT(format < arrsize(s_fmts));
const sockaddr_in & inetaddr = * (const sockaddr_in *) &addr;
StrPrintf(
str,
chars,
s_fmts[format],
inet_ntoa(inetaddr.sin_addr),
ntohs(inetaddr.sin_port)
);
}
//===========================================================================
bool NetAddressFromString (NetAddress * addr, const wchar str[], unsigned defaultPort) {
ASSERT(addr);
ASSERT(str);
// NetAddress is bigger than sockaddr_in so start by zeroing the whole thing
ZEROPTR(addr);
for (;;) {
NetAddressNode node = NodeFromString(&str);
if (node == (unsigned)-1)
break;
if (*str == L':')
defaultPort = StrToUnsigned(str + 1, nil, 10);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_port = htons((word) defaultPort);
inetaddr->sin_addr.S_un.S_addr = htonl(node);
// inetaddr->sin_zero already zeroed
return true;
}
// address already zeroed
return false;
}
//===========================================================================
unsigned NetAddressGetPort (
const NetAddress & addr
) {
return ntohs(((sockaddr_in *) &addr)->sin_port);
}
//===========================================================================
void NetAddressSetPort (
unsigned port,
NetAddress * addr
) {
((sockaddr_in *) addr)->sin_port = htons((word) port);
}
//============================================================================
NetAddressNode NetAddressGetNode (const NetAddress & addr) {
return ntohl(((const sockaddr_in *) &addr)->sin_addr.S_un.S_addr);
}
//===========================================================================
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
) {
ZEROPTR(addr);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_addr.S_un.S_addr = htonl(node);
inetaddr->sin_port = htons((word) port);
}
//===========================================================================
void NetAddressNodeToString (
NetAddressNode node,
wchar * str,
unsigned chars
) {
in_addr addr;
addr.S_un.S_addr = htonl(node);
StrPrintf(str, chars, L"%S", inet_ntoa(addr));
}
//===========================================================================
NetAddressNode NetAddressNodeFromString (
const wchar string[],
const wchar * endPtr[]
) {
if (!endPtr)
endPtr = &string;
*endPtr = string;
return NodeFromString(endPtr);
}
//===========================================================================
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
) {
NetAddressFromNode(
kHostClassALoopbackAddr,
port,
addr
);
}
//===========================================================================
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
) {
ASSERT(count);
ASSERT(addresses);
for (;;) {
// Get local computer name
char name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = arrsize(name);
if (!GetComputerName(name, &size))
StrCopy(name, "localhost", arrsize(name));
// Get IPv4 addresses for local system
const struct hostent * host = gethostbyname(name);
if (!host || !host->h_name)
break;
host = gethostbyname(host->h_name);
if (!host)
break;
if (host->h_length != sizeof(dword))
break;
// Count total number of addresses
unsigned found = 0;
const dword ** addr = (const dword **) host->h_addr_list;
for (; *addr; ++addr)
++found;
if (!found)
break;
// Create a buffer to sort the addresses
NetAddressNode * dst;
if (found > count)
dst = ALLOCA(NetAddressNode, found);
else
dst = addresses;
// Fill address buffer
const dword * src = * (const dword **) host->h_addr_list;
for (unsigned index = 0; index < found; ++index)
dst[index] = ntohl(src[index]);
// Sort addresses by priority
QSORT(
NetAddressNode,
dst,
found,
NetAddressNodeSortValueHostOrder(elem1) - NetAddressNodeSortValueHostOrder(elem2)
);
// Return the number of addresses the user actually requested
if (found > count) {
for (unsigned index = 0; index < count; ++index)
addresses[index] = dst[index];
return count;
}
return found;
}
// Initialize with a valid value
addresses[0] = kHostClassALoopbackAddr;
return 1;
}

View File

@ -0,0 +1,57 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Dll.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/

View File

@ -0,0 +1,223 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Misc.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
static MEMORYSTATUSEX s_memstatus;
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
const wchar * AppGetCommandLine () {
return GetCommandLineW();
}
//============================================================================
void MachineGetName (wchar *computerName, unsigned int length) {
DWORD len = length;
GetComputerNameW(computerName, &len);
}
/*****************************************************************************
*
* System status
*
***/
//============================================================================
void MemoryGetStatus (MemoryStatus * status) {
MEMORYSTATUSEX mem;
mem.dwLength = sizeof(mem);
GlobalMemoryStatusEx(&mem);
const qword BYTES_PER_MB = 1024 * 1024;
status->totalPhysMB = unsigned(mem.ullTotalPhys / BYTES_PER_MB);
status->availPhysMB = unsigned(mem.ullAvailPhys / BYTES_PER_MB);
status->totalPageFileMB = unsigned(mem.ullTotalPageFile / BYTES_PER_MB);
status->availPageFileMB = unsigned(mem.ullAvailPageFile / BYTES_PER_MB);
status->totalVirtualMB = unsigned(mem.ullTotalVirtual / BYTES_PER_MB);
status->availVirtualMB = unsigned(mem.ullAvailVirtual / BYTES_PER_MB);
status->memoryLoad = mem.dwMemoryLoad;
}
//============================================================================
void DiskGetStatus (ARRAY(DiskStatus) * disks) {
for (;;) {
DWORD length = GetLogicalDriveStrings(0, NULL);
if (!length || length > 2048)
break;
wchar * buffer = ALLOCA(wchar, length + 1);
if (!GetLogicalDriveStringsW(length, buffer))
break;
for (; *buffer; buffer += StrLen(buffer) + 1) {
UINT driveType = GetDriveTypeW(buffer);
if (driveType != DRIVE_FIXED)
continue;
ULARGE_INTEGER freeBytes;
ULARGE_INTEGER totalBytes;
if (!GetDiskFreeSpaceExW(buffer, &freeBytes, &totalBytes, NULL))
continue;
DiskStatus status;
StrCopy(status.name, buffer, arrsize(status.name));
const qword BYTES_PER_MB = 1024 * 1024;
status.totalSpaceMB = unsigned(totalBytes.QuadPart / BYTES_PER_MB);
status.freeSpaceMB = unsigned(freeBytes.QuadPart / BYTES_PER_MB);
disks->Add(status);
}
break;
}
}
//============================================================================
// Loosely taken from MS's cpuid code sample
void CpuGetInfo (
word * cpuCaps,
dword * cpuVendor,
word * cpuSignature
) {
dword signature = 0;
dword extended = 0;
dword flags[2] = { 0, 0 };
cpuVendor[0] = 0;
_asm {
// Detect if cpuid instruction is supported by attempting
// to change the ID bit of EFLAGS
pushfd
pop eax // get EFLAGS
mov ecx, eax // store copy of original EFLAGS
xor eax, 0x200000 // flip ID bit
push eax
popfd // replace EFLAGS
pushfd // get EFLAGS
pop eax
xor eax, ecx
je DONE
// Get processor id (GenuineIntel, AuthenticAMD, etc)
xor eax, eax
cpuid
mov edi, cpuVendor
mov [edi + 0], ebx
mov [edi + 4], edx
mov [edi + 8], ecx
// Check if capability flags are supported
cmp eax, 1
jl DONE
// Get processor capability flags and signature
mov eax, 1
cpuid
mov signature, eax
mov [flags + 0], edx
mov [flags + 4], ecx
// Check for extended capabilities
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jl DONE
// Get extended capabilities
mov eax, 0x80000001
cpuid
mov extended, edx
DONE:
}
// Decode capability flags
const static struct CpuCap {
word cpuFlag;
byte field;
byte bit;
} s_caps[] = {
// feature field bit
// ------- ----- ---
{ kCpuCapCmov, 0, 15 },
{ kCpuCapEst, 1, 7 },
{ kCpuCapHtt, 0, 28 },
{ kCpuCapMmx, 0, 23 },
{ kCpuCapPsn, 0, 18 },
{ kCpuCapSse, 0, 25 },
{ kCpuCapSse2, 0, 26 },
{ kCpuCapSse3, 1, 0 },
{ kCpuCapTsc, 0, 4 },
};
for (unsigned i = 0; i < arrsize(s_caps); ++i) {
const CpuCap & cap = s_caps[i];
if (flags[cap.field] & (1 << cap.bit))
*cpuCaps |= cap.cpuFlag;
}
// Copy signature
*cpuSignature = word(signature & 0xfff);
// If this is an AMD CPU, check for 3DNow support
const char * vendorAmd = "AuthenticAMD";
if (!MemCmp(vendorAmd, cpuVendor, 12)) {
if (extended & (1 << 31))
*cpuCaps |= kCpuCap3dNow;
}
}

View File

@ -0,0 +1,861 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Path.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local functions
*
***/
// make sure our definition is at least as big as the compiler's definition
COMPILER_ASSERT(MAX_PATH >= _MAX_PATH);
//===========================================================================
static inline bool IsSlash (wchar c) {
return (c == L'\\') || (c == L'/');
}
//===========================================================================
static inline wchar ConvertSlash (wchar c) {
return c != L'/' ? c : L'\\';
}
//===========================================================================
static inline bool IsUncPath (const wchar path[]) {
return IsSlash(path[0]) && IsSlash(path[1]);
}
//===========================================================================
static const wchar * SkipUncDrive (const wchar path[]) {
// UNC drive: "//server/share"
// skip over leading "//"
path += 2;
// scan forward to end of server name
for (;; ++path) {
if (!*path)
return path;
if (IsSlash(*path))
break;
}
// skip over '/'
++path;
// skip over share name
for (;; ++path) {
if (!*path)
return path;
if (IsSlash(*path))
return path;
}
}
//===========================================================================
static wchar * PathSkipOverSeparator (wchar * path) {
for (; *path; ++path) {
if (IsSlash(*path))
return path + 1;
}
return path;
}
//===========================================================================
static unsigned CommonPrefixLength (
const wchar src1[],
const wchar src2[]
) {
ASSERT(src1);
ASSERT(src2);
wchar const * const base = src1;
const wchar * common = nil;
for (;;) {
// Are the next components equal in length?
const wchar * next1 = PathSkipOverSeparator(const_cast<wchar *>(src1));
const wchar * next2 = PathSkipOverSeparator(const_cast<wchar *>(src2));
const int componentLen = next1 - src1;
if (componentLen != (next2 - src2))
break;
// Are the next components equal in value?
if (!StrCmpI(src1, src2, componentLen))
common = next1;
else
break;
if (!*next1)
break;
src1 = next1 + 1;
if (!*next2)
break;
src2 = next2 + 1;
}
if (!common)
return 0;
// Compute length of common subchunk;
// if it is "C:" convert it to "C:\"
unsigned commonLen = common - base;
if ((commonLen == 2) && (base[1] == L':'))
++commonLen;
return commonLen;
}
//===========================================================================
static void GetProgramName (
void * instance,
wchar * dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
if (!GetModuleFileNameW((HINSTANCE) instance, dst, dstChars)) {
ErrorAssert(__LINE__, __FILE__, "GetModuleName failed");
*dst = 0;
}
}
/****************************************************************************
*
* Exports
*
***/
//===========================================================================
void PathGetModuleName (
wchar * dst,
unsigned dstChars
) {
GetProgramName(ModuleGetInstance(), dst, dstChars);
}
//===========================================================================
void PathGetProgramName (
wchar * dst,
unsigned dstChars
) {
GetProgramName(nil, dst, dstChars);
}
//===========================================================================
bool PathFromString (
wchar * dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
for (;;) {
// enable src and dst to be the same buffer
wchar temp[MAX_PATH];
if (dst == src) {
StrCopy(temp, src, arrsize(temp));
src = temp;
}
DWORD const result = GetFullPathNameW(src, dstChars, dst, 0);
if (!result)
break;
if (dstChars < result)
break;
if (!dst[0])
break;
return true;
}
*dst = 0;
return false;
}
//===========================================================================
bool PathFromString (
wchar * dst, // ASSERT(dst);
const wchar src[], // ASSERT(src);
unsigned dstChars, // ASSERT(dstChars);
const wchar baseDir[] // ASSERT(baseDir);
) {
ASSERT(baseDir);
ASSERT(dstChars);
// Save current directory
wchar curr[MAX_PATH];
PathGetCurrentDirectory(curr, arrsize(curr));
// Perform string conversion from specified directory
bool result;
if (0 != (result = PathSetCurrentDirectory(baseDir)))
result = PathFromString(dst, src, dstChars);
else
*dst = 0;
// Restore directory
PathSetCurrentDirectory(curr);
return result;
}
//===========================================================================
// this function was originally derived from _tsplitpath in the MSVCRT library,
// but has been updated to support UNC paths and to avoid blasting off the end
// of the buffers.
void PathSplitPath (
const wchar path[],
wchar * drive,
wchar * dir,
wchar * fname,
wchar * ext
) {
ASSERT(path);
ASSERT(path != drive);
ASSERT(path != dir);
ASSERT(path != fname);
ASSERT(path != ext);
// check for UNC path
if (IsUncPath(path)) {
const wchar * pathStart = path;
path = SkipUncDrive(path);
if (drive)
StrCopy(drive, pathStart, min(MAX_DRIVE, path - pathStart + 1));
}
// regular DOS path
else if (path[0] && (path[1] == L':')) {
if (drive) {
ASSERT(MAX_DRIVE >= 3);
drive[0] = path[0];
drive[1] = L':';
drive[2] = L'\0';
}
path += 2; // skip over 'C' ':'
}
else if (drive) {
*drive = 0;
}
// extract path string, if any. Path now points to the first character
// of the path, if any, or the filename or extension, if no path was
// specified. Scan ahead for the last occurence, if any, of a '/' or
// '\' path separator character. If none is found, there is no path.
// We will also note the last '.' character found, if any, to aid in
// handling the extension.
const wchar *last_slash = nil, *last_dot = nil, *p = path;
for (; *p; p++) {
if (IsSlash(*p))
last_slash = p + 1; // point to one beyond for later copy
else if (*p == L'.')
last_dot = p;
}
if (last_slash) {
if (dir)
StrCopy(dir, path, min(MAX_DIR, last_slash - path + 1));
path = last_slash;
}
else if (dir) {
*dir = 0;
}
// extract file name and extension, if any. Path now points to the
// first character of the file name, if any, or the extension if no
// file name was given. Dot points to the '.' beginning the extension,
// if any.
if (last_dot && (last_dot >= path)) {
if (fname)
StrCopy(fname, path, min(MAX_FNAME, last_dot - path + 1));
if (ext)
StrCopy(ext, last_dot, MAX_EXT);
}
else {
if (fname)
StrCopy(fname, path, MAX_FNAME);
if (ext)
*ext = 0;
}
}
//===========================================================================
void PathMakePath (
wchar * path,
unsigned chars,
const wchar drive[],
const wchar dir[],
const wchar fname[],
const wchar ext[]
) {
ASSERT(path);
ASSERT(path != drive);
ASSERT(path != dir);
ASSERT(path != fname);
ASSERT(path != ext);
// save space for string terminator
if (!chars--)
return;
// copy drive
if (drive && *drive && chars) {
do {
*path++ = ConvertSlash(*drive++);
} while (--chars && *drive);
ASSERT(!IsSlash(path[-1]));
}
// copy directory
if (dir && *dir && chars) {
do {
*path++ = ConvertSlash(*dir++);
} while (--chars && *dir);
// add trailing backslash
if (chars && (path[-1] != '\\')) {
*path++ = L'\\';
chars--;
}
}
// copy filename
if (fname && *fname && chars) {
// skip leading backslash
if (IsSlash(*fname))
++fname;
do {
*path++ = ConvertSlash(*fname++);
} while (--chars && *fname);
}
// copy extension
if (ext && *ext && chars) {
if (*ext != L'.') {
*path++ = L'.';
chars--;
}
while (chars-- && *ext)
*path++ = ConvertSlash(*ext++);
}
// add string terminator
*path = L'\0';
}
//===========================================================================
bool PathMakeRelative (
wchar *dst,
unsigned fromFlags, // 0 or kPathFlagDirectory
const wchar from[],
unsigned toFlags, // 0 or kPathFlagDirectory
const wchar to[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(from);
ASSERT(to);
ASSERT(dstChars);
*dst = 0;
unsigned prefixLength = CommonPrefixLength(from, to);
if (!prefixLength)
return false;
wchar fromBuf[MAX_PATH];
if (fromFlags & kPathFlagDirectory)
StrCopy(fromBuf, from, arrsize(fromBuf));
else
PathRemoveFilename(fromBuf, from, arrsize(fromBuf));
wchar toBuf[MAX_PATH];
if (toFlags & kPathFlagDirectory)
StrCopy(toBuf, to, arrsize(toBuf));
else
PathRemoveFilename(toBuf, to, arrsize(toBuf));
const wchar * curr = fromBuf + prefixLength;
if (*curr) {
// build ..\.. part of the path
if (IsSlash(*curr))
curr++; // skip slash
while (*curr) {
curr = PathSkipOverSeparator(const_cast<wchar *>(curr));
StrPack(dst, *curr ? L"..\\" : L"..", dstChars);
}
}
else {
StrCopy(dst, L".", dstChars);
}
if (to[prefixLength]) {
// deal with root case
if (!IsSlash(to[prefixLength]))
--prefixLength;
ASSERT(IsSlash(to[prefixLength]));
StrPack(dst, to + prefixLength, dstChars);
}
return true;
}
//===========================================================================
bool PathIsRelative (
const wchar src[]
) {
ASSERT(src);
if (!src[0])
return true;
if (IsSlash(src[0]))
return false;
if (src[1] == L':')
return false;
return true;
}
//===========================================================================
const wchar * PathFindFilename (
const wchar path[]
) {
ASSERT(path);
if (IsUncPath(path))
path = SkipUncDrive(path);
const wchar * last_slash = path;
for (const wchar * p = path; *p; p++) {
if ((*p == L'/') || (*p == L'\\') || (*p == L':'))
last_slash = p + 1;
}
return last_slash;
}
//===========================================================================
const wchar * PathFindExtension (
const wchar path[]
) {
ASSERT(path);
const wchar * last_dot = 0;
const wchar * p = PathFindFilename(path);
for ( ; *p; p++) {
if (*p == L'.')
last_dot = p;
}
return last_dot ? last_dot : p;
}
//===========================================================================
void PathGetCurrentDirectory (
wchar * dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
DWORD result = GetCurrentDirectoryW(dstChars, dst);
if (!result || (result >= dstChars)) {
ErrorAssert(__LINE__, __FILE__, "GetDir failed");
*dst = 0;
}
}
//===========================================================================
void PathGetTempDirectory (
wchar * dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
DWORD result = GetTempPathW(dstChars, dst);
if (!result || (result >= dstChars))
StrCopy(dst, L"C:\\temp\\", dstChars);
}
//============================================================================
void PathGetUserDirectory (
wchar * dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
wchar temp[MAX_PATH]; // GetSpecialFolder path requires a buffer of MAX_PATH size or larger
if (SHGetSpecialFolderPathW(NULL, temp, CSIDL_PERSONAL, TRUE) == FALSE)
StrCopy(temp, L"C:\\", arrsize(temp));
// append the product name
PathAddFilename(dst, temp, ProductLongName(), dstChars);
#if BUILD_TYPE != BUILD_TYPE_LIVE
// non-live builds live in a subdir
PathAddFilename(dst, dst, BuildTypeString(), dstChars);
#endif
// ensure it exists
if (!PathDoesDirectoryExist(dst))
PathCreateDirectory(dst, kPathCreateDirFlagEntireTree);
}
//============================================================================
void PathGetLogDirectory (
wchar * dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
PathGetUserDirectory(dst, dstChars);
PathAddFilename(dst, dst, L"Log", dstChars);
if (!PathDoesDirectoryExist(dst))
PathCreateDirectory(dst, kPathCreateDirFlagEntireTree);
}
//============================================================================
void PathGetInitDirectory (
wchar * dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
PathGetUserDirectory(dst, dstChars);
PathAddFilename(dst, dst, L"Init", dstChars);
if (!PathDoesDirectoryExist(dst))
PathCreateDirectory(dst, kPathCreateDirFlagEntireTree);
}
//===========================================================================
bool PathSetCurrentDirectory (
const wchar path[]
) {
ASSERT(path);
return SetCurrentDirectoryW(path) != 0;
}
//===========================================================================
void PathSetProgramDirectory () {
wchar dir[MAX_PATH];
PathGetProgramDirectory(dir, arrsize(dir));
PathSetCurrentDirectory(dir);
}
//===========================================================================
void PathFindFiles (
ARRAY(PathFind) * paths,
const wchar fileSpec[],
unsigned pathFlags
) {
ASSERT(paths);
ASSERT(fileSpec);
HANDLE find;
WIN32_FIND_DATAW fd;
wchar directory[MAX_PATH];
PathRemoveFilename(directory, fileSpec, arrsize(directory));
if (INVALID_HANDLE_VALUE == (find = FindFirstFileW(fileSpec, &fd))) {
DWORD err = GetLastError();
if ((err != ERROR_FILE_NOT_FOUND) && (err != ERROR_PATH_NOT_FOUND))
ASSERTMSG(err, "PathFindFiles failed");
}
else {
// find all the items in the current directory
do {
unsigned fileFlags = 0;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (! (pathFlags & kPathFlagDirectory))
continue;
// don't add "." and ".."
if (fd.cFileName[0] == L'.') {
if (!fd.cFileName[1])
continue;
if (fd.cFileName[1] == L'.' && !fd.cFileName[2])
continue;
}
fileFlags = kPathFlagDirectory;
}
else {
if (! (pathFlags & kPathFlagFile))
continue;
fileFlags = kPathFlagFile;
}
if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
if (! (pathFlags & kPathFlagHidden))
continue;
fileFlags |= kPathFlagHidden;
}
if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
if (! (pathFlags & kPathFlagSystem))
continue;
fileFlags |= kPathFlagSystem;
}
// add this one to the list of found files
PathFind * pf = paths->New();
pf->flags = fileFlags;
pf->fileLength = ((qword) fd.nFileSizeHigh << 32) | fd.nFileSizeLow;
pf->lastWriteTime = * (const qword *) &fd.ftLastWriteTime;
PathAddFilename(pf->name, directory, fd.cFileName, arrsize(pf->name));
} while (FindNextFileW(find, &fd));
FindClose(find);
}
// check for directory recursing
if ((pathFlags & kPathFlagRecurse) || StrStr(fileSpec, L"**")) {
// recurse directories
}
else {
return;
}
wchar dirSpec[MAX_PATH];
PathAddFilename(dirSpec, directory, L"*", arrsize(dirSpec));
if (INVALID_HANDLE_VALUE == (find = FindFirstFileW(dirSpec, &fd))) {
DWORD err = GetLastError();
if ((err != ERROR_FILE_NOT_FOUND) && (err != ERROR_PATH_NOT_FOUND))
ErrorAssert(__LINE__, __FILE__, "PathFindFiles failed");
return;
}
// find all the directories in the current directory
const wchar * spec = PathFindFilename(fileSpec);
do {
if (! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
continue;
}
if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
if (! (pathFlags & kPathFlagHidden))
continue;
}
if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) {
if (! (pathFlags & kPathFlagSystem))
continue;
}
// don't recurse "." and ".."
if (fd.cFileName[0] == L'.') {
if (!fd.cFileName[1])
continue;
if (fd.cFileName[1] == L'.' && !fd.cFileName[2])
continue;
}
// recursively search subdirectory
PathAddFilename(dirSpec, directory, fd.cFileName, arrsize(dirSpec));
PathAddFilename(dirSpec, dirSpec, spec, arrsize(dirSpec));
PathFindFiles(paths, dirSpec, pathFlags);
} while (FindNextFileW(find, &fd));
FindClose(find);
}
//===========================================================================
EPathCreateDirError PathCreateDirectory (const wchar path[], unsigned flags) {
ASSERT(path);
// convert from relative path to full path
wchar dir[MAX_PATH];
if (!PathFromString(dir, path, arrsize(dir))) {
return kPathCreateDirErrInvalidPath;
}
// are we going to build the entire directory tree?
wchar * dirEnd;
if (flags & kPathCreateDirFlagEntireTree) {
dirEnd = dir;
// skip over leading slashes in UNC paths
while (IsSlash(*dirEnd))
++dirEnd;
// skip forward to first directory
dirEnd = PathSkipOverSeparator(dirEnd);
}
// we're only creating the very last entry in the path
else {
dirEnd = dir + StrLen(dir);
}
bool result = true;
for (wchar saveChar = L' '; saveChar; *dirEnd++ = saveChar) {
// find the end of the current directory string and terminate it
dirEnd = PathSkipOverSeparator(dirEnd);
saveChar = *dirEnd;
*dirEnd = 0;
// create the directory and track the result from the last call
result = CreateDirectoryW(dir, (LPSECURITY_ATTRIBUTES) nil);
}
// if we successfully created the directory then we're done
if (result) {
// Avoid check for kPathCreateDirFlagOsError
COMPILER_ASSERT(kPathCreateDirSuccess == NO_ERROR);
return kPathCreateDirSuccess;
}
unsigned error = GetLastError();
switch (error) {
case ERROR_ACCESS_DENIED:
return kPathCreateDirErrAccessDenied;
case ERROR_ALREADY_EXISTS: {
DWORD attrib;
if (0xffffffff == (attrib = GetFileAttributesW(dir)))
return kPathCreateDirErrInvalidPath;
if (! (attrib & FILE_ATTRIBUTE_DIRECTORY))
return kPathCreateDirErrFileWithSameName;
if (flags & kPathCreateDirFlagCreateNew)
return kPathCreateDirErrDirExists;
}
return kPathCreateDirSuccess;
default:
return kPathCreateDirErrInvalidPath;
}
}
//===========================================================================
void PathDeleteDirectory (const wchar path[], unsigned flags) {
ASSERT(path);
// convert from relative path to full path
wchar dir[MAX_PATH];
if (!PathFromString(dir, path, arrsize(dir)))
return;
for (;;) {
// Important: in order to ensure that we don't delete NTFS
// partition links, we must ensure that this is a directory!
dword attributes = GetFileAttributesW(dir);
if (attributes == (dword) -1)
break;
if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
break;
if (attributes & FILE_ATTRIBUTE_REPARSE_POINT)
break;
if (!RemoveDirectoryW(dir))
break;
if ((flags & kPathCreateDirFlagEntireTree) == 0)
break;
wchar * filename = PathFindFilename(dir);
if (!filename)
break;
// Move up one level in the directory hierarchy
unsigned oldLength = StrLen(dir);
while ((filename > dir) && IsSlash(filename[-1]))
--filename;
*filename = 0;
if (oldLength == StrLen(dir))
break;
}
}
//===========================================================================
bool PathDoesFileExist (const wchar fileName[]) {
dword attributes = GetFileAttributesW(fileName);
if (attributes == (dword) -1)
return false;
if (attributes & FILE_ATTRIBUTE_DIRECTORY)
return false;
return true;
}
//============================================================================
bool PathDoesDirectoryExist (const wchar directory[]) {
dword attributes = GetFileAttributesW(directory);
if (attributes == (dword) -1)
return false;
if (attributes & FILE_ATTRIBUTE_DIRECTORY)
return true;
return false;
}
//===========================================================================
bool PathDeleteFile (
const wchar file[]
) {
return DeleteFileW(file) != 0;
}
//===========================================================================
bool PathMoveFile (
const wchar src[],
const wchar dst[]
) {
return MoveFileW(src, dst) != 0;
}
//===========================================================================
bool PathCopyFile (
const wchar src[],
const wchar dst[]
) {
return CopyFileW(src, dst, FALSE) != 0;
}

View File

@ -0,0 +1,98 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Str.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars) {
return StrToAnsi(dest, source, destChars, CP_ACP);
}
//===========================================================================
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars, unsigned codePage) {
ASSERT(destChars != (unsigned)-1);
ASSERT(dest != nil);
int result = WideCharToMultiByte(codePage, 0, source, -1, dest, destChars, nil, nil);
if (result)
return result - 1; // return number of characters not including null terminator
else if (destChars) {
dest[destChars - 1] = 0; // null terminate the destination buffer
return destChars - 1;
}
else
return 0;
}
//===========================================================================
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars) {
return StrToUnicode(dest, source, destChars, CP_ACP);
}
//===========================================================================
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars, unsigned codePage) {
ASSERT(destChars != (unsigned)-1);
ASSERT(dest != nil);
int result = MultiByteToWideChar(codePage, 0, source, -1, dest, destChars);
if (result)
return result - 1; // return number of characters not including null terminator
else if (destChars) {
dest[destChars - 1] = 0; // null terminate the destination buffer
return destChars - 1;
}
else
return 0;
}

View File

@ -0,0 +1,375 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Sync.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Spin lock functions
*
***/
//===========================================================================
static inline void EnterSpinLock (long * spinLock) {
for (;;)
if (*spinLock < 0)
if (!InterlockedIncrement(spinLock))
return;
else
InterlockedDecrement(spinLock);
}
//===========================================================================
static inline void LeaveSpinLock (long * spinLock) {
InterlockedDecrement(spinLock);
}
/****************************************************************************
*
* CLockWaitSet / CLockWaitSetAllocator
*
***/
class CLockWaitSet {
private:
unsigned m_refCount;
HANDLE m_waitEvent;
public:
LINK(CLockWaitSet) link;
inline CLockWaitSet ();
inline ~CLockWaitSet ();
inline void DecRef ();
inline void IncRef ();
inline void Signal ();
inline void Wait ();
};
class CLockWaitSetAllocator {
private:
CLockWaitSet m_array[256];
CLockWaitSetAllocator * m_prev;
LISTDECL(CLockWaitSet, link) m_spareList;
LISTDECL(CLockWaitSet, link) m_usedList;
static CLockWaitSetAllocator * s_allocator;
static long s_spinLock;
public:
CLockWaitSetAllocator (CLockWaitSetAllocator * prev);
~CLockWaitSetAllocator ();
static CLockWaitSet * Alloc ();
static void Free (CLockWaitSet * waitSet);
static void __cdecl Shutdown ();
};
CLockWaitSetAllocator * CLockWaitSetAllocator::s_allocator;
long CLockWaitSetAllocator::s_spinLock = -1;
//===========================================================================
CLockWaitSet::CLockWaitSet () {
m_refCount = 0;
m_waitEvent = CreateEvent(nil, true, false, nil);
}
//===========================================================================
CLockWaitSet::~CLockWaitSet () {
ASSERT(!m_refCount);
CloseHandle(m_waitEvent);
m_waitEvent = 0;
}
//===========================================================================
void CLockWaitSet::DecRef () {
ASSERT(m_refCount);
if (!--m_refCount) {
ResetEvent(m_waitEvent);
CLockWaitSetAllocator::Free(this);
}
}
//===========================================================================
void CLockWaitSet::IncRef () {
++m_refCount;
}
//===========================================================================
void CLockWaitSet::Signal () {
ASSERT(m_refCount);
SetEvent(m_waitEvent);
}
//===========================================================================
void CLockWaitSet::Wait () {
ASSERT(m_refCount);
WaitForSingleObject(m_waitEvent, INFINITE);
}
//===========================================================================
CLockWaitSetAllocator::CLockWaitSetAllocator (CLockWaitSetAllocator * prev) {
m_prev = prev;
if (prev) {
m_spareList.Link(&prev->m_spareList);
m_usedList.Link(&prev->m_usedList);
}
for (unsigned index = arrsize(m_array); index--; )
m_spareList.Link(&m_array[index]);
}
//===========================================================================
CLockWaitSetAllocator::~CLockWaitSetAllocator () {
DEL(m_prev);
}
//===========================================================================
CLockWaitSet * CLockWaitSetAllocator::Alloc () {
EnterSpinLock(&s_spinLock);
// If there is no active allocator or if the active allocator is full,
// create a new one
if (!s_allocator || !s_allocator->m_spareList.Head()) {
if (!s_allocator)
atexit(Shutdown);
s_allocator = NEW(CLockWaitSetAllocator)(s_allocator);
}
// Get an available wait set from the active allocator
CLockWaitSet * waitSet = s_allocator->m_spareList.Head();
s_allocator->m_usedList.Link(waitSet);
LeaveSpinLock(&s_spinLock);
return waitSet;
}
//===========================================================================
void CLockWaitSetAllocator::Free (CLockWaitSet * waitSet) {
EnterSpinLock(&s_spinLock);
// Return this wait set to the active allocator's spare list
ASSERT(s_allocator);
s_allocator->m_spareList.Link(waitSet);
LeaveSpinLock(&s_spinLock);
}
//===========================================================================
void CLockWaitSetAllocator::Shutdown () {
EnterSpinLock(&s_spinLock);
// Free all allocators
while (s_allocator) {
CLockWaitSetAllocator * prev = s_allocator->m_prev;
DEL(s_allocator);
s_allocator = prev;
}
LeaveSpinLock(&s_spinLock);
}
/****************************************************************************
*
* CLock
*
***/
//===========================================================================
CLock::CLock () {
m_waitSet = nil;
m_spinLock = -1;
m_readerCount = 0;
m_writerCount = 0;
}
//===========================================================================
CLock::~CLock () {
ASSERT(!m_waitSet);
ASSERT(m_spinLock == -1);
ASSERT(!m_readerCount);
ASSERT(!m_writerCount);
}
//===========================================================================
void CLock::EnterRead () {
EnterSpinLock(&m_spinLock);
for (;;) {
// If there are no writers, claim this lock for reading
if (!m_writerCount) {
++m_readerCount;
break;
}
// Otherwise, wait until the existing writer releases the lock
CLockWaitSet * waitSet = m_waitSet = (m_waitSet ? m_waitSet : CLockWaitSetAllocator::Alloc());
waitSet->IncRef();
LeaveSpinLock(&m_spinLock);
waitSet->Wait();
EnterSpinLock(&m_spinLock);
waitSet->DecRef();
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::EnterWrite () {
EnterSpinLock(&m_spinLock);
for (;;) {
// If there are no readers or writers, claim this lock for writing
if (!m_readerCount && !m_writerCount) {
++m_writerCount;
break;
}
// Otherwise, wait until the existing writer or all existing readers
// release the lock
CLockWaitSet * waitSet = m_waitSet = (m_waitSet ? m_waitSet : CLockWaitSetAllocator::Alloc());
waitSet->IncRef();
LeaveSpinLock(&m_spinLock);
waitSet->Wait();
EnterSpinLock(&m_spinLock);
waitSet->DecRef();
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::LeaveRead () {
EnterSpinLock(&m_spinLock);
// If this is the last reader, signal waiting threads to try claiming
// the lock again
ASSERT(m_readerCount);
if (!--m_readerCount)
if (m_waitSet) {
m_waitSet->Signal();
m_waitSet = nil;
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::LeaveWrite () {
EnterSpinLock(&m_spinLock);
// This is the last writer. Signal waiting threads to try claiming the
// lock again.
ASSERT(m_writerCount == 1);
--m_writerCount;
if (m_waitSet) {
m_waitSet->Signal();
m_waitSet = nil;
}
LeaveSpinLock(&m_spinLock);
}
/*****************************************************************************
*
* CEvent
*
***/
//============================================================================
CEvent::CEvent (
ECEventResetBehavior resetType,
bool initialSet
) {
m_handle = CreateEvent(
nil, // security attributes
(resetType == kEventManualReset) ? true : false,
initialSet,
nil // name
);
}
//============================================================================
CEvent::~CEvent () {
(void) CloseHandle(m_handle);
}
//============================================================================
void CEvent::Signal () {
SetEvent(m_handle);
}
//============================================================================
void CEvent::Reset () {
ResetEvent(m_handle);
}
//============================================================================
bool CEvent::Wait (unsigned waitMs) {
ThreadAssertCanBlock(__FILE__, __LINE__);
return WaitForSingleObject(m_handle, waitMs) == WAIT_OBJECT_0;
}
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
long AtomicAdd (long * value, long increment) {
return InterlockedExchangeAdd(value, increment);
}
//===========================================================================
long AtomicSet (long * value, long set) {
return InterlockedExchange(value, set);
}

View File

@ -0,0 +1,162 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Time.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local functions
*
***/
//============================================================================
static void FormatTime (
qword time,
wchar const dateFmt[],
wchar const timeFmt[],
unsigned chars,
wchar * buffer
) {
COMPILER_ASSERT(sizeof(FILETIME) == sizeof(qword));
SYSTEMTIME sysTime;
FileTimeToSystemTime((FILETIME *)&time, &sysTime);
unsigned offset = GetDateFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&sysTime,
dateFmt,
buffer,
chars
);
if (timeFmt) {
// if we printed any characters, move offset back to overwrite the string terminator
if (offset)
--offset;
offset += GetTimeFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&sysTime,
timeFmt,
buffer + offset,
chars - offset
);
}
// if we didn't print any characters, NULL terminate the buffer
if (!offset && chars)
buffer[0] = 0;
}
/*****************************************************************************
*
* Exported functions
*
***/
#ifdef HS_BUILD_FOR_WIN32
//===========================================================================
void TimeGetDesc (
qword time,
TimeDesc * desc
) {
ASSERT(desc);
SYSTEMTIME sysTime;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
FileTimeToSystemTime((FILETIME *) &time, &sysTime);
desc->year = sysTime.wYear;
desc->month = sysTime.wMonth;
desc->day = sysTime.wDay;
desc->dayOfWeek = sysTime.wDayOfWeek;
desc->hour = sysTime.wHour;
desc->minute = sysTime.wMinute;
desc->second = sysTime.wSecond;
}
//============================================================================
qword TimeGetTime () {
qword time;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
GetSystemTimeAsFileTime((FILETIME *) &time);
return time;
}
//============================================================================
qword TimeGetLocalTime () {
qword time;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
GetSystemTimeAsFileTime((FILETIME *) &time);
FileTimeToLocalFileTime((FILETIME *) &time, (FILETIME *) &time);
return time;
}
//============================================================================
void TimePrettyPrint (
qword time,
unsigned chars,
wchar * buffer
) {
FormatTime(
time,
L"ddd MMM dd',' yyyy ",
L"hh':'mm':'ss tt",
chars,
buffer
);
}
#endif // HS_BUILD_FOR_WIN32

View File

@ -0,0 +1,187 @@
/*==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/NucleusLib/pnUtils/Private/Win32/pnUtW32Uuid.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#if 0
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(GUID));
void Uuid::Clear()
{
UuidCreateNil( (GUID *)this );
}
int Uuid::CompareTo( const Uuid * v ) const
{
RPC_STATUS s;
return UuidCompare( (GUID *)this, (GUID *)v, &s );
}
bool Uuid::IsEqualTo( const Uuid * v ) const
{
return ( CompareTo( v )==0 );
}
void Uuid::CopyFrom( const Uuid * v )
{
memcpy( (void*)fData, (const void*)v->fData, sizeof(fData) );
}
bool Uuid::IsNull() const
{
RPC_STATUS s;
return 1 == UuidIsNil( (GUID *)this, &s );
}
bool Uuid::FromString( const char * str )
{
Clear();
if ( !str )
return false;
return RPC_S_OK == UuidFromString( (unsigned char *)str, (GUID *)this );
}
bool Uuid::ToString( std::string & out ) const
{
out = "";
unsigned char * ubuf;
RPC_STATUS s;
s = UuidToString( (GUID *) this, &ubuf );
bool success = ( s==RPC_S_OK );
if ( success )
out = (char*)ubuf;
RpcStringFree( &ubuf );
return success;
}
// static
Uuid Uuid::Generate()
{
Uuid result;
UuidCreate( (GUID *)&result );
return result;
}
#endif
#ifdef HS_BUILD_FOR_WIN32
/*****************************************************************************
*
* Exports
*
***/
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(GUID));
//============================================================================
Uuid GuidGenerate () {
Uuid result;
UuidCreate( (GUID *)&result );
return result;
}
//============================================================================
void GuidClear (Uuid * uuid) {
UuidCreateNil((GUID *)uuid);
}
//============================================================================
bool GuidFromString (const wchar str[], Uuid * uuid) {
ASSERT(uuid);
COMPILER_ASSERT(sizeof(wchar) == sizeof(unsigned short));
return RPC_S_OK == UuidFromStringW((unsigned short *) str, (GUID *) uuid);
}
//============================================================================
bool GuidFromString (const char str[], Uuid * uuid) {
ASSERT(uuid);
return RPC_S_OK == UuidFromStringA((unsigned char *) str, (GUID *) uuid);
}
//============================================================================
int GuidCompare (const Uuid & a, const Uuid & b) {
RPC_STATUS s;
return UuidCompare((GUID *)&a, (GUID *)&b, &s);
}
//============================================================================
bool GuidIsNil (const Uuid & uuid) {
RPC_STATUS s;
return 1 == UuidIsNil((GUID *)&uuid, &s );
}
//============================================================================
const wchar * GuidToString (const Uuid & uuid, wchar * dst, unsigned chars) {
wchar * src;
RPC_STATUS s;
s = UuidToStringW( (GUID *) &uuid, (unsigned short**)&src );
if (RPC_S_OK == s)
StrCopy(dst, src, chars);
else
StrCopy(dst, L"", chars);
RpcStringFreeW( (unsigned short**)&src );
return dst;
}
//============================================================================
const char * GuidToString (const Uuid & uuid, char * dst, unsigned chars) {
byte * src;
RPC_STATUS s;
s = UuidToStringA( (GUID *) &uuid, &src );
if (RPC_S_OK == s)
StrCopy(dst, (char *)src, chars);
else
StrCopy(dst, "", chars);
RpcStringFreeA(&src);
return dst;
}
#endif // HS_BUILD_FOR_WIN32