diff --git a/AreaLinker.cpp b/AreaLinker.cpp new file mode 100644 index 00000000..a3e23736 --- /dev/null +++ b/AreaLinker.cpp @@ -0,0 +1,66 @@ +#include + +//#include "Constants.h" +#include "D2Structs.h" +#include "D2Helpers.h" +//#include "D2Ptrs.h" +//#include "Core.h" +#include "AreaLinker.h" + +AreaNode* GetAreaNode(int nAreaId) +{ + for(int i = 0; i < ArraySize(AreaNodes); i++) + for(int x = 0; x < AreaNodes[i].nCount; x++) + if(AreaNodes[i].nAreas[x] == nAreaId) + return &AreaNodes[i]; + + return NULL; +} + +int GetAreas(DWORD nArray[], int nSize, int nStartAreaId, WORD wX, WORD wY) +{ + int nDest = -1; + int nCount = 0; + + AreaNode* pNode = GetAreaNode(nStartAreaId); + + if(pNode) + { + for(int i = 0; i < pNode->nCount; i++) + { + Level* pLevel = GetLevel(pNode->nAreas[i]); + + if(pLevel && pLevel->dwPosX * 5 <= wX && pLevel->dwPosY * 5 <= wY && pLevel->dwPosX * 5 + pLevel->dwSizeX * 5 >= wX && pLevel->dwPosY * 5 + pLevel->dwSizeY * 5 >= wY) + { + nDest = pLevel->dwLevelNo; + break; + } + } + + nArray[nCount++] = nStartAreaId; + + if(nDest == -1 || nDest == nStartAreaId) + return nCount; + + if(nStartAreaId > nDest) + { + for(int i = nStartAreaId - 1; i >= nDest; i--) + nArray[nCount++] = i; + + if(nCount >= nSize) + return 0; + } + else if (nStartAreaId < nDest) + { + for(int i = nStartAreaId + 1; i <= nDest; i++) + { + nArray[nCount++] = i; + + if(nCount >= nSize) + return 0; + } + } + } + + return nCount; +} diff --git a/AreaLinker.h b/AreaLinker.h new file mode 100644 index 00000000..7f4c6a8b --- /dev/null +++ b/AreaLinker.h @@ -0,0 +1,27 @@ +#pragma once + +#include "Constants.h" + +#define ArraySize(x) (sizeof((x)) / sizeof((x)[0])) + +struct AreaNode +{ + int nCount; + int nAreas[64]; +}; + +extern int GetAreas(DWORD nArray[], int nSize, int nStartAreaId, WORD wX, WORD wY); + +static AreaNode AreaNodes[] = { + // Act 1 + {4, {MAP_A1_ROGUE_ENCAMPMENT, MAP_A1_BLOOD_MOOR, MAP_A1_COLD_PLAINS, MAP_A1_STONY_FIELD}}, + {6, {MAP_A1_DARK_WOOD, MAP_A1_BLACK_MARSH, MAP_A1_TAMOE_HIGHLAND, MAP_A1_MONASTERY_GATE, MAP_A1_OUTER_CLOISTER, MAP_A1_BARRACKS}}, + // Act 2 + {6, {MAP_A2_LUT_GHOLEIN, MAP_A2_ROCKY_WASTE, MAP_A2_DRY_HILLS, MAP_A2_FAR_OASIS, MAP_A2_LOST_CITY, MAP_A2_VALLEY_OF_SNAKES}}, + // Act 3 + {9, {MAP_A3_KURAST_DOCKS, MAP_A3_SPIDER_FOREST, MAP_A3_GREAT_MARSH, MAP_A3_FLAYER_JUNGLE, MAP_A3_LOWER_KURAST, MAP_A3_KURAST_BAZAAR, MAP_A3_UPPER_KURAST, MAP_A3_KURAST_CAUSEWAY, MAP_A3_TRAVINCAL}}, + // Act 4 + {4, {MAP_A4_THE_PANDEMONIUM_FORTRESS, MAP_A4_OUTER_STEPPES, MAP_A4_PLAINS_OF_DESPAIR, MAP_A4_CITY_OF_THE_DAMNED}}, + // Act 5 + {4, {MAP_A5_HARROGATH, MAP_A5_THE_BLOODY_FOOTHILLS, MAP_A5_FRIGID_HIGHLANDS, MAP_A5_ARREAT_PLATEAU}}, +}; diff --git a/ArrayEx.h b/ArrayEx.h new file mode 100644 index 00000000..aeb14acd --- /dev/null +++ b/ArrayEx.h @@ -0,0 +1,460 @@ +/************************************************************ + + ArrayEx.h + + An improved array template class provides functionalities that are + similar to the MFC "CArray" class except that: + + a) No need to link MFC libraries, can be used in any win32 applications. + b) Implemented elements sorting and searching methods using the + "qsort" and "bsearch" algorithms (requiring operators ">" and "==" + being defined for stored element data type. + c) The constant operator[] now returns "const TYPE&" instead of + a "TYPE" instance, which was the case in "CArray". + + Written by: Abin (abinn32@yahoo.com) + + May 08, 2004 Initial release. +*************************************************************/ + +#ifndef __ARRAYEX_H__ +#define __ARRAYEX_H__ + +#pragma warning(disable:4311) + +#define USE_MULTI_THREAD // uncomment this line if used in multi-thread application + +#ifdef USE_MULTI_THREAD +#include "SyncObj.h" +#endif // USE_MULTI_THREAD + +////////////////////////////////////////////////////////////////////// +// Necessary Definitions for Non-MFC applications +////////////////////////////////////////////////////////////////////// +#ifndef __AFXWIN_H__ // If non-MFC ... +#include +#include +#include +#ifndef ASSERT +#define ASSERT(x) assert(x) +#endif +#endif // __AFXWIN_H__ + + +// Element sorting states +enum { AE_SORT_NONE = 0, // Not sorted + AE_SORT_ASCENDING, // Sorted in ascending order + AE_SORT_DESCENDING }; // Sorted in descending order + +template +class CArrayEx +#ifdef USE_MULTI_THREAD +: public CSyncObj +#endif // USE_MULTI_THREAD +{ +public: + + // Constructions & Destructor + CArrayEx(); + CArrayEx(const CArrayEx& src); + virtual ~CArrayEx(); + + // Sort & Search + void Sort(BOOL bAscending = TRUE); + int IsSorted() const { return m_nSort; } + int Find(ARG_TYPE tData, int nStartAt = 0) const; + int ReverseFind(ARG_TYPE tData) const; + + // General Access + int GetSize() const { return m_nElementCount; } + int GetUpperBound() const { return m_nElementCount - 1; } + BOOL SetSize(int nNewSize); + BOOL IsEmpty() const { return m_nElementCount == 0; } + BOOL IsIndexValid(int nIndex) const { return nIndex >= 0 && nIndex < m_nElementCount; } + BOOL FreeExtra(); + BOOL Copy(const CArrayEx& src); + + // Element Insertion & Removal + int InsertAt(int nIndex, ARG_TYPE tData, int nCount = 1); + int InsertAt(int nIndex, const CArrayEx* pNewArray); + int Add(ARG_TYPE tData, int nCount = 1); + int Append(const CArrayEx& src); + int RemoveAt(int nIndex, int nCount = 1); + BOOL RemoveLast() { return RemoveAt(m_nElementCount - 1, 1) > 0; } + void RemoveAll() { m_nElementCount = 0; } + + // Element Access + const TYPE& GetLast() const { return GetAt(m_nElementCount - 1); } + TYPE& GetLast() { return ElementAt(m_nElementCount - 1); } + const TYPE& GetAt(int nIndex) const; + BOOL SetLast(ARG_TYPE tData) { return SetAt(m_nElementCount - 1, tData); } + BOOL SetAt(int nIndex, ARG_TYPE tData); + TYPE& ElementAt(int nIndex); + const TYPE* GetData() const { return m_pData; } + TYPE* GetData() { m_nSort = AE_SORT_NONE; return m_pData; } + + // Operators + TYPE& operator[](int nIndex) { return ElementAt(nIndex); } + const TYPE& operator[](int nIndex) const { return GetAt(nIndex); } + const CArrayEx& operator=(const CArrayEx& src); + +protected: + + BOOL _MakeSpaces(int nIndex, int nCount = 1); // Make spaces for new elements + BOOL _GrowSize(int nAdd); // dynamically grow array size + void _AdjustIdx(int& nIndex, BOOL bAllowGrow) const; + + // call-back compare functions + static int __cdecl _CompareAscending(const void* p1, const void* p2); + static int __cdecl _CompareDescending(const void* p1, const void* p2); + + // member data + int m_nSort; // sort states + int m_nElementCount; // element count + int m_nAllocSize; // allocated size + TYPE* m_pData; // data +}; + +template +int __cdecl CArrayEx::_CompareAscending(const void* p1, const void* p2) +{ + TYPE* pElement1 = (TYPE*)p1; + TYPE* pElement2 = (TYPE*)p2; + ASSERT(pElement1 != NULL && pElement2 != NULL); + + if (*pElement1 == *pElement2) + return 0; + + if (*pElement1 > *pElement2) + return 1; + + return -1; +} + +template +int __cdecl CArrayEx::_CompareDescending(const void* p1, const void* p2) +{ + return _CompareAscending(p2, p1); // just reverse the order +} + +template +void CArrayEx::Sort(BOOL bAscending) +{ + if (m_nElementCount < 2 + || (bAscending && (m_nSort == AE_SORT_ASCENDING)) + || (!bAscending && (m_nSort == AE_SORT_DESCENDING))) + return; // no need to resort + + // use qsort + if (bAscending) + ::qsort(m_pData, m_nElementCount, sizeof(TYPE), _CompareAscending); + else + ::qsort(m_pData, m_nElementCount, sizeof(TYPE), _CompareDescending); + + m_nSort = bAscending ? AE_SORT_ASCENDING : AE_SORT_DESCENDING; +} + +template +int CArrayEx::Find(ARG_TYPE tData, int nStartAt/*=0*/) const +{ + if (nStartAt < 0) + nStartAt = 0; + + if (!IsIndexValid(nStartAt)) + return -1; + + if (m_nSort == AE_SORT_ASCENDING) // ascending + { + void* p = ::bsearch(&tData, &m_pData[nStartAt], m_nElementCount - nStartAt, sizeof(TYPE), _CompareAscending); + int nIndex = (p == NULL) ? -1 : int(((long)p - (long)m_pData) / sizeof(TYPE)); + while (nIndex > 0 && m_pData[nIndex - 1] == tData) + nIndex--; + return nIndex; + } + else if (m_nSort == AE_SORT_DESCENDING) // descending + { + void* p = ::bsearch(&tData, &m_pData[nStartAt], m_nElementCount - nStartAt, sizeof(TYPE), _CompareDescending); + int nIndex = (p == NULL) ? -1 : int(((long)p - (long)m_pData) / sizeof(TYPE)); + while (nIndex > 0 && m_pData[nIndex - 1] == tData) + nIndex--; + return nIndex; + } + else // not sorted + { + for (int i = nStartAt; i < m_nElementCount; i++) + { + if (m_pData[i] == tData) + return i; + } + return -1; + } +} + +template +int CArrayEx::ReverseFind(ARG_TYPE tData) const +{ + if (m_nElementCount == 0) + return -1; + + if (m_nSort == AE_SORT_ASCENDING) // ascending + { + void* p = ::bsearch(&tData, m_pData, m_nElementCount, sizeof(TYPE), _CompareAscending); + int nIndex = (p == NULL) ? -1 : int(((long)p - (long)m_pData) / sizeof(TYPE)); + while (nIndex < m_nElementCount - 1 && m_pData[nIndex + 1] == tData) + nIndex++; + return nIndex; + } + else if (m_nSort == AE_SORT_DESCENDING) // descending + { + void* p = ::bsearch(&tData, m_pData, m_nElementCount, sizeof(TYPE), _CompareDescending); + int nIndex = (p == NULL) ? -1 : int(((long)p - (long)m_pData) / sizeof(TYPE)); + while (nIndex < m_nElementCount - 1 && m_pData[nIndex + 1] == tData) + nIndex++; + return nIndex; + } + else // not sorted + { + for (int i = m_nElementCount - 1; i >= 0; i--) + { + if (m_pData[i] == tData) + return i; + } + return -1; + } +} + +template +CArrayEx::CArrayEx() +{ + m_nSort = AE_SORT_NONE; + m_nElementCount = 0; + m_nAllocSize = 0; + m_pData = NULL; +}; + +template +CArrayEx::CArrayEx(const CArrayEx& src) +{ + m_nSort = AE_SORT_NONE; + m_nElementCount = 0; + m_nAllocSize = 0; + m_pData = NULL; + if (!Copy(src)) + ASSERT(FALSE); +} + +template +CArrayEx::~CArrayEx() +{ + delete [] m_pData; +}; + +template +BOOL CArrayEx::SetSize(int nNewSize) +{ + if (nNewSize < 0) + return FALSE; + + if (!_GrowSize(nNewSize - m_nElementCount)) + return FALSE; + + m_nElementCount = nNewSize; + return TRUE; +}; + +template +int CArrayEx::Add(ARG_TYPE tData, int nCount) +{ + // append at the end + return InsertAt(m_nElementCount, tData, nCount); +} + +// insert single element +template +int CArrayEx::InsertAt(int nIndex, ARG_TYPE tData, int nCount) +{ + if (nCount < 1) + return -1; + + _AdjustIdx(nIndex, TRUE); + if (!_MakeSpaces(nIndex, nCount)) + return -1; + + for (int i = 0; i < nCount; i++) + m_pData[nIndex + i] = tData; + + m_nSort = AE_SORT_NONE; + return nIndex; +} + +// insert a whole array +template +int CArrayEx::InsertAt(int nIndex, const CArrayEx* pNewArray) +{ + if (pNewArray == NULL || pNewArray->GetSize() < 1) + return -1; + + _AdjustIdx(nIndex, TRUE); + if (!_MakeSpaces(nIndex, pNewArray->GetSize())) + return -1; + + for (int i = 0; i < pNewArray->GetSize(); i++) + m_pData[nIndex + i] = pNewArray->GetAt(i); + + m_nSort = AE_SORT_NONE; + return nIndex; +} + +template +int CArrayEx::RemoveAt(int nIndex, int nCount) +{ + if (nCount > m_nElementCount - nIndex) + nCount = m_nElementCount - nIndex; + + if (!IsIndexValid(nIndex) || nCount < 1) + return 0; + + const int SEG = m_nElementCount - nIndex - nCount; + + for (int i = 0; i < SEG; i++) + m_pData[nIndex + i] = m_pData[nIndex + i + nCount]; + + m_nElementCount -= nCount; + return nCount; +} + +template +BOOL CArrayEx::FreeExtra() +{ + if (m_pData == NULL || m_nAllocSize == m_nElementCount) + return TRUE; + + // reallocate data array with optimized size + m_nAllocSize = m_nElementCount; + TYPE* p = new TYPE[m_nAllocSize]; + if (p == NULL) + return FALSE; + + for (int i = 0; i < m_nElementCount; i++) + p[i] = m_pData[i]; + + delete [] m_pData; + m_pData = p; + return TRUE; +} + +template +BOOL CArrayEx::Copy(const CArrayEx& src) +{ + if (!SetSize(src.m_nElementCount)) + return FALSE; + + for (int i = 0; i < m_nElementCount; i++) + m_pData[i] = src.m_pData[i]; + m_nSort = src.m_nSort; + return TRUE; +} + +template +int CArrayEx::Append(const CArrayEx& src) +{ + int nAppenedeAt = src.m_nElementCount > 0 ? m_nElementCount : -1; + if (!_GrowSize(src.m_nElementCount)) + return -1; + + // append at the end + for (int i = 0; i < src.m_nElementCount; i++) + m_pData[nAppenedeAt + i] = src.m_pData[i]; + + m_nElementCount += src.m_nElementCount; + m_nSort = AE_SORT_NONE; + return nAppenedeAt; +} + +template +void CArrayEx::_AdjustIdx(int& nIndex, BOOL bAllowGrow) const +{ + if (nIndex < 0) + nIndex = 0; + + if (nIndex >= m_nElementCount) + nIndex = bAllowGrow ? m_nElementCount : (m_nElementCount - 1); +} + +template +BOOL CArrayEx::_MakeSpaces(int nIndex, int nCount /*= 1*/) +{ + if (nCount < 1) + return TRUE; + + if (!_GrowSize(nCount)) + return FALSE; + + for (int i = m_nElementCount - 1; i >= nIndex; i--) + m_pData[i + nCount] = m_pData[i]; + + m_nElementCount += nCount; + return TRUE; +} + +template +BOOL CArrayEx::_GrowSize(int nAdd) +{ + if (nAdd < 1) + return TRUE; + + if (m_nAllocSize <= 0) + m_nAllocSize = 32; + + while (m_nAllocSize < m_nElementCount + nAdd) + m_nAllocSize *= 2; + + TYPE* pNew = new TYPE[m_nAllocSize]; + if (pNew == NULL) + return FALSE; // out of memory + + if (m_pData != NULL) + { + for (int i = 0; i < m_nElementCount; i++) + pNew[i] = m_pData[i]; + delete [] m_pData; + } + m_pData = pNew; + return TRUE; +} + +template +BOOL CArrayEx::SetAt(int nIndex, ARG_TYPE tData) +{ + if (!IsIndexValid(nIndex)) + return FALSE; + + m_pData[nIndex] = tData; + m_nSort = AE_SORT_NONE; + return TRUE; +} + +template +TYPE& CArrayEx::ElementAt(int nIndex) +{ + ASSERT(IsIndexValid(nIndex)); + m_nSort = AE_SORT_NONE; + return m_pData[nIndex]; +} + +template +const TYPE& CArrayEx::GetAt(int nIndex) const +{ + ASSERT(IsIndexValid(nIndex)); + return m_pData[nIndex]; +} + +template +const CArrayEx& CArrayEx::operator=(const CArrayEx& src) +{ + if (!Copy(src)) + ASSERT(FALSE); + return *this; +} + +#endif // __ARRAYEX_H__ \ No newline at end of file diff --git a/AutoRoot.cpp b/AutoRoot.cpp new file mode 100644 index 00000000..319ecd42 --- /dev/null +++ b/AutoRoot.cpp @@ -0,0 +1,30 @@ +#include "AutoRoot.h" +#include "ScriptEngine.h" + +AutoRoot::AutoRoot(jsval nvar) : var(nvar), count(0) { Take(); } +AutoRoot::~AutoRoot() { + if(count < 0) + { + fprintf(stderr, "AutoRoot failed: Count is still %i, but the root is being destroyed", count); + DebugBreak(); + exit(3); + } + JS_RemoveRoot(&var); +} + +void AutoRoot::Take() +{ + count++; + JS_AddNamedRootRT(ScriptEngine::GetRuntime(), &var, "AutoRoot"); +} + +void AutoRoot::Release() +{ + count--; + if(count < 0) + { + fprintf(stderr, "Improper AutoRoot usage: Count is less than 0"); + DebugBreak(); + exit(3); + } +} diff --git a/AutoRoot.h b/AutoRoot.h new file mode 100644 index 00000000..4626f201 --- /dev/null +++ b/AutoRoot.h @@ -0,0 +1,27 @@ +#pragma once + +#ifndef __AUTOROOT_H__ +#define __AUTOROOT_H__ + +#include "js32.h" + +class AutoRoot +{ +private: + jsval var; + int count; + + AutoRoot(const AutoRoot&); + AutoRoot& operator=(const AutoRoot&); +public: + AutoRoot() : var(JSVAL_NULL), count(0) {} + AutoRoot(jsval var); + ~AutoRoot(); + void Take(); + void Release(); + jsval* value() { return &var; } + jsval operator* () { return *value(); } + bool operator==(AutoRoot& other) { return value() == other.value(); } +}; + +#endif diff --git a/CollisionMap.cpp b/CollisionMap.cpp new file mode 100644 index 00000000..bdb52a1c --- /dev/null +++ b/CollisionMap.cpp @@ -0,0 +1,719 @@ +// CollisionMap.cpp: implementation of the CCollisionMap class. +// +////////////////////////////////////////////////////////////////////// + +#include "CollisionMap.h" +#include "D2Helpers.h" +#include "D2Ptrs.h" +#include "Constants.h" +#include "CriticalSections.h" + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CCollisionMap::CCollisionMap() +{ + m_iCurMap = 0x00; + ::memset(&m_ptLevelOrigin, 0, sizeof(POINT)); +} + +CCollisionMap::~CCollisionMap() +{ +} + +void CCollisionMap::OnMapChanged(BYTE iNewMapID) +{ + if (iNewMapID != m_iCurMap) + { + m_iCurMap = iNewMapID; + //m_map.Lock(); + m_map.Destroy(); + //m_map.Unlock(); + ::memset(&m_ptLevelOrigin, 0, sizeof(POINT)); + m_aCollisionTypes.RemoveAll(); + } +} + +void CCollisionMap::AddCollisionData(const CollMap* pCol) +{ + if (pCol == NULL) + return; + + int x = pCol->dwPosGameX - m_ptLevelOrigin.x; + int y = pCol->dwPosGameY - m_ptLevelOrigin.y; + int cx = pCol->dwSizeGameX; + int cy = pCol->dwSizeGameY; + + if (!m_map.IsValidIndex(x, y)) + { + return; + } + + int nLimitX = x + cx; + int nLimitY = y + cy; + + WORD* p = pCol->pMapStart; + for (int j = y; j < nLimitY; j++) + { + for (int i = x; i < nLimitX; i++) + { + m_map[i][j] = *p; + if (m_map[i][j] == 1024) + m_map[i][j] = MAP_DATA_AVOID; + + if (m_aCollisionTypes.Find(*p) == -1) + { + m_aCollisionTypes.Add(*p); + m_aCollisionTypes.Sort(); + } + + p++; + } + } +} + +BOOL CCollisionMap::IsValidAbsLocation(long x, long y) const +{ + if (!m_map.IsCreated()) + return FALSE; + + x -= m_ptLevelOrigin.x; + y -= m_ptLevelOrigin.y; + + return m_map.IsValidIndex(x, y); +} + +WORD CCollisionMap::GetMapData(long x, long y, BOOL bAbs) const +{ + if (!m_map.IsCreated()) + return (WORD)MAP_DATA_INVALID; + + if (bAbs) + { + x -= m_ptLevelOrigin.x; + y -= m_ptLevelOrigin.y; + } + + //m_map.Lock(); + WORD wVal = (WORD)MAP_DATA_INVALID; + + if (m_map.IsValidIndex(x, y)) + wVal = m_map[x][y]; + + //m_map.Unlock(); + return wVal; +} + +BOOL CCollisionMap::BuildMapData(DWORD AreaIds[], int nSize) +{ + UnitAny* pUnit = D2CLIENT_GetPlayerUnit(); + + if (m_map.IsCreated()) + return TRUE; + + if(!pUnit) + return FALSE; + + + //Get the most left-top level for the base and the size of the entire wanted map + Level* pBestLevel = GetLevel(AreaIds[0]); + DWORD dwXSize = 0; + DWORD dwYSize = 0; + m_ptLevelOrigin.x = pBestLevel->dwPosX * 5; + m_ptLevelOrigin.y = pBestLevel->dwPosY * 5; + dwLevelId = AreaIds[0]; + + //Loop all the given areas + for (int n = 0; n < nSize; n++) { + //Get the level struct for given id + Level* pLevel = GetLevel(AreaIds[n]); + + //Make sure we have pLevel + if (!pLevel) + continue; + + //Check if this level is even more top-left then the current one + if((m_ptLevelOrigin.x / 5) > (int)pLevel->dwPosX) + m_ptLevelOrigin.x = pLevel->dwPosX * 5; + + if((m_ptLevelOrigin.y / 5) > (int)pLevel->dwPosY) + m_ptLevelOrigin.y = pLevel->dwPosY * 5; + + //Add the size of the levels. + dwXSize += pLevel->dwSizeX * 5; + dwYSize += pLevel->dwSizeY * 5; + } + + if (!m_map.Create(dwXSize, dwYSize, (WORD)MAP_DATA_INVALID)) + return FALSE; + + DwordArray aSkip; + for (int n = 0; n < nSize; n++) { + Level* pLevel = GetLevel(AreaIds[n]); + if (!pLevel) + continue; + + Search(pLevel->pRoom2First, pUnit, aSkip, AreaIds[n]); + } + + FillGaps(); + FillGaps(); + + return TRUE; +} + +void CCollisionMap::Search(Room2 *ro, UnitAny* pPlayer, DwordArray &aSkip, DWORD dwScanArea) +{ + if (!ro || ro->pLevel->dwLevelNo != dwScanArea || aSkip.Find((DWORD)ro) != -1 || pPlayer == NULL) + return; + + BOOL add_room=FALSE; + if(!ro->pRoom1) + { + add_room=TRUE; + D2COMMON_AddRoomData(pPlayer->pAct, ro->pLevel->dwLevelNo, ro->dwPosX, ro->dwPosY, pPlayer->pPath->pRoom1); + } + + aSkip.Add((DWORD)ro); + aSkip.Sort(); + + if (ro->pRoom1) + { + AddCollisionData(ro->pRoom1->Coll); + } + + Room2 **n = ro->pRoom2Near; + for(UINT i=0; i < ro->dwRoomsNear; i++) + { + Search(n[i], pPlayer, aSkip, dwScanArea); + } + + if(add_room) + { + D2COMMON_RemoveRoomData(pPlayer->pAct,ro->pLevel->dwLevelNo, ro->dwPosX, ro->dwPosY, pPlayer->pPath->pRoom1); + } +} + +BOOL CCollisionMap::CreateMap(DWORD AreaId[], int nSize) +{ + + BOOL bOK = BuildMapData(AreaId, nSize); + + return bOK; +} +BOOL CCollisionMap::CreateMap(DWORD AreaId) +{ + DWORD dwAreas[] = {AreaId}; + return BuildMapData(dwAreas, 1); +} +POINT CCollisionMap::GetMapOrigin() const +{ + return m_ptLevelOrigin; +} + +void CCollisionMap::AbsToRelative(POINT &pt) const +{ + pt.x -= m_ptLevelOrigin.x; + pt.y -= m_ptLevelOrigin.y; +} + +void CCollisionMap::RelativeToAbs(POINT &pt) const +{ + pt.x += m_ptLevelOrigin.x; + pt.y += m_ptLevelOrigin.y; +} + +BOOL CCollisionMap::DumpMap(LPCSTR lpszFilePath, const LPPOINT lpPath, DWORD dwCount) const +{ + if (lpszFilePath == NULL) + return FALSE; + + FILE *fp = NULL; + fopen_s(&fp, lpszFilePath, "w+"); + if(fp == NULL ) + return FALSE; + + if (!m_map.IsCreated()) + return FALSE; + + //m_map.Lock(); + char szMapName[256] = ""; + + fprintf(fp, "%s (Size: %d * %d)\nKnown Collision Types: ", szMapName, m_map.GetCX(), m_map.GetCY()); + for (int i = 0; i < m_aCollisionTypes.GetSize(); i++) + { + fprintf(fp, "%d, ", m_aCollisionTypes[i]); + } + + fprintf(fp, "\n\n"); + + POINT* pPath = NULL; + if (lpPath && dwCount) + { + pPath = new POINT[dwCount]; + ::memcpy(pPath, lpPath, dwCount * sizeof(POINT)); + for (DWORD i = 0; i < dwCount; i++) + AbsToRelative(pPath[i]); + } + + UnitAny* Me = D2CLIENT_GetPlayerUnit(); + POINT ptPlayer = {Me->pPath->xPos,Me->pPath->yPos}; + AbsToRelative(ptPlayer); + + const int CX = m_map.GetCX(); + const int CY = m_map.GetCY(); + + for (int y = 0; y < CY; y++) + { + for (int x = 0; x < CX; x++) + { + char ch = IsMarkPoint(ptPlayer, x, y, pPath, dwCount); + + if (!ch) + ch = (m_map[x][y] % 2) ? 'X' : ' '; + + fprintf(fp, "%C", ch); // X - unreachable + } + + fprintf(fp, "%c", '\n'); + } + + delete [] pPath; + + //m_map.Unlock(); + fclose(fp); + + return TRUE; +} + +BOOL CCollisionMap::CheckCollision(int x, int y) { + if(!m_map.IsCreated()) + return FALSE; + if(x > m_map.GetCX() || y > m_map.GetCY()) + return FALSE; + BOOL Works = FALSE; + Works = (m_map[x][y] % 2) ? FALSE : TRUE; +return Works; +} + +char CCollisionMap::IsMarkPoint(const POINT& ptPlayer, int x, int y, const LPPOINT lpPath, DWORD dwCount) const +{ + char ch = 0; + if (x == ptPlayer.x && y == ptPlayer.y) + ch = 'P'; + + if (lpPath == NULL || dwCount == 0) + return ch; + + for (DWORD i = 0; i < dwCount; i++) + { + if (lpPath[i].x == x && lpPath[i].y == y) + { + if (i == 0) + return 'S'; // start + else if (i == dwCount - 1) + return 'E'; // end + else + return '*'; // nodes + } + } + + return ch; +} + +SIZE CCollisionMap::GetMapSize() const +{ + SIZE cz = {0}; + if (m_map.IsCreated()) + { + cz.cx = m_map.GetCX(); + cz.cy = m_map.GetCY(); + } + return cz; +} + +SIZE CCollisionMap::CopyMapData(WORD** ppBuffer, int cx, int cy) const +{ + SIZE copied = {0}; + //m_map.Lock(); + copied = m_map.ExportData(ppBuffer, cx, cy); + //m_map.Unlock(); + return copied; +} + +BOOL CCollisionMap::IsGap(int x, int y) +{ + if (m_map[x][y] % 2) + return FALSE; + + int nSpaces = 0; + int i = 0; + + // Horizontal check + for (i = x - 2; i <= x + 2 && nSpaces < 3; i++) + { + if ( i < 0 || i >= m_map.GetCX() || (m_map[i][y] % 2)) + nSpaces = 0; + else + nSpaces++; + } + + if (nSpaces < 3) + return TRUE; + + // Vertical check + nSpaces = 0; + for (i = y - 2; i <= y + 2 && nSpaces < 3; i++) + { + if ( i < 0 || i >= m_map.GetCY() || (m_map[x][i] % 2)) + nSpaces = 0; + else + nSpaces++; + } + + return nSpaces < 3; +} + +void CCollisionMap::FillGaps() +{ + if (!m_map.IsCreated()) + return; + + //m_map.Lock(); + + const int CX = m_map.GetCX(); + const int CY = m_map.GetCY(); + + for (int x = 0; x 0) + { + if(nXDiff % 2) + nXCenter = ptExitPoints[i][0].x + ((nXDiff - (nXDiff % 2)) / 2); + else + nXCenter = ptExitPoints[i][0].x + (nXDiff / 2); + } + + if(nYDiff > 0) + { + if(nYDiff % 2) + nYCenter = ptExitPoints[i][0].y + ((nYDiff - (nYDiff % 2)) / 2); + else + nYCenter = ptExitPoints[i][0].y + (nYDiff / 2); + } + + ptCenters[i].x = nXCenter ? nXCenter : ptExitPoints[i][0].x; + ptCenters[i].y = nYCenter ? nYCenter : ptExitPoints[i][0].y; + } + + + + for(Room2* pRoom = GetLevel(dwLevelId)->pRoom2First; pRoom; pRoom = pRoom->pRoom2Next) + { + Room2* *pNear = pRoom->pRoom2Near; + for(DWORD i = 0; i < pRoom->dwRoomsNear; i++) + { + if(pNear[i]->pLevel->dwLevelNo != dwLevelId) + { + int nRoomX = pRoom->dwPosX * 5; + int nRoomY = pRoom->dwPosY * 5; + + for(int j = 0; j < nTotalPoints; j++) + { + if((ptCenters[j].x + m_ptLevelOrigin.x) >= (WORD)nRoomX && (ptCenters[j].x + m_ptLevelOrigin.x) <= (WORD)(nRoomX + (pRoom->dwSizeX * 5))) + { + if((ptCenters[j].y + m_ptLevelOrigin.y) >= (WORD)nRoomY && (ptCenters[j].y + m_ptLevelOrigin.y) <= (WORD)(nRoomY + (pRoom->dwSizeY * 5))) + { + if(nCurrentExit >= nMaxExits) + { +// LeaveCriticalSection(&CriticalSection); + return FALSE; + } + + lpLevel[nCurrentExit] = new LevelExit; + lpLevel[nCurrentExit]->dwTargetLevel = pNear[i]->pLevel->dwLevelNo; + lpLevel[nCurrentExit]->ptPos.x = ptCenters[j].x + m_ptLevelOrigin.x; + lpLevel[nCurrentExit]->ptPos.y = ptCenters[j].y + m_ptLevelOrigin.y; + lpLevel[nCurrentExit]->dwType = EXIT_LEVEL; + lpLevel[nCurrentExit]->dwId = 0; + nCurrentExit++; + } + } + } + + break; + } + } + + BOOL bAdded = FALSE; + + if(!pRoom->pRoom1) + { + D2COMMON_AddRoomData(Me->pAct, pRoom->pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, Me->pPath->pRoom1); + bAdded = TRUE; + } + + for(PresetUnit* pUnit = pRoom->pPreset; pUnit; pUnit = pUnit->pPresetNext) + { + + if(nCurrentExit >= nMaxExits) + { + if(bAdded) + D2COMMON_RemoveRoomData(Me->pAct, pRoom->pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, Me->pPath->pRoom1); +// LeaveCriticalSection(&CriticalSection); + return FALSE; + } + + if(pUnit->dwType == UNIT_TILE) + { + DWORD dwTargetLevel = GetTileLevelNo(pRoom, pUnit->dwTxtFileNo); + + if(dwTargetLevel) + { + BOOL bExists = FALSE; + + for(int i = 0; i < nCurrentExit; i++) + { + if(((DWORD)lpLevel[i]->ptPos.x == (pRoom->dwPosX * 5) + pUnit->dwPosX) && + ((DWORD)lpLevel[i]->ptPos.y == (pRoom->dwPosY * 5) + pUnit->dwPosY)) + bExists = TRUE; + } + + if(!bExists) + { + lpLevel[nCurrentExit] = new LevelExit; + lpLevel[nCurrentExit]->dwTargetLevel = dwTargetLevel; + lpLevel[nCurrentExit]->ptPos.x = (pRoom->dwPosX * 5) + pUnit->dwPosX; + lpLevel[nCurrentExit]->ptPos.y = (pRoom->dwPosY * 5) + pUnit->dwPosY; + lpLevel[nCurrentExit]->dwType = EXIT_TILE; + lpLevel[nCurrentExit]->dwId = pUnit->dwTxtFileNo; + nCurrentExit++; + } + } + } + } + + if(bAdded) + D2COMMON_RemoveRoomData(Me->pAct, pRoom->pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, Me->pPath->pRoom1); + } + +// LeaveCriticalSection(&CriticalSection); + + return nCurrentExit; +} diff --git a/CollisionMap.h b/CollisionMap.h new file mode 100644 index 00000000..7cd58c07 --- /dev/null +++ b/CollisionMap.h @@ -0,0 +1,110 @@ +////////////////////////////////////////////////////////////////////// +// CollisionMap.h: interface for the CCollisionMap class. +// +// Abin (abinn32@yahoo.com) +////////////////////////////////////////////////////////////////////// + +#include + +#include "ArrayEx.h" +#include "Matrix.h" +#include "D2Structs.h" + +#ifndef __COLLISIONMAP_H__ +#define __COLLISIONMAP_H__ + +#define MAP_DATA_INVALID -1 // Invalid +#define MAP_DATA_CLEANED 11110 // Cleaned for start/end positions +#define MAP_DATA_FILLED 11111 // Filled gaps +#define MAP_DATA_THICKENED 11113 // Wall thickened +#define MAP_DATA_AVOID 11115 // Should be avoided + +#define EXIT_LEVEL 1 +#define EXIT_TILE 2 + +typedef CArrayEx DwordArray; +typedef CArrayEx WordArray; +typedef CMatrix WordMatrix; + +typedef struct LevelExit_t +{ + POINT ptPos; + DWORD dwTargetLevel; + DWORD dwType; + DWORD dwId; +} LevelExit, *LPLevelExit; + +//////////////////////////////////////////////////////////////// +// The CCollisionMap class. Synchronized access required. +//////////////////////////////////////////////////////////////// +class CCollisionMap +{ +public: + + //////////////////////////////////////////////////////////// + // Constructor & Destructor + //////////////////////////////////////////////////////////// + CCollisionMap(); + virtual ~CCollisionMap(); + + //////////////////////////////////////////////////////////// + // Operations + //////////////////////////////////////////////////////////// + BOOL CreateMap(DWORD AreaId); // Create the map data + BOOL CreateMap(DWORD AreaId[], int nSize);//Allow for multiple area ids + void DestroyMap(); + BOOL DumpMap(LPCSTR lpszFilePath, const LPPOINT lpPath, DWORD dwCount) const; // Dump map data into a disk file + + //////////////////////////////////////////////////////////// + // Attributes & Operations + //////////////////////////////////////////////////////////// + POINT GetMapOrigin() const; // Map origin point(top-left) + SIZE GetMapSize() const; // map size + WORD GetMapData(long x, long y, BOOL bAbs) const; // Retrieve map data at a particular location + BOOL IsValidAbsLocation(long x, long y) const; // Map location verification + SIZE CopyMapData(WORD** ppBuffer, int cx, int cy) const; + BOOL CopyMapData(WordMatrix& rBuffer) const; + BOOL ReportCollisionType(POINT ptOrigin, long lRadius) const; + int CCollisionMap::GetLevelExits(LPLevelExit* lpLevel); + + //////////////////////////////////////////////////////////// + // Convertions + //////////////////////////////////////////////////////////// + void AbsToRelative(POINT& pt) const; // Convert an absolute map location into a graph index + void RelativeToAbs(POINT& pt) const; // Convert a graph index into an absolute map location + static void MakeBlank(WordMatrix& rMatrix, POINT pos); + static BOOL ThickenWalls(WordMatrix& rMatrix, int nThickenBy = 1); + BOOL IsGap(int x, int y); + BOOL CheckCollision(int x, int y); + + //////////////////////////////////////////////////////////// + // Only Used by D2Hackit! Do NOT Call It!!! + //////////////////////////////////////////////////////////// + void OnMapChanged(BYTE iNewMapID); // Called by D2Hackit when map changes. Do not call this function manually! + + DWORD dwLevelId; + +private: + + //////////////////////////////////////////////////////////// + // Private Methods + //////////////////////////////////////////////////////////// + BOOL BuildMapData(DWORD AreaIds[], int nSize); + void Search(Room2* ro, UnitAny* pPlayer, DwordArray& aSkip, DWORD dwScanArea); + void AddCollisionData(const CollMap* pCol); + char IsMarkPoint(const POINT& ptPlayer, int x, int y, const LPPOINT lpPath, DWORD dwCount) const; + + void FillGaps(); + + //////////////////////////////////////////////////////////// + // Member Data + //////////////////////////////////////////////////////////// + + BYTE m_iCurMap; // Current map ID + POINT m_ptLevelOrigin; // level top-left + WordArray m_aCollisionTypes; + WordMatrix m_map; // The map + +}; + +#endif // __COLLISIONMAP_H__ diff --git a/Common.cpp b/Common.cpp new file mode 100644 index 00000000..fe063466 --- /dev/null +++ b/Common.cpp @@ -0,0 +1,172 @@ +////////////////////////////////////////////////////////// +// Common.cpp +//-------------------------------------------------------- +// Common algorithms for general uses. +// +// Abin (abinn32@yahoo.com) +////////////////////////////////////////////////////////// + +#include +#include +#include + +#include "Common.h" + +#define PI 3.1415926535 + +long CalculateDistance(const POINT& pt1, const POINT& pt2) +{ + return CalculateDistance(pt1.x, pt1.y, pt2.x, pt2.y); +} + +long CalculateAngle(const POINT& pt1, const POINT& pt2) +{ + return CalculateAngle(pt1.x, pt1.y, pt2.x, pt2.y); +} + +long CalculateDistance(long x1, long y1, long x2, long y2) +{ + return (long)::sqrt((double)((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))); +} + +BOOL PtInCircle(const POINT& pt, const POINT& ptOrigin, int nRadius) +{ + return CalculateDistance(pt, ptOrigin) < ::abs(nRadius); +} + +void NormalizeAngle(int& rAngle) +{ + if (::abs(rAngle) >= 360) + rAngle %= 360; + + if (rAngle < 0) + rAngle += 360; +} + +void NormalizeRect(RECT& rRect) +{ + NormalizeRect(&rRect); +} + +void NormalizeRect(LPRECT lpRect) +{ + if (lpRect == NULL) + return; + + long temp; + if (lpRect->left > lpRect->right) + { + temp = lpRect->left; + lpRect->left = lpRect->right; + lpRect->right = temp; + } + + if (lpRect->top > lpRect->bottom) + { + temp = lpRect->top; + lpRect->top = lpRect->bottom; + lpRect->bottom = temp; + } +} + +long CalculateAngle(long x1, long y1, long x2, long y2) +{ + // mathematic stuff, now thanks God I haven't forgot all of them... + if (x1 == x2 && y1 == y2) + return 0; + + double fAngle = 0.0; + + if (x1 == x2) + { + // vertical special case + fAngle = y2 > y1 ? 270.0 : 90.0; + } + else if (y1 == y2) + { + // horizontal special case + fAngle = x2 > x1 ? 0.0 : 180.0; + } + else + { + // common case + fAngle = ::atan(((double)y2 - (double)y1) / ((double)x2 - (double)x1)) * 180.0 / PI; + + // determine the phases (1-4) + // Phases allocation figure: + /* + y + | + P2 | P1 + | + -----------+----------->x + | + P3 | P4 + | + */ + int nPhase = 0; + if (y2 < y1) + nPhase = x2 > x1 ? 1 : 2; + else + nPhase =x2 > x1 ? 4 : 3; + + // adjust the angle according to phases + switch (nPhase) + { + case 1: + fAngle = -fAngle; + break; + + case 2: + fAngle = 180.0 - fAngle; + break; + + case 3: + fAngle = 180.0 - fAngle; + break; + + case 4: + fAngle = 360.0 - fAngle; + break; + + default: + fAngle = 0.0; + break; + } + } + + return (long)fAngle; +} + +POINT CalculatePointOnTrack(const POINT& ptOrigin, int nRadius, int nAngle) +{ + if (nRadius == 0) + return ptOrigin; + + NormalizeAngle(nAngle); + + POINT pt; + pt.x = long(double(ptOrigin.x) + ::cos((double)nAngle * PI / 180.0) * (double)nRadius); + pt.y = long(double(ptOrigin.y) - ::sin((double)nAngle * PI / 180.0) * (double)nRadius); + return pt; +} + +POINT CalculateRandomPosition(const POINT& ptOrigin, int nRadiusMin, int nRadiusMax, int nAngleMin/*=0*/, int nAngleMax/*=360*/) +{ + // Data validation + nRadiusMin = max(0, nRadiusMin); + nRadiusMax = max(0, nRadiusMax); + + NormalizeAngle(nAngleMin); + NormalizeAngle(nAngleMax); + + const int R1 = min(nRadiusMin, nRadiusMax); + const int R2 = max(nRadiusMin, nRadiusMax); + const int A1 = min(nAngleMin, nAngleMax); + const int A2 = max(nAngleMin, nAngleMax); + + const int R = (R1 == R2) ? R1 : (R1 + (::rand() % (R2 - R1))); // Final radius + const int A = (A1 == A2) ? A1 : (A1 + (::rand() % (A2 - A1))); // Final angle + + return CalculatePointOnTrack(ptOrigin, R, A); +} \ No newline at end of file diff --git a/Common.h b/Common.h new file mode 100644 index 00000000..86c056bb --- /dev/null +++ b/Common.h @@ -0,0 +1,19 @@ +////////////////////////////////////////////////////////// +// Common.h +//-------------------------------------------------------- +// Common algorithms for general uses. +// +// Abin (abinn32@yahoo.com) +////////////////////////////////////////////////////////// + + +long CalculateDistance(const POINT& pt1, const POINT& pt2); +long CalculateDistance(long x1, long y1, long x2, long y2); +long CalculateAngle(const POINT& pt1, const POINT& pt2); +long CalculateAngle(long x1, long y1, long x2, long y2); +void NormalizeAngle(int& rAngle); +void NormalizeRect(RECT& rRect); +void NormalizeRect(LPRECT lpRect); +POINT CalculatePointOnTrack(const POINT& ptOrigin, int nRadius, int nAngle); +POINT CalculateRandomPosition(const POINT& ptOrigin, int nRadiusMin, int nRadiusMax, int nAngleMin = 0, int nAngleMax = 360); +BOOL PtInCircle(const POINT& pt, const POINT& ptOrigin, int nRadius); diff --git a/Console.cpp b/Console.cpp new file mode 100644 index 00000000..be1bf67b --- /dev/null +++ b/Console.cpp @@ -0,0 +1,295 @@ +#include +#include + +#include "Console.h" +#include "ScriptEngine.h" +#include "Helpers.h" +#include "D2Ptrs.h" +#include "Core.h" + +bool Console::visible = false; +bool Console::enabled = false; +std::deque Console::history = std::deque(); +std::deque Console::lines = std::deque(); +std::deque Console::commands = std::deque(); +std::stringstream Console::cmd = std::stringstream(); +unsigned int Console::lineCount = 14; +unsigned int Console::commandPos = 0; +unsigned int Console::height = 0; +unsigned int Console::scrollIndex = 0; + +void Console::AddKey(unsigned int key) +{ + EnterCriticalSection(&Vars.cConsoleSection); + cmd << (char)key; + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::ExecuteCommand(void) +{ + if(cmd.str().length() < 1) + return; + + commands.push_back(cmd.str()); + commandPos = commands.size(); + + ProcessCommand(cmd.str().c_str(), true); + + cmd.str(""); +} + +void Console::RemoveLastKey(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + int len = cmd.str().length()-1; + if(len >= 0) + { + cmd.str(cmd.str().substr(0, len)); + if(len > 0) + { + cmd.seekg(len); + cmd.seekp(len); + } + } + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::PrevCommand(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + + if(commandPos < 1 || commandPos > commands.size()) + { + cmd.str(""); + } + else + { + if(commandPos >= 1) + commandPos--; + cmd.str(""); + cmd << commands[commandPos]; + } + + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::NextCommand(void) +{ + if(commandPos >= commands.size()) + return; + + EnterCriticalSection(&Vars.cConsoleSection); + + cmd.str(""); + cmd << commands[commandPos]; + + if (commandPos < commands.size() - 1) + commandPos++; + + LeaveCriticalSection(&Vars.cConsoleSection); +} +void Console::ScrollUp(void) +{ + if(scrollIndex == 0 || history.size() - scrollIndex ==0) + return; + EnterCriticalSection(&Vars.cConsoleSection); + scrollIndex--; + Console::UpdateLines(); + + LeaveCriticalSection(&Vars.cConsoleSection); +} +void Console::ScrollDown(void) +{ + if(history.size() < lineCount || (history.size()-lineCount == scrollIndex)) + return; + + EnterCriticalSection(&Vars.cConsoleSection); + scrollIndex++; + Console::UpdateLines(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::AddLine(std::string line) +{ + EnterCriticalSection(&Vars.cConsoleSection); + + // add the new line to the list + history.push_back(line); + + while(history.size() > 300) //set history cap at 300 + history.pop_front(); + + if(Vars.bLogConsole) + Log(const_cast(line.c_str())); + + scrollIndex =history.size() < lineCount ? 0 : history.size() - lineCount ; + Console::UpdateLines(); + + LeaveCriticalSection(&Vars.cConsoleSection); +} +void Console::UpdateLines(void) +{ +//while(lines.size() > lineCount) +// lines.pop_front(); + lines.clear(); + unsigned int lin =0; + for(int j = history.size()-scrollIndex ; j>0; j--){ + lines.push_back(history.at(history.size()-j)); + lin++; + if (lin > lineCount) break; + } + +} +void Console::Clear(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + lines.clear(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::Toggle(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + ToggleBuffer(); + TogglePrompt(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::TogglePrompt(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + if(!IsEnabled()) + ShowPrompt(); + else + HidePrompt(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::ToggleBuffer(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + if(!IsVisible()) + ShowBuffer(); + else + HideBuffer(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::Hide(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + HidePrompt(); + HideBuffer(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::HidePrompt(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + enabled = false; + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::HideBuffer(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + visible = false; + if(IsEnabled()) + HidePrompt(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::Show(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + ShowBuffer(); + ShowPrompt(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::ShowPrompt(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + enabled = true; + if(!IsVisible()) + ShowBuffer(); + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::ShowBuffer(void) +{ + EnterCriticalSection(&Vars.cConsoleSection); + visible = true; + LeaveCriticalSection(&Vars.cConsoleSection); +} + +void Console::Draw(void) +{ + static DWORD count = 0; + EnterCriticalSection(&Vars.cConsoleSection); + if(IsVisible()) + { + POINT size = GetScreenSize(); + int xsize = size.x; + int ysize = size.y; + // the default console height is 30% of the screen size + int height = (int)(((double)ysize)*.3); + size = CalculateTextLen(">", 0); + int charsize = size.x; + int charheight = size.y-10; + int cx = charsize+9; + int linelen = 115; + Console::height = height; + + int cmdsize = CalculateTextLen(cmd.str().c_str(), 0).x; + if((cmdsize/xsize) > 0) + Console::height += (cmdsize/xsize)*charheight + 1; + + // draw the box large enough to hold the whole thing + D2GFX_DrawRectangle(0, 0, xsize, Console::height, 0xdf, 0); + + std::deque::reverse_iterator it = lines.rbegin(); + for(int i = lineCount-1; i >= 0 && it != lines.rend(); i--, it++) + { + if(CalculateTextLen(it->c_str(), 0).x > (xsize - (2+charheight)*2)) + { + std::list buf; + SplitLines(*it, linelen, ' ', buf); + for(std::list::iterator it = buf.begin(); it != buf.end(); it++) + myDrawText(it->c_str(), 2+charheight, 2+charheight+((i--)*charheight), 0, 0); + } else + myDrawText(it->c_str(), 2+charheight, 2+charheight+(i*charheight), 0, 0); + } + + if(IsEnabled()) + { + myDrawText(">", 1, height, 0, 0); + int lx = cx + cmdsize - charsize + 5, + ly = height-charheight; + if(count % 30) + D2GFX_DrawLine(lx, ly, lx, height-2, 0xFF, 0xFF); + + std::string cmdstr = cmd.str(); + if(cmdstr.length() > 0) + { + if((cmdsize/xsize) > 0) + { + std::list lines; + SplitLines(cmdstr, linelen, ' ', lines); + int i = 0; + for(std::list::iterator it = lines.begin(); it != lines.end(); it++, i++) + myDrawText(it->c_str(), charsize+5, height+(charheight*i)+1, 0, 0); + } else + myDrawText(cmdstr.c_str(), charsize+5, height+1, 0, 0); + } + } + } + LeaveCriticalSection(&Vars.cConsoleSection); + + count++; +} + +unsigned int Console::GetHeight(void) +{ + return height; +} diff --git a/Console.h b/Console.h new file mode 100644 index 00000000..ad24a318 --- /dev/null +++ b/Console.h @@ -0,0 +1,48 @@ +#pragma once +#ifndef __CONSOLE_H__ +#define __CONSOLE_H__ + +#include +#include +#include +#include + +#include "D2BS.h" + +class Console +{ +private: + static bool visible, enabled; + static std::deque lines, commands,history; + static unsigned int lineCount, commandPos, height , scrollIndex; + static std::stringstream cmd; + +public: + + static void Toggle(void); + static void TogglePrompt(void); + static void ToggleBuffer(void); + static void Hide(void); + static void HidePrompt(void); + static void HideBuffer(void); + static void Show(void); + static void ShowPrompt(void); + static void ShowBuffer(void); + static bool IsVisible(void) { return visible; } + static bool IsEnabled(void) { return enabled; } + + static void AddKey(unsigned int key); + static void ExecuteCommand(void); + static void RemoveLastKey(void); + static void PrevCommand(void); + static void NextCommand(void); + static void ScrollUp(void); + static void ScrollDown(void); + static void AddLine(std::string line); + static void UpdateLines(void); + static void Clear(void); + static void Draw(void); + static unsigned int GetHeight(void); +}; + +#endif diff --git a/Constants.h b/Constants.h new file mode 100644 index 00000000..5c0f98d7 --- /dev/null +++ b/Constants.h @@ -0,0 +1,856 @@ +#ifndef _CONSTANTS_H +#define _CONSTANTS_H + +////////////////////////////////////////////////////////////////////// +// Attack Types +////////////////////////////////////////////////////////////////////// +#define ATTACKTYPE_SHIFTLEFT 0xE5 +#define ATTACKTYPE_UNITLEFT 0xC5 +#define ATTACKTYPE_SHIFTRIGHT 0x66 +#define ATTACKTYPE_RIGHT 0x46 + +/////////////////////////////////////////////////// +// Game UI Flags(From D2JSP, updated with info from TheUnknownSoldier) +/////////////////////////////////////////////////// +#define UI_GAME 0x00 +#define UI_INVENTORY 0x01 +#define UI_CHARACTER 0x02 +#define UI_MINISKILL 0x03 +#define UI_SKILLTREE 0x04 +#define UI_CHAT_CONSOLE 0x05 +#define UI_UNK 0x06 //auto disabled +#define UI_UNK_EX 0x07 //auto disabled +#define UI_NPCMENU 0x08 +#define UI_DIALOG 0x08 +#define UI_ESCMENU_MAIN 0x09 +#define UI_AUTOMAP 0x0A +#define UI_HOTKEY_CONFIG 0x0B +#define UI_NPCSHOP 0x0C +#define UI_ALTDOWN 0x0D +#define UI_GROUND_ITEMS 0x0D +#define UI_ANVIL 0x0E +#define UI_QUEST 0x0F +#define UI_BARKSCROLL 0x10 +#define UI_QUEST_LOG 0x11 +#define UI_STATUS_AREA 0x12 +#define UI_ESCMENU_EX 0x13 +#define UI_WPMENU 0x14 //Waypoints Menu +#define UI_MINIPANEL 0x15 +#define UI_PARTY 0x16 +#define UI_TRADE 0x17 +#define UI_MESSAGE_LOG 0x18 +#define UI_STASH 0x19 +#define UI_CUBE 0x1A +#define UI_UNUSED 0x1B +#define UI_INVENTORY_EX 0x1C +#define UI_INVENTORY_EXX 0x1D +#define UI_UNUSED_EX 0x1E +#define UI_BELT 0x1F +#define UI_UNUSED_EXX 0x20 +#define UI_HELP_MENU 0x21 +#define UI_HELP_BUTTON 0x22 +#define UI_ESCMENU 0x23 //unused?? +#define UI_MERC 0x24 +#define UI_SCROLL 0x25 + +/////////////////////////////////////////////////// +// Control types +/////////////////////////////////////////////////// +#define CONTROL_EDITBOX 0x01 +#define CONTROL_IMAGE 0x02 +#define CONTROL_UNUSED 0x03 +#define CONTROL_TEXTBOX 0x04 +#define CONTROL_SCROLLBAR 0x05 +#define CONTROL_BUTTON 0x06 +#define CONTROL_LIST 0x07 +#define CONTROL_TIMER 0x08 +#define CONTROL_SMACK 0x09 +#define CONTROL_PROGRESSBAR 0x0a +#define CONTROL_POPUP 0x0b +#define CONTROL_ACCOUNTLIST 0x0c + +/////////////////////////////////////////////////// +// Out of Game Locations (From ControlInfo.dbl) +/////////////////////////////////////////////////// +enum OOG_Location { + OOG_NONE = 0, + OOG_LOBBY, + OOG_INLINE, + OOG_CHAT, + OOG_CREATE, + OOG_JOIN, + OOG_LADDER, + OOG_CHANNEL, + OOG_MAIN_MENU, + OOG_LOGIN, + OOG_LOGIN_ERROR, + OOG_UNABLE_TO_CONNECT, + OOG_CHAR_SELECT, + OOG_REALM_DOWN, + OOG_DISCONNECTED, + OOG_NEW_CHARACTER, + OOG_CHARACTER_SELECT_PLEASE_WAIT, + OOG_LOST_CONNECTION, + OOG_D2SPLASH, + OOG_CDKEY_IN_USE, + OOG_DIFFICULTY, + OOG_MAIN_MENU_CONNECTING, + OOG_INVALID_CDKEY, + OOG_CONNECTING, // not used. OOG_CHARACTER_SELECT_NO_CHARS with a connecting message + OOG_SERVER_DOWN, + OOG_PLEASE_WAIT, + OOG_GAME_EXIST, + OOG_GATEWAY, + OOG_GAME_DOES_NOT_EXIST, + OOG_CHARACTER_CREATE, + OOG_CHARACTER_CREATE_ALREADY_EXISTS, + OOG_AGREE_TO_TERMS, + OOG_NEW_ACCOUNT, + OOG_PLEASE_READ, + OOG_REGISTER_EMAIL, + OOG_CREDITS, + OOG_CINEMATICS, + OOG_CHARACTOR_CHANGE_REALM, + OOG_GAME_IS_FULL, + OOG_OTHER_MULTIPLAYER, + OOG_TCP_IP, + OOG_ENTER_IP_ADDRESS, + OOG_CHARACTER_SELECT_NO_CHARS, + OOG_CHARACTER_SELECT_CHANGE_REALM, +}; +////////////////////////////////////////////////////////////////////// +// PVP Flags +////////////////////////////////////////////////////////////////////// +#define PVP_INVITED_YOU 0x01 // Invited you, but you may not have accepted +#define PVP_INVITED_BY_YOU 0x02 // Invited by you, but he may not have accepted +#define PVP_ALLIED 0x04 // Allied +#define PVP_HOSTILED_YOU 0x08 // Hostiled you, but you may not have hostiled him +#define PVP_HOSTILED_BY_YOU 0x10 // Hostiled by you, but he may not have hostiled you + +////////////////////////////////////////////////////////////////////////// +// Player Type Flags +////////////////////////////////////////////////////////////////////////// +#define PLAYER_TYPE_HARDCORE 4 +#define PLAYER_TYPE_EXPAC 32 +#define PLAYER_TYPE_LADDER 64 + +////////////////////////////////////////////////////////////////////////// +// Trade Flags +////////////////////////////////////////////////////////////////////////// +#define TRADE_OPEN 3 +#define TRADE_ACCEPTED 5 +#define TRADE_ACCEPT 7 + +/////////////////////////////////////////////////// +// Mercenary Class ID's +/////////////////////////////////////////////////// +#define MERC_A1 0x010f +#define MERC_A2 0x0152 +#define MERC_A3 0x0167 +#define MERC_A5 0x0231 + +/////////////////////////////////////////////////// +// Unit Stat ID Definition (Partial) +/////////////////////////////////////////////////// +#define STAT_STRENGTH 0 // str +#define STAT_ENERGY 1 // energy +#define STAT_DEXTERITY 2 // dexterity +#define STAT_VITALITY 3 // vitality +#define STAT_STATPOINTSLEFT 4 +#define STAT_SKILLPOINTSLEFT 5 +#define STAT_HP 6 // life +#define STAT_MAXHP 7 // max life +#define STAT_MANA 8 // mana +#define STAT_MAXMANA 9 // max mana +#define STAT_STAMINA 10 // stamina +#define STAT_MAXSTAMINA 11 // max stamina +#define STAT_LEVEL 12 // level +#define STAT_EXP 13 // experience +#define STAT_GOLD 14 // gold +#define STAT_GOLDBANK 15 // stash gold +#define STAT_TOBLOCK 20 // to block +#define STAT_DAMAGEREDUCTION 36 // damage reduction +#define STAT_MAGICDAMAGEREDUCTION 35 // magic damage reduction +#define STAT_MAGICRESIST 37 // magic resist +#define STAT_MAXMAGICRESIST 38 // max magic resist +#define STAT_FIRERESIST 39 // fire resist +#define STAT_MAXFIRERESIST 40 // max fire resist +#define STAT_LIGHTNINGRESIST 41 // lightning resist +#define STAT_MAXLIGHTNINGRESIST 42 // max lightning resist +#define STAT_COLDRESIST 43 // cold resist +#define STAT_MAXCOLDRESIST 44 // max cold resist +#define STAT_POISONRESIST 45 // poison resist +#define STAT_MAXPOISONRESIST 46 // max poison resist +#define STAT_LIFELEECH 60 // Life Leech +#define STAT_MANALEECH 62 // Mana Leech +#define STAT_VELOCITYPERCENT 67 // effective run/walk +#define STAT_AMMOQUANTITY 70 // ammo quantity(arrow/bolt/throwing) +#define STAT_DURABILITY 72 // item durability +#define STAT_MAXDURABILITY 73 // max item durability +#define STAT_GOLDFIND 79 // Gold find (GF) +#define STAT_MAGICFIND 80 // magic find (MF) +#define STAT_IAS 93 // IAS +#define STAT_FASTERRUNWALK 96 // faster run/walk +#define STAT_FASTERHITRECOVERY 99 // faster hit recovery +#define STAT_FASTERBLOCK 102 // faster block rate +#define STAT_FASTERCAST 105 // faster cast rate +#define STAT_POISONLENGTHREDUCTION 110 // Poison length reduction +#define STAT_OPENWOUNDS 135 // Open Wounds +#define STAT_CRUSHINGBLOW 136 // crushing blow +#define STAT_DEADLYSTRIKE 141 // deadly strike +#define STAT_FIREABSORBPERCENT 142 // fire absorb % +#define STAT_FIREABSORB 143 // fire absorb +#define STAT_LIGHTNINGABSORBPERCENT 144 // lightning absorb % +#define STAT_LIGHTNINGABSORB 145 // lightning absorb +#define STAT_COLDABSORBPERCENT 148 // cold absorb % +#define STAT_COLDABSORB 149 // cold absorb +#define STAT_SLOW 150 // slow % + +/////////////////////////////////////////////////// +// NodePages +/////////////////////////////////////////////////// +#define NODEPAGE_STORAGE 1 +#define NODEPAGE_BELTSLOTS 2 +#define NODEPAGE_EQUIP 3 + + +/////////////////////////////////////////////////// +// Body Locations +/////////////////////////////////////////////////// +enum { EQUIP_NONE = 0, // Not equipped +EQUIP_HEAD, // Head +EQUIP_AMULET, // Amulet +EQUIP_BODY, // Body armor +EQUIP_RIGHT_PRIMARY, // Right primary slot +EQUIP_LEFT_PRIMARY, // Left primary slot +EQUIP_RIGHT_RING, // Right ring +EQUIP_LEFT_RING, // Left ring +EQUIP_BELT, // Belt +EQUIP_FEET, // Feet +EQUIP_GLOVES, // Gloves +EQUIP_RIGHT_SECONDARY, // Right secondary slot +EQUIP_LEFT_SECONDARY, // Left secondary slot +}; + +/////////////////////////////////////////////////// +// Storage Buffers +/////////////////////////////////////////////////// +#define STORAGE_INVENTORY 0 +#define STORAGE_EQUIP 1 +#define STORAGE_BELT 2 +#define STORAGE_CUBE 3 +#define STORAGE_STASH 4 +#define STORAGE_NULL 255 + +/////////////////////////////////////////////////// +// Item Quality +/////////////////////////////////////////////////// +#define ITEM_QUALITY_INFERIOR 0x01 +#define ITEM_QUALITY_NORMAL 0x02 +#define ITEM_QUALITY_SUPERIOR 0x03 +#define ITEM_QUALITY_MAGIC 0x04 +#define ITEM_QUALITY_SET 0x05 +#define ITEM_QUALITY_RARE 0x06 +#define ITEM_QUALITY_UNIQUE 0x07 +#define ITEM_QUALITY_CRAFT 0x08 + +/////////////////////////////////////////////////// +// Player Mode Definition +/////////////////////////////////////////////////// +enum { PLAYER_MODE_DEATH = 0, // death +PLAYER_MODE_STAND_OUTTOWN, // standing outside town +PLAYER_MODE_WALK_OUTTOWN, // walking outside town +PLAYER_MODE_RUN, // running +PLAYER_MODE_BEING_HIT, // being hit +PLAYER_MODE_STAND_INTOWN, // standing inside town +PLAYER_MODE_WALK_INTOWN, // walking outside town +PLAYER_MODE_ATTACK1, // attacking 1 +PLAYER_MODE_ATTACK2, // attacking 2 +PLAYER_MODE_BLOCK, // blocking +PLAYER_MODE_CAST, // casting spell +PLAYER_MODE_THROW, // throwing +PLAYER_MODE_KICK, // kicking (assassin) +PLAYER_MODE_USESKILL1, // using skill 1 +PLAYER_MODE_USESKILL2, // using skill 2 +PLAYER_MODE_USESKILL3, // using skill 3 +PLAYER_MODE_USESKILL4, // using skill 4 +PLAYER_MODE_DEAD, // dead +PLAYER_MODE_SEQUENCE, // sequence +PLAYER_MODE_BEING_KNOCKBACK }; // being knocked back + + +/////////////////////////////////////////////////// +// NPC Mode Definition +/////////////////////////////////////////////////// +enum { NPC_MODE_DEATH = 0, // NPC death +NPC_MODE_STAND, // NPC standing still +NPC_MODE_WALK, // NPC walking +NPC_MODE_BEING_HIT, // NPC getting hit +NPC_MODE_ATTACK1, // NPC attacking 1 +NPC_MODE_ATTACK2, // NPC attacking 2 +NPC_MODE_BLOCK, // NPC blocking +NPC_MODE_CAST, // NPC casting spell skill +NPC_MODE_USESKILL1, // NPC using skill 1 +NPC_MODE_USESKILL2, // NPC using skill 2 +NPC_MODE_USESKILL3, // NPC using skill 3 +NPC_MODE_USESKILL4, // NPC using skill 4 +NPC_MODE_DEAD, // NPC dead +NPC_MODE_BEING_KNOCKBACK, // NPC being knocked back +NPC_MODE_SEQUENCE, // NPC sequence +NPC_MODE_RUN }; // NPC running + +/////////////////////////////////////////////////// +// Object Mode Definition +/////////////////////////////////////////////////// +enum { OBJ_MODE_IDLE = 0, // Object idle +OBJ_MODE_OPERATING, // Object operating +OBJ_MODE_OPENED, // Object opened +OBJ_MODE_SPECIAL1, // Object special 1 +OBJ_MODE_SPECIAL2, // Object special 2 +OBJ_MODE_SPECIAL3, // Object special 3 +OBJ_MODE_SPECIAL4, // Object special 4 +OBJ_MODE_SPECIAL5 }; // Object special 5 + +/////////////////////////////////////////////////// +// Item Mode Definition +/////////////////////////////////////////////////// +enum { ITEM_MODE_INV_STASH_CUBE_STORE = 0, // Item inven stash cube store +ITEM_MODE_EQUIPPED, // Item equipped self or merc +ITEM_MODE_IN_BELT, // Item in belt +ITEM_MODE_ON_GROUND, // Item on ground +ITEM_MODE_ON_CURSOR, // Item on cursor +ITEM_MODE_BEING_DROPPED, // Item being dropped +ITEM_MODE_SOCKETED_IN_ITEM }; // Item socketed in item + +/////////////////////////////////////////////////// +// Unit Types +/////////////////////////////////////////////////// +#define UNIT_PLAYER 0 +#define UNIT_MONSTER 1 +#define UNIT_OBJECT 2 +#define UNIT_MISSILE 3 +#define UNIT_ITEM 4 +#define UNIT_TILE 5 + +/////////////////////////////////////////////////// +// Spell Stats +/////////////////////////////////////////////////// +#define DSI_PASSIVE 0x00000001 // Spell is passive +#define DSI_RIGHTONLY 0x00000002 // Spell must be on right side, like paladin auras +#define DSI_TARGETABLE 0x00000004 // Spell cannot target, like Nova +#define DSI_NEEDCORPSE 0x00000008 // Spell requires a corpse, like Revive +#define DSI_ENABLEINTOWN 0x00000010 // Spell is enabled in town +#define DSI_PHYSICAL 0x00000020 // Spell causes physical damage +#define DSI_MAGICAL 0x00000040 // Spell causes magical damage +#define DSI_FIRE 0x00000080 // Spell causes fire damage +#define DSI_COLD 0x00000100 // Spell causes cold damage +#define DSI_LIGHTNING 0x00000200 // Spell causes lightning damage +#define DSI_POISON 0x00000400 // Spell causes poison damage +#define DSI_KNOCKBACK 0x00000800 // Spell knocks target(s) back +#define DSI_STUN 0x00001000 // Spell stuns target(s) +#define DSI_AFFECTGROUP 0x00002000 // Spell affects multuple targets +#define DSI_MELEE 0x00004000 // Spell only affects target(s) within melee range +#define DSI_SUMMON 0x00008000 // Spell summons minion(s), like Valkyrie +#define DSI_PARTYCAST 0x00010000 // Spell castable on other party members +#define DSI_GUIDED 0x00020000 // Spell is guided to enemies + +/////////////////////////////////////////////////// +// Character Classes +/////////////////////////////////////////////////// +enum { + CLASS_AMA = 0, + CLASS_SOR, + CLASS_NEC, + CLASS_PAL, + CLASS_BAR, + CLASS_DRU, + CLASS_ASN, + CLASS_NA}; + + /////////////////////////////////////////////////// + // Common Spells + /////////////////////////////////////////////////// + +#define D2S_INVALID 0xffff // should never happen +#define D2S_ATTACK 0x0000 +#define D2S_KICK 0x0001 +#define D2S_THROW 0x0002 +#define D2S_UNSUMMON 0x0003 +#define D2S_LEFTTHROW 0x0004 +#define D2S_LEFTSWING 0x0005 +#define D2S_TOMEOFIDENTIFY 0x00da +#define D2S_SCROLLOFIDENTIFY 0x00d9 +#define D2S_TOMEOFTOWNPORTAL 0x00dc +#define D2S_SCROLLOFTOWNPORTAL 0x00db + + /////////////////////////////////////////////////////////////// + // Amazon Spells + /////////////////////////////////////////////////////////////// + + // Javelin and Spear spells +#define D2S_JAB 0x000a +#define D2S_IMPALE 0x0013 +#define D2S_FEND 0x001e +#define D2S_POWERSTRIKE 0x000e +#define D2S_CHARGEDSTRIKE 0x0018 +#define D2S_LIGHTNINGSTRIKE 0x0022 +#define D2S_POISONJAVELIN 0x000f +#define D2S_LIGHTNINGBOLT 0x0014 +#define D2S_PLAGUEJAVELIN 0x0019 +#define D2S_LIGHTNINGFURY 0x0023 + + // Passive and Magic spells +#define D2S_INNERSIGHT 0x0008 +#define D2S_SLOWMISSILES 0x0011 +#define D2S_DECOY 0x001c +#define D2S_VALKYRIE 0x0020 +#define D2S_DODGE 0x000d +#define D2S_AVOID 0x0012 +#define D2S_EVADE 0x001d +#define D2S_CRITICALSTRIKE 0x0009 +#define D2S_PENETRATE 0x0017 +#define D2S_PIERCE 0x0021 + + // Bow and Crossbow spells +#define D2S_COLDARROW 0x000b +#define D2S_ICEARROW 0x0015 +#define D2S_FREEZINGARROW 0x001f +#define D2S_MAGICARROW 0x0006 +#define D2S_MULTIPLESHOT 0x000c +#define D2S_GUIDEDARROW 0x0016 +#define D2S_STRAFE 0x001a +#define D2S_FIREARROW 0x0007 +#define D2S_EXPLODINGARROW 0x0010 +#define D2S_IMMOLATIONARROW 0x001b + + + /////////////////////////////////////////////////////////////// + // Assassin Spells + /////////////////////////////////////////////////////////////// + + // Martial Arts +#define D2S_FISTSOFFIRE 0x0103 +#define D2S_CLAWSOFTHUNDER 0x010d +#define D2S_BLADESOFICE 0x0112 +#define D2S_TIGERSTRIKE 0x00fe +#define D2S_COBRASTRIKE 0x0109 +#define D2S_PHOENIXSTRIKE 0x0118 +#define D2S_DRAGONTALON 0x00ff +#define D2S_DRAGONCLAW 0x0104 +#define D2S_DRAGONTAIL 0x010e +#define D2S_DRAGONFLIGHT 0x0113 + + // Shadow Disciplines +#define D2S_BURSTOFSPEED 0x0102 +#define D2S_FADE 0x010b +#define D2S_VENOM 0x0116 +#define D2S_CLAWMASTERY 0x00fc +#define D2S_WEAPONBLOCK 0x0107 +#define D2S_SHADOWWARRIOR 0x010c +#define D2S_SHADOWMASTER 0x0117 +#define D2S_PSYCHICHAMMER 0x00fd +#define D2S_CLOAKOFSHADOWS 0x0108 +#define D2S_MINDBLAST 0x0111 + + // Traps +#define D2S_SHOCKWEB 0x0100 +#define D2S_CHARGEDBOLTSENTRY 0x0105 +#define D2S_LIGHTNINGSENTRY 0x010f +#define D2S_DEATHSENTRY 0x0114 +#define D2S_FIREBLAST 0x00fb +#define D2S_WAKEOFFIRE 0x0106 +#define D2S_WAKEOFINFERNO 0x0110 +#define D2S_BLADESENTINEL 0x0101 +#define D2S_BLADEFURY 0x010a +#define D2S_BLADESHIELD 0x0115 + + + /////////////////////////////////////////////////////////////// + // Barbarian Spells + /////////////////////////////////////////////////////////////// + + // Warcries +#define D2S_HOWL 0x0082 +#define D2S_TAUNT 0x0089 +#define D2S_BATTLECRY 0x0092 +#define D2S_WARCRY 0x009a +#define D2S_SHOUT 0x008a +#define D2S_BATTLEORDERS 0x0095 +#define D2S_BATTLECOMMAND 0x009b +#define D2S_FINDPOTION 0x0083 +#define D2S_FINDITEM 0x008e +#define D2S_GRIMWARD 0x0096 + + // Combat Masteries +#define D2S_SWORDMASTERY 0x007f +#define D2S_POLEARMMASTERY 0x0086 +#define D2S_INCREASEDSTAMINA 0x008d +#define D2S_INCREASEDSPEED 0x0094 +#define D2S_AXEMASTERY 0x0080 +#define D2S_THROWINGMASTERY 0x0087 +#define D2S_MACEMASTERY 0x0081 +#define D2S_SPEARMASTERY 0x0088 +#define D2S_IRONSKIN 0x0091 +#define D2S_NATURALRESISTANCE 0x0099 + + // Combat spells +#define D2S_LEAP 0x0084 +#define D2S_LEAPATTACK 0x008f +#define D2S_WHIRLWIND 0x0097 +#define D2S_BASH 0x007e +#define D2S_STUN 0x008b +#define D2S_CONCENTRATE 0x0090 +#define D2S_BERSERK 0x0098 +#define D2S_DOUBLESWING 0x0085 +#define D2S_DOUBLETHROW 0x008c +#define D2S_FRENZY 0x0093 + + + /////////////////////////////////////////////////////////////// + // Druid Spells + /////////////////////////////////////////////////////////////// + + // Elemental +#define D2S_FIRESTORM 0x00e1 +#define D2S_MOLTENBOULDER 0x00e5 +#define D2S_FISSURE 0x00ea +#define D2S_VOLCANO 0x00f4 +#define D2S_ARMAGEDDON 0x00f9 +#define D2S_TWISTER 0x00f0 +#define D2S_TORNADO 0x00f5 +#define D2S_HURRICANE 0x00fa +#define D2S_ARCTICBLAST 0x00e6 +#define D2S_CYCLONEARMOR 0x00eb + + // Shape Shifting +#define D2S_WEREWOLF 0x00df +#define D2S_FERALRAGE 0x00e8 +#define D2S_RABIES 0x00ee +#define D2S_FURY 0x00f8 +#define D2S_LYCANTHROPY 0x00e0 +#define D2S_FIRECLAWS 0x00ef +#define D2S_HUNGER 0x00f2 +#define D2S_WEREBEAR 0x00e4 +#define D2S_MAUL 0x00e9 +#define D2S_SHOCKWAVE 0x00f3 + + // Summoning +#define D2S_OAKSAGE 0x00e2 +#define D2S_HEARTOFWOLVERINE 0x00ec +#define D2S_SPIRITOFBARBS 0x00f6 +#define D2S_RAVEN 0x00dd +#define D2S_SUMMONSPIRITWOLF 0x00e3 +#define D2S_SUMMONDIREWOLF 0x00ed +#define D2S_SUMMONGRIZZLY 0x00f7 +#define D2S_POISONCREEPER 0x00de +#define D2S_CARRIONVINE 0x00e7 +#define D2S_SOLARCREEPER 0x00f1 + + + /////////////////////////////////////////////////////////////// + // Necromancer Spells + /////////////////////////////////////////////////////////////// + + // Summoning Spells +#define D2S_SKELETONMASTERY 0x0045 +#define D2S_GOLEMMASTERY 0x004f +#define D2S_SUMMONRESIST 0x0059 +#define D2S_CLAYGOLEM 0x004b +#define D2S_BLOODGOLEM 0x0055 +#define D2S_IRONGOLEM 0x005a +#define D2S_FIREGOLEM 0x005e +#define D2S_RAISESKELETON 0x0046 +#define D2S_RAISESKELETALMAGE 0x0050 +#define D2S_REVIVE 0x005f + + // Poison and Bone Spells +#define D2S_POISONDAGGER 0x0049 +#define D2S_POISONEXPLOSION 0x0053 +#define D2S_POISONNOVA 0x005c +#define D2S_TEETH 0x0043 +#define D2S_CORPOSEEXPLOSION 0x004a +#define D2S_BONESPEAR 0x0054 +#define D2S_BONESPIRIT 0x005d +#define D2S_BONEARMOR 0x0044 +#define D2S_BONEWALL 0x004e +#define D2S_BONEPRISON 0x0058 + + // Curses +#define D2S_DIMVISION 0x0047 +#define D2S_CONFUSE 0x0051 +#define D2S_ATTRACT 0x0056 +#define D2S_AMPLIFYDAMAGE 0x0042 +#define D2S_IRONMAIDEN 0x004c +#define D2S_LIFETAP 0x0052 +#define D2S_LOWERRESIST 0x005b +#define D2S_WEAKEN 0x0048 +#define D2S_TERROR 0x004d +#define D2S_DECREPIFY 0x0057 + + + /////////////////////////////////////////////////////////////// + // Paladin Spells + /////////////////////////////////////////////////////////////// + + // Defensive Auras +#define D2S_PRAYER 0x0063 +#define D2S_CLEANSING 0x006d +#define D2S_MEDITATION 0x0078 +#define D2S_DEFIANCE 0x0068 +#define D2S_VIGOR 0x0073 +#define D2S_REDEMPTION 0x007c +#define D2S_RESISTFIRE 0x0064 +#define D2S_RESISTCOLD 0x0069 +#define D2S_RESISTLIGHTNING 0x006e +#define D2S_SALVATION 0x007d + + // Offensive Auras +#define D2S_MIGHT 0x0062 +#define D2S_BLESSEDAIM 0x006c +#define D2S_CONCENTRATION 0x0071 +#define D2S_FANATICISM 0x007a +#define D2S_HOLYFIRE 0x0066 +#define D2S_HOLYFREEZE 0x0072 +#define D2S_HOLYSHOCK 0x0076 +#define D2S_THORNS 0x0067 +#define D2S_SANCTUARY 0x0077 +#define D2S_CONVICTION 0x007b + + // Combat spells +#define D2S_SACRIFICE 0x0060 +#define D2S_ZEAL 0x006a +#define D2S_VENGEANCE 0x006f +#define D2S_CONVERSION 0x0074 +#define D2S_HOLYBOLT 0x0065 +#define D2S_BLESSEDHAMMER 0x0070 +#define D2S_FISTOFTHEHEAVENS 0x0079 +#define D2S_SMITE 0x0061 +#define D2S_CHARGE 0x006b +#define D2S_HOLYSHIELD 0x0075 + + + /////////////////////////////////////////////////////////////// + // Sorceress Spells + /////////////////////////////////////////////////////////////// + + // Cold Spells +#define D2S_FROSTNOVA 0x002c +#define D2S_BLIZZARD 0x003b +#define D2S_FROZENORB 0x0040 +#define D2S_ICEBOLT 0x0027 +#define D2S_ICEBLAST 0x002d +#define D2S_GLACIALSPIKE 0x0037 +#define D2S_COLDMASTERY 0x0041 +#define D2S_FROZENARMOR 0x0028 +#define D2S_SHIVERARMOR 0x0032 +#define D2S_CHILLINGARMOR 0x003c + + // Lightning Spells +#define D2S_STATICFIELD 0x002a +#define D2S_NOVA 0x0030 +#define D2S_THUNDERSTORM 0x0039 +#define D2S_CHARGEDBOLT 0x0026 +#define D2S_LIGHTNING 0x0031 +#define D2S_CHAINLIGHTNING 0x0035 +#define D2S_LIGHTNINGMASTERY 0x003f +#define D2S_TELEKINESIS 0x002b +#define D2S_TELEPORT 0x0036 +#define D2S_ENERGYSHIELD 0x003a + + // Fire Spells +#define D2S_INFERNO 0x0029 +#define D2S_BLAZE 0x002e +#define D2S_FIREWALL 0x0033 +#define D2S_FIREBOLT 0x0024 +#define D2S_FIREBALL 0x002f +#define D2S_METEOR 0x0038 +#define D2S_FIREMASTERY 0x003d +#define D2S_WARMTH 0x0025 +#define D2S_ENCHANT 0x0034 +#define D2S_HYDRA 0x003e + + /////////////////////////////////////////////////// + // Map Definition + /////////////////////////////////////////////////// +#define MAP_UNKNOWN 0x00 + + /////////////////////////////////////////////////// + // Act 1 Maps + /////////////////////////////////////////////////// +#define MAP_A1_ROGUE_ENCAMPMENT 0x01 +#define MAP_A1_BLOOD_MOOR 0x02 +#define MAP_A1_COLD_PLAINS 0x03 +#define MAP_A1_STONY_FIELD 0x04 +#define MAP_A1_DARK_WOOD 0x05 +#define MAP_A1_BLACK_MARSH 0x06 +#define MAP_A1_TAMOE_HIGHLAND 0x07 +#define MAP_A1_DEN_OF_EVIL 0x08 +#define MAP_A1_CAVE_LEVEL_1 0x09 // Cave in Cold plains +#define MAP_A1_UNDERGROUND_PASSAGE_LEVEL_1 0x0a +#define MAP_A1_HOLE_LEVEL_1 0x0b +#define MAP_A1_PIT_LEVEL_1 0x0c +#define MAP_A1_CAVE_LEVEL_2 0x0d // Cave in Cold plains +#define MAP_A1_UNDERGROUND_PASSAGE_LEVEL_2 0x0e +#define MAP_A1_HOLE_LEVEL_2 0x0f +#define MAP_A1_PIT_LEVEL_2 0x10 +#define MAP_A1_BURIAL_GROUNDS 0x11 +#define MAP_A1_CRYPT 0x12 +#define MAP_A1_MAUSOLEUM 0x13 +#define MAP_A1_FORGOTTEN_TOWER 0x14 +#define MAP_A1_TOWER_CELLAR_LEVEL_1 0x15 +#define MAP_A1_TOWER_CELLAR_LEVEL_2 0x16 +#define MAP_A1_TOWER_CELLAR_LEVEL_3 0x17 +#define MAP_A1_TOWER_CELLAR_LEVEL_4 0x18 +#define MAP_A1_TOWER_CELLAR_LEVEL_5 0x19 +#define MAP_A1_MONASTERY_GATE 0x1a +#define MAP_A1_OUTER_CLOISTER 0x1b +#define MAP_A1_BARRACKS 0x1c +#define MAP_A1_JAIL_LEVEL_1 0x1d +#define MAP_A1_JAIL_LEVEL_2 0x1e +#define MAP_A1_JAIL_LEVEL_3 0x1f +#define MAP_A1_INNER_CLOISTER 0x20 +#define MAP_A1_INNER_CLOISTER_2 0x21 +#define MAP_A1_CATACOMBS_LEVEL_1 0x22 +#define MAP_A1_CATACOMBS_LEVEL_2 0x23 +#define MAP_A1_CATACOMBS_LEVEL_3 0x24 +#define MAP_A1_CATACOMBS_LEVEL_4 0x25 +#define MAP_A1_TRISTRAM 0x26 +#define MAP_A1_THE_SECRET_COW_LEVEL 0x27 + + + /////////////////////////////////////////////////// + // Act 2 Maps + /////////////////////////////////////////////////// +#define MAP_A2_LUT_GHOLEIN 0x28 +#define MAP_A2_ROCKY_WASTE 0x29 +#define MAP_A2_DRY_HILLS 0x2a +#define MAP_A2_FAR_OASIS 0x2b +#define MAP_A2_LOST_CITY 0x2c +#define MAP_A2_VALLEY_OF_SNAKES 0x2d +#define MAP_A2_CANYON_OF_THE_MAGI 0x2e +#define MAP_A2_SEWERS_LEVEL_1 0x2f +#define MAP_A2_SEWERS_LEVEL_2 0x30 +#define MAP_A2_SEWERS_LEVEL_3 0x31 +#define MAP_A2_HAREM_LEVEL_1 0x32 +#define MAP_A2_HAREM_LEVEL_2 0x33 +#define MAP_A2_PALACE_CELLAR_LEVEL_1 0x34 +#define MAP_A2_PALACE_CELLAR_LEVEL_2 0x35 +#define MAP_A2_PALACE_CELLAR_LEVEL_3 0x36 +#define MAP_A2_STONY_TOMB_LEVEL_1 0x37 +#define MAP_A2_HALLS_OF_THE_DEAD_LEVEL_1 0x38 +#define MAP_A2_HALLS_OF_THE_DEAD_LEVEL_2 0x39 +#define MAP_A2_CLAW_VIPER_TEMPLE_LEVEL_1 0x3a +#define MAP_A2_STONY_TOMB_LEVEL_2 0x3b +#define MAP_A2_HALLS_OF_THE_DEAD_LEVEL_3 0x3c +#define MAP_A2_CLAW_VIPER_TEMPLE_LEVEL_2 0x3d +#define MAP_A2_MAGGOT_LAIR_LEVEL_1 0x3e +#define MAP_A2_MAGGOT_LAIR_LEVEL_2 0x3f +#define MAP_A2_MAGGOT_LAIR_LEVEL_3 0x40 +#define MAP_A2_ANCIENT_TUNNELS 0x41 +#define MAP_A2_TAL_RASHAS_TOMB_1 0x42 +#define MAP_A2_TAL_RASHAS_TOMB_2 0x43 +#define MAP_A2_TAL_RASHAS_TOMB_3 0x44 +#define MAP_A2_TAL_RASHAS_TOMB_4 0x45 +#define MAP_A2_TAL_RASHAS_TOMB_5 0x46 +#define MAP_A2_TAL_RASHAS_TOMB_6 0x47 +#define MAP_A2_TAL_RASHAS_TOMB_7 0x48 +#define MAP_A2_TAL_RASHAS_CHAMBER 0x49 +#define MAP_A2_ARCANE_SANCTUARY 0x4a + + + /////////////////////////////////////////////////// + // Act 3 Maps + /////////////////////////////////////////////////// +#define MAP_A3_KURAST_DOCKS 0x4b +#define MAP_A3_SPIDER_FOREST 0x4c +#define MAP_A3_GREAT_MARSH 0x4d +#define MAP_A3_FLAYER_JUNGLE 0x4e +#define MAP_A3_LOWER_KURAST 0x4f +#define MAP_A3_KURAST_BAZAAR 0x50 +#define MAP_A3_UPPER_KURAST 0x51 +#define MAP_A3_KURAST_CAUSEWAY 0x52 +#define MAP_A3_TRAVINCAL 0x53 +#define MAP_A3_ARCHNID_LAIR 0x54 +#define MAP_A3_SPIDER_CAVERN 0x55 +#define MAP_A3_SWAMPY_PIT_LEVEL_1 0x56 +#define MAP_A3_SWAMPY_PIT_LEVEL_2 0x57 +#define MAP_A3_FLAYER_DUNGEON_LEVEL_1 0x58 +#define MAP_A3_FLAYER_DUNGEON_LEVEL_2 0x59 +#define MAP_A3_SWAMPY_PIT_LEVEL_3 0x5a +#define MAP_A3_FLAYER_DUNGEON_LEVEL_3 0x5b +#define MAP_A3_SEWERS_LEVEL_1 0x5c +#define MAP_A3_SEWERS_LEVEL_2 0x5d +#define MAP_A3_RUINED_TEMPLE 0x5e +#define MAP_A3_DISUSED_FANE 0x5f +#define MAP_A3_FORGOTTEN_RELIQUARY 0x60 +#define MAP_A3_FORGOTTEN_TEMPLE 0x61 +#define MAP_A3_RUINED_FANE 0x62 +#define MAP_A3_DISUSED_RELIQUARY 0x63 +#define MAP_A3_DURANCE_OF_HATE_LEVEL_1 0x64 +#define MAP_A3_DURANCE_OF_HATE_LEVEL_2 0x65 +#define MAP_A3_DURANCE_OF_HATE_LEVEL_3 0x66 + + /////////////////////////////////////////////////// + // Act 4 Maps + /////////////////////////////////////////////////// +#define MAP_A4_THE_PANDEMONIUM_FORTRESS 0x67 +#define MAP_A4_OUTER_STEPPES 0x68 +#define MAP_A4_PLAINS_OF_DESPAIR 0x69 +#define MAP_A4_CITY_OF_THE_DAMNED 0x6a +#define MAP_A4_RIVER_OF_FLAME 0x6b +#define MAP_A4_THE_CHAOS_SANCTUARY 0x6c + + /////////////////////////////////////////////////// + // Act 5 Maps + /////////////////////////////////////////////////// +#define MAP_A5_HARROGATH 0x6d +#define MAP_A5_THE_BLOODY_FOOTHILLS 0x6e +#define MAP_A5_FRIGID_HIGHLANDS 0x6f +#define MAP_A5_ARREAT_PLATEAU 0x70 +#define MAP_A5_CRYSTALLINE_PASSAGE 0x71 +#define MAP_A5_FROZEN_RIVER 0x72 +#define MAP_A5_GLACIAL_TRAIL 0x73 +#define MAP_A5_DRIFTER_CAVERN 0x74 +#define MAP_A5_FROZEN_TUNDRA 0x75 +#define MAP_A5_THE_ANCIENTS_WAY 0x76 +#define MAP_A5_ICY_CELLAR 0x77 +#define MAP_A5_ARREAT_SUMMIT 0x78 +#define MAP_A5_NIHLATHAKS_TEMPLE 0x79 +#define MAP_A5_HALLS_OF_ANGUISH 0x7a +#define MAP_A5_HALLS_OF_PAIN 0x7b +#define MAP_A5_HALLS_OF_VAUGHT 0x7c +#define MAP_A5_ABADDON 0x7d +#define MAP_A5_PIT_OF_ACHERON 0x7e +#define MAP_A5_INFERNAL_PIT 0x7f +#define MAP_A5_WORLDSTONE_KEEP_LEVEL_1 0x80 +#define MAP_A5_WORLDSTONE_KEEP_LEVEL_2 0x81 +#define MAP_A5_WORLDSTONE_KEEP_LEVEL_3 0x82 +#define MAP_A5_THRONE_OF_DESTRUCTION 0x83 +#define MAP_A5_WORLDSTONE_KEEP 0x84 +#define MAP_A5_MATRONS_DEN 0x85 +#define MAP_A5_FORGOTTEN_SANDS 0x86 +#define MAP_A5_FURNACE_OF_PAIN 0x87 +#define MAP_A5_TRISTRAM 0x88 + + /////////////////////////////////////////////////// + // Item Attributes (From D2jsp scripting document) + /////////////////////////////////////////////////// +#define ITEM_IDENTIFIED 0x00000010 // Identified +#define ITEM_SWITCHIN 0x00000040 // Switched in(activated) +#define ITEM_SWITCHOUT 0x00000080 // Switched out(deactivated) +#define ITEM_BROKEN 0x00000100 // Broken(0 durability) +#define ITEM_HASSOCKETS 0x00000800 // Has sockets +#define ITEM_INSTORE 0x00002000 // In npc store or gamble screen +#define ITEM_ISEAR 0x00010000 // Player's ear +#define ITEM_STARTITEM 0x00020000 // Start item(1 selling value each) +#define ITEM_ETHEREAL 0x00400000 // Ethreal +#define ITEM_PERSONALIZED 0x01000000 // Personalized +#define ITEM_RUNEWORD 0x04000000 // Runeword + + /////////////////////////////////////////////////// + // Item Stats + /////////////////////////////////////////////////// +#define ITEMSTAT_SOCKETS 0xC2 +#define AFFECT_JUST_PORTALED 102 + +#endif diff --git a/Control.cpp b/Control.cpp new file mode 100644 index 00000000..36d705a6 --- /dev/null +++ b/Control.cpp @@ -0,0 +1,646 @@ +#include "Control.h" +#include "D2Ptrs.h" +#include "D2Helpers.h" +#include "Helpers.h" +#include "Constants.h" + +Control* findControl(int Type, int LocaleID, int Disabled, int PosX, int PosY, int SizeX, int SizeY) +{ + if(ClientState() != ClientStateMenu) + return NULL; + + char* localeStr = NULL; + if(LocaleID >= 0) + { + localeStr = UnicodeToAnsi(D2LANG_GetLocaleText((WORD)LocaleID)); + if(!localeStr) + return NULL; + Control* res = findControl(Type, localeStr, Disabled, PosX, PosY, SizeX, SizeY); + delete[] localeStr; + return res; + } + + return NULL; +} + +Control* findControl(int Type, char* Text, int Disabled, int PosX, int PosY, int SizeX, int SizeY) +{ + if(ClientState() != ClientStateMenu) + return NULL; + + if(Type == -1 && Text == NULL && Disabled == -1 && PosX == -1 && PosY == -1 && SizeX == -1 && SizeY == -1) + return *p_D2WIN_FirstControl; + + BOOL bFound = FALSE; + + for(Control* pControl = *p_D2WIN_FirstControl; pControl; pControl = pControl->pNext) + { + if(Type >= 0 && static_cast(pControl->dwType) == Type) + bFound = TRUE; + else if(Type >= 0 && static_cast(pControl->dwType) != Type) + { + bFound = FALSE; + continue; + } + + if(Disabled >= 0 && static_cast(pControl->dwDisabled) == Disabled) + { + if(pControl->dwType == CONTROL_BUTTON && pControl->unkState == 1) + { + bFound = FALSE; + continue; + } + bFound = TRUE; + } + else if(Disabled >= 0 && static_cast(pControl->dwDisabled) != Disabled) + { + bFound = FALSE; + continue; + } + + if(PosX >= 0 && static_cast(pControl->dwPosX) == PosX) + bFound = TRUE; + else if(PosX >= 0 && static_cast(pControl->dwPosX) != PosX) + { + bFound = FALSE; + continue; + } + + if(PosY >= 0 && static_cast(pControl->dwPosY) == PosY) + bFound = TRUE; + else if(PosY >= 0 && static_cast(pControl->dwPosY) != PosY) + { + bFound = FALSE; + continue; + } + + if(SizeX >= 0 && static_cast(pControl->dwSizeX) == SizeX) + bFound = TRUE; + else if(SizeX >= 0 && static_cast(pControl->dwSizeX) != SizeX) + { + bFound = FALSE; + continue; + } + + if(SizeY >= 0 && static_cast(pControl->dwSizeY) == SizeY) + bFound = TRUE; + else if(SizeY >= 0 && static_cast(pControl->dwSizeY) != SizeY) + { + bFound = FALSE; + continue; + } + + if(Text && pControl->dwType == CONTROL_BUTTON) + { + char* text2 = UnicodeToAnsi(pControl->wText2); + if(!text2) + return NULL; + if(strcmp(text2, Text) == 0) + { + bFound = TRUE; + delete[] text2; + } + else + { + bFound = FALSE; + delete[] text2; + continue; + } + } + + if(Text && pControl->dwType == CONTROL_TEXTBOX) + { + if(pControl->pFirstText != NULL && pControl->pFirstText->wText != NULL) + { + char* text2 = UnicodeToAnsi(pControl->pFirstText->wText); + if(!text2) + return NULL; + if(strstr(Text, text2) != 0) + { + bFound = TRUE; + delete[] text2; + } + else + { + bFound = FALSE; + delete[] text2; + continue; + } + } + else + { + bFound = FALSE; + continue; + } + } + if(bFound) + return pControl; + } + + return NULL; +} + +bool clickControl(Control* pControl, int x, int y) +{ + if(ClientState() != ClientStateMenu) + return false; + + if(pControl) + { + if(x == -1) + x = pControl->dwPosX + (pControl->dwSizeX / 2); + if(y == -1) + y = pControl->dwPosY - (pControl->dwSizeY / 2); + + Sleep(100); + SendMouseClick(x, y, 0); + Sleep(100); + SendMouseClick(x, y, 1); + Sleep(100); + + return true; + } + return false; +} + +BOOL OOG_CreateCharacter(char* szCharacter, int type, bool hardcore, bool ladder) +{ + if(OOG_GetLocation() != OOG_CHAR_SELECT || strlen(szCharacter) > 15 || type > 6 || type < 0) + return FALSE; + + // click the create character button + Control* ctrl = findControl(CONTROL_BUTTON, (char*)NULL, -1, 33, 528, 168, 60); + if(ctrl) + clickControl(ctrl); + + // TODO: replace with real time checking code + int i = 0; + while((OOG_GetLocation() != OOG_CHARACTER_CREATE) && i++ < 30) + Sleep(100); + + int locs[7][5] = { + {100, 337, 80, 330, 4011}, // amazon + {626, 353, 600, 300, 4010}, // sorceress + {301, 333, 300, 330, 4009}, // necromancer + {521, 339, 500, 330, 4008}, // paladin + {400, 330, 390, 330, 4007}, // barbarian + {720, 370, 700, 370, 4012}, // druid + {232, 364, 200, 300, 4013}, // assassin + }; + + ctrl = findControl(CONTROL_IMAGE, (char*)NULL, -1, locs[type][0], locs[type][1], 88, 184); + if(ctrl) + { + clickControl(ctrl, locs[type][2], locs[type][3]); + Sleep(500); + clickControl(ctrl, locs[type][2], locs[type][3]); + } + + // verify that the correct type got selected + ctrl = findControl(CONTROL_TEXTBOX, (char*)NULL, -1, 0, 180, 800, 100); + wchar_t* name = D2LANG_GetLocaleText((WORD)locs[type][4]); + if(_wcsicmp(name, ctrl->pFirstText->wText) != 0) + return FALSE; // something bad happened? + + // set the name +// ctrl = findControl(); + // still need to find the name editbox, set the name, and click the various + // checkboxes and the ok button + + return FALSE; +} + +BOOL OOG_SelectCharacter(char* szCharacter) +{ + if(ClientState() != ClientStateMenu) + return NULL; + + // Select the first control on the character selection screen. + Control* pControl = findControl(CONTROL_TEXTBOX, (char *)NULL, -1, 237, 178, 72, 93); + ControlText* cText; + + while (pControl != NULL) + { + if(pControl->dwType == CONTROL_TEXTBOX && pControl->pFirstText != NULL && pControl->pFirstText->pNext != NULL) + cText = pControl->pFirstText->pNext; + else + cText = NULL; + + if(cText != NULL) + { + char * szLine = UnicodeToAnsi(cText->wText); + if(!szLine) + return FALSE; + if(strlen(szLine) == strlen(szCharacter) && strstr(szLine,szCharacter) != NULL) + { + delete[] szLine; + if(!clickControl(pControl)) + return FALSE; + + // OK Button + pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 627, 572, 128, 35); + if(pControl) + { + if(!clickControl(pControl)) + return FALSE; + + return TRUE; + } + else + return FALSE; + + } + else + delete[] szLine; + } + pControl = pControl->pNext; + } + return FALSE; +} + +void SetControlText(Control* pControl, const char* Text) +{ + if(ClientState() != ClientStateMenu) + return; + + if(pControl && Text) + { + wchar_t* szwText = AnsiToUnicode(Text); + if(!szwText) + return; + D2WIN_SetControlText(pControl, szwText); + delete[] szwText; + } +} + +BOOL OOG_SelectGateway(char * szGateway, size_t strSize) +{ + if(ClientState() != ClientStateMenu) + return FALSE; + + if(strstr(szGateway,"ERROR")) + return FALSE; + // Select the gateway control. + Control* pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 264, 391, 272, 25); + + // if the control exists and has the text label, check if it matches the selected gateway + if(pControl && pControl->wText2) + { + char* szLine = UnicodeToAnsi(pControl->wText2); + if(!szLine) + return FALSE; + + _strlwr_s(szLine, strlen(szLine)+1); + _strlwr_s(szGateway, strSize); + if(strstr(szLine, szGateway)) + { + // gateway is correct, do nothing and return true + delete[] szLine; + return TRUE; + } + else + { + delete[] szLine; + // gateway is NOT correct, change gateway to selected gateway if it exists + // open the gateway select screen + if(!clickControl(pControl)) + return FALSE; + + int index = 0; + bool gatefound = false; + + // loop here till we find the right gateway if we can + pControl = findControl(CONTROL_TEXTBOX, (char *)NULL, -1, 257, 500, 292, 160); + ControlText* cText; + if(pControl && pControl->pFirstText) + { + cText = pControl->pFirstText; + while(cText) + { + char * szGatelist = UnicodeToAnsi(cText->wText); + if(!szGatelist) + return FALSE; + + _strlwr_s(szGatelist, strlen(szGatelist)+1); + if(strstr(szGatelist, szGateway)) + { + // chosen gateway IS in the list and matches, cleanup and break the loop + gatefound = true; + delete[] szGatelist; + break; + } + delete[] szGatelist; + index++; + cText = cText->pNext; + } + if(gatefound) + { + // click the correct gateway using the control plus a default x and a y based on (index*24)+12 + if(!clickControl(pControl, -1, 344+((index*24)+12))) + return FALSE; + } + } + + // OK Button, gateway select screen + pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 281, 538, 96, 32); + if(pControl) + { + if(!clickControl(pControl)) + return FALSE; + } + else + return FALSE; + + return TRUE; + } + } + return FALSE; +} + +OOG_Location OOG_GetLocation(void) +{ + if(ClientState() != ClientStateMenu) + return OOG_NONE; + + if(findControl(CONTROL_BUTTON, 5103, -1, 330, 416, 128, 35)) + return OOG_MAIN_MENU_CONNECTING; //21 Connecting to Battle.net + else if(findControl(CONTROL_BUTTON, 5102, -1, 335, 412, 128, 35)) + return OOG_LOGIN_ERROR; //10 Login Error + else if (findControl(CONTROL_BUTTON, 5102, -1, 351,337,96,32)) //5102 =OK + { + if (findControl(CONTROL_TEXTBOX, 5351, -1, 268,320,264,120)) + return OOG_LOST_CONNECTION; //17 lost connection + else if (findControl(CONTROL_TEXTBOX, 5347, -1, 268,320,264,120)) + return OOG_DISCONNECTED; //14 Disconnected + else + return OOG_CHARACTER_CREATE_ALREADY_EXISTS; //30 Character Create - Dupe Name + } + else if(findControl(CONTROL_BUTTON, 5103, -1, 351,337,96,32)) //5103 = CANCEL + { + if(findControl(CONTROL_TEXTBOX, 5243, -1, 268, 300, 264, 100)) + return OOG_CHARACTER_SELECT_PLEASE_WAIT; //16 char select please wait... + if (findControl(CONTROL_TEXTBOX, (char *)NULL, -1, 268,320,264,120)) + return OOG_PLEASE_WAIT; //25 "Please Wait..."single player already exists also + } + else if(findControl(CONTROL_BUTTON, 5103, -1, 433, 433, 96, 32)) + { + if (findControl(CONTROL_TEXTBOX, (char *)NULL, -1, 427,234,300,100)) + return OOG_INLINE; //2 waiting in line + else if(findControl(CONTROL_TEXTBOX, 10018, -1, 459, 380, 150, 12)) + return OOG_CREATE; //4 Create game + else if(findControl(CONTROL_BUTTON, 5119, -1, 594, 433, 172, 32)) + return OOG_JOIN; // 5 Join Game + else if(findControl(CONTROL_BUTTON, 5102, -1, 671, 433, 96, 32)) + return OOG_CHANNEL; //7 "Channel List" + else + return OOG_LADDER; //6 "Ladder" + } + else if(findControl(CONTROL_BUTTON, 5101, -1, 33,572,128,35)) //5101 = EXIT + { + if(findControl(CONTROL_BUTTON, 5288, -1, 264, 484, 272, 35)) + return OOG_LOGIN; //9 Login + if (findControl(CONTROL_BUTTON, 5102, -1, 495,438,96,32)) + return OOG_CHARACTER_SELECT_CHANGE_REALM; //43 char select change realm + if(findControl(CONTROL_BUTTON, 5102, -1, 627,572,128,35) && findControl(CONTROL_BUTTON, 10832, -1, 33,528,168,60)) //10832=create new + { + if (findControl(CONTROL_BUTTON, 10018, -1, 264,297,272,35)) //NORMAL + return OOG_DIFFICULTY; //20 single char Difficulty + Control* pControl = findControl(CONTROL_TEXTBOX, (char *)NULL, -1, 37, 178, 200, 92); + if(pControl && pControl->pFirstText && pControl->pFirstText->pNext) + return OOG_CHAR_SELECT; //12 char select + else + { + if (findControl(CONTROL_TEXTBOX, 11162, -1,45,318,531,140) || findControl(CONTROL_TEXTBOX, 11066, -1,45,318,531,140)) + return OOG_REALM_DOWN; + else + return OOG_CHARACTER_SELECT_NO_CHARS; //42 char info not loaded + } + } + if(findControl(CONTROL_BUTTON, 5101, -1, 33, 572, 128, 35)) //5101=Exit + { + if (findControl(CONTROL_BUTTON, 5102, 0, 627,572,128,35)) //5102=ok + return OOG_CHARACTER_CREATE; //29 char create screen with char selected + else + { + if(findControl(CONTROL_TEXTBOX, 5226, -1, 321, 448, 300, 32)) + return OOG_NEW_ACCOUNT; //32 create new bnet account + else + return OOG_NEW_CHARACTER; //15 char create screen no char selected + } + } + } + if(findControl(CONTROL_BUTTON, 5102, -1, 335, 450, 128, 35)) + { + if(findControl(CONTROL_TEXTBOX, 5200, -1, 162, 270, 477, 50)) + return OOG_CDKEY_IN_USE; //19 CD-KEY in use + else if (findControl(CONTROL_TEXTBOX, 5190, -1, 162,420,477,100)) //5190="If using a modem" + return OOG_UNABLE_TO_CONNECT; //11 unable to connect + else + return OOG_INVALID_CDKEY; //22 invalid CD-KEY + } + else if (findControl(CONTROL_TEXTBOX, 5159, -1, 438, 300, 326, 150)) + return OOG_GAME_DOES_NOT_EXIST; //28 game doesn't exist + else if (findControl(CONTROL_TEXTBOX, 5161, -1, 438, 300, 326, 150)) + return OOG_GAME_IS_FULL; //38 Game is full + else if (findControl(CONTROL_TEXTBOX, 5138, -1, 438, 300, 326, 150)) + return OOG_GAME_EXIST; //26 Game already exists + else if (findControl(CONTROL_TEXTBOX, 5139, -1, 438, 300, 326, 150)) + return OOG_SERVER_DOWN; //24 server down + else if (findControl(CONTROL_BUTTON, 5106, -1, 264,324,272,35)) //5106="SINGLE PLAYER" + return OOG_MAIN_MENU; //8 Main Menu + else if (findControl(CONTROL_BUTTON, 11126, -1, 27,480,120,20)) //11126=ENTER CHAT + return OOG_LOBBY; //1 base bnet + else if (findControl(CONTROL_BUTTON, 5308, -1, 187,470,80,20)) //5308="HELP" + return OOG_CHAT; //3 chat bnet + else if(findControl(CONTROL_TEXTBOX, 21882, -1, 100, 580, 600, 80)) + return OOG_D2SPLASH; //18 Spash + else if (findControl(CONTROL_BUTTON, 5102, -1, 281,538,96,32)) + return OOG_GATEWAY; //27 select gateway + else if (findControl(CONTROL_BUTTON, 5181, -1, 525,513,128,35)) + return OOG_AGREE_TO_TERMS; //31 agree to terms + else if (findControl(CONTROL_BUTTON, 5102, -1, 525,513,128,35)) + return OOG_PLEASE_READ; //33 please read + else if (findControl(CONTROL_BUTTON, 11097, -1, 265,527,272,35)) + return OOG_REGISTER_EMAIL; //34 register email + else if (findControl(CONTROL_BUTTON, 5101, -1, 33,578,128,35)) + return OOG_CREDITS; //35 Credits + else if (findControl(CONTROL_BUTTON, 5103, -1, 334,488,128,35)) + return OOG_CINEMATICS; //36 Cinematics + else if (findControl(CONTROL_BUTTON, 5116, -1, 264,350,272,35)) + return OOG_OTHER_MULTIPLAYER; //39 other multi player + else if (findControl(CONTROL_BUTTON, 5103, -1,281,337,96,32)) + return OOG_ENTER_IP_ADDRESS; //41 enter ip + else if (findControl(CONTROL_BUTTON, 5118, -1,265,206,272,35)) + return OOG_TCP_IP; //40 tcp-ip + + return OOG_NONE; +} + +bool OOG_CreateGame(const char* name, const char* pass, int difficulty) +{ + if(ClientState() != ClientStateMenu) + return FALSE; + + // reject name/password combinations over 15 characters + if(!name || !pass || strlen(name) > 15 || strlen(pass) > 15) + return FALSE; + + Control* pControl = NULL; + + // Battle.net/open game creation + OOG_Location loc = OOG_GetLocation(); + if(!(loc == OOG_LOBBY || loc == OOG_CHAT || loc == OOG_DIFFICULTY || loc == OOG_CREATE)) + return FALSE; + + if(loc == OOG_DIFFICULTY) + { + // just click the difficulty button + Control *normal = findControl(CONTROL_BUTTON, (char *)NULL, -1, 264, 297, 272, 35), + *nightmare = findControl(CONTROL_BUTTON, (char *)NULL, -1, 264, 340, 272, 35), + *hell = findControl(CONTROL_BUTTON, (char *)NULL, -1, 264, 383, 272, 35); + + switch(difficulty) + { + case 0: // normal button + if(normal->dwDisabled != 0x0d || !clickControl(normal)) + return FALSE; + break; + case 1: // nightmare button + if(nightmare->dwDisabled != 0x0d || !clickControl(nightmare)) + return FALSE; + break; + case 2: // hell button + if(hell->dwDisabled != 0x0d || !clickControl(hell)) + return FALSE; + break; + case 3: //hardest difficulty available + if(hell->dwDisabled != 0x0d) { + if(!clickControl(hell)) + return FALSE; + } else if(nightmare->dwDisabled != 0x0d) { + if(!clickControl(nightmare)) + return FALSE; + } else if(normal->dwDisabled != 0x0d) { + if(!clickControl(normal)) + return FALSE; + } + break; + default: + return FALSE; + } + } + else + { + // Create button + if (loc != OOG_CREATE) + { + pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 533,469,120,20); + if(!pControl || !clickControl(pControl)) + return FALSE; + Sleep(100); + } + if(OOG_GetLocation() == OOG_CREATE) + { + // Game name edit box + if(name) + SetControlText(findControl(1, (char *)NULL, -1, 432,162,158,20), name); + else + return FALSE; + Sleep(100); + + // Password edit box + if(pass) + SetControlText(findControl(1, (char *)NULL, -1, 432,217,158,20), pass); + else + return FALSE; + Sleep(100); + Control *normal = findControl(CONTROL_BUTTON, (char *)NULL, -1, 430,381,16,16), + *nightmare = findControl(CONTROL_BUTTON, (char *)NULL, -1, 555,381,16,16), + *hell = findControl(CONTROL_BUTTON, (char *)NULL, -1, 698,381,16,16); + + switch(difficulty) + { + case 0: // normal button + if(normal->dwDisabled != 0x5 || !clickControl(normal)) + return FALSE; + break; + case 1: // nightmare button + if(nightmare->dwDisabled != 0x5 || !clickControl(nightmare)) + return FALSE; + break; + case 2: // hell button + if(hell->dwDisabled != 0x5 || !clickControl(hell)) + return FALSE; + break; + case 3: //hardest difficulty available + if(hell->dwDisabled != 0x5) { + if(!clickControl(hell)) + return FALSE; + } + else if(nightmare->dwDisabled != 0x5) { + if(!clickControl(nightmare)) + return FALSE; + } + else if(normal->dwDisabled != 0x5) { + if(!clickControl(normal)) + return FALSE; + } + break; + default: + return FALSE; + } + + // Create Game Button + pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 594,433,172,32); + if(!pControl || !clickControl(pControl)) + return FALSE; + } + } + + return TRUE; +} + +bool OOG_JoinGame(const char* name, const char* pass) +{ + if(ClientState() != ClientStateMenu) + return FALSE; + + // reject name/password combinations over 15 characters + if(strlen(name) > 15 || strlen(pass) > 15) + return FALSE; + + Control* pControl = NULL; + + // Battle.net/open lobby/chat area + if(!(OOG_GetLocation() == OOG_LOBBY || OOG_GetLocation() == OOG_CHAT || OOG_GetLocation() == OOG_JOIN)) + return FALSE; + + // JOIN button + if (OOG_GetLocation() != OOG_JOIN) + { + pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 652,469,120,20); + if(!pControl || !clickControl(pControl)) + return FALSE; + Sleep(100); + } + if(OOG_GetLocation() == OOG_JOIN) + { + // Game name edit box + if(name) + SetControlText(findControl(1, (char *)NULL, -1, 432,148,155,20), name); + else + return FALSE; + // Password edit box + if(pass) + SetControlText(findControl(1, (char *)NULL, -1, 606,148,155,20), pass); + else + return FALSE; + + // Join Game Button + pControl = findControl(CONTROL_BUTTON, (char *)NULL, -1, 594,433,172,32); + if(!pControl || !clickControl(pControl)) + return FALSE; + } + + return TRUE; +} diff --git a/Control.h b/Control.h new file mode 100644 index 00000000..d6161976 --- /dev/null +++ b/Control.h @@ -0,0 +1,15 @@ +#pragma once + +#include "D2Structs.h" +#include "Constants.h" + +Control* findControl(int Type, int LocaleID, int Disabled, int PosX, int PosY, int SizeX, int SizeY); +Control* findControl(int Type, char* Text, int Disabled, int PosX, int PosY, int SizeX, int SizeY); +bool clickControl(Control* pControl, int x = -1, int y = -1); +BOOL OOG_CreateCharacter(char* szCharacter, int type, bool hardcore, bool ladder); +BOOL OOG_SelectCharacter(char * szCharacter); +BOOL OOG_SelectGateway(char * szGateway, size_t strSize); +void SetControlText(Control* pControl, const char* Text); +OOG_Location OOG_GetLocation(void); +bool OOG_CreateGame(const char* name, const char* pass, int difficulty); +bool OOG_JoinGame(const char* name, const char* pass); diff --git a/Core.cpp b/Core.cpp new file mode 100644 index 00000000..c5a74e6d --- /dev/null +++ b/Core.cpp @@ -0,0 +1,225 @@ +#include +#include +#include +#include + +#include "Core.h" +#include "D2Ptrs.h" +//#include "D2Helpers.h" +#include "Helpers.h" +#include "Control.h" +#include "CriticalSections.h" +#include "Console.h" + +bool SplitLines(const std::string & str, size_t maxlen, const char delim, std::list & lst) +{ + using namespace std; + + if(str.length() < 1 || maxlen < 2) + return false; + + size_t pos, len; + string tmp(str); + + while(tmp.length() > maxlen) + { + len = tmp.length(); + // maxlen-1 since std::string::npos indexes from 0 + pos = tmp.find_last_of(delim, maxlen-1); + if(!pos || pos == string::npos) + { + //Target delimiter was not found, breaking at maxlen + // maxlen-1 since std::string::npos indexes from 0 + lst.push_back(tmp.substr(0, maxlen-1)); + tmp.erase(0, maxlen-1); + continue; + } + pos = tmp.find_last_of(delim, maxlen-1); + if(pos && pos != string::npos) + { + //We found the last delimiter before maxlen + lst.push_back(tmp.substr(0, pos) + delim); + tmp.erase(0, pos); + } + else + DebugBreak(); + } + if(!tmp.length()) + DebugBreak(); + + if(tmp.length()) + lst.push_back(tmp); + + return true; +} + +void Print(const char * szFormat, ...) +{ + using namespace std; + + const char REPLACE_CHAR = (char)(unsigned char)0xFE; + + va_list vaArgs; + va_start(vaArgs, szFormat); + int len = _vscprintf(szFormat, vaArgs); + char* str = new char[len+1]; + vsprintf_s(str, len+1, szFormat, vaArgs); + va_end(vaArgs); + + replace(str, str + len, REPLACE_CHAR, '%'); + + const uint maxlen = 98; + + // Break into lines through \n. + list lines; + string temp; + stringstream ss(str); + while(getline(ss, temp)) + SplitLines(temp, maxlen, ' ', lines); + + EnterCriticalSection(&Vars.cPrintSection); + if(Vars.bUseGamePrint) + { + if(ClientState() == ClientStateInGame) + { + // Convert and send every line. + for(list::iterator it = lines.begin(); it != lines.end(); ++it) + { + wchar_t * output = AnsiToUnicode(it->c_str()); + D2CLIENT_PrintGameString(output, 0); + delete [] output; + } + } + else if(ClientState() == ClientStateMenu && findControl(4, (char *)NULL, -1, 28, 410, 354, 298)) + { + // TODO: Double check this function, make sure it is working as intended. + for(list::iterator it = lines.begin(); it != lines.end(); ++it) + D2MULTI_PrintChannelText((char* )it->c_str(), 0); + } + } + for(list::iterator it = lines.begin(); it != lines.end(); ++it) + Console::AddLine(*it); + + LeaveCriticalSection(&Vars.cPrintSection); + + delete[] str; + str = NULL; +} + +void __declspec(naked) __fastcall Say_ASM(DWORD dwPtr) +{ + __asm + { + POP EAX + PUSH ECX + PUSH EAX + SUB ESP,0x110 + PUSH EBX + PUSH EBP + MOV EBP, [D2LANG_Say_II] + PUSH ESI + PUSH EDI + JMP D2CLIENT_Say_I + } +} + +void Say(const char *szMessage) +{ + Vars.bDontCatchNextMsg = TRUE; + + if(D2CLIENT_GetPlayerUnit()) + { + /*wchar_t* wBuffer = AnsiToUnicode(szMessage); + memcpy((wchar_t*)p_D2CLIENT_ChatMsg, wBuffer, wcslen(wBuffer)*2+1); + delete[] wBuffer; + wBuffer = NULL; + + MSG* aMsg = new MSG; + aMsg->hwnd = D2GFX_GetHwnd(); + aMsg->message = WM_CHAR; + aMsg->wParam = VK_RETURN; + aMsg->lParam = 0x11C0001; + aMsg->time = NULL; + aMsg->pt.x = 0x79; + aMsg->pt.y = 0x1; + + Say_ASM((DWORD)&aMsg); + delete aMsg; + aMsg = NULL;*/ + //Print("ÿc2D2BSÿc0 :: say() in game has been disabled for now, due to crashes"); + + Vars.bDontCatchNextMsg = FALSE; + int len = 6+strlen(szMessage); + BYTE* pPacket = new BYTE[6+strlen(szMessage)]; + memset(pPacket, 0, len); + pPacket[0] = 0x15; + pPacket[1] = 0x01; + memcpy(pPacket+3, szMessage, len-6); + D2CLIENT_SendGamePacket(len, pPacket); + } + // help button and ! ok msg for disconnected + else if(findControl(CONTROL_BUTTON, 5308, -1, 187,470,80,20) && (!findControl(CONTROL_BUTTON, 5102, -1, 351,337,96,32))) + { + memcpy((char*)p_D2MULTI_ChatBoxMsg, szMessage, strlen(szMessage) + 1); + D2MULTI_DoChat(); + } +} + +bool ClickMap(DWORD dwClickType, int wX, int wY, BOOL bShift, UnitAny* pUnit) +{ + if(ClientState() != ClientStateInGame) + return false; + + POINT Click = {wX, wY}; + if(pUnit) + { + Click.x = D2CLIENT_GetUnitX(pUnit); + Click.y = D2CLIENT_GetUnitY(pUnit); + } + + D2COMMON_MapToAbsScreen(&Click.x, &Click.y); + + Click.x -= *p_D2CLIENT_ViewportX; + Click.y -= *p_D2CLIENT_ViewportY; + + POINT OldMouse = {0, 0}; + OldMouse.x = *p_D2CLIENT_MouseX; + OldMouse.y = *p_D2CLIENT_MouseY; + *p_D2CLIENT_MouseX = 0; + *p_D2CLIENT_MouseY = 0; + + if(pUnit && pUnit != D2CLIENT_GetPlayerUnit()/* && D2CLIENT_UnitTestSelect(pUnit, 0, 0, 0)*/) + { + Vars.dwSelectedUnitId = pUnit->dwUnitId; + Vars.dwSelectedUnitType = pUnit->dwType; + + Vars.bClickAction = TRUE; + + D2CLIENT_ClickMap(dwClickType, Click.x, Click.y, bShift ? 0x0C : 0x08); + D2CLIENT_SetSelectedUnit(NULL); + + Vars.bClickAction = FALSE; + Vars.dwSelectedUnitId = NULL; + Vars.dwSelectedUnitType = NULL; + } + else + { + Vars.dwSelectedUnitId = NULL; + Vars.dwSelectedUnitType = NULL; + + Vars.bClickAction = TRUE; + D2CLIENT_ClickMap(dwClickType, Click.x, Click.y, bShift ? 0x0C : 8); + Vars.bClickAction = FALSE; + } + + *p_D2CLIENT_MouseX = OldMouse.x; + *p_D2CLIENT_MouseY = OldMouse.y; + return TRUE; +} + +void LoadMPQ(const char* mpq) +{ + D2WIN_InitMPQ("D2Win.DLL", mpq, NULL, 0, 0); + *p_BNCLIENT_XPacKey = *p_BNCLIENT_ClassicKey = *p_BNCLIENT_KeyOwner = NULL; + BNCLIENT_DecodeAndLoadKeys(); +} diff --git a/Core.h b/Core.h new file mode 100644 index 00000000..85a15b69 --- /dev/null +++ b/Core.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include +#include + +#include "D2Structs.h" + +bool SplitLines(const std::string & str, size_t maxlen, const char delim, std::list & lst); +void Print(const char * szFormat, ...); +void Say(const char* szMessage); +bool ClickMap(DWORD dwClickType, int wX, int wY, BOOL bShift, UnitAny* pUnit); +void LoadMPQ(const char* mpq); diff --git a/CriticalSections.h b/CriticalSections.h new file mode 100644 index 00000000..88139303 --- /dev/null +++ b/CriticalSections.h @@ -0,0 +1,51 @@ +#pragma once + +#include "D2BS.h" + +class CriticalRoom +{ +private: + bool bEnteredCriticalSection; + +public: + CriticalRoom() : bEnteredCriticalSection(false) {} + ~CriticalRoom() { LeaveSection(); } + + void EnterSection() { + InterlockedIncrement(&Vars.SectionCount); + EnterCriticalSection(&Vars.cGameLoopSection); + bEnteredCriticalSection = true; + } + + void LeaveSection() { + if(bEnteredCriticalSection) { + InterlockedDecrement(&Vars.SectionCount); + LeaveCriticalSection(&Vars.cGameLoopSection); + bEnteredCriticalSection = false; + } + } +}; + +class CriticalMisc +{ +private: + bool bEnteredCriticalSection; + +public: + CriticalMisc() : bEnteredCriticalSection(false) {} + ~CriticalMisc() { LeaveSection(); } + + void EnterSection() { + InterlockedIncrement( &Vars.SectionCount ); + EnterCriticalSection(&Vars.cGameLoopSection); + bEnteredCriticalSection = true; + } + + void LeaveSection() { + if(bEnteredCriticalSection) { + InterlockedDecrement( &Vars.SectionCount ); + LeaveCriticalSection(&Vars.cGameLoopSection); + bEnteredCriticalSection = false; + } + } +}; diff --git a/D2BS.cpp b/D2BS.cpp new file mode 100644 index 00000000..057a9f5d --- /dev/null +++ b/D2BS.cpp @@ -0,0 +1,146 @@ +// Diablo II Botting System Core + +#include +#include +#include + +#include "dde.h" +#include "Offset.h" +#include "ScriptEngine.h" +#include "Helpers.h" +#include "D2Handlers.h" +#include "Console.h" +#include "D2BS.h" +#include "D2Ptrs.h" + +#ifdef _MSVC_DEBUG +#include "D2Loader.h" +#endif + +static HANDLE hD2Thread = INVALID_HANDLE_VALUE; + +BOOL WINAPI DllMain(HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved) +{ + switch(dwReason) + { + case DLL_PROCESS_ATTACH: + { + DisableThreadLibraryCalls(hDll); + if(lpReserved != NULL) + { + Vars.pModule = (Module*)lpReserved; + + if(!Vars.pModule) + return FALSE; + + strcpy_s(Vars.szPath, MAX_PATH, Vars.pModule->szPath); + Vars.bLoadedWithCGuard = TRUE; + } + else + { + Vars.hModule = hDll; + GetModuleFileName(hDll, Vars.szPath, MAX_PATH); + PathRemoveFileSpec(Vars.szPath); + strcat_s(Vars.szPath, MAX_PATH, "\\"); + Vars.bLoadedWithCGuard = FALSE; + } + +#ifdef DEBUG + char errlog[516] = ""; + sprintf_s(errlog, 516, "%sd2bs.log", Vars.szPath); + AllocConsole(); + int handle = _open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT); + FILE* f = _fdopen(handle, "wt"); + *stderr = *f; + setvbuf(stderr, NULL, _IONBF, 0); + freopen_s(&f, errlog, "a+t", f); +#endif + + Vars.bShutdownFromDllMain = FALSE; + SetUnhandledExceptionFilter(ExceptionHandler); + if(!Startup()) + return FALSE; + } + break; + case DLL_PROCESS_DETACH: + if(Vars.bNeedShutdown) + { + Vars.bShutdownFromDllMain = TRUE; + Shutdown(); + } + break; + } + + return TRUE; +} + +BOOL Startup(void) +{ + InitializeCriticalSection(&Vars.cRoomSection); + InitializeCriticalSection(&Vars.cMiscSection); + InitializeCriticalSection(&Vars.cScreenhookSection); + InitializeCriticalSection(&Vars.cPrintSection); + InitializeCriticalSection(&Vars.cBoxHookSection); + InitializeCriticalSection(&Vars.cFrameHookSection); + InitializeCriticalSection(&Vars.cLineHookSection); + InitializeCriticalSection(&Vars.cImageHookSection); + InitializeCriticalSection(&Vars.cTextHookSection); + InitializeCriticalSection(&Vars.cFlushCacheSection); + InitializeCriticalSection(&Vars.cConsoleSection); + InitializeCriticalSection(&Vars.cGameLoopSection); + InitializeCriticalSection(&Vars.cUnitListSection); + + Vars.bNeedShutdown = TRUE; + Vars.bChangedAct = FALSE; + Vars.bGameLoopEntered = FALSE; + + Vars.SectionCount = 0; + + Genhook::Initialize(); + DefineOffsets(); + InstallPatches(); + CreateDdeServer(); + + if((hD2Thread = CreateThread(NULL, NULL, D2Thread, NULL, NULL, NULL)) == INVALID_HANDLE_VALUE) + return FALSE; + + return TRUE; +} + +void Shutdown(void) +{ + if(!Vars.bNeedShutdown) + return; + + Vars.bActive = FALSE; + if(!Vars.bShutdownFromDllMain) + WaitForSingleObject(hD2Thread, INFINITE); + + SetWindowLong(D2GFX_GetHwnd(),GWL_WNDPROC,(LONG)Vars.oldWNDPROC); + + RemovePatches(); + Genhook::Destroy(); + ShutdownDdeServer(); + + KillTimer(D2GFX_GetHwnd(), Vars.uTimer); + + UnhookWindowsHookEx(Vars.hMouseHook); + UnhookWindowsHookEx(Vars.hKeybHook); + + DeleteCriticalSection(&Vars.cRoomSection); + DeleteCriticalSection(&Vars.cMiscSection); + DeleteCriticalSection(&Vars.cScreenhookSection); + DeleteCriticalSection(&Vars.cPrintSection); + DeleteCriticalSection(&Vars.cBoxHookSection); + DeleteCriticalSection(&Vars.cFrameHookSection); + DeleteCriticalSection(&Vars.cLineHookSection); + DeleteCriticalSection(&Vars.cImageHookSection); + DeleteCriticalSection(&Vars.cTextHookSection); + DeleteCriticalSection(&Vars.cFlushCacheSection); + DeleteCriticalSection(&Vars.cConsoleSection); + DeleteCriticalSection(&Vars.cGameLoopSection); + DeleteCriticalSection(&Vars.cUnitListSection); + + Log("D2BS Shutdown complete."); + Vars.bNeedShutdown = false; +} diff --git a/D2BS.h b/D2BS.h new file mode 100644 index 00000000..0c7f1a6c --- /dev/null +++ b/D2BS.h @@ -0,0 +1,105 @@ +#ifndef __D2BS_H__ +#define __D2BS_H__ + +#pragma once + +#define XP_WIN +#define JS_THREADSAFE + +#define D2BS_VERSION "1.4.1" + +#include +#include + +#include "ScreenHook.h" + +struct Variables; + +#define ArraySize(x) (sizeof((x)) / sizeof((x)[0])) + +#define PRIVATE_UNIT 1 +#define PRIVATE_ITEM 3 + +struct Private { DWORD dwPrivateType; }; + +struct Module +{ + union { + HMODULE hModule; + DWORD dwBaseAddress; + }; + DWORD _1; + char szPath[MAX_PATH]; +}; + +struct Variables +{ + int nChickenHP; + int nChickenMP; + DWORD dwInjectTime; + DWORD dwGameTime; + BOOL bDontCatchNextMsg; + BOOL bClickAction; + BOOL bNeedShutdown; + BOOL bUseGamePrint; + BOOL bShutdownFromDllMain; + BOOL bChangedAct; + BOOL bGameLoopEntered; + + DWORD dwMaxGameTime; + DWORD dwGameTimeout; + BOOL bQuitOnError; + BOOL bQuitOnHostile; + BOOL bStartAtMenu; + BOOL bActive; + BOOL bBlockKeys; + BOOL bBlockMouse; + BOOL bDisableCache; + BOOL bUseProfileScript; + BOOL bLoadedWithCGuard; + BOOL bLogConsole; + int dwMemUsage; + + Module* pModule; + HMODULE hModule; + + char szPath[_MAX_PATH]; + char szScriptPath[_MAX_PATH]; + char szProfile[256]; + char szStarter[_MAX_FNAME]; + char szDefault[_MAX_FNAME]; + + WNDPROC oldWNDPROC; + HHOOK hMouseHook; + HHOOK hKeybHook; + + UINT_PTR uTimer; + long SectionCount; + + std::map mCachedCellFiles; + std::vector > vUnitList; + + CRITICAL_SECTION cRoomSection; + CRITICAL_SECTION cMiscSection; + CRITICAL_SECTION cScreenhookSection; + CRITICAL_SECTION cPrintSection; + CRITICAL_SECTION cTextHookSection; + CRITICAL_SECTION cImageHookSection; + CRITICAL_SECTION cBoxHookSection; + CRITICAL_SECTION cFrameHookSection; + CRITICAL_SECTION cLineHookSection; + CRITICAL_SECTION cFlushCacheSection; + CRITICAL_SECTION cConsoleSection; + CRITICAL_SECTION cGameLoopSection; + CRITICAL_SECTION cUnitListSection; + + DWORD dwSelectedUnitId; + DWORD dwSelectedUnitType; +}; + +extern Variables Vars; + +BOOL Startup(void); +void Shutdown(void); + +#endif diff --git a/D2BS.sln b/D2BS.sln new file mode 100644 index 00000000..05422788 --- /dev/null +++ b/D2BS.sln @@ -0,0 +1,22 @@ +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "D2BS", "D2BS.vcxproj", "{0EB43FEB-A856-4370-9F46-C8D252D9E153}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Packaging|Win32 = Packaging|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0EB43FEB-A856-4370-9F46-C8D252D9E153}.Debug|Win32.ActiveCfg = Debug|Win32 + {0EB43FEB-A856-4370-9F46-C8D252D9E153}.Debug|Win32.Build.0 = Debug|Win32 + {0EB43FEB-A856-4370-9F46-C8D252D9E153}.Packaging|Win32.ActiveCfg = Packaging|Win32 + {0EB43FEB-A856-4370-9F46-C8D252D9E153}.Packaging|Win32.Build.0 = Packaging|Win32 + {0EB43FEB-A856-4370-9F46-C8D252D9E153}.Release|Win32.ActiveCfg = Release|Win32 + {0EB43FEB-A856-4370-9F46-C8D252D9E153}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/D2BS.vcproj b/D2BS.vcproj new file mode 100644 index 00000000..ac905e4e --- /dev/null +++ b/D2BS.vcproj @@ -0,0 +1,959 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/D2Handlers.cpp b/D2Handlers.cpp new file mode 100644 index 00000000..87d2327d --- /dev/null +++ b/D2Handlers.cpp @@ -0,0 +1,458 @@ +#include +#include + +#include "D2Handlers.h" +#include "D2NetHandlers.h" +#include "Script.h" +#include "ScreenHook.h" +#include "Unit.h" +#include "Helpers.h" +#include "Core.h" +#include "Constants.h" +#include "Events.h" +#include "ScriptEngine.h" +#include "Console.h" +#include "D2BS.h" + +using namespace std; + +bool __fastcall UpdatePlayerGid(Script* script, void*, uint) { script->UpdatePlayerGid(); return true; } + +DWORD WINAPI D2Thread(LPVOID lpParam) +{ + bool beginStarter = true; + bool bInGame = false; + + InitSettings(); + if(InitHooks()) + { + Log("D2BS Engine startup complete."); + Print("ÿc2D2BSÿc0 :: Engine startup complete!"); + } + else + { + Log("D2BS Engine startup failed."); + Print("ÿc2D2BSÿc0 :: Engine startup failed!"); + return FALSE; + } + + while(Vars.bActive) + { + switch(ClientState()) + { + case ClientStateInGame: + { + if(bInGame) + { + if((Vars.dwMaxGameTime && Vars.dwGameTime && + (GetTickCount() - Vars.dwGameTime) > Vars.dwMaxGameTime) || + (!D2COMMON_IsTownByLevelNo(GetPlayerArea()) && + (Vars.nChickenHP && Vars.nChickenHP >= GetUnitHP(D2CLIENT_GetPlayerUnit())) || + (Vars.nChickenMP && Vars.nChickenMP >= GetUnitMP(D2CLIENT_GetPlayerUnit())))) + D2CLIENT_ExitGame(); + } + else + { + Sleep(1000); + + Vars.dwGameTime = GetTickCount(); + D2CLIENT_InitInventory(); + ScriptEngine::ForEachScript(UpdatePlayerGid, NULL, 0); + + GameJoined(); + + bInGame = true; + } + break; + } + case ClientStateMenu: + { + MenuEntered(beginStarter); + beginStarter = false; + if(bInGame) + { + Vars.dwGameTime = NULL; + bInGame = false; + } + break; + } + case ClientStateBusy: + case ClientStateNull: + break; + } + Sleep(50); + } + + ScriptEngine::Shutdown(); + + return NULL; +} + +DWORD __fastcall GameInput(wchar_t* wMsg) +{ + if(Vars.bDontCatchNextMsg) + { + Vars.bDontCatchNextMsg = FALSE; + return 0; + } + + bool result = false; + + if(wMsg[0] == L'.') + { + char* szBuffer = UnicodeToAnsi(wMsg); + result = ProcessCommand(szBuffer+1, false); + delete[] szBuffer; + } + + return result == true ? -1 : 0; +} + +DWORD __fastcall ChannelInput(wchar_t* wMsg) +{ + if(Vars.bDontCatchNextMsg) + { + Vars.bDontCatchNextMsg = FALSE; + return false; + } + + bool result = false; + if(wMsg[0] == L'.') + { + char* szBuffer = UnicodeToAnsi(wMsg); + result = ProcessCommand(szBuffer+1, false); + //FIXME + //D2WIN_SetControlText(*p_D2WIN_ChatInputBox, L""); + delete[] szBuffer; + } + + // false means ignore, true means send + return result ? false : true; +} + +DWORD __fastcall GamePacketReceived(BYTE* pPacket, DWORD dwSize) +{ + switch(pPacket[0]) + { + case 0x15: return ReassignPlayerHandler(pPacket, dwSize); + case 0x26: return ChatEventHandler(pPacket, dwSize); + case 0x2A: return NPCTransactionHandler(pPacket, dwSize); + case 0x5A: return EventMessagesHandler(pPacket, dwSize); + case 0x18: + case 0x95: return HPMPUpdateHandler(pPacket, dwSize); + case 0x9C: + case 0x9D: return ItemActionHandler(pPacket, dwSize); + case 0xAE: if(!Vars.bLoadedWithCGuard) TerminateProcess(GetCurrentProcess(), 0); break; + case 0xA7: return DelayedStateHandler(pPacket, dwSize); + } + + return TRUE; +} + +LONG WINAPI GameEventHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + COPYDATASTRUCT* pCopy; + switch(uMsg) + { + case WM_COPYDATA: + pCopy = (COPYDATASTRUCT*)lParam; + + if(pCopy) + { + if(pCopy->dwData == 0x1337) // 0x1337 = Execute Script + { + Script* script = ScriptEngine::CompileCommand((char*)pCopy->lpData); + if(script) + CreateThread(0, 0, ScriptThread, script, 0, 0); + } + else if(pCopy->dwData == 0x31337) // 0x31337 = Set Profile + { + const char* profile = (char*)pCopy->lpData; + if(SwitchToProfile(profile)) + Print("ÿc2D2BSÿc0 :: Switched to profile %s", profile); + else + Print("ÿc2D2BSÿc0 :: Profile %s not found", profile); + } + else CopyDataEvent(pCopy->dwData, (char*)pCopy->lpData); + } + return TRUE; + } + + return (LONG)CallWindowProcA(Vars.oldWNDPROC, hWnd, uMsg, wParam, lParam); +} + +LRESULT CALLBACK KeyPress(int code, WPARAM wParam, LPARAM lParam) +{ + if(code >= HC_ACTION) + { + WORD repeatCount = LOWORD(lParam); + bool altState = !!(HIWORD(lParam) & KF_ALTDOWN); + bool previousState = !!(HIWORD(lParam) & KF_REPEAT); + bool transitionState = !!(HIWORD(lParam) & KF_UP); + bool isRepeat = !transitionState && repeatCount != 1; + bool isDown = !(previousState && transitionState); + bool isUp = previousState && transitionState; + + bool gameState = ClientState() == ClientStateInGame; + bool chatBoxOpen = gameState ? !!D2CLIENT_GetUIState(UI_CHAT_CONSOLE) : false; + bool escMenuOpen = gameState ? !!D2CLIENT_GetUIState(UI_ESCMENU_MAIN) : false; + + if (altState && wParam == VK_F4) + return CallNextHookEx(NULL, code, wParam, lParam); + + if(Vars.bBlockKeys) + return 1; + + if(wParam == VK_HOME && !(chatBoxOpen || escMenuOpen)) + { + if(isDown && !isRepeat && code == HC_ACTION) + { + if(!altState) + Console::ToggleBuffer(); + else + Console::TogglePrompt(); + + return CallNextHookEx(NULL, code, wParam, lParam); + } + } + else if(wParam == VK_ESCAPE && Console::IsVisible()) + { + if(isDown && !isRepeat && code == HC_ACTION ) + { + Console::Hide(); + return 1; + } + return CallNextHookEx(NULL, code, wParam, lParam); + } + else if(Console::IsEnabled()) + { + BYTE layout[256] = {0}; + WORD out[2] = {0}; + switch(wParam) + { + case VK_TAB: + if(isUp) + for(int i = 0; i < 5; i++) + Console::AddKey(' '); + break; + case VK_RETURN: + if(isUp && !isRepeat && !escMenuOpen) + Console::ExecuteCommand(); + break; + case VK_BACK: + if(isDown) + Console::RemoveLastKey(); + break; + case VK_UP: + if(isUp && !isRepeat) + Console::PrevCommand(); + break; + case VK_DOWN: + if(isUp && !isRepeat) + Console::NextCommand(); + break; + case VK_NEXT: + if(isDown) + Console::ScrollDown(); + break; + case VK_PRIOR: + if(isDown ) + Console::ScrollUp(); + break; + default: + if(isDown) + { + GetKeyboardState(layout); + if(ToAscii(wParam, (lParam & 0xFF0000), layout, out, 0) != 0) + { + for(int i = 0; i < repeatCount; i++) + Console::AddKey(out[0]); + } + } + break; + } + return 1; + } + else if(code == HC_ACTION && !isRepeat && !(chatBoxOpen || escMenuOpen)) + KeyDownUpEvent(wParam, isUp); + } + return CallNextHookEx(NULL, code, wParam, lParam); +} + +LRESULT CALLBACK MouseMove(int code, WPARAM wParam, LPARAM lParam) +{ + MOUSEHOOKSTRUCT* mouse = (MOUSEHOOKSTRUCT*)lParam; + POINT pt = mouse->pt; + ScreenToClient(mouse->hwnd, &pt); + + // filter out clicks on the window border + if(code == HC_ACTION && (pt.x < 0 || pt.y < 0)) + return CallNextHookEx(NULL, code, wParam, lParam); + + if(Vars.bBlockMouse) + return 1; + + if(code == HC_ACTION) + { + bool clicked = false; + + HookClickHelper helper = {-1, {pt.x, pt.y}}; + switch(wParam) + { + case WM_LBUTTONDOWN: + MouseClickEvent(0, pt, false); + helper.button = 0; + if(Genhook::ForEachVisibleHook(ClickHook, &helper, 1)) + clicked = true; + break; + case WM_LBUTTONUP: + MouseClickEvent(0, pt, true); + break; + case WM_RBUTTONDOWN: + MouseClickEvent(1, pt, false); + helper.button = 1; + if(Genhook::ForEachVisibleHook(ClickHook, &helper, 1)) + clicked = true; + break; + case WM_RBUTTONUP: + MouseClickEvent(1, pt, true); + break; + case WM_MBUTTONDOWN: + MouseClickEvent(2, pt, false); + helper.button = 2; + if(Genhook::ForEachVisibleHook(ClickHook, &helper, 1)) + clicked = true; + break; + case WM_MBUTTONUP: + MouseClickEvent(2, pt, true); + break; + case WM_MOUSEMOVE: + // would be nice to enable these events but they bog down too much + //MouseMoveEvent(pt); + //Genhook::ForEachVisibleHook(HoverHook, &helper, 1); + break; + } + + return clicked ? 1 : CallNextHookEx(NULL, code, wParam, lParam); + } + + return CallNextHookEx(NULL, code, wParam, lParam); +} + +void GameDraw(void) +{ + if(Vars.bActive && ClientState() == ClientStateInGame) + { + Genhook::DrawAll(IG); + DrawLogo(); + Console::Draw(); + } + Sleep(10); +} + +void GameDrawOOG(void) +{ + D2WIN_DrawSprites(); + if(Vars.bActive && ClientState() == ClientStateMenu) + { + Genhook::DrawAll(OOG); + DrawLogo(); + Console::Draw(); + } + Sleep(10); +} + +void __stdcall AddUnit(UnitAny* lpUnit) +{ +// EnterCriticalSection(&Vars.cUnitListSection); +// Vars.vUnitList.push_back(make_pair(lpUnit->dwUnitId, lpUnit->dwType)); +// LeaveCriticalSection(&Vars.cUnitListSection); +} + +void __stdcall RemoveUnit(UnitAny* lpUnit) +{ +// EnterCriticalSection(&Vars.cUnitListSection); + // no need to check the return--it has to be there or the real game would have bigger issues with it +// for(vector >::iterator it = Vars.vUnitList.begin(); it != Vars.vUnitList.end(); it++) +// { +// if(it->first == lpUnit->dwUnitId && it->second == lpUnit->dwType) +// { +// Vars.vUnitList.erase(it); +// break; +// } +// } +// LeaveCriticalSection(&Vars.cUnitListSection); +} + +void __fastcall WhisperHandler(char* szAcc, char* szText) +{ + if(!Vars.bDontCatchNextMsg) + WhisperEvent(szAcc, szText); + else + Vars.bDontCatchNextMsg = FALSE; +} + +void __fastcall ChannelWhisperHandler(char* szAcc, char* szText) +{ + if(!Vars.bDontCatchNextMsg) + WhisperEvent(szAcc, szText); + else + Vars.bDontCatchNextMsg = FALSE; +} + +void __fastcall ChannelChatHandler(char* szAcc, char* szText) +{ + if(!Vars.bDontCatchNextMsg) + ChatEvent(szAcc, szText); + else + Vars.bDontCatchNextMsg = FALSE; +} + +DWORD __fastcall GameAttack(UnitInteraction* pAttack) +{ + if(!pAttack || !pAttack->lpTargetUnit || pAttack->lpTargetUnit->dwType != UNIT_MONSTER) + return (DWORD)-1; + + if(pAttack->dwMoveType == ATTACKTYPE_UNITLEFT) + pAttack->dwMoveType = ATTACKTYPE_SHIFTLEFT; + + if(pAttack->dwMoveType == ATTACKTYPE_RIGHT) + pAttack->dwMoveType = ATTACKTYPE_SHIFTRIGHT; + + return NULL; +} + +void __fastcall GamePlayerAssignment(UnitAny* pPlayer) +{ + if(!pPlayer) + return; + + PlayerAssignEvent(pPlayer->dwUnitId); +} + +void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) +{ + if(Vars.bGameLoopEntered) + LeaveCriticalSection(&Vars.cGameLoopSection); + else + Vars.bGameLoopEntered = true; + + while(Vars.SectionCount) + Sleep(0); + + EnterCriticalSection(&Vars.cGameLoopSection); +} + + +void GameLeave(void) +{ + if(Vars.bGameLoopEntered) + LeaveCriticalSection(&Vars.cGameLoopSection); + else + Vars.bGameLoopEntered = true; + + ScriptEngine::ForEachScript(StopIngameScript, NULL, 0); +// LevelMap::ClearCache(); + + EnterCriticalSection(&Vars.cGameLoopSection); +} \ No newline at end of file diff --git a/D2Handlers.h b/D2Handlers.h new file mode 100644 index 00000000..62fad908 --- /dev/null +++ b/D2Handlers.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include "D2Structs.h" + +DWORD WINAPI D2Thread(LPVOID lpParam); +DWORD __fastcall GameInput(wchar_t* wMsg); +LONG WINAPI GameEventHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); +LRESULT CALLBACK MouseMove(int code, WPARAM wParam, LPARAM lParam); +LRESULT CALLBACK KeyPress(int code, WPARAM wParam, LPARAM lParam); +void GameDraw(void); +DWORD __fastcall GamePacketReceived(BYTE* pPacket, DWORD dwSize); +void __fastcall GameResetFrames(UnitAny* pOwner); +void GameDrawOOG(void); +void __stdcall AddUnit(UnitAny* lpUnit); +void __stdcall RemoveUnit(UnitAny* lpUnit); +void __fastcall WhisperHandler(char* szAcc, char* szText); +DWORD __fastcall ChannelInput(wchar_t* wMsg); +void __fastcall ChannelWhisperHandler(char* szAcc, char* szText); +void __fastcall ChannelChatHandler(char* szAcc, char* szText); +DWORD __fastcall GameAttack(UnitInteraction* pAttack); +void __fastcall GamePlayerAssignment(UnitAny* pPlayer); +void GameLeave(void); +void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); diff --git a/D2Helpers.cpp b/D2Helpers.cpp new file mode 100644 index 00000000..0dcbd188 --- /dev/null +++ b/D2Helpers.cpp @@ -0,0 +1,1008 @@ +#include +#include +#include +#include + +#include "D2Helpers.h" +#include "Constants.h" +#include "Helpers.h" +#include "D2Skills.h" +#include "D2Intercepts.h" +#include "D2BS.h" +#include "stringhash.h" +#include "D2Ptrs.h" + +void Log(char* szFormat, ...) +{ + va_list vaArgs; + + va_start(vaArgs, szFormat); + int len = _vscprintf(szFormat, vaArgs); + char* szString = new char[len+1]; + vsprintf_s(szString, len+1, szFormat, vaArgs); + va_end(vaArgs); + + time_t tTime; + time(&tTime); + char szTime[128] = ""; + struct tm time; + localtime_s(&time, &tTime); + strftime(szTime, sizeof(szTime), "%x %X", &time); + + char path[_MAX_PATH+_MAX_FNAME] = ""; + sprintf_s(path, sizeof(path), "%sd2bs.log", Vars.szPath); + +#ifdef DEBUG + FILE* log = stderr; +#else + FILE* log = _fsopen(path, "a+", _SH_DENYNO); +#endif + fprintf(log, "[%s] D2BS %d: %s\n", szTime, GetProcessId(GetCurrentProcess()), szString); +#ifndef DEBUG + fflush(log); + fclose(log); +#endif + delete[] szString; +} + +// NOTE TO CALLERS: szTmp must be a PRE-INITIALIZED string. +const char* GetUnitName(UnitAny* pUnit, char* szTmp, size_t bufSize) +{ + if(!pUnit) + { + strcpy_s(szTmp, bufSize, "Unknown"); + return szTmp; + } + if(pUnit->dwType == UNIT_MONSTER) { + wchar_t* wName = D2CLIENT_GetUnitName(pUnit); + WideCharToMultiByte(CP_ACP, 0, wName, -1, szTmp, bufSize, 0, 0); + return szTmp; + } + if(pUnit->dwType == UNIT_PLAYER && pUnit->pPlayerData) + { + // return pUnit->pPlayerData->szName; + strcpy_s(szTmp, bufSize, pUnit->pPlayerData->szName); + return szTmp; + } + if(pUnit->dwType == UNIT_ITEM) + { + wchar_t wBuffer[256] = L""; + D2CLIENT_GetItemName(pUnit, wBuffer, sizeof(wBuffer)); + char* szBuffer = UnicodeToAnsi(wBuffer); + if(strchr(szBuffer, '\n')) + *strchr(szBuffer,'\n') = 0x00; + + strcpy_s(szTmp, bufSize, szBuffer); + delete[] szBuffer; + return szTmp; + } + if(pUnit->dwType == UNIT_OBJECT || pUnit->dwType == UNIT_TILE) + { + if(pUnit->pObjectData && pUnit->pObjectData->pTxt) + { + strcpy_s(szTmp, bufSize, pUnit->pObjectData->pTxt->szName); + return szTmp; + } + } + strcpy_s(szTmp, bufSize, "Unknown"); + return szTmp; +} + +// szBuf must be a 4-character string +void GetItemCode(UnitAny* pUnit, char* szBuf) +{ + if(pUnit->dwType == UNIT_ITEM) + { + ItemTxt* pTxt = D2COMMON_GetItemText(pUnit->dwTxtFileNo); + if(pTxt) + { + memcpy(szBuf, pTxt->szCode, 3); + szBuf[3] = 0x00; + } + } +} + +bool InArea(int x, int y, int x2, int y2, int sizex, int sizey) { + return !!(x >= x2 && x < x2+sizex && y >= y2 && y < y2+sizey); +} + +UnitAny* FindItemByPosition(DWORD x, DWORD y, DWORD Location) { + for(UnitAny* pItem = D2COMMON_GetItemFromInventory(D2CLIENT_GetPlayerUnit()->pInventory); pItem; pItem = D2COMMON_GetNextItemFromInventory(pItem)) { + if((DWORD)GetItemLocation(pItem) == Location && InArea(x,y,pItem->pObjectPath->dwPosX,pItem->pObjectPath->dwPosY,D2COMMON_GetItemText(pItem->dwTxtFileNo)->xSize,D2COMMON_GetItemText(pItem->dwTxtFileNo)->ySize)) + return pItem; + } + return NULL; +} + +void SelectInventoryItem(DWORD x, DWORD y, DWORD dwLocation) +{ + *(DWORD*)&p_D2CLIENT_SelectedInvItem = (DWORD)FindItemByPosition(x, y, dwLocation); +} + +ClientGameState ClientState(void) +{ + ClientGameState state = ClientStateNull; + + if(D2CLIENT_GetPlayerUnit() && !(*p_D2WIN_FirstControl)) + { + if(D2CLIENT_GetPlayerUnit()->pInventory && + D2CLIENT_GetPlayerUnit()->pPath && + D2CLIENT_GetPlayerUnit()->pPath->xPos && + D2CLIENT_GetPlayerUnit()->pPath->pRoom1 && + D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2 && + D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2->pLevel && + D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2->pLevel->dwLevelNo) + state = ClientStateInGame; + else + state = ClientStateBusy; + } + else if(!D2CLIENT_GetPlayerUnit() && *p_D2WIN_FirstControl) + state = ClientStateMenu; + else if(!D2CLIENT_GetPlayerUnit() && !(*p_D2WIN_FirstControl)) + state = ClientStateNull; + + return state; +} + +bool GameReady(void) +{ + return (ClientState() == ClientStateInGame ? true : false); +} + +bool WaitForGameReady(void) +{ + DWORD start = GetTickCount(); + do + { + switch(ClientState()) + { + case ClientStateNull: case ClientStateMenu: return false; + case ClientStateInGame: return true; + } + Sleep(10); + } while((Vars.dwGameTimeout == 0 ) || (Vars.dwGameTimeout > 0 && (GetTickCount() - start) < Vars.dwGameTimeout)); + return false; +} + +DWORD GetPlayerArea(void) +{ + return (ClientState() == ClientStateInGame ? D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2->pLevel->dwLevelNo : NULL); +} + +Level* GetLevel(DWORD dwLevelNo) +{ + for(Level* pLevel = D2CLIENT_GetPlayerUnit()->pAct->pMisc->pLevelFirst; pLevel; pLevel = pLevel->pNextLevel) + if(pLevel->dwLevelNo == dwLevelNo) + return pLevel; + + return D2COMMON_GetLevel(D2CLIENT_GetPlayerUnit()->pAct->pMisc, dwLevelNo); +} + +// TODO: make this use SIZE for clarity +POINT CalculateTextLen(const char* szwText, int Font) +{ + POINT ret = {0,0}; + + if(!szwText) + return ret; + + wchar_t* Buffer = AnsiToUnicode(szwText); + + DWORD dwWidth, dwFileNo; + DWORD dwOldSize = D2WIN_SetTextSize(Font); + ret.y = D2WIN_GetTextSize(Buffer, &dwWidth, &dwFileNo); + ret.x = dwWidth; + D2WIN_SetTextSize(dwOldSize); + + delete[] Buffer; + return ret; +} + +int GetSkill(WORD wSkillId) +{ + if(!D2CLIENT_GetPlayerUnit()) return 0; + + for(Skill* pSkill = D2CLIENT_GetPlayerUnit()->pInfo->pFirstSkill; pSkill; pSkill = pSkill->pNextSkill) + if(pSkill->pSkillInfo->wSkillId == wSkillId) + return D2COMMON_GetSkillLevel(D2CLIENT_GetPlayerUnit(), pSkill, TRUE); + + return 0; +} + +BOOL SetSkill(WORD wSkillId, BOOL bLeft, DWORD dwItemId) +{ + if(ClientState() != ClientStateInGame) + return FALSE; + + if(!GetSkill(wSkillId)) + return FALSE; + + BYTE aPacket[9]; + + aPacket[0] = 0x3C; + *(WORD*)&aPacket[1] = wSkillId; + aPacket[3] = 0; + aPacket[4] = (bLeft) ? 0x80 : 0; + *(DWORD*)&aPacket[5] = dwItemId; + + D2CLIENT_SendGamePacket(9, aPacket); + + UnitAny* Me = D2CLIENT_GetPlayerUnit(); + + int timeout = 0; + Skill* hand = NULL; + while(ClientState() == ClientStateInGame) + { + hand = (bLeft ? Me->pInfo->pLeftSkill : Me->pInfo->pRightSkill); + if(hand->pSkillInfo->wSkillId != wSkillId) + { + if(timeout > 10) + return FALSE; + timeout++; + } + else + return TRUE; + Sleep(100); + } + + return FALSE; +} + +// Compare the skillname to the Game_Skills struct to find the right skill ID to return +WORD GetSkillByName(char* skillname) +{ + for(int i = 0; i < 216; i++) + if(_stricmp(Game_Skills[i].name, skillname) == 0) + return Game_Skills[i].skillID; + return (WORD)-1; +} + +char* GetSkillByID(WORD id) +{ + for(int i = 0; i < 216; i++) + if(id == Game_Skills[i].skillID) + return Game_Skills[i].name; + return NULL; +} + +void SendMouseClick(int x, int y, int clicktype) +{ + // HACK: Using PostMessage instead of SendMessage--need to fix this ASAP! + LPARAM lp = x + (y << 16); + switch(clicktype) + { + case 0: + PostMessage(D2GFX_GetHwnd(), WM_LBUTTONDOWN, 0, lp); + break; + case 1: + PostMessage(D2GFX_GetHwnd(), WM_LBUTTONUP, 0, lp); + break; + case 2: + PostMessage(D2GFX_GetHwnd(), WM_RBUTTONDOWN, 0, lp); + break; + case 3: + PostMessage(D2GFX_GetHwnd(), WM_RBUTTONUP, 0, lp); + break; + } +} + +DWORD __declspec(naked) __fastcall D2CLIENT_InitAutomapLayer_STUB(DWORD nLayerNo) +{ + __asm + { + push eax; + mov eax, ecx; + call D2CLIENT_InitAutomapLayer_I; + pop eax; + ret; + } +} + +AutomapLayer* InitAutomapLayer(DWORD levelno) +{ + AutomapLayer2 *pLayer = D2COMMON_GetLayer(levelno); + return D2CLIENT_InitAutomapLayer(pLayer->nLayerNo); +} + +void WorldToScreen(POINT* pPos) +{ + D2COMMON_MapToAbsScreen(&pPos->x, &pPos->y); + pPos->x -= D2CLIENT_GetMouseXOffset(); + pPos->y -= D2CLIENT_GetMouseYOffset(); +} + +void ScreenToWorld( POINT *pPos) +{ + D2COMMON_AbsScreenToMap(&pPos->x, &pPos->y); + pPos->x += D2CLIENT_GetMouseXOffset(); + pPos->y += D2CLIENT_GetMouseYOffset(); +} + +void ScreenToAutomap(POINT* pPos) +{ + pPos->x = (pPos->x / *p_D2CLIENT_AutomapMode) - p_D2CLIENT_Offset->x + 8; + pPos->y = (pPos->y / *p_D2CLIENT_AutomapMode) - p_D2CLIENT_Offset->y - 8; +} + +void AutomapToScreen(POINT* pPos) +{ + pPos->x = 8 - p_D2CLIENT_Offset->x + (pPos->x * (*p_D2CLIENT_AutomapMode)); + pPos->y = 8 + p_D2CLIENT_Offset->y + (pPos->y * (*p_D2CLIENT_AutomapMode)); +} + +void myDrawText(const char* szwText, int x, int y, int color, int font) +{ + wchar_t* text = AnsiToUnicode(szwText); + + DWORD dwOld = D2WIN_SetTextSize(font); + D2WIN_DrawText(text, x, y, color, 0); + D2WIN_SetTextSize(dwOld); + + delete[] text; +} + + +void myDrawCenterText(const char* szText, int x, int y, int color, int font, int div) +{ + DWORD dwWidth = NULL, dwFileNo = NULL, dwOldSize = NULL; + wchar_t* Buffer = AnsiToUnicode(szText); + + dwOldSize = D2WIN_SetTextSize(font); + D2WIN_GetTextSize(Buffer, &dwWidth, &dwFileNo); + D2WIN_SetTextSize(dwOldSize); + myDrawText(szText,x-(dwWidth >> div),y,color,font); + + delete[] Buffer; +} + +void D2CLIENT_Interact(UnitAny* pUnit, DWORD dwMoveType) { + + if(!pUnit) + return; + + if(!D2CLIENT_FindUnit(pUnit->dwUnitId,pUnit->dwType)) + return; + + UnitInteraction pInteract = { + dwMoveType, + D2CLIENT_GetPlayerUnit(), + pUnit, + D2CLIENT_GetUnitX(pUnit), + D2CLIENT_GetUnitY(pUnit), + 0, 0 + }; + + D2CLIENT_Interact_STUB(&pInteract); +} + +typedef void (*fnClickEntry) (void); + +BOOL ClickNPCMenu(DWORD NPCClassId, DWORD MenuId) +{ + NPCMenu* pMenu = (NPCMenu*)p_D2CLIENT_NPCMenu; + fnClickEntry pClick = (fnClickEntry) NULL; + + for(UINT i = 0; i < *p_D2CLIENT_NPCMenuAmount; i++) + { + if(pMenu->dwNPCClassId == NPCClassId) + { + if(pMenu->wEntryId1 == MenuId) + { + pClick = (fnClickEntry)pMenu->dwEntryFunc1; + if(pClick) + pClick(); + else return FALSE; + return TRUE; + } + else if(pMenu->wEntryId2 == MenuId) + { + pClick = (fnClickEntry)pMenu->dwEntryFunc2; + if(pClick) + pClick(); + else return FALSE; + return TRUE; + } + else if(pMenu->wEntryId3 == MenuId) + { + pClick = (fnClickEntry)pMenu->dwEntryFunc3; + if(pClick) + pClick(); + else return FALSE; + return TRUE; + } + else if(pMenu->wEntryId4 == MenuId) + { + pClick = (fnClickEntry)pMenu->dwEntryFunc4; + if(pClick) + pClick(); + else return FALSE; + return TRUE; + } + } + pMenu = (NPCMenu*) ((DWORD)pMenu + sizeof(NPCMenu)); + } + + return FALSE; +} + +int GetItemLocation(UnitAny *pItem) +{ + if(!pItem || !pItem->pItemData) + return -1; + + switch(pItem->pItemData->ItemLocation) + { + case STORAGE_INVENTORY: + return STORAGE_INVENTORY; + + case STORAGE_CUBE: + return STORAGE_CUBE; + + case STORAGE_STASH: + return STORAGE_STASH; + + case STORAGE_NULL: + switch(pItem->pItemData->NodePage) + { + case NODEPAGE_EQUIP: + return STORAGE_EQUIP; + + case NODEPAGE_BELTSLOTS: + return STORAGE_BELT; + } + } + + return STORAGE_NULL; +} + +BYTE CalcPercent(DWORD dwVal, DWORD dwMaxVal, BYTE iMin) +{ + if(dwVal == 0 || dwMaxVal == 0) + return 0; + + BYTE iRes = (BYTE)((double)dwVal / (double)dwMaxVal * 100.0); + if (iRes > 100) + iRes = 100; + + return max(iRes, iMin); +} + + +DWORD GetTileLevelNo(Room2* lpRoom2, DWORD dwTileNo) +{ + for(RoomTile* pRoomTile = lpRoom2->pRoomTiles; pRoomTile; pRoomTile = pRoomTile->pNext) + { + if(*(pRoomTile->nNum) == dwTileNo) + return pRoomTile->pRoom2->pLevel->dwLevelNo; + } + + return NULL; +} + +UnitAny* D2CLIENT_FindUnit(DWORD dwId, DWORD dwType) +{ + if(dwId == -1) return NULL; + UnitAny* pUnit = D2CLIENT_FindServerSideUnit(dwId, dwType); + return pUnit ? pUnit : D2CLIENT_FindClientSideUnit(dwId, dwType); +} + +// TODO: Rewrite this and split it into two functions + +CellFile* LoadCellFile(char* lpszPath, DWORD bMPQ) +{ + // AutoDetect the Cell File + if(bMPQ == 3) + { + // Check in our directory first + + HANDLE hFile = OpenFileRead(lpszPath); + + if(hFile != INVALID_HANDLE_VALUE) + { + CloseHandle(hFile); + return LoadCellFile(lpszPath, FALSE); + } + else + { + return LoadCellFile(lpszPath, TRUE); + } + + //return NULL; + } + + unsigned __int32 hash = sfh(lpszPath, (int)strlen(lpszPath)); + if(Vars.mCachedCellFiles.count(hash) > 0) + return Vars.mCachedCellFiles[hash]; + if(bMPQ == TRUE) + { + CellFile* result = (CellFile*)D2CLIENT_LoadUIImage_ASM(lpszPath); + Vars.mCachedCellFiles[hash] = result; + return result; + } + else if(bMPQ == FALSE) + { + // see if the file exists first + if(!(_access(lpszPath, 0) != 0 && errno == ENOENT)) + { + CellFile* result = myInitCellFile((CellFile*)LoadBmpCellFile(lpszPath)); + Vars.mCachedCellFiles[hash] = result; + return result; + } + } + + return NULL; +} + +POINT GetScreenSize() +{ + // HACK: p_D2CLIENT_ScreenSize is wrong for out of game, which is hardcoded to 800x600 + POINT ingame = {*p_D2CLIENT_ScreenSizeX, *p_D2CLIENT_ScreenSizeY}, + oog = {800, 600}, + p = {0}; + if(ClientState() == ClientStateMenu) p = oog; + else p = ingame; + return p; +} + +int D2GetScreenSizeX() +{ + return GetScreenSize().x; +} + +int D2GetScreenSizeY() +{ + return GetScreenSize().y; +} + +void myDrawAutomapCell(CellFile *cellfile, int xpos, int ypos, BYTE col) +{ + if(!cellfile)return; + CellContext ct; + memset(&ct, 0, sizeof(ct)); + ct.pCellFile = cellfile; + + xpos -= (cellfile->cells[0]->width/2); + ypos += (cellfile->cells[0]->height/2); + + int xpos2 = xpos - cellfile->cells[0]->xoffs, ypos2 = ypos - cellfile->cells[0]->yoffs; + if ((xpos2 >= D2GetScreenSizeX()) || ((xpos2 + (int)cellfile->cells[0]->width) <= 0) || (ypos2 >= D2GetScreenSizeY()) || ((ypos2 + (int)cellfile->cells[0]->height) <= 0)) return; + + static BYTE coltab[2][256];//, tabno = 0, lastcol = 0; + if (!coltab[0][1]) for (int k = 0; k < 255; k++) coltab[0][k] = coltab[1][k] = (BYTE)k; + cellfile->mylastcol = coltab[cellfile->mytabno ^= (col != cellfile->mylastcol)][255] = col; + + D2GFX_DrawAutomapCell2(&ct, xpos, ypos, (DWORD)-1, 5, coltab[cellfile->mytabno]); +} + +DWORD ReadFile(HANDLE hFile, void *buf, DWORD len) +//NOTE :- validates len bytes of buf +{ + DWORD numdone = 0; + ReadFile(hFile, buf, len, &numdone, NULL); + return numdone; +} +void *memcpy2(void *dest, const void *src, size_t count) +{ + return (char *)memcpy(dest, src, count)+count; +} + +HANDLE OpenFileRead(char *filename) +{ + return CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +} + +BYTE *AllocReadFile(char *filename) +{ + HANDLE hFile = OpenFileRead(filename); + int filesize = GetFileSize(hFile, 0); + if (filesize <= 0) return 0; + BYTE *buf = new BYTE[filesize]; + ReadFile(hFile, buf, filesize); + CloseHandle(hFile); + return buf; +} + +CellFile *LoadBmpCellFile(BYTE *buf1, int width, int height) +{ + BYTE *buf2 = new BYTE[(width*height*2)+height], *dest = buf2; + + for (int i = 0; i < height; i++) { + BYTE *src = buf1+(i*((width+3)&-4)), *limit = src+width; + while (src < limit) { + BYTE *start = src, *limit2 = min(limit, src+0x7f), trans = !*src; + do src++; while ((trans == (BYTE)!*src) && (src < limit2)); + if (!trans || (src < limit)) *dest++ = (BYTE)((trans?0x80:0)+(src-start)); + if (!trans) while (start < src) *dest++ = *start++; + } + *dest++ = 0x80; + } + + static DWORD dc6head[] = {6, 1, 0, 0xeeeeeeee, 1, 1, 0x1c, 0, (DWORD)-1, (DWORD)-1, 0, 0, 0, (DWORD)-1, (DWORD)-1}; + dc6head[8] = width; + dc6head[9] = height; + dc6head[14] = dest - buf2; + dc6head[13] = sizeof(dc6head)+(dc6head[14])+3; + BYTE *ret = new BYTE[dc6head[13]]; + memset(memcpy2(memcpy2(ret, dc6head, sizeof(dc6head)), buf2, dc6head[14]), 0xee, 3); + delete[] buf2; + + return (CellFile *)ret; +} + +CellFile *LoadBmpCellFile(char *filename) +{ + BYTE *ret = 0; + + BYTE *buf1 = AllocReadFile(filename); + BITMAPFILEHEADER *bmphead1 = (BITMAPFILEHEADER *)buf1; + BITMAPINFOHEADER *bmphead2 = (BITMAPINFOHEADER *)(buf1+sizeof(BITMAPFILEHEADER)); + if (buf1 && (bmphead1->bfType == 'MB') && (bmphead2->biBitCount == 8) && (bmphead2->biCompression == BI_RGB)) { + ret = (BYTE *)LoadBmpCellFile(buf1+bmphead1->bfOffBits, bmphead2->biWidth, bmphead2->biHeight); + } + delete[] buf1; + + return (CellFile *)ret; +} + +CellFile *myInitCellFile(CellFile *cf) +{ + if(cf) + D2CMP_InitCellFile(cf, &cf, "?", 0, (DWORD)-1, "?"); + return cf; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// End of Sting's or Mousepad's +/////////////////////////////////////////////////////////////////////////////////////////////////// + + + +DWORD __declspec(naked) __fastcall D2CLIENT_GetUnitName_STUB(DWORD UnitAny) +{ + __asm + { + mov eax, ecx + jmp D2CLIENT_GetUnitName_I + } +} + +DWORD __declspec(naked) __fastcall D2CLIENT_GetUIVar_STUB(DWORD varno) +{ + __asm + { + mov eax, ecx; + jmp D2CLIENT_GetUiVar_I; + } +} + +void __declspec(naked) __fastcall D2CLIENT_SetSelectedUnit_STUB(DWORD UnitAny) +{ + __asm + { + mov eax, ecx + jmp D2CLIENT_SetSelectedUnit_I + } +} +DWORD __declspec(naked) __fastcall D2CLIENT_LoadUIImage_ASM(char* Path) +{ + __asm { + mov eax, ecx + push 0 + call D2CLIENT_LoadUIImage_I + retn + } +} + +void __declspec(naked) __fastcall D2CLIENT_Interact_ASM(DWORD Struct) +{ + __asm { + mov esi, ecx + jmp D2CLIENT_Interact_I + } +} + +DWORD __declspec(naked) __fastcall D2CLIENT_ClickParty_ASM(DWORD RosterUnit, DWORD Mode) +{ + __asm + { + mov eax, ecx + jmp D2CLIENT_ClickParty_I + } +} + +// obsoleted - use D2CLIENT_ShopAction instead +// This isn't finished anyway! +void __declspec(naked) __fastcall D2CLIENT_ClickShopItem_ASM(DWORD x, DWORD y, DWORD BuyOrSell) +{ + __asm + { + mov esi, ecx + mov edi, edx + pop eax // Save return address to eax + pop ecx // Buy or sell to ecx + push ecx + push 1 + push eax + jmp D2CLIENT_ClickShopItem_I + } +} + +void __declspec(naked) __fastcall D2CLIENT_ShopAction_ASM(DWORD pItem, DWORD pNpc, DWORD pNPC, DWORD _1, DWORD pTable2 /* Could be also the ItemCost?*/, DWORD dwMode, DWORD _2, DWORD _3) +{ + __asm { + jmp D2CLIENT_ShopAction_I + } +} + +void __declspec(naked) __fastcall D2CLIENT_ClickBelt(DWORD x, DWORD y, Inventory* pInventoryData) +{ + __asm { + mov eax, edx + jmp D2CLIENT_ClickBelt_I + } +} + +void __declspec(naked) __fastcall D2CLIENT_ClickItemRight_ASM(DWORD x, DWORD y, DWORD Location, DWORD Player, DWORD pUnitInventory) +{ + __asm + { + // ECX = y, EDX = x - Blizzard is weird :D + MOV EAX, ECX + MOV ECX, EDX + MOV EDX, EAX + + POP EAX + MOV EBX,EAX + POP EAX + PUSH EBX + jmp D2CLIENT_ClickItemRight_I + } +} + +void __declspec(naked) __fastcall D2CLIENT_ClickBeltRight_ASM(DWORD pInventory, DWORD pPlayer, DWORD HoldShift, DWORD dwPotPos) +{ + __asm + { + POP EAX + MOV EBX,EAX + POP EAX + PUSH EBX + JMP D2CLIENT_ClickBeltRight_I + } +} + +void __declspec(naked) __fastcall D2CLIENT_GetItemDesc_ASM(DWORD pUnit, wchar_t* pBuffer) +{ + __asm + { + PUSH EDI + MOV EDI, EDX + PUSH NULL + PUSH 1 // TRUE = New lines, FALSE = Comma between each stat value + PUSH ECX + CALL D2CLIENT_GetItemDesc_I + POP EDI + RETN + } +} + +void __declspec(naked) __fastcall D2COMMON_DisplayOverheadMsg_ASM(DWORD pUnit) +{ + __asm + { + LEA ESI, [ECX+0xA4] + MOV EAX, [ECX+0xA4] + + PUSH EAX + PUSH 0 + call D2COMMON_DisplayOverheadMsg_I + + RETN + } +} + +void __declspec(naked) __fastcall D2CLIENT_MercItemAction_ASM(DWORD bPacketType, DWORD dwSlot) +{ + __asm + { + mov eax, ecx + mov ecx, edx + jmp D2CLIENT_MercItemAction_I + } +} + +void __declspec(naked) __fastcall D2CLIENT_PlaySound(DWORD dwSoundId) +{ + __asm + { + MOV EBX, ECX + PUSH NULL + PUSH NULL + PUSH NULL + MOV EAX, p_D2CLIENT_PlayerUnit + MOV EAX, [EAX] + MOV ECX, EAX + MOV EDX, EBX + //CALL D2CLIENT_PlaySound_I + RETN + } +} + +__declspec(naked) void __stdcall D2CLIENT_TakeWaypoint(DWORD dwWaypointId, DWORD dwArea) +{ + __asm + { + PUSH EBP + MOV EBP, ESP + SUB ESP, 0x20 + PUSH EBX + PUSH ESI + PUSH EDI + AND DWORD PTR SS:[EBP-0x20],0 + PUSH 0 + CALL _TakeWaypoint + JMP _Exit + +_TakeWaypoint: + PUSH EBP + PUSH ESI + PUSH EDI + PUSH EBX + XOR EDI, EDI + MOV EBX, 1 + MOV ECX,DWORD PTR SS:[EBP+8] + MOV EDX,DWORD PTR SS:[EBP+0xC] + LEA EBP,DWORD PTR SS:[EBP-0x20] + JMP [D2CLIENT_TakeWaypoint_I] + + +_Exit: + POP EDI + POP ESI + POP EBX + LEAVE + RETN 8 + } +} +DWORD __declspec(naked) __fastcall D2CLIENT_TestPvpFlag_STUB(DWORD planum1, DWORD planum2, DWORD flagmask) +{ + __asm + { + push esi; + push [esp+8]; + mov esi, edx; + mov edx, ecx; + call D2CLIENT_TestPvpFlag_I; + pop esi; + ret 4; + } +} + +void __declspec(naked) __fastcall D2GFX_DrawRectFrame_STUB(RECT* rect) +{ + __asm + { + mov eax, ecx; + jmp D2CLIENT_DrawRectFrame; + } +} + +DWORD __cdecl D2CLIENT_GetMinionCount(UnitAny* pUnit, DWORD dwType) +{ + DWORD dwResult; + + __asm + { + push eax + push esi + mov eax, pUnit + mov esi, dwType + call D2CLIENT_GetMinionCount_I + mov [dwResult], eax + pop esi + pop eax + } + + return dwResult; +} + +__declspec(naked) void __fastcall D2CLIENT_HostilePartyUnit(RosterUnit* pUnit, DWORD dwButton) +{ + __asm + { + mov eax, edx + jmp [D2CLIENT_ClickParty_II] + } +} + +__declspec(naked) DWORD __fastcall D2CLIENT_SendGamePacket_ASM(DWORD dwLen, BYTE* bPacket) +{ + __asm + { + push ebx + mov ebx, ecx + push edx + call D2CLIENT_SendGamePacket_I + pop ebx + ret + } +} + +double GetDistance(long x1, long y1, long x2, long y2, DistanceType type) +{ + double dist = 0; + switch(type) + { + case Euclidean: + { + double dx = (double)(x2 - x1); + double dy = (double)(y2 - y1); + dx = pow(dx, 2); + dy = pow(dy, 2); + dist = sqrt(dx + dy); + } + break; + case Chebyshev: + { + long dx = (x2 - x1); + long dy = (y2 - y1); + dx = abs(dx); + dy = abs(dy); + dist = max(dx, dy); + } + break; + case Manhattan: + { + long dx = (x2 - x1); + long dy = (y2 - y1); + dx = abs(dx); + dy = abs(dy); + dist = (dx + dy); + } + break; + default: + dist = -1; + break; + } + return dist; +} + +bool IsScrollingText() +{ + + if(!WaitForGameReady()) + return false; + + HWND d2Hwnd = D2GFX_GetHwnd(); + WindowHandlerList* whl = p_STORM_WindowHandlers->table[(0x534D5347^(DWORD)d2Hwnd)%p_STORM_WindowHandlers->length]; + MessageHandlerHashTable* mhht; + MessageHandlerList* mhl; + + while(whl) + { + if(whl->unk_0 == 0x534D5347 && whl->hWnd == d2Hwnd) + { + mhht = whl->msgHandlers; + if(mhht != NULL && mhht->table != NULL && mhht->length != 0) + { + // 0x201 - WM_something click + mhl = mhht->table[0x201 % mhht->length]; + + if(mhl != NULL) + { + while(mhl) + { + if(mhl->message && mhl->unk_4 < 0xffffffff && mhl->handler == D2CLIENT_CloseNPCTalk) + { + return true; + } + mhl = mhl->next; + } + } + } + } + whl = whl->next; + } + + return false; +} diff --git a/D2Helpers.h b/D2Helpers.h new file mode 100644 index 00000000..63bfcaed --- /dev/null +++ b/D2Helpers.h @@ -0,0 +1,93 @@ +#ifndef D2HELPERS_H +#define D2HELPERS_H + +#include "D2Structs.h" + +enum DistanceType +{ + Euclidean, Chebyshev, Manhattan +}; + +enum ClientGameState +{ + ClientStateNull, ClientStateMenu, ClientStateInGame, ClientStateBusy +}; + +void Log(char* szFormat, ...); + +ClientGameState ClientState(void); +bool GameReady(void); +bool WaitForGameReady(void); +DWORD GetPlayerArea(void); +void SendMouseClick(int x, int y, int clicktype); +POINT CalculateTextLen(const char* szwText, int Font); +void WorldToScreen(POINT* pPos); +void ScreenToWorld(POINT *ptPos); +void ScreenToAutomap(POINT* pPos); +void AutomapToScreen(POINT* pPos); +Level* GetLevel(DWORD dwLevelNo); +void D2CLIENT_Interact(UnitAny* pUnit, DWORD dwMoveType); +void myDrawText(const char* szwText, int x, int y, int color, int font); +void myDrawCenterText(const char* szwText, int x, int y, int color, int font, int div) ; +UnitAny* FindItemByPosition(DWORD x, DWORD y, DWORD Location); +BYTE CalcPercent(DWORD dwVal, DWORD dwMaxVal, BYTE iMin = NULL); +DWORD GetTileLevelNo(Room2* lpRoom2, DWORD dwTileNo); + +BOOL ClickNPCMenu(DWORD NPCClassId, DWORD MenuId); +int GetItemLocation(UnitAny *pItem); +void SelectInventoryItem(DWORD x, DWORD y, DWORD dwLocation); + +int GetSkill(WORD wSkillId); +BOOL SetSkill(WORD wSkillId, BOOL bLeft, DWORD dwItemId = 0xFFFFFFFF); +char* GetSkillByID(WORD id); +WORD GetSkillByName(char* szSkillName); + +const char* GetUnitName(UnitAny* pUnit, char* szBuf, size_t bufSize); +void GetItemCode(UnitAny* pUnit, char* szBuf); + +InventoryLayout* GetLayoutFromTable(DWORD dwTable); +UnitAny* D2CLIENT_FindUnit(DWORD dwId, DWORD dwType); + +POINT GetScreenSize(); +int D2GetScreenSizeX(); +int D2GetScreenSizeY(); + +CellFile* LoadCellFile(char* lpszPath, DWORD bMPQ = 3); + +AutomapLayer* InitAutomapLayer(DWORD levelno); +DWORD __fastcall D2CLIENT_InitAutomapLayer_STUB(DWORD nLayerNo); +void myDrawAutomapCell(CellFile *cellfile, int xpos, int ypos, BYTE col); +DWORD ReadFile(HANDLE hFile, void *buf, DWORD len); +void *memcpy2(void *dest, const void *src, size_t count); +HANDLE OpenFileRead(char *filename); +BYTE *AllocReadFile(char *filename); +CellFile *LoadBmpCellFile(BYTE *buf1, int width, int height); +CellFile *LoadBmpCellFile(char *filename); +CellFile *myInitCellFile(CellFile *cf); + +DWORD __fastcall D2CLIENT_GetUnitName_STUB(DWORD UnitAny); +DWORD __fastcall D2CLIENT_GetUIVar_STUB(DWORD varno); +DWORD __fastcall D2CLIENT_LoadUIImage_ASM(char* Path); +void __fastcall D2CLIENT_SetSelectedUnit_STUB(DWORD UnitAny); +void __fastcall D2CLIENT_Interact_ASM(DWORD Struct); +DWORD __fastcall D2CLIENT_ClickParty_ASM(DWORD RosterUnit, DWORD Mode); +void __fastcall D2CLIENT_ClickShopItem_ASM(DWORD x, DWORD y, DWORD BuyOrSell); +void __fastcall D2CLIENT_ShopAction_ASM(DWORD pTable, DWORD pItem, DWORD pNPC, DWORD _1, DWORD pTable2 /* Could be also the ItemCost?*/, DWORD dwMode, DWORD _2, DWORD _3); +void __fastcall D2CLIENT_ClickItemRight_ASM(DWORD x, DWORD y, DWORD Location, DWORD pItem, DWORD pItemPath); +void __fastcall D2CLIENT_ClickBelt(DWORD x, DWORD y, Inventory* pInventoryData); +void __fastcall D2CLIENT_ClickBeltRight_ASM(DWORD pInventory, DWORD pPlayer, DWORD HoldShift, DWORD dwPotPos); +void __fastcall D2CLIENT_GetItemDesc_ASM(DWORD pUnit, wchar_t* pBuffer); +void __fastcall D2COMMON_DisplayOverheadMsg_ASM(DWORD pUnit); +void __fastcall D2CLIENT_MercItemAction_ASM(DWORD bPacketType, DWORD dwSlot); +DWORD __fastcall D2CLIENT_LoadUIImage_ASM(char* lpszPath); +void __fastcall D2CLIENT_PlaySound(DWORD dwSoundId); +DWORD __fastcall D2CLIENT_TestPvpFlag_STUB(DWORD planum1, DWORD planum2, DWORD flagmask); +void __fastcall D2GFX_DrawRectFrame_STUB(RECT* rect); +DWORD __cdecl D2CLIENT_GetMinionCount(UnitAny* pUnit, DWORD dwType); +void __fastcall D2CLIENT_HostilePartyUnit(RosterUnit* pUnit, DWORD dwButton); +void __stdcall D2CLIENT_TakeWaypoint(DWORD dwWaypointId, DWORD dwArea); +DWORD __fastcall D2CLIENT_SendGamePacket_ASM(DWORD dwLen, BYTE* bPacket); + +double GetDistance(long x1, long y1, long x2, long y2, DistanceType type = Euclidean); +bool IsScrollingText(); +#endif diff --git a/D2Intercepts.cpp b/D2Intercepts.cpp new file mode 100644 index 00000000..d59caba1 --- /dev/null +++ b/D2Intercepts.cpp @@ -0,0 +1,295 @@ +#include "D2Handlers.h" +#include "D2Ptrs.h" +#include "D2BS.h" + +void __declspec(naked) GamePacketReceived_Intercept() +{ + __asm + { + pop ebp; + pushad; + + call GamePacketReceived; + test eax, eax; + + popad; + jnz OldCode; + + mov edx, 0; + +OldCode: + call D2NET_ReceivePacket_I; + + push ebp; + ret; + } +} + +void __declspec(naked) GameDraw_Intercept() +{ + __asm + { + call GameDraw; + + POP ESI + POP EBX + POP ECX + RETN 4 + } +} + +void __declspec(naked) GameInput_Intercept() +{ + __asm { + pushad + mov ecx, ebx + call GameInput + cmp eax, -1 + popad + je BlockIt + call D2CLIENT_InputCall_I + ret + +BlockIt: + + xor eax,eax + ret + } +} + +UnitAny* GetSelectedUnit_Intercept(void) +{ + if(Vars.bClickAction) + { + if(Vars.dwSelectedUnitId) + { + UnitAny* pUnit = D2CLIENT_FindUnit(Vars.dwSelectedUnitId, Vars.dwSelectedUnitType); + + return pUnit; + } + + return NULL; + } + + return D2CLIENT_GetSelectedUnit(); +} + +void __declspec(naked) Whisper_Intercept() +{ + __asm + { + MOV EBP,DWORD PTR SS:[ESP+0x1FC+4] + pushad + mov ecx, edx + mov edx, ebx + call WhisperHandler + popad + //jmp D2MULTI_WhisperIntercept_Jump + retn + } +} + +void __declspec(naked) GameAttack_Intercept() +{ + __asm + { + push ecx + mov ecx, [esp+0xC] + call GameAttack + pop ecx + + cmp eax, -1 + je OldCode + + call D2CLIENT_GetSelectedUnit + + cmp eax, 0 + je OldCode + + mov [esp+0x0C], 1 + +OldCode: + mov eax, [p_D2CLIENT_ScreenSizeY] + mov eax, [eax] + retn + } +} + +void __declspec(naked) PlayerAssignment_Intercept() +{ + __asm + { + FNOP + CALL D2CLIENT_AssignPlayer_I + MOV ECX, EAX + CALL GamePlayerAssignment + RETN + } +} + +void __declspec(naked) GameCrashFix_Intercept() +{ + __asm + { + CMP ECX, 0 + JE Skip + MOV DWORD PTR DS:[ECX+0x10],EDX +Skip: + MOV DWORD PTR DS:[EAX+0xC],0 + RETN + } +} + +void GameDrawOOG_Intercept(void) +{ + GameDrawOOG(); +} + +void __declspec(naked) GameActChange_Intercept(void) +{ + __asm + { + POP EAX + PUSH EDI + XOR EDI, EDI + CMP [Vars.bChangedAct], 0 + MOV [Vars.bChangedAct], 0 + JMP EAX + } +} + +void __declspec(naked) GameActChange2_Intercept(void) +{ + __asm + { + MOV [Vars.bChangedAct], 1 + retn 4 + } +} + +void __declspec(naked) GameLeave_Intercept(void) +{ + __asm + { + call GameLeave + jmp D2CLIENT_GameLeave_I + } +} + +void __declspec(naked) ChannelInput_Intercept(void) +{ + __asm + { + push ecx + mov ecx, esi + + call ChannelInput + + test eax, eax + pop ecx + + jz SkipInput + call D2MULTI_ChannelInput_I + +SkipInput: + ret + } +} + +void __declspec(naked) ChannelWhisper_Intercept(void) +{ + __asm + { + push ecx + push edx + mov ecx, edi + mov edx, ebx + + call ChannelWhisperHandler + + test eax, eax + pop edx + pop ecx + + jz SkipWhisper + jmp D2MULTI_ChannelWhisper_I + +SkipWhisper: + ret 4 + } +} + +void __declspec(naked) ChannelChat_Intercept(void) +{ + __asm + { + push ecx + push edx + mov ecx, dword ptr ss:[esp+0xC] + mov edx, dword ptr ss:[esp+0x10] + + call ChannelChatHandler + + test eax, eax + pop edx + pop ecx + + jz SkipChat + sub esp, 0x408 + jmp D2MULTI_ChannelChat_I + +SkipChat: + ret 8 + } +} + +void __declspec(naked) ChannelEmote_Intercept(void) +{ + __asm + { + push ecx + push edx + mov ecx, dword ptr ss:[esp+0xC] + mov edx, dword ptr ss:[esp+0x10] + + call ChannelChatHandler + + test eax, eax + pop edx + pop ecx + + jz SkipChat + sub esp, 0x4F8 + jmp D2MULTI_ChannelEmote_I + +SkipChat: + ret 8 + } +} + +void __declspec(naked) AddUnit_Intercept(UnitAny* lpUnit) +{ + __asm + { + call [D2CLIENT_GameAddUnit_I] + pushad + push esi + call AddUnit + popad + retn + } +} + +void __declspec(naked) RemoveUnit_Intercept(UnitAny* lpUnit) +{ + __asm + { + pushad + push dword ptr ds:[esi+edx*4] + call RemoveUnit + popad + mov eax,dword ptr ds:[ecx+0xE4] + mov DWORD PTR ds:[esi+edx*4], eax + retn + } +} diff --git a/D2Intercepts.h b/D2Intercepts.h new file mode 100644 index 00000000..379aadcc --- /dev/null +++ b/D2Intercepts.h @@ -0,0 +1,25 @@ +#ifndef D2INTERCEPTS_H +#define D2INTERCEPTS_H + +#include "D2Structs.h" + +void GameDraw_Intercept(); +void GameInput_Intercept(); +void GamePacketReceived_Intercept(); +UnitAny* GetSelectedUnit_Intercept(void); +void Whisper_Intercept(); +void GameAttack_Intercept(); +void PlayerAssignment_Intercept(); +void GameCrashFix_Intercept(); +void GameDrawOOG_Intercept(void); +void GameActChange_Intercept(void); +void GameActChange2_Intercept(void); +void GameLeave_Intercept(void); +void ChannelInput_Intercept(void); +void ChannelWhisper_Intercept(void); +void ChannelChat_Intercept(void); +void ChannelEmote_Intercept(void); +void AddUnit_Intercept(UnitAny* lpUnit); +void RemoveUnit_Intercept(UnitAny* lpUnit); + +#endif diff --git a/D2Loader.h b/D2Loader.h new file mode 100644 index 00000000..b4ea5d75 --- /dev/null +++ b/D2Loader.h @@ -0,0 +1,23 @@ +// This file is for debugging purposes only. +// You must #define _MSVC_DEBUG in order to enable it. +// It enables loading from D2Loader as a plugin, +// making debugging easier. + +#ifdef _MSVC_DEBUG + +#include + +typedef DWORD ( __stdcall * PluginEntryFunc)(DWORD dwReason, LPVOID lpData); +DWORD __stdcall PluginEntry(DWORD dwReason, LPVOID lpData) { return TRUE; } +typedef struct { DWORD dwMagicword; DWORD dwVersion; LPCSTR szDescription; PluginEntryFunc fpEntry; } PLUGIN_INTERFACE, * LPPLUGIN_INTERFACE; +PLUGIN_INTERFACE Interface = {0x44320000,0x01000912,"D2BS",PluginEntry}; + +#ifdef __cplusplus +extern "C" { +#endif +__declspec(dllexport) LPPLUGIN_INTERFACE __cdecl QueryInterface(void) { return &Interface; } +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/D2NetHandlers.cpp b/D2NetHandlers.cpp new file mode 100644 index 00000000..e700e06d --- /dev/null +++ b/D2NetHandlers.cpp @@ -0,0 +1,188 @@ +#include "D2NetHandlers.h" +#include "Script.h" +#include "ScreenHook.h" +#include "Unit.h" +#include "Helpers.h" +#include "Core.h" +#include "Constants.h" +#include "Events.h" +#include "ScriptEngine.h" +#include "Console.h" +#include "D2BS.h" +#include "MPQStats.h" + +using namespace std; + +Variables Vars; + +DWORD ReassignPlayerHandler(BYTE* pPacket, DWORD dwSize) +{ + if(*(LPDWORD)&pPacket[2] == D2CLIENT_GetPlayerUnit()->dwUnitId) + pPacket[10] = NULL; + + return TRUE; +} + +DWORD HPMPUpdateHandler(BYTE* pPacket, DWORD dwSize) +{ + WORD Life = *(WORD*)&pPacket[1]; + WORD Mana = *(WORD*)&pPacket[3]; + + if((Life & 0x8000) == 0x8000) + { + Life ^= 0x8000; + } + if((Mana & 0x8000) == 0x8000) + { + Mana ^= 0x8000; + } + if((Mana & 0x4000) == 0x4000) + { + Mana ^= 0x4000; + } + Mana *= 2; + + static WORD SaveLife = 0; + if(SaveLife != Life) + { + SaveLife = Life; + LifeEvent(Life); + } + + static WORD SaveMana = 0; + if(SaveMana != Mana) + { + SaveMana = Mana; + ManaEvent(Mana); + } + + return TRUE; +} + +DWORD ChatEventHandler(BYTE* pPacket, DWORD dwSize) +{ + char* pName = (char*)pPacket+10; + char* pMessage = (char*)pPacket + strlen(pName) + 11; + + if(!Vars.bDontCatchNextMsg) + ChatEvent(pName, pMessage); + else + Vars.bDontCatchNextMsg = FALSE; + + return TRUE; +} + +DWORD NPCTransactionHandler(BYTE* pPacket, DWORD dwSize) +{ + char code[5] = ""; + BYTE mode = pPacket[0x02]; // [BYTE Result - 0x00 = Purchased || 0x01 = Sold || 0x0c = Insuffecient Gold] + DWORD gid = *(DWORD *)(pPacket+0x07); + + ItemActionEvent(gid, code, (100 + mode), false); + + return TRUE; +} + +DWORD EventMessagesHandler(BYTE* pPacket, DWORD dwSize) +{ + // packet breakdown: http://www.edgeofnowhere.cc/viewtopic.php?t=392307 + BYTE mode = pPacket[1]; + DWORD param1 = *(DWORD*)(pPacket+3); + BYTE param2 = pPacket[7]; + char name1[16] = "", name2[28] = ""; + strcpy_s(name1, 16, (char*)pPacket+8); + strcpy_s(name2, 16, (char*)pPacket+24); + + char* tables[3] = {"", "monstats", "objects"}; + char* columns[3] = {"", "NameStr", "Name"}; + + switch(mode) + { + case 0x06: // name1 slain by name2 + /*BYTE Param2 = Unit Type of Slayer (0x00 = Player, 0x01 = NPC) + if Type = NPC, DWORD Param1 = Monster Id Code from MPQ (points to string for %Name2)*/ + if(param2 == UNIT_MONSTER || param2 == UNIT_OBJECT) + { + WORD localeId; + FillBaseStat(tables[param2], param1, columns[param2], &localeId, sizeof(WORD)); + wchar_t* str = D2LANG_GetLocaleText(localeId); + char* str2 = UnicodeToAnsi(str); + strcpy_s(name2, 28, str2); + delete[] str2; + } + break; + case 0x07: // player relation + { + for(RosterUnit* player = *p_D2CLIENT_PlayerUnitList; player != NULL; player = player->pNext) + if(player->dwUnitId == param1) + strcpy_s(name1, 16, player->szName); + switch(param2) + { + case 0x03: // hostile + if(Vars.bQuitOnHostile) + D2CLIENT_ExitGame(); + break; + } + } + break; + case 0x0a: // name1 has items in his box + if(name1[0] == 0) + strcpy_s(name1, 16, "You"); + break; + } + GameActionEvent(mode, param1, param2, name1, name2); + + return TRUE; +} + +DWORD ItemActionHandler(BYTE* pPacket, DWORD dwSize) +{ + // TODO: fix this code later by changing the way it's parsed + INT64 icode = 0; + char code[5] = ""; + BYTE mode = pPacket[1]; + DWORD gid = *(DWORD*)&pPacket[4]; + BYTE dest = ((pPacket[13] & 0x1C) >> 2); + + switch(dest) + { + case 0: + case 2: + icode = *(INT64 *)(pPacket+15)>>0x04; + break; + case 3: + case 4: + case 6: + if(!((mode == 0 || mode == 2) && dest == 3)) + { + if(mode != 0xF && mode != 1 && mode != 12) + icode = *(INT64 *)(pPacket+17) >> 0x1C; + else + icode = *(INT64 *)(pPacket+15) >> 0x04; + } + else + icode = *(INT64 *)(pPacket+17) >> 0x05; + break; + default: + break; + } + + // Converting and Cleaning + memcpy(code, &icode, 4); + if(code[3] == ' ') code[3] = '\0'; + + if(strcmp(code, "gld") == 0) + GoldDropEvent(gid, mode); + else + ItemActionEvent(gid, code, mode, (pPacket[0] == 0x9d)); + + return TRUE; +} + +DWORD DelayedStateHandler(BYTE* pPacket, DWORD dwSize) +{ + if(pPacket[6] == AFFECT_JUST_PORTALED) + return FALSE; + + return TRUE; +} diff --git a/D2NetHandlers.h b/D2NetHandlers.h new file mode 100644 index 00000000..637a7056 --- /dev/null +++ b/D2NetHandlers.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +DWORD ReassignPlayerHandler(BYTE* pPacket, DWORD dwSize); +DWORD HPMPUpdateHandler(BYTE* pPacket, DWORD dwSize); +DWORD ChatEventHandler(BYTE* pPacket, DWORD dwSize); +DWORD NPCTransactionHandler(BYTE* pPacket, DWORD dwSize); +DWORD EventMessagesHandler(BYTE* pPacket, DWORD dwSize); +DWORD ItemActionHandler(BYTE* pPacket, DWORD dwSize); +DWORD DelayedStateHandler(BYTE* pPacket, DWORD dwSize); diff --git a/D2Ptrs.h b/D2Ptrs.h new file mode 100644 index 00000000..cde3ffe6 --- /dev/null +++ b/D2Ptrs.h @@ -0,0 +1,471 @@ +#pragma once +#ifndef __D2PTRS_H__ +#define __D2PTRS_H__ + +#include "D2Structs.h" + +#pragma warning ( push ) +#pragma warning ( disable: 4245 ) + +#pragma optimize ( "", off ) + +#ifdef _DEFINE_VARS + +enum {DLLNO_D2CLIENT, DLLNO_D2COMMON, DLLNO_D2GFX, DLLNO_D2LANG, DLLNO_D2WIN, DLLNO_D2NET, DLLNO_D2GAME, DLLNO_D2LAUNCH, DLLNO_FOG, DLLNO_BNCLIENT, DLLNO_STORM, DLLNO_D2CMP, DLLNO_D2MULTI}; + +#define DLLOFFSET(a1,b1) ((DLLNO_##a1)|((b1)<<8)) +#define FUNCPTR(d1,v1,t1,t2,o1) typedef t1 d1##_##v1##_t t2; d1##_##v1##_t *d1##_##v1 = (d1##_##v1##_t *)DLLOFFSET(d1,o1); +#define VARPTR(d1,v1,t1,o1) typedef t1 d1##_##v1##_t; d1##_##v1##_t *p_##d1##_##v1 = (d1##_##v1##_t *)DLLOFFSET(d1,o1); +#define ASMPTR(d1,v1,o1) DWORD d1##_##v1 = DLLOFFSET(d1,o1); + +#else + +#define FUNCPTR(d1,v1,t1,t2,o1) typedef t1 d1##_##v1##_t t2; extern d1##_##v1##_t *d1##_##v1; +#define VARPTR(d1,v1,t1,o1) typedef t1 d1##_##v1##_t; extern d1##_##v1##_t *p_##d1##_##v1; +#define ASMPTR(d1,v1,o1) extern DWORD d1##_##v1; + +#endif +#define _D2PTRS_START D2CLIENT_GetQuestInfo + +FUNCPTR(D2CLIENT, GetQuestInfo, void* __stdcall, (void), 0x78A80) + +FUNCPTR(D2CLIENT, SubmitItem, void __fastcall, (DWORD dwItemId), 0x79670) +FUNCPTR(D2CLIENT, Transmute, void __fastcall, (void), 0x94370) + +FUNCPTR(D2CLIENT, FindClientSideUnit, UnitAny* __fastcall, (DWORD dwId, DWORD dwType), 0x620B0) +FUNCPTR(D2CLIENT, FindServerSideUnit, UnitAny* __fastcall, (DWORD dwId, DWORD dwType), 0x620D0) +FUNCPTR(D2CLIENT, GetCurrentInteractingNPC, UnitAny* __fastcall, (void), 0x790D0) +FUNCPTR(D2CLIENT, GetSelectedUnit, UnitAny * __stdcall, (void), 0x17280) +FUNCPTR(D2CLIENT, GetCursorItem, UnitAny* __fastcall, (void), 0x144A0) +FUNCPTR(D2CLIENT, GetMercUnit, UnitAny* __fastcall, (void), 0x9C0A0) +//FUNCPTR(D2CLIENT, UnitTestSelect, DWORD __stdcall, (UnitAny* pUnit, DWORD _1, DWORD _2, DWORD _3), 0x8D030) // unused but we need to use it + +FUNCPTR(D2CLIENT, SetSelectedUnit_I, void __fastcall, (UnitAny *pUnit), 0x17060) +FUNCPTR(D2CLIENT, GetItemName, BOOL __stdcall, (UnitAny* pItem, wchar_t* wBuffer, DWORD dwSize), 0x958C0) +FUNCPTR(D2CLIENT, GetMonsterOwner, DWORD __fastcall, (DWORD nMonsterId), 0x8E2B0) +FUNCPTR(D2CLIENT, GetUnitHPPercent, DWORD __fastcall, (DWORD dwUnitId), 0x8E2B0) +FUNCPTR(D2CLIENT, InitInventory, void __fastcall, (void), 0x93280) +FUNCPTR(D2CLIENT, SetUIVar, DWORD __fastcall, (DWORD varno, DWORD howset, DWORD unknown1), 0x1C190) +FUNCPTR(D2CLIENT, GetUnitX, int __fastcall, (UnitAny* pUnit), 0x1210) +FUNCPTR(D2CLIENT, GetUnitY, int __fastcall, (UnitAny* pUnit), 0x1240) + +FUNCPTR(D2CLIENT, ShopAction, void __fastcall, (UnitAny* pItem, UnitAny* pNpc, UnitAny* pNpc2, DWORD dwSell, DWORD dwItemCost, DWORD dwMode, DWORD _2, DWORD _3), 0x7D030) + +FUNCPTR(D2CLIENT, CloseNPCInteract, void __fastcall, (void), 0x7BC10) +//FUNCPTR(D2CLIENT, ClearScreen, void __fastcall, (void), 0x492F0) // unused but I want to look into using it // wrong function +FUNCPTR(D2CLIENT, CloseInteract, void __fastcall, (void), 0x44980) + +FUNCPTR(D2CLIENT, GetAutomapSize, DWORD __stdcall, (void), 0x6FDD0) +FUNCPTR(D2CLIENT, NewAutomapCell, AutomapCell * __fastcall, (void), 0x703C0) +FUNCPTR(D2CLIENT, AddAutomapCell, void __fastcall, (AutomapCell *aCell, AutomapCell **node), 0x71EA0) +FUNCPTR(D2CLIENT, RevealAutomapRoom, void __stdcall, (Room1 *pRoom1, DWORD dwClipFlag, AutomapLayer *aLayer), 0x73160) +FUNCPTR(D2CLIENT, InitAutomapLayer_I, AutomapLayer* __fastcall, (DWORD nLayerNo), 0x733D0) + +FUNCPTR(D2CLIENT, ClickMap, void __stdcall, (DWORD MouseFlag, DWORD x, DWORD y, DWORD Type), 0x2B420) +FUNCPTR(D2CLIENT, LeftClickItem, void __stdcall, (UnitAny* pPlayer, Inventory* pInventory, int x, int y, DWORD dwClickType, InventoryLayout* pLayout, DWORD Location), 0x9AFF0) + +FUNCPTR(D2CLIENT, GetMouseXOffset, DWORD __fastcall, (void), 0x5BC20) +FUNCPTR(D2CLIENT, GetMouseYOffset, DWORD __fastcall, (void), 0x5BC30) + +FUNCPTR(D2CLIENT, PrintPartyString, void __stdcall, (wchar_t *wMessage, int nColor), 0x75C70) // unused but I want to look into using it too +FUNCPTR(D2CLIENT, PrintGameString, void __stdcall, (wchar_t *wMessage, int nColor), 0x75EB0) + +FUNCPTR(D2CLIENT, LeaveParty, void __fastcall, (void), 0xA26A0) + +FUNCPTR(D2CLIENT, AcceptTrade, void __fastcall, (void), 0x11F70) +FUNCPTR(D2CLIENT, CancelTrade, void __fastcall, (void), 0x11F30) + +FUNCPTR(D2CLIENT, GetDifficulty, BYTE __stdcall, (void), 0x42990) + +FUNCPTR(D2CLIENT, ExitGame, void __fastcall, (void), 0x43870) + +FUNCPTR(D2CLIENT, GetUiVar_I, DWORD __fastcall, (DWORD dwVarNo), 0x17C50) + +FUNCPTR(D2CLIENT, DrawRectFrame, void __fastcall, (DWORD Rect), 0x17D10) + +FUNCPTR(D2CLIENT, PerformGoldDialogAction, void __fastcall, (void), 0x197F0) + +FUNCPTR(D2CLIENT, GetPlayerUnit, UnitAny* __stdcall, (void), 0x613C0) + +FUNCPTR(D2CLIENT, GetLevelName_I, wchar_t* __fastcall, (DWORD levelId), 0x18250) + +FUNCPTR(D2CLIENT, ClearScreen, void __fastcall, (void), 0x7AB80) + +FUNCPTR(D2CLIENT, CloseNPCTalk, DWORD __stdcall, (void* unk), 0x77AB0) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Client Globals +//////////////////////////////////////////////////////////////////////////////////////////////// + +VARPTR(D2CLIENT, ScreenSizeX, DWORD, 0xF7034) +VARPTR(D2CLIENT, ScreenSizeY, DWORD, 0xF7038) + +VARPTR(D2CLIENT, CursorHoverX, DWORD, 0xEE4AC) +VARPTR(D2CLIENT, CursorHoverY, DWORD, 0xEE4B0) + +VARPTR(D2CLIENT, MouseX, DWORD, 0x11C950) +VARPTR(D2CLIENT, MouseY, DWORD, 0x11C94C) + +VARPTR(D2CLIENT, MouseOffsetY, int, 0x106840) +VARPTR(D2CLIENT, MouseOffsetX, int, 0x106844) + +VARPTR(D2CLIENT, AutomapOn, DWORD, 0x11C8B8) +VARPTR(D2CLIENT, AutomapMode, int, 0xF34F8) +VARPTR(D2CLIENT, Offset, POINT, 0x11CF5C) +VARPTR(D2CLIENT, AutomapLayer, AutomapLayer*, 0x11CF28) + +VARPTR(D2CLIENT, MercStrIndex, WORD, 0xF02D8) +VARPTR(D2CLIENT, MercReviveCost, DWORD, 0x11CEE8) + +VARPTR(D2CLIENT, ServerSideUnitHashTables, UnitHashTable, 0x1047B8) +VARPTR(D2CLIENT, ClientSideUnitHashTables, UnitHashTable, 0x103BB8) + +VARPTR(D2CLIENT, ViewportY, int, 0x106840) +VARPTR(D2CLIENT, ViewportX, int, 0x106844) + +VARPTR(D2CLIENT, GoldDialogAction, DWORD, 0x11C86C) +VARPTR(D2CLIENT, GoldDialogAmount, DWORD, 0x11D568) + +VARPTR(D2CLIENT, NPCMenu, NPCMenu*, 0xF1A90) +VARPTR(D2CLIENT, NPCMenuAmount, DWORD, 0xF21E0) + +VARPTR(D2CLIENT, TradeLayout, InventoryLayout*, 0x101598) +VARPTR(D2CLIENT, StashLayout, InventoryLayout*, 0x1015E0) +VARPTR(D2CLIENT, StoreLayout, InventoryLayout*, 0x1016C0) +VARPTR(D2CLIENT, CubeLayout, InventoryLayout*, 0x1016D8) +VARPTR(D2CLIENT, InventoryLayout, InventoryLayout*, 0x1016F0) +VARPTR(D2CLIENT, MercLayout, InventoryLayout*, 0x11CCC0) + +ASMPTR(D2CLIENT, clickParty_I, 0xA2250) + +VARPTR(D2CLIENT, RegularCursorType, DWORD, 0x11C98C) +VARPTR(D2CLIENT, ShopCursorType, DWORD, 0x11CB24) + + +VARPTR(D2CLIENT, Ping, DWORD, 0x108764) +VARPTR(D2CLIENT, FPS, DWORD, 0x11CE10) +VARPTR(D2CLIENT, Skip, DWORD, 0x108770) +VARPTR(D2CLIENT, Divisor, int, 0xF34F8) + +VARPTR(D2CLIENT, OverheadTrigger, DWORD, 0x101ABE) + +VARPTR(D2CLIENT, RecentInteractId, DWORD, 0x101895) + +VARPTR(D2CLIENT, ItemPriceList, DWORD, 0x1018B3) + +VARPTR(D2CLIENT, TransactionDialog, void*, 0x1018D3) +VARPTR(D2CLIENT, TransactionDialogs, DWORD, 0x11D58C) +VARPTR(D2CLIENT, TransactionDialogs_2, DWORD, 0x11D588) + +VARPTR(D2CLIENT, GameInfo, GameStructInfo*, 0x109738) + +VARPTR(D2CLIENT, WaypointTable, DWORD, 0x1088FD) + +VARPTR(D2CLIENT, PlayerUnit, UnitAny*, 0x11D050) +VARPTR(D2CLIENT, SelectedInvItem, UnitAny*, 0x11CB28) +//VARPTR(D2CLIENT, SelectedUnit, UnitAny*, 0x11C4D8) // unused, but can we use it somewhere maybe? // 1.12 still +VARPTR(D2CLIENT, PlayerUnitList, RosterUnit*, 0x11CB04) + +VARPTR(D2CLIENT, bWeapSwitch, DWORD, 0x11CB84) + +VARPTR(D2CLIENT, bTradeAccepted, DWORD, 0x11CD54) +VARPTR(D2CLIENT, bTradeBlock, DWORD, 0x11CD64) + +//VARPTR(D2CLIENT, RecentTradeName, wchar_t*, 0x12334C) +VARPTR(D2CLIENT, RecentTradeId, DWORD, 0x11D5AC) + +VARPTR(D2CLIENT, ExpCharFlag, DWORD, 0x1087B4) + +VARPTR(D2CLIENT, MapId, DWORD, 0x11D204) // unused but I want to add it + +VARPTR(D2CLIENT, AlwaysRun, DWORD, 0x11D234) +VARPTR(D2CLIENT, NoPickUp, DWORD, 0x11D574) // unused but I want to add it + +//VARPTR(D2CLIENT, ScreenCovered, DWORD, 0x1E8F9) // unused, appears to be an int specifying which screens (if any) are opened... + +VARPTR(D2CLIENT, ChatMsg, wchar_t*, 0x11D650) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Client Stubs +//////////////////////////////////////////////////////////////////////////////////////////////// + +ASMPTR(D2CLIENT, TakeWaypoint_I, 0x3F5F3) + +ASMPTR(D2CLIENT, ClickShopItem_I, 0x7A180) +ASMPTR(D2CLIENT, ClickBelt_I, 0x6E310) +ASMPTR(D2CLIENT, ClickBeltRight_I, 0x6FA40) +ASMPTR(D2CLIENT, ClickItemRight_I, 0x9CF30) +ASMPTR(D2CLIENT, MercItemAction_I, 0xB6B00) + +ASMPTR(D2CLIENT, Interact_I, 0x2B2E0) + +ASMPTR(D2CLIENT, ClickParty_I, 0xA2250) +ASMPTR(D2CLIENT, ClickParty_II, 0x88A50) + +ASMPTR(D2CLIENT, ShopAction_I, 0x7D030) + +ASMPTR(D2CLIENT, GetUnitName_I, 0x622E0) +ASMPTR(D2CLIENT, GetItemDesc_I, 0x2E380) + +ASMPTR(D2CLIENT, AssignPlayer_I, 0x63C70) + +ASMPTR(D2CLIENT, TestPvpFlag_I, 0x6A670) + +ASMPTR(D2CLIENT, InputCall_I, 0xB6890) + +ASMPTR(D2CLIENT, Say_I, 0xB27A6) + +ASMPTR(D2CLIENT, BodyClickTable, 0xEE4B8) + +ASMPTR(D2CLIENT, LoadUIImage_I, 0xA93E0) + +ASMPTR(D2CLIENT, GetMinionCount_I, 0x8E5B0) + +ASMPTR(D2CLIENT, GameLeave_I, 0xB4370) + +ASMPTR(D2CLIENT, ClickMap_I, 0x11C8B4) +ASMPTR(D2CLIENT, ClickMap_II, 0x11D2CC) +ASMPTR(D2CLIENT, ClickMap_III, 0x5BB50) +ASMPTR(D2CLIENT, ClickMap_IV, 0x2B499) + +ASMPTR(D2CLIENT, GameAddUnit_I, 0x628E0) + +ASMPTR(D2CLIENT, LoadAct_1, 0x737F0) +ASMPTR(D2CLIENT, LoadAct_2, 0x2B420) + +ASMPTR(D2CLIENT, GetUnitFromId_I, 0x61480) +VARPTR(D2CLIENT, pUnitTable, POINT, 0x1047B8) + +ASMPTR(D2CLIENT, OverrideShrinePatch_ORIG, 0x101B08) + +ASMPTR(D2CLIENT, SendGamePacket_I, 0xB61F0) + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Common Ordinals +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2COMMON, InitLevel, void __stdcall, (Level *pLevel), 0x6DDF0) +FUNCPTR(D2COMMON, UnloadAct, unsigned __stdcall, (Act* pAct), 0x24590) +FUNCPTR(D2COMMON, GetObjectTxt, ObjectTxt * __stdcall, (DWORD objno), 0x1ADC0) +FUNCPTR(D2COMMON, LoadAct, Act* __stdcall, (DWORD ActNumber, DWORD MapId, DWORD Unk, DWORD Unk_2, DWORD Unk_3, DWORD Unk_4, DWORD TownLevelId, DWORD Func_1, DWORD Func_2), 0x24810) + +FUNCPTR(D2COMMON, GetLevelText, LevelTxt * __stdcall, (DWORD levelno), 0x30CA0) +FUNCPTR(D2COMMON, GetObjectText, ObjectTxt * __stdcall, (DWORD objno), 0x1ADC0) +FUNCPTR(D2COMMON, GetItemText, ItemTxt *__stdcall, (DWORD dwItemNo), 0x62C70) + +FUNCPTR(D2COMMON, GetLayer, AutomapLayer2* __fastcall, (DWORD dwLevelNo), 0x30B00) +FUNCPTR(D2COMMON, GetLevel, Level * __fastcall, (ActMisc *pMisc, DWORD dwLevelNo), 0x6D440) + +FUNCPTR(D2COMMON, GetStatList, StatList* __stdcall, (UnitAny* pUnit, DWORD dwUnk, DWORD dwMaxEntries ), 0x57830) +FUNCPTR(D2COMMON, CopyStatList, DWORD __stdcall, (StatList* pStatList, Stat* pStatArray, DWORD dwMaxEntries), 0x57D30) +FUNCPTR(D2COMMON, GetUnitStat, DWORD __stdcall, (UnitAny* pUnit, DWORD dwStat, DWORD dwStat2), 0x584E0) +FUNCPTR(D2COMMON, GetUnitState, int __stdcall, (UnitAny *pUnit, DWORD dwStateNo), 0x2F310) + +FUNCPTR(D2COMMON, CheckUnitCollision, DWORD __stdcall, (UnitAny* pUnitA, UnitAny* pUnitB, DWORD dwBitMask), 0x17CF0) +FUNCPTR(D2COMMON, GetRoomFromUnit, Room1* __stdcall, (UnitAny * ptUnit), 0x16530) +FUNCPTR(D2COMMON, GetTargetUnitType, Path* __stdcall, (Path* pPath), 0x773C0) + +FUNCPTR(D2COMMON, GetSkillLevel, int __stdcall, (UnitAny* pUnit, Skill* pSkill, BOOL bTotal), 0x73D60) + +FUNCPTR(D2COMMON, GetItemLevelRequirement, DWORD __stdcall, (UnitAny* pItem, UnitAny* pPlayer), 0x45660) + +FUNCPTR(D2COMMON, GetItemPrice, DWORD __stdcall, (UnitAny* MyUnit, UnitAny* pItem, DWORD U1_,DWORD U2_,DWORD U3_,DWORD U4_), 0x48620) +FUNCPTR(D2COMMON, GetRepairCost, DWORD __stdcall, (DWORD _1, UnitAny* pUnit, DWORD dwNpcId, DWORD dwDifficulty, DWORD dwItemPriceList, DWORD _2), 0x48AD0) +FUNCPTR(D2COMMON, GetItemMagicalMods, char* __stdcall, (WORD wPrefixNum), 0x62AF0) +FUNCPTR(D2COMMON, GetItemFromInventory, UnitAny *__stdcall, (Inventory* inv), 0x37520) +FUNCPTR(D2COMMON, GetNextItemFromInventory, UnitAny *__stdcall, (UnitAny *pItem), 0x38130) + +FUNCPTR(D2COMMON, GenerateOverheadMsg, OverheadMsg* __stdcall, (DWORD dwUnk, char* szMsg, DWORD dwTrigger), 0x4DD10) +FUNCPTR(D2COMMON, FixOverheadMsg, void __stdcall, (OverheadMsg* pMsg, DWORD dwUnk), 0x4DC70) + +FUNCPTR(D2COMMON, AddRoomData, void __stdcall, (Act * ptAct, int LevelId, int Xpos, int Ypos, Room1 * pRoom), 0x24990) +FUNCPTR(D2COMMON, RemoveRoomData, void __stdcall, (Act* ptAct, int LevelId, int Xpos, int Ypos, Room1* pRoom), 0x24930) + +FUNCPTR(D2COMMON, GetQuestFlag, int __stdcall, (void* QuestInfo, DWORD dwAct, DWORD dwQuest), 0x2D7A0) + +FUNCPTR(D2COMMON, AbsScreenToMap, void __stdcall, (long *pX, long *pY), 0x35810) +FUNCPTR(D2COMMON, MapToAbsScreen, void __stdcall, (long *pX, long *pY), 0x35AA0) + +FUNCPTR(D2COMMON, CheckWaypoint, DWORD __stdcall, (DWORD WaypointTable, DWORD dwLevelId), 0x5D270) + +FUNCPTR(D2COMMON, IsTownByLevelNo, BOOL __stdcall, (DWORD dwLevelNo), 0x23950) +FUNCPTR(D2COMMON, IsTownByRoom, BOOL __stdcall, (Room1* pRoom1), 0x23B80) + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Common Globals +//////////////////////////////////////////////////////////////////////////////////////////////// + +VARPTR(D2COMMON, sgptDataTable, DWORD, 0xA33F0) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Common Stubs +//////////////////////////////////////////////////////////////////////////////////////////////// + +ASMPTR(D2COMMON, DisplayOverheadMsg_I, 0x4DCF0) +ASMPTR(D2COMMON, GetLevelIdFromRoom_I, 0x23B80) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Net Functions +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2NET, SendPacket, void __stdcall, (size_t aLen, DWORD arg1, BYTE* aPacket), 0x6F20) +FUNCPTR(D2NET, ReceivePacket_I, void __stdcall, (BYTE *aPacket, DWORD aLen), 0x6020) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Net Globals +//////////////////////////////////////////////////////////////////////////////////////////////// + +VARPTR(D2NET, CriticalPacketSection, CRITICAL_SECTION, 0xB400) // unused but we need to use it + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Gfx Ordinals +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2GFX, DrawLine, void __stdcall, (int X1, int Y1, int X2, int Y2, DWORD dwColor, DWORD dwUnk), 0x81A0) +FUNCPTR(D2GFX, DrawRectangle, void __stdcall, (int X1, int Y1, int X2, int Y2, DWORD dwColor, DWORD dwTrans), 0x8210) +FUNCPTR(D2GFX, DrawAutomapCell2, void __stdcall, (CellContext* context, DWORD xpos, DWORD ypos, DWORD bright2, DWORD bright, BYTE *coltab), 0x7E60) + +FUNCPTR(D2GFX, GetScreenSize, DWORD __stdcall, (void), 0xA940) + +FUNCPTR(D2GFX, GetHwnd, HWND __stdcall, (void), 0xB0C0) +FUNCPTR(D2GFX, DrawAutomapCell, void __stdcall, (CellContext *context, DWORD xpos, DWORD ypos, RECT *cliprect, DWORD bright), 0x7C80) + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Multi Functions +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2MULTI, DoChat, void __fastcall, (void), 0x11770) +FUNCPTR(D2MULTI, PrintChannelText, void __stdcall, (char *szText, DWORD dwColor), 0x13F30) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Multi Globals +//////////////////////////////////////////////////////////////////////////////////////////////// + +VARPTR(D2MULTI, ChatBoxMsg, char*, 0x1C150) +VARPTR(D2MULTI, GameListControl, Control*, 0x39FF0)//1.13c - Unchanged + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Multi Stubs +//////////////////////////////////////////////////////////////////////////////////////////////// + +ASMPTR(D2MULTI, ChannelChat_I, 0x14BE0) +ASMPTR(D2MULTI, ChannelEmote_I, 0x14850) +ASMPTR(D2MULTI, ChannelWhisper_I, 0x142F0) +ASMPTR(D2MULTI, ChannelInput_I, 0x11B80) + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Cmp Ordinals +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2CMP, InitCellFile, void __stdcall, (void *cellfile, CellFile **outptr, char *srcfile, DWORD lineno, DWORD filever, char *filename), 0x13B50) +FUNCPTR(D2CMP, DeleteCellFile, void __stdcall, (CellFile *cellfile), 0x99B0) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Lang Ordinals +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2LANG, GetLocaleText, wchar_t* __fastcall, (WORD nLocaleTxtNo), 0x98A0) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Lang Stubs +//////////////////////////////////////////////////////////////////////////////////////////////// + +ASMPTR(D2LANG, Say_II, 0x8C60) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Launch Globals +//////////////////////////////////////////////////////////////////////////////////////////////// + +VARPTR(D2LAUNCH, BnData, BnetData *, 0x25B30) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Win Functions +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2WIN, SetControlText, void* __fastcall, (Control* box, wchar_t* txt), 0x10680) +FUNCPTR(D2WIN, DrawSprites, void __fastcall, (void), 0xEAA0) + + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Win Ordinals +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2WIN, TakeScreenshot, void __fastcall, (), 0xDF70) + +FUNCPTR(D2WIN, DrawText, void __fastcall, (const wchar_t *wStr, int xPos, int yPos, DWORD dwColor, DWORD dwUnk), 0x13B30) + +FUNCPTR(D2WIN, GetTextSize, DWORD __fastcall, (wchar_t *wStr, DWORD* dwWidth, DWORD* dwFileNo), 0x13290) +FUNCPTR(D2WIN, SetTextSize, DWORD __fastcall, (DWORD dwSize), 0x13B70) + +FUNCPTR(D2WIN, GetTextWidthFileNo, DWORD __fastcall, (wchar_t *wStr, DWORD* dwWidth, DWORD* dwFileNo), 0x13290) +FUNCPTR(D2WIN, DestroyEditBox, VOID __fastcall, (Control* pControl), 0xF320)//1.13c +FUNCPTR(D2WIN, DestroyControl, VOID __stdcall, (Control* pControl), 0xE5F0)//1.13c +FUNCPTR(D2WIN, SetEditBoxCallback, VOID __fastcall, (Control* pControl, BOOL (__stdcall *FunCallBack)(Control* pControl, DWORD dwInputType, char* pChar)), 0xF1D0)//1.13c +FUNCPTR(D2WIN, SetEditBoxProc, void __fastcall, (Control* box, BOOL (__stdcall *FunCallBack)(Control*,DWORD,DWORD)), 0xF1D0)//Updated 1.13c +FUNCPTR(D2WIN, SelectEditBoxText, void __fastcall, (Control* box), 0x76D8) //Updated 1.13c +FUNCPTR(D2WIN, InitMPQ, DWORD __stdcall, (char *dll,const char *mpqfile, char *mpqname, int v4, int v5), 0x7E50) + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Win Globals +//////////////////////////////////////////////////////////////////////////////////////////////// + +VARPTR(D2WIN, FirstControl, Control*, 0x8DB34) +VARPTR(D2WIN, FocusedControl, Control*, 0x8DB44) // unused, but we ought to use it +VARPTR(D2MULTI, ChatInputBox, DWORD*, 0x3A0B0) + +VARPTR(BNCLIENT, ClassicKey, char*, 0x1E928) +VARPTR(BNCLIENT, XPacKey, char*, 0x1E930) +VARPTR(BNCLIENT, KeyOwner, char*, 0x1E934) +FUNCPTR(BNCLIENT, DecodeAndLoadKeys, char __cdecl, (), 0x15D10) + +VARPTR(STORM, WindowHandlers, WindowHandlerHashTable, 0x55878) + +//////////////////////////////////////////////////////////////////////////////////////////////// +// D2Game Functions +//////////////////////////////////////////////////////////////////////////////////////////////// + +FUNCPTR(D2GAME, Rand, DWORD __fastcall, (DWORD* seed), 0x1050) + + + + +#define _D2PTRS_END D2GAME_Rand + +#undef FUNCPTR +#undef VARPTR +#undef ASMPTR + +#define D2CLIENT_TestPvpFlag(dwId1, dwId2, dwFlag) (D2CLIENT_TestPvpFlag_STUB(dwId1, dwId2, dwFlag)) +#define D2CLIENT_GetUIState(dwVarNo) (D2CLIENT_GetUIVar_STUB(dwVarNo)) +#define D2CLIENT_SetUIState(dwVarNo, value) (D2CLIENT_SetUIVar(dwVarNo, value, 0)) +#define D2CLIENT_InitAutomapLayer(layerlvl) ((AutomapLayer*)D2CLIENT_InitAutomapLayer_STUB(layerlvl)) +#define D2CLIENT_GetUnitName(x) (wchar_t*)D2CLIENT_GetUnitName_STUB((DWORD)x) +#define D2CLIENT_SetSelectedUnit(x) (D2CLIENT_SetSelectedUnit_STUB((DWORD)x)) +#define D2CLIENT_LoadUIImage(x) ((CellFile*)D2CLIENT_LoadUIImage_ASM(x)) +#define D2CLIENT_Interact_STUB(x) (D2CLIENT_Interact_ASM((DWORD)x)) +#define D2CLIENT_ClickParty(x,y) (D2CLIENT_ClickParty_ASM((DWORD)x, (DWORD)y)) +#define D2CLIENT_RightClickItem(x, y, loc, player, invdata) D2CLIENT_ClickItemRight_ASM(x,y, loc, (DWORD)player, (DWORD)invdata) +#define D2CLIENT_ClickBeltRight(pPlayer, pInventory, dwShift, dwPotPos) D2CLIENT_ClickBeltRight_ASM((DWORD)pPlayer, (DWORD)pInventory, dwShift, dwPotPos) +#define D2CLIENT_GetItemDesc(pUnit, pBuffer) D2CLIENT_GetItemDesc_ASM((DWORD)pUnit, pBuffer) +#define D2CLIENT_MercItemAction(bPacketType, dwSlotId) D2CLIENT_MercItemAction_ASM(bPacketType, dwSlotId) +#define D2CLIENT_SendGamePacket(dwLen, bPacket) D2CLIENT_SendGamePacket_ASM(dwLen, bPacket) + +#define D2COMMON_DisplayOverheadMsg(pUnit) D2COMMON_DisplayOverheadMsg_ASM((DWORD)pUnit) + +#define D2GFX_DrawFrame(Rect) D2GFX_DrawRectFrame_STUB(Rect) + +#pragma warning ( pop ) +#pragma optimize ( "", on ) + +#endif \ No newline at end of file diff --git a/D2Skills.h b/D2Skills.h new file mode 100644 index 00000000..9994e18c --- /dev/null +++ b/D2Skills.h @@ -0,0 +1,234 @@ +#ifndef D2SKILLS_H +#define D2SKILLS_H +// Added by lord2800 - English skill names all in a nice and complete struct. +// TODO: Deprecate this and look it up via the MPQ tables + +struct Skill_t { + char name[64]; + unsigned short skillID; +}; + +static Skill_t Game_Skills[] = +{ + //Skill, Id + {"Attack", 0}, + {"Kick", 1}, + {"Throw", 2}, + {"Unsummon", 3}, + {"Left Hand Throw", 4}, + {"Left Hand Swing", 5}, + {"Magic Arrow", 6}, + {"Fire Arrow", 7}, + {"Inner Sight", 8}, + {"Critical Strike", 9}, + {"Jab", 10}, + {"Cold Arrow", 11}, + {"Multiple Shot", 12}, + {"Dodge", 13}, + {"Power Strike", 14}, + {"Poison Javelin", 15}, + {"Exploding Arrow", 16}, + {"Slow Missiles", 17}, + {"Avoid", 18}, + {"Impale", 19}, + {"Lightning Bolt", 20}, + {"Ice Arrow", 21}, + {"Guided Arrow", 22}, + {"Penetrate", 23}, + {"Charged Strike", 24}, + {"Plague Javelin", 25}, + {"Strafe", 26}, + {"Immolation Arrow", 27}, + {"Decoy", 28}, + {"Evade", 29}, + {"Fend", 30}, + {"Freezing Arrow", 31}, + {"Valkyrie", 32}, + {"Pierce", 33}, + {"Lightning Strike", 34}, + {"Lightning Fury", 35}, + {"Fire Bolt", 36}, + {"Warmth", 37}, + {"Charged Bolt", 38}, + {"Ice Bolt", 39}, + {"Frozen Armor", 40}, + {"Inferno", 41}, + {"Static Field", 42}, + {"Telekinesis", 43}, + {"Frost Nova", 44}, + {"Ice Blast", 45}, + {"Blaze", 46}, + {"Fire Ball", 47}, + {"Nova", 48}, + {"Lightning", 49}, + {"Shiver Armor", 50}, + {"Fire Wall", 51}, + {"Enchant", 52}, + {"Chain Lightning", 53}, + {"Teleport", 54}, + {"Glacial Spike", 55}, + {"Meteor", 56}, + {"Thunder Storm", 57}, + {"Energy Shield", 58}, + {"Blizzard", 59}, + {"Chilling Armor", 60}, + {"Fire Mastery", 61}, + {"Hydra", 62}, + {"Lightning Mastery", 63}, + {"Frozen Orb", 64}, + {"Cold Mastery", 65}, + {"Amplify Damage", 66}, + {"Teeth", 67}, + {"Bone Armor", 68}, + {"Skeleton Mastery", 69}, + {"Raise Skeleton", 70}, + {"Dim Vision", 71}, + {"Weaken", 72}, + {"Poison Dagger", 73}, + {"Corpse Explosion", 74}, + {"Clay Golem", 75}, + {"Iron Maiden", 76}, + {"Terror", 77}, + {"Bone Wall", 78}, + {"Golem Mastery", 79}, + {"Raise Skeletal Mage", 80}, + {"Confuse", 81}, + {"Life Tap", 82}, + {"Poison Explosion", 83}, + {"Bone Spear", 84}, + {"Blood Golem", 85}, + {"Attract", 86}, + {"Decrepify", 87}, + {"Bone Prison", 88}, + {"Summon Resist", 89}, + {"Iron Golem", 90}, + {"Lower Resist", 91}, + {"Poison Nova", 92}, + {"Bone Spirit", 93}, + {"Fire Golem", 94}, + {"Revive", 95}, + {"Sacrifice", 96}, + {"Smite", 97}, + {"Might", 98}, + {"Prayer", 99}, + {"Resist Fire", 100}, + {"Holy Bolt", 101}, + {"Holy Fire", 102}, + {"Thorns", 103}, + {"Defiance", 104}, + {"Resist Cold", 105}, + {"Zeal", 106}, + {"Charge", 107}, + {"Blessed Aim", 108}, + {"Cleansing", 109}, + {"Resist Lightning", 110}, + {"Vengeance", 111}, + {"Blessed Hammer", 112}, + {"Concentration", 113}, + {"Holy Freeze", 114}, + {"Vigor", 115}, + {"Conversion", 116}, + {"Holy Shield", 117}, + {"Holy Shock", 118}, + {"Sanctuary", 119}, + {"Meditation", 120}, + {"Fist of the Heavens", 121}, + {"Fanaticism", 122}, + {"Conviction", 123}, + {"Redemption", 124}, + {"Salvation", 125}, + {"Bash", 126}, + {"Sword Mastery", 127}, + {"Axe Mastery", 128}, + {"Mace Mastery", 129}, + {"Howl", 130}, + {"Find Potion", 131}, + {"Leap", 132}, + {"Double Swing", 133}, + {"Pole Arm Mastery", 134}, + {"Throwing Mastery", 135}, + {"Spear Mastery", 136}, + {"Taunt", 137}, + {"Shout", 138}, + {"Stun", 139}, + {"Double Throw", 140}, + {"Increased Stamina", 141}, + {"Find Item", 142}, + {"Leap Attack", 143}, + {"Concentrate", 144}, + {"Iron Skin", 145}, + {"Battle Cry", 146}, + {"Frenzy", 147}, + {"Increased Speed", 148}, + {"Battle Orders", 149}, + {"Grim Ward", 150}, + {"Whirlwind", 151}, + {"Berserk", 152}, + {"Natural Resistance", 153}, + {"War Cry", 154}, + {"Battle Command", 155}, + {"Scroll of Townportal", 219}, + {"Book of Townportal", 220}, + {"Raven", 221}, + {"Poison Creeper", 222}, + {"Werewolf", 223}, + {"Shape Shifting", 224}, + {"Firestorm", 225}, + {"Oak Sage", 226}, + {"Summon Spirit Wolf", 227}, + {"Werebear", 228}, + {"Molten Boulder", 229}, + {"Arctic Blast", 230}, + {"Carrion Vine", 231}, + {"Feral Rage", 232}, + {"Maul", 233}, + {"Fissure", 234}, + {"Cyclone Armor", 235}, + {"Heart of Wolverine", 236}, + {"Summon Dire Wolf", 237}, + {"Rabies", 238}, + {"Fire Claws", 239}, + {"Twister", 240}, + {"Solar Creeper", 241}, + {"Hunger", 242}, + {"Shock Wave", 243}, + {"Volcano", 244}, + {"Tornado", 245}, + {"Spirit of barbs", 246}, + {"Summon Grizzly", 247}, + {"Fury", 248}, + {"Armageddon", 249}, + {"Hurricane", 250}, + {"Fire Blast", 251}, + {"Claw Mastery", 252}, + {"Psychic Hammer", 253}, + {"Tiger Strike", 254}, + {"Dragon Talon", 255}, + {"Shock Web", 256}, + {"Blade Sentinel", 257}, + {"Burst of Speed", 258}, + {"Fists of Fire", 259}, + {"Dragon Claw", 260}, + {"Charged Bolt Sentry", 261}, + {"Wake of Fire", 262}, + {"Weapon Block", 263}, + {"Cloak of Shadows", 264}, + {"Cobra Strike", 265}, + {"Blade Fury", 266}, + {"Fade", 267}, + {"Shadow Warrior", 268}, + {"Claws of Thunder", 269}, + {"Dragon Tail", 270}, + {"Lightning Sentry", 271}, + {"Wake of Inferno", 272}, + {"Mind Blast", 273}, + {"Blades of Ice", 274}, + {"Dragon Flight", 275}, + {"Death Sentry", 276}, + {"Blade Shield", 277}, + {"Venom", 278}, + {"Shadow Master", 279}, + {"Phoenix Strike", 280} +}; + +#endif diff --git a/D2Structs.h b/D2Structs.h new file mode 100644 index 00000000..06faf0e1 --- /dev/null +++ b/D2Structs.h @@ -0,0 +1,772 @@ +#pragma once +#ifndef _D2STRUCTS_H +#define _D2STRUCTS_H + +#include + +#pragma warning ( push ) +#pragma warning ( disable: 4201 ) +#pragma optimize ( "", off ) + +struct UnitAny; +struct Room1; +struct Room2; +struct Level; +struct Act; +struct ActMisc; +struct RosterUnit; +struct OverheadMsg; + +struct SplitText +{ + wchar_t* lpwszText; + SplitText* lpsNext; +}; + +struct InventoryInfo { + int nLocation; + int nMaxXCells; + int nMaxYCells; +}; + +struct GameStructInfo { + BYTE _1[0x1B]; //0x00 + char szGameName[0x18]; //0x1B + char szGameServerIp[0x56]; //0x33 + char szAccountName[0x30]; //0x89 + char szCharName[0x18]; //0xB9 + char szRealmName[0x18]; //0xD1 + BYTE _2[0x158]; //0xE9 + char szGamePassword[0x18]; //0x241 +}; + +struct AutomapCell { + DWORD fSaved; //0x00 + WORD nCellNo; //0x04 + WORD xPixel; //0x06 + WORD yPixel; //0x08 + WORD wWeight; //0x0A + AutomapCell *pLess; //0x0C + AutomapCell *pMore; //0x10 +}; + +struct GfxCell { + DWORD flags; //0x00 + DWORD width; //0x04 + DWORD height; //0x08 + DWORD xoffs; //0x0C + DWORD yoffs; //0x10 + DWORD _2; //0x14 + DWORD lpParent; //0x18 + DWORD length; //0x1C + BYTE cols; //0x20 +}; + +struct UnitInteraction { + DWORD dwMoveType; //0x00 + UnitAny* lpPlayerUnit; //0x04 + UnitAny* lpTargetUnit; //0x08 + DWORD dwTargetX; //0x0C + DWORD dwTargetY; //0x10 + DWORD _1; //0x14 + DWORD _2; //0x18 +}; + +struct CellFile { + DWORD dwVersion; //0x00 + struct { + WORD dwFlags; + BYTE mylastcol; + BYTE mytabno:1; + }; //0x04 + DWORD eFormat; //0x08 + DWORD termination; //0x0C + DWORD numdirs; //0x10 + DWORD numcells; //0x14 + GfxCell *cells[1]; //0x18 +}; + +struct CellContext { + DWORD _1[13]; //0x00 + CellFile* pCellFile; //0x34 + DWORD _2[4]; //0x38 +}; + + +struct AutomapLayer { + DWORD nLayerNo; //0x00 + DWORD fSaved; //0x04 + AutomapCell *pFloors; //0x08 + AutomapCell *pWalls; //0x0C + AutomapCell *pObjects; //0x10 + AutomapCell *pExtras; //0x14 + AutomapLayer *pNextLayer; //0x18 +}; + +struct AutomapLayer2 { + DWORD _1[2]; //0x00 + DWORD nLayerNo; //0x08 +}; + +struct LevelTxt { + DWORD dwLevelNo; //0x00 + DWORD _1[60]; //0x04 + BYTE _2; //0xF4 + char szName[40]; //0xF5 + char szEntranceText[40]; //0x11D + char szLevelDesc[41]; //0x145 + wchar_t wName[40]; //0x16E + wchar_t wEntranceText[40]; //0x1BE + BYTE nObjGroup[8]; //0x196 + BYTE nObjPrb[8]; //0x19E +}; + +struct ControlText { + wchar_t* wText; //0x00 + DWORD _1[4]; //0x04 + DWORD dwColor; //0x14 + DWORD _2; //0x18 + ControlText* pNext;//0x1C +}; + +struct Control { + DWORD dwType; //0x00 + DWORD *_1; //0x04 // unsure? definitely a ptr but not obvious, usually points to 6 when dwType is 6 I think + DWORD dwDisabled; //0x08 + DWORD dwPosX; //0x0C + DWORD dwPosY; //0x10 + DWORD dwSizeX; //0x14 + DWORD dwSizeY; //0x18 + // I think _2 thru _9 are a handler table of some sort + DWORD *_2; //0x1C // some sort of function (maybe click?) + DWORD _3; //0x20 + DWORD *_4; //0x24 // some sort of function + DWORD *_5; //0x28 + DWORD _6; //0x2C + DWORD *_7; //0x30 // ptr to something... + DWORD *_8; //0x34 // another random ptr... mostly dead ends when I examined them + DWORD _9; //0x38 + Control* pNext; //0x3C + DWORD _10; //0x40 + DWORD unkState; //0x44 _11 0 when button avail to be clicked 1 when greyed - still need to look at this more + ControlText* pFirstText; //0x48 + ControlText* pLastText; //0x4C + ControlText* pSelectedText; //0x50 + DWORD dwSelectEnd; //0x54 + DWORD dwSelectStart; //0x58 + union { + struct { //Textboxes + wchar_t wText[256]; //0x5C + DWORD dwCursorPos; + DWORD dwIsCloaked; + }; + struct { //Buttons + DWORD _12[2]; //0x5C + wchar_t wText2[256]; //0x6C + }; + }; +}; + +#pragma pack(push) +#pragma pack(1) + +struct RoomTile { + Room2* pRoom2; //0x00 + RoomTile* pNext; //0x04 + DWORD _2[2]; //0x08 + DWORD *nNum; //0x10 +}; + +struct RosterUnit { + char szName[16]; //0x00 + DWORD dwUnitId; //0x10 + DWORD dwPartyLife; //0x14 + DWORD _1; //0x18 + DWORD dwClassId; //0x1C + WORD wLevel; //0x20 + WORD wPartyId; //0x22 + DWORD dwLevelId; //0x24 + DWORD Xpos; //0x28 + DWORD Ypos; //0x2C + DWORD dwPartyFlags; //0x30 + BYTE * _5; //0x34 + DWORD _6[11]; //0x38 + WORD _7; //0x64 + char szName2[16]; //0x66 + WORD _8; //0x76 + DWORD _9[2]; //0x78 + RosterUnit * pNext; //0x80 +}; + +struct QuestInfo { + void *pBuffer; //0x00 + DWORD _1; //0x04 +}; + +struct Waypoint { + BYTE flags; //0x00 +}; + +struct PlayerData { + char szName[0x10]; //0x00 + QuestInfo *pNormalQuest; //0x10 + QuestInfo *pNightmareQuest; //0x14 + QuestInfo *pHellQuest; //0x18 + Waypoint *pNormalWaypoint; //0x1c + Waypoint *pNightmareWaypoint; //0x20 + Waypoint *pHellWaypoint; //0x24 +}; + +struct CollMap { + DWORD dwPosGameX; //0x00 + DWORD dwPosGameY; //0x04 + DWORD dwSizeGameX; //0x08 + DWORD dwSizeGameY; //0x0C + DWORD dwPosRoomX; //0x10 + DWORD dwPosRoomY; //0x14 + DWORD dwSizeRoomX; //0x18 + DWORD dwSizeRoomY; //0x1C + WORD *pMapStart; //0x20 + WORD *pMapEnd; //0x22 +}; + +struct PresetUnit { + DWORD _1; //0x00 + DWORD dwTxtFileNo; //0x04 + DWORD dwPosX; //0x08 + PresetUnit* pPresetNext; //0x0C + DWORD _3; //0x10 + DWORD dwType; //0x14 + DWORD dwPosY; //0x18 +}; + +struct Level { + DWORD _1[4]; //0x00 + Room2* pRoom2First; //0x10 + DWORD _2[2]; //0x14 + DWORD dwPosX; //0x1C + DWORD dwPosY; //0x20 + DWORD dwSizeX; //0x24 + DWORD dwSizeY; //0x28 + DWORD _3[96]; //0x2C + Level* pNextLevel; //0x1AC + DWORD _4; //0x1B0 + ActMisc* pMisc; //0x1B4 + DWORD _5[6]; //0x1BC + DWORD dwLevelNo; //0x1D0 + DWORD _6[3]; //0x1D4 + union { + DWORD RoomCenterX[9]; + DWORD WarpX[9]; + }; //0x1E0 + union { + DWORD RoomCenterY[9]; + DWORD WarpY[9]; + }; //0x204 + DWORD dwRoomEntries; //0x228 +}; + +struct Room2 { + DWORD _1[2]; //0x00 + Room2** pRoom2Near; //0x08 + DWORD _2[5]; //0x0C + struct { + DWORD dwRoomNumber; //0x00 + DWORD _1; //0x04 + DWORD* pdwSubNumber;//0x08 + } *pType2Info; //0x20 + Room2* pRoom2Next; //0x24 + DWORD dwRoomFlags; //0x28 + DWORD dwRoomsNear; //0x2C + Room1* pRoom1; //0x30 + DWORD dwPosX; //0x34 + DWORD dwPosY; //0x38 + DWORD dwSizeX; //0x3C + DWORD dwSizeY; //0x40 + DWORD _3; //0x44 + DWORD dwPresetType; //0x48 + RoomTile* pRoomTiles; //0x4C + DWORD _4[2]; //0x50 + Level* pLevel; //0x58 + PresetUnit* pPreset; //0x5C +}; + +#pragma pack(pop) + +struct Room1 { + Room1** pRoomsNear; //0x00 + DWORD _1[3]; //0x04 + Room2* pRoom2; //0x10 + DWORD _2[3]; //0x14 + CollMap* Coll; //0x20 + DWORD dwRoomsNear; //0x24 + DWORD _3[9]; //0x28 + DWORD dwXStart; //0x4C + DWORD dwYStart; //0x50 + DWORD dwXSize; //0x54 + DWORD dwYSize; //0x58 + DWORD _4[6]; //0x5C + UnitAny* pUnitFirst; //0x74 + DWORD _5; //0x78 + Room1* pRoomNext; //0x7C +}; + +struct ActMisc { + DWORD _1[37]; //0x00 + DWORD dwStaffTombLevel; //0x94 + DWORD _2[245]; //0x98 + Act* pAct; //0x46C + DWORD _3[3]; //0x470 + Level* pLevelFirst; //0x47C +}; + +struct Act { + DWORD _1[3]; //0x00 + DWORD dwMapSeed; //0x0C + Room1* pRoom1; //0x10 + DWORD dwAct; //0x14 + DWORD _2[12]; //0x18 + ActMisc* pMisc; //0x48 +}; + +struct Path { + WORD xOffset; //0x00 + WORD xPos; //0x02 + WORD yOffset; //0x04 + WORD yPos; //0x06 + DWORD _1[2]; //0x08 + WORD xTarget; //0x10 + WORD yTarget; //0x12 + DWORD _2[2]; //0x14 + Room1 *pRoom1; //0x1C + Room1 *pRoomUnk; //0x20 + DWORD _3[3]; //0x24 + UnitAny *pUnit; //0x30 + DWORD dwFlags; //0x34 + DWORD _4; //0x38 + DWORD dwPathType; //0x3C + DWORD dwPrevPathType; //0x40 + DWORD dwUnitSize; //0x44 + DWORD _5[4]; //0x48 + UnitAny *pTargetUnit; //0x58 + DWORD dwTargetType; //0x5C + DWORD dwTargetId; //0x60 + BYTE bDirection; //0x64 +}; + +struct ItemPath { + DWORD _1[3]; //0x00 + DWORD dwPosX; //0x0C + DWORD dwPosY; //0x10 + //Use Path for the rest +}; + +struct Stat { + WORD wSubIndex; //0x00 + WORD wStatIndex; //0x02 + DWORD dwStatValue; //0x04 +}; + +// Credits to SVR, http://phrozenkeep.hugelaser.com/forum/viewtopic.php?f=8&t=31458&p=224066 +struct StatList { + DWORD _1; //0x00 + UnitAny* pUnit; //0x04 + DWORD dwUnitType; //0x08 + DWORD dwUnitId; //0x0C + DWORD dwFlags; //0x10 + DWORD _2[4]; //0x14 + Stat *pStat; //0x24 + WORD wStatCount1; //0x28 + WORD wnSize; //0x2A + StatList *pPrevLink; //0x2C + DWORD _3; //0x30 + StatList *pPrev; //0x34 + DWORD _4; //0x38 + StatList *pNext; //0x3C + StatList *pSetList; //0x40 + DWORD _5; //0x44 + Stat *pSetStat; //0x48 + WORD wSetStatCount; //0x4C +}; + +struct Inventory { + DWORD dwSignature; //0x00 + BYTE *bGame1C; //0x04 + UnitAny *pOwner; //0x08 + UnitAny *pFirstItem; //0x0C + UnitAny *pLastItem; //0x10 + DWORD _1[2]; //0x14 + DWORD dwLeftItemUid; //0x1C + UnitAny *pCursorItem; //0x20 + DWORD dwOwnerId; //0x24 + DWORD dwItemCount; //0x28 +}; + +struct Light { + DWORD _1[3]; //0x00 + DWORD dwType; //0x0C + DWORD _2[7]; //0x10 + DWORD dwStaticValid; //0x2C + int *pnStaticMap; //0x30 +}; + +struct SkillInfo { + WORD wSkillId; //0x00 +}; + +struct Skill { + SkillInfo *pSkillInfo; //0x00 + Skill *pNextSkill; //0x04 + DWORD _1[8]; //0x08 + DWORD dwSkillLevel; //0x28 + DWORD _2[2]; //0x2C + DWORD dwFlags; //0x30 +}; + +struct Info { + BYTE *pGame1C; //0x00 + Skill *pFirstSkill; //0x04 + Skill *pLeftSkill; //0x08 + Skill *pRightSkill; //0x0C +}; + +struct ItemData { + DWORD dwQuality; //0x00 + DWORD _1[2]; //0x04 + DWORD dwItemFlags; //0x0C 1 = Owned by player, 0xFFFFFFFF = Not owned + DWORD _2[2]; //0x10 + DWORD dwFlags; //0x18 + DWORD _3[3]; //0x1C + DWORD dwQuality2; //0x28 + DWORD dwItemLevel; //0x2C + DWORD _4[2]; //0x30 + WORD wPrefix; //0x38 + WORD _5[2]; //0x3A + WORD wSuffix; //0x3E + DWORD _6; //0x40 + BYTE BodyLocation; //0x44 + BYTE ItemLocation; //0x45 Non-body/belt location (Body/Belt == 0xFF) + BYTE _7; //0x46 + WORD _8; //0x47 + DWORD _9[4]; //0x48 + Inventory *pOwnerInventory; //0x5C + DWORD _10; //0x60 + UnitAny *pNextInvItem; //0x64 + BYTE _11; //0x68 + BYTE NodePage; //0x69 Actual location, this is the most reliable by far + WORD _12; //0x6A + DWORD _13[6]; //0x6C + UnitAny *pOwner; //0x84 +}; + +struct ItemTxt { + wchar_t szName2[0x40]; //0x00 + union { + DWORD dwCode; + char szCode[4]; + }; //0x40 + BYTE _2[0x70]; //0x84 + WORD nLocaleTxtNo; //0xF4 + BYTE _2a[0x19]; //0xF7 + BYTE xSize; //0xFC + BYTE ySize; //0xFD + BYTE _2b[13]; //0xFE + BYTE nType; //0x11E + BYTE _3[0x0d]; //0x11F + BYTE fQuest; //0x12A +}; + +struct MonsterTxt { + BYTE _1[0x6]; //0x00 + WORD nLocaleTxtNo; //0x06 + WORD flag; //0x08 + WORD _1a; //0x0A + union { + DWORD flag1; //0x0C + struct { + BYTE flag1a; //0x0C + BYTE flag1b; //0x0D + BYTE flag1c[2]; //0x0E + }; + }; + BYTE _2[0x22]; //0x10 + WORD velocity; //0x32 + BYTE _2a[0x52]; //0x34 + WORD tcs[3][4]; //0x86 + BYTE _2b[0x52]; //0x9E + wchar_t szDescriptor[0x3c]; //0xF0 + BYTE _3[0x1a0]; //0x12C +}; + +struct MonsterData { + BYTE _1[22]; //0x00 + struct + { + BYTE fUnk:1; + BYTE fNormal:1; + BYTE fChamp:1; + BYTE fBoss:1; + BYTE fMinion:1; + }; //0x16 + BYTE _2[5]; + BYTE anEnchants[9]; //0x1C + WORD wUniqueNo; //0x26 + DWORD _5; //0x28 + struct { + wchar_t wName[28]; + }; //0x2C +}; + +struct ObjectTxt { + char szName[0x40]; //0x00 + wchar_t wszName[0x40]; //0x40 + BYTE _1[4]; //0xC0 + BYTE nSelectable0; //0xC4 + BYTE _2[0x87]; //0xC5 + BYTE nOrientation; //0x14C + BYTE _2b[0x19]; //0x14D + BYTE nSubClass; //0x166 + BYTE _3[0x11]; //0x167 + BYTE nParm0; //0x178 + BYTE _4[0x39]; //0x179 + BYTE nPopulateFn; //0x1B2 + BYTE nOperateFn; //0x1B3 + BYTE _5[8]; //0x1B4 + DWORD nAutoMap; //0x1BB +}; + +struct ObjectData { + ObjectTxt *pTxt; //0x00 + union { + BYTE Type; //0x04 (0x0F would be a Exp Shrine) + struct { + BYTE _1:7; + BYTE ChestLocked:1; + }; + }; + DWORD _2[8]; //0x08 + char szOwner[0x10]; //0x28 +}; + +struct ObjectPath { + Room1 *pRoom1; //0x00 + DWORD _1[2]; //0x04 + DWORD dwPosX; //0x0C + DWORD dwPosY; //0x10 + //Leaving rest undefined, use Path +}; + +struct UnitAny { + DWORD dwType; //0x00 + DWORD dwTxtFileNo; //0x04 + DWORD _1; //0x08 + DWORD dwUnitId; //0x0C + DWORD dwMode; //0x10 + union + { + PlayerData *pPlayerData; + ItemData *pItemData; + MonsterData *pMonsterData; + ObjectData *pObjectData; + //TileData *pTileData doesn't appear to exist anymore + }; //0x14 + DWORD dwAct; //0x18 + Act *pAct; //0x1C + DWORD dwSeed[2]; //0x20 + DWORD _2; //0x28 + union + { + Path *pPath; + ItemPath *pItemPath; + ObjectPath *pObjectPath; + }; //0x2C + DWORD _3[5]; //0x30 + DWORD dwGfxFrame; //0x44 + DWORD dwFrameRemain; //0x48 + WORD wFrameRate; //0x4C + WORD _4; //0x4E + BYTE *pGfxUnk; //0x50 + DWORD *pGfxInfo; //0x54 + DWORD _5; //0x58 + StatList *pStats; //0x5C + Inventory *pInventory; //0x60 + Light *ptLight; //0x64 + DWORD _6[9]; //0x68 + WORD wX; //0x8C + WORD wY; //0x8E + DWORD _7; //0x90 + DWORD dwOwnerType; //0x94 + DWORD dwOwnerId; //0x98 + DWORD _8[2]; //0x9C + OverheadMsg* pOMsg; //0xA4 + Info *pInfo; //0xA8 + DWORD _9[6]; //0xAC + DWORD dwFlags; //0xC4 + DWORD dwFlags2; //0xC8 + DWORD _10[5]; //0xCC + UnitAny *pChangedNext; //0xE0 + UnitAny *pListNext; //0xE4 -> 0xD8 + UnitAny *pRoomNext; //0xE8 +}; + +struct UnitHashTable +{ + UnitAny* table[128]; +}; + +struct BnetData { + DWORD dwId; //0x00 + DWORD dwId2; //0x04 + BYTE _12[13]; //0xC0 + //DWORD dwId3; //0x14 + //WORD Unk3; //0x18 + BYTE _13[6]; //0xC0 + char szGameName[22]; //0x1A + char szGameIP[16]; //0x30 + DWORD _2[15]; //0x40 + DWORD dwId4; //0x80 + BYTE _3[5]; //0x84 + char szAccountName[48]; //0x88 + char szPlayerName[24]; //0xB8 + char szRealmName[8]; //0xD0 + BYTE _4[273]; //0xD8 + BYTE nCharClass; //0x1E9 + BYTE nCharFlags; //0x1EA + BYTE nMaxLvlDifference; //0x1EB + BYTE _5[31]; //0x1EC + BYTE nDifficulty; //0x20B + void *_6; //0x20C + DWORD _7[3]; //0x210 + WORD _8; //0x224 + BYTE _9[7]; //0x226 + char szRealmName2[24]; //0x227 + char szGamePass[24]; //0x23F + char szGameDesc[256]; //0x257 + WORD _10; //0x348 + BYTE _11; //0x34B +}; + + +struct WardenClientRegion_t { + DWORD cbAllocSize; //+00 + DWORD offsetFunc1; //+04 + DWORD offsetRelocAddressTable; //+08 + DWORD nRelocCount; //+0c + DWORD offsetWardenSetup; //+10 + DWORD _2[2]; + DWORD offsetImportAddressTable; //+1c + DWORD nImportDllCount; //+20 + DWORD nSectionCount; //+24 +}; + +struct SMemBlock_t { + DWORD _1[6]; + DWORD cbSize; //+18 + DWORD _2[31]; + BYTE data[1]; //+98 +}; + +struct WardenClient_t { + WardenClientRegion_t* pWardenRegion; //+00 + DWORD cbSize; //+04 + DWORD nModuleCount; //+08 + DWORD param; //+0c + DWORD fnSetupWarden; //+10 +}; + +struct WardenIATInfo_t { + DWORD offsetModuleName; + DWORD offsetImportTable; +}; + +#pragma pack(push) +#pragma pack(1) + +struct NPCMenu { + DWORD dwNPCClassId; + DWORD dwEntryAmount; + WORD wEntryId1; + WORD wEntryId2; + WORD wEntryId3; + WORD wEntryId4; + WORD _1; + DWORD dwEntryFunc1; + DWORD dwEntryFunc2; + DWORD dwEntryFunc3; + DWORD dwEntryFunc4; + BYTE _2[5]; +}; + +struct OverheadMsg { + DWORD _1; + DWORD dwTrigger; + DWORD _2[2]; + char Msg[232]; +}; + +#pragma pack(pop) + +struct D2MSG { + HWND myHWND; + char lpBuf[256]; +}; + + +struct InventoryLayout { + BYTE SlotWidth; + BYTE SlotHeight; + BYTE unk1; + BYTE unk2; + DWORD Left; + DWORD Right; + DWORD Top; + DWORD Bottom; + BYTE SlotPixelWidth; + BYTE SlotPixelHeight; +}; + +struct MpqTable; + +struct sgptDataTable { + MpqTable* pPlayerClass; + DWORD dwPlayerClassRecords; + MpqTable* pBodyLocs; + DWORD dwBodyLocsRecords; + MpqTable* pStorePage; + DWORD dwStorePageRecords; + MpqTable* pElemTypes; +}; + +struct MessageHandlerList +{ + DWORD message; + DWORD unk_4; + DWORD (__stdcall *handler)(void*); + struct MessageHandlerList* next; +}; + +struct MessageHandlerHashTable +{ + struct MessageHandlerList** table; + DWORD length; +}; + +struct WindowHandlerHashTable +{ + struct WindowHandlerList** table; + DWORD length; +}; + +struct WindowHandlerList +{ + DWORD unk_0; + HWND hWnd; + DWORD unk_8; + struct MessageHandlerHashTable* msgHandlers; + struct WindowHandlerList* next; +}; + +#pragma warning ( pop ) +#pragma optimize ( "", on ) + +#endif \ No newline at end of file diff --git a/Events.cpp b/Events.cpp new file mode 100644 index 00000000..ee314107 --- /dev/null +++ b/Events.cpp @@ -0,0 +1,331 @@ +#include "ScriptEngine.h" + +struct ChatEventHelper +{ + char *event, *nick, *msg; +}; + +struct CopyDataHelper +{ + DWORD mode; + char* msg; +}; + +struct ItemEventHelper +{ + DWORD id; + char* code; + WORD mode; + bool global; +}; + +struct KeyEventHelper +{ + BOOL up; + WPARAM key; +}; + +struct GameActionEventHelper +{ + BYTE mode; + DWORD param1, param2; + char *name1, *name2; +}; + +struct SingleArgHelper +{ + DWORD arg1; +}; + +struct DoubleArgHelper +{ + DWORD arg1, arg2; +}; + +struct TripleArgHelper +{ + DWORD arg1, arg2, arg3; +}; + +struct BCastEventHelper +{ + jsval* argv; + uintN argc; +}; + +bool __fastcall LifeEventCallback(Script* script, void* argv, uint argc) +{ + SingleArgHelper* helper = (SingleArgHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("melife")) + { + AutoRoot** argv = new AutoRoot*[1]; + argv[0] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg1, argv[0]->value()); + script->ExecEventAsync("melife", 1, argv); + } + return true; +} + +void LifeEvent(DWORD dwLife) +{ + SingleArgHelper helper = {dwLife}; + ScriptEngine::ForEachScript(LifeEventCallback, &helper, 1); +} + +bool __fastcall ManaEventCallback(Script* script, void* argv, uint argc) +{ + SingleArgHelper* helper = (SingleArgHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("memana")) + { + AutoRoot** argv = new AutoRoot*[1]; + argv[0] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg1, argv[0]->value()); + script->ExecEventAsync("memana", 1, argv); + } + return true; +} + +void ManaEvent(DWORD dwMana) +{ + SingleArgHelper helper = {dwMana}; + ScriptEngine::ForEachScript(ManaEventCallback, &helper, 1); +} + +bool __fastcall KeyEventCallback(Script* script, void* argv, uint argc) +{ + KeyEventHelper* helper = (KeyEventHelper*)argv; + char* event = (helper->up ? "keyup" : "keydown"); + if(script->IsRunning() && script->IsListenerRegistered(event)) + { + AutoRoot** argv = new AutoRoot*[1]; + argv[0] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->key, argv[0]->value()); + script->ExecEventAsync(event, 1, argv); + } + return true; +} + +void KeyDownUpEvent(WPARAM key, BYTE bUp) +{ + KeyEventHelper helper = {bUp, key}; + ScriptEngine::ForEachScript(KeyEventCallback, &helper, 1); +} + +bool __fastcall PlayerAssignCallback(Script* script, void* argv, uint argc) +{ + SingleArgHelper* helper = (SingleArgHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("playerassign")) + { + AutoRoot** argv = new AutoRoot*[1]; + argv[0] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg1, argv[0]->value()); + script->ExecEventAsync("playerassign", 1, argv); + } + return true; +} + +void PlayerAssignEvent(DWORD dwUnitId) +{ + SingleArgHelper helper = {dwUnitId}; + ScriptEngine::ForEachScript(PlayerAssignCallback, &helper, 1); +} + +bool __fastcall MouseClickCallback(Script* script, void* argv, uint argc) +{ + TripleArgHelper* helper = (TripleArgHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("mouseclick")) + { + AutoRoot** argv = new AutoRoot*[3]; + argv[0] = new AutoRoot(INT_TO_JSVAL(helper->arg1)); + argv[1] = new AutoRoot(INT_TO_JSVAL(helper->arg2)); + argv[2] = new AutoRoot(INT_TO_JSVAL(helper->arg3)); + script->ExecEventAsync("mouseclick", 3, argv); + } + return true; +} + +void MouseClickEvent(int button, POINT pt, bool bUp) +{ + TripleArgHelper helper = {button, pt.x, pt.y}; + ScriptEngine::ForEachScript(MouseClickCallback, &helper, 1); +} + +bool __fastcall MouseMoveCallback(Script* script, void* argv, uint argc) +{ + DoubleArgHelper* helper = (DoubleArgHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("mousemove")) + { + AutoRoot** argv = new AutoRoot*[2]; + argv[0] = new AutoRoot(); + argv[1] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg1, argv[0]->value()); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg2, argv[1]->value()); + script->ExecEventAsync("mousemove", 2, argv); + } + return true; +} + +void MouseMoveEvent(POINT pt) +{ + DoubleArgHelper helper = {pt.x, pt.y}; + ScriptEngine::ForEachScript(MouseMoveCallback, &helper, 1); +} + +bool __fastcall BCastEventCallback(Script* script, void* argv, uint argc) +{ + BCastEventHelper* helper = (BCastEventHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("scriptmsg")) + { + AutoRoot** args = new AutoRoot*[helper->argc]; + for(uintN i = 0; i < helper->argc; i++) + args[i] = new AutoRoot(helper->argv[i]); + script->ExecEventAsync("scriptmsg", helper->argc, args); + } + return true; +} + +void ScriptBroadcastEvent(uintN argc, jsval* args) +{ + BCastEventHelper helper = {args, argc}; + ScriptEngine::ForEachScript(BCastEventCallback, &helper, 1); +} + +bool __fastcall GoldDropCallback(Script* script, void* argv, uint argc) +{ + DoubleArgHelper* helper = (DoubleArgHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("golddrop")) + { + AutoRoot** argv = new AutoRoot*[2]; + argv[0] = new AutoRoot(); + argv[1] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg1, argv[0]->value()); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->arg2, argv[1]->value()); + script->ExecEventAsync("golddrop", 2, argv); + } + return true; +} + +void GoldDropEvent(DWORD GID, BYTE Mode) +{ + DoubleArgHelper helper = {GID, Mode}; + ScriptEngine::ForEachScript(GoldDropCallback, &helper, 1); +} + +bool __fastcall ChatEventCallback(Script* script, void* argv, uint argc) +{ + ChatEventHelper* helper = (ChatEventHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered(helper->event)) + { + AutoRoot** argv = new AutoRoot*[2]; + JS_SetContextThread(ScriptEngine::GetGlobalContext()); + argv[0] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), helper->nick))); + argv[1] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), helper->msg))); + JS_ClearContextThread(ScriptEngine::GetGlobalContext()); + script->ExecEventAsync(helper->event, 2, argv); + } + return true; +} + +void ChatEvent(char* lpszNick, char* lpszMsg) +{ + ChatEventHelper helper = {"chatmsg", lpszNick, lpszMsg}; + ScriptEngine::ForEachScript(ChatEventCallback, &helper, 1); +} + +void WhisperEvent(char* lpszNick, char* lpszMsg) +{ + ChatEventHelper helper = {"whispermsg", lpszNick, lpszMsg}; + ScriptEngine::ForEachScript(ChatEventCallback, &helper, 1); +} + +bool __fastcall CopyDataCallback(Script* script, void* argv, uint argc) +{ + CopyDataHelper* helper = (CopyDataHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("copydata")) + { + AutoRoot** argv = new AutoRoot*[2]; + JS_SetContextThread(ScriptEngine::GetGlobalContext()); + argv[0] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->mode, argv[0]->value()); + argv[1] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), helper->msg))); + JS_ClearContextThread(ScriptEngine::GetGlobalContext()); + script->ExecEventAsync("copydata", 2, argv); + } + return true; +} + +void CopyDataEvent(DWORD dwMode, char* lpszMsg) +{ + CopyDataHelper helper = {dwMode, lpszMsg}; + ScriptEngine::ForEachScript(CopyDataCallback, &helper, 1); +} + +bool __fastcall GameEventCallback(Script* script, void* argv, uint argc) +{ + if(script->IsRunning() && script->IsListenerRegistered("gamemsg")) + { + AutoRoot** argv = new AutoRoot*[1]; + JS_SetContextThread(ScriptEngine::GetGlobalContext()); + argv[0] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), (char*)argv))); + JS_ClearContextThread(ScriptEngine::GetGlobalContext()); + script->ExecEventAsync("gamemsg", 1, argv); + } + return true; +} + +void GameMsgEvent(char* lpszMsg) +{ + ScriptEngine::ForEachScript(GameEventCallback, lpszMsg, 1); +} + +bool __fastcall ItemEventCallback(Script* script, void* argv, uint argc) +{ + ItemEventHelper* helper = (ItemEventHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("itemaction")) + { + AutoRoot** argv = new AutoRoot*[4]; + JS_SetContextThread(ScriptEngine::GetGlobalContext()); + argv[0] = new AutoRoot(); + argv[1] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->id, argv[0]->value()); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->mode, argv[1]->value()); + argv[2] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), helper->code))); + argv[3] = new AutoRoot(BOOLEAN_TO_JSVAL(helper->global)); + JS_ClearContextThread(ScriptEngine::GetGlobalContext()); + script->ExecEventAsync("itemaction", 4, argv); + } + return true; +} + +void ItemActionEvent(DWORD GID, char* Code, BYTE Mode, bool Global) +{ + ItemEventHelper helper = {GID, Code, Mode, Global}; + ScriptEngine::ForEachScript(ItemEventCallback, &helper, 1); +} + +bool __fastcall GameActionEventCallback(Script* script, void* argv, uint argc) +{ + GameActionEventHelper* helper = (GameActionEventHelper*)argv; + if(script->IsRunning() && script->IsListenerRegistered("gameevent")) + { + AutoRoot** argv = new AutoRoot*[5]; + JS_SetContextThread(ScriptEngine::GetGlobalContext()); + argv[0] = new AutoRoot(); + argv[1] = new AutoRoot(); + argv[2] = new AutoRoot(); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->mode, argv[0]->value()); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->param1, argv[1]->value()); + JS_NewNumberValue(ScriptEngine::GetGlobalContext(), helper->param2, argv[2]->value()); + argv[3] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), helper->name1))); + argv[4] = new AutoRoot(STRING_TO_JSVAL(JS_NewStringCopyZ(ScriptEngine::GetGlobalContext(), helper->name2))); + JS_ClearContextThread(ScriptEngine::GetGlobalContext()); + script->ExecEventAsync("gameevent", 5, argv); + } + return true; +} + +void GameActionEvent(BYTE mode, DWORD param1, DWORD param2, char* name1, char* name2) +{ + GameActionEventHelper helper = {mode, param1, param2, name1, name2}; + ScriptEngine::ForEachScript(GameActionEventCallback, &helper, 1); +} diff --git a/Events.h b/Events.h new file mode 100644 index 00000000..2655e2d3 --- /dev/null +++ b/Events.h @@ -0,0 +1,18 @@ +#pragma once + +#include + +void ChatEvent(char* lpszNick, char* lpszMsg); +void LifeEvent(DWORD dwLife); +void ManaEvent(DWORD dwMana); +void CopyDataEvent(DWORD dwMode, char* lpszMsg); +void GameMsgEvent(char* lpszMsg); +void GameActionEvent(BYTE mode, DWORD param1, DWORD param2, char* name1, char* name2); +void WhisperEvent(char* lpszNick, char* lpszMsg); +void KeyDownUpEvent(WPARAM bByte, BYTE bUp); +void PlayerAssignEvent(DWORD dwUnitId); +void MouseClickEvent(int button, POINT pt, bool bUp); +void MouseMoveEvent(POINT pt); +void ScriptBroadcastEvent(uintN argc, jsval* argv); +void GoldDropEvent(DWORD GID, BYTE Mode); +void ItemActionEvent(DWORD GID, char* Code, BYTE Mode, bool Global); diff --git a/File.cpp b/File.cpp new file mode 100644 index 00000000..ccc88943 --- /dev/null +++ b/File.cpp @@ -0,0 +1,190 @@ +/* + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include +#include +#include + +#include + +#include "File.h" + +using namespace std; + +const char* readLine(FILE* fptr, bool locking) +{ + if(feof(fptr)) + return NULL; + string buffer; + char c = 0; + // grab all the characters in this line + do { + if(locking) + c = (char)fgetc(fptr); + else + c = (char)_fgetc_nolock(fptr); + // append the new character unless it's a carriage return + if(c != '\r' && c != '\n' && !feof(fptr)) + buffer.append(1, c); + } while(!feof(fptr) && c != '\n'); + return _strdup(buffer.c_str()); +} + +bool writeValue(FILE* fptr, JSContext* cx, jsval value, bool isBinary, bool locking) +{ + char* str; + int len = 0, result; + int32 ival = 0; + jsdouble dval = 0; + bool bval; + + switch(JS_TypeOfValue(cx, value)) + { + case JSTYPE_VOID: case JSTYPE_NULL: + if(locking) + result = fwrite(&ival, sizeof(int), 1, fptr); + else + result = _fwrite_nolock(&ival, sizeof(int), 1, fptr); + if(result == 1) + return true; + break; + case JSTYPE_STRING: + str = JS_GetStringBytes(JSVAL_TO_STRING(value)); + if(locking) + result = fwrite(str, sizeof(char), strlen(str), fptr); + else + result = _fwrite_nolock(str, sizeof(char), strlen(str), fptr); + return (int)strlen(str) == result; + break; + case JSTYPE_NUMBER: + if(isBinary) + { + if(JSVAL_IS_DOUBLE(value)) + { + if(JS_ValueToNumber(cx, value, &dval)) + { + if(locking) + result = fwrite(&dval, sizeof(jsdouble), 1, fptr); + else + result = _fwrite_nolock(&dval, sizeof(jsdouble), 1, fptr); + return result == 1; + } + else + return false; + } + else if(JSVAL_IS_INT(value)) + { + if(JS_ValueToInt32(cx, value, &ival)) + { + if(locking) + result = fwrite(&ival, sizeof(int32), 1, fptr); + else + result = _fwrite_nolock(&dval, sizeof(int32), 1, fptr); + return result == 1; + } + else + return false; + } + } + else + { + if(JSVAL_IS_DOUBLE(value)) + { + if(JS_ValueToNumber(cx, value, &dval) == JS_FALSE) + return false; + // jsdouble will never be a 64-char string, but I'd rather be safe than sorry + str = new char[64]; + sprintf_s(str, 64, "%.16f", dval); + len = strlen(str); + if(locking) + result = fwrite(str, sizeof(char), len, fptr); + else + result = _fwrite_nolock(str, sizeof(char), len, fptr); + delete[] str; + if(result == len) + return true; + } + else if(JSVAL_IS_INT(value)) + { + if(JS_ValueToInt32(cx, value, &ival) == JS_FALSE) + return false; + str = new char[16]; + _itoa_s(ival, str, 16, 10); + len = strlen(str); + if(locking) + result = fwrite(str, sizeof(char), len, fptr); + else + result = _fwrite_nolock(str, sizeof(char), len, fptr); + delete[] str; + if(result == len) + return true; + } + } + break; + case JSTYPE_BOOLEAN: + if(!isBinary) + { + bval = !!JSVAL_TO_BOOLEAN(value); + str = bval ? "true" : "false"; + if(locking) + result = fwrite(str, sizeof(char), strlen(str), fptr); + else + result = _fwrite_nolock(str, sizeof(char), strlen(str), fptr); + return (int)strlen(str) == result; + } + else + { + bval = !!JSVAL_TO_BOOLEAN(value); + if(locking) + result = fwrite(&bval, sizeof(bool), 1, fptr); + else + result = _fwrite_nolock(&bval, sizeof(bool), 1, fptr); + return result == 1; + } + break; +/* case JSTYPE_OBJECT: + JSObject *arr = JSVAL_TO_OBJECT(value); + if(JS_IsArrayObject(cx, arr)) { + JS_GetArrayLength(cx, arr, &uival); + for(jsuint i = 0; i < uival; i++) + { + jsval val; + JS_GetElement(cx, arr, i, &val); + if(!writeValue(fptr, cx, val, isBinary)) + return false; + } + return true; + } + else + { + JSString* jsstr = JS_ValueToString(cx, value); + str = JS_GetStringBytes(jsstr); + if(locking) + result = fwrite(str, sizeof(char), strlen(str), fptr); + else + result = _fwrite_nolock(str, sizeof(char), strlen(str), fptr); + return strlen(str) == result; + } + break; +*/ + } + return false; +} + +bool isValidPath(const char* name) +{ + return (!strstr(name, "..\\") && !strstr(name, "../") && (strcspn(name, "\":?*<>|") == strlen(name))); +} diff --git a/File.h b/File.h new file mode 100644 index 00000000..ac1db307 --- /dev/null +++ b/File.h @@ -0,0 +1,10 @@ +#ifndef __FILE_H__ +#define __FILE_H__ + +#include "js32.h" + +const char* readLine(FILE* fptr, bool locking); +bool writeValue(FILE* fptr, JSContext* cx, jsval value, bool isBinary, bool locking); +bool isValidPath(const char* name); + +#endif diff --git a/Game.cpp b/Game.cpp new file mode 100644 index 00000000..c232a63a --- /dev/null +++ b/Game.cpp @@ -0,0 +1,43 @@ +#include "Game.h" +#include "D2Ptrs.h" +#include "Constants.h" +#include "D2Helpers.h" + +// TODO: Refactor a lot of the JSGame functions here + +void SendGold(int nGold, int nMode) +{ + *p_D2CLIENT_GoldDialogAmount = nGold; + *p_D2CLIENT_GoldDialogAction = nMode; + D2CLIENT_PerformGoldDialogAction(); +} + +void __fastcall UseStatPoint(WORD stat, int count) +{ + if(D2COMMON_GetUnitStat(D2CLIENT_GetPlayerUnit(), STAT_STATPOINTSLEFT, 0) < count) + return; + + BYTE packet[3] = {0x3A}; + *(WORD*)&packet[1] = stat; + + for(int i = 0; i < count; i++) + { + D2CLIENT_SendGamePacket(3, packet); + if(i != count-1) Sleep(500); + } +} + +void __fastcall UseSkillPoint(WORD skill, int count) +{ + if(D2COMMON_GetUnitStat(D2CLIENT_GetPlayerUnit(), STAT_SKILLPOINTSLEFT, 0) < count) + return; + + BYTE packet[3] = {0x3B}; + *(WORD*)&packet[1] = skill; + + for(int i = 0; i < count; i++) + { + D2CLIENT_SendGamePacket(3, packet); + if(i != count-1) Sleep(500); + } +} diff --git a/Game.h b/Game.h new file mode 100644 index 00000000..9fd5c4b4 --- /dev/null +++ b/Game.h @@ -0,0 +1,6 @@ +#include +#include "D2Ptrs.h" + +void SendGold(int nGold, int nMode); +void __fastcall UseStatPoint(WORD stat, int count = 1); +void __fastcall UseSkillPoint(WORD skill, int count = 1); diff --git a/Hash.cpp b/Hash.cpp new file mode 100644 index 00000000..f9d7c985 --- /dev/null +++ b/Hash.cpp @@ -0,0 +1,151 @@ +#include + +#include "D2Helpers.h" +#include "Hash.h" + +using namespace std; + +char* HashString(char* dataIn, ALG_ID algo) +{ + // set up the crypto environment + HCRYPTPROV provider; + HCRYPTHASH hash; + DWORD lenOut = 0; + + if(!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) + return NULL; + if(!CryptCreateHash(provider, algo, 0, 0, &hash)) + { + CryptReleaseContext(provider, 0); + return NULL; + } + + // now we have a working crypto environment, let's encrypt + if(!CryptHashData(hash, (BYTE*)dataIn, strlen(dataIn), 0)) + { + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + if(!CryptGetHashParam(hash, HP_HASHVAL, NULL, &lenOut, 0)) + { + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + + BYTE* result = new BYTE[lenOut]; + memset(result, 0, lenOut); + if(!CryptGetHashParam(hash, HP_HASHVAL, result, &lenOut, 0)) + { + delete[] result; + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + + // tear down the crypto environment + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + + // it's the caller's responsibility to clean up the result + char* szBuffer1 = new char[lenOut*2 + 1], szBuffer2[10] = ""; + memset(szBuffer1, 0, lenOut*2+1); + for(DWORD i = 0; i < lenOut; i++) + { + sprintf_s(szBuffer2, 10, "%.2x", result[i]); + strcat_s(szBuffer1, lenOut*2+1, szBuffer2); + } + delete[] result; + return szBuffer1; +} + +char* HashFile(char* file, ALG_ID algo) +{ + // set up the crypto environment + HCRYPTPROV provider; + HCRYPTHASH hash; + DWORD lenOut = 0; + if(!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, 0)) + return NULL; + if(!CryptCreateHash(provider, algo, 0, 0, &hash)) + { + CryptReleaseContext(provider, 0); + return NULL; + } + + // now we have a working crypto environment, let's encrypt + // open the file + FILE* fp = NULL; + fopen_s(&fp, file, "r"); + if(!fp) + return NULL; + + // read it to end, adding it to the hash stream + fseek(fp, 0, SEEK_END); + unsigned int size = ftell(fp); + fseek(fp, 0, SEEK_SET); + + char* contents = new char[size]; + if(fread(contents, sizeof(char), size, fp) != size && ferror(fp)) + { + fclose(fp); + delete[] contents; + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + fclose(fp); + if(!CryptHashData(hash, (BYTE*)contents, size, 0)) + { + delete[] contents; + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + delete[] contents; + + if(!CryptGetHashParam(hash, HP_HASHVAL, NULL, &lenOut, 0)) + { + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + + BYTE* result = new BYTE[lenOut]; + memset(result, 0, lenOut); + if(!CryptGetHashParam(hash, HP_HASHVAL, result, &lenOut, 0)) + { + delete[] result; + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + return NULL; + } + + // tear down the crypto environment + CryptDestroyHash(hash); + CryptReleaseContext(provider, 0); + + // it's the caller's responsibility to clean up the result + char* szBuffer1 = new char[lenOut*2 + 1], szBuffer2[10] = ""; + memset(szBuffer1, 0, lenOut*2+1); + for(DWORD i = 0; i < lenOut; i++) + { + sprintf_s(szBuffer2, 10, "%.2x", result[i]); + strcat_s(szBuffer1, lenOut*2+1, szBuffer2); + } + delete[] result; + return szBuffer1; +} + +char* md5(char* str) { return HashString(str, CALG_MD5); } +char* sha1(char* str) { return HashString(str, CALG_SHA1); } +char* sha256(char* str) { return HashString(str, CALG_SHA_256); } +char* sha384(char* str) { return HashString(str, CALG_SHA_384); } +char* sha512(char* str) { return HashString(str, CALG_SHA_512); } + +char* md5_file(char* file) { return HashFile(file, CALG_MD5); } +char* sha1_file(char* file) { return HashFile(file, CALG_SHA1); } +char* sha256_file(char* file) { return HashFile(file, CALG_SHA_256); } +char* sha384_file(char* file) { return HashFile(file, CALG_SHA_384); } +char* sha512_file(char* file) { return HashFile(file, CALG_SHA_512); } diff --git a/Hash.h b/Hash.h new file mode 100644 index 00000000..59e760c2 --- /dev/null +++ b/Hash.h @@ -0,0 +1,18 @@ +#pragma once +#pragma comment (lib, "Crypt32") + +#include +#include + +char* HashString(char* string, ALG_ID algo); +char* HashFile(char* file, ALG_ID algo); +char* md5(char* string); +char* sha1(char* string); +char* sha256(char* string); +char* sha384(char* string); +char* sha512(char* string); +char* md5_file(char* string); +char* sha1_file(char* string); +char* sha256_file(char* string); +char* sha384_file(char* string); +char* sha512_file(char* string); diff --git a/Helpers.cpp b/Helpers.cpp new file mode 100644 index 00000000..682403a8 --- /dev/null +++ b/Helpers.cpp @@ -0,0 +1,474 @@ +#include "D2BS.h" +#include "Core.h" +#include "Script.h" +#include "ScriptEngine.h" +#include "string.h" +#include "D2Handlers.h" +#include "Control.h" +#include "D2Ptrs.h" +#include "Helpers.h" +#include "DbgHelp.h" + +wchar_t* AnsiToUnicode(const char* str) +{ + wchar_t* buf = NULL; + int len = MultiByteToWideChar(CP_ACP, 0, str, -1, buf, 0); + buf = new wchar_t[len]; + MultiByteToWideChar(CP_ACP, 0, str, -1, buf, len); + return buf; +} + +char* UnicodeToAnsi(const wchar_t* str) +{ + char* buf = NULL; + int len = WideCharToMultiByte(CP_ACP, 0, str, -1, buf, 0, "?", NULL); + buf = new char[len]; + WideCharToMultiByte(CP_ACP, 0, str, -1, buf, len, "?", NULL); + return buf; +} + +bool StringToBool(const char* str) +{ + switch(tolower(str[0])) + { + case 't': case '1': + return true; + case 'f': case '0': default: + return false; + } +} + +void StringReplace(char* str, const char find, const char replace, size_t buflen) +{ + for(size_t i = 0; i < buflen; i++) + { + if(str[i] == find) + str[i] = replace; + } +} + +bool SwitchToProfile(const char* profile) +{ + if(Vars.bUseProfileScript != TRUE || !ProfileExists(profile)) + return false; + + char file[_MAX_FNAME+_MAX_PATH] = "", + defaultStarter[_MAX_FNAME] = "", + defaultGame[_MAX_FNAME] = "", + scriptPath[_MAX_PATH] = ""; + sprintf_s(file, sizeof(file), "%sd2bs.ini", Vars.szPath); + + GetPrivateProfileString(profile, "ScriptPath", "scripts", scriptPath, _MAX_PATH, file); + GetPrivateProfileString(profile, "DefaultGameScript", "", defaultGame, _MAX_FNAME, file); + GetPrivateProfileString(profile, "DefaultStarterScript", "", defaultStarter, _MAX_FNAME, file); + + strcpy_s(Vars.szProfile, 256, profile); + sprintf_s(Vars.szScriptPath, _MAX_PATH, "%s%s", Vars.szPath, scriptPath); + if(strlen(defaultGame) > 0) + strcpy_s(Vars.szDefault, _MAX_FNAME, defaultGame); + if(strlen(defaultStarter) > 0) + strcpy_s(Vars.szStarter, _MAX_FNAME, defaultStarter); + + Vars.bUseProfileScript = FALSE; + Reload(); + return true; +} + +bool ProfileExists(const char *profile) +{ + char file[_MAX_FNAME+_MAX_PATH], profiles[65535] = ""; + sprintf_s(file, sizeof(file), "%sd2bs.ini", Vars.szPath); + + int count = GetPrivateProfileString(NULL, NULL, NULL, profiles, 65535, file); + if(count > 0) + { + int i = 0; + while(i < count) + { + if(_strcmpi(profiles+i, profile) == 0) + return true; + + i += strlen(profiles+i)+1; + } + } + return false; +} + +void InitSettings(void) +{ + char fname[_MAX_FNAME+MAX_PATH], scriptPath[_MAX_PATH], defaultStarter[_MAX_FNAME], defaultGame[_MAX_FNAME], + debug[6], quitOnHostile[6], quitOnError[6], maxGameTime[6], gameTimeout[6], + startAtMenu[6], disableCache[6], memUsage[6], gamePrint[6], useProfilePath[6], logConsole[6]; + + sprintf_s(fname, sizeof(fname), "%sd2bs.ini", Vars.szPath); + + GetPrivateProfileString("settings", "ScriptPath", "scripts", scriptPath, _MAX_PATH, fname); + GetPrivateProfileString("settings", "DefaultGameScript", "default.dbj", defaultGame, _MAX_FNAME, fname); + GetPrivateProfileString("settings", "DefaultStarterScript", "starter.dbj", defaultStarter, _MAX_FNAME, fname); + GetPrivateProfileString("settings", "MaxGameTime", "0", maxGameTime, 6, fname); + GetPrivateProfileString("settings", "Debug", "false", debug, 6, fname); + GetPrivateProfileString("settings", "QuitOnHostile", "false", quitOnHostile, 6, fname); + GetPrivateProfileString("settings", "QuitOnError", "false", quitOnError, 6, fname); + GetPrivateProfileString("settings", "StartAtMenu", "true", startAtMenu, 6, fname); + GetPrivateProfileString("settings", "DisableCache", "true", disableCache, 6, fname); + GetPrivateProfileString("settings", "MemoryLimit", "50", memUsage, 6, fname); + GetPrivateProfileString("settings", "UseGamePrint", "false", gamePrint, 6, fname); + GetPrivateProfileString("settings", "GameReadyTimeout", "5", gameTimeout, 6, fname); + GetPrivateProfileString("settings", "UseProfileScript", "false", useProfilePath, 6, fname); + GetPrivateProfileString("settings", "LogConsoleOutput", "false", logConsole, 6, fname); + + sprintf_s(Vars.szScriptPath, _MAX_PATH, "%s%s", Vars.szPath, scriptPath); + strcpy_s(Vars.szStarter, _MAX_FNAME, defaultStarter); + strcpy_s(Vars.szDefault, _MAX_FNAME, defaultGame); + + Vars.dwGameTime = GetTickCount(); + Vars.dwMaxGameTime = abs(atoi(maxGameTime) * 1000); + Vars.dwGameTimeout = abs(atoi(gameTimeout) * 1000); + + Vars.bQuitOnHostile = StringToBool(quitOnHostile); + Vars.bQuitOnError = StringToBool(quitOnError); + Vars.bStartAtMenu = StringToBool(startAtMenu); + Vars.bDisableCache = StringToBool(disableCache); + Vars.bUseGamePrint = StringToBool(gamePrint); + Vars.bUseProfileScript = StringToBool(useProfilePath); + Vars.bLogConsole = StringToBool(logConsole); + + Vars.dwMemUsage = abs(atoi(memUsage)); + if(Vars.dwMemUsage < 1) + Vars.dwMemUsage = 50; + Vars.dwMemUsage *= 1024*1024; + Vars.oldWNDPROC = NULL; +} + +bool InitHooks(void) +{ + int i = 0; + while(!Vars.bActive) + { + if(i >= 300) + { + MessageBox(0, "Failed to set hooks, exiting!", "D2BS", 0); + return false; + } + + if(D2GFX_GetHwnd() && (ClientState() == ClientStateMenu || ClientState() == ClientStateInGame)) + { + Vars.oldWNDPROC = (WNDPROC)SetWindowLong(D2GFX_GetHwnd(), GWL_WNDPROC, (LONG)GameEventHandler); + if(!Vars.oldWNDPROC) + continue; + + Vars.uTimer = SetTimer(D2GFX_GetHwnd(), 1, 0, TimerProc); + + DWORD mainThread = GetWindowThreadProcessId(D2GFX_GetHwnd(),0); + if(mainThread) + { + if(!Vars.hKeybHook) + Vars.hKeybHook = SetWindowsHookEx(WH_KEYBOARD, KeyPress, NULL, mainThread); + if(!Vars.hMouseHook) + Vars.hMouseHook = SetWindowsHookEx(WH_MOUSE, MouseMove, NULL, mainThread); + } + } + else + continue; + + if(Vars.hKeybHook && Vars.hMouseHook) + { + if(!ScriptEngine::Startup()) + return false; + + Vars.bActive = TRUE; + + if(ClientState() == ClientStateMenu && Vars.bStartAtMenu) + clickControl(*p_D2WIN_FirstControl); + } + Sleep(50); + i++; + } + return true; +} + +const char* GetStarterScriptName(void) +{ + return (ClientState() == ClientStateInGame ? Vars.szDefault : ClientState() == ClientStateMenu ? Vars.szStarter : NULL); +} + +ScriptState GetStarterScriptState(void) +{ + // the default return is InGame because that's the least harmful of the options + return (ClientState() == ClientStateInGame ? InGame : ClientState() == ClientStateMenu ? OutOfGame : InGame); +} + +bool ExecCommand(const char* command) +{ + Script* script = ScriptEngine::CompileCommand(command); + return (script && CreateThread(0, 0, ScriptThread, script, 0, 0) != INVALID_HANDLE_VALUE); +} + +bool StartScript(const char* scriptname, ScriptState state) +{ + char file[_MAX_FNAME+_MAX_PATH]; + sprintf_s(file, _MAX_FNAME+_MAX_PATH, "%s\\%s", Vars.szScriptPath, scriptname); + Script* script = ScriptEngine::CompileFile(file, state); + return (script && CreateThread(0, 0, ScriptThread, script, 0, 0) != INVALID_HANDLE_VALUE); +} + +void Reload(void) +{ + if(ScriptEngine::GetCount() > 0) + Print("ÿc2D2BSÿc0 :: Stopping all scripts"); + ScriptEngine::StopAll(); + + if(Vars.bDisableCache != TRUE) + Print("ÿc2D2BSÿc0 :: Flushing the script cache"); + ScriptEngine::FlushCache(); + + // wait for things to catch up + Sleep(500); + + if(!Vars.bUseProfileScript) + { + const char* script = GetStarterScriptName(); + if(StartScript(script, GetStarterScriptState())) + Print("ÿc2D2BSÿc0 :: Started %s", script); + else + Print("ÿc2D2BSÿc0 :: Failed to start %s", script); + } +} + +bool ProcessCommand(const char* command, bool unprocessedIsCommand) +{ + bool result = false; + char* buf = _strdup(command); + char* next_token1; + char* argv = strtok_s(buf, " ", &next_token1); + + // no command? + if(argv == NULL) + return false; + + if(_strcmpi(argv, "start") == 0) + { + const char* script = GetStarterScriptName(); + if(StartScript(script, GetStarterScriptState())) + Print("ÿc2D2BSÿc0 :: Started %s", script); + else + Print("ÿc2D2BSÿc0 :: Failed to start %s", script); + result = true; + } + else if(_strcmpi(argv, "stop") == 0) + { + if(ScriptEngine::GetCount() > 0) + Print("ÿc2D2BSÿc0 :: Stopping all scripts"); + ScriptEngine::StopAll(); + result = true; + } + else if(_strcmpi(argv, "flush") == 0) + { + if(Vars.bDisableCache != TRUE) + Print("ÿc2D2BSÿc0 :: Flushing the script cache"); + ScriptEngine::FlushCache(); + result = true; + } + else if(_strcmpi(argv, "load") == 0) + { + const char* script = command+5; + if(StartScript(script, GetStarterScriptState())) + Print("ÿc2D2BSÿc0 :: Started %s", script); + else + Print("ÿc2D2BSÿc0 :: Failed to start %s", script); + result = true; + } + else if(_strcmpi(argv, "reload") == 0) + { + Reload(); + result = true; + } +#if DEBUG + else if(_strcmpi(argv, "crash") == 0) + { + DWORD zero = 0; + double value = 1/zero; + Print("%d", value); + } + else if(_strcmpi(argv, "profile") == 0) + { + const char* profile = command+8; + if(SwitchToProfile(profile)) + Print("ÿc2D2BSÿc0 :: Switched to profile %s", profile); + else + Print("ÿc2D2BSÿc0 :: Profile %s not found", profile); + result = true; + } +#endif + else if(_strcmpi(argv, "exec") == 0 && !unprocessedIsCommand) + { + ExecCommand(command+5); + result = true; + } + else if(unprocessedIsCommand) + { + ExecCommand(command); + result = true; + } + return result; +} + +void GameJoined(void) +{ + if(!Vars.bUseProfileScript) + { + const char* starter = GetStarterScriptName(); + if(starter != NULL) + { + Print("ÿc2D2BSÿc0 :: Starting %s", starter); + if(StartScript(starter, GetStarterScriptState())) + Print("ÿc2D2BSÿc0 :: %s running.", starter); + else + Print("ÿc2D2BSÿc0 :: Failed to start %s!", starter); + } + } +} + +void MenuEntered(bool beginStarter) +{ + if(beginStarter && !Vars.bUseProfileScript) + { + const char* starter = GetStarterScriptName(); + if(starter != NULL) + { + Print("ÿc2D2BSÿc0 :: Starting %s", starter); + if(StartScript(starter, GetStarterScriptState())) + Print("ÿc2D2BSÿc0 :: %s running.", starter); + else + Print("ÿc2D2BSÿc0 :: Failed to start %s!", starter); + } + } +} + +SYMBOL_INFO* GetSymFromAddr(HANDLE hProcess, DWORD64 addr) +{ + char* symbols = new char[sizeof(SYMBOL_INFO) + 512]; + memset(symbols, 0, sizeof(SYMBOL_INFO) + 512); + + SYMBOL_INFO* sym = (SYMBOL_INFO*)(symbols); + sym->SizeOfStruct = sizeof(SYMBOL_INFO); + sym->MaxNameLen = 512; + + DWORD64 dummy; + bool success = SymFromAddr(hProcess, addr, &dummy, sym) == TRUE ? true : false; + if(!success) + { + delete[] symbols; + sym = NULL; + } + + return sym; +} + +IMAGEHLP_LINE64* GetLineFromAddr(HANDLE hProcess, DWORD64 addr) +{ + IMAGEHLP_LINE64* line = new IMAGEHLP_LINE64; + line->SizeOfStruct = sizeof(IMAGEHLP_LINE64); + + DWORD dummy; + bool success = SymGetLineFromAddr64(hProcess, addr, &dummy, line) == TRUE ? true : false; + if(!success) + { + delete line; + line = NULL; + } + return line; +} + +LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS* ptrs) +{ + EXCEPTION_RECORD* rec = ptrs->ExceptionRecord; + CONTEXT* ctx = ptrs->ContextRecord; + DWORD base = Vars.pModule ? Vars.pModule->dwBaseAddress : (DWORD)Vars.hModule; + + char path[MAX_PATH+_MAX_FNAME] = ""; + sprintf_s(path, sizeof(path), "%s\\D2BS.bin", Vars.szPath); + + HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessId()); + HANDLE hThread = GetCurrentThread(); + CONTEXT context = *ctx; + + SymSetOptions(SYMOPT_LOAD_LINES|SYMOPT_FAIL_CRITICAL_ERRORS|SYMOPT_NO_PROMPTS|SYMOPT_DEFERRED_LOADS); + SymInitialize(hProcess, Vars.szPath, TRUE); + SymLoadModule64(hProcess, NULL, path, NULL, base, 0); + + STACKFRAME64 stack; + stack.AddrPC.Offset = context.Eip; + stack.AddrPC.Mode = AddrModeFlat; + stack.AddrStack.Offset = context.Esp; + stack.AddrStack.Mode = AddrModeFlat; + stack.AddrFrame.Offset = context.Ebp; + stack.AddrFrame.Mode = AddrModeFlat; + + std::string trace; + + for(int i = 0; i < 64; i++) + { + if(!StackWalk64(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &stack, &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) + break; + + // infinite loop + if(stack.AddrReturn.Offset == stack.AddrPC.Offset) + break; + // jump to 0 + if(stack.AddrPC.Offset == 0) + break; + + SYMBOL_INFO* sym = GetSymFromAddr(hProcess, stack.AddrPC.Offset); + + if(sym) + { + char msg[1024]; + ULONG64 base = (sym->Address - sym->ModBase); + + IMAGEHLP_LINE64* line = GetLineFromAddr(hProcess, stack.AddrPC.Offset); + if(line) + sprintf_s(msg, 1024, "\t%s+0x%08x, File: %s line %d\n", + sym->Name, base, strrchr(line->FileName, '\\')+1, line->LineNumber); + else + sprintf_s(msg, 1024, "\t%s+0x%08x\n", sym->Name, base); + + trace.append(msg); + delete line; + } + else + { + char addr[100]; + sprintf_s(addr, sizeof(addr), "\t0x%08x\n", stack.AddrFrame.Offset); + trace.append(addr); + } + + delete[] (char*)sym; + } + + SYMBOL_INFO* sym = GetSymFromAddr(hProcess, (DWORD64)rec->ExceptionAddress); + + IMAGEHLP_LINE64* line = GetLineFromAddr(hProcess, (DWORD64)rec->ExceptionAddress); + + Log("EXCEPTION!\n*** 0x%08x at 0x%08x (%s in %s line %d)\n" + "D2BS loaded at: 0x%08x\n" + "Registers:\n" + "\tEIP: 0x%08x, ESP: 0x%08x\n" + "\tCS: 0x%04x, DS: 0x%04x, ES: 0x%04x, SS: 0x%04x, FS: 0x%04x, GS: 0x%04x\n" + "\tEAX: 0x%08x, EBX: 0x%08x, ECX: 0x%08x, EDX: 0x%08x, ESI: 0x%08x, EDI: 0x%08x, EBP: 0x%08x, FLG: 0x%08x\n" + "Stack Trace:\n%s\nEnd of stack trace.", + rec->ExceptionCode, rec->ExceptionAddress, + sym != NULL ? sym->Name : "Unknown", line != NULL ? strrchr(line->FileName, '\\')+1 : "Unknown", line != NULL ? line->LineNumber : 0, + base, + ctx->Eip, ctx->Esp, + ctx->SegCs, ctx->SegDs, ctx->SegEs, ctx->SegSs, ctx->SegFs, ctx->SegGs, + ctx->Eax, ctx->Ebx, ctx->Ecx, ctx->Edx, ctx->Esi, ctx->Edi, ctx->Ebp, ctx->EFlags, + trace.c_str()); + + delete[] (char*)sym; + delete line; + + SymCleanup(hProcess); + + return EXCEPTION_EXECUTE_HANDLER; +} diff --git a/Helpers.h b/Helpers.h new file mode 100644 index 00000000..56b6276f --- /dev/null +++ b/Helpers.h @@ -0,0 +1,26 @@ +#pragma once + +#ifndef __HELPERS_H__ +#define __HELPERS_H__ + +#include "Script.h" + +wchar_t* AnsiToUnicode(const char* str); +char* UnicodeToAnsi(const wchar_t* str); +bool StringToBool(const char* str); +void StringReplace(char* str, const char find, const char replace, size_t buflen); +bool SwitchToProfile(const char* profile); +bool ProfileExists(const char* profile); +void InitSettings(void); +bool InitHooks(void); +bool ExecCommand(const char* command); +bool StartScript(const char* script, ScriptState state); +void Reload(void); +bool ProcessCommand(const char* command, bool unprocessedIsCommand); + +void GameJoined(void); +void MenuEntered(bool beginStarter); + +LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS* ptrs); + +#endif diff --git a/JSArea.cpp b/JSArea.cpp new file mode 100644 index 00000000..8efd510a --- /dev/null +++ b/JSArea.cpp @@ -0,0 +1,154 @@ +#include "JSArea.h" +#include "D2Ptrs.h" +#include "JSExits.h" +#include "CriticalSections.h" +#include "CollisionMap.h" + +EMPTY_CTOR(area) + +void area_finalize(JSContext *cx, JSObject *obj) +{ + myArea* pArea = (myArea*)JS_GetPrivate(cx, obj); + + if(pArea) + { + if(pArea->ExitArray) + JS_RemoveRoot(&pArea->ExitArray); + JS_SetPrivate(cx, obj, NULL); + delete pArea; + } +} + +JSAPI_PROP(area_getProperty) +{ + myArea* pArea = (myArea*)JS_GetPrivate(cx, obj);; + if(!pArea) + return JS_FALSE; + + Level* pLevel = GetLevel(pArea->AreaId); + if(!pLevel) + return JS_FALSE; + + switch(JSVAL_TO_INT(id)) + { + case AUNIT_EXITS: + { + if(pArea->ExitArray == NULL) + { + pArea->ExitArray = JS_NewArrayObject(cx, 0, NULL); + JS_AddRoot(&pArea->ExitArray); + + CriticalRoom cRoom; + cRoom.EnterSection(); + + CCollisionMap cMap; + + if(!cMap.CreateMap(pArea->AreaId)) + { + *vp = JSVAL_FALSE; + return JS_TRUE; + } + + LevelExit* ExitArray[255]; + int count = cMap.GetLevelExits(ExitArray); + + for(int i = 0; i < count; i++) + { + myExit* pExit = new myExit; + pExit->id = ExitArray[i]->dwTargetLevel; + pExit->x = ExitArray[i]->ptPos.x; + pExit->y = ExitArray[i]->ptPos.y; + pExit->type = ExitArray[i]->dwType; + pExit->tileid = ExitArray[i]->dwId; + pExit->level = pArea->AreaId; + + JSObject* jsUnit = BuildObject(cx, &exit_class, NULL, exit_props, pExit); + if(!jsUnit) + { + delete pExit; + pExit = NULL; + THROW_ERROR(cx, "Failed to create exit object!"); + } + + jsval a = OBJECT_TO_JSVAL(jsUnit); + JS_SetElement(cx, pArea->ExitArray, i, &a); + } + } + *vp = OBJECT_TO_JSVAL(pArea->ExitArray); + } + break; + case AUNIT_NAME: + { + LevelTxt* pTxt = D2COMMON_GetLevelText(pArea->AreaId); + if(pTxt) + *vp = STRING_TO_JSVAL(JS_InternString(cx, pTxt->szName)); + } + break; + case AUNIT_X: + *vp = INT_TO_JSVAL(pLevel->dwPosX); + break; + case AUNIT_Y: + *vp = INT_TO_JSVAL(pLevel->dwPosY); + break; + case AUNIT_XSIZE: + *vp = INT_TO_JSVAL(pLevel->dwSizeX); + break; + case AUNIT_YSIZE: + *vp = INT_TO_JSVAL(pLevel->dwSizeY); + break; + case AUNIT_ID: + *vp = INT_TO_JSVAL(pLevel->dwLevelNo); + break; + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getArea) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + int32 nArea = GetPlayerArea(); + + if(argc == 1) + { + if(JSVAL_IS_INT(argv[0])) + JS_ValueToECMAInt32(cx, argv[0], &nArea); + else + THROW_ERROR(cx, "Invalid parameter passed to getArea!"); + } + + if(nArea < 0) + THROW_ERROR(cx, "Invalid parameter passed to getArea!"); + + Level* pLevel = GetLevel(nArea); + + if(!pLevel) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + myArea* pArea = new myArea; + if(!pArea) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + pArea->AreaId = nArea; + pArea->ExitArray = NULL; + + JSObject* unit = BuildObject(cx, &area_class, NULL, area_props, pArea); + if(!unit) + { + delete pArea; + pArea = NULL; + THROW_ERROR(cx, "Failed to build area unit!"); + } + + *rval = OBJECT_TO_JSVAL(unit); + + return JS_TRUE; +} diff --git a/JSArea.h b/JSArea.h new file mode 100644 index 00000000..d7bbdc6e --- /dev/null +++ b/JSArea.h @@ -0,0 +1,43 @@ +#ifndef AREA_H +#define AREA_H + +#include +#include "js32.h" + +CLASS_CTOR(area); + +void area_finalize(JSContext *cx, JSObject *obj); + +JSAPI_PROP(area_getProperty); + +JSAPI_FUNC(my_getArea); + +enum area_tinyid { + AUNIT_EXITS, + AUNIT_NAME, + AUNIT_X, + AUNIT_XSIZE, + AUNIT_Y, + AUNIT_YSIZE, + AUNIT_ID +}; + + +static JSPropertySpec area_props[] = { + {"exits", AUNIT_EXITS, JSPROP_PERMANENT_VAR, area_getProperty}, + {"name", AUNIT_NAME, JSPROP_PERMANENT_VAR, area_getProperty}, + {"x", AUNIT_X, JSPROP_PERMANENT_VAR, area_getProperty}, + {"xsize", AUNIT_XSIZE, JSPROP_PERMANENT_VAR, area_getProperty}, + {"y", AUNIT_Y, JSPROP_PERMANENT_VAR, area_getProperty}, + {"ysize", AUNIT_YSIZE, JSPROP_PERMANENT_VAR, area_getProperty}, + {"id", AUNIT_ID, JSPROP_PERMANENT_VAR, area_getProperty}, + {0}, +}; + +struct myArea { + DWORD AreaId; + DWORD Exits; + JSObject* ExitArray; +}; + +#endif \ No newline at end of file diff --git a/JSControl.cpp b/JSControl.cpp new file mode 100644 index 00000000..9ad3455e --- /dev/null +++ b/JSControl.cpp @@ -0,0 +1,307 @@ +//#include "Control.h" +#include "JSControl.h" +#include "Helpers.h" +#include "D2Helpers.h" + +EMPTY_CTOR(control) + +void control_finalize(JSContext *cx, JSObject *obj) +{ + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + + if(pData) + { + JS_SetPrivate(cx, obj, NULL); + delete pData; + } +} + +JSAPI_PROP(control_getProperty) +{ + if(ClientState() != ClientStateMenu) + return JS_FALSE; + + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + if(!pData) + return JS_FALSE; + + Control* ctrl = findControl(pData->dwType, (char *)NULL, -1, pData->dwX, pData->dwY, pData->dwSizeX, pData->dwSizeY); + if(!ctrl) + return JS_FALSE; + + switch(JSVAL_TO_INT(id)) + { + case CONTROL_TEXT: + if(ctrl->dwIsCloaked != 33) + { + char* tmp = UnicodeToAnsi((ctrl->dwType == 6 ? ctrl->wText2 : ctrl->wText)); + *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); + delete[] tmp; + } + break; + case CONTROL_X: + JS_NewNumberValue(cx, ctrl->dwPosX, vp); + break; + case CONTROL_Y: + JS_NewNumberValue(cx, ctrl->dwPosY, vp); + break; + case CONTROL_XSIZE: + JS_NewNumberValue(cx, ctrl->dwSizeX, vp); + break; + case CONTROL_YSIZE: + JS_NewNumberValue(cx, ctrl->dwSizeY, vp); + break; + case CONTROL_STATE: + JS_NewNumberValue(cx, (ctrl->dwDisabled - 2), vp); + break; + case CONTROL_MAXLENGTH: + //JS_NewNumberValue(cx, ctrl->dwMaxLength, vp); + break; + case CONTROL_TYPE: + JS_NewNumberValue(cx, ctrl->dwType, vp); + break; + case CONTROL_VISIBLE: + // nothing to do yet because we don't know what to do + break; + case CONTROL_CURSORPOS: + JS_NewNumberValue(cx, ctrl->dwCursorPos, vp); + break; + case CONTROL_SELECTSTART: + JS_NewNumberValue(cx, ctrl->dwSelectStart, vp); + break; + case CONTROL_SELECTEND: + JS_NewNumberValue(cx, ctrl->dwSelectEnd, vp); + break; + case CONTROL_PASSWORD: + *vp = BOOLEAN_TO_JSVAL(!!(ctrl->dwIsCloaked == 33)); + break; + case CONTROL_DISABLED: + JS_NewNumberValue(cx, ctrl->dwDisabled, vp); + break; + } + + return JS_TRUE; +} + +JSAPI_PROP(control_setProperty) +{ + if(ClientState() != ClientStateMenu) + return JS_FALSE; + + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + if(!pData) + return JS_FALSE; + + Control* ctrl = findControl(pData->dwType, (char *)NULL, -1, pData->dwX, pData->dwY, pData->dwSizeX, pData->dwSizeY); + if(!ctrl) + return JS_FALSE; + + switch(JSVAL_TO_INT(id)) + { + case CONTROL_TEXT: + if(ctrl->dwType == 1 && JSVAL_IS_STRING(*vp)) + { + char* pText = JS_GetStringBytes(JS_ValueToString(cx, *vp)); + if(!pText) + return JS_TRUE; + wchar_t* szwText = AnsiToUnicode(pText); + D2WIN_SetControlText(ctrl, szwText); + delete[] szwText; + } + break; + case CONTROL_STATE: + if(JSVAL_IS_INT(*vp)) + { + int32 nState; + if(!JS_ValueToECMAInt32(cx, *vp, &nState) || nState < 0 || nState > 3) + THROW_ERROR(cx, "Invalid state value"); + memset((void*)&ctrl->dwDisabled, (nState + 2), sizeof(DWORD)); + } + break; + case CONTROL_CURSORPOS: + if(JSVAL_IS_INT(*vp)) + { + DWORD dwPos; + if(!JS_ValueToECMAUint32(cx, *vp, &dwPos)) + THROW_ERROR(cx, "Invalid cursor position value"); + memset((void*)&ctrl->dwCursorPos, dwPos, sizeof(DWORD)); + } + break; + case CONTROL_DISABLED: + if(JSVAL_IS_INT(*vp)) + { + memset((void*)&ctrl->dwDisabled, JSVAL_TO_INT(*vp), sizeof(DWORD)); + } + break; + } + + return JS_TRUE; +} + +JSAPI_FUNC(control_getNext) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + if(!pData) + return JS_TRUE; + + Control* pControl = findControl(pData->dwType, (char *)NULL, -1, pData->dwX, pData->dwY, pData->dwSizeX, pData->dwSizeY); + if(pControl && pControl->pNext) + pControl = pControl->pNext; + else + pControl = NULL; + + if(pControl) + { + pData->pControl = pControl; + pData->dwType = pData->pControl->dwType; + pData->dwX = pData->pControl->dwPosX; + pData->dwY = pData->pControl->dwPosY; + pData->dwSizeX = pData->pControl->dwSizeX; + pData->dwSizeY = pData->pControl->dwSizeY; + JS_SetPrivate(cx, obj, pData); + *rval = OBJECT_TO_JSVAL(obj); + } + else + { + JS_ClearScope(cx, obj); + if(JS_ValueToObject(cx, JSVAL_NULL, &obj) == JS_FALSE) + return JS_TRUE; + *rval = JSVAL_FALSE; + } + + return JS_TRUE; +} + +JSAPI_FUNC(control_click) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + if(!pData) + return JS_TRUE; + + Control* pControl = findControl(pData->dwType, (char *)NULL, -1, pData->dwX, pData->dwY, pData->dwSizeX, pData->dwSizeY); + if(!pControl) + { + *rval = INT_TO_JSVAL(0); + return JS_TRUE; + } + + uint32 x = (uint32)-1, y = (uint32)-1; + + if(argc > 1 && JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1])) + { + JS_ValueToECMAUint32(cx, argv[0], &x); + JS_ValueToECMAUint32(cx, argv[1], &y); + } + + clickControl(pControl, x, y); + + return JS_TRUE; +} + +JSAPI_FUNC(control_setText) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + if(!pData) + return JS_TRUE; + + Control* pControl = findControl(pData->dwType, (char *)NULL, -1, pData->dwX, pData->dwY, pData->dwSizeX, pData->dwSizeY); + if(!pControl) + { + *rval = INT_TO_JSVAL(0); + return JS_TRUE; + } + + if(argc < 0 || !JSVAL_IS_STRING(argv[0])) + return JS_TRUE; + + char* pText = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!pText) + return JS_TRUE; + wchar_t* szwText = AnsiToUnicode(pText); + + D2WIN_SetControlText(pControl, szwText); + + delete[] szwText; + return JS_TRUE; +} + +JSAPI_FUNC(control_getText) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + ControlData *pData = ((ControlData*)JS_GetPrivate(cx, obj)); + if(!pData) + return JS_TRUE; + + Control* pControl = findControl(pData->dwType, (char *)NULL, -1, pData->dwX, pData->dwY, pData->dwSizeX, pData->dwSizeY); + if(!pControl) + { + *rval = INT_TO_JSVAL(0); + return JS_TRUE; + } + + if(pControl->dwType != 4 || !pControl->pFirstText) + return JS_TRUE; + + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(pReturnArray); + int nArrayCount = 0; + + for(ControlText* pText = pControl->pFirstText; pText; pText = pText->pNext) + { + if(!pText->wText) + continue; + + char* tmp = UnicodeToAnsi(pText->wText); + jsval aString = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, tmp)); + delete[] tmp; + JS_SetElement(cx, pReturnArray, nArrayCount, &aString); + + nArrayCount++; + } + + return JS_TRUE; +} + + +JSAPI_FUNC(my_getControl) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + int32 nType = -1, nX = -1, nY = -1, nXSize = -1, nYSize = -1; + int32 *args[] = {&nType, &nX, &nY, &nXSize, &nYSize}; + + for(uintN i = 0; i < argc; i++) + if(JSVAL_IS_INT(argv[i])) + JS_ValueToECMAInt32(cx, argv[i], args[i]); + + Control* pControl = findControl(nType, (char*)NULL, -1, nX, nY, nXSize, nYSize); + if(!pControl) + return JS_TRUE; + + ControlData* data = new ControlData; + data->dwType = nType; + data->dwX = nX; + data->dwY = nY; + data->dwSizeX = nXSize; + data->dwSizeY = nYSize; + + JSObject* control = BuildObject(cx, &control_class, control_funcs, control_props, data); + if(!control) + THROW_ERROR(cx, "Failed to build control!"); + + *rval = OBJECT_TO_JSVAL(control); + + return JS_TRUE; +} diff --git a/JSControl.h b/JSControl.h new file mode 100644 index 00000000..aac9bfb0 --- /dev/null +++ b/JSControl.h @@ -0,0 +1,74 @@ +#pragma once + +#include "Control.h" + +#include "js32.h" +#include +#include "D2Ptrs.h" + +CLASS_CTOR(control); + +void control_finalize(JSContext *cx, JSObject *obj); + +JSAPI_FUNC(control_getNext); +JSAPI_FUNC(control_click); +JSAPI_FUNC(control_setText); +JSAPI_FUNC(control_getText); + +JSAPI_PROP(control_getProperty); +JSAPI_PROP(control_setProperty); + +struct ControlData { + DWORD _dwPrivate; + Control* pControl; + + DWORD dwType; + DWORD dwX; + DWORD dwY; + DWORD dwSizeX; + DWORD dwSizeY; +}; + +enum control_tinyid { + CONTROL_TEXT = -1, + CONTROL_X = -2, + CONTROL_Y = -3, + CONTROL_XSIZE = -4, + CONTROL_YSIZE = -5, + CONTROL_STATE = -6, + CONTROL_MAXLENGTH = -7, + CONTROL_TYPE = -8, + CONTROL_VISIBLE = -9, + CONTROL_CURSORPOS = -10, + CONTROL_SELECTSTART = -11, + CONTROL_SELECTEND = -12, + CONTROL_PASSWORD = -13, + CONTROL_DISABLED = -14 +}; + + +static JSPropertySpec control_props[] = { + {"text", CONTROL_TEXT, JSPROP_STATIC_VAR, control_getProperty, control_setProperty}, + {"x", CONTROL_X, JSPROP_PERMANENT_VAR, control_getProperty}, + {"y", CONTROL_Y, JSPROP_PERMANENT_VAR, control_getProperty}, + {"xsize", CONTROL_XSIZE, JSPROP_PERMANENT_VAR, control_getProperty}, + {"ysize", CONTROL_YSIZE, JSPROP_PERMANENT_VAR, control_getProperty}, + {"state", CONTROL_STATE, JSPROP_STATIC_VAR, control_getProperty, control_setProperty}, + {"password", CONTROL_PASSWORD, JSPROP_PERMANENT_VAR, control_getProperty}, +// {"maxlength", CONTROL_MAXLENGTH, JSPROP_PERMANENT_VAR, control_getProperty}, + {"type", CONTROL_TYPE, JSPROP_PERMANENT_VAR, control_getProperty}, +// {"visible", CONTROL_VISIBLE, JSPROP_PERMANENT_VAR, control_getProperty}, + {"cursorpos", CONTROL_CURSORPOS, JSPROP_STATIC_VAR, control_getProperty, control_setProperty}, + {"selectstart", CONTROL_SELECTSTART, JSPROP_PERMANENT_VAR, control_getProperty}, + {"selectend", CONTROL_SELECTEND, JSPROP_PERMANENT_VAR, control_getProperty}, + {"disabled", CONTROL_DISABLED, JSPROP_PERMANENT_VAR, control_getProperty, control_setProperty}, + {0}, +}; + +static JSFunctionSpec control_funcs[] = { + {"getNext", control_getNext, 0}, + {"click", control_click, 0}, + {"setText", control_setText, 1}, + {"getText", control_getText, 0}, + {0}, +}; \ No newline at end of file diff --git a/JSCore.cpp b/JSCore.cpp new file mode 100644 index 00000000..779815a6 --- /dev/null +++ b/JSCore.cpp @@ -0,0 +1,419 @@ +#include +#include +#include + +//#include "js32.h" +//#include "Script.h" +#include "JSCore.h" +#include "Core.h" +#include "Helpers.h" +#include "dde.h" +//#include "ScriptEngine.h" +//#include "D2BS.h" +#include "Events.h" +#include "Console.h" +#include "D2Ptrs.h" +#include "File.h" + +JSAPI_FUNC(my_print) +{ + for(uintN i = 0; i < argc; i++) + { + if(!JSVAL_IS_NULL(argv[i])) + { + if(!JS_ConvertValue(cx, argv[i], JSTYPE_STRING, &(argv[i]))) + { + JS_ReportError(cx, "Converting to string failed"); + return JS_FALSE; + } + + char* Text = JS_GetStringBytes(JS_ValueToString(cx, argv[i])); + if(Text == NULL) + { + JS_ReportError(cx, "Could not get string for value"); + return JS_FALSE; + } + + jsrefcount depth = JS_SuspendRequest(cx); + if(!Text) + Print("undefined"); + else { + std::replace(Text, Text + strlen(Text), '%', (char)(unsigned char)0xFE); + Print(Text); + } + JS_ResumeRequest(cx, depth); + } + } + return JS_TRUE; +} + +JSAPI_FUNC(my_delay) +{ + uint32 nDelay = 0; + if(!JS_ConvertArguments(cx, argc, argv, "u", &nDelay)) + return JS_FALSE; + + if(nDelay) + { + jsrefcount depth = JS_SuspendRequest(cx); + Sleep(nDelay); + JS_ResumeRequest(cx, depth); + } + else + JS_ReportWarning(cx, "delay(0) called, argument must be >= 1"); + + return JS_TRUE; +} + +JSAPI_FUNC(my_load) +{ + *rval = JSVAL_FALSE; + + Script* script = (Script*)JS_GetContextPrivate(cx); + if(!script) + { + JS_ReportError(cx, "Failed to get script object"); + return JS_FALSE; + } + + char* file = NULL; + if(!JS_ConvertArguments(cx, argc, argv, "s", &file)) + return JS_FALSE; + + if(strlen(file) > (_MAX_FNAME + _MAX_PATH - strlen(Vars.szScriptPath))) + { + JS_ReportError(cx, "File name too long!"); + return JS_FALSE; + } + + char buf[_MAX_PATH+_MAX_FNAME]; + ScriptState scriptState = script->GetState(); + if(scriptState == Command) + scriptState = (ClientState() == ClientStateInGame ? InGame : OutOfGame); + + sprintf_s(buf, sizeof(buf), "%s\\%s", Vars.szScriptPath, file); + StringReplace(buf, '/', '\\', _MAX_PATH+_MAX_FNAME); + Script* newScript = ScriptEngine::CompileFile(buf, scriptState); + if(newScript) + { + CreateThread(0, 0, ScriptThread, newScript, 0, 0); + *rval = JSVAL_TRUE; + } + else + { + // TODO: Should this actually be there? No notification is bad, but do we want this? maybe throw an exception? + Print("File \"%s\" not found.", file); + *rval = JSVAL_FALSE; + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_include) +{ + *rval = JSVAL_FALSE; + + Script* script = (Script*)JS_GetContextPrivate(cx); + if(!script) + { + JS_ReportError(cx, "Failed to get script object"); + return JS_FALSE; + } + + char* file = NULL; + if(!JS_ConvertArguments(cx, argc, argv, "s", &file)) + return JS_FALSE; + + if(strlen(file) > (_MAX_FNAME + _MAX_PATH - strlen(Vars.szScriptPath) - 6)) + { + JS_ReportError(cx, "File name too long!"); + return JS_FALSE; + } + + char buf[_MAX_PATH+_MAX_FNAME]; + sprintf_s(buf, sizeof(buf), "%s\\libs\\%s", Vars.szScriptPath, file); + if(_access(buf, 0) == 0) + *rval = BOOLEAN_TO_JSVAL(script->Include(buf)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_stop) +{ + if(argc > 0 && (JSVAL_IS_INT(argv[0]) && JSVAL_TO_INT(argv[0]) == 1) || + (JSVAL_IS_BOOLEAN(argv[0]) && JSVAL_TO_BOOLEAN(argv[0]) == TRUE)) + { + Script* script = (Script*)JS_GetContextPrivate(cx); + if(script) + script->Stop(); + } + else + ScriptEngine::StopAll(); + + return JS_FALSE; +} + +JSAPI_FUNC(my_beep) +{ + jsint nBeepId = NULL; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + nBeepId = JSVAL_TO_INT(argv[0]); + + MessageBeep(nBeepId); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getTickCount) +{ + *rval = INT_TO_JSVAL(GetTickCount()); + return JS_TRUE; +} + +JSAPI_FUNC(my_getThreadPriority) +{ + *rval = GetThreadPriority(GetCurrentThread()); + return JS_TRUE; +} + +JSAPI_FUNC(my_isIncluded) +{ + char* file = NULL; + if(!JS_ConvertArguments(cx, argc, argv, "s", &file)) + return JS_FALSE; + + if(strlen(file) > (_MAX_FNAME+_MAX_PATH-strlen(Vars.szScriptPath)-6)) + { + JS_ReportError(cx, "File name too long"); + return JS_FALSE; + } + + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, _MAX_FNAME+_MAX_PATH, "%s\\libs\\%s", Vars.szScriptPath, file); + Script* script = (Script*)JS_GetContextPrivate(cx); + *rval = BOOLEAN_TO_JSVAL(script->IsIncluded(path)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_version) +{ + if(argc < 1) + { + *rval = STRING_TO_JSVAL(JS_InternString(cx, D2BS_VERSION)); + return JS_TRUE; + } + + Print("ÿc4D2BSÿc1 ÿc3%s for Diablo II 1.13c.", D2BS_VERSION); + + return JS_TRUE; +} + +JSAPI_FUNC(my_debugLog) +{ + for(uintN i = 0; i < argc; i++) + { + if(!JSVAL_IS_NULL(argv[i])) + { + if(!JS_ConvertValue(cx, argv[i], JSTYPE_STRING, &(argv[i]))) + { + JS_ReportError(cx, "Converting to string failed"); + return JS_FALSE; + } + + char* Text = JS_GetStringBytes(JS_ValueToString(cx, argv[i])); + if(Text == NULL) + { + JS_ReportError(cx, "Could not get string for value"); + return JS_FALSE; + } + + jsrefcount depth = JS_SuspendRequest(cx); + if(!Text) + Log("undefined"); + else { + StringReplace(Text, '%', (unsigned char)0xFE, strlen(Text)); + Log(Text); + } + JS_ResumeRequest(cx, depth); + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_sendCopyData) +{ + if(argc < 4) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + char *windowClassName = NULL, *windowName = NULL, *data = NULL; + jsint nModeId = NULL; + + if(!JS_ConvertArguments(cx, argc, argv, "ssis", &windowClassName, &windowName, &nModeId, &data)) + return JS_FALSE; + + if(_strcmpi(windowClassName, "null") == 0) + windowClassName = NULL; + if(_strcmpi(windowName, "null") == 0) + windowName = NULL; + + HWND hWnd = FindWindow(windowClassName, windowName); + if(!hWnd) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + // if data is NULL, strlen crashes + if(data == NULL) + data = ""; + + COPYDATASTRUCT aCopy = { nModeId, strlen(data)+1, data }; + // HACK: Using PostMessage instead of SendMessage--need to fix this ASAP! + *rval = INT_TO_JSVAL(SendMessage(hWnd, WM_COPYDATA, (WPARAM)D2GFX_GetHwnd(), (LPARAM)&aCopy)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_sendDDE) +{ + jsint mode; + char *pszDDEServer = "\"\"", *pszTopic = "\"\"", *pszItem = "\"\"", *pszData = "\"\""; + + if(!JS_ConvertArguments(cx, argc, argv, "issss", &mode, &pszDDEServer, &pszTopic, &pszItem, &pszData)) + return JS_FALSE; + + char buffer[255] = ""; + if(SendDDE(mode, pszDDEServer, pszTopic, pszItem, pszData, (char**)&buffer, 255)) + { + if(mode == 0) + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, buffer)); + } + else + THROW_ERROR(cx, "DDE Failed! Check the log for the error message."); + + return JS_TRUE; +} + +JSAPI_FUNC(my_keystate) +{ + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + *rval = BOOLEAN_TO_JSVAL(!!GetAsyncKeyState(JSVAL_TO_INT(argv[0]))); + + return JS_TRUE; +} + +JSAPI_FUNC(my_addEventListener) +{ + if(JSVAL_IS_STRING(argv[0]) && JSVAL_IS_FUNCTION(cx, argv[1])) + { + char* evtName = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(evtName && strlen(evtName)) + { + Script* self = (Script*)JS_GetContextPrivate(cx); + self->RegisterEvent(JS_GetStringBytes(JSVAL_TO_STRING(argv[0])), argv[1]); + } + else + THROW_ERROR(cx, "Event name is invalid!"); + } + return JS_TRUE; +} + +JSAPI_FUNC(my_removeEventListener) +{ + if(JSVAL_IS_STRING(argv[0]) && JSVAL_IS_FUNCTION(cx, argv[1])) + { + char* evtName = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(evtName && strlen(evtName)) + { + Script* self = (Script*)JS_GetContextPrivate(cx); + self->UnregisterEvent(evtName, argv[1]); + } + else + THROW_ERROR(cx, "Event name is invalid!"); + } + return JS_TRUE; +} + +JSAPI_FUNC(my_clearEvent) +{ + if(JSVAL_IS_STRING(argv[0])) + { + Script* self = (Script*)JS_GetContextPrivate(cx); + self->ClearEvent(JS_GetStringBytes(JSVAL_TO_STRING(argv[0]))); + } + return JS_TRUE; +} + +JSAPI_FUNC(my_clearAllEvents) +{ + Script* self = (Script*)JS_GetContextPrivate(cx); + self->ClearAllEvents(); + return JS_TRUE; +} + +JSAPI_FUNC(my_js_strict) +{ + if(argc == NULL) + { + *rval = BOOLEAN_TO_JSVAL(((JS_GetOptions(cx) & JSOPTION_STRICT) == JSOPTION_STRICT)); + return JS_TRUE; + } + + if(argc == 1) + { + bool bFlag = ((JS_GetOptions(cx) & JSOPTION_STRICT) == JSOPTION_STRICT); + if(JSVAL_TO_BOOLEAN(argv[0])) + { + if(!bFlag) + JS_ToggleOptions(cx, JSOPTION_STRICT); + } + else + { + if(bFlag) + JS_ToggleOptions(cx, JSOPTION_STRICT); + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_scriptBroadcast) +{ + if(argc < 1) + THROW_ERROR(cx, "You must specify something to broadcast"); + + ScriptBroadcastEvent(argc, argv); + return JS_TRUE; +} + +JSAPI_FUNC(my_showConsole) +{ + Console::Show(); + return JS_TRUE; +} + +JSAPI_FUNC(my_hideConsole) +{ + Console::Hide(); + return JS_TRUE; +} + +JSAPI_FUNC(my_loadMpq) +{ + char* path = NULL; + if(!JS_ConvertArguments(cx, argc, argv, "s", &path)) + return JS_FALSE; + + if(isValidPath(path)) + LoadMPQ(path); + + return JS_TRUE; +} diff --git a/JSCore.h b/JSCore.h new file mode 100644 index 00000000..4ccabe81 --- /dev/null +++ b/JSCore.h @@ -0,0 +1,27 @@ +#pragma once + +#include "js32.h" + +JSAPI_FUNC(my_getThreadPriority); +JSAPI_FUNC(my_debugLog); +JSAPI_FUNC(my_print); +JSAPI_FUNC(my_delay); +JSAPI_FUNC(my_load); +JSAPI_FUNC(my_include); +JSAPI_FUNC(my_isIncluded); +JSAPI_FUNC(my_stop); +JSAPI_FUNC(my_beep); +JSAPI_FUNC(my_sendCopyData); +JSAPI_FUNC(my_sendDDE); +JSAPI_FUNC(my_keystate); +JSAPI_FUNC(my_getTickCount); +JSAPI_FUNC(my_addEventListener); +JSAPI_FUNC(my_removeEventListener); +JSAPI_FUNC(my_clearEvent); +JSAPI_FUNC(my_clearAllEvents); +JSAPI_FUNC(my_js_strict); +JSAPI_FUNC(my_version); +JSAPI_FUNC(my_scriptBroadcast); +JSAPI_FUNC(my_showConsole); +JSAPI_FUNC(my_hideConsole); +JSAPI_FUNC(my_loadMpq); diff --git a/JSDirectory.cpp b/JSDirectory.cpp new file mode 100644 index 00000000..8902e00f --- /dev/null +++ b/JSDirectory.cpp @@ -0,0 +1,213 @@ +/* + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +// TODO: Rewrite this crap :( + +#define _USE_32BIT_TIME_T + +#include +#include +#include + +#include "JSDirectory.h" +#include "D2BS.h" +#include "File.h" +//#include "js32.h" + +//////////////////////////////////////////////////////////////////////////////// +// Directory stuff +//////////////////////////////////////////////////////////////////////////////// + +EMPTY_CTOR(dir) + +JSAPI_FUNC(my_openDir) +{ + if(argc != 1) + return JS_TRUE; + + char path[_MAX_PATH]; + char* name = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + + if(!isValidPath(name)) + return JS_TRUE; + + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, name); + + if((_mkdir(path) == -1) && (errno == ENOENT)) { + JS_ReportError(cx, "Couldn't get directory %s, path '%s' not found", name, path); + return JS_FALSE; + } + else { + DirData* d = new DirData(name); + JSObject *jsdir = BuildObject(cx, &folder_class, dir_methods, dir_props, d); + *rval = OBJECT_TO_JSVAL(jsdir); + } + + return JS_TRUE; +} + + +//////////////////////////////////////////////////////////////////////////////// +// dir_getFiles +// searches a directory for files with a specified extension(*.* assumed) +// +// Added by lord2800 +//////////////////////////////////////////////////////////////////////////////// + +JSAPI_FUNC(dir_getFiles) +{ + if(argc > 1) + return JS_TRUE; + if(argc < 1) + argv[0] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, "*.*")); + + DirData* d = (DirData*)JS_GetPrivate(cx, obj); + char* search = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!search) + THROW_ERROR(cx, "Failed to get search string"); + + long hFile; + char path[_MAX_PATH], oldpath[_MAX_PATH]; + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, d->name); + + _getcwd(oldpath, _MAX_PATH); + _chdir(path); + + _finddata_t found; + JSObject* jsarray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(jsarray); + + if((hFile = _findfirst(search, &found)) != -1L) + { + jsint element = 0; + do + { + if((found.attrib & _A_SUBDIR)) + continue; + jsval file = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, found.name)); + JS_SetElement(cx, jsarray, element++, &file); + } while(_findnext(hFile, &found) == 0); + } + + _chdir(oldpath); + + return JS_TRUE; +} + +JSAPI_FUNC(dir_getFolders) +{ + if(argc > 1) + return JS_TRUE; + if(argc < 1) + argv[0] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, "*.*")); + + DirData* d = (DirData*)JS_GetPrivate(cx, obj); + char* search = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!search) + THROW_ERROR(cx, "Failed to get search string"); + + long hFile; + char path[_MAX_PATH], oldpath[_MAX_PATH]; + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, d->name); + + _getcwd(oldpath, _MAX_PATH); + _chdir(path); + + _finddata_t found; + JSObject* jsarray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(jsarray); + + if((hFile = _findfirst(search, &found)) != -1L) + { + jsint element = 0; + do + { + if(!strcmp(found.name, "..") || !strcmp(found.name, ".") || !(found.attrib & _A_SUBDIR)) + continue; + jsval file = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, found.name)); + JS_SetElement(cx, jsarray, element++, &file); + } while(_findnext(hFile, &found) == 0); + } + + _chdir(oldpath); + + return JS_TRUE; +} + +JSAPI_FUNC(dir_create) +{ + DirData* d = (DirData*)JS_GetPrivate(cx, obj); + char path[_MAX_PATH]; + char* name = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + + if(!isValidPath(name)) + return JS_TRUE; + + sprintf_s(path, sizeof(path), "%s\\%s\\%s", Vars.szScriptPath, d->name, name); + if(_mkdir(path) == -1 && (errno == ENOENT)) { + JS_ReportError(cx, "Couldn't create directory %s, path %s not found", name, path); + return JS_FALSE; + } + else { + DirData* d = new DirData(name); + JSObject* jsdir = BuildObject(cx, &folder_class, dir_methods, dir_props, d); + *rval = OBJECT_TO_JSVAL(jsdir); + } + + return JS_TRUE; +} + +JSAPI_FUNC(dir_delete) +{ + DirData* d = (DirData*)JS_GetPrivate(cx, obj); + + char path[_MAX_PATH]; + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, d->name); + + if(_rmdir(path) == -1) + { + // TODO: Make an optional param that specifies recursive delete + if(errno == ENOTEMPTY) + THROW_ERROR(cx, "Tried to delete directory, but it is not empty or is the current working directory"); + if(errno == ENOENT) + THROW_ERROR(cx, "Path not found"); + } + *rval = JSVAL_TRUE; + + return JS_TRUE; +} + +JSAPI_PROP(dir_getProperty) +{ + DirData* d = (DirData*)JS_GetPrivate(cx, obj); + + if(!d) return JS_FALSE; + + switch(JSVAL_TO_INT(id)) + { + case DIR_NAME: + *vp = STRING_TO_JSVAL(JS_InternString(cx, d->name)); + break; + } + return JS_TRUE; +} + +void dir_finalize(JSContext *cx, JSObject *obj) +{ + DirData* d = (DirData*)JS_GetPrivate(cx, obj); + delete d; +} + diff --git a/JSDirectory.h b/JSDirectory.h new file mode 100644 index 00000000..baa41a42 --- /dev/null +++ b/JSDirectory.h @@ -0,0 +1,51 @@ +#ifndef __JSDIRECTORY_H__ +#define __JSDIRECTORY_H__ + +// TODO: Rewrite this mess of crap too + +#include "js32.h" +#include +#include + +CLASS_CTOR(dir); + +JSAPI_FUNC(dir_getFiles); +JSAPI_FUNC(dir_getFolders); +JSAPI_FUNC(dir_create); +JSAPI_FUNC(dir_delete); +JSAPI_FUNC(my_openDir); + +JSAPI_PROP(dir_getProperty); + +void dir_finalize(JSContext *cx, JSObject *obj); + + +////////////////////////////////////////////////////////////////// +// directory stuff +////////////////////////////////////////////////////////////////// + +enum {DIR_NAME}; + +static JSPropertySpec dir_props[] = { + {"name", DIR_NAME, JSPROP_PERMANENT_VAR, dir_getProperty}, + {0} +}; + +static JSFunctionSpec dir_methods[] = { + {"create", dir_create, 1}, + {"remove", dir_delete, 1}, + {"getFiles", dir_getFiles, 1}, + {"getFolders", dir_getFolders, 1}, + {0} +}; + +class DirData { +public: + char name[_MAX_FNAME]; + DirData(char* newname) + { + strcpy_s(name, _MAX_FNAME, newname); + } +}; + +#endif diff --git a/JSExits.cpp b/JSExits.cpp new file mode 100644 index 00000000..69c8a138 --- /dev/null +++ b/JSExits.cpp @@ -0,0 +1,46 @@ +#include "JSExits.h" + +EMPTY_CTOR(exit) + +void exit_finalize(JSContext *cx, JSObject *obj) +{ + myExit* pExit = (myExit*)JS_GetPrivate(cx, obj); + delete pExit; +} + +JSAPI_PROP(exit_getProperty) +{ + myExit* pExit = (myExit*)JS_GetPrivate(cx, obj); + + *vp = JSVAL_VOID; + + if(!pExit) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) + { + case EXIT_X: + *vp = INT_TO_JSVAL(pExit->x); + break; + case EXIT_Y: + *vp = INT_TO_JSVAL(pExit->y); + break; + case EXIT_TARGET: + *vp = INT_TO_JSVAL(pExit->id); + break; + case EXIT_TYPE: + *vp = INT_TO_JSVAL(pExit->type); + break; + case EXIT_TILEID: + *vp = INT_TO_JSVAL(pExit->tileid); + break; + case EXIT_LEVELID: + *vp = INT_TO_JSVAL(pExit->level); + break; + default: + break; + } + + return JS_TRUE; +} + diff --git a/JSExits.h b/JSExits.h new file mode 100644 index 00000000..15976e13 --- /dev/null +++ b/JSExits.h @@ -0,0 +1,41 @@ +#ifndef EXITS_H +#define EXITS_H + +#include "js32.h" +#include + +CLASS_CTOR(exit); + +void exit_finalize(JSContext *cx, JSObject *obj); +JSAPI_PROP(exit_getProperty); + +enum exit_tinyid { + EXIT_X, + EXIT_Y, + EXIT_TARGET, + EXIT_TYPE, + EXIT_TILEID, + EXIT_LEVELID +}; + + +static JSPropertySpec exit_props[] = { + {"x", EXIT_X, JSPROP_PERMANENT_VAR, exit_getProperty}, + {"y", EXIT_Y, JSPROP_PERMANENT_VAR, exit_getProperty}, + {"target", EXIT_TARGET, JSPROP_PERMANENT_VAR, exit_getProperty}, + {"type", EXIT_TYPE, JSPROP_PERMANENT_VAR, exit_getProperty}, + {"tileid", EXIT_TILEID, JSPROP_PERMANENT_VAR, exit_getProperty}, + {"level", EXIT_LEVELID, JSPROP_PERMANENT_VAR, exit_getProperty}, + {0}, +}; + +struct myExit { + DWORD x; + DWORD y; + DWORD id; + DWORD type; + DWORD tileid; + DWORD level; +}; + +#endif \ No newline at end of file diff --git a/JSFile.cpp b/JSFile.cpp new file mode 100644 index 00000000..05f5f04f --- /dev/null +++ b/JSFile.cpp @@ -0,0 +1,544 @@ +/* + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#define _USE_32BIT_TIME_T + +#include +#include +#include + +#include "JSFile.h" +#include "D2BS.h" +#include "File.h" + +struct FileData { + int mode; + char* path; + bool autoflush, locked; + FILE* fptr; +#if DEBUG + char* lockLocation; + int line; +#endif +}; + +EMPTY_CTOR(file) + +JSBool file_equality(JSContext *cx, JSObject *obj, jsval v, JSBool *bp) +{ + *bp = JS_FALSE; + if(JSVAL_IS_OBJECT(v) && !JSVAL_IS_VOID(v) && !JSVAL_IS_NULL(v)) + { + FileData* ptr = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + FileData* ptr2 = (FileData*)JS_GetInstancePrivate(cx, JSVAL_TO_OBJECT(v), &file_class_ex.base, NULL); + if(ptr && ptr2 && !_strcmpi(ptr->path, ptr2->path) && ptr->mode == ptr2->mode) + *bp = JS_TRUE; + } + return JS_TRUE; +} + +JSAPI_PROP(file_getProperty) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + struct _stat filestat = {0}; + if(fdata) + { + switch(JSVAL_TO_INT(id)) + { + case FILE_READABLE: + *vp = BOOLEAN_TO_JSVAL((fdata->fptr && !feof(fdata->fptr) && !ferror(fdata->fptr))); + break; + case FILE_WRITEABLE: + *vp = BOOLEAN_TO_JSVAL((fdata->fptr && !ferror(fdata->fptr) && (fdata->mode % 3) > FILE_READ)); + break; + case FILE_SEEKABLE: + *vp = BOOLEAN_TO_JSVAL((fdata->fptr && !ferror(fdata->fptr))); + break; + case FILE_MODE: + *vp = INT_TO_JSVAL((fdata->mode % 3)); + break; + case FILE_BINARYMODE: + *vp = BOOLEAN_TO_JSVAL((fdata->mode > 2)); + break; + case FILE_LENGTH: + if(fdata->fptr) + *vp = INT_TO_JSVAL(_filelength(_fileno(fdata->fptr))); + else + *vp = JSVAL_ZERO; + break; + case FILE_PATH: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, fdata->path+strlen(Vars.szScriptPath)+1)); + break; + case FILE_POSITION: + if(fdata->fptr) + { + if(fdata->locked) + *vp = INT_TO_JSVAL(ftell(fdata->fptr)); + else + *vp = INT_TO_JSVAL(_ftell_nolock(fdata->fptr)); + } + else + *vp = JSVAL_ZERO; + break; + case FILE_EOF: + if(fdata->fptr) + *vp = BOOLEAN_TO_JSVAL(!!feof(fdata->fptr)); + else + *vp = JSVAL_TRUE; + break; + case FILE_AUTOFLUSH: + *vp = BOOLEAN_TO_JSVAL(fdata->autoflush); + break; + case FILE_ACCESSED: + if(fdata->fptr) + { + _fstat(_fileno(fdata->fptr), &filestat); + JS_NewNumberValue(cx, (jsdouble)filestat.st_atime, vp); + } + else *vp = JSVAL_ZERO; + break; + case FILE_MODIFIED: + if(fdata->fptr) + { + _fstat(_fileno(fdata->fptr), &filestat); + JS_NewNumberValue(cx, (jsdouble)filestat.st_mtime, vp); + } + else *vp = JSVAL_ZERO; + break; + case FILE_CREATED: + if(fdata->fptr) + { + _fstat(_fileno(fdata->fptr), &filestat); + JS_NewNumberValue(cx, (jsdouble)filestat.st_ctime, vp); + } + else *vp = JSVAL_ZERO; + break; + } + } + else + THROW_ERROR(cx, "Couldn't get file object"); + +return JS_TRUE; +} + +JSAPI_PROP(file_setProperty) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata) + { + switch(JSVAL_TO_INT(id)) + { + case FILE_AUTOFLUSH: + if(JSVAL_IS_BOOLEAN(*vp)) + fdata->autoflush = !!JSVAL_TO_BOOLEAN(*vp); + break; + } + } + else + THROW_ERROR(cx, "Couldn't get file object"); + + return JS_TRUE; +} + +JSAPI_FUNC(file_open) +{ + if(argc < 2) + THROW_ERROR(cx, "Not enough parameters, 2 or more expected"); + if(!JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "Parameter 1 not a string"); + if(!JSVAL_IS_INT(argv[1])) + THROW_ERROR(cx, "Parameter 2 not a mode"); + + // check for attempts to break the sandbox and for invalid file name characters + char* file = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!(file && file[0] && isValidPath(file))) + THROW_ERROR(cx, "Invalid file name"); + + int32 mode; + if(JS_ValueToInt32(cx, argv[1], &mode) == JS_FALSE) + THROW_ERROR(cx, "Could not convert parameter 2"); + + // this could be simplified to: mode > FILE_APPEND || mode < FILE_READ + // but then it takes a hit for readability + if(!(mode == FILE_READ || mode == FILE_WRITE || mode == FILE_APPEND)) + THROW_ERROR(cx, "Invalid file mode"); + + bool binary = false, autoflush = false, lockFile = false; + if(argc > 2 && JSVAL_IS_BOOLEAN(argv[2])) + binary = !!JSVAL_TO_BOOLEAN(argv[2]); + if(argc > 3 && JSVAL_IS_BOOLEAN(argv[3])) + autoflush = !!JSVAL_TO_BOOLEAN(argv[3]); + if(argc > 4 && JSVAL_IS_BOOLEAN(argv[4])) + lockFile = !!JSVAL_TO_BOOLEAN(argv[4]); + + if(binary) + mode += 3; + static const char* modes[] = {"rt", "w+t", "a+t", "rb", "w+b", "a+b"}; + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, file); + + FILE* fptr = NULL; + fopen_s(&fptr, path, modes[mode]); + if(!fptr) { + JS_ReportError(cx, "Couldn't open file %s: %s", file, _strerror(NULL)); + return JS_FALSE; + } + + FileData* fdata = new FileData; + if(!fdata) + { + fclose(fptr); + THROW_ERROR(cx, "Couldn't allocate memory for the FileData object"); + } + + fdata->mode = mode; + fdata->path = _strdup(path); + fdata->autoflush = autoflush; + fdata->locked = lockFile; + fdata->fptr = fptr; + if(lockFile) + { + _lock_file(fptr); +#if DEBUG + fdata->lockLocation = __FILE__; + fdata->line = __LINE__; +#endif + } + + JSObject* res = BuildObject(cx, &file_class_ex.base, file_methods, file_props, fdata); + if(!res) + { + if(lockFile) + fclose(fptr); + else + _fclose_nolock(fptr); + delete fdata; + THROW_ERROR(cx, "Failed to define the file object"); + } + *rval = OBJECT_TO_JSVAL(res); + return JS_TRUE; +} + +JSAPI_FUNC(file_close) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata) + { + if(fdata->fptr) + { + if(fdata->locked) + { + _unlock_file(fdata->fptr); +#if DEBUG + fdata->lockLocation = __FILE__; + fdata->line = __LINE__; +#endif + if(!!fclose(fdata->fptr)) + THROW_ERROR(cx, _strerror("Close failed")); + } + else if(!!_fclose_nolock(fdata->fptr)) + THROW_ERROR(cx, _strerror("Close failed")); + fdata->fptr = NULL; + } + else + THROW_ERROR(cx, "File is not open"); + } + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +JSAPI_FUNC(file_reopen) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata) + if(!fdata->fptr) { + static const char* modes[] = {"rt", "w+t", "a+t", "rb", "w+b", "a+b"}; + fdata->fptr = NULL; + fopen_s(&fdata->fptr, fdata->path, modes[fdata->mode]); + if(!fdata->fptr) + THROW_ERROR(cx, _strerror("Could not reopen file")); + if(fdata->locked) + { + _lock_file(fdata->fptr); +#if DEBUG + fdata->lockLocation = __FILE__; + fdata->line = __LINE__; +#endif + } + } else THROW_ERROR(cx, "File is not closed"); + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +JSAPI_FUNC(file_read) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) + { + clearerr(fdata->fptr); + int32 count = 1; + if(!(argc > 0 && JSVAL_TO_INT(argv[0]) > 0 && JS_ValueToInt32(cx, argv[0], &count))) + THROW_ERROR(cx, "Invalid arguments"); + + if(fdata->mode > 2) + { + // binary mode + int* result = new int[count+1]; + memset(result, 0, count+1); + uint32 size = 0; + if(fdata->locked) + size = fread(result, sizeof(int), count, fdata->fptr); + else + size = _fread_nolock(result, sizeof(int), count, fdata->fptr); + + if(size != (uint32)count && ferror(fdata->fptr)) + { + delete[] result; + THROW_ERROR(cx, _strerror("Read failed")); + } + if(count == 1) + *rval = INT_TO_JSVAL(result[0]); + else + { + JSObject* arr = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(arr); + for(int i = 0; i < count; i++) { + jsval val = INT_TO_JSVAL(result[i]); + JS_SetElement(cx, arr, i, &val); + } + } + } + else + { + // text mode + if(fdata->locked) + fflush(fdata->fptr); + else + _fflush_nolock(fdata->fptr); + + char* result = new char[count+1]; + memset(result, 0, count+1); + uint32 size = 0; + if(fdata->locked) + size = fread(result, sizeof(char), count, fdata->fptr); + else + size = _fread_nolock(result, sizeof(char), count, fdata->fptr); + + if(size != (uint32)count && ferror(fdata->fptr)) + { + delete[] result; + THROW_ERROR(cx, _strerror("Read failed")); + } + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, result)); + delete[] result; + } + } + return JS_TRUE; +} + +JSAPI_FUNC(file_readLine) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) { + const char* line = readLine(fdata->fptr, fdata->locked); + if(!line) + THROW_ERROR(cx, _strerror("Read failed")); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, line)); + delete[] line; + } + return JS_TRUE; +} + +JSAPI_FUNC(file_readAllLines) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) { + JSObject* arr = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(arr); + int i = 0; + while(!feof(fdata->fptr)) { + const char* line = readLine(fdata->fptr, fdata->locked); + if(!line) + THROW_ERROR(cx, _strerror("Read failed")); + jsval val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, line)); + JS_SetElement(cx, arr, i++, &val); + delete[] line; + } + } + return JS_TRUE; +} + +JSAPI_FUNC(file_readAll) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) { + if(fdata->locked) + fseek(fdata->fptr, 0, SEEK_END); + else + _fseek_nolock(fdata->fptr, 0, SEEK_END); + + uint size = 0; + if(fdata->locked) + size = ftell(fdata->fptr); + else + size = _ftell_nolock(fdata->fptr); + + if(fdata->locked) + fseek(fdata->fptr, 0, SEEK_SET); + else + _fseek_nolock(fdata->fptr, 0, SEEK_SET); + + char* contents = new char[size]; + uint count = 0; + if(fdata->locked) + count = fread(contents, sizeof(char), size, fdata->fptr); + else + count = _fread_nolock(contents, sizeof(char), size, fdata->fptr); + + if(count != size && ferror(fdata->fptr)) + { + delete[] contents; + THROW_ERROR(cx, _strerror("Read failed")); + } + *rval = STRING_TO_JSVAL(JS_NewStringCopyN(cx, contents, size)); + delete[] contents; + } + return JS_TRUE; + +} + +JSAPI_FUNC(file_write) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) { + for(uintN i = 0; i < argc; i++) + writeValue(fdata->fptr, cx, argv[i], !!(fdata->mode > 2), fdata->locked); + + if(fdata->autoflush) + { + if(fdata->locked) + fflush(fdata->fptr); + else + _fflush_nolock(fdata->fptr); + } + } + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +JSAPI_FUNC(file_seek) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) + { + if(argc > 0) + { + int32 bytes; + bool isLines = false, fromStart = false; + if(JS_ValueToInt32(cx, argv[0], &bytes) == JS_FALSE) + THROW_ERROR(cx, "Could not convert parameter 1"); + if(argc > 1 && JSVAL_IS_BOOLEAN(argv[1])) + isLines = !!JSVAL_TO_BOOLEAN(argv[1]); + if(argc > 2 && JSVAL_IS_BOOLEAN(argv[2])) + fromStart = !!JSVAL_TO_BOOLEAN(argv[1]); + if(!isLines) + { + if(fdata->locked && fseek(fdata->fptr, _ftell_nolock(fdata->fptr)+bytes, SEEK_CUR)) { + THROW_ERROR(cx, _strerror("Seek failed")); + } else if(_fseek_nolock(fdata->fptr, ftell(fdata->fptr)+bytes, SEEK_CUR)) + THROW_ERROR(cx, _strerror("Seek failed")); + } + else + { + if(fromStart) + rewind(fdata->fptr); + // semi-ugly hack to seek to the specified line + // if I were unlazy I wouldn't be allocating/deallocating all this memory, but for now it's ok + while(bytes--) + delete[] readLine(fdata->fptr, fdata->locked); + } + } + else + THROW_ERROR(cx, "Not enough parameters"); + } + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +JSAPI_FUNC(file_flush) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) + if(fdata->locked) + fflush(fdata->fptr); + else + _fflush_nolock(fdata->fptr); + + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +JSAPI_FUNC(file_reset) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) { + if(fdata->locked && fseek(fdata->fptr, 0L, SEEK_SET)) { + THROW_ERROR(cx, _strerror("Seek failed")); + } else if(_fseek_nolock(fdata->fptr, 0L, SEEK_SET)) + THROW_ERROR(cx, _strerror("Seek failed")); + } + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +JSAPI_FUNC(file_end) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata && fdata->fptr) + { + if(fdata->locked && fseek(fdata->fptr, 0L, SEEK_END)) { + THROW_ERROR(cx, _strerror("Seek failed")); + } else if(_fseek_nolock(fdata->fptr, 0L, SEEK_END)) + THROW_ERROR(cx, _strerror("Seek failed")); + } + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; +} + +void file_finalize(JSContext *cx, JSObject *obj) +{ + FileData* fdata = (FileData*)JS_GetInstancePrivate(cx, obj, &file_class_ex.base, NULL); + if(fdata) + { + free(fdata->path); + if(fdata->fptr) + { + if(fdata->locked) + { + _unlock_file(fdata->fptr); +#if DEBUG + fdata->lockLocation = __FILE__; + fdata->line = __LINE__; +#endif + fclose(fdata->fptr); + } + else + _fclose_nolock(fdata->fptr); + } + delete fdata; + } +} + diff --git a/JSFile.h b/JSFile.h new file mode 100644 index 00000000..04119891 --- /dev/null +++ b/JSFile.h @@ -0,0 +1,119 @@ +#ifndef __JSFILE_H__ +#define __JSFILE_H__ + +#include "js32.h" + +////////////////////////////////////////////////////////////////// +// file stuff +////////////////////////////////////////////////////////////////// + +CLASS_CTOR(file); +JSBool file_equality(JSContext *cx, JSObject *obj, jsval v, JSBool *bp); + +JSAPI_PROP(file_getProperty); +JSAPI_PROP(file_setProperty); + +JSAPI_FUNC(file_open); +JSAPI_FUNC(file_close); +JSAPI_FUNC(file_reopen); +JSAPI_FUNC(file_read); +JSAPI_FUNC(file_readLine); +JSAPI_FUNC(file_readAllLines); +JSAPI_FUNC(file_readAll); +JSAPI_FUNC(file_write); +JSAPI_FUNC(file_seek); +JSAPI_FUNC(file_flush); +JSAPI_FUNC(file_reset); +JSAPI_FUNC(file_end); + +void file_finalize(JSContext *cx, JSObject *obj); + +/** +File object: + +File File.open(string path, mode [, bool binaryMode [, bool autoflush [, bool lockFile]]]) - static - open the specified file, return a File object, mode = one of the constants of the File object listed below, binaryMode = default setting of file.binaryMode, autoflush = default setting of file.autoflush, lockFile = if true lock the file on open and unlock it on close, so other threads/programs can't open it + +File file.close() - object - close the current file +File file.reopen() - object - reopen the current file +string/int file.read(int num) - object - read num amount of characters or bytes from the file, if in non-binary mode this will be null terminated +string file.readLine() - object - read a single line from the file, assuming the line ends with \n or \r\n, throws an exception if the file is in binary mode +array file.readAllLines() - object - read the full contents of the file and split it up into an array of lines, and return the array of lines, throws an exception if the file is in binary mode +string/array file.readAll() - object - read the full contents of the file and return it as one big string or if in binary mode, array +File file.write(object contents, ...) - object - write the specified byte/strings/objects/array-of-bytes to a file, throws an exception if not all of the parameters could be written to disk +File file.seek(int bytes [, bool isLines [, bool fromStart]]) - object - seek the specified number of bytes, or optionally lines, in the file, optionally from the start of the file, stops at the end of the file +File file.flush() - object - flushes the remaining buffer to disk +File file.reset() - object - seek to the beginning of the file +File file.end() - object - seek to the end of the file +**/ + +static JSFunctionSpec file_methods[] = { + {"close", file_close, 0}, + {"reopen", file_reopen, 0}, + {"read", file_read, 1}, + {"readLine", file_readLine, 0}, + {"readAllLines",file_readAllLines, 0}, + {"readAll", file_readAll, 0}, + {"write", file_write, 1}, + {"seek", file_seek, 1}, + {"flush", file_flush, 0}, + {"reset", file_reset, 0}, + {"end", file_end, 0}, + {0} +}; + +static JSFunctionSpec file_s_methods[] = { + {"open", file_open, 2}, + {0} +}; + +// ensure that read/write/append get the correct values +enum { + FILE_READ = 0, + FILE_WRITE = 1, + FILE_APPEND = 2, + FILE_READABLE, + FILE_WRITEABLE, + FILE_SEEKABLE, + FILE_MODE, + FILE_LENGTH, + FILE_PATH, + FILE_POSITION, + FILE_EOF, + FILE_AUTOFLUSH, + FILE_BINARYMODE, + FILE_ACCESSED, + FILE_CREATED, + FILE_MODIFIED, +}; + +/** +bool file.readable - object - can read from the file +bool file.writable - object - can write from the file +bool file.seekable - object - can seek within the file +int file.mode - object - the mode the file was opened in, one of the FILE_MODE constants of the file object +bool file.binaryMode - object - determines if the file is in binary mode for read operations (write operations happen based on the parameter specified) +bool file.autoflush - object - automatically flush the file buffer after each write, defaults to off +int file.length - object - the length of the file in bytes +string file.path - object - the name and path (relative to the scripts/ folder) of the file +int file.position - object - the current position in the file +bool file.eof - object - determines if the file is at end-of-file or not +**/ + +static JSPropertySpec file_props[] = { + {"readable", FILE_READABLE, JSPROP_PERMANENT_VAR, file_getProperty}, + {"writeable", FILE_WRITEABLE, JSPROP_PERMANENT_VAR, file_getProperty}, + {"seekable", FILE_SEEKABLE, JSPROP_PERMANENT_VAR, file_getProperty}, + {"mode", FILE_MODE, JSPROP_PERMANENT_VAR, file_getProperty}, + {"binaryMode", FILE_BINARYMODE,JSPROP_PERMANENT_VAR, file_getProperty}, + {"length", FILE_LENGTH, JSPROP_PERMANENT_VAR, file_getProperty}, + {"path", FILE_PATH, JSPROP_PERMANENT_VAR, file_getProperty}, + {"position", FILE_POSITION, JSPROP_PERMANENT_VAR, file_getProperty}, + {"eof", FILE_EOF, JSPROP_PERMANENT_VAR, file_getProperty}, + {"accessed", FILE_ACCESSED, JSPROP_PERMANENT_VAR, file_getProperty}, + {"created", FILE_CREATED, JSPROP_PERMANENT_VAR, file_getProperty}, + {"modified", FILE_MODIFIED, JSPROP_PERMANENT_VAR, file_getProperty}, + {"autoflush", FILE_AUTOFLUSH, JSPROP_STATIC_VAR, file_getProperty, file_setProperty}, + {0} +}; + +#endif diff --git a/JSFileTools.cpp b/JSFileTools.cpp new file mode 100644 index 00000000..766f1854 --- /dev/null +++ b/JSFileTools.cpp @@ -0,0 +1,235 @@ +/* + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include +#include +#include +#include + +#include "JSFileTools.h" +#include "D2BS.h" +#include "File.h" + +using namespace std; + +EMPTY_CTOR(filetools) + +JSAPI_FUNC(filetools_remove) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "You must supply a file name"); + char* file = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(file)) + THROW_ERROR(cx, "Invalid file name"); + char path[_MAX_PATH+_MAX_FNAME]; + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, file); + + remove(path); + + return JS_TRUE; +} + +JSAPI_FUNC(filetools_rename) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "You must supply an original file name"); + char* orig = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(orig)) + THROW_ERROR(cx, "Invalid file name"); + char porig[_MAX_PATH+_MAX_FNAME]; + sprintf_s(porig, sizeof(porig), "%s\\%s", Vars.szScriptPath, orig); + + if(argc < 2 || !JSVAL_IS_STRING(argv[1])) + THROW_ERROR(cx, "You must supply a new file name"); + char* newName = JS_GetStringBytes(JSVAL_TO_STRING(argv[1])); + if(!isValidPath(newName)) + THROW_ERROR(cx, "Invalid file name"); + char pnewName[_MAX_PATH+_MAX_FNAME]; + sprintf_s(pnewName, sizeof(pnewName), "%s\\%s", Vars.szScriptPath, newName); + + rename(porig, pnewName); + + return JS_TRUE; +} + +JSAPI_FUNC(filetools_copy) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "You must supply an original file name"); + char* orig = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(orig)) + THROW_ERROR(cx, "Invalid file name"); + char porig[_MAX_PATH+_MAX_FNAME]; + sprintf_s(porig, sizeof(porig), "%s\\%s", Vars.szScriptPath, orig); + + if(argc < 2 || !JSVAL_IS_STRING(argv[1])) + THROW_ERROR(cx, "You must supply a new file name"); + char* newName = JS_GetStringBytes(JSVAL_TO_STRING(argv[1])); + if(!isValidPath(newName)) + THROW_ERROR(cx, "Invalid file name"); + char pnewName[_MAX_PATH+_MAX_FNAME]; + sprintf_s(pnewName, sizeof(pnewName), "%s\\%s", Vars.szScriptPath, newName); + + bool overwrite = false; + if(argc > 2 && JSVAL_IS_BOOLEAN(argv[2])) + overwrite = !!JSVAL_TO_BOOLEAN(argv[2]); + + if(overwrite && _access(pnewName, 0) == 0) + return JS_TRUE; + + FILE* fptr1 = NULL; + fopen_s(&fptr1, porig, "r"); + FILE* fptr2 = NULL; + fopen_s(&fptr2, pnewName, "w"); + + //Sanity check to make sure the file opened for reading! + if(!fptr1) + THROW_ERROR(cx, _strerror("Read file open failed")); + // Same for file opened for writing + if(!fptr2) + THROW_ERROR(cx, _strerror("Write file open failed")); + + while(!feof(fptr1)) + { + int ch = fgetc(fptr1); + if(ferror(fptr1)) + { + THROW_ERROR(cx, _strerror("Read Error")); + break; + } + else + { + if(!feof(fptr1)) + fputc(ch, fptr2); + if(ferror(fptr2)) + { + THROW_ERROR(cx, _strerror("Write Error")); + break; + } + } + } + if(ferror(fptr1) || ferror(fptr2)) + { + clearerr(fptr1); + clearerr(fptr2); + fflush(fptr2); + fclose(fptr2); + fclose(fptr1); + remove(pnewName); // delete the partial file so it doesnt look like we succeeded + THROW_ERROR(cx, _strerror("File copy failed")); + } + + fflush(fptr2); + fclose(fptr2); + fclose(fptr1); + + return JS_TRUE; +} + +JSAPI_FUNC(filetools_exists) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "Invalid file name"); + char* file = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(file)) + THROW_ERROR(cx, "Invalid file name"); + char path[_MAX_PATH+_MAX_FNAME]; + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, file); + + *rval = BOOLEAN_TO_JSVAL(!(_access(path, 0) != 0 && errno == ENOENT)); + + return JS_TRUE; +} + +JSAPI_FUNC(filetools_readText) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "You must supply an original file name"); + char* orig = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(orig)) + THROW_ERROR(cx, "Invalid file name"); + char porig[_MAX_PATH+_MAX_FNAME]; + sprintf_s(porig, sizeof(porig), "%s\\%s", Vars.szScriptPath, orig); + + if((_access(porig, 0) != 0 && errno == ENOENT)) + THROW_ERROR(cx, "File not found"); + + FILE* fptr = NULL; + fopen_s(&fptr, porig, "r"); + fseek(fptr, 0, SEEK_END); + uint size = ftell(fptr); + fseek(fptr, 0, SEEK_SET); + char* contents = new char[size]; + memset(contents, 0, size); + if(fread(contents, 1, size, fptr) != size && ferror(fptr)) + { + delete[] contents; + THROW_ERROR(cx, _strerror("Read failed")); + } + fclose(fptr); + + *rval = STRING_TO_JSVAL(JS_NewStringCopyN(cx, contents, size)); + delete[] contents; + return JS_TRUE; +} + +JSAPI_FUNC(filetools_writeText) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "You must supply an original file name"); + char* orig = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(orig)) + THROW_ERROR(cx, "Invalid file name"); + char porig[_MAX_PATH+_MAX_FNAME]; + sprintf_s(porig, sizeof(porig), "%s\\%s", Vars.szScriptPath, orig); + + bool result = true; + FILE* fptr = NULL; + fopen_s(&fptr, porig, "w"); + for(uintN i = 1; i < argc; i++) + if(!writeValue(fptr, cx, argv[i], false, true)) + result = false; + fflush(fptr); + fclose(fptr); + *rval = BOOLEAN_TO_JSVAL(result); + + return JS_TRUE; +} + +JSAPI_FUNC(filetools_appendText) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "You must supply an original file name"); + char* orig = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(!isValidPath(orig)) + THROW_ERROR(cx, "Invalid file name"); + char porig[_MAX_PATH+_MAX_FNAME]; + sprintf_s(porig, sizeof(porig), "%s\\%s", Vars.szScriptPath, orig); + + bool result = true; + FILE* fptr = NULL; + if(fopen_s(&fptr, porig, "a+") != 0) + THROW_ERROR(cx, _strerror("Failed to open file")); + for(uintN i = 1; i < argc; i++) + if(!writeValue(fptr, cx, argv[i], false, true)) + result = false; + fflush(fptr); + fclose(fptr); + *rval = BOOLEAN_TO_JSVAL(result); + + return JS_TRUE; +} + diff --git a/JSFileTools.h b/JSFileTools.h new file mode 100644 index 00000000..2fb9ace8 --- /dev/null +++ b/JSFileTools.h @@ -0,0 +1,42 @@ +#ifndef __FILETOOLS_H__ +#define __FILETOOLS_H__ + +#include "js32.h" + +/** +These are non-atomic operations: + +FileTools.remove(string name) - static - remove a file based on name +FileTools.rename(string oldName, string newName) - static - rename a file +FileTools.copy(string original, string copy) - static - copy file 'original' to 'copy' +FileTools.exists(string path) - static - determines if a file exists or not + +These are atomic operations: + +string FileTools.readText(string path) - static - open a file in read mode, read the full contents, return it as a string +bool FileTools.writeText(string path, object contents, ...) - static - open a file in write mode, write the content parameters into the file, and close it, true if the write succeeded, false if not +bool FileTools.appendText(string path, string contents) - static - open a file in append mode, write contents into the file, close it, true if the write succeeded, false if not +**/ + +CLASS_CTOR(filetools); + +JSAPI_FUNC(filetools_remove); +JSAPI_FUNC(filetools_rename); +JSAPI_FUNC(filetools_copy); +JSAPI_FUNC(filetools_exists); +JSAPI_FUNC(filetools_readText); +JSAPI_FUNC(filetools_writeText); +JSAPI_FUNC(filetools_appendText); + +static JSFunctionSpec filetools_s_methods[] = { + {"remove", filetools_remove, 1}, + {"rename", filetools_rename, 2}, + {"copy", filetools_copy, 2}, + {"exists", filetools_exists, 1}, + {"readText", filetools_readText, 1}, + {"writeText", filetools_writeText, 2}, + {"appendText", filetools_appendText, 2}, + {0} +}; + +#endif \ No newline at end of file diff --git a/JSGame.cpp b/JSGame.cpp new file mode 100644 index 00000000..23f9ca8d --- /dev/null +++ b/JSGame.cpp @@ -0,0 +1,1452 @@ +#include "Constants.h" +#include "JSGame.h" +#include "D2Helpers.h" +#include "CriticalSections.h" +#include "AreaLinker.h" +#include "CollisionMap.h" +#include "TeleportPath.h" +#include "WalkPath.h" +#include "D2Skills.h" +#include "MPQStats.h" +#include "Core.h" +#include "Helpers.h" +#include "Game.h" +#include "JSArea.h" +#include "JSGlobalClasses.h" +#include "TimedAlloc.h" + +#include + +JSAPI_FUNC(my_copyUnit) +{ + if(argc >= 1 && JSVAL_IS_OBJECT(argv[0]) && !JSVAL_IS_NULL(argv[0])) + { + *rval = JSVAL_VOID; + Private* myPrivate = (Private*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + + if(!myPrivate) + return JS_TRUE; + + if(myPrivate->dwPrivateType == PRIVATE_UNIT) + { + myUnit* lpOldUnit = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + myUnit* lpUnit = new myUnit; + + if(lpUnit) + { + memcpy(lpUnit, lpOldUnit, sizeof(myUnit)); + JSObject* jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, lpUnit); + if(!jsunit) + { + delete lpUnit; + lpUnit = NULL; + THROW_ERROR(cx, "Couldn't copy unit"); + } + + *rval = OBJECT_TO_JSVAL(jsunit); + } + } + else if(myPrivate->dwPrivateType == PRIVATE_ITEM) + { + invUnit* lpOldUnit = (invUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + invUnit* lpUnit = new invUnit; + + if(lpUnit) + { + memcpy(lpUnit, lpOldUnit, sizeof(invUnit)); + JSObject* jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, lpUnit); + if(!jsunit) + { + delete lpUnit; + lpUnit = NULL; + THROW_ERROR(cx, "Couldn't copy unit"); + } + + *rval = OBJECT_TO_JSVAL(jsunit); + } + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_clickMap) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + uint16 nClickType = NULL, nShift = NULL, nX = NULL, nY = NULL; + + *rval = JSVAL_FALSE; + + if(argc < 3) + return JS_TRUE; + + if(JSVAL_IS_INT(argv[0])) + JS_ValueToUint16(cx, argv[0], &nClickType); + if(JSVAL_IS_INT(argv[1]) || JSVAL_IS_BOOLEAN(argv[1])) + JS_ValueToUint16(cx, argv[1], &nShift); + if(JSVAL_IS_INT(argv[2])) + JS_ValueToUint16(cx, argv[2], &nX); + if(JSVAL_IS_INT(argv[3])) + JS_ValueToUint16(cx, argv[3], &nY); + + if(argc == 3 && JSVAL_IS_INT(argv[0]) && + (JSVAL_IS_INT(argv[1]) || JSVAL_IS_BOOLEAN(argv[1])) && + JSVAL_IS_OBJECT(argv[2]) && !JSVAL_IS_NULL(argv[2])) + { + myUnit* mypUnit = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[2])); + + if(!mypUnit || (mypUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(mypUnit->dwUnitId, mypUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + Vars.dwSelectedUnitId = NULL; + Vars.dwSelectedUnitType = NULL; + + *rval = BOOLEAN_TO_JSVAL(ClickMap(nClickType, nX, nY, nShift, pUnit)); + } + else if(argc > 3 && JSVAL_IS_INT(argv[0]) && + (JSVAL_IS_INT(argv[1]) || JSVAL_IS_BOOLEAN(argv[1])) && + JSVAL_IS_INT(argv[2]) && JSVAL_IS_INT(argv[3])) + { + *rval = BOOLEAN_TO_JSVAL(ClickMap(nClickType, nX, nY, nShift, NULL)); + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_acceptTrade) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + // TODO: Fix this nonsense. + if(argc > 0 && JSVAL_TO_INT(argv[0]) == 1) // Called with a '1' it will return if we already accepted it or not + { + *rval = BOOLEAN_TO_JSVAL((*p_D2CLIENT_bTradeAccepted)); + return JS_TRUE; + } + else if(JSVAL_TO_INT(argv[0]) == 2) // Called with a '2' it will return the trade flag + { + *rval = INT_TO_JSVAL((*p_D2CLIENT_RecentTradeId)); + return JS_TRUE; + } + else if(JSVAL_TO_INT(argv[0]) == 3) // Called with a '3' it will return if the 'check' is red or not + { + *rval = BOOLEAN_TO_JSVAL((*p_D2CLIENT_bTradeBlock)); + return JS_TRUE; + } + + CriticalMisc myMisc; + myMisc.EnterSection(); + + if((*p_D2CLIENT_RecentTradeId) == 3 || (*p_D2CLIENT_RecentTradeId) == 5 || (*p_D2CLIENT_RecentTradeId) == 7) + { + if((*p_D2CLIENT_bTradeBlock)) + { + // Don't operate if we can't trade anyway ... + *rval = JSVAL_FALSE; + } + else if((*p_D2CLIENT_bTradeAccepted)) + { + (*p_D2CLIENT_bTradeAccepted) = FALSE; + D2CLIENT_CancelTrade(); + *rval = JSVAL_TRUE; + } + else + { + (*p_D2CLIENT_bTradeAccepted) = TRUE; + D2CLIENT_AcceptTrade(); + *rval = JSVAL_TRUE; + } + return JS_TRUE; + } + + THROW_ERROR(cx, "Invalid parameter passed to acceptTrade!"); +} + +JSAPI_FUNC(my_getPath) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 5) + THROW_ERROR(cx, "Not enough parameters were passed to getPath!"); + + CriticalRoom myMisc; + myMisc.EnterSection(); + + *rval = JSVAL_FALSE; + DWORD dwCount = NULL; + POINT lpBuffer[255] = {0}; + DWORD *AreaIds = NULL; + jsuint dwLength = 0; + DWORD Area = 0; + + if (JSVAL_IS_OBJECT(argv[0])) { + JSObject* pObject = JSVAL_TO_OBJECT(argv[0]); + JS_GetArrayLength(cx, pObject, &dwLength); + AreaIds = new DWORD[dwLength]; + jsval nVal; + for (int n = 0; n < (int)dwLength; n++) { + JS_GetElement(cx, pObject, n, &nVal); + JS_ValueToECMAUint32(cx, nVal, &(AreaIds[n])); + } + Area = AreaIds[0]; + } else { + JS_ValueToECMAUint32(cx, argv[0], &Area); + } + + uint32 x, y, x2, y2; + JS_ValueToECMAUint32(cx, argv[1], &x); + JS_ValueToECMAUint32(cx, argv[2], &y); + JS_ValueToECMAUint32(cx, argv[3], &x2); + JS_ValueToECMAUint32(cx, argv[4], &y2); + + POINT ptStart = {x, y}, ptEnd = {x2, y2}; + BOOL UseTele = !D2COMMON_IsTownByLevelNo(Area); + BOOL Reduction = true; + if(argc >= 6) + UseTele = JSVAL_TO_BOOLEAN(argv[5]); + DWORD Radius = (!D2COMMON_IsTownByLevelNo(Area) && UseTele) ? 35 : 20; + if(argc >= 7) + JS_ValueToECMAUint32(cx, argv[6], &Radius); + if(argc == 8) + Reduction = !!JSVAL_TO_BOOLEAN(argv[7]); + + CCollisionMap g_collisionMap; + + DWORD nAreas[64] = {0}; + int nLen = GetAreas(nAreas, 64, Area, (WORD)ptEnd.x, (WORD)ptEnd.y); + + if (JSVAL_IS_OBJECT(argv[0])) { + if (!g_collisionMap.CreateMap(AreaIds, dwLength)) { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + } else { + if(nLen) + { + if(!g_collisionMap.CreateMap(nAreas, nLen)) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + } + else + if(!g_collisionMap.CreateMap(Area)) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + } + + if (!g_collisionMap.IsValidAbsLocation(ptStart.x, ptStart.y) || + !g_collisionMap.IsValidAbsLocation(ptEnd.x, ptEnd.y)) + return JS_TRUE; + + g_collisionMap.AbsToRelative(ptStart); + g_collisionMap.AbsToRelative(ptEnd); + + WordMatrix matrix; + if(!g_collisionMap.CopyMapData(matrix)) + return JS_TRUE; + + g_collisionMap.MakeBlank(matrix, ptStart); + g_collisionMap.MakeBlank(matrix, ptEnd); + + bool bFix = FALSE; + + if(UseTele) + { + CTeleportPath tf(matrix.GetData(), matrix.GetCX(), matrix.GetCY()); + dwCount = tf.FindTeleportPath(ptStart, ptEnd, lpBuffer, 255, Radius); + } + else + { + g_collisionMap.ThickenWalls(matrix, 1); + CWalkPath wp(matrix.GetData(), matrix.GetCX(), matrix.GetCY()); + + dwCount = (DWORD)wp.FindWalkPath(ptStart, ptEnd, lpBuffer, 255, Radius, !!Reduction); + } + + if(dwCount > 1) + bFix = TRUE; + if(dwCount) + { + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(pReturnArray); + for(DWORD i = 0; i < dwCount; i++) + g_collisionMap.RelativeToAbs(lpBuffer[i]); + + DWORD dwArray = NULL; + DWORD i = 0; + if(bFix) + i++; + + while(i < dwCount) + { + JSObject* pObj = BuildObject(cx); + JS_AddRoot(&pObj); + + jsval x = INT_TO_JSVAL(lpBuffer[i].x); + jsval y = INT_TO_JSVAL(lpBuffer[i].y); + + JS_SetProperty(cx, pObj, "x", &x); + JS_SetProperty(cx, pObj, "y", &y); + + jsval aObj = OBJECT_TO_JSVAL(pObj); + + JS_SetElement(cx, pReturnArray, dwArray, &aObj); + JS_RemoveRoot(&pObj); + dwArray++; + i++; + } + } + return JS_TRUE; +} + +JSAPI_FUNC(my_getCollision) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + CriticalRoom myMisc; + myMisc.EnterSection(); + bool found = false; + JSBool cachedOnly = JS_FALSE; + uint32 nLevelId, nX, nY; + if(!JS_ConvertArguments(cx, argc, argv, "uuu/b", &nLevelId, &nX, &nY, &cachedOnly)) + return JS_FALSE; + + int32 x = D2CLIENT_GetUnitX(D2CLIENT_GetPlayerUnit()), y = D2CLIENT_GetUnitY(D2CLIENT_GetPlayerUnit()); + if(GetDistance(x, y, nX, nY) < 60) { // look in near rooms first + Level* level = GetLevel(nLevelId); + Room2* room = D2COMMON_GetRoomFromUnit(D2CLIENT_GetPlayerUnit())->pRoom2; + int roomsNear = room->dwRoomsNear; + Room2** rooms = room->pRoom2Near; + int i = 0; + do { + bool added = false; + if(!room->pRoom1) { + added = true; + D2COMMON_AddRoomData(level->pMisc->pAct, level->dwLevelNo, room->dwPosX, room->dwPosY, room->pRoom1); + } + CollMap* map = room->pRoom1->Coll; + if(nX >= map->dwPosGameX && nY >= map->dwPosGameY && + nX < (map->dwPosGameX + map->dwSizeGameX) && nY < (map->dwPosGameY + map->dwSizeGameY)) + { + found = true; + // this is the room + int index = (nY - map->dwPosGameY) * (map->dwSizeGameY) + (nX - map->dwPosGameX); + //if(*(map->pMapStart + index) < *(map->pMapEnd)) + JS_NewNumberValue(cx, *(map->pMapStart+index), rval); + if(added) + D2COMMON_RemoveRoomData(level->pMisc->pAct, level->dwLevelNo, room->dwPosX, room->dwPosY, room->pRoom1); + break; + } + if(added) + D2COMMON_RemoveRoomData(level->pMisc->pAct, level->dwLevelNo, room->dwPosX, room->dwPosY, room->pRoom1); + room = rooms[i++]; + } while(room != NULL && i < roomsNear +1); + } + if(!found){ // if not found search all rooms + Level* level = GetLevel(nLevelId); + for(Room2* room = level->pRoom2First; room; room = room->pRoom2Next) + { + bool bAdded = FALSE; + if(!room->pRoom1) + { + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct, level->dwLevelNo, room->dwPosX, room->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + bAdded = TRUE; + } + + CollMap* map = room->pRoom1->Coll; + if(nX >= map->dwPosGameX && nY >= map->dwPosGameY && + nX < (map->dwPosGameX + map->dwSizeGameX) && nY < (map->dwPosGameY + map->dwSizeGameY)) + { + found = true; + // this is the room + int index = (nY - map->dwPosGameY) * (map->dwSizeGameY) + (nX - map->dwPosGameX); + //if(*(map->pMapStart + index) < *(map->pMapEnd)) + JS_NewNumberValue(cx, *(map->pMapStart+index), rval); + if(bAdded) + D2COMMON_RemoveRoomData(level->pMisc->pAct, level->dwLevelNo, room->dwPosX, room->dwPosY, room->pRoom1); + break; + } + + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, level->dwLevelNo, room->dwPosX, room->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_clickItem) +{ +typedef void __fastcall clickequip(UnitAny * pPlayer, Inventory * pIventory, int loc); + + CriticalMisc myMisc; + myMisc.EnterSection(); + + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(*p_D2CLIENT_TransactionDialog != 0 || *p_D2CLIENT_TransactionDialogs != 0 || *p_D2CLIENT_TransactionDialogs_2 != 0) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + myUnit* pmyUnit = NULL; + UnitAny* pUnit = NULL; + + //int ScreenSize = D2GFX_GetScreenSize(); + + POINT Belt[] = + { + {0,0}, // 0 + {1,0}, // 1 + {2,0}, // 2 + {3,0}, // 3 + + {0,1}, // 4 + {1,1}, // 5 + {2,1}, // 6 + {3,1}, // 7 + + {0,2}, // 8 + {1,2}, // 9 + {2,2}, // 10 + {3,2}, // 11 + + {0,3}, // 12 + {1,3}, // 13 + {2,3}, // 14 + {3,3}, // 15 + }; + + *p_D2CLIENT_CursorHoverX = 0xFFFFFFFF; + *p_D2CLIENT_CursorHoverY = 0xFFFFFFFF; + + if(argc == 1 && JSVAL_IS_OBJECT(argv[0])) + { + pmyUnit = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + clickequip * click = (clickequip*)*(DWORD*)(D2CLIENT_BodyClickTable + (4 * pUnit->pItemData->BodyLocation)); + + if(!click) + return JS_TRUE; + + click(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, pUnit->pItemData->BodyLocation); + + return JS_TRUE; + } + else if(argc == 2 && JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1])) + { + jsint nClickType = JSVAL_TO_INT(argv[0]); + jsint nBodyLoc = JSVAL_TO_INT(argv[1]); + + + if(nClickType == NULL) + { + clickequip * click = (clickequip*)*(DWORD*)(D2CLIENT_BodyClickTable + (4 * nBodyLoc)); + + if(!click) + return JS_TRUE; + + click(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, nBodyLoc); + } + // Click Merc Gear + else if(nClickType == 4) + { + if(nBodyLoc == 1 || nBodyLoc == 3 || nBodyLoc == 4) + { + UnitAny* pMerc = D2CLIENT_GetMercUnit(); + + if(pMerc) + { + D2CLIENT_MercItemAction(0x61, nBodyLoc); + } + } + } + + return JS_TRUE; + } + else if(argc == 2 && JSVAL_IS_INT(argv[0]) && JSVAL_IS_OBJECT(argv[1])) + { + pmyUnit = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[1])); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + jsint nClickType = JSVAL_TO_INT(argv[0]); + + if(!pUnit || !(pUnit->dwType == UNIT_ITEM) || !pUnit->pItemData) + THROW_ERROR(cx, "Object is not an item!"); + + int InventoryLocation = GetItemLocation(pUnit); + + int x = pUnit->pItemPath->dwPosX; + int y = pUnit->pItemPath->dwPosY; + + *p_D2CLIENT_CursorHoverX = x; + *p_D2CLIENT_CursorHoverY = y; + + InventoryLayout* pLayout = NULL; + + if(nClickType == 4) + { + UnitAny* pMerc = D2CLIENT_GetMercUnit(); + + if(pMerc) + if(pUnit->pItemData && pUnit->pItemData->pOwner) + if(pUnit->pItemData->pOwner->dwUnitId == pMerc->dwUnitId) + { + D2CLIENT_MercItemAction(0x61, pUnit->pItemData->BodyLocation); + } + + return JS_TRUE; + } + else if(InventoryLocation == STORAGE_INVENTORY || InventoryLocation == STORAGE_STASH || InventoryLocation == STORAGE_CUBE) + { + switch(InventoryLocation) + { + case STORAGE_INVENTORY: + pLayout = (InventoryLayout*)p_D2CLIENT_InventoryLayout; + break; + case STORAGE_STASH: + pLayout = (InventoryLayout*)p_D2CLIENT_StashLayout; + break; + case STORAGE_CUBE: + pLayout = (InventoryLayout*)p_D2CLIENT_CubeLayout; + break; + } + + x = pLayout->Left + x * pLayout->SlotPixelWidth + 10; + y = pLayout->Top + y * pLayout->SlotPixelHeight + 10; + + if(nClickType == NULL) + D2CLIENT_LeftClickItem(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, x, y, nClickType, pLayout, pUnit->pItemData->ItemLocation); + else + D2CLIENT_RightClickItem(x,y, pUnit->pItemData->ItemLocation, D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory); + + } + else if(InventoryLocation == STORAGE_BELT) + { + int i = x; + + if( i < 0 || i > 0x0F) + return JS_TRUE; + + if(D2GFX_GetScreenSize() == 2) + { + x = 440 + (Belt[i].x * 29); + y = 580 - (Belt[i].y * 29); + } + else { + x = 360 + (Belt[i].x * 29); + y = 460 - (Belt[i].y * 29); + } + if(nClickType == NULL) + D2CLIENT_ClickBelt(x, y, D2CLIENT_GetPlayerUnit()->pInventory); + else + D2CLIENT_ClickBeltRight(D2CLIENT_GetPlayerUnit()->pInventory, D2CLIENT_GetPlayerUnit(), nClickType == 1 ? FALSE : TRUE, i); + } + else if(D2CLIENT_GetCursorItem() == pUnit) + { + if(nClickType < 1 || nClickType > 12) + return JS_TRUE; + + clickequip * click = (clickequip*)*(DWORD*)(D2CLIENT_BodyClickTable + (4 * nClickType)); + + if(!click) + return JS_TRUE; + + click(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, nClickType); + } + } + else if(argc == 4) + { + if(JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1]) && JSVAL_IS_INT(argv[2]) && JSVAL_IS_INT(argv[3])) + { + jsint nButton = JSVAL_TO_INT(argv[0]); + jsint nX = JSVAL_TO_INT(argv[1]); + jsint nY = JSVAL_TO_INT(argv[2]); + jsint nLoc = JSVAL_TO_INT(argv[3]); + + InventoryLayout* pLayout = NULL; + + *p_D2CLIENT_CursorHoverX = nX; + *p_D2CLIENT_CursorHoverY = nY; + + // Fixing the location - so Diablo can handle it! + if(nLoc != 5) + { + UnitAny* pItem = D2CLIENT_GetCursorItem(); + if(pItem) + { + ItemTxt* pTxt = D2COMMON_GetItemText(pItem->dwTxtFileNo); + if(pTxt) + { + if(pTxt->ySize > 1) + nY += 1; + + if(pTxt->xSize > 1) + nX += 1; + } + + } + } + + //nLoc is location=: 0=inventory, 2=player trade, 3=cube, 4=stash, 5=belt + if(nLoc == 0 || nLoc == 2 || nLoc == 3 || nLoc == 4) + { + switch(nLoc) + { + case 0: + pLayout = (InventoryLayout*)p_D2CLIENT_InventoryLayout; + break; + case 2: + pLayout = (InventoryLayout*)p_D2CLIENT_TradeLayout; + break; + case 3: + pLayout = (InventoryLayout*)p_D2CLIENT_CubeLayout; + break; + case 4: + pLayout = (InventoryLayout*)p_D2CLIENT_StashLayout; + break; + } + + int x = pLayout->Left + nX * pLayout->SlotPixelWidth + 10; + int y = pLayout->Top + nY * pLayout->SlotPixelHeight + 10; + + if(nButton == 0) // Left Click + D2CLIENT_LeftClickItem(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, x, y, 1, pLayout, nLoc); + else if(nButton == 1) // Right Click + D2CLIENT_RightClickItem(x, y, nLoc, D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory); + else if(nButton == 2) // Shift Left Click + D2CLIENT_LeftClickItem(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, x, y, 5, pLayout, nLoc); + + return JS_TRUE; + } + else if(nLoc == 5) // Belt + { + + int z = -1; + + for(UINT i = 0; i < ArraySize(Belt); i++) + { + if(Belt[i].x == nX && Belt[i].y == nY) + { + z = (int)i; + break; + } + } + + if(z == -1) + return JS_TRUE; + + int x = NULL; + int y = NULL; + + if(D2GFX_GetScreenSize() == 2) + { + x = 440 + (Belt[z].x * 29); + y = 580 - (Belt[z].y * 29); + } + else { + x = 360 + (Belt[z].x * 29); + y = 460 - (Belt[z].y * 29); + } + + if(nButton == 0) + D2CLIENT_ClickBelt(x, y, D2CLIENT_GetPlayerUnit()->pInventory); + else if(nButton == 1) + D2CLIENT_ClickBeltRight(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, FALSE, z); + else if(nButton == 2) + D2CLIENT_ClickBeltRight(D2CLIENT_GetPlayerUnit(), D2CLIENT_GetPlayerUnit()->pInventory, TRUE, z); + + return JS_TRUE; + } + } + } + + return JS_TRUE; +} + + +JSAPI_FUNC(my_getLocaleString) +{ + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + uint16 localeId; + JS_ValueToUint16(cx, argv[0], &localeId); + wchar_t* wString = D2LANG_GetLocaleText(localeId); + char* szTmp = UnicodeToAnsi(wString); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szTmp)); + delete[] szTmp; + + return JS_TRUE; +} + +JSAPI_FUNC(my_rand) +{ + if(argc < 2 || !JSVAL_IS_INT(argv[0]) || !JSVAL_IS_INT(argv[1])) + { + *rval = INT_TO_JSVAL(0); + return JS_TRUE; + } + + // only seed the rng once + static bool seeded = false; + if(!seeded) + { + srand(GetTickCount()); + seeded = true; + } + + long long seed = 0; + if(ClientState() == ClientStateInGame) + seed = D2GAME_Rand(D2CLIENT_GetPlayerUnit()->dwSeed); + else + seed = rand(); + + jsint high; + jsint low; + + if(JS_ValueToInt32(cx, argv[0], &low) == JS_FALSE) + THROW_ERROR(cx, "Could not convert low value"); + + if(JS_ValueToInt32(cx, argv[1], &high) == JS_FALSE) + THROW_ERROR(cx, "Could not convert high value"); + + if(high > low+1) + { + int i = (seed % (high - low + 1)) + low; + *rval = INT_TO_JSVAL(i); + } + else + *rval = INT_TO_JSVAL(high); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getDistance) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + // TODO: Add the type of distance to the api design + jsint nX1 = NULL; + jsint nX2 = NULL; + jsint nY1 = NULL; + jsint nY2 = NULL; + + if(argc == 2 && JSVAL_IS_OBJECT(argv[0]) && JSVAL_IS_OBJECT(argv[1])) + { + myUnit* pUnit1 = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + myUnit* pUnit2 = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[1])); + + if(!pUnit1 || (pUnit1->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + if(!pUnit2 || (pUnit2->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnitA = D2CLIENT_FindUnit(pUnit1->dwUnitId, pUnit1->dwType); + UnitAny* pUnitB = D2CLIENT_FindUnit(pUnit2->dwUnitId, pUnit2->dwType); + + if(!pUnitA || !pUnitB) + return JS_TRUE; + + nX1 = D2CLIENT_GetUnitX(pUnitA); + nY1 = D2CLIENT_GetUnitY(pUnitA); + nX2 = D2CLIENT_GetUnitX(pUnitB); + nY2 = D2CLIENT_GetUnitY(pUnitB); + + } + else if(argc == 3) + { + if(JSVAL_IS_OBJECT(argv[0]) && JSVAL_IS_INT(argv[1]) && JSVAL_IS_INT(argv[2])) + { + myUnit* pUnit1 = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + + if(!pUnit1 || (pUnit1->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnitA = D2CLIENT_FindUnit(pUnit1->dwUnitId, pUnit1->dwType); + + if(!pUnitA) + return JS_TRUE; + + nX1 = D2CLIENT_GetUnitX(pUnitA); + nY1 = D2CLIENT_GetUnitY(pUnitA); + JS_ValueToECMAInt32(cx, argv[1], &nX2); + JS_ValueToECMAInt32(cx, argv[2], &nY2); + } + else if(JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1]) && JSVAL_IS_OBJECT(argv[2])) + { + myUnit* pUnit1 = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[2])); + + if(!pUnit1 || (pUnit1->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnitA = D2CLIENT_FindUnit(pUnit1->dwUnitId, pUnit1->dwType); + + if(!pUnitA) + return JS_TRUE; + + nX1 = D2CLIENT_GetUnitX(pUnitA); + nY1 = D2CLIENT_GetUnitY(pUnitA); + JS_ValueToECMAInt32(cx, argv[0], &nX2); + JS_ValueToECMAInt32(cx, argv[1], &nY2); + } + } + else if(argc == 4) + { + if(JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1]) && JSVAL_IS_INT(argv[2]) && JSVAL_IS_INT(argv[3])) + { + JS_ValueToECMAInt32(cx, argv[0], &nX1); + JS_ValueToECMAInt32(cx, argv[1], &nY1); + JS_ValueToECMAInt32(cx, argv[2], &nX2); + JS_ValueToECMAInt32(cx, argv[3], &nY2); + } + } + + jsdouble jsdist = (jsdouble)abs(GetDistance(nX1, nY1, nX2, nY2)); + JS_NewNumberValue(cx, jsdist, rval); + + return JS_TRUE; +} + +JSAPI_FUNC(my_gold) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + jsint nGold = NULL; + jsint nMode = 1; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + nGold = JSVAL_TO_INT(argv[0]); + + if(argc > 1 && JSVAL_IS_INT(argv[1])) + nMode = JSVAL_TO_INT(argv[1]); + + SendGold(nGold, nMode); + return JS_TRUE; +} + +JSAPI_FUNC(my_checkCollision) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc == 3 && JSVAL_IS_OBJECT(argv[0]) && JSVAL_IS_OBJECT(argv[1]) && JSVAL_IS_INT(argv[2])) + { + myUnit* pUnitA = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + myUnit* pUnitB = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[1])); + jsint nBitMask = JSVAL_TO_INT(argv[2]); + + if(!pUnitA || (pUnitA->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT || !pUnitB || (pUnitB->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit1 = D2CLIENT_FindUnit(pUnitA->dwUnitId, pUnitA->dwType); + UnitAny* pUnit2 = D2CLIENT_FindUnit(pUnitB->dwUnitId, pUnitB->dwType); + + if(!pUnit1 || !pUnit2) + return JS_TRUE; + + *rval = INT_TO_JSVAL(D2COMMON_CheckUnitCollision(pUnit1, pUnit2, nBitMask)); + return JS_TRUE; + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getMercHP) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + // TODO: Can we replace this with D2CLIENT_GetMercUnit()? + if(D2CLIENT_GetPlayerUnit() && D2CLIENT_GetPlayerUnit()->pAct) + { + for(Room1* pRoom = D2CLIENT_GetPlayerUnit()->pAct->pRoom1; pRoom; pRoom = pRoom->pRoomNext) + { + for(UnitAny* pUnit = pRoom->pUnitFirst; pUnit; pUnit = pUnit->pRoomNext) + { + if(pUnit->dwType == UNIT_MONSTER && + (pUnit->dwTxtFileNo == MERC_A1 || pUnit->dwTxtFileNo == MERC_A2 || + pUnit->dwTxtFileNo == MERC_A3 || pUnit->dwTxtFileNo == MERC_A5) && + D2CLIENT_GetMonsterOwner(pUnit->dwUnitId) == D2CLIENT_GetPlayerUnit()->dwUnitId) + + { + *rval = (pUnit->dwMode == 12 ? JSVAL_ZERO : INT_TO_JSVAL(D2CLIENT_GetUnitHPPercent(pUnit->dwUnitId))); + return JS_TRUE; + } + } + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getCursorType) +{ + jsint nType = NULL; + + if(argc > 0) + nType = JSVAL_TO_INT(argv[0]); + + *rval = INT_TO_JSVAL(nType == 1 ? *p_D2CLIENT_ShopCursorType : *p_D2CLIENT_RegularCursorType); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getSkillByName) +{ + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + return JS_TRUE; + + char *lpszText = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!(lpszText && lpszText[0])) + THROW_ERROR(cx, "Could not convert string"); + + for(int i = 0; i < ArraySize(Game_Skills); i++) + { + if(!_strcmpi(Game_Skills[i].name, lpszText)) + { + *rval = INT_TO_JSVAL(Game_Skills[i].skillID); + return JS_TRUE; + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getSkillById) +{ + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + jsint nId = JSVAL_TO_INT(argv[0]); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, "Unknown")); + + int row = 0; + if(FillBaseStat("skills", nId, "skilldesc", &row, sizeof(int))) + if(FillBaseStat("skilldesc", row, "str name", &row, sizeof(int))) + { + wchar_t* szName = D2LANG_GetLocaleText((WORD)row); + char* str = UnicodeToAnsi(szName); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, str)); + delete[] str; + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getTextSize) +{ + if(argc < 2 || !JSVAL_IS_STRING(argv[0]) || !JSVAL_IS_INT(argv[1])) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + char* pString = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!pString) + THROW_ERROR(cx, "Could not convert string"); + + POINT r = CalculateTextLen(pString, JSVAL_TO_INT(argv[1])); + jsval x = INT_TO_JSVAL(r.x); + jsval y = INT_TO_JSVAL(r.y); + + JSObject* pObj = NULL; + if(argc > 2 && JSVAL_IS_BOOLEAN(argv[2]) && JSVAL_TO_BOOLEAN(argv[2]) == TRUE) + { + // return an object with a height/width rather than an array + pObj = BuildObject(cx, NULL); + if(!pObj) + THROW_ERROR(cx, "Could not build object"); + JS_AddRoot(&pObj); + if(JS_SetProperty(cx, pObj, "width", &x) == JS_FALSE) + THROW_ERROR(cx, "Could not set width property"); + if(JS_SetProperty(cx, pObj, "height", &y) == JS_FALSE) + THROW_ERROR(cx, "Could not set height property"); + } + else + { + pObj = JS_NewArrayObject(cx, NULL, NULL); + JS_AddRoot(&pObj); + JS_SetElement(cx, pObj, 0, &x); + JS_SetElement(cx, pObj, 1, &y); + } + *rval = OBJECT_TO_JSVAL(pObj); + JS_RemoveRoot(&pObj); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getTradeInfo) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + jsint nMode = JSVAL_TO_INT(argv[0]); + + if(nMode == 0) + { + *rval = INT_TO_JSVAL((*p_D2CLIENT_RecentTradeId)); + return JS_TRUE; + } + else if(nMode == 1) + { + //FIXME + //char* tmp = UnicodeToAnsi((wchar_t*)(*p_D2CLIENT_RecentTradeName)); + //*rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, tmp)); + //delete[] tmp; + + return JS_TRUE; + } + else if(nMode == 2) + { + *rval = INT_TO_JSVAL((*p_D2CLIENT_RecentTradeId)); + return JS_TRUE; + } + *rval = JSVAL_FALSE; + + return JS_TRUE; +} + +JSAPI_FUNC(my_getUIFlag) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + { + *rval = JSVAL_VOID; + return JS_TRUE; + } + + jsint nUIId = JSVAL_TO_INT(argv[0]); + *rval = BOOLEAN_TO_JSVAL(D2CLIENT_GetUIState(nUIId)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getWaypoint) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + jsint nWaypointId = JSVAL_TO_INT(argv[0]); + + if(nWaypointId > 40) + nWaypointId = NULL; + + *rval = BOOLEAN_TO_JSVAL(!!D2COMMON_CheckWaypoint((*p_D2CLIENT_WaypointTable), nWaypointId)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_quitGame) +{ + if(ClientState() != ClientStateMenu) + D2CLIENT_ExitGame(); + + // give the core a chance to shut down + Shutdown(); + TerminateProcess(GetCurrentProcess(), 0); + + return JS_TRUE; +} + +JSAPI_FUNC(my_quit) +{ + if(ClientState() != ClientStateMenu) + D2CLIENT_ExitGame(); + + return JS_TRUE; +} + +JSAPI_FUNC(my_playSound) +{ +// I need to take a closer look at the D2CLIENT_PlaySound function + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + jsint nSoundId = JSVAL_TO_INT(argv[0]); + D2CLIENT_PlaySound(nSoundId); + + *rval = JSVAL_TRUE; + + return JS_TRUE; +} + +JSAPI_FUNC(my_say) +{ + for(uintN i = 0; i < argc; i++) + { + if(!JSVAL_IS_NULL(argv[i])) + { + if(!JS_ConvertValue(cx, argv[i], JSTYPE_STRING, &(argv[i]))) + { + JS_ReportError(cx, "Converting to string failed"); + return JS_FALSE; + } + + char* Text = JS_GetStringBytes(JS_ValueToString(cx, argv[i])); + if(Text == NULL) + { + JS_ReportError(cx, "Could not get string for value"); + return JS_FALSE; + } + + jsrefcount depth = JS_SuspendRequest(cx); + if(Text) Say(Text); + JS_ResumeRequest(cx, depth); + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_clickParty) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + *rval = JSVAL_FALSE; + + if(argc < 2 || !JSVAL_IS_OBJECT(argv[0]) || !JSVAL_IS_INT(argv[1])) + return JS_TRUE; + + RosterUnit* pUnit = (RosterUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + RosterUnit* mypUnit = *p_D2CLIENT_PlayerUnitList; + + if(!pUnit || !mypUnit) + return JS_TRUE; + + BOOL bFound = FALSE; + + for(RosterUnit* pScan = mypUnit; pScan; pScan = pScan->pNext) + if(pScan->dwUnitId == pUnit->dwUnitId) + bFound = TRUE; + + if(!bFound) + return JS_TRUE; + + jsint nMode = JSVAL_TO_INT(argv[1]); + + BnetData* pData = (*p_D2LAUNCH_BnData); + + // Attempt to loot player, check first if it's hardcore + if(nMode == 0 && pData && !(pData->nCharFlags & PLAYER_TYPE_HARDCORE)) + return JS_TRUE; + + // Attempt to party a player who is already in party ^_~ + if(nMode == 2 && pUnit->wPartyId != 0xFFFF && mypUnit->wPartyId == pUnit->wPartyId && pUnit->wPartyId != 0xFFFF) + return JS_TRUE; + + // don't leave a party if we are in none! + if(nMode == 3 && pUnit->wPartyId == 0xFFFF) + return JS_TRUE; + else if(nMode == 3 && pUnit->wPartyId != 0xFFFF) { + *rval = JSVAL_TRUE; + D2CLIENT_LeaveParty(); + return JS_TRUE; + } + + if(nMode < 0 || nMode > 3) + return JS_TRUE; + + + if(nMode == 1) + D2CLIENT_HostilePartyUnit(pUnit, 1); + else + D2CLIENT_ClickParty(pUnit, nMode); + + *rval = JSVAL_TRUE; + + return JS_TRUE; +} + +JSAPI_FUNC(my_useStatPoint) +{ + WORD stat = 0; + int32 count = 1; + if(!JS_ConvertArguments(cx, argc, argv, "c/u", &stat, &count)) + return JS_FALSE; + + UseStatPoint(stat, count); + return JS_TRUE; +} + +JSAPI_FUNC(my_useSkillPoint) +{ + WORD skill = 0; + int32 count = 1; + if(!JS_ConvertArguments(cx, argc, argv, "c/u", &skill, &count)) + return JS_FALSE; + + UseSkillPoint(skill, count); + return JS_TRUE; +} + +JSAPI_FUNC(my_getBaseStat) +{ + if(argc > 2) + { + char *szStatName = NULL, *szTableName = NULL; + jsint nBaseStat = 0; + jsint nClassId = 0; + jsint nStat = -1; + + if(JSVAL_IS_STRING(argv[0])) + { + szTableName = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!szTableName) + THROW_ERROR(cx, "Invalid table value"); + } + else if(JSVAL_IS_NUMBER(argv[0])) + JS_ValueToECMAInt32(cx, argv[0], &nBaseStat); + else + THROW_ERROR(cx, "Invalid table value"); + + JS_ValueToECMAInt32(cx, argv[1], &nClassId); + + if(JSVAL_IS_STRING(argv[2])) + { + szStatName = JS_GetStringBytes(JS_ValueToString(cx, argv[2])); + if(!szStatName) + THROW_ERROR(cx, "Invalid column value"); + } + else if(JSVAL_IS_NUMBER(argv[2])) + JS_ValueToECMAInt32(cx, argv[2], &nStat); + else + THROW_ERROR(cx, "Invalid column value"); + + FillBaseStat(cx, rval, nBaseStat, nClassId, nStat, szTableName, szStatName); + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_weaponSwitch) +{ + *rval = JSVAL_FALSE; + + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + jsint nParameter = NULL; + if(argc > 0) + if(JS_ValueToInt32(cx, argv[0], &nParameter) == JS_FALSE) + THROW_ERROR(cx, "Could not convert value"); + + if(nParameter == NULL) + { + // don't perform a weapon switch if current gametype is classic + BnetData* pData = (*p_D2LAUNCH_BnData); + if(pData) + { + if(!(pData->nCharFlags & PLAYER_TYPE_EXPAC)) + return JS_TRUE; + } + else + THROW_ERROR(cx, "Could not acquire BnData"); + + BYTE aPacket[1]; + aPacket[0] = 0x60; + D2NET_SendPacket(1, 1, aPacket); + *rval = JSVAL_TRUE; + } + else + *rval = INT_TO_JSVAL((*p_D2CLIENT_bWeapSwitch)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_transmute) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + bool cubeOn = !!D2CLIENT_GetUIState(UI_CUBE); + if(!cubeOn) + D2CLIENT_SetUIState(UI_CUBE, TRUE); + + D2CLIENT_Transmute(); + + if(!cubeOn) + D2CLIENT_SetUIState(UI_CUBE, FALSE); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getPlayerFlag) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc != 3 || !JSVAL_IS_NUMBER(argv[0]) || !JSVAL_IS_NUMBER(argv[1]) || !JSVAL_IS_NUMBER(argv[2])) + return JS_TRUE; + + uint32 nFirstUnitId = (uint32)-1; + uint32 nSecondUnitId = (uint32)-1; + + JS_ValueToECMAUint32(cx, argv[0], &nFirstUnitId); + JS_ValueToECMAUint32(cx, argv[1], &nSecondUnitId); + + DWORD nFlag = JSVAL_TO_INT(argv[2]); + + *rval = BOOLEAN_TO_JSVAL(D2CLIENT_TestPvpFlag(nFirstUnitId, nSecondUnitId, nFlag)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getMouseCoords) +{ + bool nFlag = false, nReturn = false; + + if(argc > 0 && JSVAL_IS_INT(argv[0]) || JSVAL_IS_BOOLEAN(argv[0])) + nFlag = !!JSVAL_TO_BOOLEAN(argv[0]); + if(argc > 1 && JSVAL_IS_INT(argv[1]) || JSVAL_IS_BOOLEAN(argv[1])) + nReturn = !!JSVAL_TO_BOOLEAN(argv[1]); + + JSObject* pObj = NULL; + + POINT Coords = {*p_D2CLIENT_MouseX, *p_D2CLIENT_MouseY}; + + if(nFlag) + { + Coords.x += *p_D2CLIENT_ViewportX; + Coords.y += *p_D2CLIENT_ViewportY; + + D2COMMON_AbsScreenToMap(&Coords.x, &Coords.y); + } + + jsval jsX = INT_TO_JSVAL(Coords.x); + jsval jsY = INT_TO_JSVAL(Coords.y); + + if(nReturn) + { + pObj = BuildObject(cx, NULL); + JS_AddRoot(&pObj); + if(!pObj) + THROW_ERROR(cx, "Could not build object"); + if(JS_SetProperty(cx, pObj, "x", &jsX) == JS_FALSE) + THROW_ERROR(cx, "Could not set x property"); + if(JS_SetProperty(cx, pObj, "y", &jsY) == JS_FALSE) + THROW_ERROR(cx, "Could not set y property"); + } + else + { + pObj = JS_NewArrayObject(cx, NULL, NULL); + JS_AddRoot(&pObj); + JS_SetElement(cx, pObj, 0, &jsX); + JS_SetElement(cx, pObj, 1, &jsY); + } + + if(!pObj) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(pObj); + JS_RemoveRoot(&pObj); + return JS_TRUE; +} + +JSAPI_FUNC(my_submitItem) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(UnitAny* pUnit = D2CLIENT_GetCursorItem()) + { + D2CLIENT_SubmitItem(pUnit->dwUnitId); + *rval = JSVAL_TRUE; + } + else + *rval = JSVAL_FALSE; + + return JS_TRUE; +} + +JSAPI_FUNC(my_getIsTalkingNPC) +{ + *rval = BOOLEAN_TO_JSVAL(IsScrollingText()); + return JS_TRUE; +} + +JSAPI_FUNC(my_getInteractedNPC) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + UnitAny* pNPC = D2CLIENT_GetCurrentInteractingNPC(); + if(!pNPC) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + myUnit* pmyUnit = new myUnit; // leaked? + if(!pmyUnit) + return JS_TRUE; + + char szName[256] = ""; + pmyUnit->_dwPrivateType = PRIVATE_UNIT; + pmyUnit->dwClassId = pNPC->dwTxtFileNo; + pmyUnit->dwMode = pNPC->dwMode; + pmyUnit->dwType = pNPC->dwType; + pmyUnit->dwUnitId = pNPC->dwUnitId; + strcpy_s(pmyUnit->szName, sizeof(pmyUnit->szName), szName); + + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyUnit); + if(!jsunit) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(jsunit); + return JS_TRUE; +} + +JSAPI_FUNC(my_takeScreenshot) +{ + D2WIN_TakeScreenshot(); + return JS_TRUE; +} diff --git a/JSGame.h b/JSGame.h new file mode 100644 index 00000000..450d0f07 --- /dev/null +++ b/JSGame.h @@ -0,0 +1,45 @@ +#pragma once +#ifndef __JSGAME_H__ +#define __JSGAME_H__ + +#include "js32.h" + +JSAPI_FUNC(my_rand); +JSAPI_FUNC(my_submitItem); +JSAPI_FUNC(my_copyUnit); +JSAPI_FUNC(my_clickMap); +JSAPI_FUNC(my_acceptTrade); +JSAPI_FUNC(my_clickItem); +JSAPI_FUNC(my_gold); +JSAPI_FUNC(my_checkCollision); +JSAPI_FUNC(my_playSound); +JSAPI_FUNC(my_quit); +JSAPI_FUNC(my_quitGame); +JSAPI_FUNC(my_say); +JSAPI_FUNC(my_weaponSwitch); +JSAPI_FUNC(my_transmute); +JSAPI_FUNC(my_clickParty); +JSAPI_FUNC(my_useStatPoint); +JSAPI_FUNC(my_useSkillPoint); + +JSAPI_FUNC(my_getInteractedNPC); +JSAPI_FUNC(my_getIsTalkingNPC); + +JSAPI_FUNC(my_takeScreenshot); +JSAPI_FUNC(my_getMouseCoords); +JSAPI_FUNC(my_getDistance); +JSAPI_FUNC(my_getPath); +JSAPI_FUNC(my_getCollision); +JSAPI_FUNC(my_getMercHP); +JSAPI_FUNC(my_getCursorType); +JSAPI_FUNC(my_getSkillByName); +JSAPI_FUNC(my_getSkillById); +JSAPI_FUNC(my_getLocaleString); +JSAPI_FUNC(my_getTextSize); +JSAPI_FUNC(my_getUIFlag); +JSAPI_FUNC(my_getTradeInfo); +JSAPI_FUNC(my_getWaypoint); +JSAPI_FUNC(my_getBaseStat); +JSAPI_FUNC(my_getPlayerFlag); + +#endif diff --git a/JSGlobalClasses.cpp b/JSGlobalClasses.cpp new file mode 100644 index 00000000..97ca0068 --- /dev/null +++ b/JSGlobalClasses.cpp @@ -0,0 +1,203 @@ +#include "js32.h" +#include "JSFile.h" +#include "JSSQLite.h" +#include "JSSandbox.h" +#include "JSUnit.h" +#include "JSScreenHook.h" +#include "JSPresetUnit.h" +#include "JSDirectory.h" +#include "JSFileTools.h" +#include "JSArea.h" +#include "JSControl.h" +#include "JSParty.h" +#include "JSExits.h" +#include "JSRoom.h" +#include "JSScript.h" + +JSClass global_obj = { + "global", JSCLASS_GLOBAL_FLAGS, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, + JSCLASS_NO_OPTIONAL_MEMBERS +}; + +JSClass sqlite_db = { + "SQLite", JSCLASS_HAS_PRIVATE | JSCLASS_IS_EXTENDED, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, sqlite_finalize, + NULL, NULL, NULL, sqlite_ctor, NULL, NULL, NULL, NULL +}; + +JSClass sqlite_stmt = { + "DBStatement", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, sqlite_stmt_finalize, + NULL, NULL, NULL, sqlite_stmt_ctor +}; + +JSClass script_class = { + "D2BSScript", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, + NULL, NULL, NULL, script_ctor +}; + +JSClass frame_class = { + "Frame", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, hook_finalize, + NULL, NULL, NULL, frame_ctor, NULL, NULL, NULL, NULL +}; + +JSClass box_class = { + "Box", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, hook_finalize, + NULL, NULL, NULL, box_ctor, NULL, NULL, NULL, NULL +}; + +JSClass line_class = { + "Line", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, hook_finalize, + NULL, NULL, NULL, line_ctor, NULL, NULL, NULL, NULL +}; + +JSClass text_class = { + "Text", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, hook_finalize, + NULL, NULL, NULL, text_ctor, NULL, NULL, NULL, NULL +}; + +JSClass image_class = { + "Image", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, hook_finalize, + NULL, NULL, NULL, image_ctor, NULL, NULL, NULL, NULL +}; + +JSClass sandbox_class = { + "Sandbox", JSCLASS_HAS_PRIVATE, + sandbox_addProperty, sandbox_delProperty, sandbox_getProperty, sandbox_setProperty, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, sandbox_finalize, + NULL, NULL, NULL, sandbox_ctor, NULL, NULL, NULL, NULL +}; + +JSClass room_class = { + "Room", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, + NULL, NULL, NULL, room_ctor +}; + +JSClass presetunit_class = { + "PresetUnit", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, presetunit_finalize, + NULL, NULL, NULL, presetunit_ctor +}; + +JSClass party_class = { + "Party", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, + NULL, NULL, NULL, party_ctor +}; + +JSClass filetools_class = { + "FileTools", NULL, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, + NULL, NULL, NULL, filetools_ctor, NULL, NULL, NULL, NULL +}; + +JSClass file_class = { + "File", JSCLASS_HAS_PRIVATE | JSCLASS_IS_EXTENDED, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, file_finalize, + NULL, NULL, NULL, file_ctor, NULL, NULL, NULL, NULL +}; + +JSClass exit_class = { + "Exit", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, exit_finalize, + NULL, NULL, NULL, exit_ctor +}; + +JSClass folder_class = { + "Folder", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, dir_finalize, + NULL, NULL, NULL, dir_ctor +}; + +JSClass control_class = { + "Control", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, control_finalize, + NULL, NULL, NULL, control_ctor +}; + +JSClass area_class = { + "Area", JSCLASS_HAS_PRIVATE, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, area_finalize, + NULL, NULL, NULL, area_ctor +}; + +JSClass unit_class = { + "Unit", JSCLASS_HAS_PRIVATE | JSCLASS_IS_EXTENDED, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, unit_finalize, + NULL, NULL, NULL, unit_ctor +}; + + +JSExtendedClass unit_class_ex = { + unit_class, + unit_equal, + NULL, NULL, NULL, NULL +}; + +JSExtendedClass file_class_ex = { + file_class, + file_equality, + NULL, NULL, NULL, NULL +}; + +JSExtendedClass sqlite_db_ex = { + sqlite_db, + sqlite_equal, + NULL, NULL, NULL, NULL +}; + +JSClassSpec global_classes[] = { + /*JSClass* properties functions static props static funcs */ + // game objects + {&unit_class_ex.base, unit_props, unit_methods, NULL, NULL}, + {&presetunit_class, presetunit_props, NULL, NULL, NULL}, + {&area_class, area_props, NULL, NULL, NULL}, + {&control_class, control_props, control_funcs, NULL, NULL}, + {&folder_class, dir_props, dir_methods, NULL, NULL}, + {&exit_class, exit_props, NULL, NULL, NULL}, + {&party_class, party_props, party_methods, NULL, NULL}, + {&room_class, room_props, room_methods, NULL, NULL}, + + // utility objects + {&file_class_ex.base, file_props, file_methods, NULL, file_s_methods}, + {&sqlite_db_ex.base, sqlite_props, sqlite_methods, NULL, NULL}, + {&sqlite_stmt, sqlite_stmt_props, sqlite_stmt_methods, NULL, NULL}, + {&filetools_class, NULL, NULL, NULL, filetools_s_methods}, + {&sandbox_class, NULL, sandbox_methods, NULL, NULL}, + {&script_class, script_props, script_methods, NULL, NULL}, + + // screenhook objects + {&frame_class, frame_props, frame_methods, NULL, NULL}, + {&box_class, box_props, box_methods, NULL, NULL}, + {&line_class, line_props, line_methods, NULL, NULL}, + {&text_class, text_props, text_methods, NULL, NULL}, + {&image_class, image_props, image_methods, NULL, NULL}, + {0} +}; diff --git a/JSGlobalClasses.h b/JSGlobalClasses.h new file mode 100644 index 00000000..8bda25f3 --- /dev/null +++ b/JSGlobalClasses.h @@ -0,0 +1,38 @@ +#pragma once + +#include "js32.h" + +struct JSClassSpec { + JSClass* js_class; + JSPropertySpec* props; + JSFunctionSpec* funcs; + JSPropertySpec* static_props; + JSFunctionSpec* static_funcs; +}; + +extern JSClassSpec global_classes[]; + +extern JSClass global_obj; +extern JSClass sqlite_db; +extern JSClass sqlite_stmt; +extern JSClass script_class; +extern JSClass frame_class; +extern JSClass box_class; +extern JSClass line_class; +extern JSClass text_class; +extern JSClass image_class; +extern JSClass sandbox_class; +extern JSClass room_class; +extern JSClass presetunit_class; +extern JSClass party_class; +extern JSClass filetools_class; +extern JSClass file_class; +extern JSClass exit_class; +extern JSClass folder_class; +extern JSClass control_class; +extern JSClass area_class; +extern JSClass unit_class; + +extern JSExtendedClass unit_class_ex; +extern JSExtendedClass file_class_ex; +extern JSExtendedClass sqlite_db_ex; diff --git a/JSGlobalFuncs.h b/JSGlobalFuncs.h new file mode 100644 index 00000000..9c8bfa67 --- /dev/null +++ b/JSGlobalFuncs.h @@ -0,0 +1,123 @@ +#pragma once + +#include "js32.h" +#include "JSCore.h" +#include "JSGame.h" +#include "JSMenu.h" +#include "JSHash.h" + +#include "JSFile.h" +#include "JSFileTools.h" +#include "JSDirectory.h" +#include "JSSQLite.h" +#include "JSSandbox.h" +#include "JSScreenHook.h" +#include "JSParty.h" +#include "JSArea.h" +#include "JSPresetUnit.h" +#include "JSUnit.h" +#include "JSScript.h" +#include "JSRoom.h" + +static JSFunctionSpec global_funcs[] = { + // "get" functions + {"getUnit", unit_getUnit, 1}, + {"getPath", my_getPath, 0}, + {"getCollision", my_getCollision, 0}, + {"getMercHP", my_getMercHP, 0}, + {"getCursorType", my_getCursorType, 0}, + {"getSkillByName", my_getSkillByName, 1}, + {"getSkillById", my_getSkillById, 1}, + {"getLocaleString", my_getLocaleString, 1}, + {"getTextSize", my_getTextSize, 2}, + {"getThreadPriority", my_getThreadPriority, 0}, + {"getUIFlag", my_getUIFlag, 1}, + {"getTradeInfo", my_getTradeInfo, 0}, + {"getWaypoint", my_getWaypoint, 1}, + {"getScript", my_getScript, 0}, + {"getRoom", my_getRoom, 0}, + {"getParty", my_getParty, 0}, + {"getPresetUnit", my_getPresetUnit, 0}, + {"getPresetUnits", my_getPresetUnits, 0}, + {"getArea", my_getArea, 0}, + {"getBaseStat", my_getBaseStat, 0}, + {"getControl", my_getControl, 0}, + {"getPlayerFlag", my_getPlayerFlag, 2}, + {"getTickCount", my_getTickCount, 0}, + {"getInteractedNPC", my_getInteractedNPC, 0}, + {"getIsTalkingNPC", my_getIsTalkingNPC, 0}, + + // utility functions that don't have anything to do with the game + {"print", my_print, 1}, + {"delay", my_delay, 1}, + {"load", my_load, 1}, + {"isIncluded", my_isIncluded, 1}, + {"include", my_include, 1}, + {"stop", my_stop, 0}, + {"rand", my_rand, 0}, + {"sendCopyData", my_sendCopyData, 4}, + {"sendDDE", my_sendDDE, 0}, + {"keystate", my_keystate, 0}, + {"addEventListener", my_addEventListener, 2}, + {"removeEventListener", my_removeEventListener, 2}, + {"clearEvent", my_clearEvent, 1}, + {"clearAllEvents", my_clearAllEvents, 0}, + {"js_strict", my_js_strict, 0}, + {"version", my_version, 0}, + {"scriptBroadcast", my_scriptBroadcast, 1}, + {"sqlite_version", my_sqlite_version, 0}, + {"sqlite_memusage", my_sqlite_memusage, 0}, + {"dopen", my_openDir, 1}, + {"debugLog", my_debugLog, 1}, + {"showConsole", my_showConsole, 0}, + {"hideConsole", my_hideConsole, 0}, + + // out of game functions + {"login", my_login, 1}, +// {"createCharacter", my_createCharacter, 4}, // this function is not finished + {"selectCharacter", my_selectChar, 1}, + {"createGame", my_createGame, 3}, + {"joinGame", my_joinGame, 2}, + {"addProfile", my_addProfile, 6}, + {"getLocation", my_getOOGLocation, 0}, + {"loadMpq", my_loadMpq, 1}, + + // game functions that don't have anything to do with gathering data + {"submitItem", my_submitItem, 0}, + {"getMouseCoords", my_getMouseCoords, 1}, + {"copyUnit", my_copyUnit, 1}, + {"clickMap", my_clickMap, 3}, + {"acceptTrade", my_acceptTrade, 0}, + {"beep", my_beep, 0}, + {"clickItem", my_clickItem, 0}, + {"getDistance", my_getDistance, 2}, + {"gold", my_gold, 1}, + {"checkCollision", my_checkCollision, 2}, + {"playSound", my_playSound, 1}, + {"quit", my_quit, 0}, + {"quitGame", my_quitGame, 0}, + {"say", my_say, 1}, + {"clickParty", my_clickParty, 1}, + {"weaponSwitch", my_weaponSwitch, 0}, + {"transmute", my_transmute, 0}, + {"useStatPoint", my_useStatPoint, 1}, + {"useSkillPoint", my_useSkillPoint, 1}, + {"takeScreenshot", my_takeScreenshot, 0}, + + // drawing functions + {"screenToAutomap", screenToAutomap, 1}, + {"automapToScreen", automapToScreen, 1}, + + // hash functions + {"md5", my_md5, 1}, + {"sha1", my_sha1, 1}, + {"sha256", my_sha256, 1}, + {"sha384", my_sha384, 1}, + {"sha512", my_sha512, 1}, + {"md5_file", my_md5_file, 1}, + {"sha1_file", my_sha1_file, 1}, + {"sha256_file", my_sha256_file, 1}, + {"sha384_file", my_sha384_file, 1}, + {"sha512_file", my_sha512_file, 1}, + {0} +}; diff --git a/JSHash.cpp b/JSHash.cpp new file mode 100644 index 00000000..fec6ccd8 --- /dev/null +++ b/JSHash.cpp @@ -0,0 +1,160 @@ +#include "JSHash.h" +#include "Hash.h" +#include "File.h" +#include "D2BS.h" + +JSAPI_FUNC(my_md5) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* result = md5(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_InternString(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha1) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* result = sha1(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_InternString(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha256) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* result = sha256(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_InternString(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha384) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* result = sha384(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_InternString(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha512) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* result = sha512(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_InternString(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_md5_file) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* file = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!(file && file[0] && isValidPath(file))) + THROW_ERROR(cx, "Invalid file path!"); + + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, _MAX_FNAME+_MAX_PATH, "%s\\%s", Vars.szScriptPath, file); + + char* result = md5_file(path); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha1_file) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* file = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!(file && file[0] && isValidPath(file))) + THROW_ERROR(cx, "Invalid file path!"); + + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, _MAX_FNAME+_MAX_PATH, "%s\\%s", Vars.szScriptPath, file); + + char* result = sha1_file(path); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha256_file) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* file = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!(file && file[0] && isValidPath(file))) + THROW_ERROR(cx, "Invalid file path!"); + + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, _MAX_FNAME+_MAX_PATH, "%s\\%s", Vars.szScriptPath, file); + + char* result = sha256_file(path); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha384_file) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* file = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!(file && file[0] && isValidPath(file))) + THROW_ERROR(cx, "Invalid file path!"); + + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, _MAX_FNAME+_MAX_PATH, "%s\\%s", Vars.szScriptPath, file); + + char* result = sha384_file(path); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, result)); + delete result; + return JS_TRUE; +} + +JSAPI_FUNC(my_sha512_file) +{ + if(argc != 1) + THROW_ERROR(cx, "Invalid arguments"); + + char* file = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!(file && file[0] && isValidPath(file))) + THROW_ERROR(cx, "Invalid file path!"); + + char path[_MAX_FNAME+_MAX_PATH]; + sprintf_s(path, _MAX_FNAME+_MAX_PATH, "%s\\%s", Vars.szScriptPath, file); + + char* result = sha512_file(path); + if(result && result[0]) + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, result)); + delete result; + return JS_TRUE; +} + diff --git a/JSHash.h b/JSHash.h new file mode 100644 index 00000000..b13c46f0 --- /dev/null +++ b/JSHash.h @@ -0,0 +1,14 @@ +#pragma once + +#include "js32.h" + +JSAPI_FUNC(my_md5); +JSAPI_FUNC(my_sha1); +JSAPI_FUNC(my_sha256); +JSAPI_FUNC(my_sha384); +JSAPI_FUNC(my_sha512); +JSAPI_FUNC(my_md5_file); +JSAPI_FUNC(my_sha1_file); +JSAPI_FUNC(my_sha256_file); +JSAPI_FUNC(my_sha384_file); +JSAPI_FUNC(my_sha512_file); diff --git a/JSMenu.cpp b/JSMenu.cpp new file mode 100644 index 00000000..d359a969 --- /dev/null +++ b/JSMenu.cpp @@ -0,0 +1,383 @@ +#include "JSMenu.h" +//#include "Control.h" +#include "JSControl.h" +#include "Constants.h" +#include "Helpers.h" +#include "D2BS.h" + +JSAPI_FUNC(my_login) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + char file[_MAX_FNAME+MAX_PATH], *profile = NULL, + mode[256], username[48], password[256], gateway[256], charname[24], + difficulty[10], maxLoginTime[10], maxCharTime[10]; + + int loginTime = 0, charTime = 0, SPdifficulty = 0; + bool copiedProfile = false; + + if(!JSVAL_IS_STRING(argv[0])) + { + if(Vars.szProfile != NULL) + { + int size = strlen(Vars.szProfile)+1; + profile = new char[size]; + strcpy_s(profile, size, Vars.szProfile); + copiedProfile = true; + } + else + THROW_ERROR(cx, "Invalid profile specified!"); + } else { + profile = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + strcpy_s(Vars.szProfile, 256, profile); + } + + if(!profile) THROW_ERROR(cx, "Could not get profile!"); + if(!ProfileExists(profile)) THROW_ERROR(cx, "Profile does not exist!"); + + sprintf_s(file, sizeof(file), "%sd2bs.ini", Vars.szPath); + + GetPrivateProfileString(profile, "mode", "single", mode, sizeof(mode), file); + GetPrivateProfileString(profile, "character", "ERROR", charname, sizeof(charname), file); + GetPrivateProfileString(profile, "spdifficulty", "0", difficulty, sizeof(difficulty), file); + GetPrivateProfileString(profile, "username", "ERROR", username, sizeof(username), file); + GetPrivateProfileString(profile, "password", "ERROR", password, sizeof(password), file); + GetPrivateProfileString(profile, "gateway", "ERROR", gateway, sizeof(gateway), file); + + if(copiedProfile) + delete[] profile; + + GetPrivateProfileString("settings", "MaxLoginTime", "5", maxLoginTime, sizeof(maxLoginTime), file); + GetPrivateProfileString("settings", "MaxCharSelectTime", "5", maxCharTime, sizeof(maxCharTime), file); + + char* errorMsg = ""; + loginTime = abs(atoi(maxLoginTime) * 1000); + charTime = abs(atoi(maxCharTime) * 1000); + SPdifficulty = atoi(difficulty); + Control* pControl = NULL; + int location = 0; + int timeout = 0; + bool loginComplete = FALSE, skippedToBnet = TRUE; + Vars.bBlockKeys = Vars.bBlockMouse = TRUE; + + char ipaddress[16] = ""; + /* + clickedOnce is needed because, when in OOG_OTHER_MULTIPLAYER + the clickControl () is done twice and the second time it is + failing because the button is not there anymore. + */ + int clickedOnce = false; + + while(!loginComplete) + { + location = OOG_GetLocation(); + switch(location) + { + case OOG_D2SPLASH: + clickControl(*p_D2WIN_FirstControl); + break; + case OOG_CHAR_SELECT: + if (!OOG_SelectCharacter(charname)) + errorMsg = "Invalid character name"; + break; + case OOG_MAIN_MENU: + if (tolower(mode[0])== 's') + if(!clickControl(findControl(6, (char *)NULL, -1, 264,324,272,35))) + errorMsg = "Failed to click the Single button?"; + if(tolower(mode[0])== 'b') + { + OOG_SelectGateway(gateway, 256); + if(!clickControl(findControl(6, (char *)NULL, -1, 264, 366, 272, 35))) + errorMsg = "Failed to click the 'Battle.net' button?"; + } + if(tolower(mode[0])== 'o') + { + if(!clickControl(findControl(6, (char *)NULL, -1, 264, 433, 272, 35))) + errorMsg = "Failed to click the 'Other Multiplayer' button?"; + else + skippedToBnet = FALSE; + } + break; + case OOG_LOGIN: + if((tolower(mode[0])== 's') || ((tolower(mode[0]) == 'o') && skippedToBnet)) + { + if(!clickControl(findControl(6, "EXIT", -1,33,572,128,35))) + errorMsg = "Failed to click the exit button?"; + break; + } + pControl = findControl(1, (char *)NULL, -1, 322, 342, 162, 19); + if(pControl) + SetControlText(pControl, username); + else + errorMsg = "Failed to set the 'Username' text-edit box."; + // Password text-edit box + pControl = findControl(1, (char *)NULL, -1, 322, 396, 162, 19); + if(pControl) + SetControlText(pControl, password); + else + errorMsg = "Failed to set the 'Password' text-edit box."; + + pControl = findControl(6, (char *)NULL, -1, 264, 484, 272, 35); + if(pControl) + if(!clickControl(pControl)) + errorMsg ="Failed to click the 'Log in' button?"; + timeout++; + break; + case OOG_DIFFICULTY: + switch(SPdifficulty) + { + case 0: + // normal button + if(!clickControl(findControl(6, (char *)NULL, -1, 264, 297, 272, 35))) + errorMsg ="Failed to click the 'Normal Difficulty' button?"; + break; + case 1: + // nightmare button + if(!clickControl(findControl(6, (char *)NULL, -1, 264, 340, 272, 35))) + errorMsg = "Failed to click the 'Nightmare Difficulty' button?"; + break; + case 2: + // hell button + if(!clickControl(findControl(6, (char *)NULL, -1, 264, 383, 272, 35))) + errorMsg = "Failed to click the 'Hell Difficulty' button?"; + break; + default: + errorMsg = "Invalid single player difficulty level specified!"; + break; + } + case OOG_OTHER_MULTIPLAYER: + // Open Battle.net + if (tolower(mode[18])== 'o') + if(!clickControl(findControl(6, (char *)NULL, -1, 264, 310, 272, 35))) + errorMsg = "Failed to click the 'Open Battle.net' button?"; + // TCP/IP Game + if (tolower(mode[18])== 't') + if(!clickControl(findControl(6, (char *)NULL, -1, 264,350,272,35)) && !clickedOnce) + errorMsg = "Failed to click the 'TCP/IP Game' button?"; + else + clickedOnce = true; + + break; + case OOG_TCP_IP: + if (tolower(mode[25])== 'h') + if(!clickControl(findControl(6, (char *)NULL, -1,265,206,272,35))) + errorMsg = "Failed to click the 'Host Game' button?"; + if (tolower(mode[25])== 'j') + if(!clickControl(findControl(6, (char *)NULL, -1,265,264,272,35))) + errorMsg = "Failed to click the 'Join Game' button?"; + break; + case OOG_ENTER_IP_ADDRESS: + strncpy_s (ipaddress, &mode[30], (size_t)16); + + if (_strcmpi(ipaddress, "")) { + pControl = findControl(1, (char *)NULL, -1, 300, 268, -1, -1); + if(pControl) { + SetControlText(pControl, ipaddress); + + // Click the OK button + if(!clickControl(findControl(6, (char *)NULL, -1, 421, 337, 96, 32))) { + errorMsg = "Failed to click the OK button"; + } + } else + errorMsg = "Failed to find the 'Host IP Address' text-edit box."; + } else + errorMsg = "Could not get the IP address from the profile in the d2bs.ini file."; + + break; + case OOG_MAIN_MENU_CONNECTING: + case OOG_CHARACTER_SELECT_PLEASE_WAIT: + case OOG_PLEASE_WAIT: + case OOG_GATEWAY: + case OOG_CHARACTER_SELECT_NO_CHARS: + case OOG_NONE: + timeout++; + break; + case OOG_LOBBY: + case OOG_INLINE: + case OOG_CHAT: + case OOG_CREATE: + case OOG_JOIN: + case OOG_LADDER: + case OOG_CHANNEL: + case OOG_GAME_EXIST: + case OOG_GAME_DOES_NOT_EXIST: + loginComplete=TRUE; + break; + case OOG_UNABLE_TO_CONNECT: + errorMsg = "Unable to connect"; + break; + case OOG_CDKEY_IN_USE: + errorMsg = "CD-Key in use"; + break; + case OOG_LOGIN_ERROR: + errorMsg = "Bad account or password"; + break; + case OOG_REALM_DOWN: + errorMsg = "Realm Down"; + break; + default: + errorMsg = "Unhandled login location"; + break; + } + + if(_strcmpi(errorMsg, "")) + { + Vars.bBlockKeys = Vars.bBlockMouse = FALSE; + THROW_ERROR(cx, errorMsg); + break; + } + + if((timeout*100) > loginTime) + { + Vars.bBlockKeys = Vars.bBlockMouse = FALSE; + THROW_ERROR(cx, "login time out"); + break; + } + + if(ClientState() == ClientStateInGame) + loginComplete = TRUE; + + Sleep(100); + } + Vars.bBlockKeys = Vars.bBlockMouse = FALSE; + + return JS_TRUE; +} + +JSAPI_FUNC(my_selectChar) +{ + if(argc != 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "Invalid parameters specified to selectCharacter"); + + char* profile = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!ProfileExists(profile)) + THROW_ERROR(cx, "Invalid profile specified"); + char charname[24], file[_MAX_FNAME+MAX_PATH]; + sprintf_s(file, sizeof(file), "%sd2bs.ini", Vars.szPath); + GetPrivateProfileString(profile, "character", "ERROR", charname, sizeof(charname), file); + + *rval = JSVAL_TO_BOOLEAN(OOG_SelectCharacter(charname)); + return JS_TRUE; +} + +JSAPI_FUNC(my_createGame) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + char *name = NULL, *pass = NULL; + int32 diff = 3; + if(!JS_ConvertArguments(cx, argc, argv, "s/si", &name, &pass, &diff)) + { + JS_ReportError(cx, "Invalid arguments specified to createGame"); + return JS_FALSE; + } + if(!pass) + pass = ""; + + if(strlen(name) > 15 || strlen(pass) > 15) + THROW_ERROR(cx, "Invalid game name or password length"); + + if(!OOG_CreateGame(name, pass, diff)) + THROW_ERROR(cx, "createGame failed"); + + return JS_TRUE; +} + +JSAPI_FUNC(my_joinGame) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + char *name = NULL, *pass = NULL; + if(!JS_ConvertArguments(cx, argc, argv, "s/s", &name, &pass)) + { + JS_ReportError(cx, "Invalid arguments specified to createGame"); + return JS_FALSE; + } + if(!pass) + pass = ""; + + if(strlen(name) > 15 || strlen(pass) > 15) + THROW_ERROR(cx, "Invalid game name or password length"); + + if(!OOG_JoinGame(name, pass)) + THROW_ERROR(cx, "joinGame failed"); + + return JS_TRUE; +} + +JSAPI_FUNC(my_addProfile) +{ + // validate the args... + char *profile, *mode, *gateway, *username, *password, *charname; + profile = mode = gateway = username = password = charname = NULL; + int spdifficulty = 3; + if(argc < 6 || argc > 7) + THROW_ERROR(cx, "Invalid arguments passed to addProfile"); + + char** args[] = {&profile, &mode, &gateway, &username, &password, &charname}; + for(uintN i = 0; i < 6; i++) + { + if(!JSVAL_IS_STRING(argv[i])) + { + THROW_ERROR(cx, "Invalid argument passed to addProfile"); + } + else + *args[i] = JS_GetStringBytes(JSVAL_TO_STRING(argv[i])); + } + + for(int i = 0; i < 6; i++) + { + if(!(*args[i])) + THROW_ERROR(cx, "Failed to convert string"); + } + + if(argc == 7) + spdifficulty = JSVAL_TO_INT(argv[6]); + + if(spdifficulty > 3 || spdifficulty < 0) + THROW_ERROR(cx, "Invalid argument passed to addProfile"); + + char file[_MAX_FNAME+_MAX_PATH]; + + sprintf_s(file, sizeof(file), "%sd2bs.ini", Vars.szPath); + if(!ProfileExists(*args[0])) + { + char settings[600] = ""; + sprintf_s(settings, sizeof(settings), + "mode=%s\tgateway=%s\tusername=%s\tpassword=%s\tcharacter=%s\tspdifficulty=%d\t", + mode, gateway, username, password, charname, spdifficulty); + + StringReplace(settings, '\t', '\0', 600); + WritePrivateProfileSection(*args[0], settings, file); + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getOOGLocation) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + *rval = INT_TO_JSVAL(OOG_GetLocation()); + + return JS_TRUE; +} + +JSAPI_FUNC(my_createCharacter) +{ + if(ClientState() != ClientStateMenu) + return JS_TRUE; + + char* name = NULL; + int32 type = -1; + JSBool hc = JS_FALSE, ladder = JS_FALSE; + if(!JS_ConvertArguments(cx, argc, argv, "si/bb", &name, &type, &hc, &ladder)) + return JS_FALSE; + + *rval = BOOLEAN_TO_JSVAL(!!OOG_CreateCharacter(name, type, !!hc, !!ladder)); + return JS_TRUE; +} \ No newline at end of file diff --git a/JSMenu.h b/JSMenu.h new file mode 100644 index 00000000..14357424 --- /dev/null +++ b/JSMenu.h @@ -0,0 +1,16 @@ +#pragma once +#ifndef __JSMENU_H__ +#define __JSMENU_H__ + +#include "js32.h" + +JSAPI_FUNC(my_getControl); +JSAPI_FUNC(my_login); +JSAPI_FUNC(my_selectChar); +JSAPI_FUNC(my_createGame); +JSAPI_FUNC(my_joinGame); +JSAPI_FUNC(my_addProfile); +JSAPI_FUNC(my_getOOGLocation); +JSAPI_FUNC(my_createCharacter); + +#endif diff --git a/JSParty.cpp b/JSParty.cpp new file mode 100644 index 00000000..30ed0317 --- /dev/null +++ b/JSParty.cpp @@ -0,0 +1,102 @@ +#include "JSParty.h" +#include "D2Structs.h" +#include "D2Helpers.h" +#include "D2Ptrs.h" +#include "JSGlobalClasses.h" + +EMPTY_CTOR(party) + +JSAPI_PROP(party_getProperty) +{ + RosterUnit* pUnit = (RosterUnit*)JS_GetPrivate(cx, obj); + + if(!pUnit) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) + { + case PARTY_NAME: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pUnit->szName)); + break; + case PARTY_X: + *vp = INT_TO_JSVAL(pUnit->Xpos); + break; + case PARTY_Y: + *vp = INT_TO_JSVAL(pUnit->Ypos); + break; + case PARTY_AREA: + *vp = INT_TO_JSVAL(pUnit->dwLevelId); + break; + case PARTY_GID: + JS_NewNumberValue(cx, (jsdouble)pUnit->dwUnitId, vp); + //*vp = INT_TO_JSVAL(pUnit->dwUnitId); + break; + case PARTY_LIFE: + *vp = INT_TO_JSVAL(pUnit->dwPartyLife); + break; + case PARTY_CLASSID: + *vp = INT_TO_JSVAL(pUnit->dwClassId); + break; + case PARTY_LEVEL: + *vp = INT_TO_JSVAL(pUnit->wLevel); + break; + case PARTY_FLAG: + *vp = INT_TO_JSVAL(pUnit->dwPartyFlags); + break; + case PARTY_ID: + *vp = INT_TO_JSVAL(pUnit->wPartyId); + break; + default: + break; + } + return JS_TRUE; +} + +JSAPI_FUNC(party_getNext) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + RosterUnit *pUnit = (RosterUnit*)JS_GetPrivate(cx, obj); + + if(!pUnit) + { + *rval = INT_TO_JSVAL(0); + return JS_TRUE; + } + + pUnit = pUnit->pNext; + + if(pUnit) + { + JS_SetPrivate(cx, obj, pUnit); + *rval = OBJECT_TO_JSVAL(obj); + } + else + { + JS_ClearScope(cx, obj); + if(JS_ValueToObject(cx, JSVAL_NULL, &obj)) + *rval = INT_TO_JSVAL(0); + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_getParty) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + RosterUnit* pUnit = *p_D2CLIENT_PlayerUnitList; + + if(!pUnit) + return JS_TRUE; + + JSObject* jsUnit = BuildObject(cx, &party_class, party_methods, party_props, pUnit); + if(!jsUnit) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(jsUnit); + + return JS_TRUE; +} diff --git a/JSParty.h b/JSParty.h new file mode 100644 index 00000000..632b32aa --- /dev/null +++ b/JSParty.h @@ -0,0 +1,47 @@ +#ifndef PARTY_H +#define PARTY_H + +#include "js32.h" + +CLASS_CTOR(party); + +JSAPI_PROP(party_getProperty); + +JSAPI_FUNC(party_getNext); + +JSAPI_FUNC(my_getParty); + +enum party_tinyid { + PARTY_AREA, + PARTY_X, + PARTY_Y, + PARTY_GID, + PARTY_LIFE, + PARTY_NAME, + PARTY_FLAG, + PARTY_ID, + PARTY_CLASSID, + PARTY_LEVEL +}; + + +static JSPropertySpec party_props[] = { + {"x", PARTY_X, JSPROP_PERMANENT_VAR, party_getProperty}, + {"y", PARTY_Y, JSPROP_PERMANENT_VAR, party_getProperty}, + {"area", PARTY_AREA, JSPROP_PERMANENT_VAR, party_getProperty}, + {"gid", PARTY_GID, JSPROP_PERMANENT_VAR, party_getProperty}, + {"life", PARTY_LIFE, JSPROP_PERMANENT_VAR, party_getProperty}, + {"partyflag", PARTY_FLAG, JSPROP_PERMANENT_VAR, party_getProperty}, + {"partyid", PARTY_ID, JSPROP_PERMANENT_VAR, party_getProperty}, + {"name", PARTY_NAME, JSPROP_PERMANENT_VAR, party_getProperty}, + {"classid", PARTY_CLASSID, JSPROP_PERMANENT_VAR, party_getProperty}, + {"level", PARTY_LEVEL, JSPROP_PERMANENT_VAR, party_getProperty}, + {0}, +}; + +static JSFunctionSpec party_methods[] = { + {"getNext", party_getNext, 0}, + {0}, +}; + +#endif \ No newline at end of file diff --git a/JSPresetUnit.cpp b/JSPresetUnit.cpp new file mode 100644 index 00000000..764df1a2 --- /dev/null +++ b/JSPresetUnit.cpp @@ -0,0 +1,220 @@ +#include "JSPresetUnit.h" + +#include "D2Ptrs.h" +#include "CriticalSections.h" +#include "D2Helpers.h" + +EMPTY_CTOR(presetunit) + +void presetunit_finalize(JSContext *cx, JSObject *obj) +{ + myPresetUnit *pUnit = (myPresetUnit*)JS_GetPrivate(cx, obj); + + if(pUnit) + { + JS_SetPrivate(cx, obj, NULL); + delete pUnit; + } +} + +JSAPI_PROP(presetunit_getProperty) +{ + myPresetUnit* pUnit = (myPresetUnit*)JS_GetPrivate(cx, obj); + + if(!pUnit) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) + { + case PUNIT_TYPE: + *vp = INT_TO_JSVAL(pUnit->dwType); + break; + case PUNIT_ROOMX: + *vp = INT_TO_JSVAL(pUnit->dwRoomX); + break; + case PUNIT_ROOMY: + *vp = INT_TO_JSVAL(pUnit->dwRoomY); + break; + case PUNIT_X: + *vp = INT_TO_JSVAL(pUnit->dwPosX); + break; + case PUNIT_Y: + *vp = INT_TO_JSVAL(pUnit->dwPosY); + break; + case PUNIT_ID: + *vp = INT_TO_JSVAL(pUnit->dwId); + break; + case PUINT_LEVEL: + *vp = INT_TO_JSVAL(pUnit->dwLevel); + default: + break; + } + return JS_TRUE; +} + +JSAPI_FUNC(my_getPresetUnits) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + uint32 levelId; + JS_ValueToECMAUint32(cx, argv[0], &levelId); + Level* pLevel = GetLevel(levelId); + + if(!pLevel) + THROW_ERROR(cx, "getPresetUnits failed, couldn't access the level!"); + + uint nClassId = NULL; + uint nType = NULL; + + if(argc >= 2) + nType = JSVAL_TO_INT(argv[1]); + if(argc >= 3) + nClassId = JSVAL_TO_INT(argv[2]); + + CriticalRoom cRoom; + cRoom.EnterSection(); + + bool bAddedRoom = FALSE; + DWORD dwArrayCount = NULL; + + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + JS_AddRoot(&pReturnArray); + for(Room2 *pRoom = pLevel->pRoom2First; pRoom; pRoom = pRoom->pRoom2Next) + { + bAddedRoom = FALSE; + + if(!pRoom->pPreset) + { + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + bAddedRoom = TRUE; + } + + for(PresetUnit* pUnit = pRoom->pPreset; pUnit; pUnit = pUnit->pPresetNext) + { + // Does it fit? + if((nType == NULL || pUnit->dwType == nType) && (nClassId == NULL || pUnit->dwTxtFileNo == nClassId)) + { + myPresetUnit* mypUnit = new myPresetUnit; + + mypUnit->dwPosX = pUnit->dwPosX; + mypUnit->dwPosY = pUnit->dwPosY; + mypUnit->dwRoomX = pRoom->dwPosX; + mypUnit->dwRoomY = pRoom->dwPosY; + mypUnit->dwType = pUnit->dwType; + mypUnit->dwId = pUnit->dwTxtFileNo; + mypUnit->dwLevel = levelId; + + JSObject* unit = BuildObject(cx, &presetunit_class, NULL, presetunit_props, mypUnit); + if(!unit) + { + delete mypUnit; + THROW_ERROR(cx, "Failed to build object?"); + } + + jsval a = OBJECT_TO_JSVAL(unit); + JS_SetElement(cx, pReturnArray, dwArrayCount, &a); + + dwArrayCount++; + } + } + + if(bAddedRoom) + { + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + bAddedRoom = FALSE; + } + } + + *rval = OBJECT_TO_JSVAL(pReturnArray); + JS_RemoveRoot(&pReturnArray); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getPresetUnit) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + uint32 levelId; + JS_ValueToECMAUint32(cx, argv[0], &levelId); + Level* pLevel = GetLevel(levelId); + + if(!pLevel) + THROW_ERROR(cx, "getPresetUnits failed, couldn't access the level!"); + + DWORD nClassId = NULL; + DWORD nType = NULL; + + if(argc >= 2) + nType = JSVAL_TO_INT(argv[1]); + if(argc >= 3) + nClassId = JSVAL_TO_INT(argv[2]); + + CriticalRoom cRoom; + cRoom.EnterSection(); + + bool bAddedRoom = FALSE; + + for(Room2 *pRoom = pLevel->pRoom2First; pRoom; pRoom = pRoom->pRoom2Next) { + + bAddedRoom = FALSE; + + if(!pRoom->pRoom1) + { + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + bAddedRoom = TRUE; + } + + for(PresetUnit* pUnit = pRoom->pPreset; pUnit; pUnit = pUnit->pPresetNext) + { + // Does it fit? + if((nType == NULL || pUnit->dwType == nType) && (nClassId == NULL || pUnit->dwTxtFileNo == nClassId)) + { + // Yes it fits! Return it + myPresetUnit* mypUnit = new myPresetUnit; + + mypUnit->dwPosX = pUnit->dwPosX; + mypUnit->dwPosY = pUnit->dwPosY; + mypUnit->dwRoomX = pRoom->dwPosX; + mypUnit->dwRoomY = pRoom->dwPosY; + mypUnit->dwType = pUnit->dwType; + mypUnit->dwId = pUnit->dwTxtFileNo; + mypUnit->dwLevel = levelId; + + JSObject* obj = BuildObject(cx, &presetunit_class, NULL, presetunit_props, mypUnit); + if(!obj) + { + delete mypUnit; + THROW_ERROR(cx, "Failed to create presetunit object"); + } + + *rval = OBJECT_TO_JSVAL(obj); + return JS_TRUE; + } + } + + if(bAddedRoom) + { + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + bAddedRoom = FALSE; + } + } + + *rval = JSVAL_FALSE; + + return JS_TRUE; +} diff --git a/JSPresetUnit.h b/JSPresetUnit.h new file mode 100644 index 00000000..c9df2d38 --- /dev/null +++ b/JSPresetUnit.h @@ -0,0 +1,47 @@ +#ifndef PRESETUNIT_H +#define PRESETUNIT_H + +#include +#include "js32.h" + +CLASS_CTOR(presetunit); + +void presetunit_finalize(JSContext *cx, JSObject *obj); +JSAPI_PROP(presetunit_getProperty); + +JSAPI_FUNC(my_getPresetUnit); +JSAPI_FUNC(my_getPresetUnits); + +enum presetunit_tinyid { + PUNIT_TYPE, // 0 + PUNIT_ROOMX, // 1 + PUNIT_ROOMY, // 2 + PUNIT_X, // 3 + PUNIT_Y, // 4 + PUNIT_ID, // 5 + PUINT_LEVEL // 6 +}; + +static JSPropertySpec presetunit_props[] = { + {"type", PUNIT_TYPE, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {"roomx", PUNIT_ROOMX, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {"roomy", PUNIT_ROOMY, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {"x", PUNIT_X, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {"y", PUNIT_Y, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {"id", PUNIT_ID, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {"level", PUINT_LEVEL, JSPROP_PERMANENT_VAR, presetunit_getProperty}, + {0}, +}; + +struct myPresetUnit +{ + DWORD dwType; + DWORD dwRoomX; + DWORD dwRoomY; + DWORD dwPosX; + DWORD dwPosY; + DWORD dwId; + DWORD dwLevel; +}; + +#endif \ No newline at end of file diff --git a/JSRoom.cpp b/JSRoom.cpp new file mode 100644 index 00000000..da87f8c3 --- /dev/null +++ b/JSRoom.cpp @@ -0,0 +1,515 @@ +#include "JSRoom.h" +#include "CriticalSections.h" +#include "JSPresetUnit.h" +//#include "JSUnit.h" +//#include "D2Helpers.h" +#include "D2Ptrs.h" +//#include "Room.h" + +EMPTY_CTOR(room) + +JSAPI_PROP(room_getProperty) +{ + Room2 *pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + + if(!pRoom2) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) + { + case ROOM_NUM: + if(pRoom2->dwPresetType != 2) + *vp = INT_TO_JSVAL(-1); + else if(pRoom2->pType2Info) + *vp = INT_TO_JSVAL(pRoom2->pType2Info->dwRoomNumber); + break; + case ROOM_XPOS: + *vp = INT_TO_JSVAL(pRoom2->dwPosX); + break; + case ROOM_YPOS: + *vp = INT_TO_JSVAL(pRoom2->dwPosY); + break; + case ROOM_XSIZE: + *vp = INT_TO_JSVAL(pRoom2->dwSizeX * 5); + break; + case ROOM_YSIZE: + *vp = INT_TO_JSVAL(pRoom2->dwSizeY * 5); + break; + case ROOM_AREA: case ROOM_LEVEL: + if(pRoom2->pLevel) + *vp = INT_TO_JSVAL(pRoom2->pLevel->dwLevelNo); + break; + + case ROOM_CORRECTTOMB: + if(pRoom2->pLevel && pRoom2->pLevel->pMisc && pRoom2->pLevel->pMisc->dwStaffTombLevel) + *vp = INT_TO_JSVAL(pRoom2->pLevel->pMisc->dwStaffTombLevel); + break; + + default: + break; + } + + return JS_TRUE; +} + +JSAPI_FUNC(room_getNext) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + pRoom2 = pRoom2->pRoom2Next; + + if(!pRoom2) + { + JS_ClearScope(cx, obj); + if(JS_ValueToObject(cx, JSVAL_NULL, &obj)) + *rval = JSVAL_FALSE; + } + else + { + JS_SetPrivate(cx, obj, pRoom2); + *rval = JSVAL_TRUE; + } + + return JS_TRUE; +} + +JSAPI_FUNC(room_getPresetUnits) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2) + return JS_TRUE; + + DWORD nType = NULL; + DWORD nClass = NULL; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + nType = JSVAL_TO_INT(argv[0]); + if(argc > 1 && JSVAL_IS_INT(argv[1])) + nClass = JSVAL_TO_INT(argv[1]); + + bool bAdded = FALSE; + DWORD dwArrayCount = NULL; + + CriticalRoom cRoom; + cRoom.EnterSection(); + + if(!pRoom2->pRoom1) + { + bAdded = TRUE; + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + } + + + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + JS_AddRoot(&pReturnArray); + for(PresetUnit* pUnit = pRoom2->pPreset; pUnit; pUnit = pUnit->pPresetNext) + { + if((pUnit->dwType == nType || nType == NULL) && (pUnit->dwTxtFileNo == nClass || nClass == NULL)) + { + myPresetUnit* mypUnit = new myPresetUnit; + + mypUnit->dwPosX = pUnit->dwPosX; + mypUnit->dwPosY = pUnit->dwPosY; + mypUnit->dwRoomX = pRoom2->dwPosX; + mypUnit->dwRoomY = pRoom2->dwPosY; + mypUnit->dwType = pUnit->dwType; + mypUnit->dwId = pUnit->dwTxtFileNo; + + JSObject* jsUnit = BuildObject(cx, &presetunit_class, NULL, presetunit_props, mypUnit); + if(!jsUnit) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + jsval a = OBJECT_TO_JSVAL(jsUnit); + JS_SetElement(cx, pReturnArray, dwArrayCount, &a); + + dwArrayCount++; + } + } + + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + + *rval = OBJECT_TO_JSVAL(pReturnArray); + JS_RemoveRoot(&pReturnArray); + + return JS_TRUE; +} + +JSAPI_FUNC(room_getCollision) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2) + return JS_TRUE; + + JSObject* jsobjy = JS_NewArrayObject(cx, NULL, NULL); + JS_AddRoot(&jsobjy); + if(!jsobjy) + return JS_TRUE; + + bool bAdded = FALSE; + CollMap* pCol = NULL; + + CriticalRoom cRoom; + cRoom.EnterSection(); + + if(!pRoom2->pRoom1) + { + bAdded = TRUE; + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + } + + if(pRoom2->pRoom1) + pCol = pRoom2->pRoom1->Coll; + + if(!pCol) + { + JS_RemoveRoot(&jsobjy); + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + return JS_TRUE; + } + + int x = pCol->dwPosGameX - pRoom2->pLevel->dwPosX * 5; + int y = pCol->dwPosGameY - pRoom2->pLevel->dwPosY * 5; + int nCx = pCol->dwSizeGameX; + int nCy = pCol->dwSizeGameY; + + int nLimitX = x + nCx; + int nLimitY = y + nCy; + + int nCurrentArrayY = NULL; + + WORD* p = pCol->pMapStart; + + for(int j = y; j < nLimitY; j++) + { + JSObject* jsobjx = JS_NewArrayObject(cx, NULL, NULL); + + int nCurrentArrayX = NULL; + + for (int i = x; i < nLimitX; i++) + { + jsval nNode = INT_TO_JSVAL(*p); + + if(!JS_SetElement(cx, jsobjx, nCurrentArrayX, &nNode)) + { + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + JS_RemoveRoot(&jsobjy); + return JS_TRUE; + } + + nCurrentArrayX ++; + p++; + } + + + jsval jsu = OBJECT_TO_JSVAL(jsobjx); + + if(!JS_SetElement(cx, jsobjy, nCurrentArrayY, &jsu)) + { + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + JS_RemoveRoot(&jsobjy); + return JS_TRUE; + } + nCurrentArrayY++; + } + + + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + + *rval=OBJECT_TO_JSVAL(jsobjy); + JS_RemoveRoot(&jsobjy); + return JS_TRUE; +} + +JSAPI_FUNC(room_getNearby) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2) + return JS_TRUE; + + JSObject* jsobj = JS_NewArrayObject(cx, NULL, NULL); + + if(!jsobj) + return JS_TRUE; + + DWORD dwArrayCount = NULL; + + for(UINT i = 0; i < pRoom2->dwRoomsNear; i++) + { + JSObject* jsroom = BuildObject(cx, &room_class, room_methods, room_props, pRoom2->pRoom2Near[i]); + if(!jsroom) + return JS_TRUE; + jsval jsu = OBJECT_TO_JSVAL(jsroom); + + if(!JS_SetElement(cx, jsobj, dwArrayCount, &jsu)) + return JS_TRUE; + + dwArrayCount ++; + } + + *rval = OBJECT_TO_JSVAL(jsobj); + + return JS_TRUE; +} + +// Don't know whether it works or not +JSAPI_FUNC(room_getStat) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2) + return JS_TRUE; + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + jsint nStat = JSVAL_TO_INT(argv[0]); + + bool bAdded = false; + + CriticalRoom cRoom; + cRoom.EnterSection(); + + if(!pRoom2->pRoom1) + { + bAdded = true; + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct,pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + } + + if(!pRoom2->pRoom1) + return JS_TRUE; + + if(nStat == 0) // xStart + *rval = INT_TO_JSVAL(pRoom2->pRoom1->dwXStart); + else if(nStat == 1) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->dwYStart); + else if(nStat == 2) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->dwXSize); + else if(nStat == 3) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->dwYSize); + else if(nStat == 4) + *rval = INT_TO_JSVAL(pRoom2->dwPosX); + else if(nStat == 5) + *rval = INT_TO_JSVAL(pRoom2->dwPosY); + else if(nStat == 6) + *rval = INT_TO_JSVAL(pRoom2->dwSizeX); + else if(nStat == 7) + *rval = INT_TO_JSVAL(pRoom2->dwSizeY); +// else if(nStat == 8) +// *rval = INT_TO_JSVAL(pRoom2->pRoom1->dwYStart); // God knows??!!??!?!?!?! + else if(nStat == 9) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwPosGameX); + else if(nStat == 10) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwPosGameY); + else if(nStat == 11) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwSizeGameX); + else if(nStat == 12) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwSizeGameY); + else if(nStat == 13) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwPosRoomX); + else if(nStat == 14) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwPosGameY); + else if(nStat == 15) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwSizeRoomX); + else if(nStat == 16) + *rval = INT_TO_JSVAL(pRoom2->pRoom1->Coll->dwSizeRoomY); + + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct,pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + + return JS_TRUE; +} + +JSAPI_FUNC(room_getFirst) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2 || !pRoom2->pLevel || !pRoom2->pLevel->pRoom2First ) + return JS_TRUE; + + JSObject* jsroom = BuildObject(cx, &room_class, room_methods, room_props, pRoom2->pLevel->pRoom2First); + if(!jsroom) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(jsroom); + + return JS_TRUE; +} + +JSAPI_FUNC(room_unitInRoom) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2 || argc < 1 || !JSVAL_IS_OBJECT(argv[0])) + return JS_TRUE; + + myUnit* pmyUnit = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + Room1* pRoom1 = D2COMMON_GetRoomFromUnit(pUnit); + + if(!pRoom1 || !pRoom1->pRoom2) + return JS_TRUE; + + *rval = BOOLEAN_TO_JSVAL(!!(pRoom1->pRoom2 == pRoom2)); + + return JS_TRUE; +} + +JSAPI_FUNC(room_reveal) +{ + Room2* pRoom2 = (Room2*)JS_GetPrivate(cx, obj); + if(!pRoom2) + return JS_TRUE; + + CriticalMisc cMisc; + cMisc.EnterSection(); + + BOOL bDrawPresets = false; + if (argc == 1 && JSVAL_IS_BOOLEAN(argv[0])) + bDrawPresets = !!JSVAL_TO_BOOLEAN(argv[0]); + + *rval = BOOLEAN_TO_JSVAL(RevealRoom(pRoom2, bDrawPresets)); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getRoom) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + CriticalRoom cRoom; + cRoom.EnterSection(); + + if(argc == 1 && JSVAL_IS_INT(argv[0])) + { + uint32 levelId; + JS_ValueToECMAUint32(cx, argv[0], &levelId); + if(levelId != 0) // 1 Parameter, AreaId + { + Level* pLevel = GetLevel(levelId); + + if(!pLevel || !pLevel->pRoom2First) + return JS_TRUE; + + JSObject *jsroom = BuildObject(cx, &room_class, room_methods, room_props, pLevel->pRoom2First); + if (!jsroom) + return JS_TRUE; + + *rval=OBJECT_TO_JSVAL(jsroom); + + return JS_TRUE; + } + else if(levelId == 0) + { + Room1* pRoom1 = D2COMMON_GetRoomFromUnit(D2CLIENT_GetPlayerUnit()); + + if(!pRoom1 || !pRoom1->pRoom2) + return JS_TRUE; + + JSObject *jsroom = BuildObject(cx, &room_class, room_methods, room_props, pRoom1->pRoom2); + if (!jsroom) + return JS_TRUE; + *rval=OBJECT_TO_JSVAL(jsroom); + + return JS_TRUE; + } + } + else if(argc == 3 || argc == 2) // area ,x and y + { + Level* pLevel = NULL; + + uint32 levelId; + JS_ValueToECMAUint32(cx, argv[0], &levelId); + + if(argc == 3) + pLevel = GetLevel(levelId); + else if(D2CLIENT_GetPlayerUnit() && D2CLIENT_GetPlayerUnit()->pPath && D2CLIENT_GetPlayerUnit()->pPath->pRoom1 && D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2) + pLevel = D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2->pLevel; + + if(!pLevel || !pLevel->pRoom2First) + return JS_TRUE; + + uint32 nX = NULL; + uint32 nY = NULL; + + if(argc == 2) + { + JS_ValueToECMAUint32(cx, argv[0], &nX); + JS_ValueToECMAUint32(cx, argv[1], &nY); + } + else if(argc == 3) + { + JS_ValueToECMAUint32(cx, argv[1], &nX); + JS_ValueToECMAUint32(cx, argv[2], &nY); + } + + if(!nX || !nY) + return JS_TRUE; + + // Scan for the room with the matching x,y coordinates. + for(Room2* pRoom = pLevel->pRoom2First; pRoom; pRoom = pRoom->pRoom2Next) + { + bool bAdded = FALSE; + if(!pRoom->pRoom1) + { + D2COMMON_AddRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + bAdded = TRUE; + } + + CollMap* map = pRoom->pRoom1->Coll; + if(nX >= map->dwPosGameX && nY >= map->dwPosGameY && + nX < (map->dwPosGameX + map->dwSizeGameX) && nY < (map->dwPosGameY + map->dwSizeGameY)) + { + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + + JSObject *jsroom = BuildObject(cx, &room_class, room_methods, room_props, pRoom); + if (!jsroom) + return JS_TRUE; + + *rval=OBJECT_TO_JSVAL(jsroom); + + return JS_TRUE; + } + + if(bAdded) + D2COMMON_RemoveRoomData(D2CLIENT_GetPlayerUnit()->pAct, pLevel->dwLevelNo, pRoom->dwPosX, pRoom->dwPosY, D2CLIENT_GetPlayerUnit()->pPath->pRoom1); + } + + JSObject *jsroom = BuildObject(cx, &room_class, room_methods, room_props, pLevel->pRoom2First); + if (!jsroom) + return JS_TRUE; + + *rval=OBJECT_TO_JSVAL(jsroom); + + return JS_TRUE; + } + else { + JSObject *jsroom = BuildObject(cx, &room_class, room_methods, room_props, D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2->pLevel->pRoom2First); + if (!jsroom) + return JS_TRUE; + + *rval=OBJECT_TO_JSVAL(jsroom); + return JS_TRUE; + } + + return JS_TRUE; +} diff --git a/JSRoom.h b/JSRoom.h new file mode 100644 index 00000000..fcea9952 --- /dev/null +++ b/JSRoom.h @@ -0,0 +1,60 @@ +#ifndef ROOM_H +#define ROOM_H + +#include "Room.h" + +#include "js32.h" + +CLASS_CTOR(room); + +JSAPI_PROP(room_getProperty); + +JSAPI_FUNC(room_getNext); +JSAPI_FUNC(room_getPresetUnits); +JSAPI_FUNC(room_getCollision); +JSAPI_FUNC(room_getNearby); +JSAPI_FUNC(room_getStat); +JSAPI_FUNC(room_getFirst); +JSAPI_FUNC(room_unitInRoom); +JSAPI_FUNC(room_reveal); + +JSAPI_FUNC(my_getRoom); + +enum room_tinyid { + ROOM_NUM, + ROOM_XPOS, + ROOM_YPOS, + ROOM_XSIZE, + ROOM_YSIZE, + ROOM_SUBNUMBER, + ROOM_AREA, + ROOM_LEVEL, + ROOM_CORRECTTOMB, +}; + +static JSPropertySpec room_props[] = { + {"number", ROOM_NUM, JSPROP_PERMANENT_VAR, room_getProperty}, + {"x", ROOM_XPOS, JSPROP_PERMANENT_VAR, room_getProperty}, + {"y", ROOM_YPOS, JSPROP_PERMANENT_VAR, room_getProperty}, + {"xsize", ROOM_XSIZE, JSPROP_PERMANENT_VAR, room_getProperty}, + {"ysize", ROOM_YSIZE, JSPROP_PERMANENT_VAR, room_getProperty}, + {"subnumber", ROOM_SUBNUMBER, JSPROP_PERMANENT_VAR, room_getProperty}, + {"area", ROOM_AREA, JSPROP_PERMANENT_VAR, room_getProperty}, + {"level", ROOM_LEVEL, JSPROP_PERMANENT_VAR, room_getProperty}, + {"correcttomb", ROOM_CORRECTTOMB, JSPROP_PERMANENT_VAR, room_getProperty}, + {0} +}; + +static JSFunctionSpec room_methods[] = { + {"getNext", room_getNext, 0}, + {"reveal", room_reveal, 1}, + {"getPresetUnits", room_getPresetUnits, 0}, + {"getCollision", room_getCollision, 0}, + {"getNearby", room_getNearby, 0}, + {"getStat", room_getStat, 0}, + {"getFirst", room_getFirst, 0}, + {"unitInRoom", room_unitInRoom, 1}, + {0} +}; + +#endif diff --git a/JSSQLite.cpp b/JSSQLite.cpp new file mode 100644 index 00000000..9b94241a --- /dev/null +++ b/JSSQLite.cpp @@ -0,0 +1,574 @@ +/* + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include + +#include "JSSQLite.h" +#include "D2BS.h" +#include "File.h" + +using namespace std; + +struct SqliteDB; +struct DBStmt; +typedef std::set StmtList; + +struct SqliteDB { + sqlite3* db; + bool open; + char* path; + StmtList stmts; +}; + +struct DBStmt { + sqlite3_stmt* stmt; + bool open, canGet; + SqliteDB* assoc_db; + JSObject *current_row; +}; + +void close_db_stmt(DBStmt* stmt); +bool clean_sqlite_db(SqliteDB* db); + +bool clean_sqlite_db(SqliteDB* db) { + if(db && db->open) { + for(StmtList::iterator it = db->stmts.begin(); it != db->stmts.end(); it++) { + close_db_stmt(*it); + } + db->stmts.clear(); + if(SQLITE_OK != sqlite3_close(db->db)) return false; + } + return true; +} + +void close_db_stmt(DBStmt* stmt) { + if(stmt->stmt && stmt->open) { + sqlite3_finalize(stmt->stmt); + stmt->stmt = NULL; + stmt->open = false; + } +} + +JSAPI_FUNC(my_sqlite_version) +{ + *rval = STRING_TO_JSVAL(JS_InternString(cx, sqlite3_version)); + return JS_TRUE; +} + +JSAPI_FUNC(my_sqlite_memusage) +{ + JS_NewNumberValue(cx, (jsdouble)sqlite3_memory_used(), rval); + return JS_TRUE; +} + +EMPTY_CTOR(sqlite_stmt) + +JSAPI_FUNC(sqlite_ctor) +{ + if(argc > 0 && !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "Invalid parameters in SQLite constructor"); + char* path = ":memory:"; + if(argc > 0) + path = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + + // if the path is not a special placeholder (:memory:, et. al.), sandbox it + if(path[0] != ':') { + if(!isValidPath(path)) + THROW_ERROR(cx, "Invalid characters in database name"); + + char* tmp = new char[_MAX_PATH+_MAX_FNAME]; + sprintf_s(tmp, _MAX_PATH+_MAX_FNAME, "%s\\%s", Vars.szScriptPath, path); + path = _strdup(tmp); + delete[] tmp; + } + + bool autoOpen = true; + if(JSVAL_IS_BOOLEAN(argv[1])) + autoOpen = !!JSVAL_TO_BOOLEAN(argv[1]); + + sqlite3* db = NULL; + if(autoOpen) { + if(SQLITE_OK != sqlite3_open(path, &db)) { + char msg[1024]; + sprintf_s(msg, sizeof(msg), "Could not open database: %s", sqlite3_errmsg(db)); + THROW_ERROR(cx, msg); + } + } + + + SqliteDB* dbobj = new SqliteDB; // leaked? + dbobj->db = db; + dbobj->open = autoOpen; + dbobj->path = _strdup(path); + + // if the path is not a special placeholder, it needs to be freed + if(path[0] != ':') + free(path); + + JSObject* jsdb = BuildObject(cx, &sqlite_db_ex.base, sqlite_methods, sqlite_props, dbobj); + if(!jsdb) { + sqlite3_close(db); + free(dbobj->path); + delete dbobj; + THROW_ERROR(cx, "Could not create the sqlite object"); + } + *rval = OBJECT_TO_JSVAL(jsdb); + + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_execute) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + if(dbobj->open != true) + THROW_ERROR(cx, "Database must first be opened!"); + if(argc < 1 || argc > 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "Invalid parameters in SQLite.execute"); + + char* sql = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])), *err = NULL; + if(SQLITE_OK != sqlite3_exec(dbobj->db, sql, NULL, NULL, &err)) { + char msg[2048]; + strcpy_s(msg, sizeof(msg), err); + sqlite3_free(err); + THROW_ERROR(cx, msg); + } + *rval = JSVAL_TRUE; + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_query) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + if(dbobj->open != true) + THROW_ERROR(cx, "Database must first be opened!"); + if(argc < 1 || !JSVAL_IS_STRING(argv[0])) + THROW_ERROR(cx, "Invalid parameters to SQLite.query"); + + char* sql = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + sqlite3_stmt* stmt; + if(SQLITE_OK != sqlite3_prepare_v2(dbobj->db, sql, strlen(sql), &stmt, NULL)) { + THROW_ERROR(cx, sqlite3_errmsg(dbobj->db)); + } + if(stmt == NULL) { + THROW_ERROR(cx, "Statement has no effect"); + } + + for(uintN i = 1; i < argc; i++) { + switch(JS_TypeOfValue(cx, argv[i])) { + case JSTYPE_VOID: + sqlite3_bind_null(stmt, i); + break; + case JSTYPE_STRING: + sqlite3_bind_text(stmt, i, JS_GetStringBytes(JSVAL_TO_STRING(argv[i])), -1, SQLITE_STATIC); + break; + case JSTYPE_NUMBER: + if(JSVAL_IS_DOUBLE(argv[i])) + sqlite3_bind_double(stmt, i, *(double*)JSVAL_TO_DOUBLE(argv[i])); + else if(JSVAL_IS_INT(argv[i])) + sqlite3_bind_int(stmt, i, JSVAL_TO_INT(argv[i])); + break; + case JSTYPE_BOOLEAN: + sqlite3_bind_text(stmt, i, JSVAL_TO_BOOLEAN(argv[i]) ? "true" : "false", -1, SQLITE_STATIC); + break; + default: + sqlite3_finalize(stmt); + char msg[1024]; + sprintf_s(msg, sizeof(msg), "Invalid bound parameter %i", i); + THROW_ERROR(cx, msg); + break; + } + } + + DBStmt* dbstmt = new DBStmt; + dbstmt->stmt = stmt; + dbstmt->open = true; + dbstmt->canGet = false; + dbstmt->assoc_db = dbobj; + dbstmt->current_row = NULL; + dbobj->stmts.insert(dbstmt); + + JSObject* row = BuildObject(cx, &sqlite_stmt, sqlite_stmt_methods, sqlite_stmt_props, dbstmt); + if(!row) { + sqlite3_finalize(stmt); + delete dbstmt; + THROW_ERROR(cx, "Could not create the sqlite row object"); + } + *rval = OBJECT_TO_JSVAL(row); + return JS_TRUE; +} + + +JSAPI_FUNC(sqlite_close) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + if(!clean_sqlite_db(dbobj)) { + char msg[1024]; + sprintf_s(msg, sizeof(msg), "Could not close database: %s", sqlite3_errmsg(dbobj->db)); + THROW_ERROR(cx, msg); + } + *rval = JSVAL_TRUE; + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_open) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + if(!dbobj->open) { + if(SQLITE_OK != sqlite3_open(dbobj->path, &dbobj->db)) { + char msg[1024]; + sprintf_s(msg, sizeof(msg), "Could not open database: %s", sqlite3_errmsg(dbobj->db)); + THROW_ERROR(cx, msg); + } + } + *rval = JSVAL_TRUE; + return JS_TRUE; +} + +JSAPI_PROP(sqlite_getProperty) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + + switch(JSVAL_TO_INT(id)) { + case SQLITE_PATH: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, dbobj->path)); + break; + case SQLITE_OPEN: + *vp = BOOLEAN_TO_JSVAL(dbobj->open); + break; + case SQLITE_LASTROWID: + *vp = INT_TO_JSVAL(sqlite3_last_insert_rowid(dbobj->db)); + break; + case SQLITE_STMTS: { + JSObject *stmts = JS_NewArrayObject(cx, dbobj->stmts.size(), NULL); + *vp = OBJECT_TO_JSVAL(stmts); + int i = 0; + for(StmtList::iterator it = dbobj->stmts.begin(); it != dbobj->stmts.end(); it++, i++) { + if((*it)->open) { + JSObject* stmt = BuildObject(cx, &sqlite_stmt, sqlite_stmt_methods, sqlite_stmt_props, *it); + jsval tmp = OBJECT_TO_JSVAL(stmt); + JS_SetElement(cx, stmts, i, &tmp); + } + } + } + break; + case SQLITE_CHANGES: + JS_NewNumberValue(cx, (jsdouble)sqlite3_changes(dbobj->db), vp); + break; + } + return JS_TRUE; +} + +void sqlite_finalize(JSContext *cx, JSObject *obj) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + JS_SetPrivate(cx, obj, NULL); + if(dbobj) { + clean_sqlite_db(dbobj); + delete[] dbobj->path; + delete dbobj; + } +} + +JSBool sqlite_equal(JSContext *cx, JSObject *obj, jsval v, JSBool *bp) +{ + SqliteDB* dbobj = (SqliteDB*)JS_GetInstancePrivate(cx, obj, &sqlite_db_ex.base, NULL); + if(!JSVAL_IS_OBJECT(v)) + return JS_TRUE; + JSObject *obj2 = JSVAL_TO_OBJECT(v); + if(!obj2 || JS_GET_CLASS(cx, obj2) != JS_GET_CLASS(cx, obj)) + return JS_TRUE; + + SqliteDB* dbobj2 = (SqliteDB*)JS_GetPrivate(cx, obj2); + if(dbobj2->db != dbobj->db) + return JS_TRUE; + + *bp = JS_TRUE; + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_getobject) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + sqlite3_stmt *stmt = stmtobj->stmt; + + if(!stmtobj->canGet) { + *rval = JSVAL_NULL; + return JS_TRUE; + } + if(stmtobj->current_row) { + *rval = OBJECT_TO_JSVAL(stmtobj->current_row); + return JS_TRUE; + } + + int cols = sqlite3_column_count(stmt); + if(cols == 0) { + *rval = JSVAL_TRUE; + return JS_TRUE; + } + + JSObject *obj2 = JS_ConstructObject(cx, NULL, NULL, NULL); + jsval val; + if(!obj2) + THROW_ERROR(cx, "Failed to create row result object"); + for(int i = 0; i < cols; i++) { + const char* colnam = sqlite3_column_name(stmt, i); + switch(sqlite3_column_type(stmt, i)) { + case SQLITE_INTEGER: + // jsdouble == double, so this conversion is no problem + JS_NewNumberValue(cx, (jsdouble)sqlite3_column_int64(stmt, i), &val); + if(!JS_SetProperty(cx, obj2, colnam, &val)) + THROW_ERROR(cx, "Failed to add column to row results"); + break; + case SQLITE_FLOAT: + JS_NewNumberValue(cx, sqlite3_column_double(stmt, i), &val); + if(!JS_SetProperty(cx, obj2, colnam, &val)) + THROW_ERROR(cx, "Failed to add column to row results"); + break; + case SQLITE_TEXT: + val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, reinterpret_cast(sqlite3_column_text(stmt, i)))); + if(!JS_SetProperty(cx, obj2, colnam, &val)) + THROW_ERROR(cx, "Failed to add column to row results"); + break; + case SQLITE_BLOB: + // currently not supported + THROW_ERROR(cx, "Blob type not supported (yet)"); + break; + case SQLITE_NULL: + if(!JS_SetProperty(cx, obj2, colnam, JSVAL_NULL)) + THROW_ERROR(cx, "Failed to add column to row results"); + break; + } + } + stmtobj->current_row = obj2; + if(JS_AddRoot(&stmtobj->current_row) == JS_FALSE) + return JS_TRUE; + *rval = OBJECT_TO_JSVAL(obj2); + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_colcount) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + sqlite3_stmt *stmt = stmtobj->stmt; + + if(!stmtobj->canGet) + THROW_ERROR(cx, "Statement is not ready"); + + *rval = INT_TO_JSVAL(sqlite3_column_count(stmt)); + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_colval) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + sqlite3_stmt *stmt = stmtobj->stmt; + + if(!stmtobj->canGet) + THROW_ERROR(cx, "Statement is not ready"); + + if(argc < 1 || argc > 1 || !JSVAL_IS_INT(argv[0])) + THROW_ERROR(cx, "Invalid parameter for SQLiteStatement.getColumnValue"); + + int i = JSVAL_TO_INT(argv[0]); + switch(sqlite3_column_type(stmt, i)) { + case SQLITE_INTEGER: + // jsdouble == double, so this conversion is no problem + JS_NewNumberValue(cx, (jsdouble)sqlite3_column_int64(stmt, i), rval); + break; + case SQLITE_FLOAT: + JS_NewNumberValue(cx, sqlite3_column_double(stmt, i), rval); + break; + case SQLITE_TEXT: + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, reinterpret_cast(sqlite3_column_text(stmt, i)))); + break; + case SQLITE_BLOB: + // currently not supported + THROW_ERROR(cx, "Blob type not supported (yet)"); + break; + case SQLITE_NULL: + *rval = JSVAL_NULL; + break; + } + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_colname) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + sqlite3_stmt *stmt = stmtobj->stmt; + + if(!stmtobj->canGet) + THROW_ERROR(cx, "Statement is not ready"); + + if(argc < 1 || argc > 1 || !JSVAL_IS_INT(argv[0])) + THROW_ERROR(cx, "Invalid parameter for SQLiteStatement.getColumnValue"); + + int i = JSVAL_TO_INT(argv[0]); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, sqlite3_column_name(stmt, i))); + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_execute) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + + int res = sqlite3_step(stmtobj->stmt); + + if(SQLITE_ROW != res && SQLITE_DONE != res) + THROW_ERROR(cx, sqlite3_errmsg(stmtobj->assoc_db->db)); + close_db_stmt(stmtobj); + *rval = BOOLEAN_TO_JSVAL((SQLITE_DONE == res)); + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_bind) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + sqlite3_stmt* stmt = stmtobj->stmt; + if(argc < 2 || argc > 2 || !(JSVAL_IS_STRING(argv[0]) || JSVAL_IS_INT(argv[0]))) + THROW_ERROR(cx, "Invalid parameters for SQLiteStatement.bind"); + + int colnum = -1; + if(JSVAL_IS_INT(argv[0])) + colnum = JSVAL_TO_INT(argv[0]); + else + colnum = sqlite3_bind_parameter_index(stmt, JS_GetStringBytes(JSVAL_TO_STRING(argv[0]))); + + if(colnum == 0) + THROW_ERROR(cx, "Invalid parameter number, parameters start at 1"); + + switch(JS_TypeOfValue(cx, argv[1])) { + case JSTYPE_VOID: + sqlite3_bind_null(stmt, colnum); + break; + case JSTYPE_STRING: + sqlite3_bind_text(stmt, colnum, JS_GetStringBytes(JSVAL_TO_STRING(argv[1])), -1, SQLITE_STATIC); + break; + case JSTYPE_NUMBER: + if(JSVAL_IS_DOUBLE(argv[1])) + sqlite3_bind_double(stmt, colnum, *(double*)JSVAL_TO_DOUBLE(argv[1])); + else if(JSVAL_IS_INT(argv[1])) + sqlite3_bind_int(stmt, colnum, JSVAL_TO_INT(argv[1])); + break; + case JSTYPE_BOOLEAN: + sqlite3_bind_text(stmt, colnum, JSVAL_TO_BOOLEAN(argv[1]) ? "true" : "false", -1, SQLITE_STATIC); + break; + default: + THROW_ERROR(cx, "Invalid bound parameter"); + break; + } + + *rval = JSVAL_TRUE; + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_next) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + + int res = sqlite3_step(stmtobj->stmt); + + if(SQLITE_ROW != res && SQLITE_DONE != res) + THROW_ERROR(cx, sqlite3_errmsg(stmtobj->assoc_db->db)); + + stmtobj->canGet = !!(SQLITE_ROW == res); + if(stmtobj->current_row) { + JS_RemoveRoot(&stmtobj->current_row); + stmtobj->current_row = NULL; + } + *rval = BOOLEAN_TO_JSVAL((SQLITE_ROW == res)); + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_skip) +{ + *rval = argv[0]; + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + THROW_ERROR(cx, "Invalid parameter to SQLiteStatement.skip"); + for(int i = JSVAL_TO_INT(argv[0])-1; i >= 0; i++) { + int res = sqlite3_step(stmtobj->stmt); + if(res != SQLITE_ROW) { + if(res == SQLITE_DONE) { + *rval = INT_TO_JSVAL((JSVAL_TO_INT(argv[0]-1)-i)); + stmtobj->canGet = false; + i = 0; + continue; + } + THROW_ERROR(cx, sqlite3_errmsg(stmtobj->assoc_db->db)); + } + stmtobj->canGet = true; + } + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_reset) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + if(SQLITE_OK != sqlite3_reset(stmtobj->stmt)) + THROW_ERROR(cx, sqlite3_errmsg(stmtobj->assoc_db->db)); + stmtobj->canGet = false; + *rval = JSVAL_TRUE; + return JS_TRUE; +} + +JSAPI_FUNC(sqlite_stmt_close) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + if(stmtobj->current_row) + JS_RemoveRoot(&stmtobj->current_row); + close_db_stmt(stmtobj); + delete stmtobj; + + JS_SetPrivate(cx, obj, NULL); + *rval = JSVAL_TRUE; + JS_ClearScope(cx, obj); + if(JS_ValueToObject(cx, JSVAL_NULL, &obj) == JS_FALSE) + return JS_TRUE; + + return JS_TRUE; +} + +JSAPI_PROP(sqlite_stmt_getProperty) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + + switch(JSVAL_TO_INT(id)) { + case SQLITE_STMT_SQL: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, sqlite3_sql(stmtobj->stmt))); + break; + case SQLITE_STMT_READY: + *vp = BOOLEAN_TO_JSVAL(stmtobj->canGet); + break; + } + return JS_TRUE; +} + +void sqlite_stmt_finalize(JSContext *cx, JSObject *obj) +{ + DBStmt* stmtobj = (DBStmt*)JS_GetInstancePrivate(cx, obj, &sqlite_stmt, NULL); + JS_SetPrivate(cx, obj, NULL); + if(stmtobj) { + if(stmtobj->stmt && stmtobj->open) { + stmtobj->assoc_db->stmts.erase(stmtobj); + if(stmtobj->current_row) + JS_RemoveRoot(&stmtobj->current_row); + close_db_stmt(stmtobj); + } + delete stmtobj; + } +} + diff --git a/JSSQLite.h b/JSSQLite.h new file mode 100644 index 00000000..e7c7005d --- /dev/null +++ b/JSSQLite.h @@ -0,0 +1,86 @@ +#ifndef SQLITE_H +#define SQLITE_H + +#include "js32.h" +#include "sqlite3.h" +#include "JSGlobalClasses.h" + +JSAPI_FUNC(my_sqlite_version); +JSAPI_FUNC(my_sqlite_memusage); + +JSAPI_FUNC(sqlite_ctor); +JSAPI_FUNC(sqlite_execute); +JSAPI_FUNC(sqlite_query); +JSAPI_FUNC(sqlite_close); +JSAPI_FUNC(sqlite_open); +JSAPI_PROP(sqlite_getProperty); +void sqlite_finalize(JSContext *cx, JSObject *obj); +JSBool sqlite_equal(JSContext *cx, JSObject *obj, jsval v, JSBool *bp); + +CLASS_CTOR(sqlite_stmt); + +JSAPI_FUNC(sqlite_stmt_getobject); +JSAPI_FUNC(sqlite_stmt_colcount); +JSAPI_FUNC(sqlite_stmt_colval); +JSAPI_FUNC(sqlite_stmt_colname); +JSAPI_FUNC(sqlite_stmt_execute); +JSAPI_FUNC(sqlite_stmt_next); +JSAPI_FUNC(sqlite_stmt_reset); +JSAPI_FUNC(sqlite_stmt_skip); +JSAPI_FUNC(sqlite_stmt_close); +JSAPI_FUNC(sqlite_stmt_bind); +JSAPI_PROP(sqlite_stmt_getProperty); +void sqlite_stmt_finalize(JSContext *cx, JSObject *obj); + +enum { + SQLITE_PATH, + SQLITE_STMTS, + SQLITE_OPEN, + SQLITE_LASTROWID, + SQLITE_CHANGES +}; + +enum { + SQLITE_STMT_SQL, + SQLITE_STMT_READY +}; + + +static JSFunctionSpec sqlite_methods[] = { + {"execute", sqlite_execute, 1}, + {"query", sqlite_query, 1}, + {"open", sqlite_open, 0}, + {"close", sqlite_close, 0}, + {0} +}; + +static JSPropertySpec sqlite_props[] = { + {"path", SQLITE_PATH, JSPROP_PERMANENT_VAR, sqlite_getProperty}, + {"statements", SQLITE_STMTS, JSPROP_PERMANENT_VAR, sqlite_getProperty}, + {"isOpen", SQLITE_OPEN, JSPROP_PERMANENT_VAR, sqlite_getProperty}, + {"lastRowId", SQLITE_LASTROWID, JSPROP_PERMANENT_VAR, sqlite_getProperty}, + {"changes", SQLITE_CHANGES, JSPROP_PERMANENT_VAR, sqlite_getProperty}, + {0} +}; + +static JSFunctionSpec sqlite_stmt_methods[] = { + {"getObject", sqlite_stmt_getobject, 0}, + {"getColumnCount", sqlite_stmt_colcount, 0}, + {"getColumnValue", sqlite_stmt_colval, 1}, + {"getColumnName", sqlite_stmt_colname, 1}, + {"go", sqlite_stmt_execute, 0}, + {"next", sqlite_stmt_next, 0}, + {"skip", sqlite_stmt_skip, 1}, + {"reset", sqlite_stmt_reset, 0}, + {"close", sqlite_stmt_close, 0}, + {"bind", sqlite_stmt_bind, 2}, + {0} +}; + +static JSPropertySpec sqlite_stmt_props[] = { + {"sql", SQLITE_STMT_SQL, JSPROP_PERMANENT_VAR, sqlite_stmt_getProperty}, + {"ready", SQLITE_STMT_READY, JSPROP_PERMANENT_VAR, sqlite_stmt_getProperty}, + {0} +}; + +#endif SQLITE_H diff --git a/JSSandbox.cpp b/JSSandbox.cpp new file mode 100644 index 00000000..5549cf64 --- /dev/null +++ b/JSSandbox.cpp @@ -0,0 +1,244 @@ +#include "JSSandbox.h" +#include "D2BS.h" +#include "ScriptEngine.h" + +JSAPI_FUNC(sandbox_ctor) +{ + sandbox* box = new sandbox; // leaked? + box->context = JS_NewContext(ScriptEngine::GetRuntime(), 0x2000); + if(!box->context) + { + delete box; + return JS_TRUE; + } + box->innerObj = JS_NewObject(box->context, &global_obj, NULL, NULL); + if(!box->innerObj) + { + JS_DestroyContext(box->context); + delete box; + return JS_TRUE; + } + + if(JS_InitStandardClasses(box->context, box->innerObj) == JS_FALSE) + { + JS_DestroyContext(box->context); + delete box; + return JS_TRUE; + } + + // TODO: add a default include function for sandboxed scripts + // how do I do that individually though? :/ + + JSObject* res = JS_NewObject(cx, &sandbox_class, NULL, NULL); + if(JS_AddRoot(&res) == JS_FALSE) + { + JS_DestroyContext(box->context); + delete box; + return JS_TRUE; + } + if(!res || !JS_DefineFunctions(cx, res, sandbox_methods)) + { + JS_RemoveRoot(&box->innerObj); + JS_DestroyContext(box->context); + delete box; + return JS_TRUE; + } + JS_SetPrivate(cx, res, box); + JS_RemoveRoot(&res); + *rval = OBJECT_TO_JSVAL(res); + + return JS_TRUE; +} + +JSAPI_PROP(sandbox_addProperty) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + JSContext* cxptr = (!box ? cx : box->context); + JSObject* ptr = (!box ? obj : box->innerObj); + + if(JSVAL_IS_INT(id)) + { + int32 i; + if(JS_ValueToInt32(cx, id, &i) == JS_FALSE) + return JS_TRUE; + char name[32]; + _itoa_s(i, name, 32, 10); + JSBool found; + if(JS_HasProperty(cxptr, ptr, name, &found) == JS_FALSE) + return JS_TRUE; + if(found) + return JS_TRUE; + + return JS_DefineProperty(cxptr, ptr, name, *vp, NULL, NULL, JSPROP_ENUMERATE); + } + else if(JSVAL_IS_STRING(id)) + { + char* name = JS_GetStringBytes(JSVAL_TO_STRING(id)); + JSBool found; + if(JS_HasProperty(cxptr, ptr, name, &found) == JS_FALSE) + return JS_TRUE; + if(found) + return JS_TRUE; + + return JS_DefineProperty(cxptr, ptr, name, *vp, NULL, NULL, JSPROP_ENUMERATE); + } + return JS_FALSE; +} + +JSAPI_PROP(sandbox_delProperty) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + + if(JSVAL_IS_INT(id)) + { + int32 i; + if(JS_ValueToInt32(cx, id, &i) == JS_FALSE) + return JS_TRUE; + char name[32]; + _itoa_s(i, name, 32, 10); + if(box && JS_DeleteProperty(box->context, box->innerObj, name)) + return JS_TRUE; + } + else if(JSVAL_IS_STRING(id)) + { + char* name = JS_GetStringBytes(JSVAL_TO_STRING(id)); + if(box && JS_DeleteProperty(box->context, box->innerObj, name)) + return JS_TRUE; + } + return JS_FALSE; +} + +JSAPI_PROP(sandbox_getProperty) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + + if(JSVAL_IS_INT(id)) + { + int32 i; + if(JS_ValueToInt32(cx, id, &i) == JS_FALSE) + return JS_TRUE; + char name[32]; + _itoa_s(i, name, 32, 10); + *vp = JSVAL_VOID; + if(box && JS_LookupProperty(box->context, box->innerObj, name, vp)) + return JS_TRUE; + if(JSVAL_IS_VOID(*vp) && JS_LookupProperty(cx, obj, name, vp)) + return JS_TRUE; + } + else if(JSVAL_IS_STRING(id)) + { + char* name = JS_GetStringBytes(JSVAL_TO_STRING(id)); + *vp = JSVAL_VOID; + if(box && (JS_LookupProperty(box->context, box->innerObj, name, vp))) + return JS_TRUE; + if(JSVAL_IS_VOID(*vp) && JS_LookupProperty(cx, obj, name, vp)) + return JS_TRUE; + } + return JS_FALSE; +} + +JSAPI_PROP(sandbox_setProperty) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + + if(JSVAL_IS_INT(id)) + { + int32 i; + if(JS_ValueToInt32(cx, id, &i) == JS_FALSE) + return JS_TRUE; + char name[32]; + _itoa_s(i, name, 32, 10); + if(box) + if(JS_SetProperty(box->context, box->innerObj, name, vp)) + return JS_TRUE; + } + else if(JSVAL_IS_STRING(id)) + { + char* name = JS_GetStringBytes(JSVAL_TO_STRING(id)); + if(box) + if(JS_SetProperty(box->context, box->innerObj, name, vp)) + return JS_TRUE; + } + return JS_FALSE; +} + +void sandbox_finalize(JSContext *cx, JSObject *obj) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + if(box) { + JS_SetContextThread(box->context); + JS_DestroyContext(box->context); + delete box; + } +} + +JSAPI_FUNC(sandbox_eval) +{ + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + { + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + if(!box) + THROW_ERROR(cx, "Invalid execution object!"); + char* code = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + jsval result; + if(JS_BufferIsCompilableUnit(box->context, box->innerObj, code, strlen(code)) && + JS_EvaluateScript(box->context, box->innerObj, code, strlen(code), "sandbox", 0, &result)) + *rval = result; + } else THROW_ERROR(cx, "Invalid parameter, string expected"); + return JS_TRUE; +} + +JSAPI_FUNC(sandbox_include) +{ + *rval = JSVAL_FALSE; + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + { + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + char* file = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(file && strlen(file) <= _MAX_FNAME && box) + { + char buf[_MAX_PATH+_MAX_FNAME]; + sprintf_s(buf, sizeof(buf), "%s\\libs\\%s", Vars.szScriptPath, file); + if(box->list.count(std::string(file)) == -1) + { + JSScript* tmp = JS_CompileFile(box->context, box->innerObj, buf); + if(tmp) + { + jsval result; + if(JS_ExecuteScript(box->context, box->innerObj, tmp, &result)) + { + box->list[file] = true; + *rval = result; + } + JS_DestroyScript(cx, tmp); + } + } + } + } + else + THROW_ERROR(cx, "Invalid parameter, file expected"); + + return JS_TRUE; +} + +JSAPI_FUNC(sandbox_isIncluded) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + if(argc > 0 && JSVAL_IS_STRING(argv[0]) && box) + { + char* file = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + char buf[_MAX_PATH+_MAX_FNAME]; + sprintf_s(buf, sizeof(buf), "%s\\libs\\%s", Vars.szScriptPath, file); + *rval = BOOLEAN_TO_JSVAL(!!box->list.count(std::string(buf))); + } else THROW_ERROR(cx, "Invalid parameter, file expected"); + return JS_TRUE; +} + +JSAPI_FUNC(sandbox_clear) +{ + sandbox* box = (sandbox*)JS_GetInstancePrivate(cx, obj, &sandbox_class, NULL); + if(box) + JS_ClearScope(cx, box->innerObj); + return JS_TRUE; +} + diff --git a/JSSandbox.h b/JSSandbox.h new file mode 100644 index 00000000..8a207295 --- /dev/null +++ b/JSSandbox.h @@ -0,0 +1,34 @@ +#ifndef JSSANDBOX_H +#define JSSANDBOX_H + +#include "Script.h" + +JSAPI_FUNC(sandbox_ctor); + +JSAPI_PROP(sandbox_addProperty); +JSAPI_PROP(sandbox_delProperty); +JSAPI_PROP(sandbox_getProperty); +JSAPI_PROP(sandbox_setProperty); + +JSAPI_FUNC(sandbox_eval); +JSAPI_FUNC(sandbox_include); +JSAPI_FUNC(sandbox_isIncluded); +JSAPI_FUNC(sandbox_clear); + +void sandbox_finalize(JSContext *cx, JSObject *obj); + +struct sandbox { + JSContext* context; + JSObject* innerObj; + IncludeList list; +}; + +static JSFunctionSpec sandbox_methods[] = { + {"evaluate", sandbox_eval, 1}, + {"include", sandbox_include, 1}, + {"isIncluded", sandbox_isIncluded, 1}, + {"clearScope", sandbox_clear, 0}, + {0} +}; + +#endif diff --git a/JSScreenHook.cpp b/JSScreenHook.cpp new file mode 100644 index 00000000..29d316ac --- /dev/null +++ b/JSScreenHook.cpp @@ -0,0 +1,846 @@ +#include "JSScreenHook.h" +#include "D2BS.h" +#include "ScreenHook.h" +#include "Script.h" +#include "File.h" +using namespace std; + +void hook_finalize(JSContext *cx, JSObject *obj) +{ + Genhook* hook = (Genhook*)JS_GetPrivate(cx, obj); + + if(hook) + { + JS_SetPrivate(cx, obj, NULL); + delete hook; + } +} + +JSAPI_FUNC(hook_remove) +{ + Genhook* hook = (Genhook*)JS_GetPrivate(cx, obj); + if(hook) + { + hook->SetIsVisible(false); + delete hook; + } + + JS_SetPrivate(cx, obj, NULL); + JS_ClearScope(cx, obj); + JS_ValueToObject(cx, JSVAL_VOID, &obj); + + return JS_TRUE; +} + +// Function to create a frame which gets called on a "new Frame ()" +// Parameters: x, y, xsize, ysize, alignment, automap, onClick, onHover +JSAPI_FUNC(frame_ctor) +{ + Script* script = (Script*)JS_GetContextPrivate(cx); + + uint x = 0, y = 0, x2 = 0, y2 = 0; + Align align = Left; + bool automap = false; + jsval click = JSVAL_VOID, hover = JSVAL_VOID; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + x = JSVAL_TO_INT(argv[0]); + if(argc > 1 && JSVAL_IS_INT(argv[1])) + y = JSVAL_TO_INT(argv[1]); + if(argc > 2 && JSVAL_IS_INT(argv[2])) + x2 = JSVAL_TO_INT(argv[2]); + if(argc > 3 && JSVAL_IS_INT(argv[3])) + y2 = JSVAL_TO_INT(argv[3]); + if(argc > 4 && JSVAL_IS_INT(argv[4])) + align = (Align)JSVAL_TO_INT(argv[4]); + if(argc > 5 && JSVAL_IS_BOOLEAN(argv[5])) + automap = !!JSVAL_TO_BOOLEAN(argv[5]); + if(argc > 6 && JSVAL_IS_FUNCTION(cx, argv[6])) + click = argv[6]; + if(argc > 7 && JSVAL_IS_FUNCTION(cx, argv[7])) + hover = argv[7]; + + JSObject* hook = BuildObject(cx, &frame_class, frame_methods, frame_props); + if(!hook) + THROW_ERROR(cx, "Failed to create frame object"); + + // framehooks don't work out of game -- they just crash + FrameHook* pFrameHook = new FrameHook(script, hook, x, y, x2, y2, automap, align, IG); + + if (!pFrameHook) + THROW_ERROR(cx, "Failed to create framehook"); + + JS_SetPrivate(cx, hook, pFrameHook); + pFrameHook->SetClickHandler(click); + pFrameHook->SetHoverHandler(hover); + + *rval = OBJECT_TO_JSVAL(hook); + + return JS_TRUE; +} + +JSAPI_PROP(frame_getProperty) +{ + FrameHook* pFramehook = (FrameHook*)JS_GetPrivate(cx, obj); + if(!pFramehook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case FRAME_X: + *vp = INT_TO_JSVAL(pFramehook->GetX()); + break; + case FRAME_Y: + *vp = INT_TO_JSVAL(pFramehook->GetY()); + break; + case FRAME_XSIZE: + *vp = INT_TO_JSVAL(pFramehook->GetXSize()); + break; + case FRAME_YSIZE: + *vp = INT_TO_JSVAL(pFramehook->GetYSize()); + break; + case FRAME_ALIGN: + *vp = INT_TO_JSVAL(pFramehook->GetAlign()); + break; + case FRAME_VISIBLE: + *vp = BOOLEAN_TO_JSVAL(pFramehook->GetIsVisible()); + break; + case FRAME_ZORDER: + *vp = INT_TO_JSVAL(pFramehook->GetZOrder()); + break; + case FRAME_ONCLICK: + *vp = pFramehook->GetClickHandler(); + break; + case FRAME_ONHOVER: + *vp = pFramehook->GetHoverHandler(); + break; + } + return JS_TRUE; +} + +JSAPI_PROP(frame_setProperty) +{ + FrameHook* pFramehook = (FrameHook*)JS_GetPrivate(cx, obj); + if(!pFramehook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case FRAME_X: + if(JSVAL_IS_INT(*vp)) + pFramehook->SetX(JSVAL_TO_INT(*vp)); + break; + case FRAME_Y: + if(JSVAL_IS_INT(*vp)) + pFramehook->SetY(JSVAL_TO_INT(*vp)); + break; + case FRAME_XSIZE: + if(JSVAL_IS_INT(*vp)) + pFramehook->SetXSize(JSVAL_TO_INT(*vp)); + break; + case FRAME_YSIZE: + if(JSVAL_IS_INT(*vp)) + pFramehook->SetYSize(JSVAL_TO_INT(*vp)); + break; + case FRAME_ALIGN: + if(JSVAL_IS_INT(*vp)) + pFramehook->SetAlign((Align)JSVAL_TO_INT(*vp)); + break; + case FRAME_VISIBLE: + if(JSVAL_IS_BOOLEAN(*vp)) + pFramehook->SetIsVisible(!!JSVAL_TO_BOOLEAN(*vp)); + break; + case FRAME_ZORDER: + if(JSVAL_IS_INT(*vp)) + pFramehook->SetZOrder((ushort)JSVAL_TO_INT(*vp)); + break; + case FRAME_ONCLICK: + pFramehook->SetClickHandler(*vp); + break; + case FRAME_ONHOVER: + pFramehook->SetHoverHandler(*vp); + break; + } + return JS_TRUE; +} + +//Box functions + +//Parameters: x, y, xsize, ysize, color, opacity, alignment, automap, onClick, onHover +JSAPI_FUNC(box_ctor) +{ + Script* script = (Script*)JS_GetContextPrivate(cx); + + ScreenhookState state = (script->GetState () == OutOfGame) ? OOG : IG; + uint x = 0, y = 0, x2 = 0, y2 = 0; + ushort color = 0, opacity = 0; + Align align = Left; + bool automap = false; + jsval click = JSVAL_VOID, hover = JSVAL_VOID; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + x = JSVAL_TO_INT(argv[0]); + if(argc > 1 && JSVAL_IS_INT(argv[1])) + y = JSVAL_TO_INT(argv[1]); + if(argc > 2 && JSVAL_IS_INT(argv[2])) + x2 = JSVAL_TO_INT(argv[2]); + if(argc > 3 && JSVAL_IS_INT(argv[3])) + y2 = JSVAL_TO_INT(argv[3]); + if(argc > 4 && JSVAL_IS_INT(argv[4])) + color = (ushort)JSVAL_TO_INT(argv[4]); + if(argc > 5 && JSVAL_IS_INT(argv[5])) + opacity = (ushort)JSVAL_TO_INT(argv[5]); + if(argc > 6 && JSVAL_IS_INT(argv[6])) + align = (Align)JSVAL_TO_INT(argv[6]); + if(argc > 7 && JSVAL_IS_BOOLEAN(argv[7])) + automap = !!JSVAL_TO_BOOLEAN(argv[7]); + if(argc > 8 && JSVAL_IS_FUNCTION(cx, argv[8])) + click = argv[8]; + if(argc > 9 && JSVAL_IS_FUNCTION(cx, argv[9])) + hover = argv[9]; + + JSObject* hook = BuildObject(cx, &box_class, box_methods, box_props); + if(!hook) + THROW_ERROR(cx, "Failed to create box object"); + + BoxHook* pBoxHook = new BoxHook(script, hook, x, y, x2, y2, color, opacity, automap, align, state); + + if (!pBoxHook) + THROW_ERROR(cx, "Unable to initalize a box class."); + + JS_SetPrivate(cx, hook, pBoxHook); + pBoxHook->SetClickHandler(click); + pBoxHook->SetHoverHandler(hover); + + *rval = OBJECT_TO_JSVAL(hook); + + return JS_TRUE; +} +JSAPI_PROP(box_getProperty) +{ + BoxHook* pBoxHook = (BoxHook*)JS_GetPrivate(cx, obj); + if(!pBoxHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case BOX_X: + *vp = INT_TO_JSVAL(pBoxHook->GetX()); + break; + case BOX_Y: + *vp = INT_TO_JSVAL(pBoxHook->GetY()); + break; + case BOX_XSIZE: + *vp = INT_TO_JSVAL(pBoxHook->GetXSize()); + break; + case BOX_YSIZE: + *vp = INT_TO_JSVAL(pBoxHook->GetYSize()); + break; + case BOX_ALIGN: + *vp = INT_TO_JSVAL(pBoxHook->GetAlign()); + break; + case BOX_COLOR: + *vp = INT_TO_JSVAL(pBoxHook->GetColor()); + break; + case BOX_OPACITY: + *vp = INT_TO_JSVAL(pBoxHook->GetOpacity()); + break; + case BOX_VISIBLE: + *vp = BOOLEAN_TO_JSVAL(pBoxHook->GetIsVisible()); + break; + case BOX_ZORDER: + *vp = INT_TO_JSVAL(pBoxHook->GetZOrder()); + break; + case BOX_ONCLICK: + *vp = pBoxHook->GetClickHandler(); + break; + case BOX_ONHOVER: + *vp = pBoxHook->GetHoverHandler(); + break; + } + return JS_TRUE; +} + +JSAPI_PROP(box_setProperty) +{ + BoxHook* pBoxHook = (BoxHook*)JS_GetPrivate(cx, obj); + if(!pBoxHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case BOX_X: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetX(JSVAL_TO_INT(*vp)); + break; + case BOX_Y: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetY(JSVAL_TO_INT(*vp)); + break; + case BOX_XSIZE: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetXSize(JSVAL_TO_INT(*vp)); + break; + case BOX_YSIZE: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetYSize(JSVAL_TO_INT(*vp)); + break; + case BOX_OPACITY: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetOpacity((ushort)JSVAL_TO_INT(*vp)); + break; + case BOX_COLOR: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetColor((ushort)JSVAL_TO_INT(*vp)); + break; + case BOX_ALIGN: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetAlign((Align)JSVAL_TO_INT(*vp)); + break; + case BOX_VISIBLE: + if(JSVAL_IS_BOOLEAN(*vp)) + pBoxHook->SetIsVisible(!!JSVAL_TO_BOOLEAN(*vp)); + break; + case BOX_ZORDER: + if(JSVAL_IS_INT(*vp)) + pBoxHook->SetZOrder((ushort)JSVAL_TO_INT(*vp)); + break; + case BOX_ONCLICK: + pBoxHook->SetClickHandler(*vp); + break; + case BOX_ONHOVER: + pBoxHook->SetHoverHandler(*vp); + break; + } + return JS_TRUE; +} + + +//Line functions + +// Parameters: x, y, x2, y2, color, automap, click, hover +JSAPI_FUNC(line_ctor) +{ + Script* script = (Script*)JS_GetContextPrivate(cx); + + ScreenhookState state = (script->GetState () == OutOfGame) ? OOG : IG; + int x = 0, y = 0, x2 = 0, y2 = 0; + ushort color = 0; + bool automap = false; + jsval click = JSVAL_VOID, hover = JSVAL_VOID; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + x = JSVAL_TO_INT(argv[0]); + if(argc > 1 && JSVAL_IS_INT(argv[1])) + y = JSVAL_TO_INT(argv[1]); + if(argc > 2 && JSVAL_IS_INT(argv[2])) + x2 = JSVAL_TO_INT(argv[2]); + if(argc > 3 && JSVAL_IS_INT(argv[3])) + y2 = JSVAL_TO_INT(argv[3]); + if(argc > 4 && JSVAL_IS_INT(argv[4])) + color = (ushort)JSVAL_TO_INT(argv[4]); + if(argc > 5 && JSVAL_IS_BOOLEAN(argv[5])) + automap = !!JSVAL_TO_BOOLEAN(argv[5]); + if(argc > 6 && JSVAL_IS_FUNCTION(cx, argv[6])) + click = argv[6]; + if(argc > 7 && JSVAL_IS_FUNCTION(cx, argv[7])) + hover = argv[7]; + + JSObject* hook = BuildObject(cx, &line_class, line_methods, line_props); + if(!hook) + THROW_ERROR(cx, "Failed to create line object"); + + LineHook* pLineHook = new LineHook(script, hook, x, y, x2, y2, color, automap, Left, state); + + if (!pLineHook) + THROW_ERROR(cx, "Unable to initalize a line class."); + + JS_SetPrivate(cx, hook, pLineHook); + pLineHook->SetClickHandler(click); + pLineHook->SetHoverHandler(hover); + + *rval = OBJECT_TO_JSVAL(hook); + + return JS_TRUE; +} + + +JSAPI_PROP(line_getProperty) +{ + LineHook* pLineHook = (LineHook*)JS_GetPrivate(cx, obj); + if(!pLineHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case LINE_X: + *vp = INT_TO_JSVAL(pLineHook->GetX()); + break; + case LINE_Y: + *vp = INT_TO_JSVAL(pLineHook->GetY()); + break; + case LINE_XSIZE: + *vp = INT_TO_JSVAL(pLineHook->GetX2()); + break; + case LINE_YSIZE: + *vp = INT_TO_JSVAL(pLineHook->GetY2()); + break; + case LINE_COLOR: + *vp = INT_TO_JSVAL(pLineHook->GetColor()); + break; + case LINE_VISIBLE: + *vp = BOOLEAN_TO_JSVAL(pLineHook->GetIsVisible()); + break; + case LINE_ZORDER: + *vp = INT_TO_JSVAL(pLineHook->GetZOrder()); + break; + case LINE_ONCLICK: + *vp = pLineHook->GetClickHandler(); + break; + case LINE_ONHOVER: + *vp = pLineHook->GetHoverHandler(); + break; + } + return JS_TRUE; +} + +JSAPI_PROP(line_setProperty) +{ + LineHook* pLineHook = (LineHook*)JS_GetPrivate(cx, obj); + if(!pLineHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case LINE_X: + if (JSVAL_IS_INT(*vp)) + pLineHook->SetX(JSVAL_TO_INT(*vp)); + break; + case LINE_Y: + if (JSVAL_IS_INT(*vp)) + pLineHook->SetY(JSVAL_TO_INT(*vp)); + break; + case LINE_XSIZE: + if (JSVAL_IS_INT(*vp)) + pLineHook->SetX2(JSVAL_TO_INT(*vp)); + break; + case LINE_YSIZE: + if (JSVAL_IS_INT(*vp)) + pLineHook->SetY2(JSVAL_TO_INT(*vp)); + break; + case LINE_COLOR: + if (JSVAL_IS_INT(*vp)) + pLineHook->SetColor((ushort)JSVAL_TO_INT(*vp)); + break; + case LINE_VISIBLE: + if (JSVAL_IS_BOOLEAN(*vp)) + pLineHook->SetIsVisible(!!JSVAL_TO_BOOLEAN(*vp)); + break; + case LINE_ZORDER: + if(JSVAL_IS_INT(*vp)) + pLineHook->SetZOrder((ushort)JSVAL_TO_INT(*vp)); + break; + case LINE_ONCLICK: + pLineHook->SetClickHandler(*vp); + break; + case LINE_ONHOVER: + pLineHook->SetHoverHandler(*vp); + break; + } + return JS_TRUE; +} + + +// Function to create a text which gets called on a "new text ()" + +// Parameters: text, x, y, color, font, align, automap, onHover, onText +JSAPI_FUNC(text_ctor) +{ + Script* script = (Script*)JS_GetContextPrivate(cx); + + ScreenhookState state = (script->GetState () == OutOfGame) ? OOG : IG; + uint x = 0, y = 0; + ushort color = 0, font = 0; + Align align = Left; + bool automap = false; + jsval click = JSVAL_VOID, hover = JSVAL_VOID; + char* szText = ""; + + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + szText = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!szText) + return JS_TRUE; + if(argc > 1 && JSVAL_IS_INT(argv[1])) + x = JSVAL_TO_INT(argv[1]); + if(argc > 2 && JSVAL_IS_INT(argv[2])) + y = JSVAL_TO_INT(argv[2]); + if(argc > 3 && JSVAL_IS_INT(argv[3])) + color = (ushort)JSVAL_TO_INT(argv[3]); + if(argc > 4 && JSVAL_IS_INT(argv[4])) + font = (ushort)JSVAL_TO_INT(argv[4]); + if(argc > 5 && JSVAL_IS_INT(argv[5])) + align = (Align)JSVAL_TO_INT(argv[5]); + if(argc > 6 && JSVAL_IS_BOOLEAN(argv[6])) + automap = !!JSVAL_TO_BOOLEAN(argv[6]); + if(argc > 7 && JSVAL_IS_FUNCTION(cx, argv[7])) + click = argv[7]; + if(argc > 8 && JSVAL_IS_FUNCTION(cx, argv[8])) + hover = argv[8]; + + JSObject* hook = BuildObject(cx, &text_class, text_methods, text_props); + if(!hook) + THROW_ERROR(cx, "Failed to create text object"); + + TextHook* pTextHook = new TextHook(script, hook, szText, x, y, font, color, automap, align, state); + + if(!pTextHook) + THROW_ERROR(cx, "Failed to create texthook"); + + JS_SetPrivate(cx, hook, pTextHook); + pTextHook->SetClickHandler(click); + pTextHook->SetHoverHandler(hover); + + *rval = OBJECT_TO_JSVAL(hook); + + return JS_TRUE; +} + +JSAPI_PROP(text_getProperty) +{ + TextHook* pTextHook = (TextHook*)JS_GetPrivate(cx, obj); + if(!pTextHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case TEXT_X: + *vp = INT_TO_JSVAL(pTextHook->GetX()); + break; + case TEXT_Y: + *vp = INT_TO_JSVAL(pTextHook->GetY()); + break; + case TEXT_COLOR: + *vp = INT_TO_JSVAL(pTextHook->GetColor()); + break; + case TEXT_FONT: + *vp = INT_TO_JSVAL(pTextHook->GetFont()); + break; + case TEXT_TEXT: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pTextHook->GetText())); + break; + case TEXT_ALIGN: + *vp = INT_TO_JSVAL(pTextHook->GetAlign()); + break; + case TEXT_VISIBLE: + *vp = BOOLEAN_TO_JSVAL(pTextHook->GetIsVisible()); + break; + case TEXT_ZORDER: + *vp = INT_TO_JSVAL(pTextHook->GetZOrder()); + break; + case TEXT_ONCLICK: + *vp = pTextHook->GetClickHandler(); + break; + case TEXT_ONHOVER: + *vp = pTextHook->GetHoverHandler(); + break; + } + return JS_TRUE; +} + +JSAPI_PROP(text_setProperty) +{ + TextHook* pTextHook = (TextHook*)JS_GetPrivate(cx, obj); + if(!pTextHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case TEXT_X: + if(JSVAL_IS_INT(*vp)) + pTextHook->SetX(JSVAL_TO_INT(*vp)); + break; + case TEXT_Y: + if(JSVAL_IS_INT(*vp)) + pTextHook->SetY(JSVAL_TO_INT(*vp)); + break; + case TEXT_COLOR: + if(JSVAL_IS_INT(*vp)) + pTextHook->SetColor((ushort)JSVAL_TO_INT(*vp)); + break; + case TEXT_FONT: + if(JSVAL_IS_INT(*vp)) + pTextHook->SetFont((ushort)JSVAL_TO_INT(*vp)); + break; + case TEXT_TEXT: + if(JSVAL_IS_STRING(*vp)) + { + char* pText = JS_GetStringBytes(JS_ValueToString(cx, *vp)); + if(!pText) + return JS_TRUE; + pTextHook->SetText(pText); + } + break; + case TEXT_ALIGN: + if(JSVAL_IS_INT(*vp)) + pTextHook->SetAlign((Align)JSVAL_TO_INT(*vp)); + break; + case TEXT_VISIBLE: + if(JSVAL_IS_BOOLEAN(*vp)) + pTextHook->SetIsVisible(!!JSVAL_TO_BOOLEAN(*vp)); + break; + case TEXT_ZORDER: + if(JSVAL_IS_INT(*vp)) + pTextHook->SetZOrder((ushort)JSVAL_TO_INT(*vp)); + break; + case TEXT_ONCLICK: + pTextHook->SetClickHandler(*vp); + break; + case TEXT_ONHOVER: + pTextHook->SetHoverHandler(*vp); + break; + } + return JS_TRUE; +} + + +// Function to create a image which gets called on a "new Image ()" + +// Parameters: image, x, y, color, align, automap, onHover, onimage +JSAPI_FUNC(image_ctor) +{ + Script* script = (Script*)JS_GetContextPrivate(cx); + + ScreenhookState state = (script->GetState () == OutOfGame) ? OOG : IG; + uint x = 0, y = 0; + ushort color = 0; + Align align = Left; + bool automap = false; + jsval click = JSVAL_VOID, hover = JSVAL_VOID; + char* szText = ""; + char path[_MAX_FNAME+_MAX_PATH]; + + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + szText = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(!szText) + return JS_TRUE; + if(argc > 1 && JSVAL_IS_INT(argv[1])) + x = JSVAL_TO_INT(argv[1]); + if(argc > 2 && JSVAL_IS_INT(argv[2])) + y = JSVAL_TO_INT(argv[2]); + if(argc > 3 && JSVAL_IS_INT(argv[3])) + color = (ushort)JSVAL_TO_INT(argv[3]); + if(argc > 4 && JSVAL_IS_INT(argv[4])) + align = (Align)JSVAL_TO_INT(argv[4]); + if(argc > 5 && JSVAL_IS_BOOLEAN(argv[5])) + automap = !!JSVAL_TO_BOOLEAN(argv[5]); + if(argc > 6 && JSVAL_IS_FUNCTION(cx, argv[6])) + click = argv[6]; + if(argc > 7 && JSVAL_IS_FUNCTION(cx, argv[7])) + hover = argv[7]; + + if(!isValidPath(path)) + THROW_ERROR(cx, "Invalid image file path"); + + JSObject* hook = BuildObject(cx, &image_class, image_methods, image_props); + if(!hook) + THROW_ERROR(cx, "Failed to create image object"); + + sprintf_s(path, sizeof(path), "%s\\%s", Vars.szScriptPath, szText); + ImageHook* pImageHook = new ImageHook(script, hook, path, x, y, color, automap, align, state); + + if(!pImageHook) + THROW_ERROR(cx, "Failed to create ImageHook"); + + JS_SetPrivate(cx, hook, pImageHook); + pImageHook->SetClickHandler(click); + pImageHook->SetHoverHandler(hover); + + *rval = OBJECT_TO_JSVAL(hook); + + return JS_TRUE; +} + +JSAPI_PROP(image_getProperty) +{ + ImageHook* pImageHook = (ImageHook*)JS_GetPrivate(cx, obj); + if(!pImageHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case IMAGE_X: + *vp = INT_TO_JSVAL(pImageHook->GetX()); + break; + case IMAGE_Y: + *vp = INT_TO_JSVAL(pImageHook->GetY()); + break; + case IMAGE_LOCATION: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pImageHook->GetImage())); + break; + case IMAGE_ALIGN: + *vp = INT_TO_JSVAL(pImageHook->GetAlign()); + break; + case IMAGE_VISIBLE: + *vp = BOOLEAN_TO_JSVAL(pImageHook->GetIsVisible()); + break; + case IMAGE_ZORDER: + *vp = INT_TO_JSVAL(pImageHook->GetZOrder()); + break; + case IMAGE_ONCLICK: + *vp = pImageHook->GetClickHandler(); + break; + case IMAGE_ONHOVER: + *vp = pImageHook->GetHoverHandler(); + break; + } + return JS_TRUE; +} + +JSAPI_PROP(image_setProperty) +{ + ImageHook* pImageHook = (ImageHook*)JS_GetPrivate(cx, obj); + if(!pImageHook) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) { + case IMAGE_X: + if(JSVAL_IS_INT(*vp)) + pImageHook->SetX(JSVAL_TO_INT(*vp)); + break; + case IMAGE_Y: + if(JSVAL_IS_INT(*vp)) + pImageHook->SetY(JSVAL_TO_INT(*vp)); + break; + case IMAGE_LOCATION: + if(JSVAL_IS_STRING(*vp)) + { + char* pimage = JS_GetStringBytes(JS_ValueToString(cx, *vp)); + if(!pimage) + return JS_TRUE; + pImageHook->SetImage(pimage); + } + break; + case IMAGE_ALIGN: + if(JSVAL_IS_INT(*vp)) + pImageHook->SetAlign((Align)JSVAL_TO_INT(*vp)); + break; + case IMAGE_VISIBLE: + if(JSVAL_IS_BOOLEAN(*vp)) + pImageHook->SetIsVisible(!!JSVAL_TO_BOOLEAN(*vp)); + break; + case IMAGE_ZORDER: + if(JSVAL_IS_INT(*vp)) + pImageHook->SetZOrder((ushort)JSVAL_TO_INT(*vp)); + break; + case IMAGE_ONCLICK: + pImageHook->SetClickHandler(*vp); + break; + case IMAGE_ONHOVER: + pImageHook->SetHoverHandler(*vp); + break; + } + return JS_TRUE; +} + +JSAPI_FUNC(screenToAutomap) +{ + if(argc == 1) + { + // the arg must be an object with an x and a y that we can convert + if(JSVAL_IS_OBJECT(argv[0])) + { + // get the params + JSObject* arg = JSVAL_TO_OBJECT(argv[0]); + jsval x, y; + if(JS_GetProperty(cx, arg, "x", &x) == JS_FALSE || JS_GetProperty(cx, arg, "y", &y) == JS_FALSE) + THROW_ERROR(cx, "Failed to get x and/or y values"); + if(!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) + THROW_ERROR(cx, "Input has an x or y, but they aren't the correct type!"); + int32 ix, iy; + if(JS_ValueToInt32(cx, x, &ix) == JS_FALSE || JS_ValueToInt32(cx, y, &iy)) + THROW_ERROR(cx, "Failed to convert x and/or y values"); + // convert the values + POINT result = {ix * 32, iy * 32}; + ScreenToAutomap(&result); + x = INT_TO_JSVAL(result.x); + y = INT_TO_JSVAL(result.y); + JSObject* res = JS_NewObject(cx, NULL, NULL, NULL); + if(JS_SetProperty(cx, res, "x", &argv[0]) == JS_FALSE || JS_SetProperty(cx, res, "y", &argv[1]) == JS_FALSE) + THROW_ERROR(cx, "Failed to set x and/or y values"); + *rval = OBJECT_TO_JSVAL(res); + } + else + THROW_ERROR(cx, "Invalid object specified to screenToAutomap"); + } + else if(argc == 2) + { + // the args must be ints + if(JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1])) + { + int32 ix, iy; + if(JS_ValueToInt32(cx, argv[0], &ix) == JS_FALSE || JS_ValueToInt32(cx, argv[1], &iy) == JS_FALSE) + THROW_ERROR(cx, "Failed to convert x and/or y values"); + // convert the values + POINT result = {ix * 32, iy * 32}; + ScreenToAutomap(&result); + argv[0] = INT_TO_JSVAL(result.x); + argv[1] = INT_TO_JSVAL(result.y); + JSObject* res = JS_NewObject(cx, NULL, NULL, NULL); + if(JS_SetProperty(cx, res, "x", &argv[0]) == JS_FALSE || JS_SetProperty(cx, res, "y", &argv[1]) == JS_FALSE) + THROW_ERROR(cx, "Failed to set x and/or y values"); + *rval = OBJECT_TO_JSVAL(res); + } + else + THROW_ERROR(cx, "screenToAutomap expects two arguments to be two integers"); + } + else + THROW_ERROR(cx, "Invalid arguments specified for screenToAutomap"); + return JS_TRUE; +} + +JSAPI_FUNC(automapToScreen) +{ + if(argc == 1) + { + // the arg must be an object with an x and a y that we can convert + if(JSVAL_IS_OBJECT(argv[0])) + { + // get the params + JSObject* arg = JSVAL_TO_OBJECT(argv[0]); + jsval x, y; + if(JS_GetProperty(cx, arg, "x", &x) == JS_FALSE || JS_GetProperty(cx, arg, "y", &y) == JS_FALSE) + THROW_ERROR(cx, "Failed to get x and/or y values"); + if(!JSVAL_IS_INT(x) || !JSVAL_IS_INT(y)) + THROW_ERROR(cx, "Input has an x or y, but they aren't the correct type!"); + int32 ix, iy; + if(JS_ValueToInt32(cx, x, &ix) == JS_FALSE || JS_ValueToInt32(cx, y, &iy)) + THROW_ERROR(cx, "Failed to convert x and/or y values"); + // convert the values + POINT result = {ix,iy}; + AutomapToScreen(&result); + x = INT_TO_JSVAL(ix); + y = INT_TO_JSVAL(iy); + if(JS_SetProperty(cx, arg, "x", &x) == JS_FALSE || JS_SetProperty(cx, arg, "y", &y) == JS_FALSE) + THROW_ERROR(cx, "Failed to set x and/or y values"); + *rval = OBJECT_TO_JSVAL(arg); + } + else + THROW_ERROR(cx, "Invalid object specified to automapToScreen"); + } + else if(argc == 2) + { + // the args must be ints + if(JSVAL_IS_INT(argv[0]) && JSVAL_IS_INT(argv[1])) + { + int32 ix, iy; + if(JS_ValueToInt32(cx, argv[0], &ix) == JS_FALSE || JS_ValueToInt32(cx, argv[1], &iy) == JS_FALSE) + THROW_ERROR(cx, "Failed to convert x and/or y values"); + // convert the values + POINT result = {ix,iy}; + AutomapToScreen(&result); + argv[0] = INT_TO_JSVAL(result.x); + argv[1] = INT_TO_JSVAL(result.y); + JSObject* res = JS_NewObject(cx, NULL, NULL, NULL); + if(JS_SetProperty(cx, res, "x", &argv[0]) == JS_FALSE || JS_SetProperty(cx, res, "y", &argv[1]) == JS_FALSE) + THROW_ERROR(cx, "Failed to set x and/or y values"); + *rval = OBJECT_TO_JSVAL(res); + } + else + THROW_ERROR(cx, "automapToScreen expects two arguments to be two integers"); + } + else + THROW_ERROR(cx, "Invalid arguments specified for automapToScreen"); + return JS_TRUE; +} + diff --git a/JSScreenHook.h b/JSScreenHook.h new file mode 100644 index 00000000..375cca6c --- /dev/null +++ b/JSScreenHook.h @@ -0,0 +1,202 @@ +#ifndef __JSSCREENHOOK_H__ +#define __JSSCREENHOOK_H__ + +#include "js32.h" + +JSAPI_FUNC(hook_remove); +void hook_finalize(JSContext *cx, JSObject *obj); + +/********************************************************* + Frame Header +**********************************************************/ +JSAPI_FUNC(frame_ctor); +JSAPI_PROP(frame_getProperty); +JSAPI_PROP(frame_setProperty); + +enum frame_tinyid { + FRAME_X, + FRAME_Y, + FRAME_XSIZE, + FRAME_YSIZE, + FRAME_VISIBLE, + FRAME_ALIGN, + FRAME_ONCLICK, + FRAME_ONHOVER, + FRAME_ZORDER +}; + +static JSPropertySpec frame_props[] = { + {"x", FRAME_X, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"y", FRAME_Y, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"xsize", FRAME_XSIZE, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"ysize", FRAME_YSIZE, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"visible", FRAME_VISIBLE, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"align", FRAME_ALIGN, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"zorder", FRAME_ZORDER, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"click", FRAME_ONCLICK, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {"hover", FRAME_ONHOVER, JSPROP_STATIC_VAR, frame_getProperty, frame_setProperty}, + {0}, +}; + +static JSFunctionSpec frame_methods[] = { + {"remove", hook_remove, 0}, + {0}, +}; + +/********************************************************* + box Header +**********************************************************/ +JSAPI_FUNC(box_ctor); +JSAPI_PROP(box_getProperty); +JSAPI_PROP(box_setProperty); + +enum box_tinyid { + BOX_X, + BOX_Y, + BOX_XSIZE, + BOX_YSIZE, + BOX_COLOR, + BOX_OPACITY, + BOX_VISIBLE, + BOX_ALIGN, + BOX_ONCLICK, + BOX_ONHOVER, + BOX_ZORDER +}; + +static JSPropertySpec box_props[] = { + {"x", BOX_X, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"y", BOX_Y, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"xsize", BOX_XSIZE, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"ysize", BOX_YSIZE, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"visible", BOX_VISIBLE, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"color", BOX_COLOR, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"opacity", BOX_OPACITY, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"align", BOX_ALIGN, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"zorder", BOX_ZORDER, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"click", BOX_ONCLICK, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {"hover", BOX_ONHOVER, JSPROP_STATIC_VAR, box_getProperty, box_setProperty}, + {0}, +}; + +static JSFunctionSpec box_methods[] = { + {"remove", hook_remove, 0}, + {0}, +}; + + +/********************************************************* + Line Header +**********************************************************/ +JSAPI_FUNC(line_ctor); +JSAPI_PROP(line_getProperty); +JSAPI_PROP(line_setProperty); + +enum line_tinyid { + LINE_X, + LINE_Y, + LINE_XSIZE, + LINE_YSIZE, + LINE_COLOR, + LINE_VISIBLE, + LINE_ONCLICK, + LINE_ONHOVER, + LINE_ZORDER +}; + +static JSPropertySpec line_props[] = { + {"x", LINE_X, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"y", LINE_Y, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"x2", LINE_XSIZE, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"y2", LINE_YSIZE, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"visible", LINE_VISIBLE, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"color", LINE_COLOR, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"zorder", LINE_ZORDER, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"click", LINE_ONCLICK, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {"hover", LINE_ONHOVER, JSPROP_STATIC_VAR, line_getProperty, line_setProperty}, + {0}, +}; + +static JSFunctionSpec line_methods[] = { + {"remove", hook_remove, 0}, + {0}, +}; + +/********************************************************* + Text Header +**********************************************************/ +JSAPI_FUNC(text_ctor); +JSAPI_PROP(text_getProperty); +JSAPI_PROP(text_setProperty); + +enum text_tinyid { + TEXT_X, + TEXT_Y, + TEXT_COLOR, + TEXT_FONT, + TEXT_TEXT, + TEXT_ALIGN, + TEXT_VISIBLE, + TEXT_ONCLICK, + TEXT_ONHOVER, + TEXT_ZORDER +}; + +static JSPropertySpec text_props[] = { + {"x", TEXT_X, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"y", TEXT_Y, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"color", TEXT_COLOR, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"font", TEXT_FONT, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"visible", TEXT_VISIBLE, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"text", TEXT_TEXT, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"align", TEXT_ALIGN, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"zorder", TEXT_ZORDER, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"click", TEXT_ONCLICK, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {"hover", TEXT_ONHOVER, JSPROP_STATIC_VAR, text_getProperty, text_setProperty}, + {0}, +}; + +static JSFunctionSpec text_methods[] = { + {"remove", hook_remove, 0}, + {0}, +}; + +/********************************************************* + Image Header +**********************************************************/ +JSAPI_FUNC(image_ctor); +JSAPI_PROP(image_getProperty); +JSAPI_PROP(image_setProperty); + +enum image_tinyid { + IMAGE_X, + IMAGE_Y, + IMAGE_LOCATION, + IMAGE_ALIGN, + IMAGE_VISIBLE, + IMAGE_ONCLICK, + IMAGE_ONHOVER, + IMAGE_ZORDER +}; + +static JSPropertySpec image_props[] = { + {"x", IMAGE_X, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"y", IMAGE_Y, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"visible", IMAGE_VISIBLE, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"location",IMAGE_LOCATION, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"align", IMAGE_ALIGN, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"zorder", IMAGE_ZORDER, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"click", IMAGE_ONCLICK, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {"hover", IMAGE_ONHOVER, JSPROP_STATIC_VAR, image_getProperty, image_setProperty}, + {0}, +}; + +static JSFunctionSpec image_methods[] = { + {"remove", hook_remove, 0}, + {0}, +}; + +JSAPI_FUNC(screenToAutomap); +JSAPI_FUNC(automapToScreen); + +#endif diff --git a/JSScript.cpp b/JSScript.cpp new file mode 100644 index 00000000..9d387275 --- /dev/null +++ b/JSScript.cpp @@ -0,0 +1,180 @@ +#include "JSScript.h" +#include "Script.h" +#include "ScriptEngine.h" +#include "D2BS.h" +#include "Helpers.h" + +EMPTY_CTOR(script) + +struct FindHelper +{ + DWORD tid; + char* name; + Script* script; +}; + +bool __fastcall FindScriptByTid(Script* script, void* argv, uint argc); +bool __fastcall FindScriptByName(Script* script, void* argv, uint argc); + +JSAPI_PROP(script_getProperty) +{ + JSContext* iterp = (JSContext*)JS_GetInstancePrivate(cx, obj, &script_class, NULL); + Script* script = (Script*)JS_GetContextPrivate(iterp); + + // TODO: make this check stronger + if(!script) + return JS_TRUE; + + switch(JSVAL_TO_INT(id)) + { + case SCRIPT_FILENAME: + *vp = STRING_TO_JSVAL(JS_InternString(cx, script->GetShortFilename())); + break; + case SCRIPT_GAMETYPE: + *vp = script->GetState() == InGame ? INT_TO_JSVAL(0) : INT_TO_JSVAL(1); + break; + case SCRIPT_RUNNING: + *vp = BOOLEAN_TO_JSVAL(script->IsRunning()); + break; + case SCRIPT_THREADID: + *vp = INT_TO_JSVAL(script->GetThreadId()); + break; + default: + break; + } + + return JS_TRUE; +} + +JSAPI_FUNC(script_getNext) +{ + JSContext* iterp = (JSContext*)JS_GetInstancePrivate(cx, obj, &script_class, NULL); + if(JS_ContextIterator(ScriptEngine::GetRuntime(), &iterp) == NULL || !JS_GetContextPrivate(iterp)) + *rval = JSVAL_FALSE; + else + { + JS_SetPrivate(cx, obj, iterp); + *rval = JSVAL_TRUE; + } + + return JS_TRUE; +} + +JSAPI_FUNC(script_stop) +{ + JSContext* iterp = (JSContext*)JS_GetInstancePrivate(cx, obj, &script_class, NULL); + Script* script = (Script*)JS_GetContextPrivate(iterp); + if(script->IsRunning()) + script->Stop(); + + return JS_TRUE; +} + +JSAPI_FUNC(script_pause) +{ + JSContext* iterp = (JSContext*)JS_GetInstancePrivate(cx, obj, &script_class, NULL); + Script* script = (Script*)JS_GetContextPrivate(iterp); + + if(script->IsRunning()) + script->Pause(); + + return JS_TRUE; +} + +JSAPI_FUNC(script_resume) +{ + JSContext* iterp = (JSContext*)JS_GetInstancePrivate(cx, obj, &script_class, NULL); + Script* script = (Script*)JS_GetContextPrivate(iterp); + + if(script->IsPaused()) + script->Resume(); + + return JS_TRUE; +} + +JSAPI_FUNC(script_send) +{ + JSContext* iterp = (JSContext*)JS_GetInstancePrivate(cx, obj, &script_class, NULL); + Script* script = (Script*)JS_GetContextPrivate(iterp); + + AutoRoot** args = new AutoRoot*[argc]; + for(uintN i = 0; i < argc; i++) + args[i] = new AutoRoot(argv[i]); + + // this event has to occur as such because it's not a broadcasted event, just a local one + script->ExecEventAsync("scriptmsg", argc, args); + + return JS_TRUE; +} + +JSAPI_FUNC(my_getScript) +{ + JSContext* iterp = NULL; + if(argc == 1 && JSVAL_IS_BOOLEAN(argv[0]) && JSVAL_TO_BOOLEAN(argv[0]) == JS_TRUE) + iterp = cx; + else if(argc == 1 && JSVAL_IS_INT(argv[0])) + { + // loop over the Scripts in ScriptEngine and find the one with the right threadid + DWORD tid = (DWORD)JSVAL_TO_INT(argv[0]); + FindHelper args = {tid, NULL, NULL}; + ScriptEngine::ForEachScript(FindScriptByTid, &args, 1); + if(args.script != NULL) + iterp = args.script->GetContext(); + else + return JS_TRUE; + } + else if(argc == 1 && JSVAL_IS_STRING(argv[0])) + { + char* name = JS_GetStringBytes(JSVAL_TO_STRING(argv[0])); + if(name) + StringReplace(name, '/', '\\', strlen(name)); + FindHelper args = {0, name, NULL}; + ScriptEngine::ForEachScript(FindScriptByName, &args, 1); + if(args.script != NULL) + iterp = args.script->GetContext(); + else + return JS_TRUE; + } + else + { + // find the first context that has private data + while(JS_ContextIterator(ScriptEngine::GetRuntime(), &iterp) != NULL) + if(JS_GetContextPrivate(iterp) != NULL) + break; + + if(iterp == NULL) + return JS_TRUE; + } + + JSObject* res = BuildObject(cx, &script_class, script_methods, script_props, iterp); + + if(!res) + THROW_ERROR(cx, "Failed to build the script object"); + *rval = OBJECT_TO_JSVAL(res); + + return JS_TRUE; +} + +bool __fastcall FindScriptByName(Script* script, void* argv, uint argc) +{ + FindHelper* helper = (FindHelper*)argv; + static uint pathlen = strlen(Vars.szScriptPath) + 1; + const char* fname = script->GetShortFilename(); + if(_strcmpi(fname, helper->name) == 0) + { + helper->script = script; + return false; + } + return true; +} + +bool __fastcall FindScriptByTid(Script* script, void* argv, uint argc) +{ + FindHelper* helper = (FindHelper*)argv; + if(script->GetThreadId() == helper->tid) + { + helper->script = script; + return false; + } + return true; +} diff --git a/JSScript.h b/JSScript.h new file mode 100644 index 00000000..66ff646d --- /dev/null +++ b/JSScript.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include "Script.h" + +#include "js32.h" + +CLASS_CTOR(script); + +JSAPI_PROP(script_getProperty); + +JSAPI_FUNC(script_getNext); +JSAPI_FUNC(script_stop); +JSAPI_FUNC(script_send); +JSAPI_FUNC(script_pause); +JSAPI_FUNC(script_resume); +JSAPI_FUNC(my_getScript); + +enum script_tinyid { + SCRIPT_FILENAME, + SCRIPT_GAMETYPE, + SCRIPT_RUNNING, + SCRIPT_THREADID, +}; + +static JSPropertySpec script_props[] = { + {"name", SCRIPT_FILENAME, JSPROP_PERMANENT_VAR, script_getProperty}, + {"type", SCRIPT_GAMETYPE, JSPROP_PERMANENT_VAR, script_getProperty}, + {"running", SCRIPT_RUNNING, JSPROP_PERMANENT_VAR, script_getProperty}, + {"threadid", SCRIPT_THREADID, JSPROP_PERMANENT_VAR, script_getProperty}, + {0}, +}; + +static JSFunctionSpec script_methods[] = { + {"getNext", script_getNext, 0}, + {"pause", script_pause, 0}, + {"resume", script_resume, 0}, + {"stop", script_stop, 0}, + {"send", script_send, 1}, + {0}, +}; diff --git a/JSUnit.cpp b/JSUnit.cpp new file mode 100644 index 00000000..075d4363 --- /dev/null +++ b/JSUnit.cpp @@ -0,0 +1,1844 @@ +#include "JSUnit.h" +#include "D2Helpers.h" +#include "Constants.h" +#include "Helpers.h" +#include "Unit.h" +#include "Core.h" +#include "CriticalSections.h" +#include "D2Skills.h" +#include "MPQStats.h" + +EMPTY_CTOR(unit) + +void unit_finalize(JSContext *cx, JSObject *obj) +{ + Private* lpUnit = (Private*)JS_GetPrivate(cx, obj); + + if(lpUnit) + { + switch(lpUnit->dwPrivateType) + { + case PRIVATE_UNIT: + { + myUnit* unit = (myUnit*)lpUnit; + delete unit; + break; + } + case PRIVATE_ITEM: + { + invUnit* unit = (invUnit*)lpUnit; + delete unit; + break; + } + } + } + JS_SetPrivate(cx, obj, NULL); +} + +JSBool unit_equal(JSContext *cx, JSObject *obj, jsval v, JSBool *bp) +{ + if(ClientState() == ClientStateInGame) { + *bp = JS_InstanceOf(cx, obj, &unit_class_ex.base, NULL); + myUnit* one = (myUnit*)JS_GetInstancePrivate(cx, obj, &unit_class_ex.base, NULL); + myUnit* two = (myUnit*)JS_GetInstancePrivate(cx, obj, &unit_class_ex.base, NULL); + UnitAny* pUnit1 = D2CLIENT_FindUnit(one->dwUnitId, one->dwType); + UnitAny* pUnit2 = D2CLIENT_FindUnit(two->dwUnitId, two->dwType); + if(!pUnit1 || !pUnit2 || pUnit1->dwUnitId != pUnit2->dwUnitId) + *bp = JS_FALSE; + } + return JS_TRUE; +} + +JSAPI_PROP(unit_getProperty) +{ + BnetData* pData = *p_D2LAUNCH_BnData; + GameStructInfo* pInfo = *p_D2CLIENT_GameInfo; + switch(JSVAL_TO_INT(id)) + { + case ME_PID: + JS_NewNumberValue(cx, (jsdouble)GetCurrentProcessId(), vp); + break; + case ME_PROFILE: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, Vars.szProfile)); + break; + case ME_GAMEREADY: + *vp = BOOLEAN_TO_JSVAL(GameReady()); + break; + case ME_ACCOUNT: + if(!pData) + return JS_TRUE; + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szAccountName)); + break; + case ME_CHARNAME: + if(!pInfo) + return JS_TRUE; + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szCharName)); + break; + case ME_CHICKENHP: + *vp = INT_TO_JSVAL(Vars.nChickenHP); + break; + case ME_CHICKENMP: + *vp = INT_TO_JSVAL(Vars.nChickenMP); + break; + case ME_DIFF: + *vp = INT_TO_JSVAL(D2CLIENT_GetDifficulty()); + break; + case ME_GAMENAME: + if(!pInfo) + return JS_TRUE; + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGameName)); + break; + case ME_GAMEPASSWORD: + if(!pInfo) + return JS_TRUE; + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGamePassword)); + break; + case ME_GAMESERVERIP: + if(!pInfo) + return JS_TRUE; + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGameServerIp)); + break; + case ME_GAMESTARTTIME: + JS_NewNumberValue(cx, (jsdouble)Vars.dwGameTime, vp); + //*vp = INT_TO_JSVAL(Vars.dwGameTime); + break; + case ME_GAMETYPE: + *vp = INT_TO_JSVAL(*p_D2CLIENT_ExpCharFlag); + break; + case ME_PLAYERTYPE: + if(pData) + *vp = INT_TO_JSVAL(((pData->nCharFlags & PLAYER_TYPE_HARDCORE) == TRUE)); + break; + case ME_ITEMONCURSOR: + *vp = BOOLEAN_TO_JSVAL(!!D2CLIENT_GetCursorItem()); + break; + case ME_LADDER: + if(pData) + *vp = BOOLEAN_TO_JSVAL(((pData->nCharFlags & PLAYER_TYPE_LADDER) == TRUE)); + break; + case ME_QUITONHOSTILE: + *vp = BOOLEAN_TO_JSVAL(Vars.bQuitOnHostile); + break; + case ME_REALM: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szRealmName)); + break; + case ME_REALMSHORT: + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szRealmName2)); + break; + case OOG_SCREENSIZE: + *vp = INT_TO_JSVAL(D2GFX_GetScreenSize()); + break; + case OOG_WINDOWTITLE: + char szTitle[128]; + GetWindowText(D2GFX_GetHwnd(), szTitle, 128); + *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szTitle)); + break; + case ME_PING: + *vp = INT_TO_JSVAL(*p_D2CLIENT_Ping); + break; + case ME_FPS: + *vp = INT_TO_JSVAL(*p_D2CLIENT_FPS); + break; + case OOG_INGAME: + *vp = (ClientState() == ClientStateMenu ? JSVAL_FALSE : JSVAL_TRUE); + break; + case OOG_QUITONERROR: + *vp = BOOLEAN_TO_JSVAL(Vars.bQuitOnError); + break; + case OOG_MAXGAMETIME: + *vp = INT_TO_JSVAL(Vars.dwMaxGameTime); + break; + case ME_MERCREVIVECOST: + *vp = INT_TO_JSVAL((*p_D2CLIENT_MercReviveCost)); + break; + case ME_BLOCKKEYS: + *vp = BOOLEAN_TO_JSVAL(Vars.bBlockKeys); + break; + case ME_BLOCKMOUSE: + *vp = BOOLEAN_TO_JSVAL(Vars.bBlockMouse); + break; + default: + break; + } + + if(ClientState() != ClientStateInGame) + return JS_TRUE; + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + if(!pUnit) + return JS_TRUE; + Room1* pRoom = NULL; + + switch(JSVAL_TO_INT(id)) + { + case UNIT_TYPE: + *vp = INT_TO_JSVAL(pUnit->dwType); + break; + case UNIT_CLASSID: + *vp = INT_TO_JSVAL(pUnit->dwTxtFileNo); + break; + case UNIT_MODE: + *vp = INT_TO_JSVAL(pUnit->dwMode); + break; + case UNIT_NAME: + { + char tmp[128] = ""; + GetUnitName(pUnit, tmp, 128); + *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); + } + break; + case ME_MAPID: + *vp = INT_TO_JSVAL(*p_D2CLIENT_MapId); + break; + case ME_NOPICKUP: + *vp = BOOLEAN_TO_JSVAL(!!*p_D2CLIENT_NoPickUp); + break; + case UNIT_ACT: + *vp = INT_TO_JSVAL(pUnit->dwAct + 1); + break; + case UNIT_AREA: + pRoom = D2COMMON_GetRoomFromUnit(pUnit); + if(pRoom && pRoom->pRoom2 && pRoom->pRoom2->pLevel) + *vp = INT_TO_JSVAL(pRoom->pRoom2->pLevel->dwLevelNo); + break; + case UNIT_ID: + JS_NewNumberValue(cx, (jsdouble)pUnit->dwUnitId, vp); + break; + case UNIT_XPOS: + *vp = INT_TO_JSVAL(D2CLIENT_GetUnitX(pUnit)); + break; + case UNIT_YPOS: + *vp = INT_TO_JSVAL(D2CLIENT_GetUnitY(pUnit)); + break; + case UNIT_HP: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 6, 0) >> 8); + break; + case UNIT_HPMAX: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 7, 0) >> 8); + break; + case UNIT_MP: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 8, 0) >> 8); + break; + case UNIT_MPMAX: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 9, 0) >> 8); + break; + case UNIT_STAMINA: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 10, 0) >> 8); + break; + case UNIT_STAMINAMAX: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 11, 0) >> 8); + break; + case UNIT_CHARLVL: + *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 12, 0)); + break; + case ME_RUNWALK: + if(pUnit == D2CLIENT_GetPlayerUnit()) + *vp = INT_TO_JSVAL(*p_D2CLIENT_AlwaysRun); + break; + case UNIT_SPECTYPE: + DWORD SpecType; + SpecType = NULL; + if(pUnit->dwType == UNIT_MONSTER && pUnit->pMonsterData) + { + if(pUnit->pMonsterData->fMinion & 1) + SpecType |= 0x08; + if(pUnit->pMonsterData->fBoss & 1) + SpecType |= 0x04; + if(pUnit->pMonsterData->fChamp & 1) + SpecType |= 0x02; + if((pUnit->pMonsterData->fBoss & 1) && (pUnit->pMonsterData->fNormal & 1)) + SpecType |= 0x01; + if(pUnit->pMonsterData->fNormal & 1) + SpecType |= 0x00; + *vp = INT_TO_JSVAL(SpecType); + return JS_TRUE; + } + break; + case UNIT_UNIQUEID: + if(pUnit->dwType == UNIT_MONSTER && pUnit->pMonsterData->fBoss && pUnit->pMonsterData->fNormal) + *vp = INT_TO_JSVAL(pUnit->pMonsterData->wUniqueNo); + else + *vp = INT_TO_JSVAL(-1); + break; + case ITEM_CODE: // replace with better method if found + if(!(pUnit->dwType == UNIT_ITEM) && pUnit->pItemData) + break; + ItemTxt* pTxt; + pTxt = D2COMMON_GetItemText(pUnit->dwTxtFileNo); + if(!pTxt) { + *vp = STRING_TO_JSVAL(JS_InternString(cx, "Unknown")); + return JS_TRUE; + } + char szCode[4]; + memcpy(szCode, pTxt->szCode, 3); + szCode[3] = 0x00; + *vp = STRING_TO_JSVAL(JS_InternString(cx, szCode)); + break; + case ITEM_PREFIX: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + if (D2COMMON_GetItemMagicalMods(pUnit->pItemData->wPrefix)) + *vp = STRING_TO_JSVAL(JS_InternString(cx, D2COMMON_GetItemMagicalMods(pUnit->pItemData->wPrefix))); + break; + case ITEM_SUFFIX: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + if (D2COMMON_GetItemMagicalMods(pUnit->pItemData->wSuffix)) + *vp = STRING_TO_JSVAL(JS_InternString(cx, D2COMMON_GetItemMagicalMods(pUnit->pItemData->wSuffix))); + break; + case ITEM_PREFIXNUM: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->wPrefix); + break; + case ITEM_SUFFIXNUM: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->wSuffix); + break; + case ITEM_FNAME: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { + wchar_t wszfname[256] = L""; + D2CLIENT_GetItemName(pUnit, wszfname, sizeof(wszfname)); + if(wszfname) { + char* tmp = UnicodeToAnsi(wszfname); + *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); + delete[] tmp; + tmp = NULL; + } + } + break; + case ITEM_QUALITY: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->dwQuality); + break; + case ITEM_NODE: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->NodePage); + break; + case ITEM_LOC: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->ItemLocation); + break; + case ITEM_SIZEX: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { + if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo)) + break; + *vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->xSize); + } + break; + case ITEM_SIZEY: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { + if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo)) + break; + *vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->ySize); + } + break; + case ITEM_TYPE: + if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { + if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo)) + break; + *vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->nType); + } + break; + case ITEM_DESC: + { + if(pUnit->dwType != UNIT_ITEM) + break; + + wchar_t wBuffer[2048] = L""; + D2CLIENT_GetItemDesc(pUnit, wBuffer); + + char *tmp = UnicodeToAnsi(wBuffer); + if(tmp) + { + *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); + delete[] tmp; + tmp = NULL; + } + } + break; + case UNIT_ITEMCOUNT: + if(pUnit->pInventory) + *vp = INT_TO_JSVAL(pUnit->pInventory->dwItemCount); + break; + case ITEM_BODYLOCATION: + if(pUnit->dwType != UNIT_ITEM) + break; + if(pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->BodyLocation); + break; + case UNIT_OWNER: + *vp = INT_TO_JSVAL(pUnit->dwOwnerId); + break; + case UNIT_OWNERTYPE: + *vp = INT_TO_JSVAL(pUnit->dwOwnerType); + break; + case ITEM_LEVEL: + if(pUnit->dwType != UNIT_ITEM) + break; + if(pUnit->pItemData) + *vp = INT_TO_JSVAL(pUnit->pItemData->dwItemLevel); + break; + case ITEM_LEVELREQ: + if(pUnit->dwType != UNIT_ITEM) + break; + *vp = INT_TO_JSVAL(D2COMMON_GetItemLevelRequirement(pUnit, D2CLIENT_GetPlayerUnit())); + break; + case UNIT_DIRECTION: + if(pUnit->pPath) + *vp = INT_TO_JSVAL(pUnit->pPath->bDirection); + break; + case OBJECT_TYPE: + if(pUnit->dwType == UNIT_OBJECT && pUnit->pObjectData) + { + pRoom = D2COMMON_GetRoomFromUnit(pUnit); + if(pRoom && D2COMMON_IsTownByRoom(pRoom)) + *vp = INT_TO_JSVAL(pUnit->pObjectData->Type & 255); + else + *vp = INT_TO_JSVAL(pUnit->pObjectData->Type); + } + break; + case OBJECT_LOCKED: + if(pUnit->dwType == UNIT_OBJECT && pUnit->pObjectData) + *vp = INT_TO_JSVAL( pUnit->pObjectData->ChestLocked ); + break; + case ME_WSWITCH: + if(pUnit == D2CLIENT_GetPlayerUnit()) + *vp = INT_TO_JSVAL(*p_D2CLIENT_bWeapSwitch); + break; + default: + break; + } + + return JS_TRUE; +} + +JSAPI_PROP(unit_setProperty) +{ + switch(JSVAL_TO_INT(id)) + { + case ME_CHICKENHP: + if(JSVAL_IS_INT(*vp)) + Vars.nChickenHP = JSVAL_TO_INT(*vp); + break; + case ME_CHICKENMP: + if(JSVAL_IS_INT(*vp)) + Vars.nChickenMP = JSVAL_TO_INT(*vp); + break; + case ME_QUITONHOSTILE: + if(JSVAL_IS_BOOLEAN(*vp)) + Vars.bQuitOnHostile = JSVAL_TO_BOOLEAN(*vp); + break; + case OOG_QUITONERROR: + if(JSVAL_IS_BOOLEAN(*vp)) + Vars.bQuitOnError = JSVAL_TO_BOOLEAN(*vp); + break; + case OOG_MAXGAMETIME: + if(JSVAL_IS_INT(*vp)) + Vars.dwMaxGameTime = JSVAL_TO_INT(*vp); + break; + case ME_BLOCKKEYS: + if(JSVAL_IS_BOOLEAN(*vp)) + Vars.bBlockKeys = JSVAL_TO_BOOLEAN(*vp); + break; + case ME_BLOCKMOUSE: + if(JSVAL_IS_BOOLEAN(*vp)) + Vars.bBlockMouse = JSVAL_TO_BOOLEAN(*vp); + break; + case ME_RUNWALK: + { + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + if(!pUnit) + return JS_TRUE; + if(pUnit == D2CLIENT_GetPlayerUnit()) + *p_D2CLIENT_AlwaysRun = !!JSVAL_TO_INT(*vp); + } + break; + case ME_NOPICKUP: + *p_D2CLIENT_NoPickUp = !!JSVAL_TO_INT(*vp); + break; + } + return JS_TRUE; +} + +JSAPI_FUNC(unit_getUnit) +{ + if(argc < 1) + return JS_TRUE; + + int nType = -1; + uint32 nClassId = (uint32)-1; + uint32 nMode = (uint32)-1; + uint32 nUnitId = (uint32)-1; + char szName[128] = ""; + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + nType = JSVAL_TO_INT(argv[0]); + + if(argc > 1 && JSVAL_IS_STRING(argv[1])) + strcpy_s(szName, sizeof(szName), JS_GetStringBytes(JS_ValueToString(cx, argv[1]))); + + if(argc > 1 && JSVAL_IS_NUMBER(argv[1]) && !JSVAL_IS_NULL(argv[1])) + JS_ValueToECMAUint32(cx, argv[1], &nClassId); + + if(argc > 2 && JSVAL_IS_NUMBER(argv[2]) && !JSVAL_IS_NULL(argv[2])) + JS_ValueToECMAUint32(cx, argv[2], &nMode); + + if(argc > 3 && JSVAL_IS_NUMBER(argv[3]) && !JSVAL_IS_NULL(argv[3])) + JS_ValueToECMAUint32(cx, argv[3], &nUnitId); + + UnitAny* pUnit = NULL; + + if(nType == 100) + pUnit = D2CLIENT_GetCursorItem(); + else if(nType == 101) + { + pUnit = D2CLIENT_GetSelectedUnit(); + if(!pUnit) + pUnit = (*p_D2CLIENT_SelectedInvItem); + } + else + pUnit = GetUnit(szName, nClassId, nType, nMode, nUnitId); + + if(!pUnit) + return JS_TRUE; + + myUnit* pmyUnit = new myUnit; // leaked? + + if(!pmyUnit) + return JS_TRUE; + + pmyUnit->_dwPrivateType = PRIVATE_UNIT; + pmyUnit->dwClassId = nClassId; + pmyUnit->dwMode = nMode; + pmyUnit->dwType = pUnit->dwType; + pmyUnit->dwUnitId = pUnit->dwUnitId; + strcpy_s(pmyUnit->szName, sizeof(pmyUnit->szName), szName); + + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyUnit); + + if(!jsunit) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(jsunit); + + return JS_TRUE; +} + +JSAPI_FUNC(unit_getNext) +{ + Private* unit = (Private*)JS_GetPrivate(cx, obj); + + if(!unit) + return JS_TRUE; + + if(unit->dwPrivateType == PRIVATE_UNIT) + { + myUnit* lpUnit = (myUnit*)unit; + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + strcpy_s(lpUnit->szName, 128, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + + if(argc > 0 && JSVAL_IS_NUMBER(argv[0]) && !JSVAL_IS_NULL(argv[1])) + JS_ValueToECMAUint32(cx, argv[0], &(lpUnit->dwClassId)); + + if(argc > 1 && JSVAL_IS_NUMBER(argv[1]) && !JSVAL_IS_NULL(argv[2])) + JS_ValueToECMAUint32(cx, argv[1], &(lpUnit->dwMode)); + + pUnit = GetNextUnit(pUnit, lpUnit->szName, lpUnit->dwClassId, lpUnit->dwType, lpUnit->dwMode); + + if(!pUnit) + { + JS_ClearScope(cx, obj); + if(JS_ValueToObject(cx, JSVAL_NULL, &obj) == JS_FALSE) + return JS_TRUE; + *rval = JSVAL_FALSE; + } + else + { + lpUnit->dwUnitId = pUnit->dwUnitId; + JS_SetPrivate(cx, obj, lpUnit); + *rval = JSVAL_TRUE; + } + } + else if(unit->dwPrivateType == PRIVATE_ITEM) + { + invUnit *pmyUnit = (invUnit*)unit; + if(!pmyUnit) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + UnitAny* pOwner = D2CLIENT_FindUnit(pmyUnit->dwOwnerId, pmyUnit->dwOwnerType); + if(!pUnit || !pOwner) + return JS_TRUE; + + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + strcpy_s(pmyUnit->szName, 128, JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + + if(argc > 0 && JSVAL_IS_NUMBER(argv[0]) && !JSVAL_IS_NULL(argv[1])) + JS_ValueToECMAUint32(cx, argv[0], &(pmyUnit->dwClassId)); + + if(argc > 1 && JSVAL_IS_NUMBER(argv[1]) && !JSVAL_IS_NULL(argv[2])) + JS_ValueToECMAUint32(cx, argv[1], &(pmyUnit->dwMode)); + + UnitAny* nextItem = GetInvNextUnit(pUnit, pOwner, pmyUnit->szName, pmyUnit->dwClassId, pmyUnit->dwMode); + if(!nextItem) + { + JS_ClearScope(cx, obj); + if(JS_ValueToObject(cx, JSVAL_NULL, &obj) == JS_FALSE) + return JS_TRUE; + *rval = JSVAL_FALSE; + } + else + { + pmyUnit->dwUnitId = nextItem->dwUnitId; + JS_SetPrivate(cx, obj, pmyUnit); + *rval = JSVAL_TRUE; + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(unit_cancel) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + + + DWORD automapOn =*p_D2CLIENT_AutomapOn; + + if(IsScrollingText()) + D2CLIENT_ClearScreen(); + else if(D2CLIENT_GetCurrentInteractingNPC()) + D2CLIENT_CloseNPCInteract(); + else if(D2CLIENT_GetCursorItem()) + D2CLIENT_ClickMap(0, 10, 10, 0x08); + else + D2CLIENT_CloseInteract(); + + *p_D2CLIENT_AutomapOn =automapOn; + + return JS_TRUE; +} + +JSAPI_FUNC(unit_repair) +{ + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + *rval = JSVAL_FALSE; + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + BYTE aPacket[17] = { NULL }; + aPacket[0] = 0x35; + *(DWORD*)&aPacket[1] = *p_D2CLIENT_RecentInteractId; + aPacket[16] = 0x80; + D2NET_SendPacket(17,1, aPacket); + + // note: this crashes while minimized +// D2CLIENT_PerformNpcAction(pUnit,1, NULL); + *rval = JSVAL_TRUE; + + return JS_TRUE; +} + +JSAPI_FUNC(unit_useMenu) +{ + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + *rval = JSVAL_FALSE; + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + *rval = BOOLEAN_TO_JSVAL(ClickNPCMenu(pUnit->dwTxtFileNo, JSVAL_TO_INT(argv[0]))); + + return JS_TRUE; +} + +JSAPI_FUNC(unit_interact) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + *rval = JSVAL_FALSE; + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || pUnit == D2CLIENT_GetPlayerUnit()) + return JS_TRUE; + + if(pUnit->dwType == UNIT_ITEM && pUnit->dwMode != ITEM_MODE_ON_GROUND && pUnit->dwMode != ITEM_MODE_BEING_DROPPED) + { + int nLocation = GetItemLocation(pUnit); + + BYTE aPacket[13] = {NULL}; + + if(nLocation == STORAGE_INVENTORY) + { + aPacket[0] = 0x20; + *(DWORD*)&aPacket[1] = pUnit->dwUnitId; + *(DWORD*)&aPacket[5] = D2CLIENT_GetPlayerUnit()->pPath->xPos; + *(DWORD*)&aPacket[9] = D2CLIENT_GetPlayerUnit()->pPath->yPos; + D2NET_SendPacket(13, 1, aPacket); + return JS_TRUE; + } + else if(nLocation == STORAGE_BELT) + { + aPacket[0] = 0x26; + *(DWORD*)&aPacket[1] = pUnit->dwUnitId; + *(DWORD*)&aPacket[5] = 0; + *(DWORD*)&aPacket[9] = 0; + D2NET_SendPacket(13, 1, aPacket); + return JS_TRUE; + } + } + + if(pUnit->dwType == UNIT_OBJECT && argc == 1 && JSVAL_IS_INT(argv[0])) + { + // TODO: check the range on argv[0] to make sure it won't crash the game + D2CLIENT_TakeWaypoint(pUnit->dwUnitId, JSVAL_TO_INT(argv[0])); //updated by shep rev 720 + if(!D2CLIENT_GetUIState(UI_GAME)) + D2CLIENT_CloseInteract(); + + *rval = JSVAL_TRUE; + return JS_TRUE; + } +// else if(pUnit->dwType == UNIT_PLAYER && argc == 1 && JSVAL_IS_INT(argv[0]) && JSVAL_TO_INT(argv[0]) == 1) +// { + // Accept Trade +// } + else + { + *rval = JSVAL_TRUE; + ClickMap(0, D2CLIENT_GetUnitX(pUnit), D2CLIENT_GetUnitY(pUnit), FALSE, pUnit); + //D2CLIENT_Interact(pUnit, 0x45); + } + + return JS_TRUE; +} + +void InsertStatsToGenericObject(UnitAny* pUnit, StatList* pStatList, JSContext* pJSContext, JSObject* pGenericObject); +void InsertStatsNow(Stat* pStat, int nStat, JSContext* cx, JSObject* pArray); + +JSAPI_FUNC(unit_getStat) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + *rval = JSVAL_FALSE; + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + jsint nStat = JSVAL_TO_INT(argv[0]); + jsint nSubIndex = NULL; + + if(argc > 1 && JSVAL_IS_INT(argv[1])) + nSubIndex = JSVAL_TO_INT(argv[1]); + + if(nStat >= 6 && nStat <= 11) + *rval = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, nStat, nSubIndex)>>8); + else if(nStat == 13 || nStat == 29 || nStat == 30) + JS_NewNumberValue(cx, (unsigned int)D2COMMON_GetUnitStat(pUnit, nStat, nSubIndex), rval); + else if(nStat == 92) + *rval = INT_TO_JSVAL(D2COMMON_GetItemLevelRequirement(pUnit, D2CLIENT_GetPlayerUnit())); + else if(nStat == -1) + { + Stat aStatList[256] = { NULL }; + StatList* pStatList = D2COMMON_GetStatList(pUnit, NULL, 0x40); + + if(pStatList) + { + DWORD dwStats = D2COMMON_CopyStatList(pStatList, (Stat*)aStatList, 256); + + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(pReturnArray); + + for(UINT i = 0; i < dwStats; i++) + { + JSObject* pArrayInsert = JS_NewArrayObject(cx, 0, NULL); + JS_AddRoot(&pArrayInsert); + + if(!pArrayInsert) + continue; + + jsval nIndex = INT_TO_JSVAL(aStatList[i].wStatIndex); + jsval nSubIndex = INT_TO_JSVAL(aStatList[i].wSubIndex); + jsval nValue = INT_TO_JSVAL(aStatList[i].dwStatValue); + + JS_SetElement(cx, pArrayInsert, 0, &nIndex); + JS_SetElement(cx, pArrayInsert, 1, &nSubIndex); + JS_SetElement(cx, pArrayInsert, 2, &nValue); + + jsval aObj = OBJECT_TO_JSVAL(pArrayInsert); + + JS_SetElement(cx, pReturnArray, i, &aObj); + JS_RemoveRoot(&pArrayInsert); + } + } + } + else if(nStat == -2) + { + JSObject* pArray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(pArray); + + InsertStatsToGenericObject(pUnit, pUnit->pStats, cx, pArray); + //InsertStatsToGenericObject(pUnit, pUnit->pStats->pNext, cx, pArray); // only check the current unit stats! + // InsertStatsToGenericObject(pUnit, pUnit->pStats->pSetList, cx, pArray); + } + else + JS_NewNumberValue(cx, D2COMMON_GetUnitStat(pUnit, nStat, nSubIndex), rval); + //*rval = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, nStat, nSubIndex)); + + return JS_TRUE; +} + +void InsertStatsToGenericObject(UnitAny* pUnit, StatList* pStatList, JSContext* cx, JSObject* pArray) +{ + Stat* pStat; + + + + + //for(; pStatList; pStatList = pStatList->pPrevLink) // no need to jump lists + //{ + if((pStatList->dwUnitId == pUnit->dwUnitId && pStatList->dwUnitType == pUnit->dwType) || pStatList->pUnit == pUnit) + { + pStat = pStatList->pStat; + + if(pStatList->wStatCount1) + for(int nStat = 0; nStat < pStatList->wStatCount1; nStat++) + { + InsertStatsNow(pStat, nStat, cx, pArray); + } + } + if((pStatList->dwFlags >> 24 & 0x80)) + { + pStat = pStatList->pSetStat; + + if(pStatList->wSetStatCount) + for(int nStat = 0; nStat < pStatList->wSetStatCount; nStat++) + { + InsertStatsNow(pStat, nStat, cx, pArray); + } + } + //} +} + +void InsertStatsNow(Stat* pStat, int nStat, JSContext* cx, JSObject* pArray) +{ + if(pStat[nStat].wSubIndex > 0x200) + { + // subindex is the skill id and level + int skill = pStat[nStat].wSubIndex >> 6, + level = pStat[nStat].wSubIndex & 0x3F, + charges = 0, + maxcharges = 0; + if(pStat[nStat].dwStatValue > 0x200) + { + charges = pStat[nStat].dwStatValue & 0xFF; + maxcharges = pStat[nStat].dwStatValue >> 8; + } + JSObject* val = BuildObject(cx, NULL); + jsval jsskill = INT_TO_JSVAL(skill), + jslevel = INT_TO_JSVAL(level), + jscharges = INT_TO_JSVAL(charges), + jsmaxcharges = INT_TO_JSVAL(maxcharges); + // val is an anonymous object that holds properties + if(!JS_SetProperty(cx, val, "skill", &jsskill) || + !JS_SetProperty(cx, val, "level", &jslevel)) + return; + if(maxcharges > 0) + { + if(!JS_SetProperty(cx, val, "charges", &jscharges) || + !JS_SetProperty(cx, val, "maxcharges", &jsmaxcharges)) + return; + } + // find where we should put it + jsval index = JSVAL_VOID, + obj = OBJECT_TO_JSVAL(val); + if(!JS_GetElement(cx, pArray, pStat[nStat].wStatIndex, &index)) + return; + if(index != JSVAL_VOID) + { + // modify the existing object by stuffing it into an array + if(!JS_IsArrayObject(cx, JSVAL_TO_OBJECT(index))) + { + // it's not an array, build one + JSObject* arr = JS_NewArrayObject(cx, 0, NULL); + JS_AddRoot(&arr); + JS_SetElement(cx, arr, 0, &index); + JS_SetElement(cx, arr, 1, &obj); + jsval arr2 = OBJECT_TO_JSVAL(arr); + JS_SetElement(cx, pArray, pStat[nStat].wStatIndex, &arr2); + JS_RemoveRoot(&arr); + } + else + { + // it is an array, append the new value + JSObject* arr = JSVAL_TO_OBJECT(index); + jsuint len = 0; + if(!JS_GetArrayLength(cx, arr, &len)) + return; + len++; + JS_SetElement(cx, arr, len, &obj); + } + } + else + JS_SetElement(cx, pArray, pStat[nStat].wStatIndex, &obj); + } + else + { + //Make sure to bit shift life, mana and stamina properly! + int value = pStat[nStat].dwStatValue; + if(pStat[nStat].wStatIndex >= 6 && pStat[nStat].wStatIndex <= 11) + value = value >> 8; + + jsval index = JSVAL_VOID, val = INT_TO_JSVAL(value); + if(!JS_GetElement(cx, pArray, pStat[nStat].wStatIndex, &index)) + return; + if(index == JSVAL_VOID) + { + // the array index doesn't exist, make it + index = OBJECT_TO_JSVAL(JS_NewArrayObject(cx, 0, NULL)); + if(!JS_SetElement(cx, pArray, pStat[nStat].wStatIndex, &index)) + return; + } + // index now points to the correct array index + JS_SetElement(cx, JSVAL_TO_OBJECT(index), pStat[nStat].wSubIndex, &val); + } +} + +JSAPI_FUNC(unit_getState) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + *rval = JSVAL_FALSE; + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + jsint nState; + + if(JS_ValueToInt32(cx, argv[0], &nState) == JS_FALSE) + return JS_TRUE; + + // TODO: make these constants so we know what we're checking here + if(nState > 159 || nState < 0) + return JS_TRUE; + + *rval = BOOLEAN_TO_JSVAL(!!D2COMMON_GetUnitState(pUnit, nState)); + + return JS_TRUE; +} + +JSAPI_FUNC(item_getFlags) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || pUnit->dwType != UNIT_ITEM) + return JS_TRUE; + + *rval = INT_TO_JSVAL(pUnit->pItemData->dwFlags); + + return JS_TRUE; +} + +JSAPI_FUNC(item_getFlag) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || pUnit->dwType != UNIT_ITEM) + return JS_TRUE; + + jsint nFlag = JSVAL_TO_INT(argv[0]); + + *rval = BOOLEAN_TO_JSVAL(!!(nFlag & pUnit->pItemData->dwFlags)); + + return JS_TRUE; +} + +JSAPI_FUNC(item_getPrice) +{ + DEPRECATED; + + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + int diff = D2CLIENT_GetDifficulty(); + //D2COMMON_GetItemPrice(D2CLIENT_GetPlayerUnit(), pUnit, diff, *p_D2CLIENT_ItemPriceList, NPCID, buysell) + int buysell = 0; + int NPCID = 148; + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + if(argc>0) + { + if(JSVAL_IS_OBJECT(argv[0])) + { + myUnit* pmyNpc = (myUnit*)JS_GetPrivate(cx, JSVAL_TO_OBJECT(argv[0])); + + if(!pmyNpc || (pmyNpc->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pNpc = D2CLIENT_FindUnit(pmyNpc->dwUnitId, pmyNpc->dwType); + + if(!pNpc) + return JS_TRUE; + + NPCID = pNpc->dwTxtFileNo; + } + else if(JSVAL_IS_INT(argv[0])) + NPCID = JSVAL_TO_INT(argv[0]); + } + if(argc>1) + buysell = JSVAL_TO_INT(argv[1]); + if(argc>2) + diff = JSVAL_TO_INT(argv[2]); + + *rval = INT_TO_JSVAL(D2COMMON_GetItemPrice(D2CLIENT_GetPlayerUnit(), pUnit, diff, *p_D2CLIENT_ItemPriceList, NPCID, buysell)); + + return JS_TRUE; +} + +JSAPI_FUNC(item_getItemCost) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + jsint nMode; + UnitAny* npc = D2CLIENT_GetCurrentInteractingNPC(); + jsint nNpcClassId = (npc ? npc->dwTxtFileNo : 0x9A); + jsint nDifficulty = D2CLIENT_GetDifficulty(); + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || pUnit->dwType != UNIT_ITEM) + return JS_TRUE; + + nMode = JSVAL_TO_INT(argv[0]); + + if(argc > 1 && JSVAL_IS_INT(argv[1])) + nNpcClassId = JSVAL_TO_INT(argv[1]); + + if(argc > 2 && JSVAL_IS_INT(argv[2])) + nDifficulty = JSVAL_TO_INT(argv[2]); + + switch(nMode) + { + case 0: // Buy + case 1: // Sell + *rval = INT_TO_JSVAL(D2COMMON_GetItemPrice(D2CLIENT_GetPlayerUnit(), pUnit, nDifficulty, *p_D2CLIENT_ItemPriceList, nNpcClassId, nMode)); + break; + case 2: // Repair + *rval = INT_TO_JSVAL(D2COMMON_GetItemPrice(D2CLIENT_GetPlayerUnit(), pUnit, nDifficulty, *p_D2CLIENT_ItemPriceList, nNpcClassId, 3)); + break; + default: + break; + } + + return JS_TRUE; +} + +JSAPI_FUNC(unit_getItems) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || !pUnit->pInventory || !pUnit->pInventory->pFirstItem) + return JS_TRUE; + + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + + if(!pReturnArray) + return JS_TRUE; + JS_AddRoot(&pReturnArray); + + DWORD dwArrayCount = 0; + + for(UnitAny* pItem = pUnit->pInventory->pFirstItem; pItem; pItem = D2COMMON_GetNextItemFromInventory(pItem), dwArrayCount++) + { + invUnit* pmyUnit = new invUnit; + + if(!pmyUnit) + continue; + + pmyUnit->_dwPrivateType = PRIVATE_UNIT; + pmyUnit->szName[0] = NULL; + pmyUnit->dwMode = pItem->dwMode; + pmyUnit->dwClassId = pItem->dwTxtFileNo; + pmyUnit->dwUnitId = pItem->dwUnitId; + pmyUnit->dwType = UNIT_ITEM; + pmyUnit->dwOwnerId = pUnit->dwUnitId; + pmyUnit->dwOwnerType = pUnit->dwType; + + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyUnit); + if(!jsunit) + { + JS_RemoveRoot(&pReturnArray); + THROW_ERROR(cx, "Failed to build item array"); + } + + jsval a = OBJECT_TO_JSVAL(jsunit); + JS_SetElement(cx, pReturnArray, dwArrayCount, &a); + } + + *rval = OBJECT_TO_JSVAL(pReturnArray); + JS_RemoveRoot(&pReturnArray); + + return JS_TRUE; +} + + +JSAPI_FUNC(unit_getSkill) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + jsint nSkillId = NULL; + jsint nExt = NULL; + + myUnit* pmyUnit = (myUnit*)JS_GetPrivate(cx, obj); + if(!pmyUnit) + return JS_TRUE; + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + if(!pUnit) + return JS_TRUE; + + if(argc == NULL) + return JS_TRUE; + + if(argc == 1) + { + if(!JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + nSkillId = JSVAL_TO_INT(argv[0]); + } + else if(argc == 2) + { + if(!JSVAL_IS_INT(argv[0]) || !JSVAL_IS_INT(argv[1])) + return JS_TRUE; + + nSkillId = JSVAL_TO_INT(argv[0]); + nExt = JSVAL_TO_INT(argv[1]); + } + if(argc == 1) + { + WORD wLeftSkillId = pUnit->pInfo->pLeftSkill->pSkillInfo->wSkillId; + WORD wRightSkillId = pUnit->pInfo->pRightSkill->pSkillInfo->wSkillId; + switch(nSkillId) + { + case 0: + { + int row = 0; + if(FillBaseStat("skills", wRightSkillId, "skilldesc", &row, sizeof(int))) + if(FillBaseStat("skilldesc", row, "str name", &row, sizeof(int))) + { + wchar_t* szName = D2LANG_GetLocaleText((WORD)row); + char* str = UnicodeToAnsi(szName); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, str)); + delete[] str; + } + } + break; + case 1: + { + int row = 0; + if(FillBaseStat("skills", wLeftSkillId, "skilldesc", &row, sizeof(int))) + if(FillBaseStat("skilldesc", row, "str name", &row, sizeof(int))) + { + wchar_t* szName = D2LANG_GetLocaleText((WORD)row); + char* str = UnicodeToAnsi(szName); + *rval = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, str)); + delete[] str; + } + } + break; + case 2: *rval = INT_TO_JSVAL(wRightSkillId); break; + case 3: *rval = INT_TO_JSVAL(wLeftSkillId); break; + case 4: { + JSObject* pReturnArray = JS_NewArrayObject(cx, 0, NULL); + *rval = OBJECT_TO_JSVAL(pReturnArray); + int i = 0; + for(Skill* pSkill = pUnit->pInfo->pFirstSkill; pSkill; pSkill = pSkill->pNextSkill) { + JSObject* pArrayInsert = JS_NewArrayObject(cx, 0, NULL); + JS_AddRoot(&pArrayInsert); + + if(!pArrayInsert) + continue; + + jsval nId = INT_TO_JSVAL(pSkill->pSkillInfo->wSkillId); + jsval nBase = INT_TO_JSVAL(pSkill->dwSkillLevel); + jsval nTotal = INT_TO_JSVAL(D2COMMON_GetSkillLevel(pUnit, pSkill, 1)); + + JS_SetElement(cx, pArrayInsert, 0, &nId); + JS_SetElement(cx, pArrayInsert, 1, &nBase); + JS_SetElement(cx, pArrayInsert, 2, &nTotal); + + jsval aObj = OBJECT_TO_JSVAL(pArrayInsert); + + JS_SetElement(cx, pReturnArray, i, &aObj); + JS_RemoveRoot(&pArrayInsert); + i++; + } + break; + } + default: + *rval = JSVAL_FALSE; + break; + } + return JS_TRUE; + } + else if(argc == 2) + { + if(pUnit && pUnit->pInfo && pUnit->pInfo->pFirstSkill) + { + for(Skill* pSkill = pUnit->pInfo->pFirstSkill; pSkill; pSkill = pSkill->pNextSkill) + { + if(pSkill->pSkillInfo && pSkill->pSkillInfo->wSkillId == nSkillId) + { + *rval = INT_TO_JSVAL(D2COMMON_GetSkillLevel(pUnit, pSkill, nExt)); + return JS_TRUE; + } + } + } + + } + + *rval = JSVAL_FALSE; + + return JS_TRUE; +} + +JSAPI_FUNC(item_shop) +{ + CriticalMisc myMisc; + myMisc.EnterSection(); + + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(*p_D2CLIENT_TransactionDialog != 0 || *p_D2CLIENT_TransactionDialogs != 0 || *p_D2CLIENT_TransactionDialogs_2 != 0) + { + *rval = JSVAL_FALSE; + return JS_TRUE; + } + + myUnit* lpItem = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpItem || (lpItem->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pItem = D2CLIENT_FindUnit(lpItem->dwUnitId, lpItem->dwType); + + if(!pItem || pItem->dwType != UNIT_ITEM) + return JS_TRUE; + + if(!D2CLIENT_GetUIState(UI_NPCSHOP)) + return JS_TRUE; + + UnitAny* pNPC = D2CLIENT_GetCurrentInteractingNPC(); + DWORD dwMode = JSVAL_TO_INT(argv[argc - 1]); + + //Check if we are interacted. + if(!pNPC) + return JS_TRUE; + + //Check for proper mode. + if ((dwMode != 1) && (dwMode != 2) && (dwMode != 6)) + return JS_TRUE; + + //Selling an Item + if(dwMode == 1) + { + //Check if we own the item! + if (pItem->pItemData->pOwnerInventory->pOwner->dwUnitId != D2CLIENT_GetPlayerUnit()->dwUnitId) + return JS_TRUE; + + D2CLIENT_ShopAction(pItem, pNPC, pNPC, 1, 0, 1, 1, NULL); + } + else + { + //Make sure the item is owned by the NPC interacted with. + if (pItem->pItemData->pOwnerInventory->pOwner->dwUnitId != pNPC->dwUnitId) + return JS_TRUE; + + D2CLIENT_ShopAction(pItem, pNPC, pNPC, 0, 0, dwMode, 1, NULL); + } + + /*BYTE pPacket[17] = {NULL}; + + if(dwMode == 2 || dwMode == 6) + pPacket[0] = 0x32; + else pPacket[0] = 0x33; + + *(DWORD*)&pPacket[1] = pNPC->dwUnitId; + *(DWORD*)&pPacket[5] = pItem->dwUnitId; + + if(dwMode == 1) // Sell + { + if(D2CLIENT_GetCursorItem() && D2CLIENT_GetCursorItem() == pItem) + *(DWORD*)&pPacket[9] = 0x04; + else + *(DWORD*)&pPacket[9] = 0; + } + else if(dwMode == 2) // Buy + { + if(pItem->pItemData->dwFlags & 0x10) + *(DWORD*)&pPacket[9] = 0x00; + else + *(DWORD*)&pPacket[9] = 0x02; + } + else + *(BYTE*)&pPacket[9+3] = 0x80; + + int nBuySell = NULL; + + if(dwMode == 2 || dwMode == 6) + nBuySell = NULL; + else nBuySell = 1; + + *(DWORD*)&pPacket[13] = D2COMMON_GetItemPrice(D2CLIENT_GetPlayerUnit(), pItem, D2CLIENT_GetDifficulty(), *p_D2CLIENT_ItemPriceList, pNPC->dwTxtFileNo, nBuySell); + + D2NET_SendPacket(sizeof(pPacket), 1, pPacket);*/ + + *rval = JSVAL_TRUE; + + return JS_TRUE; +} + +JSAPI_FUNC(unit_getParent) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit || (lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + if(pUnit->dwType == UNIT_MONSTER) + { + DWORD dwOwnerId = D2CLIENT_GetMonsterOwner(pUnit->dwUnitId); + if(dwOwnerId == -1) + return JS_TRUE; + + UnitAny* pMonster = GetUnit(NULL, (DWORD)-1, (DWORD)-1, (DWORD)-1, dwOwnerId); +// if (!pMonster) +// pMonster = GetUnit(NULL, (DWORD)-1, UNIT_MONSTER, (DWORD)-1, dwOwnerId); + if (!pMonster) + return JS_TRUE; + + myUnit* pmyUnit = new myUnit; + if(!pmyUnit) + return JS_TRUE; + + pmyUnit->_dwPrivateType = PRIVATE_UNIT; + pmyUnit->dwUnitId = pMonster->dwUnitId; + pmyUnit->dwClassId = pMonster->dwTxtFileNo; + pmyUnit->dwMode = pMonster->dwMode; + pmyUnit->dwType = pMonster->dwType; + pmyUnit->szName[0] = NULL; + + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyUnit); + if (!jsunit) + return JS_TRUE; + *rval = OBJECT_TO_JSVAL(jsunit); + return JS_TRUE; + } + else if(pUnit->dwType == UNIT_OBJECT) + { + if(pUnit->pObjectData) + { + char szBuffer[128] = ""; + strcpy_s(szBuffer, sizeof(szBuffer), pUnit->pObjectData->szOwner); + + *rval = STRING_TO_JSVAL(JS_InternString(cx, szBuffer)); + } + } + else if(pUnit->dwType == UNIT_ITEM) + { + if(pUnit->pItemData && pUnit->pItemData->pOwnerInventory && pUnit->pItemData->pOwnerInventory->pOwner) + { + myUnit* pmyUnit = new myUnit; // leaks + + if(!pmyUnit) + return JS_TRUE; + + pmyUnit->_dwPrivateType = PRIVATE_UNIT; + pmyUnit->dwUnitId = pUnit->pItemData->pOwnerInventory->pOwner->dwUnitId; + pmyUnit->dwClassId = pUnit->pItemData->pOwnerInventory->pOwner->dwTxtFileNo; + pmyUnit->dwMode = pUnit->pItemData->pOwnerInventory->pOwner->dwMode; + pmyUnit->dwType = pUnit->pItemData->pOwnerInventory->pOwner->dwType; + pmyUnit->szName[0] = NULL; + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyUnit); + + *rval = OBJECT_TO_JSVAL(jsunit); + } + } + + return JS_TRUE; +} + +// Works only on players sinces monsters _CANT_ have mercs! +JSAPI_FUNC(unit_getMerc) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!lpUnit ||(lpUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); + + if(!pUnit || pUnit->dwType != UNIT_PLAYER) + return JS_TRUE; + + if(argc > 0 && JSVAL_IS_INT(argv[0]) && JSVAL_TO_INT(argv[0]) == 1) + { + UnitAny* pMerc = NULL; + if(D2CLIENT_GetPlayerUnit()->pAct) + { + for(Room1* pRoom = D2CLIENT_GetPlayerUnit()->pAct->pRoom1; pRoom; pRoom = pRoom->pRoomNext) + { + for(UnitAny* pUnit = pRoom->pUnitFirst; pUnit; pUnit = pUnit->pRoomNext) + { + if(pUnit->dwType != UNIT_MONSTER) + continue; + + if(pUnit->dwTxtFileNo == MERC_A1 || pUnit->dwTxtFileNo == MERC_A2 || pUnit->dwTxtFileNo == MERC_A3 || pUnit->dwTxtFileNo == MERC_A5) + { + if(D2CLIENT_GetMonsterOwner(pUnit->dwUnitId) == D2CLIENT_GetPlayerUnit()->dwUnitId) + { + *rval = JSVAL_TRUE; + return JS_TRUE; + } + } + } + } + } + + if(pMerc) + *rval = JSVAL_TRUE; + else if(*p_D2CLIENT_MercStrIndex == 0xFFFF) + *rval = JSVAL_FALSE; + else + *rval = JSVAL_NULL; + + return JS_TRUE; + } + + if(D2CLIENT_GetPlayerUnit() && D2CLIENT_GetPlayerUnit()->pAct) + { + for(Room1* pRoom = D2CLIENT_GetPlayerUnit()->pAct->pRoom1; pRoom; pRoom = pRoom->pRoomNext) + { + for(UnitAny* pMonster = pRoom->pUnitFirst; pMonster; pMonster = pMonster->pRoomNext) + { + if(pMonster->dwType == UNIT_MONSTER) + { + if(pMonster->dwTxtFileNo == MERC_A1 || pMonster->dwTxtFileNo == MERC_A2 || pMonster->dwTxtFileNo == MERC_A3 || pMonster->dwTxtFileNo == MERC_A5) + { + if(D2CLIENT_GetMonsterOwner(pMonster->dwUnitId) == pUnit->dwUnitId) + { + myUnit* pmyUnit = new myUnit; + + if(!pmyUnit) + return JS_TRUE; + + pmyUnit->_dwPrivateType = PRIVATE_UNIT; + pmyUnit->dwUnitId = pMonster->dwUnitId; + pmyUnit->dwClassId = pMonster->dwTxtFileNo; + pmyUnit->dwMode = NULL; + pmyUnit->dwType = UNIT_MONSTER; + pmyUnit->szName[0] = NULL; + + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyUnit); + if (!jsunit) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(jsunit); + } + } + } + } + } + } + + return JS_TRUE; +} + +// unit.setSkill( int skillId OR String skillName, int hand [, int itemGlobalId] ); +JSAPI_FUNC(unit_setskill) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + WORD nSkillId = (WORD)-1; + BOOL nHand = FALSE; + DWORD itemId = (DWORD)-1; + *rval = JSVAL_FALSE; + + if(argc < 1) + return JS_TRUE; + + if(JSVAL_IS_STRING(argv[0])) + nSkillId = GetSkillByName(JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + else if(JSVAL_IS_INT(argv[0])) + nSkillId = (WORD)JSVAL_TO_INT(argv[0]); + else + return JS_TRUE; + + if(JSVAL_IS_INT(argv[1])) + nHand = !!JSVAL_TO_INT(argv[1]); + else + return JS_TRUE; + + if(argc == 3 && JSVAL_IS_OBJECT(argv[2])) + { + JSObject* obj = JSVAL_TO_OBJECT(argv[2]); + if(JS_InstanceOf(cx, obj, &unit_class_ex.base, argv)) + { + myUnit* unit = (myUnit*)JS_GetPrivate(cx, obj); + if(unit->dwType == UNIT_ITEM) + itemId = unit->dwUnitId; + } + } + + + if(SetSkill(nSkillId, nHand, itemId)) + *rval = JSVAL_TRUE; + + return JS_TRUE; +} + +JSAPI_FUNC(my_overhead) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit *pmyUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + if(!pUnit) + return JS_TRUE; + + if(!JSVAL_IS_NULL(argv[0]) && !JSVAL_IS_VOID(argv[0])) + { + char *lpszText = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); + if(lpszText && lpszText[0]) + { + OverheadMsg* pMsg = D2COMMON_GenerateOverheadMsg(NULL, lpszText, *p_D2CLIENT_OverheadTrigger); + if(pMsg) + { + D2COMMON_FixOverheadMsg(pMsg, NULL); + pUnit->pOMsg = pMsg; + } + } + } + + return JS_TRUE; +} + +JSAPI_FUNC(my_revive) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + BYTE pPacket[] = {0x41}; + D2NET_SendPacket(1, 1, pPacket); + return JS_TRUE; +} + + +JSAPI_FUNC(unit_getItem) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit *pmyUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + if(!pUnit || !pUnit->pInventory) + return JS_TRUE; + + uint32 nClassId = (uint32)-1; + uint32 nMode = (uint32)-1; + uint32 nUnitId = (uint32)-1; + char szName[128] = ""; + + if(argc > 0 && JSVAL_IS_STRING(argv[0])) + strcpy_s(szName, sizeof(szName), JS_GetStringBytes(JS_ValueToString(cx, argv[0]))); + + if(argc > 0 && JSVAL_IS_NUMBER(argv[0]) && !JSVAL_IS_NULL(argv[0])) + JS_ValueToECMAUint32(cx, argv[0], &nClassId); + + if(argc > 1 && JSVAL_IS_NUMBER(argv[1]) && !JSVAL_IS_NULL(argv[1])) + JS_ValueToECMAUint32(cx, argv[1], &nMode); + + if(argc > 2 && JSVAL_IS_NUMBER(argv[2]) && !JSVAL_IS_NULL(argv[2])) + JS_ValueToECMAUint32(cx, argv[2], &nUnitId); + + UnitAny* pItem = GetInvUnit(pUnit, szName, nClassId, nMode, nUnitId); + + if(!pItem) + return JS_TRUE; + + invUnit* pmyItem = new invUnit; // leaked? + + if(!pmyItem) + return JS_TRUE; + + pmyItem->_dwPrivateType = PRIVATE_ITEM; + pmyItem->dwClassId = nClassId; + pmyItem->dwMode = nMode; + pmyItem->dwType = pItem->dwType; + pmyItem->dwUnitId = pItem->dwUnitId; + pmyItem->dwOwnerId = pmyUnit->dwUnitId; + pmyItem->dwOwnerType = pmyUnit->dwType; + strcpy_s(pmyItem->szName, sizeof(pmyItem->szName), szName); + + JSObject *jsunit = BuildObject(cx, &unit_class_ex.base, unit_methods, unit_props, pmyItem); + + if(!jsunit) + return JS_TRUE; + + *rval = OBJECT_TO_JSVAL(jsunit); + + return JS_TRUE; +} + +JSAPI_FUNC(unit_move) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + myUnit *pmyUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + UnitAny *pPlayer = D2CLIENT_GetPlayerUnit(); + + if(!pPlayer || !pUnit) + return JS_TRUE; + + int32 x, y; + + if(pUnit == pPlayer) + { + + if(argc < 2) + return JS_TRUE; + + if(JS_ValueToInt32(cx, argv[0], &x) == JS_FALSE) + return JS_TRUE; + if(JS_ValueToInt32(cx, argv[1], &y) == JS_FALSE) + return JS_TRUE; + } + else + { + x = D2CLIENT_GetUnitX(pUnit); + y = D2CLIENT_GetUnitY(pUnit); + } + + ClickMap(0, (WORD)x, (WORD)y, FALSE, NULL); + Sleep(50); + ClickMap(2, (WORD)x, (WORD)y, FALSE, NULL); +// D2CLIENT_Move((WORD)x, (WORD)y); + return JS_TRUE; +} + +JSAPI_FUNC(unit_getEnchant) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + myUnit *pmyUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + if(!pUnit || pUnit->dwType != UNIT_MONSTER) + return JS_TRUE; + + int nEnchant = JSVAL_TO_INT(argv[0]); + + *rval = INT_TO_JSVAL(0); + + for(int i = 0; i < 9; i++) + if(pUnit->pMonsterData->anEnchants[i] == nEnchant) + { + *rval = JSVAL_TRUE; + break; + } + + return JS_TRUE; +} + +JSAPI_FUNC(unit_getQuest) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 2 || !JSVAL_IS_INT(argv[0]) || !JSVAL_IS_INT(argv[1])) + return JS_TRUE; + + jsint nAct = JSVAL_TO_INT(argv[0]); + jsint nQuest = JSVAL_TO_INT(argv[1]); + + *rval = INT_TO_JSVAL(D2COMMON_GetQuestFlag(D2CLIENT_GetQuestInfo(), nAct, nQuest)); + + return JS_TRUE; +} + +JSAPI_FUNC(unit_getMinionCount) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + if(argc < 1 || !JSVAL_IS_INT(argv[0])) + return JS_TRUE; + + jsint nType = JSVAL_TO_INT(argv[0]); + + myUnit *pmyUnit = (myUnit*)JS_GetPrivate(cx, obj); + + if(!pmyUnit || (pmyUnit->_dwPrivateType & PRIVATE_UNIT) != PRIVATE_UNIT) + return JS_TRUE; + + UnitAny* pUnit = D2CLIENT_FindUnit(pmyUnit->dwUnitId, pmyUnit->dwType); + + if(!pUnit || (pUnit->dwType != UNIT_MONSTER && pUnit->dwType != UNIT_PLAYER)) + return JS_TRUE; + + *rval = INT_TO_JSVAL(D2CLIENT_GetMinionCount(pUnit, (DWORD)nType)); + + return JS_TRUE; +} + + + +JSAPI_FUNC(me_getRepairCost) +{ + if(!WaitForGameReady()) + THROW_WARNING(cx, "Game not ready"); + + UnitAny* npc = D2CLIENT_GetCurrentInteractingNPC(); + jsint nNpcClassId = (npc ? npc->dwTxtFileNo : 0x9A); + + if(argc > 0 && JSVAL_IS_INT(argv[0])) + nNpcClassId = JSVAL_TO_INT(argv[0]); + + *rval = INT_TO_JSVAL(D2COMMON_GetRepairCost(NULL, D2CLIENT_GetPlayerUnit(), nNpcClassId, D2CLIENT_GetDifficulty(), *p_D2CLIENT_ItemPriceList, 0)); + + return JS_TRUE; +} diff --git a/JSUnit.h b/JSUnit.h new file mode 100644 index 00000000..f7eb257c --- /dev/null +++ b/JSUnit.h @@ -0,0 +1,261 @@ +#pragma once + +#include +#include "js32.h" + +CLASS_CTOR(unit); + +JSAPI_FUNC(unit_getUnit); +JSAPI_FUNC(unit_getNext); +JSAPI_FUNC(unit_cancel); +JSAPI_FUNC(unit_repair); +JSAPI_FUNC(unit_useMenu); +JSAPI_FUNC(unit_interact); +JSAPI_FUNC(unit_getStat); +JSAPI_FUNC(unit_getState); +JSAPI_FUNC(unit_getItems); +JSAPI_FUNC(unit_getSkill); +JSAPI_FUNC(unit_getParent); +JSAPI_FUNC(unit_setskill); +JSAPI_FUNC(unit_getMerc); +JSAPI_FUNC(unit_getItem); +JSAPI_FUNC(unit_move); +JSAPI_FUNC(item_getFlag); +JSAPI_FUNC(item_getFlags); +JSAPI_FUNC(item_getPrice); +JSAPI_FUNC(item_shop); +JSAPI_FUNC(my_overhead); +JSAPI_FUNC(my_revive); +JSAPI_FUNC(unit_getEnchant); +JSAPI_FUNC(unit_getQuest); +JSAPI_FUNC(unit_getMinionCount); +JSAPI_FUNC(me_getRepairCost); +JSAPI_FUNC(item_getItemCost); + +void unit_finalize(JSContext *cx, JSObject *obj); +JSAPI_PROP(unit_getProperty); +JSAPI_PROP(unit_setProperty); +JSBool unit_equal(JSContext *cx, JSObject *obj, jsval v, JSBool *bp); + +struct myUnit +{ + DWORD _dwPrivateType; + DWORD dwUnitId; + DWORD dwClassId; + DWORD dwType; + DWORD dwMode; + char szName[128]; +}; + +struct invUnit +{ + DWORD _dwPrivateType; + DWORD dwUnitId; + DWORD dwClassId; + DWORD dwType; + DWORD dwMode; + char szName[128]; + DWORD dwOwnerId; + DWORD dwOwnerType; +}; + +enum unit_tinyid +{ + UNIT_TYPE, UNIT_CLASSID, UNIT_ID, UNIT_MODE, UNIT_NAME, UNIT_BUSY, + UNIT_ACT, UNIT_XPOS, UNIT_YPOS, ME_WSWITCH, UNIT_AREA, UNIT_HP, + UNIT_HPMAX, UNIT_MP, UNIT_MPMAX, UNIT_STAMINA, UNIT_STAMINAMAX, + UNIT_CHARLVL, ME_RUNWALK, ITEM_CODE, ITEM_PREFIX, ITEM_SUFFIX, ITEM_FNAME, + ITEM_QUALITY, ITEM_NODE, UNIT_SELECTABLE, ITEM_LOC, ITEM_SIZEX, + ITEM_SIZEY, ITEM_TYPE, MISSILE_DIR, MISSILE_VEL, ITEM_CLASS, + UNIT_SPECTYPE, ITEM_DESC, ITEM_BODYLOCATION, UNIT_ITEMCOUNT, ITEM_LEVELREQ, + UNIT_OWNER, UNIT_OWNERTYPE, UNIT_UNIQUEID, ITEM_LEVEL, UNIT_DIRECTION, + ITEM_SUFFIXNUM, ITEM_PREFIXNUM, OBJECT_TYPE, OBJECT_LOCKED +}; + +enum me_tinyid { + ME_ACCOUNT = 90, + ME_CHARNAME, + ME_CHICKENHP, + ME_CHICKENMP, + ME_DIFF, + ME_GAMENAME, + ME_GAMEPASSWORD, + ME_GAMESERVERIP, + ME_GAMESTARTTIME, + ME_GAMETYPE, + ME_ITEMONCURSOR, + ME_LADDER, + ME_PING, + ME_FPS, + ME_PLAYERTYPE, + ME_QUITONHOSTILE, + ME_REALM, + ME_REALMSHORT, + ME_MERCREVIVECOST, + ME_MAPID, + OOG_WINDOWTITLE, + OOG_SCREENSIZE, + OOG_INGAME, + OOG_QUITONERROR, + OOG_MAXGAMETIME, + ME_BLOCKKEYS, + ME_BLOCKMOUSE, + ME_GAMEREADY, + ME_PROFILE, + ME_NOPICKUP, + ME_PID +}; + +static JSPropertySpec me_props[] = { + {"account", ME_ACCOUNT, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"charname", ME_CHARNAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"diff", ME_DIFF, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gamename", ME_GAMENAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gamepassword", ME_GAMEPASSWORD, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gameserverip", ME_GAMESERVERIP, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gamestarttime", ME_GAMESTARTTIME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gametype", ME_GAMETYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"itemoncursor", ME_ITEMONCURSOR, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ladder", ME_LADDER, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ping", ME_PING, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"fps", ME_FPS, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"playertype", ME_PLAYERTYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"realm", ME_REALM, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"realmshort", ME_REALMSHORT, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mercrevivecost", ME_MERCREVIVECOST, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"runwalk", ME_RUNWALK, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"weaponswitch", ME_WSWITCH, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"chickenhp", ME_CHICKENHP, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"chickenmp", ME_CHICKENMP, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"quitonhostile", ME_QUITONHOSTILE, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"blockKeys", ME_BLOCKKEYS, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"blockMouse", ME_BLOCKMOUSE, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"gameReady", ME_GAMEREADY, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"profile", ME_PROFILE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"nopickup", ME_NOPICKUP, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"pid", ME_PID, JSPROP_PERMANENT_VAR, unit_getProperty}, + + {"screensize", OOG_SCREENSIZE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"windowtitle", OOG_WINDOWTITLE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ingame", OOG_INGAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"quitonerror", OOG_QUITONERROR, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + {"maxgametime", OOG_MAXGAMETIME, JSPROP_STATIC_VAR, unit_getProperty, unit_setProperty}, + + {"type", UNIT_TYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"classid", UNIT_CLASSID, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mode", UNIT_MODE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"name", UNIT_NAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mapid", ME_MAPID, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"act", UNIT_ACT, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gid", UNIT_ID, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"x", UNIT_XPOS, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"y", UNIT_YPOS, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"area", UNIT_AREA, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"hp", UNIT_HP, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"hpmax", UNIT_HPMAX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mp", UNIT_MP, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mpmax", UNIT_MPMAX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"stamina", UNIT_STAMINA, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"staminamax", UNIT_STAMINAMAX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"charlvl", UNIT_CHARLVL, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"itemcount", UNIT_ITEMCOUNT, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"owner", UNIT_OWNER, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ownertype", UNIT_OWNERTYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"spectype", UNIT_SPECTYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"direction", UNIT_DIRECTION, JSPROP_PERMANENT_VAR, unit_getProperty}, + + {"code", ITEM_CODE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"prefix", ITEM_PREFIX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"suffix", ITEM_SUFFIX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"prefixnum", ITEM_PREFIXNUM, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"suffixnum", ITEM_SUFFIXNUM, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"fname", ITEM_FNAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"quality", ITEM_QUALITY, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"node", ITEM_NODE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"location", ITEM_LOC, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"sizex", ITEM_SIZEX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"sizey", ITEM_SIZEY, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"itemType", ITEM_TYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"description", ITEM_DESC, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"bodylocation", ITEM_BODYLOCATION, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ilvl", ITEM_LEVEL, JSPROP_PERMANENT_VAR, unit_getProperty}, + {0}, +}; + +static JSPropertySpec unit_props[] = { + {"type", UNIT_TYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"classid", UNIT_CLASSID, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mode", UNIT_MODE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"name", UNIT_NAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"act", UNIT_ACT, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"gid", UNIT_ID, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"x", UNIT_XPOS, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"y", UNIT_YPOS, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"area", UNIT_AREA, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"hp", UNIT_HP, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"hpmax", UNIT_HPMAX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mp", UNIT_MP, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"mpmax", UNIT_MPMAX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"stamina", UNIT_STAMINA, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"staminamax", UNIT_STAMINAMAX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"charlvl", UNIT_CHARLVL, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"itemcount", UNIT_ITEMCOUNT, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"owner", UNIT_OWNER, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ownertype", UNIT_OWNERTYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"spectype", UNIT_SPECTYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"direction", UNIT_DIRECTION, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"uniqueid", UNIT_UNIQUEID, JSPROP_PERMANENT_VAR, unit_getProperty}, + + {"code", ITEM_CODE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"prefix", ITEM_PREFIX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"suffix", ITEM_SUFFIX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"prefixnum", ITEM_PREFIXNUM, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"suffixnum", ITEM_SUFFIXNUM, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"fname", ITEM_FNAME, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"quality", ITEM_QUALITY, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"node", ITEM_NODE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"location", ITEM_LOC, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"sizex", ITEM_SIZEX, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"sizey", ITEM_SIZEY, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"itemType", ITEM_TYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"description", ITEM_DESC, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"bodylocation",ITEM_BODYLOCATION, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"ilvl", ITEM_LEVEL, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"lvlreq", ITEM_LEVELREQ, JSPROP_PERMANENT_VAR, unit_getProperty}, + + {"runwalk", ME_RUNWALK, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"weaponswitch",ME_WSWITCH, JSPROP_PERMANENT_VAR, unit_getProperty}, + + {"objtype", OBJECT_TYPE, JSPROP_PERMANENT_VAR, unit_getProperty}, + {"islocked", OBJECT_LOCKED, JSPROP_PERMANENT_VAR, unit_getProperty}, + {0}, +}; + +static JSFunctionSpec unit_methods[] = { + {"getNext", unit_getNext, 0}, + {"cancel", unit_cancel, 0}, + {"repair", unit_repair, 0}, + {"useMenu", unit_useMenu, 0}, + {"interact", unit_interact, 0}, + {"getItem", unit_getItem, 3}, + {"getItems", unit_getItems, 0}, + {"getMerc", unit_getMerc, 0}, + {"getSkill", unit_getSkill, 0}, + {"getParent", unit_getParent, 0}, + {"overhead", my_overhead, 0}, + {"revive", my_revive, 0}, + {"getFlags", item_getFlags, 1}, + {"getFlag", item_getFlag, 1}, + {"getStat", unit_getStat, 1}, + {"getState", unit_getState, 1}, + {"getPrice", item_getPrice, 1}, + {"getEnchant", unit_getEnchant, 1}, + {"shop", item_shop, 2}, + {"setSkill", unit_setskill, 2}, + {"move", unit_move, 2}, + {"getQuest", unit_getQuest, 2}, + {"getMinionCount", unit_getMinionCount, 1}, + {"getRepairCost", me_getRepairCost, 1}, + {"getItemCost", item_getItemCost, 1}, + {0}, +}; diff --git a/MPQStats.cpp b/MPQStats.cpp new file mode 100644 index 00000000..94992526 --- /dev/null +++ b/MPQStats.cpp @@ -0,0 +1,292 @@ +#include "MPQStats.h" +#include "D2Ptrs.h" +#include "Core.h" + +MPQTable BaseStatTable[] = { + //DWORD dwEntry, DWORD dwMaxEntriesOffset, BinField* pTable, char szTableName, WORD wTableSize, WORD wUnknown + {0x6FDF4CB4, 0x6FDF4CB0, itemTable, "items", ARRAYSIZE(itemTable), 0xFFFF}, + {0xA78, 0xA80, monstatsTable, "monstats", ARRAYSIZE(monstatsTable), 0xFFFF}, + {0xB8C, 0xB94, skilldescTable, "skilldesc", ARRAYSIZE(skilldescTable), 0xFFFF}, + {0xB98, 0xBA0, skillsTable, "skills", ARRAYSIZE(skillsTable), 0xFFFF}, + {0x6FDF5830, 0x6FDF5834, objectsTable, "objects", ARRAYSIZE(objectsTable), 0xFFFF}, + {0xB64, 0xB6C, missilesTable, "missiles", ARRAYSIZE(missilesTable), 0xFFFF}, + {0xA90, 0xA98, monstats2Table, "monstats2", ARRAYSIZE(monstats2Table), 0xFFFF}, + {0xBCC, 0xBD4, itemstatcostTable, "itemstatcost", ARRAYSIZE(itemstatcostTable), 0xFFFF}, + {0xC58, 0xC5C, levelsTable, "levels", ARRAYSIZE(levelsTable), 0xFFFF}, + {0xC60, 0x00, leveldefsTable, "leveldefs", ARRAYSIZE(leveldefsTable), 0xFFFF}, + {0x6FDF654C, 0x6FDF6540, lvlmazeTable, "lvlmaze", ARRAYSIZE(lvlmazeTable), 0xFFFF}, + {0x6FDF6534, 0x6FDF6538, lvlsubTable, "lvlsub", ARRAYSIZE(lvlsubTable), 0xFFFF}, // v + {0x6FDF652C, 0x6FDF6530, lvlwarpTable, "lvlwarp", ARRAYSIZE(lvlwarpTable), 0xFFFF}, // v + {0xC64, 0xC68, lvlprestTable, "lvlprest", ARRAYSIZE(lvlprestTable), 0xFFFF}, + {0x6FDF141C, 0x6FDF1428, lvltypesTable, "lvltypes", ARRAYSIZE(lvltypesTable), 0xFFFF}, // v - Fixed to fully dump the same as d2jsp - TechnoHunter + {0xBC4, 0xBC8, charstatsTable, "charstats", ARRAYSIZE(charstatsTable), 0xFFFF}, + {0xC18, 0xC1C, setitemsTable, "setitems", ARRAYSIZE(setitemsTable), 0xFFFF}, + {0xC24, 0xC28, uniqueitemsTable, "uniqueitems", ARRAYSIZE(uniqueitemsTable), 0xFFFF}, + {0xC0C, 0xC10, setsTable, "sets", ARRAYSIZE(setsTable), 0xFFFF}, + {0xBF8, 0xBFC, itemtypesTable, "itemtypes", ARRAYSIZE(itemtypesTable), 0xFFFF}, + {0x6FDF4CF4, 0x6FDF4CF0, runesTable, "runes", ARRAYSIZE(runesTable), 0xFFFF}, // v + {0x6FDF652C, 0x6FDF6530, cubemainTable, "cubemain", ARRAYSIZE(cubemainTable), 0xFFFF}, //v + {0x6FDF4CEC, 0x6FDF4CE8, gemsTable, "gems", ARRAYSIZE(gemsTable), 0xFFFF}, + {0x6FDF64D0, 0x0, experienceTable, "experience", ARRAYSIZE(experienceTable), 0xFFFF}, // v - doesnt tap the last 2 levels of exp, ends at level 97 - TechnoHunter + {0xBE8, 0xBF0, pettypeTable, "pettable", ARRAYSIZE(pettypeTable), 0xFFFF}, + {0xAD4, 0xADC, superuniquesTable, "superuniques", ARRAYSIZE(superuniquesTable), 0xFFFF}, + {0} +}; + +DWORD GetBaseTable(int table, int row) +{ + DWORD dwResult = NULL; + DWORD dwD2MPQTable = NULL; + + if(table < sizeof(BaseStatTable)) + { + DWORD dwTableOffset = BaseStatTable[table].dwEntry; + + if(dwTableOffset <= 0xFFFF) + dwD2MPQTable = (*p_D2COMMON_sgptDataTable); + else dwD2MPQTable = NULL; + + DWORD dwMaxEntriesOffset = BaseStatTable[table].dwMaxEntriesOffset; + + DWORD dwMaxEntries; + if(dwMaxEntriesOffset) + dwMaxEntries = *(DWORD*)(dwMaxEntriesOffset + dwD2MPQTable); + else dwMaxEntries = 0xFF; + + if((DWORD)row < dwMaxEntries) + { + DWORD dwMultiplicator = BaseStatTable[table].pTable[BaseStatTable[table].wTableSize-1].dwFieldOffset; + DWORD dwTable = row * dwMultiplicator; + dwResult = *(DWORD*)(dwTableOffset + dwD2MPQTable) + dwTable; + } + } + + return dwResult; +} + +bool FillBaseStat(char* szTable, int row, char* szStat, void* result, size_t size) +{ + int table = -1; + for(int i = 0; BaseStatTable[i].pTable != NULL; i++) + if(!_strcmpi(szTable, BaseStatTable[i].szTableName)) + { + table = i; + break; + } + + if(table == -1) + return false; + + return FillBaseStat(table, row, szStat, result, size); +} + +bool FillBaseStat(char* szTable, int row, int column, void* result, size_t size) +{ + int table = -1; + for(int i = 0; BaseStatTable[i].pTable != NULL; i++) + if(!_strcmpi(szTable, BaseStatTable[i].szTableName)) + { + table = i; + break; + } + + if(table == -1) + return false; + + return FillBaseStat(table, row, column, result, size); +} + +bool FillBaseStat(int table, int row, char* szStat, void* result, size_t size) +{ + BinField* pTable = BaseStatTable[table].pTable; + + int column = -1; + for(int i = 0; i < BaseStatTable[table].wTableSize; i++) + if(!_strcmpi(szStat, pTable[i].szFieldName)) + { + column = i; + break; + } + + if(column == -1) + return false; + + return FillBaseStat(table, row, column, result, size); +} + +bool FillBaseStat(int table, int row, int column, void* result, size_t size) +{ + BinField* pTable = BaseStatTable[table].pTable; + DWORD dwRetValue = GetBaseTable(table, row); + + if(!dwRetValue || column > BaseStatTable[table].wTableSize) + return false; + + DWORD dwHelperSize = pTable[column+1].dwFieldOffset - pTable[column].dwFieldOffset; + if(dwHelperSize > 4) + dwHelperSize = 4; + switch(pTable[column].eFieldType) + { + case FIELDTYPE_DATA_ASCII: + if(size < pTable[column].dwFieldLength) + return false; + memcpy_s(result, pTable[column].dwFieldLength, (BYTE*)(dwRetValue+pTable[column].dwFieldOffset), pTable[column].dwFieldLength); + break; + case FIELDTYPE_DATA_DWORD: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), sizeof(DWORD)); + break; + case FIELDTYPE_CALC_TO_DWORD: + case FIELDTYPE_NAME_TO_DWORD: + case FIELDTYPE_DATA_DWORD_2: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), sizeof(DWORD)); + break; + case FIELDTYPE_UNKNOWN_11: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), sizeof(DWORD)); + break; + case FIELDTYPE_NAME_TO_INDEX_2: + case FIELDTYPE_NAME_TO_WORD_2: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), sizeof(WORD)); + if(((WORD)result) >= 0xFFFF) + *(WORD*)result = (((WORD)result) - 0xFFFF) * -1; + break; + case FIELDTYPE_NAME_TO_INDEX: + case FIELDTYPE_NAME_TO_WORD: + case FIELDTYPE_KEY_TO_WORD: + case FIELDTYPE_DATA_WORD: + case FIELDTYPE_CODE_TO_WORD: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), sizeof(WORD)); + break; + case FIELDTYPE_CODE_TO_BYTE: + case FIELDTYPE_DATA_BYTE_2: + case FIELDTYPE_DATA_BYTE: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), dwHelperSize); + break; + case FIELDTYPE_DATA_BIT: + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), sizeof(DWORD)); + *(BOOL*)result = (*(BOOL*)result & (1 << pTable[column].dwFieldLength)) ? 1 : 0; + break; + case FIELDTYPE_ASCII_TO_CODE: + case FIELDTYPE_DATA_RAW: + if(size != 5) + return false; + memcpy(result, (LPVOID)(dwRetValue+pTable[column].dwFieldOffset), size-1); + break; + case FIELDTYPE_MONSTER_COMPS: + // ..? :E + return false; + } + + return true; +} + +DWORD FillBaseStat(JSContext* cx, jsval *argv, int table, int row, int column, char* szTable, char* szStat) +{ + if(szTable) + { + table = -1; + for(int i = 0; BaseStatTable[i].pTable != NULL; i++) + if(!_strcmpi(szTable, BaseStatTable[i].szTableName)) + { + table = i; + break; + } + + if(table == -1) + return false; + } + + BinField* pTable = BaseStatTable[table].pTable; + + if(szStat) + { + column = -1; + for(int i = 0; i < BaseStatTable[table].wTableSize; i++) + if(!_strcmpi(szStat, pTable[i].szFieldName)) + { + column = i; + break; + } + + if(column == -1) + return false; + } + + if(column > BaseStatTable[table].wTableSize) + return FALSE; + + DWORD dwBuffer = 0; + WORD wBuffer = 0; + char* szBuffer = NULL; + DWORD dwHelperSize = pTable[column+1].dwFieldOffset - pTable[column].dwFieldOffset; + if(dwHelperSize > 4) + dwHelperSize = 4; + + switch(pTable[column].eFieldType) + { + case FIELDTYPE_DATA_ASCII: + szBuffer = new char[(pTable[column].dwFieldLength + 1)]; + memset(szBuffer, NULL, pTable[column].dwFieldLength + 1); + if(!FillBaseStat(table, row, column, szBuffer, pTable[column].dwFieldLength+1)) + (*argv) = JSVAL_VOID; + else + (*argv) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szBuffer)); + delete[] szBuffer; + return TRUE; + + case FIELDTYPE_DATA_DWORD: + case FIELDTYPE_CALC_TO_DWORD: + case FIELDTYPE_NAME_TO_DWORD: + case FIELDTYPE_DATA_DWORD_2: + case FIELDTYPE_UNKNOWN_11: + if(!FillBaseStat(table, row, column, &dwBuffer, sizeof(DWORD))) + (*argv) = JSVAL_VOID; + else + JS_NewNumberValue(cx, (jsdouble)dwBuffer, argv); + return TRUE; + + case FIELDTYPE_NAME_TO_INDEX_2: + case FIELDTYPE_NAME_TO_WORD_2: + case FIELDTYPE_NAME_TO_INDEX: + case FIELDTYPE_NAME_TO_WORD: + case FIELDTYPE_KEY_TO_WORD: + case FIELDTYPE_DATA_WORD: + case FIELDTYPE_CODE_TO_WORD: + if(!FillBaseStat(table, row, column, &wBuffer, sizeof(WORD))) + (*argv) = JSVAL_VOID; + else + (*argv) = INT_TO_JSVAL(wBuffer); + return TRUE; + + case FIELDTYPE_CODE_TO_BYTE: + case FIELDTYPE_DATA_BYTE_2: + case FIELDTYPE_DATA_BYTE: + if(!FillBaseStat(table, row, column, &dwBuffer, dwHelperSize)) + (*argv) = JSVAL_VOID; + else + (*argv) = INT_TO_JSVAL(dwBuffer); + return TRUE; + + case FIELDTYPE_DATA_BIT: + if(!FillBaseStat(table, row, column, &dwBuffer, sizeof(DWORD))) + (*argv) = JSVAL_VOID; + else + (*argv) = BOOLEAN_TO_JSVAL(!!dwBuffer); + return TRUE; + + case FIELDTYPE_ASCII_TO_CODE: + case FIELDTYPE_DATA_RAW: + szBuffer = new char[5]; + memset(szBuffer, NULL, 5); + if(!FillBaseStat(table, row, column, szBuffer, 5)) + (*argv) = JSVAL_VOID; + else + (*argv) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szBuffer)); + delete[] szBuffer; + return TRUE; + + case FIELDTYPE_MONSTER_COMPS: + // ..? :E + return FALSE; + } + return FALSE; +} diff --git a/MPQStats.h b/MPQStats.h new file mode 100644 index 00000000..a44a7e99 --- /dev/null +++ b/MPQStats.h @@ -0,0 +1,2345 @@ +#pragma once + +#include + +#include "js32.h" + +// Information taken from +// http://phrozenkeep.planetdiablo.gamespy.com/forum/viewtopic.php?t=48175 + +enum +{ + FIELDTYPE_END = 0, + FIELDTYPE_DATA_ASCII = 1, + FIELDTYPE_DATA_DWORD = 2, + FIELDTYPE_DATA_WORD = 3, + FIELDTYPE_DATA_BYTE = 4, + FIELDTYPE_UNKNOWN_5 = 5, + FIELDTYPE_DATA_BYTE_2 = 6, + FIELDTYPE_DATA_DWORD_2 = 8, + FIELDTYPE_DATA_RAW = 9, + FIELDTYPE_ASCII_TO_CODE = 10, + FIELDTYPE_UNKNOWN_11 = 11, + FIELDTYPE_UNKNOWN_12 = 12, + FIELDTYPE_CODE_TO_BYTE = 13, + FIELDTYPE_UNKNOWN_14 = 14, + FIELDTYPE_CODE_TO_WORD = 15, + FIELDTYPE_UNKNOWN_16 = 16, + FIELDTYPE_NAME_TO_INDEX = 17, + FIELDTYPE_NAME_TO_INDEX_2 = 18, + FIELDTYPE_NAME_TO_DWORD = 19, + FIELDTYPE_NAME_TO_WORD = 20, + FIELDTYPE_NAME_TO_WORD_2 = 21, + FIELDTYPE_KEY_TO_WORD = 22, + FIELDTYPE_MONSTER_COMPS = 23, + FIELDTYPE_UNKNOWN_24 = 24, + FIELDTYPE_CALC_TO_DWORD = 25, + FIELDTYPE_DATA_BIT = 26, +}; + +struct BinField +{ + char szFieldName[64]; + DWORD eFieldType; + DWORD dwFieldLength; + DWORD dwFieldOffset; +}; + +struct MPQTable +{ + DWORD dwEntry; // if > 0xFFFF it is not located in the exported mpq data.. + DWORD dwMaxEntriesOffset; // "" + BinField* pTable; + char szTableName[15]; + WORD wTableSize; + WORD wUnknown; +}; + +DWORD GetBaseTable(int nBaseStat, int nClassId); +bool FillBaseStat(char* szTable, int row, char* szStat, void* result, size_t size); +bool FillBaseStat(char* szTable, int row, int column, void* result, size_t size); +bool FillBaseStat(int table, int row, char* szStat, void* result, size_t size); +bool FillBaseStat(int table, int row, int column, void* result, size_t size); +DWORD FillBaseStat(JSContext* cx, jsval *argv, int table, int row, int column, char* szTable, char* szStat); + +// Tables dumped by Sheppard + +static BinField itemTable[] = { + {"flippyfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x0}, + {"invfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x20}, + {"uniqueinvfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x40}, + {"setinvfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x60}, + {"code", FIELDTYPE_ASCII_TO_CODE, 0x0, 0x80}, + {"normcode", FIELDTYPE_DATA_RAW, 0x0, 0x84}, + {"ubercode", FIELDTYPE_DATA_RAW, 0x0, 0x88}, + {"ultracode", FIELDTYPE_DATA_RAW, 0x0, 0x8c}, + {"alternategfx", FIELDTYPE_DATA_RAW, 0x0, 0x90}, + {"pSpell", FIELDTYPE_DATA_DWORD, 0x0, 0x94}, + {"state", FIELDTYPE_NAME_TO_WORD, 0x0, 0x98}, + {"cstate1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9a}, + {"cstate2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9c}, + {"stat1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9e}, + {"stat2", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa0}, + {"stat3", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa2}, + {"calc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa4}, + {"calc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa8}, + {"calc3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xac}, + {"len", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb0}, + {"spelldesc", FIELDTYPE_DATA_BYTE, 0x0, 0xb4}, + {"spelldescstr", FIELDTYPE_KEY_TO_WORD, 0x0, 0xb6}, + {"spelldesccalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb8}, + {"BetterGem", FIELDTYPE_DATA_RAW, 0x0, 0xbc}, + {"wclass", FIELDTYPE_DATA_RAW, 0x0, 0xc0}, + {"2handedwclass", FIELDTYPE_DATA_RAW, 0x0, 0xc4}, + {"TMogType", FIELDTYPE_DATA_RAW, 0x0, 0xc8}, + {"minac", FIELDTYPE_DATA_DWORD, 0x0, 0xcc}, + {"maxac", FIELDTYPE_DATA_DWORD, 0x0, 0xd0}, + {"gamble cost", FIELDTYPE_DATA_DWORD, 0x0, 0xd4}, + {"speed", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd8}, + {"bitfield1", FIELDTYPE_DATA_DWORD, 0x0, 0xdc}, + {"cost", FIELDTYPE_DATA_DWORD, 0x0, 0xe0}, + {"minstack", FIELDTYPE_DATA_DWORD, 0x0, 0xe4}, + {"maxstack", FIELDTYPE_DATA_DWORD, 0x0, 0xe8}, + {"spawnstack", FIELDTYPE_DATA_DWORD, 0x0, 0xec}, + {"gemoffset", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf0}, + {"namestr", FIELDTYPE_KEY_TO_WORD, 0x0, 0xf4}, + {"version", FIELDTYPE_DATA_WORD, 0x0, 0xf6}, + {"auto prefix", FIELDTYPE_DATA_WORD, 0x0, 0xf8}, + {"missiletype", FIELDTYPE_DATA_WORD, 0x0, 0xfa}, + {"rarity", FIELDTYPE_DATA_BYTE, 0x0, 0xfc}, + {"level", FIELDTYPE_DATA_BYTE, 0x0, 0xfd}, + {"mindam", FIELDTYPE_DATA_BYTE_2, 0x0, 0xfe}, + {"maxdam", FIELDTYPE_DATA_BYTE_2, 0x0, 0xff}, + {"minmisdam", FIELDTYPE_DATA_BYTE, 0x0, 0x100}, + {"maxmisdam", FIELDTYPE_DATA_BYTE, 0x0, 0x101}, + {"2handmindam", FIELDTYPE_DATA_BYTE_2, 0x0, 0x102}, + {"2handmaxdam", FIELDTYPE_DATA_BYTE_2, 0x0, 0x103}, + {"rangeadder", FIELDTYPE_DATA_BYTE_2, 0x0, 0x104}, + {"strbonus", FIELDTYPE_DATA_WORD, 0x0, 0x106}, + {"dexbonus", FIELDTYPE_DATA_WORD, 0x0, 0x108}, + {"reqstr", FIELDTYPE_DATA_WORD, 0x0, 0x10a}, + {"reqdex", FIELDTYPE_DATA_WORD, 0x0, 0x10c}, + {"absorbs", FIELDTYPE_DATA_BYTE_2, 0x0, 0x10e}, + {"invwidth", FIELDTYPE_DATA_BYTE, 0x0, 0x10f}, + {"invheight", FIELDTYPE_DATA_BYTE, 0x0, 0x110}, + {"block", FIELDTYPE_DATA_BYTE_2, 0x0, 0x111}, + {"durability", FIELDTYPE_DATA_BYTE_2, 0x0, 0x112}, + {"nodurability", FIELDTYPE_DATA_BYTE, 0x0, 0x113}, + {"missile", FIELDTYPE_DATA_BYTE_2, 0x0, 0x114}, + {"component", FIELDTYPE_DATA_BYTE, 0x0, 0x115}, + {"rArm", FIELDTYPE_DATA_BYTE_2, 0x0, 0x116}, + {"lArm", FIELDTYPE_DATA_BYTE_2, 0x0, 0x117}, + {"torso", FIELDTYPE_DATA_BYTE_2, 0x0, 0x118}, + {"legs", FIELDTYPE_DATA_BYTE_2, 0x0, 0x119}, + {"rspad", FIELDTYPE_DATA_BYTE_2, 0x0, 0x11a}, + {"lspad", FIELDTYPE_DATA_BYTE_2, 0x0, 0x11b}, + {"2handed", FIELDTYPE_DATA_BYTE_2, 0x0, 0x11c}, + {"useable", FIELDTYPE_DATA_BYTE, 0x0, 0x11d}, + {"type", FIELDTYPE_CODE_TO_WORD, 0x0, 0x11e}, + {"type2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x120}, + {"subtype", FIELDTYPE_DATA_BYTE_2, 0x0, 0x122}, + {"dropsound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x124}, + {"usesound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x126}, + {"dropsfxframe", FIELDTYPE_DATA_BYTE, 0x0, 0x128}, + {"unique", FIELDTYPE_DATA_BYTE, 0x0, 0x129}, + {"quest", FIELDTYPE_DATA_BYTE, 0x0, 0x12a}, + {"questdiffcheck", FIELDTYPE_DATA_BYTE, 0x0, 0x12b}, + {"transparent", FIELDTYPE_DATA_BYTE, 0x0, 0x12c}, + {"transtbl", FIELDTYPE_DATA_BYTE, 0x0, 0x12d}, + {"lightradius", FIELDTYPE_DATA_BYTE, 0x0, 0x12f}, + {"belt", FIELDTYPE_DATA_BYTE, 0x0, 0x130}, + {"autobelt", FIELDTYPE_DATA_BYTE, 0x0, 0x131}, + {"stackable", FIELDTYPE_DATA_BYTE, 0x0, 0x132}, + {"spawnable", FIELDTYPE_DATA_BYTE, 0x0, 0x133}, + {"spellicon", FIELDTYPE_DATA_BYTE_2, 0x0, 0x134}, + {"durwarning", FIELDTYPE_DATA_BYTE, 0x0, 0x135}, + {"qntwarning", FIELDTYPE_DATA_BYTE, 0x0, 0x136}, + {"hasinv", FIELDTYPE_DATA_BYTE_2, 0x0, 0x137}, + {"gemsockets", FIELDTYPE_DATA_BYTE_2, 0x0, 0x138}, + {"Transmogrify", FIELDTYPE_DATA_BYTE_2, 0x0, 0x139}, + {"TMogMin", FIELDTYPE_DATA_BYTE_2, 0x0, 0x13a}, + {"TMogMax", FIELDTYPE_DATA_BYTE_2, 0x0, 0x13b}, + {"hit class", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x13c}, + {"1or2handed", FIELDTYPE_DATA_BYTE_2, 0x0, 0x13d}, + {"gemapplytype", FIELDTYPE_DATA_BYTE, 0x0, 0x13e}, + {"levelreq", FIELDTYPE_DATA_BYTE, 0x0, 0x13f}, + {"magic lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x140}, + {"Transform", FIELDTYPE_DATA_BYTE, 0x0, 0x141}, + {"InvTrans", FIELDTYPE_DATA_BYTE, 0x0, 0x142}, + {"compactsave", FIELDTYPE_DATA_BYTE_2, 0x0, 0x143}, + {"SkipName", FIELDTYPE_DATA_BYTE, 0x0, 0x144}, + {"Nameable", FIELDTYPE_DATA_BYTE, 0x0, 0x145}, + {"AkaraMin", FIELDTYPE_DATA_BYTE, 0x0, 0x146}, + {"GheedMin", FIELDTYPE_DATA_BYTE, 0x0, 0x147}, + {"CharsiMin", FIELDTYPE_DATA_BYTE, 0x0, 0x148}, + {"FaraMin", FIELDTYPE_DATA_BYTE, 0x0, 0x149}, + {"LysanderMin", FIELDTYPE_DATA_BYTE, 0x0, 0x14a}, + {"DrognanMin", FIELDTYPE_DATA_BYTE, 0x0, 0x14b}, + {"HraltiMin", FIELDTYPE_DATA_BYTE, 0x0, 0x14c}, + {"AlkorMin", FIELDTYPE_DATA_BYTE, 0x0, 0x14d}, + {"OrmusMin", FIELDTYPE_DATA_BYTE, 0x0, 0x14e}, + {"ElzixMin", FIELDTYPE_DATA_BYTE, 0x0, 0x14f}, + {"AshearaMin", FIELDTYPE_DATA_BYTE, 0x0, 0x150}, + {"CainMin", FIELDTYPE_DATA_BYTE, 0x0, 0x151}, + {"HalbuMin", FIELDTYPE_DATA_BYTE, 0x0, 0x152}, + {"JamellaMin", FIELDTYPE_DATA_BYTE, 0x0, 0x153}, + {"MalahMin", FIELDTYPE_DATA_BYTE, 0x0, 0x154}, + {"LarzukMin", FIELDTYPE_DATA_BYTE, 0x0, 0x155}, + {"DrehyaMin", FIELDTYPE_DATA_BYTE, 0x0, 0x156}, + {"AkaraMax", FIELDTYPE_DATA_BYTE, 0x0, 0x157}, + {"GheedMax", FIELDTYPE_DATA_BYTE, 0x0, 0x158}, + {"CharsiMax", FIELDTYPE_DATA_BYTE, 0x0, 0x159}, + {"FaraMax", FIELDTYPE_DATA_BYTE, 0x0, 0x15a}, + {"LysanderMax", FIELDTYPE_DATA_BYTE, 0x0, 0x15b}, + {"DrognanMax", FIELDTYPE_DATA_BYTE, 0x0, 0x15c}, + {"HraltiMax", FIELDTYPE_DATA_BYTE, 0x0, 0x15d}, + {"AlkorMax", FIELDTYPE_DATA_BYTE, 0x0, 0x15e}, + {"OrmusMax", FIELDTYPE_DATA_BYTE, 0x0, 0x15f}, + {"ElzixMax", FIELDTYPE_DATA_BYTE, 0x0, 0x160}, + {"AshearaMax", FIELDTYPE_DATA_BYTE, 0x0, 0x161}, + {"CainMax", FIELDTYPE_DATA_BYTE, 0x0, 0x162}, + {"HalbuMax", FIELDTYPE_DATA_BYTE, 0x0, 0x163}, + {"JamellaMax", FIELDTYPE_DATA_BYTE, 0x0, 0x164}, + {"MalahMax", FIELDTYPE_DATA_BYTE, 0x0, 0x165}, + {"LarzukMax", FIELDTYPE_DATA_BYTE, 0x0, 0x166}, + {"DrehyaMax", FIELDTYPE_DATA_BYTE, 0x0, 0x167}, + {"AkaraMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x168}, + {"GheedMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x169}, + {"CharsiMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x16a}, + {"FaraMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x16b}, + {"LysanderMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x16c}, + {"DrognanMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x16d}, + {"HraltiMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x16e}, + {"AlkorMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x16f}, + {"OrmusMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x170}, + {"ElzixMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x171}, + {"AshearaMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x172}, + {"CainMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x173}, + {"HalbuMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x174}, + {"JamellaMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x175}, + {"MalahMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x176}, + {"LarzukMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x177}, + {"DrehyaMagicMin", FIELDTYPE_DATA_BYTE, 0x0, 0x178}, + {"AkaraMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x179}, + {"GheedMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x17a}, + {"CharsiMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x17b}, + {"FaraMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x17c}, + {"LysanderMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x17d}, + {"DrognanMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x17e}, + {"HraltiMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x17f}, + {"AlkorMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x180}, + {"OrmusMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x181}, + {"ElzixMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x182}, + {"AshearaMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x183}, + {"CainMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x184}, + {"HalbuMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x185}, + {"JamellaMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x186}, + {"MalahMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x187}, + {"LarzukMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x188}, + {"DrehyaMagicMax", FIELDTYPE_DATA_BYTE, 0x0, 0x189}, + {"AkaraMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x18a}, + {"GheedMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x18b}, + {"CharsiMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x18c}, + {"FaraMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x18d}, + {"LysanderMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x18e}, + {"DrognanMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x18f}, + {"HraltiMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x190}, + {"AlkorMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x191}, + {"OrmusMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x192}, + {"ElzixMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x193}, + {"AshearaMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x194}, + {"CainMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x195}, + {"HalbuMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x196}, + {"JamellaMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x197}, + {"MalahMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x198}, + {"LarzukMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x199}, + {"DrehyaMagicLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19a}, + {"NightmareUpgrade", FIELDTYPE_DATA_RAW, 0x0, 0x19c}, + {"HellUpgrade", FIELDTYPE_DATA_RAW, 0x0, 0x1a0}, + {"PermStoreItem", FIELDTYPE_DATA_BYTE, 0x0, 0x1a4}, + {"multibuy", FIELDTYPE_DATA_BYTE, 0x0, 0x1a5}, + {"end", FIELDTYPE_END, 0x0, 0x1a8}, +}; +static BinField monstatsTable[] = { + {"Id", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"BaseId", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2}, + {"NextInClass", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4}, + {"NameStr", FIELDTYPE_KEY_TO_WORD, 0x0, 0x6}, + {"DescStr", FIELDTYPE_KEY_TO_WORD, 0x0, 0x8}, + {"isSpawn", FIELDTYPE_DATA_BIT, 0x0, 0xc}, + {"isMelee", FIELDTYPE_DATA_BIT, 0x1, 0xc}, + {"noRatio", FIELDTYPE_DATA_BIT, 0x2, 0xc}, + {"opendoors", FIELDTYPE_DATA_BIT, 0x3, 0xc}, + {"SetBoss", FIELDTYPE_DATA_BIT, 0x4, 0xc}, + {"BossXfer", FIELDTYPE_DATA_BIT, 0x5, 0xc}, + {"boss", FIELDTYPE_DATA_BIT, 0x6, 0xc}, + {"primeevil", FIELDTYPE_DATA_BIT, 0x7, 0xc}, + {"npc", FIELDTYPE_DATA_BIT, 0x8, 0xc}, + {"interact", FIELDTYPE_DATA_BIT, 0x9, 0xc}, + {"inTown", FIELDTYPE_DATA_BIT, 0xa, 0xc}, + {"lUndead", FIELDTYPE_DATA_BIT, 0xb, 0xc}, + {"hUndead", FIELDTYPE_DATA_BIT, 0xc, 0xc}, + {"demon", FIELDTYPE_DATA_BIT, 0xd, 0xc}, + {"flying", FIELDTYPE_DATA_BIT, 0xe, 0xc}, + {"killable", FIELDTYPE_DATA_BIT, 0xf, 0xc}, + {"switchai", FIELDTYPE_DATA_BIT, 0x10, 0xc}, + {"nomultishot", FIELDTYPE_DATA_BIT, 0x11, 0xc}, + {"neverCount", FIELDTYPE_DATA_BIT, 0x12, 0xc}, + {"petIgnore", FIELDTYPE_DATA_BIT, 0x13, 0xc}, + {"deathDmg", FIELDTYPE_DATA_BIT, 0x14, 0xc}, + {"genericSpawn", FIELDTYPE_DATA_BIT, 0x15, 0xc}, + {"zoo", FIELDTYPE_DATA_BIT, 0x16, 0xc}, + {"placespawn", FIELDTYPE_DATA_BIT, 0x17, 0xc}, + {"inventory", FIELDTYPE_DATA_BIT, 0x18, 0xc}, + {"enabled", FIELDTYPE_DATA_BIT, 0x19, 0xc}, + {"NoShldBlock", FIELDTYPE_DATA_BIT, 0x1a, 0xc}, + {"noaura", FIELDTYPE_DATA_BIT, 0x1b, 0xc}, + {"rangedtype", FIELDTYPE_DATA_BIT, 0x1c, 0xc}, + {"Code", FIELDTYPE_DATA_RAW, 0x0, 0x10}, + {"MonSound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x14}, + {"UMonSound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x16}, + {"MonStatsEx", FIELDTYPE_NAME_TO_WORD, 0x0, 0x18}, + {"MonProp", FIELDTYPE_NAME_TO_WORD, 0x0, 0x1a}, + {"MonType", FIELDTYPE_NAME_TO_WORD, 0x0, 0x1c}, + {"AI", FIELDTYPE_NAME_TO_WORD, 0x0, 0x1e}, + {"spawn", FIELDTYPE_NAME_TO_WORD, 0x0, 0x20}, + {"spawnx", FIELDTYPE_DATA_BYTE, 0x0, 0x22}, + {"spawny", FIELDTYPE_DATA_BYTE, 0x0, 0x23}, + {"spawnmode", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x24}, + {"minion1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x26}, + {"minion2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x28}, + {"PartyMin", FIELDTYPE_DATA_BYTE, 0x0, 0x2c}, + {"PartyMax", FIELDTYPE_DATA_BYTE, 0x0, 0x2d}, + {"Rarity", FIELDTYPE_DATA_BYTE, 0x0, 0x2e}, + {"MinGrp", FIELDTYPE_DATA_BYTE, 0x0, 0x2f}, + {"MaxGrp", FIELDTYPE_DATA_BYTE, 0x0, 0x30}, + {"sparsePopulate", FIELDTYPE_DATA_BYTE, 0x0, 0x31}, + {"Velocity", FIELDTYPE_DATA_WORD, 0x0, 0x32}, + {"Run", FIELDTYPE_DATA_WORD, 0x0, 0x34}, + {"MissA1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3a}, + {"MissA2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3c}, + {"MissS1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3e}, + {"MissS2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x40}, + {"MissS3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x42}, + {"MissS4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x44}, + {"MissC", FIELDTYPE_NAME_TO_WORD, 0x0, 0x46}, + {"MissSQ", FIELDTYPE_NAME_TO_WORD, 0x0, 0x48}, + {"Align", FIELDTYPE_DATA_BYTE, 0x0, 0x4c}, + {"TransLvl", FIELDTYPE_DATA_BYTE, 0x0, 0x4d}, + {"threat", FIELDTYPE_DATA_BYTE, 0x0, 0x4e}, + {"aidel", FIELDTYPE_DATA_BYTE, 0x0, 0x4f}, + {"aidel(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x50}, + {"aidel(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x51}, + {"aidist", FIELDTYPE_DATA_BYTE, 0x0, 0x52}, + {"aidist(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x53}, + {"aidist(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x54}, + {"aip1", FIELDTYPE_DATA_WORD, 0x0, 0x56}, + {"aip1(N)", FIELDTYPE_DATA_WORD, 0x0, 0x58}, + {"aip1(H)", FIELDTYPE_DATA_WORD, 0x0, 0x5a}, + {"aip2", FIELDTYPE_DATA_WORD, 0x0, 0x5c}, + {"aip2(N)", FIELDTYPE_DATA_WORD, 0x0, 0x5e}, + {"aip2(H)", FIELDTYPE_DATA_WORD, 0x0, 0x60}, + {"aip3", FIELDTYPE_DATA_WORD, 0x0, 0x62}, + {"aip3(N)", FIELDTYPE_DATA_WORD, 0x0, 0x64}, + {"aip3(H)", FIELDTYPE_DATA_WORD, 0x0, 0x66}, + {"aip4", FIELDTYPE_DATA_WORD, 0x0, 0x68}, + {"aip4(N)", FIELDTYPE_DATA_WORD, 0x0, 0x6a}, + {"aip4(H)", FIELDTYPE_DATA_WORD, 0x0, 0x6c}, + {"aip5", FIELDTYPE_DATA_WORD, 0x0, 0x6e}, + {"aip5(N)", FIELDTYPE_DATA_WORD, 0x0, 0x70}, + {"aip5(H)", FIELDTYPE_DATA_WORD, 0x0, 0x72}, + {"aip6", FIELDTYPE_DATA_WORD, 0x0, 0x74}, + {"aip6(N)", FIELDTYPE_DATA_WORD, 0x0, 0x76}, + {"aip6(H)", FIELDTYPE_DATA_WORD, 0x0, 0x78}, + {"aip7", FIELDTYPE_DATA_WORD, 0x0, 0x7a}, + {"aip7(N)", FIELDTYPE_DATA_WORD, 0x0, 0x7c}, + {"aip7(H)", FIELDTYPE_DATA_WORD, 0x0, 0x7e}, + {"aip8", FIELDTYPE_DATA_WORD, 0x0, 0x80}, + {"aip8(N)", FIELDTYPE_DATA_WORD, 0x0, 0x82}, + {"aip8(H)", FIELDTYPE_DATA_WORD, 0x0, 0x84}, + {"TreasureClass1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x86}, + {"TreasureClass2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x88}, + {"TreasureClass3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x8a}, + {"TreasureClass4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x8c}, + {"TreasureClass1(N)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x8e}, + {"TreasureClass2(N)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x90}, + {"TreasureClass3(N)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x92}, + {"TreasureClass4(N)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x94}, + {"TreasureClass1(H)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x96}, + {"TreasureClass2(H)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x98}, + {"TreasureClass3(H)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9a}, + {"TreasureClass4(H)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9c}, + {"TCQuestId", FIELDTYPE_DATA_BYTE, 0x0, 0x9e}, + {"TCQuestCP", FIELDTYPE_DATA_BYTE, 0x0, 0x9f}, + {"Drain", FIELDTYPE_DATA_BYTE, 0x0, 0xa0}, + {"Drain(N)", FIELDTYPE_DATA_BYTE, 0x0, 0xa1}, + {"Drain(H)", FIELDTYPE_DATA_BYTE, 0x0, 0xa2}, + {"ToBlock", FIELDTYPE_DATA_BYTE, 0x0, 0xa3}, + {"ToBlock(N)", FIELDTYPE_DATA_BYTE, 0x0, 0xa4}, + {"ToBlock(H)", FIELDTYPE_DATA_BYTE, 0x0, 0xa5}, + {"Crit", FIELDTYPE_DATA_BYTE, 0x0, 0xa6}, + {"SkillDamage", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa8}, + {"Level", FIELDTYPE_DATA_WORD, 0x0, 0xaa}, + {"Level(N)", FIELDTYPE_DATA_WORD, 0x0, 0xac}, + {"Level(H)", FIELDTYPE_DATA_WORD, 0x0, 0xae}, + {"MinHP", FIELDTYPE_DATA_WORD, 0x0, 0xb0}, + {"MinHP(N)", FIELDTYPE_DATA_WORD, 0x0, 0xb2}, + {"MinHP(H)", FIELDTYPE_DATA_WORD, 0x0, 0xb4}, + {"MaxHP", FIELDTYPE_DATA_WORD, 0x0, 0xb6}, + {"MaxHP(N)", FIELDTYPE_DATA_WORD, 0x0, 0xb8}, + {"MaxHP(H)", FIELDTYPE_DATA_WORD, 0x0, 0xba}, + {"AC", FIELDTYPE_DATA_WORD, 0x0, 0xbc}, + {"AC(N)", FIELDTYPE_DATA_WORD, 0x0, 0xbe}, + {"AC(H)", FIELDTYPE_DATA_WORD, 0x0, 0xc0}, + {"A1TH", FIELDTYPE_DATA_WORD, 0x0, 0xc2}, + {"A1TH(N)", FIELDTYPE_DATA_WORD, 0x0, 0xc4}, + {"A1TH(H)", FIELDTYPE_DATA_WORD, 0x0, 0xc6}, + {"A2TH", FIELDTYPE_DATA_WORD, 0x0, 0xc8}, + {"A2TH(N)", FIELDTYPE_DATA_WORD, 0x0, 0xca}, + {"A2TH(H)", FIELDTYPE_DATA_WORD, 0x0, 0xcc}, + {"S1TH", FIELDTYPE_DATA_WORD, 0x0, 0xce}, + {"S1TH(N)", FIELDTYPE_DATA_WORD, 0x0, 0xd0}, + {"S1TH(H)", FIELDTYPE_DATA_WORD, 0x0, 0xd2}, + {"Exp", FIELDTYPE_DATA_WORD, 0x0, 0xd4}, + {"Exp(N)", FIELDTYPE_DATA_WORD, 0x0, 0xd6}, + {"Exp(H)", FIELDTYPE_DATA_WORD, 0x0, 0xd8}, + {"A1MinD", FIELDTYPE_DATA_WORD, 0x0, 0xda}, + {"A1MinD(N)", FIELDTYPE_DATA_WORD, 0x0, 0xdc}, + {"A1MinD(H)", FIELDTYPE_DATA_WORD, 0x0, 0xde}, + {"A1MaxD", FIELDTYPE_DATA_WORD, 0x0, 0xe0}, + {"A1MaxD(N)", FIELDTYPE_DATA_WORD, 0x0, 0xe2}, + {"A1MaxD(H)", FIELDTYPE_DATA_WORD, 0x0, 0xe4}, + {"A2MinD", FIELDTYPE_DATA_WORD, 0x0, 0xe6}, + {"A2MinD(N)", FIELDTYPE_DATA_WORD, 0x0, 0xe8}, + {"A2MinD(H)", FIELDTYPE_DATA_WORD, 0x0, 0xea}, + {"A2MaxD", FIELDTYPE_DATA_WORD, 0x0, 0xec}, + {"A2MaxD(N)", FIELDTYPE_DATA_WORD, 0x0, 0xee}, + {"A2MaxD(H)", FIELDTYPE_DATA_WORD, 0x0, 0xf0}, + {"S1MinD", FIELDTYPE_DATA_WORD, 0x0, 0xf2}, + {"S1MinD(N)", FIELDTYPE_DATA_WORD, 0x0, 0xf4}, + {"S1MinD(H)", FIELDTYPE_DATA_WORD, 0x0, 0xf6}, + {"S1MaxD", FIELDTYPE_DATA_WORD, 0x0, 0xf8}, + {"S1MaxD(N)", FIELDTYPE_DATA_WORD, 0x0, 0xfa}, + {"S1MaxD(H)", FIELDTYPE_DATA_WORD, 0x0, 0xfc}, + {"El1Mode", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xfe}, + {"El2Mode", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xff}, + {"El3Mode", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x100}, + {"El1Type", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x101}, + {"El2Type", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x102}, + {"El3Type", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x103}, + {"El1Pct", FIELDTYPE_DATA_BYTE, 0x0, 0x104}, + {"El1Pct(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x105}, + {"El1Pct(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x106}, + {"El2Pct", FIELDTYPE_DATA_BYTE, 0x0, 0x107}, + {"El2Pct(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x108}, + {"El2Pct(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x109}, + {"El3Pct", FIELDTYPE_DATA_BYTE, 0x0, 0x10a}, + {"El3Pct(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x10b}, + {"El3Pct(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x10c}, + {"El1MinD", FIELDTYPE_DATA_WORD, 0x0, 0x10e}, + {"El1MinD(N)", FIELDTYPE_DATA_WORD, 0x0, 0x110}, + {"El1MinD(H)", FIELDTYPE_DATA_WORD, 0x0, 0x112}, + {"El2MinD", FIELDTYPE_DATA_WORD, 0x0, 0x114}, + {"El2MinD(N)", FIELDTYPE_DATA_WORD, 0x0, 0x116}, + {"El2MinD(H)", FIELDTYPE_DATA_WORD, 0x0, 0x118}, + {"El3MinD", FIELDTYPE_DATA_WORD, 0x0, 0x11a}, + {"El3MinD(N)", FIELDTYPE_DATA_WORD, 0x0, 0x11c}, + {"El3MinD(H)", FIELDTYPE_DATA_WORD, 0x0, 0x11e}, + {"El1MaxD", FIELDTYPE_DATA_WORD, 0x0, 0x120}, + {"El1MaxD(N)", FIELDTYPE_DATA_WORD, 0x0, 0x122}, + {"El1MaxD(H)", FIELDTYPE_DATA_WORD, 0x0, 0x124}, + {"El2MaxD", FIELDTYPE_DATA_WORD, 0x0, 0x126}, + {"El2MaxD(N)", FIELDTYPE_DATA_WORD, 0x0, 0x128}, + {"El2MaxD(H)", FIELDTYPE_DATA_WORD, 0x0, 0x12a}, + {"El3MaxD", FIELDTYPE_DATA_WORD, 0x0, 0x12c}, + {"El3MaxD(N)", FIELDTYPE_DATA_WORD, 0x0, 0x12e}, + {"El3MaxD(H)", FIELDTYPE_DATA_WORD, 0x0, 0x130}, + {"El1Dur", FIELDTYPE_DATA_WORD, 0x0, 0x132}, + {"El1Dur(N)", FIELDTYPE_DATA_WORD, 0x0, 0x134}, + {"El1Dur(H)", FIELDTYPE_DATA_WORD, 0x0, 0x136}, + {"El2Dur", FIELDTYPE_DATA_WORD, 0x0, 0x138}, + {"El2Dur(N)", FIELDTYPE_DATA_WORD, 0x0, 0x13a}, + {"El2Dur(H)", FIELDTYPE_DATA_WORD, 0x0, 0x13c}, + {"El3Dur", FIELDTYPE_DATA_WORD, 0x0, 0x13e}, + {"El3Dur(N)", FIELDTYPE_DATA_WORD, 0x0, 0x140}, + {"El3Dur(H)", FIELDTYPE_DATA_WORD, 0x0, 0x142}, + {"ResDm", FIELDTYPE_DATA_WORD, 0x0, 0x144}, + {"ResDm(N)", FIELDTYPE_DATA_WORD, 0x0, 0x146}, + {"ResDm(H)", FIELDTYPE_DATA_WORD, 0x0, 0x148}, + {"ResMa", FIELDTYPE_DATA_WORD, 0x0, 0x14a}, + {"ResMa(N)", FIELDTYPE_DATA_WORD, 0x0, 0x14c}, + {"ResMa(H)", FIELDTYPE_DATA_WORD, 0x0, 0x14e}, + {"ResFi", FIELDTYPE_DATA_WORD, 0x0, 0x150}, + {"ResFi(N)", FIELDTYPE_DATA_WORD, 0x0, 0x152}, + {"ResFi(H)", FIELDTYPE_DATA_WORD, 0x0, 0x154}, + {"ResLi", FIELDTYPE_DATA_WORD, 0x0, 0x156}, + {"ResLi(N)", FIELDTYPE_DATA_WORD, 0x0, 0x158}, + {"ResLi(H)", FIELDTYPE_DATA_WORD, 0x0, 0x15a}, + {"ResCo", FIELDTYPE_DATA_WORD, 0x0, 0x15c}, + {"ResCo(N)", FIELDTYPE_DATA_WORD, 0x0, 0x15e}, + {"ResCo(H)", FIELDTYPE_DATA_WORD, 0x0, 0x160}, + {"ResPo", FIELDTYPE_DATA_WORD, 0x0, 0x162}, + {"ResPo(N)", FIELDTYPE_DATA_WORD, 0x0, 0x164}, + {"ResPo(H)", FIELDTYPE_DATA_WORD, 0x0, 0x166}, + {"ColdEffect", FIELDTYPE_DATA_BYTE, 0x0, 0x168}, + {"ColdEffect(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x169}, + {"ColdEffect(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x16a}, + {"SendSkills", FIELDTYPE_DATA_DWORD_2, 0x0, 0x16c}, + {"Skill1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x170}, + {"Skill2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x172}, + {"Skill3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x174}, + {"Skill4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x176}, + {"Skill5", FIELDTYPE_NAME_TO_WORD, 0x0, 0x178}, + {"Skill6", FIELDTYPE_NAME_TO_WORD, 0x0, 0x17a}, + {"Skill7", FIELDTYPE_NAME_TO_WORD, 0x0, 0x17c}, + {"Skill8", FIELDTYPE_NAME_TO_WORD, 0x0, 0x17e}, + {"Sk1lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x198}, + {"Sk2lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x199}, + {"Sk3lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19a}, + {"Sk4lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19b}, + {"Sk5lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19c}, + {"Sk6lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19d}, + {"Sk7lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19e}, + {"Sk8lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x19f}, + {"DamageRegen", FIELDTYPE_DATA_DWORD, 0x0, 0x1a0}, + {"SplEndDeath", FIELDTYPE_DATA_BYTE, 0x0, 0x1a4}, + {"SplGetModeChart", FIELDTYPE_DATA_BYTE, 0x0, 0x1a5}, + {"SplEndGeneric", FIELDTYPE_DATA_BYTE, 0x0, 0x1a6}, + {"SplClientEnd", FIELDTYPE_DATA_BYTE, 0x0, 0x1a7}, + {"end", FIELDTYPE_END, 0x0, 0x1a8}, +}; +static BinField skilldescTable[] = { + {"skilldesc", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"skillpage", FIELDTYPE_DATA_BYTE, 0x0, 0x2}, + {"skillrow", FIELDTYPE_DATA_BYTE, 0x0, 0x3}, + {"skillcolumn", FIELDTYPE_DATA_BYTE, 0x0, 0x4}, + {"ListRow", FIELDTYPE_DATA_BYTE, 0x0, 0x5}, + {"ListPool", FIELDTYPE_DATA_BYTE, 0x0, 0x6}, + {"iconcel", FIELDTYPE_DATA_BYTE, 0x0, 0x7}, + {"str name", FIELDTYPE_KEY_TO_WORD, 0x0, 0x8}, + {"str short", FIELDTYPE_KEY_TO_WORD, 0x0, 0xa}, + {"str long", FIELDTYPE_KEY_TO_WORD, 0x0, 0xc}, + {"str alt", FIELDTYPE_KEY_TO_WORD, 0x0, 0xe}, + {"str mana", FIELDTYPE_KEY_TO_WORD, 0x0, 0x10}, + {"descdam", FIELDTYPE_DATA_WORD, 0x0, 0x12}, + {"descatt", FIELDTYPE_DATA_WORD, 0x0, 0x14}, + {"ddam calc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x18}, + {"ddam calc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x1c}, + {"p1dmelem", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x20}, + {"p2dmelem", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x21}, + {"p3dmelem", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x22}, + {"p1dmmin", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x24}, + {"p2dmmin", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x28}, + {"p3dmmin", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x2c}, + {"p1dmmax", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x30}, + {"p2dmmax", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x34}, + {"p3dmmax", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x38}, + {"descmissile1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3c}, + {"descmissile2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3e}, + {"descmissile3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x40}, + {"descline1", FIELDTYPE_DATA_BYTE, 0x0, 0x42}, + {"descline2", FIELDTYPE_DATA_BYTE, 0x0, 0x43}, + {"descline3", FIELDTYPE_DATA_BYTE, 0x0, 0x44}, + {"descline4", FIELDTYPE_DATA_BYTE, 0x0, 0x45}, + {"descline5", FIELDTYPE_DATA_BYTE, 0x0, 0x46}, + {"descline6", FIELDTYPE_DATA_BYTE, 0x0, 0x47}, + {"dsc2line1", FIELDTYPE_DATA_BYTE, 0x0, 0x48}, + {"dsc2line2", FIELDTYPE_DATA_BYTE, 0x0, 0x49}, + {"dsc2line3", FIELDTYPE_DATA_BYTE, 0x0, 0x4a}, + {"dsc2line4", FIELDTYPE_DATA_BYTE, 0x0, 0x4b}, + {"dsc3line1", FIELDTYPE_DATA_BYTE, 0x0, 0x4c}, + {"dsc3line2", FIELDTYPE_DATA_BYTE, 0x0, 0x4d}, + {"dsc3line3", FIELDTYPE_DATA_BYTE, 0x0, 0x4e}, + {"dsc3line4", FIELDTYPE_DATA_BYTE, 0x0, 0x4f}, + {"dsc3line5", FIELDTYPE_DATA_BYTE, 0x0, 0x50}, + {"dsc3line6", FIELDTYPE_DATA_BYTE, 0x0, 0x51}, + {"dsc3line7", FIELDTYPE_DATA_BYTE, 0x0, 0x52}, + {"desctexta1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x54}, + {"desctexta2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x56}, + {"desctexta3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x58}, + {"desctexta4", FIELDTYPE_KEY_TO_WORD, 0x0, 0x5a}, + {"desctexta5", FIELDTYPE_KEY_TO_WORD, 0x0, 0x5c}, + {"desctexta6", FIELDTYPE_KEY_TO_WORD, 0x0, 0x5e}, + {"dsc2texta1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x60}, + {"dsc2texta2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x62}, + {"dsc2texta3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x64}, + {"dsc2texta4", FIELDTYPE_KEY_TO_WORD, 0x0, 0x66}, + {"dsc3texta1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x68}, + {"dsc3texta2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x6a}, + {"dsc3texta3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x6c}, + {"dsc3texta4", FIELDTYPE_KEY_TO_WORD, 0x0, 0x6e}, + {"dsc3texta5", FIELDTYPE_KEY_TO_WORD, 0x0, 0x70}, + {"dsc3texta6", FIELDTYPE_KEY_TO_WORD, 0x0, 0x72}, + {"dsc3texta7", FIELDTYPE_KEY_TO_WORD, 0x0, 0x74}, + {"desctextb1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x76}, + {"desctextb2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x78}, + {"desctextb3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x7a}, + {"desctextb4", FIELDTYPE_KEY_TO_WORD, 0x0, 0x7c}, + {"desctextb5", FIELDTYPE_KEY_TO_WORD, 0x0, 0x7e}, + {"desctextb6", FIELDTYPE_KEY_TO_WORD, 0x0, 0x80}, + {"dsc2textb1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x82}, + {"dsc2textb2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x84}, + {"dsc2textb3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x86}, + {"dsc2textb4", FIELDTYPE_KEY_TO_WORD, 0x0, 0x88}, + {"dsc3textb1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x8a}, + {"dsc3textb2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x8c}, + {"dsc3textb3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x8e}, + {"dsc3textb4", FIELDTYPE_KEY_TO_WORD, 0x0, 0x90}, + {"dsc3textb5", FIELDTYPE_KEY_TO_WORD, 0x0, 0x92}, + {"dsc3textb6", FIELDTYPE_KEY_TO_WORD, 0x0, 0x94}, + {"dsc3textb7", FIELDTYPE_KEY_TO_WORD, 0x0, 0x96}, + {"desccalca1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x98}, + {"desccalca2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x9c}, + {"desccalca3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa0}, + {"desccalca4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa4}, + {"desccalca5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa8}, + {"desccalca6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xac}, + {"dsc2calca1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb0}, + {"dsc2calca2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb4}, + {"dsc2calca3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb8}, + {"dsc2calca4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xbc}, + {"dsc3calca1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc0}, + {"dsc3calca2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc4}, + {"dsc3calca3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc8}, + {"dsc3calca4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xcc}, + {"dsc3calca5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd0}, + {"dsc3calca6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd4}, + {"dsc3calca7", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd8}, + {"desccalcb1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xdc}, + {"desccalcb2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe0}, + {"desccalcb3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe4}, + {"desccalcb4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe8}, + {"desccalcb5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xec}, + {"desccalcb6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xf0}, + {"dsc2calcb1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xf4}, + {"dsc2calcb2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xf8}, + {"dsc2calcb3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xfc}, + {"dsc2calcb4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x100}, + {"dsc3calcb1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x104}, + {"dsc3calcb2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x108}, + {"dsc3calcb3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x10c}, + {"dsc3calcb4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x110}, + {"dsc3calcb5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x114}, + {"dsc3calcb6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x118}, + {"dsc3calcb7", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x11c}, + {"end", FIELDTYPE_END, 0x0, 0x120}, +}; +static BinField skillsTable[] = { + {"skill", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"decquant", FIELDTYPE_DATA_BIT, 0x0, 0x4}, + {"lob", FIELDTYPE_DATA_BIT, 0x1, 0x4}, + {"progressive", FIELDTYPE_DATA_BIT, 0x2, 0x4}, + {"finishing", FIELDTYPE_DATA_BIT, 0x3, 0x4}, + {"passive", FIELDTYPE_DATA_BIT, 0x4, 0x4}, + {"aura", FIELDTYPE_DATA_BIT, 0x5, 0x4}, + {"periodic", FIELDTYPE_DATA_BIT, 0x6, 0x4}, + {"prgstack", FIELDTYPE_DATA_BIT, 0x7, 0x4}, + {"InTown", FIELDTYPE_DATA_BIT, 0x8, 0x4}, + {"Kick", FIELDTYPE_DATA_BIT, 0x9, 0x4}, + {"InGame", FIELDTYPE_DATA_BIT, 0xa, 0x4}, + {"repeat", FIELDTYPE_DATA_BIT, 0xb, 0x4}, + {"stsuccessonly", FIELDTYPE_DATA_BIT, 0xc, 0x4}, + {"stsounddelay", FIELDTYPE_DATA_BIT, 0xd, 0x4}, + {"weaponsnd", FIELDTYPE_DATA_BIT, 0xe, 0x4}, + {"immediate", FIELDTYPE_DATA_BIT, 0xf, 0x4}, + {"noammo", FIELDTYPE_DATA_BIT, 0x10, 0x4}, + {"enhanceable", FIELDTYPE_DATA_BIT, 0x11, 0x4}, + {"durability", FIELDTYPE_DATA_BIT, 0x12, 0x4}, + {"UseAttackRate", FIELDTYPE_DATA_BIT, 0x13, 0x4}, + {"TargetableOnly", FIELDTYPE_DATA_BIT, 0x14, 0x4}, + {"SearchEnemyXY", FIELDTYPE_DATA_BIT, 0x15, 0x4}, + {"SearchEnemyNear", FIELDTYPE_DATA_BIT, 0x16, 0x4}, + {"SearchOpenXY", FIELDTYPE_DATA_BIT, 0x17, 0x4}, + {"TargetCorpse", FIELDTYPE_DATA_BIT, 0x18, 0x4}, + {"TargetPet", FIELDTYPE_DATA_BIT, 0x19, 0x4}, + {"TargetAlly", FIELDTYPE_DATA_BIT, 0x1a, 0x4}, + {"TargetItem", FIELDTYPE_DATA_BIT, 0x1b, 0x4}, + {"AttackNoMana", FIELDTYPE_DATA_BIT, 0x1c, 0x4}, + {"ItemTgtDo", FIELDTYPE_DATA_BIT, 0x1d, 0x4}, + {"leftskill", FIELDTYPE_DATA_BIT, 0x1e, 0x4}, + {"interrupt", FIELDTYPE_DATA_BIT, 0x1f, 0x4}, + {"TgtPlaceCheck", FIELDTYPE_DATA_BIT, 0x20, 0x4}, + {"ItemCheckStart", FIELDTYPE_DATA_BIT, 0x21, 0x4}, + {"ItemCltCheckStart", FIELDTYPE_DATA_BIT, 0x22, 0x4}, + {"general", FIELDTYPE_DATA_BIT, 0x23, 0x4}, + {"scroll", FIELDTYPE_DATA_BIT, 0x24, 0x4}, + {"usemanaondo", FIELDTYPE_DATA_BIT, 0x25, 0x4}, + {"warp", FIELDTYPE_DATA_BIT, 0x26, 0x4}, + {"charclass", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xc}, + {"anim", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x10}, + {"monanim", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x11}, + {"seqtrans", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x12}, + {"seqnum", FIELDTYPE_DATA_BYTE, 0x0, 0x13}, + {"range", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x14}, + {"SelectProc", FIELDTYPE_DATA_BYTE, 0x0, 0x15}, + {"seqinput", FIELDTYPE_DATA_BYTE, 0x0, 0x16}, + {"itypea1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x18}, + {"itypea2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x1a}, + {"itypea3", FIELDTYPE_CODE_TO_WORD, 0x0, 0x1c}, + {"itypeb1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x1e}, + {"itypeb2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x20}, + {"itypeb3", FIELDTYPE_CODE_TO_WORD, 0x0, 0x22}, + {"etypea1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x24}, + {"etypea2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x26}, + {"etypeb1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x28}, + {"etypeb2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x2a}, + {"srvstfunc", FIELDTYPE_DATA_WORD, 0x0, 0x2c}, + {"srvdofunc", FIELDTYPE_DATA_WORD, 0x0, 0x2e}, + {"srvprgfunc1", FIELDTYPE_DATA_WORD, 0x0, 0x30}, + {"srvprgfunc2", FIELDTYPE_DATA_WORD, 0x0, 0x32}, + {"srvprgfunc3", FIELDTYPE_DATA_WORD, 0x0, 0x34}, + {"prgcalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x38}, + {"prgcalc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x3c}, + {"prgcalc3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x40}, + {"prgdam", FIELDTYPE_DATA_BYTE, 0x0, 0x44}, + {"srvmissile", FIELDTYPE_NAME_TO_WORD, 0x0, 0x46}, + {"srvmissilea", FIELDTYPE_NAME_TO_WORD, 0x0, 0x48}, + {"srvmissileb", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4a}, + {"srvmissilec", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4c}, + {"srvoverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4e}, + {"aurafilter", FIELDTYPE_DATA_DWORD, 0x0, 0x50}, + {"aurastat1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x54}, + {"aurastat2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x56}, + {"aurastat3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x58}, + {"aurastat4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5a}, + {"aurastat5", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5c}, + {"aurastat6", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5e}, + {"auralencalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x60}, + {"aurarangecalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x64}, + {"aurastatcalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x68}, + {"aurastatcalc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x6c}, + {"aurastatcalc3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x70}, + {"aurastatcalc4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x74}, + {"aurastatcalc5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x78}, + {"aurastatcalc6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x7c}, + {"aurastate", FIELDTYPE_NAME_TO_WORD, 0x0, 0x80}, + {"auratargetstate", FIELDTYPE_NAME_TO_WORD, 0x0, 0x82}, + {"auraevent1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x84}, + {"auraevent2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x86}, + {"auraevent3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x88}, + {"auraeventfunc1", FIELDTYPE_DATA_WORD, 0x0, 0x8a}, + {"auraeventfunc2", FIELDTYPE_DATA_WORD, 0x0, 0x8c}, + {"auraeventfunc3", FIELDTYPE_DATA_WORD, 0x0, 0x8e}, + {"auratgtevent", FIELDTYPE_NAME_TO_WORD, 0x0, 0x90}, + {"auratgteventfunc", FIELDTYPE_DATA_WORD, 0x0, 0x92}, + {"passivestate", FIELDTYPE_NAME_TO_WORD, 0x0, 0x94}, + {"passiveitype", FIELDTYPE_CODE_TO_WORD, 0x0, 0x96}, + {"passivestat1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x98}, + {"passivestat2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9a}, + {"passivestat3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9c}, + {"passivestat4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9e}, + {"passivestat5", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa0}, + {"passivecalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa4}, + {"passivecalc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa8}, + {"passivecalc3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xac}, + {"passivecalc4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb0}, + {"passivecalc5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb4}, + {"passiveevent", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb8}, + {"passiveeventfunc", FIELDTYPE_DATA_WORD, 0x0, 0xba}, + {"summon", FIELDTYPE_NAME_TO_WORD, 0x0, 0xbc}, + {"pettype", FIELDTYPE_NAME_TO_WORD_2, 0x0, 0xbe}, + {"summode", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xbf}, + {"petmax", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc0}, + {"sumskill1", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc4}, + {"sumskill2", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc6}, + {"sumskill3", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc8}, + {"sumskill4", FIELDTYPE_NAME_TO_WORD, 0x0, 0xca}, + {"sumskill5", FIELDTYPE_NAME_TO_WORD, 0x0, 0xcc}, + {"sumsk1calc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd0}, + {"sumsk2calc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd4}, + {"sumsk3calc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd8}, + {"sumsk4calc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xdc}, + {"sumsk5calc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe0}, + {"sumumod", FIELDTYPE_DATA_WORD, 0x0, 0xe4}, + {"sumoverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0xe6}, + {"cltmissile", FIELDTYPE_NAME_TO_WORD, 0x0, 0xe8}, + {"cltmissilea", FIELDTYPE_NAME_TO_WORD, 0x0, 0xea}, + {"cltmissileb", FIELDTYPE_NAME_TO_WORD, 0x0, 0xec}, + {"cltmissilec", FIELDTYPE_NAME_TO_WORD, 0x0, 0xee}, + {"cltmissiled", FIELDTYPE_NAME_TO_WORD, 0x0, 0xf0}, + {"cltstfunc", FIELDTYPE_DATA_WORD, 0x0, 0xf2}, + {"cltdofunc", FIELDTYPE_DATA_WORD, 0x0, 0xf4}, + {"cltprgfunc1", FIELDTYPE_DATA_WORD, 0x0, 0xf6}, + {"cltprgfunc2", FIELDTYPE_DATA_WORD, 0x0, 0xf8}, + {"cltprgfunc3", FIELDTYPE_DATA_WORD, 0x0, 0xfa}, + {"stsound", FIELDTYPE_NAME_TO_WORD, 0x0, 0xfc}, + {"stsoundclass", FIELDTYPE_NAME_TO_WORD, 0x0, 0xfe}, + {"dosound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x100}, + {"dosound a", FIELDTYPE_NAME_TO_WORD, 0x0, 0x102}, + {"dosound b", FIELDTYPE_NAME_TO_WORD, 0x0, 0x104}, + {"castoverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0x106}, + {"tgtoverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0x108}, + {"tgtsound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x10a}, + {"prgoverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0x10c}, + {"prgsound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x10e}, + {"cltoverlaya", FIELDTYPE_NAME_TO_WORD, 0x0, 0x110}, + {"cltoverlayb", FIELDTYPE_NAME_TO_WORD, 0x0, 0x112}, + {"cltcalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x114}, + {"cltcalc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x118}, + {"cltcalc3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x11c}, + {"ItemTarget", FIELDTYPE_DATA_BYTE, 0x0, 0x120}, + {"ItemCastSound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x122}, + {"ItemCastOverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0x124}, + {"perdelay", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x128}, + {"maxlvl", FIELDTYPE_DATA_WORD, 0x0, 0x12c}, + {"ResultFlags", FIELDTYPE_DATA_WORD, 0x0, 0x12e}, + {"HitFlags", FIELDTYPE_DATA_DWORD_2, 0x0, 0x130}, + {"HitClass", FIELDTYPE_DATA_DWORD_2, 0x0, 0x134}, + {"calc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x138}, + {"calc2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x13c}, + {"calc3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x140}, + {"calc4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x144}, + {"Param1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x148}, + {"Param2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x14c}, + {"Param3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x150}, + {"Param4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x154}, + {"Param5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x158}, + {"Param6", FIELDTYPE_DATA_DWORD_2, 0x0, 0x15c}, + {"Param7", FIELDTYPE_DATA_DWORD_2, 0x0, 0x160}, + {"Param8", FIELDTYPE_DATA_DWORD_2, 0x0, 0x164}, + {"weapsel", FIELDTYPE_DATA_BYTE, 0x0, 0x168}, + {"ItemEffect", FIELDTYPE_DATA_WORD, 0x0, 0x16a}, + {"ItemCltEffect", FIELDTYPE_DATA_WORD, 0x0, 0x16c}, + {"skpoints", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x170}, + {"reqlevel", FIELDTYPE_DATA_WORD, 0x0, 0x174}, + {"reqstr", FIELDTYPE_DATA_WORD, 0x0, 0x176}, + {"reqdex", FIELDTYPE_DATA_WORD, 0x0, 0x178}, + {"reqint", FIELDTYPE_DATA_WORD, 0x0, 0x17a}, + {"reqvit", FIELDTYPE_DATA_WORD, 0x0, 0x17c}, + {"reqskill1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x17e}, + {"reqskill2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x180}, + {"reqskill3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x182}, + {"startmana", FIELDTYPE_DATA_WORD, 0x0, 0x184}, + {"minmana", FIELDTYPE_DATA_WORD, 0x0, 0x186}, + {"manashift", FIELDTYPE_DATA_WORD, 0x0, 0x188}, + {"mana", FIELDTYPE_DATA_WORD, 0x0, 0x18a}, + {"lvlmana", FIELDTYPE_DATA_WORD, 0x0, 0x18c}, + {"attackrank", FIELDTYPE_DATA_BYTE, 0x0, 0x18e}, + {"lineofsight", FIELDTYPE_DATA_BYTE, 0x0, 0x18f}, + {"delay", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x190}, + {"skilldesc", FIELDTYPE_NAME_TO_WORD, 0x0, 0x194}, + {"ToHit", FIELDTYPE_DATA_DWORD, 0x0, 0x198}, + {"LevToHit", FIELDTYPE_DATA_DWORD, 0x0, 0x19c}, + {"ToHitCalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x1a0}, + {"HitShift", FIELDTYPE_DATA_BYTE, 0x0, 0x1a4}, + {"SrcDam", FIELDTYPE_DATA_BYTE, 0x0, 0x1a5}, + {"MinDam", FIELDTYPE_DATA_DWORD, 0x0, 0x1a8}, + {"MaxDam", FIELDTYPE_DATA_DWORD, 0x0, 0x1ac}, + {"MinLevDam1", FIELDTYPE_DATA_DWORD, 0x0, 0x1b0}, + {"MinLevDam2", FIELDTYPE_DATA_DWORD, 0x0, 0x1b4}, + {"MinLevDam3", FIELDTYPE_DATA_DWORD, 0x0, 0x1b8}, + {"MinLevDam4", FIELDTYPE_DATA_DWORD, 0x0, 0x1bc}, + {"MinLevDam5", FIELDTYPE_DATA_DWORD, 0x0, 0x1c0}, + {"MaxLevDam1", FIELDTYPE_DATA_DWORD, 0x0, 0x1c4}, + {"MaxLevDam2", FIELDTYPE_DATA_DWORD, 0x0, 0x1c8}, + {"MaxLevDam3", FIELDTYPE_DATA_DWORD, 0x0, 0x1cc}, + {"MaxLevDam4", FIELDTYPE_DATA_DWORD, 0x0, 0x1d0}, + {"MaxLevDam5", FIELDTYPE_DATA_DWORD, 0x0, 0x1d4}, + {"DmgSymPerCalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x1d8}, + {"EType", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x1dc}, + {"EMin", FIELDTYPE_DATA_DWORD, 0x0, 0x1e0}, + {"EMax", FIELDTYPE_DATA_DWORD, 0x0, 0x1e4}, + {"EMinLev1", FIELDTYPE_DATA_DWORD, 0x0, 0x1e8}, + {"EMinLev2", FIELDTYPE_DATA_DWORD, 0x0, 0x1ec}, + {"EMinLev3", FIELDTYPE_DATA_DWORD, 0x0, 0x1f0}, + {"EMinLev4", FIELDTYPE_DATA_DWORD, 0x0, 0x1f4}, + {"EMinLev5", FIELDTYPE_DATA_DWORD, 0x0, 0x1f8}, + {"EMaxLev1", FIELDTYPE_DATA_DWORD, 0x0, 0x1fc}, + {"EMaxLev2", FIELDTYPE_DATA_DWORD, 0x0, 0x200}, + {"EMaxLev3", FIELDTYPE_DATA_DWORD, 0x0, 0x204}, + {"EMaxLev4", FIELDTYPE_DATA_DWORD, 0x0, 0x208}, + {"EMaxLev5", FIELDTYPE_DATA_DWORD, 0x0, 0x20c}, + {"EDmgSymPerCalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x210}, + {"ELen", FIELDTYPE_DATA_DWORD, 0x0, 0x214}, + {"ELevLen1", FIELDTYPE_DATA_DWORD, 0x0, 0x218}, + {"ELevLen2", FIELDTYPE_DATA_DWORD, 0x0, 0x21c}, + {"ELevLen3", FIELDTYPE_DATA_DWORD, 0x0, 0x220}, + {"ELenSymPerCalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x224}, + {"restrict", FIELDTYPE_DATA_BYTE, 0x0, 0x228}, + {"state1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x22a}, + {"state2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x22c}, + {"state3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x22e}, + {"aitype", FIELDTYPE_DATA_BYTE, 0x0, 0x230}, + {"aibonus", FIELDTYPE_DATA_WORD, 0x0, 0x232}, + {"cost mult", FIELDTYPE_DATA_DWORD, 0x0, 0x234}, + {"cost add", FIELDTYPE_DATA_DWORD, 0x0, 0x238}, + {"end", FIELDTYPE_END, 0x0, 0x23c}, +}; +static BinField objectsTable[] = { + {"Name", FIELDTYPE_DATA_ASCII, 0x3f, 0x0}, + {"Token", FIELDTYPE_DATA_ASCII, 0x2, 0xc0}, + {"SpawnMax", FIELDTYPE_DATA_BYTE, 0x0, 0xc3}, + {"Selectable0", FIELDTYPE_DATA_BYTE, 0x0, 0xc4}, + {"Selectable1", FIELDTYPE_DATA_BYTE, 0x0, 0xc5}, + {"Selectable2", FIELDTYPE_DATA_BYTE, 0x0, 0xc6}, + {"Selectable3", FIELDTYPE_DATA_BYTE, 0x0, 0xc7}, + {"Selectable4", FIELDTYPE_DATA_BYTE, 0x0, 0xc8}, + {"Selectable5", FIELDTYPE_DATA_BYTE, 0x0, 0xc9}, + {"Selectable6", FIELDTYPE_DATA_BYTE, 0x0, 0xca}, + {"Selectable7", FIELDTYPE_DATA_BYTE, 0x0, 0xcb}, + {"TrapProb", FIELDTYPE_DATA_BYTE, 0x0, 0xcc}, + {"SizeX", FIELDTYPE_DATA_DWORD, 0x0, 0xd0}, + {"SizeY", FIELDTYPE_DATA_DWORD, 0x0, 0xd4}, + {"FrameCnt0", FIELDTYPE_DATA_DWORD, 0x0, 0xd8}, + {"FrameCnt1", FIELDTYPE_DATA_DWORD, 0x0, 0xdc}, + {"FrameCnt2", FIELDTYPE_DATA_DWORD, 0x0, 0xe0}, + {"FrameCnt3", FIELDTYPE_DATA_DWORD, 0x0, 0xe4}, + {"FrameCnt4", FIELDTYPE_DATA_DWORD, 0x0, 0xe8}, + {"FrameCnt5", FIELDTYPE_DATA_DWORD, 0x0, 0xec}, + {"FrameCnt6", FIELDTYPE_DATA_DWORD, 0x0, 0xf0}, + {"FrameCnt7", FIELDTYPE_DATA_DWORD, 0x0, 0xf4}, + {"FrameDelta0", FIELDTYPE_DATA_WORD, 0x0, 0xf8}, + {"FrameDelta1", FIELDTYPE_DATA_WORD, 0x0, 0xfa}, + {"FrameDelta2", FIELDTYPE_DATA_WORD, 0x0, 0xfc}, + {"FrameDelta3", FIELDTYPE_DATA_WORD, 0x0, 0xfe}, + {"FrameDelta4", FIELDTYPE_DATA_WORD, 0x0, 0x100}, + {"FrameDelta5", FIELDTYPE_DATA_WORD, 0x0, 0x102}, + {"FrameDelta6", FIELDTYPE_DATA_WORD, 0x0, 0x104}, + {"FrameDelta7", FIELDTYPE_DATA_WORD, 0x0, 0x106}, + {"CycleAnim0", FIELDTYPE_DATA_BYTE, 0x0, 0x108}, + {"CycleAnim1", FIELDTYPE_DATA_BYTE, 0x0, 0x109}, + {"CycleAnim2", FIELDTYPE_DATA_BYTE, 0x0, 0x10a}, + {"CycleAnim3", FIELDTYPE_DATA_BYTE, 0x0, 0x10b}, + {"CycleAnim4", FIELDTYPE_DATA_BYTE, 0x0, 0x10c}, + {"CycleAnim5", FIELDTYPE_DATA_BYTE, 0x0, 0x10d}, + {"CycleAnim6", FIELDTYPE_DATA_BYTE, 0x0, 0x10e}, + {"CycleAnim7", FIELDTYPE_DATA_BYTE, 0x0, 0x10f}, + {"Lit0", FIELDTYPE_DATA_BYTE, 0x0, 0x110}, + {"Lit1", FIELDTYPE_DATA_BYTE, 0x0, 0x111}, + {"Lit2", FIELDTYPE_DATA_BYTE, 0x0, 0x112}, + {"Lit3", FIELDTYPE_DATA_BYTE, 0x0, 0x113}, + {"Lit4", FIELDTYPE_DATA_BYTE, 0x0, 0x114}, + {"Lit5", FIELDTYPE_DATA_BYTE, 0x0, 0x115}, + {"Lit6", FIELDTYPE_DATA_BYTE, 0x0, 0x116}, + {"Lit7", FIELDTYPE_DATA_BYTE, 0x0, 0x117}, + {"BlocksLight0", FIELDTYPE_DATA_BYTE, 0x0, 0x118}, + {"BlocksLight1", FIELDTYPE_DATA_BYTE, 0x0, 0x119}, + {"BlocksLight2", FIELDTYPE_DATA_BYTE, 0x0, 0x11a}, + {"BlocksLight3", FIELDTYPE_DATA_BYTE, 0x0, 0x11b}, + {"BlocksLight4", FIELDTYPE_DATA_BYTE, 0x0, 0x11c}, + {"BlocksLight5", FIELDTYPE_DATA_BYTE, 0x0, 0x11d}, + {"BlocksLight6", FIELDTYPE_DATA_BYTE, 0x0, 0x11e}, + {"BlocksLight7", FIELDTYPE_DATA_BYTE, 0x0, 0x11f}, + {"HasCollision0", FIELDTYPE_DATA_BYTE, 0x0, 0x120}, + {"HasCollision1", FIELDTYPE_DATA_BYTE, 0x0, 0x121}, + {"HasCollision2", FIELDTYPE_DATA_BYTE, 0x0, 0x122}, + {"HasCollision3", FIELDTYPE_DATA_BYTE, 0x0, 0x123}, + {"HasCollision4", FIELDTYPE_DATA_BYTE, 0x0, 0x124}, + {"HasCollision5", FIELDTYPE_DATA_BYTE, 0x0, 0x125}, + {"HasCollision6", FIELDTYPE_DATA_BYTE, 0x0, 0x126}, + {"HasCollision7", FIELDTYPE_DATA_BYTE, 0x0, 0x127}, + {"IsAttackable0", FIELDTYPE_DATA_BYTE, 0x0, 0x128}, + {"Start0", FIELDTYPE_DATA_BYTE, 0x0, 0x129}, + {"Start1", FIELDTYPE_DATA_BYTE, 0x0, 0x12a}, + {"Start2", FIELDTYPE_DATA_BYTE, 0x0, 0x12b}, + {"Start3", FIELDTYPE_DATA_BYTE, 0x0, 0x12c}, + {"Start4", FIELDTYPE_DATA_BYTE, 0x0, 0x12d}, + {"Start5", FIELDTYPE_DATA_BYTE, 0x0, 0x12e}, + {"Start6", FIELDTYPE_DATA_BYTE, 0x0, 0x12f}, + {"Start7", FIELDTYPE_DATA_BYTE, 0x0, 0x130}, + {"OrderFlag0", FIELDTYPE_DATA_BYTE, 0x0, 0x131}, + {"OrderFlag1", FIELDTYPE_DATA_BYTE, 0x0, 0x132}, + {"OrderFlag2", FIELDTYPE_DATA_BYTE, 0x0, 0x133}, + {"OrderFlag3", FIELDTYPE_DATA_BYTE, 0x0, 0x134}, + {"OrderFlag4", FIELDTYPE_DATA_BYTE, 0x0, 0x135}, + {"OrderFlag5", FIELDTYPE_DATA_BYTE, 0x0, 0x136}, + {"OrderFlag6", FIELDTYPE_DATA_BYTE, 0x0, 0x137}, + {"OrderFlag7", FIELDTYPE_DATA_BYTE, 0x0, 0x138}, + {"EnvEffect", FIELDTYPE_DATA_BYTE, 0x0, 0x139}, + {"IsDoor", FIELDTYPE_DATA_BYTE, 0x0, 0x13a}, + {"BlocksVis", FIELDTYPE_DATA_BYTE, 0x0, 0x13b}, + {"Orientation", FIELDTYPE_DATA_BYTE, 0x0, 0x13c}, + {"PreOperate", FIELDTYPE_DATA_BYTE, 0x0, 0x13d}, + {"Trans", FIELDTYPE_DATA_BYTE, 0x0, 0x13e}, + {"Mode0", FIELDTYPE_DATA_BYTE, 0x0, 0x13f}, + {"Mode1", FIELDTYPE_DATA_BYTE, 0x0, 0x140}, + {"Mode2", FIELDTYPE_DATA_BYTE, 0x0, 0x141}, + {"Mode3", FIELDTYPE_DATA_BYTE, 0x0, 0x142}, + {"Mode4", FIELDTYPE_DATA_BYTE, 0x0, 0x143}, + {"Mode5", FIELDTYPE_DATA_BYTE, 0x0, 0x144}, + {"Mode6", FIELDTYPE_DATA_BYTE, 0x0, 0x145}, + {"Mode7", FIELDTYPE_DATA_BYTE, 0x0, 0x146}, + {"Xoffset", FIELDTYPE_DATA_DWORD_2, 0x0, 0x148}, + {"Yoffset", FIELDTYPE_DATA_DWORD_2, 0x0, 0x14c}, + {"Draw", FIELDTYPE_DATA_BYTE, 0x0, 0x150}, + {"HD", FIELDTYPE_DATA_BYTE, 0x0, 0x151}, + {"TR", FIELDTYPE_DATA_BYTE, 0x0, 0x152}, + {"LG", FIELDTYPE_DATA_BYTE, 0x0, 0x153}, + {"RA", FIELDTYPE_DATA_BYTE, 0x0, 0x154}, + {"LA", FIELDTYPE_DATA_BYTE, 0x0, 0x155}, + {"RH", FIELDTYPE_DATA_BYTE, 0x0, 0x156}, + {"LH", FIELDTYPE_DATA_BYTE, 0x0, 0x157}, + {"SH", FIELDTYPE_DATA_BYTE, 0x0, 0x158}, + {"S1", FIELDTYPE_DATA_BYTE, 0x0, 0x159}, + {"S2", FIELDTYPE_DATA_BYTE, 0x0, 0x15a}, + {"S3", FIELDTYPE_DATA_BYTE, 0x0, 0x15b}, + {"S4", FIELDTYPE_DATA_BYTE, 0x0, 0x15c}, + {"S5", FIELDTYPE_DATA_BYTE, 0x0, 0x15d}, + {"S6", FIELDTYPE_DATA_BYTE, 0x0, 0x15e}, + {"S7", FIELDTYPE_DATA_BYTE, 0x0, 0x15f}, + {"S8", FIELDTYPE_DATA_BYTE, 0x0, 0x160}, + {"TotalPieces", FIELDTYPE_DATA_BYTE, 0x0, 0x161}, + {"XSpace", FIELDTYPE_DATA_BYTE, 0x0, 0x162}, + {"YSpace", FIELDTYPE_DATA_BYTE, 0x0, 0x163}, + {"Red", FIELDTYPE_DATA_BYTE, 0x0, 0x164}, + {"Green", FIELDTYPE_DATA_BYTE, 0x0, 0x165}, + {"Blue", FIELDTYPE_DATA_BYTE, 0x0, 0x166}, + {"SubClass", FIELDTYPE_DATA_BYTE, 0x0, 0x167}, + {"NameOffset", FIELDTYPE_DATA_DWORD_2, 0x0, 0x168}, + {"MonsterOK", FIELDTYPE_DATA_BYTE, 0x0, 0x16d}, + {"OperateRange", FIELDTYPE_DATA_BYTE, 0x0, 0x16e}, + {"ShrineFunction", FIELDTYPE_DATA_BYTE, 0x0, 0x16f}, + {"Act", FIELDTYPE_DATA_BYTE, 0x0, 0x170}, + {"Lockable", FIELDTYPE_DATA_BYTE, 0x0, 0x171}, + {"Gore", FIELDTYPE_DATA_BYTE, 0x0, 0x172}, + {"Restore", FIELDTYPE_DATA_BYTE, 0x0, 0x173}, + {"RestoreVirgins", FIELDTYPE_DATA_BYTE, 0x0, 0x174}, + {"Sync", FIELDTYPE_DATA_BYTE, 0x0, 0x175}, + {"Parm0", FIELDTYPE_DATA_DWORD_2, 0x0, 0x178}, + {"Parm1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x17c}, + {"Parm2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x180}, + {"Parm3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x184}, + {"Parm4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x188}, + {"Parm5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x18c}, + {"Parm6", FIELDTYPE_DATA_DWORD_2, 0x0, 0x190}, + {"Parm7", FIELDTYPE_DATA_DWORD_2, 0x0, 0x194}, + {"nTgtFX", FIELDTYPE_DATA_BYTE, 0x0, 0x198}, + {"nTgtFY", FIELDTYPE_DATA_BYTE, 0x0, 0x199}, + {"nTgtBX", FIELDTYPE_DATA_BYTE, 0x0, 0x19a}, + {"nTgtBY", FIELDTYPE_DATA_BYTE, 0x0, 0x19b}, + {"Damage", FIELDTYPE_DATA_BYTE, 0x0, 0x19c}, + {"CollisionSubst", FIELDTYPE_DATA_BYTE, 0x0, 0x19d}, + {"Left", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1a0}, + {"Top", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1a4}, + {"Width", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1a8}, + {"Height", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1ac}, + {"Beta", FIELDTYPE_DATA_BYTE, 0x0, 0x1b0}, + {"InitFn", FIELDTYPE_DATA_BYTE, 0x0, 0x1b1}, + {"PopulateFn", FIELDTYPE_DATA_BYTE, 0x0, 0x1b2}, + {"OperateFn", FIELDTYPE_DATA_BYTE, 0x0, 0x1b3}, + {"ClientFn", FIELDTYPE_DATA_BYTE, 0x0, 0x1b4}, + {"Overlay", FIELDTYPE_DATA_BYTE, 0x0, 0x1b5}, + {"BlockMissile", FIELDTYPE_DATA_BYTE, 0x0, 0x1b6}, + {"DrawUnder", FIELDTYPE_DATA_BYTE, 0x0, 0x1b7}, + {"OpenWarp", FIELDTYPE_DATA_BYTE, 0x0, 0x1b8}, + {"AutoMap", FIELDTYPE_DATA_DWORD, 0x0, 0x1bc}, + {"end", FIELDTYPE_END, 0x0, 0x1c0}, +}; +static BinField missilesTable[] = { + {"Missile", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"LastCollide", FIELDTYPE_DATA_BIT, 0x0, 0x4}, + {"Explosion", FIELDTYPE_DATA_BIT, 0x1, 0x4}, + {"Pierce", FIELDTYPE_DATA_BIT, 0x2, 0x4}, + {"CanSlow", FIELDTYPE_DATA_BIT, 0x3, 0x4}, + {"CanDestroy", FIELDTYPE_DATA_BIT, 0x4, 0x4}, + {"ClientSend", FIELDTYPE_DATA_BIT, 0x5, 0x4}, + {"GetHit", FIELDTYPE_DATA_BIT, 0x6, 0x4}, + {"SoftHit", FIELDTYPE_DATA_BIT, 0x7, 0x4}, + {"ApplyMastery", FIELDTYPE_DATA_BIT, 0x8, 0x4}, + {"ReturnFire", FIELDTYPE_DATA_BIT, 0x9, 0x4}, + {"Town", FIELDTYPE_DATA_BIT, 0xa, 0x4}, + {"SrcTown", FIELDTYPE_DATA_BIT, 0xb, 0x4}, + {"NoMultiShot", FIELDTYPE_DATA_BIT, 0xc, 0x4}, + {"NoUniqueMod", FIELDTYPE_DATA_BIT, 0xd, 0x4}, + {"Half2HSrc", FIELDTYPE_DATA_BIT, 0xe, 0x4}, + {"MissileSkill", FIELDTYPE_DATA_BIT, 0xf, 0x4}, + {"pCltDoFunc", FIELDTYPE_DATA_WORD, 0x0, 0x8}, + {"pCltHitFunc", FIELDTYPE_DATA_WORD, 0x0, 0xa}, + {"pSrvDoFunc", FIELDTYPE_DATA_WORD, 0x0, 0xc}, + {"pSrvHitFunc", FIELDTYPE_DATA_WORD, 0x0, 0xe}, + {"pSrvDmgFunc", FIELDTYPE_DATA_WORD, 0x0, 0x10}, + {"TravelSound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x12}, + {"HitSound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x14}, + {"ExplosionMissile", FIELDTYPE_NAME_TO_WORD, 0x0, 0x16}, + {"SubMissile1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x18}, + {"SubMissile2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x1a}, + {"SubMissile3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x1c}, + {"CltSubMissile1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x1e}, + {"CltSubMissile2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x20}, + {"CltSubMissile3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x22}, + {"HitSubMissile1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x24}, + {"HitSubMissile2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x26}, + {"HitSubMissile3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x28}, + {"HitSubMissile4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2a}, + {"CltHitSubMissile1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2c}, + {"CltHitSubMissile2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2e}, + {"CltHitSubMissile3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x30}, + {"CltHitSubMissile4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x32}, + {"ProgSound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x34}, + {"ProgOverlay", FIELDTYPE_NAME_TO_WORD, 0x0, 0x36}, + {"Param1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x38}, + {"Param2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x3c}, + {"Param3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x40}, + {"Param4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x44}, + {"Param5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x48}, + {"sHitPar1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x4c}, + {"sHitPar2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x50}, + {"sHitPar3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x54}, + {"CltParam1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x58}, + {"CltParam2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x5c}, + {"CltParam3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x60}, + {"CltParam4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x64}, + {"CltParam5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x68}, + {"cHitPar1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x6c}, + {"cHitPar2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x70}, + {"cHitPar3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x74}, + {"dParam1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x78}, + {"dParam2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x7c}, + {"SrvCalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x80}, + {"CltCalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x84}, + {"SHitCalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x88}, + {"CHitCalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x8c}, + {"DmgCalc1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x90}, + {"HitClass", FIELDTYPE_DATA_BYTE, 0x0, 0x94}, + {"Range", FIELDTYPE_DATA_WORD, 0x0, 0x96}, + {"LevRange", FIELDTYPE_DATA_WORD, 0x0, 0x98}, + {"Vel", FIELDTYPE_DATA_BYTE, 0x0, 0x9a}, + {"VelLev", FIELDTYPE_DATA_BYTE, 0x0, 0x9b}, + {"MaxVel", FIELDTYPE_DATA_BYTE, 0x0, 0x9c}, + {"Accel", FIELDTYPE_DATA_WORD, 0x0, 0x9e}, + {"animrate", FIELDTYPE_DATA_WORD, 0x0, 0xa0}, + {"xoffset", FIELDTYPE_DATA_WORD, 0x0, 0xa2}, + {"yoffset", FIELDTYPE_DATA_WORD, 0x0, 0xa4}, + {"zoffset", FIELDTYPE_DATA_WORD, 0x0, 0xa6}, + {"HitFlags", FIELDTYPE_DATA_DWORD_2, 0x0, 0xa8}, + {"ResultFlags", FIELDTYPE_DATA_WORD, 0x0, 0xac}, + {"KnockBack", FIELDTYPE_DATA_BYTE, 0x0, 0xae}, + {"MinDamage", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb0}, + {"MaxDamage", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb4}, + {"MinLevDam1", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb8}, + {"MinLevDam2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xbc}, + {"MinLevDam3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc0}, + {"MinLevDam4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc4}, + {"MinLevDam5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc8}, + {"MaxLevDam1", FIELDTYPE_DATA_DWORD_2, 0x0, 0xcc}, + {"MaxLevDam2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd0}, + {"MaxLevDam3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd4}, + {"MaxLevDam4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd8}, + {"MaxLevDam5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xdc}, + {"DmgSymPerCalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe0}, + {"EType", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xe4}, + {"EMin", FIELDTYPE_DATA_DWORD_2, 0x0, 0xe8}, + {"EMax", FIELDTYPE_DATA_DWORD_2, 0x0, 0xec}, + {"MinELev1", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf0}, + {"MinELev2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf4}, + {"MinELev3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf8}, + {"MinELev4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xfc}, + {"MinELev5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x100}, + {"MaxELev1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x104}, + {"MaxELev2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x108}, + {"MaxELev3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x10c}, + {"MaxELev4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x110}, + {"MaxELev5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x114}, + {"EDmgSymPerCalc", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x118}, + {"ELen", FIELDTYPE_DATA_DWORD_2, 0x0, 0x11c}, + {"ELevLen1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x120}, + {"ELevLen2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x124}, + {"ELevLen3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x128}, + {"CltSrcTown", FIELDTYPE_DATA_BYTE, 0x0, 0x12c}, + {"SrcDamage", FIELDTYPE_DATA_BYTE, 0x0, 0x12d}, + {"SrcMissDmg", FIELDTYPE_DATA_BYTE, 0x0, 0x12e}, + {"Holy", FIELDTYPE_DATA_BYTE, 0x0, 0x12f}, + {"Light", FIELDTYPE_DATA_BYTE, 0x0, 0x130}, + {"Flicker", FIELDTYPE_DATA_BYTE, 0x0, 0x131}, + {"Red", FIELDTYPE_DATA_BYTE, 0x0, 0x132}, + {"Green", FIELDTYPE_DATA_BYTE, 0x0, 0x133}, + {"Blue", FIELDTYPE_DATA_BYTE, 0x0, 0x134}, + {"InitSteps", FIELDTYPE_DATA_BYTE, 0x0, 0x135}, + {"Activate", FIELDTYPE_DATA_BYTE, 0x0, 0x136}, + {"LoopAnim", FIELDTYPE_DATA_BYTE, 0x0, 0x137}, + {"CelFile", FIELDTYPE_DATA_ASCII, 0x40, 0x138}, + {"AnimLen", FIELDTYPE_DATA_BYTE, 0x0, 0x178}, + {"RandStart", FIELDTYPE_DATA_DWORD_2, 0x0, 0x17c}, + {"SubLoop", FIELDTYPE_DATA_BYTE, 0x0, 0x180}, + {"SubStart", FIELDTYPE_DATA_BYTE, 0x0, 0x181}, + {"SubStop", FIELDTYPE_DATA_BYTE, 0x0, 0x182}, + {"CollideType", FIELDTYPE_DATA_BYTE, 0x0, 0x183}, + {"Collision", FIELDTYPE_DATA_BYTE, 0x0, 0x184}, + {"ClientCol", FIELDTYPE_DATA_BYTE, 0x0, 0x185}, + {"CollideKill", FIELDTYPE_DATA_BYTE, 0x0, 0x186}, + {"CollideFriend", FIELDTYPE_DATA_BYTE, 0x0, 0x187}, + {"NextHit", FIELDTYPE_DATA_BYTE, 0x0, 0x188}, + {"NextDelay", FIELDTYPE_DATA_BYTE, 0x0, 0x189}, + {"Size", FIELDTYPE_DATA_BYTE, 0x0, 0x18a}, + {"ToHit", FIELDTYPE_DATA_BYTE, 0x0, 0x18b}, + {"AlwaysExplode", FIELDTYPE_DATA_BYTE, 0x0, 0x18c}, + {"Trans", FIELDTYPE_DATA_BYTE, 0x0, 0x18d}, + {"Qty", FIELDTYPE_DATA_BYTE, 0x0, 0x18e}, + {"SpecialSetup", FIELDTYPE_DATA_DWORD_2, 0x0, 0x190}, + {"Skill", FIELDTYPE_NAME_TO_WORD, 0x0, 0x194}, + {"HitShift", FIELDTYPE_DATA_BYTE, 0x0, 0x196}, + {"DamageRate", FIELDTYPE_DATA_DWORD_2, 0x0, 0x19c}, + {"NumDirections", FIELDTYPE_DATA_BYTE, 0x0, 0x1a0}, + {"AnimSpeed", FIELDTYPE_DATA_BYTE, 0x0, 0x1a1}, + {"LocalBlood", FIELDTYPE_DATA_BYTE, 0x0, 0x1a2}, + {"end", FIELDTYPE_END, 0x0, 0x1a4}, +}; +static BinField monstats2Table[] = { + {"Id", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"noGfxHitTest", FIELDTYPE_DATA_BIT, 0x0, 0x4}, + {"noMap", FIELDTYPE_DATA_BIT, 0x1, 0x4}, + {"noOvly", FIELDTYPE_DATA_BIT, 0x2, 0x4}, + {"isSel", FIELDTYPE_DATA_BIT, 0x3, 0x4}, + {"alSel", FIELDTYPE_DATA_BIT, 0x4, 0x4}, + {"noSel", FIELDTYPE_DATA_BIT, 0x5, 0x4}, + {"shiftSel", FIELDTYPE_DATA_BIT, 0x6, 0x4}, + {"corpseSel", FIELDTYPE_DATA_BIT, 0x7, 0x4}, + {"revive", FIELDTYPE_DATA_BIT, 0x8, 0x4}, + {"isAtt", FIELDTYPE_DATA_BIT, 0x9, 0x4}, + {"small", FIELDTYPE_DATA_BIT, 0xa, 0x4}, + {"large", FIELDTYPE_DATA_BIT, 0xb, 0x4}, + {"soft", FIELDTYPE_DATA_BIT, 0xc, 0x4}, + {"critter", FIELDTYPE_DATA_BIT, 0xd, 0x4}, + {"shadow", FIELDTYPE_DATA_BIT, 0xe, 0x4}, + {"noUniqueShift", FIELDTYPE_DATA_BIT, 0xf, 0x4}, + {"compositeDeath", FIELDTYPE_DATA_BIT, 0x10, 0x4}, + {"inert", FIELDTYPE_DATA_BIT, 0x11, 0x4}, + {"objCol", FIELDTYPE_DATA_BIT, 0x12, 0x4}, + {"deadCol", FIELDTYPE_DATA_BIT, 0x13, 0x4}, + {"unflatDead", FIELDTYPE_DATA_BIT, 0x14, 0x4}, + {"SizeX", FIELDTYPE_DATA_BYTE, 0x0, 0x8}, + {"SizeY", FIELDTYPE_DATA_BYTE, 0x0, 0x9}, + {"spawnCol", FIELDTYPE_DATA_BYTE, 0x0, 0xa}, + {"Height", FIELDTYPE_DATA_BYTE, 0x0, 0xb}, + {"overlayHeight", FIELDTYPE_DATA_BYTE, 0x0, 0xc}, + {"pixHeight", FIELDTYPE_DATA_BYTE, 0x0, 0xd}, + {"MeleeRng", FIELDTYPE_DATA_BYTE, 0x0, 0xe}, + {"BaseW", FIELDTYPE_DATA_RAW, 0x0, 0x10}, + {"HitClass", FIELDTYPE_DATA_BYTE, 0x0, 0x14}, + {"HD", FIELDTYPE_DATA_BIT, 0x0, 0xe8}, + {"TR", FIELDTYPE_DATA_BIT, 0x1, 0xe8}, + {"LG", FIELDTYPE_DATA_BIT, 0x2, 0xe8}, + {"RA", FIELDTYPE_DATA_BIT, 0x3, 0xe8}, + {"LA", FIELDTYPE_DATA_BIT, 0x4, 0xe8}, + {"RH", FIELDTYPE_DATA_BIT, 0x5, 0xe8}, + {"LH", FIELDTYPE_DATA_BIT, 0x6, 0xe8}, + {"SH", FIELDTYPE_DATA_BIT, 0x7, 0xe8}, + {"S1", FIELDTYPE_DATA_BIT, 0x8, 0xe8}, + {"S2", FIELDTYPE_DATA_BIT, 0x9, 0xe8}, + {"S3", FIELDTYPE_DATA_BIT, 0xa, 0xe8}, + {"S4", FIELDTYPE_DATA_BIT, 0xb, 0xe8}, + {"S5", FIELDTYPE_DATA_BIT, 0xc, 0xe8}, + {"S6", FIELDTYPE_DATA_BIT, 0xd, 0xe8}, + {"S7", FIELDTYPE_DATA_BIT, 0xe, 0xe8}, + {"S8", FIELDTYPE_DATA_BIT, 0xf, 0xe8}, + {"TotalPieces", FIELDTYPE_DATA_BYTE, 0x0, 0xec}, + {"mDT", FIELDTYPE_DATA_BIT, 0x0, 0xf0}, + {"mNU", FIELDTYPE_DATA_BIT, 0x1, 0xf0}, + {"mWL", FIELDTYPE_DATA_BIT, 0x2, 0xf0}, + {"mGH", FIELDTYPE_DATA_BIT, 0x3, 0xf0}, + {"mA1", FIELDTYPE_DATA_BIT, 0x4, 0xf0}, + {"mA2", FIELDTYPE_DATA_BIT, 0x5, 0xf0}, + {"mBL", FIELDTYPE_DATA_BIT, 0x6, 0xf0}, + {"mSC", FIELDTYPE_DATA_BIT, 0x7, 0xf0}, + {"mS1", FIELDTYPE_DATA_BIT, 0x8, 0xf0}, + {"mS2", FIELDTYPE_DATA_BIT, 0x9, 0xf0}, + {"mS3", FIELDTYPE_DATA_BIT, 0xa, 0xf0}, + {"mS4", FIELDTYPE_DATA_BIT, 0xb, 0xf0}, + {"mDD", FIELDTYPE_DATA_BIT, 0xc, 0xf0}, + {"mKB", FIELDTYPE_DATA_BIT, 0xd, 0xf0}, + {"mSQ", FIELDTYPE_DATA_BIT, 0xe, 0xf0}, + {"mRN", FIELDTYPE_DATA_BIT, 0xf, 0xf0}, + {"dDT", FIELDTYPE_DATA_BYTE, 0x0, 0xf4}, + {"dNU", FIELDTYPE_DATA_BYTE, 0x0, 0xf5}, + {"dWL", FIELDTYPE_DATA_BYTE, 0x0, 0xf6}, + {"dGH", FIELDTYPE_DATA_BYTE, 0x0, 0xf7}, + {"dA1", FIELDTYPE_DATA_BYTE, 0x0, 0xf8}, + {"dA2", FIELDTYPE_DATA_BYTE, 0x0, 0xf9}, + {"dBL", FIELDTYPE_DATA_BYTE, 0x0, 0xfa}, + {"dSC", FIELDTYPE_DATA_BYTE, 0x0, 0xfb}, + {"dS1", FIELDTYPE_DATA_BYTE, 0x0, 0xfc}, + {"dS2", FIELDTYPE_DATA_BYTE, 0x0, 0xfd}, + {"dS3", FIELDTYPE_DATA_BYTE, 0x0, 0xfe}, + {"dS4", FIELDTYPE_DATA_BYTE, 0x0, 0xff}, + {"dDD", FIELDTYPE_DATA_BYTE, 0x0, 0x100}, + {"dKB", FIELDTYPE_DATA_BYTE, 0x0, 0x101}, + {"dSQ", FIELDTYPE_DATA_BYTE, 0x0, 0x102}, + {"dRN", FIELDTYPE_DATA_BYTE, 0x0, 0x103}, + {"A1mv", FIELDTYPE_DATA_BIT, 0x4, 0x104}, + {"A2mv", FIELDTYPE_DATA_BIT, 0x5, 0x104}, + {"SCmv", FIELDTYPE_DATA_BIT, 0x7, 0x104}, + {"S1mv", FIELDTYPE_DATA_BIT, 0x8, 0x104}, + {"S2mv", FIELDTYPE_DATA_BIT, 0x9, 0x104}, + {"S3mv", FIELDTYPE_DATA_BIT, 0xa, 0x104}, + {"S4mv", FIELDTYPE_DATA_BIT, 0xb, 0x104}, + {"InfernoLen", FIELDTYPE_DATA_BYTE, 0x0, 0x108}, + {"InfernoAnim", FIELDTYPE_DATA_BYTE, 0x0, 0x109}, + {"InfernoRollback", FIELDTYPE_DATA_BYTE, 0x0, 0x10a}, + {"ResurrectMode", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x10b}, + {"ResurrectSkill", FIELDTYPE_NAME_TO_WORD, 0x0, 0x10c}, + {"htTop", FIELDTYPE_DATA_WORD, 0x0, 0x10e}, + {"htLeft", FIELDTYPE_DATA_WORD, 0x0, 0x110}, + {"htWidth", FIELDTYPE_DATA_WORD, 0x0, 0x112}, + {"htHeight", FIELDTYPE_DATA_WORD, 0x0, 0x114}, + {"automapCel", FIELDTYPE_DATA_DWORD, 0x0, 0x118}, + {"localBlood", FIELDTYPE_DATA_BYTE, 0x0, 0x11c}, + {"bleed", FIELDTYPE_DATA_BYTE, 0x0, 0x11d}, + {"light", FIELDTYPE_DATA_BYTE, 0x0, 0x11e}, + {"light-r", FIELDTYPE_DATA_BYTE, 0x0, 0x11f}, + {"light-g", FIELDTYPE_DATA_BYTE, 0x0, 0x120}, + {"light-b", FIELDTYPE_DATA_BYTE, 0x0, 0x121}, + {"Utrans", FIELDTYPE_DATA_BYTE, 0x0, 0x122}, + {"Utrans(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x123}, + {"Utrans(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x124}, + {"Heart", FIELDTYPE_DATA_RAW, 0x0, 0x128}, + {"BodyPart", FIELDTYPE_DATA_RAW, 0x0, 0x12c}, + {"restore", FIELDTYPE_DATA_BYTE, 0x0, 0x130}, + {"end", FIELDTYPE_END, 0x0, 0x134}, +}; +static BinField itemstatcostTable[] = { + {"stat", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"send other", FIELDTYPE_DATA_BIT, 0x0, 0x4}, + {"signed", FIELDTYPE_DATA_BIT, 0x1, 0x4}, + {"damagerelated", FIELDTYPE_DATA_BIT, 0x2, 0x4}, + {"itemspecific", FIELDTYPE_DATA_BIT, 0x3, 0x4}, + {"direct", FIELDTYPE_DATA_BIT, 0x4, 0x4}, + {"updateanimrate", FIELDTYPE_DATA_BIT, 0x9, 0x4}, + {"fmin", FIELDTYPE_DATA_BIT, 0xa, 0x4}, + {"fcallback", FIELDTYPE_DATA_BIT, 0xb, 0x4}, + {"saved", FIELDTYPE_DATA_BIT, 0xc, 0x4}, + {"csvsigned", FIELDTYPE_DATA_BIT, 0xd, 0x4}, + {"send bits", FIELDTYPE_DATA_BYTE, 0x0, 0x8}, + {"send param bits", FIELDTYPE_DATA_BYTE, 0x0, 0x9}, + {"csvbits", FIELDTYPE_DATA_BYTE, 0x0, 0xa}, + {"csvparam", FIELDTYPE_DATA_BYTE, 0x0, 0xb}, + {"divide", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"multiply", FIELDTYPE_DATA_DWORD_2, 0x0, 0x10}, + {"add", FIELDTYPE_DATA_DWORD, 0x0, 0x14}, + {"valshift", FIELDTYPE_DATA_BYTE, 0x0, 0x18}, + {"save bits", FIELDTYPE_DATA_BYTE, 0x0, 0x19}, + {"1.09-save bits", FIELDTYPE_DATA_BYTE, 0x0, 0x1a}, + {"save add", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1c}, + {"1.09-save add", FIELDTYPE_DATA_DWORD_2, 0x0, 0x20}, + {"save param bits", FIELDTYPE_DATA_DWORD, 0x0, 0x24}, + {"minaccr", FIELDTYPE_DATA_DWORD, 0x0, 0x2c}, + {"encode", FIELDTYPE_DATA_BYTE, 0x0, 0x30}, + {"maxstat", FIELDTYPE_NAME_TO_WORD, 0x0, 0x32}, + {"descpriority", FIELDTYPE_DATA_WORD, 0x0, 0x34}, + {"descfunc", FIELDTYPE_DATA_BYTE, 0x0, 0x36}, + {"descval", FIELDTYPE_DATA_BYTE, 0x0, 0x37}, + {"descstrpos", FIELDTYPE_KEY_TO_WORD, 0x0, 0x38}, + {"descstrneg", FIELDTYPE_KEY_TO_WORD, 0x0, 0x3a}, + {"descstr2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x3c}, + {"dgrp", FIELDTYPE_DATA_WORD, 0x0, 0x3e}, + {"dgrpfunc", FIELDTYPE_DATA_BYTE, 0x0, 0x40}, + {"dgrpval", FIELDTYPE_DATA_BYTE, 0x0, 0x41}, + {"dgrpstrpos", FIELDTYPE_KEY_TO_WORD, 0x0, 0x42}, + {"dgrpstrneg", FIELDTYPE_KEY_TO_WORD, 0x0, 0x44}, + {"dgrpstr2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x46}, + {"itemevent1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x48}, + {"itemevent2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4a}, + {"itemeventfunc1", FIELDTYPE_DATA_WORD, 0x0, 0x4c}, + {"itemeventfunc2", FIELDTYPE_DATA_WORD, 0x0, 0x4e}, + {"keepzero", FIELDTYPE_DATA_BYTE, 0x0, 0x50}, + {"op", FIELDTYPE_DATA_BYTE, 0x0, 0x54}, + {"op param", FIELDTYPE_DATA_BYTE, 0x0, 0x55}, + {"op base", FIELDTYPE_NAME_TO_WORD, 0x0, 0x56}, + {"op stat1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x58}, + {"op stat2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5a}, + {"op stat3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5c}, + {"stuff", FIELDTYPE_DATA_DWORD, 0x0, 0x140}, + {"end", FIELDTYPE_END, 0x0, 0x144}, +}; +static BinField levelsTable[] = { + {"Id", FIELDTYPE_DATA_BYTE, 0x0, 0x0}, + {"Pal", FIELDTYPE_DATA_BYTE, 0x0, 0x2}, + {"Act", FIELDTYPE_DATA_BYTE, 0x0, 0x3}, + {"Teleport", FIELDTYPE_DATA_BYTE, 0x0, 0x4}, + {"Rain", FIELDTYPE_DATA_BYTE, 0x0, 0x5}, + {"Mud", FIELDTYPE_DATA_BYTE, 0x0, 0x6}, + {"NoPer", FIELDTYPE_DATA_BYTE, 0x0, 0x7}, + {"IsInside", FIELDTYPE_DATA_BYTE, 0x0, 0x8}, + {"DrawEdges", FIELDTYPE_DATA_BYTE, 0x0, 0x9}, + {"WarpDist", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"MonLvl1", FIELDTYPE_DATA_WORD, 0x0, 0x10}, + {"MonLvl2", FIELDTYPE_DATA_WORD, 0x0, 0x12}, + {"MonLvl3", FIELDTYPE_DATA_WORD, 0x0, 0x14}, + {"MonLvl1Ex", FIELDTYPE_DATA_WORD, 0x0, 0x16}, + {"MonLvl2Ex", FIELDTYPE_DATA_WORD, 0x0, 0x18}, + {"MonLvl3Ex", FIELDTYPE_DATA_WORD, 0x0, 0x1a}, + {"MonDen", FIELDTYPE_DATA_DWORD, 0x0, 0x1c}, + {"MonDen(N)", FIELDTYPE_DATA_DWORD, 0x0, 0x20}, + {"MonDen(H)", FIELDTYPE_DATA_DWORD, 0x0, 0x24}, + {"MonUMin", FIELDTYPE_DATA_BYTE, 0x0, 0x28}, + {"MonUMin(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x29}, + {"MonUMin(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x2a}, + {"MonUMax", FIELDTYPE_DATA_BYTE, 0x0, 0x2b}, + {"MonUMax(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x2c}, + {"MonUMax(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x2d}, + {"MonWndr", FIELDTYPE_DATA_BYTE, 0x0, 0x2e}, + {"MonSpcWalk", FIELDTYPE_DATA_BYTE, 0x0, 0x2f}, + {"Quest", FIELDTYPE_DATA_BYTE, 0x0, 0x30}, + {"rangedspawn", FIELDTYPE_DATA_BYTE, 0x0, 0x31}, + {"NumMon", FIELDTYPE_DATA_BYTE, 0x0, 0x32}, + {"mon1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x36}, + {"mon2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x38}, + {"mon3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3a}, + {"mon4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3c}, + {"mon5", FIELDTYPE_NAME_TO_WORD, 0x0, 0x3e}, + {"mon6", FIELDTYPE_NAME_TO_WORD, 0x0, 0x40}, + {"mon7", FIELDTYPE_NAME_TO_WORD, 0x0, 0x42}, + {"mon8", FIELDTYPE_NAME_TO_WORD, 0x0, 0x44}, + {"mon9", FIELDTYPE_NAME_TO_WORD, 0x0, 0x46}, + {"mon10", FIELDTYPE_NAME_TO_WORD, 0x0, 0x48}, + {"mon11", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4a}, + {"mon12", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4c}, + {"mon13", FIELDTYPE_NAME_TO_WORD, 0x0, 0x4e}, + {"mon14", FIELDTYPE_NAME_TO_WORD, 0x0, 0x50}, + {"mon15", FIELDTYPE_NAME_TO_WORD, 0x0, 0x52}, + {"mon16", FIELDTYPE_NAME_TO_WORD, 0x0, 0x54}, + {"mon17", FIELDTYPE_NAME_TO_WORD, 0x0, 0x56}, + {"mon18", FIELDTYPE_NAME_TO_WORD, 0x0, 0x58}, + {"mon19", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5a}, + {"mon20", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5c}, + {"mon21", FIELDTYPE_NAME_TO_WORD, 0x0, 0x5e}, + {"mon22", FIELDTYPE_NAME_TO_WORD, 0x0, 0x60}, + {"mon23", FIELDTYPE_NAME_TO_WORD, 0x0, 0x62}, + {"mon24", FIELDTYPE_NAME_TO_WORD, 0x0, 0x64}, + {"mon25", FIELDTYPE_NAME_TO_WORD, 0x0, 0x66}, + {"nmon1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x68}, + {"nmon2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x6a}, + {"nmon3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x6c}, + {"nmon4", FIELDTYPE_NAME_TO_WORD, 0x0, 0x6e}, + {"nmon5", FIELDTYPE_NAME_TO_WORD, 0x0, 0x70}, + {"nmon6", FIELDTYPE_NAME_TO_WORD, 0x0, 0x72}, + {"nmon7", FIELDTYPE_NAME_TO_WORD, 0x0, 0x74}, + {"nmon8", FIELDTYPE_NAME_TO_WORD, 0x0, 0x76}, + {"nmon9", FIELDTYPE_NAME_TO_WORD, 0x0, 0x78}, + {"nmon10", FIELDTYPE_NAME_TO_WORD, 0x0, 0x7a}, + {"nmon11", FIELDTYPE_NAME_TO_WORD, 0x0, 0x7c}, + {"nmon12", FIELDTYPE_NAME_TO_WORD, 0x0, 0x7e}, + {"nmon13", FIELDTYPE_NAME_TO_WORD, 0x0, 0x80}, + {"nmon14", FIELDTYPE_NAME_TO_WORD, 0x0, 0x82}, + {"nmon15", FIELDTYPE_NAME_TO_WORD, 0x0, 0x84}, + {"nmon16", FIELDTYPE_NAME_TO_WORD, 0x0, 0x86}, + {"nmon17", FIELDTYPE_NAME_TO_WORD, 0x0, 0x88}, + {"nmon18", FIELDTYPE_NAME_TO_WORD, 0x0, 0x8a}, + {"nmon19", FIELDTYPE_NAME_TO_WORD, 0x0, 0x8c}, + {"nmon20", FIELDTYPE_NAME_TO_WORD, 0x0, 0x8e}, + {"nmon21", FIELDTYPE_NAME_TO_WORD, 0x0, 0x90}, + {"nmon22", FIELDTYPE_NAME_TO_WORD, 0x0, 0x92}, + {"nmon23", FIELDTYPE_NAME_TO_WORD, 0x0, 0x94}, + {"nmon24", FIELDTYPE_NAME_TO_WORD, 0x0, 0x96}, + {"nmon25", FIELDTYPE_NAME_TO_WORD, 0x0, 0x98}, + {"umon1", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9a}, + {"umon2", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9c}, + {"umon3", FIELDTYPE_NAME_TO_WORD, 0x0, 0x9e}, + {"umon4", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa0}, + {"umon5", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa2}, + {"umon6", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa4}, + {"umon7", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa6}, + {"umon8", FIELDTYPE_NAME_TO_WORD, 0x0, 0xa8}, + {"umon9", FIELDTYPE_NAME_TO_WORD, 0x0, 0xaa}, + {"umon10", FIELDTYPE_NAME_TO_WORD, 0x0, 0xac}, + {"umon11", FIELDTYPE_NAME_TO_WORD, 0x0, 0xae}, + {"umon12", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb0}, + {"umon13", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb2}, + {"umon14", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb4}, + {"umon15", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb6}, + {"umon16", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb8}, + {"umon17", FIELDTYPE_NAME_TO_WORD, 0x0, 0xba}, + {"umon18", FIELDTYPE_NAME_TO_WORD, 0x0, 0xbc}, + {"umon19", FIELDTYPE_NAME_TO_WORD, 0x0, 0xbe}, + {"umon20", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc0}, + {"umon21", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc2}, + {"umon22", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc4}, + {"umon23", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc6}, + {"umon24", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc8}, + {"umon25", FIELDTYPE_NAME_TO_WORD, 0x0, 0xca}, + {"cmon1", FIELDTYPE_NAME_TO_WORD, 0x0, 0xcc}, + {"cmon2", FIELDTYPE_NAME_TO_WORD, 0x0, 0xce}, + {"cmon3", FIELDTYPE_NAME_TO_WORD, 0x0, 0xd0}, + {"cmon4", FIELDTYPE_NAME_TO_WORD, 0x0, 0xd2}, + {"cpct1", FIELDTYPE_DATA_WORD, 0x0, 0xd4}, + {"cpct2", FIELDTYPE_DATA_WORD, 0x0, 0xd6}, + {"cpct3", FIELDTYPE_DATA_WORD, 0x0, 0xd8}, + {"cpct4", FIELDTYPE_DATA_WORD, 0x0, 0xda}, + {"camt1", FIELDTYPE_DATA_WORD, 0x0, 0xdc}, + {"camt2", FIELDTYPE_DATA_WORD, 0x0, 0xdc}, + {"camt3", FIELDTYPE_DATA_WORD, 0x0, 0xdc}, + {"camt4", FIELDTYPE_DATA_WORD, 0x0, 0xdc}, + {"Waypoint", FIELDTYPE_DATA_BYTE, 0x0, 0xe4}, + {"ObjGrp0", FIELDTYPE_DATA_BYTE, 0x0, 0xe5}, + {"ObjGrp1", FIELDTYPE_DATA_BYTE, 0x0, 0xe6}, + {"ObjGrp2", FIELDTYPE_DATA_BYTE, 0x0, 0xe7}, + {"ObjGrp3", FIELDTYPE_DATA_BYTE, 0x0, 0xe8}, + {"ObjGrp4", FIELDTYPE_DATA_BYTE, 0x0, 0xe9}, + {"ObjGrp5", FIELDTYPE_DATA_BYTE, 0x0, 0xea}, + {"ObjGrp6", FIELDTYPE_DATA_BYTE, 0x0, 0xeb}, + {"ObjGrp7", FIELDTYPE_DATA_BYTE, 0x0, 0xec}, + {"ObjPrb0", FIELDTYPE_DATA_BYTE, 0x0, 0xed}, + {"ObjPrb1", FIELDTYPE_DATA_BYTE, 0x0, 0xee}, + {"ObjPrb2", FIELDTYPE_DATA_BYTE, 0x0, 0xef}, + {"ObjPrb3", FIELDTYPE_DATA_BYTE, 0x0, 0xf0}, + {"ObjPrb4", FIELDTYPE_DATA_BYTE, 0x0, 0xf1}, + {"ObjPrb5", FIELDTYPE_DATA_BYTE, 0x0, 0xf2}, + {"ObjPrb6", FIELDTYPE_DATA_BYTE, 0x0, 0xf3}, + {"ObjPrb7", FIELDTYPE_DATA_BYTE, 0x0, 0xf4}, + {"LevelName", FIELDTYPE_DATA_ASCII, 0x27, 0xf5}, + {"LevelWarp", FIELDTYPE_DATA_ASCII, 0x27, 0x11d}, + {"EntryFile", FIELDTYPE_DATA_ASCII, 0x27, 0x145}, + {"Themes", FIELDTYPE_DATA_DWORD, 0x0, 0x210}, + {"FloorFilter", FIELDTYPE_DATA_DWORD, 0x0, 0x214}, + {"BlankScreen", FIELDTYPE_DATA_DWORD, 0x0, 0x218}, + {"SoundEnv", FIELDTYPE_DATA_BYTE, 0x0, 0x21c}, + {"end", FIELDTYPE_END, 0x0, 0x220}, +}; +static BinField leveldefsTable[] = { + {"QuestFlag", FIELDTYPE_DATA_DWORD_2, 0x0, 0x0}, + {"QuestFlagEx", FIELDTYPE_DATA_DWORD_2, 0x0, 0x4}, + {"Layer", FIELDTYPE_DATA_DWORD_2, 0x0, 0x8}, + {"SizeX", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc}, + {"SizeX(N)", FIELDTYPE_DATA_DWORD_2, 0x0, 0x10}, + {"SizeX(H)", FIELDTYPE_DATA_DWORD_2, 0x0, 0x14}, + {"SizeY", FIELDTYPE_DATA_DWORD_2, 0x0, 0x18}, + {"SizeY(N)", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1c}, + {"SizeY(H)", FIELDTYPE_DATA_DWORD_2, 0x0, 0x20}, + {"OffsetX", FIELDTYPE_DATA_DWORD_2, 0x0, 0x24}, + {"OffsetY", FIELDTYPE_DATA_DWORD_2, 0x0, 0x28}, + {"Depend", FIELDTYPE_DATA_DWORD_2, 0x0, 0x2c}, + {"DrlgType", FIELDTYPE_DATA_DWORD_2, 0x0, 0x30}, + {"LevelType", FIELDTYPE_DATA_DWORD_2, 0x0, 0x34}, + {"SubType", FIELDTYPE_DATA_DWORD_2, 0x0, 0x38}, + {"SubTheme", FIELDTYPE_DATA_DWORD_2, 0x0, 0x3c}, + {"SubWaypoint", FIELDTYPE_DATA_DWORD_2, 0x0, 0x40}, + {"SubShrine", FIELDTYPE_DATA_DWORD_2, 0x0, 0x44}, + {"Vis0", FIELDTYPE_DATA_DWORD_2, 0x0, 0x48}, + {"Vis1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x4c}, + {"Vis2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x50}, + {"Vis3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x54}, + {"Vis4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x58}, + {"Vis5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x5c}, + {"Vis6", FIELDTYPE_DATA_DWORD_2, 0x0, 0x60}, + {"Vis7", FIELDTYPE_DATA_DWORD_2, 0x0, 0x64}, + {"Warp0", FIELDTYPE_DATA_DWORD_2, 0x0, 0x68}, + {"Warp1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x6c}, + {"Warp2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x70}, + {"Warp3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x74}, + {"Warp4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x78}, + {"Warp5", FIELDTYPE_DATA_DWORD_2, 0x0, 0x7c}, + {"Warp6", FIELDTYPE_DATA_DWORD_2, 0x0, 0x80}, + {"Warp7", FIELDTYPE_DATA_DWORD_2, 0x0, 0x84}, + {"Intensity", FIELDTYPE_DATA_BYTE, 0x0, 0x88},// WRONG + {"Red", FIELDTYPE_DATA_BYTE, 0x0, 0x89}, + {"Green", FIELDTYPE_DATA_BYTE, 0x0, 0x8a}, + {"Blue", FIELDTYPE_DATA_BYTE, 0x0, 0x8b}, + {"Portal", FIELDTYPE_DATA_DWORD_2, 0x0, 0x8c}, + {"Position", FIELDTYPE_DATA_DWORD_2, 0x0, 0x90}, + {"SaveMonsters", FIELDTYPE_DATA_DWORD_2, 0x0, 0x94}, + {"LOSDraw", FIELDTYPE_DATA_DWORD_2, 0x0, 0x98}, + {"end", FIELDTYPE_END, 0x0, 0x9c}, +}; +static BinField lvlmazeTable[] = { + {"Level", FIELDTYPE_DATA_DWORD, 0x0, 0x0}, + {"Rooms", FIELDTYPE_DATA_DWORD, 0x0, 0x4}, + {"Rooms(N)", FIELDTYPE_DATA_DWORD, 0x0, 0x8}, + {"Rooms(H)", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"SizeX", FIELDTYPE_DATA_DWORD, 0x0, 0x10}, + {"SizeY", FIELDTYPE_DATA_DWORD, 0x0, 0x14}, + {"Merge", FIELDTYPE_DATA_DWORD, 0x0, 0x18}, + {"end", FIELDTYPE_END, 0x0, 0x1c}, +}; +static BinField lvlsubTable[] = { + {"Type", FIELDTYPE_DATA_DWORD, 0x0, 0x0}, + {"File", FIELDTYPE_DATA_ASCII, 0x3b, 0x4}, + {"CheckAll", FIELDTYPE_DATA_DWORD_2, 0x0, 0x40}, + {"BordType", FIELDTYPE_DATA_DWORD_2, 0x0, 0x44}, + {"Dt1Mask", FIELDTYPE_DATA_DWORD, 0x0, 0x48}, + {"GridSize", FIELDTYPE_DATA_DWORD, 0x0, 0x4c}, + {"Prob0", FIELDTYPE_DATA_DWORD, 0x0, 0x11c}, + {"Prob1", FIELDTYPE_DATA_DWORD, 0x0, 0x120}, + {"Prob2", FIELDTYPE_DATA_DWORD, 0x0, 0x124}, + {"Prob3", FIELDTYPE_DATA_DWORD, 0x0, 0x128}, + {"Prob4", FIELDTYPE_DATA_DWORD, 0x0, 0x12c}, + {"Trials0", FIELDTYPE_DATA_DWORD_2, 0x0, 0x130}, + {"Trials1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x134}, + {"Trials2", FIELDTYPE_DATA_DWORD_2, 0x0, 0x138}, + {"Trials3", FIELDTYPE_DATA_DWORD_2, 0x0, 0x13c}, + {"Trials4", FIELDTYPE_DATA_DWORD_2, 0x0, 0x140}, + {"Max0", FIELDTYPE_DATA_DWORD, 0x0, 0x144}, + {"Max1", FIELDTYPE_DATA_DWORD, 0x0, 0x148}, + {"Max2", FIELDTYPE_DATA_DWORD, 0x0, 0x14c}, + {"Max3", FIELDTYPE_DATA_DWORD, 0x0, 0x150}, + {"Max4", FIELDTYPE_DATA_DWORD, 0x0, 0x154}, + {"Expansion", FIELDTYPE_DATA_DWORD, 0x0, 0x158}, + {"end", FIELDTYPE_END, 0x0, 0x15c}, +}; +static BinField lvlwarpTable[] = { + {"Id", FIELDTYPE_DATA_DWORD_2, 0x0, 0x0}, + {"SelectX", FIELDTYPE_DATA_DWORD_2, 0x0, 0x4}, + {"SelectY", FIELDTYPE_DATA_DWORD_2, 0x0, 0x8}, + {"SelectDX", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc}, + {"SelectDY", FIELDTYPE_DATA_DWORD_2, 0x0, 0x10}, + {"ExitWalkX", FIELDTYPE_DATA_DWORD_2, 0x0, 0x14}, + {"ExitWalkY", FIELDTYPE_DATA_DWORD_2, 0x0, 0x18}, + {"OffsetX", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1c}, + {"OffsetY", FIELDTYPE_DATA_DWORD_2, 0x0, 0x20}, + {"LitVersion", FIELDTYPE_DATA_DWORD_2, 0x0, 0x24}, + {"Tiles", FIELDTYPE_DATA_DWORD_2, 0x0, 0x28}, + {"Direction", FIELDTYPE_DATA_ASCII, 0x1, 0x2c}, + {"end", FIELDTYPE_END, 0x0, 0x30}, +}; +static BinField lvlprestTable[] = { + {"Def", FIELDTYPE_DATA_DWORD, 0x0, 0x0}, + {"LevelId", FIELDTYPE_DATA_DWORD, 0x0, 0x4}, + {"Populate", FIELDTYPE_DATA_DWORD, 0x0, 0x8}, + {"Logicals", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"Outdoors", FIELDTYPE_DATA_DWORD, 0x0, 0x10}, + {"Animate", FIELDTYPE_DATA_DWORD, 0x0, 0x14}, + {"KillEdge", FIELDTYPE_DATA_DWORD, 0x0, 0x18}, + {"FillBlanks", FIELDTYPE_DATA_DWORD, 0x0, 0x1c}, + {"Expansion", FIELDTYPE_DATA_DWORD, 0x0, 0x20}, + {"SizeX", FIELDTYPE_DATA_DWORD, 0x0, 0x28}, + {"SizeY", FIELDTYPE_DATA_DWORD, 0x0, 0x2c}, + {"AutoMap", FIELDTYPE_DATA_DWORD, 0x0, 0x30}, + {"Scan", FIELDTYPE_DATA_DWORD, 0x0, 0x34}, + {"Pops", FIELDTYPE_DATA_DWORD_2, 0x0, 0x38}, + {"PopPad", FIELDTYPE_DATA_DWORD_2, 0x0, 0x3c}, + {"Files", FIELDTYPE_DATA_DWORD, 0x0, 0x40}, + {"File1", FIELDTYPE_DATA_ASCII, 0x3b, 0x44}, + {"File2", FIELDTYPE_DATA_ASCII, 0x3b, 0x80}, + {"File3", FIELDTYPE_DATA_ASCII, 0x3b, 0xbc}, + {"File4", FIELDTYPE_DATA_ASCII, 0x3b, 0xf8}, + {"File5", FIELDTYPE_DATA_ASCII, 0x3b, 0x134}, + {"File6", FIELDTYPE_DATA_ASCII, 0x3b, 0x170}, + {"Dt1Mask", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1ac}, + {"end", FIELDTYPE_END, 0x0, 0x1b0}, +}; +static BinField lvltypesTable[] = { + {"File 1", FIELDTYPE_DATA_ASCII, 0x3b, 0x0}, + {"File 2", FIELDTYPE_DATA_ASCII, 0x3b, 0x3c}, + {"File 3", FIELDTYPE_DATA_ASCII, 0x3b, 0x78}, + {"File 4", FIELDTYPE_DATA_ASCII, 0x3b, 0xb4}, + {"File 5", FIELDTYPE_DATA_ASCII, 0x3b, 0xf0}, + {"File 6", FIELDTYPE_DATA_ASCII, 0x3b, 0x12c}, + {"File 7", FIELDTYPE_DATA_ASCII, 0x3b, 0x168}, + {"File 8", FIELDTYPE_DATA_ASCII, 0x3b, 0x1a4}, + {"File 9", FIELDTYPE_DATA_ASCII, 0x3b, 0x1e0}, + {"File 10", FIELDTYPE_DATA_ASCII, 0x3b, 0x21c}, + {"File 11", FIELDTYPE_DATA_ASCII, 0x3b, 0x258}, + {"File 12", FIELDTYPE_DATA_ASCII, 0x3b, 0x294}, + {"File 13", FIELDTYPE_DATA_ASCII, 0x3b, 0x2d0}, + {"File 14", FIELDTYPE_DATA_ASCII, 0x3b, 0x30c}, + {"File 15", FIELDTYPE_DATA_ASCII, 0x3b, 0x348}, + {"File 16", FIELDTYPE_DATA_ASCII, 0x3b, 0x384}, + {"File 17", FIELDTYPE_DATA_ASCII, 0x3b, 0x3c0}, + {"File 18", FIELDTYPE_DATA_ASCII, 0x3b, 0x3fc}, + {"File 19", FIELDTYPE_DATA_ASCII, 0x3b, 0x438}, + {"File 20", FIELDTYPE_DATA_ASCII, 0x3b, 0x474}, + {"File 21", FIELDTYPE_DATA_ASCII, 0x3b, 0x4b0}, + {"File 22", FIELDTYPE_DATA_ASCII, 0x3b, 0x4ec}, + {"File 23", FIELDTYPE_DATA_ASCII, 0x3b, 0x528}, + {"File 24", FIELDTYPE_DATA_ASCII, 0x3b, 0x564}, + {"File 25", FIELDTYPE_DATA_ASCII, 0x3b, 0x5a0}, + {"File 26", FIELDTYPE_DATA_ASCII, 0x3b, 0x5dc}, + {"File 27", FIELDTYPE_DATA_ASCII, 0x3b, 0x618}, + {"File 28", FIELDTYPE_DATA_ASCII, 0x3b, 0x654}, + {"File 29", FIELDTYPE_DATA_ASCII, 0x3b, 0x690}, + {"File 30", FIELDTYPE_DATA_ASCII, 0x3b, 0x6cc}, + {"File 31", FIELDTYPE_DATA_ASCII, 0x3b, 0x708}, + {"File 32", FIELDTYPE_DATA_ASCII, 0x3b, 0x744}, + {"Act", FIELDTYPE_DATA_BYTE, 0x0, 0x780}, + {"Expansion", FIELDTYPE_DATA_DWORD, 0x0, 0x784}, + {"end", FIELDTYPE_END, 0x0, 0x788}, +}; +static BinField charstatsTable[] = { + {"wclass", FIELDTYPE_DATA_ASCII, 0x20, 0x00}, + {"class", FIELDTYPE_DATA_ASCII, 0xf, 0x20}, + {"str", FIELDTYPE_DATA_BYTE, 0x0, 0x30}, + {"dex", FIELDTYPE_DATA_BYTE, 0x0, 0x31}, + {"int", FIELDTYPE_DATA_BYTE, 0x0, 0x32}, + {"vit", FIELDTYPE_DATA_BYTE, 0x0, 0x33}, + {"stamina", FIELDTYPE_DATA_BYTE, 0x0, 0x34}, + {"hpadd", FIELDTYPE_DATA_BYTE, 0x0, 0x35}, + {"PercentStr", FIELDTYPE_DATA_BYTE, 0x0, 0x36}, + {"PercentInt", FIELDTYPE_DATA_BYTE, 0x0, 0x37}, + {"PercentDex", FIELDTYPE_DATA_BYTE, 0x0, 0x38}, + {"PercentVit", FIELDTYPE_DATA_BYTE, 0x0, 0x39}, + {"ManaRegen", FIELDTYPE_DATA_BYTE, 0x0, 0x3a}, + {"ToHitFactor", FIELDTYPE_DATA_DWORD_2, 0x0, 0x3c}, + {"WalkVelocity", FIELDTYPE_DATA_BYTE, 0x0, 0x40}, + {"RunVelocity", FIELDTYPE_DATA_BYTE, 0x0, 0x41}, + {"RunDrain", FIELDTYPE_DATA_BYTE, 0x0, 0x42}, + {"LifePerLevel", FIELDTYPE_DATA_BYTE, 0x0, 0x43}, + {"StaminaPerLevel", FIELDTYPE_DATA_BYTE, 0x0, 0x44}, + {"ManaPerLevel", FIELDTYPE_DATA_BYTE, 0x0, 0x45}, + {"LifePerVitality", FIELDTYPE_DATA_BYTE, 0x0, 0x46}, + {"StaminaPerVitality", FIELDTYPE_DATA_BYTE, 0x0, 0x47}, + {"ManaPerMagic", FIELDTYPE_DATA_BYTE, 0x0, 0x48}, + {"BlockFactor", FIELDTYPE_DATA_BYTE, 0x0, 0x49}, + {"basewclass", FIELDTYPE_DATA_RAW, 0x0, 0x4c}, + {"StatPerLevel", FIELDTYPE_DATA_BYTE, 0x0, 0x50}, + {"StrAllSkills", FIELDTYPE_KEY_TO_WORD, 0x0, 0x52}, + {"StrSkillTab1", FIELDTYPE_KEY_TO_WORD, 0x0, 0x54}, + {"StrSkillTab2", FIELDTYPE_KEY_TO_WORD, 0x0, 0x56}, + {"StrSkillTab3", FIELDTYPE_KEY_TO_WORD, 0x0, 0x58}, + {"StrClassOnly", FIELDTYPE_KEY_TO_WORD, 0x0, 0x5a}, + {"item1", FIELDTYPE_DATA_RAW, 0x0, 0x5c}, + {"item1loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x60}, + {"item1count", FIELDTYPE_DATA_BYTE, 0x0, 0x61}, + {"item2", FIELDTYPE_DATA_RAW, 0x0, 0x64}, + {"item2loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x68}, + {"item2count", FIELDTYPE_DATA_BYTE, 0x0, 0x69}, + {"item3", FIELDTYPE_DATA_RAW, 0x0, 0x6c}, + {"item3loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x70}, + {"item3count", FIELDTYPE_DATA_BYTE, 0x0, 0x71}, + {"item4", FIELDTYPE_DATA_RAW, 0x0, 0x74}, + {"item4loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x78}, + {"item4count", FIELDTYPE_DATA_BYTE, 0x0, 0x79}, + {"item5", FIELDTYPE_DATA_RAW, 0x0, 0x7c}, + {"item5loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x80}, + {"item5count", FIELDTYPE_DATA_BYTE, 0x0, 0x81}, + {"item6", FIELDTYPE_DATA_RAW, 0x0, 0x84}, + {"item6loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x88}, + {"item6count", FIELDTYPE_DATA_BYTE, 0x0, 0x89}, + {"item7", FIELDTYPE_DATA_RAW, 0x0, 0x8c}, + {"item7loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x90}, + {"item7count", FIELDTYPE_DATA_BYTE, 0x0, 0x91}, + {"item8", FIELDTYPE_DATA_RAW, 0x0, 0x94}, + {"item8loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x98}, + {"item8count", FIELDTYPE_DATA_BYTE, 0x0, 0x99}, + {"item9", FIELDTYPE_DATA_RAW, 0x0, 0x9c}, + {"item9loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xa0}, + {"item9count", FIELDTYPE_DATA_BYTE, 0x0, 0xa1}, + {"item10", FIELDTYPE_DATA_RAW, 0x0, 0xa4}, + {"item10loc", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xa8}, + {"item10count", FIELDTYPE_DATA_BYTE, 0x0, 0xa9}, + {"StartSkill", FIELDTYPE_NAME_TO_WORD, 0x0, 0xac}, + {"Skill 1", FIELDTYPE_NAME_TO_WORD, 0x0, 0xae}, + {"Skill 2", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb0}, + {"Skill 3", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb2}, + {"Skill 4", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb4}, + {"Skill 5", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb6}, + {"Skill 6", FIELDTYPE_NAME_TO_WORD, 0x0, 0xb8}, + {"Skill 7", FIELDTYPE_NAME_TO_WORD, 0x0, 0xba}, + {"Skill 8", FIELDTYPE_NAME_TO_WORD, 0x0, 0xbc}, + {"Skill 9", FIELDTYPE_NAME_TO_WORD, 0x0, 0xbe}, + {"Skill 10", FIELDTYPE_NAME_TO_WORD, 0x0, 0xc0}, + {"end", FIELDTYPE_END, 0x0, 0xc4}, +}; +static BinField setitemsTable[] = { + {"index", FIELDTYPE_CODE_TO_WORD, 3, 0}, + {"name", FIELDTYPE_DATA_ASCII, 0x1F, 0x2}, + {"version", FIELDTYPE_DATA_WORD, 0, 0x22}, + {"namestr", FIELDTYPE_DATA_WORD, 0, 0x24}, + {"item", FIELDTYPE_DATA_RAW, 0x0, 0x28}, + {"set", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2c}, + {"lvl", FIELDTYPE_DATA_WORD, 0x0, 0x30}, + {"lvl req", FIELDTYPE_DATA_WORD, 0x0, 0x32}, + {"rarity", FIELDTYPE_DATA_DWORD, 0x0, 0x34}, + {"cost mult", FIELDTYPE_DATA_DWORD_2, 0x0, 0x38}, + {"cost add", FIELDTYPE_DATA_DWORD_2, 0x0, 0x3c}, + {"chrtransform", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x40}, + {"invtransform", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x41}, + {"flippyfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x42}, + {"invfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x62}, + {"dropsound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x82}, + {"usesound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x84}, + {"dropsfxframe", FIELDTYPE_DATA_BYTE, 0x0, 0x86}, + {"add func", FIELDTYPE_DATA_BYTE, 0x0, 0x87}, + {"prop1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x88}, + {"par1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x8c}, + {"min1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x90}, + {"max1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x94}, + {"prop2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x98}, + {"par2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x9c}, + {"min2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xa0}, + {"max2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xa4}, + {"prop3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xa8}, + {"par3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xac}, + {"min3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb0}, + {"max3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb4}, + {"prop4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xb8}, + {"par4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xbc}, + {"min4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc0}, + {"max4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc4}, + {"prop5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xc8}, + {"par5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xcc}, + {"min5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd0}, + {"max5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd4}, + {"prop6", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xd8}, + {"par6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xdc}, + {"min6", FIELDTYPE_DATA_DWORD_2, 0x0, 0xe0}, + {"max6", FIELDTYPE_DATA_DWORD_2, 0x0, 0xe4}, + {"prop7", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xe8}, + {"par7", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xec}, + {"min7", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf0}, + {"max7", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf4}, + {"prop8", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xf8}, + {"par8", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xfc}, + {"min8", FIELDTYPE_DATA_DWORD_2, 0x0, 0x100}, + {"max8", FIELDTYPE_DATA_DWORD_2, 0x0, 0x104}, + {"prop9", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x108}, + {"par9", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x10c}, + {"min9", FIELDTYPE_DATA_DWORD_2, 0x0, 0x110}, + {"max9", FIELDTYPE_DATA_DWORD_2, 0x0, 0x114}, + {"aprop1a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x118}, + {"apar1a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x11c}, + {"amin1a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x120}, + {"amax1a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x124}, + {"aprop1b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x128}, + {"apar1b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x12c}, + {"amin1b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x130}, + {"amax1b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x134}, + {"aprop2a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x138}, + {"apar2a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x13c}, + {"amin2a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x140}, + {"amax2a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x144}, + {"aprop2b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x148}, + {"apar2b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x14c}, + {"amin2b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x150}, + {"amax2b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x154}, + {"aprop3a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x158}, + {"apar3a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x15c}, + {"amin3a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x160}, + {"amax3a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x164}, + {"aprop3b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x168}, + {"apar3b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x16c}, + {"amin3b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x170}, + {"amax3b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x174}, + {"aprop4a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x178}, + {"apar4a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x17c}, + {"amin4a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x180}, + {"amax4a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x184}, + {"aprop4b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x188}, + {"apar4b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x18c}, + {"amin4b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x190}, + {"amax4b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x194}, + {"aprop5a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x198}, + {"apar5a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x19c}, + {"amin5a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1a0}, + {"amax5a", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1a4}, + {"aprop5b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x1a8}, + {"apar5b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x1ac}, + {"amin5b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1b0}, + {"amax5b", FIELDTYPE_DATA_DWORD_2, 0x0, 0x1b4}, + {"end", FIELDTYPE_END, 0x0, 0x1b8}, +}; +static BinField uniqueitemsTable[] = { + {"index", FIELDTYPE_DATA_WORD, 0, 0x0}, + {"name", FIELDTYPE_DATA_ASCII, 0x1F, 0x2}, + {"namestr", FIELDTYPE_DATA_WORD, 0, 0x22}, + {"version", FIELDTYPE_DATA_WORD, 0x0, 0x24}, + {"code", FIELDTYPE_DATA_RAW, 0x0, 0x28}, + {"enabled", FIELDTYPE_DATA_BIT, 0x0, 0x2c}, + {"nolimit", FIELDTYPE_DATA_BIT, 0x1, 0x2c}, + {"carry1", FIELDTYPE_DATA_BIT, 0x2, 0x2c}, + {"ladder", FIELDTYPE_DATA_BIT, 0x3, 0x2c}, + {"rarity", FIELDTYPE_DATA_WORD, 0x0, 0x30}, + {"lvl", FIELDTYPE_DATA_WORD, 0x0, 0x34}, + {"lvl req", FIELDTYPE_DATA_WORD, 0x0, 0x36}, + {"chrtransform", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x38}, + {"invtransform", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x39}, + {"flippyfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x3a}, + {"invfile", FIELDTYPE_DATA_ASCII, 0x1f, 0x5a}, + {"cost mult", FIELDTYPE_DATA_DWORD_2, 0x0, 0x7c}, + {"cost add", FIELDTYPE_DATA_DWORD_2, 0x0, 0x80}, + {"dropsound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x84}, + {"usesound", FIELDTYPE_NAME_TO_WORD, 0x0, 0x86}, + {"dropsfxframe", FIELDTYPE_DATA_BYTE, 0x0, 0x88}, + {"prop1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x8c}, + {"par1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x90}, + {"min1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x94}, + {"max1", FIELDTYPE_DATA_DWORD_2, 0x0, 0x98}, + {"prop2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x9c}, + {"par2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa0}, + {"min2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xa4}, + {"max2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xa8}, + {"prop3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xac}, + {"par3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb0}, + {"min3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb4}, + {"max3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb8}, + {"prop4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xbc}, + {"par4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc0}, + {"min4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc4}, + {"max4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc8}, + {"prop5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xcc}, + {"par5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd0}, + {"min5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd4}, + {"max5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd8}, + {"prop6", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xdc}, + {"par6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe0}, + {"min6", FIELDTYPE_DATA_DWORD_2, 0x0, 0xe4}, + {"max6", FIELDTYPE_DATA_DWORD_2, 0x0, 0xe8}, + {"prop7", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xec}, + {"par7", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xf0}, + {"min7", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf4}, + {"max7", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf8}, + {"prop8", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xfc}, + {"par8", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x100}, + {"min8", FIELDTYPE_DATA_DWORD_2, 0x0, 0x104}, + {"max8", FIELDTYPE_DATA_DWORD_2, 0x0, 0x108}, + {"prop9", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x10c}, + {"par9", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x110}, + {"min9", FIELDTYPE_DATA_DWORD_2, 0x0, 0x114}, + {"max9", FIELDTYPE_DATA_DWORD_2, 0x0, 0x118}, + {"prop10", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x11c}, + {"par10", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x120}, + {"min10", FIELDTYPE_DATA_DWORD_2, 0x0, 0x124}, + {"max10", FIELDTYPE_DATA_DWORD_2, 0x0, 0x128}, + {"prop11", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x12c}, + {"par11", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x130}, + {"min11", FIELDTYPE_DATA_DWORD_2, 0x0, 0x134}, + {"max11", FIELDTYPE_DATA_DWORD_2, 0x0, 0x138}, + {"prop12", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x13c}, + {"par12", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x140}, + {"min12", FIELDTYPE_DATA_DWORD_2, 0x0, 0x144}, + {"max12", FIELDTYPE_DATA_DWORD_2, 0x0, 0x148}, + {"end", FIELDTYPE_END, 0x0, 0x14c}, +}; +static BinField setsTable[] = { + {"index", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"name", FIELDTYPE_KEY_TO_WORD, 0x0, 0x2}, + {"version", FIELDTYPE_DATA_WORD, 0x0, 0x4}, + {"pcode2a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x10}, + {"pparam2a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x14}, + {"pmin2a", FIELDTYPE_DATA_DWORD, 0x0, 0x18}, + {"pmax2a", FIELDTYPE_DATA_DWORD, 0x0, 0x1c}, + {"pcode2b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x20}, + {"pparam2b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x24}, + {"pmin2b", FIELDTYPE_DATA_DWORD, 0x0, 0x28}, + {"pmax2b", FIELDTYPE_DATA_DWORD, 0x0, 0x2c}, + {"pcode3a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x30}, + {"pparam3a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x34}, + {"pmin3a", FIELDTYPE_DATA_DWORD, 0x0, 0x38}, + {"pmax3a", FIELDTYPE_DATA_DWORD, 0x0, 0x3c}, + {"pcode3b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x40}, + {"pparam3b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x44}, + {"pmin3b", FIELDTYPE_DATA_DWORD, 0x0, 0x48}, + {"pmax3b", FIELDTYPE_DATA_DWORD, 0x0, 0x4c}, + {"pcode4a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x50}, + {"pparam4a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x54}, + {"pmin4a", FIELDTYPE_DATA_DWORD, 0x0, 0x58}, + {"pmax4a", FIELDTYPE_DATA_DWORD, 0x0, 0x5c}, + {"pcode4b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x60}, + {"pparam4b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x64}, + {"pmin4b", FIELDTYPE_DATA_DWORD, 0x0, 0x68}, + {"pmax4b", FIELDTYPE_DATA_DWORD, 0x0, 0x6c}, + {"pcode5a", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x70}, + {"pparam5a", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x74}, + {"pmin5a", FIELDTYPE_DATA_DWORD, 0x0, 0x78}, + {"pmax5a", FIELDTYPE_DATA_DWORD, 0x0, 0x7c}, + {"pcode5b", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x80}, + {"pparam5b", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x84}, + {"pmin5b", FIELDTYPE_DATA_DWORD, 0x0, 0x88}, + {"pmax5b", FIELDTYPE_DATA_DWORD, 0x0, 0x8c}, + {"fcode1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x90}, + {"fparam1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x94}, + {"fmin1", FIELDTYPE_DATA_DWORD, 0x0, 0x98}, + {"fmax1", FIELDTYPE_DATA_DWORD, 0x0, 0x9c}, + {"fcode2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xa0}, + {"fparam2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa4}, + {"fmin2", FIELDTYPE_DATA_DWORD, 0x0, 0xa8}, + {"fmax2", FIELDTYPE_DATA_DWORD, 0x0, 0xac}, + {"fcode3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xb0}, + {"fparam3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb4}, + {"fmin3", FIELDTYPE_DATA_DWORD, 0x0, 0xb8}, + {"fmax3", FIELDTYPE_DATA_DWORD, 0x0, 0xbc}, + {"fcode4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xc0}, + {"fparam4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc4}, + {"fmin4", FIELDTYPE_DATA_DWORD, 0x0, 0xc8}, + {"fmax4", FIELDTYPE_DATA_DWORD, 0x0, 0xcc}, + {"fcode5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xd0}, + {"fparam5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd4}, + {"fmin5", FIELDTYPE_DATA_DWORD, 0x0, 0xd8}, + {"fmax5", FIELDTYPE_DATA_DWORD, 0x0, 0xdc}, + {"fcode6", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xe0}, + {"fparam6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe4}, + {"fmin6", FIELDTYPE_DATA_DWORD, 0x0, 0xe8}, + {"fmax6", FIELDTYPE_DATA_DWORD, 0x0, 0xec}, + {"fcode7", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xf0}, + {"fparam7", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xf4}, + {"fmin7", FIELDTYPE_DATA_DWORD, 0x0, 0xf8}, + {"fmax7", FIELDTYPE_DATA_DWORD, 0x0, 0xfc}, + {"fcode8", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x100}, + {"fparam8", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x104}, + {"fmin8", FIELDTYPE_DATA_DWORD, 0x0, 0x108}, + {"fmax8", FIELDTYPE_DATA_DWORD, 0x0, 0x10c}, + {"end", FIELDTYPE_END, 0x0, 0x128}, +}; +static BinField itemtypesTable[] = { + {"code", FIELDTYPE_ASCII_TO_CODE, 0x0, 0x0}, + {"equiv1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x4}, + {"equiv2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x6}, + {"repair", FIELDTYPE_DATA_BYTE, 0x0, 0x8}, + {"body", FIELDTYPE_DATA_BYTE, 0x0, 0x9}, + {"bodyloc1", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xa}, + {"bodyloc2", FIELDTYPE_CODE_TO_BYTE, 0x0, 0xb}, + {"shoots", FIELDTYPE_CODE_TO_WORD, 0x0, 0xc}, + {"quiver", FIELDTYPE_CODE_TO_WORD, 0x0, 0xe}, + {"throwable", FIELDTYPE_DATA_BYTE, 0x0, 0x10}, + {"reload", FIELDTYPE_DATA_BYTE, 0x0, 0x11}, + {"reequip", FIELDTYPE_DATA_BYTE, 0x0, 0x12}, + {"autostack", FIELDTYPE_DATA_BYTE, 0x0, 0x13}, + {"magic", FIELDTYPE_DATA_BYTE, 0x0, 0x14}, + {"rare", FIELDTYPE_DATA_BYTE, 0x0, 0x15}, + {"normal", FIELDTYPE_DATA_BYTE, 0x0, 0x16}, + {"charm", FIELDTYPE_DATA_BYTE, 0x0, 0x17}, + {"gem", FIELDTYPE_DATA_BYTE, 0x0, 0x18}, + {"beltable", FIELDTYPE_DATA_BYTE, 0x0, 0x19}, + {"maxsock1", FIELDTYPE_DATA_BYTE, 0x0, 0x1a}, + {"maxsock25", FIELDTYPE_DATA_BYTE, 0x0, 0x1b}, + {"maxsock40", FIELDTYPE_DATA_BYTE, 0x0, 0x1c}, + {"treasureclass", FIELDTYPE_DATA_BYTE, 0x0, 0x1d}, + {"rarity", FIELDTYPE_DATA_BYTE, 0x0, 0x1e}, + {"staffmods", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x1f}, + {"costformula", FIELDTYPE_DATA_BYTE, 0x0, 0x20}, + {"class", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x21}, + {"storepage", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x22}, + {"varinvgfx", FIELDTYPE_DATA_BYTE, 0x0, 0x23}, + {"invgfx1", FIELDTYPE_DATA_ASCII, 0x1f, 0x24}, + {"invgfx2", FIELDTYPE_DATA_ASCII, 0x1f, 0x44}, + {"invgfx3", FIELDTYPE_DATA_ASCII, 0x1f, 0x64}, + {"invgfx4", FIELDTYPE_DATA_ASCII, 0x1f, 0x84}, + {"invgfx5", FIELDTYPE_DATA_ASCII, 0x1f, 0xa4}, + {"invgfx6", FIELDTYPE_DATA_ASCII, 0x1f, 0xc4}, + {"end", FIELDTYPE_END, 0x0, 0xe4}, +}; +static BinField runesTable[] = { + {"name", FIELDTYPE_DATA_ASCII, 0x3f, 0x0}, + {"rune name", FIELDTYPE_DATA_ASCII, 0x3f, 0x40}, + {"complete", FIELDTYPE_DATA_BYTE, 0x0, 0x80}, + {"server", FIELDTYPE_DATA_BYTE, 0x0, 0x81}, + {"itype1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x86}, + {"itype2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x88}, + {"itype3", FIELDTYPE_CODE_TO_WORD, 0x0, 0x8a}, + {"itype4", FIELDTYPE_CODE_TO_WORD, 0x0, 0x8c}, + {"itype5", FIELDTYPE_CODE_TO_WORD, 0x0, 0x8e}, + {"itype6", FIELDTYPE_CODE_TO_WORD, 0x0, 0x90}, + {"etype1", FIELDTYPE_CODE_TO_WORD, 0x0, 0x92}, + {"etype2", FIELDTYPE_CODE_TO_WORD, 0x0, 0x94}, + {"etype3", FIELDTYPE_CODE_TO_WORD, 0x0, 0x96}, + {"rune1", FIELDTYPE_UNKNOWN_11, 0x0, 0x98}, + {"rune2", FIELDTYPE_UNKNOWN_11, 0x0, 0x9c}, + {"rune3", FIELDTYPE_UNKNOWN_11, 0x0, 0xa0}, + {"rune4", FIELDTYPE_UNKNOWN_11, 0x0, 0xa4}, + {"rune5", FIELDTYPE_UNKNOWN_11, 0x0, 0xa8}, + {"rune6", FIELDTYPE_UNKNOWN_11, 0x0, 0xac}, + {"t1code1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xb0}, + {"t1param1", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb4}, + {"t1min1", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb8}, + {"t1max1", FIELDTYPE_DATA_DWORD_2, 0x0, 0xbc}, + {"t1code2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xc0}, + {"t1param2", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xc4}, + {"t1min2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xc8}, + {"t1max2", FIELDTYPE_DATA_DWORD_2, 0x0, 0xcc}, + {"t1code3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xd0}, + {"t1param3", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xd4}, + {"t1min3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xd8}, + {"t1max3", FIELDTYPE_DATA_DWORD_2, 0x0, 0xdc}, + {"t1code4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xe0}, + {"t1param4", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xe4}, + {"t1min4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xe8}, + {"t1max4", FIELDTYPE_DATA_DWORD_2, 0x0, 0xec}, + {"t1code5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xf0}, + {"t1param5", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xf4}, + {"t1min5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xf8}, + {"t1max5", FIELDTYPE_DATA_DWORD_2, 0x0, 0xfc}, + {"t1code6", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x100}, + {"t1param6", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x104}, + {"t1min6", FIELDTYPE_DATA_DWORD_2, 0x0, 0x108}, + {"t1max6", FIELDTYPE_DATA_DWORD_2, 0x0, 0x10c}, + {"t1code7", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x110}, + {"t1param7", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x114}, + {"t1min7", FIELDTYPE_DATA_DWORD_2, 0x0, 0x118}, + {"t1max7", FIELDTYPE_DATA_DWORD_2, 0x0, 0x11c}, + {"end", FIELDTYPE_END, 0x0, 0x120}, +}; +static BinField cubemainTable[] = { + {"enabled", FIELDTYPE_DATA_BYTE, 0x0, 0x0}, + {"ladder", FIELDTYPE_DATA_BYTE, 0x0, 0x1}, + {"min diff", FIELDTYPE_DATA_BYTE, 0x0, 0x2}, + {"class", FIELDTYPE_CODE_TO_BYTE, 0x0, 0x3}, + {"op", FIELDTYPE_DATA_BYTE, 0x0, 0x4}, + {"param", FIELDTYPE_DATA_DWORD, 0x0, 0x8}, + {"value", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"numinputs", FIELDTYPE_DATA_BYTE, 0x0, 0x10}, + {"version", FIELDTYPE_DATA_WORD, 0x0, 0x12}, + {"input item 1 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x14}, + {"input item 1 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x14}, + {"input item 1 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x14}, + {"input item 1 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x14}, + {"input item 1 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x14}, + {"input item 1 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x14}, + {"input item 1 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x14}, + {"input item 1 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x14}, + {"input 1 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x15}, + {"input 1 item", FIELDTYPE_DATA_BYTE, 0x0, 0x16}, + {"input 1 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x18}, + {"input 1 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x1a}, + {"input 1 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x1b}, + {"input item 2 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x1c}, + {"input item 2 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x1c}, + {"input item 2 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x1c}, + {"input item 2 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x1c}, + {"input item 2 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x1c}, + {"input item 2 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x1c}, + {"input item 2 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x1c}, + {"input item 2 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x1c}, + {"input 2 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x1d}, + {"input 2 item", FIELDTYPE_DATA_BYTE, 0x0, 0x1e}, + {"input 2 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x20}, + {"input 2 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x22}, + {"input 2 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x23}, + {"input item 3 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x24}, + {"input item 3 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x24}, + {"input item 3 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x24}, + {"input item 3 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x24}, + {"input item 3 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x24}, + {"input item 3 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x24}, + {"input item 3 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x24}, + {"input item 3 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x24}, + {"input 3 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x25}, + {"input 3 item", FIELDTYPE_DATA_BYTE, 0x0, 0x26}, + {"input 3 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x28}, + {"input 3 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x2a}, + {"input 3 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x2b}, + {"input item 4 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x2c}, + {"input item 4 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x2c}, + {"input item 4 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x2c}, + {"input item 4 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x2c}, + {"input item 4 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x2c}, + {"input item 4 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x2c}, + {"input item 4 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x2c}, + {"input item 4 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x2c}, + {"input 4 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x2d}, + {"input 4 item", FIELDTYPE_DATA_BYTE, 0x0, 0x2e}, + {"input 4 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x30}, + {"input 4 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x32}, + {"input 4 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x33}, + {"input item 5 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x34}, + {"input item 5 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x34}, + {"input item 5 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x34}, + {"input item 5 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x34}, + {"input item 5 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x34}, + {"input item 5 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x34}, + {"input item 5 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x34}, + {"input item 5 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x34}, + {"input 5 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x35}, + {"input 5 item", FIELDTYPE_DATA_BYTE, 0x0, 0x36}, + {"input 5 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x38}, + {"input 5 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x3a}, + {"input 5 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x3b}, + {"input item 6 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x3c}, + {"input item 6 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x3c}, + {"input item 6 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x3c}, + {"input item 6 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x3c}, + {"input item 6 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x3c}, + {"input item 6 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x3c}, + {"input item 6 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x3c}, + {"input item 6 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x3c}, + {"input 6 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x3d}, + {"input 6 item", FIELDTYPE_DATA_BYTE, 0x0, 0x3e}, + {"input 6 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x40}, + {"input 6 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x42}, + {"input 6 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x43}, + {"input item 7 item code flag", FIELDTYPE_DATA_BIT, 0x0, 0x44}, + {"input item 7 item class flag", FIELDTYPE_DATA_BIT, 0x1, 0x44}, + {"input item 7 any flag", FIELDTYPE_DATA_BIT, 0x2, 0x44}, + {"input item 7 socket flag", FIELDTYPE_DATA_BIT, 0x3, 0x44}, + {"input item 7 no ethereal flag", FIELDTYPE_DATA_BIT, 0x4, 0x44}, + {"input item 7 repair flag", FIELDTYPE_DATA_BIT, 0x5, 0x44}, + {"input item 7 unique item name flag", FIELDTYPE_DATA_BIT, 0x6, 0x44}, + {"input item 7 upg flag", FIELDTYPE_DATA_BIT, 0x7, 0x44}, + {"input 7 item type", FIELDTYPE_DATA_BYTE, 0x0, 0x45}, + {"input 7 item", FIELDTYPE_DATA_BYTE, 0x0, 0x46}, + {"input 7 item id", FIELDTYPE_DATA_BYTE, 0x0, 0x48}, + {"input 7 quality", FIELDTYPE_DATA_BYTE, 0x0, 0x4a}, + {"input 7 quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x4b}, + {"output item flags", FIELDTYPE_DATA_BYTE, 0x0, 0x4c}, + {"output item type", FIELDTYPE_DATA_BYTE, 0x0, 0x4d}, + {"output item", FIELDTYPE_DATA_BYTE, 0x0, 0x4e}, + {"output item id", FIELDTYPE_DATA_BYTE, 0x0, 0x50}, + {"output item quality", FIELDTYPE_DATA_BYTE, 0x0, 0x52}, + {"output item quantity", FIELDTYPE_DATA_BYTE, 0x0, 0x53}, + {"output type", FIELDTYPE_DATA_BYTE, 0x0, 0x54}, + {"lvl", FIELDTYPE_DATA_BYTE, 0x0, 0x55}, + {"plvl", FIELDTYPE_DATA_BYTE, 0x0, 0x56}, + {"ilvl", FIELDTYPE_DATA_BYTE, 0x0, 0x57}, + {"output item prefix id", FIELDTYPE_DATA_BYTE, 0x0, 0x58}, + {"output item unknown", FIELDTYPE_DATA_BYTE, 0x0, 0x5a}, + {"output item suffix id", FIELDTYPE_DATA_BYTE, 0x0, 0x5e}, + {"unknown field", FIELDTYPE_DATA_BYTE, 0x0, 0x60}, + {"mod 1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x64}, + {"mod 1 param", FIELDTYPE_DATA_WORD, 0x0, 0x68}, + {"mod 1 min", FIELDTYPE_DATA_WORD, 0x0, 0x6a}, + {"mod 1 max", FIELDTYPE_DATA_WORD, 0x0, 0x6c}, + {"mod 1 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x6e}, + {"mod 2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x70}, + {"mod 2 param", FIELDTYPE_DATA_WORD, 0x0, 0x74}, + {"mod 2 min", FIELDTYPE_DATA_WORD, 0x0, 0x76}, + {"mod 2 max", FIELDTYPE_DATA_WORD, 0x0, 0x78}, + {"mod 2 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x7a}, + {"mod 3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x7c}, + {"mod 3 param", FIELDTYPE_DATA_WORD, 0x0, 0x80}, + {"mod 3 min", FIELDTYPE_DATA_WORD, 0x0, 0x82}, + {"mod 3 max", FIELDTYPE_DATA_WORD, 0x0, 0x84}, + {"mod 3 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x86}, + {"mod 4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x88}, + {"mod 4 param", FIELDTYPE_DATA_WORD, 0x0, 0x8c}, + {"mod 4 min", FIELDTYPE_DATA_WORD, 0x0, 0x8e}, + {"mod 4 max", FIELDTYPE_DATA_WORD, 0x0, 0x90}, + {"mod 4 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x92}, + {"mod 5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x94}, + {"mod 5 param", FIELDTYPE_DATA_WORD, 0x0, 0x98}, + {"mod 5 min", FIELDTYPE_DATA_WORD, 0x0, 0x9a}, + {"mod 5 max", FIELDTYPE_DATA_WORD, 0x0, 0x9c}, + {"mod 5 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x9e}, + {"b lvl", FIELDTYPE_DATA_BYTE, 0x0, 0xa9}, + {"b plvl", FIELDTYPE_DATA_BYTE, 0x0, 0xaa}, + {"b ilvl", FIELDTYPE_DATA_BYTE, 0x0, 0xab}, + {"b mod 1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xb8}, + {"b mod 1 param", FIELDTYPE_DATA_WORD, 0x0, 0xbc}, + {"b mod 1 min", FIELDTYPE_DATA_WORD, 0x0, 0xbe}, + {"b mod 1 max", FIELDTYPE_DATA_WORD, 0x0, 0xc0}, + {"b mod 1 chance", FIELDTYPE_DATA_BYTE, 0x0, 0xc2}, + {"b mod 2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xc4}, + {"b mod 2 param", FIELDTYPE_DATA_WORD, 0x0, 0xc8}, + {"b mod 2 min", FIELDTYPE_DATA_WORD, 0x0, 0xca}, + {"b mod 2 max", FIELDTYPE_DATA_WORD, 0x0, 0xcc}, + {"b mod 2 chance", FIELDTYPE_DATA_BYTE, 0x0, 0xce}, + {"b mod 3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xd0}, + {"b mod 3 param", FIELDTYPE_DATA_WORD, 0x0, 0xd4}, + {"b mod 3 min", FIELDTYPE_DATA_WORD, 0x0, 0xd6}, + {"b mod 3 max", FIELDTYPE_DATA_WORD, 0x0, 0xd8}, + {"b mod 3 chance", FIELDTYPE_DATA_BYTE, 0x0, 0xda}, + {"b mod 4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xdc}, + {"b mod 4 param", FIELDTYPE_DATA_WORD, 0x0, 0xe0}, + {"b mod 4 min", FIELDTYPE_DATA_WORD, 0x0, 0xe2}, + {"b mod 4 max", FIELDTYPE_DATA_WORD, 0x0, 0xe4}, + {"b mod 4 chance", FIELDTYPE_DATA_BYTE, 0x0, 0xe6}, + {"b mod 5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xe8}, + {"b mod 5 param", FIELDTYPE_DATA_WORD, 0x0, 0xec}, + {"b mod 5 min", FIELDTYPE_DATA_WORD, 0x0, 0xee}, + {"b mod 5 max", FIELDTYPE_DATA_WORD, 0x0, 0xf0}, + {"b mod 5 chance", FIELDTYPE_DATA_BYTE, 0x0, 0xf2}, + {"c lvl", FIELDTYPE_DATA_BYTE, 0x0, 0xfd}, + {"c plvl", FIELDTYPE_DATA_BYTE, 0x0, 0xfe}, + {"c ilvl", FIELDTYPE_DATA_BYTE, 0x0, 0xff}, + {"c mod 1", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x10c}, + {"c mod 1 param", FIELDTYPE_DATA_WORD, 0x0, 0x110}, + {"c mod 1 min", FIELDTYPE_DATA_WORD, 0x0, 0x112}, + {"c mod 1 max", FIELDTYPE_DATA_WORD, 0x0, 0x114}, + {"c mod 1 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x116}, + {"c mod 2", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x118}, + {"c mod 2 param", FIELDTYPE_DATA_WORD, 0x0, 0x11c}, + {"c mod 2 min", FIELDTYPE_DATA_WORD, 0x0, 0x11e}, + {"c mod 2 max", FIELDTYPE_DATA_WORD, 0x0, 0x120}, + {"c mod 2 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x122}, + {"c mod 3", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x124}, + {"c mod 3 param", FIELDTYPE_DATA_WORD, 0x0, 0x128}, + {"c mod 3 min", FIELDTYPE_DATA_WORD, 0x0, 0x12a}, + {"c mod 3 max", FIELDTYPE_DATA_WORD, 0x0, 0x12c}, + {"c mod 3 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x12e}, + {"c mod 4", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x130}, + {"c mod 4 param", FIELDTYPE_DATA_WORD, 0x0, 0x134}, + {"c mod 4 min", FIELDTYPE_DATA_WORD, 0x0, 0x136}, + {"c mod 4 max", FIELDTYPE_DATA_WORD, 0x0, 0x138}, + {"c mod 4 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x13a}, + {"c mod 5", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x13c}, + {"c mod 5 param", FIELDTYPE_DATA_WORD, 0x0, 0x140}, + {"c mod 5 min", FIELDTYPE_DATA_WORD, 0x0, 0x142}, + {"c mod 5 max", FIELDTYPE_DATA_WORD, 0x0, 0x144}, + {"c mod 5 chance", FIELDTYPE_DATA_BYTE, 0x0, 0x146}, + {"end", FIELDTYPE_END, 0x0, 0x148}, +}; +static BinField gemsTable[] = { + {"name", FIELDTYPE_DATA_ASCII, 0x1f, 0x0}, + {"letter", FIELDTYPE_DATA_ASCII, 0x5, 0x20}, + {"code", FIELDTYPE_UNKNOWN_11, 0x0, 0x28}, + {"nummods", FIELDTYPE_DATA_BYTE, 0x0, 0x2e}, + {"transform", FIELDTYPE_DATA_BYTE, 0x0, 0x2f}, + {"weaponmod1code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x30}, + {"weaponmod1param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x34}, + {"weaponmod1min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x38}, + {"weaponmod1max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x3c}, + {"weaponmod2code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x40}, + {"weaponmod2param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x44}, + {"weaponmod2min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x48}, + {"weaponmod2max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x4c}, + {"weaponmod3code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x50}, + {"weaponmod3param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x54}, + {"weaponmod3min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x58}, + {"weaponmod3max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x5c}, + {"helmmod1code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x60}, + {"helmmod1param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x64}, + {"helmmod1min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x68}, + {"helmmod1max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x6c}, + {"helmmod2code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x70}, + {"helmmod2param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x74}, + {"helmmod2min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x78}, + {"helmmod2max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x7c}, + {"helmmod3code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x80}, + {"helmmod3param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x84}, + {"helmmod3min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x88}, + {"helmmod3max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x8c}, + {"shieldmod1code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x90}, + {"shieldmod1param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0x94}, + {"shieldmod1min", FIELDTYPE_DATA_DWORD_2, 0x0, 0x98}, + {"shieldmod1max", FIELDTYPE_DATA_DWORD_2, 0x0, 0x9c}, + {"shieldmod2code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xa0}, + {"shieldmod2param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xa4}, + {"shieldmod2min", FIELDTYPE_DATA_DWORD_2, 0x0, 0xa8}, + {"shieldmod2max", FIELDTYPE_DATA_DWORD_2, 0x0, 0xac}, + {"shieldmod3code", FIELDTYPE_NAME_TO_DWORD, 0x0, 0xb0}, + {"shieldmod3param", FIELDTYPE_CALC_TO_DWORD, 0x0, 0xb4}, + {"shieldmod3min", FIELDTYPE_DATA_DWORD_2, 0x0, 0xb8}, + {"shieldmod3max", FIELDTYPE_DATA_DWORD_2, 0x0, 0xbc}, + {"end", FIELDTYPE_END, 0x0, 0xc0}, +}; +static BinField experienceTable[] = { + {"Amazon", FIELDTYPE_DATA_DWORD, 0x0, 0x0}, + {"Sorceress", FIELDTYPE_DATA_DWORD, 0x0, 0x4}, + {"Necromancer", FIELDTYPE_DATA_DWORD, 0x0, 0x8}, + {"Paladin", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"Barbarian", FIELDTYPE_DATA_DWORD, 0x0, 0x10}, + {"Druid", FIELDTYPE_DATA_DWORD, 0x0, 0x14}, + {"Assassin", FIELDTYPE_DATA_DWORD, 0x0, 0x18}, + {"end", FIELDTYPE_END, 0x0, 0x20}, +}; +static BinField pettypeTable[] = { + {"pet type", FIELDTYPE_NAME_TO_INDEX_2, 0x0, 0x0}, + {"warp", FIELDTYPE_DATA_BIT, 0x0, 0x4}, + {"range", FIELDTYPE_DATA_BIT, 0x1, 0x4}, + {"partysend", FIELDTYPE_DATA_BIT, 0x2, 0x4}, + {"unsummon", FIELDTYPE_DATA_BIT, 0x3, 0x4}, + {"automap", FIELDTYPE_DATA_BIT, 0x4, 0x4}, + {"drawhp", FIELDTYPE_DATA_BIT, 0x5, 0x4}, + {"group", FIELDTYPE_DATA_WORD, 0x0, 0x8}, + {"basemax", FIELDTYPE_DATA_WORD, 0x0, 0xa}, + {"name", FIELDTYPE_KEY_TO_WORD, 0x0, 0xc}, + {"icontype", FIELDTYPE_DATA_BYTE, 0x0, 0xe}, + {"baseicon", FIELDTYPE_DATA_ASCII, 0x20, 0xf}, + {"micon1", FIELDTYPE_DATA_ASCII, 0x20, 0x2f}, + {"micon2", FIELDTYPE_DATA_ASCII, 0x20, 0x4f}, + {"micon3", FIELDTYPE_DATA_ASCII, 0x20, 0x6f}, + {"micon4", FIELDTYPE_DATA_ASCII, 0x20, 0x8f}, + {"mclass1", FIELDTYPE_DATA_WORD, 0x0, 0xb2}, + {"mclass2", FIELDTYPE_DATA_WORD, 0x0, 0xb4}, + {"mclass3", FIELDTYPE_DATA_WORD, 0x0, 0xb6}, + {"mclass4", FIELDTYPE_DATA_WORD, 0x0, 0xb8}, + {"end", FIELDTYPE_END, 0x0, 0xe0}, +}; +static BinField superuniquesTable[] = { + {"Superunique", FIELDTYPE_NAME_TO_INDEX, 0x0, 0x0}, + {"Name", FIELDTYPE_KEY_TO_WORD, 0x0, 0x2}, + {"Class", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x4}, + {"hcIdx", FIELDTYPE_DATA_DWORD, 0x0, 0x8}, + {"Mod1", FIELDTYPE_DATA_DWORD, 0x0, 0xc}, + {"Mod2", FIELDTYPE_DATA_DWORD, 0x0, 0x10}, + {"Mod3", FIELDTYPE_DATA_DWORD, 0x0, 0x14}, + {"MonSound", FIELDTYPE_NAME_TO_DWORD, 0x0, 0x18}, + {"MinGrp", FIELDTYPE_DATA_DWORD, 0x0, 0x1c}, + {"MaxGrp", FIELDTYPE_DATA_DWORD, 0x0, 0x20}, + {"AutoPos", FIELDTYPE_DATA_BYTE, 0x0, 0x24}, + {"EClass", FIELDTYPE_DATA_BYTE, 0x0, 0x25}, + {"Stacks", FIELDTYPE_DATA_BYTE, 0x0, 0x26}, + {"Replaceable", FIELDTYPE_DATA_BYTE, 0x0, 0x27}, + {"Utrans", FIELDTYPE_DATA_BYTE, 0x0, 0x28}, + {"Utrans(N)", FIELDTYPE_DATA_BYTE, 0x0, 0x29}, + {"Utrans(H)", FIELDTYPE_DATA_BYTE, 0x0, 0x2a}, + {"TC", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2c}, + {"TC(N)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x2e}, + {"TC(H)", FIELDTYPE_NAME_TO_WORD, 0x0, 0x30}, + {"end", FIELDTYPE_END, 0x0, 0x34}, +}; diff --git a/Matrix.h b/Matrix.h new file mode 100644 index 00000000..57467ab2 --- /dev/null +++ b/Matrix.h @@ -0,0 +1,320 @@ +//////////////////////////////////////////////////////////////////////////// +// CMatrix +// +// Two dimensional array template class. +// +// Abin (abinn32@yahoo.com) +//////////////////////////////////////////////////////////////////////////// + +#ifndef __MATRIX_H__ +#define __MATRIX_H__ + +#define USE_MULTI_THREAD // uncomment this line if used in multi-thread application + +#ifdef USE_MULTI_THREAD +#include "SyncObj.h" +#endif // USE_MULTI_THREAD + +////////////////////////////////////////////////////////////////////// +// Necessary Definitions for Non-MFC applications +////////////////////////////////////////////////////////////////////// +#ifndef __AFXWIN_H__ // If non-MFC ... +#include +#include +#include +#ifndef ASSERT +#define ASSERT(x) assert(x) +#endif +#endif // __AFXWIN_H__ + +template +class CMatrix +#ifdef USE_MULTI_THREAD +: public CSyncObj +#endif // USE_MULTI_THREAD +{ +public: + + ///////////////////////////////////////////////////////////// + // Constructor & Destructor + ///////////////////////////////////////////////////////////// + CMatrix(); + virtual ~CMatrix(); + + ///////////////////////////////////////////////////////////// + // Creation & Deletion + ///////////////////////////////////////////////////////////// + BOOL Create(int cx, int cy); + BOOL Create(int cx, int cy, ARG_TYPE initValue); + void Destroy(); + + ///////////////////////////////////////////////////////////// + // Attributes & Operations + ///////////////////////////////////////////////////////////// + BOOL IsCreated() const; + BOOL IsValidIndex(int x, int y) const; + const TYPE& GetAt(int x, int y) const; + TYPE& ElementAt(int x, int y); + BOOL SetAt(int x, int y, ARG_TYPE data); + TYPE** GetData(); + const TYPE** GetData() const; + int GetCX() const; + int GetCY() const; + BOOL ImportData(const TYPE** ppSrc, int cx, int cy); + BOOL ImportData(const CMatrix& rSrc); + SIZE ExportData(TYPE** ppBuffer, int cx, int cy) const; + BOOL ExportData(CMatrix& rMatrix) const; + + ///////////////////////////////////////////////////////////// + // Operator Overloads + ///////////////////////////////////////////////////////////// + TYPE* operator[] (int nIndex); + const TYPE* operator[] (int nIndex) const; + +protected: + + ///////////////////////////////////////////////////////////// + // Member Data + ///////////////////////////////////////////////////////////// + TYPE** m_ppData; // The matrix data array + int m_cx; // Matrix size x + int m_cy; // Matrix size y +}; + +template +CMatrix::CMatrix() +{ + m_ppData = NULL; + m_cx = 0; + m_cy = 0; +} + +template +CMatrix::~CMatrix() +{ + Destroy(); +} + +template +BOOL CMatrix::Create(int cx, int cy) +{ + Destroy(); + + if (cx <= 0 || cy <= 0) + return FALSE; + m_cx = cx; + m_cy = cy; + + m_ppData = new TYPE*[m_cx]; + if (m_ppData == NULL) + return FALSE; + + ::memset(m_ppData, 0, m_cx * sizeof(TYPE*)); + for (int i = 0; i < m_cx; i++) + { + m_ppData[i] = new TYPE[m_cy]; + if (m_ppData[i] == NULL) + { + Destroy(); + return FALSE; + } + } + + return TRUE; +} + +template +BOOL CMatrix::Create(int cx, int cy, ARG_TYPE initValue) +{ + if (!Create(cx, cy)) + return FALSE; + + for (int i = 0; i < m_cx; i++) + { + for (int j = 0; j < m_cy; j++) + m_ppData[i][j] = initValue; + } + + return TRUE; +} + +template +void CMatrix::Destroy() +{ + if (m_ppData) + { + for (int i = 0; i < m_cx; i++) + { + if (m_ppData[i]) + { + delete [] m_ppData[i]; + m_ppData[i] = NULL; + } + } + + delete [] m_ppData; + m_ppData = NULL; + } + + m_cx = 0; + m_cy = 0; +} + +template +BOOL CMatrix::IsValidIndex(int x, int y) const +{ + return m_ppData != NULL && x >= 0 && x < m_cx && y >= 0 && y < m_cy; +} + +template +const TYPE& CMatrix::GetAt(int x, int y) const +{ + ASSERT(IsValidIndex(x, y)); + return m_ppData[x][y]; +} + +template +TYPE& CMatrix::ElementAt(int x, int y) +{ + ASSERT(IsValidIndex(x, y)); + return m_ppData[x][y]; +} + +template +BOOL CMatrix::SetAt(int x, int y, ARG_TYPE data) +{ + if (!IsValidIndex(x, y)) + return FALSE; + + m_ppData[x][y] = data; + return TRUE; +} + +template +TYPE** CMatrix::GetData() +{ + return m_ppData; +} + +template +const TYPE** CMatrix::GetData() const +{ + return (const TYPE**)m_ppData; +} + +template +TYPE* CMatrix::operator[] (int nIndex) +{ + if (nIndex < 0 || nIndex >= m_cx) + return NULL; + + return m_ppData[nIndex]; +} + +template +const TYPE* CMatrix::operator[] (int nIndex) const +{ + if (nIndex < 0 || nIndex >= m_cx) + return NULL; + + return (const TYPE*)m_ppData[nIndex]; +} + +template +int CMatrix::GetCX() const +{ + return m_cx; +} + +template +int CMatrix::GetCY() const +{ + return m_cy; +} + +template +BOOL CMatrix::IsCreated() const +{ + return m_ppData != NULL; +} + +template +SIZE CMatrix::ExportData(TYPE** ppBuffer, int cx, int cy) const +{ + SIZE cz = { 0 }; + + if (ppBuffer == m_ppData) + { + cz.cx = m_cx; + cz.cy = m_cy; + return cz; + } + + if (ppBuffer == NULL || cx <= 0 || cy <= 0 || !IsCreated()) + return cz; + + cz.cx = min(cx, m_cx); + cz.cy = min(cy, m_cy); + + for (int i = 0; i < cz.cx; i++) + { + for (int j = 0; j < cz.cy; j++) + ppBuffer[i][j] = m_ppData[i][j]; + } + + return cz; +} + +template +BOOL CMatrix::ExportData(CMatrix& rMatrix) const +{ + if (&rMatrix == this) + return IsCreated(); + + if (!IsCreated()) + return FALSE; + + if (rMatrix.GetCX() != m_cx || rMatrix.GetCY() != m_cy) + { + if (!rMatrix.Create(m_cx, m_cy)) + return FALSE; + } + + for (int i = 0; i < m_cx; i++) + { + for (int j = 0; j < m_cy; j++) + rMatrix.m_ppData[i][j] = m_ppData[i][j]; + } + + return TRUE; +} + +template +BOOL CMatrix::ImportData(const TYPE** ppSrc, int cx, int cy) +{ + if (ppSrc == m_ppData) + return IsCreated(); + + Destroy(); + if (ppSrc == NULL || cx <= 0 || cy <= 0) + return FALSE; + + if (!Create(cx, cy)) + return FALSE; + + for (int i = 0; i < m_cx; i++) + { + for (int j = 0; j < m_cy; j++) + m_ppData[i][j] = ppSrc[i][j]; + } + + return TRUE; +} + +template +BOOL CMatrix::ImportData(const CMatrix& rSrc) +{ + return rSrc.ExportData(*this); +} + +#endif // __MATRIX_H__ \ No newline at end of file diff --git a/Offset.cpp b/Offset.cpp new file mode 100644 index 00000000..26f1ddb4 --- /dev/null +++ b/Offset.cpp @@ -0,0 +1,124 @@ +#define _DEFINE_VARS +#include "D2Ptrs.h" +#include "Patch.h" + +#ifndef ArraySize +#define ArraySize(x) (sizeof((x)) / sizeof((x)[0])) +#endif + +void DefineOffsets() +{ + DWORD *p = (DWORD *)&_D2PTRS_START; + do { + *p = GetDllOffset(*p); + } while(++p <= (DWORD *)&_D2PTRS_END); +} + +DWORD GetDllOffset(char *DllName, int Offset) +{ + HMODULE hMod = GetModuleHandle(DllName); + + if(!hMod) + hMod = LoadLibrary(DllName); + + if(!hMod) + return 0; + + if(Offset < 0) + return (DWORD)GetProcAddress(hMod, (LPCSTR)(-Offset)); + + return ((DWORD)hMod)+Offset; +} + +DWORD GetDllOffset(int num) +{ + static char *dlls[] = {"D2Client.DLL", "D2Common.DLL", "D2Gfx.DLL", "D2Lang.DLL", + "D2Win.DLL", "D2Net.DLL", "D2Game.DLL", "D2Launch.DLL", "Fog.DLL", "BNClient.DLL", + "Storm.DLL", "D2Cmp.DLL", "D2Multi.DLL"}; + if((num&0xff) > 12) + return 0; + return GetDllOffset(dlls[num&0xff], num>>8); +} + +void InstallPatches() +{ + + for(int x = 0; x < ArraySize(Patches); x++) + { + Patches[x].bOldCode = new BYTE[Patches[x].dwLen]; + ::ReadProcessMemory(GetCurrentProcess(), (void*)Patches[x].dwAddr, Patches[x].bOldCode, Patches[x].dwLen, NULL); + Patches[x].pFunc(Patches[x].dwAddr, Patches[x].dwFunc, Patches[x].dwLen); + } + +} + +void RemovePatches() +{ + + for(int x = 0; x < ArraySize(Patches); x++) + { + WriteBytes((void*)Patches[x].dwAddr, Patches[x].bOldCode, Patches[x].dwLen); + delete[] Patches[x].bOldCode; + } + +} + +BOOL WriteBytes(void *pAddr, void *pData, DWORD dwLen) +{ + DWORD dwOld; + + if(!VirtualProtect(pAddr, dwLen, PAGE_READWRITE, &dwOld)) + return FALSE; + + ::memcpy(pAddr, pData, dwLen); + return VirtualProtect(pAddr, dwLen, dwOld, &dwOld); +} + +void FillBytes(void *pAddr, BYTE bFill, DWORD dwLen) +{ + BYTE *bCode = new BYTE[dwLen]; + ::memset(bCode, bFill, dwLen); + + WriteBytes(pAddr, bCode, dwLen); + + delete[] bCode; +} + +void InterceptLocalCode(BYTE bInst, DWORD pAddr, DWORD pFunc, DWORD dwLen) +{ + BYTE *bCode = new BYTE[dwLen]; + ::memset(bCode, 0x90, dwLen); + DWORD dwFunc = pFunc - (pAddr + 5); + + bCode[0] = bInst; + *(DWORD *)&bCode[1] = dwFunc; + WriteBytes((void*)pAddr, bCode, dwLen); + + delete[] bCode; +} + +void PatchCall(DWORD dwAddr, DWORD dwFunc, DWORD dwLen) +{ + InterceptLocalCode(INST_CALL, dwAddr, dwFunc, dwLen); +} + +void PatchJmp(DWORD dwAddr, DWORD dwFunc, DWORD dwLen) +{ + InterceptLocalCode(INST_JMP, dwAddr, dwFunc, dwLen); +} + +void PatchBytes(DWORD dwAddr, DWORD dwValue, DWORD dwLen) +{ + BYTE *bCode = new BYTE[dwLen]; + ::memset(bCode, (BYTE)dwValue, dwLen); + + WriteBytes((LPVOID)dwAddr, bCode, dwLen); + + delete[] bCode; +} + +PatchHook *RetrievePatchHooks(PINT pBuffer) +{ + *pBuffer = ArraySize(Patches); + return &Patches[0]; +} diff --git a/Offset.h b/Offset.h new file mode 100644 index 00000000..f018034e --- /dev/null +++ b/Offset.h @@ -0,0 +1,35 @@ +#ifndef _OFFSET_H +#define _OFFSET_H + +#define INST_INT3 0xCC +#define INST_CALL 0xE8 +#define INST_NOP 0x90 +#define INST_JMP 0xE9 +#define INST_RET 0xC3 + +typedef struct PatchHook_t +{ + void (*pFunc)(DWORD, DWORD, DWORD); + DWORD dwAddr; + DWORD dwFunc; + DWORD dwLen; + BYTE *bOldCode; +} PatchHook; + + +void DefineOffsets(); +DWORD GetDllOffset(int num); +DWORD GetDllOffset(char *DllName, int Offset); + +PatchHook *RetrievePatchHooks(PINT pBuffer); +void PatchBytes(DWORD dwAddr, DWORD dwValue, DWORD dwLen); +void PatchJmp(DWORD dwAddr, DWORD dwFunc, DWORD dwLen); +void PatchCall(DWORD dwAddr, DWORD dwFunc, DWORD dwLen); +void InterceptLocalCode(BYTE bInst, DWORD pAddr, DWORD pFunc, DWORD dwLen); +void FillBytes(void *pAddr, BYTE bFill, DWORD dwLen); +BOOL WriteBytes(void *pAddr, void *pData, DWORD dwLen); +void RemovePatches(); +void InstallPatches(); + + +#endif \ No newline at end of file diff --git a/Patch.h b/Patch.h new file mode 100644 index 00000000..12047919 --- /dev/null +++ b/Patch.h @@ -0,0 +1,31 @@ +#pragma once + +#include "Offset.h" +#include "D2Intercepts.h" +#include "D2Handlers.h" + +PatchHook Patches[] = { + {PatchCall, GetDllOffset("D2Client.dll", 0xB2342), (DWORD)GameInput_Intercept, 5},//1.13d + {PatchJmp, GetDllOffset("D2Client.dll", 0x1D7B4), (DWORD)GameDraw_Intercept, 6},//1.13d + {PatchCall, GetDllOffset("D2Client.dll", 0x83301), (DWORD)GamePacketReceived_Intercept, 5},//1.13d + {PatchCall, GetDllOffset("D2Client.dll", 0x2B494), (DWORD)GetSelectedUnit_Intercept, 5},//1.13d + {PatchJmp, GetDllOffset("D2Client.dll", 0x84417), (DWORD)PlayerAssignment_Intercept, 5},//1.13d + {PatchBytes,GetDllOffset("D2Client.dll", 0x14630), (DWORD)0xc3, 1},//1.13d + {PatchCall, GetDllOffset("D2Client.dll", 0x1B047), (DWORD)GameActChange_Intercept, 5},//1.13d + {PatchJmp, GetDllOffset("D2Client.dll", 0x1B474), (DWORD)GameActChange2_Intercept, 5},//1.13d + {PatchCall, GetDllOffset("D2Client.dll", 0x461AD), (DWORD)GameLeave_Intercept, 5},//1.13d + {PatchCall, GetDllOffset("D2Client.dll", 0x29560), (DWORD)GameAttack_Intercept, 5},//1.13d + +// {PatchCall, GetDllOffset("D2Client.dll", 0xA7364), (DWORD)AddUnit_Intercept, 5}, +// {PatchCall, GetDllOffset("D2Client.dll", 0xA6F25), (DWORD)RemoveUnit_Intercept, 9}, + + {PatchCall, GetDllOffset("D2Multi.dll", 0x142FC6f), (DWORD)Whisper_Intercept, 7},//1.13d + {PatchCall, GetDllOffset("D2Multi.dll", 0x11D63), (DWORD)ChannelInput_Intercept, 5},//1.13d + {PatchCall, GetDllOffset("D2Multi.dll", 0x14A9A), (DWORD)ChannelWhisper_Intercept, 5},//1.13d + {PatchJmp, GetDllOffset("D2Multi.dll", 0x14BE0), (DWORD)ChannelChat_Intercept, 6},//1.13d + {PatchJmp, GetDllOffset("D2Multi.dll", 0x14850), (DWORD)ChannelEmote_Intercept, 6},//1.13d + + {PatchCall, GetDllOffset("D2Win.dll", 0xEC68), (DWORD)GameDrawOOG_Intercept, 5},//1.13d + + {PatchCall, GetDllOffset("D2CMP.dll", 0x14CD5), (DWORD)GameCrashFix_Intercept, 10},//1.13d +}; \ No newline at end of file diff --git a/Room.cpp b/Room.cpp new file mode 100644 index 00000000..8f51a351 --- /dev/null +++ b/Room.cpp @@ -0,0 +1,113 @@ +#include "Room.h" +#include "CriticalSections.h" +#include "D2Ptrs.h" + +BOOL RevealRoom(Room2* pRoom2, BOOL revealPresets) { + bool bAdded = false; + bool bInit = false; + + DWORD dwLevelNo = D2CLIENT_GetPlayerUnit()->pPath->pRoom1->pRoom2->pLevel->dwLevelNo; + + CriticalRoom room; + room.EnterSection(); + //Make sure we have the room. + if (!pRoom2) + return false; + + UnitAny* player = D2CLIENT_GetPlayerUnit(); + //Check if we have Room1(Needed in order to reveal) + if (!(pRoom2 && pRoom2->pRoom1)) { + D2COMMON_AddRoomData(pRoom2->pLevel->pMisc->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, NULL); + bAdded = true; + } + if (!(pRoom2 && pRoom2->pRoom1)){// second check added to see if we DID indeed init the room! + return false; + } + + //If we are somewhere other then the given area, init automap layer to be drawn to. + if(!(pRoom2 && pRoom2->pLevel && pRoom2->pLevel->dwLevelNo && player->pPath && player->pPath->pRoom1 && player->pPath->pRoom1->pRoom2 && player->pPath->pRoom1->pRoom2->pLevel && player->pPath->pRoom1->pRoom2->pLevel->dwLevelNo == pRoom2->pLevel->dwLevelNo)){ + InitAutomapLayer(pRoom2->pLevel->dwLevelNo); + bInit = true; + } + + //Reveal this room! + D2CLIENT_RevealAutomapRoom(pRoom2->pRoom1, TRUE, (*p_D2CLIENT_AutomapLayer)); + + if(revealPresets) + DrawPresets(pRoom2); + + //Remove room data if we have added. + if(bAdded) + D2COMMON_RemoveRoomData(pRoom2->pLevel->pMisc->pAct, pRoom2->pLevel->dwLevelNo, pRoom2->dwPosX, pRoom2->dwPosY, NULL); + + if(bInit) + InitAutomapLayer(dwLevelNo); + + return true; +} + +/*void DrawPresets(Room2 *pRoom2) + * This will find all the shrines, special automap icons, and level names and place on map. + */ +void DrawPresets (Room2 *pRoom2) +{ + //UnitAny* Player = D2CLIENT_GetPlayerUnit(); + //Grabs all the preset units in room. + for (PresetUnit *pUnit = pRoom2->pPreset; pUnit; pUnit = pUnit->pPresetNext) + { + int mCell = -1; + if (pUnit->dwType == 1)//Special NPCs. + { + if (pUnit->dwTxtFileNo == 256)//Izzy + mCell = 300; + if (pUnit->dwTxtFileNo == 745)//Hephasto + mCell = 745; + } else if (pUnit->dwType == 2) { //Objects on Map + + //Add's a special Chest icon over the hidden uberchests in Lower Kurast + if (pUnit->dwTxtFileNo == 580 && pRoom2->pLevel->dwLevelNo == 79) + mCell = 318; + + //Special Units that require special checking:) + if (pUnit->dwTxtFileNo == 371) + mCell = 301; //Countess Chest + if (pUnit->dwTxtFileNo == 152) + mCell = 300; //A2 Orifice + if (pUnit->dwTxtFileNo == 460) + mCell = 1468; //Frozen Anya + if ((pUnit->dwTxtFileNo == 402) && (pRoom2->pLevel->dwLevelNo == 46)) + mCell = 0; //Canyon/Arcane Waypoint + if ((pUnit->dwTxtFileNo == 267) && (pRoom2->pLevel->dwLevelNo != 75) && (pRoom2->pLevel->dwLevelNo != 103)) + mCell = 0; + if ((pUnit->dwTxtFileNo == 376) && (pRoom2->pLevel->dwLevelNo == 107)) + mCell = 376; + + if (pUnit->dwTxtFileNo > 574) + mCell = 0; + + if (mCell == -1) + { + //Get the object cell + ObjectTxt *obj = D2COMMON_GetObjectText(pUnit->dwTxtFileNo); + + if (mCell == -1) + { + mCell = obj->nAutoMap;//Set the cell number then. + } + } + } + + //Draw the cell if wanted. + if ((mCell > 0) && (mCell < 1258)) + { + AutomapCell *pCell = D2CLIENT_NewAutomapCell(); + pCell->nCellNo = (WORD)mCell; + int pX = (pUnit->dwPosX + (pRoom2->dwPosX * 5)); + int pY = (pUnit->dwPosY + (pRoom2->dwPosY * 5)); + pCell->xPixel = (WORD)((((pX - pY) * 16) / 10) + 1); + pCell->yPixel = (WORD)((((pY + pX) * 8) / 10) - 3); + + D2CLIENT_AddAutomapCell(pCell, &((*p_D2CLIENT_AutomapLayer)->pObjects)); + } + } +} diff --git a/Room.h b/Room.h new file mode 100644 index 00000000..52923179 --- /dev/null +++ b/Room.h @@ -0,0 +1,9 @@ +#ifndef _ROOM_H +#define _ROOM_H + +#include "D2Structs.h" + +BOOL RevealRoom(Room2* pRoom2, BOOL revealPresets); +void DrawPresets (Room2 *pRoom2); + +#endif diff --git a/ScreenHook.cpp b/ScreenHook.cpp new file mode 100644 index 00000000..e6a47415 --- /dev/null +++ b/ScreenHook.cpp @@ -0,0 +1,467 @@ +#include "ScreenHook.h" +#include "JSScreenHook.h" +#include "D2BS.h" +#include "Console.h" +#include "D2Ptrs.h" + +#include + +using namespace std; + +bool Genhook::init = false; +HookList Genhook::visible = HookList(); +HookList Genhook::invisible = HookList(); +CRITICAL_SECTION Genhook::globalSection = {0}; + +void DrawLogo(void) +{ + static char img[_MAX_PATH+_MAX_FNAME] = ""; + static char version[] = "D2BS " D2BS_VERSION; + static int x = (CalculateTextLen(version, 0).x/2); + + if(img[0] == '\0') + sprintf_s(img, sizeof(img), "%sversion.bmp", Vars.szPath); + + CellFile* vimg = LoadCellFile(img, FALSE); + int dx = (GetScreenSize().x/2); + if(!Console::IsVisible()) + { + myDrawAutomapCell(vimg, dx, 10, 0); + myDrawText(version, dx-x, 13, 4, 0); + } else { + myDrawAutomapCell(vimg, dx, Console::GetHeight()+9, 0); + myDrawText(version, dx-x, Console::GetHeight()+14, 4, 0); + } +} + +bool zOrderSort(Genhook* first, Genhook* second) +{ + return first->GetZOrder() < second->GetZOrder(); +} + +bool __fastcall HoverHook(Genhook* hook, void* argv, uint argc) +{ + HookClickHelper* helper = (HookClickHelper*)argv; + hook->Hover(&helper->point); + return true; +} + +bool __fastcall ClickHook(Genhook* hook, void* argv, uint argc) +{ + HookClickHelper* helper = (HookClickHelper*)argv; + return hook->Click(helper->button, &helper->point); +} + +bool __fastcall DrawHook(Genhook* hook, void* argv, uint argc) +{ + if((hook->GetGameState() == (ScreenhookState)(int)argv || hook->GetGameState() == Perm) && + (!hook->GetIsAutomap() || (hook->GetIsAutomap() && *p_D2CLIENT_AutomapOn))) + hook->Draw(); + return true; +} + +bool __fastcall CleanHook(Genhook* hook, void* argv, uint argc) +{ + if(hook->owner == (Script*)argv) + hook->SetIsVisible(false); + return true; +} + +void Genhook::DrawAll(ScreenhookState type) +{ + if(!init) + return; + ForEachVisibleHook(DrawHook, (void*)type, 1); +} + +bool Genhook::ForEachHook(HookCallback proc, void* argv, uint argc) +{ + // iterate the visible ones, then the invisible ones + EnterCriticalSection(&globalSection); + + bool result = false; + std::vector list; + for(HookIterator it = visible.begin(); it != visible.end(); it++) + list.push_back(*it); + int count = list.size(); + + for(int i = 0; i < count; i++) + if(proc(list[i], argv, argc)) + result = true; + + if(!result) + { + list.clear(); + for(HookIterator it = visible.begin(); it != visible.end(); it++) + list.push_back(*it); + count = list.size(); + + for(int i = 0; i < count; i++) + if(proc(list[i], argv, argc)) + result = true; + } + + LeaveCriticalSection(&globalSection); + return result; +} + +bool Genhook::ForEachVisibleHook(HookCallback proc, void* argv, uint argc) +{ + // iterate the visible ones, then the invisible ones + EnterCriticalSection(&globalSection); + + bool result = false; + std::vector list; + for(HookIterator it = visible.begin(); it != visible.end(); it++) + list.push_back(*it); + int count = list.size(); + + for(int i = 0; i < count; i++) + if(proc(list[i], argv, argc)) + result = true; + + LeaveCriticalSection(&globalSection); + return result; +} + +bool Genhook::ForEachInvisibleHook(HookCallback proc, void* argv, uint argc) +{ + // iterate the visible ones, then the invisible ones + EnterCriticalSection(&globalSection); + + bool result = false; + std::vector list; + for(HookIterator it = invisible.begin(); it != invisible.end(); it++) + list.push_back(*it); + int count = list.size(); + + for(int i = 0; i < count; i++) + if(proc(list[i], argv, argc)) + result = true; + + + LeaveCriticalSection(&globalSection); + return result; +} + +void Genhook::Clean(Script* owner) +{ + if(!init) + return; + + ForEachHook(CleanHook, owner, 1); +} + +Genhook::Genhook(Script* nowner, JSObject* nself, uint x, uint y, ushort nopacity, bool nisAutomap, Align nalign, ScreenhookState ngameState) : + owner(nowner), isAutomap(nisAutomap), isVisible(true), alignment(nalign), opacity(nopacity), gameState(ngameState), zorder(1) +{ + InitializeCriticalSection(&hookSection); + clicked = JSVAL_VOID; + hovered = JSVAL_VOID; + JS_AddRoot(&self); + self = nself; + SetX(x); SetY(y); + visible.push_back(this); +} + +Genhook::~Genhook(void) { + Lock(); + if(owner && !JSVAL_IS_VOID(clicked)) + JS_RemoveRoot(&clicked); + if(owner && !JSVAL_IS_VOID(hovered)) + JS_RemoveRoot(&hovered); + JS_RemoveRoot(&self); + + EnterCriticalSection(&globalSection); + + owner = NULL; + location.x = -1; + location.y = -1; + if(isVisible) + visible.remove(this); + else + invisible.remove(this); + + LeaveCriticalSection(&globalSection); + + Unlock(); + DeleteCriticalSection(&hookSection); +} + +bool Genhook::Click(int button, POINT* loc) +{ + if(!IsInRange(loc)) + return false; + + bool result = false; + + JSContext* cx = ScriptEngine::GetGlobalContext(); + JS_SetContextThread(cx); + JS_BeginRequest(cx); + if(owner && JSVAL_IS_FUNCTION(cx, clicked)) + { + Lock(); + + JS_EnterLocalRootScope(cx); + jsval rval = JSVAL_VOID; + jsval args[3] = { INT_TO_JSVAL(button), INT_TO_JSVAL(loc->x), INT_TO_JSVAL(loc->y) }; + + JS_CallFunctionValue(cx, self, clicked, 3, args, &rval); + + result = !!!(JSVAL_IS_BOOLEAN(rval) && JSVAL_TO_BOOLEAN(rval)); + JS_LeaveLocalRootScope(cx); + + Unlock(); + } + JS_EndRequest(cx); + JS_ClearContextThread(cx); + + return result; +} + +void Genhook::Hover(POINT* loc) +{ + if(!IsInRange(loc)) + return; + + JSContext* cx = ScriptEngine::GetGlobalContext(); + JS_SetContextThread(cx); + JS_BeginRequest(cx); + if(owner && (JSVAL_IS_FUNCTION(cx, hovered))) + { + Lock(); + + JS_EnterLocalRootScope(cx); + jsval rval = JSVAL_VOID; + jsval args[2] = { INT_TO_JSVAL(loc->x), INT_TO_JSVAL(loc->y) }; + + JS_CallFunctionValue(cx, self, hovered, 2, args, &rval); + + JS_LeaveLocalRootScope(cx); + + Unlock(); + } + JS_EndRequest(cx); + JS_ClearContextThread(cx); +} + +void Genhook::SetClickHandler(jsval handler) +{ + if(!owner) + return; + Lock(); + if(!JSVAL_IS_VOID(clicked)) + JS_RemoveRoot(&clicked); + JSContext* cx = ScriptEngine::GetGlobalContext(); + JS_SetContextThread(cx); + JS_BeginRequest(cx); + if(JSVAL_IS_FUNCTION(cx, handler)) + clicked = handler; + if(!JSVAL_IS_VOID(clicked)) + { + if(JS_AddRoot(&clicked) == JS_FALSE) + { + Unlock(); + JS_EndRequest(cx); + JS_ClearContextThread(cx); + return; + } + } + JS_EndRequest(cx); + JS_ClearContextThread(cx); + Unlock(); +} + +void Genhook::SetHoverHandler(jsval handler) +{ + if(!owner) + return; + Lock(); + if(!JSVAL_IS_VOID(hovered)) + JS_RemoveRoot(&hovered); + if(JSVAL_IS_FUNCTION(owner->GetContext(), handler)) + hovered = handler; + if(!JSVAL_IS_VOID(hovered)) + { + if(JS_AddRoot(&hovered) == JS_FALSE) + { + Unlock(); + return; + } + } + Unlock(); +} + +void TextHook::Draw(void) +{ + Lock(); + if(GetIsVisible() && GetX() != -1 && GetY() != -1 && text) + { + uint x = GetX(), y = GetY(), w = CalculateTextLen(text, font).x; + x -= (alignment != Center ? (alignment != Right ? 0 : w) : w/2); + POINT loc = {x, y}; + if(GetIsAutomap()) + { + ScreenToAutomap(&loc); + } + EnterCriticalSection(&Vars.cTextHookSection); + myDrawText(text, loc.x, loc.y, color, font); + LeaveCriticalSection(&Vars.cTextHookSection); + } + Unlock(); +} + +bool TextHook::IsInRange(int dx, int dy) +{ + Lock(); + POINT size = CalculateTextLen(text, font); + int x = GetX(), y = GetY(), w = size.x, h = size.y, + xp = x - (alignment != Center ? (alignment != Right ? 0 : w) : w/2); + Unlock(); + return (xp < dx && y > dy && (xp+w) > dx && (y-h) < dy); +} + +void TextHook::SetText(const char* ntext) +{ + Lock(); + free(text); + text = NULL; + if(ntext) + text = _strdup(ntext); + Unlock(); +} + +void ImageHook::Draw(void) +{ + Lock(); + if(GetIsVisible() && GetX() != -1 && GetY() != -1 && + GetImage() != NULL && image != NULL) + { + uint x = GetX(), y = GetY(), w = image->cells[0]->width; + x += (alignment != Left ? (alignment != Right ? 0 : -1*(w/2)) : w/2); + POINT loc = {x, y}; + if(GetIsAutomap()) + { + ScreenToAutomap(&loc); + } + EnterCriticalSection(&Vars.cImageHookSection); + myDrawAutomapCell(image, loc.x, loc.y, (BYTE)color); + LeaveCriticalSection(&Vars.cImageHookSection); + } + Unlock(); +} + +bool ImageHook::IsInRange(int dx, int dy) +{ + if(image) + { + Lock(); + int x = GetX(); + int y = GetY(); + int w = image->cells[0]->width; + int h = image->cells[0]->height; + int xp = x - (alignment != Left ? (alignment != Right ? w/2 : w) : -1*w); + int yp = y - (h/2); + Unlock(); + return (xp < dx && yp < dy && (xp+w) > dx && (yp+h) > dy); + } + + return false; +} + +void ImageHook::SetImage(const char* nimage) +{ + Lock(); + free(location); + delete[] image; + + location = _strdup(nimage); + image = LoadCellFile(location); + Unlock(); +} + +void LineHook::Draw(void) +{ + Lock(); + if(GetIsVisible() && GetX() != -1 && GetY() != -1) + { + uint x = GetX(), y = GetY(), x2 = GetX2(), y2 = GetY2(); + POINT loc = {x, y}; + POINT sz = {x2, y2}; + if(GetIsAutomap()) + { + ScreenToAutomap(&loc); + ScreenToAutomap(&sz); + } + EnterCriticalSection(&Vars.cLineHookSection); + D2GFX_DrawLine(loc.x, loc.y, sz.x, sz.y, color, 0xFF); + LeaveCriticalSection(&Vars.cLineHookSection); + } + Unlock(); +} + +void BoxHook::Draw(void) +{ + Lock(); + if(GetIsVisible() && GetX() != -1 && GetY() != -1) + { + uint x = GetX(), y = GetY(), x2 = GetXSize(), y2 = GetYSize(); + if(alignment == Center) + { + x -= x2/2; + } + else if (alignment == Right) + { + x += x2/2; + } + POINT loc = {x, y}; + POINT sz = {x+x2, y+y2}; + if(GetIsAutomap()) + { + ScreenToAutomap(&loc); + ScreenToAutomap(&sz); + } + EnterCriticalSection(&Vars.cBoxHookSection); + D2GFX_DrawRectangle(loc.x, loc.y, sz.x, sz.y, color, opacity); + LeaveCriticalSection(&Vars.cBoxHookSection); + } + Unlock(); +} + +bool BoxHook::IsInRange(int dx, int dy) +{ + Lock(); + int x = GetX(), y = GetY(), x2 = GetXSize(), y2 = GetYSize(); + Unlock(); + return (x < dx && y < dy && (x+x2) > dx && (y+y2) > dy); +} + +void FrameHook::Draw(void) +{ + Lock(); + if(GetIsVisible() && GetX() != -1 && GetY() != -1) + { + uint x = GetX(), y = GetY(), x2 = GetXSize(), y2 = GetYSize(); + if(alignment == Center) + { + x -= x2/2; + } + else if (alignment == Right) + { + x += x2/2; + } + RECT rect = {x, y, x+x2, y+y2}; + EnterCriticalSection(&Vars.cFrameHookSection); + D2GFX_DrawFrame(&rect); + LeaveCriticalSection(&Vars.cFrameHookSection); + } + Unlock(); +} + +bool FrameHook::IsInRange(int dx, int dy) +{ + Lock(); + int x = GetX(), y = GetY(), x2 = GetXSize(), y2 = GetYSize(); + Unlock(); + return (x < dx && y < dy && (x+x2) > dx && (y+y2) > dy); +} diff --git a/ScreenHook.h b/ScreenHook.h new file mode 100644 index 00000000..cbb8350f --- /dev/null +++ b/ScreenHook.h @@ -0,0 +1,275 @@ +#pragma once + +#include +#include +#include + +#include "Script.h" +#include "ScriptEngine.h" +#include "D2Helpers.h" + + +void DrawLogo(void); + +typedef unsigned short ushort; + +class Genhook; + +typedef std::list HookList; +typedef HookList::iterator HookIterator; + +struct HookClickHelper +{ + int button; + POINT point; +}; + +typedef bool (__fastcall *HookCallback)(Genhook*, void*, uint); + +enum Align { Left, Right, Center }; +enum ScreenhookState { OOG, IG, Perm }; + +class Genhook +{ +private: + static bool init; + static HookList visible, invisible; + static CRITICAL_SECTION globalSection; + +protected: + Script* owner; + ScreenhookState gameState; + Align alignment; + jsval clicked, hovered; + JSObject* self; + bool isAutomap, isVisible; + ushort opacity, zorder; + POINT location; + CRITICAL_SECTION hookSection; + + Genhook(const Genhook&); + Genhook& operator=(const Genhook&); + +public: + Genhook::Genhook(Script* nowner, JSObject* nself, uint x, uint y, ushort nopacity, bool nisAutomap = false, + Align nalign = Left, ScreenhookState ngameState = Perm); + ~Genhook(void); + + friend bool __fastcall DrawHook(Genhook* hook, void* argv, uint argc); + friend bool __fastcall CleanHook(Genhook* hook, void* argv, uint argc); + friend bool __fastcall ClickHook(Genhook* hook, void* argv, uint argc); + friend bool __fastcall HoverHook(Genhook* hook, void* argv, uint argc); + + static void DrawAll(ScreenhookState type); + + static bool ForEachHook(HookCallback proc, void* argv, uint argc); + static bool ForEachVisibleHook(HookCallback proc, void* argv, uint argc); + static bool ForEachInvisibleHook(HookCallback proc, void* argv, uint argc); + + static void Clean(Script* owner); + static void Initialize(void) { InitializeCriticalSection(&globalSection); init = true; } + static void Destroy(void) { init = false; DeleteCriticalSection(&globalSection); } + +protected: + virtual void Draw(void) = 0; + +public: + + bool Click(int button, POINT* loc); + void Hover(POINT* loc); + + bool IsInRange(POINT* pt) { return IsInRange(pt->x, pt->y); } + virtual bool IsInRange(int dx, int dy) = 0; + + void Move(POINT* dist) { Move(dist->x, dist->y); } + void Move(uint nx, uint ny) { SetX(GetX()+nx); SetY(GetY()+ny); } + + void SetX(uint x) { Lock(); location.x = x; Unlock(); } + void SetY(uint y) { Lock(); location.y = y; Unlock(); } + void SetAlign(Align nalign) { Lock(); alignment = nalign; Unlock(); } + void SetOpacity(ushort nopacity) { Lock(); opacity = nopacity; Unlock(); } + void SetIsVisible(bool nisVisible) { + Lock(); + if(!nisVisible) + { + if(isVisible) + { + visible.remove(this); + invisible.push_back(this); + } + } else { + if(!isVisible) + { + invisible.remove(this); + visible.push_back(this); + } + } + isVisible = nisVisible; + Unlock(); + } + void SetZOrder(ushort norder) { Lock(); zorder = norder; Unlock(); } + void SetClickHandler(jsval handler); + void SetHoverHandler(jsval handler); + + POINT GetLocation(void) const { return location; } + uint GetX(void) const { return location.x; } + uint GetY(void) const { return location.y; } + Align GetAlign(void) const { return alignment; } + ushort GetOpacity(void) const { return opacity; } + ScreenhookState GetGameState(void) const { return gameState; } + bool GetIsAutomap(void) const { return isAutomap; } + bool GetIsVisible(void) const { return isVisible; } + ushort GetZOrder(void) const { return zorder; } + jsval GetClickHandler(void) { return clicked; } + jsval GetHoverHandler(void) { return hovered; } + + void Lock() { /*EnterCriticalSection(&hookSection); isLocked = true;*/ } + void Unlock() { /*if(!IsLocked()) return; LeaveCriticalSection(&hookSection); isLocked = false;*/ } +}; + +class TextHook : public Genhook +{ +private: + char* text; + ushort font, color; + + TextHook(const TextHook&); + TextHook& operator=(const TextHook&); +public: + TextHook(Script* owner, JSObject* nself, char* text, uint x, uint y, ushort nfont, + ushort ncolor, bool automap = false, Align align = Left, + ScreenhookState state = Perm) : + Genhook(owner, nself, x, y, 0, automap, align, state), text(NULL), font(nfont), color(ncolor) + { this->text = _strdup(text); } + ~TextHook(void) + { + free(text); + } + +protected: + void Draw(void); + +public: + bool IsInRange(int dx, int dy); + + void SetFont(ushort nfont) { Lock(); font = nfont; Unlock(); } + void SetColor(ushort ncolor) { Lock(); color = ncolor; Unlock(); } + void SetText(const char* ntext); + + ushort GetFont(void) const { return font; } + ushort GetColor(void) const { return color; } + const char* GetText(void) const { return text; } +}; + +class ImageHook : public Genhook +{ +private: + char* location; + CellFile* image; + ushort color; + + ImageHook(const ImageHook&); + ImageHook& operator=(const ImageHook&); +public: + ImageHook(Script* owner, JSObject* nself, const char* nloc, uint x, uint y, ushort ncolor, + bool automap = false, Align align = Left, ScreenhookState state = Perm, bool fromFile = true) : + Genhook(owner, nself, x, y, 0, automap, align, state), color(ncolor), image(NULL), location(NULL) + { location = _strdup(nloc); image = LoadCellFile(location, fromFile); } + ~ImageHook(void) { free(location); delete[] image; } + +protected: + void Draw(void); + +public: + bool IsInRange(int dx, int dy); + + void SetImage(const char* nimage); + void SetColor(ushort ncolor) { Lock(); color = ncolor; Unlock(); } + + const char* GetImage(void) const { return location; } + ushort GetColor(void) const { return color; } +}; + +class LineHook : public Genhook +{ +private: + uint x2, y2; + ushort color; + + LineHook(const LineHook&); + LineHook& operator=(const LineHook&); +public: + LineHook(Script* owner, JSObject* nself, uint x, uint y, uint nx2, uint ny2, ushort ncolor, + bool automap = false, Align align = Left, ScreenhookState state = Perm) : + Genhook(owner, nself, x, y, 0, automap, align, state), x2(nx2), y2(ny2), color(ncolor) {} + ~LineHook(void) {} + +protected: + void Draw(void); + +public: + bool IsInRange(int dx, int dy) { return false; } + + void SetX2(uint nx2) { Lock(); x2 = nx2; Unlock(); } + void SetY2(uint ny2) { Lock(); y2 = ny2; Unlock(); } + void SetColor(ushort ncolor) { Lock(); color = ncolor; Unlock(); } + + uint GetX2(void) const { return x2; } + uint GetY2(void) const { return y2; } + ushort GetColor(void) const { return color; } +}; + +class BoxHook : public Genhook +{ +private: + uint xsize, ysize; + ushort color; + + BoxHook(const BoxHook&); + BoxHook& operator=(const BoxHook&); +public: + BoxHook(Script* owner, JSObject* nself, uint x, uint y, uint nxsize, uint nysize, ushort ncolor, + ushort opacity, bool automap = false, Align align = Left, ScreenhookState state = Perm) : + Genhook(owner, nself, x, y, opacity, automap, align, state), xsize(nxsize), ysize(nysize), color(ncolor) {} + ~BoxHook(void) {} + +protected: + void Draw(void); + +public: + bool IsInRange(int dx, int dy); + + void SetXSize(uint nxsize) { Lock(); xsize = nxsize; Unlock(); } + void SetYSize(uint nysize) { Lock(); ysize = nysize; Unlock(); } + void SetColor(ushort ncolor) { Lock(); color = ncolor; Unlock(); } + + uint GetXSize(void) const { return xsize; } + uint GetYSize(void) const { return ysize; } + ushort GetColor(void) const { return color; } +}; + +class FrameHook : public Genhook +{ +private: + uint xsize, ysize; + + FrameHook(const FrameHook&); + FrameHook& operator=(const FrameHook&); +public: + FrameHook(Script* owner, JSObject* nself, uint x, uint y, uint nxsize, uint nysize, + bool automap = false, Align align = Left, ScreenhookState state = Perm) : + Genhook(owner, nself, x, y, 0, automap, align, state), xsize(nxsize), ysize(nysize) {} + ~FrameHook(void) {} + +protected: + void Draw(void); + +public: + bool IsInRange(int dx, int dy); + + void SetXSize(uint nxsize) { Lock(); xsize = nxsize; Unlock(); } + void SetYSize(uint nysize) { Lock(); ysize = nysize; Unlock(); } + + uint GetXSize(void) const { return xsize; } + uint GetYSize(void) const { return ysize; } +}; diff --git a/Script.cpp b/Script.cpp new file mode 100644 index 00000000..9127f811 --- /dev/null +++ b/Script.cpp @@ -0,0 +1,504 @@ +#include +#include + +#include "Script.h" +#include "Core.h" +#include "Constants.h" +#include "D2Ptrs.h" +#include "JSUnit.h" +#include "Helpers.h" +#include "ScriptEngine.h" +#include "D2BS.h" + +using namespace std; + +Script::Script(const char* file, ScriptState state) : + context(NULL), globalObject(NULL), scriptObject(NULL), script(NULL), execCount(0), + isAborted(false), isPaused(false), isReallyPaused(false), scriptState(state), + threadHandle(INVALID_HANDLE_VALUE), threadId(0) +{ + InitializeCriticalSection(&lock); + EnterCriticalSection(&lock); + + if(scriptState == Command) + { + fileName = string("Command Line"); + } + else + { + if(_access(file, 0) != 0) + throw std::exception("File not found"); + + char* tmpName = _strdup(file); + if(!tmpName) + throw std::exception("Could not dup filename"); + + _strlwr_s(tmpName, strlen(file)+1); + fileName = string(tmpName); + replace(fileName.begin(), fileName.end(), '/', '\\'); + free(tmpName); + } + try + { + context = JS_NewContext(ScriptEngine::GetRuntime(), 0x2000); + if(!context) + throw std::exception("Couldn't create the context"); + + JS_SetContextPrivate(context, this); + JS_BeginRequest(context); + + globalObject = JS_GetGlobalObject(context); + jsval meVal = JSVAL_VOID; + if(JS_GetProperty(GetContext(), globalObject, "me", &meVal) != JS_FALSE) + { + JSObject* meObject = JSVAL_TO_OBJECT(meVal); + me = (myUnit*)JS_GetPrivate(GetContext(), meObject); + } + + if(state == Command) + script = JS_CompileScript(context, globalObject, file, strlen(file), "Command Line", 1); + else + script = JS_CompileFile(context, globalObject, fileName.c_str()); + if(!script) + throw std::exception("Couldn't compile the script"); + + scriptObject = JS_NewScriptObject(context, script); + if(!scriptObject) + throw std::exception("Couldn't create the script object"); + + if(JS_AddNamedRoot(context, &scriptObject, "script object") == JS_FALSE) + throw std::exception("Couldn't add named root for scriptObject"); + + JS_EndRequest(context); + + LeaveCriticalSection(&lock); + } catch(std::exception&) { + if(scriptObject) + JS_RemoveRoot(&scriptObject); + if(script && !scriptObject) + JS_DestroyScript(context, script); + if(context) + { + JS_EndRequest(context); + JS_DestroyContext(context); + } + LeaveCriticalSection(&lock); + throw; + } +} + +Script::~Script(void) +{ + EnterCriticalSection(&lock); + Stop(true, true); + + JS_SetContextThread(context); + + JS_BeginRequest(context); + + // these calls can, and probably should, be moved to the context callback on cleanup + JS_RemoveRoot(&globalObject); + JS_RemoveRoot(&scriptObject); + + JS_DestroyContextNoGC(context); + + context = NULL; + scriptObject = NULL; + globalObject = NULL; + script = NULL; + + includes.clear(); + if(threadHandle) + CloseHandle(threadHandle); + LeaveCriticalSection(&lock); + DeleteCriticalSection(&lock); +} + +int Script::GetExecutionCount(void) +{ + return execCount; +} + +DWORD Script::GetThreadId(void) +{ + return (threadHandle == NULL ? -1 : threadId); +} + +void Script::Run(void) +{ + // only let the script run if it's not already running + if(IsRunning()) + return; + + isAborted = false; + DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &threadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS); + threadId = GetCurrentThreadId(); + + jsval main = JSVAL_VOID, dummy = JSVAL_VOID; + JS_AddRoot(&main); + + JS_SetContextThread(GetContext()); + JS_BeginRequest(GetContext()); + + if(JS_ExecuteScript(GetContext(), globalObject, script, &dummy) != JS_FALSE && + JS_GetProperty(GetContext(), globalObject, "main", &main) != JS_FALSE && + JSVAL_IS_FUNCTION(GetContext(), main)) + { + JS_CallFunctionValue(GetContext(), globalObject, main, 0, NULL, &dummy); + } + + if(GetState() == Command) + { + // if we just processed a command, print the results of the command + if(!JSVAL_IS_NULL(dummy) && !JSVAL_IS_VOID(dummy)) + { + JS_ConvertValue(GetContext(), dummy, JSTYPE_STRING, &dummy); + Print(JS_GetStringBytes(JS_ValueToString(GetContext(), dummy))); + } + } + + JS_RemoveRoot(&main); + JS_EndRequest(GetContext()); + JS_ClearContextThread(GetContext()); + + execCount++; + Stop(); +} + +void Script::UpdatePlayerGid(void) +{ + me->dwUnitId = (D2CLIENT_GetPlayerUnit() == NULL ? NULL : D2CLIENT_GetPlayerUnit()->dwUnitId); +} + +void Script::Pause(void) +{ + //EnterCriticalSection(&lock); + if(!IsAborted() && !IsPaused()) + isPaused = true; + //LeaveCriticalSection(&lock); +} + +void Script::Resume(void) +{ + //EnterCriticalSection(&lock); + if(!IsAborted() && IsPaused()) + isPaused = false; + //LeaveCriticalSection(&lock); +} + +bool Script::IsPaused(void) +{ + return isPaused; +} + +const char* Script::GetShortFilename() +{ + if(strcmp(fileName.c_str(), "Command Line") == 0) return fileName.c_str(); + else return (fileName.c_str() + strlen(Vars.szScriptPath) + 1); +} + +void Script::Stop(bool force, bool reallyForce) +{ + // if we've already stopped, just return + if(isAborted) + return; + + EnterCriticalSection(&lock); + + // tell everyone else that the script is aborted FIRST + isAborted = true; + isPaused = false; + isReallyPaused = false; + if(GetState() != Command) + { + const char* displayName = fileName.c_str() + strlen(Vars.szScriptPath) + 1; + Print("Script %s ended", displayName); + } + + ClearAllEvents(); + Genhook::Clean(this); + + // normal wait: 500ms, forced wait: 300ms, really forced wait: 100ms + int maxCount = (force ? (reallyForce ? 10 : 30) : 50); + for(int i = 0; IsRunning(); i++) + { + // if we pass the time frame, just ignore the wait because the thread will end forcefully anyway + if(i >= maxCount) + break; + Sleep(10); + } + + if(threadHandle) + CloseHandle(threadHandle); + threadHandle = NULL; + LeaveCriticalSection(&lock); +} + +bool Script::IsIncluded(const char* file) +{ + uint count = 0; + char* fname = _strdup(file); + if(!fname) + return false; + + _strlwr_s(fname, strlen(fname)+1); + StringReplace(fname, '/', '\\', strlen(fname)); + count = includes.count(string(fname)); + free(fname); + + return !!count; +} + +bool Script::Include(const char* file) +{ + // since includes will happen on the same thread, locking here is acceptable + EnterCriticalSection(&lock); + char* fname = _strdup((char*)file); + if(!fname) + return false; + _strlwr_s(fname, strlen(fname)+1); + StringReplace(fname, '/', '\\', strlen(fname)); + + // don't invoke the string ctor more than once... + string currentFileName = string(fname); + // ignore already included, 'in-progress' includes, and self-inclusion + if(!!includes.count(currentFileName) || + !!inProgress.count(string(currentFileName)) || + (fileName == string(currentFileName))) + { + LeaveCriticalSection(&lock); + free(fname); + return true; + } + bool rval = false; + + JSContext* cx = GetContext(); + + JS_BeginRequest(cx); + + JSScript* script = JS_CompileFile(cx, GetGlobalObject(), fname); + if(script) + { + JSObject* scriptObj = JS_NewScriptObject(cx, script); + JS_AddRoot(&scriptObj); + jsval dummy; + inProgress[fname] = true; + rval = !!JS_ExecuteScript(cx, GetGlobalObject(), script, &dummy); + if(rval) + includes[fname] = true; + else + JS_ReportPendingException(cx); + inProgress.erase(fname); + JS_RemoveRoot(&scriptObj); + } else JS_ReportPendingException(cx); + + JS_EndRequest(cx); + LeaveCriticalSection(&lock); + free(fname); + return rval; +} + +bool Script::IsRunning(void) +{ + return context && !(!JS_IsRunning(context) || IsPaused()); +} + +bool Script::IsAborted() +{ + return isAborted; +} + +bool Script::IsListenerRegistered(const char* evtName) +{ + return strlen(evtName) > 0 && functions.count(evtName) > 0; +} + +void Script::RegisterEvent(const char* evtName, jsval evtFunc) +{ + EnterCriticalSection(&lock); + if(JSVAL_IS_FUNCTION(context, evtFunc) && strlen(evtName) > 0) + { + AutoRoot* root = new AutoRoot(evtFunc); + functions[evtName].push_back(root); + } + LeaveCriticalSection(&lock); +} + +bool Script::IsRegisteredEvent(const char* evtName, jsval evtFunc) +{ + // nothing can be registered under an empty name + if(strlen(evtName) < 1) + return false; + + // if there are no events registered under that name at all, then obviously there + // can't be a specific one registered under that name + if(functions.count(evtName) < 1) + return false; + + for(FunctionList::iterator it = functions[evtName].begin(); it != functions[evtName].end(); it++) + if(*(*it)->value() == evtFunc) + return true; + + return false; +} + +void Script::UnregisterEvent(const char* evtName, jsval evtFunc) +{ + if(strlen(evtName) < 1) + return; + + EnterCriticalSection(&lock); + AutoRoot* func = NULL; + for(FunctionList::iterator it = functions[evtName].begin(); it != functions[evtName].end(); it++) + { + if(*(*it)->value() == evtFunc) + { + func = *it; + break; + } + } + functions[evtName].remove(func); + func->Release(); + delete func; + LeaveCriticalSection(&lock); +} + +void Script::ClearEvent(const char* evtName) +{ + EnterCriticalSection(&lock); + for(FunctionList::iterator it = functions[evtName].begin(); it != functions[evtName].end(); it++) + { + AutoRoot* func = *it; + func->Release(); + delete func; + } + functions[evtName].clear(); + LeaveCriticalSection(&lock); +} + +void Script::ClearAllEvents(void) +{ + EnterCriticalSection(&lock); + for(FunctionMap::iterator it = functions.begin(); it != functions.end(); it++) + ClearEvent(it->first.c_str()); + functions.clear(); + LeaveCriticalSection(&lock); +} + +void Script::ExecEventAsync(char* evtName, uintN argc, AutoRoot** argv) +{ + if(!(!IsAborted() && !IsPaused() && functions.count(evtName))) + { + // no event will happen, clean up the roots + for(uintN i = 0; i < argc; i++) + delete argv[i]; + delete[] argv; + return; + } + + for(uintN i = 0; i < argc; i++) + argv[i]->Take(); + + Event* evt = new Event; + evt->owner = this; + evt->functions = functions[evtName]; + evt->argc = argc; + evt->argv = argv; + evt->object = globalObject; + + CreateThread(0, 0, FuncThread, evt, 0, 0); +} + +#ifdef DEBUG +typedef struct tagTHREADNAME_INFO +{ + DWORD dwType; // must be 0x1000 + LPCSTR szName; // pointer to name (in user addr space) + DWORD dwThreadID; // thread ID (-1=caller thread) + DWORD dwFlags; // reserved for future use, must be zero +} THREADNAME_INFO; + +void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) +{ + THREADNAME_INFO info; + info.dwType = 0x1000; + info.szName = szThreadName; + info.dwThreadID = dwThreadID; + info.dwFlags = 0; + + __try + { + RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info ); + } + __except(EXCEPTION_CONTINUE_EXECUTION) + { + } +} +#endif + + +DWORD WINAPI ScriptThread(void* data) +{ + Script* script = (Script*)data; + if(script) + { +#ifdef DEBUG + SetThreadName(0xFFFFFFFF, script->GetShortFilename()); +#endif + script->Run(); + if(Vars.bDisableCache) + ScriptEngine::DisposeScript(script); + } + return 0; +} + +DWORD WINAPI FuncThread(void* data) +{ + Event* evt = (Event*)data; + if(!evt) + return 0; + + JSContext* cx = JS_NewContext(ScriptEngine::GetRuntime(), 8192); + JS_SetContextPrivate(cx, evt->owner); + JS_BeginRequest(cx); + + if(evt->owner->IsRunning() && !(evt->owner->GetState() == InGame && ClientState() != ClientStateInGame)) + { + jsval* args = new jsval[evt->argc]; + for(uintN i = 0; i < evt->argc; i++) + { + args[i] = *evt->argv[i]->value(); + if(JS_AddRoot(&args[i]) == JS_FALSE) + { + if(evt->argv) + delete[] evt->argv; + delete evt; + return NULL; + } + } + jsval dummy = JSVAL_VOID; + + for(FunctionList::iterator it = evt->functions.begin(); it != evt->functions.end(); it++) + { + JS_CallFunctionValue(cx, evt->object, *(*it)->value(), evt->argc, args, &dummy); + } + + for(uintN i = 0; i < evt->argc; i++) + JS_RemoveRoot(&args[i]); + delete[] args; + } + + JS_DestroyContextNoGC(cx); + // we have to clean up the event + for(uintN i = 0; i < evt->argc; i++) + { + evt->argv[i]->Release(); + if(evt->argv[i]) + delete evt->argv[i]; + } + if(evt->argv) + delete[] evt->argv; + delete evt; + + return 0; +} diff --git a/Script.h b/Script.h new file mode 100644 index 00000000..3abb2379 --- /dev/null +++ b/Script.h @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include +#include + +#include "js32.h" +#include "JSGlobalClasses.h" +#include "AutoRoot.h" +#include "JSUnit.h" + +enum ScriptState { + InGame, + OutOfGame, + Command +}; + +class Script; + +typedef std::map IncludeList; +typedef std::list FunctionList; +typedef std::map FunctionMap; +typedef std::list ScriptList; + +struct Event { + Script* owner; + JSObject* object; + FunctionList functions; + AutoRoot** argv; + uintN argc; +}; + +class Script +{ +private: + std::string fileName; + int execCount; + ScriptState scriptState; + JSContext* context; + JSScript* script; + myUnit* me; + + JSObject *globalObject, *scriptObject; + bool isLocked, isPaused, isReallyPaused, isAborted; + + IncludeList includes, inProgress; + FunctionMap functions; + HANDLE threadHandle; + DWORD threadId; + CRITICAL_SECTION lock; + + Script(const char* file, ScriptState state); + Script(const Script&); + Script& operator=(const Script&); + ~Script(void); + +public: + friend class ScriptEngine; + + void Run(void); + void Pause(void); + void Resume(void); + bool IsPaused(void); + inline void SetPauseState(bool reallyPaused) { isReallyPaused = reallyPaused; } + inline bool IsReallyPaused(void) { return isReallyPaused; } + void Stop(bool force = false, bool reallyForce = false); + + inline const char* GetFilename(void) { return fileName.c_str(); } + const char* GetShortFilename(void); + inline JSContext* GetContext(void) { return context; } + inline JSObject* GetGlobalObject(void) { return globalObject; } + inline JSObject* GetScriptObject(void) { return scriptObject; } + inline ScriptState GetState(void) { return scriptState; } + int GetExecutionCount(void); + DWORD GetThreadId(void); + // UGLY HACK to fix up the player gid on game join for cached scripts/oog scripts + void UpdatePlayerGid(void); + + bool IsRunning(void); + bool IsAborted(void); + + bool IsIncluded(const char* file); + bool Include(const char* file); + + bool IsListenerRegistered(const char* evtName); + void RegisterEvent(const char* evtName, jsval evtFunc); + bool IsRegisteredEvent(const char* evtName, jsval evtFunc); + void UnregisterEvent(const char* evtName, jsval evtFunc); + void ClearEvent(const char* evtName); + void ClearAllEvents(void); + + void ExecEventAsync(char* evtName, uintN argc, AutoRoot** argv); +}; + +DWORD WINAPI ScriptThread(void* data); +DWORD WINAPI FuncThread(void* data); diff --git a/ScriptEngine.cpp b/ScriptEngine.cpp new file mode 100644 index 00000000..d85f3586 --- /dev/null +++ b/ScriptEngine.cpp @@ -0,0 +1,419 @@ +#include +#include +#include + +#include "ScriptEngine.h" +#include "Core.h" +#include "JSGlobalFuncs.h" +#include "JSGlobalClasses.h" +#include "JSUnit.h" +#include "Constants.h" +#include "D2BS.h" +#include "Console.h" +#include "D2Ptrs.h" + +using namespace std; + +JSRuntime* ScriptEngine::runtime = NULL; +ScriptMap ScriptEngine::scripts = ScriptMap(); +EngineState ScriptEngine::state = Stopped; +CRITICAL_SECTION ScriptEngine::lock = {0}; +JSContext* ScriptEngine::context = NULL; + +// internal ForEachScript helpers +bool __fastcall DisposeScript(Script* script, void*, uint); +bool __fastcall StopScript(Script* script, void* argv, uint argc); +bool __fastcall GCPauseScript(Script* script, void* argv, uint argc); + +Script* ScriptEngine::CompileFile(const char* file, ScriptState state, bool recompile) +{ + if(GetState() != Running) + return NULL; + char* fileName = _strdup(file); + _strlwr_s(fileName, strlen(file)+1); + try + { + EnterCriticalSection(&lock); + if(!Vars.bDisableCache) + { + if(recompile && scripts.count(fileName) > 0) + { + scripts[fileName]->Stop(true, true); + DisposeScript(scripts[fileName]); + } + else if(scripts.count(fileName) > 0) + { + Script* ret = scripts[fileName]; + ret->Stop(true, true); + delete[] fileName; + LeaveCriticalSection(&lock); + return ret; + } + } + Script* script = new Script(fileName, state); + scripts[fileName] = script; + LeaveCriticalSection(&lock); + delete[] fileName; + return script; + } + catch(std::exception e) + { + LeaveCriticalSection(&lock); + Print(const_cast(e.what())); + delete[] fileName; + return NULL; + } +} + +Script* ScriptEngine::CompileCommand(const char* command) +{ + if(GetState() != Running) + return NULL; + try + { + EnterCriticalSection(&lock); + if(!Vars.bDisableCache) + { + if(scripts.count("Command Line") > 0) + { + DisposeScript(scripts["Command Line"]); + } + } + Script* script = new Script(command, Command); + scripts["Command Line"] = script; + LeaveCriticalSection(&lock); + return script; + } + catch(std::exception e) + { + LeaveCriticalSection(&lock); + Print(const_cast(e.what())); + return NULL; + } +} + +void ScriptEngine::DisposeScript(Script* script) +{ + EnterCriticalSection(&lock); + + if(scripts.count(script->GetFilename())) + scripts.erase(script->GetFilename()); + delete script; + + LeaveCriticalSection(&lock); +} + +unsigned int ScriptEngine::GetCount(bool active, bool unexecuted) +{ + if(GetState() != Running) + return 0; + + EnterCriticalSection(&lock); + int count = scripts.size(); + for(ScriptMap::iterator it = scripts.begin(); it != scripts.end(); it++) + { + if(!active && it->second->IsRunning() && !it->second->IsAborted()) + count--; + if(!unexecuted && it->second->GetExecutionCount() == 0 && !it->second->IsRunning()) + count--; + } + assert(count >= 0); + LeaveCriticalSection(&lock); + return count; +} + +BOOL ScriptEngine::Startup(void) +{ + if(GetState() == Stopped) + { + state = Starting; + InitializeCriticalSection(&lock); + EnterCriticalSection(&lock); + // set UTF-8 to enabled--currently not supported, need to recompile spidermonkey + //JS_SetCStringsAreUTF8(); + // create the runtime with the requested memory limit + runtime = JS_NewRuntime(Vars.dwMemUsage); + if(!runtime) + { + LeaveCriticalSection(&lock); + return FALSE; + } + + // create a context for internal use before we set the callback + context = JS_NewContext(runtime, 8192); + JS_SetErrorReporter(context, reportError); + JS_SetBranchCallback(context, branchCallback); + JS_SetOptions(context, JSOPTION_STRICT|JSOPTION_VAROBJFIX|JSOPTION_XML|JSOPTION_NATIVE_BRANCH_CALLBACK); + JS_SetVersion(context, JSVERSION_1_7); + + JS_SetContextCallback(runtime, contextCallback); + JS_SetGCCallbackRT(runtime, gcCallback); + + state = Running; + LeaveCriticalSection(&lock); + } + return TRUE; +} + +void ScriptEngine::Shutdown(void) +{ + if(GetState() == Running) + { + // bring the engine down properly + EnterCriticalSection(&lock); + state = Stopping; + StopAll(true); + + // clear all scripts now that they're stopped + ForEachScript(::DisposeScript, NULL, 0); + + if(!scripts.empty()) + scripts.clear(); + + if(runtime) + { + JS_DestroyContextNoGC(context); + JS_DestroyRuntime(runtime); + JS_ShutDown(); + runtime = NULL; + } + + LeaveCriticalSection(&lock); + DeleteCriticalSection(&lock); + state = Stopped; + } +} + +void ScriptEngine::StopAll(bool forceStop) +{ + if(GetState() != Running) + return; + + EnterCriticalSection(&lock); + + ForEachScript(StopScript, &forceStop, 1); + + LeaveCriticalSection(&lock); +} + +void ScriptEngine::FlushCache(void) +{ + if(GetState() != Running) + return; + + static bool isFlushing = false; + + if(isFlushing || Vars.bDisableCache) + return; + + EnterCriticalSection(&lock); + // TODO: examine if this lock is necessary any more + EnterCriticalSection(&Vars.cFlushCacheSection); + + isFlushing = true; + + ForEachScript(::DisposeScript, NULL, 0); + + isFlushing = false; + + LeaveCriticalSection(&Vars.cFlushCacheSection); + LeaveCriticalSection(&lock); +} + +void ScriptEngine::ForEachScript(ScriptCallback callback, void* argv, uint argc) +{ + if(callback == NULL || scripts.size() < 1) + return; + + EnterCriticalSection(&lock); + + // damn std::list not supporting operator[]... + std::vector list; + for(ScriptMap::iterator it = scripts.begin(); it != scripts.end(); it++) + list.push_back(it->second); + int count = list.size(); + // damn std::iterator not supporting manipulating the list... + for(int i = 0; i < count; i++) + { + if(!callback(list[i], argv, argc)) + break; + } + + LeaveCriticalSection(&lock); +} + +void ScriptEngine::ExecEventAsync(char* evtName, AutoRoot** argv, uintN argc) +{ + if(GetState() != Running) + return; + + EventHelper helper = {evtName, argv, argc}; + ForEachScript(ExecEventOnScript, &helper, 1); +} + +void ScriptEngine::InitClass(JSContext* context, JSObject* globalObject, JSClass* classp, + JSFunctionSpec* methods, JSPropertySpec* props, + JSFunctionSpec* s_methods, JSPropertySpec* s_props) +{ + if(!JS_InitClass(context, globalObject, NULL, classp, classp->construct, 0, props, methods, s_props, s_methods)) + throw std::exception("Couldn't initialize the class"); +} + +void ScriptEngine::DefineConstant(JSContext* context, JSObject* globalObject, const char* name, int value) +{ + if(!JS_DefineProperty(context, globalObject, name, INT_TO_JSVAL(value), NULL, NULL, JSPROP_PERMANENT_VAR)) + throw std::exception("Couldn't initialize the constant"); +} + +// internal ForEachScript helper functions +bool __fastcall DisposeScript(Script* script, void*, uint) +{ + ScriptEngine::DisposeScript(script); + return true; +} + +bool __fastcall StopScript(Script* script, void* argv, uint argc) +{ + script->Stop(*(bool*)(argv), ScriptEngine::GetState() == Stopping); + return true; +} + +bool __fastcall StopIngameScript(Script* script, void*, uint) +{ + if(script->GetState() == InGame) + script->Stop(true); + return true; +} + +bool __fastcall ExecEventOnScript(Script* script, void* argv, uint argc) +{ + EventHelper* helper = (EventHelper*)argv; + if(script->IsListenerRegistered(helper->evtName)) + script->ExecEventAsync(helper->evtName, helper->argc, helper->argv); + return true; +} + +JSBool branchCallback(JSContext* cx, JSScript*) +{ + Script* script = (Script*)JS_GetContextPrivate(cx); + + jsrefcount depth = JS_SuspendRequest(cx); + + bool pause = script->IsPaused(); + + if(pause) + script->SetPauseState(true); + while(script->IsPaused()) + { + Sleep(50); + JS_MaybeGC(cx); + } + if(pause) + script->SetPauseState(false); + + JS_ResumeRequest(cx, depth); + + return !!!(JSBool)(script->IsAborted() || ((script->GetState() == InGame) && ClientState() == ClientStateMenu)); +} + +JSBool contextCallback(JSContext* cx, uintN contextOp) +{ + if(contextOp == JSCONTEXT_NEW) + { + JS_BeginRequest(cx); + + JS_SetErrorReporter(cx, reportError); + JS_SetBranchCallback(cx, branchCallback); + JS_SetOptions(cx, JSOPTION_STRICT|JSOPTION_VAROBJFIX|JSOPTION_XML|JSOPTION_NATIVE_BRANCH_CALLBACK); + JS_SetVersion(cx, JSVERSION_1_7); + + JSObject* globalObject = JS_NewObject(cx, &global_obj, NULL, NULL); + if(!globalObject) + return JS_FALSE; + + if(JS_InitStandardClasses(cx, globalObject) == JS_FALSE) + return JS_FALSE; + if(JS_DefineFunctions(cx, globalObject, global_funcs) == JS_FALSE) + return JS_FALSE; + + myUnit* lpUnit = new myUnit; + memset(lpUnit, NULL, sizeof(myUnit)); + + UnitAny* player = D2CLIENT_GetPlayerUnit(); + lpUnit->dwMode = (DWORD)-1; + lpUnit->dwClassId = (DWORD)-1; + lpUnit->dwType = UNIT_PLAYER; + lpUnit->dwUnitId = player ? player->dwUnitId : NULL; + lpUnit->_dwPrivateType = PRIVATE_UNIT; + + for(JSClassSpec* entry = global_classes; entry->js_class != NULL; entry++) + ScriptEngine::InitClass(cx, globalObject, entry->js_class, entry->funcs, entry->props, + entry->static_funcs, entry->static_props); + + JSObject* meObject = BuildObject(cx, &unit_class_ex.base, unit_methods, me_props, lpUnit); + if(!meObject) + return JS_FALSE; + + if(JS_DefineProperty(cx, globalObject, "me", OBJECT_TO_JSVAL(meObject), NULL, NULL, JSPROP_PERMANENT_VAR) == JS_FALSE) + return JS_FALSE; + +#define DEFCONST(vp) ScriptEngine::DefineConstant(cx, globalObject, #vp, vp) + DEFCONST(FILE_READ); + DEFCONST(FILE_WRITE); + DEFCONST(FILE_APPEND); +#undef DEFCONST + + JS_EndRequest(cx); + } + return JS_TRUE; +} + +JSBool gcCallback(JSContext *cx, JSGCStatus status) +{ + if(status == JSGC_BEGIN) + { +// EnterCriticalSection(&ScriptEngine::lock); +#ifdef DEBUG + Log("*** ENTERING GC ***"); +#ifdef lord2800_INFO + Print("*** ENTERING GC ***"); +#endif +#endif + } + else if(status == JSGC_END) + { +#ifdef DEBUG + Log("*** LEAVING GC ***"); +#ifdef lord2800_INFO + Print("*** LEAVING GC ***"); +#endif +#endif +// LeaveCriticalSection(&ScriptEngine::lock); + } + return JS_TRUE; +} + +void reportError(JSContext *cx, const char *message, JSErrorReport *report) +{ + bool warn = JSREPORT_IS_WARNING(report->flags); + bool isStrict = JSREPORT_IS_STRICT(report->flags); + const char* type = (warn ? "Warning" : "Error"); + const char* strict = (isStrict ? "Strict " : ""); + char* filename = report->filename ? _strdup(report->filename) : _strdup(""); + char* displayName = filename; + if(_stricmp("Command Line", filename) != 0 && _stricmp("", filename) != 0) + displayName = filename + strlen(Vars.szPath); + + Log("[%s%s] Code(%d) File(%s:%d) %s\nLine: %s", + strict, type, report->errorNumber, filename, report->lineno, message, report->linebuf); + + Print("[ÿc%d%s%sÿc0 (%d)] File(%s:%d) %s", + (warn ? 9 : 1), strict, type, report->errorNumber, displayName, report->lineno, message); + + free(filename); + + if(Vars.bQuitOnError && !JSREPORT_IS_WARNING(report->flags) && ClientState() == ClientStateInGame) + D2CLIENT_ExitGame(); + else + Console::ShowBuffer(); +} diff --git a/ScriptEngine.h b/ScriptEngine.h new file mode 100644 index 00000000..acfc8c58 --- /dev/null +++ b/ScriptEngine.h @@ -0,0 +1,84 @@ +#pragma once +#ifndef __SCRIPTENGINE_H__ +#define __SCRIPTENGINE_H__ + +#include +#include +#include + +#include "js32.h" +#include "AutoRoot.h" +#include "Script.h" + +typedef std::map ScriptMap; + +typedef bool (__fastcall *ScriptCallback)(Script*, void*, uint); + +enum EngineState { + Starting, + Running, + Paused, + Stopping, + Stopped +}; + +class ScriptEngine +{ + ScriptEngine(void) {}; + virtual ~ScriptEngine(void) = 0; + ScriptEngine(const ScriptEngine&); + ScriptEngine& operator=(const ScriptEngine&); + + static JSRuntime* runtime; + static JSContext* context; + static ScriptMap scripts; + static EngineState state; + static CRITICAL_SECTION lock; + +public: + friend class Script; + + static BOOL Startup(void); + static void Shutdown(void); + static EngineState GetState(void) { return state; } + + static void FlushCache(void); + + static Script* CompileFile(const char* file, ScriptState state, bool recompile = false); + static Script* CompileCommand(const char* command); + static void DisposeScript(Script* script); + + static void ForEachScript(ScriptCallback callback, void* argv, uint argc); + static unsigned int GetCount(bool active = true, bool unexecuted = false); + + static JSRuntime* GetRuntime(void) { return runtime; } + static JSContext* GetGlobalContext(void) { return context; } + + static void StopAll(bool forceStop = false); + static void ExecEventAsync(char* evtName, AutoRoot** argv, uintN argc); + static void InitClass(JSContext* context, JSObject* globalObject, JSClass* classp, + JSFunctionSpec* methods, JSPropertySpec* props, + JSFunctionSpec* s_methods, JSPropertySpec* s_props); + static void DefineConstant(JSContext* context, JSObject* globalObject, const char* name, int value); + + friend JSBool gcCallback(JSContext* cx, JSGCStatus status); +}; + +// these ForEachScript helpers are exposed in case they can be of use somewhere +bool __fastcall StopIngameScript(Script* script, void*, uint); +bool __fastcall ExecEventOnScript(Script* script, void* argv, uint argc); +struct EventHelper +{ + char* evtName; + AutoRoot** argv; + uintN argc; + bool executed; +}; + +JSBool branchCallback(JSContext* cx, JSScript* script); +JSBool contextCallback(JSContext* cx, uintN contextOp); +JSBool gcCallback(JSContext* cx, JSGCStatus status); +void reportError(JSContext *cx, const char *message, JSErrorReport *report); + +#endif + diff --git a/SyncObj.h b/SyncObj.h new file mode 100644 index 00000000..713bc487 --- /dev/null +++ b/SyncObj.h @@ -0,0 +1,39 @@ +////////////////////////////////////////////////////////////////////// +// SyncObj.h +// +// Abin (abinn32@yahoo.com) +////////////////////////////////////////////////////////////////////// + +#ifndef __SYNCOBJ_H__ +#define __SYNCOBJ_H__ + +#include +#include + +class CSyncObj +{ +public: + + ///////////////////////////////////////////////////////////////// + // Constructor & Destructor + ///////////////////////////////////////////////////////////////// + CSyncObj() { ::InitializeCriticalSection(&m_cs); IsLocked = false;} + virtual ~CSyncObj() { ::DeleteCriticalSection(&m_cs); } + + ///////////////////////////////////////////////////////////////// + // Public Operations + ///////////////////////////////////////////////////////////////// + void Lock() { /* ::EnterCriticalSection((LPCRITICAL_SECTION)&m_cs); */ IsLocked = true; } + void Unlock() { /* ::LeaveCriticalSection((LPCRITICAL_SECTION)&m_cs);*/ IsLocked = false; } + + bool IsLocked; + +private: + + ///////////////////////////////////////////////////////////////// + // Private Member Data + ///////////////////////////////////////////////////////////////// + CRITICAL_SECTION m_cs; +}; + +#endif // __SYNCOBJ_H__ diff --git a/TeleportPath.cpp b/TeleportPath.cpp new file mode 100644 index 00000000..49788303 --- /dev/null +++ b/TeleportPath.cpp @@ -0,0 +1,240 @@ +/////////////////////////////////////////////////////////// +// TeleportPath.cpp +// +// Abin (abinn32@yahoo.com) +/////////////////////////////////////////////////////////// + +#include + +#include "TeleportPath.h" +#include "Common.h" + +#define RANGE_INVALID 10000 // invalid range flag +int TP_RANGE = 35; + +///////////////////////////////////////////////////////////////////// +// Path Finding Result +///////////////////////////////////////////////////////////////////// +enum { PATH_FAIL = 0, // Failed, error occurred or no available path + PATH_CONTINUE, // Path OK, destination not reached yet + PATH_REACHED }; // Path OK, destination reached(Path finding completed successfully) + + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +CTeleportPath::CTeleportPath(WORD** pCollisionMap, int cx, int cy) +{ + m_ppTable = pCollisionMap; + m_nCX = cx; + m_nCY = cy; + ::memset(&m_ptStart, 0, sizeof(POINT)); + ::memset(&m_ptEnd, 0, sizeof(POINT)); +} + +CTeleportPath::~CTeleportPath() +{ +} + +BOOL CTeleportPath::MakeDistanceTable() +{ + if (m_ppTable == NULL) + return FALSE; + + // convert the graph into a distance table + for (int x = 0; x < m_nCX; x++) + { + for (int y = 0; y < m_nCY; y++) + { + if ((m_ppTable[x][y] % 2) == 0) + m_ppTable[x][y] = (short)CalculateDistance(x, y, m_ptEnd.x, m_ptEnd.y); + else + m_ppTable[x][y] = RANGE_INVALID; + } + } + + m_ppTable[m_ptEnd.x][m_ptEnd.y] = 1; + return TRUE; +} + +///////////////////////////////////////////////////////////////////// +// The "Get Best Move" Algorithm +// +// Originally developed by Niren7, Modified by Abin +///////////////////////////////////////////////////////////////////// +BOOL CTeleportPath::GetBestMove(POINT& pos, int nAdjust) +{ + if(CalculateDistance(m_ptEnd, pos) <= TP_RANGE) + { + pos = m_ptEnd; + return PATH_REACHED; // we reached the destination + } + + if (!IsValidIndex(pos.x, pos.y)) + return PATH_FAIL; // fail + + Block(pos, nAdjust); + + POINT p, best = {0}; + int value = RANGE_INVALID; + + for (p.x = pos.x - TP_RANGE; p.x <= pos.x + TP_RANGE; p.x++) + { + for (p.y = pos.y - TP_RANGE; p.y <= pos.y + TP_RANGE; p.y++) + { + if (!IsValidIndex(p.x, p.y)) + continue; + + if (m_ppTable[p.x][p.y] < value && CalculateDistance(p, pos) <= TP_RANGE) + { + value = m_ppTable[p.x][p.y]; + best = p; + } + } + } + + if (value >= RANGE_INVALID) + return PATH_FAIL; // no path at all + + pos = best; + Block(pos, nAdjust); + return PATH_CONTINUE; // ok but not reached yet +} + +DWORD CTeleportPath::FindTeleportPath(POINT ptStart, POINT ptEnd, LPPOINT lpBuffer, DWORD dwMaxCount, int Range) +{ + + if (lpBuffer == NULL || dwMaxCount == 0 || m_nCX <= 0 || m_nCY <= 0 || m_ppTable == NULL) + return 0; + + unsigned int oldRange = TP_RANGE; + TP_RANGE = Range; + + memset(lpBuffer, 0, sizeof(POINT) * dwMaxCount); + m_ptStart = ptStart; + m_ptEnd = ptEnd; + + //GameInfof("start %d %d End %d %d", ptStart.x, ptStart.y, ptEnd.x, ptEnd.y); + + MakeDistanceTable(); + //DumpDistanceTable("c:\\map2.txt"); + + lpBuffer[0] = ptStart; // start point + DWORD dwFound = 1; + + POINT pos = ptStart; + + BOOL bOK = FALSE; + int nRes = GetBestMove(pos); + while (nRes != PATH_FAIL && dwFound < dwMaxCount) + { + // Reached? + if (nRes == PATH_REACHED) + { + bOK = TRUE; + lpBuffer[dwFound] = ptEnd; + dwFound++; + break; // Finished + } + + // Perform a redundancy check + int nRedundancy = GetRedundancy(lpBuffer, dwFound, pos); + if (nRedundancy == -1) + { + // no redundancy + lpBuffer[dwFound] = pos; + dwFound++; + } + else + { + // redundancy found, discard all redundant steps + dwFound = nRedundancy + 1; + lpBuffer[dwFound] = pos; + } + + nRes = GetBestMove(pos); + } + + if (!bOK) + dwFound = 0; + + TP_RANGE = oldRange; + return dwFound; +} + +void CTeleportPath::Block(POINT pos, int nRange) +{ + nRange = max(nRange, 1); + + for (int i = pos.x - nRange; i < pos.x + nRange; i++) + { + for (int j = pos.y - nRange; j < pos.y + nRange; j++) + { + if (IsValidIndex(i, j)) + m_ppTable[i][j] = RANGE_INVALID; + } + } +} + +int CTeleportPath::GetRedundancy(const LPPOINT lpPath, DWORD dwMaxCount, const POINT &pos) +{ + // step redundancy check + if (lpPath == NULL || dwMaxCount == 0) + return -1; + + for (DWORD i = 1; i < dwMaxCount; i++) + { + if (CalculateDistance(lpPath[i].x, lpPath[i].y, pos.x, pos.y) <= TP_RANGE / 2) + return i; + } + + return -1; +} + +BOOL CTeleportPath::IsValidIndex(int x, int y) const +{ + return x >= 0 && x < m_nCX && y >= 0 && y < m_nCY; +} + +BOOL CTeleportPath::DumpDistanceTable(LPCSTR lpszFilePath) const +{ + if (lpszFilePath == NULL || m_ppTable == NULL) + return FALSE; + + FILE *fp = NULL; + fopen_s(&fp, lpszFilePath, "w+"); + if(fp == NULL ) + return FALSE; + + for (int y = 0; y < m_nCY; y++) + { + for (int x = 0; x < m_nCX; x++) + { + if (m_ptStart.x == x && m_ptStart.y == y) + { + fprintf(fp, "%s ", "St"); + } + else if (m_ptEnd.x == x && m_ptEnd.y == y) + { + fprintf(fp, "%s ", "En"); + } + else + { + short iDis = m_ppTable[x][y]; + + if (iDis == RANGE_INVALID) + fprintf(fp, "%s ", " "); + else if (iDis >= 255) + fprintf(fp, "%s ", "??"); + else + fprintf(fp, "%02X ", iDis); + } + } + + fprintf(fp, "%c", '\n'); + } + + fclose(fp); + return TRUE; +} diff --git a/TeleportPath.h b/TeleportPath.h new file mode 100644 index 00000000..4fbf5dd1 --- /dev/null +++ b/TeleportPath.h @@ -0,0 +1,45 @@ +////////////////////////////////////////////////////////////////////// +// TeleportPath.h +// +// Diablo II game path finding(teleport) algorithms. +// +// I must give credits to both Niren7 and Ninjai, their code helped me +// start this class to say the least. +// +// Ustc_tweeg also helped me a lot on completing this algorithm. +// +// Written by Abin(abinn32@yahoo.com) +// Sep 10th, 2004 +//////////////////////////////////////////////////////////////////////// + +#ifndef __TELEPORTPATH_H__ +#define __TELEPORTPATH_H__ + +#include + +class CTeleportPath +{ +public: + + CTeleportPath(WORD** pCollisionMap, int cx, int cy); + virtual ~CTeleportPath(); + + DWORD FindTeleportPath(POINT ptStart, POINT ptEnd, LPPOINT lpBuffer, DWORD dwMaxCount, int Range); // Calculate path + +private: + + BOOL DumpDistanceTable(LPCSTR lpszFilePath) const; + static int GetRedundancy(const LPPOINT lpPath, DWORD dwMaxCount, const POINT& pos); + void Block(POINT pos, int nRange); + BOOL GetBestMove(POINT& rResult, int nAdjust = 2); + BOOL MakeDistanceTable(); + BOOL IsValidIndex(int x, int y) const; + + WORD** m_ppTable; // Distance table + POINT m_ptStart; + POINT m_ptEnd; + int m_nCX; + int m_nCY; +}; + +#endif // __TELEPORTPATH_H__ diff --git a/TimedAlloc.h b/TimedAlloc.h new file mode 100644 index 00000000..fc56abd8 --- /dev/null +++ b/TimedAlloc.h @@ -0,0 +1,129 @@ +#pragma once + +#include + +template > class TimedAlloc; + +template <> class TimedAlloc +{ +public: + typedef void* pointer; + typedef const void* const_pointer; + typedef void value_type; + template struct rebind { typedef TimedAlloc other; }; +}; + +template +class TimedAlloc +{ +private: + Alloc allocator; + int allocs, deallocs, ctors, dtors; + double alloctime, dealloctime, ctortime, dtortime; + +public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef T* pointer; + typedef const T* const_pointer; + typedef T& reference; + typedef const T& const_reference; + typedef T value_type; + + template struct rebind { typedef TimedAlloc other; }; + + pointer address(reference x) const { return &x; } + const_pointer address(const_reference x) const { return &x; } + + TimedAlloc() : allocs(0), deallocs(0), ctors(0), dtors(0), + alloctime(0), dealloctime(0), ctortime(0), dtortime(0), allocator(Alloc()) {} + template TimedAlloc(const TimedAlloc&){} + ~TimedAlloc() {} + size_type max_size() const throw() { return allocator.max_size(); } + + pointer allocate(size_type count, const_pointer hint = 0) + { + allocs++; + LARGE_INTEGER start, end; + + QueryPerformanceCounter(&start); + pointer result = static_cast(allocator.allocate(count, hint)); + QueryPerformanceCounter(&end); + + alloctime += end.QuadPart - start.QuadPart; + return result; + } + void deallocate(pointer p, size_type n) + { + deallocs++; + LARGE_INTEGER start, end; + + QueryPerformanceCounter(&start); + allocator.deallocate(p, n); + QueryPerformanceCounter(&end); + + dealloctime += end.QuadPart - start.QuadPart; + } + + void construct(pointer p, const T& value) + { + ctors++; + LARGE_INTEGER start, end; + + QueryPerformanceCounter(&start); + new(static_cast(p)) T(value); + QueryPerformanceCounter(&end); + + ctortime += end.QuadPart - start.QuadPart; + } + void construct(pointer p) + { + ctors++; + LARGE_INTEGER start, end; + + QueryPerformanceCounter(&start); + new(static_cast(p)) T(); + QueryPerformanceCounter(&end); + + ctortime += end.QuadPart - start.QuadPart; + } + void destroy(pointer p) + { + dtors++; + LARGE_INTEGER start, end; + + QueryPerformanceCounter(&start); + p->~T(); + QueryPerformanceCounter(&end); + + dtortime += end.QuadPart - start.QuadPart; + } + + void DumpStats(FILE* f) const + { + LARGE_INTEGER totalfreq; + QueryPerformanceFrequency(&totalfreq); + double freq = (double)(totalfreq.QuadPart / 1000); + + double realalloctime = (alloctime / freq), + realdealloctime = (dealloctime / freq), + realctortime = (ctortime / freq), + realdtortime = (dtortime / freq), + allocperpsec = (allocs == 0 ? 0 : realalloctime*1000 / allocs), + deallocperpsec = (deallocs == 0 ? 0 : realdealloctime*1000 / deallocs), + ctorperobj = (ctors == 0 ? 0 : realctortime*1000 / ctors), + dtorperobj = (dtors == 0 ? 0 : realdtortime*1000 / dtors); + + fprintf(f, "Allocations: %d, Deallocations: %d, Objects constructed: %d, Objects destructed: %d\n" + "Time spent allocating: %gms (%f microseconds/alloc), Time spent deallocating: %gms (%f microseconds/dealloc)\n" + "Time spent constructing: %gms (%f microseconds/ctor), Time spent destructing: %gms (%f microseconds/dtor)\n", + allocs, deallocs, ctors, dtors, + realalloctime, allocperpsec, realdealloctime, deallocperpsec, + realctortime, realdtortime, ctorperobj, dtorperobj); + } +}; + +template +inline bool operator==(const TimedAlloc&, const TimedAlloc&) { return true; } +template +inline bool operator!=(const TimedAlloc&, const TimedAlloc&) { return false; } diff --git a/Unit.cpp b/Unit.cpp new file mode 100644 index 00000000..2567905b --- /dev/null +++ b/Unit.cpp @@ -0,0 +1,324 @@ +#include + +#include "Unit.h" +#include "Constants.h" +#include "D2Helpers.h" +#include "D2BS.h" + +#define HAS_BIT(value, bit) ((((value) >> (bit)) & 0x1) == 0x1) + +using namespace std; + +// TODO: If UnitId is the unique id of the unit, we can just look up that +// location in the table +static UnitAny* GetUnitFromTables(UnitHashTable* unitTables, DWORD dwTypeLow, + DWORD dwTypeHigh, char* szName, DWORD dwClassId, DWORD dwType, DWORD dwMode, + DWORD dwUnitId) +{ + unsigned int i, j; + unsigned int hashLow, hashHigh; + UnitAny* tmpUnit; + + if(dwUnitId != -1) + hashLow = hashHigh = dwUnitId & 0x7F; // % 128 + else + { + hashLow = 0; + hashHigh = 127; + } + + // Go through all the types + for(i = dwTypeLow; i <= dwTypeHigh; ++i) + { + // Go through all the hash values + for(j = hashLow; j <= hashHigh; ++j) + { + // Go through all the units in a given hash value + for(tmpUnit = unitTables[i].table[j]; tmpUnit != NULL; + tmpUnit = tmpUnit->pListNext) + // Check if it matches + if(CheckUnit(tmpUnit, szName, dwClassId, dwType, dwMode, + dwUnitId)) + return tmpUnit; + } + } + + return NULL; +} + +UnitAny* GetUnit(char* szName, DWORD dwClassId, DWORD dwType, DWORD dwMode, + DWORD dwUnitId) +{ + if(ClientState() != ClientStateInGame) + return NULL; + + // If we have a valid type, just check that value, other wise, check all + // values. There are 6 valid types, 0-5 + if(dwType == 3) + return GetUnitFromTables(p_D2CLIENT_ClientSideUnitHashTables, dwType, + dwType, szName, dwClassId, dwType, dwMode, dwUnitId); + + if(dwType >= 0 && dwType <= 5) + return GetUnitFromTables(p_D2CLIENT_ServerSideUnitHashTables, dwType, + dwType, szName, dwClassId, dwType, dwMode, dwUnitId); + else + return GetUnitFromTables(p_D2CLIENT_ServerSideUnitHashTables, 0, 5, + szName, dwClassId, dwType, dwMode, dwUnitId); + + +/* EnterCriticalSection(&Vars.cUnitListSection); + + UnitAny* result = NULL; + for(vector >::iterator it = Vars.vUnitList.begin(); it != Vars.vUnitList.end(); it++) + { + UnitAny* unit = D2CLIENT_FindUnit(it->first, it->second); + if(unit != NULL && CheckUnit(unit, szName, dwClassId, dwType, dwMode, dwUnitId)) + { + result = unit; + break; + } + } + + LeaveCriticalSection(&Vars.cUnitListSection); + + return result;*/ + + // First off, check for near units +/* UnitAny* player = D2CLIENT_GetPlayerUnit(); + if(player && player->pPath && player->pPath->pRoom1 && player->pPath->pRoom1->pRoom2 && + player->pPath->pRoom1->pRoom2->pLevel) + { + Room2* ptRoomOther = player->pPath->pRoom1->pRoom2->pLevel->pRoom2First; + + for(;ptRoomOther; ptRoomOther = ptRoomOther->pRoom2Next) + { + if(!ptRoomOther->pRoom1) + continue; + for(UnitAny* lpUnit = ptRoomOther->pRoom1->pUnitFirst; lpUnit; lpUnit = lpUnit->pListNext) + { + if(CheckUnit(lpUnit, szName, dwClassId, dwType, dwMode, dwUnitId)) + return lpUnit; + } + } + } + + return NULL;*/ +} + +static DWORD dwMax(DWORD a, DWORD b) +{ + return a > b ? a : b; +} + +static UnitAny* GetNextUnitFromTables(UnitAny* curUnit, + UnitHashTable* unitTables, DWORD dwTypeLow, DWORD dwTypeHigh, char* szName, + DWORD dwClassId, DWORD dwType, DWORD dwMode) +{ + unsigned int i, j; + UnitAny* tmpUnit; + + // If we're looking for the same type unit, or any type then finish off the + // current inner iterations + if(dwType == -1 || dwType == curUnit->dwType) + { + i = curUnit->dwType; + + // Finish off the current linked list + for(tmpUnit = curUnit->pListNext; tmpUnit != NULL; tmpUnit = tmpUnit->pListNext) + // Check if it matches + if(CheckUnit(tmpUnit, szName, dwClassId, dwType, dwMode, (DWORD)-1)) + return tmpUnit; + + // Finish off the current hash table + for(j = (curUnit->dwUnitId & 0x7f) + 1; j <= 127; ++j) + // Go through all the units in this linked list + for(tmpUnit = unitTables[i].table[j]; tmpUnit != NULL; + tmpUnit = tmpUnit->pListNext) + // Check if it matches + if(CheckUnit(tmpUnit, szName, dwClassId, dwType, dwMode, + (DWORD)-1)) + return tmpUnit; + } + + // Go through all the remaining types + for(i = dwMax(dwTypeLow, curUnit->dwType + 1); i <= dwTypeHigh; ++i) + { + // Go through all the hash values + for(j = 0; j < 127; ++j) + { + // Go through all the units in a given hash value + for(tmpUnit = unitTables[i].table[j]; tmpUnit != NULL; + tmpUnit = tmpUnit->pListNext) + // Check if it matches + if(CheckUnit(tmpUnit, szName, dwClassId, dwType, dwMode, + (DWORD)-1)) + return tmpUnit; + } + } + + return NULL; +} + +UnitAny* GetNextUnit(UnitAny* pUnit, char* szName, DWORD dwClassId, + DWORD dwType, DWORD dwMode) +{ + if(ClientState() != ClientStateInGame) + return NULL; + + if(!pUnit) + return NULL; + + if(dwType >= 0 && dwType <= 5) + return GetNextUnitFromTables(pUnit, p_D2CLIENT_ServerSideUnitHashTables, + dwType, dwType, szName, dwClassId, dwType, dwMode); + else + return GetNextUnitFromTables(pUnit, p_D2CLIENT_ServerSideUnitHashTables, + 0, 5, szName, dwClassId, dwType, dwMode); + +/* EnterCriticalSection(&Vars.cUnitListSection); + + UnitAny* result = NULL; + // find where we left off + vector >::iterator it = Vars.vUnitList.begin(); + for(; it != Vars.vUnitList.end(); it++) + { + if(it->first == pUnit->dwUnitId && it->second == pUnit->dwType) + // this is where we left off + break; + } + + if(it != Vars.vUnitList.end()) + { + it++; + + for(; it != Vars.vUnitList.end(); it++) + { + UnitAny* unit = D2CLIENT_FindUnit(it->first, it->second); + if(unit != NULL && CheckUnit(unit, szName, dwClassId, dwType, dwMode, (DWORD)-1)) + { + result = unit; + break; + } + } + } + + LeaveCriticalSection(&Vars.cUnitListSection); + + return result;*/ + +/* UnitAny* lpUnit = pUnit->pListNext; + Room1* ptRoom = D2COMMON_GetRoomFromUnit(pUnit); + Room2* ptRoomOther = NULL; + + if(ptRoom) + { + ptRoomOther = ptRoom->pRoom2; + + if(!lpUnit && ptRoomOther) + ptRoomOther = ptRoomOther->pRoom2Next; + + for(; ptRoomOther; ptRoomOther = ptRoomOther->pRoom2Next) + { + if(ptRoomOther->pRoom1) + { + if(!lpUnit) + lpUnit = ptRoomOther->pRoom1->pUnitFirst; + + for(; lpUnit; lpUnit = lpUnit->pListNext) + { + if(CheckUnit(lpUnit, szName, dwClassId, dwType, dwMode, (DWORD)-1)) + return lpUnit; + } + } + } + } + + return NULL;*/ +} + +UnitAny* GetInvUnit(UnitAny* pOwner, char* szName, DWORD dwClassId, DWORD dwMode, DWORD dwUnitId) +{ + for(UnitAny* pItem = D2COMMON_GetItemFromInventory(pOwner->pInventory); pItem; pItem = D2COMMON_GetNextItemFromInventory(pItem)) + { + if(CheckUnit(pItem, szName, dwClassId, 4, dwMode, dwUnitId)) + return pItem; + } + + return NULL; +} + +UnitAny* GetInvNextUnit(UnitAny* pUnit, UnitAny* pOwner, char* szName, DWORD dwClassId, DWORD dwMode) +{ + if(pUnit->dwType == UNIT_ITEM) + { + // Check first if it belongs to a person + if(pUnit->pItemData && pUnit->pItemData->pOwnerInventory && pUnit->pItemData->pOwnerInventory == pOwner->pInventory) + { + // Get the next matching unit from the owner's inventory + for(UnitAny* pItem = D2COMMON_GetNextItemFromInventory(pUnit); pItem; pItem = D2COMMON_GetNextItemFromInventory(pItem)) + { + if(CheckUnit(pItem, szName, dwClassId, 4, dwMode, (DWORD)-1)) + return pItem; + } + + } + } + + return NULL; +} + +BOOL CheckUnit(UnitAny* pUnit, char* szName, DWORD dwClassId, DWORD dwType, DWORD dwMode, DWORD dwUnitId) +{ + if((dwUnitId != -1 && pUnit->dwUnitId != dwUnitId) || + (dwType != -1 && pUnit->dwType != dwType) || + (dwClassId != -1 && pUnit->dwTxtFileNo != dwClassId)) + return FALSE; + + if(dwMode != -1) + { + if(dwMode >= 100 && pUnit->dwType == UNIT_ITEM) + { + if(pUnit->pItemData && dwMode-100 != pUnit->pItemData->ItemLocation) + return FALSE; + } + else + { + if(HAS_BIT(dwMode, 29)) + { + bool result = false; + // mode is a mask + for(unsigned int i = 0; i < 28; i++) + if(HAS_BIT(dwMode, i) && pUnit->dwMode == i) + result = true; + if(!result) + return FALSE; + } + else if(pUnit->dwMode != dwMode) + return FALSE; + } + } + + if(szName && szName[0]) + { + char szBuf[512] = ""; + + if(dwType == UNIT_ITEM) + GetItemCode(pUnit, szBuf); + else + GetUnitName(pUnit, szBuf, 512); + if(!!_stricmp(szBuf, szName)) + return FALSE; + } + + return TRUE; +} + +int GetUnitHP(UnitAny* pUnit) +{ + return (int)(D2COMMON_GetUnitStat(pUnit, STAT_HP, 0) >> 8); +} + +int GetUnitMP(UnitAny* pUnit) +{ + return (int)(D2COMMON_GetUnitStat(pUnit, STAT_MANA, 0) >> 8); +} diff --git a/Unit.h b/Unit.h new file mode 100644 index 00000000..6940ae17 --- /dev/null +++ b/Unit.h @@ -0,0 +1,11 @@ +#pragma once + +#include "D2Ptrs.h" + +UnitAny* GetUnit(char* szName, DWORD dwClassId, DWORD dwType, DWORD dwMode, DWORD dwUnitId); +UnitAny* GetNextUnit(UnitAny* pUnit, char* szName, DWORD dwClassId, DWORD dwType, DWORD dwMode); +UnitAny* GetInvUnit(UnitAny* pOwner, char* szName, DWORD dwClassId, DWORD dwMode, DWORD dwUnitId); +UnitAny* GetInvNextUnit(UnitAny* pUnit, UnitAny* pOwner, char* szName, DWORD dwClassId, DWORD dwMode); +BOOL CheckUnit(UnitAny* pUnit, char* szName, DWORD dwClassId, DWORD dwType, DWORD dwMode, DWORD dwUnitId); +int GetUnitHP(UnitAny* pUnit); +int GetUnitMP(UnitAny* pUnit); diff --git a/WalkPath.cpp b/WalkPath.cpp new file mode 100644 index 00000000..f2d87ce7 --- /dev/null +++ b/WalkPath.cpp @@ -0,0 +1,485 @@ +///////////////////////////////////////////////////////////////////// +// +// WalkPath.cpp +// +// Ustc_tweeg < ustc_tweeg@tom.com > +// +///////////////////////////////////////////////////////////////////// + +#include "WalkPath.h" +#include "Common.h" + +// #define __SHOW_DEBUG_INFO__ // comment this line if you do not want to output debug messages + +#ifndef __SHOW_DEBUG_INFO__ + #define __PRINTF DummyMsg +#else + #ifndef __IN_DIABLOII__ + #define __PRINTF printf + #else + #define __PRINTF Print + #endif +#endif + +#define STRAIGHTEN_A 6 +#define STRAIGHTEN_B 3 +#define STRAIGHTEN_C 2 +unsigned int MAX_WALK_RANGE = 15; + +struct DIRECT2DATA +{ + BOOL bDirect; + const CWalkPath* pClass; + CArrayEx* pSubPath; +}; + +// deta-x, deta-y, counterclockwise, clockwise, right-wall-next-point, left-wall-next-point + +static const int Nearby[8][6] = { { 1, 0, 1, 7, 6, 2 }, + { 1, 1, 2, 0, 0, 2 }, + { 0, 1, 3, 1, 0, 4 }, + {-1, 1, 4, 2, 2, 4 }, + {-1, 0, 5, 3, 2, 6 }, + {-1,-1, 6, 4, 4, 6 }, + { 0,-1, 7, 5, 4, 0 }, + { 1,-1, 0, 6, 6, 0 } }; + + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +int DummyMsg(LPCSTR lpszFmt, ...) +{ + return 0; // silent to screen messages +} + + +CWalkPath::CWalkPath(WORD** Map, int MapSizeX, int MapSizeY) +{ + + m_Map = Map; + + m_MapSizeX = MapSizeX; + m_MapSizeY = MapSizeY; + + m_Count = 0; + + m_FollowWallSuccess = TRUE; +} + +CWalkPath::~CWalkPath() +{ + +} + +/////////////////////////////////////////////////////////////////////// +// Private Functions +/////////////////////////////////////////////////////////////////////// + +BOOL CWalkPath::IsBorder(POINT pt) +{ + return ( pt.x<0 || pt.y<0 || pt.x >= m_MapSizeX || pt.y >= m_MapSizeY); +} + +BOOL CWalkPath::IsBarrier(POINT pt) const +{ + return (m_Map[pt.x][pt.y] % 2); +} + +void CWalkPath::FollowTheRope(POINT Dot) +{ + ContinuousPath.Add(Dot); +} + +BOOL CWalkPath::FollowTheWall(BOOL RightWall, POINT FollowEnd) +{ + POINT NearbyC,NearbyA, NearbyB,TempCurrent; + int m,n; // follow-right-wall-nearbya, follow-left-wall-nearbya + TempCurrent.x = TempCurrent.y = 0; + + if(RightWall) + { + //__PRINTF("right current %d %d\n" , m_RCurrent.x,m_RCurrent.y); + m = m_RStart; + for(int i=0; i<8; i++) + { + NearbyC.x = m_RCurrent.x + Nearby [Nearby[m][2]] [0]; + NearbyC.y = m_RCurrent.y + Nearby [Nearby[m][2]] [1]; + NearbyA.x = m_RCurrent.x + Nearby [m] [0]; + NearbyA.y = m_RCurrent.y + Nearby [m] [1]; + NearbyB.x = m_RCurrent.x + Nearby [Nearby[m][3]] [0]; + NearbyB.y = m_RCurrent.y + Nearby [Nearby[m][3]] [1]; + + if( NearbyA.x == FollowEnd.x && NearbyA.y == FollowEnd.y) return true; + + //__PRINTF("right nearbya %d %d\n" , NearbyA.x,NearbyA.y); + + if( !(IsBorder(NearbyA) || IsBarrier(NearbyA)) + && ( IsBorder(NearbyB) || IsBarrier(NearbyB)) ) + { + if(!TempCurrent.x && !TempCurrent.y) + { + TempCurrent = NearbyA; + + if(!(IsBorder(NearbyC) || IsBarrier(NearbyC))) + RightWallPath.Add(NearbyC); + else + RightWallPath.Add(NearbyA); + + m_RStart = Nearby[m][4]; + } + } + m = Nearby[m][2]; + } + m_RCurrent = TempCurrent; + TempCurrent.x = TempCurrent.y = 0; + } + else + { + n = m_LStart; + //__PRINTF("left current %d %d\n" , m_LCurrent.x,m_LCurrent.y); + for(int i=0; i<8; i++) + { + NearbyC.x = m_LCurrent.x + Nearby [Nearby[n][3]] [0]; + NearbyC.y = m_LCurrent.y + Nearby [Nearby[n][3]] [1]; + NearbyA.x = m_LCurrent.x + Nearby [n] [0]; + NearbyA.y = m_LCurrent.y + Nearby [n] [1]; + NearbyB.x = m_LCurrent.x + Nearby [Nearby[n][2]] [0]; + NearbyB.y = m_LCurrent.y + Nearby [Nearby[n][2]] [1]; + + if( NearbyA.x == FollowEnd.x && NearbyA.y == FollowEnd.y) return true; + + //__PRINTF("left nearbya %d %d\n" , NearbyA.x,NearbyA.y); + if( !(IsBorder(NearbyA) || IsBarrier(NearbyA)) + && ( IsBorder(NearbyB) || IsBarrier(NearbyB))) + { + if(!TempCurrent.x && !TempCurrent.y) + { + TempCurrent = NearbyA; + + if(!(IsBorder(NearbyC) || IsBarrier(NearbyC))) + LeftWallPath.Add(NearbyC); + else + LeftWallPath.Add(NearbyA); + m_LStart = Nearby[n][5]; + } + } + n = Nearby[n][3]; + } + m_LCurrent = TempCurrent; + TempCurrent.x = TempCurrent.y = 0; + + } + return false; +} + +void CALLBACK CWalkPath::FindPathProc(int x, int y, LPARAM pWp) +{ + CWalkPath* p = (CWalkPath*)pWp; + + POINT TempPoint; + TempPoint.x = x; + TempPoint.y = y; + + if( p->IsBarrier(TempPoint) && !p->IsBarrier(p->m_LastLineDot) && p->m_FollowWallSuccess ) + { + p->m_Seperate = p->m_LastLineDot; + for(int i=0; i<8; i++) + { + if((TempPoint.x- p->m_LastLineDot.x)==Nearby[i][0] + && (TempPoint.y- p->m_LastLineDot.y)==Nearby[i][1]) + p->m_LStart = p->m_RStart = i; + } + __PRINTF("seperate x=%d y=%d\n",p->m_Seperate.x,p->m_Seperate.y); + } + else if(!p->IsBarrier(TempPoint) ) + { + if( p->IsBarrier(p->m_LastLineDot)) + { + p->m_Meet = TempPoint; + __PRINTF("meet x=%d y=%d\n",p->m_Meet.x,p->m_Meet.y); + p->m_LCurrent = p->m_RCurrent = p->m_Seperate; + p->SaveFollowWallPath(); + } + if(p->m_FollowWallSuccess) p->FollowTheRope(TempPoint); + } + p->m_LastLineDot = TempPoint; + +} + +void CWalkPath::SaveFollowWallPath() +{ + for(int i=0; i<3000; i++)//3000 + { + if(FollowTheWall(TRUE, m_Meet)) + { + for(int j=0; j< RightWallPath.GetSize(); j++) + ContinuousPath.Add( RightWallPath[j]); + + RightWallPath.RemoveAll(); + LeftWallPath.RemoveAll(); + m_FollowWallSuccess = TRUE; + + return; + } + + if(FollowTheWall(FALSE,m_Meet)) + { + for(int j=0; j< LeftWallPath.GetSize(); j++) + ContinuousPath.Add( LeftWallPath[j]); + + RightWallPath.RemoveAll(); + LeftWallPath.RemoveAll(); + m_FollowWallSuccess = TRUE; + + return; + } + } + + RightWallPath.RemoveAll(); + LeftWallPath.RemoveAll(); + m_FollowWallSuccess = FALSE; +} + +void CWalkPath::StraightenThePath(LPPOINT Path, DWORD dwMaxCount) +{ + + CArrayEx TempPathA; + CArrayEx TempPathB; + + int TempCountB,TempCountC; + int i,j; + + TempCountB = TempCountC = 0; + + __PRINTF("ContinuousCount %d\n", ContinuousPath.GetSize()); + + // first straighten + for( i=STRAIGHTEN_A; iIsBarrier(TempPoint)) p->m_Direct = FALSE; +} + +/////////////////////////////////////////////////////////////////////// +// Public Functions +/////////////////////////////////////////////////////////////////////// + +int CWalkPath::FindWalkPath (POINT Start, POINT End, LPPOINT Path, DWORD dwMaxCount, int Range, bool Reduction) +{ + m_Start = m_LastLineDot = Start; + m_End = End; + + unsigned int oldRange = MAX_WALK_RANGE; + MAX_WALK_RANGE = Range; + + if(!(IsBorder(End)|| IsBorder(Start))) + { + __PRINTF("start x=%d y=%d\n",m_Start.x,m_Start.y); + LineDDA(Start.x, Start.y, End.x, End.y, FindPathProc, (long)this); + FindPathProc(End.x, End.y, (long)this); + __PRINTF("end x=%d y=%d\n",m_End.x,m_End.y); + + if(m_FollowWallSuccess) + { + /* FILE *fp = fopen("a.txt", "w+"); + for (int y = 0; y < m_MapSizeY; y ++) + { + for (int x= 0; x< m_MapSizeX; x ++) + { + char ch=0; + for(int k=0; k aTemp; + aTemp.SetSize(dwMaxCount); + for (int t = 0; t < (int)dwMaxCount; t++) + aTemp[t] = lpPath[t]; + + // straighten the path + for (int nStart = 0; nStart + 2 < aTemp.GetSize(); nStart++) + { + for (int nEnd = aTemp.GetSize() - 1; nEnd > nStart + 1; nEnd--) + { + if (IsDirect(aTemp[nStart], aTemp[nEnd])) + { + aTemp.RemoveAt(nStart + 1, nEnd - nStart - 1); + break; + } + } + } + + if (aTemp.GetSize() >= (int)dwMaxCount) + return dwMaxCount; + + // split long paths + CArrayEx aSubPath; + for (int i = 0; i + 1 < aTemp.GetSize(); i++) + { + int nSubPath = Split(aTemp[i], aTemp[i + 1], aSubPath); + if (nSubPath) + { + aTemp.InsertAt(i + 1, &aSubPath); + i += nSubPath; + } + } + + // output + const DWORD OUTPUT = min((DWORD)aTemp.GetSize(), dwMaxCount); + ::memcpy(lpPath, aTemp.GetData(), OUTPUT * sizeof(POINT)); + return OUTPUT; +} + +int CWalkPath::Split(const POINT &pt1, const POINT &pt2, CArrayEx &aSubPath) +{ + aSubPath.RemoveAll(); + const DWORD DISTANCE = CalculateDistance(pt1, pt2); + if (DISTANCE <= MAX_WALK_RANGE) + return 0; + + DWORD dwSubCount = DISTANCE / MAX_WALK_RANGE; + if ((DISTANCE % MAX_WALK_RANGE) == 0) + dwSubCount--; + + const int ANGLE = CalculateAngle(pt1, pt2); + + for (DWORD i = 0; i < dwSubCount; i++) + aSubPath.Add(CalculatePointOnTrack(pt1, MAX_WALK_RANGE * (i + 1), ANGLE)); + + return aSubPath.GetSize(); +} diff --git a/WalkPath.h b/WalkPath.h new file mode 100644 index 00000000..f42d3e64 --- /dev/null +++ b/WalkPath.h @@ -0,0 +1,67 @@ +///////////////////////////////////////////////////////////////////////// +// +// WalkPath.h +// +// Labyrinth Pathing Algorithm by Ustc_tweeg +// +// Ustc_tweeg < ustc_tweeg@tom.com > +// +///////////////////////////////////////////////////////////////////////// + +#ifndef __WALKPATH_H__ +#define __WALKPATH_H__ + +#define __IN_DIABLOII__ // Comment this line out if not used in game + + +#ifndef __IN_DIABLOII__ + #include +#endif + +#include "ArrayEx.h" + +class CWalkPath +{ +public: + + CWalkPath(WORD** Map, int MapSizeX, int MapSizeY); + virtual ~CWalkPath(); + + // return number of path points found, including the start and the end point + // return 0 if pathing fail + int FindWalkPath(POINT Start, POINT End, LPPOINT Path, DWORD dwMaxCount, int Range, bool Reduction); + +private: + + WORD** m_Map; + int m_MapSizeX, m_MapSizeY; + int m_Count; + + POINT m_Start,m_End,m_Meet,m_Seperate; + POINT m_LCurrent,m_RCurrent,m_LastLineDot; + + CArrayEx ContinuousPath; + CArrayEx LeftWallPath; + CArrayEx RightWallPath; + + + int m_LStart,m_RStart; + + BOOL m_Direct,m_FollowWallSuccess; + + BOOL IsBorder(POINT pt); + BOOL IsBarrier(POINT pt) const; + BOOL IsDirect(POINT pt1, POINT pt2); + void FollowTheRope(POINT Dot); + BOOL FollowTheWall(BOOL RightWall, POINT FollowEnd); + void SaveFollowWallPath(); + void StraightenThePath(LPPOINT Path, DWORD dwMaxCount); + DWORD FurtherStraighten(LPPOINT lpPath, DWORD dwMaxCount); + static void CALLBACK FindPathProc(int X, int Y, LPARAM lpData); + static void CALLBACK IsDirectProc(int x, int y, LPARAM lpData); + static int Split(const POINT& pt1, const POINT& pt2, CArrayEx& aSubPath); +}; + + + +#endif // __WALKPATH_H__ diff --git a/dde.cpp b/dde.cpp new file mode 100644 index 00000000..3208779b --- /dev/null +++ b/dde.cpp @@ -0,0 +1,106 @@ +#include "ScriptEngine.h" +#include "D2Helpers.h" +#include "Helpers.h" +#include "dde.h" + +DWORD DdeSrvInst = 0; +HSZ hszD2BSns; + +HDDEDATA CALLBACK DdeCallback(UINT uType, UINT uFmt, HCONV hconv, HSZ hsz1, + HSZ hsz2, HDDEDATA hdata, DWORD dwData1, DWORD dwData2) +{ + char pszItem[65535] = ""; + switch(uType) { + case XTYP_CONNECT: + return (HDDEDATA)TRUE; + case XTYP_POKE: + DdeGetData(hdata, (LPBYTE)pszItem, 255, 0); + if(SwitchToProfile(pszItem)) + Log("Switched to profile %s", pszItem); + else + Log("Profile %s not found", pszItem); + break; + case XTYP_EXECUTE: + DdeGetData(hdata, (LPBYTE)pszItem, sizeof(pszItem), 0); + Script* script = ScriptEngine::CompileCommand(pszItem); + if(script) + CreateThread(0, 0, ScriptThread, script, 0, 0); + break; + } + return (HDDEDATA)0; +} + +DWORD CreateDdeServer() { + char buf[1000]; + + int ret = DdeInitialize(&DdeSrvInst, DdeCallback, + APPCLASS_STANDARD | APPCMD_FILTERINITS | CBF_FAIL_ADVISES | + CBF_FAIL_REQUESTS | CBF_SKIP_CONNECT_CONFIRMS | CBF_SKIP_REGISTRATIONS | + CBF_SKIP_UNREGISTRATIONS, 0); + if(ret != DMLERR_NO_ERROR) + return 0; + char handle[25]; + sprintf_s(handle, sizeof(handle), "d2bs-%d", GetProcessId(GetCurrentProcess())); + hszD2BSns = DdeCreateStringHandle(DdeSrvInst, handle, CP_WINANSI); + if(!hszD2BSns) + return 0; + if(!DdeNameService(DdeSrvInst, hszD2BSns, 0L, DNS_REGISTER | DNS_FILTERON)) { + sprintf_s(buf, sizeof(buf), "DdeServer DdeNameService Error: %X", DdeGetLastError(DdeSrvInst)); + OutputDebugString(buf); + return 0; + } + return GetLastError(); +} + +BOOL ShutdownDdeServer() { + DdeFreeStringHandle(DdeSrvInst, hszD2BSns); + return DdeUninitialize(DdeSrvInst); +} + +BOOL SendDDE(int mode, char* pszDDEServer, char* pszTopic, char* pszItem, char* pszData, char** result, uint size) +{ + DWORD pidInst = 0; + HCONV hConv; + DWORD dwTimeout = 5000; + + int ret = DdeInitialize(&pidInst, (PFNCALLBACK) DdeCallback, APPCMD_CLIENTONLY, 0); + if(ret != DMLERR_NO_ERROR) + { + Log("DdeInitialize Error: %X", ret); + return FALSE; + } + + HSZ hszDDEServer = DdeCreateStringHandle(pidInst, (strlen(pszDDEServer) == 0 ? "\"\"" : pszDDEServer), CP_WINANSI); + HSZ hszTopic = DdeCreateStringHandle(pidInst, (strlen(pszTopic) == 0 ? "\"\"" : pszTopic), CP_WINANSI); + HSZ hszCommand = DdeCreateStringHandle(pidInst, (strlen(pszItem) == 0 ? "\"\"" : pszItem), CP_WINANSI); + + if((!hszDDEServer || !hszTopic || !hszCommand) && DdeGetLastError(pidInst) != 0) + { + Log("Error creating DDE Handles: %d", DdeGetLastError(pidInst)); + return FALSE; + } + + hConv = DdeConnect(pidInst, hszDDEServer, hszTopic, 0); + + switch(mode) + { + case 0: { + HDDEDATA DdeSrvData = DdeClientTransaction(0, 0, hConv, hszCommand, CF_TEXT, XTYP_REQUEST, dwTimeout, 0); + DdeGetData(DdeSrvData, (LPBYTE)result, size, 0); + break; + } + case 1: + DdeClientTransaction((LPBYTE)pszData, strlen(pszData)+1, hConv, hszCommand, CF_TEXT, XTYP_POKE, dwTimeout, 0); + break; + case 2: + DdeClientTransaction((LPBYTE)pszData, strlen(pszData)+1, hConv, 0L, 0, XTYP_EXECUTE, dwTimeout, 0); + break; + } + + DdeFreeStringHandle(pidInst, hszDDEServer); + DdeFreeStringHandle(pidInst, hszTopic); + DdeFreeStringHandle(pidInst, hszCommand); + DdeUninitialize(pidInst); + + return TRUE; +} diff --git a/dde.h b/dde.h new file mode 100644 index 00000000..d4874394 --- /dev/null +++ b/dde.h @@ -0,0 +1,8 @@ +#pragma once +#include +#include + +HDDEDATA CALLBACK DdeCallback(UINT uType, UINT uFmt, HCONV hconv, HSZ hsz1, HSZ hsz2, HDDEDATA hdata, DWORD dwData1, DWORD dwData2); +DWORD CreateDdeServer(); +BOOL ShutdownDdeServer(); +BOOL SendDDE(int mode, char* pszDDEServer, char* pszTopic, char* pszItem, char* pszData, char** result, unsigned int size); diff --git a/doc/Area.h b/doc/Area.h new file mode 100644 index 00000000..298fd188 --- /dev/null +++ b/doc/Area.h @@ -0,0 +1,34 @@ +/** Represent an Area of the map. + */ +class Area +{ +public: + /** Get an array of the Area's exits. This includes arrays where you can + * walk between two areas and warp Unit s. + */ + Exit[] exits; + + /** The name of the Area. + */ + String name; + + /** The x coordinate of the left side of the map. + */ + int x; + + /** The x size (width) of the map. + */ + int xsize; + + /** The y coordinate of the bottom (smallest y) of the map. + */ + int y; + + /** The y size (height) of the map. + */ + int ysize; + + /** The area id. See Unit::area. + */ + int id; +}; diff --git a/doc/Box.h b/doc/Box.h new file mode 100644 index 00000000..51115bea --- /dev/null +++ b/doc/Box.h @@ -0,0 +1,296 @@ +#include "ScreenHooks.h" + +/** A Box screen hook + * + * \todo Explain (and understand) this better. + * \todo Verify all the documentation in this class. + */ +class Box +{ +public: + /** Create a Box hook with the given parameters. + * + * Uses defaults x = 0, y = 0, x2 = 0, y2 = 0, color = 0, opacity = 0, + * align = 0, automap = false, click = null, hover = null. + */ + Box(); + + /** Create a Box hook with the given parameters. + * + * Uses defaults y = 0, x2 = 0, y2 = 0, color = 0, opacity = 0, align = 0, + * automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + */ + Box(int x); + + /** Create a Box hook with the given parameters. + * + * Uses defaults x2 = 0, y2 = 0, color = 0, opacity = 0, align = 0, + * automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + */ + Box(int x, int y); + + /** Create a Box hook with the given parameters. + * + * Uses defaults y2 = 0, color = 0, opacity = 0, align = 0, automap = false, + * click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + */ + Box(int x, int y, int x2); + + /** Create a Box hook with the given parameters. + * + * Uses defaults color = 0, opacity = 0, align = 0, automap = false, + * click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + */ + Box(int x, int y, int x2, int y2); + + /** Create a Box hook with the given parameters. + * + * Uses defaults opacity = 0, align = 0, automap = false, click = null, + * hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + * + * \param color The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + Box(int x, int y, int x2, int y2, int color); + + /** Create a Box hook with the given parameters. + * + * Uses defaults align = 0, automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + * + * \param color The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param opacity How much of the controls underneath the Box should show + * through. + */ + Box(int x, int y, int x2, int y2, int color, int opacity); + + /** Create a Box hook with the given parameters. + * + * Uses defaults automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + * + * \param color The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param opacity How much of the controls underneath the Box should show + * through. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + Box(int x, int y, int x2, int y2, int color, int opacity, int align); + + /** Create a Box hook with the given parameters. + * + * Uses defaults click = null, hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + * + * \param color The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param opacity How much of the controls underneath the Box should show + * through. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Box is in automap coordinate space (true) or + * screen coordinate space (false). + */ + Box(int x, int y, int x2, int y2, int color, int opacity, int align, + bool automap); + + /** Create a Box hook with the given parameters. + * + * Uses default hover = null. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + * + * \param color The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param opacity How much of the controls underneath the Box should show + * through. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Box is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Box is + * clicked. + */ + Box(int x, int y, int x2, int y2, int color, int opacity, int align, + bool automap, ClickHandler click); + + /** Create a Box hook with the given parameters. + * + * \param x The x coordinate (left) of the Box. + * + * \param y The y coordinate (top) of the Box. + * + * \param x2 The xsize (width) of the Box. + * + * \param y2 The ysize (height) of the Box. + * + * \param color The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param opacity How much of the controls underneath the Box should show + * through. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Box is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Box is + * clicked. + * + * \param hover The hover handler that gets called when the Box gets + * hovered over. + */ + Box(int x, int y, int x2, int y2, int color, int opacity, int align, + bool automap, ClickHandler click, HoverHandler hover); + + /** Remove the Box from the screen and destroy the corresponding object. + */ + void remove(); + + /** The x coordinate (left) of the Box. + */ + int x; + + /** The y coordinate (top) of the Box. + */ + int y; + + /** The xsize (width) of the Box. + */ + int xsize; + + /** The ysize (height) of the Box. + */ + int ysize; + + /** Whether or not the Box is visible. + */ + bool visible; + + /** The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + int align; + + /** The z-order of the Box (what it covers up and is covered by). + */ + int zorder; + + /** The click handler that gets called when the Box is clicked. + */ + ClickHandler click; + + /** The hover handler that gets called when the Box gets hovered over. + */ + HoverHandler hover; + + /** The color of the Box. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + int color; + + /** How much of the controls underneath the Box should show through. + */ + int opacity; +}; diff --git a/doc/Control.h b/doc/Control.h new file mode 100644 index 00000000..efc7aef4 --- /dev/null +++ b/doc/Control.h @@ -0,0 +1,115 @@ +/** This class represents out of game (OOG) Control s. + */ +class Control +{ +public: + /** Gets the next Control from the linked list. This is done by finding the + * old Control based on type, location and size. + */ + Control getNext(); + + /** Click Control in the center of the Control. + */ + void click(); + + /** Click Control at the given location. This is equivalent with clicking at + * the given location. + * + * \param x The x coordinate of the point to click. + * + * \param y The y coordinate of the point to click. + */ + void click(uint32_t x, uint32_t y); + + /** Set the Control's text. + * + * \param text The text to set the Control's text field to. + */ + void setText(String text); + + /** Get the texts from a label Control. Only works for labels. + * + * \return An array of all the Control's texts. + */ + String[] getText(); + + /** The text of the Control. + */ + String text; + + /** The x coordinate of the Control. + */ + double x; + + /** The y coordinate of the Control. + */ + double y; + + /** The xsize (width) of the Control. + */ + double xsize; + + /** The ysize (height) of the Control. + */ + double ysize; + + /** The state (?) of the Control. + * + * \todo Find a reference for these values. + */ + double state; + + /** Return whether or not the Control holds a password (starred out text). + */ + bool password; + + /** The type of control. + * + * 1 - TextBox + * + * 2 - Image + * + * 3 - Image2 + * + * 4 - LabelBox + * + * 5 - ScrollBar + * + * 6 - Button + * + * 7 - List + * + * 8 - Timer + * + * 9 - Smack + * + * 10 - ProgressBar + * + * 11 - Popup + * + * 12 - AccountList + */ + double type; + + /** Something... + * + * \todo Determine what this is. + */ + double cursorPos; + + /** Someting... + * + * \todo Determine what this is. + */ + double selectstart; + + /** Something... + * + * \todo Determine what this is. + */ + double selectend; + + /** Whether the Control is disabled or not. + */ + double disabled; +}; diff --git a/doc/D2BS.conf b/doc/D2BS.conf new file mode 100644 index 00000000..42325e48 --- /dev/null +++ b/doc/D2BS.conf @@ -0,0 +1,1510 @@ +# Doxyfile 1.5.8 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = D2BS + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = output + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Farsi, Finnish, French, German, Greek, +# Hungarian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, Polish, +# Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, Slovene, +# Spanish, Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = NO + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = NO + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to FRAME, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. Other possible values +# for this tag are: HIERARCHIES, which will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list; +# ALL, which combines the behavior of FRAME and HIERARCHIES; and NONE, which +# disables this behavior completely. For backwards compatibility with previous +# releases of Doxygen, the values YES and NO are equivalent to FRAME and NONE +# respectively. + +GENERATE_TREEVIEW = NONE + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Options related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/doc/D2BSScript.h b/doc/D2BSScript.h new file mode 100644 index 00000000..8ccb5a4b --- /dev/null +++ b/doc/D2BSScript.h @@ -0,0 +1,50 @@ +/** Represents a script (a thread), created by either loading a file, or typing + * something in the console. + */ +class D2BSScript +{ +public: + /** Get the next script. + * + * \return Whether there was another script or not. + */ + bool getNext(); + + /** Pause the script. + */ + void pause(); + + /** Resume the script. + */ + void resume(); + + /** Stop the script. + */ + void stop(); + + /** Send some values to the script. Has the effect of calling the any + * listeners to scriptmsg with the parameters provided. + */ + void send(...); + + /** The relative filename of the script. If the script is from the console + * the filename will be reported as "Command Line". + */ + String name; + + /** The type of script. + * + * 0 - InGame + * + * 1 - OutOfGame or Command + */ + int type; + + /** Whether or not the script is running. + */ + bool running; + + /** The thread id. + */ + int threadid; +}; diff --git a/doc/DBStatement.h b/doc/DBStatement.h new file mode 100644 index 00000000..b2a16163 --- /dev/null +++ b/doc/DBStatement.h @@ -0,0 +1,130 @@ +/** A class describing ... + * + * \todo Get a better description (and understanding). + */ +class DBStatement +{ +public: + /** An object with property names from the column names and property values + * coming from the data. + * + * \return The object with all the data. + */ + Object getObject(); + + /** Get the column count. + * + * \return The column count. + */ + int getColumnCount(); + + /** Get the value from the column specified by index. + * + * \param colIndex The index of the column to get data from. + * + * \return The data. + */ + double getColumnValue(int colIndex); + + /** Get the value from the column specified by index. + * + * \param colIndex The index of the column to get data from. + * + * \return The data. + */ + String getColumnValue(int colIndex); + + /** Get the name of the column at the given index. + * + * \param colIndex The index of the column to get data from. + * + * \return The column name. + */ + getColumnName(int colIndex); + + /** Call sqlite3_step and close_db_stmt on the statement. + * + * \todo Interpret what this means. + * + * \return Whether the result is SQLITE_DONE. + */ + bool go(); + + /** Call sqlite3_step on the statement. + * + * \todo Interpret what this means and how's it's different from go(). + * + * \return Whether the result is SQLITE_ROW. + */ + bool next(); + + /** Skip a certain number of rows in the results. + * + * \param rows The number of rows to skip. + * + * \return The number of rows actually skipped. + */ + int skip(int rows); + + /** Call sqlite3_reset. + * + * \todo Interpret what this does. + * + * \return true. + */ + bool reset(); + + /** Close the statement. + * + * \return true. + */ + bool close(); + + /** Bind the given data to the given column. + * + * \param colnum The column number to bind to. + * + * \param val The data to bind. + * + * \return true. + */ + bool bind(int colnum, double val); + + /** Bind the given data to the given column. + * + * \param colnum The column number to bind to. + * + * \param val The data to bind. + * + * \return true. + */ + bool bind(int colnum, int val); + + /** Bind the given data to the given column. + * + * \param colnum The column number to bind to. + * + * \param val The data to bind. + * + * \return true. + */ + bool bind(int colnum, String val); + + /** Bind the given data to the given column. + * + * \param colnum The column number to bind to. + * + * \param val The data to bind. + * + * \return true. + */ + bool bind(int colnum, bool val); + + /** The statement string. + */ + String sql; + + /** Whether or not there is more data to be gotten. + */ + bool ready; +}; diff --git a/doc/Directory.h b/doc/Directory.h new file mode 100644 index 00000000..71940099 --- /dev/null +++ b/doc/Directory.h @@ -0,0 +1,36 @@ +/** Represents a folder. + */ +class Folder +{ +public: + /** The path name to the directory. + */ + String name; + + /** Create a new directory. + * + * \param name The name of the directory to create under the current + * directory. + * + * \return The new Folder created. + */ + Folder create(String name); + + /** Remove the directory. Must be empty to work properly. + * + * \return true. + */ + bool remove(); + + /** Get the filename for each of the files in the directory. + * + * \return An array of all the filenames. + */ + String[] getFiles(); + + /** Get the name for each of the sub-directories in the current directory. + * + * \return An array of all the folder names. + */ + String[] getFolders(); +}; diff --git a/doc/Exit.h b/doc/Exit.h new file mode 100644 index 00000000..0cfef577 --- /dev/null +++ b/doc/Exit.h @@ -0,0 +1,33 @@ +/** Represents a method of getting from one Area to another. + */ +class Exit +{ +public: + /** The x coordinate of the exit. + */ + int x; + + /** The y coordinate of the exit. + */ + int y; + + /** The Area ID of the target level. + */ + int target; + + /** The Exit type. + * + * 1 - A walk through Exit + * + * 2 - A stairs type Exit + */ + int type; + + /** The class ID of the Exit if it is a stairs type Exit, 0 otherwise. + */ + int tileid; + + /** The Area ID of the source side of the Exit. + */ + int level; +}; diff --git a/doc/File.h b/doc/File.h new file mode 100644 index 00000000..7ac5cc08 --- /dev/null +++ b/doc/File.h @@ -0,0 +1,252 @@ +/** This class handles the opening, reading and writing of files. + */ +class File +{ +public: + /** Close the current file and then return it. + * + * \return The same File object. + */ + File close(); + + /** Reopen the file, equivalent to calling open with the same parameters + * as were used the first time. + * + * \return The same File object. + */ + File reopen(); + + /** Read count chars from the file. Used when the file was not opened in + * binary mode. + * + * \param count The number of characters to read. + * + * \return The characters that were read. + */ + String read(int count); + + /** Read count bytes from the file. Used when the file was opened in binary + * mode. + * + * \param count The number of bytes to read. + * + * \return An array of the bytes read. + */ + byte[] read(int count); + + /** Read a line from the file and return it. + * + * \return The line. + */ + String readLine(); + + /** Read all the lines from the file into a String array. + * + * \return An array of all the lines in the file. + */ + String[] readAllLines(); + + /** Read the entire file and return as a String. Includes a seek to start + * from the beginning of the file, regardless of where the current position + * was. + * + * \return The entire file in a String. + */ + String readAll(); + + /** Write the string representation (for standard files) or the binary + * representation (for binary files) of each of the arguments to the File. + * + * \return The File. + */ + File write(...); + + /** Seek n bytes from the current location. + * + * \param n Number of bytes to move.. + * + * \return The File. + */ + File seek(int n); + + /** Seek n bytes or lines (depending on isLines) from the current location. + * + * \param n Number of bytes or lines to move. + * + * \param isLines Whether n is a number of lines, or just bytes. + * + * \return The File. + */ + File seek(int n, bool isLines); + + /** Seek n bytes or lines (depending on isLines) from the current location + * or the start of file (depending on fromStart). + * + * \param n Number of bytes or lines to move. + * + * \param isLines Whether n is a number of lines, or just bytes. + * + * \param fromStart Whether to start from the start of file, or the current + * location. + * + * \return The File. + */ + File seek(int n, bool isLines, bool fromStart); + + /** Flush the buffers for the File. + * + * \return The File. + */ + File flush(); + + /** Seek back to the beginning of the File. + * + * \return The File. + */ + File reset(); + + /** Seek to the end of the File. + * + * \return The File. + */ + File end(); + + /** Open a file with the given settings. + * + * Uses defaults: binary = false, autoflush = false, lockFile = false. + * + * \param file The filename. + * + * \param mode The mode of the file (read/write/append). Use FILE_READ, + * FILE_WRITE and FILE_APPEND. + * FILE_READ corresponds to a C mode of "r". + * FILE_WRITE corresponds to a C mode of "w+". + * FILE_APPEND corresponds to a C mode of "a+". + * + * \return The File object just created. + */ + static File open(String file, int mode); + + /** Open a file with the given settings. + * + * Uses defaults: autoflush = false, lockFile = false. + * + * \param file The filename. + * + * \param mode The mode of the file (read/write/append). Use FILE_READ, + * FILE_WRITE and FILE_APPEND. + * FILE_READ corresponds to a C mode of "r". + * FILE_WRITE corresponds to a C mode of "w+". + * FILE_APPEND corresponds to a C mode of "a+". + * + * \param binary Whether to open the file in text or binary mode. If opening + * in text mode a "t" is appended to the C mode, otherwise a "b" is + * appended. + * + * \return The File object just created. + */ + static File open(String file, int mode, bool binary); + + /** Open a file with the given settings. + * + * Uses default: lockFile = false. + * + * \param file The filename. + * + * \param mode The mode of the file (read/write/append). Use FILE_READ, + * FILE_WRITE and FILE_APPEND. + * FILE_READ corresponds to a C mode of "r". + * FILE_WRITE corresponds to a C mode of "w+". + * FILE_APPEND corresponds to a C mode of "a+". + * + * \param binary Whether to open the file in text or binary mode. If opening + * in text mode a "t" is appended to the C mode, otherwise a "b" is + * appended. + * + * \param autoflush Whether to flush after each write. + * + * \return The File object just created. + */ + static File open(String file, int mode, bool binary, bool autoflush); + + /** Open a file with the given settings. + * + * \param file The filename. + * + * \param mode The mode of the file (read/write/append). Use FILE_READ, + * FILE_WRITE and FILE_APPEND. + * FILE_READ corresponds to a C mode of "r". + * FILE_WRITE corresponds to a C mode of "w+". + * FILE_APPEND corresponds to a C mode of "a+". + * + * \param binary Whether to open the file in text or binary mode. If opening + * in text mode a "t" is appended to the C mode, otherwise a "b" is + * appended. + * + * \param autoflush Whether to flush after each write. + * + * \param lockFile Whether or not to lock the file. + * + * \return The File object just created. + */ + static File open(String file, int mode, bool binary, bool autoflush, + bool lockFile); + + /** Whether or not the file can be read from. Based on whether the File is + * open, whether it is at the end of file, and whether there is an error + * pending. + */ + bool readable; + + /** Whether or not the file is writeable. Based on whether the File is open, + * whether there is an error pending and whether the File was opened for + * writing or not. + */ + bool writeable; + + /** Whether or not the file is seekable. Based on whether the File is open + * and whether there is an error pending. + */ + bool seekable; + + /** The mode the file was opened with. Compare with FILE_READ, FILE_WRITE + * and FILE_APPEND. + */ + int mode; + + /** Whether the file was opened as a binary file or not. + */ + bool binaryMode; + + /** The file length. + */ + int length; + + /** The relative path to the File (the filename/path given for opening). + */ + String path; + + /** The position in the File (where the next read or write will occur). + */ + int position; + + /** Whether or not the File is at end of file. + */ + bool eof; + + /** The last accessed time of the File. + */ + int accessed; + + /** The creation time of the File. + */ + int created; + + /** The last modified time of the File. + */ + int modified; + + /** Whether or not to autoflush the File. + */ + bool autoflush; +}; diff --git a/doc/FileTools.h b/doc/FileTools.h new file mode 100644 index 00000000..37758d44 --- /dev/null +++ b/doc/FileTools.h @@ -0,0 +1,62 @@ +/** A collection of tools to do things like move files and determine whether + * files exist. + */ +class FileTools +{ +public: + /** Remove (delete) a file. + * + * \param file The filename of the file to delete. + */ + static void remove(String file); + + /** Rename a file. + * + * \param orig The original filename. + * + * \param newName The new filename. + */ + static void rename(String orig, String newName); + + /** Copy a file. + * + * \param orig The original filename. + * + * \param newName The filename of the new file. + */ + static void copy(String orig, String newName); + + /** Determine if a file exists. + * + * \param file The filename of the file to check. + * + * \return Whether or not the file exists. + */ + static bool exists(String file); + + /** Read the contents of a file into a String. + * + * \param file The filename of the file to open. + * + * \return The contents of the file. + */ + static String readText(String file); + + /** Write the string representation (for standard files) or the binary + * representation (for binary files) of each of the arguments to the file. + * + * \param file The filename of the file to write to. + * + * \return Whether or not the operation was successful. + */ + bool writeText(String file, ...); + + /** Append the string representation (for standard files) or the binary + * representation (for binary files) of each of the arguments to the file. + * + * \param file The filename of the file to write to. + * + * \return Whether or not the operation was successful. + */ + bool appendText(String file, ...); +}; diff --git a/doc/Frame.h b/doc/Frame.h new file mode 100644 index 00000000..8785fdd1 --- /dev/null +++ b/doc/Frame.h @@ -0,0 +1,216 @@ +#include "ScreenHooks.h" + +/** This class represents a screen hook for a Frame. + * + * \todo Explain (and understand) this better. + * \todo Verify all the documentation in this class. + */ +class Frame +{ +public: + /** Create a Frame hook with the given parameters. + * + * Uses defaults x = 0, y = 0, x2 = 0, y2 = 0, align = 0, automap = false, + * click = null, hover = null. + */ + Frame(); + + /** Create a Frame hook with the given parameters. + * + * Uses defaults y = 0, x2 = 0, y2 = 0, align = 0, automap = false, + * click = null, hover = null. + * + * \param x The x coordinate (left) of the Frame. + */ + Frame(int x); + + /** Create a Frame hook with the given parameters. + * + * Uses defaults x2 = 0, y2 = 0, align = 0, automap = false, click = null, + * hover = null. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + */ + Frame(int x, int y); + + /** Create a Frame hook with the given parameters. + * + * Uses defaults y2 = 0, align = 0, automap = false, click = null, + * hover = null. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + * + * \param x2 The xsize (width) of the Frame. + */ + Frame(int x, int y, int x2); + + /** Create a Frame hook with the given parameters. + * + * Uses defaults align = 0, automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + * + * \param x2 The xsize (width) of the Frame. + * + * \param y2 The ysize (height) of the Frame. + */ + Frame(int x, int y, int x2, int y2); + + /** Create a Frame hook with the given parameters. + * + * Uses defaults automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + * + * \param x2 The xsize (width) of the Frame. + * + * \param y2 The ysize (height) of the Frame. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + Frame(int x, int y, int x2, int y2, int align); + + /** Create a Frame hook with the given parameters. + * + * Uses defaults automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + * + * \param x2 The xsize (width) of the Frame. + * + * \param y2 The ysize (height) of the Frame. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Frame is in automap coordinate space (true) or + * screen coordinate space (false). + */ + Frame(int x, int y, int x2, int y2, int align, bool automap); + + /** Create a Frame hook with the given parameters. + * + * Uses default hover = null. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + * + * \param x2 The xsize (width) of the Frame. + * + * \param y2 The ysize (height) of the Frame. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Frame is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Frame is + * clicked. + */ + Frame(int x, int y, int x2, int y2, int align, bool automap, + ClickHandler click); + + /** Create a Frame hook with the given parameters. + * + * \param x The x coordinate (left) of the Frame. + * + * \param y The y coordinate (top) of the Frame. + * + * \param x2 The xsize (width) of the Frame. + * + * \param y2 The ysize (height) of the Frame. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Frame is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Frame is + * clicked. + * + * \param hover The hover handler that gets called when the Frame gets + * hovered over. + */ + Frame(int x, int y, int x2, int y2, int align, bool automap, + ClickHandler click, HoverHandler hover); + + /** Remove the Frame from the screen and destroy the corresponding object. + */ + void remove(); + + /** The x coordinate (left) of the Frame. + */ + int x; + + /** The y coordinate (top) of the Frame. + */ + int y; + + /** The xsize (width) of the Frame. + */ + int xsize; + + /** The ysize (height) of the Frame. + */ + int ysize; + + /** Whether or not the Frame is visible. + */ + bool visible; + + /** The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + int align; + + /** The z-order of the Frame (what it covers up and is covered by). + */ + int zorder; + + /** The click handler that gets called when the Frame is clicked. + */ + ClickHandler click; + + /** The hover handler that gets called when the Frame gets hovered over. + */ + HoverHandler hover; +}; diff --git a/doc/Handlers.h b/doc/Handlers.h new file mode 100644 index 00000000..0778c1df --- /dev/null +++ b/doc/Handlers.h @@ -0,0 +1,3 @@ +/** \defgroup handlers Handler fuction types. + */ + diff --git a/doc/Image.h b/doc/Image.h new file mode 100644 index 00000000..40d0109a --- /dev/null +++ b/doc/Image.h @@ -0,0 +1,222 @@ +#include "ScreenHooks.h" + +/** This class represents a screen hook for a Image. + * + * \todo Explain (and understand) this better. + * \todo Verify all the documentation in this class. + */ +class Image +{ +public: + /** Create an Image hook with the given parameters. + * + * Uses defaults szText = "", x = 0, y = 0, color = 0, align = 0, + * automap = false, click = null, hover = null + */ + Image(); + + /** Create an Image hook with the given parameters. + * + * Uses defaults x = 0, y = 0, color = 0, align = 0, automap = false, + * click = null, hover = null + * + * \param szText The filename to load the image from. + */ + Image(String szText); + + /** Create an Image hook with the given parameters. + * + * Uses defaults y = 0, color = 0, align = 0, automap = false, click = null, + * hover = null + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + */ + Image(String szText, int x); + + /** Create an Image hook with the given parameters. + * + * Uses defaults color = 0, align = 0, automap = false, click = null, + * hover = null + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + * + * \param y The y coordinate (top) of the Image. + */ + Image(String szText, int x, int y); + + /** Create an Image hook with the given parameters. + * + * Uses defaults align = 0, automap = false, click = null, hover = null + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + * + * \param y The y coordinate (top) of the Image. + * + * \param color The color of the Image. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + Image(String szText, int x, int y, int color); + + /** Create an Image hook with the given parameters. + * + * Uses defaults automap = false, click = null, hover = null + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + * + * \param y The y coordinate (top) of the Image. + * + * \param color The color of the Image. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + Image(String szText, int x, int y, int color, int align); + + /** Create an Image hook with the given parameters. + * + * Uses defaults click = null, hover = null + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + * + * \param y The y coordinate (top) of the Image. + * + * \param color The color of the Image. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Image is in automap coordinate space (true) or + * screen coordinate space (false). + */ + Image(String szText, int x, int y, int color, int align, bool automap); + + /** Create an Image hook with the given parameters. + * + * Uses default hover = null + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + * + * \param y The y coordinate (top) of the Image. + * + * \param color The color of the Image. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Image is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Image is + * clicked. + */ + Image(String szText, int x, int y, int color, int align, bool automap, + ClickHandler click); + + /** Create an Image hook with the given parameters. + * + * \param szText The filename to load the image from. + * + * \param x The x coordinate (left) of the Image. + * + * \param y The y coordinate (top) of the Image. + * + * \param color The color of the Image. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Image is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Image is + * clicked. + * + * \param hover The hover handler that gets called when the Image gets + * hovered over. + */ + Image(String szText, int x, int y, int color, int align, bool automap, + ClickHandler click, HoverHandler hover); + + /** Remove the Image from the screen and destroy the corresponding object. + */ + void remove(); + + /** The x coordinate (left) of the Image. + */ + int x; + + /** The y coordinate (top) of the Image. + */ + int y; + + /** Whether or not the Image is visible. + */ + bool visible; + + /** The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + int align; + + /** The z-order of the Image (what it covers up and is covered by). + */ + int zorder; + + /** The click handler that gets called when the Image is clicked. + */ + ClickHandler click; + + /** The hover handler that gets called when the Image gets hovered over. + */ + HoverHandler hover; + + /** Location of the file to load for display. + */ + String location; +}; diff --git a/doc/Line.h b/doc/Line.h new file mode 100644 index 00000000..e84f8f9c --- /dev/null +++ b/doc/Line.h @@ -0,0 +1,195 @@ +#include "ScreenHooks.h" + +/** A 2d line. + * + * \todo Verify all the documentation in this class. + */ +class Line +{ +public: + /** Create a Line hook with the given parameters. + * + * Uses defaults x = 0, y = 0, x2 = 0, y2 = 0, color = 0, automap = false, + * click = null, hover = null. + */ + Line(); + + /** Create a Line hook with the given parameters. + * + * Uses defaults y = 0, x2 = 0, y2 = 0, color = 0, automap = false, + * click = null, hover = null. + * + * \param x The x coordinate (left) of the Line. + */ + Line(int x); + + /** Create a Line hook with the given parameters. + * + * Uses defaults x2 = 0, y2 = 0, color = 0, automap = false, click = null, + * hover = null. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + */ + Line(int x, int y); + + /** Create a Line hook with the given parameters. + * + * Uses defaults y2 = 0, color = 0, automap = false, click = null, + * hover = null. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + * + * \param x2 The xsize (width) of the Line. + */ + Line(int x, int y, int x2); + + /** Create a Line hook with the given parameters. + * + * Uses defaults color = 0, automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + * + * \param x2 The xsize (width) of the Line. + * + * \param y2 The ysize (height) of the Line. + */ + Line(int x, int y, int x2, int y2); + + /** Create a Line hook with the given parameters. + * + * Uses default automap = false, click = null, hover = null. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + * + * \param x2 The xsize (width) of the Line. + * + * \param y2 The ysize (height) of the Line. + * + * \param color The color of the Line. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + Line(int x, int y, int x2, int y2, int color); + + /** Create a Line hook with the given parameters. + * + * Uses defaults click = null, hover = null. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + * + * \param x2 The xsize (width) of the Line. + * + * \param y2 The ysize (height) of the Line. + * + * \param color The color of the Line. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param automap Whether the Line is in automap coordinate space (true) or + * screen coordinate space (false). + */ + Line(int x, int y, int x2, int y2, int color, bool automap); + + /** Create a Line hook with the given parameters. + * + * Uses default hover = null. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + * + * \param x2 The xsize (width) of the Line. + * + * \param y2 The ysize (height) of the Line. + * + * \param color The color of the Line. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param automap Whether the Line is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Line is + * clicked. + */ + Line(int x, int y, int x2, int y2, int color, bool automap, + ClickHandler click); + + /** Create a Line hook with the given parameters. + * + * \param x The x coordinate (left) of the Line. + * + * \param y The y coordinate (top) of the Line. + * + * \param x2 The xsize (width) of the Line. + * + * \param y2 The ysize (height) of the Line. + * + * \param color The color of the Line. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param automap Whether the Line is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Line is + * clicked. + * + * \param hover The hover handler that gets called when the Line gets + * hovered over. + */ + Line(int x, int y, int x2, int y2, int color, bool automap, + ClickHandler click, HoverHandler hover); + + /** Remove the Line from the screen and destroy the corresponding object. + */ + void remove(); + + /** The first x coordinate of the Line. + */ + int x; + + /** The first y coordinate of the Line. + */ + int y; + + /** The second x coordinate of the Line. + */ + int x2; + + /** The second y coordinate of the Line. + */ + int y2; + + /** Whether or not the Line is visible. + */ + bool visible; + + /** The color of the Line. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + int color; + + /** The z-order of the Line (what it covers up and is covered by). + */ + int zorder; + + /** The click handler that gets called when the Line is clicked. + */ + ClickHandler click; + + /** The hover handler that gets called when the Line gets hovered over. + */ + HoverHandler hover; +}; diff --git a/doc/MainPage.h b/doc/MainPage.h new file mode 100644 index 00000000..e41d681b --- /dev/null +++ b/doc/MainPage.h @@ -0,0 +1,4 @@ +/** \mainpage D2BS Docs + * + * These docs are based on code from /branches/patch-113 r1223. + */ diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 00000000..c992d8db --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,11 @@ +.PHONY : all +all : docs updateFiles + +.PHONY : docs +docs : *.h + doxygen D2BS.conf + +.PHONY : updateFiles +updateFiles : docs + sudo cp output/html/* /var/www/d2bsDocs/htdocs/ + sudo chown -R apache:apache /var/www/d2bsDocs/htdocs/ diff --git a/doc/Me.h b/doc/Me.h new file mode 100644 index 00000000..1522af6c --- /dev/null +++ b/doc/Me.h @@ -0,0 +1,1061 @@ +/** The class that represents the controlled unit. Technically, also called + * Unit, but since C++ doesn't support class overloading, called it Me here + * instead. + */ +class Me +{ +public: + /** Get the next unit that matches the originally given name or class id and + * originally specified mode. + * + * \return Whether another unit was found. + */ + bool getNext(); + + /** Get the next unit that matches the given name and originally specified + * mode. + * + * \param szName The name to look for. + * + * \return Whether another unit was found. + */ + bool getNext(String szName); + + /** Get the next unit that matches the given class id and originally + * specified mode. + * + * \param dwClassId The class id to look for. + * + * \return Whether another unit was found. + */ + bool getNext(int dwClassId); + + /** Get the next unit that matches the given name and mode. + * + * \param szName The name to look for. + * + * \param dwMode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched for. + * + * \return Whether another unit was found. + */ + bool getNext(String szName, int dwMode); + + /** Get the next unit that matches the given class id and mode. + * + * \param dwClassId The class id to look for. + * + * \param dwMode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched for. + * + * \return Whether another unit was found. + */ + bool getNext(int dwClassId, int dwMode); + + /** If player is holding an item, drop it. + */ + void cancel(); + + /** Close some form of interaction. + * + * \todo Clarify what each of the calls do. + * + * \param type Type of interaction to cancel + * + * 0 - Call D2CLIENT_CloseInteract + * + * 1 - Call D2CLIENT_CloseNPCInteract + */ + void cancel(int type); + + /** Try to repair. + * + * Need to be able to find unit that you're trying to repair with. That + * means the unit needs to still be in the server unit hash table. + * + * \return true if successful. + */ + bool repair(); + + /** Use an NPC menu. + * + * Need to be able to find unit that you're trying to repair with. That + * means the unit needs to still be in the server unit hash table. + * + * \param menuItem Index of the menu item to click. + * + * \return true if menu was found. + */ + bool useMenu(int menuItem); + + /** Interact with the unit. + * + * If the unit is an item in inventory pick it up. Otherwise click it on + * the map. + */ + bool interact(); + + /** Interact with a waypoint. + * + * If the unit is an object, assume it's a waypoint, and take it. + * + * \param destId The area id of the destination to select. + */ + bool interact(int destId); + + /** Get the first item from inventory. + * + * \return The first item from inventory. + */ + Unit getItem(); + + /** Get an item from inventory by name. + * + * \param name The name of the item to look for. + * + * \return The first item found that matches the description. + */ + Unit getItem(String name); + + /** Get an item from inventory by classId. + * + * \param classId The class id of the unit. + * + * \return The first item found that matches the description. + */ + Unit getItem(uint32_t classId); + + /** Get an item from inventory by name and mode. + * + * \param name The name of the unit to look for. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \return The first item found that matches the description. + */ + Unit getItem(String name, uint32_t mode); + + /** Get an item from inventory by classId and mode. + * + * \param classId The class id of the unit. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \return The first item found that matches the description. + */ + Unit getItem(uint32_t classId, uint32_t mode); + + /** Get an item from inventory by name, mode and nUnitId. + * + * \param name The name of the unit to look for. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \param nUnitId The unique id of the unit. + * + * \return The first item found that matches the description. + */ + Unit getItem(String name, uint32_t mode, uint32_t nUnitId); + + /** Get an item from inventory by classId, mode and nUnitId. + * + * \param classId The class id of the unit. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \param nUnitId The unique id of the unit. + * + * \return The first item found that matches the description. + */ + Unit getItem(uint32_t classId, uint32_t mode, uint32_t nUnitId); + + /** Get all items from inventory. + * + * \return An array of all the items from inventory. + */ + Unit[] getItems(); + + /** Get whether this player has a merc. + * + * The unit being operated on should be a player. + * + * \param dummy Used to signify boolean result instead of object. Should + * be true. + * + * \return true if the player has a live merc. + */ + bool getMerc(bool dummy); + + /** Get a player's merc. + * + * The unit being operated on should be a player. + * + * \return The merc if there is one. + */ + Unit getMerc(); + + /** Get skill name from hand. + * + * \param hand Hand to get the skill name off. + * + * 0 - Right hand + * + * 1 - Left hand + * + * \return Skill name. + */ + String getSkill(int hand); + + /** Get skill id from hand. + * + * \param hand Hand to get the skill id off. + * + * 2 - Right hand + * + * 3 - Left hand + * + * \return Skill id. + */ + int getSkill(int hand); + + /** Get all skills. + * + * Gets all skill ids, along with corresponding base and total skill + * levels. + * + * \param dummy Should be 4. + * + * \return An array of arrays of integers. Inside the inner array the + * 0th index is the skill id, the 1st index is the base skill level and + * the 2nd index is the total skill level. Only the first 256 skills are + * read. + */ + int[][] getSkill(int dummy); + + /** Calls D2COMMON_GetSkillLevel and returns the result. + * + * \todo Figure out what D2COMMON_GetSkillLevel does. + * + * \returns Whatever D2COMMON_GetSkillLevel returns. + */ + int getSkill(int nSkillId, int nExt); + + /** Gets the parent of a unit. + * + * This function is used for monster and item units. + * + * \return The parent unit. + */ + Unit getParent(); + + /** Gets the parent of a unit. + * + * This function is used for object units. + * + * \return The parent's name. + */ + String getParent(); + + /** Puts the string equivalent of message over the unit. + */ + void overhead(Object message); + + /** Revive the character. + * + * BE CAREFUL! This function directly sends packets without checks. If you + * call this function and are not dead, you might get flagged/banned. + */ + void revive(); + + /** Returns the item flags. + * + * \returns Item flags: + * + * 0x00000001 - Equipped + * + * 0x00000008 - In socket + * + * 0x00000010 - Identified + * + * 0x00000040 - Weapon/shield is in the active weapon switch + * + * 0x00000080 - Weapon/shield is in the inactive weapon switch + * + * 0x00000100 - Item is broken + * + * 0x00000400 - Full rejuv + * + * 0x00000800 - Socketed + * + * 0x00002000 - In the trade or gamble screen + * + * 0x00004000 - Not in a socket + * + * 0x00010000 - Is an ear + * + * 0x00020000 - A starting item (worth only 1 gold) + * + * 0x00200000 - Rune, or potion, or mephisto's soulstone + * + * 0x00400000 - Ethereal + * + * 0x00800000 - Is an item + * + * 0x01000000 - Personalized + * + * 0x04000000 - Runeword + * + * Source: http://subversion.assembla.com/svn/d2bs/scripts/YAMB/libs/YAMB/common/YAM-Common.dbl r1086 + */ + int getFlags(); + + /** Same as getFlags, but returns a boolean. + * + * Returns true if any of the flags given match the item flags. + * + * \ref getFlags + * + * \param flags Flags to check. + * + * \return true if any of the flags are set in the item flags. + */ + bool getFlag(int flags); + + /** Get a stat by stat id. + * + * Used for stat 13. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \return The stat value. + */ + double getStat(int nStat); + + /** Get a stat by stat id and sub index. + * + * Used for everything except stat 13. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \return The stat value. + */ + int getStat(int nStat); + + /** Get a stat by stat id and sub index. + * + * Used for stat 13. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \param nSubIndex A subindex to a certain type of stat. For instance a + * specific skill for the +1 to skill tab stat. + * + * \return The stat value. + */ + double getStat(int nStat, int nSubIndex); + + /** Get a stat by stat id and sub index. + * + * Used for everything except stat 13. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \param nSubIndex A subindex to a certain type of stat. For instance a + * specific skill for the +1 to skill tab stat. + * + * \return The stat value. + */ + int getStat(int nStat, int nSubIndex); + + /** Get an array of all the stats of the item. + * + * \param nStat Set to -1. + * + * \return An array of the first 64 stats. The indices of the inner array + * are: 0 - nStat, 1 - nSubIndex, 2 - nValue. + */ + int[][] getStat(int nStat); + + /** Get an array of all the stats of the item. + * + * \param nStat Set to -1. + * + * \param nSubIndex Ignored. + * + * \return An array of the first 64 stats. The indices of the inner array + * are: 0 - nStat, 1 - nSubIndex, 2 - nValue. + */ + int[][] getStat(int nStat, int nSubIndex); + + /** Return whether or not the unit has a given state. + * + * \param nState The state id. + * + * \return Whether or not the unit has the state. + */ + bool getState(int nState); + + /** Get the price of the item at npc 148, with "buysell" of 0, in the + * current difficult. + * + * \todo Determine if this is the buy or sell price. "buysell" is 0. + * + * \return Some sort of price. + */ + int getPrice(); + + /** Get the price of the item at a given npc, with "buysell" of 0, in the + * current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npc The npc to determine the price at. + * + * \return The price requested. + */ + int getPrice(Unit npc); + + /** Get the price of the item at a given npc (by id), with "buysell" of 0, + * in the current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npcId The id of the npc to determine the price at. + * + * \return The price requested. + */ + int getPrice(int npcId); + + /** Get the price of the item at a given npc, with choice of buying or + * selling, in the current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npc The npc to determine the price at. + * + * \param buysell Unknown + * + * \return The price requested. + */ + int getPrice(Unit npc, int buysell); + + /** Get the price of the item at a given npc (by id), which choice of buying + * or selling, in the current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npcId The id of the npc to determine the price at. + * + * \param buysell Unknown + * + * \return The price requested. + */ + int getPrice(int npcId, int buysell); + + /** Get the price of the item at a given npc, with choice of buying or + * selling, in a given difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npc The npc to determine the price at. + * + * \param buysell Unknown + * + * \param difficulty The difficulty of interest: 0 - normal, 1 - nightmare, + * 2 - hell + * + * \return The price requested. + */ + int getPrice(Unit npc, int buysell, int difficulty); + + /** Get the price of the item at a given npc (by id), with choice of buying + * or selling, in a given difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npcId The id of the npc to determine the price at. + * + * \param buysell Unknown + * + * \param difficulty The difficulty of interest: 0 - normal, 1 - nightmare, + * 2 - hell + * + * \return The price requested. + */ + int getPrice(int npcId, int buysell, int difficulty); + + /** Determine whether or not a unit has a given enchant. + * + * \param nEnchant Enchantment id. + * + * \return Whether or not the unit has the enchantment. + */ + bool getEnchant(int nEnchant); + + /** Shop with a given npc, either buying or selling. + * + * \param dwMode What to do with the item. 1 - Sell, 2 - Buy, 6 - ? + * + * \return Whether or not the shop went through. + */ + bool shop(int dwMode); + + /** Set the skill on the given hand to be skill with name skillName. + * + * Waits up to one second for the skill to be set. + * + * \todo Fix argc < 1, should be argc < 2 + * + * \param skillName Name of the skill to put up. + * + * \param nHand Hand to put the skill on. non-zero left, 0 - right. + * + * \return Whether operation was successful. + */ + bool setSkill(String skillName, int nHand); + + /** Set the skill on the given hand to be skill with id nSkillId. + * + * Waits up to one second for the skill to be set. + * + * \todo Fix argc < 1, should be argc < 2 + * + * \param nSkillId Id of the skill to put up. + * + * \param nHand Hand to put the skill on. non-zero left, 0 - right. + * + * \return Whether operation was successful. + */ + bool setSkill(int nSkillId, int nHand); + + /** Set the skill on the given hand to be skill with name skillName. + * + * Waits up to one second for the skill to be set. + * + * \todo Fix argc < 1, should be argc < 2 + * + * \param skillName Name of the skill to put up. + * + * \param nHand Hand to put the skill on. non-zero left, 0 - right. + * + * \param item The item that the skill is attached to. + * + * \return Whether operation was successful. + */ + bool setSkill(String skillName, int nHand, Unit item); + + /** Set the skill on the given hand to be skill with id nSkillId. + * + * Waits up to one second for the skill to be set. + * + * \todo Fix argc < 1, should be argc < 2 + * + * \param nSkillId Id of the skill to put up. + * + * \param nHand Hand to put the skill on. non-zero left, 0 - right. + * + * \param item The item that the skill is attached to. + * + * \return Whether operation was successful. + */ + bool setSkill(int nSkillId, int nHand, Unit item); + + /** Move to the given location. + * + * \param x The x location. + * + * \param y The y location. + */ + void move(int x, int y); + + /** Move to this unit. + */ + void move(); + + /** Get the quest flag for a quest specified by act and quest number. + * + * \param nAct The act of the quest. + * + * \param nQuest The quest number. + * + * \return The quest flag for the specified quest. + */ + int getQuest(int nAct, int nQuest); + + /** Get the number of minions of a certain type. + * + * \param nType The type of the minions. + * + * \return The number of minions of the specified type. + */ + int getMinionCount(int nType); + + /** Get price to repair this unit at the current npc or npc 0x9A if not + * currently interacting. + * + * \return The price to repair the given unit. + */ + int getRepairCost(); + + /** Get price to repair this unit at the current npc given by nNpcClassId. + * + * \param nNpcClassId The class id of the npc to get the price for repair + * at. + * + * \return The price to repair the given unit. + */ + int getRepairCost(int nNpcClassId); + + /** Get the cost to do something (buy, sell, repair) with the given item. + * + * \param nMode What to do: 0 - buy, 1 - sell, 2 - repair. + * + * \return The price. + */ + int getItemCost(int nMode); + + /** Get the cost to do something (buy, sell, repair) with the given item, at + * the given npc. + * + * \param nMode What to do: 0 - buy, 1 - sell, 2 - repair. + * + * \param nNpcClassId The class id of the npc to check the price with. + * + * \return The price. + */ + int getItemCost(int nMode, int nNpcClassId); + + /** Get the cost to do something (buy, sell, repair) with the given item, at + * the given npc, in the given difficulty. + * + * \param nMode What to do: 0 - buy, 1 - sell, 2 - repair. + * + * \param nNpcClassId The class id of the npc to check the price with. + * + * \param nDifficulty The difficulty to check the price in. + * + * \return The price. + */ + int getItemCost(int nMode, int nNpcClassId, int nDifficulty); + + /** The type of the unit. + * + * 0 - Player + * + * 1 - NPC + * + * 2 - Object + * + * 3 - Missile + * + * 4 - Item + * + * 5 - Warp + * + * Source: botNET + */ + int type; + + /** The class id of the object. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1002 + * + * http://forums.d2botnet.org/viewtopic.php?f=18&t=986 and + * + * http://forums.d2botnet.org/viewtopic.php?f=18&t=985 + */ + int classId; + + /** The mode of the unit. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=988 + */ + int mode; + + /** The name of the unit. + */ + String name; + + /** The seed used to create the map. + */ + int mapid; + + /** The act where the unit is currently located. + */ + int act; + + /** The unit unique id. Referred to simply as the unit id. Used along with + * the unit type to uniquely identify the unit. + */ + int gid; + + /** The x location of the unit. + */ + int x; + + /** The y location of the unit. + */ + int y; + + /** The id of the area (level) the unit is located in. + */ + int area; + + /** The unit's current health. + */ + int hp; + + /** The unit's maximum health. + */ + int hpmax; + + /** The unit's current mana. + */ + int mp; + + /** The unit's maximum mana. + */ + int mpmax; + + /** The unit's current stamina. + */ + int stamina; + + /** The unit's maximum stamina. + */ + int staminamax; + + /** The character level. The level that determines stat points, skill + * levels, etc. + */ + int charlvl; + + /** The number of items in inventory. + */ + int itemcount; + + /** The unit id of the owner of the unit. + */ + int owner; + + /** The type of owner. + * + * \ref type + */ + int ownertype; + + /** The special type of the unit. Represents things like unique, minion, + * boss, etc. + * + * 1 - "Normal" Boss + * 2 - Champion + * 4 - Boss + * 8 - Minion + */ + int spectype; + + /** The direction of the unit. + * + * \todo Figure out what the direction is. + */ + int direction; + + /** The three digit code for an item. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=991 + */ + String code; + + /** The magic prefix of the item. + */ + String prefix; + + /** The magic suffix of the item. + */ + String suffix; + + /** The id code for the magic prefix. + */ + int prefixnum; + + /** The id code for the magic suffix. + */ + int suffixnum; + + /** The full name of an item. + */ + String fname; + + /** The item quality. + * + * 1 - Low quality + * + * 2 - Normal + * + * 3 - Superior + * + * 4 - Magic + * + * 5 - Set + * + * 6 - Rare + * + * 7 - Unique + * + * 8 - Crafted + * + * Source: botNET + */ + int quality; + + /** No clue. + * + * \todo Get a clue. + */ + int node; + + /** The location of the item (ground, inventory, stash, etc.). + * + * 0 - Ground + * + * 1 - Equipped + * + * 2 - Belt + * + * 3 - Inventory + * + * 4 - Store + * + * 5 - Trade + * + * 6 - Cube + * + * 7 - Stash + */ + int location; + + /** The x size of the item. + */ + int sizex; + + /** The y size of the item. + */ + int sizey; + + /** The type of the item. + * + * \todo Put together a reference for item type. + */ + int itemType; + + /** The description of the item. + */ + String description; + + /** The equipped location of the item. + * + * 0 - Not equipped + * + * 1 - Helmet + * + * 2 - Amulet + * + * 3 - Armor + * + * 4 - Right hand slot 1 + * + * 5 - Left hand slot 1 + * + * 6 - Right ring + * + * 7 - Left ring + * + * 8 - Belt + * + * 9 - Boots + * + * 10 - Gloves + * + * 11 - Right hand slot 2 + * + * 12 - Left hand slot 2 + */ + int bodylocation; + + /** Item level. Used for things like item stat rolling. + */ + int ilvl; + + /** Whether the controlled character is in the always run mode or not. + * + * 0 - Walk unless directed to run + * 1 - Always run + */ + int runwalk; + + /** Set the weapon switch. + */ + int weaponswitch; + + /** The account name used to log on to the account. + */ + String account; + + /** The character name. + */ + String charname; + + /** The difficulty of the game. + * + * 0 - Normal + * + * 1 - Nightmare + * + * 2 - Hell + */ + int diff; + + /** The name of the game. + */ + String gamename; + + /** The password of the game. + */ + String gamepassword; + + /** A string representation of the IPv4 address of the game server. + */ + String gameserverip; + + /** Some sort of representation of the start time of the game. + * + * \todo Figure out what this represents. + */ + double gamestarttime; + + /** The game type, expansion or not. + * + * \todo Determine what the values are. + */ + int gametype; + + /** Whether or not there is an item on the cursor. + */ + bool itemoncursor; + + /** Whether or not the game is a ladder game. + */ + bool ladder; + + /** The ping in milliseconds. + */ + int ping; + + /** The frame rate. + */ + int fps; + + /** Whether or not the gametype is hardcore. + */ + int playertype; + + /** The realm name. + */ + String realm; + + /** The short realm name. + * + * \todo Determine the difference between this and realm. + */ + String realmshort; + + /** The cost to revive the merc. + */ + int mercrevivecost; + + /** Whether the controlled character is in the always run mode or not. + * + * 0 - Walk unless directed to run + * 1 - Always run + */ + int runwalk; + + /** The health at which to chicken if the character drops below. + */ + int chickenhp; + + /** The mana at which to chicken if the character drops below. + */ + int chickenmp; + + /** Whether to chicken if another player hostiles the controlled character. + */ + bool quitonhostile; + + /** Block keys... + * + * \todo Determine what this means. + */ + bool blockKeys; + + /** Block mouse... + * + * \todo Determine what this means. + */ + bool blockMouse; + + /** Whether or not the game window is in the game. + */ + bool gameReady; + + /** The profile currently being used. + */ + String profile; + + /** Whether the game is set to not pick up items or not. + */ + int nopickup; + + /** The process id of Diablo II. + */ + double pid; + + /** The window size. + * + * \todo Determine what the numbers mean. + */ + int screensize; + + /** The window title. + */ + String windowtitle; + + /** True if the game is not at menu. + * + * \todo Determine when this is different from gameReady. Maybe when going + * between acts for instance. + */ + bool ingame; + + /** Whether or not to quit when there's an error. + * + * \todo Figure out if this means js errors. + */ + bool quitonerror; + + /** The max time in milliseconds to stay in game before the game auto-quits. + */ + int maxgametime; +}; diff --git a/doc/Party.h b/doc/Party.h new file mode 100644 index 00000000..2734b3a4 --- /dev/null +++ b/doc/Party.h @@ -0,0 +1,58 @@ +/** Represents the items in the list in the Party screen. Also called a + * RosterUnit. + */ +class Party +{ +public: + /** The x coordinate of the location of the RosterUnit. + */ + int x; + + /** The y coordinate of the location of the RosterUnit. + */ + int y; + + /** The Area ID of the RosterUnit. + */ + int area; + + /** The unique id of the RosterUnit. + */ + int gid; + + /** The life of the RosterUnit. + * + * \todo Determine how one is to get the maximum life of the RosterUnit. + */ + int life; + + /** The Party flags of the RosterUnit. + * + * \todo Determine the values that this can take on. + */ + int partyflag; + + /** The Party ID. + * + * \todo Determine what a Party ID is. + */ + int partyid; + + /** The name of the RosterUnit. + */ + String name; + + /** The class ID of the RosterUnit. See Unit::classId. + */ + int classid; + + /** The character level of the RosterUnit. + * + * \todo Verify that this level is the character level. + */ + int level; + + /** Move to the next RosterUnit. + */ + void getNext(); +}; diff --git a/doc/PresetUnit.h b/doc/PresetUnit.h new file mode 100644 index 00000000..425a1ff4 --- /dev/null +++ b/doc/PresetUnit.h @@ -0,0 +1,36 @@ +/** Represents a PresetUnit (a type of Unit that is available as soon as the + * Area data is available). + * + * \todo Determine how location is determine based off roomx, roomy, x, and y. + */ +class PresetUnit +{ +public: + /** The type ID. See Unit::type. + */ + int type; + + /** The room X (?). + */ + int roomx; + + /** The room Y (?). + */ + int roomy; + + /** The X coordinate (?). + */ + int x; + + /** The Y coordinate (?). + */ + int y; + + /** The unique ID of the PresetUnit. + */ + int id; + + /** The Area ID of the Area the PresetUnit is in. + */ + int level; +}; diff --git a/doc/Room.h b/doc/Room.h new file mode 100644 index 00000000..57383f97 --- /dev/null +++ b/doc/Room.h @@ -0,0 +1,154 @@ +/** Represents a "Room" in the game. A Room is a rectangular piece of the map + * data. It has pointers to many lists, such as a list of PresetUnit s. + */ +class Room +{ +public: + /** Move to the next Room. + * + * \return Whether there was another Room to move to or not. + */ + bool getNext(); + + /** Reveal the Room on the map. + * + * \return Whether or not the Room was successfully revealed. + */ + bool reveal(); + + /** Get the PresetUnit s from the current Room. + * + * \return An array of all the PresetUnit s from the current Room. + */ + PresetUnit[] getPresetUnits(); + + /** Get the PresetUnit s from the current Room. + * + * \param nType The type of Unit to get. See Unit::type. + * + * \return An array of all the PresetUnit s from the current Room. + */ + PresetUnit[] getPresetUnits(int nType); + + /** Get the PresetUnit s from the current Room. + * + * \param nType The type of Unit to get. See Unit::type. + * + * \param nClass The class id of the Unit (s) to find. See Unit::classId. + * + * \return An array of all the PresetUnit s from the current Room. + */ + PresetUnit[] getPresetUnits(int nType, int nClass); + + /** Get the collision data for the Room. + * + * \todo Verify that the array does actually have reverse of usual + * dimensions. + * + * \return An array with the collision data. The first dimension is the y + * coordinate, the second is the x coordinate. + */ + int[][] getCollision(); + + /** Get the "nearby" Rooms from pRoom2Near member. + * + * \return An array of the nearby Rooms. + */ + Room[] getNearby(); + + /** Get some property of the Room. + * + * \param nStat Which property to get: + * + * 0 - xStart (room 1) + * + * 1 - yStart (room 1) + * + * 2 - xSize (room 1) + * + * 3 - ySize (room 1) + * + * 4 - posX (room 2) + * + * 5 - posY (room 2) + * + * 6 - sizeX (room 2) + * + * 7 - sizeY (room 2) + * + * 9 - posGameX (coll) + * + * 10 - posGameY (coll) + * + * 11 - sizeGameX (coll) + * + * 12 - sizeGameY (coll) + * + * 13 - posRoomX (coll) + * + * 14 - posGameY (coll) + * + * 15 - sizeRoomX (coll) + * + * 16 - sizeRoomY (coll) + * + * \return The stat value. + */ + int getStat(int nStat); + + /** Get the first Room of the level this Room is on. + * + * \return The first Room. + */ + Room getFirst(); + + /** Determine whether or not the Unit is in the Room. + * + * \param unit The unit to check. + * + * \return Whether or not the Unit is in the Room. + */ + bool unitInRoom(Unit unit); + + /** Get the Room number. + * + * \todo Determine what a "room number" is. + */ + int number; + + /** Get the x coordinate of the Room. + */ + int x; + + /** Get the y coordinate of the Room. + */ + int y; + + /** Get the x size (width) of the Room. + */ + int xsize; + + /** Get the y size (height) of the Room. + */ + int ysize; + + /** No implementation. + */ + int subnumber; + + /** Get the Area ID for the area which the Room is in. + */ + int area; + + /** Get the Area ID for the area which the Room is in. + */ + int level; + + /** Get the correct tomb. + * + * \todo Determine if this is the Area ID of the correct tomb. + * + * \todo Determine what Room s this is valid on. + */ + int correcttomb; +}; diff --git a/doc/SQLite.h b/doc/SQLite.h new file mode 100644 index 00000000..6015abc5 --- /dev/null +++ b/doc/SQLite.h @@ -0,0 +1,77 @@ +/** Class for dealing with an SQLite database. + */ +class SQLite +{ +public: + /** Create a database object which can be used to open SQLite databases and + * execute queries. Opens the :memory: path immediately. + */ + SQLite(); + + /** Create a database object which can be used to open SQLite databases and + * execute queries. Opens the database immediately. + * + * \param path The path to the database to open. + */ + SQLite(String path); + + /** Create a database object which can be used to open SQLite databases and + * execute queries. + * + * \param path The path to the database to open. + * + * \param autoOpen Whether to open the database immediately or not. + */ + SQLite(String path, bool autoOpen); + + /** Execute a query on the database. + * + * \param queryString The query string to execute. + * + * \return true + */ + bool execute(String queryString); + + /** Do a sqlite3_prepare_v2 on the database with sql, then call the + * appropriate sqlite3_bind_ functions on the remaining parameters. + * + * \param sql The query to pass to sqlite3_prepare v2. + * + * \todo Determine what this function does (better documenation). + * + * \return The resulting DBStatement. + */ + DBStatement query(String sql, ...); + + /** Open the database. + * + * \return true + */ + bool open(); + + /** Close the database. + * + * \return true + */ + bool close(); + + /** Get the path used to open the database. + */ + String path; + + /** Get all the statements that have been queried. + */ + DBStatement[] statements; + + /** Whether or not the database is open. + */ + bool isOpen; + + /** Get the row id of the last inserted row. + */ + int lastRowId; + + /** Get the number of rows modified/inserted/deleted by the last statement. + */ + double changes; +}; diff --git a/doc/Sandbox.h b/doc/Sandbox.h new file mode 100644 index 00000000..32aae42b --- /dev/null +++ b/doc/Sandbox.h @@ -0,0 +1,39 @@ +/** A separate context to run scripts in. + */ +class Sandbox +{ +public: + /** Create a Sandbox. This creates a separate context to run things in. + */ + Sandbox(); + + /** Evaluate the code passed in and return the result. + * + * \param code The code to run, literally JavaScript code to run. + * + * \return The result of the last expression statement. + */ + Object evaluate(String code); + + /** Include a file from ScriptPath\\libs\\file. + * + * \param file The filename relative to ScriptPath\\libs to include. + * + * \return The result of the last expression statement. + */ + Object include(String file); + + /** Determine whether a file has been included yet or not. + * + * \param file The filename relative to ScriptPath\\libs to include. + * + * \return Whether or not the file has been included. + */ + bool isInclude(String file); + + /** Clear the scope of the Sandbox's global object. + * + * \todo Clarify what this means (i.e. post-conditions). + */ + void clearScope(); +}; diff --git a/doc/ScreenHooks.h b/doc/ScreenHooks.h new file mode 100644 index 00000000..766cf5ed --- /dev/null +++ b/doc/ScreenHooks.h @@ -0,0 +1,21 @@ +/** The type of a click handler. + * + * \ingroup handlers + * + * \param button The button clicked. + * + * \param x The x coordinate clicked. + * + * \param y The y coordinate clicked. + */ +typedef ClickHandler (bool*)(int button, int x, int y); + +/** The type of a hover handler. + * + * \ingroup handlers + * + * \param x The x coordinate hovered. + * + * \param y The y coordinate hovered. + */ +typedef HoverHandler (void*)(int x, int y); diff --git a/doc/Text.h b/doc/Text.h new file mode 100644 index 00000000..54926ba8 --- /dev/null +++ b/doc/Text.h @@ -0,0 +1,260 @@ +#include "ScreenHooks.h" + +/** A Text screen hook + * + * \todo Verify all the documentation in this class. + */ +class Text +{ +public: + /** Create a Text hook with the given parameters. + * + * Uses defaults szText = "", x = 0, y = 0, color = 0, font = 0, align = 0, + * automap = false, click = null, hover = null. + */ + Text(); + + /** Create a Text hook with the given parameters. + * + * Uses defaults x = 0, y = 0, color = 0, font = 0, align = 0, + * automap = false, click = null, hover = null. + * + * \param szText The string that the Text hook displays. + */ + Text(String szText); + + /** Create a Text hook with the given parameters. + * + * Uses defaults y = 0, color = 0, font = 0, align = 0, automap = false, + * click = null, hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + */ + Text(String szText, int x); + + /** Create a Text hook with the given parameters. + * + * Uses defaults color = 0, font = 0, align = 0, automap = false, + * click = null, hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + */ + Text(String szText, int x, int y); + + /** Create a Text hook with the given parameters. + * + * Uses defaults font = 0, align = 0, automap = false, click = null, + * hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + * + * \param color The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + Text(String szText, int x, int y, int color); + + /** Create a Text hook with the given parameters. + * + * Uses defaults align = 0, automap = false, click = null, hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + * + * \param color The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param font Something that determines the font. + */ + Text(String szText, int x, int y, int color, int font); + + /** Create a Text hook with the given parameters. + * + * Uses defaults automap = false, click = null, hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + * + * \param color The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param font Something that determines the font. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + Text(String szText, int x, int y, int color, int font, int align); + + /** Create a Text hook with the given parameters. + * + * Uses defaults click = null, hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + * + * \param color The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param font Something that determines the font. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Text is in automap coordinate space (true) or + * screen coordinate space (false). + */ + Text(String szText, int x, int y, int color, int font, int align, + bool automap); + + /** Create a Text hook with the given parameters. + * + * Uses default hover = null. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + * + * \param color The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param font Something that determines the font. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Text is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Text is + * clicked. + */ + Text(String szText, int x, int y, int color, int font, int align, + bool automap, ClickHandler click); + + /** Create a Text hook with the given parameters. + * + * \param szText The string that the Text hook displays. + * + * \param x The x coordinate (left) of the Text. + * + * \param y The y coordinate (top) of the Text. + * + * \param color The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + * + * \param font Something that determines the font. + * + * \param align The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + * + * \param automap Whether the Text is in automap coordinate space (true) or + * screen coordinate space (false). + * + * \param click The click handler that gets called when the Text is + * clicked. + * + * \param hover The hover handler that gets called when the Text gets + * hovered over. + */ + Text(String szText, int x, int y, int color, int font, int align, + bool automap, ClickHandler click, HoverHandler hover); + + /** Remove the Text hook from the screen and destroy the corresponding + * object. + */ + void remove(); + + /** The x coordinate (left) of the Text. + */ + int x; + + /** The y coordinate (top) of the Text. + */ + int y; + + /** Whether or not the Text is visible. + */ + bool visible; + + /** The horizontal alignment. + * + * 0 - Left + * + * 1 - Right + * + * 2 - Center + */ + int align; + + /** The z-order of the Text (what it covers up and is covered by). + */ + int zorder; + + /** The click handler that gets called when the Text is clicked. + */ + ClickHandler click; + + /** The hover handler that gets called when the Text gets hovered over. + */ + HoverHandler hover; + + /** The color of the Text. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1000 + */ + int color; + + /** Something that determines the font. + */ + int font; + + /** The string that the Text hook displays. + */ + String text; +}; diff --git a/doc/Unit.h b/doc/Unit.h new file mode 100644 index 00000000..73ecb067 --- /dev/null +++ b/doc/Unit.h @@ -0,0 +1,895 @@ +/** This class represents a unit (monster, wp, npc, character, etc) in the + * game. + */ +class Unit +{ +public: + /** Get the next unit that matches the originally given name or class id and + * originally specified mode. + * + * \return Whether another unit was found. + */ + bool getNext(); + + /** Get the next unit that matches the given name and originally specified + * mode. + * + * \param szName The name to look for. + * + * \return Whether another unit was found. + */ + bool getNext(String szName); + + /** Get the next unit that matches the given class id and originally + * specified mode. + * + * \param dwClassId The class id to look for. + * + * \return Whether another unit was found. + */ + bool getNext(uint32_t dwClassId); + + /** Get the next unit that matches the given name and mode. + * + * \param szName The name to look for. + * + * \param dwMode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched for. + * + * \return Whether another unit was found. + */ + bool getNext(String szName, uint32_t dwMode); + + /** Get the next unit that matches the given class id and mode. + * + * \param dwClassId The class id to look for. + * + * \param dwMode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched for. + * + * \return Whether another unit was found. + */ + bool getNext(uint32_t dwClassId, uint32_t dwMode); + + /** Cancel whatever's going on. + * + * If there's scrolling text clear it. + * If you're interacting to an NPC, stop. + * If there's an item on the cursor, drop it. + * Otherwise close any other interaction that might be going on. + */ + void cancel(); + + /** Close some form of interaction. + * + * \todo Clarify what each of the calls do. + * + * \param type Type of interaction to cancel + * + * 0 - Call D2CLIENT_CloseInteract + * + * 1 - Call D2CLIENT_CloseNPCInteract + */ + void cancel(int type); + + /** Try to repair. + * + * Need to be able to find unit that you're trying to repair with. That + * means the unit needs to still be in the server unit hash table. + * + * \return true if successful. + */ + bool repair(); + + /** Use an NPC menu. + * + * Need to be able to find unit that you're trying to repair with. That + * means the unit needs to still be in the server unit hash table. + * + * \param menuItem Index of the menu item to click. + * + * \return true if menu was found. + */ + bool useMenu(int menuItem); + + /** Interact with the unit. + * + * If the unit is an item in inventory pick it up. Otherwise click it on + * the map. + */ + bool interact(); + + /** Interact with a waypoint. + * + * If the unit is an object, assume it's a waypoint, and take it. + * + * \param destId The area id of the destination to select. + */ + bool interact(int destId); + + /** Get the first item from inventory. + * + * \return The first item from inventory. + */ + Unit getItem(); + + /** Get an item from inventory by name. + * + * \param name The name of the item to look for. + * + * \return The first item found that matches the description. + */ + Unit getItem(String name); + + /** Get an item from inventory by classId. + * + * \param classId The class id of the unit. + * + * \return The first item found that matches the description. + */ + Unit getItem(uint32_t classId); + + /** Get an item from inventory by name and mode. + * + * \param name The name of the unit to look for. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \return The first item found that matches the description. + */ + Unit getItem(String name, uint32_t mode); + + /** Get an item from inventory by classId and mode. + * + * \param classId The class id of the unit. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \return The first item found that matches the description. + */ + Unit getItem(uint32_t classId, uint32_t mode); + + /** Get an item from inventory by name, mode and nUnitId. + * + * \param name The name of the unit to look for. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \param nUnitId The unique id of the unit. + * + * \return The first item found that matches the description. + */ + Unit getItem(String name, uint32_t mode, uint32_t nUnitId); + + /** Get an item from inventory by classId, mode and nUnitId. + * + * \param classId The class id of the unit. + * + * \param mode Either the mode being searched for, or a bitmask with bit + * 29 set and bits 0-28 corresponding to modes of units being searched + * for. + * + * \param nUnitId The unique id of the unit. + * + * \return The first item found that matches the description. + */ + Unit getItem(uint32_t classId, uint32_t mode, uint32_t nUnitId); + + /** Get all items from inventory. + * + * \return An array of all the items from inventory. + */ + Unit[] getItems(); + + /** Get whether this player has a merc. + * + * The unit being operated on should be a player. + * + * \param dummy Used to signify boolean result instead of object. Should + * be true. + * + * \return true if the player has a live merc. + */ + bool getMerc(bool dummy); + + /** Get a player's merc. + * + * The unit being operated on should be a player. + * + * \return The merc if there is one. + */ + Unit getMerc(); + + /** Get skill name from hand. + * + * \param hand Hand to get the skill name off. + * + * 0 - Right hand + * + * 1 - Left hand + * + * \return Skill name. + */ + String getSkill(int hand); + + /** Get skill id from hand. + * + * \param hand Hand to get the skill id off. + * + * 2 - Right hand + * + * 3 - Left hand + * + * \return Skill id. + */ + int getSkill(int hand); + + /** Get all skills. + * + * Gets all skill ids, along with corresponding base and total skill + * levels. + * + * \param dummy Should be 4. + * + * \return An array of arrays of integers. Inside the inner array the + * 0th index is the skill id, the 1st index is the base skill level and + * the 2nd index is the total skill level. Only the first 256 skills are + * read. + */ + int[][] getSkill(int dummy); + + /** Calls D2COMMON_GetSkillLevel and returns the result. + * + * \todo Figure out what D2COMMON_GetSkillLevel does. + * + * \returns Whatever D2COMMON_GetSkillLevel returns. + */ + int getSkill(int nSkillId, int nExt); + + /** Gets the parent of a unit. + * + * This function is used for monster and item units. + * + * \return The parent unit. + */ + Unit getParent(); + + /** Gets the parent of a unit. + * + * This function is used for object units. + * + * \return The parent's name. + */ + String getParent(); + + /** Puts the string equivalent of message over the unit. + */ + void overhead(Object message); + + /** Returns the item flags. + * + * \returns Item flags: + * + * 0x00000001 - Equipped + * + * 0x00000008 - In socket + * + * 0x00000010 - Identified + * + * 0x00000040 - Weapon/shield is in the active weapon switch + * + * 0x00000080 - Weapon/shield is in the inactive weapon switch + * + * 0x00000100 - Item is broken + * + * 0x00000400 - Full rejuv + * + * 0x00000800 - Socketed + * + * 0x00002000 - In the trade or gamble screen + * + * 0x00004000 - Not in a socket + * + * 0x00010000 - Is an ear + * + * 0x00020000 - A starting item (worth only 1 gold) + * + * 0x00200000 - Rune, or potion, or mephisto's soulstone + * + * 0x00400000 - Ethereal + * + * 0x00800000 - Is an item + * + * 0x01000000 - Personalized + * + * 0x04000000 - Runeword + * + * Source: http://subversion.assembla.com/svn/d2bs/scripts/YAMB/libs/YAMB/common/YAM-Common.dbl r1086 + */ + int getFlags(); + + /** Same as getFlags, but returns a boolean. + * + * Returns true if any of the flags given match the item flags. + * + * \ref getFlags + * + * \param flags Flags to check. + * + * \return true if any of the flags are set in the item flags. + */ + bool getFlag(int flags); + + /** Get a stat by stat id. + * + * Used for everything except stats 6-11. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \return The stat value. + */ + double getStat(int nStat); + + /** Get a stat by stat id and sub index. + * + * Used for stats 6-11. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \return The stat value. + */ + int getStat(int nStat); + + /** Get a stat by stat id and sub index. + * + * Used for stat 13. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \param nSubIndex A subindex to a certain type of stat. For instance a + * specific skill for the +1 to skill tab stat. + * + * \return The stat value. + */ + double getStat(int nStat, int nSubIndex); + + /** Get a stat by stat id and sub index. + * + * Used for everything except stat 13. + * + * \param nStat The stat type. + * See http://forums.d2botnet.org/viewtopic.php?f=18&t=989 + * + * \param nSubIndex A subindex to a certain type of stat. For instance a + * specific skill for the +1 to skill tab stat. + * + * \return The stat value. + */ + int getStat(int nStat, int nSubIndex); + + /** Get an array of all the stats of the item. + * + * \param nStat Set to -1. + * + * \return An array of the first 64 stats. The indices of the inner array + * are: 0 - nStat, 1 - nSubIndex, 2 - nValue. + */ + int[][] getStat(int nStat); + + /** Get an array of all the stats of the item. + * + * \param nStat Set to -1. + * + * \param nSubIndex Ignored. + * + * \return An array of the first 64 stats. The indices of the inner array + * are: 0 - nStat, 1 - nSubIndex, 2 - nValue. + */ + int[][] getStat(int nStat, int nSubIndex); + + /** Return whether or not the unit has a given state. + * + * \param nState The state id. + * + * \return Whether or not the unit has the state. + */ + bool getState(int nState); + + /** Get the price of the item at npc 148, with "buysell" of 0, in the + * current difficult. + * + * \todo Determine if this is the buy or sell price. "buysell" is 0. + * + * \return Some sort of price. + */ + int getPrice(); + + /** Get the price of the item at a given npc, with "buysell" of 0, in the + * current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npc The npc to determine the price at. + * + * \return The price requested. + */ + int getPrice(Unit npc); + + /** Get the price of the item at a given npc (by id), with "buysell" of 0, + * in the current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npcId The id of the npc to determine the price at. + * + * \return The price requested. + */ + int getPrice(int npcId); + + /** Get the price of the item at a given npc, with choice of buying or + * selling, in the current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npc The npc to determine the price at. + * + * \param buysell Unknown + * + * \return The price requested. + */ + int getPrice(Unit npc, int buysell); + + /** Get the price of the item at a given npc (by id), which choice of buying + * or selling, in the current difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npcId The id of the npc to determine the price at. + * + * \param buysell Unknown + * + * \return The price requested. + */ + int getPrice(int npcId, int buysell); + + /** Get the price of the item at a given npc, with choice of buying or + * selling, in a given difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npc The npc to determine the price at. + * + * \param buysell Unknown + * + * \param difficulty The difficulty of interest: 0 - normal, 1 - nightmare, + * 2 - hell + * + * \return The price requested. + */ + int getPrice(Unit npc, int buysell, int difficulty); + + /** Get the price of the item at a given npc (by id), with choice of buying + * or selling, in a given difficulty. + * + * \todo Determine the meaning of "buysell". + * + * \param npcId The id of the npc to determine the price at. + * + * \param buysell Unknown + * + * \param difficulty The difficulty of interest: 0 - normal, 1 - nightmare, + * 2 - hell + * + * \return The price requested. + */ + int getPrice(int npcId, int buysell, int difficulty); + + /** Determine whether or not a unit has a given enchant. + * + * \param nEnchant Enchantment id. + * + * \return Whether or not the unit has the enchantment. + */ + bool getEnchant(int nEnchant); + + /** Shop with a given npc, either buying or selling. + * + * \param dwMode What to do with the item. 1 - Sell, 2 - Buy, 6 - ? + * + * \return Whether or not the shop went through. + */ + bool shop(int dwMode); + + /** Set the skill on the given hand to be skill with name skillName. + * + * Waits up to one second for the skill to be set. + * + * \todo Fix argc < 1, should be argc < 2 + * + * \param skillName Name of the skill to put up. + * + * \param nHand Hand to put the skill on. non-zero left, 0 - right. + * + * \return Whether operation was successful. + */ + bool setSkill(String skillName, int nHand); + + /** Set the skill on the given hand to be skill with id nSkillId. + * + * Waits up to one second for the skill to be set. + * + * \todo Fix argc < 1, should be argc < 2 + * + * \param nSkillId Id of the skill to put up. + * + * \param nHand Hand to put the skill on. non-zero left, 0 - right. + * + * \return Whether operation was successful. + */ + bool setSkill(int nSkillId, int nHand); + + /** Move to the given location. + * + * \param x The x location. + * + * \param y The y location. + */ + void move(int x, int y); + + /** Move to this unit. + */ + void move(); + + /** Get the quest flag for a quest specified by act and quest number. + * + * \param nAct The act of the quest. + * + * \param nQuest The quest number. + * + * \return The quest flag for the specified quest. + */ + int getQuest(int nAct, int nQuest); + + /** Get the number of minions of a certain type. + * + * \param nType The type of the minions. + * + * \return The number of minions of the specified type. + */ + int getMinionCount(int nType); + + /** Get price to repair this unit at the current npc or npc 0x9A if not + * currently interacting. + * + * \return The price to repair the given unit. + */ + int getRepairCost(); + + /** Get price to repair this unit at the current npc given by nNpcClassId. + * + * \param nNpcClassId The class id of the npc to get the price for repair + * at. + * + * \return The price to repair the given unit. + */ + int getRepairCost(int nNpcClassId); + + /** Get the cost to do something (buy, sell, repair) with the given item. + * + * \param nMode What to do: 0 - buy, 1 - sell, 2 - repair. + * + * \return The price. + */ + int getItemCost(int nMode); + + /** Get the cost to do something (buy, sell, repair) with the given item, at + * the given npc. + * + * \param nMode What to do: 0 - buy, 1 - sell, 2 - repair. + * + * \param nNpcClassId The class id of the npc to check the price with. + * + * \return The price. + */ + int getItemCost(int nMode, int nNpcClassId); + + /** Get the cost to do something (buy, sell, repair) with the given item, at + * the given npc, in the given difficulty. + * + * \param nMode What to do: 0 - buy, 1 - sell, 2 - repair. + * + * \param nNpcClassId The class id of the npc to check the price with. + * + * \param nDifficulty The difficulty to check the price in. + * + * \return The price. + */ + int getItemCost(int nMode, int nNpcClassId, int nDifficulty); + + /** The type of the unit. + * + * 0 - Player + * + * 1 - NPC + * + * 2 - Object + * + * 3 - Missile + * + * 4 - Item + * + * 5 - Warp + * + * Source: botNET + */ + int type; + + /** The class id of the object. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=1002 + * + * http://forums.d2botnet.org/viewtopic.php?f=18&t=986 and + * + * http://forums.d2botnet.org/viewtopic.php?f=18&t=985 + */ + int classId; + + /** The mode of the unit. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=988 + */ + int mode; + + /** The name of the unit. + */ + String name; + + /** The act where the unit is currently located. + */ + int act; + + /** The unit unique id. Referred to simply as the unit id. Used along with + * the unit type to uniquely identify the unit. + */ + int gid; + + /** The x location of the unit. + */ + int x; + + /** The y location of the unit. + */ + int y; + + /** The id of the area (level) the unit is located in. + * + * \todo Get a reference for the area IDs. + */ + int area; + + /** The unit's current health. + */ + int hp; + + /** The unit's maximum health. + */ + int hpmax; + + /** The unit's current mana. + */ + int mp; + + /** The unit's maximum mana. + */ + int mpmax; + + /** The unit's current stamina. + */ + int stamina; + + /** The unit's maximum stamina. + */ + int staminamax; + + /** The character level. The level that determines stat points, skill + * levels, etc. + */ + int charlvl; + + /** The number of items in inventory. + */ + int itemcount; + + /** The unit id of the owner of the unit. + */ + int owner; + + /** The type of owner. + * + * \ref type + */ + int ownertype; + + /** The special type of the unit. Represents things like unique, minion, + * boss, etc. + * + * 1 - "Normal" Boss + * 2 - Champion + * 4 - Boss + * 8 - Minion + */ + int spectype; + + /** The direction of the unit. + * + * \todo Figure out what the direction is. + */ + int direction; + + /** The unique id of a boss. Taken from pUnit->pMonsterData->wUniqueNo. Not + * the same thing as the gid (unit id). + */ + int uniqueid; + + /** The three digit code for an item. + * + * See: http://forums.d2botnet.org/viewtopic.php?f=18&t=991 + */ + String code; + + /** The magic prefix of the item. + */ + String prefix; + + /** The magic suffix of the item. + */ + String suffix; + + /** The id code for the magic prefix. + */ + int prefixnum; + + /** The id code for the magic suffix. + */ + int suffixnum; + + /** The full name of an item. + */ + String fname; + + /** The item quality. + * + * 1 - Low quality + * + * 2 - Normal + * + * 3 - Superior + * + * 4 - Magic + * + * 5 - Set + * + * 6 - Rare + * + * 7 - Unique + * + * 8 - Crafted + * + * Source: botNET + */ + int quality; + + /** No clue. + * + * \todo Get a clue. + */ + int node; + + /** The location of the item (ground, inventory, stash, etc.). + * + * 0 - Ground + * + * 1 - Equipped + * + * 2 - Belt + * + * 3 - Inventory + * + * 4 - Store + * + * 5 - Trade + * + * 6 - Cube + * + * 7 - Stash + * + * Source: d2botnet code + */ + int location; + + /** The x size of the item. + */ + int sizex; + + /** The y size of the item. + */ + int sizey; + + /** The type of the item. + * + * \todo Put together a reference for item type. + */ + int itemType; + + /** The description of the item. + */ + String description; + + /** The equipped location of the item. + * + * 0 - Not equipped + * + * 1 - Helmet + * + * 2 - Amulet + * + * 3 - Armor + * + * 4 - Right hand slot 1 + * + * 5 - Left hand slot 1 + * + * 6 - Right ring + * + * 7 - Left ring + * + * 8 - Belt + * + * 9 - Boots + * + * 10 - Gloves + * + * 11 - Right hand slot 2 + * + * 12 - Left hand slot 2 + */ + int bodylocation; + + /** Item level. Used for things like item stat rolling. + */ + int ilvl; + + /** Level requirement (character level required to use the item). + */ + int ilvlreq; + + /** Whether the controlled character is in the always run mode or not. + * + * 0 - Walk unless directed to run + * 1 - Always run + */ + int runwalk; + + /** Set the weapon switch. + */ + int weaponswitch; + + /** The object type. + * + * \todo Figure out what this means. + */ + int objtype; + + /** Whether or not the chest is locked. + */ + int islocked; +}; diff --git a/doc/globalFuncs.h b/doc/globalFuncs.h new file mode 100644 index 00000000..74a4cc22 --- /dev/null +++ b/doc/globalFuncs.h @@ -0,0 +1,2273 @@ +/** \defgroup globalFunctions Global functions + */ + +/** Get a unit by type. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type); + +/** Get a unit by type and name. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \param name The name of the unit to look for. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type, char* name); + +/** Get a unit by type and class id. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \param classId The class id of the unit. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type, uint32_t classId); + +/** Get a unit by type, name and mode. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \param name The name of the unit to look for. + * + * \param mode Either the mode being searched for, or a bitmask with bit 29 set + * and bits 0-28 corresponding to modes of units being searched for. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type, char* name, uint32_t mode); + +/** Get a unit by type, classId and mode. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \param classId The class id of the unit. + * + * \param mode Either the mode being searched for, or a bitmask with bit 29 set + * and bits 0-28 corresponding to modes of units being searched for. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type, uint32_t classId, uint32_t mode); + +/** Get a unit by type, name, mode and nUnitId. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \param name The name of the unit to look for. + * + * \param mode Either the mode being searched for, or a bitmask with bit 29 set + * and bits 0-28 corresponding to modes of units being searched for. + * + * \param nUnitId The unique id of the unit. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type, char* name, uint32_t mode, uint32_t nUnitId); + +/** Get a unit by type, classId, mode and nUnitId. + * + * \ingroup globalFunctions + * + * \param type The type of the unit. Set to -1 to get any unit. 100 gets the + * cursor item, 101 gets the selected unit. + * + * \param classId The class id of the unit. + * + * \param mode Either the mode being searched for, or a bitmask with bit 29 set + * and bits 0-28 corresponding to modes of units being searched for. + * + * \param nUnitId The unique id of the unit. + * + * \return The first unit found that matches the description. + */ +Unit getUnit(int type, uint32_t classId, uint32_t mode, uint32_t nUnitId); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area ID, source and destination points as parameters. + * + * \ingroup globalFunctions + * + * \param Area The Area ID to path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t Area, uint32_t srcX, uint32_t srcY, uint32_t dstX, + int dstY); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area ID, source and destination points, and walking or + * teleporting as parameters. + * + * \ingroup globalFunctions + * + * \param Area The Area ID to path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \param UseTele Whether or not the path can do things like jump walls. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t Area, uint32_t srcX, uint32_t srcY, uint32_t dstX, + int dstY, bool UseTele); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area ID(s), source and destination points, walking or + * teleporting and range as parameters. + * + * \ingroup globalFunctions + * + * \param Area The Area ID to path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \param UseTele Whether or not the path can do things like jump walls. + * + * \param Radius The distance between each point. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t Area, uint32_t srcX, uint32_t srcY, uint32_t dstX, + int dstY, bool UseTele, uint32_t Radius); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area ID, source and destination points, walking or + * teleporting, range and reduction or not as parameters. + * + * \ingroup globalFunctions + * + * \param Area The Area ID to path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \param UseTele Whether or not the path can do things like jump walls. + * + * \param Radius The distance between each point. + * + * \param Reduction Whether or not to reduce the path. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t Area, uint32_t srcX, uint32_t srcY, uint32_t dstX, + int dstY, bool UseTele, uint32_t Radius, bool Reduction); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area IDs, source and destination points as parameters. + * Assumes teleporting unless in town. + * + * \ingroup globalFunctions + * + * \param AreaIds An array of Area IDs to possibly path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t[] AreaIds, uint32_t srcX, uint32_t srcY, + uint32_t dstX, int dstY); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area IDs, source and destination points, and walking or + * teleporting as parameters. + * + * \ingroup globalFunctions + * + * \param AreaIds An array of Area IDs to possibly path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \param UseTele Whether or not the path can do things like jump walls. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t[] AreaIds, uint32_t srcX, uint32_t srcY, + uint32_t dstX, int dstY, bool UseTele); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area IDs, source and destination points, walking or + * teleporting, and range as parameters. + * + * \ingroup globalFunctions + * + * \param AreaIds An array of Area IDs to possibly path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \param UseTele Whether or not the path can do things like jump walls. + * + * \param Radius The distance between each point. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t[] AreaIds, uint32_t srcX, uint32_t srcY, + uint32_t dstX, int dstY, bool UseTele, uint32_t Radius); + +/** Creates a path (walking or teleporting) from the source to the destination. + * Returns an array of points that form a path from the source to the + * destination. Takes Area IDs, source and destination points, walking or + * teleporting, range and reduction or not as parameters. + * + * \ingroup globalFunctions + * + * \param AreaIds An array of Area IDs to possibly path through. + * + * \param srcX The source X coordinate. + * + * \param srcY The source Y coordinate. + * + * \param dstX The destination X coordinate. + * + * \param dstY The destination Y coordinate. + * + * \param UseTele Whether or not the path can do things like jump walls. + * + * \param Radius The distance between each point. + * + * \param Reduction Whether or not to reduce the path. + * + * \return The path as an array of objects with x and y properties. + */ +object[] getPath(uint32_t[] AreaIds, uint32_t srcX, uint32_t srcY, + uint32_t dstX, int dstY, bool UseTele, uint32_t Radius, bool Reduction); + +/** Get the collision flags at a given point in a given area. + * + * \ingroup globalFunctions + * + * \param nLevelId The level id of the area in question. + * + * \param nX The x coordinate of the point in question. + * + * \param nY The y coordinate of the point in question. + * + * \return The collision flags. For details see: + * http://forums.d2botnet.org/viewtopic.php?f=18&t=1212 . + */ +unsigned short getCollision(uint32_t nLevelId, int32_t nX, int32_t nY); + +/** Get the health points of the controlled unit's merc. + * + * \ingroup globalFunctions + * + * \return The health points. + */ +int getMercHP(); + +/** Get the cursor type from p_D2CLIENT_RegularCursorType. + * + * \ingroup globalFunctions + * + * \todo Determine what the return value means. + * + * \return The regular cursor type. + */ +int getCursorType(); + +/** Get the cursor type from p_D2CLIENT_RegularCursorType if nType != 1, from + * p_D2CLIENT_ShopCursorType if nType == 1. + * + * \ingroup globalFunctions + * + * \param nType What type of cursor to get. 1 - ShopCursorType, other - + * RegularCursorType. + * + * \todo Determine what the return value means. + * + * \return The cursor type. + */ +int getCursorType(int nType); + +/** Get skill ID by name. + * + * \ingroup globalFunctions + * + * \param skillName The skill name. + * + * \return The skill ID. + */ +int getSkillByName(String skillName); + +/** Get skill name by ID. + * + * \ingroup globalFunctions + * + * \param skillId The skill ID. + * + * \return The skill name. + */ +String getSkillById(int skillId); + +/** Get the String in the current locale that corresponds to the given id. + * + * \ingroup globalFunctions + * + * \param localeId The id of the String. + * + * \return The String in the current locale. + */ +String getLocaleString(uint16_t localeId); + +/** Get the width and height of the given text in the given font. + * + * \ingroup globalFunctions + * + * \param string The string to get the size of. + * + * \param font The font to use. + * + * \return The width and height of the text. 0 - width, 1 - height. + */ +int[] getTextSize(String string, int font); + +/** Get the width and height of the given text in the given font. + * + * \ingroup globalFunctions + * + * \param string The string to get the size of. + * + * \param font The font to use. + * + * \param asObject False to return as an array. + * + * \return The width and height of the text. 0 - width, 1 - height. + */ +int[] getTextWidthHeight(String string, int font, bool asObject); + +/** Get the width and height of the given text in the given font. + * + * \ingroup globalFunctions + * + * \param string The string to get the size of. + * + * \param font The font to use. + * + * \param asObject True to return as an object. + * + * \return The width and height of the text. Has properties .width and .height. + */ +Object getTextWidthHeight(String string, int font, bool asObject); + +/** Get the priority of the current thread. + * + * \ingroup globalFunctions + * + * \return The priority. + */ +int getThreadPriority(); + +/** Get whether or not a UI flag is set. + * + * \ingroup globalFunctions + * + * \todo Get a reference for the UI IDs. + * + * \param nUIId The ID of the UI in question. + * + * \return Whether or not the flag is set. + */ +bool getUIFlag(int nUIId); + +/** Get the TradeFlag or RecentTradeId. + * + * \ingroup globalFunctions + * + * \todo Determine what this means. + * + * \param nMode What to return. 0 - TradeFlag, 2 - RecentTradeId. + * + * \return The TradeFlag or RecentTradeId. + */ +int getTradeInfo(int nMode); + +/** Get the RecentTradeName. + * + * \ingroup globalFunctions + * + * \todo Determine what these are. + * + * \param nMode What to return. 1 - RecentTradeName. + * + * \return The RecentTradeName. + */ +String getTradeInfo(int nMode); + +/** Get whether the controlled unit has the given waypoint. + * + * \ingroup globalFunctions + * + * \param nWaypointId The area id of the waypoint in question. + * + * \return Whether or not the controlled unit has the waypoint. + */ +bool getWaypoint(int nWaypointId); + +/** Get the current or first context. + * + * \ingroup globalFunctions + * + * \param currentScript Whether to get the current script (true) or the first + * (false). + * + * \return A D2BSScript object for the request script. + */ +D2BSScript getScript(bool currentScript); + +/** Get a script by thread id. + * + * \ingroup globalFunctions + * + * \param threadId The thread id of the script to get. + * + * \return A D2BSScript object for the script from the given thread. + */ +D2BSScript getScript(int threadId); + +/** Get a script by filename. + * + * \ingroup globalFunctions + * + * \param name The filename of the script to find. + * + * \return A D2BSScript object for the script. + */ +D2BSScript getScript(String name); + +/** Get the first script. + * + * \ingroup globalFunctions + * + * \return A D2BSScript representing the first script in the runtime. + */ +D2BSScript getScript(); + +/** Get the first room in area given by level id. + * + * \ingroup globalFunctions + * + * \param levelId The id of the area to get the room from, or 0 to get the room + * the controlled unit is in. + * + * \return The first room in the area. + */ +Room getRoom(uint32_t levelId); + +/** Get the room that the given point is in from the given level id. + * + * \ingroup globalFunctions + * + * \param levelId The level id to look in. + * + * \param x The x coordinate to find a room for. + * + * \param y The y coordinate to find a room for. + * + * \return The room at the given point. + */ +Room getRoom(uint32_t levelId, int x, int y); + +/** Get the room that the given point is in. + * + * \ingroup globalFunctions + * + * \param x The x coordinate to find a room for. + * + * \param y The y coordinate to find a room for. + * + * \return The room at the given point. + */ +Room getRoom(int x, int y); + +/** Get the first room in the current area. + * + * \ingroup globalFunctions + * + * \return The first room in the current area. + */ +Room getRoom(); + +/** Get the first party. + * + * \ingroup globalFunctions + * + * \return The first party. + */ +Party getParty(); + +/** Get the first PresetUnit in the given level. + * + * \ingroup globalFunctions + * + * \param levelId The area id of the level to look for a PresetUnit in. + * + * \return The first PresetUnit found. + */ +PresetUnit getPresetUnit(uint32_t levelId); + +/** Get the first PresetUnit of the given type. + * + * \ingroup globalFunctions + * + * \param levelId The area id of the level to look for a PresetUnit in. + * + * \param nType The type of the PresetUnit. See getUnit for type codes. + * + * \return The first PresetUnit found of type nType. + */ +PresetUnit getPresetUnit(uint32_t levelId, int nType); + +/** Get the first PresetUnit of the given type and class id. + * + * \ingroup globalFunctions + * + * \param levelId The area id of the level to look for a PresetUnit in. + * + * \param nType The type of the PresetUnit. See getUnit for type codes. + * + * \param nClassId The class id to find. See: + * http://forums.d2botnet.org/viewtopic.php?f=18&t=986 and + * http://forums.d2botnet.org/viewtopic.php?f=18&t=985 . + * + * \return The first PresetUnit found of type nType and class ID nClassId. + */ +PresetUnit getPresetUnit(uint32_t levelId, int nType, int nClassId); + +/** Get an array of all the PresetUnit s in the given level. + * + * \ingroup globalFunctions + * + * \param levelId The area id of the level to look for PresetUnit s in. + * + * \return An array of all the PresetUnit s on the given level. + */ +PresetUnit[] getPresetUnits(uint32_t levelId); + +/** Get an array of all the PresetUnit s of the given type. + * + * \ingroup globalFunctions + * + * \param levelId The area id of the level to look for PresetUnit s in. + * + * \param nType The type of the PresetUnit. See getUnit for type codes. + * + * \return An array of all PresetUnit s found of type nType. + */ +PresetUnit[] getPresetUnits(uint32_t levelId, int nType); + +/** Get an array of PresetUnit s of the given type and class id. + * + * \ingroup globalFunctions + * + * \param levelId The area id of the level to look for PresetUnit s in. + * + * \param nType The type of the PresetUnit. See getUnit for type codes. + * + * \param nClassId The class id to find. See: + * http://forums.d2botnet.org/viewtopic.php?f=18&t=986 and + * http://forums.d2botnet.org/viewtopic.php?f=18&t=985 . + * + * \return An array of PresetUnit s found of type nType and class ID nClassId. + */ +PresetUnit[] getPresetUnits(uint32_t levelId, int nType, int nClassId); + +/** Get the Area where the controlled unit currently resides. + * + * \ingroup globalFunctions + * + * \return An Area object for the current object. + */ +Area getArea(); + +/** Get the Area for area ID nArea. + * + * \ingroup globalFunctions + * + * \param nArea The area ID. + * + * \return An Area object. + */ +Area getArea(int32_t nArea); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +String getBaseStat(String szTableName, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +String getBaseStat(int32_t nBaseStat, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +String getBaseStat(String szTableName, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +String getBaseStat(int32_t nBaseStat, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +int getBaseStat(String szTableName, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +int getBaseStat(int32_t nBaseStat, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +int getBaseStat(String szTableName, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +int getBaseStat(int32_t nBaseStat, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +bool getBaseStat(String szTableName, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +bool getBaseStat(int32_t nBaseStat, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +bool getBaseStat(String szTableName, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +bool getBaseStat(int32_t nBaseStat, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +double getBaseStat(String szTableName, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * name. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param szStatName The stat name. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +double getBaseStat(int32_t nBaseStat, int32_t nClassId, String szStatName); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param szTableName The name of the table to look in. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +double getBaseStat(String szTableName, int32_t nClassId, int32_t nStat); + +/** Get the base stat from the given table with the given class ID and stat + * ID. + * + * \ingroup globalFunctions + * + * \param nBaseStat The stat to look up. + * + * \param nClassId The class ID of the ... + * + * \param nStat The stat ID. + * + * \todo Determine what these tables are. + * + * \return The stat. + */ +double getBaseStat(int32_t nBaseStat, int32_t nClassId, int32_t nStat); + +/** Get the control specified by type. + * + * \ingroup globalFunctions + * + * \param nType The type of control (button, text box, etc.) + * + * \todo Get a reference for nType + * + * \return A Control object representing the Control found. + */ +Control getControl(int32_t nType); + +/** Get the control specified by type, x location. + * + * \ingroup globalFunctions + * + * \param nType The type of control (button, text box, etc.) + * + * \param nX The x coordinate of the control of the control to find. + * + * \todo Get a reference for nType + * + * \return A Control object representing the Control found. + */ +Control getControl(int32_t nType, int32_t nX); + +/** Get the control specified by type and location. + * + * \ingroup globalFunctions + * + * \param nType The type of control (button, text box, etc.) + * + * \param nX The x coordinate of the control of the control to find. + * + * \param nY The y coordinate of the control of the control to find. + * + * \todo Get a reference for nType + * + * \return A Control object representing the Control found. + */ +Control getControl(int32_t nType, int32_t nX, int32_t nY); + +/** Get the control specified by type, location and width. + * + * \ingroup globalFunctions + * + * \param nType The type of control (button, text box, etc.) + * + * \param nX The x coordinate of the control of the control to find. + * + * \param nY The y coordinate of the control of the control to find. + * + * \param nXSize The width of the control. + * + * \todo Get a reference for nType + * + * \return A Control object representing the Control found. + */ +Control getControl(int32_t nType, int32_t nX, int32_t nY, int32_t nXSize); + +/** Get the control specified by type, location and size. + * + * \ingroup globalFunctions + * + * \param nType The type of control (button, text box, etc.) + * + * \param nX The x coordinate of the control of the control to find. + * + * \param nY The y coordinate of the control of the control to find. + * + * \param nXSize The width of the control. + * + * \param nYSize The height of the control. + * + * \todo Get a reference for nType + * + * \return A Control object representing the Control found. + */ +Control getControl(int32_t nType, int32_t nX, int32_t nY, int32_t nXSize, + int32_t nYSize); + +/** Get the relation between two units. + * + * \ingroup globalFunctions + * + * \param nFirstUnitId The unit id for the unit making the relationship. + * + * \param nSecondUnitId The unit id for the unit receiving the relationship. + * + * \param nFlag The relationship. + * + * \todo Determine what the flags are. + * + * \todo Should this return bool instead of int? (i.e. change the d2bs code). + * + * \return Whether or not the relationship is of the type specified. + */ +int getPlayerFlag(int nFirstUnitId, int nSecondUnitId, int nFlag); + +/** Get the tick count. Returns GetTickCount(). + * + * \ingroup globalFunctions + * + * \return The tick count. + */ +int getTickCount(); + +/** Get the Unit that the controlled Unit is currently interacting with. + * + * \ingroup globalFunctions + * + * \return The Unit currently being interacted with. + */ +Unit getInteractedNPC(); + +/** Print the String representation of the arguments to the console. + * + * \ingroup globalFunctions + */ +void print(...); + +/** Delay for nDelay milliseconds. This is done by suspending the context, + * sleeping, then resuming the context for short (<50 ms) delays. For longer + * delays the context is suspended, 50ms are slept away, the context is resumed, + * sequence repeats until time slept is greater then nDelay ms. + * + * \ingroup globalFunctions + * + * \param nDelay Milliseconds to sleep. + */ +void delay(uint32_t nDelay); + +/** Load file and create a thread with it's main function. File taken from + * scriptDir\\file. + * + * \ingroup globalFunctions + * + * \param file The filename of the script. + * + * \return Whether or not the script was successfully loaded and started. + */ +bool load(String file); + +/** Determine whether a file has been included yet or not. File taken from + * scriptDir\\libs\\file + * + * \ingroup globalFunctions + * + * \param file Filename of the file that might have been included. + * + * \return Whether or not the file has been included. + */ +bool isIncluded(String file); + +/** Include file from the scriptDir\\libs directory. + * + * \ingroup globalFunctions + * + * \param file Filename of the file to include. + * + * \return Whether the inclusion was successful. + */ +bool include(String file); + +/** Stop all scripts. + * + * \ingroup globalFunctions + */ +void stop(); + +/** Conditionally stop current script. + * + * \ingroup globalFunctions + * + * \param stop 1 if current script should be stopped. + */ +void stop(int stop); + +/** Conditionnaly stop current script. + * + * \ingroup globalFunctions + * + * \param stop True if current script should be stopped. + */ +void stop(bool stop); + +/** Return a random number between low and high. Uses C rand() when out of game, + * and D2GAME_D2Rand with the game seed while in game. + * + * \ingroup globalFunctions + * + * \param low The lowest possible integer to return. + * + * \param high The highest possible integer to return. + * + * \return A random integer in the range [low,high]. + */ +int rand(int32_t low, int32_t high); + +/** Send data to another window by means of the WM_COPYDATA message. Uses + * FindWindow to get the HWND and SendMessage to send the message. + * + * \ingroup globalFunctions + * + * \param windowClassName The class name of the receiving window. + * + * \param windowName The window name of the receiving window. + * + * \param nModeId Data to be sent as the dwData member of the copy data. + * + * \param data Data to be send as the lpData member of the copy data. + * + * \return The result of SendMessage. + */ +int sendCopyData(String windowClassName, String windowName, int32_t nModeId, + String data); + +/** Send data to a DDE server by means of DdeClientTransaction. + * + * \ingroup globalFunctions + * + * \param mode The mode of transaction to use. + * + * 0 - Do command given by pszItem with an XTYP_REQUEST and get the resulting + * data. + * + * 1 - Do command given by pszItem with an XTYP_POKE sending "" + * + * 2 - Do command with an XTYP_EXECUTE sending "" + * + * \param pszDDEServer The service name of the DDE server to connect to. + * + * \param pszTopic The topic with which to start the connection. + * + * \param pszItem Data to be sent. + * + * \return Result data if mode was 0. + */ +String sendDDE(int32_t mode, String pszDDEServer, String pszTopic, + String pszItem); + +/** Get whether or not a key is pressed. Returns the value of GetAsyncKeyState. + * + * \ingroup globalFunctions + * + * \param vKey The virtual key code for the key in question. See: + * http://msdn.microsoft.com/en-us/library/dd375731%28v=VS.85%29.aspx + * + * \return Whether not the key is pressed. + */ +bool keystate(int vKey); + +/** Add an event handler to the list of listeners for the given event. + * + * \ingroup globalFunctions + * + * \param event The name of the event. Can be: + * + * melife (uint32_t dwLife) + * + * memana (uint32_t dwMana) + * + * keyup (uint32_t key) + * + * keydown (uint32_t key) + * + * mouseclick (uint32_t button, bool bUp, uint32_t x, uint32_t y) + * + * mousemove (uint32_t x, uint32_t y) + * + * scriptmsg (...) + * + * golddrop (uint32_t gId, uint32_t Mode) + * + * chatmsg (String lpszNick, String lpszMsg) + * + * whispermsg (String lpszNick, String lpszMsg) + * + * copydata (int32_t dwMode, String lpszMsg) + * + * gamemsg (String lpszMsg) + * + * itemaction (uint32_t gId, uint32_t mode, String code, Bool global) + * + * gameevent (BYTE mode, DWORD param1, DWORD param2, String name1, String name2) + * + * From http://www.blizzhackers.cc/viewtopic.php?t=392307 Dark_Mage- + * + * mode: + * + * 0x00 - "%Name1(%Name2) dropped due to time out." + * 0x01 - "%Name1(%Name2) dropped due to errors." + * 0x02 - "%Name1(%Name2) joined our world. Diablo's minions grow stronger." + * 0x03 - "%Name1(%Name2) left our world. Diablo's minions weaken." + * 0x04 - "%Name1 is not in the game." + * 0x05 - "%Name1 is not logged in." + * + * 0x06 - "%Name1 was Slain by %Name2" + * BYTE Param2 = Unit Type of Slayer (0x00 = Player, 0x01 = NPC) + * if Type = Player, %Name2 = Slayer Character Name & DWORD Param1 = Slayer Character Type + * if Type = NPC, DWORD Param1 = Monster Id Code from MPQ (points to string for %Name2) + * if Type = NPC & Monster is Unique, %Name2 = Unique Monster Id + * + * 0x07 - Player Relations (Bottom Left Text) + * DWORD Param1 = Player Id + * Player Id = Pointer to Character Name + * BYTE Param2 = Action Taken + * Actions: + * 0x01 - "%Player permits you to loot his corpse." + * 0x02 - "%Player permits you to loot her corpse." + * 0x03 - "%Player has declared hostility towards you." + * 0x04 - "%Player is no longer hostile towards you." + * 0x05 - "%Player invites you to ally against the forces of evil." + * 0x06 - "%Player has canceled party invite." + * 0x07 - "%Player has joined your party to fight the forces of evil." + * 0x08 - "You are now allied with %Player." + * 0x09 - "%Player has left your party." + * 0x0a - "%Player no longer allows you to access his corpse." + * 0x0b - "%Player no longer allows you to access her corpse." + * + * 0x08 - "%Name1 is busy." + * 0x09 - "You must wait a short time to trade with that player." + * + * 0x0a - "%Name1 has items in his box." + * if %Name1 = 0x00, "You have items in your box." + * + * 0x0b - + * 0x0c - + * 0x0d - "%Name1 is not listening to you." + * 0x0e - Received on 'Not enough mana' speech. + * 0x0f - "Realm going down in %Param1 minutes." + * 0x10 - "You must wait a short time to declare hostility with that player." + * 0x11 - "%Param1 Stones of Jordan Sold to Merchants" + * 0x12 - "Diablo Walks the Earth" + * + * \param eventHandler A function with the signature listed above that handles + * the event. + */ +void addEventListener(String event, Function eventHandler); + +/** Removes a previously added event from the listener list. + * + * \ingroup globalFunctions + * + * \param event The event name (the one used to add the event). + * + * \param eventHandler The handler to remove. + */ +void removeEventListener(String event, Function eventHandler); + +/** Clear the event handler list for given event. + * + * \ingroup globalFunctions + * + * \param event The name of the event to clear the handler list for. + */ +void clearEvent(String event); + +/** Clear all event handlers (from all events). + * + * \ingroup globalFunctions + */ +void clearAllEvents(); + +/** Get whether or not the JSOPTION_STRICT flag is set. + * + * \ingroup globalFunctions + * + * \return Whether or not the strict flag is set. + */ +bool js_strict(); + +/** Set or clear the JSOPTION_STRICT flag. + * + * \ingroup globalFunctions + * + * \param setStrictFlag The new JSOPTION_STRICT state. + */ +void js_strict(bool setStrictFlag); + +/** Get the D2BS version string. + * + * \ingroup globalFunctions + * + * \return The D2BS version string. + */ +String version(); + +/** Print the D2BS version string. + * + * \ingroup globalFunctions + */ +void version(int a); + +/** Broadcast a message to all other scripts. D2BS calls each scripts scriptmsg + * event listeners with the messages passed in. + * + * \ingroup globalFunctions + */ +void scriptBroadcast(...); + +/** Get the sqlite version string (from sqlite3_version). + * + * \ingroup globalFunctions + * + * \return The sqlite version string. + */ +String sqlite_version(); + +/** Return the sqlite memory usage. + * + * \ingroup globalFunctions + */ +double sqlite_memusage(); + +/** Get the Folder object for the directory scriptPath\\name + * + * \ingroup globalFunctions + * + * \param name The name of the Folder to open. + * + * \return A Folder object representing the Folder name. + */ +Folder dopen(String name); + +/** Log the String representation of the arguments. + * + * \ingroup globalFunctions + */ +void debugLog(...); + +/** Show the console. + * + * \ingroup globalFunctions + */ +void showConsole(); + +/** Hide the console. + * + * \ingroup globalFunctions + */ +void hideConsole(); + +/** Loads the default (either from config or copydata or DDE) profile from + * d2bs.ini and gets to the lobby (for battle.net chars) or into a game (for + * single player characters). + * + * \ingroup globalFunctions + * + * \throw String May throw one of the following: + * + * "invalid character name" - If it fails to select the character. + * + * "Failed to click the Single button?" - If it fails to click the single player + * button. + * + * "Failed to click the 'Battle.net' button?" - If it fails to click the + * battle.net button. + * + * "Failed to click the 'Other Multiplayer' button?" - If it fails to click the + * Other Multiplayer button. + * + * "Failed to click the 'Open Battle.net' button?" - If it fails to click the + * Open battle.net button. + * + * "Failed to click the 'TCP/IP' button?" - If it fails to click the TCP/IP + * button. + * + * "Failed to click the 'Host Game' button?" - If it fails to click the Host + * Game (TCP/IP) button. + * + * "Failed to click the 'Join Game' button?" - If it fails to click the Join + * Game (TCP/IP) button. + * + * "Failed to click the OK button" - If it fails to click the OK button (TCP/IP + * enter IP address). + * + * "Failed to find the 'Host IP Address' text-edit box." - If it can't find the + * host IP address (TCP/IP) text box. + * + * "Could not get the IP address from the profile in the d2bs.ini file." - If + * the user failed to specify the IP address in the d2bs.ini file. + * + * "Failed to click the exit button?" - If it is login and fails to click the + * exit button. + * + * "Failed to set the 'Username' text-edit box.' - If it can't find the username + * control. + * + * "Failed to set the 'Password' text-edit box." - If it can't find the password + * control. + * + * "Failed to click the 'Log in' button?" - If it can't click the login button. + * + * "Failed to click the 'Normal Difficulty' button?" - If it can't click the + * normal button in single player game creation. + * + * "Failed to click the 'Nightmare Difficulty' button?" - If it can't click the + * nightmare button in single player game creation. + * + * "Failed to click the 'Hell Difficulty' button?" - If it can't click the hell + * button in single player game creation. + * + * "Invalid single player difficulty level specified!" - If the difficulty level + * is invalid. + * + * "Unable to connect" - If the unable to connect screen is shown. + * + * "CD-Key in use" - If the cdkey in use screen is shown. + * + * "Bad account or password" - If the username/password wrong screen is shown. + * + * "Realm Down" - If the realm down message is shown. + * + * "Unhandled login location" - If the game is in an unsupported location. + */ +void login(); + +/** Loads the profile from d2bs.ini and gets to the lobby (for battle.net chars) + * or into a game (for single player characters). + * + * \ingroup globalFunctions + * + * \param profile The profile to load. + * + * \throw String May throw one of the following: + * + * "invalid character name" - If it fails to select the character. + * + * "Failed to click the Single button?" - If it fails to click the single player + * button. + * + * "Failed to click the 'Battle.net' button?" - If it fails to click the + * battle.net button. + * + * "Failed to click the 'Other Multiplayer' button?" - If it fails to click the + * Other Multiplayer button. + * + * "Failed to click the 'Open Battle.net' button?" - If it fails to click the + * Open battle.net button. + * + * "Failed to click the exit button?" - If it is login and fails to click the + * exit button. + * + * "Failed to set the 'Username' text-edit box.' - If it can't find the username + * control. + * + * "Failed to set the 'Password' text-edit box." - If it can't find the password + * control. + * + * "Failed to click the 'Log in' button?" - If it can't click the login button. + * + * "Failed to click the 'Normal Difficulty' button?" - If it can't click the + * normal button in single player game creation. + * + * "Failed to click the 'Nightmare Difficulty' button?" - If it can't click the + * nightmare button in single player game creation. + * + * "Failed to click the 'Hell Difficulty' button?" - If it can't click the hell + * button in single player game creation. + * + * "Invalid single player difficulty level specified!" - If the difficulty level + * is invalid. + * + * "Unable to connect" - If the unable to connect screen is shown. + * + * "CD-Key in use" - If the cdkey in use screen is shown. + * + * "Bad account or password" - If the username/password wrong screen is shown. + * + * "Realm Down" - If the realm down message is shown. + * + * "Unhandled login location" - If the game is in an unsupported location. + */ +void login(String profile); + +/** Select the character from the given profile. Keeps all details except the + * character name from old profile. + * + * \ingroup globalFunctions + * + * \param profile The profile to get the character name from. + * + * \return Whether or not character swap was successful. + */ +bool selectCharacter(String profile); + +/** Create a game with the given name. + * + * \ingroup globalFunctions + * + * \param name The game name + */ +void createGame(String name); + +/** Create a game with the given name and password. + * + * \ingroup globalFunctions + * + * \param name The game name + * + * \param pass The game password + */ +void createGame(String name, String pass); + +/** Create a game with the given name and password in the given difficulty. + * + * \ingroup globalFunctions + * + * \param name The game name. + * + * \param pass The game password. + * + * \param diff The game difficulty. 0 - normal, 1 - nightmare, 2 - hell, 3 - + * hardest difficulty available. + */ +void createGame(String name, String pass, int32_t diff); + +/** Join a game with the given name. + * + * \ingroup globalFunctions + * + * \param name The game name. + */ +void joinGame(String name); + +/** Join a game with the given name and password. + * + * \ingroup globalFunctions + * + * \param name The game name. + * + * \param pass The game password. + */ +void joinGame(String name, String pass); + +/** Create a profile with the given profile name, mode, gateway, username, + * password and character name. + * + * \ingroup globalFunctions + * + * \param profile The profile name. + * + * \param mode The mode (single player/battle.net/etc). + * + * \param gateway The realm gateway. + * + * \param username Account username. + * + * \param password Account password. + * + * \param charname Character name (case sensitive). + */ +void addProfile(String profile, String mode, String gateway, String username, + String password, String charname); + +/** Create a profile with the given profile name, mode, gateway, username, + * password, character name and single player difficulty. + * + * \ingroup globalFunctions + * + * \param profile The profile name. + * + * \param mode The mode (single player/battle.net/etc). + * + * \param gateway The realm gateway. + * + * \param username Account username. + * + * \param password Account password. + * + * \param charname Character name (case sensitive). + * + * \param spDifficulty The difficulty to create games for a single player + * character. + */ +void addProfile(String profile, String mode, String gateway, String username, + String password, String charname, int spDifficulty); + +/** Get the current OOG location. + * + * \ingroup globalFunctions + * + * \todo Create a reference for the return values. + * + * \return The current OOG location. + */ +int getLocation(); + +/** Load an mpq file. + * + * \ingroup globalFunctions + * + * \param path The mpq file to load + */ +void loadMpq(String path); + +/** Submit the item on the cursor to the open screen (like the add sockets + * screen). + * + * \ingroup globalFunctions + * + * \return Whether or not it was successful. + */ +bool submitItem(); + +/** Get the mouse coordinates (in screen space) and return as an array. + * + * \ingroup globalFunctions + * + * \return The mouse coordinates in an array. 0 - x, 1 - y. + */ +int[] getMouseCoords(); + +/** Get the mouse coordinates (in screen or map space) and return as an array. + * + * \ingroup globalFunctions + * + * \param nFlag Whether to return in map space (true) or screen space (false). + * + * \return The mouse coordinates in an array. 0 - x, 1 - y. + */ +int[] getMouseCoords(bool nFlag); + +/** Get the mouse coordinates (in screen or map space) and return as an array. + * + * \ingroup globalFunctions + * + * \param nFlag Whether to return in map space (true) or screen space (false). + * + * \param nReturn Whether to return as an array or as an Object, false for array + * format. + * + * \return The mouse coordinates in an array. 0 - x, 1 - y. + */ +int[] getMouseCoords(bool nFlag, int nReturn); + +/** Get the mouse coordinates (in screen or map space) and return as an Object. + * + * \ingroup globalFunctions + * + * \param nFlag Whether to return in map space (true) or screen space (false). + * + * \param nReturn Whether to return as an array or as an Object, true for Object + * format. + * + * \return The mouse coordinates in an array. Has properties .x and .y. + */ +Object getMouseCoords(bool nFlag, int nReturn); + +/** Copy the cached data associated with given unit. This is things like type + * and unit id. + * + * \ingroup globalFunctions + * + * \todo Figure out why anyone would want to copy a unit. + * + * \return The new copy of the unit. + */ +Unit copyUnit(Unit other); + +/** Click on the map with the given click type and possibly shift at the given + * unit. + * + * \ingroup globalFunctions + * + * \param nClickType The click type to do. + * + * \param nShift Whether or not to be holding down shift. 0 - Don't hold shift, + * 1 - hold shift. + * + * \param toClick The unit to click on. + * + * \todo Get a reference for nClickType. + * + * \return Whether or not the click was successful. + */ +bool clickMap(uint16_t nClickType, uint16_t nShift, Unit toClick); + +/** Click on the map with the given click type and possibly shift at the given + * unit. + * + * \ingroup globalFunctions + * + * \param nClickType The click type to do. + * + * \param nShift Whether or not to be holding down shift. + * + * \param toClick The unit to click on. + * + * \todo Get a reference for nClickType. + * + * \return Whether or not the click was successful. + */ +bool clickMap(uint16_t nClickType, bool nShift, Unit toClick); + +/** Click on the map with the given click type and possibly shift at the given + * point. + * + * \ingroup globalFunctions + * + * \param nClickType The click type to do. + * + * \param nShift Whether or not to be holding down shift. 0 - Don't hold shift, + * 1 - hold shift. + * + * \param nX The x coordinate to click at. + * + * \param nY The y coordinate to click at. + * + * \todo Get a reference for nClickType. + * + * \return Whether or not the click was successful. + */ +bool clickMap(uint16_t nClickType, uint16_t nShift, uint16_t nX, uint16_t nY); + +/** Click on the map with the given click type and possibly shift at the given + * point. + * + * \ingroup globalFunctions + * + * \param nClickType The click type to do. + * + * \param nShift Whether or not to be holding down shift. + * + * \param nX The x coordinate to click at. + * + * \param nY The y coordinate to click at. + * + * \todo Get a reference for nClickType. + * + * \return Whether or not the click was successful. + */ +bool clickMap(uint16_t nClickType, bool nShift, uint16_t nX, uint16_t nY); + +/** Get or do something to do with accepting trade. + * + * \ingroup globalFunctions + * + * \param action What action to perform. + * + * 1 - Get whether trade we've accepted trade already or not. + * + * 2 - Get the trade flag ... + * + * 3 - Get whether the check is red or not. + * + * \return The flag specified by action. + */ +bool acceptTrade(int action); + +/** Accept a trade if not already accepted, cancel a trade if already accepted. + * + * \ingroup globalFunctions + * + * \todo Verify that I understand this correctly. + * + * \return Whether or not trade was accepted. + */ +bool acceptTrade(); + +/** Make the windows default beep sound. + * + * \ingroup globalFunctions + */ +void beep(); + +/** Beep with beep ID nBeepId. + * + * \ingroup globalFunctions + * + * \param nBeepId ID of the beep to make. See: + * http://msdn.microsoft.com/en-us/library/ms680356%28VS.85%29.aspx . + */ +void beep(init nBeepId); + +/** Click an item. + * + * \ingroup globalFunctions + * + * \param item The item to click on. + */ +void clickItem(Unit item); + +/** Click on a body location with a certain click type. + * + * \ingroup globalFunctions + * + * \todo Determine values for nClickType + * + * \param nClickType The click type. 4 for merc locations. + * + * \param nBodyLoc The body location. + * + * 0 - Not equipped + * + * 1 - Helmet + * + * 2 - Amulet + * + * 3 - Armor + * + * 4 - Right hand slot 1 + * + * 5 - Left hand slot 1 + * + * 6 - Right ring + * + * 7 - Left ring + * + * 8 - Belt + * + * 9 - Boots + * + * 10 - Gloves + * + * 11 - Right hand slot 2 + * + * 12 - Left hand slot 2 + */ +void clickItem(int nClickType, int nBodyLoc); + +/** Click on a given item with the given click type. + * + * \ingroup globalFunctions + * + * \todo Determine values for nClickType + * + * \param nClickType The click type. 4 for merc locations. + * + * \param item The item to click. + * + * \param nClickType + */ +void clickItem(int nClickType, Unit item); + +/** Click an item location with the given click type. + * + * \param nClickType The click type. 4 for merc locations. + * + * \param nX The x coordinate of the location to click. + * + * \param nY The y coordinate of the location to click. + * + * \param nLoc The location of the item. + * + * 0 - Inventory + * + * 2 - Player trade + * + * 3 - Cube + * + * 4 - Stash + * + * 5 - Belt + */ +void clickItem(int nButton, nX, nY, nLoc); + +/** Get the euclidean distance from a to b. + * + * \ingroup globalFunctions + * + * \param a The first Unit. + * + * \param b The second Unit. + * + * \return The euclidean distance from a to b. + */ +double getDistance(Unit a, Unit b); + +/** Get the euclidean distance from a to b. + * + * \ingroup globalFunctions + * + * \param a The first Unit. + * + * \param bx The x coordinate of point b. + * + * \param by The y coordinate of point b. + * + * \return The euclidean distance from a to b. + */ +double getDistance(Unit a, int32_t bx, int32_t by); + +/** Get the euclidean distance from a to b. + * + * \ingroup globalFunctions + * + * \param ax The x coordinate of point a. + * + * \param ay The y coordinate of point a. + * + * \param b The second Unit. + * + * \return The euclidean distance from a to b. + */ +double getDistance(int32_t ax, int32_t ay, Unit b); + +/** Get the euclidean distance from a to b. + * + * \ingroup globalFunctions + * + * \param ax The x coordinate of point a. + * + * \param ay The y coordinate of point a. + * + * \param bx The x coordinate of point b. + * + * \param by The y coordinate of point b. + * + * \return The euclidean distance from a to b. + */ +double getDistance(int32_t ax, int32_t ay, int32_t bx, int32_t by); + +/** Drop some gold. + * + * \ingroup globalFunctions + * + * \param nGold The amount of gold to drop. + */ +void gold(int nGold); + +/** Do something with some gold. + * + * \ingroup globalFunctions + * + * \todo Determine what the values for nMode are. + * + * \param nGold The amount of gold to move around. + * + * \param nMode What to do with the gold. + */ +void gold(int nGold, int nMode); + +/** Check if two units collide. + * + * \ingroup globalFunctions + * + * \param a Unit a. + * + * \param b Unit b. + * + * \param nBitMask Bit mask to check collision of a and b with. + */ +int checkCollision(Unit a, Unit b, int nBitMask); + +/** Play d2 sound by id. + * + * \ingroup globalFunctions + * + * \return true + */ +bool playSound(int nSoundId); + +/** Quit the game. + * + * \ingroup globalFunctions + */ +void quit(); + +/** Quit Diablo II. Allows the core to shutdown, than terminates the process. + * + * \ingroup globalFunctions + */ +void quitGame(); + +/** Say the string equivalent of the each of the arguments. + * + * \ingroup globalFunctions + * + * \return true if at least one parameter was sent in. + */ +bool say(...); + +/** Click one of the buttons in the party screen for the given player. + * + * \ingroup globalFunctions + * + * \param player The player who's button you wish to click. + * + * \param nMode Which button to click. + * + * 0 - Allow loot corpse + * + * 1 - Hostile player + * + * 2 - Join party + * + * 3 - Leave party (doesn't matter which party is passed in) + */ +bool clickParty(Party player, int nMode); + +/** Switch the weapons. + * + * \ingroup globalFunctions + * + * \return true + */ +bool weaponSwitch(); + +/** Get which weapon switch is being used. + * + * \ingroup globalFunctions + * + * \param dummy Any int other than 0. + * + * \return Which weapon switch is active. + */ +int weaponSwitch(int32_t dummy); + +/** Switch the weapons. + * + * \ingroup globalFunctions + * + * \param dummy 0 to use this mode. + * + * \return true + */ +bool weaponSwitch(int32_t dummy); + +/** Hit the transmute button. + * + * \ingroup globalFunctions + */ +void transmute(); + +/** Use a stat point. + * + * BE CAREFUL! This function directly sends packets without checks. If you + * call this function and do not have the points, or specify an invalid stat, + * you might get flagged/banned. + * + * \ingroup globalFunctions + * + * \todo Come up with a reference for the statType values + * + * \param statType The type of stat to add the point to + */ +void useStatPoint(uint16_t statType); + +/** Use a stat point. + * + * BE CAREFUL! This function directly sends packets without checks. If you + * call this function and do not have the points, or specify an invalid stat, + * you might get flagged/banned. + * + * \ingroup globalFunctions + * + * \todo Come up with a reference for the statType values + * + * \param statType The type of stat to add the points to + * + * \param count The number of points to add + */ +void useStatPoint(uint16_t statType, uint32_t count); + +/** Use a skill point + * + * BE CAREFUL! This function directly sends packets without checks. If you + * call this function and do not have the points, or specify an invalid skill, + * you might get flagged/banned. + * + * \ingroup globalFunctions + * + * \todo Come up with a reference for the skill values + * + * \param skill The skill to add the point to + */ +void useSkillPoint(uint16_t skill); + +/** Use a skill point + * + * BE CAREFUL! This function directly sends packets without checks. If you + * call this function and do not have the points, or specify an invalid skill, + * you might get flagged/banned. + * + * \ingroup globalFunctions + * + * \todo Come up with a reference for the skill values + * + * \param skill The skill to add the points to + * + * \param count The number points to spend + */ +void useSkillPoint(uint16_t skill, uint32_t count); + +/** Take a screenshot + * + * Performs the action that pressing print screen (by default) would do + * + * \ingroup globalFunctions + */ +void takeScreenshot(); + +/** Convert a point from screen coordinates to automap coordinates. + * + * \ingroup globalFunctions + * + * \param arg An object with x and y parameters specifying the point. + * + * \return An object with x and y, containing the automap coordinate. + */ +Object screenToAutomap(Object arg); + +/** Convert a point from screen coordinates to automap coordinates. + * + * \ingroup globalFunctions + * + * \param ix The x coordinate. + * + * \param iy The y coordinate. + * + * \return An object with x and y, containing the automap coordinate. + */ +Object screenToAutomap(int ix, int iy); + +/** Convert a point from automap coordinates to screen coordinates. + * + * \ingroup globalFunctions + * + * \param arg An object with x and y parameters specifying the point. + * + * \return An object with x and y, containing the screen coordinate. + */ +Object automapToScreen(Object arg); + +/** Convert a point from automap coordinates to screen coordinates. + * + * \ingroup globalFunctions + * + * \param ix The x coordinate. + * + * \param iy The y coordinate. + * + * \return An object with x and y, containing the screen coordinate. + */ +Object automapToScreen(int ix, int iy); + +/** Takes the md5 hash. + * + * \ingroup globalFunctions + * + * \param str The string to hash. + * + * \return The md5 hash of the string. + */ +String md5(String str); + +/** Takes the sha1 hash. + * + * \ingroup globalFunctions + * + * \param str The string to hash. + * + * \return The sha1 hash of the string. + */ +String sha1(String str); + +/** Takes the sha256 hash. + * + * \ingroup globalFunctions + * + * \param str The string to hash. + * + * \return The sha256 hash of the string. + */ +String sha256(String str); + +/** Takes the sha384 hash. + * + * \ingroup globalFunctions + * + * \param str The string to hash. + * + * \return The sha384 hash of the string. + */ +String sha384(String str); + +/** Takes the sha512 hash. + * + * \ingroup globalFunctions + * + * \param str The string to hash. + * + * \return The sha512 hash of the string. + */ +String sha512(String str); + +/** Take the md5 hash of a file. + * + * \ingroup globalFunctions + * + * \param file Filename relative to script path. + * + * \return The md5 hash of the file. + */ +String md5_file(String file); + +/** Take the sha1 hash of a file. + * + * \ingroup globalFunctions + * + * \param file Filename relative to script path. + * + * \return The sha1 hash of the file. + */ +String sha1_file(String file); + +/** Take the sha256 hash of a file. + * + * \ingroup globalFunctions + * + * \param file Filename relative to script path. + * + * \return The sha256 hash of the file. + */ +String sha256_file(String file); + +/** Take the sha384 hash of a file. + * + * \ingroup globalFunctions + * + * \param file Filename relative to script path. + * + * \return The sha384 hash of the file. + */ +String sha384_file(String file); + +/** Take the sha512 hash of a file. + * + * \ingroup globalFunctions + * + * \param file Filename relative to script path. + * + * \return The sha512 hash of the file. + */ +String sha512_file(String file); diff --git a/js32.cpp b/js32.cpp new file mode 100644 index 00000000..aab4f9d5 --- /dev/null +++ b/js32.cpp @@ -0,0 +1,22 @@ +#include "ScriptEngine.h" +#include "js32.h" + +JSObject* BuildObject(JSContext* cx, JSClass* classp, JSFunctionSpec* funcs, JSPropertySpec* props, void* priv, JSObject* proto, JSObject* parent) +{ + JSObject* obj = JS_NewObject(cx, classp, proto, parent); + + if(obj) + { + // add root to avoid newborn root problem + if(JS_AddRoot(&obj) == JS_FALSE) + return NULL; + if(obj && funcs && !JS_DefineFunctions(cx, obj, funcs)) + obj = NULL; + if(obj && props && !JS_DefineProperties(cx, obj, props)) + obj = NULL; + if(obj && priv) + JS_SetPrivate(cx, obj, priv); + JS_RemoveRoot(&obj); + } + return obj; +} diff --git a/js32.h b/js32.h new file mode 100644 index 00000000..e7acc8bd --- /dev/null +++ b/js32.h @@ -0,0 +1,35 @@ +#pragma once + +#define JS_THREADSAFE +#define XP_WIN + +#include "js32/jsapi.h" +#include "js32/jsdbgapi.h" +// this should be included, but can't be due to compiler include cycles +// however, every file that includes this one includes ScriptEngine.h first anyway +//#include "ScriptEngine.h" + +#define JSAPI_FUNC(fName) JSBool fName (JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) +#define JSAPI_PROP(fName) JSBool fName (JSContext *cx, JSObject *obj, jsval id, jsval *vp) + +#define JSVAL_IS_FUNCTION(cx, var) (JSVAL_IS_OBJECT(var) && JS_ObjectIsFunction(cx, JSVAL_TO_OBJECT(var))) + +#define JSPROP_PERMANENT_VAR (JSPROP_READONLY | JSPROP_ENUMERATE | JSPROP_PERMANENT) +#define JSPROP_STATIC_VAR (JSPROP_ENUMERATE | JSPROP_PERMANENT) + +#define NUM(x) #x +#define NAME(line, v) (__FILE__ "@" NUM(line) ": " #v) +#define JS_AddRoot(vp) JS_AddNamedRootRT(ScriptEngine::GetRuntime(), (vp), NAME(__LINE__, vp)) +#define JS_RemoveRoot(vp) JS_RemoveRootRT(ScriptEngine::GetRuntime(), (vp)); + +#define DEPRECATED JS_ReportWarning(cx, "This function has been deprecated, and will be removed from future releases.") + +JSObject* BuildObject(JSContext* cx, JSClass* classp = NULL, JSFunctionSpec* funcs = NULL, JSPropertySpec* props = NULL, void* priv = NULL, JSObject* proto = NULL, JSObject* parent = NULL); +#define THROW_ERROR(cx, msg) { JS_ReportError(cx, msg); return JS_FALSE; } +#define THROW_WARNING(cx, msg) { JS_ReportWarning(cx, msg); } + +#define CLASS_CTOR(name) JSBool name##_ctor (JSContext *cx, JSObject* obj, uintN argc, jsval *argv, jsval *rval) +#define EMPTY_CTOR(name) \ +JSBool name##_ctor (JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { \ + THROW_ERROR(cx, "Invalid Operation"); } + diff --git a/js32/js32.lib b/js32/js32.lib new file mode 100644 index 00000000..3ef461ed Binary files /dev/null and b/js32/js32.lib differ diff --git a/js32/js32d.lib b/js32/js32d.lib new file mode 100644 index 00000000..2dbab18a Binary files /dev/null and b/js32/js32d.lib differ diff --git a/js32/jsapi.h b/js32/jsapi.h new file mode 100644 index 00000000..464f19ff --- /dev/null +++ b/js32/jsapi.h @@ -0,0 +1,2220 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef jsapi_h___ +#define jsapi_h___ +/* + * JavaScript API. + */ +#include +#include +#include "jspubtd.h" + +JS_BEGIN_EXTERN_C + +/* + * Type tags stored in the low bits of a jsval. + */ +#define JSVAL_OBJECT 0x0 /* untagged reference to object */ +#define JSVAL_INT 0x1 /* tagged 31-bit integer value */ +#define JSVAL_DOUBLE 0x2 /* tagged reference to double */ +#define JSVAL_STRING 0x4 /* tagged reference to string */ +#define JSVAL_BOOLEAN 0x6 /* tagged boolean value */ + +/* Type tag bitfield length and derived macros. */ +#define JSVAL_TAGBITS 3 +#define JSVAL_TAGMASK JS_BITMASK(JSVAL_TAGBITS) +#define JSVAL_TAG(v) ((v) & JSVAL_TAGMASK) +#define JSVAL_SETTAG(v,t) ((v) | (t)) +#define JSVAL_CLRTAG(v) ((v) & ~(jsval)JSVAL_TAGMASK) +#define JSVAL_ALIGN JS_BIT(JSVAL_TAGBITS) + +/* Predicates for type testing. */ +#define JSVAL_IS_OBJECT(v) (JSVAL_TAG(v) == JSVAL_OBJECT) +#define JSVAL_IS_NUMBER(v) (JSVAL_IS_INT(v) || JSVAL_IS_DOUBLE(v)) +#define JSVAL_IS_INT(v) (((v) & JSVAL_INT) && (v) != JSVAL_VOID) +#define JSVAL_IS_DOUBLE(v) (JSVAL_TAG(v) == JSVAL_DOUBLE) +#define JSVAL_IS_STRING(v) (JSVAL_TAG(v) == JSVAL_STRING) +#define JSVAL_IS_BOOLEAN(v) (JSVAL_TAG(v) == JSVAL_BOOLEAN) +#define JSVAL_IS_NULL(v) ((v) == JSVAL_NULL) +#define JSVAL_IS_VOID(v) ((v) == JSVAL_VOID) +#define JSVAL_IS_PRIMITIVE(v) (!JSVAL_IS_OBJECT(v) || JSVAL_IS_NULL(v)) + +/* Objects, strings, and doubles are GC'ed. */ +#define JSVAL_IS_GCTHING(v) (!((v) & JSVAL_INT) && !JSVAL_IS_BOOLEAN(v)) +#define JSVAL_TO_GCTHING(v) ((void *)JSVAL_CLRTAG(v)) +#define JSVAL_TO_OBJECT(v) ((JSObject *)JSVAL_TO_GCTHING(v)) +#define JSVAL_TO_DOUBLE(v) ((jsdouble *)JSVAL_TO_GCTHING(v)) +#define JSVAL_TO_STRING(v) ((JSString *)JSVAL_TO_GCTHING(v)) +#define OBJECT_TO_JSVAL(obj) ((jsval)(obj)) +#define DOUBLE_TO_JSVAL(dp) JSVAL_SETTAG((jsval)(dp), JSVAL_DOUBLE) +#define STRING_TO_JSVAL(str) JSVAL_SETTAG((jsval)(str), JSVAL_STRING) + +/* Lock and unlock the GC thing held by a jsval. */ +#define JSVAL_LOCK(cx,v) (JSVAL_IS_GCTHING(v) \ + ? JS_LockGCThing(cx, JSVAL_TO_GCTHING(v)) \ + : JS_TRUE) +#define JSVAL_UNLOCK(cx,v) (JSVAL_IS_GCTHING(v) \ + ? JS_UnlockGCThing(cx, JSVAL_TO_GCTHING(v)) \ + : JS_TRUE) + +/* Domain limits for the jsval int type. */ +#define JSVAL_INT_BITS 31 +#define JSVAL_INT_POW2(n) ((jsval)1 << (n)) +#define JSVAL_INT_MIN ((jsval)1 - JSVAL_INT_POW2(30)) +#define JSVAL_INT_MAX (JSVAL_INT_POW2(30) - 1) +#define INT_FITS_IN_JSVAL(i) ((jsuint)((i)+JSVAL_INT_MAX) <= 2*JSVAL_INT_MAX) +#define JSVAL_TO_INT(v) ((jsint)(v) >> 1) +#define INT_TO_JSVAL(i) (((jsval)(i) << 1) | JSVAL_INT) + +/* Convert between boolean and jsval. */ +#define JSVAL_TO_BOOLEAN(v) ((JSBool)((v) >> JSVAL_TAGBITS)) +#define BOOLEAN_TO_JSVAL(b) JSVAL_SETTAG((jsval)(b) << JSVAL_TAGBITS, \ + JSVAL_BOOLEAN) + +/* A private data pointer (2-byte-aligned) can be stored as an int jsval. */ +#define JSVAL_TO_PRIVATE(v) ((void *)((v) & ~JSVAL_INT)) +#define PRIVATE_TO_JSVAL(p) ((jsval)(p) | JSVAL_INT) + +/* Property attributes, set in JSPropertySpec and passed to API functions. */ +#define JSPROP_ENUMERATE 0x01 /* property is visible to for/in loop */ +#define JSPROP_READONLY 0x02 /* not settable: assignment is no-op */ +#define JSPROP_PERMANENT 0x04 /* property cannot be deleted */ +#define JSPROP_EXPORTED 0x08 /* property is exported from object */ +#define JSPROP_GETTER 0x10 /* property holds getter function */ +#define JSPROP_SETTER 0x20 /* property holds setter function */ +#define JSPROP_SHARED 0x40 /* don't allocate a value slot for this + property; don't copy the property on + set of the same-named property in an + object that delegates to a prototype + containing this property */ +#define JSPROP_INDEX 0x80 /* name is actually (jsint) index */ + +/* Function flags, set in JSFunctionSpec and passed to JS_NewFunction etc. */ +#define JSFUN_LAMBDA 0x08 /* expressed, not declared, function */ +#define JSFUN_GETTER JSPROP_GETTER +#define JSFUN_SETTER JSPROP_SETTER +#define JSFUN_BOUND_METHOD 0x40 /* bind this to fun->object's parent */ +#define JSFUN_HEAVYWEIGHT 0x80 /* activation requires a Call object */ + +#define JSFUN_DISJOINT_FLAGS(f) ((f) & 0x0f) +#define JSFUN_GSFLAGS(f) ((f) & (JSFUN_GETTER | JSFUN_SETTER)) + +#ifdef MOZILLA_1_8_BRANCH + +/* + * Squeeze three more bits into existing 8-bit flags by taking advantage of + * the invalid combination (JSFUN_GETTER | JSFUN_SETTER). + */ +#define JSFUN_GETTER_TEST(f) (JSFUN_GSFLAGS(f) == JSFUN_GETTER) +#define JSFUN_SETTER_TEST(f) (JSFUN_GSFLAGS(f) == JSFUN_SETTER) +#define JSFUN_FLAGS_TEST(f,t) (JSFUN_GSFLAGS(~(f)) ? (f) & (t) : 0) +#define JSFUN_BOUND_METHOD_TEST(f) JSFUN_FLAGS_TEST(f, JSFUN_BOUND_METHOD) +#define JSFUN_HEAVYWEIGHT_TEST(f) JSFUN_FLAGS_TEST(f, JSFUN_HEAVYWEIGHT) + +#define JSFUN_GSFLAG2ATTR(f) (JSFUN_GETTER_TEST(f) ? JSPROP_GETTER : \ + JSFUN_SETTER_TEST(f) ? JSPROP_SETTER : 0) + +#define JSFUN_THISP_FLAGS(f) (JSFUN_GSFLAGS(~(f)) ? 0 : \ + (f) & JSFUN_THISP_PRIMITIVE) +#define JSFUN_THISP_TEST(f,t) ((f) == (t) || (f) == JSFUN_THISP_PRIMITIVE) + +#define JSFUN_THISP_STRING 0x30 /* |this| may be a primitive string */ +#define JSFUN_THISP_NUMBER 0x70 /* |this| may be a primitive number */ +#define JSFUN_THISP_BOOLEAN 0xb0 /* |this| may be a primitive boolean */ +#define JSFUN_THISP_PRIMITIVE 0xf0 /* |this| may be any primitive value */ + +#define JSFUN_FLAGS_MASK 0xf8 /* overlay JSFUN_* attributes */ + +#else + +#define JSFUN_GETTER_TEST(f) ((f) & JSFUN_GETTER) +#define JSFUN_SETTER_TEST(f) ((f) & JSFUN_SETTER) +#define JSFUN_BOUND_METHOD_TEST(f) ((f) & JSFUN_BOUND_METHOD) +#define JSFUN_HEAVYWEIGHT_TEST(f) ((f) & JSFUN_HEAVYWEIGHT) + +#define JSFUN_GSFLAG2ATTR(f) JSFUN_GSFLAGS(f) + +#define JSFUN_THISP_FLAGS(f) (f) +#define JSFUN_THISP_TEST(f,t) ((f) & t) + +#define JSFUN_THISP_STRING 0x0100 /* |this| may be a primitive string */ +#define JSFUN_THISP_NUMBER 0x0200 /* |this| may be a primitive number */ +#define JSFUN_THISP_BOOLEAN 0x0400 /* |this| may be a primitive boolean */ +#define JSFUN_THISP_PRIMITIVE 0x0700 /* |this| may be any primitive value */ + +#define JSFUN_FLAGS_MASK 0x07f8 /* overlay JSFUN_* attributes -- + note that bit #15 is used internally + to flag interpreted functions */ + +#endif + +/* + * Re-use JSFUN_LAMBDA, which applies only to scripted functions, for use in + * JSFunctionSpec arrays that specify generic native prototype methods, i.e., + * methods of a class prototype that are exposed as static methods taking an + * extra leading argument: the generic |this| parameter. + * + * If you set this flag in a JSFunctionSpec struct's flags initializer, then + * that struct must live at least as long as the native static method object + * created due to this flag by JS_DefineFunctions or JS_InitClass. Typically + * JSFunctionSpec structs are allocated in static arrays. + */ +#define JSFUN_GENERIC_NATIVE JSFUN_LAMBDA + +/* + * Well-known JS values. The extern'd variables are initialized when the + * first JSContext is created by JS_NewContext (see below). + */ +#define JSVAL_VOID INT_TO_JSVAL(0 - JSVAL_INT_POW2(30)) +#define JSVAL_NULL OBJECT_TO_JSVAL(0) +#define JSVAL_ZERO INT_TO_JSVAL(0) +#define JSVAL_ONE INT_TO_JSVAL(1) +#define JSVAL_FALSE BOOLEAN_TO_JSVAL(JS_FALSE) +#define JSVAL_TRUE BOOLEAN_TO_JSVAL(JS_TRUE) + +/* + * Microseconds since the epoch, midnight, January 1, 1970 UTC. See the + * comment in jstypes.h regarding safe int64 usage. + */ +extern JS_PUBLIC_API(int64) +JS_Now(); + +/* Don't want to export data, so provide accessors for non-inline jsvals. */ +extern JS_PUBLIC_API(jsval) +JS_GetNaNValue(JSContext *cx); + +extern JS_PUBLIC_API(jsval) +JS_GetNegativeInfinityValue(JSContext *cx); + +extern JS_PUBLIC_API(jsval) +JS_GetPositiveInfinityValue(JSContext *cx); + +extern JS_PUBLIC_API(jsval) +JS_GetEmptyStringValue(JSContext *cx); + +/* + * Format is a string of the following characters (spaces are insignificant), + * specifying the tabulated type conversions: + * + * b JSBool Boolean + * c uint16/jschar ECMA uint16, Unicode char + * i int32 ECMA int32 + * u uint32 ECMA uint32 + * j int32 Rounded int32 (coordinate) + * d jsdouble IEEE double + * I jsdouble Integral IEEE double + * s char * C string + * S JSString * Unicode string, accessed by a JSString pointer + * W jschar * Unicode character vector, 0-terminated (W for wide) + * o JSObject * Object reference + * f JSFunction * Function private + * v jsval Argument value (no conversion) + * * N/A Skip this argument (no vararg) + * / N/A End of required arguments + * + * The variable argument list after format must consist of &b, &c, &s, e.g., + * where those variables have the types given above. For the pointer types + * char *, JSString *, and JSObject *, the pointed-at memory returned belongs + * to the JS runtime, not to the calling native code. The runtime promises + * to keep this memory valid so long as argv refers to allocated stack space + * (so long as the native function is active). + * + * Fewer arguments than format specifies may be passed only if there is a / + * in format after the last required argument specifier and argc is at least + * the number of required arguments. More arguments than format specifies + * may be passed without error; it is up to the caller to deal with trailing + * unconverted arguments. + */ +extern JS_PUBLIC_API(JSBool) +JS_ConvertArguments(JSContext *cx, uintN argc, jsval *argv, const char *format, + ...); + +#ifdef va_start +extern JS_PUBLIC_API(JSBool) +JS_ConvertArgumentsVA(JSContext *cx, uintN argc, jsval *argv, + const char *format, va_list ap); +#endif + +/* + * Inverse of JS_ConvertArguments: scan format and convert trailing arguments + * into jsvals, GC-rooted if necessary by the JS stack. Return null on error, + * and a pointer to the new argument vector on success. Also return a stack + * mark on success via *markp, in which case the caller must eventually clean + * up by calling JS_PopArguments. + * + * Note that the number of actual arguments supplied is specified exclusively + * by format, so there is no argc parameter. + */ +extern JS_PUBLIC_API(jsval *) +JS_PushArguments(JSContext *cx, void **markp, const char *format, ...); + +#ifdef va_start +extern JS_PUBLIC_API(jsval *) +JS_PushArgumentsVA(JSContext *cx, void **markp, const char *format, va_list ap); +#endif + +extern JS_PUBLIC_API(void) +JS_PopArguments(JSContext *cx, void *mark); + +#ifdef JS_ARGUMENT_FORMATTER_DEFINED + +/* + * Add and remove a format string handler for JS_{Convert,Push}Arguments{,VA}. + * The handler function has this signature (see jspubtd.h): + * + * JSBool MyArgumentFormatter(JSContext *cx, const char *format, + * JSBool fromJS, jsval **vpp, va_list *app); + * + * It should return true on success, and return false after reporting an error + * or detecting an already-reported error. + * + * For a given format string, for example "AA", the formatter is called from + * JS_ConvertArgumentsVA like so: + * + * formatter(cx, "AA...", JS_TRUE, &sp, &ap); + * + * sp points into the arguments array on the JS stack, while ap points into + * the stdarg.h va_list on the C stack. The JS_TRUE passed for fromJS tells + * the formatter to convert zero or more jsvals at sp to zero or more C values + * accessed via pointers-to-values at ap, updating both sp (via *vpp) and ap + * (via *app) to point past the converted arguments and their result pointers + * on the C stack. + * + * When called from JS_PushArgumentsVA, the formatter is invoked thus: + * + * formatter(cx, "AA...", JS_FALSE, &sp, &ap); + * + * where JS_FALSE for fromJS means to wrap the C values at ap according to the + * format specifier and store them at sp, updating ap and sp appropriately. + * + * The "..." after "AA" is the rest of the format string that was passed into + * JS_{Convert,Push}Arguments{,VA}. The actual format trailing substring used + * in each Convert or PushArguments call is passed to the formatter, so that + * one such function may implement several formats, in order to share code. + * + * Remove just forgets about any handler associated with format. Add does not + * copy format, it points at the string storage allocated by the caller, which + * is typically a string constant. If format is in dynamic storage, it is up + * to the caller to keep the string alive until Remove is called. + */ +extern JS_PUBLIC_API(JSBool) +JS_AddArgumentFormatter(JSContext *cx, const char *format, + JSArgumentFormatter formatter); + +extern JS_PUBLIC_API(void) +JS_RemoveArgumentFormatter(JSContext *cx, const char *format); + +#endif /* JS_ARGUMENT_FORMATTER_DEFINED */ + +extern JS_PUBLIC_API(JSBool) +JS_ConvertValue(JSContext *cx, jsval v, JSType type, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_ValueToObject(JSContext *cx, jsval v, JSObject **objp); + +extern JS_PUBLIC_API(JSFunction *) +JS_ValueToFunction(JSContext *cx, jsval v); + +extern JS_PUBLIC_API(JSFunction *) +JS_ValueToConstructor(JSContext *cx, jsval v); + +extern JS_PUBLIC_API(JSString *) +JS_ValueToString(JSContext *cx, jsval v); + +extern JS_PUBLIC_API(JSBool) +JS_ValueToNumber(JSContext *cx, jsval v, jsdouble *dp); + +/* + * Convert a value to a number, then to an int32, according to the ECMA rules + * for ToInt32. + */ +extern JS_PUBLIC_API(JSBool) +JS_ValueToECMAInt32(JSContext *cx, jsval v, int32 *ip); + +/* + * Convert a value to a number, then to a uint32, according to the ECMA rules + * for ToUint32. + */ +extern JS_PUBLIC_API(JSBool) +JS_ValueToECMAUint32(JSContext *cx, jsval v, uint32 *ip); + +/* + * Convert a value to a number, then to an int32 if it fits by rounding to + * nearest; but failing with an error report if the double is out of range + * or unordered. + */ +extern JS_PUBLIC_API(JSBool) +JS_ValueToInt32(JSContext *cx, jsval v, int32 *ip); + +/* + * ECMA ToUint16, for mapping a jsval to a Unicode point. + */ +extern JS_PUBLIC_API(JSBool) +JS_ValueToUint16(JSContext *cx, jsval v, uint16 *ip); + +extern JS_PUBLIC_API(JSBool) +JS_ValueToBoolean(JSContext *cx, jsval v, JSBool *bp); + +extern JS_PUBLIC_API(JSType) +JS_TypeOfValue(JSContext *cx, jsval v); + +extern JS_PUBLIC_API(const char *) +JS_GetTypeName(JSContext *cx, JSType type); + +/************************************************************************/ + +/* + * Initialization, locking, contexts, and memory allocation. + */ +#define JS_NewRuntime JS_Init +#define JS_DestroyRuntime JS_Finish +#define JS_LockRuntime JS_Lock +#define JS_UnlockRuntime JS_Unlock + +extern JS_PUBLIC_API(JSRuntime *) +JS_NewRuntime(uint32 maxbytes); + +extern JS_PUBLIC_API(void) +JS_DestroyRuntime(JSRuntime *rt); + +extern JS_PUBLIC_API(void) +JS_ShutDown(void); + +JS_PUBLIC_API(void *) +JS_GetRuntimePrivate(JSRuntime *rt); + +JS_PUBLIC_API(void) +JS_SetRuntimePrivate(JSRuntime *rt, void *data); + +#ifdef JS_THREADSAFE + +extern JS_PUBLIC_API(void) +JS_BeginRequest(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_EndRequest(JSContext *cx); + +/* Yield to pending GC operations, regardless of request depth */ +extern JS_PUBLIC_API(void) +JS_YieldRequest(JSContext *cx); + +extern JS_PUBLIC_API(jsrefcount) +JS_SuspendRequest(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_ResumeRequest(JSContext *cx, jsrefcount saveDepth); + +#ifdef __cplusplus +JS_END_EXTERN_C + +class JSAutoRequest { + public: + JSAutoRequest(JSContext *cx) : mContext(cx), mSaveDepth(0) { + JS_BeginRequest(mContext); + } + ~JSAutoRequest() { + JS_EndRequest(mContext); + } + + void suspend() { + mSaveDepth = JS_SuspendRequest(mContext); + } + void resume() { + JS_ResumeRequest(mContext, mSaveDepth); + } + + protected: + JSContext *mContext; + jsrefcount mSaveDepth; + +#if 0 + private: + static void *operator new(size_t) CPP_THROW_NEW { return 0; }; + static void operator delete(void *, size_t) { }; +#endif +}; + +JS_BEGIN_EXTERN_C +#endif + +#endif /* JS_THREADSAFE */ + +extern JS_PUBLIC_API(void) +JS_Lock(JSRuntime *rt); + +extern JS_PUBLIC_API(void) +JS_Unlock(JSRuntime *rt); + +extern JS_PUBLIC_API(JSContextCallback) +JS_SetContextCallback(JSRuntime *rt, JSContextCallback cxCallback); + +extern JS_PUBLIC_API(JSContext *) +JS_NewContext(JSRuntime *rt, size_t stackChunkSize); + +extern JS_PUBLIC_API(void) +JS_DestroyContext(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_DestroyContextNoGC(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_DestroyContextMaybeGC(JSContext *cx); + +extern JS_PUBLIC_API(void *) +JS_GetContextPrivate(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_SetContextPrivate(JSContext *cx, void *data); + +extern JS_PUBLIC_API(JSRuntime *) +JS_GetRuntime(JSContext *cx); + +extern JS_PUBLIC_API(JSContext *) +JS_ContextIterator(JSRuntime *rt, JSContext **iterp); + +extern JS_PUBLIC_API(JSVersion) +JS_GetVersion(JSContext *cx); + +extern JS_PUBLIC_API(JSVersion) +JS_SetVersion(JSContext *cx, JSVersion version); + +extern JS_PUBLIC_API(const char *) +JS_VersionToString(JSVersion version); + +extern JS_PUBLIC_API(JSVersion) +JS_StringToVersion(const char *string); + +/* + * JS options are orthogonal to version, and may be freely composed with one + * another as well as with version. + * + * JSOPTION_VAROBJFIX is recommended -- see the comments associated with the + * prototypes for JS_ExecuteScript, JS_EvaluateScript, etc. + */ +#define JSOPTION_STRICT JS_BIT(0) /* warn on dubious practice */ +#define JSOPTION_WERROR JS_BIT(1) /* convert warning to error */ +#define JSOPTION_VAROBJFIX JS_BIT(2) /* make JS_EvaluateScript use + the last object on its 'obj' + param's scope chain as the + ECMA 'variables object' */ +#define JSOPTION_PRIVATE_IS_NSISUPPORTS \ + JS_BIT(3) /* context private data points + to an nsISupports subclass */ +#define JSOPTION_COMPILE_N_GO JS_BIT(4) /* caller of JS_Compile*Script + promises to execute compiled + script once only; enables + compile-time scope chain + resolution of consts. */ +#define JSOPTION_ATLINE JS_BIT(5) /* //@line number ["filename"] + option supported for the + XUL preprocessor and kindred + beasts. */ +#define JSOPTION_XML JS_BIT(6) /* EMCAScript for XML support: + parse as a token, + not backward compatible with + the comment-hiding hack used + in HTML script tags. */ +#define JSOPTION_NATIVE_BRANCH_CALLBACK \ + JS_BIT(7) /* the branch callback set by + JS_SetBranchCallback may be + called with a null script + parameter, by native code + that loops intensively */ +#define JSOPTION_DONT_REPORT_UNCAUGHT \ + JS_BIT(8) /* When returning from the + outermost API call, prevent + uncaught exceptions from + being converted to error + reports */ + +extern JS_PUBLIC_API(uint32) +JS_GetOptions(JSContext *cx); + +extern JS_PUBLIC_API(uint32) +JS_SetOptions(JSContext *cx, uint32 options); + +extern JS_PUBLIC_API(uint32) +JS_ToggleOptions(JSContext *cx, uint32 options); + +extern JS_PUBLIC_API(const char *) +JS_GetImplementationVersion(void); + +extern JS_PUBLIC_API(JSObject *) +JS_GetGlobalObject(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_SetGlobalObject(JSContext *cx, JSObject *obj); + +/* + * Initialize standard JS class constructors, prototypes, and any top-level + * functions and constants associated with the standard classes (e.g. isNaN + * for Number). + * + * NB: This sets cx's global object to obj if it was null. + */ +extern JS_PUBLIC_API(JSBool) +JS_InitStandardClasses(JSContext *cx, JSObject *obj); + +/* + * Resolve id, which must contain either a string or an int, to a standard + * class name in obj if possible, defining the class's constructor and/or + * prototype and storing true in *resolved. If id does not name a standard + * class or a top-level property induced by initializing a standard class, + * store false in *resolved and just return true. Return false on error, + * as usual for JSBool result-typed API entry points. + * + * This API can be called directly from a global object class's resolve op, + * to define standard classes lazily. The class's enumerate op should call + * JS_EnumerateStandardClasses(cx, obj), to define eagerly during for..in + * loops any classes not yet resolved lazily. + */ +extern JS_PUBLIC_API(JSBool) +JS_ResolveStandardClass(JSContext *cx, JSObject *obj, jsval id, + JSBool *resolved); + +extern JS_PUBLIC_API(JSBool) +JS_EnumerateStandardClasses(JSContext *cx, JSObject *obj); + +/* + * Enumerate any already-resolved standard class ids into ida, or into a new + * JSIdArray if ida is null. Return the augmented array on success, null on + * failure with ida (if it was non-null on entry) destroyed. + */ +extern JS_PUBLIC_API(JSIdArray *) +JS_EnumerateResolvedStandardClasses(JSContext *cx, JSObject *obj, + JSIdArray *ida); + +extern JS_PUBLIC_API(JSBool) +JS_GetClassObject(JSContext *cx, JSObject *obj, JSProtoKey key, + JSObject **objp); + +extern JS_PUBLIC_API(JSObject *) +JS_GetScopeChain(JSContext *cx); + +extern JS_PUBLIC_API(void *) +JS_malloc(JSContext *cx, size_t nbytes); + +extern JS_PUBLIC_API(void *) +JS_realloc(JSContext *cx, void *p, size_t nbytes); + +extern JS_PUBLIC_API(void) +JS_free(JSContext *cx, void *p); + +extern JS_PUBLIC_API(char *) +JS_strdup(JSContext *cx, const char *s); + +extern JS_PUBLIC_API(jsdouble *) +JS_NewDouble(JSContext *cx, jsdouble d); + +extern JS_PUBLIC_API(JSBool) +JS_NewDoubleValue(JSContext *cx, jsdouble d, jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_NewNumberValue(JSContext *cx, jsdouble d, jsval *rval); + +/* + * A JS GC root is a pointer to a JSObject *, JSString *, or jsdouble * that + * itself points into the GC heap (more recently, we support this extension: + * a root may be a pointer to a jsval v for which JSVAL_IS_GCTHING(v) is true). + * + * Therefore, you never pass JSObject *obj to JS_AddRoot(cx, obj). You always + * call JS_AddRoot(cx, &obj), passing obj by reference. And later, before obj + * or the structure it is embedded within goes out of scope or is freed, you + * must call JS_RemoveRoot(cx, &obj). + * + * Also, use JS_AddNamedRoot(cx, &structPtr->memberObj, "structPtr->memberObj") + * in preference to JS_AddRoot(cx, &structPtr->memberObj), in order to identify + * roots by their source callsites. This way, you can find the callsite while + * debugging if you should fail to do JS_RemoveRoot(cx, &structPtr->memberObj) + * before freeing structPtr's memory. + */ +extern JS_PUBLIC_API(JSBool) +JS_AddRoot(JSContext *cx, void *rp); + +#ifdef NAME_ALL_GC_ROOTS +#define JS_DEFINE_TO_TOKEN(def) #def +#define JS_DEFINE_TO_STRING(def) JS_DEFINE_TO_TOKEN(def) +#define JS_AddRoot(cx,rp) JS_AddNamedRoot((cx), (rp), (__FILE__ ":" JS_TOKEN_TO_STRING(__LINE__)) +#endif + +extern JS_PUBLIC_API(JSBool) +JS_AddNamedRoot(JSContext *cx, void *rp, const char *name); + +extern JS_PUBLIC_API(JSBool) +JS_AddNamedRootRT(JSRuntime *rt, void *rp, const char *name); + +extern JS_PUBLIC_API(JSBool) +JS_RemoveRoot(JSContext *cx, void *rp); + +extern JS_PUBLIC_API(JSBool) +JS_RemoveRootRT(JSRuntime *rt, void *rp); + +/* + * The last GC thing of each type (object, string, double, external string + * types) created on a given context is kept alive until another thing of the + * same type is created, using a newborn root in the context. These newborn + * roots help native code protect newly-created GC-things from GC invocations + * activated before those things can be rooted using local or global roots. + * + * However, the newborn roots can also entrain great gobs of garbage, so the + * JS_GC entry point clears them for the context on which GC is being forced. + * Embeddings may need to do likewise for all contexts. + * + * See the scoped local root API immediately below for a better way to manage + * newborns in cases where native hooks (functions, getters, setters, etc.) + * create many GC-things, potentially without connecting them to predefined + * local roots such as *rval or argv[i] in an active native function. Using + * JS_EnterLocalRootScope disables updating of the context's per-gc-thing-type + * newborn roots, until control flow unwinds and leaves the outermost nesting + * local root scope. + */ +extern JS_PUBLIC_API(void) +JS_ClearNewbornRoots(JSContext *cx); + +/* + * Scoped local root management allows native functions, getter/setters, etc. + * to avoid worrying about the newborn root pigeon-holes, overloading local + * roots allocated in argv and *rval, or ending up having to call JS_Add*Root + * and JS_RemoveRoot to manage global roots temporarily. + * + * Instead, calling JS_EnterLocalRootScope and JS_LeaveLocalRootScope around + * the body of the native hook causes the engine to allocate a local root for + * each newborn created in between the two API calls, using a local root stack + * associated with cx. For example: + * + * JSBool + * my_GetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) + * { + * JSBool ok; + * + * if (!JS_EnterLocalRootScope(cx)) + * return JS_FALSE; + * ok = my_GetPropertyBody(cx, obj, id, vp); + * JS_LeaveLocalRootScope(cx); + * return ok; + * } + * + * NB: JS_LeaveLocalRootScope must be called once for every prior successful + * call to JS_EnterLocalRootScope. If JS_EnterLocalRootScope fails, you must + * not make the matching JS_LeaveLocalRootScope call. + * + * JS_LeaveLocalRootScopeWithResult(cx, rval) is an alternative way to leave + * a local root scope that protects a result or return value, by effectively + * pushing it in the caller's local root scope. + * + * In case a native hook allocates many objects or other GC-things, but the + * native protects some of those GC-things by storing them as property values + * in an object that is itself protected, the hook can call JS_ForgetLocalRoot + * to free the local root automatically pushed for the now-protected GC-thing. + * + * JS_ForgetLocalRoot works on any GC-thing allocated in the current local + * root scope, but it's more time-efficient when called on references to more + * recently created GC-things. Calling it successively on other than the most + * recently allocated GC-thing will tend to average the time inefficiency, and + * may risk O(n^2) growth rate, but in any event, you shouldn't allocate too + * many local roots if you can root as you go (build a tree of objects from + * the top down, forgetting each latest-allocated GC-thing immediately upon + * linking it to its parent). + */ +extern JS_PUBLIC_API(JSBool) +JS_EnterLocalRootScope(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_LeaveLocalRootScope(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_LeaveLocalRootScopeWithResult(JSContext *cx, jsval rval); + +extern JS_PUBLIC_API(void) +JS_ForgetLocalRoot(JSContext *cx, void *thing); + +#ifdef __cplusplus +JS_END_EXTERN_C + +class JSAutoLocalRootScope { + public: + JSAutoLocalRootScope(JSContext *cx) : mContext(cx) { + JS_EnterLocalRootScope(mContext); + } + ~JSAutoLocalRootScope() { + JS_LeaveLocalRootScope(mContext); + } + + void forget(void *thing) { + JS_ForgetLocalRoot(mContext, thing); + } + + protected: + JSContext *mContext; + +#if 0 + private: + static void *operator new(size_t) CPP_THROW_NEW { return 0; }; + static void operator delete(void *, size_t) { }; +#endif +}; + +JS_BEGIN_EXTERN_C +#endif + +#ifdef DEBUG +extern JS_PUBLIC_API(void) +JS_DumpNamedRoots(JSRuntime *rt, + void (*dump)(const char *name, void *rp, void *data), + void *data); +#endif + +/* + * Call JS_MapGCRoots to map the GC's roots table using map(rp, name, data). + * The root is pointed at by rp; if the root is unnamed, name is null; data is + * supplied from the third parameter to JS_MapGCRoots. + * + * The map function should return JS_MAP_GCROOT_REMOVE to cause the currently + * enumerated root to be removed. To stop enumeration, set JS_MAP_GCROOT_STOP + * in the return value. To keep on mapping, return JS_MAP_GCROOT_NEXT. These + * constants are flags; you can OR them together. + * + * This function acquires and releases rt's GC lock around the mapping of the + * roots table, so the map function should run to completion in as few cycles + * as possible. Of course, map cannot call JS_GC, JS_MaybeGC, JS_BeginRequest, + * or any JS API entry point that acquires locks, without double-tripping or + * deadlocking on the GC lock. + * + * JS_MapGCRoots returns the count of roots that were successfully mapped. + */ +#define JS_MAP_GCROOT_NEXT 0 /* continue mapping entries */ +#define JS_MAP_GCROOT_STOP 1 /* stop mapping entries */ +#define JS_MAP_GCROOT_REMOVE 2 /* remove and free the current entry */ + +typedef intN +(* JS_DLL_CALLBACK JSGCRootMapFun)(void *rp, const char *name, void *data); + +extern JS_PUBLIC_API(uint32) +JS_MapGCRoots(JSRuntime *rt, JSGCRootMapFun map, void *data); + +extern JS_PUBLIC_API(JSBool) +JS_LockGCThing(JSContext *cx, void *thing); + +extern JS_PUBLIC_API(JSBool) +JS_LockGCThingRT(JSRuntime *rt, void *thing); + +extern JS_PUBLIC_API(JSBool) +JS_UnlockGCThing(JSContext *cx, void *thing); + +extern JS_PUBLIC_API(JSBool) +JS_UnlockGCThingRT(JSRuntime *rt, void *thing); + +/* + * For implementors of JSObjectOps.mark, to mark a GC-thing reachable via a + * property or other strong ref identified for debugging purposes by name. + * The name argument's storage needs to live only as long as the call to + * this routine. + * + * The final arg is used by GC_MARK_DEBUG code to build a ref path through + * the GC's live thing graph. Implementors of JSObjectOps.mark should pass + * its final arg through to this function when marking all GC-things that are + * directly reachable from the object being marked. + * + * See the JSMarkOp typedef in jspubtd.h, and the JSObjectOps struct below. + */ +extern JS_PUBLIC_API(void) +JS_MarkGCThing(JSContext *cx, void *thing, const char *name, void *arg); + +extern JS_PUBLIC_API(void) +JS_GC(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_MaybeGC(JSContext *cx); + +extern JS_PUBLIC_API(JSGCCallback) +JS_SetGCCallback(JSContext *cx, JSGCCallback cb); + +extern JS_PUBLIC_API(JSGCCallback) +JS_SetGCCallbackRT(JSRuntime *rt, JSGCCallback cb); + +extern JS_PUBLIC_API(JSBool) +JS_IsAboutToBeFinalized(JSContext *cx, void *thing); + +typedef enum JSGCParamKey { + JSGC_MAX_BYTES = 0, /* maximum nominal heap before last ditch GC */ + JSGC_MAX_MALLOC_BYTES = 1 /* # of JS_malloc bytes before last ditch GC */ +} JSGCParamKey; + +extern JS_PUBLIC_API(void) +JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32 value); + +/* + * Add a finalizer for external strings created by JS_NewExternalString (see + * below) using a type-code returned from this function, and that understands + * how to free or release the memory pointed at by JS_GetStringChars(str). + * + * Return a nonnegative type index if there is room for finalizer in the + * global GC finalizers table, else return -1. If the engine is compiled + * JS_THREADSAFE and used in a multi-threaded environment, this function must + * be invoked on the primordial thread only, at startup -- or else the entire + * program must single-thread itself while loading a module that calls this + * function. + */ +extern JS_PUBLIC_API(intN) +JS_AddExternalStringFinalizer(JSStringFinalizeOp finalizer); + +/* + * Remove finalizer from the global GC finalizers table, returning its type + * code if found, -1 if not found. + * + * As with JS_AddExternalStringFinalizer, there is a threading restriction + * if you compile the engine JS_THREADSAFE: this function may be called for a + * given finalizer pointer on only one thread; different threads may call to + * remove distinct finalizers safely. + * + * You must ensure that all strings with finalizer's type have been collected + * before calling this function. Otherwise, string data will be leaked by the + * GC, for want of a finalizer to call. + */ +extern JS_PUBLIC_API(intN) +JS_RemoveExternalStringFinalizer(JSStringFinalizeOp finalizer); + +/* + * Create a new JSString whose chars member refers to external memory, i.e., + * memory requiring special, type-specific finalization. The type code must + * be a nonnegative return value from JS_AddExternalStringFinalizer. + */ +extern JS_PUBLIC_API(JSString *) +JS_NewExternalString(JSContext *cx, jschar *chars, size_t length, intN type); + +/* + * Returns the external-string finalizer index for this string, or -1 if it is + * an "internal" (native to JS engine) string. + */ +extern JS_PUBLIC_API(intN) +JS_GetExternalStringGCType(JSRuntime *rt, JSString *str); + +/* + * Sets maximum (if stack grows upward) or minimum (downward) legal stack byte + * address in limitAddr for the thread or process stack used by cx. To disable + * stack size checking, pass 0 for limitAddr. + */ +extern JS_PUBLIC_API(void) +JS_SetThreadStackLimit(JSContext *cx, jsuword limitAddr); + +/************************************************************************/ + +/* + * Classes, objects, and properties. + */ + +/* For detailed comments on the function pointer types, see jspubtd.h. */ +struct JSClass { + const char *name; + uint32 flags; + + /* Mandatory non-null function pointer members. */ + JSPropertyOp addProperty; + JSPropertyOp delProperty; + JSPropertyOp getProperty; + JSPropertyOp setProperty; + JSEnumerateOp enumerate; + JSResolveOp resolve; + JSConvertOp convert; + JSFinalizeOp finalize; + + /* Optionally non-null members start here. */ + JSGetObjectOps getObjectOps; + JSCheckAccessOp checkAccess; + JSNative call; + JSNative construct; + JSXDRObjectOp xdrObject; + JSHasInstanceOp hasInstance; + JSMarkOp mark; + JSReserveSlotsOp reserveSlots; +}; + +struct JSExtendedClass { + JSClass base; + JSEqualityOp equality; + JSObjectOp outerObject; + JSObjectOp innerObject; + void (*reserved0)(); + void (*reserved1)(); + void (*reserved2)(); + void (*reserved3)(); + void (*reserved4)(); +}; + +#define JSCLASS_HAS_PRIVATE (1<<0) /* objects have private slot */ +#define JSCLASS_NEW_ENUMERATE (1<<1) /* has JSNewEnumerateOp hook */ +#define JSCLASS_NEW_RESOLVE (1<<2) /* has JSNewResolveOp hook */ +#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) /* private is (nsISupports *) */ +#define JSCLASS_SHARE_ALL_PROPERTIES (1<<4) /* all properties are SHARED */ +#define JSCLASS_NEW_RESOLVE_GETS_START (1<<5) /* JSNewResolveOp gets starting + object in prototype chain + passed in via *objp in/out + parameter */ +#define JSCLASS_CONSTRUCT_PROTOTYPE (1<<6) /* call constructor on class + prototype */ +#define JSCLASS_DOCUMENT_OBSERVER (1<<7) /* DOM document observer */ + +/* + * To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or + * JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where + * n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. + */ +#define JSCLASS_RESERVED_SLOTS_SHIFT 8 /* room for 8 flags below */ +#define JSCLASS_RESERVED_SLOTS_WIDTH 8 /* and 16 above this field */ +#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) +#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ + << JSCLASS_RESERVED_SLOTS_SHIFT) +#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ + >> JSCLASS_RESERVED_SLOTS_SHIFT) \ + & JSCLASS_RESERVED_SLOTS_MASK) + +#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ + JSCLASS_RESERVED_SLOTS_WIDTH) + +/* True if JSClass is really a JSExtendedClass. */ +#define JSCLASS_IS_EXTENDED (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) +#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) +#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) + +/* + * ECMA-262 requires that most constructors used internally create objects + * with "the original Foo.prototype value" as their [[Prototype]] (__proto__) + * member initial value. The "original ... value" verbiage is there because + * in ECMA-262, global properties naming class objects are read/write and + * deleteable, for the most part. + * + * Implementing this efficiently requires that global objects have classes + * with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS won't break + * anything except the ECMA-262 "original prototype value" behavior, which was + * broken for years in SpiderMonkey. In other words, without these flags you + * get backward compatibility. + */ +#define JSCLASS_GLOBAL_FLAGS \ + (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSProto_LIMIT)) + +/* Fast access to the original value of each standard class's prototype. */ +#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 8) +#define JSCLASS_CACHED_PROTO_WIDTH 8 +#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH) +#define JSCLASS_HAS_CACHED_PROTO(key) ((key) << JSCLASS_CACHED_PROTO_SHIFT) +#define JSCLASS_CACHED_PROTO_KEY(clasp) (((clasp)->flags \ + >> JSCLASS_CACHED_PROTO_SHIFT) \ + & JSCLASS_CACHED_PROTO_MASK) + +/* Initializer for unused members of statically initialized JSClass structs. */ +#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,0,0,0 +#define JSCLASS_NO_RESERVED_MEMBERS 0,0,0,0,0 + +/* For detailed comments on these function pointer types, see jspubtd.h. */ +struct JSObjectOps { + /* Mandatory non-null function pointer members. */ + JSNewObjectMapOp newObjectMap; + JSObjectMapOp destroyObjectMap; + JSLookupPropOp lookupProperty; + JSDefinePropOp defineProperty; + JSPropertyIdOp getProperty; + JSPropertyIdOp setProperty; + JSAttributesOp getAttributes; + JSAttributesOp setAttributes; + JSPropertyIdOp deleteProperty; + JSConvertOp defaultValue; + JSNewEnumerateOp enumerate; + JSCheckAccessIdOp checkAccess; + + /* Optionally non-null members start here. */ + JSObjectOp thisObject; + JSPropertyRefOp dropProperty; + JSNative call; + JSNative construct; + JSXDRObjectOp xdrObject; + JSHasInstanceOp hasInstance; + JSSetObjectSlotOp setProto; + JSSetObjectSlotOp setParent; + JSMarkOp mark; + JSFinalizeOp clear; + JSGetRequiredSlotOp getRequiredSlot; + JSSetRequiredSlotOp setRequiredSlot; +}; + +struct JSXMLObjectOps { + JSObjectOps base; + JSGetMethodOp getMethod; + JSSetMethodOp setMethod; + JSEnumerateValuesOp enumerateValues; + JSEqualityOp equality; + JSConcatenateOp concatenate; +}; + +/* + * Classes that expose JSObjectOps via a non-null getObjectOps class hook may + * derive a property structure from this struct, return a pointer to it from + * lookupProperty and defineProperty, and use the pointer to avoid rehashing + * in getAttributes and setAttributes. + * + * The jsid type contains either an int jsval (see JSVAL_IS_INT above), or an + * internal pointer that is opaque to users of this API, but which users may + * convert from and to a jsval using JS_ValueToId and JS_IdToValue. + */ +struct JSProperty { + jsid id; +}; + +struct JSIdArray { + jsint length; + jsid vector[1]; /* actually, length jsid words */ +}; + +extern JS_PUBLIC_API(void) +JS_DestroyIdArray(JSContext *cx, JSIdArray *ida); + +extern JS_PUBLIC_API(JSBool) +JS_ValueToId(JSContext *cx, jsval v, jsid *idp); + +extern JS_PUBLIC_API(JSBool) +JS_IdToValue(JSContext *cx, jsid id, jsval *vp); + +/* + * The magic XML namespace id is int-tagged, but not a valid integer jsval. + * Global object classes in embeddings that enable JS_HAS_XML_SUPPORT (E4X) + * should handle this id specially before converting id via JSVAL_TO_INT. + */ +#define JS_DEFAULT_XML_NAMESPACE_ID ((jsid) JSVAL_VOID) + +/* + * JSNewResolveOp flag bits. + */ +#define JSRESOLVE_QUALIFIED 0x01 /* resolve a qualified property id */ +#define JSRESOLVE_ASSIGNING 0x02 /* resolve on the left of assignment */ +#define JSRESOLVE_DETECTING 0x04 /* 'if (o.p)...' or '(o.p) ?...:...' */ +#define JSRESOLVE_DECLARING 0x08 /* var, const, or function prolog op */ +#define JSRESOLVE_CLASSNAME 0x10 /* class name used when constructing */ + +extern JS_PUBLIC_API(JSBool) +JS_PropertyStub(JSContext *cx, JSObject *obj, jsval id, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_EnumerateStub(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_ResolveStub(JSContext *cx, JSObject *obj, jsval id); + +extern JS_PUBLIC_API(JSBool) +JS_ConvertStub(JSContext *cx, JSObject *obj, JSType type, jsval *vp); + +extern JS_PUBLIC_API(void) +JS_FinalizeStub(JSContext *cx, JSObject *obj); + +struct JSConstDoubleSpec { + jsdouble dval; + const char *name; + uint8 flags; + uint8 spare[3]; +}; + +/* + * To define an array element rather than a named property member, cast the + * element's index to (const char *) and initialize name with it, and set the + * JSPROP_INDEX bit in flags. + */ +struct JSPropertySpec { + const char *name; + int8 tinyid; + uint8 flags; + JSPropertyOp getter; + JSPropertyOp setter; +}; + +struct JSFunctionSpec { + const char *name; + JSNative call; +#ifdef MOZILLA_1_8_BRANCH + uint8 nargs; + uint8 flags; + uint16 extra; +#else + uint16 nargs; + uint16 flags; + uint32 extra; /* extra & 0xFFFF: + number of arg slots for local GC roots + extra >> 16: + reserved, must be zero */ +#endif +}; + +extern JS_PUBLIC_API(JSObject *) +JS_InitClass(JSContext *cx, JSObject *obj, JSObject *parent_proto, + JSClass *clasp, JSNative constructor, uintN nargs, + JSPropertySpec *ps, JSFunctionSpec *fs, + JSPropertySpec *static_ps, JSFunctionSpec *static_fs); + +#ifdef JS_THREADSAFE +extern JS_PUBLIC_API(JSClass *) +JS_GetClass(JSContext *cx, JSObject *obj); + +#define JS_GET_CLASS(cx,obj) JS_GetClass(cx, obj) +#else +extern JS_PUBLIC_API(JSClass *) +JS_GetClass(JSObject *obj); + +#define JS_GET_CLASS(cx,obj) JS_GetClass(obj) +#endif + +extern JS_PUBLIC_API(JSBool) +JS_InstanceOf(JSContext *cx, JSObject *obj, JSClass *clasp, jsval *argv); + +extern JS_PUBLIC_API(JSBool) +JS_HasInstance(JSContext *cx, JSObject *obj, jsval v, JSBool *bp); + +extern JS_PUBLIC_API(void *) +JS_GetPrivate(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_SetPrivate(JSContext *cx, JSObject *obj, void *data); + +extern JS_PUBLIC_API(void *) +JS_GetInstancePrivate(JSContext *cx, JSObject *obj, JSClass *clasp, + jsval *argv); + +extern JS_PUBLIC_API(JSObject *) +JS_GetPrototype(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_SetPrototype(JSContext *cx, JSObject *obj, JSObject *proto); + +extern JS_PUBLIC_API(JSObject *) +JS_GetParent(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_SetParent(JSContext *cx, JSObject *obj, JSObject *parent); + +extern JS_PUBLIC_API(JSObject *) +JS_GetConstructor(JSContext *cx, JSObject *proto); + +/* + * Get a unique identifier for obj, good for the lifetime of obj (even if it + * is moved by a copying GC). Return false on failure (likely out of memory), + * and true with *idp containing the unique id on success. + */ +extern JS_PUBLIC_API(JSBool) +JS_GetObjectId(JSContext *cx, JSObject *obj, jsid *idp); + +extern JS_PUBLIC_API(JSObject *) +JS_NewObject(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); + +extern JS_PUBLIC_API(JSBool) +JS_SealObject(JSContext *cx, JSObject *obj, JSBool deep); + +extern JS_PUBLIC_API(JSObject *) +JS_ConstructObject(JSContext *cx, JSClass *clasp, JSObject *proto, + JSObject *parent); + +extern JS_PUBLIC_API(JSObject *) +JS_ConstructObjectWithArguments(JSContext *cx, JSClass *clasp, JSObject *proto, + JSObject *parent, uintN argc, jsval *argv); + +extern JS_PUBLIC_API(JSObject *) +JS_DefineObject(JSContext *cx, JSObject *obj, const char *name, JSClass *clasp, + JSObject *proto, uintN attrs); + +extern JS_PUBLIC_API(JSBool) +JS_DefineConstDoubles(JSContext *cx, JSObject *obj, JSConstDoubleSpec *cds); + +extern JS_PUBLIC_API(JSBool) +JS_DefineProperties(JSContext *cx, JSObject *obj, JSPropertySpec *ps); + +extern JS_PUBLIC_API(JSBool) +JS_DefineProperty(JSContext *cx, JSObject *obj, const char *name, jsval value, + JSPropertyOp getter, JSPropertyOp setter, uintN attrs); + +/* + * Determine the attributes (JSPROP_* flags) of a property on a given object. + * + * If the object does not have a property by that name, *foundp will be + * JS_FALSE and the value of *attrsp is undefined. + */ +extern JS_PUBLIC_API(JSBool) +JS_GetPropertyAttributes(JSContext *cx, JSObject *obj, const char *name, + uintN *attrsp, JSBool *foundp); + +/* + * The same, but if the property is native, return its getter and setter via + * *getterp and *setterp, respectively (and only if the out parameter pointer + * is not null). + */ +extern JS_PUBLIC_API(JSBool) +JS_GetPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *obj, + const char *name, + uintN *attrsp, JSBool *foundp, + JSPropertyOp *getterp, + JSPropertyOp *setterp); + +/* + * Set the attributes of a property on a given object. + * + * If the object does not have a property by that name, *foundp will be + * JS_FALSE and nothing will be altered. + */ +extern JS_PUBLIC_API(JSBool) +JS_SetPropertyAttributes(JSContext *cx, JSObject *obj, const char *name, + uintN attrs, JSBool *foundp); + +extern JS_PUBLIC_API(JSBool) +JS_DefinePropertyWithTinyId(JSContext *cx, JSObject *obj, const char *name, + int8 tinyid, jsval value, + JSPropertyOp getter, JSPropertyOp setter, + uintN attrs); + +extern JS_PUBLIC_API(JSBool) +JS_AliasProperty(JSContext *cx, JSObject *obj, const char *name, + const char *alias); + +extern JS_PUBLIC_API(JSBool) +JS_HasProperty(JSContext *cx, JSObject *obj, const char *name, JSBool *foundp); + +extern JS_PUBLIC_API(JSBool) +JS_LookupProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_LookupPropertyWithFlags(JSContext *cx, JSObject *obj, const char *name, + uintN flags, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_GetProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_GetMethodById(JSContext *cx, JSObject *obj, jsid id, JSObject **objp, + jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_GetMethod(JSContext *cx, JSObject *obj, const char *name, JSObject **objp, + jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_SetProperty(JSContext *cx, JSObject *obj, const char *name, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_DeleteProperty(JSContext *cx, JSObject *obj, const char *name); + +extern JS_PUBLIC_API(JSBool) +JS_DeleteProperty2(JSContext *cx, JSObject *obj, const char *name, + jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_DefineUCProperty(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, jsval value, + JSPropertyOp getter, JSPropertyOp setter, + uintN attrs); + +/* + * Determine the attributes (JSPROP_* flags) of a property on a given object. + * + * If the object does not have a property by that name, *foundp will be + * JS_FALSE and the value of *attrsp is undefined. + */ +extern JS_PUBLIC_API(JSBool) +JS_GetUCPropertyAttributes(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + uintN *attrsp, JSBool *foundp); + +/* + * The same, but if the property is native, return its getter and setter via + * *getterp and *setterp, respectively (and only if the out parameter pointer + * is not null). + */ +extern JS_PUBLIC_API(JSBool) +JS_GetUCPropertyAttrsGetterAndSetter(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + uintN *attrsp, JSBool *foundp, + JSPropertyOp *getterp, + JSPropertyOp *setterp); + +/* + * Set the attributes of a property on a given object. + * + * If the object does not have a property by that name, *foundp will be + * JS_FALSE and nothing will be altered. + */ +extern JS_PUBLIC_API(JSBool) +JS_SetUCPropertyAttributes(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + uintN attrs, JSBool *foundp); + + +extern JS_PUBLIC_API(JSBool) +JS_DefineUCPropertyWithTinyId(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + int8 tinyid, jsval value, + JSPropertyOp getter, JSPropertyOp setter, + uintN attrs); + +extern JS_PUBLIC_API(JSBool) +JS_HasUCProperty(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + JSBool *vp); + +extern JS_PUBLIC_API(JSBool) +JS_LookupUCProperty(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_GetUCProperty(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_SetUCProperty(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_DeleteUCProperty2(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, + jsval *rval); + +extern JS_PUBLIC_API(JSObject *) +JS_NewArrayObject(JSContext *cx, jsint length, jsval *vector); + +extern JS_PUBLIC_API(JSBool) +JS_IsArrayObject(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_GetArrayLength(JSContext *cx, JSObject *obj, jsuint *lengthp); + +extern JS_PUBLIC_API(JSBool) +JS_SetArrayLength(JSContext *cx, JSObject *obj, jsuint length); + +extern JS_PUBLIC_API(JSBool) +JS_HasArrayLength(JSContext *cx, JSObject *obj, jsuint *lengthp); + +extern JS_PUBLIC_API(JSBool) +JS_DefineElement(JSContext *cx, JSObject *obj, jsint index, jsval value, + JSPropertyOp getter, JSPropertyOp setter, uintN attrs); + +extern JS_PUBLIC_API(JSBool) +JS_AliasElement(JSContext *cx, JSObject *obj, const char *name, jsint alias); + +extern JS_PUBLIC_API(JSBool) +JS_HasElement(JSContext *cx, JSObject *obj, jsint index, JSBool *foundp); + +extern JS_PUBLIC_API(JSBool) +JS_LookupElement(JSContext *cx, JSObject *obj, jsint index, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_GetElement(JSContext *cx, JSObject *obj, jsint index, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_SetElement(JSContext *cx, JSObject *obj, jsint index, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_DeleteElement(JSContext *cx, JSObject *obj, jsint index); + +extern JS_PUBLIC_API(JSBool) +JS_DeleteElement2(JSContext *cx, JSObject *obj, jsint index, jsval *rval); + +extern JS_PUBLIC_API(void) +JS_ClearScope(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSIdArray *) +JS_Enumerate(JSContext *cx, JSObject *obj); + +/* + * Create an object to iterate over enumerable properties of obj, in arbitrary + * property definition order. NB: This differs from longstanding for..in loop + * order, which uses order of property definition in obj. + */ +extern JS_PUBLIC_API(JSObject *) +JS_NewPropertyIterator(JSContext *cx, JSObject *obj); + +/* + * Return true on success with *idp containing the id of the next enumerable + * property to visit using iterobj, or JSVAL_VOID if there is no such property + * left to visit. Return false on error. + */ +extern JS_PUBLIC_API(JSBool) +JS_NextProperty(JSContext *cx, JSObject *iterobj, jsid *idp); + +extern JS_PUBLIC_API(JSBool) +JS_CheckAccess(JSContext *cx, JSObject *obj, jsid id, JSAccessMode mode, + jsval *vp, uintN *attrsp); + +extern JS_PUBLIC_API(JSCheckAccessOp) +JS_SetCheckObjectAccessCallback(JSRuntime *rt, JSCheckAccessOp acb); + +extern JS_PUBLIC_API(JSBool) +JS_GetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, jsval *vp); + +extern JS_PUBLIC_API(JSBool) +JS_SetReservedSlot(JSContext *cx, JSObject *obj, uint32 index, jsval v); + +/************************************************************************/ + +/* + * Security protocol. + */ +struct JSPrincipals { + char *codebase; + + /* XXX unspecified and unused by Mozilla code -- can we remove these? */ + void * (* JS_DLL_CALLBACK getPrincipalArray)(JSContext *cx, JSPrincipals *); + JSBool (* JS_DLL_CALLBACK globalPrivilegesEnabled)(JSContext *cx, JSPrincipals *); + + /* Don't call "destroy"; use reference counting macros below. */ + jsrefcount refcount; + + void (* JS_DLL_CALLBACK destroy)(JSContext *cx, JSPrincipals *); + JSBool (* JS_DLL_CALLBACK subsume)(JSPrincipals *, JSPrincipals *); +}; + +#ifdef JS_THREADSAFE +#define JSPRINCIPALS_HOLD(cx, principals) JS_HoldPrincipals(cx,principals) +#define JSPRINCIPALS_DROP(cx, principals) JS_DropPrincipals(cx,principals) + +extern JS_PUBLIC_API(jsrefcount) +JS_HoldPrincipals(JSContext *cx, JSPrincipals *principals); + +extern JS_PUBLIC_API(jsrefcount) +JS_DropPrincipals(JSContext *cx, JSPrincipals *principals); + +#else +#define JSPRINCIPALS_HOLD(cx, principals) (++(principals)->refcount) +#define JSPRINCIPALS_DROP(cx, principals) \ + ((--(principals)->refcount == 0) \ + ? ((*(principals)->destroy)((cx), (principals)), 0) \ + : (principals)->refcount) +#endif + +extern JS_PUBLIC_API(JSPrincipalsTranscoder) +JS_SetPrincipalsTranscoder(JSRuntime *rt, JSPrincipalsTranscoder px); + +extern JS_PUBLIC_API(JSObjectPrincipalsFinder) +JS_SetObjectPrincipalsFinder(JSRuntime *rt, JSObjectPrincipalsFinder fop); + +/************************************************************************/ + +/* + * Functions and scripts. + */ +extern JS_PUBLIC_API(JSFunction *) +JS_NewFunction(JSContext *cx, JSNative call, uintN nargs, uintN flags, + JSObject *parent, const char *name); + +extern JS_PUBLIC_API(JSObject *) +JS_GetFunctionObject(JSFunction *fun); + +/* + * Deprecated, useful only for diagnostics. Use JS_GetFunctionId instead for + * anonymous vs. "anonymous" disambiguation and Unicode fidelity. + */ +extern JS_PUBLIC_API(const char *) +JS_GetFunctionName(JSFunction *fun); + +/* + * Return the function's identifier as a JSString, or null if fun is unnamed. + * The returned string lives as long as fun, so you don't need to root a saved + * reference to it if fun is well-connected or rooted, and provided you bound + * the use of the saved reference by fun's lifetime. + * + * Prefer JS_GetFunctionId over JS_GetFunctionName because it returns null for + * truly anonymous functions, and because it doesn't chop to ISO-Latin-1 chars + * from UTF-16-ish jschars. + */ +extern JS_PUBLIC_API(JSString *) +JS_GetFunctionId(JSFunction *fun); + +/* + * Return JSFUN_* flags for fun. + */ +extern JS_PUBLIC_API(uintN) +JS_GetFunctionFlags(JSFunction *fun); + +/* + * Return the arity (length) of fun. + */ +extern JS_PUBLIC_API(uint16) +JS_GetFunctionArity(JSFunction *fun); + +/* + * Infallible predicate to test whether obj is a function object (faster than + * comparing obj's class name to "Function", but equivalent unless someone has + * overwritten the "Function" identifier with a different constructor and then + * created instances using that constructor that might be passed in as obj). + */ +extern JS_PUBLIC_API(JSBool) +JS_ObjectIsFunction(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_DefineFunctions(JSContext *cx, JSObject *obj, JSFunctionSpec *fs); + +extern JS_PUBLIC_API(JSFunction *) +JS_DefineFunction(JSContext *cx, JSObject *obj, const char *name, JSNative call, + uintN nargs, uintN attrs); + +extern JS_PUBLIC_API(JSFunction *) +JS_DefineUCFunction(JSContext *cx, JSObject *obj, + const jschar *name, size_t namelen, JSNative call, + uintN nargs, uintN attrs); + +extern JS_PUBLIC_API(JSObject *) +JS_CloneFunctionObject(JSContext *cx, JSObject *funobj, JSObject *parent); + +/* + * Given a buffer, return JS_FALSE if the buffer might become a valid + * javascript statement with the addition of more lines. Otherwise return + * JS_TRUE. The intent is to support interactive compilation - accumulate + * lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to + * the compiler. + */ +extern JS_PUBLIC_API(JSBool) +JS_BufferIsCompilableUnit(JSContext *cx, JSObject *obj, + const char *bytes, size_t length); + +/* + * The JSScript objects returned by the following functions refer to string and + * other kinds of literals, including doubles and RegExp objects. These + * literals are vulnerable to garbage collection; to root script objects and + * prevent literals from being collected, create a rootable object using + * JS_NewScriptObject, and root the resulting object using JS_Add[Named]Root. + */ +extern JS_PUBLIC_API(JSScript *) +JS_CompileScript(JSContext *cx, JSObject *obj, + const char *bytes, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSScript *) +JS_CompileScriptForPrincipals(JSContext *cx, JSObject *obj, + JSPrincipals *principals, + const char *bytes, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSScript *) +JS_CompileUCScript(JSContext *cx, JSObject *obj, + const jschar *chars, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSScript *) +JS_CompileUCScriptForPrincipals(JSContext *cx, JSObject *obj, + JSPrincipals *principals, + const jschar *chars, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSScript *) +JS_CompileFile(JSContext *cx, JSObject *obj, const char *filename); + +extern JS_PUBLIC_API(JSScript *) +JS_CompileFileHandle(JSContext *cx, JSObject *obj, const char *filename, + FILE *fh); + +extern JS_PUBLIC_API(JSScript *) +JS_CompileFileHandleForPrincipals(JSContext *cx, JSObject *obj, + const char *filename, FILE *fh, + JSPrincipals *principals); + +/* + * NB: you must use JS_NewScriptObject and root a pointer to its return value + * in order to keep a JSScript and its atoms safe from garbage collection after + * creating the script via JS_Compile* and before a JS_ExecuteScript* call. + * E.g., and without error checks: + * + * JSScript *script = JS_CompileFile(cx, global, filename); + * JSObject *scrobj = JS_NewScriptObject(cx, script); + * JS_AddNamedRoot(cx, &scrobj, "scrobj"); + * do { + * jsval result; + * JS_ExecuteScript(cx, global, script, &result); + * JS_GC(); + * } while (!JSVAL_IS_BOOLEAN(result) || JSVAL_TO_BOOLEAN(result)); + * JS_RemoveRoot(cx, &scrobj); + */ +extern JS_PUBLIC_API(JSObject *) +JS_NewScriptObject(JSContext *cx, JSScript *script); + +/* + * Infallible getter for a script's object. If JS_NewScriptObject has not been + * called on script yet, the return value will be null. + */ +extern JS_PUBLIC_API(JSObject *) +JS_GetScriptObject(JSScript *script); + +extern JS_PUBLIC_API(void) +JS_DestroyScript(JSContext *cx, JSScript *script); + +extern JS_PUBLIC_API(JSFunction *) +JS_CompileFunction(JSContext *cx, JSObject *obj, const char *name, + uintN nargs, const char **argnames, + const char *bytes, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSFunction *) +JS_CompileFunctionForPrincipals(JSContext *cx, JSObject *obj, + JSPrincipals *principals, const char *name, + uintN nargs, const char **argnames, + const char *bytes, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSFunction *) +JS_CompileUCFunction(JSContext *cx, JSObject *obj, const char *name, + uintN nargs, const char **argnames, + const jschar *chars, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSFunction *) +JS_CompileUCFunctionForPrincipals(JSContext *cx, JSObject *obj, + JSPrincipals *principals, const char *name, + uintN nargs, const char **argnames, + const jschar *chars, size_t length, + const char *filename, uintN lineno); + +extern JS_PUBLIC_API(JSString *) +JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, + uintN indent); + +/* + * API extension: OR this into indent to avoid pretty-printing the decompiled + * source resulting from JS_DecompileFunction{,Body}. + */ +#define JS_DONT_PRETTY_PRINT ((uintN)0x8000) + +extern JS_PUBLIC_API(JSString *) +JS_DecompileFunction(JSContext *cx, JSFunction *fun, uintN indent); + +extern JS_PUBLIC_API(JSString *) +JS_DecompileFunctionBody(JSContext *cx, JSFunction *fun, uintN indent); + +/* + * NB: JS_ExecuteScript, JS_ExecuteScriptPart, and the JS_Evaluate*Script* + * quadruplets all use the obj parameter as the initial scope chain header, + * the 'this' keyword value, and the variables object (ECMA parlance for where + * 'var' and 'function' bind names) of the execution context for script. + * + * Using obj as the variables object is problematic if obj's parent (which is + * the scope chain link; see JS_SetParent and JS_NewObject) is not null: in + * this case, variables created by 'var x = 0', e.g., go in obj, but variables + * created by assignment to an unbound id, 'x = 0', go in the last object on + * the scope chain linked by parent. + * + * ECMA calls that last scoping object the "global object", but note that many + * embeddings have several such objects. ECMA requires that "global code" be + * executed with the variables object equal to this global object. But these + * JS API entry points provide freedom to execute code against a "sub-global", + * i.e., a parented or scoped object, in which case the variables object will + * differ from the last object on the scope chain, resulting in confusing and + * non-ECMA explicit vs. implicit variable creation. + * + * Caveat embedders: unless you already depend on this buggy variables object + * binding behavior, you should call JS_SetOptions(cx, JSOPTION_VAROBJFIX) or + * JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_VAROBJFIX) -- the latter if + * someone may have set other options on cx already -- for each context in the + * application, if you pass parented objects as the obj parameter, or may ever + * pass such objects in the future. + * + * Why a runtime option? The alternative is to add six or so new API entry + * points with signatures matching the following six, and that doesn't seem + * worth the code bloat cost. Such new entry points would probably have less + * obvious names, too, so would not tend to be used. The JS_SetOption call, + * OTOH, can be more easily hacked into existing code that does not depend on + * the bug; such code can continue to use the familiar JS_EvaluateScript, + * etc., entry points. + */ +extern JS_PUBLIC_API(JSBool) +JS_ExecuteScript(JSContext *cx, JSObject *obj, JSScript *script, jsval *rval); + +/* + * Execute either the function-defining prolog of a script, or the script's + * main body, but not both. + */ +typedef enum JSExecPart { JSEXEC_PROLOG, JSEXEC_MAIN } JSExecPart; + +extern JS_PUBLIC_API(JSBool) +JS_ExecuteScriptPart(JSContext *cx, JSObject *obj, JSScript *script, + JSExecPart part, jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_EvaluateScript(JSContext *cx, JSObject *obj, + const char *bytes, uintN length, + const char *filename, uintN lineno, + jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_EvaluateScriptForPrincipals(JSContext *cx, JSObject *obj, + JSPrincipals *principals, + const char *bytes, uintN length, + const char *filename, uintN lineno, + jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_EvaluateUCScript(JSContext *cx, JSObject *obj, + const jschar *chars, uintN length, + const char *filename, uintN lineno, + jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_EvaluateUCScriptForPrincipals(JSContext *cx, JSObject *obj, + JSPrincipals *principals, + const jschar *chars, uintN length, + const char *filename, uintN lineno, + jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_CallFunction(JSContext *cx, JSObject *obj, JSFunction *fun, uintN argc, + jsval *argv, jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_CallFunctionName(JSContext *cx, JSObject *obj, const char *name, uintN argc, + jsval *argv, jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_CallFunctionValue(JSContext *cx, JSObject *obj, jsval fval, uintN argc, + jsval *argv, jsval *rval); + +extern JS_PUBLIC_API(JSBranchCallback) +JS_SetBranchCallback(JSContext *cx, JSBranchCallback cb); + +extern JS_PUBLIC_API(JSBool) +JS_IsRunning(JSContext *cx); + +extern JS_PUBLIC_API(JSBool) +JS_IsConstructing(JSContext *cx); + +/* + * Returns true if a script is executing and its current bytecode is a set + * (assignment) operation, even if there are native (no script) stack frames + * between the script and the caller to JS_IsAssigning. + */ +extern JS_FRIEND_API(JSBool) +JS_IsAssigning(JSContext *cx); + +/* + * Set the second return value, which should be a string or int jsval that + * identifies a property in the returned object, to form an ECMA reference + * type value (obj, id). Only native methods can return reference types, + * and if the returned value is used on the left-hand side of an assignment + * op, the identified property will be set. If the return value is in an + * r-value, the interpreter just gets obj[id]'s value. + */ +extern JS_PUBLIC_API(void) +JS_SetCallReturnValue2(JSContext *cx, jsval v); + +/* + * Saving and restoring frame chains. + * + * These two functions are used to set aside cx->fp while that frame is + * inactive. After a call to JS_SaveFrameChain, it looks as if there is no + * code running on cx. Before calling JS_RestoreFrameChain, cx's call stack + * must be balanced and all nested calls to JS_SaveFrameChain must have had + * matching JS_RestoreFrameChain calls. + * + * JS_SaveFrameChain deals with cx not having any code running on it. A null + * return does not signify an error and JS_RestoreFrameChain handles null + * frames. + */ +extern JS_PUBLIC_API(JSStackFrame *) +JS_SaveFrameChain(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_RestoreFrameChain(JSContext *cx, JSStackFrame *fp); + +/************************************************************************/ + +/* + * Strings. + * + * NB: JS_NewString takes ownership of bytes on success, avoiding a copy; but + * on error (signified by null return), it leaves bytes owned by the caller. + * So the caller must free bytes in the error case, if it has no use for them. + * In contrast, all the JS_New*StringCopy* functions do not take ownership of + * the character memory passed to them -- they copy it. + */ +extern JS_PUBLIC_API(JSString *) +JS_NewString(JSContext *cx, char *bytes, size_t length); + +extern JS_PUBLIC_API(JSString *) +JS_NewStringCopyN(JSContext *cx, const char *s, size_t n); + +extern JS_PUBLIC_API(JSString *) +JS_NewStringCopyZ(JSContext *cx, const char *s); + +extern JS_PUBLIC_API(JSString *) +JS_InternString(JSContext *cx, const char *s); + +extern JS_PUBLIC_API(JSString *) +JS_NewUCString(JSContext *cx, jschar *chars, size_t length); + +extern JS_PUBLIC_API(JSString *) +JS_NewUCStringCopyN(JSContext *cx, const jschar *s, size_t n); + +extern JS_PUBLIC_API(JSString *) +JS_NewUCStringCopyZ(JSContext *cx, const jschar *s); + +extern JS_PUBLIC_API(JSString *) +JS_InternUCStringN(JSContext *cx, const jschar *s, size_t length); + +extern JS_PUBLIC_API(JSString *) +JS_InternUCString(JSContext *cx, const jschar *s); + +extern JS_PUBLIC_API(char *) +JS_GetStringBytes(JSString *str); + +extern JS_PUBLIC_API(jschar *) +JS_GetStringChars(JSString *str); + +extern JS_PUBLIC_API(size_t) +JS_GetStringLength(JSString *str); + +extern JS_PUBLIC_API(intN) +JS_CompareStrings(JSString *str1, JSString *str2); + +/* + * Mutable string support. A string's characters are never mutable in this JS + * implementation, but a growable string has a buffer that can be reallocated, + * and a dependent string is a substring of another (growable, dependent, or + * immutable) string. The direct data members of the (opaque to API clients) + * JSString struct may be changed in a single-threaded way for growable and + * dependent strings. + * + * Therefore mutable strings cannot be used by more than one thread at a time. + * You may call JS_MakeStringImmutable to convert the string from a mutable + * (growable or dependent) string to an immutable (and therefore thread-safe) + * string. The engine takes care of converting growable and dependent strings + * to immutable for you if you store strings in multi-threaded objects using + * JS_SetProperty or kindred API entry points. + * + * If you store a JSString pointer in a native data structure that is (safely) + * accessible to multiple threads, you must call JS_MakeStringImmutable before + * retiring the store. + */ +extern JS_PUBLIC_API(JSString *) +JS_NewGrowableString(JSContext *cx, jschar *chars, size_t length); + +/* + * Create a dependent string, i.e., a string that owns no character storage, + * but that refers to a slice of another string's chars. Dependent strings + * are mutable by definition, so the thread safety comments above apply. + */ +extern JS_PUBLIC_API(JSString *) +JS_NewDependentString(JSContext *cx, JSString *str, size_t start, + size_t length); + +/* + * Concatenate two strings, resulting in a new growable string. If you create + * the left string and pass it to JS_ConcatStrings on a single thread, try to + * use JS_NewGrowableString to create the left string -- doing so helps Concat + * avoid allocating a new buffer for the result and copying left's chars into + * the new buffer. See above for thread safety comments. + */ +extern JS_PUBLIC_API(JSString *) +JS_ConcatStrings(JSContext *cx, JSString *left, JSString *right); + +/* + * Convert a dependent string into an independent one. This function does not + * change the string's mutability, so the thread safety comments above apply. + */ +extern JS_PUBLIC_API(const jschar *) +JS_UndependString(JSContext *cx, JSString *str); + +/* + * Convert a mutable string (either growable or dependent) into an immutable, + * thread-safe one. + */ +extern JS_PUBLIC_API(JSBool) +JS_MakeStringImmutable(JSContext *cx, JSString *str); + +/* + * Return JS_TRUE if C (char []) strings passed via the API and internally + * are UTF-8. The source must be compiled with JS_C_STRINGS_ARE_UTF8 defined + * to get UTF-8 support. + */ +JS_PUBLIC_API(JSBool) +JS_CStringsAreUTF8(); + +/* + * Character encoding support. + * + * For both JS_EncodeCharacters and JS_DecodeBytes, set *dstlenp to the size + * of the destination buffer before the call; on return, *dstlenp contains the + * number of bytes (JS_EncodeCharacters) or jschars (JS_DecodeBytes) actually + * stored. To determine the necessary destination buffer size, make a sizing + * call that passes NULL for dst. + * + * On errors, the functions report the error. In that case, *dstlenp contains + * the number of characters or bytes transferred so far. If cx is NULL, no + * error is reported on failure, and the functions simply return JS_FALSE. + * + * NB: Neither function stores an additional zero byte or jschar after the + * transcoded string. + * + * If the source has been compiled with the #define JS_C_STRINGS_ARE_UTF8 to + * enable UTF-8 interpretation of C char[] strings, then JS_EncodeCharacters + * encodes to UTF-8, and JS_DecodeBytes decodes from UTF-8, which may create + * addititional errors if the character sequence is malformed. If UTF-8 + * support is disabled, the functions deflate and inflate, respectively. + */ +JS_PUBLIC_API(JSBool) +JS_EncodeCharacters(JSContext *cx, const jschar *src, size_t srclen, char *dst, + size_t *dstlenp); + +JS_PUBLIC_API(JSBool) +JS_DecodeBytes(JSContext *cx, const char *src, size_t srclen, jschar *dst, + size_t *dstlenp); + +/************************************************************************/ + +/* + * Locale specific string conversion and error message callbacks. + */ +struct JSLocaleCallbacks { + JSLocaleToUpperCase localeToUpperCase; + JSLocaleToLowerCase localeToLowerCase; + JSLocaleCompare localeCompare; + JSLocaleToUnicode localeToUnicode; + JSErrorCallback localeGetErrorMessage; +}; + +/* + * Establish locale callbacks. The pointer must persist as long as the + * JSContext. Passing NULL restores the default behaviour. + */ +extern JS_PUBLIC_API(void) +JS_SetLocaleCallbacks(JSContext *cx, JSLocaleCallbacks *callbacks); + +/* + * Return the address of the current locale callbacks struct, which may + * be NULL. + */ +extern JS_PUBLIC_API(JSLocaleCallbacks *) +JS_GetLocaleCallbacks(JSContext *cx); + +/************************************************************************/ + +/* + * Error reporting. + */ + +/* + * Report an exception represented by the sprintf-like conversion of format + * and its arguments. This exception message string is passed to a pre-set + * JSErrorReporter function (set by JS_SetErrorReporter; see jspubtd.h for + * the JSErrorReporter typedef). + */ +extern JS_PUBLIC_API(void) +JS_ReportError(JSContext *cx, const char *format, ...); + +/* + * Use an errorNumber to retrieve the format string, args are char * + */ +extern JS_PUBLIC_API(void) +JS_ReportErrorNumber(JSContext *cx, JSErrorCallback errorCallback, + void *userRef, const uintN errorNumber, ...); + +/* + * Use an errorNumber to retrieve the format string, args are jschar * + */ +extern JS_PUBLIC_API(void) +JS_ReportErrorNumberUC(JSContext *cx, JSErrorCallback errorCallback, + void *userRef, const uintN errorNumber, ...); + +/* + * As above, but report a warning instead (JSREPORT_IS_WARNING(report.flags)). + * Return true if there was no error trying to issue the warning, and if the + * warning was not converted into an error due to the JSOPTION_WERROR option + * being set, false otherwise. + */ +extern JS_PUBLIC_API(JSBool) +JS_ReportWarning(JSContext *cx, const char *format, ...); + +extern JS_PUBLIC_API(JSBool) +JS_ReportErrorFlagsAndNumber(JSContext *cx, uintN flags, + JSErrorCallback errorCallback, void *userRef, + const uintN errorNumber, ...); + +extern JS_PUBLIC_API(JSBool) +JS_ReportErrorFlagsAndNumberUC(JSContext *cx, uintN flags, + JSErrorCallback errorCallback, void *userRef, + const uintN errorNumber, ...); + +/* + * Complain when out of memory. + */ +extern JS_PUBLIC_API(void) +JS_ReportOutOfMemory(JSContext *cx); + +struct JSErrorReport { + const char *filename; /* source file name, URL, etc., or null */ + uintN lineno; /* source line number */ + const char *linebuf; /* offending source line without final \n */ + const char *tokenptr; /* pointer to error token in linebuf */ + const jschar *uclinebuf; /* unicode (original) line buffer */ + const jschar *uctokenptr; /* unicode (original) token pointer */ + uintN flags; /* error/warning, etc. */ + uintN errorNumber; /* the error number, e.g. see js.msg */ + const jschar *ucmessage; /* the (default) error message */ + const jschar **messageArgs; /* arguments for the error message */ +}; + +/* + * JSErrorReport flag values. These may be freely composed. + */ +#define JSREPORT_ERROR 0x0 /* pseudo-flag for default case */ +#define JSREPORT_WARNING 0x1 /* reported via JS_ReportWarning */ +#define JSREPORT_EXCEPTION 0x2 /* exception was thrown */ +#define JSREPORT_STRICT 0x4 /* error or warning due to strict option */ + +/* + * If JSREPORT_EXCEPTION is set, then a JavaScript-catchable exception + * has been thrown for this runtime error, and the host should ignore it. + * Exception-aware hosts should also check for JS_IsExceptionPending if + * JS_ExecuteScript returns failure, and signal or propagate the exception, as + * appropriate. + */ +#define JSREPORT_IS_WARNING(flags) (((flags) & JSREPORT_WARNING) != 0) +#define JSREPORT_IS_EXCEPTION(flags) (((flags) & JSREPORT_EXCEPTION) != 0) +#define JSREPORT_IS_STRICT(flags) (((flags) & JSREPORT_STRICT) != 0) + +extern JS_PUBLIC_API(JSErrorReporter) +JS_SetErrorReporter(JSContext *cx, JSErrorReporter er); + +/************************************************************************/ + +/* + * Regular Expressions. + */ +#define JSREG_FOLD 0x01 /* fold uppercase to lowercase */ +#define JSREG_GLOB 0x02 /* global exec, creates array of matches */ +#define JSREG_MULTILINE 0x04 /* treat ^ and $ as begin and end of line */ + +extern JS_PUBLIC_API(JSObject *) +JS_NewRegExpObject(JSContext *cx, char *bytes, size_t length, uintN flags); + +extern JS_PUBLIC_API(JSObject *) +JS_NewUCRegExpObject(JSContext *cx, jschar *chars, size_t length, uintN flags); + +extern JS_PUBLIC_API(void) +JS_SetRegExpInput(JSContext *cx, JSString *input, JSBool multiline); + +extern JS_PUBLIC_API(void) +JS_ClearRegExpStatics(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_ClearRegExpRoots(JSContext *cx); + +/* TODO: compile, exec, get/set other statics... */ + +/************************************************************************/ + +extern JS_PUBLIC_API(JSBool) +JS_IsExceptionPending(JSContext *cx); + +extern JS_PUBLIC_API(JSBool) +JS_GetPendingException(JSContext *cx, jsval *vp); + +extern JS_PUBLIC_API(void) +JS_SetPendingException(JSContext *cx, jsval v); + +extern JS_PUBLIC_API(void) +JS_ClearPendingException(JSContext *cx); + +extern JS_PUBLIC_API(JSBool) +JS_ReportPendingException(JSContext *cx); + +/* + * Save the current exception state. This takes a snapshot of cx's current + * exception state without making any change to that state. + * + * The returned state pointer MUST be passed later to JS_RestoreExceptionState + * (to restore that saved state, overriding any more recent state) or else to + * JS_DropExceptionState (to free the state struct in case it is not correct + * or desirable to restore it). Both Restore and Drop free the state struct, + * so callers must stop using the pointer returned from Save after calling the + * Release or Drop API. + */ +extern JS_PUBLIC_API(JSExceptionState *) +JS_SaveExceptionState(JSContext *cx); + +extern JS_PUBLIC_API(void) +JS_RestoreExceptionState(JSContext *cx, JSExceptionState *state); + +extern JS_PUBLIC_API(void) +JS_DropExceptionState(JSContext *cx, JSExceptionState *state); + +/* + * If the given value is an exception object that originated from an error, + * the exception will contain an error report struct, and this API will return + * the address of that struct. Otherwise, it returns NULL. The lifetime of + * the error report struct that might be returned is the same as the lifetime + * of the exception object. + */ +extern JS_PUBLIC_API(JSErrorReport *) +JS_ErrorFromException(JSContext *cx, jsval v); + +/* + * Given a reported error's message and JSErrorReport struct pointer, throw + * the corresponding exception on cx. + */ +extern JS_PUBLIC_API(JSBool) +JS_ThrowReportedError(JSContext *cx, const char *message, + JSErrorReport *reportp); + +#ifdef JS_THREADSAFE + +/* + * Associate the current thread with the given context. This is done + * implicitly by JS_NewContext. + * + * Returns the old thread id for this context, which should be treated as + * an opaque value. This value is provided for comparison to 0, which + * indicates that ClearContextThread has been called on this context + * since the last SetContextThread, or non-0, which indicates the opposite. + */ +extern JS_PUBLIC_API(jsword) +JS_GetContextThread(JSContext *cx); + +extern JS_PUBLIC_API(jsword) +JS_SetContextThread(JSContext *cx); + +extern JS_PUBLIC_API(jsword) +JS_ClearContextThread(JSContext *cx); + +#endif /* JS_THREADSAFE */ + +/************************************************************************/ + +JS_END_EXTERN_C + +#endif /* jsapi_h___ */ diff --git a/js32/jscompat.h b/js32/jscompat.h new file mode 100644 index 00000000..80d86056 --- /dev/null +++ b/js32/jscompat.h @@ -0,0 +1,57 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* -*- Mode: C; tab-width: 8 -*- + * Copyright (C) 1996-1999 Netscape Communications Corporation, All Rights Reserved. + */ +#ifndef jscompat_h___ +#define jscompat_h___ +/* + * Compatibility glue for various NSPR versions. We must always define int8, + * int16, jsword, and so on to minimize differences with js/ref, no matter what + * the NSPR typedef names may be. + */ +#include "jstypes.h" +#include "jslong.h" + +typedef JSIntn intN; +typedef JSUintn uintN; +typedef JSUword jsuword; +typedef JSWord jsword; +typedef float float32; +#define allocPriv allocPool +#endif /* jscompat_h___ */ diff --git a/js32/jsconfig.h b/js32/jsconfig.h new file mode 100644 index 00000000..f0c05632 --- /dev/null +++ b/js32/jsconfig.h @@ -0,0 +1,208 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* + * JS configuration macros. + */ +#ifndef JS_VERSION +#define JS_VERSION 170 +#endif + +/* + * Compile-time JS version configuration. The JS version numbers lie on the + * number line like so: + * + * 1.0 1.1 1.2 1.3 1.4 ECMAv3 1.5 1.6 + * ^ ^ + * | | + * basis for ECMAv1 close to ECMAv2 + * + * where ECMAv3 stands for ECMA-262 Edition 3. See the runtime version enum + * JSVersion in jspubtd.h. Code in the engine can therefore count on version + * <= JSVERSION_1_4 to mean "before the Third Edition of ECMA-262" and version + * > JSVERSION_1_4 to mean "at or after the Third Edition". + * + * In the (likely?) event that SpiderMonkey grows to implement JavaScript 2.0, + * or ECMA-262 Edition 4 (JS2 without certain extensions), the version number + * to use would be near 200, or greater. + * + * The JS_VERSION_ECMA_3 version is the minimal configuration conforming to + * the ECMA-262 Edition 3 specification. Use it for minimal embeddings, where + * you're sure you don't need any of the extensions disabled in this version. + * In order to facilitate testing, JS_HAS_OBJ_PROTO_PROP is defined as part of + * the JS_VERSION_ECMA_3_TEST version. + * + * To keep things sane in the modern age, where we need exceptions in order to + * implement, e.g., iterators and generators, we are dropping support for all + * versions <= 1.4. + */ +#define JS_VERSION_ECMA_3 148 +#define JS_VERSION_ECMA_3_TEST 149 + +#if JS_VERSION == JS_VERSION_ECMA_3 || \ + JS_VERSION == JS_VERSION_ECMA_3_TEST + +#define JS_HAS_STR_HTML_HELPERS 0 /* has str.anchor, str.bold, etc. */ +#define JS_HAS_PERL_SUBSTR 0 /* has str.substr */ +#if JS_VERSION == JS_VERSION_ECMA_3_TEST +#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ +#else +#define JS_HAS_OBJ_PROTO_PROP 0 /* has o.__proto__ etc. */ +#endif +#define JS_HAS_OBJ_WATCHPOINT 0 /* has o.watch and o.unwatch */ +#define JS_HAS_EXPORT_IMPORT 0 /* has export fun; import obj.fun */ +#define JS_HAS_EVAL_THIS_SCOPE 0 /* Math.eval is same as with (Math) */ +#define JS_HAS_SHARP_VARS 0 /* has #n=, #n# for object literals */ +#define JS_HAS_SCRIPT_OBJECT 0 /* has (new Script("x++")).exec() */ +#define JS_HAS_XDR 0 /* has XDR API and internal support */ +#define JS_HAS_XDR_FREEZE_THAW 0 /* has XDR freeze/thaw script methods */ +#define JS_HAS_TOSOURCE 0 /* has Object/Array toSource method */ +#define JS_HAS_DEBUGGER_KEYWORD 0 /* has hook for debugger keyword */ +#define JS_HAS_CATCH_GUARD 0 /* has exception handling catch guard */ +#define JS_HAS_SPARSE_ARRAYS 0 /* array methods preserve empty elems */ +#define JS_HAS_GETTER_SETTER 0 /* has JS2 getter/setter functions */ +#define JS_HAS_UNEVAL 0 /* has uneval() top-level function */ +#define JS_HAS_CONST 0 /* has JS2 const as alternative var */ +#define JS_HAS_FUN_EXPR_STMT 0 /* has function expression statement */ +#define JS_HAS_LVALUE_RETURN 1 /* has o.item(i) = j; for native item */ +#define JS_HAS_NO_SUCH_METHOD 0 /* has o.__noSuchMethod__ handler */ +#define JS_HAS_XML_SUPPORT 0 /* has ECMAScript for XML support */ +#define JS_HAS_ARRAY_EXTRAS 0 /* has indexOf and Lispy extras */ +#define JS_HAS_GENERATORS 0 /* has yield in generator function */ +#define JS_HAS_BLOCK_SCOPE 0 /* has block scope via let/arraycomp */ +#define JS_HAS_DESTRUCTURING 0 /* has [a,b] = ... or {p:a,q:b} = ... */ + +#elif JS_VERSION < 150 + +#error "unsupported JS_VERSION" + +#elif JS_VERSION == 150 + +#define JS_HAS_STR_HTML_HELPERS 1 /* has str.anchor, str.bold, etc. */ +#define JS_HAS_PERL_SUBSTR 1 /* has str.substr */ +#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ +#define JS_HAS_OBJ_WATCHPOINT 1 /* has o.watch and o.unwatch */ +#define JS_HAS_EXPORT_IMPORT 1 /* has export fun; import obj.fun */ +#define JS_HAS_EVAL_THIS_SCOPE 1 /* Math.eval is same as with (Math) */ +#define JS_HAS_SHARP_VARS 1 /* has #n=, #n# for object literals */ +#define JS_HAS_SCRIPT_OBJECT 1 /* has (new Script("x++")).exec() */ +#define JS_HAS_XDR 1 /* has XDR API and internal support */ +#define JS_HAS_XDR_FREEZE_THAW 0 /* has XDR freeze/thaw script methods */ +#define JS_HAS_TOSOURCE 1 /* has Object/Array toSource method */ +#define JS_HAS_DEBUGGER_KEYWORD 1 /* has hook for debugger keyword */ +#define JS_HAS_CATCH_GUARD 1 /* has exception handling catch guard */ +#define JS_HAS_SPARSE_ARRAYS 0 /* array methods preserve empty elems */ +#define JS_HAS_GETTER_SETTER 1 /* has JS2 getter/setter functions */ +#define JS_HAS_UNEVAL 1 /* has uneval() top-level function */ +#define JS_HAS_CONST 1 /* has JS2 const as alternative var */ +#define JS_HAS_FUN_EXPR_STMT 1 /* has function expression statement */ +#define JS_HAS_LVALUE_RETURN 1 /* has o.item(i) = j; for native item */ +#define JS_HAS_NO_SUCH_METHOD 1 /* has o.__noSuchMethod__ handler */ +#define JS_HAS_XML_SUPPORT 0 /* has ECMAScript for XML support */ +#define JS_HAS_ARRAY_EXTRAS 0 /* has indexOf and Lispy extras */ +#define JS_HAS_GENERATORS 0 /* has yield in generator function */ +#define JS_HAS_BLOCK_SCOPE 0 /* has block scope via let/arraycomp */ +#define JS_HAS_DESTRUCTURING 0 /* has [a,b] = ... or {p:a,q:b} = ... */ + +#elif JS_VERSION == 160 + +#define JS_HAS_STR_HTML_HELPERS 1 /* has str.anchor, str.bold, etc. */ +#define JS_HAS_PERL_SUBSTR 1 /* has str.substr */ +#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ +#define JS_HAS_OBJ_WATCHPOINT 1 /* has o.watch and o.unwatch */ +#define JS_HAS_EXPORT_IMPORT 1 /* has export fun; import obj.fun */ +#define JS_HAS_EVAL_THIS_SCOPE 1 /* Math.eval is same as with (Math) */ +#define JS_HAS_SHARP_VARS 1 /* has #n=, #n# for object literals */ +#define JS_HAS_SCRIPT_OBJECT 1 /* has (new Script("x++")).exec() */ +#define JS_HAS_XDR 1 /* has XDR API and internal support */ +#define JS_HAS_XDR_FREEZE_THAW 0 /* has XDR freeze/thaw script methods */ +#define JS_HAS_TOSOURCE 1 /* has Object/Array toSource method */ +#define JS_HAS_DEBUGGER_KEYWORD 1 /* has hook for debugger keyword */ +#define JS_HAS_CATCH_GUARD 1 /* has exception handling catch guard */ +#define JS_HAS_SPARSE_ARRAYS 0 /* array methods preserve empty elems */ +#define JS_HAS_GETTER_SETTER 1 /* has JS2 getter/setter functions */ +#define JS_HAS_UNEVAL 1 /* has uneval() top-level function */ +#define JS_HAS_CONST 1 /* has JS2 const as alternative var */ +#define JS_HAS_FUN_EXPR_STMT 1 /* has function expression statement */ +#define JS_HAS_LVALUE_RETURN 1 /* has o.item(i) = j; for native item */ +#define JS_HAS_NO_SUCH_METHOD 1 /* has o.__noSuchMethod__ handler */ +#define JS_HAS_XML_SUPPORT 1 /* has ECMAScript for XML support */ +#define JS_HAS_ARRAY_EXTRAS 1 /* has indexOf and Lispy extras */ +#define JS_HAS_GENERATORS 0 /* has yield in generator function */ +#define JS_HAS_BLOCK_SCOPE 0 /* has block scope via let/arraycomp */ +#define JS_HAS_DESTRUCTURING 0 /* has [a,b] = ... or {p:a,q:b} = ... */ + +#elif JS_VERSION == 170 + +#define JS_HAS_STR_HTML_HELPERS 1 /* has str.anchor, str.bold, etc. */ +#define JS_HAS_PERL_SUBSTR 1 /* has str.substr */ +#define JS_HAS_OBJ_PROTO_PROP 1 /* has o.__proto__ etc. */ +#define JS_HAS_OBJ_WATCHPOINT 1 /* has o.watch and o.unwatch */ +#define JS_HAS_EXPORT_IMPORT 1 /* has export fun; import obj.fun */ +#define JS_HAS_EVAL_THIS_SCOPE 1 /* Math.eval is same as with (Math) */ +#define JS_HAS_SHARP_VARS 1 /* has #n=, #n# for object literals */ +#define JS_HAS_SCRIPT_OBJECT 1 /* has (new Script("x++")).exec() */ +#define JS_HAS_XDR 1 /* has XDR API and internal support */ +#define JS_HAS_XDR_FREEZE_THAW 0 /* has XDR freeze/thaw script methods */ +#define JS_HAS_TOSOURCE 1 /* has Object/Array toSource method */ +#define JS_HAS_DEBUGGER_KEYWORD 1 /* has hook for debugger keyword */ +#define JS_HAS_CATCH_GUARD 1 /* has exception handling catch guard */ +#define JS_HAS_SPARSE_ARRAYS 0 /* array methods preserve empty elems */ +#define JS_HAS_GETTER_SETTER 1 /* has JS2 getter/setter functions */ +#define JS_HAS_UNEVAL 1 /* has uneval() top-level function */ +#define JS_HAS_CONST 1 /* has JS2 const as alternative var */ +#define JS_HAS_FUN_EXPR_STMT 1 /* has function expression statement */ +#define JS_HAS_LVALUE_RETURN 1 /* has o.item(i) = j; for native item */ +#define JS_HAS_NO_SUCH_METHOD 1 /* has o.__noSuchMethod__ handler */ +#define JS_HAS_XML_SUPPORT 1 /* has ECMAScript for XML support */ +#define JS_HAS_ARRAY_EXTRAS 1 /* has indexOf and Lispy extras */ +#define JS_HAS_GENERATORS 1 /* has yield in generator function */ +#define JS_HAS_BLOCK_SCOPE 1 /* has block scope via let/arraycomp */ +#define JS_HAS_DESTRUCTURING 1 /* has [a,b] = ... or {p:a,q:b} = ... */ + +#else + +#error "unknown JS_VERSION" + +#endif + +/* Features that are present in all versions. */ +#define JS_HAS_RESERVED_JAVA_KEYWORDS 1 +#define JS_HAS_RESERVED_ECMA_KEYWORDS 1 + diff --git a/js32/jscpucfg.h b/js32/jscpucfg.h new file mode 100644 index 00000000..63ef932a --- /dev/null +++ b/js32/jscpucfg.h @@ -0,0 +1,212 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef js_cpucfg___ +#define js_cpucfg___ + +#include "jsosdep.h" + +#if defined(XP_WIN) || defined(XP_OS2) || defined(WINCE) + +#if defined(_WIN64) + +#if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) +#define IS_LITTLE_ENDIAN 1 +#undef IS_BIG_ENDIAN + +#define JS_BYTES_PER_BYTE 1L +#define JS_BYTES_PER_SHORT 2L +#define JS_BYTES_PER_INT 4L +#define JS_BYTES_PER_INT64 8L +#define JS_BYTES_PER_LONG 4L +#define JS_BYTES_PER_FLOAT 4L +#define JS_BYTES_PER_DOUBLE 8L +#define JS_BYTES_PER_WORD 8L +#define JS_BYTES_PER_DWORD 8L + +#define JS_BITS_PER_BYTE 8L +#define JS_BITS_PER_SHORT 16L +#define JS_BITS_PER_INT 32L +#define JS_BITS_PER_INT64 64L +#define JS_BITS_PER_LONG 32L +#define JS_BITS_PER_FLOAT 32L +#define JS_BITS_PER_DOUBLE 64L +#define JS_BITS_PER_WORD 64L + +#define JS_BITS_PER_BYTE_LOG2 3L +#define JS_BITS_PER_SHORT_LOG2 4L +#define JS_BITS_PER_INT_LOG2 5L +#define JS_BITS_PER_INT64_LOG2 6L +#define JS_BITS_PER_LONG_LOG2 5L +#define JS_BITS_PER_FLOAT_LOG2 5L +#define JS_BITS_PER_DOUBLE_LOG2 6L +#define JS_BITS_PER_WORD_LOG2 6L + +#define JS_ALIGN_OF_SHORT 2L +#define JS_ALIGN_OF_INT 4L +#define JS_ALIGN_OF_LONG 4L +#define JS_ALIGN_OF_INT64 8L +#define JS_ALIGN_OF_FLOAT 4L +#define JS_ALIGN_OF_DOUBLE 8L +#define JS_ALIGN_OF_POINTER 8L +#define JS_ALIGN_OF_WORD 8L + +#define JS_BYTES_PER_WORD_LOG2 3L +#define JS_BYTES_PER_DWORD_LOG2 3L +#define PR_WORDS_PER_DWORD_LOG2 0L +#else /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ +#error "CPU type is unknown" +#endif /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ + +#elif defined(_WIN32) || defined(XP_OS2) || defined(WINCE) + +#ifdef __WATCOMC__ +#define HAVE_VA_LIST_AS_ARRAY +#endif + +#define IS_LITTLE_ENDIAN 1 +#undef IS_BIG_ENDIAN + +#define JS_BYTES_PER_BYTE 1L +#define JS_BYTES_PER_SHORT 2L +#define JS_BYTES_PER_INT 4L +#define JS_BYTES_PER_INT64 8L +#define JS_BYTES_PER_LONG 4L +#define JS_BYTES_PER_FLOAT 4L +#define JS_BYTES_PER_DOUBLE 8L +#define JS_BYTES_PER_WORD 4L +#define JS_BYTES_PER_DWORD 8L + +#define JS_BITS_PER_BYTE 8L +#define JS_BITS_PER_SHORT 16L +#define JS_BITS_PER_INT 32L +#define JS_BITS_PER_INT64 64L +#define JS_BITS_PER_LONG 32L +#define JS_BITS_PER_FLOAT 32L +#define JS_BITS_PER_DOUBLE 64L +#define JS_BITS_PER_WORD 32L + +#define JS_BITS_PER_BYTE_LOG2 3L +#define JS_BITS_PER_SHORT_LOG2 4L +#define JS_BITS_PER_INT_LOG2 5L +#define JS_BITS_PER_INT64_LOG2 6L +#define JS_BITS_PER_LONG_LOG2 5L +#define JS_BITS_PER_FLOAT_LOG2 5L +#define JS_BITS_PER_DOUBLE_LOG2 6L +#define JS_BITS_PER_WORD_LOG2 5L + +#define JS_ALIGN_OF_SHORT 2L +#define JS_ALIGN_OF_INT 4L +#define JS_ALIGN_OF_LONG 4L +#define JS_ALIGN_OF_INT64 8L +#define JS_ALIGN_OF_FLOAT 4L +#define JS_ALIGN_OF_DOUBLE 4L +#define JS_ALIGN_OF_POINTER 4L +#define JS_ALIGN_OF_WORD 4L + +#define JS_BYTES_PER_WORD_LOG2 2L +#define JS_BYTES_PER_DWORD_LOG2 3L +#define PR_WORDS_PER_DWORD_LOG2 1L +#endif /* _WIN32 || XP_OS2 || WINCE*/ + +#if defined(_WINDOWS) && !defined(_WIN32) /* WIN16 */ + +#define IS_LITTLE_ENDIAN 1 +#undef IS_BIG_ENDIAN + +#define JS_BYTES_PER_BYTE 1L +#define JS_BYTES_PER_SHORT 2L +#define JS_BYTES_PER_INT 2L +#define JS_BYTES_PER_INT64 8L +#define JS_BYTES_PER_LONG 4L +#define JS_BYTES_PER_FLOAT 4L +#define JS_BYTES_PER_DOUBLE 8L +#define JS_BYTES_PER_WORD 4L +#define JS_BYTES_PER_DWORD 8L + +#define JS_BITS_PER_BYTE 8L +#define JS_BITS_PER_SHORT 16L +#define JS_BITS_PER_INT 16L +#define JS_BITS_PER_INT64 64L +#define JS_BITS_PER_LONG 32L +#define JS_BITS_PER_FLOAT 32L +#define JS_BITS_PER_DOUBLE 64L +#define JS_BITS_PER_WORD 32L + +#define JS_BITS_PER_BYTE_LOG2 3L +#define JS_BITS_PER_SHORT_LOG2 4L +#define JS_BITS_PER_INT_LOG2 4L +#define JS_BITS_PER_INT64_LOG2 6L +#define JS_BITS_PER_LONG_LOG2 5L +#define JS_BITS_PER_FLOAT_LOG2 5L +#define JS_BITS_PER_DOUBLE_LOG2 6L +#define JS_BITS_PER_WORD_LOG2 5L + +#define JS_ALIGN_OF_SHORT 2L +#define JS_ALIGN_OF_INT 2L +#define JS_ALIGN_OF_LONG 2L +#define JS_ALIGN_OF_INT64 2L +#define JS_ALIGN_OF_FLOAT 2L +#define JS_ALIGN_OF_DOUBLE 2L +#define JS_ALIGN_OF_POINTER 2L +#define JS_ALIGN_OF_WORD 2L + +#define JS_BYTES_PER_WORD_LOG2 2L +#define JS_BYTES_PER_DWORD_LOG2 3L +#define PR_WORDS_PER_DWORD_LOG2 1L + +#endif /* defined(_WINDOWS) && !defined(_WIN32) */ + +#elif defined(XP_UNIX) || defined(XP_BEOS) + +#error "This file is supposed to be auto-generated on UNIX platforms, but the" +#error "static version for Mac and Windows platforms is being used." +#error "Something's probably wrong with paths/headers/dependencies/Makefiles." + +#else + +#error "Must define one of XP_BEOS, XP_OS2, XP_WIN, or XP_UNIX" + +#endif + +#ifndef JS_STACK_GROWTH_DIRECTION +#define JS_STACK_GROWTH_DIRECTION (-1) +#endif + +#endif /* js_cpucfg___ */ diff --git a/js32/jsdbgapi.h b/js32/jsdbgapi.h new file mode 100644 index 00000000..d2e1f1c6 --- /dev/null +++ b/js32/jsdbgapi.h @@ -0,0 +1,406 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef jsdbgapi_h___ +#define jsdbgapi_h___ +/* + * JS debugger API. + */ +#include "jsapi.h" +#include "jsopcode.h" +#include "jsprvtd.h" + +JS_BEGIN_EXTERN_C + +extern void +js_PatchOpcode(JSContext *cx, JSScript *script, jsbytecode *pc, JSOp op); + +extern JS_PUBLIC_API(JSBool) +JS_SetTrap(JSContext *cx, JSScript *script, jsbytecode *pc, + JSTrapHandler handler, void *closure); + +extern JS_PUBLIC_API(JSOp) +JS_GetTrapOpcode(JSContext *cx, JSScript *script, jsbytecode *pc); + +extern JS_PUBLIC_API(void) +JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, + JSTrapHandler *handlerp, void **closurep); + +extern JS_PUBLIC_API(void) +JS_ClearScriptTraps(JSContext *cx, JSScript *script); + +extern JS_PUBLIC_API(void) +JS_ClearAllTraps(JSContext *cx); + +extern JS_PUBLIC_API(JSTrapStatus) +JS_HandleTrap(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_SetInterrupt(JSRuntime *rt, JSTrapHandler handler, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_ClearInterrupt(JSRuntime *rt, JSTrapHandler *handlerp, void **closurep); + +/************************************************************************/ + +extern JS_PUBLIC_API(JSBool) +JS_SetWatchPoint(JSContext *cx, JSObject *obj, jsval id, + JSWatchPointHandler handler, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_ClearWatchPoint(JSContext *cx, JSObject *obj, jsval id, + JSWatchPointHandler *handlerp, void **closurep); + +extern JS_PUBLIC_API(JSBool) +JS_ClearWatchPointsForObject(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(JSBool) +JS_ClearAllWatchPoints(JSContext *cx); + +#ifdef JS_HAS_OBJ_WATCHPOINT +/* + * Hide these non-API function prototypes by testing whether the internal + * header file "jsconfig.h" has been included. + */ +extern void +js_MarkWatchPoints(JSContext *cx); + +extern JSScopeProperty * +js_FindWatchPoint(JSRuntime *rt, JSScope *scope, jsid id); + +extern JSPropertyOp +js_GetWatchedSetter(JSRuntime *rt, JSScope *scope, + const JSScopeProperty *sprop); + +extern JSBool JS_DLL_CALLBACK +js_watch_set(JSContext *cx, JSObject *obj, jsval id, jsval *vp); + +extern JSBool JS_DLL_CALLBACK +js_watch_set_wrapper(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, + jsval *rval); + +extern JSPropertyOp +js_WrapWatchedSetter(JSContext *cx, jsid id, uintN attrs, JSPropertyOp setter); + +#endif /* JS_HAS_OBJ_WATCHPOINT */ + +/************************************************************************/ + +extern JS_PUBLIC_API(uintN) +JS_PCToLineNumber(JSContext *cx, JSScript *script, jsbytecode *pc); + +extern JS_PUBLIC_API(jsbytecode *) +JS_LineNumberToPC(JSContext *cx, JSScript *script, uintN lineno); + +extern JS_PUBLIC_API(JSScript *) +JS_GetFunctionScript(JSContext *cx, JSFunction *fun); + +extern JS_PUBLIC_API(JSNative) +JS_GetFunctionNative(JSContext *cx, JSFunction *fun); + +extern JS_PUBLIC_API(JSPrincipals *) +JS_GetScriptPrincipals(JSContext *cx, JSScript *script); + +/* + * Stack Frame Iterator + * + * Used to iterate through the JS stack frames to extract + * information from the frames. + */ + +extern JS_PUBLIC_API(JSStackFrame *) +JS_FrameIterator(JSContext *cx, JSStackFrame **iteratorp); + +extern JS_PUBLIC_API(JSScript *) +JS_GetFrameScript(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(jsbytecode *) +JS_GetFramePC(JSContext *cx, JSStackFrame *fp); + +/* + * Get the closest scripted frame below fp. If fp is null, start from cx->fp. + */ +extern JS_PUBLIC_API(JSStackFrame *) +JS_GetScriptedCaller(JSContext *cx, JSStackFrame *fp); + +/* + * Return a weak reference to fp's principals. A null return does not denote + * an error, it means there are no principals. + */ +extern JS_PUBLIC_API(JSPrincipals *) +JS_StackFramePrincipals(JSContext *cx, JSStackFrame *fp); + +/* + * This API is like JS_StackFramePrincipals(cx, caller), except that if + * cx->runtime->findObjectPrincipals is non-null, it returns the weaker of + * the caller's principals and the object principals of fp's callee function + * object (fp->argv[-2]), which is eval, Function, or a similar eval-like + * method. The caller parameter should be JS_GetScriptedCaller(cx, fp). + * + * All eval-like methods must use JS_EvalFramePrincipals to acquire a weak + * reference to the correct principals for the eval call to be secure, given + * an embedding that calls JS_SetObjectPrincipalsFinder (see jsapi.h). + */ +extern JS_PUBLIC_API(JSPrincipals *) +JS_EvalFramePrincipals(JSContext *cx, JSStackFrame *fp, JSStackFrame *caller); + +extern JS_PUBLIC_API(void *) +JS_GetFrameAnnotation(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(void) +JS_SetFrameAnnotation(JSContext *cx, JSStackFrame *fp, void *annotation); + +extern JS_PUBLIC_API(void *) +JS_GetFramePrincipalArray(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSBool) +JS_IsNativeFrame(JSContext *cx, JSStackFrame *fp); + +/* this is deprecated, use JS_GetFrameScopeChain instead */ +extern JS_PUBLIC_API(JSObject *) +JS_GetFrameObject(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSObject *) +JS_GetFrameScopeChain(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSObject *) +JS_GetFrameCallObject(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSObject *) +JS_GetFrameThis(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSFunction *) +JS_GetFrameFunction(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSObject *) +JS_GetFrameFunctionObject(JSContext *cx, JSStackFrame *fp); + +/* XXXrginda Initially published with typo */ +#define JS_IsContructorFrame JS_IsConstructorFrame +extern JS_PUBLIC_API(JSBool) +JS_IsConstructorFrame(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(JSBool) +JS_IsDebuggerFrame(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(jsval) +JS_GetFrameReturnValue(JSContext *cx, JSStackFrame *fp); + +extern JS_PUBLIC_API(void) +JS_SetFrameReturnValue(JSContext *cx, JSStackFrame *fp, jsval rval); + +/** + * Return fp's callee function object (fp->argv[-2]) if it has one. + */ +extern JS_PUBLIC_API(JSObject *) +JS_GetFrameCalleeObject(JSContext *cx, JSStackFrame *fp); + +/************************************************************************/ + +extern JS_PUBLIC_API(const char *) +JS_GetScriptFilename(JSContext *cx, JSScript *script); + +extern JS_PUBLIC_API(uintN) +JS_GetScriptBaseLineNumber(JSContext *cx, JSScript *script); + +extern JS_PUBLIC_API(uintN) +JS_GetScriptLineExtent(JSContext *cx, JSScript *script); + +extern JS_PUBLIC_API(JSVersion) +JS_GetScriptVersion(JSContext *cx, JSScript *script); + +/************************************************************************/ + +/* + * Hook setters for script creation and destruction, see jsprvtd.h for the + * typedefs. These macros provide binary compatibility and newer, shorter + * synonyms. + */ +#define JS_SetNewScriptHook JS_SetNewScriptHookProc +#define JS_SetDestroyScriptHook JS_SetDestroyScriptHookProc + +extern JS_PUBLIC_API(void) +JS_SetNewScriptHook(JSRuntime *rt, JSNewScriptHook hook, void *callerdata); + +extern JS_PUBLIC_API(void) +JS_SetDestroyScriptHook(JSRuntime *rt, JSDestroyScriptHook hook, + void *callerdata); + +/************************************************************************/ + +extern JS_PUBLIC_API(JSBool) +JS_EvaluateUCInStackFrame(JSContext *cx, JSStackFrame *fp, + const jschar *chars, uintN length, + const char *filename, uintN lineno, + jsval *rval); + +extern JS_PUBLIC_API(JSBool) +JS_EvaluateInStackFrame(JSContext *cx, JSStackFrame *fp, + const char *bytes, uintN length, + const char *filename, uintN lineno, + jsval *rval); + +/************************************************************************/ + +typedef struct JSPropertyDesc { + jsval id; /* primary id, a string or int */ + jsval value; /* property value */ + uint8 flags; /* flags, see below */ + uint8 spare; /* unused */ + uint16 slot; /* argument/variable slot */ + jsval alias; /* alias id if JSPD_ALIAS flag */ +} JSPropertyDesc; + +#define JSPD_ENUMERATE 0x01 /* visible to for/in loop */ +#define JSPD_READONLY 0x02 /* assignment is error */ +#define JSPD_PERMANENT 0x04 /* property cannot be deleted */ +#define JSPD_ALIAS 0x08 /* property has an alias id */ +#define JSPD_ARGUMENT 0x10 /* argument to function */ +#define JSPD_VARIABLE 0x20 /* local variable in function */ +#define JSPD_EXCEPTION 0x40 /* exception occurred fetching the property, */ + /* value is exception */ +#define JSPD_ERROR 0x80 /* native getter returned JS_FALSE without */ + /* throwing an exception */ + +typedef struct JSPropertyDescArray { + uint32 length; /* number of elements in array */ + JSPropertyDesc *array; /* alloc'd by Get, freed by Put */ +} JSPropertyDescArray; + +extern JS_PUBLIC_API(JSScopeProperty *) +JS_PropertyIterator(JSObject *obj, JSScopeProperty **iteratorp); + +extern JS_PUBLIC_API(JSBool) +JS_GetPropertyDesc(JSContext *cx, JSObject *obj, JSScopeProperty *sprop, + JSPropertyDesc *pd); + +extern JS_PUBLIC_API(JSBool) +JS_GetPropertyDescArray(JSContext *cx, JSObject *obj, JSPropertyDescArray *pda); + +extern JS_PUBLIC_API(void) +JS_PutPropertyDescArray(JSContext *cx, JSPropertyDescArray *pda); + +/************************************************************************/ + +extern JS_PUBLIC_API(JSBool) +JS_SetDebuggerHandler(JSRuntime *rt, JSTrapHandler handler, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_SetSourceHandler(JSRuntime *rt, JSSourceHandler handler, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_SetExecuteHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_SetCallHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_SetObjectHook(JSRuntime *rt, JSObjectHook hook, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_SetThrowHook(JSRuntime *rt, JSTrapHandler hook, void *closure); + +extern JS_PUBLIC_API(JSBool) +JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); + +/************************************************************************/ + +extern JS_PUBLIC_API(size_t) +JS_GetObjectTotalSize(JSContext *cx, JSObject *obj); + +extern JS_PUBLIC_API(size_t) +JS_GetFunctionTotalSize(JSContext *cx, JSFunction *fun); + +extern JS_PUBLIC_API(size_t) +JS_GetScriptTotalSize(JSContext *cx, JSScript *script); + +/* + * Get the top-most running script on cx starting from fp, or from the top of + * cx's frame stack if fp is null, and return its script filename flags. If + * the script has a null filename member, return JSFILENAME_NULL. + */ +extern JS_PUBLIC_API(uint32) +JS_GetTopScriptFilenameFlags(JSContext *cx, JSStackFrame *fp); + +/* + * Get the script filename flags for the script. If the script doesn't have a + * filename, return JSFILENAME_NULL. + */ +extern JS_PUBLIC_API(uint32) +JS_GetScriptFilenameFlags(JSScript *script); + +/* + * Associate flags with a script filename prefix in rt, so that any subsequent + * script compilation will inherit those flags if the script's filename is the + * same as prefix, or if prefix is a substring of the script's filename. + * + * The API defines only one flag bit, JSFILENAME_SYSTEM, leaving the remaining + * 31 bits up to the API client to define. The union of all 32 bits must not + * be a legal combination, however, in order to preserve JSFILENAME_NULL as a + * unique value. API clients may depend on JSFILENAME_SYSTEM being a set bit + * in JSFILENAME_NULL -- a script with a null filename member is presumed to + * be a "system" script. + */ +extern JS_PUBLIC_API(JSBool) +JS_FlagScriptFilenamePrefix(JSRuntime *rt, const char *prefix, uint32 flags); + +#define JSFILENAME_NULL 0xffffffff /* null script filename */ +#define JSFILENAME_SYSTEM 0x00000001 /* "system" script, see below */ + +/* + * Return true if obj is a "system" object, that is, one flagged by a prior + * call to JS_FlagSystemObject(cx, obj). What "system" means is up to the API + * client, but it can be used to coordinate access control policies based on + * script filenames and their prefixes, using JS_FlagScriptFilenamePrefix and + * JS_GetTopScriptFilenameFlags. + */ +extern JS_PUBLIC_API(JSBool) +JS_IsSystemObject(JSContext *cx, JSObject *obj); + +/* + * Flag obj as a "system" object. The API client can flag system objects to + * optimize access control checks. The engine stores but does not interpret + * the per-object flag set by this call. + */ +extern JS_PUBLIC_API(void) +JS_FlagSystemObject(JSContext *cx, JSObject *obj); + +JS_END_EXTERN_C + +#endif /* jsdbgapi_h___ */ diff --git a/js32/jslong.h b/js32/jslong.h new file mode 100644 index 00000000..059cf00b --- /dev/null +++ b/js32/jslong.h @@ -0,0 +1,437 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* +** File: jslong.h +** Description: Portable access to 64 bit numerics +** +** Long-long (64-bit signed integer type) support. Some C compilers +** don't support 64 bit integers yet, so we use these macros to +** support both machines that do and don't. +**/ +#ifndef jslong_h___ +#define jslong_h___ + +#include "jstypes.h" + +JS_BEGIN_EXTERN_C + +/*********************************************************************** +** DEFINES: JSLL_MaxInt +** JSLL_MinInt +** JSLL_Zero +** DESCRIPTION: +** Various interesting constants and static variable +** initializer +***********************************************************************/ +#ifdef HAVE_WATCOM_BUG_2 +JSInt64 __pascal __loadds __export + JSLL_MaxInt(void); +JSInt64 __pascal __loadds __export + JSLL_MinInt(void); +JSInt64 __pascal __loadds __export + JSLL_Zero(void); +#else +extern JS_PUBLIC_API(JSInt64) JSLL_MaxInt(void); +extern JS_PUBLIC_API(JSInt64) JSLL_MinInt(void); +extern JS_PUBLIC_API(JSInt64) JSLL_Zero(void); +#endif + +#define JSLL_MAXINT JSLL_MaxInt() +#define JSLL_MININT JSLL_MinInt() +#define JSLL_ZERO JSLL_Zero() + +#ifdef JS_HAVE_LONG_LONG + +#if JS_BYTES_PER_LONG == 8 +#define JSLL_INIT(hi, lo) ((hi ## L << 32) + lo ## L) +#elif (defined(WIN32) || defined(WIN16)) && !defined(__GNUC__) +#define JSLL_INIT(hi, lo) ((hi ## i64 << 32) + lo ## i64) +#else +#define JSLL_INIT(hi, lo) ((hi ## LL << 32) + lo ## LL) +#endif + +/*********************************************************************** +** MACROS: JSLL_* +** DESCRIPTION: +** The following macros define portable access to the 64 bit +** math facilities. +** +***********************************************************************/ + +/*********************************************************************** +** MACROS: JSLL_ +** +** JSLL_IS_ZERO Test for zero +** JSLL_EQ Test for equality +** JSLL_NE Test for inequality +** JSLL_GE_ZERO Test for zero or positive +** JSLL_CMP Compare two values +***********************************************************************/ +#define JSLL_IS_ZERO(a) ((a) == 0) +#define JSLL_EQ(a, b) ((a) == (b)) +#define JSLL_NE(a, b) ((a) != (b)) +#define JSLL_GE_ZERO(a) ((a) >= 0) +#define JSLL_CMP(a, op, b) ((JSInt64)(a) op (JSInt64)(b)) +#define JSLL_UCMP(a, op, b) ((JSUint64)(a) op (JSUint64)(b)) + +/*********************************************************************** +** MACROS: JSLL_ +** +** JSLL_AND Logical and +** JSLL_OR Logical or +** JSLL_XOR Logical exclusion +** JSLL_OR2 A disgusting deviation +** JSLL_NOT Negation (one's compliment) +***********************************************************************/ +#define JSLL_AND(r, a, b) ((r) = (a) & (b)) +#define JSLL_OR(r, a, b) ((r) = (a) | (b)) +#define JSLL_XOR(r, a, b) ((r) = (a) ^ (b)) +#define JSLL_OR2(r, a) ((r) = (r) | (a)) +#define JSLL_NOT(r, a) ((r) = ~(a)) + +/*********************************************************************** +** MACROS: JSLL_ +** +** JSLL_NEG Negation (two's compliment) +** JSLL_ADD Summation (two's compliment) +** JSLL_SUB Difference (two's compliment) +***********************************************************************/ +#define JSLL_NEG(r, a) ((r) = -(a)) +#define JSLL_ADD(r, a, b) ((r) = (a) + (b)) +#define JSLL_SUB(r, a, b) ((r) = (a) - (b)) + +/*********************************************************************** +** MACROS: JSLL_ +** +** JSLL_MUL Product (two's compliment) +** JSLL_DIV Quotient (two's compliment) +** JSLL_MOD Modulus (two's compliment) +***********************************************************************/ +#define JSLL_MUL(r, a, b) ((r) = (a) * (b)) +#define JSLL_DIV(r, a, b) ((r) = (a) / (b)) +#define JSLL_MOD(r, a, b) ((r) = (a) % (b)) + +/*********************************************************************** +** MACROS: JSLL_ +** +** JSLL_SHL Shift left [0..64] bits +** JSLL_SHR Shift right [0..64] bits with sign extension +** JSLL_USHR Unsigned shift right [0..64] bits +** JSLL_ISHL Signed shift left [0..64] bits +***********************************************************************/ +#define JSLL_SHL(r, a, b) ((r) = (JSInt64)(a) << (b)) +#define JSLL_SHR(r, a, b) ((r) = (JSInt64)(a) >> (b)) +#define JSLL_USHR(r, a, b) ((r) = (JSUint64)(a) >> (b)) +#define JSLL_ISHL(r, a, b) ((r) = (JSInt64)(a) << (b)) + +/*********************************************************************** +** MACROS: JSLL_ +** +** JSLL_L2I Convert to signed 32 bit +** JSLL_L2UI Convert to unsigned 32 bit +** JSLL_L2F Convert to floating point +** JSLL_L2D Convert to floating point +** JSLL_I2L Convert signed to 64 bit +** JSLL_UI2L Convert unsigned to 64 bit +** JSLL_F2L Convert float to 64 bit +** JSLL_D2L Convert float to 64 bit +***********************************************************************/ +#define JSLL_L2I(i, l) ((i) = (JSInt32)(l)) +#define JSLL_L2UI(ui, l) ((ui) = (JSUint32)(l)) +#define JSLL_L2F(f, l) ((f) = (JSFloat64)(l)) +#define JSLL_L2D(d, l) ((d) = (JSFloat64)(l)) + +#define JSLL_I2L(l, i) ((l) = (JSInt64)(i)) +#define JSLL_UI2L(l, ui) ((l) = (JSInt64)(ui)) +#define JSLL_F2L(l, f) ((l) = (JSInt64)(f)) +#define JSLL_D2L(l, d) ((l) = (JSInt64)(d)) + +/*********************************************************************** +** MACROS: JSLL_UDIVMOD +** DESCRIPTION: +** Produce both a quotient and a remainder given an unsigned +** INPUTS: JSUint64 a: The dividend of the operation +** JSUint64 b: The quotient of the operation +** OUTPUTS: JSUint64 *qp: pointer to quotient +** JSUint64 *rp: pointer to remainder +***********************************************************************/ +#define JSLL_UDIVMOD(qp, rp, a, b) \ + (*(qp) = ((JSUint64)(a) / (b)), \ + *(rp) = ((JSUint64)(a) % (b))) + +#else /* !JS_HAVE_LONG_LONG */ + +#ifdef IS_LITTLE_ENDIAN +#define JSLL_INIT(hi, lo) {JS_INT32(lo), JS_INT32(hi)} +#else +#define JSLL_INIT(hi, lo) {JS_INT32(hi), JS_INT32(lo)} +#endif + +#define JSLL_IS_ZERO(a) (((a).hi == 0) && ((a).lo == 0)) +#define JSLL_EQ(a, b) (((a).hi == (b).hi) && ((a).lo == (b).lo)) +#define JSLL_NE(a, b) (((a).hi != (b).hi) || ((a).lo != (b).lo)) +#define JSLL_GE_ZERO(a) (((a).hi >> 31) == 0) + +#ifdef DEBUG +#define JSLL_CMP(a, op, b) (JS_ASSERT((#op)[1] != '='), JSLL_REAL_CMP(a, op, b)) +#define JSLL_UCMP(a, op, b) (JS_ASSERT((#op)[1] != '='), JSLL_REAL_UCMP(a, op, b)) +#else +#define JSLL_CMP(a, op, b) JSLL_REAL_CMP(a, op, b) +#define JSLL_UCMP(a, op, b) JSLL_REAL_UCMP(a, op, b) +#endif + +#define JSLL_REAL_CMP(a,op,b) (((JSInt32)(a).hi op (JSInt32)(b).hi) || \ + (((a).hi == (b).hi) && ((a).lo op (b).lo))) +#define JSLL_REAL_UCMP(a,op,b) (((a).hi op (b).hi) || \ + (((a).hi == (b).hi) && ((a).lo op (b).lo))) + +#define JSLL_AND(r, a, b) ((r).lo = (a).lo & (b).lo, \ + (r).hi = (a).hi & (b).hi) +#define JSLL_OR(r, a, b) ((r).lo = (a).lo | (b).lo, \ + (r).hi = (a).hi | (b).hi) +#define JSLL_XOR(r, a, b) ((r).lo = (a).lo ^ (b).lo, \ + (r).hi = (a).hi ^ (b).hi) +#define JSLL_OR2(r, a) ((r).lo = (r).lo | (a).lo, \ + (r).hi = (r).hi | (a).hi) +#define JSLL_NOT(r, a) ((r).lo = ~(a).lo, \ + (r).hi = ~(a).hi) + +#define JSLL_NEG(r, a) ((r).lo = -(JSInt32)(a).lo, \ + (r).hi = -(JSInt32)(a).hi - ((r).lo != 0)) +#define JSLL_ADD(r, a, b) { \ + JSInt64 _a, _b; \ + _a = a; _b = b; \ + (r).lo = _a.lo + _b.lo; \ + (r).hi = _a.hi + _b.hi + ((r).lo < _b.lo); \ +} + +#define JSLL_SUB(r, a, b) { \ + JSInt64 _a, _b; \ + _a = a; _b = b; \ + (r).lo = _a.lo - _b.lo; \ + (r).hi = _a.hi - _b.hi - (_a.lo < _b.lo); \ +} + +#define JSLL_MUL(r, a, b) { \ + JSInt64 _a, _b; \ + _a = a; _b = b; \ + JSLL_MUL32(r, _a.lo, _b.lo); \ + (r).hi += _a.hi * _b.lo + _a.lo * _b.hi; \ +} + +#define jslo16(a) ((a) & JS_BITMASK(16)) +#define jshi16(a) ((a) >> 16) + +#define JSLL_MUL32(r, a, b) { \ + JSUint32 _a1, _a0, _b1, _b0, _y0, _y1, _y2, _y3; \ + _a1 = jshi16(a), _a0 = jslo16(a); \ + _b1 = jshi16(b), _b0 = jslo16(b); \ + _y0 = _a0 * _b0; \ + _y1 = _a0 * _b1; \ + _y2 = _a1 * _b0; \ + _y3 = _a1 * _b1; \ + _y1 += jshi16(_y0); /* can't carry */ \ + _y1 += _y2; /* might carry */ \ + if (_y1 < _y2) \ + _y3 += (JSUint32)(JS_BIT(16)); /* propagate */ \ + (r).lo = (jslo16(_y1) << 16) + jslo16(_y0); \ + (r).hi = _y3 + jshi16(_y1); \ +} + +#define JSLL_UDIVMOD(qp, rp, a, b) jsll_udivmod(qp, rp, a, b) + +extern JS_PUBLIC_API(void) jsll_udivmod(JSUint64 *qp, JSUint64 *rp, JSUint64 a, JSUint64 b); + +#define JSLL_DIV(r, a, b) { \ + JSInt64 _a, _b; \ + JSUint32 _negative = (JSInt32)(a).hi < 0; \ + if (_negative) { \ + JSLL_NEG(_a, a); \ + } else { \ + _a = a; \ + } \ + if ((JSInt32)(b).hi < 0) { \ + _negative ^= 1; \ + JSLL_NEG(_b, b); \ + } else { \ + _b = b; \ + } \ + JSLL_UDIVMOD(&(r), 0, _a, _b); \ + if (_negative) \ + JSLL_NEG(r, r); \ +} + +#define JSLL_MOD(r, a, b) { \ + JSInt64 _a, _b; \ + JSUint32 _negative = (JSInt32)(a).hi < 0; \ + if (_negative) { \ + JSLL_NEG(_a, a); \ + } else { \ + _a = a; \ + } \ + if ((JSInt32)(b).hi < 0) { \ + JSLL_NEG(_b, b); \ + } else { \ + _b = b; \ + } \ + JSLL_UDIVMOD(0, &(r), _a, _b); \ + if (_negative) \ + JSLL_NEG(r, r); \ +} + +#define JSLL_SHL(r, a, b) { \ + if (b) { \ + JSInt64 _a; \ + _a = a; \ + if ((b) < 32) { \ + (r).lo = _a.lo << ((b) & 31); \ + (r).hi = (_a.hi << ((b) & 31)) | (_a.lo >> (32 - (b))); \ + } else { \ + (r).lo = 0; \ + (r).hi = _a.lo << ((b) & 31); \ + } \ + } else { \ + (r) = (a); \ + } \ +} + +/* a is an JSInt32, b is JSInt32, r is JSInt64 */ +#define JSLL_ISHL(r, a, b) { \ + if (b) { \ + JSInt64 _a; \ + _a.lo = (a); \ + _a.hi = 0; \ + if ((b) < 32) { \ + (r).lo = (a) << ((b) & 31); \ + (r).hi = ((a) >> (32 - (b))); \ + } else { \ + (r).lo = 0; \ + (r).hi = (a) << ((b) & 31); \ + } \ + } else { \ + (r).lo = (a); \ + (r).hi = 0; \ + } \ +} + +#define JSLL_SHR(r, a, b) { \ + if (b) { \ + JSInt64 _a; \ + _a = a; \ + if ((b) < 32) { \ + (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \ + (r).hi = (JSInt32)_a.hi >> ((b) & 31); \ + } else { \ + (r).lo = (JSInt32)_a.hi >> ((b) & 31); \ + (r).hi = (JSInt32)_a.hi >> 31; \ + } \ + } else { \ + (r) = (a); \ + } \ +} + +#define JSLL_USHR(r, a, b) { \ + if (b) { \ + JSInt64 _a; \ + _a = a; \ + if ((b) < 32) { \ + (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \ + (r).hi = _a.hi >> ((b) & 31); \ + } else { \ + (r).lo = _a.hi >> ((b) & 31); \ + (r).hi = 0; \ + } \ + } else { \ + (r) = (a); \ + } \ +} + +#define JSLL_L2I(i, l) ((i) = (l).lo) +#define JSLL_L2UI(ui, l) ((ui) = (l).lo) +#define JSLL_L2F(f, l) { double _d; JSLL_L2D(_d, l); (f) = (JSFloat64)_d; } + +#define JSLL_L2D(d, l) { \ + int _negative; \ + JSInt64 _absval; \ + \ + _negative = (l).hi >> 31; \ + if (_negative) { \ + JSLL_NEG(_absval, l); \ + } else { \ + _absval = l; \ + } \ + (d) = (double)_absval.hi * 4.294967296e9 + _absval.lo; \ + if (_negative) \ + (d) = -(d); \ +} + +#define JSLL_I2L(l, i) { JSInt32 _i = (i) >> 31; (l).lo = (i); (l).hi = _i; } +#define JSLL_UI2L(l, ui) ((l).lo = (ui), (l).hi = 0) +#define JSLL_F2L(l, f) { double _d = (double)f; JSLL_D2L(l, _d); } + +#define JSLL_D2L(l, d) { \ + int _negative; \ + double _absval, _d_hi; \ + JSInt64 _lo_d; \ + \ + _negative = ((d) < 0); \ + _absval = _negative ? -(d) : (d); \ + \ + (l).hi = _absval / 4.294967296e9; \ + (l).lo = 0; \ + JSLL_L2D(_d_hi, l); \ + _absval -= _d_hi; \ + _lo_d.hi = 0; \ + if (_absval < 0) { \ + _lo_d.lo = -_absval; \ + JSLL_SUB(l, l, _lo_d); \ + } else { \ + _lo_d.lo = _absval; \ + JSLL_ADD(l, l, _lo_d); \ + } \ + \ + if (_negative) \ + JSLL_NEG(l, l); \ +} + +#endif /* !JS_HAVE_LONG_LONG */ + +JS_END_EXTERN_C + +#endif /* jslong_h___ */ diff --git a/js32/jsopcode.h b/js32/jsopcode.h new file mode 100644 index 00000000..3f7e1de9 --- /dev/null +++ b/js32/jsopcode.h @@ -0,0 +1,318 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef jsopcode_h___ +#define jsopcode_h___ +/* + * JS bytecode definitions. + */ +#include +#include "jsprvtd.h" +#include "jspubtd.h" +#include "jsutil.h" + +JS_BEGIN_EXTERN_C + +/* + * JS operation bytecodes. + */ +typedef enum JSOp { +#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \ + op = val, +#include "jsopcode.tbl" +#undef OPDEF + JSOP_LIMIT +} JSOp; + +typedef enum JSOpLength { +#define OPDEF(op,val,name,token,length,nuses,ndefs,prec,format) \ + op##_LENGTH = length, +#include "jsopcode.tbl" +#undef OPDEF + JSOP_LIMIT_LENGTH +} JSOpLength; + +/* + * JS bytecode formats. + */ +#define JOF_BYTE 0 /* single bytecode, no immediates */ +#define JOF_JUMP 1 /* signed 16-bit jump offset immediate */ +#define JOF_CONST 2 /* unsigned 16-bit constant pool index */ +#define JOF_UINT16 3 /* unsigned 16-bit immediate operand */ +#define JOF_TABLESWITCH 4 /* table switch */ +#define JOF_LOOKUPSWITCH 5 /* lookup switch */ +#define JOF_QARG 6 /* quickened get/set function argument ops */ +#define JOF_QVAR 7 /* quickened get/set local variable ops */ +#define JOF_INDEXCONST 8 /* uint16 slot index + constant pool index */ +#define JOF_JUMPX 9 /* signed 32-bit jump offset immediate */ +#define JOF_TABLESWITCHX 10 /* extended (32-bit offset) table switch */ +#define JOF_LOOKUPSWITCHX 11 /* extended (32-bit offset) lookup switch */ +#define JOF_UINT24 12 /* extended unsigned 24-bit literal (index) */ +#define JOF_LITOPX 13 /* JOF_UINT24 followed by op being extended, + where op if JOF_CONST has no unsigned 16- + bit immediate operand */ +#define JOF_LOCAL 14 /* block-local operand stack variable */ +#define JOF_TYPEMASK 0x000f /* mask for above immediate types */ +#define JOF_NAME 0x0010 /* name operation */ +#define JOF_PROP 0x0020 /* obj.prop operation */ +#define JOF_ELEM 0x0030 /* obj[index] operation */ +#define JOF_MODEMASK 0x0030 /* mask for above addressing modes */ +#define JOF_SET 0x0040 /* set (i.e., assignment) operation */ +#define JOF_DEL 0x0080 /* delete operation */ +#define JOF_DEC 0x0100 /* decrement (--, not ++) opcode */ +#define JOF_INC 0x0200 /* increment (++, not --) opcode */ +#define JOF_INCDEC 0x0300 /* increment or decrement opcode */ +#define JOF_POST 0x0400 /* postorder increment or decrement */ +#define JOF_IMPORT 0x0800 /* import property op */ +#define JOF_FOR 0x1000 /* for-in property op */ +#define JOF_ASSIGNING JOF_SET /* hint for JSClass.resolve, used for ops + that do simplex assignment */ +#define JOF_DETECTING 0x2000 /* object detection flag for JSNewResolveOp */ +#define JOF_BACKPATCH 0x4000 /* backpatch placeholder during codegen */ +#define JOF_LEFTASSOC 0x8000 /* left-associative operator */ +#define JOF_DECLARING 0x10000 /* var, const, or function declaration op */ +#define JOF_XMLNAME 0x20000 /* XML name: *, a::b, @a, @a::b, etc. */ + +#define JOF_TYPE_IS_EXTENDED_JUMP(t) \ + ((unsigned)((t) - JOF_JUMPX) <= (unsigned)(JOF_LOOKUPSWITCHX - JOF_JUMPX)) + +/* + * Immediate operand getters, setters, and bounds. + */ + +/* Short (2-byte signed offset) relative jump macros. */ +#define JUMP_OFFSET_LEN 2 +#define JUMP_OFFSET_HI(off) ((jsbytecode)((off) >> 8)) +#define JUMP_OFFSET_LO(off) ((jsbytecode)(off)) +#define GET_JUMP_OFFSET(pc) ((int16)(((pc)[1] << 8) | (pc)[2])) +#define SET_JUMP_OFFSET(pc,off) ((pc)[1] = JUMP_OFFSET_HI(off), \ + (pc)[2] = JUMP_OFFSET_LO(off)) +#define JUMP_OFFSET_MIN ((int16)0x8000) +#define JUMP_OFFSET_MAX ((int16)0x7fff) + +/* + * When a short jump won't hold a relative offset, its 2-byte immediate offset + * operand is an unsigned index of a span-dependency record, maintained until + * code generation finishes -- after which some (but we hope not nearly all) + * span-dependent jumps must be extended (see OptimizeSpanDeps in jsemit.c). + * + * If the span-dependency record index overflows SPANDEP_INDEX_MAX, the jump + * offset will contain SPANDEP_INDEX_HUGE, indicating that the record must be + * found (via binary search) by its "before span-dependency optimization" pc + * offset (from script main entry point). + */ +#define GET_SPANDEP_INDEX(pc) ((uint16)(((pc)[1] << 8) | (pc)[2])) +#define SET_SPANDEP_INDEX(pc,i) ((pc)[1] = JUMP_OFFSET_HI(i), \ + (pc)[2] = JUMP_OFFSET_LO(i)) +#define SPANDEP_INDEX_MAX ((uint16)0xfffe) +#define SPANDEP_INDEX_HUGE ((uint16)0xffff) + +/* Ultimately, if short jumps won't do, emit long (4-byte signed) offsets. */ +#define JUMPX_OFFSET_LEN 4 +#define JUMPX_OFFSET_B3(off) ((jsbytecode)((off) >> 24)) +#define JUMPX_OFFSET_B2(off) ((jsbytecode)((off) >> 16)) +#define JUMPX_OFFSET_B1(off) ((jsbytecode)((off) >> 8)) +#define JUMPX_OFFSET_B0(off) ((jsbytecode)(off)) +#define GET_JUMPX_OFFSET(pc) ((int32)(((pc)[1] << 24) | ((pc)[2] << 16) \ + | ((pc)[3] << 8) | (pc)[4])) +#define SET_JUMPX_OFFSET(pc,off)((pc)[1] = JUMPX_OFFSET_B3(off), \ + (pc)[2] = JUMPX_OFFSET_B2(off), \ + (pc)[3] = JUMPX_OFFSET_B1(off), \ + (pc)[4] = JUMPX_OFFSET_B0(off)) +#define JUMPX_OFFSET_MIN ((int32)0x80000000) +#define JUMPX_OFFSET_MAX ((int32)0x7fffffff) + +/* + * A literal is indexed by a per-script atom map. Most scripts have relatively + * few literals, so the standard JOF_CONST format specifies a fixed 16 bits of + * immediate operand index. A script with more than 64K literals must push all + * high-indexed literals on the stack using JSOP_LITERAL, then use JOF_ELEM ops + * instead of JOF_PROP, etc. + */ +#define ATOM_INDEX_LEN 2 +#define ATOM_INDEX_HI(i) ((jsbytecode)((i) >> 8)) +#define ATOM_INDEX_LO(i) ((jsbytecode)(i)) +#define GET_ATOM_INDEX(pc) ((jsatomid)(((pc)[1] << 8) | (pc)[2])) +#define SET_ATOM_INDEX(pc,i) ((pc)[1] = ATOM_INDEX_HI(i), \ + (pc)[2] = ATOM_INDEX_LO(i)) +#define GET_ATOM(cx,script,pc) js_GetAtom((cx), &(script)->atomMap, \ + GET_ATOM_INDEX(pc)) + +/* A full atom index for JSOP_UINT24 uses 24 bits of immediate operand. */ +#define UINT24_HI(i) ((jsbytecode)((i) >> 16)) +#define UINT24_MID(i) ((jsbytecode)((i) >> 8)) +#define UINT24_LO(i) ((jsbytecode)(i)) +#define GET_UINT24(pc) ((jsatomid)(((pc)[1] << 16) | \ + ((pc)[2] << 8) | \ + (pc)[3])) +#define SET_UINT24(pc,i) ((pc)[1] = UINT24_HI(i), \ + (pc)[2] = UINT24_MID(i), \ + (pc)[3] = UINT24_LO(i)) + +/* Same format for JSOP_LITERAL, etc., but future-proof with different names. */ +#define LITERAL_INDEX_LEN 3 +#define LITERAL_INDEX_HI(i) UINT24_HI(i) +#define LITERAL_INDEX_MID(i) UINT24_MID(i) +#define LITERAL_INDEX_LO(i) UINT24_LO(i) +#define GET_LITERAL_INDEX(pc) GET_UINT24(pc) +#define SET_LITERAL_INDEX(pc,i) SET_UINT24(pc,i) + +/* Atom index limit is determined by SN_3BYTE_OFFSET_FLAG, see jsemit.h. */ +#define ATOM_INDEX_LIMIT_LOG2 23 +#define ATOM_INDEX_LIMIT ((uint32)1 << ATOM_INDEX_LIMIT_LOG2) + +JS_STATIC_ASSERT(sizeof(jsatomid) * JS_BITS_PER_BYTE >= + ATOM_INDEX_LIMIT_LOG2 + 1); + +/* Common uint16 immediate format helpers. */ +#define UINT16_HI(i) ((jsbytecode)((i) >> 8)) +#define UINT16_LO(i) ((jsbytecode)(i)) +#define GET_UINT16(pc) ((uintN)(((pc)[1] << 8) | (pc)[2])) +#define SET_UINT16(pc,i) ((pc)[1] = UINT16_HI(i), (pc)[2] = UINT16_LO(i)) +#define UINT16_LIMIT ((uintN)1 << 16) + +/* Actual argument count operand format helpers. */ +#define ARGC_HI(argc) UINT16_HI(argc) +#define ARGC_LO(argc) UINT16_LO(argc) +#define GET_ARGC(pc) GET_UINT16(pc) +#define ARGC_LIMIT UINT16_LIMIT + +/* Synonyms for quick JOF_QARG and JOF_QVAR bytecodes. */ +#define GET_ARGNO(pc) GET_UINT16(pc) +#define SET_ARGNO(pc,argno) SET_UINT16(pc,argno) +#define ARGNO_LEN 2 +#define ARGNO_LIMIT UINT16_LIMIT + +#define GET_VARNO(pc) GET_UINT16(pc) +#define SET_VARNO(pc,varno) SET_UINT16(pc,varno) +#define VARNO_LEN 2 +#define VARNO_LIMIT UINT16_LIMIT + +struct JSCodeSpec { + const char *name; /* JS bytecode name */ + const char *token; /* JS source literal or null */ + int8 length; /* length including opcode byte */ + int8 nuses; /* arity, -1 if variadic */ + int8 ndefs; /* number of stack results */ + uint8 prec; /* operator precedence */ + uint32 format; /* immediate operand format */ +}; + +extern const JSCodeSpec js_CodeSpec[]; +extern uintN js_NumCodeSpecs; +extern const jschar js_EscapeMap[]; + +/* + * Return a GC'ed string containing the chars in str, with any non-printing + * chars or quotes (' or " as specified by the quote argument) escaped, and + * with the quote character at the beginning and end of the result string. + */ +extern JSString * +js_QuoteString(JSContext *cx, JSString *str, jschar quote); + +/* + * JSPrinter operations, for printf style message formatting. The return + * value from js_GetPrinterOutput() is the printer's cumulative output, in + * a GC'ed string. + */ +extern JSPrinter * +js_NewPrinter(JSContext *cx, const char *name, uintN indent, JSBool pretty); + +extern void +js_DestroyPrinter(JSPrinter *jp); + +extern JSString * +js_GetPrinterOutput(JSPrinter *jp); + +extern int +js_printf(JSPrinter *jp, const char *format, ...); + +extern JSBool +js_puts(JSPrinter *jp, const char *s); + +#ifdef DEBUG +/* + * Disassemblers, for debugging only. + */ +#include + +extern JS_FRIEND_API(JSBool) +js_Disassemble(JSContext *cx, JSScript *script, JSBool lines, FILE *fp); + +extern JS_FRIEND_API(uintN) +js_Disassemble1(JSContext *cx, JSScript *script, jsbytecode *pc, uintN loc, + JSBool lines, FILE *fp); +#endif /* DEBUG */ + +/* + * Decompilers, for script, function, and expression pretty-printing. + */ +extern JSBool +js_DecompileCode(JSPrinter *jp, JSScript *script, jsbytecode *pc, uintN len, + uintN pcdepth); + +extern JSBool +js_DecompileScript(JSPrinter *jp, JSScript *script); + +extern JSBool +js_DecompileFunctionBody(JSPrinter *jp, JSFunction *fun); + +extern JSBool +js_DecompileFunction(JSPrinter *jp, JSFunction *fun); + +/* + * Find the source expression that resulted in v, and return a new string + * containing it. Fall back on v's string conversion (fallback) if we can't + * find the bytecode that generated and pushed v on the operand stack. + * + * Search the current stack frame if spindex is JSDVG_SEARCH_STACK. Don't + * look for v on the stack if spindex is JSDVG_IGNORE_STACK. Otherwise, + * spindex is the negative index of v, measured from cx->fp->sp, or from a + * lower frame's sp if cx->fp is native. + */ +extern JSString * +js_DecompileValueGenerator(JSContext *cx, intN spindex, jsval v, + JSString *fallback); + +#define JSDVG_IGNORE_STACK 0 +#define JSDVG_SEARCH_STACK 1 + +JS_END_EXTERN_C + +#endif /* jsopcode_h___ */ diff --git a/js32/jsopcode.tbl b/js32/jsopcode.tbl new file mode 100644 index 00000000..4a4ca898 --- /dev/null +++ b/js32/jsopcode.tbl @@ -0,0 +1,478 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sw=4 et tw=0 ft=C: + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* + * JavaScript operation bytecodes. If you need to allocate a bytecode, look + * for a name of the form JSOP_UNUSED* and claim it. Otherwise, always add at + * the end of the table. + * + * Includers must define an OPDEF macro of the following form: + * + * #define OPDEF(op,val,name,image,length,nuses,ndefs,prec,format) ... + * + * Selected arguments can be expanded in initializers. The op argument is + * expanded followed by comma in the JSOp enum (jsopcode.h), e.g. The value + * field must be dense for now, because jsopcode.c uses an OPDEF() expansion + * inside the js_CodeSpec[] initializer. + * + * Field Description + * op Bytecode name, which is the JSOp enumerator name + * value Bytecode value, which is the JSOp enumerator value + * name C string containing name for disassembler + * image C string containing "image" for pretty-printer, null if ugly + * length Number of bytes including any immediate operands + * nuses Number of stack slots consumed by bytecode, -1 if variadic + * ndefs Number of stack slots produced by bytecode + * prec Operator precedence, zero if not an operator + * format Bytecode plus immediate operand encoding format + * + * Precedence Operators Opcodes + * 1 let (x = y) z, w JSOP_LEAVEBLOCKEXPR + * 2 , JSOP_POP with SRC_PCDELTA note + * 3 =, +=, etc. JSOP_SETNAME, etc. (all JOF_ASSIGNING) + * 4 ?: JSOP_IFEQ, JSOP_IFEQX + * 5 || JSOP_OR, JSOP_ORX + * 6 && JSOP_AND, JSOP_ANDX + * 7 | JSOP_BITOR + * 8 ^ JSOP_BITXOR + * 9 & JSOP_BITAND + * 10 ==, !=, etc. JSOP_EQ, JSOP_NE, etc. + * 11 <, in, etc. JSOP_LT, JSOP_IN, etc. + * 12 <<, >>, >>> JSOP_LSH, JSOP_RSH, JSOP_URSH + * 13 +, -, etc. JSOP_ADD, JSOP_SUB, etc. + * 14 *, /, % JSOP_MUL, JSOP_DIV, JSOP_MOD + * 15 !, ~, etc. JSOP_NOT, JSOP_BITNOT, etc. + * 16 0, function(){} etc. JSOP_ZERO, JSOP_ANONFUNOBJ, etc. + * 17 delete, new JSOP_DEL*, JSOP_NEW + * 18 x.y, f(), etc. JSOP_GETPROP, JSOP_CALL, etc. + * 19 x, null, etc. JSOP_NAME, JSOP_NULL, etc. + * + * The push-numeric-constant operators, JSOP_ZERO, JSOP_NUMBER, etc., have + * lower precedence than the member operators emitted for the . operator, to + * cause the decompiler to parenthesize the . left operand, e.g. (0).foo. + * Otherwise the . could be taken as a decimal point. We use the same level + * 16 for function expressions too, to force parenthesization. + * + * This file is best viewed with 128 columns: +12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 + */ + +/* legend: op val name image len use def prec format */ + +/* Longstanding JavaScript bytecodes. */ +OPDEF(JSOP_NOP, 0, "nop", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_PUSH, 1, "push", NULL, 1, 0, 1, 0, JOF_BYTE) +OPDEF(JSOP_POPV, 2, "popv", NULL, 1, 1, 0, 2, JOF_BYTE) +OPDEF(JSOP_ENTERWITH, 3, "enterwith", NULL, 1, 1, 1, 0, JOF_BYTE) +OPDEF(JSOP_LEAVEWITH, 4, "leavewith", NULL, 1, 1, 0, 0, JOF_BYTE) +OPDEF(JSOP_RETURN, 5, "return", NULL, 1, 1, 0, 0, JOF_BYTE) +OPDEF(JSOP_GOTO, 6, "goto", NULL, 3, 0, 0, 0, JOF_JUMP) +OPDEF(JSOP_IFEQ, 7, "ifeq", NULL, 3, 1, 0, 4, JOF_JUMP|JOF_DETECTING) +OPDEF(JSOP_IFNE, 8, "ifne", NULL, 3, 1, 0, 0, JOF_JUMP) + +/* Get the arguments object for the current, lightweight function activation. */ +OPDEF(JSOP_ARGUMENTS, 9, js_arguments_str, js_arguments_str, 1, 0, 1, 18, JOF_BYTE) + +/* ECMA-compliant for-in loop with argument or local variable loop control. */ +OPDEF(JSOP_FORARG, 10, "forarg", NULL, 3, 0, 1, 19, JOF_QARG|JOF_NAME|JOF_FOR) +OPDEF(JSOP_FORVAR, 11, "forvar", NULL, 3, 0, 1, 19, JOF_QVAR|JOF_NAME|JOF_FOR) + +/* More longstanding bytecodes. */ +OPDEF(JSOP_DUP, 12, "dup", NULL, 1, 1, 2, 0, JOF_BYTE) +OPDEF(JSOP_DUP2, 13, "dup2", NULL, 1, 2, 4, 0, JOF_BYTE) +OPDEF(JSOP_SETCONST, 14, "setconst", NULL, 3, 1, 1, 3, JOF_CONST|JOF_NAME|JOF_SET|JOF_ASSIGNING) +OPDEF(JSOP_BITOR, 15, "bitor", "|", 1, 2, 1, 7, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_BITXOR, 16, "bitxor", "^", 1, 2, 1, 8, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_BITAND, 17, "bitand", "&", 1, 2, 1, 9, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_EQ, 18, "eq", "==", 1, 2, 1, 10, JOF_BYTE|JOF_LEFTASSOC|JOF_DETECTING) +OPDEF(JSOP_NE, 19, "ne", "!=", 1, 2, 1, 10, JOF_BYTE|JOF_LEFTASSOC|JOF_DETECTING) +OPDEF(JSOP_LT, 20, "lt", "<", 1, 2, 1, 11, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_LE, 21, "le", "<=", 1, 2, 1, 11, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_GT, 22, "gt", ">", 1, 2, 1, 11, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_GE, 23, "ge", ">=", 1, 2, 1, 11, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_LSH, 24, "lsh", "<<", 1, 2, 1, 12, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_RSH, 25, "rsh", ">>", 1, 2, 1, 12, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_URSH, 26, "ursh", ">>>", 1, 2, 1, 12, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_ADD, 27, "add", "+", 1, 2, 1, 13, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_SUB, 28, "sub", "-", 1, 2, 1, 13, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_MUL, 29, "mul", "*", 1, 2, 1, 14, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_DIV, 30, "div", "/", 1, 2, 1, 14, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_MOD, 31, "mod", "%", 1, 2, 1, 14, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_NOT, 32, "not", "!", 1, 1, 1, 15, JOF_BYTE|JOF_DETECTING) +OPDEF(JSOP_BITNOT, 33, "bitnot", "~", 1, 1, 1, 15, JOF_BYTE) +OPDEF(JSOP_NEG, 34, "neg", "- ", 1, 1, 1, 15, JOF_BYTE) +OPDEF(JSOP_NEW, 35, js_new_str, NULL, 3, -1, 1, 17, JOF_UINT16) +OPDEF(JSOP_DELNAME, 36, "delname", NULL, 3, 0, 1, 17, JOF_CONST|JOF_NAME|JOF_DEL) +OPDEF(JSOP_DELPROP, 37, "delprop", NULL, 3, 1, 1, 17, JOF_CONST|JOF_PROP|JOF_DEL) +OPDEF(JSOP_DELELEM, 38, "delelem", NULL, 1, 2, 1, 17, JOF_BYTE |JOF_ELEM|JOF_DEL) +OPDEF(JSOP_TYPEOF, 39, js_typeof_str,NULL, 1, 1, 1, 15, JOF_BYTE|JOF_DETECTING) +OPDEF(JSOP_VOID, 40, js_void_str, NULL, 1, 1, 1, 15, JOF_BYTE) +OPDEF(JSOP_INCNAME, 41, "incname", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_INC) +OPDEF(JSOP_INCPROP, 42, "incprop", NULL, 3, 1, 1, 15, JOF_CONST|JOF_PROP|JOF_INC) +OPDEF(JSOP_INCELEM, 43, "incelem", NULL, 1, 2, 1, 15, JOF_BYTE |JOF_ELEM|JOF_INC) +OPDEF(JSOP_DECNAME, 44, "decname", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_DEC) +OPDEF(JSOP_DECPROP, 45, "decprop", NULL, 3, 1, 1, 15, JOF_CONST|JOF_PROP|JOF_DEC) +OPDEF(JSOP_DECELEM, 46, "decelem", NULL, 1, 2, 1, 15, JOF_BYTE |JOF_ELEM|JOF_DEC) +OPDEF(JSOP_NAMEINC, 47, "nameinc", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_INC|JOF_POST) +OPDEF(JSOP_PROPINC, 48, "propinc", NULL, 3, 1, 1, 15, JOF_CONST|JOF_PROP|JOF_INC|JOF_POST) +OPDEF(JSOP_ELEMINC, 49, "eleminc", NULL, 1, 2, 1, 15, JOF_BYTE |JOF_ELEM|JOF_INC|JOF_POST) +OPDEF(JSOP_NAMEDEC, 50, "namedec", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_DEC|JOF_POST) +OPDEF(JSOP_PROPDEC, 51, "propdec", NULL, 3, 1, 1, 15, JOF_CONST|JOF_PROP|JOF_DEC|JOF_POST) +OPDEF(JSOP_ELEMDEC, 52, "elemdec", NULL, 1, 2, 1, 15, JOF_BYTE |JOF_ELEM|JOF_DEC|JOF_POST) +OPDEF(JSOP_GETPROP, 53, "getprop", NULL, 3, 1, 1, 18, JOF_CONST|JOF_PROP) +OPDEF(JSOP_SETPROP, 54, "setprop", NULL, 3, 2, 1, 3, JOF_CONST|JOF_PROP|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) +OPDEF(JSOP_GETELEM, 55, "getelem", NULL, 1, 2, 1, 18, JOF_BYTE |JOF_ELEM|JOF_LEFTASSOC) +OPDEF(JSOP_SETELEM, 56, "setelem", NULL, 1, 3, 1, 3, JOF_BYTE |JOF_ELEM|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) +OPDEF(JSOP_PUSHOBJ, 57, "pushobj", NULL, 1, 0, 1, 0, JOF_BYTE) +OPDEF(JSOP_CALL, 58, "call", NULL, 3, -1, 1, 18, JOF_UINT16) +OPDEF(JSOP_NAME, 59, "name", NULL, 3, 0, 1, 19, JOF_CONST|JOF_NAME) +OPDEF(JSOP_NUMBER, 60, "number", NULL, 3, 0, 1, 16, JOF_CONST) +OPDEF(JSOP_STRING, 61, "string", NULL, 3, 0, 1, 19, JOF_CONST) +OPDEF(JSOP_ZERO, 62, "zero", "0", 1, 0, 1, 16, JOF_BYTE) +OPDEF(JSOP_ONE, 63, "one", "1", 1, 0, 1, 16, JOF_BYTE) +OPDEF(JSOP_NULL, 64, js_null_str, js_null_str, 1, 0, 1, 19, JOF_BYTE) +OPDEF(JSOP_THIS, 65, js_this_str, js_this_str, 1, 0, 1, 19, JOF_BYTE) +OPDEF(JSOP_FALSE, 66, js_false_str, js_false_str, 1, 0, 1, 19, JOF_BYTE) +OPDEF(JSOP_TRUE, 67, js_true_str, js_true_str, 1, 0, 1, 19, JOF_BYTE) +OPDEF(JSOP_OR, 68, "or", NULL, 3, 1, 0, 5, JOF_JUMP|JOF_DETECTING) +OPDEF(JSOP_AND, 69, "and", NULL, 3, 1, 0, 6, JOF_JUMP|JOF_DETECTING) + +/* The switch bytecodes have variable length. */ +OPDEF(JSOP_TABLESWITCH, 70, "tableswitch", NULL, -1, 1, 0, 0, JOF_TABLESWITCH|JOF_DETECTING) +OPDEF(JSOP_LOOKUPSWITCH, 71, "lookupswitch", NULL, -1, 1, 0, 0, JOF_LOOKUPSWITCH|JOF_DETECTING) + +/* New, infallible/transitive identity ops. */ +OPDEF(JSOP_NEW_EQ, 72, "eq", NULL, 1, 2, 1, 10, JOF_BYTE|JOF_DETECTING) +OPDEF(JSOP_NEW_NE, 73, "ne", NULL, 1, 2, 1, 10, JOF_BYTE|JOF_DETECTING) + +/* Lexical closure constructor. */ +OPDEF(JSOP_CLOSURE, 74, "closure", NULL, 3, 0, 0, 0, JOF_CONST) + +/* Export and import ops. */ +OPDEF(JSOP_EXPORTALL, 75, "exportall", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_EXPORTNAME,76, "exportname", NULL, 3, 0, 0, 0, JOF_CONST|JOF_NAME) +OPDEF(JSOP_IMPORTALL, 77, "importall", NULL, 1, 1, 0, 0, JOF_BYTE) +OPDEF(JSOP_IMPORTPROP,78, "importprop", NULL, 3, 1, 0, 0, JOF_CONST|JOF_PROP|JOF_IMPORT) +OPDEF(JSOP_IMPORTELEM,79, "importelem", NULL, 1, 2, 0, 0, JOF_BYTE |JOF_ELEM|JOF_IMPORT) + +/* Push object literal. */ +OPDEF(JSOP_OBJECT, 80, "object", NULL, 3, 0, 1, 19, JOF_CONST) + +/* Pop value and discard it. */ +OPDEF(JSOP_POP, 81, "pop", NULL, 1, 1, 0, 2, JOF_BYTE) + +/* Convert value to number, for unary +. */ +OPDEF(JSOP_POS, 82, "pos", "+ ", 1, 1, 1, 15, JOF_BYTE) + +/* Trap into debugger for breakpoint, etc. */ +OPDEF(JSOP_TRAP, 83, "trap", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* Fast get/set ops for function arguments and local variables. */ +OPDEF(JSOP_GETARG, 84, "getarg", NULL, 3, 0, 1, 19, JOF_QARG |JOF_NAME) +OPDEF(JSOP_SETARG, 85, "setarg", NULL, 3, 1, 1, 3, JOF_QARG |JOF_NAME|JOF_SET|JOF_ASSIGNING) +OPDEF(JSOP_GETVAR, 86, "getvar", NULL, 3, 0, 1, 19, JOF_QVAR |JOF_NAME) +OPDEF(JSOP_SETVAR, 87, "setvar", NULL, 3, 1, 1, 3, JOF_QVAR |JOF_NAME|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) + +/* Push unsigned 16-bit int constant. */ +OPDEF(JSOP_UINT16, 88, "uint16", NULL, 3, 0, 1, 16, JOF_UINT16) + +/* Object and array literal support. */ +OPDEF(JSOP_NEWINIT, 89, "newinit", NULL, 1, 2, 1, 0, JOF_BYTE) +OPDEF(JSOP_ENDINIT, 90, "endinit", NULL, 1, 0, 0, 19, JOF_BYTE) +OPDEF(JSOP_INITPROP, 91, "initprop", NULL, 3, 1, 0, 3, JOF_CONST|JOF_PROP|JOF_DETECTING) +OPDEF(JSOP_INITELEM, 92, "initelem", NULL, 1, 2, 0, 3, JOF_BYTE |JOF_ELEM|JOF_DETECTING) +OPDEF(JSOP_DEFSHARP, 93, "defsharp", NULL, 3, 0, 0, 0, JOF_UINT16) +OPDEF(JSOP_USESHARP, 94, "usesharp", NULL, 3, 0, 1, 0, JOF_UINT16) + +/* Fast inc/dec ops for args and local vars. */ +OPDEF(JSOP_INCARG, 95, "incarg", NULL, 3, 0, 1, 15, JOF_QARG |JOF_NAME|JOF_INC) +OPDEF(JSOP_INCVAR, 96, "incvar", NULL, 3, 0, 1, 15, JOF_QVAR |JOF_NAME|JOF_INC) +OPDEF(JSOP_DECARG, 97, "decarg", NULL, 3, 0, 1, 15, JOF_QARG |JOF_NAME|JOF_DEC) +OPDEF(JSOP_DECVAR, 98, "decvar", NULL, 3, 0, 1, 15, JOF_QVAR |JOF_NAME|JOF_DEC) +OPDEF(JSOP_ARGINC, 99, "arginc", NULL, 3, 0, 1, 15, JOF_QARG |JOF_NAME|JOF_INC|JOF_POST) +OPDEF(JSOP_VARINC, 100,"varinc", NULL, 3, 0, 1, 15, JOF_QVAR |JOF_NAME|JOF_INC|JOF_POST) +OPDEF(JSOP_ARGDEC, 101,"argdec", NULL, 3, 0, 1, 15, JOF_QARG |JOF_NAME|JOF_DEC|JOF_POST) +OPDEF(JSOP_VARDEC, 102,"vardec", NULL, 3, 0, 1, 15, JOF_QVAR |JOF_NAME|JOF_DEC|JOF_POST) + +/* + * Initialize for-in iterator. See also JSOP_FOREACH and JSOP_FOREACHKEYVAL. + */ +OPDEF(JSOP_FORIN, 103,"forin", NULL, 1, 1, 1, 0, JOF_BYTE) + +/* ECMA-compliant for/in ops. */ +OPDEF(JSOP_FORNAME, 104,"forname", NULL, 3, 0, 1, 19, JOF_CONST|JOF_NAME|JOF_FOR) +OPDEF(JSOP_FORPROP, 105,"forprop", NULL, 3, 1, 1, 18, JOF_CONST|JOF_PROP|JOF_FOR) +OPDEF(JSOP_FORELEM, 106,"forelem", NULL, 1, 1, 3, 18, JOF_BYTE |JOF_ELEM|JOF_FOR) +OPDEF(JSOP_POP2, 107,"pop2", NULL, 1, 2, 0, 0, JOF_BYTE) + +/* ECMA-compliant assignment ops. */ +OPDEF(JSOP_BINDNAME, 108,"bindname", NULL, 3, 0, 1, 0, JOF_CONST|JOF_NAME|JOF_SET|JOF_ASSIGNING) +OPDEF(JSOP_SETNAME, 109,"setname", NULL, 3, 2, 1, 3, JOF_CONST|JOF_NAME|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) + +/* Exception handling ops. */ +OPDEF(JSOP_THROW, 110,"throw", NULL, 1, 1, 0, 0, JOF_BYTE) + +/* 'in' and 'instanceof' ops. */ +OPDEF(JSOP_IN, 111,js_in_str, js_in_str, 1, 2, 1, 11, JOF_BYTE|JOF_LEFTASSOC) +OPDEF(JSOP_INSTANCEOF,112,js_instanceof_str,js_instanceof_str,1,2,1,11,JOF_BYTE|JOF_LEFTASSOC) + +/* debugger op */ +OPDEF(JSOP_DEBUGGER, 113,"debugger", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* gosub/retsub for finally handling */ +OPDEF(JSOP_GOSUB, 114,"gosub", NULL, 3, 0, 0, 0, JOF_JUMP) +OPDEF(JSOP_RETSUB, 115,"retsub", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* More exception handling ops. */ +OPDEF(JSOP_EXCEPTION, 116,"exception", NULL, 1, 0, 1, 0, JOF_BYTE) +OPDEF(JSOP_SETSP, 117,"setsp", NULL, 3, 0, 0, 0, JOF_UINT16) + +/* + * ECMA-compliant switch statement ops. + * CONDSWITCH is a decompilable NOP; CASE is ===, POP, jump if true, re-push + * lval if false; and DEFAULT is POP lval and GOTO. + */ +OPDEF(JSOP_CONDSWITCH,118,"condswitch", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_CASE, 119,"case", NULL, 3, 1, 0, 0, JOF_JUMP) +OPDEF(JSOP_DEFAULT, 120,"default", NULL, 3, 1, 0, 0, JOF_JUMP) + +/* + * ECMA-compliant call to eval op + */ +OPDEF(JSOP_EVAL, 121,"eval", NULL, 3, -1, 1, 18, JOF_UINT16) + +/* + * ECMA-compliant helper for 'for (x[i] in o)' loops. + */ +OPDEF(JSOP_ENUMELEM, 122,"enumelem", NULL, 1, 3, 0, 3, JOF_BYTE |JOF_SET|JOF_ASSIGNING) + +/* + * Getter and setter prefix bytecodes. These modify the next bytecode, either + * an assignment or a property initializer code, which then defines a property + * getter or setter. + */ +OPDEF(JSOP_GETTER, 123,js_getter_str,NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_SETTER, 124,js_setter_str,NULL, 1, 0, 0, 0, JOF_BYTE) + +/* + * Prolog bytecodes for defining function, var, and const names. + */ +OPDEF(JSOP_DEFFUN, 125,"deffun", NULL, 3, 0, 0, 0, JOF_CONST|JOF_DECLARING) +OPDEF(JSOP_DEFCONST, 126,"defconst", NULL, 3, 0, 0, 0, JOF_CONST|JOF_DECLARING) +OPDEF(JSOP_DEFVAR, 127,"defvar", NULL, 3, 0, 0, 0, JOF_CONST|JOF_DECLARING) + +/* Auto-clone (if needed due to re-parenting) and push an anonymous function. */ +OPDEF(JSOP_ANONFUNOBJ, 128, "anonfunobj", NULL, 3, 0, 1, 16, JOF_CONST) + +/* ECMA ed. 3 named function expression. */ +OPDEF(JSOP_NAMEDFUNOBJ, 129, "namedfunobj", NULL, 3, 0, 1, 16, JOF_CONST) + +/* + * Like JSOP_SETLOCAL, but specialized to avoid requiring JSOP_POP immediately + * after to throw away the exception value. + */ +OPDEF(JSOP_SETLOCALPOP, 130, "setlocalpop", NULL, 3, 1, 0, 3, JOF_LOCAL|JOF_NAME|JOF_SET) + +/* ECMA-mandated parenthesization opcode, which nulls the reference base register, obj; see jsinterp.c. */ +OPDEF(JSOP_GROUP, 131, "group", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* Host object extension: given 'o.item(i) = j', the left-hand side compiles JSOP_SETCALL, rather than JSOP_CALL. */ +OPDEF(JSOP_SETCALL, 132, "setcall", NULL, 3, -1, 2, 18, JOF_UINT16|JOF_SET|JOF_ASSIGNING) + +/* + * Exception handling no-ops, for more economical byte-coding than SRC_TRYFIN + * srcnote-annotated JSOP_NOPs. + */ +OPDEF(JSOP_TRY, 133,"try", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_FINALLY, 134,"finally", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* + * Swap the top two stack elements. + */ +OPDEF(JSOP_SWAP, 135,"swap", NULL, 1, 2, 2, 0, JOF_BYTE) + +/* + * Bytecodes that avoid making an arguments object in most cases: + * JSOP_ARGSUB gets arguments[i] from fp->argv, iff i is in [0, fp->argc-1]. + * JSOP_ARGCNT returns fp->argc. + */ +OPDEF(JSOP_ARGSUB, 136,"argsub", NULL, 3, 0, 1, 18, JOF_QARG |JOF_NAME) +OPDEF(JSOP_ARGCNT, 137,"argcnt", NULL, 1, 0, 1, 18, JOF_BYTE) + +/* + * Define a local function object as a local variable. + * The local variable's slot number is the first immediate two-byte operand. + * The function object's atom index is the second immediate operand. + */ +OPDEF(JSOP_DEFLOCALFUN, 138,"deflocalfun",NULL, 5, 0, 0, 0, JOF_INDEXCONST|JOF_DECLARING) + +/* Extended jumps. */ +OPDEF(JSOP_GOTOX, 139,"gotox", NULL, 5, 0, 0, 0, JOF_JUMPX) +OPDEF(JSOP_IFEQX, 140,"ifeqx", NULL, 5, 1, 0, 3, JOF_JUMPX|JOF_DETECTING) +OPDEF(JSOP_IFNEX, 141,"ifnex", NULL, 5, 1, 0, 0, JOF_JUMPX) +OPDEF(JSOP_ORX, 142,"orx", NULL, 5, 1, 0, 5, JOF_JUMPX|JOF_DETECTING) +OPDEF(JSOP_ANDX, 143,"andx", NULL, 5, 1, 0, 6, JOF_JUMPX|JOF_DETECTING) +OPDEF(JSOP_GOSUBX, 144,"gosubx", NULL, 5, 0, 0, 0, JOF_JUMPX) +OPDEF(JSOP_CASEX, 145,"casex", NULL, 5, 1, 0, 0, JOF_JUMPX) +OPDEF(JSOP_DEFAULTX, 146,"defaultx", NULL, 5, 1, 0, 0, JOF_JUMPX) +OPDEF(JSOP_TABLESWITCHX, 147,"tableswitchx",NULL, -1, 1, 0, 0, JOF_TABLESWITCHX|JOF_DETECTING) +OPDEF(JSOP_LOOKUPSWITCHX, 148,"lookupswitchx",NULL, -1, 1, 0, 0, JOF_LOOKUPSWITCHX|JOF_DETECTING) + +/* Placeholders for a real jump opcode set during backpatch chain fixup. */ +OPDEF(JSOP_BACKPATCH, 149,"backpatch",NULL, 3, 0, 0, 0, JOF_JUMP|JOF_BACKPATCH) +OPDEF(JSOP_BACKPATCH_POP, 150,"backpatch_pop",NULL, 3, 1, 0, 0, JOF_JUMP|JOF_BACKPATCH) + +/* Set pending exception from the stack, to trigger rethrow. */ +OPDEF(JSOP_THROWING, 151,"throwing", NULL, 1, 1, 0, 0, JOF_BYTE) + +/* Set and get return value pseudo-register in stack frame. */ +OPDEF(JSOP_SETRVAL, 152,"setrval", NULL, 1, 1, 0, 0, JOF_BYTE) +OPDEF(JSOP_RETRVAL, 153,"retrval", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* Optimized global variable ops (we don't bother doing a JSOP_FORGVAR op). */ +OPDEF(JSOP_GETGVAR, 154,"getgvar", NULL, 3, 0, 1, 19, JOF_CONST|JOF_NAME) +OPDEF(JSOP_SETGVAR, 155,"setgvar", NULL, 3, 1, 1, 3, JOF_CONST|JOF_NAME|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) +OPDEF(JSOP_INCGVAR, 156,"incgvar", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_INC) +OPDEF(JSOP_DECGVAR, 157,"decgvar", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_DEC) +OPDEF(JSOP_GVARINC, 158,"gvarinc", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_INC|JOF_POST) +OPDEF(JSOP_GVARDEC, 159,"gvardec", NULL, 3, 0, 1, 15, JOF_CONST|JOF_NAME|JOF_DEC|JOF_POST) + +/* Regular expression literal requiring special "fork on exec" handling. */ +OPDEF(JSOP_REGEXP, 160,"regexp", NULL, 3, 0, 1, 19, JOF_CONST) + +/* XML (ECMA-357, a.k.a. "E4X") support. */ +OPDEF(JSOP_DEFXMLNS, 161,"defxmlns", NULL, 1, 1, 0, 0, JOF_BYTE) +OPDEF(JSOP_ANYNAME, 162,"anyname", NULL, 1, 0, 1, 19, JOF_BYTE|JOF_XMLNAME) +OPDEF(JSOP_QNAMEPART, 163,"qnamepart", NULL, 3, 0, 1, 19, JOF_CONST|JOF_XMLNAME) +OPDEF(JSOP_QNAMECONST, 164,"qnameconst", NULL, 3, 1, 1, 19, JOF_CONST|JOF_XMLNAME) +OPDEF(JSOP_QNAME, 165,"qname", NULL, 1, 2, 1, 0, JOF_BYTE|JOF_XMLNAME) +OPDEF(JSOP_TOATTRNAME, 166,"toattrname", NULL, 1, 1, 1, 19, JOF_BYTE|JOF_XMLNAME) +OPDEF(JSOP_TOATTRVAL, 167,"toattrval", NULL, 1, 1, 1, 19, JOF_BYTE) +OPDEF(JSOP_ADDATTRNAME, 168,"addattrname",NULL, 1, 2, 1, 13, JOF_BYTE) +OPDEF(JSOP_ADDATTRVAL, 169,"addattrval", NULL, 1, 2, 1, 13, JOF_BYTE) +OPDEF(JSOP_BINDXMLNAME, 170,"bindxmlname",NULL, 1, 1, 2, 3, JOF_BYTE|JOF_SET|JOF_ASSIGNING) +OPDEF(JSOP_SETXMLNAME, 171,"setxmlname", NULL, 1, 3, 1, 3, JOF_BYTE|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) +OPDEF(JSOP_XMLNAME, 172,"xmlname", NULL, 1, 1, 1, 19, JOF_BYTE) +OPDEF(JSOP_DESCENDANTS, 173,"descendants",NULL, 1, 2, 1, 18, JOF_BYTE) +OPDEF(JSOP_FILTER, 174,"filter", NULL, 3, 1, 1, 0, JOF_JUMP) +OPDEF(JSOP_ENDFILTER, 175,"endfilter", NULL, 1, 1, 0, 18, JOF_BYTE) +OPDEF(JSOP_TOXML, 176,"toxml", NULL, 1, 1, 1, 19, JOF_BYTE) +OPDEF(JSOP_TOXMLLIST, 177,"toxmllist", NULL, 1, 1, 1, 19, JOF_BYTE) +OPDEF(JSOP_XMLTAGEXPR, 178,"xmltagexpr", NULL, 1, 1, 1, 0, JOF_BYTE) +OPDEF(JSOP_XMLELTEXPR, 179,"xmleltexpr", NULL, 1, 1, 1, 0, JOF_BYTE) +OPDEF(JSOP_XMLOBJECT, 180,"xmlobject", NULL, 3, 0, 1, 19, JOF_CONST) +OPDEF(JSOP_XMLCDATA, 181,"xmlcdata", NULL, 3, 0, 1, 19, JOF_CONST) +OPDEF(JSOP_XMLCOMMENT, 182,"xmlcomment", NULL, 3, 0, 1, 19, JOF_CONST) +OPDEF(JSOP_XMLPI, 183,"xmlpi", NULL, 3, 1, 1, 19, JOF_CONST) +OPDEF(JSOP_GETMETHOD, 184,"getmethod", NULL, 3, 1, 1, 18, JOF_CONST|JOF_PROP) +OPDEF(JSOP_GETFUNNS, 185,"getfunns", NULL, 1, 0, 1, 19, JOF_BYTE) +OPDEF(JSOP_FOREACH, 186,"foreach", NULL, 1, 1, 1, 0, JOF_BYTE) +OPDEF(JSOP_DELDESC, 187,"deldesc", NULL, 1, 2, 1, 17, JOF_BYTE |JOF_ELEM|JOF_DEL) + +/* + * Opcodes for extended literal addressing, using unsigned 24-bit immediate + * operands to hold integer operands (JSOP_UINT24), extended atom indexes in + * script->atomMap (JSOP_LITERAL, JSOP_FINDNAME), and ops prefixed by such + * atom index immediates (JSOP_LITOPX). See jsemit.c, EmitAtomIndexOp. + */ +OPDEF(JSOP_UINT24, 188,"uint24", NULL, 4, 0, 1, 16, JOF_UINT24) +OPDEF(JSOP_LITERAL, 189,"literal", NULL, 4, 0, 1, 19, JOF_UINT24) +OPDEF(JSOP_FINDNAME, 190,"findname", NULL, 4, 0, 2, 0, JOF_UINT24) +OPDEF(JSOP_LITOPX, 191,"litopx", NULL, 5, 0, 0, 0, JOF_LITOPX) + +/* + * Opcodes to help the decompiler deal with XML. + */ +OPDEF(JSOP_STARTXML, 192,"startxml", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_STARTXMLEXPR, 193,"startxmlexpr",NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_SETMETHOD, 194,"setmethod", NULL, 3, 2, 1, 3, JOF_CONST|JOF_PROP|JOF_SET|JOF_ASSIGNING|JOF_DETECTING) + +/* + * Stop interpretation, emitted at end of script to save the threaded bytecode + * interpreter an extra branch test on every DO_NEXT_OP (see jsinterp.c). + */ +OPDEF(JSOP_STOP, 195,"stop", NULL, 1, 0, 0, 0, JOF_BYTE) + +/* + * Get an extant property or element value, throwing ReferenceError if the + * identified property does not exist. + */ +OPDEF(JSOP_GETXPROP, 196,"getxprop", NULL, 3, 1, 1, 18, JOF_CONST|JOF_PROP) +OPDEF(JSOP_GETXELEM, 197,"getxelem", NULL, 1, 2, 1, 18, JOF_BYTE |JOF_ELEM|JOF_LEFTASSOC) + +/* + * Specialized JSOP_TYPEOF to avoid reporting undefined for typeof(0, undef). + */ +OPDEF(JSOP_TYPEOFEXPR, 198,js_typeof_str, NULL, 1, 1, 1, 15, JOF_BYTE|JOF_DETECTING) + +/* + * Block-local scope support. + */ +OPDEF(JSOP_ENTERBLOCK, 199,"enterblock", NULL, 3, 0, 0, 0, JOF_CONST) +OPDEF(JSOP_LEAVEBLOCK, 200,"leaveblock", NULL, 3, 0, 0, 0, JOF_UINT16) +OPDEF(JSOP_GETLOCAL, 201,"getlocal", NULL, 3, 0, 1, 19, JOF_LOCAL|JOF_NAME) +OPDEF(JSOP_SETLOCAL, 202,"setlocal", NULL, 3, 1, 1, 3, JOF_LOCAL|JOF_NAME|JOF_SET) +OPDEF(JSOP_INCLOCAL, 203,"inclocal", NULL, 3, 0, 1, 15, JOF_LOCAL|JOF_NAME|JOF_INC) +OPDEF(JSOP_DECLOCAL, 204,"declocal", NULL, 3, 0, 1, 15, JOF_LOCAL|JOF_NAME|JOF_DEC) +OPDEF(JSOP_LOCALINC, 205,"localinc", NULL, 3, 0, 1, 15, JOF_LOCAL|JOF_NAME|JOF_INC|JOF_POST) +OPDEF(JSOP_LOCALDEC, 206,"localdec", NULL, 3, 0, 1, 15, JOF_LOCAL|JOF_NAME|JOF_DEC|JOF_POST) +OPDEF(JSOP_FORLOCAL, 207,"forlocal", NULL, 3, 0, 1, 19, JOF_LOCAL|JOF_NAME|JOF_FOR) + +/* + * Iterator, generator, and array comprehension support. + */ +OPDEF(JSOP_STARTITER, 208,"startiter", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_ENDITER, 209,"enditer", NULL, 1, 1, 0, 0, JOF_BYTE) +OPDEF(JSOP_GENERATOR, 210,"generator", NULL, 1, 0, 0, 0, JOF_BYTE) +OPDEF(JSOP_YIELD, 211,"yield", NULL, 1, 1, 1, 1, JOF_BYTE) +OPDEF(JSOP_ARRAYPUSH, 212,"arraypush", NULL, 3, 1, 0, 3, JOF_LOCAL) + +OPDEF(JSOP_FOREACHKEYVAL, 213,"foreachkeyval",NULL, 1, 1, 1, 0, JOF_BYTE) + +/* + * Variant of JSOP_ENUMELEM for destructuring const (const [a, b] = ...). + */ +OPDEF(JSOP_ENUMCONSTELEM, 214,"enumconstelem",NULL, 1, 3, 0, 3, JOF_BYTE|JOF_SET|JOF_ASSIGNING) + +/* + * Variant of JSOP_LEAVEBLOCK has a result on the stack above the locals, + * which must be moved down when the block pops. + */ +OPDEF(JSOP_LEAVEBLOCKEXPR,215,"leaveblockexpr",NULL, 3, 0, 0, 1, JOF_UINT16) diff --git a/js32/jsosdep.h b/js32/jsosdep.h new file mode 100644 index 00000000..a2661448 --- /dev/null +++ b/js32/jsosdep.h @@ -0,0 +1,115 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef jsosdep_h___ +#define jsosdep_h___ +/* + * OS (and machine, and compiler XXX) dependent information. + */ + +#if defined(XP_WIN) || defined(XP_OS2) + +#if defined(_WIN32) || defined (XP_OS2) +#define JS_HAVE_LONG_LONG +#else +#undef JS_HAVE_LONG_LONG +#endif +#endif /* XP_WIN || XP_OS2 */ + +#ifdef XP_BEOS +#define JS_HAVE_LONG_LONG +#endif + + +#ifdef XP_UNIX + +/* + * Get OS specific header information. + */ +#if defined(XP_MACOSX) || defined(DARWIN) +#define JS_HAVE_LONG_LONG + +#elif defined(AIXV3) || defined(AIX) +#define JS_HAVE_LONG_LONG + +#elif defined(BSDI) +#define JS_HAVE_LONG_LONG + +#elif defined(HPUX) +#define JS_HAVE_LONG_LONG + +#elif defined(IRIX) +#define JS_HAVE_LONG_LONG + +#elif defined(linux) +#define JS_HAVE_LONG_LONG + +#elif defined(OSF1) +#define JS_HAVE_LONG_LONG + +#elif defined(_SCO_DS) +#undef JS_HAVE_LONG_LONG + +#elif defined(SOLARIS) +#define JS_HAVE_LONG_LONG + +#elif defined(FREEBSD) +#define JS_HAVE_LONG_LONG + +#elif defined(SUNOS4) +#undef JS_HAVE_LONG_LONG + +/* +** Missing function prototypes +*/ + +extern void *sbrk(int); + +#elif defined(UNIXWARE) +#undef JS_HAVE_LONG_LONG + +#elif defined(VMS) && defined(__ALPHA) +#define JS_HAVE_LONG_LONG + +#endif + +#endif /* XP_UNIX */ + +#endif /* jsosdep_h___ */ + diff --git a/js32/jsotypes.h b/js32/jsotypes.h new file mode 100644 index 00000000..38d72869 --- /dev/null +++ b/js32/jsotypes.h @@ -0,0 +1,202 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* + * This section typedefs the old 'native' types to the new PRs. + * These definitions are scheduled to be eliminated at the earliest + * possible time. The NSPR API is implemented and documented using + * the new definitions. + */ + +/* + * Note that we test for PROTYPES_H, not JSOTYPES_H. This is to avoid + * double-definitions of scalar types such as uint32, if NSPR's + * protypes.h is also included. + */ +#ifndef PROTYPES_H +#define PROTYPES_H + +#ifdef XP_BEOS +/* BeOS defines most int types in SupportDefs.h (int8, uint8, int16, + * uint16, int32, uint32, int64, uint64), so in the interest of + * not conflicting with other definitions elsewhere we have to skip the + * #ifdef jungle below, duplicate some definitions, and do our stuff. + */ +#include + +typedef JSUintn uintn; +#ifndef _XP_Core_ +typedef JSIntn intn; +#endif + +#else + +/* SVR4 typedef of uint is commonly found on UNIX machines. */ +#if defined(XP_UNIX) && !defined(__QNXNTO__) +#include +#else +typedef JSUintn uint; +#endif + +typedef JSUintn uintn; +typedef JSUint64 uint64; +#if !defined(_WIN32) && !defined(XP_OS2) +typedef JSUint32 uint32; +#else +typedef unsigned long uint32; +#endif +typedef JSUint16 uint16; +typedef JSUint8 uint8; + +#ifndef _XP_Core_ +typedef JSIntn intn; +#endif + +/* + * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h, a very + * common header file) defines the types int8, int16, int32, and int64. + * So we don't define these four types here to avoid conflicts in case + * the code also includes sys/types.h. + */ +#if defined(AIX) && defined(HAVE_SYS_INTTYPES_H) +#include +#else +typedef JSInt64 int64; + +/* /usr/include/model.h on HP-UX defines int8, int16, and int32 */ +#ifdef HPUX +#include +#else +#if !defined(_WIN32) && !defined(XP_OS2) +typedef JSInt32 int32; +#else +typedef long int32; +#endif +typedef JSInt16 int16; +typedef JSInt8 int8; +#endif /* HPUX */ +#endif /* AIX && HAVE_SYS_INTTYPES_H */ + +#endif /* XP_BEOS */ + +typedef JSFloat64 float64; + +/* Re: jsbit.h */ +#define TEST_BIT JS_TEST_BIT +#define SET_BIT JS_SET_BIT +#define CLEAR_BIT JS_CLEAR_BIT + +/* Re: prarena.h->plarena.h */ +#define PRArena PLArena +#define PRArenaPool PLArenaPool +#define PRArenaStats PLArenaStats +#define PR_ARENA_ALIGN PL_ARENA_ALIGN +#define PR_INIT_ARENA_POOL PL_INIT_ARENA_POOL +#define PR_ARENA_ALLOCATE PL_ARENA_ALLOCATE +#define PR_ARENA_GROW PL_ARENA_GROW +#define PR_ARENA_MARK PL_ARENA_MARK +#define PR_CLEAR_UNUSED PL_CLEAR_UNUSED +#define PR_CLEAR_ARENA PL_CLEAR_ARENA +#define PR_ARENA_RELEASE PL_ARENA_RELEASE +#define PR_COUNT_ARENA PL_COUNT_ARENA +#define PR_ARENA_DESTROY PL_ARENA_DESTROY +#define PR_InitArenaPool PL_InitArenaPool +#define PR_FreeArenaPool PL_FreeArenaPool +#define PR_FinishArenaPool PL_FinishArenaPool +#define PR_CompactArenaPool PL_CompactArenaPool +#define PR_ArenaFinish PL_ArenaFinish +#define PR_ArenaAllocate PL_ArenaAllocate +#define PR_ArenaGrow PL_ArenaGrow +#define PR_ArenaRelease PL_ArenaRelease +#define PR_ArenaCountAllocation PL_ArenaCountAllocation +#define PR_ArenaCountInplaceGrowth PL_ArenaCountInplaceGrowth +#define PR_ArenaCountGrowth PL_ArenaCountGrowth +#define PR_ArenaCountRelease PL_ArenaCountRelease +#define PR_ArenaCountRetract PL_ArenaCountRetract + +/* Re: prevent.h->plevent.h */ +#define PREvent PLEvent +#define PREventQueue PLEventQueue +#define PR_CreateEventQueue PL_CreateEventQueue +#define PR_DestroyEventQueue PL_DestroyEventQueue +#define PR_GetEventQueueMonitor PL_GetEventQueueMonitor +#define PR_ENTER_EVENT_QUEUE_MONITOR PL_ENTER_EVENT_QUEUE_MONITOR +#define PR_EXIT_EVENT_QUEUE_MONITOR PL_EXIT_EVENT_QUEUE_MONITOR +#define PR_PostEvent PL_PostEvent +#define PR_PostSynchronousEvent PL_PostSynchronousEvent +#define PR_GetEvent PL_GetEvent +#define PR_EventAvailable PL_EventAvailable +#define PREventFunProc PLEventFunProc +#define PR_MapEvents PL_MapEvents +#define PR_RevokeEvents PL_RevokeEvents +#define PR_ProcessPendingEvents PL_ProcessPendingEvents +#define PR_WaitForEvent PL_WaitForEvent +#define PR_EventLoop PL_EventLoop +#define PR_GetEventQueueSelectFD PL_GetEventQueueSelectFD +#define PRHandleEventProc PLHandleEventProc +#define PRDestroyEventProc PLDestroyEventProc +#define PR_InitEvent PL_InitEvent +#define PR_GetEventOwner PL_GetEventOwner +#define PR_HandleEvent PL_HandleEvent +#define PR_DestroyEvent PL_DestroyEvent +#define PR_DequeueEvent PL_DequeueEvent +#define PR_GetMainEventQueue PL_GetMainEventQueue + +/* Re: prhash.h->plhash.h */ +#define PRHashEntry PLHashEntry +#define PRHashTable PLHashTable +#define PRHashNumber PLHashNumber +#define PRHashFunction PLHashFunction +#define PRHashComparator PLHashComparator +#define PRHashEnumerator PLHashEnumerator +#define PRHashAllocOps PLHashAllocOps +#define PR_NewHashTable PL_NewHashTable +#define PR_HashTableDestroy PL_HashTableDestroy +#define PR_HashTableRawLookup PL_HashTableRawLookup +#define PR_HashTableRawAdd PL_HashTableRawAdd +#define PR_HashTableRawRemove PL_HashTableRawRemove +#define PR_HashTableAdd PL_HashTableAdd +#define PR_HashTableRemove PL_HashTableRemove +#define PR_HashTableEnumerateEntries PL_HashTableEnumerateEntries +#define PR_HashTableLookup PL_HashTableLookup +#define PR_HashTableDump PL_HashTableDump +#define PR_HashString PL_HashString +#define PR_CompareStrings PL_CompareStrings +#define PR_CompareValues PL_CompareValues + +#endif /* !defined(PROTYPES_H) */ diff --git a/js32/jsproto.tbl b/js32/jsproto.tbl new file mode 100644 index 00000000..8966b930 --- /dev/null +++ b/js32/jsproto.tbl @@ -0,0 +1,116 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set sw=4 ts=8 et tw=80 ft=c: + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is SpiderMonkey 1.7 work in progress, released + * February 14, 2006. + * + * The Initial Developer of the Original Code is + * Brendan Eich + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "jsconfig.h" + +#if JS_HAS_SCRIPT_OBJECT +# define SCRIPT_INIT js_InitScriptClass +#else +# define SCRIPT_INIT js_InitNullClass +#endif + +#if JS_HAS_XML_SUPPORT +# define XML_INIT js_InitXMLClass +# define NAMESPACE_INIT js_InitNamespaceClass +# define QNAME_INIT js_InitQNameClass +# define ANYNAME_INIT js_InitAnyNameClass +# define ATTRIBUTE_INIT js_InitAttributeNameClass +#else +# define XML_INIT js_InitNullClass +# define NAMESPACE_INIT js_InitNullClass +# define QNAME_INIT js_InitNullClass +# define ANYNAME_INIT js_InitNullClass +# define ATTRIBUTE_INIT js_InitNullClass +#endif + +#if JS_HAS_GENERATORS +# define GENERATOR_INIT js_InitIteratorClasses +#else +# define GENERATOR_INIT js_InitNullClass +#endif + +#if JS_HAS_FILE_OBJECT +# define FILE_INIT js_InitFileClass +#else +# define FILE_INIT js_InitNullClass +#endif + +/* + * Enumerator codes in the second column must not change -- they are part of + * the JS XDR API. + */ +JS_PROTO(Null, 0, js_InitNullClass) +JS_PROTO(Object, 1, js_InitFunctionAndObjectClasses) +JS_PROTO(Function, 2, js_InitFunctionAndObjectClasses) +JS_PROTO(Array, 3, js_InitArrayClass) +JS_PROTO(Boolean, 4, js_InitBooleanClass) +JS_PROTO(Call, 5, js_InitCallClass) +JS_PROTO(Date, 6, js_InitDateClass) +JS_PROTO(Math, 7, js_InitMathClass) +JS_PROTO(Number, 8, js_InitNumberClass) +JS_PROTO(String, 9, js_InitStringClass) +JS_PROTO(RegExp, 10, js_InitRegExpClass) +JS_PROTO(Script, 11, SCRIPT_INIT) +JS_PROTO(XML, 12, XML_INIT) +JS_PROTO(Namespace, 13, NAMESPACE_INIT) +JS_PROTO(QName, 14, QNAME_INIT) +JS_PROTO(AnyName, 15, ANYNAME_INIT) +JS_PROTO(AttributeName, 16, ATTRIBUTE_INIT) +JS_PROTO(Error, 17, js_InitExceptionClasses) +JS_PROTO(InternalError, 18, js_InitExceptionClasses) +JS_PROTO(EvalError, 19, js_InitExceptionClasses) +JS_PROTO(RangeError, 20, js_InitExceptionClasses) +JS_PROTO(ReferenceError, 21, js_InitExceptionClasses) +JS_PROTO(SyntaxError, 22, js_InitExceptionClasses) +JS_PROTO(TypeError, 23, js_InitExceptionClasses) +JS_PROTO(URIError, 24, js_InitExceptionClasses) +JS_PROTO(Generator, 25, GENERATOR_INIT) +JS_PROTO(Iterator, 26, js_InitIteratorClasses) +JS_PROTO(StopIteration, 27, js_InitIteratorClasses) +JS_PROTO(UnusedProto28, 28, js_InitNullClass) +JS_PROTO(File, 29, FILE_INIT) +JS_PROTO(Block, 30, js_InitBlockClass) + +#undef SCRIPT_INIT +#undef XML_INIT +#undef NAMESPACE_INIT +#undef QNAME_INIT +#undef ANYNAME_INIT +#undef ATTRIBUTE_INIT +#undef GENERATOR_INIT +#undef FILE_INIT diff --git a/js32/jsprvtd.h b/js32/jsprvtd.h new file mode 100644 index 00000000..f71b9a50 --- /dev/null +++ b/js32/jsprvtd.h @@ -0,0 +1,202 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef jsprvtd_h___ +#define jsprvtd_h___ +/* + * JS private typename definitions. + * + * This header is included only in other .h files, for convenience and for + * simplicity of type naming. The alternative for structures is to use tags, + * which are named the same as their typedef names (legal in C/C++, and less + * noisy than suffixing the typedef name with "Struct" or "Str"). Instead, + * all .h files that include this file may use the same typedef name, whether + * declaring a pointer to struct type, or defining a member of struct type. + * + * A few fundamental scalar types are defined here too. Neither the scalar + * nor the struct typedefs should change much, therefore the nearly-global + * make dependency induced by this file should not prove painful. + */ + +#include "jspubtd.h" + +/* Internal identifier (jsid) macros. */ +#define JSID_ATOM 0x0 +#define JSID_INT 0x1 +#define JSID_OBJECT 0x2 +#define JSID_TAGMASK 0x3 +#define JSID_TAG(id) ((id) & JSID_TAGMASK) +#define JSID_SETTAG(id,t) ((id) | (t)) +#define JSID_CLRTAG(id) ((id) & ~(jsid)JSID_TAGMASK) + +#define JSID_IS_ATOM(id) (JSID_TAG(id) == JSID_ATOM) +#define JSID_TO_ATOM(id) ((JSAtom *)(id)) +#define ATOM_TO_JSID(atom) ((jsid)(atom)) +#define ATOM_JSID_TO_JSVAL(id) ATOM_KEY(JSID_TO_ATOM(id)) + +#define JSID_IS_INT(id) ((id) & JSID_INT) +#define JSID_TO_INT(id) ((jsint)(id) >> 1) +#define INT_TO_JSID(i) (((jsint)(i) << 1) | JSID_INT) +#define INT_JSID_TO_JSVAL(id) (id) +#define INT_JSVAL_TO_JSID(v) (v) + +#define JSID_IS_OBJECT(id) (JSID_TAG(id) == JSID_OBJECT) +#define JSID_TO_OBJECT(id) ((JSObject *) JSID_CLRTAG(id)) +#define OBJECT_TO_JSID(obj) ((jsid)(obj) | JSID_OBJECT) +#define OBJECT_JSID_TO_JSVAL(id) OBJECT_TO_JSVAL(JSID_CLRTAG(id)) +#define OBJECT_JSVAL_TO_JSID(v) OBJECT_TO_JSID(JSVAL_TO_OBJECT(v)) + +/* Scalar typedefs. */ +typedef uint8 jsbytecode; +typedef uint8 jssrcnote; +typedef uint32 jsatomid; + +/* Struct typedefs. */ +typedef struct JSArgumentFormatMap JSArgumentFormatMap; +typedef struct JSCodeGenerator JSCodeGenerator; +typedef struct JSDependentString JSDependentString; +typedef struct JSGCThing JSGCThing; +typedef struct JSGenerator JSGenerator; +typedef struct JSParseNode JSParseNode; +typedef struct JSSharpObjectMap JSSharpObjectMap; +typedef struct JSThread JSThread; +typedef struct JSToken JSToken; +typedef struct JSTokenPos JSTokenPos; +typedef struct JSTokenPtr JSTokenPtr; +typedef struct JSTokenStream JSTokenStream; +typedef struct JSTreeContext JSTreeContext; +typedef struct JSTryNote JSTryNote; + +/* Friend "Advanced API" typedefs. */ +typedef struct JSAtom JSAtom; +typedef struct JSAtomList JSAtomList; +typedef struct JSAtomListElement JSAtomListElement; +typedef struct JSAtomMap JSAtomMap; +typedef struct JSAtomState JSAtomState; +typedef struct JSCodeSpec JSCodeSpec; +typedef struct JSPrinter JSPrinter; +typedef struct JSRegExp JSRegExp; +typedef struct JSRegExpStatics JSRegExpStatics; +typedef struct JSScope JSScope; +typedef struct JSScopeOps JSScopeOps; +typedef struct JSScopeProperty JSScopeProperty; +typedef struct JSStackHeader JSStackHeader; +typedef struct JSStringBuffer JSStringBuffer; +typedef struct JSSubString JSSubString; +typedef struct JSXML JSXML; +typedef struct JSXMLNamespace JSXMLNamespace; +typedef struct JSXMLQName JSXMLQName; +typedef struct JSXMLArray JSXMLArray; +typedef struct JSXMLArrayCursor JSXMLArrayCursor; + +/* "Friend" types used by jscntxt.h and jsdbgapi.h. */ +typedef enum JSTrapStatus { + JSTRAP_ERROR, + JSTRAP_CONTINUE, + JSTRAP_RETURN, + JSTRAP_THROW, + JSTRAP_LIMIT +} JSTrapStatus; + +typedef JSTrapStatus +(* JS_DLL_CALLBACK JSTrapHandler)(JSContext *cx, JSScript *script, + jsbytecode *pc, jsval *rval, void *closure); + +typedef JSBool +(* JS_DLL_CALLBACK JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsval id, + jsval old, jsval *newp, void *closure); + +/* called just after script creation */ +typedef void +(* JS_DLL_CALLBACK JSNewScriptHook)(JSContext *cx, + const char *filename, /* URL of script */ + uintN lineno, /* first line */ + JSScript *script, + JSFunction *fun, + void *callerdata); + +/* called just before script destruction */ +typedef void +(* JS_DLL_CALLBACK JSDestroyScriptHook)(JSContext *cx, + JSScript *script, + void *callerdata); + +typedef void +(* JS_DLL_CALLBACK JSSourceHandler)(const char *filename, uintN lineno, + jschar *str, size_t length, + void **listenerTSData, void *closure); + +/* + * This hook captures high level script execution and function calls (JS or + * native). It is used by JS_SetExecuteHook to hook top level scripts and by + * JS_SetCallHook to hook function calls. It will get called twice per script + * or function call: just before execution begins and just after it finishes. + * In both cases the 'current' frame is that of the executing code. + * + * The 'before' param is JS_TRUE for the hook invocation before the execution + * and JS_FALSE for the invocation after the code has run. + * + * The 'ok' param is significant only on the post execution invocation to + * signify whether or not the code completed 'normally'. + * + * The 'closure' param is as passed to JS_SetExecuteHook or JS_SetCallHook + * for the 'before'invocation, but is whatever value is returned from that + * invocation for the 'after' invocation. Thus, the hook implementor *could* + * allocate a structure in the 'before' invocation and return a pointer to that + * structure. The pointer would then be handed to the hook for the 'after' + * invocation. Alternately, the 'before' could just return the same value as + * in 'closure' to cause the 'after' invocation to be called with the same + * 'closure' value as the 'before'. + * + * Returning NULL in the 'before' hook will cause the 'after' hook *not* to + * be called. + */ +typedef void * +(* JS_DLL_CALLBACK JSInterpreterHook)(JSContext *cx, JSStackFrame *fp, JSBool before, + JSBool *ok, void *closure); + +typedef void +(* JS_DLL_CALLBACK JSObjectHook)(JSContext *cx, JSObject *obj, JSBool isNew, + void *closure); + +typedef JSBool +(* JS_DLL_CALLBACK JSDebugErrorHook)(JSContext *cx, const char *message, + JSErrorReport *report, void *closure); + +#endif /* jsprvtd_h___ */ diff --git a/js32/jspubtd.h b/js32/jspubtd.h new file mode 100644 index 00000000..4e8c92a6 --- /dev/null +++ b/js32/jspubtd.h @@ -0,0 +1,667 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#ifndef jspubtd_h___ +#define jspubtd_h___ +/* + * JS public API typedefs. + */ +#include "jstypes.h" +#include "jscompat.h" + +JS_BEGIN_EXTERN_C + +/* Scalar typedefs. */ +typedef uint16 jschar; +typedef int32 jsint; +typedef uint32 jsuint; +typedef float64 jsdouble; +typedef jsword jsval; +typedef jsword jsid; +typedef int32 jsrefcount; /* PRInt32 if JS_THREADSAFE, see jslock.h */ + +/* + * Run-time version enumeration. See jsconfig.h for compile-time counterparts + * to these values that may be selected by the JS_VERSION macro, and tested by + * #if expressions. + */ +typedef enum JSVersion { + JSVERSION_1_0 = 100, + JSVERSION_1_1 = 110, + JSVERSION_1_2 = 120, + JSVERSION_1_3 = 130, + JSVERSION_1_4 = 140, + JSVERSION_ECMA_3 = 148, + JSVERSION_1_5 = 150, + JSVERSION_1_6 = 160, + JSVERSION_1_7 = 170, + JSVERSION_DEFAULT = 0, + JSVERSION_UNKNOWN = -1 +} JSVersion; + +#define JSVERSION_IS_ECMA(version) \ + ((version) == JSVERSION_DEFAULT || (version) >= JSVERSION_1_3) + +/* Result of typeof operator enumeration. */ +typedef enum JSType { + JSTYPE_VOID, /* undefined */ + JSTYPE_OBJECT, /* object */ + JSTYPE_FUNCTION, /* function */ + JSTYPE_STRING, /* string */ + JSTYPE_NUMBER, /* number */ + JSTYPE_BOOLEAN, /* boolean */ + JSTYPE_NULL, /* null */ + JSTYPE_XML, /* xml object */ + JSTYPE_LIMIT +} JSType; + +/* Dense index into cached prototypes and class atoms for standard objects. */ +typedef enum JSProtoKey { +#define JS_PROTO(name,code,init) JSProto_##name = code, +#include "jsproto.tbl" +#undef JS_PROTO + JSProto_LIMIT +} JSProtoKey; + +/* JSObjectOps.checkAccess mode enumeration. */ +typedef enum JSAccessMode { + JSACC_PROTO = 0, /* XXXbe redundant w.r.t. id */ + JSACC_PARENT = 1, /* XXXbe redundant w.r.t. id */ + JSACC_IMPORT = 2, /* import foo.bar */ + JSACC_WATCH = 3, /* a watchpoint on object foo for id 'bar' */ + JSACC_READ = 4, /* a "get" of foo.bar */ + JSACC_WRITE = 8, /* a "set" of foo.bar = baz */ + JSACC_LIMIT +} JSAccessMode; + +#define JSACC_TYPEMASK (JSACC_WRITE - 1) + +/* + * This enum type is used to control the behavior of a JSObject property + * iterator function that has type JSNewEnumerate. + */ +typedef enum JSIterateOp { + JSENUMERATE_INIT, /* Create new iterator state */ + JSENUMERATE_NEXT, /* Iterate once */ + JSENUMERATE_DESTROY /* Destroy iterator state */ +} JSIterateOp; + +/* Struct typedefs. */ +typedef struct JSClass JSClass; +typedef struct JSExtendedClass JSExtendedClass; +typedef struct JSConstDoubleSpec JSConstDoubleSpec; +typedef struct JSContext JSContext; +typedef struct JSErrorReport JSErrorReport; +typedef struct JSFunction JSFunction; +typedef struct JSFunctionSpec JSFunctionSpec; +typedef struct JSIdArray JSIdArray; +typedef struct JSProperty JSProperty; +typedef struct JSPropertySpec JSPropertySpec; +typedef struct JSObject JSObject; +typedef struct JSObjectMap JSObjectMap; +typedef struct JSObjectOps JSObjectOps; +typedef struct JSXMLObjectOps JSXMLObjectOps; +typedef struct JSRuntime JSRuntime; +typedef struct JSRuntime JSTaskState; /* XXX deprecated name */ +typedef struct JSScript JSScript; +typedef struct JSStackFrame JSStackFrame; +typedef struct JSString JSString; +typedef struct JSXDRState JSXDRState; +typedef struct JSExceptionState JSExceptionState; +typedef struct JSLocaleCallbacks JSLocaleCallbacks; + +/* JSClass (and JSObjectOps where appropriate) function pointer typedefs. */ + +/* + * Add, delete, get or set a property named by id in obj. Note the jsval id + * type -- id may be a string (Unicode property identifier) or an int (element + * index). The *vp out parameter, on success, is the new property value after + * an add, get, or set. After a successful delete, *vp is JSVAL_FALSE iff + * obj[id] can't be deleted (because it's permanent). + */ +typedef JSBool +(* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id, + jsval *vp); + +/* + * This function type is used for callbacks that enumerate the properties of + * a JSObject. The behavior depends on the value of enum_op: + * + * JSENUMERATE_INIT + * A new, opaque iterator state should be allocated and stored in *statep. + * (You can use PRIVATE_TO_JSVAL() to tag the pointer to be stored). + * + * The number of properties that will be enumerated should be returned as + * an integer jsval in *idp, if idp is non-null, and provided the number of + * enumerable properties is known. If idp is non-null and the number of + * enumerable properties can't be computed in advance, *idp should be set + * to JSVAL_ZERO. + * + * JSENUMERATE_NEXT + * A previously allocated opaque iterator state is passed in via statep. + * Return the next jsid in the iteration using *idp. The opaque iterator + * state pointed at by statep is destroyed and *statep is set to JSVAL_NULL + * if there are no properties left to enumerate. + * + * JSENUMERATE_DESTROY + * Destroy the opaque iterator state previously allocated in *statep by a + * call to this function when enum_op was JSENUMERATE_INIT. + * + * The return value is used to indicate success, with a value of JS_FALSE + * indicating failure. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSNewEnumerateOp)(JSContext *cx, JSObject *obj, + JSIterateOp enum_op, + jsval *statep, jsid *idp); + +/* + * The old-style JSClass.enumerate op should define all lazy properties not + * yet reflected in obj. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSEnumerateOp)(JSContext *cx, JSObject *obj); + +/* + * Resolve a lazy property named by id in obj by defining it directly in obj. + * Lazy properties are those reflected from some peer native property space + * (e.g., the DOM attributes for a given node reflected as obj) on demand. + * + * JS looks for a property in an object, and if not found, tries to resolve + * the given id. If resolve succeeds, the engine looks again in case resolve + * defined obj[id]. If no such property exists directly in obj, the process + * is repeated with obj's prototype, etc. + * + * NB: JSNewResolveOp provides a cheaper way to resolve lazy properties. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSResolveOp)(JSContext *cx, JSObject *obj, jsval id); + +/* + * Like JSResolveOp, but flags provide contextual information as follows: + * + * JSRESOLVE_QUALIFIED a qualified property id: obj.id or obj[id], not id + * JSRESOLVE_ASSIGNING obj[id] is on the left-hand side of an assignment + * JSRESOLVE_DETECTING 'if (o.p)...' or similar detection opcode sequence + * JSRESOLVE_DECLARING var, const, or function prolog declaration opcode + * JSRESOLVE_CLASSNAME class name used when constructing + * + * The *objp out parameter, on success, should be null to indicate that id + * was not resolved; and non-null, referring to obj or one of its prototypes, + * if id was resolved. + * + * This hook instead of JSResolveOp is called via the JSClass.resolve member + * if JSCLASS_NEW_RESOLVE is set in JSClass.flags. + * + * Setting JSCLASS_NEW_RESOLVE and JSCLASS_NEW_RESOLVE_GETS_START further + * extends this hook by passing in the starting object on the prototype chain + * via *objp. Thus a resolve hook implementation may define the property id + * being resolved in the object in which the id was first sought, rather than + * in a prototype object whose class led to the resolve hook being called. + * + * When using JSCLASS_NEW_RESOLVE_GETS_START, the resolve hook must therefore + * null *objp to signify "not resolved". With only JSCLASS_NEW_RESOLVE and no + * JSCLASS_NEW_RESOLVE_GETS_START, the hook can assume *objp is null on entry. + * This is not good practice, but enough existing hook implementations count + * on it that we can't break compatibility by passing the starting object in + * *objp without a new JSClass flag. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSNewResolveOp)(JSContext *cx, JSObject *obj, jsval id, + uintN flags, JSObject **objp); + +/* + * Convert obj to the given type, returning true with the resulting value in + * *vp on success, and returning false on error or exception. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSConvertOp)(JSContext *cx, JSObject *obj, JSType type, + jsval *vp); + +/* + * Finalize obj, which the garbage collector has determined to be unreachable + * from other live objects or from GC roots. Obviously, finalizers must never + * store a reference to obj. + */ +typedef void +(* JS_DLL_CALLBACK JSFinalizeOp)(JSContext *cx, JSObject *obj); + +/* + * Used by JS_AddExternalStringFinalizer and JS_RemoveExternalStringFinalizer + * to extend and reduce the set of string types finalized by the GC. + */ +typedef void +(* JS_DLL_CALLBACK JSStringFinalizeOp)(JSContext *cx, JSString *str); + +/* + * The signature for JSClass.getObjectOps, used by JS_NewObject's internals + * to discover the set of high-level object operations to use for new objects + * of the given class. All native objects have a JSClass, which is stored as + * a private (int-tagged) pointer in obj->slots[JSSLOT_CLASS]. In contrast, + * all native and host objects have a JSObjectMap at obj->map, which may be + * shared among a number of objects, and which contains the JSObjectOps *ops + * pointer used to dispatch object operations from API calls. + * + * Thus JSClass (which pre-dates JSObjectOps in the API) provides a low-level + * interface to class-specific code and data, while JSObjectOps allows for a + * higher level of operation, which does not use the object's class except to + * find the class's JSObjectOps struct, by calling clasp->getObjectOps, and to + * finalize the object. + * + * If this seems backwards, that's because it is! API compatibility requires + * a JSClass *clasp parameter to JS_NewObject, etc. Most host objects do not + * need to implement the larger JSObjectOps, and can share the common JSScope + * code and data used by the native (js_ObjectOps, see jsobj.c) ops. + * + * Further extension to preserve API compatibility: if this function returns + * a pointer to JSXMLObjectOps.base, not to JSObjectOps, then the engine calls + * extended hooks needed for E4X. + */ +typedef JSObjectOps * +(* JS_DLL_CALLBACK JSGetObjectOps)(JSContext *cx, JSClass *clasp); + +/* + * JSClass.checkAccess type: check whether obj[id] may be accessed per mode, + * returning false on error/exception, true on success with obj[id]'s last-got + * value in *vp, and its attributes in *attrsp. As for JSPropertyOp above, id + * is either a string or an int jsval. + * + * See JSCheckAccessIdOp, below, for the JSObjectOps counterpart, which takes + * a jsid (a tagged int or aligned, unique identifier pointer) rather than a + * jsval. The native js_ObjectOps.checkAccess simply forwards to the object's + * clasp->checkAccess, so that both JSClass and JSObjectOps implementors may + * specialize access checks. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSCheckAccessOp)(JSContext *cx, JSObject *obj, jsval id, + JSAccessMode mode, jsval *vp); + +/* + * Encode or decode an object, given an XDR state record representing external + * data. See jsxdrapi.h. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSXDRObjectOp)(JSXDRState *xdr, JSObject **objp); + +/* + * Check whether v is an instance of obj. Return false on error or exception, + * true on success with JS_TRUE in *bp if v is an instance of obj, JS_FALSE in + * *bp otherwise. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSHasInstanceOp)(JSContext *cx, JSObject *obj, jsval v, + JSBool *bp); + +/* + * Function type for JSClass.mark and JSObjectOps.mark, called from the GC to + * scan live GC-things reachable from obj's private data structure. For each + * such thing, a mark implementation must call + * + * JS_MarkGCThing(cx, thing, name, arg); + * + * The trailing name and arg parameters are used for GC_MARK_DEBUG-mode heap + * dumping and ref-path tracing. The mark function should pass a (typically + * literal) string naming the private data member for name, and it must pass + * the opaque arg parameter through from its caller. + * + * For the JSObjectOps.mark hook, the return value is the number of slots at + * obj->slots to scan. For JSClass.mark, the return value is ignored. + * + * NB: JSMarkOp implementations cannot allocate new GC-things (JS_NewObject + * called from a mark function will fail silently, e.g.). + */ +typedef uint32 +(* JS_DLL_CALLBACK JSMarkOp)(JSContext *cx, JSObject *obj, void *arg); + +/* + * The optional JSClass.reserveSlots hook allows a class to make computed + * per-instance object slots reservations, in addition to or instead of using + * JSCLASS_HAS_RESERVED_SLOTS(n) in the JSClass.flags initializer to reserve + * a constant-per-class number of slots. Implementations of this hook should + * return the number of slots to reserve, not including any reserved by using + * JSCLASS_HAS_RESERVED_SLOTS(n) in JSClass.flags. + * + * NB: called with obj locked by the JSObjectOps-specific mutual exclusion + * mechanism appropriate for obj, so don't nest other operations that might + * also lock obj. + */ +typedef uint32 +(* JS_DLL_CALLBACK JSReserveSlotsOp)(JSContext *cx, JSObject *obj); + +/* JSObjectOps function pointer typedefs. */ + +/* + * Create a new subclass of JSObjectMap (see jsobj.h), with the nrefs and ops + * members initialized from the same-named parameters, and with the nslots and + * freeslot members initialized according to ops and clasp. Return null on + * error, non-null on success. + * + * JSObjectMaps are reference-counted by generic code in the engine. Usually, + * the nrefs parameter to JSObjectOps.newObjectMap will be 1, to count the ref + * returned to the caller on success. After a successful construction, some + * number of js_HoldObjectMap and js_DropObjectMap calls ensue. When nrefs + * reaches 0 due to a js_DropObjectMap call, JSObjectOps.destroyObjectMap will + * be called to dispose of the map. + */ +typedef JSObjectMap * +(* JS_DLL_CALLBACK JSNewObjectMapOp)(JSContext *cx, jsrefcount nrefs, + JSObjectOps *ops, JSClass *clasp, + JSObject *obj); + +/* + * Generic type for an infallible JSObjectMap operation, used currently by + * JSObjectOps.destroyObjectMap. + */ +typedef void +(* JS_DLL_CALLBACK JSObjectMapOp)(JSContext *cx, JSObjectMap *map); + +/* + * Look for id in obj and its prototype chain, returning false on error or + * exception, true on success. On success, return null in *propp if id was + * not found. If id was found, return the first object searching from obj + * along its prototype chain in which id names a direct property in *objp, and + * return a non-null, opaque property pointer in *propp. + * + * If JSLookupPropOp succeeds and returns with *propp non-null, that pointer + * may be passed as the prop parameter to a JSAttributesOp, as a short-cut + * that bypasses id re-lookup. In any case, a non-null *propp result after a + * successful lookup must be dropped via JSObjectOps.dropProperty. + * + * NB: successful return with non-null *propp means the implementation may + * have locked *objp and added a reference count associated with *propp, so + * callers should not risk deadlock by nesting or interleaving other lookups + * or any obj-bearing ops before dropping *propp. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSLookupPropOp)(JSContext *cx, JSObject *obj, jsid id, + JSObject **objp, JSProperty **propp); + +/* + * Define obj[id], a direct property of obj named id, having the given initial + * value, with the specified getter, setter, and attributes. If the propp out + * param is non-null, *propp on successful return contains an opaque property + * pointer usable as a speedup hint with JSAttributesOp. But note that propp + * may be null, indicating that the caller is not interested in recovering an + * opaque pointer to the newly-defined property. + * + * If propp is non-null and JSDefinePropOp succeeds, its caller must be sure + * to drop *propp using JSObjectOps.dropProperty in short order, just as with + * JSLookupPropOp. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSDefinePropOp)(JSContext *cx, JSObject *obj, + jsid id, jsval value, + JSPropertyOp getter, JSPropertyOp setter, + uintN attrs, JSProperty **propp); + +/* + * Get, set, or delete obj[id], returning false on error or exception, true + * on success. If getting or setting, the new value is returned in *vp on + * success. If deleting without error, *vp will be JSVAL_FALSE if obj[id] is + * permanent, and JSVAL_TRUE if id named a direct property of obj that was in + * fact deleted, or if id names no direct property of obj (id could name a + * prototype property, or no property in obj or its prototype chain). + */ +typedef JSBool +(* JS_DLL_CALLBACK JSPropertyIdOp)(JSContext *cx, JSObject *obj, jsid id, + jsval *vp); + +/* + * Get or set attributes of the property obj[id]. Return false on error or + * exception, true with current attributes in *attrsp. If prop is non-null, + * it must come from the *propp out parameter of a prior JSDefinePropOp or + * JSLookupPropOp call. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSAttributesOp)(JSContext *cx, JSObject *obj, jsid id, + JSProperty *prop, uintN *attrsp); + +/* + * JSObjectOps.checkAccess type: check whether obj[id] may be accessed per + * mode, returning false on error/exception, true on success with obj[id]'s + * last-got value in *vp, and its attributes in *attrsp. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSCheckAccessIdOp)(JSContext *cx, JSObject *obj, jsid id, + JSAccessMode mode, jsval *vp, + uintN *attrsp); + +/* + * A generic type for functions mapping an object to another object, or null + * if an error or exception was thrown on cx. Used by JSObjectOps.thisObject + * at present. + */ +typedef JSObject * +(* JS_DLL_CALLBACK JSObjectOp)(JSContext *cx, JSObject *obj); + +/* + * A generic type for functions taking a context, object, and property, with + * no return value. Used by JSObjectOps.dropProperty currently (see above, + * JSDefinePropOp and JSLookupPropOp, for the object-locking protocol in which + * dropProperty participates). + */ +typedef void +(* JS_DLL_CALLBACK JSPropertyRefOp)(JSContext *cx, JSObject *obj, + JSProperty *prop); + +/* + * Function type for JSObjectOps.setProto and JSObjectOps.setParent. These + * hooks must check for cycles without deadlocking, and otherwise take special + * steps. See jsobj.c, js_SetProtoOrParent, for an example. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSSetObjectSlotOp)(JSContext *cx, JSObject *obj, + uint32 slot, JSObject *pobj); + +/* + * Get and set a required slot, one that should already have been allocated. + * These operations are infallible, so required slots must be pre-allocated, + * or implementations must suppress out-of-memory errors. The native ops + * (js_ObjectOps, see jsobj.c) access slots reserved by including a call to + * the JSCLASS_HAS_RESERVED_SLOTS(n) macro in the JSClass.flags initializer. + * + * NB: the slot parameter is a zero-based index into obj->slots[], unlike the + * index parameter to the JS_GetReservedSlot and JS_SetReservedSlot API entry + * points, which is a zero-based index into the JSCLASS_RESERVED_SLOTS(clasp) + * reserved slots that come after the initial well-known slots: proto, parent, + * class, and optionally, the private data slot. + */ +typedef jsval +(* JS_DLL_CALLBACK JSGetRequiredSlotOp)(JSContext *cx, JSObject *obj, + uint32 slot); + +typedef JSBool +(* JS_DLL_CALLBACK JSSetRequiredSlotOp)(JSContext *cx, JSObject *obj, + uint32 slot, jsval v); + +typedef JSObject * +(* JS_DLL_CALLBACK JSGetMethodOp)(JSContext *cx, JSObject *obj, jsid id, + jsval *vp); + +typedef JSBool +(* JS_DLL_CALLBACK JSSetMethodOp)(JSContext *cx, JSObject *obj, jsid id, + jsval *vp); + +typedef JSBool +(* JS_DLL_CALLBACK JSEnumerateValuesOp)(JSContext *cx, JSObject *obj, + JSIterateOp enum_op, + jsval *statep, jsid *idp, jsval *vp); + +typedef JSBool +(* JS_DLL_CALLBACK JSEqualityOp)(JSContext *cx, JSObject *obj, jsval v, + JSBool *bp); + +typedef JSBool +(* JS_DLL_CALLBACK JSConcatenateOp)(JSContext *cx, JSObject *obj, jsval v, + jsval *vp); + +/* Typedef for native functions called by the JS VM. */ + +typedef JSBool +(* JS_DLL_CALLBACK JSNative)(JSContext *cx, JSObject *obj, uintN argc, + jsval *argv, jsval *rval); + +/* Callbacks and their arguments. */ + +typedef enum JSContextOp { + JSCONTEXT_NEW, + JSCONTEXT_DESTROY +} JSContextOp; + +/* + * The possible values for contextOp when the runtime calls the callback are: + * JSCONTEXT_NEW JS_NewContext succesfully created a new JSContext + * instance. The callback can initialize the instance as + * required. If the callback returns false, the instance + * will be destroyed and JS_NewContext returns null. In + * this case the callback is not called again. + * JSCONTEXT_DESTROY One of JS_DestroyContext* methods is called. The + * callback may perform its own cleanup and must always + * return true. + * Any other value For future compatibility the callback must do nothing + * and return true in this case. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSContextCallback)(JSContext *cx, uintN contextOp); + +typedef enum JSGCStatus { + JSGC_BEGIN, + JSGC_END, + JSGC_MARK_END, + JSGC_FINALIZE_END +} JSGCStatus; + +typedef JSBool +(* JS_DLL_CALLBACK JSGCCallback)(JSContext *cx, JSGCStatus status); + +typedef JSBool +(* JS_DLL_CALLBACK JSBranchCallback)(JSContext *cx, JSScript *script); + +typedef void +(* JS_DLL_CALLBACK JSErrorReporter)(JSContext *cx, const char *message, + JSErrorReport *report); + +/* + * Possible exception types. These types are part of a JSErrorFormatString + * structure. They define which error to throw in case of a runtime error. + * JSEXN_NONE marks an unthrowable error. + */ +typedef enum JSExnType { + JSEXN_NONE = -1, + JSEXN_ERR, + JSEXN_INTERNALERR, + JSEXN_EVALERR, + JSEXN_RANGEERR, + JSEXN_REFERENCEERR, + JSEXN_SYNTAXERR, + JSEXN_TYPEERR, + JSEXN_URIERR, + JSEXN_LIMIT +} JSExnType; + +typedef struct JSErrorFormatString { + /* The error format string (UTF-8 if JS_C_STRINGS_ARE_UTF8 is defined). */ + const char *format; + + /* The number of arguments to expand in the formatted error message. */ + uint16 argCount; + + /* One of the JSExnType constants above. */ + int16 exnType; +} JSErrorFormatString; + +typedef const JSErrorFormatString * +(* JS_DLL_CALLBACK JSErrorCallback)(void *userRef, const char *locale, + const uintN errorNumber); + +#ifdef va_start +#define JS_ARGUMENT_FORMATTER_DEFINED 1 + +typedef JSBool +(* JS_DLL_CALLBACK JSArgumentFormatter)(JSContext *cx, const char *format, + JSBool fromJS, jsval **vpp, + va_list *app); +#endif + +typedef JSBool +(* JS_DLL_CALLBACK JSLocaleToUpperCase)(JSContext *cx, JSString *src, + jsval *rval); + +typedef JSBool +(* JS_DLL_CALLBACK JSLocaleToLowerCase)(JSContext *cx, JSString *src, + jsval *rval); + +typedef JSBool +(* JS_DLL_CALLBACK JSLocaleCompare)(JSContext *cx, + JSString *src1, JSString *src2, + jsval *rval); + +typedef JSBool +(* JS_DLL_CALLBACK JSLocaleToUnicode)(JSContext *cx, char *src, jsval *rval); + +/* + * Security protocol types. + */ +typedef struct JSPrincipals JSPrincipals; + +/* + * XDR-encode or -decode a principals instance, based on whether xdr->mode is + * JSXDR_ENCODE, in which case *principalsp should be encoded; or JSXDR_DECODE, + * in which case implementations must return a held (via JSPRINCIPALS_HOLD), + * non-null *principalsp out parameter. Return true on success, false on any + * error, which the implementation must have reported. + */ +typedef JSBool +(* JS_DLL_CALLBACK JSPrincipalsTranscoder)(JSXDRState *xdr, + JSPrincipals **principalsp); + +/* + * Return a weak reference to the principals associated with obj, possibly via + * the immutable parent chain leading from obj to a top-level container (e.g., + * a window object in the DOM level 0). If there are no principals associated + * with obj, return null. Therefore null does not mean an error was reported; + * in no event should an error be reported or an exception be thrown by this + * callback's implementation. + */ +typedef JSPrincipals * +(* JS_DLL_CALLBACK JSObjectPrincipalsFinder)(JSContext *cx, JSObject *obj); + +JS_END_EXTERN_C + +#endif /* jspubtd_h___ */ diff --git a/js32/jstypes.h b/js32/jstypes.h new file mode 100644 index 00000000..8aca929c --- /dev/null +++ b/js32/jstypes.h @@ -0,0 +1,464 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * IBM Corp. + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* +** File: jstypes.h +** Description: Definitions of NSPR's basic types +** +** Prototypes and macros used to make up for deficiencies in ANSI environments +** that we have found. +** +** Since we do not wrap and all the other standard headers, authors +** of portable code will not know in general that they need these definitions. +** Instead of requiring these authors to find the dependent uses in their code +** and take the following steps only in those C files, we take steps once here +** for all C files. +**/ + +#ifndef jstypes_h___ +#define jstypes_h___ + +#include + +/*********************************************************************** +** MACROS: JS_EXTERN_API +** JS_EXPORT_API +** DESCRIPTION: +** These are only for externally visible routines and globals. For +** internal routines, just use "extern" for type checking and that +** will not export internal cross-file or forward-declared symbols. +** Define a macro for declaring procedures return types. We use this to +** deal with windoze specific type hackery for DLL definitions. Use +** JS_EXTERN_API when the prototype for the method is declared. Use +** JS_EXPORT_API for the implementation of the method. +** +** Example: +** in dowhim.h +** JS_EXTERN_API( void ) DoWhatIMean( void ); +** in dowhim.c +** JS_EXPORT_API( void ) DoWhatIMean( void ) { return; } +** +** +***********************************************************************/ +#ifdef WIN32 +/* These also work for __MWERKS__ */ +#define JS_EXTERN_API(__type) extern __declspec(dllexport) __type +#define JS_EXPORT_API(__type) __declspec(dllexport) __type +#define JS_EXTERN_DATA(__type) extern __declspec(dllexport) __type +#define JS_EXPORT_DATA(__type) __declspec(dllexport) __type + +#define JS_DLL_CALLBACK +#define JS_STATIC_DLL_CALLBACK(__x) static __x + +#elif defined(XP_OS2) && defined(__declspec) + +#define JS_EXTERN_API(__type) extern __declspec(dllexport) __type +#define JS_EXPORT_API(__type) __declspec(dllexport) __type +#define JS_EXTERN_DATA(__type) extern __declspec(dllexport) __type +#define JS_EXPORT_DATA(__type) __declspec(dllexport) __type + +#define JS_DLL_CALLBACK +#define JS_STATIC_DLL_CALLBACK(__x) static __x + +#elif defined(WIN16) + +#ifdef _WINDLL +#define JS_EXTERN_API(__type) extern __type _cdecl _export _loadds +#define JS_EXPORT_API(__type) __type _cdecl _export _loadds +#define JS_EXTERN_DATA(__type) extern __type _export +#define JS_EXPORT_DATA(__type) __type _export + +#define JS_DLL_CALLBACK __cdecl __loadds +#define JS_STATIC_DLL_CALLBACK(__x) static __x CALLBACK + +#else /* this must be .EXE */ +#define JS_EXTERN_API(__type) extern __type _cdecl _export +#define JS_EXPORT_API(__type) __type _cdecl _export +#define JS_EXTERN_DATA(__type) extern __type _export +#define JS_EXPORT_DATA(__type) __type _export + +#define JS_DLL_CALLBACK __cdecl __loadds +#define JS_STATIC_DLL_CALLBACK(__x) __x JS_DLL_CALLBACK +#endif /* _WINDLL */ + +#else /* Unix */ + +#ifdef HAVE_VISIBILITY_ATTRIBUTE +#define JS_EXTERNAL_VIS __attribute__((visibility ("default"))) +#else +#define JS_EXTERNAL_VIS +#endif + +#define JS_EXTERN_API(__type) extern JS_EXTERNAL_VIS __type +#define JS_EXPORT_API(__type) JS_EXTERNAL_VIS __type +#define JS_EXTERN_DATA(__type) extern JS_EXTERNAL_VIS __type +#define JS_EXPORT_DATA(__type) JS_EXTERNAL_VIS __type + +#define JS_DLL_CALLBACK +#define JS_STATIC_DLL_CALLBACK(__x) static __x + +#endif + +#ifdef _WIN32 +# if defined(__MWERKS__) || defined(__GNUC__) +# define JS_IMPORT_API(__x) __x +# else +# define JS_IMPORT_API(__x) __declspec(dllimport) __x +# endif +#elif defined(XP_OS2) && defined(__declspec) +# define JS_IMPORT_API(__x) __declspec(dllimport) __x +#else +# define JS_IMPORT_API(__x) JS_EXPORT_API (__x) +#endif + +#if defined(_WIN32) && !defined(__MWERKS__) +# define JS_IMPORT_DATA(__x) __declspec(dllimport) __x +#elif defined(XP_OS2) && defined(__declspec) +# define JS_IMPORT_DATA(__x) __declspec(dllimport) __x +#else +# define JS_IMPORT_DATA(__x) JS_EXPORT_DATA (__x) +#endif + +/* + * The linkage of JS API functions differs depending on whether the file is + * used within the JS library or not. Any source file within the JS + * interpreter should define EXPORT_JS_API whereas any client of the library + * should not. + */ +#ifdef EXPORT_JS_API +#define JS_PUBLIC_API(t) JS_EXPORT_API(t) +#define JS_PUBLIC_DATA(t) JS_EXPORT_DATA(t) +#else +#define JS_PUBLIC_API(t) JS_IMPORT_API(t) +#define JS_PUBLIC_DATA(t) JS_IMPORT_DATA(t) +#endif + +#define JS_FRIEND_API(t) JS_PUBLIC_API(t) +#define JS_FRIEND_DATA(t) JS_PUBLIC_DATA(t) + +#ifdef _WIN32 +# define JS_INLINE __inline +#elif defined(__GNUC__) +# define JS_INLINE +#else +# define JS_INLINE +#endif + +/*********************************************************************** +** MACROS: JS_BEGIN_MACRO +** JS_END_MACRO +** DESCRIPTION: +** Macro body brackets so that macros with compound statement definitions +** behave syntactically more like functions when called. +***********************************************************************/ +#define JS_BEGIN_MACRO do { +#define JS_END_MACRO } while (0) + +/*********************************************************************** +** MACROS: JS_BEGIN_EXTERN_C +** JS_END_EXTERN_C +** DESCRIPTION: +** Macro shorthands for conditional C++ extern block delimiters. +***********************************************************************/ +#ifdef __cplusplus +#define JS_BEGIN_EXTERN_C extern "C" { +#define JS_END_EXTERN_C } +#else +#define JS_BEGIN_EXTERN_C +#define JS_END_EXTERN_C +#endif + +/*********************************************************************** +** MACROS: JS_BIT +** JS_BITMASK +** DESCRIPTION: +** Bit masking macros. XXX n must be <= 31 to be portable +***********************************************************************/ +#define JS_BIT(n) ((JSUint32)1 << (n)) +#define JS_BITMASK(n) (JS_BIT(n) - 1) + +/*********************************************************************** +** MACROS: JS_PTR_TO_INT32 +** JS_PTR_TO_UINT32 +** JS_INT32_TO_PTR +** JS_UINT32_TO_PTR +** DESCRIPTION: +** Integer to pointer and pointer to integer conversion macros. +***********************************************************************/ +#define JS_PTR_TO_INT32(x) ((jsint)((char *)(x) - (char *)0)) +#define JS_PTR_TO_UINT32(x) ((jsuint)((char *)(x) - (char *)0)) +#define JS_INT32_TO_PTR(x) ((void *)((char *)0 + (jsint)(x))) +#define JS_UINT32_TO_PTR(x) ((void *)((char *)0 + (jsuint)(x))) + +/*********************************************************************** +** MACROS: JS_HOWMANY +** JS_ROUNDUP +** JS_MIN +** JS_MAX +** DESCRIPTION: +** Commonly used macros for operations on compatible types. +***********************************************************************/ +#define JS_HOWMANY(x,y) (((x)+(y)-1)/(y)) +#define JS_ROUNDUP(x,y) (JS_HOWMANY(x,y)*(y)) +#define JS_MIN(x,y) ((x)<(y)?(x):(y)) +#define JS_MAX(x,y) ((x)>(y)?(x):(y)) + +#if (defined(XP_WIN) && !defined(CROSS_COMPILE)) || defined (WINCE) +# include "jscpucfg.h" /* Use standard Mac or Windows configuration */ +#elif defined(XP_UNIX) || defined(XP_BEOS) || defined(XP_OS2) || defined(CROSS_COMPILE) +# include "jsautocfg.h" /* Use auto-detected configuration */ +# include "jsosdep.h" /* ...and platform-specific flags */ +#else +# error "Must define one of XP_BEOS, XP_OS2, XP_WIN or XP_UNIX" +#endif + +JS_BEGIN_EXTERN_C + +/************************************************************************ +** TYPES: JSUint8 +** JSInt8 +** DESCRIPTION: +** The int8 types are known to be 8 bits each. There is no type that +** is equivalent to a plain "char". +************************************************************************/ +#if JS_BYTES_PER_BYTE == 1 +typedef unsigned char JSUint8; +typedef signed char JSInt8; +#else +#error No suitable type for JSInt8/JSUint8 +#endif + +/************************************************************************ +** TYPES: JSUint16 +** JSInt16 +** DESCRIPTION: +** The int16 types are known to be 16 bits each. +************************************************************************/ +#if JS_BYTES_PER_SHORT == 2 +typedef unsigned short JSUint16; +typedef short JSInt16; +#else +#error No suitable type for JSInt16/JSUint16 +#endif + +/************************************************************************ +** TYPES: JSUint32 +** JSInt32 +** DESCRIPTION: +** The int32 types are known to be 32 bits each. +************************************************************************/ +#if JS_BYTES_PER_INT == 4 +typedef unsigned int JSUint32; +typedef int JSInt32; +#define JS_INT32(x) x +#define JS_UINT32(x) x ## U +#elif JS_BYTES_PER_LONG == 4 +typedef unsigned long JSUint32; +typedef long JSInt32; +#define JS_INT32(x) x ## L +#define JS_UINT32(x) x ## UL +#else +#error No suitable type for JSInt32/JSUint32 +#endif + +/************************************************************************ +** TYPES: JSUint64 +** JSInt64 +** DESCRIPTION: +** The int64 types are known to be 64 bits each. Care must be used when +** declaring variables of type JSUint64 or JSInt64. Different hardware +** architectures and even different compilers have varying support for +** 64 bit values. The only guaranteed portability requires the use of +** the JSLL_ macros (see jslong.h). +************************************************************************/ +#ifdef JS_HAVE_LONG_LONG +#if JS_BYTES_PER_LONG == 8 +typedef long JSInt64; +typedef unsigned long JSUint64; +#elif defined(WIN16) +typedef __int64 JSInt64; +typedef unsigned __int64 JSUint64; +#elif defined(WIN32) && !defined(__GNUC__) +typedef __int64 JSInt64; +typedef unsigned __int64 JSUint64; +#else +typedef long long JSInt64; +typedef unsigned long long JSUint64; +#endif /* JS_BYTES_PER_LONG == 8 */ +#else /* !JS_HAVE_LONG_LONG */ +typedef struct { +#ifdef IS_LITTLE_ENDIAN + JSUint32 lo, hi; +#else + JSUint32 hi, lo; +#endif +} JSInt64; +typedef JSInt64 JSUint64; +#endif /* !JS_HAVE_LONG_LONG */ + +/************************************************************************ +** TYPES: JSUintn +** JSIntn +** DESCRIPTION: +** The JSIntn types are most appropriate for automatic variables. They are +** guaranteed to be at least 16 bits, though various architectures may +** define them to be wider (e.g., 32 or even 64 bits). These types are +** never valid for fields of a structure. +************************************************************************/ +#if JS_BYTES_PER_INT >= 2 +typedef int JSIntn; +typedef unsigned int JSUintn; +#else +#error 'sizeof(int)' not sufficient for platform use +#endif + +/************************************************************************ +** TYPES: JSFloat64 +** DESCRIPTION: +** NSPR's floating point type is always 64 bits. +************************************************************************/ +typedef double JSFloat64; + +/************************************************************************ +** TYPES: JSSize +** DESCRIPTION: +** A type for representing the size of objects. +************************************************************************/ +typedef size_t JSSize; + +/************************************************************************ +** TYPES: JSPtrDiff +** DESCRIPTION: +** A type for pointer difference. Variables of this type are suitable +** for storing a pointer or pointer sutraction. +************************************************************************/ +typedef ptrdiff_t JSPtrdiff; + +/************************************************************************ +** TYPES: JSUptrdiff +** DESCRIPTION: +** A type for pointer difference. Variables of this type are suitable +** for storing a pointer or pointer sutraction. +************************************************************************/ +#if JS_BYTES_PER_WORD == 8 && JS_BYTES_PER_LONG != 8 +typedef JSUint64 JSUptrdiff; +#else +typedef unsigned long JSUptrdiff; +#endif + +/************************************************************************ +** TYPES: JSBool +** DESCRIPTION: +** Use JSBool for variables and parameter types. Use JS_FALSE and JS_TRUE +** for clarity of target type in assignments and actual arguments. Use +** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans +** just as you would C int-valued conditions. +************************************************************************/ +typedef JSIntn JSBool; +#define JS_TRUE (JSIntn)1 +#define JS_FALSE (JSIntn)0 + +/************************************************************************ +** TYPES: JSPackedBool +** DESCRIPTION: +** Use JSPackedBool within structs where bitfields are not desireable +** but minimum and consistent overhead matters. +************************************************************************/ +typedef JSUint8 JSPackedBool; + +/* +** A JSWord is an integer that is the same size as a void* +*/ +#if JS_BYTES_PER_WORD == 8 && JS_BYTES_PER_LONG != 8 +typedef JSInt64 JSWord; +typedef JSUint64 JSUword; +#else +typedef long JSWord; +typedef unsigned long JSUword; +#endif + +#include "jsotypes.h" + +/*********************************************************************** +** MACROS: JS_LIKELY +** JS_UNLIKELY +** DESCRIPTION: +** These macros allow you to give a hint to the compiler about branch +** probability so that it can better optimize. Use them like this: +** +** if (JS_LIKELY(v == 1)) { +** ... expected code path ... +** } +** +** if (JS_UNLIKELY(v == 0)) { +** ... non-expected code path ... +** } +** +***********************************************************************/ +#if defined(__GNUC__) && (__GNUC__ > 2) +#define JS_LIKELY(x) (__builtin_expect((x), 1)) +#define JS_UNLIKELY(x) (__builtin_expect((x), 0)) +#else +#define JS_LIKELY(x) (x) +#define JS_UNLIKELY(x) (x) +#endif + +/*********************************************************************** +** MACROS: JS_ARRAY_LENGTH +** JS_ARRAY_END +** DESCRIPTION: +** Macros to get the number of elements and the pointer to one past the +** last element of a C array. Use them like this: +** +** jschar buf[10], *s; +** JSString *str; +** ... +** for (s = buf; s != JS_ARRAY_END(buf); ++s) *s = ...; +** ... +** str = JS_NewStringCopyN(cx, buf, JS_ARRAY_LENGTH(buf)); +** ... +** +***********************************************************************/ + +#define JS_ARRAY_LENGTH(array) (sizeof (array) / sizeof (array)[0]) +#define JS_ARRAY_END(array) ((array) + JS_ARRAY_LENGTH(array)) + +JS_END_EXTERN_C + +#endif /* jstypes_h___ */ diff --git a/js32/jsutil.h b/js32/jsutil.h new file mode 100644 index 00000000..efcb614c --- /dev/null +++ b/js32/jsutil.h @@ -0,0 +1,106 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* + * PR assertion checker. + */ + +#ifndef jsutil_h___ +#define jsutil_h___ + +JS_BEGIN_EXTERN_C + +#ifdef DEBUG + +extern JS_PUBLIC_API(void) +JS_Assert(const char *s, const char *file, JSIntn ln); +#define JS_ASSERT(_expr) \ + ((_expr)?((void)0):JS_Assert(# _expr,__FILE__,__LINE__)) + +#define JS_NOT_REACHED(_reasonStr) \ + JS_Assert(_reasonStr,__FILE__,__LINE__) + +#else + +#define JS_ASSERT(expr) ((void) 0) +#define JS_NOT_REACHED(reasonStr) + +#endif /* defined(DEBUG) */ + +/* + * Compile-time assert. "condition" must be a constant expression. + * The macro should be used only once per source line in places where + * a "typedef" declaration is allowed. + */ +#define JS_STATIC_ASSERT(condition) \ + JS_STATIC_ASSERT_IMPL(condition, __LINE__) +#define JS_STATIC_ASSERT_IMPL(condition, line) \ + JS_STATIC_ASSERT_IMPL2(condition, line) +#define JS_STATIC_ASSERT_IMPL2(condition, line) \ + typedef int js_static_assert_line_##line[(condition) ? 1 : -1] + +/* +** Abort the process in a non-graceful manner. This will cause a core file, +** call to the debugger or other moral equivalent as well as causing the +** entire process to stop. +*/ +extern JS_PUBLIC_API(void) JS_Abort(void); + +#ifdef XP_UNIX + +typedef struct JSCallsite JSCallsite; + +struct JSCallsite { + uint32 pc; + char *name; + const char *library; + int offset; + JSCallsite *parent; + JSCallsite *siblings; + JSCallsite *kids; + void *handy; +}; + +extern JSCallsite *JS_Backtrace(int skip); + +#endif + +JS_END_EXTERN_C + +#endif /* jsutil_h___ */ diff --git a/resource.h b/resource.h new file mode 100644 index 00000000..5272dd72 --- /dev/null +++ b/resource.h @@ -0,0 +1,15 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by version.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/resources/HISTORY.txt b/resources/HISTORY.txt new file mode 100644 index 00000000..ee2733e6 --- /dev/null +++ b/resources/HISTORY.txt @@ -0,0 +1,939 @@ +Version History: + +Version 1.4 - + + . API changes: + - Added useStatPoint(statid, count) and useSkillPoint(skillid, count)--no significant error checking + is done, so be careful or you may cause a crash (or worse, a ban)! + - Added loadMpq(string mpqname) (this allows you to switch cd keys on the fly) + - Added me.revive()--no error checking is done, so you may cause a ban if you're not dead + - Added takeScreenshot()--this is the same as pressing the print screen key in D2 + - Added me.pid--this returns the process id for the current D2 that D2BS is loaded to + - Added me.nopickup--returns the current nopickup setting, and allows you to enable/disable nopickup + - Added me.mapid--returns the current map seed + - Added me.profile--returns the last profile used for login() OR the profile set as the default + - Renamed getTextWidthHeight to getTextSize + - Changed the return from getPath--now it returns an array of objects with x and y properties + - Added support for setting skills from item charges (me.setSkill(skill, hand [, item object]) where + item object is the result of getUnit(TYPE_ITEM)) + + . Fixes: + - say() fixed to properly detect the screen location and correctly encode % characters + - Multiple problems with screenhook clicking and hovering. + - Signed/unsigned problems with stat ids 13, 29 and 30 + - Channel chat input parsing + - unit.getStat(-2) now properly bitshifts life, mana, and stamina + - clickMap no longer crashes with a null 'unit' argument + - FileTools functions now correctly use the locking API + - Unit.getFlags() now correctly works + - me.cancel no longer affects the automap + - The D2BSScript object is now initialized properly like all the others + - The event code now correctly returns a 32-bit integer--this was similar to the old getUnit bug, but + more subtle + + . Added partial support for TCP/IP games in login() + + . Had to revert the new map code--it wasn't working for all area exits, and existing scripts rely + on that behavior. :( + + . Changed the Warden behavior so that you can load D2BS without cGuard, and it will terminate on + Warden if not loaded with cGuard + + . Upgraded the SQLite library to version 3.7.5 + + . Downgraded "Game not ready" exception from an error to a warning. + + . Added the ability to change the default starting script names, as well as the ability to let the + profile specify both the script path and the default starting script names (see the new values in + d2bs.ini for more details) + + . Added the ability to specify the profile to use *before* calling login(): + - The profile is activated by the first time you call login() OR + - The first WM_COPYDATA message with an ID of 0x31337 (the data is treated as a profile name) OR + - The first XTYP_POKE sent via DDE (the data is treated as a profile name) OR + - Setting the profile via the "profile" command on the console. + - After the first profile is set, you cannot change it. However, specifying a different profile + via login() will allow you to login using a different profile (but me.profile will *not* be + updated, it will remain as-is, and the script path will remain the same) + + . The console is now scrollable using page up/down. Only the last 300 lines are saved. + + . Added new debug code! D2 will now silently crash when it does crash (no more "Window not found" + errors!), and will output debug information to D2BS.log. + + . Known issues: + - Calling say() in game causes a crash. Dunno exactly why yet. Just don't do it. + - getBaseStat does not correctly detect the end of the the item table. Calling it with a rowid greater + than the last rowid will cause a crash. + +Version 1.3.3 - + + . Fixed OOG_GetLocation for Lost Connection + + . Changed the internal unit finding code to use D2's unit hash tables. (Speeds up Unit finding by a + couple orders of magnitude.) + +Version 1.3.2 - + + . Changed the internal unit finding code to use an internal list instead of room searching. + + . Fixed sendDDE (multiple bugs, the least of which was an unused parameter...) + + . Fixed me.cancel once again to detect scrolling text ("summoner bug") + + . Fixed a rather large memory leak with Script::GetFilename (d'oh!) + + . Removed some of the strictness checks for getBaseStat (got sick of trying to debug it). + + . Fixed an issue where getScript could return a script that had no valid parameters, meaning + it would just error when you tried to use it. + + . Added "param2" parameter to the "gameevent" event. You may now detect what kind of party + message you just got (hostile vs. invite vs. accept, etc.) + +Version 1.3.1 - + + . Fixed me.cancel(1) (was using the wrong function pointer... whoops!) + (this also fixes the "gamble bug") + +Version 1.3 - + + . Updated to 1.13c + + . Various leaks and bugs fixed, nothing major + + . "chatmsg" and "whispermsg" now listen to channel events as well as in-game events. + + . Lots of little stability fixes and whatnot. + +Version 1.2 - + + . Fixes: + - me was not getting reset between games with the script cache enabled + - various interactions used to incorrectly cause deadlocks when the client was minimized + - getUnit now correctly interprets the gid parameter + - itemdrop has been renamed to itemaction, and passes different parameters: + gid, mode, code, globalEvent. gid is still the item's gid, mode is the type of action + (I'll make a list later), code is the item code, and globalEvent is whether the action + came from a 9c or 9d packet. + - Added new event: gameaction, triggers on 0x5a packets, params vary based on the action. + See the breakdown in the packet list sticky for more info. + - various crashes with images, including one where the version background image didn't exist + - Events now use their own independent context, to help prevent crashes. + + . Made all classes properly exposed to the scripter so they can be properly extended. + + . Made scripts wait less time while trying to stop, as the old duration was ridiculous. + + . Added/changed new functions/properties: + - selectCharacter -- takes the profile name, selects the character specified by that profile. + - Area.exits -- now returns the exit array instead of the number of exits + - getExits -- removed in preference of Area.exits. + - Exit.id -- renamed to Exit.level + - showConsole -- shows the console + - hideConsole -- hides the console + + . Updated sqlite version to 3.6.22. + + . Turned on compiler optimizations (finally). + + . Screenhook images are now cached. You only have to load them once, and any further loads + will return the same image. + + . Changed screenhook handling so that hidden screenhooks no longer are considered for drawing + period, meaning they're MUCH faster. + + . Changed the logo drawing code similarly, so that it draws on its own without being treated + as a screenhook (which means it always draws centered and draws much faster) + + . Changed the console drawing code similar to above, so that it handles long lines correctly + without being broken (this includes input, which drops to a newline on long lines). + + . Changed the handling for commands, you no longer have to print() the result you want--the + last value is printed by default now. + + . Loader changes: + - Added a new (and very cool) splash screen (thanks to Game_Slave for designing it!) + - Changed the default delay for child process detection to 1 second (up from .5 second) + +Version 1.1.2 - + + . Changed item.getPrice to item.getItemCost, getPrice is still there but marked as deprecated + - you can ignore warnings about it, it doesn't harm anything + + . Added me.fps -- returns the current FPS (obviously) + + . Added item.getItemCost(mode[, classid[, difficulty ] ]) + mode: 0 = buy, 1 = sell, 2 = repair + classid: any npc classid (default is the current npc) + difficulty: 0 = normal, 1 = nightmare, 2 = hell (default is the current difficulty) + + . Added me.getRepairCost([ classid ]) -- again, the classid is any npc classid with the default + being the current npc + + . getUnit() now accepts a mask for the mode parameter. + To use it, set bit 30 (0x20000000) to on, and then every bit from 1-28 is + treated as a mode bit--the unit must match at least one of the modes specified + i.e.: + getUnit(1, null, null, 0x2000001F); // finds monsters with any mode from 0-4 + + . Corrected item.getStat(-2) output (was adding a bunch of invalid properties) + + . Made me.runwalk able to be set--now you can toggle run/walk from a script + + . Loader changes: + - Made it take a guess where the Diablo II directory is + - Made it able to find the child process of Diablo II.exe--you no longer have to specify game.exe! + + . Fixed a race condition where D2BS was racing with the game in various places + - This means you no longer get corrupted graphics occasionally, and D2BS is much more stable + - Additionally, switched to the internal method of buying/selling instead of using packet-based + as it no longer crashes! + + . Fixed room.reveal to not be quite as buggy or crash-happy as before (all you maphackers, this + means game on!) + + . Fixed a (relatively stupid) crash with scriptBroadcast and more than 1 argument + + . Fixed SQLite crash when closing the DB when there were open queries (d'oh... stupid iterators...) + + . Fixed script.send to handle multiple arguments correctly (d'oh!) + + . Corrected bug with monster enchantments not being correctly detected + + . Corrected types for integer values from SQLite--was causing a wraparound for values over ~2 billion + + . Known issues: + - Certain item stats are still not correctly handled, which means you have to sort out the value + on your own (most are just value >> 8) + +Version 1.1.1 - + + . Included in this release is a build for the 1.13 PTR. To use it: + - open D2BS.exe, click on options (if not greeted with the options dialog) + - change the D2BS DLL from cGuard.dll to D2BS.dll + - keep in mind that you MUST change it back if you switch back to 1.12 + + . Fixes for numerous things, including a lot of core stability. + - Clicking on the window UI elements caused a click event with negative values. + - Deadlocks all over the place, especially with the script cache. + - Running a command via .exec or the console would screw the script list up. + - Calling include could sometimes cause crashes. + - Made (most, if not all) paths that get displayed to the user/exposed to the scripter + relative to the scripts folder. + - getScript, script.send, and scriptBroadcast now don't crash + - script iteration (internally) now correctly holds the engine lock long enough + to ensure that the list is valid until iteration is complete + - console/.exec commands no longer invalidate the script list (d'oh!) + - me.blockMouse would cause the entire window to lock up when the title bar was clicked + while it was enabled + - unit.getMinionCount no longer crashes in release mode + - getArea now correctly interprets no parameter as me.area (d'oh...) + - Changed item.shop to packet-based shopping for now--the internal function we were using was + causing crashes while minimized + - Sheppard, with the last minute assist, corrected a bunch of incorrect D2 functions (thanks!) + + . Split up events a bit further to make them less spammy, and added a few more events to + assist with this change + - melife now spawns only for life changes + - memana spawns only for mana changes + - itemdrop no longer includes gold drops + - golddrop now spawns for only gold drop events + + . Lots of internal buffers were shrunk down to more acceptable levels to combat memory usage + + . Scripts no longer randomly resume when the GC is called. + - a side effect of this is that sometimes scripts that were destructed don't always get + removed so occasionally it can crash (we haven't experienced it frequently enough to debug + it at all) + + . Lots of loader changes: + - To sum up: + . x86/x64 no longer matters for the injector, it uses x86 period. + . --inject and --kill check that the pid is a valid d2 window. + . --dll lets you specify what dll to inject, the default if you don't specify one is + cGuard.dll. + . --params sends everything after it to d2. + . --path lets you specify the path to d2. + . --exe lets you specify the d2 executable. + . --save causes it to write a configuration file for future use. + - Fixed a bug where the loader would assume you had no sane configuration when you really did. + - The loader now exposes a number of useful internal functions for other .NET assemblies. + + . A few API details: + - rnd has been renamed to rand, and now uses the game's internal RNG when you're in-game + - units now have an islocked property that tells you if a chest is locked + - runGC is now gone, iniread and iniwrite will soon follow + - All screenhooks have had a zorder property for a while, but now it's actually used (someone + commented out the sort...) + - getUnit(4) now no longer scans a unit's inventory; this caused a series of infinite loop + bugs, so we had to axe it (it still scans ground items) + - in return, unit.getItem has been changed to use the same parameters as getUnit (without the + type) and return the first inventory item that matches from the unit's inventory + - unit.getNext has different behavior depending on where the unit came from: + . if the unit came from getUnit, getNext will only scan units in the available rooms + . if the unit came from unit.getItem, getNext will only scan units in the same + original owner's inventory + . if the owner of the item from unit.getItem changes, getNext will return false + - item.getStat(-2) returns an associative array (NOT an object with properties matching array + indexes) of all the item's stats and substats, and includes runeword properties (and + correctly interprets skills for on-funcs and charges) + - getScript parameter additions: true now returns the current script, and passing the full + relative script name returns that script (or undefined if it's not running) + - added createGame and joinGame functions for oog scripts + + . Sped up print() by a factor of 30 when dealing with large strings. + + . Events now use a different means of spawning, so they no longer cause horrific crashes that + are hard to debug + + . .start/.stop/.reload (and their console alternatives) now correctly figure out which script + to start or stop, and .reload benefits from this as well. + + +Version 1.1 - + + . Way too many fixes to detail. Here's a small sample: + - getBaseStat was broken somehow, but that's fixed too. + - unit.getParent is fixed too (though what was broken about it escapes me) + - me.cancel is fixed as well (same as above) + - me.ingame now correctly detects in-game between act changes. + - graphics apparently are no longer corrupted on minimize + + . Changed a number of core functions. + - registerEvent(EVENT_*, function) --> addEventListener(eventName, function); + - getScreenHook() --> new Line(), new Text(), new Box(), new Image(), new Frame() + - Entire screenhook API + - Entire file API + FileTools object: + Static Functions: + remove - string name - remove a file based on name + rename - string oldName, string newName - rename a file + copy - string original, string copy - copy file 'original' to 'copy' + exists - string path - determines if a file exists or not + readText - string path - open a file in read mode, read the full contents, return + it as a string + writeText - string path, object contents, ... - open a file in write mode, write + the content parameters into the file, and close it, true if the write + succeeded, false if not + appendText - string path, object contents, ... - open a file in append mode, write + contents into the file, close it, true if the write succeeded, false if not + + File object: + Static Functions: + open - string path, mode [, bool binaryMode [, bool autoflush [, bool lockFile]]] - + open the specified file, return a File object, mode = one of the constants of + the File object listed below, binaryMode = default setting of + file.binaryMode, autoflush = default setting of file.autoflush, lockFile = + if true lock the file on open and unlock it on close, so other + threads/programs can't open it + + Functions: + close - close the current file + reopen - reopen the current file + read - int num - read num amount of characters or bytes from the file, if in + non-binary mode this will be null terminated + readLine - read a single line from the file, assuming the line ends with \n or + \r\n, throws an exception if the file is in binary mode + readAllLines - read the full contents of the file and split it up into an array + of lines, and return the array of lines, throws an exception if the file is + in binary mode + readAll - read the full contents of the file and return it as one big string or + if in binary mode, array + write - object contents, ... - write the specified byte/strings/objects/ + array-of-bytes to a file, throws an exception if not all of the parameters + could be written to disk + seek - int bytes [, bool isLines [, bool fromStart]] - seek the specified number + of bytes, or optionally lines, in the file, optionally from the start of the + file, stops at the end of the file + flush - flushes the remaining buffer to disk + reset - seek to the beginning of the file + end - seek to the end of the file + + Properties: + readable - can read from the file + writable - can write from the file + seekable - can seek within the file + mode - the mode the file was opened in, one of the FILE_MODE constants of the + file object + binaryMode - determines if the file is in binary mode for read operations (write + operations happen based on the parameter specified) + autoflush - automatically flush the file buffer after each write, defaults to off + length - the length of the file in bytes + path - the name and path (relative to the scripts/ folder) of the file + position - the current position in the file + eof - determines if the file is at end-of-file or not + accessed - a timestamp representing the last access time/date for the file + created - a timestamp representing the creation time/date for the file + modified - a timestamp representing the last modified time/date for the file + - Lots of other minor things. Those are the major changes, though. + + . Added some new global functions. I honestly don't even remember any more. + + . Added a new Sandbox object that lets you include scripts without tampering + with the global namespace. + + . Re-added room.reveal. + + . New injector to simplify your life and ours. + + . Added a console to display status messages out of game as well as in game. + - Pressing the HOME key shows the console, while ALT+HOME allows you to type + commands into it. + - The special commands 'start', 'stop', 'reload', 'flushcache', and 'load' + work as per their chat box counterparts (only without the . prefix), but any + other command is interpreted as a javascript string and will be executed (as + per the old .exec). + - All output is now directed to the new console instead of to the screen. + + . Added hash algorithms: md5, sha1, sha256, sha384, sha512 and counterparts to work + on files. + + . Added configuration file for setting various things before scripts execute. + See d2bs.ini for the specifics. + + . Added a new oog function (login) to manage user accounts and character selection. + See d2bs.ini for the specifics to this as well. + + . Added a bunch of sample code in the form of test cases. These provide examples + of how to use certain API functions. You can check the code out at: + http://code.assembla.com/d2bs/subversion/nodes/scripts/testcases + + . Complete-ish list of fixes: http://www.assembla.com/spaces/d2bs/tickets?tickets_report_id=5 + + . Known issues: + - sometimes the core just deadlocks, we're not sure exactly why. + - anything listed here: http://www.assembla.com/spaces/d2bs/tickets?tickets_report_id=1 + +Version 1.0 - + + . Updated D2BS to Patch 1.12a. + + . Added cGuard Anti-Detection. + + . Added getPlayerFlag(int firstUnitId, int secondUnitId, int flag); + + . Added EVENT_PLAYERASSIGN event. + Code: + registerEvent(EVENT_PLAYERASSIGN, assignPlayer); + function assignPlayer(unitid) + { + var player = getUnit(0, null, null, unitid); + if(player) print("New player: " + player.name); + } + + . Added unit.getEnchant( int enchantid ); + + . Added getBaseStat: + + varied = getBaseStat( basestat, classid, statnum ); + + 0 - items + 1 - monstats (&npcs) + 2 - skilldesc + 3 - skills + 4 - objects + 5 - missiles + 6 - monstats2 + 7 - itemstatcost + 8 - levels + 9 - leveldefs + 10 - lvlmaze + 11 - lvlsub + 12 - lvlwarp + 13 - lvlprest + 14 - lvltypes + 15 - charstats + 16 - setitems + 17 - uniqueitems + 18 - sets + 19 - itemtypes + 20 - runes + 21 - cubemain + 22 - gems + 23 - experience + 24 - pettype + 25 - SuperUniques + + Examples: + // If not killable... + if (getBaseStat(1, monster.classid, 20) == 0) return false; + + // Align, on our side? + if (getBaseStat(1, monster.classid, 63)) return false; + + . Removed Message() function. + + . Removed room.reveal() function. + + . Fixed clickParty(partyobj, 3); + no longer causes a crash also it will leave the party now! + + . Fixed say(); + no longer causes the stack to fuck up! + + . Fixed getUnit(type, [classid, [mode, [unitid]]]); + mode finally works on items now aswell! + + . Fixed room.getCollision(); + +Version 0.9.0.4 - + + . Added a missing LeaveCriticalSection which caused the scripts to stop. + + . Added Maplayer drawing, just define the screenhook type with one of the automap types. + + Automap Line : 3 + Automap Box : 4 + Automap Image : 5 + + Example: + + var sh = getScreenHook(); + + sh.x = me.x; + sh.y = me.y; + sh.font = 6; + sh.color = 1; + sh.type = 4; + sh.text = "Hello!"; + + . Added room.reveal(); - allows you to reveal rooms! I included a lite maphack in the scripts folder. + + . Added local storage via SQLite. See http://www.edgeofnowhere.cc/viewtopic.php?t=397403&start=0 for the API. + + . Fixed playSound(integer soundid); - henceforth it plays all sound ids! + + . Fixed the D2BS Logo Background, it was screwed when the resolution was set to 640x480. + + . Fixed a bug in the Screenhooks which caused to draw a line if x2 and y2 is undefined. + + . Fixed another bug in the Screenhooks which caused a crash. + + . The goddamn toolsthread stoppage in NTBot is finally fucking fixed. In fact, scripts randomly stopping in general has been fixed. + + . unit.fname and item-related-friends return undefined on units that aren't items. Finally. + + . All outstanding compiler errors with the latest SVN source are fixed. + + . print now outputs "undefined" if you call it with an undefined value, instead of printing nothing. + + . version(1) now returns the version number as a string, instead of attempting to cast it to an int. + + . Fixed minor misspellings in various warnings, removed some really stupid warnings that don't need to exist. + +Version 0.9.0.3 - + + . Fixed Screenhooks, those caused a crash when your script stopped. + + . Fixed unit detection + + . Fixed an issue with sendCopyData + + . Fixed clickItem(), works now well with items that have a height of 4 rows + + . Fixed a bug in clickMap, that could cause the bot to stop. Thanks Kimsout! + + . gold(int amount, [mode]); has been rewritten. + + . Added item.suffixnum along with item.prefixnum - returns the prefix/suffix number. + +Version 0.9.0.2 - + + . Fixed getArea(), it crashed when you tried to pass a value that is not an integer. + + . Fixed getUnit(UNIT_TYPE); - Thanks to lord2800 for pointing that out! + + . Fixed stop(); - Will no longer crash if you call it with the command line. + + . Fixed print(); - Will no longer crash if you pass a text that is longer than 2048 chars. + + . Rewrote Screenhooks! + + Example: + sh = getScreenHook(); + sh.type = 1; // 0 = Line, 1 = Box, 2 = Image + sh.x = 100; + sh.y = 100; + sh.x2 = 200; + sh.y2 = 200; + sh.text = "I'm a box hook, eek!"; + sh.color = 4; + sh.font = 1; + + // Using Image hooks works like this, + sh = getScreenHook(); + sh.type = 2; + sh.image = "DATA\\GLOBAL\\UI\\FrontEnd\\textbox2"; + sh.x = 100; + sh.y = 200; + + . Added unit.getStat(-1); - It will return a list of all stats that belong to a unit. + Example: + stats = item.getStat(-1); + for(var i = 0; i < stats.length; i++) + print("Index: " + stats[i][0] + ", SubIndex: " + stats[i][1] + ", Value: " + stats[i][2]); + + . Added md5([String/Integer]); + +Version 0.9.0.1 - + + . Screenhooks do now work out of game! + + . Imagehooks do work now again! Simply pass a mpq path or a file path. + Example: + sh = getImageHook(); + sh.x = 100; + sh.y = 100; + sh.image = "DATA\\GLOBAL\\ui\\panel\\arrow6"; // loads the out of arrows image + + . Added D2BS Loader! + + . Renamed "oog.dbj" to "starter.dbj"! + +Version 0.9.0.0 - + + . Fixed item.shop(); - It will no longer crash when executed minimized! + +Version 0.8.9.9 - + + . Added Tile Exits to the Exit units! + You can determinate if a Unit is a level exit or a tile exit by using unit.type + 1 = Level, 2 = Tile + + . Added a new mode to clickItem! + You can click merc items now by using clickItem(3, BodyLocation) or clickItem(3, itemobject); + Valid Bodylocations of the merc are + 1 - Helmet + 3 - Armor + 4 - Weapon + 5 - Shield + + . Updated me.getMerc(mode); + If you call me.getMerc(1); it will return wether your player has a merc or not. + me.getMerc(2); returns the locale string index, you can grab the name off it by using getLocaleString(); + me.getMerc(3); returns the revive cost. + + . Fixed EVENT_COPYDATA - Thanks to McGod (Aka Chipped) + + . Fixed item.getStat(); - Thanks to lord2800 and Kimsout for pointing that out. + + . Updated say(); - works now out of game aswell (You have to be in the chat to use this!) + + . Updated print(); - works now out of game aswell (You have to be in the chat to use this!) + + . Added a few more CriticalSections + +Version 0.8.9.8 - + + . Added some CriticalSection code! (Makes d2bs more stable) + + . Added getRecentNPC(); + + . Fixed say(); + + . Fixed item.shop(); it caused a crash when it was executed while Diablo was minimized. + +Version 0.8.9.7 - + + . Added unit.direction; (Useful for Missiledodge!) + + . Enabled Screenhook clicking! + + . Fixed room.getCollision(); Finally works without problems! + + . Added getMercHP(); Returns the % life of your merc! + +Version 0.8.9.6 - + + . Fixed me.gametype (I forgot to add a * ;/) + + . Added socket.recv(event); ! + + . Rewrote the EVENT_CHATMSG stuff + +Version 0.8.9.5 - + + . Rewrote submitItem(); - Doesn't simulate a click anymore! + + . Rewrote unit.overhead(text); - Doesn't spoof a packet anymore! + + . Fixed a memory problem while executing events. + + . Fixed me.gametype (Should work proper now!!) + + . Fixed a bug in the spidermonkey ErrorReporter, it will close the errorlog after it wrote to it. + + . Added ExtraWork Check (Will terminate Diablo as soon as a ExtraWork is loaded by Diablo) + + . Added CheckRevision Check (Will terminate Diablo if a unknown CheckRevision was loaded) + + . Added checkCollision(unit1, unit2, bitmask); // returns if units have line of sight to each other + Bitmask: + bit 0 : block walk + bit 1 : block light + block Line Of Sight (the possibility to see monsters) + bit 2 : block jump (and teleport I believe) + bit 3 : block Player's walk but not Mercenary's walk (weird) + bit 4 : ? + bit 5 : block light only (not LOS) + bit 6 : ? + bit 7 : ? + Return 0 or 1. 0 = Has Line Of Sight, 1 = Does NOT Have Line Of Sight + + . Added Socket units! D2BS can now connect to the IRC or where ever you would like to! + Example: + sock = getSocket(); + sock.ip = "irc.synirc.net"; + sock.port = 6667; + sock.connect(); + sock.send("NICK aD2BSSocket\n"); + ... // What ever you'd like to have here! + sock.close(); + + . Added item.bodylocation + 0 : Not Equipped + 1 : Head + 2 : Amulet + 3 : Body + 4 : Right Primary Slot + 5 : Left Primary Slot + 6 : Right Ring + 7 : Left Ring + 8 : Belt + 9 : Feet + 10 : Gloves + 11 : Right Secondary Slot + 12 : Left Secondary Slot + + . Added unit.itemcount + + . Added unit.owner; returns the id of the owner (eg, single player, 1 for you, -1 for no owner) + This is meant as an alternative for getParent(); which will be phased out eventually + When used on a missile, returns the id of the owner of the missile + + . Added unit.ownertype; returns the owner type of a missile (0 player, 1 npc/monster) + + . Added item.ilvl; returns the level of the item. + + . Added me.quitonerror; Defaults to 0, set this to 1 to have a script automatically quit if an error occurs. + Not recommended to set this until your script is mature, this is just to prevent the odd misc error from stopping infinite runs. + + . Moved to Spidermonkey 1.7.0! Make sure you use the newst js32.dll! + Check the changelog of it here http://www.mozilla.org/js/spidermonkey/release-notes/JS_170.html + New in JavaScript 1.7 -> http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7 + +Version 0.8.9.4 - + + . Added unit.getMerc(); + + . Added unit.getMinionCount([ClassId]); + + . Fixed item.shop(); - Finally item selling works + +Version 0.8.9.3 - + + . Added some more checks into Unit related functions. It will make D2BS more stable (hopefully!) + + . Fixed a bug in getCursorType(); - Forgot to change JSVAL_TO_INT to INT_TO_JSVAL! (D'oh) + + . Included a Identifying example into default.dbj + +Version 0.8.9.2 - + + . Added item.description + + . Added getCursorType([optional 1]); + Returns the cursor type of your cursor, pass one to see "Shop Mode" cursor types. + + Regular Modes: 1 = regular, 3 and 4 = item on cursor, 6 = id scroll, 7 = shop cursor + + Shop Mode (7): 1 = regular, 2 = repair, 3 = buy, 4 = sell + + +Version 0.8.9.1 - + + . Fixed a bug in clickItem! Clicking items right should work now!! + +Version 0.8.9 - + + . Added JS_MaybeGC to the CallBack function to free not used memory (Which makes D2BS much more stable!) + + . Fixed clickItem! Works now proper for stash + +Version 0.8.8 - + + . Fixed unit.cancel([int type]); + + . Fixed a bug that could cause a crash in the unit code. + + . Fixed a bug in unit.getParent() + + . Fixed a bug that could cause a crash in item properties. + + . Added sendDDE + + . Rewrote say( string text ); + No longer using Packets for this. + +Version 0.8.7 - + + . Added getRoom stuff. It's similar to the D2JSP functions, + + . Added getScript stuff. It's similar to the D2JSP functions. + + . Note: I'm remaking the Script documentation. + +Version 0.8.6 - + + . Rewrote unit.useMenu - Thanks to Darawk for helping me to disable + the padding in the NPCMenu struct. + +Version 0.8.5 - + + . Added Belt left/shift rightclick to clickItem. I'm sorry about that, + I forgot to add it last version! + +Version 0.8.4 - + + . Fixed a crash that appeared if you define Text in screeenhooks before + you define the font! + + . Rewrote unit.shop(); - It uses now the Diablo II function instead of + sending a packet. + + . Rewrote clickItem! + clickItem(button,[other..]); // button: 0=left, 1=right, 2=shift left click(put to belt) params are as follows: + either pass: x, y, location (0,0 is top left, always, 1,1 is one left, one down in the grid, etc + location=: 0=inventory, 2=player trade, 3=cube, 4=stash, 5=belt + Or, if you'd like to simply click an item already in your inv/stash/cube, etc: clickItem(button,item); + Also, you can call your body location: clickItem(body_location); + + +Version 0.8.3 - + + . Fixed a crash that appeared when the SpiderMonkey ErrorReporter tries to + submit a very long crash message. It will print Messages that will crash + Diablo to a file (ErrorReport.log). + Thanks to Chipped for reporting it :~) + +Version 0.8.2 - + + . Fixed clickMap! It will no longer crash when you call it with a unit! + + . Rewrote clickItem! + + . Changed compiling settings from MultiThreaded to SingleThreaded (This fixed all HeapFree crashes!) + + . Changed CleanUp function + + . Added js_strict([bool flag]); + + . me.getSkill is now similar to the d2jsp one! + +version 0.8.1 - + + . Added me properties (Check the command reference) + + . Updated the Command Reference at EoN! + + . Fixed unit.interact(); <- Didn't work proper with wps. + + . Added core chickening.. + + . Changed clickMap, Unit's will get now namelocked before the actual click gets send. + +version 0.8 - + + . Fixed getExits(); + + . Reworked getCollision(x,y); + + . Added Control units! + + . Added OOG Script ability. + + . Added a EVENT_COPYDATA! + The first parameter is the mode and the second is a string. + Example: + registerEvent(pfunc, EVENT_COPYDATA); + function pfunc(a,b) + { + printf(a + ": " + b); + } + + . Fixed another crash that appeared when D2BS was about to build a CollisionMap. + + . Fixed getWaypoint(int area); - Thanks to Chipped for reporting this! + + . Added unit.spectype! + +version 0.7.3 - + + . Fixed the crash that happened during building CollisionMap & PresetUnit. + +version 0.7.2 - + . Added unit.returnNext(); - because Zoxc was slapping me all day for it + + . Added clickItem(item || x,y,buffer); + +version 0.7.1 - + . Fixed copyUnit, thanks to Zoxc and LivedKrad for reporting it! + +version 0.7 - + . Reworked unit.interact(); + + . Added npc.useMenu( int ); + + . Added unit.getItems(); + - Returns a Array of items in the it has in it's inventory. + + . Added unit.getSkill(Mode|Skillid [, Ext] ); + if unit.getSkill is called like this unit.getSkill(0, 2); + it will return the current selected right skillname. + Modes: + 0 - Right Hand Skill Name + 1 - Left Hand Skill Name + 2 - Right Hand Skill Id + 3 - Left Hand Skill Id + if it's called only with the skillid it will return the skill level. + + . Added Party Object. Check the Command Reference at EoN for more informations. + + . Added item.shop(NPC Object, mode); + + . Added iniread, iniwrite to the core. + +version 0.6 - + . Fixed a bug that caused a crash when using copyUnit with a invaild Object + + . Fixed a bug in the Screenhooks that caused a crash when you defined + text before a font. + + . Added me.cancel(); + + . Added me.repair(); + + . Added item.getPrice([NPCObject or NPC ClassId, 0/1 Buy or Sell, Difficult]); + +version 0.5 - + . Added Screenhooks! + Take a look at the COmmand Reference + http://www.edgeofnowhere.cc/viewtopic.php?t=377768&start=0 + +version 0.4 - + . Added unit = copyUnit( unit ); + + . Fixed a bug in the Core that caused a crash. + +version 0.3 - + . Added AreaUnit = getArea ( [int areaid ] ); + Example: print(getArea(me.area).name); // Prints out the current AreaName! + + . Added ExitArray = getExits ( AreaUnit ); + Note: Take a look at the Command Refernece -> http://www.edgeofnowhere.cc/viewtopic.php?t=377768&start=0 + +version 0.2 - + . Fixed getPath, returns now a fully working Path! + +version 0.1 - + . Inital Release \ No newline at end of file diff --git a/resources/LICENSE.txt b/resources/LICENSE.txt new file mode 100644 index 00000000..10cfeb6a --- /dev/null +++ b/resources/LICENSE.txt @@ -0,0 +1,88 @@ +GNU GENERAL PUBLIC LICENSE Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, +Boston, MA 02110-1301 USA +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + +a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + +b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + +c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + +a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + +b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + +c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. \ No newline at end of file diff --git a/resources/api.html b/resources/api.html new file mode 100644 index 00000000..5151dd84 --- /dev/null +++ b/resources/api.html @@ -0,0 +1,10444 @@ + + + + + + + + + + + + + D2BS API - everything you wanted to know about D2BS, but were afraid to ask + + + + + + + + + + + +
+
+
+
+
+
+
+
+
+
+
+
<!--{{{-->
+<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' />
+<!--}}}-->
+
+
+
+
Background: #fff
+Foreground: #000
+PrimaryPale: #8cf
+PrimaryLight: #18f
+PrimaryMid: #04b
+PrimaryDark: #014
+SecondaryPale: #ffc
+SecondaryLight: #fe8
+SecondaryMid: #db4
+SecondaryDark: #841
+TertiaryPale: #eee
+TertiaryLight: #ccc
+TertiaryMid: #999
+TertiaryDark: #666
+Error: #f88
+
+
+
+
/*{{{*/
+body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
+
+a {color:[[ColorPalette::PrimaryMid]];}
+a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
+a img {border:0;}
+
+h1,h2,h3,h4,h5,h6 {color:[[ColorPalette::SecondaryDark]]; background:transparent;}
+h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
+h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}
+
+.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
+.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
+.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}
+
+.header {background:[[ColorPalette::PrimaryMid]];}
+.headerShadow {color:[[ColorPalette::Foreground]];}
+.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
+.headerForeground {color:[[ColorPalette::Background]];}
+.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}
+
+.tabSelected{color:[[ColorPalette::PrimaryDark]];
+	background:[[ColorPalette::TertiaryPale]];
+	border-left:1px solid [[ColorPalette::TertiaryLight]];
+	border-top:1px solid [[ColorPalette::TertiaryLight]];
+	border-right:1px solid [[ColorPalette::TertiaryLight]];
+}
+.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
+.tabContents {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::TertiaryPale]]; border:1px solid [[ColorPalette::TertiaryLight]];}
+.tabContents .button {border:0;}
+
+#sidebar {}
+#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
+#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
+#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
+#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
+#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}
+
+.wizard {background:[[ColorPalette::PrimaryPale]]; border:1px solid [[ColorPalette::PrimaryMid]];}
+.wizard h1 {color:[[ColorPalette::PrimaryDark]]; border:none;}
+.wizard h2 {color:[[ColorPalette::Foreground]]; border:none;}
+.wizardStep {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];
+	border:1px solid [[ColorPalette::PrimaryMid]];}
+.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
+.wizardFooter {background:[[ColorPalette::PrimaryPale]];}
+.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
+.wizard .button {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
+	border-color:[[ColorPalette::SecondaryPale]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryPale]];}
+.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
+.wizard .button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
+	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];}
+
+.wizard .notChanged {background:transparent;}
+.wizard .changedLocally {background:#80ff80;}
+.wizard .changedServer {background:#8080ff;}
+.wizard .changedBoth {background:#ff8080;}
+.wizard .notFound {background:#ffff80;}
+.wizard .putToServer {background:#ff80ff;}
+.wizard .gotFromServer {background:#80ffff;}
+
+#messageArea {border:1px solid [[ColorPalette::SecondaryMid]]; background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]];}
+#messageArea .button {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none;}
+
+.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}
+
+.popup {background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]]; border-left:1px solid [[ColorPalette::TertiaryMid]]; border-top:1px solid [[ColorPalette::TertiaryMid]]; border-right:2px solid [[ColorPalette::TertiaryDark]]; border-bottom:2px solid [[ColorPalette::TertiaryDark]];}
+.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
+.popup li.disabled {color:[[ColorPalette::TertiaryMid]];}
+.popup li a, .popup li a:visited {color:[[ColorPalette::Foreground]]; border: none;}
+.popup li a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border: none;}
+.popup li a:active {background:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::Foreground]]; border: none;}
+.popupHighlight {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
+.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}
+
+.tiddler .defaultCommand {font-weight:bold;}
+
+.shadow .title {color:[[ColorPalette::TertiaryDark]];}
+
+.title {color:[[ColorPalette::SecondaryDark]];}
+.subtitle {color:[[ColorPalette::TertiaryDark]];}
+
+.toolbar {color:[[ColorPalette::PrimaryMid]];}
+.toolbar a {color:[[ColorPalette::TertiaryLight]];}
+.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
+.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}
+
+.tagging, .tagged {border:1px solid [[ColorPalette::TertiaryPale]]; background-color:[[ColorPalette::TertiaryPale]];}
+.selected .tagging, .selected .tagged {background-color:[[ColorPalette::TertiaryLight]]; border:1px solid [[ColorPalette::TertiaryMid]];}
+.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
+.tagging .button, .tagged .button {border:none;}
+
+.footer {color:[[ColorPalette::TertiaryLight]];}
+.selected .footer {color:[[ColorPalette::TertiaryMid]];}
+
+.sparkline {background:[[ColorPalette::PrimaryPale]]; border:0;}
+.sparktick {background:[[ColorPalette::PrimaryDark]];}
+
+.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
+.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
+.lowlight {background:[[ColorPalette::TertiaryLight]];}
+
+.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}
+
+.imageLink, #displayArea .imageLink {background:transparent;}
+
+.annotation {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border:2px solid [[ColorPalette::SecondaryMid]];}
+
+.viewer .listTitle {list-style-type:none; margin-left:-2em;}
+.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
+.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}
+
+.viewer table, table.twtable {border:2px solid [[ColorPalette::TertiaryDark]];}
+.viewer th, .viewer thead td, .twtable th, .twtable thead td {background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::Background]];}
+.viewer td, .viewer tr, .twtable td, .twtable tr {border:1px solid [[ColorPalette::TertiaryDark]];}
+
+.viewer pre {border:1px solid [[ColorPalette::SecondaryLight]]; background:[[ColorPalette::SecondaryPale]];}
+.viewer code {color:[[ColorPalette::SecondaryDark]];}
+.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}
+
+.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}
+
+.editor input {border:1px solid [[ColorPalette::PrimaryMid]];}
+.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%;}
+.editorFooter {color:[[ColorPalette::TertiaryMid]];}
+
+#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
+#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
+#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
+#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
+#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
+#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
+#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
+.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
+.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
+#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:'alpha(opacity=60)';}
+/*}}}*/
+
+
+
/*{{{*/
+* html .tiddler {height:1%;}
+
+body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}
+
+h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
+h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
+h4,h5,h6 {margin-top:1em;}
+h1 {font-size:1.35em;}
+h2 {font-size:1.25em;}
+h3 {font-size:1.1em;}
+h4 {font-size:1em;}
+h5 {font-size:.9em;}
+
+hr {height:1px;}
+
+a {text-decoration:none;}
+
+dt {font-weight:bold;}
+
+ol {list-style-type:decimal;}
+ol ol {list-style-type:lower-alpha;}
+ol ol ol {list-style-type:lower-roman;}
+ol ol ol ol {list-style-type:decimal;}
+ol ol ol ol ol {list-style-type:lower-alpha;}
+ol ol ol ol ol ol {list-style-type:lower-roman;}
+ol ol ol ol ol ol ol {list-style-type:decimal;}
+
+.txtOptionInput {width:11em;}
+
+#contentWrapper .chkOptionInput {border:0;}
+
+.externalLink {text-decoration:underline;}
+
+.indent {margin-left:3em;}
+.outdent {margin-left:3em; text-indent:-3em;}
+code.escaped {white-space:nowrap;}
+
+.tiddlyLinkExisting {font-weight:bold;}
+.tiddlyLinkNonExisting {font-style:italic;}
+
+/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
+a.tiddlyLinkNonExisting.shadow {font-weight:bold;}
+
+#mainMenu .tiddlyLinkExisting,
+	#mainMenu .tiddlyLinkNonExisting,
+	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
+#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}
+
+.header {position:relative;}
+.header a:hover {background:transparent;}
+.headerShadow {position:relative; padding:4.5em 0 1em 1em; left:-1px; top:-1px;}
+.headerForeground {position:absolute; padding:4.5em 0 1em 1em; left:0px; top:0px;}
+
+.siteTitle {font-size:3em;}
+.siteSubtitle {font-size:1.2em;}
+
+#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}
+
+#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
+#sidebarOptions {padding-top:0.3em;}
+#sidebarOptions a {margin:0 0.2em; padding:0.2em 0.3em; display:block;}
+#sidebarOptions input {margin:0.4em 0.5em;}
+#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
+#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
+#sidebarOptions .sliderPanel input {margin:0 0 0.3em 0;}
+#sidebarTabs .tabContents {width:15em; overflow:hidden;}
+
+.wizard {padding:0.1em 1em 0 2em;}
+.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
+.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
+.wizardStep {padding:1em 1em 1em 1em;}
+.wizard .button {margin:0.5em 0 0; font-size:1.2em;}
+.wizardFooter {padding:0.8em 0.4em 0.8em 0;}
+.wizardFooter .status {padding:0 0.4em; margin-left:1em;}
+.wizard .button {padding:0.1em 0.2em;}
+
+#messageArea {position:fixed; top:2em; right:0; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
+.messageToolbar {display:block; text-align:right; padding:0.2em;}
+#messageArea a {text-decoration:underline;}
+
+.tiddlerPopupButton {padding:0.2em;}
+.popupTiddler {position: absolute; z-index:300; padding:1em; margin:0;}
+
+.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
+.popup .popupMessage {padding:0.4em;}
+.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0;}
+.popup li.disabled {padding:0.4em;}
+.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
+.listBreak {font-size:1px; line-height:1px;}
+.listBreak div {margin:2px 0;}
+
+.tabset {padding:1em 0 0 0.5em;}
+.tab {margin:0 0 0 0.25em; padding:2px;}
+.tabContents {padding:0.5em;}
+.tabContents ul, .tabContents ol {margin:0; padding:0;}
+.txtMainTab .tabContents li {list-style:none;}
+.tabContents li.listLink { margin-left:.75em;}
+
+#contentWrapper {display:block;}
+#splashScreen {display:none;}
+
+#displayArea {margin:1em 17em 0 14em;}
+
+.toolbar {text-align:right; font-size:.9em;}
+
+.tiddler {padding:1em 1em 0;}
+
+.missing .viewer,.missing .title {font-style:italic;}
+
+.title {font-size:1.6em; font-weight:bold;}
+
+.missing .subtitle {display:none;}
+.subtitle {font-size:1.1em;}
+
+.tiddler .button {padding:0.2em 0.4em;}
+
+.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
+.isTag .tagging {display:block;}
+.tagged {margin:0.5em; float:right;}
+.tagging, .tagged {font-size:0.9em; padding:0.25em;}
+.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
+.tagClear {clear:both;}
+
+.footer {font-size:.9em;}
+.footer li {display:inline;}
+
+.annotation {padding:0.5em; margin:0.5em;}
+
+* html .viewer pre {width:99%; padding:0 0 1em 0;}
+.viewer {line-height:1.4em; padding-top:0.5em;}
+.viewer .button {margin:0 0.25em; padding:0 0.25em;}
+.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
+.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}
+
+.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
+.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
+table.listView {font-size:0.85em; margin:0.8em 1.0em;}
+table.listView th, table.listView td, table.listView tr {padding:0px 3px 0px 3px;}
+
+.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
+.viewer code {font-size:1.2em; line-height:1.4em;}
+
+.editor {font-size:1.1em;}
+.editor input, .editor textarea {display:block; width:100%; font:inherit;}
+.editorFooter {padding:0.25em 0; font-size:.9em;}
+.editorFooter .button {padding-top:0px; padding-bottom:0px;}
+
+.fieldsetFix {border:0; padding:0; margin:1px 0px;}
+
+.sparkline {line-height:1em;}
+.sparktick {outline:0;}
+
+.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
+.zoomer div {padding:1em;}
+
+* html #backstage {width:99%;}
+* html #backstageArea {width:99%;}
+#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em;}
+#backstageToolbar {position:relative;}
+#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em;}
+#backstageButton {display:none; position:absolute; z-index:175; top:0; right:0;}
+#backstageButton a {padding:0.1em 0.4em; margin:0.1em;}
+#backstage {position:relative; width:100%; z-index:50;}
+#backstagePanel {display:none; z-index:100; position:absolute; width:90%; margin-left:3em; padding:1em;}
+.backstagePanelFooter {padding-top:0.2em; float:right;}
+.backstagePanelFooter a {padding:0.2em 0.4em;}
+#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}
+
+.whenBackstage {display:none;}
+.backstageVisible .whenBackstage {display:block;}
+/*}}}*/
+
+
+
+
/***
+StyleSheet for use when a translation requires any css style changes.
+This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
+***/
+/*{{{*/
+body {font-size:0.8em;}
+#sidebarOptions {font-size:1.05em;}
+#sidebarOptions a {font-style:normal;}
+#sidebarOptions .sliderPanel {font-size:0.95em;}
+.subtitle {font-size:0.8em;}
+.viewer table.listView {font-size:0.95em;}
+/*}}}*/
+
+
+
/*{{{*/
+@media print {
+#mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea {display: none !important;}
+#displayArea {margin: 1em 1em 0em;}
+noscript {display:none;} /* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
+}
+/*}}}*/
+
+
+
<!--{{{-->
+<div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
+<div class='headerShadow'>
+<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
+<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
+</div>
+<div class='headerForeground'>
+<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
+<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
+</div>
+</div>
+<div id='mainMenu' refresh='content' tiddler='MainMenu'></div>
+<div id='sidebar'>
+<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
+<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
+</div>
+<div id='displayArea'>
+<div id='messageArea'></div>
+<div id='tiddlerDisplay'></div>
+</div>
+<!--}}}-->
+
+
+
<!--{{{-->
+<div class='toolbar' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
+<div class='title' macro='view title'></div>
+<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
+<div class='tagging' macro='tagging'></div>
+<div class='tagged' macro='tags'></div>
+<div class='viewer' macro='view text wikified'></div>
+<div class='tagClear'></div>
+<!--}}}-->
+
+
+
<!--{{{-->
+<div class='toolbar' macro='toolbar [[ToolbarCommands::EditToolbar]]'></div>
+<div class='title' macro='view title'></div>
+<div class='editor' macro='edit title'></div>
+<div macro='annotations'></div>
+<div class='editor' macro='edit text'></div>
+<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser excludeLists'></span></div>
+<!--}}}-->
+
+
+
To get started with this blank [[TiddlyWiki]], you'll need to modify the following tiddlers:
+* [[SiteTitle]] & [[SiteSubtitle]]: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
+* [[MainMenu]]: The menu (usually on the left)
+* [[DefaultTiddlers]]: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
+You'll also need to enter your username for signing your edits: <<option txtUserName>>
+
+
+
These [[InterfaceOptions]] for customising [[TiddlyWiki]] are saved in your browser
+
+Your username for signing your edits. Write it as a [[WikiWord]] (eg [[JoeBloggs]])
+
+<<option txtUserName>>
+<<option chkSaveBackups>> [[SaveBackups]]
+<<option chkAutoSave>> [[AutoSave]]
+<<option chkRegExpSearch>> [[RegExpSearch]]
+<<option chkCaseSensitiveSearch>> [[CaseSensitiveSearch]]
+<<option chkAnimate>> [[EnableAnimations]]
+
+----
+Also see [[AdvancedOptions]]
+
+
+
<<importTiddlers>>
+
+
+ +
+
+
D2BS stands for Diablo II Botting System.
+
+
+
Welcome
+
+
+
//{{{
+
+config.macros.eventList = {
+	handler: function (place, macroName, params, wikifier, paramString) {
+		var functions = "!Events:\r\n\r\n";
+		params = params.sort();
+		for(var i = 0; i < params.length; i++)
+			functions += '[[' + params[i] + ']]\r\n';
+
+		wikify(functions, place);
+	}
+};
+
+//}}}
+
+
+
//{{{
+
+config.macros.event = {
+	handler: function (place, macroName, params, wikifier, paramString, tiddler) {
+		var p = paramString.parseParams(null, null, true);
+		var len = tiddler.title.indexOf('Event');
+		if(len == -1) len = tiddler.title.length;
+		var name = getParam(p, "name") || tiddler.title.slice(0, len);
+		var args = getParam(p, "args");
+		var retVal = getParam(p, "returnType") || 'void';
+		var remarks = getParam(p, "remarks") || 'none';
+		var example = getParam(p, "example") || '';
+		wikify("!Event:\r\n{{{" + retVal + " " + name + "(" + args + ")}}}\r\n\r\n" +
+			 "!!!''Remarks:''\r\n" + remarks + "\r\n\r\n" +
+			 "!!!''Example:''\r\n{{{" + example + "}}}",
+			 place);
+	}
+};
+
+//}}}
+
+
+
<<eventList
+	ItemActionEvent
+	GameMsgEvent
+	ChatMsgEvent
+	WhisperMsgEvent
+	MeLifeEvent
+	MeManaEvent
+	KeyUpEvent
+	KeyDownEvent
+	PlayerAssignEvent
+	MouseClickEvent
+	ScriptMsgEvent
+	GoldDropEvent
+	CopyDataEvent
+	GameEventEvent
+>>
+
+
+
[[Terminology]]
+[[How D2BS works]]
+[[How to run a script]]
+[[How to write a script]]
+
+
+
<<func prefix:"File" args:"" returnType:"" returns:"" remarks:"" example:"">>
+
+
+
<<functionList prefix:"File" type:"Static"
+	open
+>>
+<<functionList prefix:"File"
+	close
+	reopen
+	read
+	readLine
+	readAllLines
+	readAll
+	write
+	seek
+	flush
+	reset
+	end
+>>
+<<propertyList prefix:"File"
+	readable
+	writable
+	seekable
+	mode
+	binaryMode
+	autoflush
+	length
+	path
+	position
+	eof
+>>
+
+
+
<<func prefix:"FileTools" args:"string name, object content [, ... ]" returnType:"bool" returns:"True if all the content was successfully appended, otherwise false." remarks:"Appends all of the contents to a file based on the file name. All paths are relative to the script folder." example:"FileTools.appendText('/logs/mylog.txt', 'January 2nd. Got eaten by a grue. Apparently he wanted the beans.');">>
+
+
+
<<func prefix:"FileTools" args:"string original, string newname" returnType:"bool" returns:"True if the copy succeeded, otherwise false." remarks:"Copies a file on disk to a new name. All paths are relative to the script folder." example:"var contents = FileTools.copy('/logs/mylog.txt', '/logs/mybackup.txt');">>
+
+
+
<<func prefix:"FileTools" args:"string name" returnType:"bool" returns:"True if the file exists, otherwise false." remarks:"Checks to see if the specified file exists on disk. All paths are relative to the script folder." example:"if(FileTools.exists('/logs/mylog.txt'))
+	print('I have a log!');">>
+
+
+
<<func prefix:"FileTools" args:"string name" returnType:"string" returns:"The entire file contents." remarks:"Reads all of the contents from the specified file and returns it as a string. All paths are relative to the script folder." example:"var contents = FileTools.readText('/logs/mylog.txt');">>
+
+
+
<<func prefix:"FileTools" args:"string name" returnType:"bool" returns:"True if the file was removed, otherwise false." remarks:"Remove a file based on the file name. All paths are relative to the script folder." example:"FileTools.remove('/some/file.txt');">>
+
+
+
<<func prefix:"FileTools" args:"string original, string newname" returnType:"bool" returns:"True if the rename succeeded, otherwise false." remarks:"Renames a file on disk to a new name. All paths are relative to the script folder." example:"var contents = FileTools.rename('/logs/mylog.txt', '/logs/oldlog.txt');">>
+
+
+
<<func prefix:"FileTools" args:"string name, object content [, ... ]" returnType:"bool" returns:"True if of all the contents were successfully written, otherwise false." remarks:"Overwrites all of the old contents of a file with the new specified contents based on the file name. All paths are relative to the script folder." example:"FileTools.writeText('/logs/mylog.txt', 'January 1st. Found an old can of beans. No idea what it's for, but it's got to be useful for something.');">>
+
+
+
<<functionList prefix:"FileTools"
+	remove
+	rename
+	copy
+	exists
+	readText
+	writeText
+	appendText
+>>
+
+
+
//{{{
+
+config.macros.functionList = {
+	handler: function (place, macroName, params, wikifier, paramString) {
+		var args = paramString.parseParams(null,null,true);
+
+		var prefix = getParam(args, "prefix") || '';
+		if(prefix != '') {
+			prefix += '.';
+			params.shift();
+		}
+
+		var type = getParam(args, "type") || '';
+		if(type != '') {
+			type += ' ';
+			params.shift();
+		}
+
+		params = params.sort();
+		var functions = '!' + type + 'Functions:\r\n\r\n';
+		for(var i = 0; i < params.length; i++)
+		{
+			functions += '[[' + prefix + params[i] + ']]\r\n';
+		}
+
+		wikify(functions, place);
+	}
+};
+
+//}}}
+
+
+
//{{{
+
+config.macros.func = {
+	handler: function (place, macroName, params, wikifier, paramString, tiddler) {
+		var p = paramString.parseParams(null, null, true);
+		var name = getParam(p, "name") || tiddler.title.slice(tiddler.title.indexOf('.')+1);
+		var args = getParam(p, "args") || '';
+		var retVal = getParam(p, "returnType") || 'void';
+		var ret = getParam(p, "returns") || 'void';
+		var remarks = getParam(p, "remarks") || 'none';
+		var example = getParam(p, "example") || '';
+		var prefix = getParam(p, "prefix") || '';
+		wikify("!Function:\r\n{{{" + retVal + " " + (prefix != '' ? prefix + '.' : '') + name + "(" + args + ")}}}\r\n\r\n" +
+			 "''Returns:'' " + ret + "\r\n\r\n" +
+			 "!!!''Remarks:''\r\n" + remarks + "\r\n\r\n" +
+			 "!!!''Example:''\r\n{{{" + example + "}}}",
+			 place);
+	}
+};
+
+//}}}
+
+
+
<<functionList
+	getUnit
+	getPath
+	getCollision
+	getMercHP
+	getCursorType
+	getSkillByName
+	getSkillById
+	getLocaleString
+	getTextWidthHeight
+	getThreadPriority
+	getUIFlag
+	getTradeInfo
+	getWaypoint
+	getScript
+	getRoom
+	getParty
+	getPresetUnit
+	getPresetUnits
+	getArea
+	getBaseStat
+	getControl
+	getPlayerFlag
+	getTickCount
+	getInteractedNPC
+	print
+	delay
+	load
+	isIncluded
+	include
+	stop
+	rand
+	sendCopyData
+	sendDDE
+	keystate
+	addEventListener
+	removeEventListener
+	clearEvent
+	clearAllEvents
+	js_strict
+	version
+	scriptBroadcast
+	sqlite_version
+	dopen
+	debugLog
+	iniread
+	iniwrite
+	submitItem
+	login
+	createGame
+	joinGame
+	getLocation
+	getMouseCoords
+	copyUnit
+	clickMap
+	acceptTrade
+	beep
+	clickItem
+	getDistance
+	gold
+	checkCollision
+	playSound
+	quit
+	quitGame
+	say
+	clickParty
+	blockMinimize
+	weaponSwitch
+	transmute
+	md5
+	sha1
+	sha256
+	sha384
+	sha512
+	md5_file
+	sha1_file
+	sha256_file
+	sha384_file
+	sha512_file
+	addProfile
+	profileExists
+>>
+
+
+
<<objectList
+	me
+>>
+
+
+
As a test, we'll use a continuous spam message while we remain in game.
+
+Here's the code:
+{{{
+while(me.ingame)
+{
+	me.overhead("Hello, world!");
+	delay(1500);
+}
+}}}
+
+Save the above code as, for now, "test.dbj" inside of your scripts folder.
+
+Now open the default.dbj and add the following to the top of that file:
+
+{{{load("test.dbj");}}}
+
+Then, join a game and watch as your character says "Hello, world!" in his overhead message box!
+
+
+
<<event args:"int gid, int mode, string code, bool global" remarks:"If global is true, the item action is a 'world action', meaning everyone in game got the same event">>
+
+
+
GlobalFunctions
+GlobalObjects
+[[Objects]]
+[[Events]]
+[[FAQs]]
+
+
+
//{{{
+
+config.macros.objectList = {
+	handler: function (place, macroName, params, wikifier, paramString) {
+		var functions = "!Objects:\r\n\r\n";
+		params = params.sort();
+		for(var i = 0; i < params.length; i++)
+			functions += '[[' + params[i] + ']]\r\n';
+
+		wikify(functions, place);
+	}
+};
+
+//}}}
+
+
+
<<objectList
+	SQLiteObject
+	DBStatementObject
+	FileObject
+	FileToolsObject
+	D2BSScriptObject
+	FrameObject
+	BoxObject
+	LineObject
+	TextObject
+	ImageObject
+	SandboxObject
+	RoomObject
+	PresetUnitObject
+	PartyObject
+	ExitObject
+	DirectoryObject
+	ControlObject
+	AreaObject
+	UnitObject
+>>
+
+
+
//{{{
+
+config.macros.propertyList = {
+	handler: function (place, macroName, params, wikifier, paramString) {
+		var args = paramString.parseParams(null,null,true);
+		var prefix = getParam(args, "prefix") || '';
+		if(prefix != '') {
+			prefix += '.';
+			params.shift();
+		}
+		var functions = '!Properties:\r\n\r\n';
+		var start = (prefix != '' ? 1 : 0);
+		params = params.sort();
+		for(var i = start; i < params.length; i++)
+		{
+			functions += '[[' + prefix + params[i] + ']]\r\n';
+		}
+		wikify(functions, place);
+	}
+};
+
+//}}}
+
+
+
//{{{
+
+config.macros.property = {
+	handler: function (place, macroName, params, wikifier, paramString, tiddler) {
+		var p = paramString.parseParams(null, null, true);
+		var name = getParam(p, "name") || tiddler.title.slice(tiddler.title.indexOf('.')+1);
+		var type = getParam(p, "type") || '';
+		var remarks = getParam(p, "remarks") || 'none';
+		var example = getParam(p, "example") || '';
+		var prefix = getParam(p, "prefix") || '';
+		wikify("!Property:\r\n{{{" + type + " " + (prefix != '' ? prefix + '.' : '') + name +";}}}\r\n\r\n" +
+			 "!!!''Remarks:''\r\n" + remarks + "\r\n\r\n" +
+			 "!!!''Example:''\r\n{{{" + example + "}}}",
+			 place);
+	}
+};
+
+//}}}
+
+
+
everything you wanted to know about D2BS, but were afraid to ask
+
+
+
D2BS API
+
+
+
http://www.assembla.com/wiki/show/d2bs/
+
+
+
code { color: #555 !important; margin-left: 15px !important; }
+
+
+
!Function:
+{{{$1($2)}}}
+
+''Returns:'' $3
+
+!!!''Remarks:''
+$4
+
+!!!''Example:''
+{{{$5}}}
+
+
+
Welcome to the D2BS API Documentation.
+
+Online support is available [[via forums|http://www.edgeofnowhere.cc/index.php?c=22]] and [[via irc|irc://irc.synirc.net/d2bs]].
+
+The Assembla project page is available [[here|http://www.assembla.com/wiki/show/d2bs/]], and the latest release can be downloaded from the [[files section|http://www.assembla.com/spaces/d2bs/documents]].
+
+!!THIS DOCUMENT HAS BEEN SUPERCEDED BY THE DOCUMENTATION [[HERE|http://docs.d2bs.org]]
+
+This document is not complete! A lot of things are still missing, a lot of things have just stubs, and a lot of things need to be double checked to ensure accuracy! If you want to help with this, please contact any member of the D2BS team via forums or irc (linked above).
+
+
+
<<func args:"[ int mode ]" returnType:"int" returns:"If you pass a mode, the return value varies based on what mode. If you do not pass a mode, the return value is true if the trade action was not blocked, otherwise false" remarks:"Modes:
+1 - Whether or not you have accepted trade
+2 - Returns the trade flags (Not documented yet)
+3 - Whether or not the 'checkbox' is red (unable to trade)" example:"">>
+
+
+
<<func args:"string event, Function listener" returnType:"" returns:"" remarks:"Registers listener to listen to events of the specified type" example:"">>
+
+
+
<<func args:"string name, string mode, string gateway, string username, string password, string character" remarks:"Adds the specified profile to ~D2BS.ini." example:"if(!profileExists('test')) addProfile('test', 'single', '', '', '', 'tester');">>
+
+
+
<<func args:"uint type" remarks:"This function is the equivalent of the ~WinAPI function [[MessageBeep|http://msdn.microsoft.com/en-us/library/ms680356%28VS.85%29.aspx]]." example:"">>
+
+
+
<<func args:"bool enabled" returnType:"void" returns:"Nothing." remarks:"Enables or disables minimize blocking." example:"blockMinimize(true);">>
+
+
+
<<func args:"Unit a, Unit b, int collisionFlag" returnType:"bool" returns:"True if the collision values between Units a and b match the flag, otherwise false" remarks:"Uses the internal game's collision checking function" example:"">>
+
+
+
<<func args:"" returnType:"" returns:"" remarks:"Clears all registered event handlers for all events on the current script" example:"">>
+
+
+
<<func args:"string event" returnType:"" returns:"" remarks:"Clears all registered event handlers for the specified event on the current script" example:"">>
+
+
+
<<func args:"int clickType, [Unit item OR int x, int y [, int location] ]" remarks:"This function's parameters vary based on the desired functionality.
+Locations:
+0 - Inventory
+2 - Trade Window
+3 - Cube
+4 - Stash
+5 - Belt
+
+Click Types:
+0 - Left
+1 - Right
+2 - Shift-left (put to belt)
+3 - Mercenary Item (see below)
+
+Mercenary Body Locations:
+1 - Helmet
+3 - Armor
+4 - Weapon" example:"">>
+
+
+
<<func args:"int type, bool shift, [Unit a OR int x, int y]" returnType:"bool" returns:"True if the click succeeded, otherwise false" remarks:"Either a unit or an x/y is required. If you specify a unit, that unit will be selected prior to clicking. If shift is true, the character will stand in place while clicking. The coordinates are in-game coordinates.
+Click types:
+0 - Left down
+1 - Left held
+2 - Left up
+3 - Right down
+4 - Right held
+5 - Right up" example:"">>
+
+
+
<<func args:"Party obj, int mode" remarks:"The Party object comes from the [[getParty]] function
+Modes:
+0 - Loot player
+1 - Hostile player
+2 - Party with player
+3 - Leave current party" example:"">>
+
+
+
<<func args:"Unit a" returnType:"Unit" returns:"A copy of the Unit passed in" remarks:"Because Unit.getNext modifies the underlying unit instead of returning the new unit, this function is necessary to keep a copy of the old unit before working with it." example:"">>
+
+
+
<<func args:"string name[, string pass[, int difficulty ] ]" returns:"" remarks:"Attempts to create a game with the specified name and password in the specified difficulty.
+Difficulties:
+0 - Normal
+1 - Nightmare
+2 - Hell
+3 - Pick the hardest available" example:"">>
+
+
+
<<func args:"string message" returnType:"" returns:"" remarks:"Writes the specified message to the D2BS log" example:"">>
+
+
+
<<func args:"int milliseconds" returnType:"" returns:"" remarks:"Delays for the specified number of milliseconds. Milliseconds must be greater than 0." example:"">>
+
+
+
<<func args:"string path" returnType:"Directory" returns:"A [[Directory|DirectoryObject]] object representing the specified directory" remarks:"If the directory does not exist, it is created." example:"">>
+
+
+
<<func args:"[ int id ]" returnType:"Area" returns:"An Area object representing the specified area, if no area specified then the current one is assumed" remarks:"" example:"">>
+
+
+
<<func args:"int table OR string tableName, int row, int column OR string columnName" returnType:"string/int" returns:"The MPQ value for the specified row/column in the specified table" remarks:"Tables (these names are also valid for argument 1):
+0 - items
+1 - monstats
+2 - skilldesc
+3 - skills
+4 - objects
+5 - missiles
+6 - monstats2
+7 - itemstatcost
+8 - levels
+9 - leveldefs
+10 - lvlmaze
+11 - lvlsub
+12 - lvlwarp
+13 - lvlprest
+14 - lvltypes
+15 - charstats
+16 - setitems
+17 - uniqueitems
+18 - sets
+19 - itemtypes
+20 - runes
+21 - cubemain
+22 - gems 
+23 - experience
+24 - pettype
+25 - superuniques" example:"">>
+
+
+
<<func args:"int area, int x, int y" returnType:"int" returns:"The collision data for the specified (x, y) in the specified area" remarks:"" example:"">>
+
+
+
<<func args:"[ int type[, int x[, int y[, int xsize[, int ysize ] ] ] ] ]" returnType:"Control" returns:"A Control object matching the specified (if any) parameters" remarks:"All parameters are optional." example:"">>
+
+
+
<<func args:"[ bool shopType ]" returnType:"int" returns:"The type of cursor currently selected (possible values to be filled in later)" remarks:"" example:"">>
+
+
+
<<func args:"pick one: Unit a, Unit b OR int x, int y, Unit a OR Unit a, int x, int y OR int x, int y, int x2, int y2" returnType:"int" returns:"The distance between the specified points (Unit parameters use their x/y positions)" remarks:"This function has a complicated set of parameters for a reason: nearly anything can be passed to it." example:"">>
+
+
+
<<func args:"Area area" returnType:"Exit[]" returns:"An array of exits leading from the specified area" remarks:"" example:"">>
+
+
+
<<func args:"" returnType:"Unit" returns:"A [[Unit|UnitObject]] representing the current NPC you are interacted with; if not interacted, returns undefined" remarks:"" example:"">>
+
+
+
<<func args:"int id" returnType:"string" returns:"A string from the locale table representing the specified id" remarks:"" example:"">>
+
+
+
<<func args:"" returnType:"int" returns:"The current 'location' in the game menu." remarks:"Locations:
+0 - None
+1 - Lobby
+2 - In line
+3 - Chat channel
+4 - Create game screen
+5 - Join game screen
+6 - Ladder screen
+7 - Channel menu
+8 - Main menu
+9 - Login screen
+10 - Login error screen
+11 - Unable to Connect
+12 - Character select screen
+13 - Realm down
+14 - Disconnected
+15 - New Character (no character type selected) screen
+16 - Please Wait for Character Select
+17 - Lost connection screen
+18 - Diablo II Splash screen (prior to main menu)
+19 - CD Key in use screen
+20 - Single player difficulty selection screen
+21 - 'Connecting' screen (main menu)
+22 - Invalid CD Key screen
+23 - Some other 'Connecting' screen (need more documentation)
+24 - Server is Down screen
+25 - Please Wait screen
+26 - Game Exists screen
+27 - Gateway select screen
+28 - Game Does Not Exist message
+29 - New Character (character type selected) screen
+30 - Character Already Exists
+31 - 'Agree to terms' screen
+32 - New Account screen
+33 - 'Please read' screen
+34 - Register email screen
+35 - Credits screen
+36 - Cinematics list
+37 - Switch Realm (on character select) screen
+38 - Game is full message
+39 - Other Multiplayer screen
+40 - TCP/IP screen
+41 - 'Enter IP address' screen
+42 - Character select screen -- no characters are displayed
+43 - Change realm on character select screen (...? need more documentation here too)" example:"">>
+
+
+
<<func args:"" returnType:"int" returns:"The HP value (in percentage form) of your mercenary" remarks:"" example:"">>
+
+
+
<<func args:"[ bool mapCoords[, bool returnObject ] ]" returnType:"Array/Object" returns:"The current mouse coordinates." remarks:"If mapCoords is true, the coordinates are converted to map coordinates first. If returnObject is true, an object with an x/y property is returned instead of an array." example:"">>
+
+
+
<<func args:"" returnType:"Party" returns:"A Party object representing the first roster in the list" remarks:"" example:"">>
+
+
+
<<func args:"int area or int[] areas, int startX, int startY, int endX, int endY [, bool useTeleportPathing [, int radius [, bool useReduction ] ] ]" returnType:"int[]" returns:"A path representing the points needed to travel in order to get from (startX, startY) to (endX, endY) with the specified parameters" remarks:"" example:"">>
+
+
+
<<func args:"int unitid, int unitid, int flag" returnType:"bool" returns:"True if the specified flag is set, otherwise false" remarks:"The units must be specified by gid. Need documentation on what flags are available." example:"">>
+
+
+
<<func args:"int area[, int type[, int classid ] ]" returnType:"PresetUnit" returns:"The first preset unit matching the specified type and classid in the specified area" remarks:"" example:"">>
+
+
+
<<func args:"int area[, int type[, int classid ] ]" returnType:"PresetUnit[]" returns:"An array of all preset units matching the specified type and classid in the specified area" remarks:"" example:"">>
+
+
+
<<func args:"[ int area OR int x, int y OR int area, int x, int y ]" returnType:"Room" returns:"A Room object matching the specified parameters" remarks:"If area is 0, then the current area is assumed" example:"">>
+
+
+
<<func args:"[ bool current OR string name OR int threadId ]" returnType:"D2BSScript" returns:"A ~D2BSScript object matching either the name or the thread id (or the current script, if true is passed instead)." remarks:"" example:"">>
+
+
+
<<func args:"int id" returnType:"string" returns:"The name of the specified skill ID." remarks:"Looks up the name of the skill ID based on the internal table (this will be replaced with MPQ lookup at some point)." example:"var name = getSkillById(1);">>
+
+
+
<<func args:"string name" returnType:"int" returns:"The ID of the specified skill name." remarks:"Looks up the ID of the skill name based on the internal table (this will be replaced with MPQ lookup at some point)." example:"var id = getSkillByName('kick');">>
+
+
+
<<func args:"string text[, bool returnObject ]" returnType:"Array/Object" returns:"The width and height of the specified text" remarks:"If returnObject is true, an object with a width/height property is returned instead of an array" example:"">>
+
+
+
<<func returnType:"int" returns:"The priority of the current script's execution thread." remarks:"This function is the equivalent of the ~WinAPI function [[of the same name|http://msdn.microsoft.com/en-us/library/ms683235%28VS.85%29.aspx]]." example:"print('My thread priority is ' + getThreadPriority());">>
+
+
+
<<func args:"" returnType:"int" returns:"The current system tick count" remarks:"This function is identical to the ~WinAPI function [[of the same name|http://msdn.microsoft.com/en-us/library/ms724408%28VS.85%29.aspx]]." example:"">>
+
+
+
<<func args:"int mode" returnType:"int" returns:"If mode is 0, returns the current trade flags. If mode is 1, returns the name of the most recent trading partner. If mode is 2, returns the gid of the most recent trading partner." remarks:"" example:"">>
+
+
+
<<func args:"int flag" returnType:"bool" returns:"True if the specified screen is open, otherwise false" remarks:"Flags:
+0 - Nothing
+1 - Inventory screen
+2 - Character screen
+3 - Skill speedbar
+4 - Skill tree
+5 - Chat box
+6 - Unknown
+7 - Unknown
+8 - NPC menu
+9 - NPC dialog (NPC talking at you)
+10 - Main ESC menu
+11 - Automap
+12 - Hotkey configuration
+13 - NPC shop menu
+14 - ALT held
+15 - Item submit screen
+16 - Quest button visible
+17 - Bark scroll (...? Need more documentation)
+18 - Quest screen
+19 - Status area (...? Need more documentation)
+20 - ESC menu extras (...? Need more documentation)
+21 - Waypoint screen
+22 - Mini-panel visible
+23 - Party screen
+24 - Trade screen (which one? Need more documentation)
+25 - Message log
+26 - Stash screen
+27 - Cube screen
+28 - Inventory extras (...? Need more documentation)
+29 - Inventory extras 2 (...? Need more documentation)
+30 - Belt open
+31 - Help screen
+32 - Help button visible
+33 - ESC menu (unused?)
+34 - Mercenary screen
+35 - Scroll (...? Need more documentation)" example:"">>
+
+
+
<<func args:"int type [, string localizedName or int classid [, int mode [, int globalid ] ] ]" returnType:"Unit" returns:"A [[Unit|UnitObject]] object representing the specified unit, or undefined" remarks:"This function scans the local rooms for units matching the specified criteria.
+If bit 30 of mode is on, then mode is treated as a bitmask, where the number of the bit corresponds to the mode to check, and any unit matching any of the specified modes is returned." example:"">>
+
+
+
<<func args:"int waypoint" returnType:"bool" returns:"True if the player has the specified waypoint, otherwise false" remarks:"You must interact with a waypoint before you can call this function, otherwise it will always return false. Waypoints are ordered by their actual number on the waypoint page (i.e. Rogue Encampment is 0, Lut Gholein is 10)" example:"">>
+
+
+
<<func args:"int amount, int mode" remarks:"Performs the requested gold transaction with the specified amount
+Modes:
+Currently unknown (needs to be documented)" example:"">>
+
+
+
<<func args:"string file" returnType:"bool" returns:"True if the file successfully included, otherwise false" remarks:"The file path is relative to the <scripts>\libs folder." example:"">>
+
+
+
<<func args:"string file, string section, string key, string default" returnType:"string" returns:"The specified key in the specified section of the specified INI file" remarks:"''THIS FUNCTION IS DEPRECATED.'' It will be removed in future releases." example:"">>
+
+
+
<<func args:"string file, string section, string key, string value" returnType:"void" returns:"" remarks:"''THIS FUNCTION IS DEPRECATED.'' It will be removed in future releases.
+Writes the specified key with the specified value to the specified section of the specified file." example:"">>
+
+
+
<<func args:"string file" returnType:"bool" returns:"True if the file is included, otherwise false" remarks:"The file path is relative to the <scripts>\libs folder." example:"">>
+
+
+
<<func args:"string name[, string password]" returns:"" remarks:"Attempts to join the specified game" example:"">>
+
+
+
<<func args:"[bool enabled]" returnType:"bool" returns:"If no parameter is passed, returns the current strict setting. Otherwise, no return value." remarks:"Enables or disables strict evaluation for the current script. Defaults to disabled, but highly recommended to enable" example:"js_strict(true);">>
+
+
+
<<func args:"int vKey" returnType:"bool" returns:"True if the key is currently pressed, otherwise false" remarks:"This function is identical to the ~WinAPI function [[GetAsyncKeyState|http://msdn.microsoft.com/en-us/library/ms646293%28VS.85%29.aspx]]." example:"">>
+
+
+
<<func args:"string file" returnType:"bool" returns:"True if the script successfully loaded, otherwise false" remarks:"The file path is relative to the <scripts> folder." example:"">>
+
+
+
<<func args:"string profileName" returnType:"" returns:"" remarks:"Attempts to log into the specified profileName. The profileName comes from the section inside d2bs.ini." example:"">>
+
+
+
D2BS lead developer and all around awesome guy.
+
+
+
<<func args:"string value" returnType:"string" returns:"The ~MD5 value of the input." remarks:"This function implements the algorithm described [[here|http://en.wikipedia.org/wiki/Md5]]." example:"var result = md5('Hello');">>
+
+
+
<<func args:"string fileName" returnType:"string" returns:"The ~MD5 value of the file specified as input." remarks:"This function implements the algorithm described [[here|http://en.wikipedia.org/wiki/Md5]]. All paths are relative to the script folder." example:"var result = md5_file('Hello.txt');">>
+
+
+
<<functionList prefix:"me"
+	getRepairCost
+>>
+
+<<propertyList prefix:"me"
+	account
+	charname
+	diff
+	gamename
+	gamepassword
+	gameserverip
+	gamestarttime
+	gametype
+	itemoncursor
+	ladder
+	ping
+	fps
+	playertype
+	realm
+	realmshort
+	mercrevivecost
+	runwalk
+	weaponswitch
+	chickenhp
+	chickenmp
+	quitonhostile
+	blockKeys
+	blockMouse
+	screensize
+	windowtitle
+	ingame
+	quitonerror
+	maxgametime
+>>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current account name, or undefined if not logged into Battle.net" example:"print('I am currently logged into ' + me.account);">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns the current keystroke block setting (can be toggled, true to enable key blocking, false to disable)" example:"me.blockKeys = true; /* block incoming keystrokes from reaching the client */">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns the current mouse block setting (can be toggled, true to enable mouse blocking, false to disable)" example:"me.blockMouse = true; /* block mouse moves/clicks from reaching the client */">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current character name, or an empty string if not in a game" example:"print('I am ' + me.charname);">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current HP chicken setting (can be set to change the current HP chicken setting, 0 to disable)" example:"me.chickenhp = parseInt(me.hpmax * .1, 10); /* set to chicken at 10% health */">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current MP chicken setting (can be set to change the current MP chicken setting, 0 to disable)" example:"me.chickenmp = parseInt(me.mpmax * .2, 10); /* set to chicken at 20% mana */">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the difficulty of the current game, or 0 if not in a game.
+0 - Normal
+1 - Nightmare
+2 - Hell"
+example:"print('I am in ' + ['normal', 'nightmare', 'hell'][me.diff] + ' difficulty');">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current frames-per-second (as measured by the client)" example:"print('The current fps is ' + me.fps);">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current game name, or an empty string if not in a game or in a single player game" example:"print('The current game is ' + me.gamename);">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current game password, or an empty string if not in a game or in a single player game" example:"print('The current game's password is ' + me.gamepassword);">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current game's ip address" example:"print('The current game server is ' + me.gameserverip);">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the start time (in ticks) of the current game" example:"print('I entered this game ' + me.gamestarttime + ' ticks ago');">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current game type
+0 - Classic
+1 - Expansion" example:"print('The current game type is ' + ['Classic', 'Expansion'][me.gametype]);">>
+
+
+
<<func prefix:"me" args:"[ int classid ]" returnType:"" returns:"" remarks:"The classid parameter is any NPC classid with (defaults to the current NPC)" example:"">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns false if at the menu, otherwise true" example:"print('I am' + (me.ingame ? ' ' : ' not ') + 'in a game');">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns true if you have an item on the cursor, false if not" example:"print('I ' + (me.itemoncursor ? 'do' : 'do not') +' have an item on my cursor');">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns true if the character is a ladder character, false if not" example:"print('I am' + (me.ladder ? ' ' : ' not ') + 'a ladder character');">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current maximum game time (in seconds, 0 to disable)" example:"me.maxgametime = 300; /* quit after 300 seconds */">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the cost to revive your merc (0 if already alive)" example:"print('My merc is ' + (me.mercrevivecost > 0 ? 'dead' : 'alive'));">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current ping (as measured by the client)" example:"print('The current ping is ' + me.ping);">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current player type
+0 - Softcore
+1 - Hardcore" example:"print('I am a ' + ['softcore', 'hardcore'][me.playertype] + ' character');">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns the current error chicken setting (can be set to change the current error chicken setting, false to disable)" example:"me.quitonerror = true; /* quit if my script has an error */">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns the current hostile chicken setting (can be set to change the current hostile chicken setting, false to disable)" example:"me.quitonhostile = true; /* set to chicken on hostile */">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current realm (long name)" example:"print('The current realm is ' + me.realm);">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current realm (short name)" example:"print('The (shorter) current realm is ' + me.realmshort);">>
+
+
+
<<property type:"bool" prefix:"me" remarks:"Returns true if run/walk is set to run, false if not (can also be set to enable/disable run/walk)" example:"print('I am currently ' + ['walking', 'running'][parseInt(me.runwalk, 10)]);">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current screen size
+0 - 640x480
+1 - 800x600" example:"print('I am running at ' + ['640x480', '800x600'][me.screensize]);">>
+
+
+
<<property type:"int" prefix:"me" remarks:"Returns the current weapon switch (can also be set to toggle the weapon switch)" example:"print('My current weapon switch is ' + me.weaponswitch);">>
+
+
+
<<property type:"string" prefix:"me" remarks:"Returns the current window title" example:"print('The window title is ' + me.windowtitle);">>
+
+
+
<<func args:"int soundId" remarks:"Plays the sound based on the id you pass in (the id can be found in the sounds.txt file in patch_d2.mpq)" example:"">>
+
+
+
<<func args:"string message, ..." returnType:"" returns:"" remarks:"Writes the specified messages to the console and (optionally, based on the d2bs.ini setting) the screen" example:"">>
+
+
+
<<func args:"string profileName" returnType:"bool" returns:"True if the profile exists, otherwise false" remarks:"Checks the existing profiles in ~D2BS.ini to see if the specified one exists.">>
+
+
+
<<func remarks:"Quits the current game" example:"">>
+
+
+
<<func remarks:"Quits the entire Diablo II process" example:"">>
+
+
+
<<func args:"int min, int max" returnType:"int" returns:"A number between min and max" remarks:"Uses C [[rand|http://www.cppreference.com/wiki/c/other/rand]] (seeded with the current time) when out of game, and Diablo II's internal RNG when in game." example:"">>
+
+
+
<<func args:"string event, Function listener" returnType:"" returns:"" remarks:"If listener is registered for event, it is removed" example:"">>
+
+
+
<<func args:"string message" remarks:"Sends a message to the other players in the game" example:"">>
+
+
+
<<func args:"..." returnType:"" returns:"" remarks:"Takes any number of arguments and broadcasts them as-is to all scripts currently running." example:"">>
+
+
+
<<func args:"string windowClass, string windowName, int mode, string data" returnType:"int" returns:"False if the window is not found, otherwise true or false depending on if the window processed the message" remarks:"This function sends a [[WM_COPYDATA|http://msdn.microsoft.com/en-us/library/ms649011%28VS.85%29.aspx]] event to the target window." example:"">>
+
+
+
<<func args:"int mode, string server, string topic, string item, string data" returnType:"" returns:"" remarks:"For more information, see [[here|http://msdn.microsoft.com/en-us/library/ms648774%28VS.85%29.aspx]].
+Modes:
+0 - ~XTYP_REQUEST
+1 - ~XTYP_POKE
+2 - ~XTYP_EXECUTE" example:"">>
+
+
+
<<func args:"string value" returnType:"string" returns:"The ~SHA-1 value of the input." remarks:"This function implements the algorithm for ~SHA-1 described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]." example:"var result = sha1('Hello');">>
+
+
+
<<func args:"string fileName" returnType:"string" returns:"The ~SHA-1 value of the file specified as input." remarks:"This function implements the ~SHA-1 algorithm described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]. All paths are relative to the script folder." example:"var result = sha1_file('Hello.txt');">>
+
+
+
<<func args:"string value" returnType:"string" returns:"The ~SHA-256 value of the input." remarks:"This function implements the algorithm for ~SHA-256 described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]." example:"var result = sha256('Hello');">>
+
+
+
<<func args:"string fileName" returnType:"string" returns:"The ~SHA-256 value of the file specified as input." remarks:"This function implements the ~SHA-256 algorithm described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]. All paths are relative to the script folder." example:"var result = sha256_file('Hello.txt');">>
+
+
+
<<func args:"string value" returnType:"string" returns:"The ~SHA-384 value of the input." remarks:"This function implements the algorithm for ~SHA-384 described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]." example:"var result = sha384('Hello');">>
+
+
+
<<func args:"string fileName" returnType:"string" returns:"The ~SHA-384 value of the file specified as input." remarks:"This function implements the ~SHA-384 algorithm described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]. All paths are relative to the script folder." example:"var result = sha384_file('Hello.txt');">>
+
+
+
<<func args:"string value" returnType:"string" returns:"The ~SHA-512 value of the input." remarks:"This function implements the algorithm for ~SHA-512 described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]." example:"var result = sha512('Hello');">>
+
+
+
<<func args:"string fileName" returnType:"string" returns:"The ~SHA-512 value of the file specified as input." remarks:"This function implements the ~SHA-512 algorithm described [[here|http://en.wikipedia.org/wiki/SHA_hash_functions]]. All paths are relative to the script folder." example:"var result = sha512_file('Hello.txt');">>
+
+
+
<<func args:"" returnType:"string" returns:"The ~SQLite library version" remarks:"" example:"">>
+
+
+
<<func args:"[ bool stopAll ]" returnType:"" returns:"" remarks:"Stops the current script, if stopAll is true then it stops all scripts." example:"">>
+
+
+
<<func args:"" returnType:"" returns:"" remarks:"Submits the item on the cursor." example:"">>
+
+
+
<<func remarks:"Transmutes the current contents of the Horadric Cube. The cube must be open for this function to work." example:"clickItem(1, getUnit(4, 'box')); delay(1000); transmute();">>
+
+
+
<<func args:"[ bool returnAsWell ]" returnType:"string" returns:"The current version" remarks:"Prints the current version, and if returnAsWell is true, returns it" example:"">>
+
+
+
<<func args:"[ bool switch ]" returnType:"int" returns:"True if switch is specified, otherwise the current weapon switch" remarks:"The return value varies depending on the arguments passed in; if you pass true, the return value is always true, otherwise the return value is an int representing the current weapon switch." example:"">>
+
+
+ + + + + + + + + + + + + diff --git a/resources/d2bs.ini b/resources/d2bs.ini new file mode 100644 index 00000000..633a1deb --- /dev/null +++ b/resources/d2bs.ini @@ -0,0 +1,62 @@ +; boolean values: +; 't' or 'T' or 'true' or 'TRUE' or 1 for true/enabled +; 'f' or 'F' or 'false' or 'FALSE' or 0 for false/disabled + +; UseProfileScript - set to true to specify the ScriptPath, DefaultGameScript, and DefaultStarterScript settings per-profile (requires external support) +; ScriptPath - set to the folder (relative to d2bs) where your scripts are located +; DefaultGameScript - set to the file inside ScriptPath that you want to start as the default game script +; DefaultStarterScript - set to the file inside ScriptPath that you want to start when D2BS is first loaded and runs during the channel stuff +; MaxGameTime - set to 0 to disable, otherwise this is the max length of the game in seconds +; QuitOnHostile - set to a boolean value to disable/enable quitting on hostile +; QuitOnError - set to a boolean value to disable/enable quitting on errors +; StartAtMenu - set to a boolean value to disable/enable starting at menu (has no effect for users, developer toggle) +; MemoryLimit - set to 0 for default(50MB), otherwise the number of MB to limit memory to - Don't change this unless you know what you are doing. +; MaxLoginTime - time in seconds to wait for logging in +; MaxCharSelectTime - time in seconds to wait for the character select screen to load +; GameReadyTimeout - time in seconds to wait for act changes, etc. before the core reports a failure +; DisableCache - setting for developers to test loading scripts, defaults to false +; UseGamePrint - set to false to use only the console for printing, or true to print to the console and the game buffer +; LogConsoleOutput - set to true to log the console output to d2bs.log, or false to disable + +[settings] +UseProfileScript=false +ScriptPath=scripts +DefaultGameScript=default.dbj +DefaultStarterScript=starter.dbj + +MaxGameTime=0 +QuitOnHostile=false +QuitOnError=false +StartAtMenu=false +MemoryLimit=0 +MaxLoginTime=5 +MaxCharSelectTime=5 +GameReadyTimeout=5 +DisableCache=true +UseGamePrint=false +LogConsoleOutput=false + +; these settings are for the login() function +; you pass the name of the section (i.e. "my sp character") +; as the argument to login, and it takes care of the rest +; example as per below: login("my single player character"); + +; ScriptPath - as per the entry in [settings] +; DefaultGameScript - as per the entry in [settings] +; DefaultStarterScript - as per the entry in [settings] +; see: UseProfileScript for more information +; mode - the type of login it is. possible modes: single, battle.net, other multiplayer +; character - the actual name of the character, as displayed on the screen +; spdifficulty - the single player difficulty setting. possible difficulties: 0 - normal, 1 - nightmare, 2 - hell +; note: this has NOTHING AT ALL to do with battle.net game creation! +; username - your battle.net username +; password - the password to the above account +; gateway - the gateway your account resides on (US East, US West, etc.) + +; [my single player character] +; mode=single +; character=whatever +; spdifficulty=0 +; username= +; password= +; gateway= diff --git a/resources/version.bmp b/resources/version.bmp new file mode 100644 index 00000000..4e708f6b Binary files /dev/null and b/resources/version.bmp differ diff --git a/sqlite3.c b/sqlite3.c new file mode 100644 index 00000000..10833111 --- /dev/null +++ b/sqlite3.c @@ -0,0 +1,123309 @@ +/****************************************************************************** +** This file is an amalgamation of many separate C source files from SQLite +** version 3.7.5. By combining all the individual C code files into this +** single large file, the entire code can be compiled as a one translation +** unit. This allows many compilers to do optimizations that would not be +** possible if the files were compiled separately. Performance improvements +** of 5% or more are commonly seen when SQLite is compiled as a single +** translation unit. +** +** This file is all you need to compile SQLite. To use SQLite in other +** programs, you need this file and the "sqlite3.h" header file that defines +** the programming interface to the SQLite library. (If you do not have +** the "sqlite3.h" header file at hand, you will find a copy embedded within +** the text of this file. Search for "Begin file sqlite3.h" to find the start +** of the embedded sqlite3.h header file.) Additional code files may be needed +** if you want a wrapper to interface SQLite with your choice of programming +** language. The code for the "sqlite3" command-line shell is also in a +** separate file. This file contains only code for the core SQLite library. +*/ +#define SQLITE_CORE 1 +#define SQLITE_AMALGAMATION 1 +#ifndef SQLITE_PRIVATE +# define SQLITE_PRIVATE static +#endif +#ifndef SQLITE_API +# define SQLITE_API +#endif +/************** Begin file sqliteInt.h ***************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Internal interface definitions for SQLite. +** +*/ +#ifndef _SQLITEINT_H_ +#define _SQLITEINT_H_ + +/* +** These #defines should enable >2GB file support on POSIX if the +** underlying operating system supports it. If the OS lacks +** large file support, or if the OS is windows, these should be no-ops. +** +** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any +** system #includes. Hence, this block of code must be the very first +** code in all source files. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: Red Hat 7.2) but you want your code to work +** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in Red Hat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + +/* +** Include the configuration header output by 'configure' if we're using the +** autoconf-based build +*/ +#ifdef _HAVE_SQLITE_CONFIG_H +#include "config.h" +#endif + +/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ +/************** Begin file sqliteLimit.h *************************************/ +/* +** 2007 May 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file defines various limits of what SQLite can process. +*/ + +/* +** The maximum length of a TEXT or BLOB in bytes. This also +** limits the size of a row in a table or index. +** +** The hard limit is the ability of a 32-bit signed integer +** to count the size: 2^31-1 or 2147483647. +*/ +#ifndef SQLITE_MAX_LENGTH +# define SQLITE_MAX_LENGTH 1000000000 +#endif + +/* +** This is the maximum number of +** +** * Columns in a table +** * Columns in an index +** * Columns in a view +** * Terms in the SET clause of an UPDATE statement +** * Terms in the result set of a SELECT statement +** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. +** * Terms in the VALUES clause of an INSERT statement +** +** The hard upper limit here is 32676. Most database people will +** tell you that in a well-normalized database, you usually should +** not have more than a dozen or so columns in any table. And if +** that is the case, there is no point in having more than a few +** dozen values in any of the other situations described above. +*/ +#ifndef SQLITE_MAX_COLUMN +# define SQLITE_MAX_COLUMN 2000 +#endif + +/* +** The maximum length of a single SQL statement in bytes. +** +** It used to be the case that setting this value to zero would +** turn the limit off. That is no longer true. It is not possible +** to turn this limit off. +*/ +#ifndef SQLITE_MAX_SQL_LENGTH +# define SQLITE_MAX_SQL_LENGTH 1000000000 +#endif + +/* +** The maximum depth of an expression tree. This is limited to +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might +** want to place more severe limits on the complexity of an +** expression. +** +** A value of 0 used to mean that the limit was not enforced. +** But that is no longer true. The limit is now strictly enforced +** at all times. +*/ +#ifndef SQLITE_MAX_EXPR_DEPTH +# define SQLITE_MAX_EXPR_DEPTH 1000 +#endif + +/* +** The maximum number of terms in a compound SELECT statement. +** The code generator for compound SELECT statements does one +** level of recursion for each term. A stack overflow can result +** if the number of terms is too large. In practice, most SQL +** never has more than 3 or 4 terms. Use a value of 0 to disable +** any limit on the number of terms in a compount SELECT. +*/ +#ifndef SQLITE_MAX_COMPOUND_SELECT +# define SQLITE_MAX_COMPOUND_SELECT 500 +#endif + +/* +** The maximum number of opcodes in a VDBE program. +** Not currently enforced. +*/ +#ifndef SQLITE_MAX_VDBE_OP +# define SQLITE_MAX_VDBE_OP 25000 +#endif + +/* +** The maximum number of arguments to an SQL function. +*/ +#ifndef SQLITE_MAX_FUNCTION_ARG +# define SQLITE_MAX_FUNCTION_ARG 127 +#endif + +/* +** The maximum number of in-memory pages to use for the main database +** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE +*/ +#ifndef SQLITE_DEFAULT_CACHE_SIZE +# define SQLITE_DEFAULT_CACHE_SIZE 2000 +#endif +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 +#endif + +/* +** The default number of frames to accumulate in the log file before +** checkpointing the database in WAL mode. +*/ +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 +#endif + +/* +** The maximum number of attached databases. This must be between 0 +** and 30. The upper bound on 30 is because a 32-bit integer bitmap +** is used internally to track attached databases. +*/ +#ifndef SQLITE_MAX_ATTACHED +# define SQLITE_MAX_ATTACHED 10 +#endif + + +/* +** The maximum value of a ?nnn wildcard that the parser will accept. +*/ +#ifndef SQLITE_MAX_VARIABLE_NUMBER +# define SQLITE_MAX_VARIABLE_NUMBER 999 +#endif + +/* Maximum page size. The upper bound on this value is 65536. This a limit +** imposed by the use of 16-bit offsets within each page. +** +** Earlier versions of SQLite allowed the user to change this value at +** compile time. This is no longer permitted, on the grounds that it creates +** a library that is technically incompatible with an SQLite library +** compiled with a different limit. If a process operating on a database +** with a page-size of 65536 bytes crashes, then an instance of SQLite +** compiled with the default page-size limit will not be able to rollback +** the aborted transaction. This could lead to database corruption. +*/ +#ifdef SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_PAGE_SIZE +#endif +#define SQLITE_MAX_PAGE_SIZE 65536 + + +/* +** The default size of a database page. +*/ +#ifndef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE 1024 +#endif +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_DEFAULT_PAGE_SIZE +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + +/* +** Ordinarily, if no value is explicitly provided, SQLite creates databases +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain +** device characteristics (sector-size and atomic write() support), +** SQLite may choose a larger value. This constant is the maximum value +** SQLite will choose on its own. +*/ +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 +#endif +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE +#endif + + +/* +** Maximum number of pages in one database file. +** +** This is really just the default value for the max_page_count pragma. +** This value can be lowered (or raised) at run-time using that the +** max_page_count macro. +*/ +#ifndef SQLITE_MAX_PAGE_COUNT +# define SQLITE_MAX_PAGE_COUNT 1073741823 +#endif + +/* +** Maximum length (in bytes) of the pattern in a LIKE or GLOB +** operator. +*/ +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 +#endif + +/* +** Maximum depth of recursion for triggers. +** +** A value of 1 means that a trigger program will not be able to itself +** fire any triggers. A value of 0 means that no trigger programs at all +** may be executed. +*/ +#ifndef SQLITE_MAX_TRIGGER_DEPTH +# define SQLITE_MAX_TRIGGER_DEPTH 1000 +#endif + +/************** End of sqliteLimit.h *****************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/* Disable nuisance warnings on Borland compilers */ +#if defined(__BORLANDC__) +#pragma warn -rch /* unreachable code */ +#pragma warn -ccc /* Condition is always true or false */ +#pragma warn -aus /* Assigned value is never used */ +#pragma warn -csu /* Comparing signed and unsigned */ +#pragma warn -spa /* Suspicious pointer arithmetic */ +#endif + +/* Needed for various definitions... */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE +#endif + +/* +** Include standard header files as necessary +*/ +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif + +/* +** The number of samples of an index that SQLite takes in order to +** construct a histogram of the table content when running ANALYZE +** and with SQLITE_ENABLE_STAT2 +*/ +#define SQLITE_INDEX_SAMPLES 10 + +/* +** The following macros are used to cast pointers to integers and +** integers to pointers. The way you do this varies from one compiler +** to the next, so we have developed the following set of #if statements +** to generate appropriate macros for a wide range of compilers. +** +** The correct "ANSI" way to do this is to use the intptr_t type. +** Unfortunately, that typedef is not available on all compilers, or +** if it is available, it requires an #include of specific headers +** that vary from one machine to the next. +** +** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on +** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). +** So we have to define the macros in different ways depending on the +** compiler. +*/ +#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ +# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) +#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ +# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) +# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) +#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ +# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) +#else /* Generates a warning - but it always works */ +# define SQLITE_INT_TO_PTR(X) ((void*)(X)) +# define SQLITE_PTR_TO_INT(X) ((int)(X)) +#endif + +/* +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. +** 0 means mutexes are permanently disable and the library is never +** threadsafe. 1 means the library is serialized which is the highest +** level of threadsafety. 2 means the libary is multithreaded - multiple +** threads can use SQLite as long as no two threads try to use the same +** database connection at the same time. +** +** Older versions of SQLite used an optional THREADSAFE macro. +** We support that for legacy. +*/ +#if !defined(SQLITE_THREADSAFE) +#if defined(THREADSAFE) +# define SQLITE_THREADSAFE THREADSAFE +#else +# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ +#endif +#endif + +/* +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. +** It determines whether or not the features related to +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can +** be overridden at runtime using the sqlite3_config() API. +*/ +#if !defined(SQLITE_DEFAULT_MEMSTATUS) +# define SQLITE_DEFAULT_MEMSTATUS 1 +#endif + +/* +** Exactly one of the following macros must be defined in order to +** specify which memory allocation subsystem to use. +** +** SQLITE_SYSTEM_MALLOC // Use normal system malloc() +** SQLITE_MEMDEBUG // Debugging version of system malloc() +** +** (Historical note: There used to be several other options, but we've +** pared it down to just these two.) +** +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as +** the default. +*/ +#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1 +# error "At most one of the following compile-time configuration options\ + is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG" +#endif +#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0 +# define SQLITE_SYSTEM_MALLOC 1 +#endif + +/* +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the +** sizes of memory allocations below this value where possible. +*/ +#if !defined(SQLITE_MALLOC_SOFT_LIMIT) +# define SQLITE_MALLOC_SOFT_LIMIT 1024 +#endif + +/* +** We need to define _XOPEN_SOURCE as follows in order to enable +** recursive mutexes on most Unix systems. But Mac OS X is different. +** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, +** so it is omitted there. See ticket #2673. +** +** Later we learn that _XOPEN_SOURCE is poorly or incorrectly +** implemented on some systems. So we avoid defining it at all +** if it is already defined or if it is unneeded because we are +** not doing a threadsafe build. Ticket #2681. +** +** See also ticket #2741. +*/ +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE +# define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ +#endif + +/* +** The TCL headers are only needed when compiling the TCL bindings. +*/ +#if defined(SQLITE_TCL) || defined(TCLSH) +# include +#endif + +/* +** Many people are failing to set -DNDEBUG=1 when compiling SQLite. +** Setting NDEBUG makes the code smaller and run faster. So the following +** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1 +** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out +** feature. +*/ +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) +# define NDEBUG 1 +#endif + +/* +** The testcase() macro is used to aid in coverage testing. When +** doing coverage testing, the condition inside the argument to +** testcase() must be evaluated both true and false in order to +** get full branch coverage. The testcase() macro is inserted +** to help ensure adequate test coverage in places where simple +** condition/decision coverage is inadequate. For example, testcase() +** can be used to make sure boundary values are tested. For +** bitmask tests, testcase() can be used to make sure each bit +** is significant and used at least once. On switch statements +** where multiple cases go to the same block of code, testcase() +** can insure that all cases are evaluated. +** +*/ +#ifdef SQLITE_COVERAGE_TEST +SQLITE_PRIVATE void sqlite3Coverage(int); +# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } +#else +# define testcase(X) +#endif + +/* +** The TESTONLY macro is used to enclose variable declarations or +** other bits of code that are needed to support the arguments +** within testcase() and assert() macros. +*/ +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) +# define TESTONLY(X) X +#else +# define TESTONLY(X) +#endif + +/* +** Sometimes we need a small amount of code such as a variable initialization +** to setup for a later assert() statement. We do not want this code to +** appear when assert() is disabled. The following macro is therefore +** used to contain that setup code. The "VVA" acronym stands for +** "Verification, Validation, and Accreditation". In other words, the +** code within VVA_ONLY() will only run during verification processes. +*/ +#ifndef NDEBUG +# define VVA_ONLY(X) X +#else +# define VVA_ONLY(X) +#endif + +/* +** The ALWAYS and NEVER macros surround boolean expressions which +** are intended to always be true or false, respectively. Such +** expressions could be omitted from the code completely. But they +** are included in a few cases in order to enhance the resilience +** of SQLite to unexpected behavior - to make the code "self-healing" +** or "ductile" rather than being "brittle" and crashing at the first +** hint of unplanned behavior. +** +** In other words, ALWAYS and NEVER are added for defensive code. +** +** When doing coverage testing ALWAYS and NEVER are hard-coded to +** be true and false so that the unreachable code then specify will +** not be counted as untested code. +*/ +#if defined(SQLITE_COVERAGE_TEST) +# define ALWAYS(X) (1) +# define NEVER(X) (0) +#elif !defined(NDEBUG) +# define ALWAYS(X) ((X)?1:(assert(0),0)) +# define NEVER(X) ((X)?(assert(0),1):0) +#else +# define ALWAYS(X) (X) +# define NEVER(X) (X) +#endif + +/* +** Return true (non-zero) if the input is a integer that is too large +** to fit in 32-bits. This macro is used inside of various testcase() +** macros to verify that we have tested SQLite for large-file support. +*/ +#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) + +/* +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. GCC is able to +** use these hints to generate better code, sometimes. +*/ +#if defined(__GNUC__) && 0 +# define likely(X) __builtin_expect((X),1) +# define unlikely(X) __builtin_expect((X),0) +#else +# define likely(X) !!(X) +# define unlikely(X) !!(X) +#endif + +/************** Include sqlite3.h in the middle of sqliteInt.h ***************/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve the right to make minor changes +** if experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +#ifndef SQLITE_API +# define SQLITE_API +#endif + + +/* +** These no-op macros are used in front of interfaces to mark those +** interfaces as either deprecated or experimental. New applications +** should not use deprecated interfaces - they are support for backwards +** compatibility only. Application writers should be aware that +** experimental interfaces are subject to change in point releases. +** +** These macros used to resolve to various kinds of compiler magic that +** would generate warning messages when they were used. But that +** compiler magic ended up generating such a flurry of bug reports +** that we have taken it all out and gone back to using simple +** noop macros. +*/ +#define SQLITE_DEPRECATED +#define SQLITE_EXPERIMENTAL + +/* +** Ensure these symbols were not defined by some previous header file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers +** +** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header +** evaluates to a string literal that is the SQLite version in the +** format "X.Y.Z" where X is the major version number (always 3 for +** SQLite3) and Y is the minor version number and Z is the release number.)^ +** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same +** numbers used in [SQLITE_VERSION].)^ +** The SQLITE_VERSION_NUMBER for any given release of SQLite will also +** be larger than the release from which it is derived. Either Y will +** be held constant and Z will be incremented or else Y will be incremented +** and Z will be reset to zero. +** +** Since version 3.6.18, SQLite source code has been stored in the +** Fossil configuration management +** system. ^The SQLITE_SOURCE_ID macro evaluates to +** a string which identifies a particular check-in of SQLite +** within its configuration management system. ^The SQLITE_SOURCE_ID +** string contains the date and time of the check-in (UTC) and an SHA1 +** hash of the entire source tree. +** +** See also: [sqlite3_libversion()], +** [sqlite3_libversion_number()], [sqlite3_sourceid()], +** [sqlite_version()] and [sqlite_source_id()]. +*/ +#define SQLITE_VERSION "3.7.5" +#define SQLITE_VERSION_NUMBER 3007005 +#define SQLITE_SOURCE_ID "2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7" + +/* +** CAPI3REF: Run-Time Library Version Numbers +** KEYWORDS: sqlite3_version, sqlite3_sourceid +** +** These interfaces provide the same information as the [SQLITE_VERSION], +** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros +** but are associated with the library instead of the header file. ^(Cautious +** programmers might include assert() statements in their application to +** verify that values returned by these interfaces match the macros in +** the header, and thus insure that the application is +** compiled with matching library and header files. +** +**
+** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
+** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
+** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
+** 
)^ +** +** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] +** macro. ^The sqlite3_libversion() function returns a pointer to the +** to the sqlite3_version[] string constant. The sqlite3_libversion() +** function is provided for use in DLLs since DLL users usually do not have +** direct access to string constants within the DLL. ^The +** sqlite3_libversion_number() function returns an integer equal to +** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns +** a pointer to a string constant whose value is the same as the +** [SQLITE_SOURCE_ID] C preprocessor macro. +** +** See also: [sqlite_version()] and [sqlite_source_id()]. +*/ +SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; +SQLITE_API const char *sqlite3_libversion(void); +SQLITE_API const char *sqlite3_sourceid(void); +SQLITE_API int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Run-Time Library Compilation Options Diagnostics +** +** ^The sqlite3_compileoption_used() function returns 0 or 1 +** indicating whether the specified option was defined at +** compile time. ^The SQLITE_ prefix may be omitted from the +** option name passed to sqlite3_compileoption_used(). +** +** ^The sqlite3_compileoption_get() function allows iterating +** over the list of options that were defined at compile time by +** returning the N-th compile time option string. ^If N is out of range, +** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ +** prefix is omitted from any strings returned by +** sqlite3_compileoption_get(). +** +** ^Support for the diagnostic functions sqlite3_compileoption_used() +** and sqlite3_compileoption_get() may be omitted by specifying the +** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. +** +** See also: SQL functions [sqlite_compileoption_used()] and +** [sqlite_compileoption_get()] and the [compile_options pragma]. +*/ +#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS +SQLITE_API int sqlite3_compileoption_used(const char *zOptName); +SQLITE_API const char *sqlite3_compileoption_get(int N); +#endif + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe +** +** ^The sqlite3_threadsafe() function returns zero if and only if +** SQLite was compiled mutexing code omitted due to the +** [SQLITE_THREADSAFE] compile-time option being set to 0. +** +** SQLite can be compiled with or without mutexes. When +** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes +** are enabled and SQLite is threadsafe. When the +** [SQLITE_THREADSAFE] macro is 0, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite concurrently from more than one thread. +** +** Enabling mutexes incurs a measurable performance penalty. +** So if speed is of utmost importance, it makes sense to disable +** the mutexes. But for maximum safety, mutexes should be enabled. +** ^The default behavior is for mutexes to be enabled. +** +** This interface can be used by an application to make sure that the +** version of SQLite that it is linking against was compiled with +** the desired setting of the [SQLITE_THREADSAFE] macro. +** +** This interface only reports on the compile-time mutex setting +** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with +** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but +** can be fully or partially disabled using a call to [sqlite3_config()] +** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], +** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the +** sqlite3_threadsafe() function shows only the compile-time setting of +** thread safety, not any run-time changes to that setting made by +** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() +** is unchanged by calls to sqlite3_config().)^ +** +** See the [threading mode] documentation for additional information. +*/ +SQLITE_API int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle +** KEYWORDS: {database connection} {database connections} +** +** Each open SQLite database is represented by a pointer to an instance of +** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] +** is its destructor. There are many other interfaces (such as +** [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on an +** sqlite3 object. +*/ +typedef struct sqlite3 sqlite3; + +/* +** CAPI3REF: 64-Bit Integer Types +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. +** The sqlite_int64 and sqlite_uint64 types are supported for backwards +** compatibility only. +** +** ^The sqlite3_int64 and sqlite_int64 types can store integer values +** between -9223372036854775808 and +9223372036854775807 inclusive. ^The +** sqlite3_uint64 and sqlite_uint64 types can store integer values +** between 0 and +18446744073709551615 inclusive. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection +** +** ^The sqlite3_close() routine is the destructor for the [sqlite3] object. +** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is +** successfully destroyed and all associated resources are deallocated. +** +** Applications must [sqlite3_finalize | finalize] all [prepared statements] +** and [sqlite3_blob_close | close] all [BLOB handles] associated with +** the [sqlite3] object prior to attempting to close the object. ^If +** sqlite3_close() is called on a [database connection] that still has +** outstanding [prepared statements] or [BLOB handles], then it returns +** SQLITE_BUSY. +** +** ^If [sqlite3_close()] is invoked while a transaction is open, +** the transaction is automatically rolled back. +** +** The C parameter to [sqlite3_close(C)] must be either a NULL +** pointer or an [sqlite3] object pointer obtained +** from [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()], and not previously closed. +** ^Calling sqlite3_close() with a NULL pointer argument is a +** harmless no-op. +*/ +SQLITE_API int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface +** +** The sqlite3_exec() interface is a convenience wrapper around +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], +** that allows an application to run multiple statements of SQL +** without having to use a lot of C code. +** +** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, +** semicolon-separate SQL statements passed into its 2nd argument, +** in the context of the [database connection] passed in as its 1st +** argument. ^If the callback function of the 3rd argument to +** sqlite3_exec() is not NULL, then it is invoked for each result row +** coming out of the evaluated SQL statements. ^The 4th argument to +** to sqlite3_exec() is relayed through to the 1st argument of each +** callback invocation. ^If the callback pointer to sqlite3_exec() +** is NULL, then no callback is ever invoked and result rows are +** ignored. +** +** ^If an error occurs while evaluating the SQL statements passed into +** sqlite3_exec(), then execution of the current statement stops and +** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() +** is not NULL then any error message is written into memory obtained +** from [sqlite3_malloc()] and passed back through the 5th parameter. +** To avoid memory leaks, the application should invoke [sqlite3_free()] +** on error message strings returned through the 5th parameter of +** of sqlite3_exec() after the error message string is no longer needed. +** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors +** occur, then sqlite3_exec() sets the pointer in its 5th parameter to +** NULL before returning. +** +** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() +** routine returns SQLITE_ABORT without invoking the callback again and +** without running any subsequent SQL statements. +** +** ^The 2nd argument to the sqlite3_exec() callback function is the +** number of columns in the result. ^The 3rd argument to the sqlite3_exec() +** callback is an array of pointers to strings obtained as if from +** [sqlite3_column_text()], one for each column. ^If an element of a +** result row is NULL then the corresponding string pointer for the +** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the +** sqlite3_exec() callback is an array of pointers to strings where each +** entry represents the name of corresponding result column as obtained +** from [sqlite3_column_name()]. +** +** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer +** to an empty string, or a pointer that contains only whitespace and/or +** SQL comments, then no SQL statements are evaluated and the database +** is not changed. +** +** Restrictions: +** +**
    +**
  • The application must insure that the 1st parameter to sqlite3_exec() +** is a valid and open [database connection]. +**
  • The application must not close [database connection] specified by +** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. +**
  • The application must not modify the SQL statement text passed into +** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. +**
+*/ +SQLITE_API int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes +** KEYWORDS: SQLITE_OK {error code} {error codes} +** KEYWORDS: {result code} {result codes} +** +** Many SQLite functions return an integer result code from the set shown +** here in order to indicates success or failure. +** +** New error codes may be added in future versions of SQLite. +** +** See also: [SQLITE_IOERR_READ | extended result codes] +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result code} {extended result codes} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that many of +** these result codes are too coarse-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. The extended result codes are enabled or disabled +** on a per database connection basis using the +** [sqlite3_extended_result_codes()] API. +** +** Some of the available extended result codes are listed here. +** One may expect the number of extended result codes will be expand +** over time. Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) +#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) +#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) +#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) +#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) +#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) +#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) +#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) +#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) +#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) +#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) + +/* +** CAPI3REF: Flags For File Open Operations +** +** These bit values are intended for use in the +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ +#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ +#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ +#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ +#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ +#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ + +/* +** CAPI3REF: Device Characteristics +** +** The xDeviceCharacteristics method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 +#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 + +/* +** CAPI3REF: File Locking Levels +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags +** +** When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of +** these integer values as the second argument. +** +** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. If the lower four bits of the flag +** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. +** If the lower four bits equal SQLITE_SYNC_FULL, that means +** to use Mac OS X style fullsync instead of fsync(). +** +** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags +** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL +** settings. The [synchronous pragma] determines when calls to the +** xSync VFS method occur and applies uniformly across all platforms. +** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how +** energetic or rigorous or forceful the sync operations are and +** only make a difference on Mac OSX for the default SQLite code. +** (Third-party VFS implementations might also make the distinction +** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the +** operating systems natively supported by SQLite, only Mac OSX +** cares about the difference.) +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + +/* +** CAPI3REF: OS Interface Open File Handle +** +** An [sqlite3_file] object represents an open file in the +** [sqlite3_vfs | OS interface layer]. Individual OS interface +** implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object +** +** Every file opened by the [sqlite3_vfs] xOpen method populates an +** [sqlite3_file] object (or, more commonly, a subclass of the +** [sqlite3_file] object) with a pointer to an instance of this object. +** This object defines the methods used to perform various operations +** against the open file represented by the [sqlite3_file] object. +** +** If the xOpen method sets the sqlite3_file.pMethods element +** to a non-NULL pointer, then the sqlite3_io_methods.xClose method +** may be invoked even if the xOpen reported that it failed. The +** only way to prevent a call to xClose following a failed xOpen +** is for the xOpen to set the sqlite3_file.pMethods element to NULL. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] +** flag may be ORed in to indicate that only the data of the file +** and not its inode needs to be synced. +** +** The integer values to xLock() and xUnlock() are one of +**
    +**
  • [SQLITE_LOCK_NONE], +**
  • [SQLITE_LOCK_SHARED], +**
  • [SQLITE_LOCK_RESERVED], +**
  • [SQLITE_LOCK_PENDING], or +**
  • [SQLITE_LOCK_EXCLUSIVE]. +**
+** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method checks whether any database connection, +** either in this process or in some other process, is holding a RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false otherwise. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument is an +** integer opcode. The third argument is a generic pointer intended to +** point to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves all opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. VFS implementations should +** return [SQLITE_NOTFOUND] for file control opcodes that they do not +** recognize. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
    +**
  • [SQLITE_IOCAP_ATOMIC] +**
  • [SQLITE_IOCAP_ATOMIC512] +**
  • [SQLITE_IOCAP_ATOMIC1K] +**
  • [SQLITE_IOCAP_ATOMIC2K] +**
  • [SQLITE_IOCAP_ATOMIC4K] +**
  • [SQLITE_IOCAP_ATOMIC8K] +**
  • [SQLITE_IOCAP_ATOMIC16K] +**
  • [SQLITE_IOCAP_ATOMIC32K] +**
  • [SQLITE_IOCAP_ATOMIC64K] +**
  • [SQLITE_IOCAP_SAFE_APPEND] +**
  • [SQLITE_IOCAP_SEQUENTIAL] +**
+** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +** +** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill +** in the unread portions of the buffer with zeros. A VFS that +** fails to zero-fill short reads might seem to work. However, +** failure to zero-fill short reads will eventually lead to +** database corruption. +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Methods above are valid for version 1 */ + int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); + int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); + void (*xShmBarrier)(sqlite3_file*); + int (*xShmUnmap)(sqlite3_file*, int deleteFlag); + /* Methods above are valid for version 2 */ + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** interface. +** +** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode causes the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +** +** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS +** layer a hint of how large the database file will grow to be during the +** current transaction. This hint is not guaranteed to be accurate but it +** is often close. The underlying VFS might choose to preallocate database +** file space based on this hint in order to help writes to the database +** file run faster. +** +** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS +** extends and truncates the database file in chunks of a size specified +** by the user. The fourth argument to [sqlite3_file_control()] should +** point to an integer (type int) containing the new chunk-size to use +** for the nominated database. Allocating database file space in large +** chunks (say 1MB at a time), may reduce file-system fragmentation and +** improve performance on some systems. +** +** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer +** to the [sqlite3_file] object associated with a particular database +** connection. See the [sqlite3_file_control()] documentation for +** additional information. +** +** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by +** SQLite and sent to all VFSes in place of a call to the xSync method +** when the database connection has [PRAGMA synchronous] set to OFF.)^ +** Some specialized VFSes need this signal in order to operate correctly +** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most +** VFSes do not need this signal and should silently ignore this opcode. +** Applications should not call [sqlite3_file_control()] with this +** opcode as doing so may disrupt the operation of the specilized VFSes +** that do require it. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 +#define SQLITE_GET_LOCKPROXYFILE 2 +#define SQLITE_SET_LOCKPROXYFILE 3 +#define SQLITE_LAST_ERRNO 4 +#define SQLITE_FCNTL_SIZE_HINT 5 +#define SQLITE_FCNTL_CHUNK_SIZE 6 +#define SQLITE_FCNTL_FILE_POINTER 7 +#define SQLITE_FCNTL_SYNC_OMITTED 8 + + +/* +** CAPI3REF: Mutex Handle +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object +** +** An instance of the sqlite3_vfs object defines the interface between +** the SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The value of the iVersion field is initially 1 but may be larger in +** future versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. Note that the structure +** of the sqlite3_vfs object changes in the transaction between +** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not +** modified. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered sqlite3_vfs objects are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. Neither the application code nor the VFS +** implementation should use the pNext pointer. +** +** The pNext field is the only field in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** ^SQLite guarantees that the zFilename parameter to xOpen +** is either a NULL pointer or string obtained +** from xFullPathname() with an optional suffix added. +** ^If a suffix is added to the zFilename parameter, it will +** consist of a single "-" character followed by no more than +** 10 alphanumeric and/or "-" characters. +** ^SQLite further guarantees that +** the string will be valid and unchanged until xClose() is +** called. Because of the previous sentence, +** the [sqlite3_file] can safely store a pointer to the +** filename if it needs to remember the filename for some reason. +** If the zFilename parameter to xOpen is a NULL pointer then xOpen +** must invent its own temporary name for the file. ^Whenever the +** xFilename parameter is NULL it will also be the case that the +** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. +** +** The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. +** +** ^(SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
    +**
  • [SQLITE_OPEN_MAIN_DB] +**
  • [SQLITE_OPEN_MAIN_JOURNAL] +**
  • [SQLITE_OPEN_TEMP_DB] +**
  • [SQLITE_OPEN_TEMP_JOURNAL] +**
  • [SQLITE_OPEN_TRANSIENT_DB] +**
  • [SQLITE_OPEN_SUBJOURNAL] +**
  • [SQLITE_OPEN_MASTER_JOURNAL] +**
  • [SQLITE_OPEN_WAL] +**
)^ +** +** The file I/O implementation can use the object type flags to +** change the way it deals with files. For example, an application +** that does not care about crash recovery or rollback might make +** the open of a journal file a no-op. Writes to this journal would +** also be no-ops, and any attempt to read the journal would return +** SQLITE_IOERR. Or the implementation might recognize that a database +** file will be doing page-aligned sector reads and writes in a random +** order and set up its I/O subsystem accordingly. +** +** SQLite might also add one of the following flags to the xOpen method: +** +**
    +**
  • [SQLITE_OPEN_DELETEONCLOSE] +**
  • [SQLITE_OPEN_EXCLUSIVE] +**
+** +** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases and their journals, transient +** databases, and subjournals. +** +** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction +** with the [SQLITE_OPEN_CREATE] flag, which are both directly +** analogous to the O_EXCL and O_CREAT flags of the POSIX open() +** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the +** SQLITE_OPEN_CREATE, is used to indicate that file should always +** be created, and that it is an error if it already exists. +** It is not used to indicate the file should be opened +** for exclusive access. +** +** ^At least szOsFile bytes of memory are allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. The xOpen method does not have to +** allocate the structure; it should just fill it in. Note that +** the xOpen method must set the sqlite3_file.pMethods to either +** a valid [sqlite3_io_methods] object or to NULL. xOpen must do +** this even if the open fails. SQLite expects that the sqlite3_file.pMethods +** element will be valid after xOpen returns regardless of the success +** or failure of the xOpen call. +** +** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to +** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test whether a file is at least readable. The file can be a +** directory. +** +** ^SQLite will always allocate at least mxPathname+1 bytes for the +** output buffer xFullPathname. The exact size of the output buffer +** is also passed as a parameter to both methods. If the output buffer +** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is +** handled as a fatal error by SQLite, vfs implementations should endeavor +** to prevent this by setting mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() +** interfaces are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. +** The xSleep() method causes the calling thread to sleep for at +** least the number of microseconds given. ^The xCurrentTime() +** method returns a Julian Day Number for the current date and time as +** a floating point value. +** ^The xCurrentTimeInt64() method returns, as an integer, the Julian +** Day Number multipled by 86400000 (the number of milliseconds in +** a 24-hour day). +** ^SQLite will use the xCurrentTimeInt64() method to get the current +** date and time if that method is available (if iVersion is 2 or +** greater and the function pointer is not NULL) and will fall back +** to xCurrentTime() if xCurrentTimeInt64() is unavailable. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number (currently 2) */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + int (*xGetLastError)(sqlite3_vfs*, int, char *); + /* + ** The methods above are in version 1 of the sqlite_vfs object + ** definition. Those that follow are added in version 2 or later + */ + int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); + /* + ** The methods above are in versions 1 and 2 of the sqlite_vfs object. + ** New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. + */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method +** +** These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. They determine +** what kind of permissions the xAccess method is looking for. +** With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks whether the file exists. +** With SQLITE_ACCESS_READWRITE, the xAccess method +** checks whether the named directory is both readable and writable +** (in other words, if files can be added, removed, and renamed within +** the directory). +** The SQLITE_ACCESS_READWRITE constant is currently used only by the +** [temp_store_directory pragma], though this could change in a future +** release of SQLite. +** With SQLITE_ACCESS_READ, the xAccess method +** checks whether the file is readable. The SQLITE_ACCESS_READ constant is +** currently unused, though it might be used in a future release of +** SQLite. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ +#define SQLITE_ACCESS_READ 2 /* Unused */ + +/* +** CAPI3REF: Flags for the xShmLock VFS method +** +** These integer constants define the various locking operations +** allowed by the xShmLock method of [sqlite3_io_methods]. The +** following are the only legal combinations of flags to the +** xShmLock method: +** +**
    +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED +**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE +**
+** +** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as +** was given no the corresponding lock. +** +** The xShmLock method can transition between unlocked and SHARED or +** between unlocked and EXCLUSIVE. It cannot transition between SHARED +** and EXCLUSIVE. +*/ +#define SQLITE_SHM_UNLOCK 1 +#define SQLITE_SHM_LOCK 2 +#define SQLITE_SHM_SHARED 4 +#define SQLITE_SHM_EXCLUSIVE 8 + +/* +** CAPI3REF: Maximum xShmLock index +** +** The xShmLock method on [sqlite3_io_methods] may use values +** between 0 and this upper bound as its "offset" argument. +** The SQLite core will never attempt to acquire or release a +** lock outside of this range +*/ +#define SQLITE_SHM_NLOCK 8 + + +/* +** CAPI3REF: Initialize The SQLite Library +** +** ^The sqlite3_initialize() routine initializes the +** SQLite library. ^The sqlite3_shutdown() routine +** deallocates any resources that were allocated by sqlite3_initialize(). +** These routines are designed to aid in process initialization and +** shutdown on embedded systems. Workstation applications using +** SQLite normally do not need to invoke either of these routines. +** +** A call to sqlite3_initialize() is an "effective" call if it is +** the first time sqlite3_initialize() is invoked during the lifetime of +** the process, or if it is the first time sqlite3_initialize() is invoked +** following a call to sqlite3_shutdown(). ^(Only an effective call +** of sqlite3_initialize() does any initialization. All other calls +** are harmless no-ops.)^ +** +** A call to sqlite3_shutdown() is an "effective" call if it is the first +** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only +** an effective call to sqlite3_shutdown() does any deinitialization. +** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ +** +** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() +** is not. The sqlite3_shutdown() interface must only be called from a +** single thread. All open [database connections] must be closed and all +** other SQLite resources must be deallocated prior to invoking +** sqlite3_shutdown(). +** +** Among other things, ^sqlite3_initialize() will invoke +** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() +** will invoke sqlite3_os_end(). +** +** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. +** ^If for some reason, sqlite3_initialize() is unable to initialize +** the library (perhaps it is unable to allocate a needed resource such +** as a mutex) it returns an [error code] other than [SQLITE_OK]. +** +** ^The sqlite3_initialize() routine is called internally by many other +** SQLite interfaces so that an application usually does not need to +** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] +** calls sqlite3_initialize() so the SQLite library will be automatically +** initialized when [sqlite3_open()] is called if it has not be initialized +** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] +** compile-time option, then the automatic calls to sqlite3_initialize() +** are omitted and the application must call sqlite3_initialize() directly +** prior to using any other SQLite interface. For maximum portability, +** it is recommended that applications always invoke sqlite3_initialize() +** directly prior to using any other SQLite interface. Future releases +** of SQLite may require this. In other words, the behavior exhibited +** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the +** default behavior in some future release of SQLite. +** +** The sqlite3_os_init() routine does operating-system specific +** initialization of the SQLite library. The sqlite3_os_end() +** routine undoes the effect of sqlite3_os_init(). Typical tasks +** performed by these routines include allocation or deallocation +** of static resources, initialization of global variables, +** setting up a default [sqlite3_vfs] module, or setting up +** a default configuration using [sqlite3_config()]. +** +** The application should never invoke either sqlite3_os_init() +** or sqlite3_os_end() directly. The application should only invoke +** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() +** interface is called automatically by sqlite3_initialize() and +** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate +** implementations for sqlite3_os_init() and sqlite3_os_end() +** are built into SQLite when it is compiled for Unix, Windows, or OS/2. +** When [custom builds | built for other platforms] +** (using the [SQLITE_OS_OTHER=1] compile-time +** option) the application must supply a suitable implementation for +** sqlite3_os_init() and sqlite3_os_end(). An application-supplied +** implementation of sqlite3_os_init() or sqlite3_os_end() +** must return [SQLITE_OK] on success and some other [error code] upon +** failure. +*/ +SQLITE_API int sqlite3_initialize(void); +SQLITE_API int sqlite3_shutdown(void); +SQLITE_API int sqlite3_os_init(void); +SQLITE_API int sqlite3_os_end(void); + +/* +** CAPI3REF: Configuring The SQLite Library +** +** The sqlite3_config() interface is used to make global configuration +** changes to SQLite in order to tune SQLite to the specific needs of +** the application. The default configuration is recommended for most +** applications and so this routine is usually not necessary. It is +** provided to support rare applications with unusual needs. +** +** The sqlite3_config() interface is not threadsafe. The application +** must insure that no other SQLite interfaces are invoked by other +** threads while sqlite3_config() is running. Furthermore, sqlite3_config() +** may only be invoked prior to library initialization using +** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. +** ^If sqlite3_config() is called after [sqlite3_initialize()] and before +** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. +** Note, however, that ^sqlite3_config() can be called as part of the +** implementation of an application-defined [sqlite3_os_init()]. +** +** The first argument to sqlite3_config() is an integer +** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines +** what property of SQLite is to be configured. Subsequent arguments +** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option] +** in the first argument. +** +** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. +** ^If the option is unknown or SQLite is unable to set the option +** then this routine returns a non-zero [error code]. +*/ +SQLITE_API int sqlite3_config(int, ...); + +/* +** CAPI3REF: Configure database connections +** +** The sqlite3_db_config() interface is used to make configuration +** changes to a [database connection]. The interface is similar to +** [sqlite3_config()] except that the changes apply to a single +** [database connection] (specified in the first argument). The +** sqlite3_db_config() interface should only be used immediately after +** the database connection is created using [sqlite3_open()], +** [sqlite3_open16()], or [sqlite3_open_v2()]. +** +** The second argument to sqlite3_db_config(D,V,...) is the +** configuration verb - an integer code that indicates what +** aspect of the [database connection] is being configured. +** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE]. +** New verbs are likely to be added in future releases of SQLite. +** Additional arguments depend on the verb. +** +** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if +** the call is considered successful. +*/ +SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); + +/* +** CAPI3REF: Memory Allocation Routines +** +** An instance of this object defines the interface between SQLite +** and low-level memory allocation routines. +** +** This object is used in only one place in the SQLite interface. +** A pointer to an instance of this object is the argument to +** [sqlite3_config()] when the configuration option is +** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. +** By creating an instance of this object +** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) +** during configuration, an application can specify an alternative +** memory allocation subsystem for SQLite to use for all of its +** dynamic memory needs. +** +** Note that SQLite comes with several [built-in memory allocators] +** that are perfectly adequate for the overwhelming majority of applications +** and that this object is only useful to a tiny minority of applications +** with specialized memory allocation requirements. This object is +** also used during testing of SQLite in order to specify an alternative +** memory allocator that simulates memory out-of-memory conditions in +** order to verify that SQLite recovers gracefully from such +** conditions. +** +** The xMalloc and xFree methods must work like the +** malloc() and free() functions from the standard C library. +** The xRealloc method must work like realloc() from the standard C library +** with the exception that if the second argument to xRealloc is zero, +** xRealloc must be a no-op - it must not perform any allocation or +** deallocation. ^SQLite guarantees that the second argument to +** xRealloc is always a value returned by a prior call to xRoundup. +** And so in cases where xRoundup always returns a positive number, +** xRealloc can perform exactly as the standard library realloc() and +** still be in compliance with this specification. +** +** xSize should return the allocated size of a memory allocation +** previously obtained from xMalloc or xRealloc. The allocated size +** is always at least as big as the requested size but may be larger. +** +** The xRoundup method returns what would be the allocated size of +** a memory allocation given a particular requested size. Most memory +** allocators round up memory allocations at least to the next multiple +** of 8. Some allocators round up to a larger multiple or to a power of 2. +** Every memory allocation request coming in through [sqlite3_malloc()] +** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, +** that causes the corresponding memory allocation to fail. +** +** The xInit method initializes the memory allocator. (For example, +** it might allocate any require mutexes or initialize internal data +** structures. The xShutdown method is invoked (indirectly) by +** [sqlite3_shutdown()] and should deallocate any resources acquired +** by xInit. The pAppData pointer is used as the only parameter to +** xInit and xShutdown. +** +** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes +** the xInit method, so the xInit method need not be threadsafe. The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. For all other methods, SQLite +** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the +** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which +** it is by default) and so the methods are automatically serialized. +** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other +** methods must be threadsafe or else make their own arrangements for +** serialization. +** +** SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +*/ +typedef struct sqlite3_mem_methods sqlite3_mem_methods; +struct sqlite3_mem_methods { + void *(*xMalloc)(int); /* Memory allocation function */ + void (*xFree)(void*); /* Free a prior allocation */ + void *(*xRealloc)(void*,int); /* Resize an allocation */ + int (*xSize)(void*); /* Return the size of an allocation */ + int (*xRoundup)(int); /* Round up request size to allocation size */ + int (*xInit)(void*); /* Initialize the memory allocator */ + void (*xShutdown)(void*); /* Deinitialize the memory allocator */ + void *pAppData; /* Argument to xInit() and xShutdown() */ +}; + +/* +** CAPI3REF: Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the first argument to the [sqlite3_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_config()] to make sure that +** the call worked. The [sqlite3_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_CONFIG_SINGLETHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Single-thread. In other words, it disables +** all mutexing and puts SQLite into a mode where it can only be used +** by a single thread. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to change the [threading mode] from its default +** value of Single-thread and so [sqlite3_config()] will return +** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD +** configuration option.
+** +**
SQLITE_CONFIG_MULTITHREAD
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Multi-thread. In other words, it disables +** mutexing on [database connection] and [prepared statement] objects. +** The application is responsible for serializing access to +** [database connections] and [prepared statements]. But other mutexes +** are enabled so that SQLite will be safe to use in a multi-threaded +** environment as long as no two threads attempt to use the same +** [database connection] at the same time. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Multi-thread [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_MULTITHREAD configuration option.
+** +**
SQLITE_CONFIG_SERIALIZED
+**
There are no arguments to this option. ^This option sets the +** [threading mode] to Serialized. In other words, this option enables +** all mutexes including the recursive +** mutexes on [database connection] and [prepared statement] objects. +** In this mode (which is the default when SQLite is compiled with +** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access +** to [database connections] and [prepared statements] so that the +** application is free to use the same [database connection] or the +** same [prepared statement] in different threads at the same time. +** ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** it is not possible to set the Serialized [threading mode] and +** [sqlite3_config()] will return [SQLITE_ERROR] if called with the +** SQLITE_CONFIG_SERIALIZED configuration option.
+** +**
SQLITE_CONFIG_MALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The argument specifies +** alternative low-level memory allocation routines to be used in place of +** the memory allocation routines built into SQLite.)^ ^SQLite makes +** its own private copy of the content of the [sqlite3_mem_methods] structure +** before the [sqlite3_config()] call returns.
+** +**
SQLITE_CONFIG_GETMALLOC
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] +** structure is filled with the currently defined memory allocation routines.)^ +** This option can be used to overload the default memory allocation +** routines with a wrapper that simulations memory allocation failure or +** tracks memory usage, for example.
+** +**
SQLITE_CONFIG_MEMSTATUS
+**
^This option takes single argument of type int, interpreted as a +** boolean, which enables or disables the collection of memory allocation +** statistics. ^(When memory allocation statistics are disabled, the +** following SQLite interfaces become non-operational: +**
    +**
  • [sqlite3_memory_used()] +**
  • [sqlite3_memory_highwater()] +**
  • [sqlite3_soft_heap_limit64()] +**
  • [sqlite3_status()] +**
)^ +** ^Memory allocation statistics are enabled by default unless SQLite is +** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory +** allocation statistics are disabled by default. +**
+** +**
SQLITE_CONFIG_SCRATCH
+**
^This option specifies a static memory buffer that SQLite can use for +** scratch memory. There are three arguments: A pointer an 8-byte +** aligned memory buffer from which the scrach allocations will be +** drawn, the size of each scratch allocation (sz), +** and the maximum number of scratch allocations (N). The sz +** argument must be a multiple of 16. +** The first argument must be a pointer to an 8-byte aligned buffer +** of at least sz*N bytes of memory. +** ^SQLite will use no more than two scratch buffers per thread. So +** N should be set to twice the expected maximum number of threads. +** ^SQLite will never require a scratch buffer that is more than 6 +** times the database page size. ^If SQLite needs needs additional +** scratch memory beyond what is provided by this configuration option, then +** [sqlite3_malloc()] will be used to obtain the memory needed.
+** +**
SQLITE_CONFIG_PAGECACHE
+**
^This option specifies a static memory buffer that SQLite can use for +** the database page cache with the default page cache implemenation. +** This configuration should not be used if an application-define page +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option. +** There are three arguments to this option: A pointer to 8-byte aligned +** memory, the size of each page buffer (sz), and the number of pages (N). +** The sz argument should be the size of the largest database page +** (a power of two between 512 and 32768) plus a little extra for each +** page header. ^The page header size is 20 to 40 bytes depending on +** the host architecture. ^It is harmless, apart from the wasted memory, +** to make sz a little too large. The first +** argument should point to an allocation of at least sz*N bytes of memory. +** ^SQLite will use the memory provided by the first argument to satisfy its +** memory needs for the first N pages that it adds to cache. ^If additional +** page cache memory is needed beyond what is provided by this option, then +** SQLite goes to [sqlite3_malloc()] for the additional storage space. +** The pointer in the first argument must +** be aligned to an 8-byte boundary or subsequent behavior of SQLite +** will be undefined.
+** +**
SQLITE_CONFIG_HEAP
+**
^This option specifies a static memory buffer that SQLite will use +** for all of its dynamic memory allocation needs beyond those provided +** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. +** There are three arguments: An 8-byte aligned pointer to the memory, +** the number of bytes in the memory buffer, and the minimum allocation size. +** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts +** to using its default memory allocator (the system malloc() implementation), +** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the +** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or +** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory +** allocator is engaged to handle all of SQLites memory allocation needs. +** The first pointer (the memory pointer) must be aligned to an 8-byte +** boundary or subsequent behavior of SQLite will be undefined.
+** +**
SQLITE_CONFIG_MUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The argument specifies +** alternative low-level mutex routines to be used in place +** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the +** content of the [sqlite3_mutex_methods] structure before the call to +** [sqlite3_config()] returns. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will +** return [SQLITE_ERROR].
+** +**
SQLITE_CONFIG_GETMUTEX
+**
^(This option takes a single argument which is a pointer to an +** instance of the [sqlite3_mutex_methods] structure. The +** [sqlite3_mutex_methods] +** structure is filled with the currently defined mutex routines.)^ +** This option can be used to overload the default mutex allocation +** routines with a wrapper used to track mutex usage for performance +** profiling or testing, for example. ^If SQLite is compiled with +** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then +** the entire mutexing subsystem is omitted from the build and hence calls to +** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will +** return [SQLITE_ERROR].
+** +**
SQLITE_CONFIG_LOOKASIDE
+**
^(This option takes two arguments that determine the default +** memory allocation for the lookaside memory allocator on each +** [database connection]. The first argument is the +** size of each lookaside buffer slot and the second is the number of +** slots allocated to each database connection.)^ ^(This option sets the +** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] +** verb to [sqlite3_db_config()] can be used to change the lookaside +** configuration on individual connections.)^
+** +**
SQLITE_CONFIG_PCACHE
+**
^(This option takes a single argument which is a pointer to +** an [sqlite3_pcache_methods] object. This object specifies the interface +** to a custom page cache implementation.)^ ^SQLite makes a copy of the +** object and uses it for page cache memory allocations.
+** +**
SQLITE_CONFIG_GETPCACHE
+**
^(This option takes a single argument which is a pointer to an +** [sqlite3_pcache_methods] object. SQLite copies of the current +** page cache implementation into that object.)^
+** +**
SQLITE_CONFIG_LOG
+**
^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a +** function with a call signature of void(*)(void*,int,const char*), +** and a pointer to void. ^If the function pointer is not NULL, it is +** invoked by [sqlite3_log()] to process each logging event. ^If the +** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. +** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is +** passed through as the first parameter to the application-defined logger +** function whenever that function is invoked. ^The second parameter to +** the logger function is a copy of the first parameter to the corresponding +** [sqlite3_log()] call and is intended to be a [result code] or an +** [extended result code]. ^The third parameter passed to the logger is +** log message after formatting via [sqlite3_snprintf()]. +** The SQLite logging interface is not reentrant; the logger function +** supplied by the application must not invoke any SQLite interface. +** In a multi-threaded application, the application-defined logger +** function must be threadsafe.
+** +**
+*/ +#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ +#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ +#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ +#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ +#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ +#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ +#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ +#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ +#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ +#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ +/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ +#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ +#define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ +#define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ +#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ + +/* +** CAPI3REF: Database Connection Configuration Options +** +** These constants are the available integer configuration options that +** can be passed as the second argument to the [sqlite3_db_config()] interface. +** +** New configuration options may be added in future releases of SQLite. +** Existing configuration options might be discontinued. Applications +** should check the return code from [sqlite3_db_config()] to make sure that +** the call worked. ^The [sqlite3_db_config()] interface will return a +** non-zero [error code] if a discontinued or unsupported configuration option +** is invoked. +** +**
+**
SQLITE_DBCONFIG_LOOKASIDE
+**
^This option takes three additional arguments that determine the +** [lookaside memory allocator] configuration for the [database connection]. +** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** pointer to an memory buffer to use for lookaside memory. +** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb +** may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the +** size of each lookaside buffer slot. ^The third argument is the number of +** slots. The size of the buffer in the first argument must be greater than +** or equal to the product of the second and third arguments. The buffer +** must be aligned to an 8-byte boundary. ^If the second argument to +** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally +** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** configuration for a database connection can only be changed when that +** connection is not currently using lookaside memory, or in other words +** when the "current value" returned by +** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. +** Any attempt to change the lookaside memory configuration when lookaside +** memory is in use leaves the configuration unchanged and returns +** [SQLITE_BUSY].)^
+** +**
+*/ +#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ + + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes +** +** ^The sqlite3_extended_result_codes() routine enables or disables the +** [extended result codes] feature of SQLite. ^The extended result +** codes are disabled by default for historical compatibility. +*/ +SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid +** +** ^Each entry in an SQLite table has a unique 64-bit signed +** integer key called the [ROWID | "rowid"]. ^The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. ^If +** the table has a column of type [INTEGER PRIMARY KEY] then that column +** is another alias for the rowid. +** +** ^This routine returns the [rowid] of the most recent +** successful [INSERT] into the database from the [database connection] +** in the first argument. ^If no successful [INSERT]s +** have ever occurred on that database connection, zero is returned. +** +** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted +** row is returned by this routine as long as the trigger is running. +** But once the trigger terminates, the value returned by this routine +** reverts to the last value inserted before the trigger fired.)^ +** +** ^An [INSERT] that fails due to a constraint violation is not a +** successful [INSERT] and does not change the value returned by this +** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. ^(When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface.)^ +** +** ^For the purposes of this routine, an [INSERT] is considered to +** be successful even if it is subsequently rolled back. +** +** This function is accessible to SQL statements via the +** [last_insert_rowid() SQL function]. +** +** If a separate thread performs a new [INSERT] on the same +** database connection while the [sqlite3_last_insert_rowid()] +** function is running and thus changes the last insert [rowid], +** then the value returned by [sqlite3_last_insert_rowid()] is +** unpredictable and might not equal either the old or the new +** last insert [rowid]. +*/ +SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified +** +** ^This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the [database connection] specified by the first parameter. +** ^(Only changes that are directly specified by the [INSERT], [UPDATE], +** or [DELETE] statement are counted. Auxiliary changes caused by +** triggers or [foreign key actions] are not counted.)^ Use the +** [sqlite3_total_changes()] function to find the total number of changes +** including changes caused by triggers and foreign key actions. +** +** ^Changes to a view that are simulated by an [INSTEAD OF trigger] +** are not counted. Only real table changes are counted. +** +** ^(A "row change" is a change to a single row of a single table +** caused by an INSERT, DELETE, or UPDATE statement. Rows that +** are changed as side effects of [REPLACE] constraint resolution, +** rollback, ABORT processing, [DROP TABLE], or by any other +** mechanisms do not count as direct row changes.)^ +** +** A "trigger context" is a scope of execution that begins and +** ends with the script of a [CREATE TRIGGER | trigger]. +** Most SQL statements are +** evaluated outside of any trigger. This is the "top level" +** trigger context. If a trigger fires from the top level, a +** new trigger context is entered for the duration of that one +** trigger. Subtriggers create subcontexts for their duration. +** +** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does +** not create a new trigger context. +** +** ^This function returns the number of direct row changes in the +** most recent INSERT, UPDATE, or DELETE statement within the same +** trigger context. +** +** ^Thus, when called from the top level, this function returns the +** number of changes in the most recent INSERT, UPDATE, or DELETE +** that also occurred at the top level. ^(Within the body of a trigger, +** the sqlite3_changes() interface can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** However, the number returned does not include changes +** caused by subtriggers since those have their own context.)^ +** +** See also the [sqlite3_total_changes()] interface, the +** [count_changes pragma], and the [changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified +** +** ^This function returns the number of row changes caused by [INSERT], +** [UPDATE] or [DELETE] statements since the [database connection] was opened. +** ^(The count returned by sqlite3_total_changes() includes all changes +** from all [CREATE TRIGGER | trigger] contexts and changes made by +** [foreign key actions]. However, +** the count does not include changes used to implement [REPLACE] constraints, +** do rollbacks or ABORT processing, or [DROP TABLE] processing. The +** count does not include rows of views that fire an [INSTEAD OF trigger], +** though if the INSTEAD OF trigger makes changes of its own, those changes +** are counted.)^ +** ^The sqlite3_total_changes() function counts the changes as soon as +** the statement that makes them is completed (when the statement handle +** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). +** +** See also the [sqlite3_changes()] interface, the +** [count_changes pragma], and the [total_changes() SQL function]. +** +** If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and not meaningful. +*/ +SQLITE_API int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query +** +** ^This function causes any pending database operation to abort and +** return at its earliest opportunity. This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** ^It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. But it +** is not safe to call this routine with a [database connection] that +** is closed or might close before sqlite3_interrupt() returns. +** +** ^If an SQL operation is very nearly finished at the time when +** sqlite3_interrupt() is called, then it might not have an opportunity +** to be interrupted and might continue to completion. +** +** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. +** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE +** that is inside an explicit transaction, then the entire transaction +** will be rolled back automatically. +** +** ^The sqlite3_interrupt(D) call is in effect until all currently running +** SQL statements on [database connection] D complete. ^Any new SQL statements +** that are started after the sqlite3_interrupt() call and before the +** running statements reaches zero are interrupted as if they had been +** running prior to the sqlite3_interrupt() call. ^New SQL statements +** that are started after the running statement count reaches zero are +** not effected by the sqlite3_interrupt(). +** ^A call to sqlite3_interrupt(D) that occurs when there are no running +** SQL statements is a no-op and has no effect on SQL statements +** that are started after the sqlite3_interrupt() call returns. +** +** If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. +*/ +SQLITE_API void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete +** +** These routines are useful during command-line input to determine if the +** currently entered text seems to form a complete SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. ^These routines return 1 if the input string +** appears to be a complete SQL statement. ^A statement is judged to be +** complete if it ends with a semicolon token and is not a prefix of a +** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within +** string literals or quoted identifier names or comments are not +** independent tokens (they are part of the token in which they are +** embedded) and thus do not count as a statement terminator. ^Whitespace +** and comments that follow the final semicolon are ignored. +** +** ^These routines return 0 if the statement is incomplete. ^If a +** memory allocation fails, then SQLITE_NOMEM is returned. +** +** ^These routines do not parse the SQL statements thus +** will not detect syntactically incorrect SQL. +** +** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior +** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked +** automatically by sqlite3_complete16(). If that initialization fails, +** then the return value from sqlite3_complete16() will be non-zero +** regardless of whether or not the input SQL is complete.)^ +** +** The input to [sqlite3_complete()] must be a zero-terminated +** UTF-8 string. +** +** The input to [sqlite3_complete16()] must be a zero-terminated +** UTF-16 string in native byte order. +*/ +SQLITE_API int sqlite3_complete(const char *sql); +SQLITE_API int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors +** +** ^This routine sets a callback function that might be invoked whenever +** an attempt is made to open a database table that another thread +** or process has locked. +** +** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. ^If the busy callback +** is not NULL, then the callback might be invoked with two arguments. +** +** ^The first argument to the busy handler is a copy of the void* pointer which +** is the third argument to sqlite3_busy_handler(). ^The second argument to +** the busy handler callback is the number of times that the busy handler has +** been invoked for this locking event. ^If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** ^If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that it will be invoked +** when there is lock contention. ^If SQLite determines that invoking the busy +** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** ^The default busy callback is NULL. +** +** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. ^If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion +** forces an automatic rollback of the changes. See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** ^(There can only be a single busy handler defined for each +** [database connection]. Setting a new busy handler clears any +** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] +** will also set or clear the busy handler. +** +** The busy callback should not take any actions which modify the +** database connection that invoked the busy handler. Any such actions +** result in undefined behavior. +** +** A busy handler must not close the database connection +** or [prepared statement] that invoked the busy handler. +*/ +SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout +** +** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps +** for a specified amount of time when a table is locked. ^The handler +** will sleep multiple times until at least "ms" milliseconds of sleeping +** have accumulated. ^After at least "ms" milliseconds of sleeping, +** the handler returns 0 which causes [sqlite3_step()] to return +** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** ^Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** ^(There can only be a single busy handler for a particular +** [database connection] any any given moment. If another busy handler +** was defined (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared.)^ +*/ +SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries +** +** This is a legacy interface that is preserved for backwards compatibility. +** Use of this interface is not recommended. +** +** Definition: A result table is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** The table conceptually has a number of rows and columns. But +** these numbers are not part of the result table itself. These +** numbers are obtained separately. Let N be the number of rows +** and M be the number of columns. +** +** A result table is an array of pointers to zero-terminated UTF-8 strings. +** There are (N+1)*M elements in the array. The first M pointers point +** to zero-terminated strings that contain the names of the columns. +** The remaining entries all point to query results. NULL values result +** in NULL pointers. All other values are in their UTF-8 zero-terminated +** string representation as returned by [sqlite3_column_text()]. +** +** A result table might consist of one or more memory allocations. +** It is not safe to pass a result table directly to [sqlite3_free()]. +** A result table should be deallocated using [sqlite3_free_table()]. +** +** ^(As an example of the result table format, suppose a query result +** is as follows: +** +**
+**        Name        | Age
+**        -----------------------
+**        Alice       | 43
+**        Bob         | 28
+**        Cindy       | 21
+** 
+** +** There are two column (M==2) and three rows (N==3). Thus the +** result table has 8 entries. Suppose the result table is stored +** in an array names azResult. Then azResult holds this content: +** +**
+**        azResult[0] = "Name";
+**        azResult[1] = "Age";
+**        azResult[2] = "Alice";
+**        azResult[3] = "43";
+**        azResult[4] = "Bob";
+**        azResult[5] = "28";
+**        azResult[6] = "Cindy";
+**        azResult[7] = "21";
+** 
)^ +** +** ^The sqlite3_get_table() function evaluates one or more +** semicolon-separated SQL statements in the zero-terminated UTF-8 +** string of its 2nd parameter and returns a result table to the +** pointer given in its 3rd parameter. +** +** After the application has finished with the result from sqlite3_get_table(), +** it must pass the result table pointer to sqlite3_free_table() in order to +** release the memory that was malloced. Because of the way the +** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling +** function must not try to call [sqlite3_free()] directly. Only +** [sqlite3_free_table()] is able to release the memory properly and safely. +** +** The sqlite3_get_table() interface is implemented as a wrapper around +** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access +** to any internal data structures of SQLite. It uses only the public +** interface defined here. As a consequence, errors that occur in the +** wrapper layer outside of the internal [sqlite3_exec()] call are not +** reflected in subsequent calls to [sqlite3_errcode()] or +** [sqlite3_errmsg()]. +*/ +SQLITE_API int sqlite3_get_table( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + char ***pazResult, /* Results of the query */ + int *pnRow, /* Number of result rows written here */ + int *pnColumn, /* Number of result columns written here */ + char **pzErrmsg /* Error msg written here */ +); +SQLITE_API void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions +** +** These routines are work-alikes of the "printf()" family of functions +** from the standard C library. +** +** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** The strings returned by these two routines should be +** released by [sqlite3_free()]. ^Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. Note that the order of the +** first two parameters is reversed from snprintf().)^ This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. ^(Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer.)^ We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** ^As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. ^The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. So the longest string that can be completely +** written will be n-1 characters. +** +** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf() formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** ^(The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal.)^ By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, assume the string variable zText contains text as follows: +** +**
+**  char *zText = "It's a happy day!";
+** 
+** +** One can use this text in an SQL statement as follows: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
+**  INSERT INTO table1 VALUES('It''s a happy day!')
+** 
+** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
+**  INSERT INTO table1 VALUES('It's a happy day!');
+** 
+** +** This second example is an SQL syntax error. As a general rule you should +** always use %q instead of %s when inserting text into a string literal. +** +** ^(The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Additionally, if the parameter in the +** argument list is a NULL pointer, %Q substitutes the text "NULL" (without +** single quotes).)^ So, for example, one could say: +** +**
+**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
+**  sqlite3_exec(db, zSQL, 0, 0, 0);
+**  sqlite3_free(zSQL);
+** 
+** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** ^(The "%z" formatting option works like "%s" but with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string.)^ +*/ +SQLITE_API char *sqlite3_mprintf(const char*,...); +SQLITE_API char *sqlite3_vmprintf(const char*, va_list); +SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); +SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); + +/* +** CAPI3REF: Memory Allocation Subsystem +** +** The SQLite core uses these three routines for all of its own +** internal memory allocation needs. "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** Windows VFS uses native malloc() and free() for some operations. +** +** ^The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** ^If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. ^If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** ^Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. ^The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_realloc(). +** +** ^(The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter.)^ ^ If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** ^If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** ^sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** ^If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** ^If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary, or to a +** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time +** option is used. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be used. +** +** The Windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular Windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +** +** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else pointers obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have +** not yet been released. +** +** The application must not read or write any part of +** a block of memory after it has been released using +** [sqlite3_free()] or [sqlite3_realloc()]. +*/ +SQLITE_API void *sqlite3_malloc(int); +SQLITE_API void *sqlite3_realloc(void*, int); +SQLITE_API void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** routines, which form the built-in memory allocation subsystem. +** +** ^The [sqlite3_memory_used()] routine returns the number of bytes +** of memory currently outstanding (malloced but not freed). +** ^The [sqlite3_memory_highwater()] routine returns the maximum +** value of [sqlite3_memory_used()] since the high-water mark +** was last reset. ^The values returned by [sqlite3_memory_used()] and +** [sqlite3_memory_highwater()] include any overhead +** added by SQLite in its implementation of [sqlite3_malloc()], +** but not overhead added by the any underlying system library +** routines that [sqlite3_malloc()] may call. +** +** ^The memory high-water mark is reset to the current value of +** [sqlite3_memory_used()] if and only if the parameter to +** [sqlite3_memory_highwater()] is true. ^The value returned +** by [sqlite3_memory_highwater(1)] is the high-water mark +** prior to the reset. +*/ +SQLITE_API sqlite3_int64 sqlite3_memory_used(void); +SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Pseudo-Random Number Generator +** +** SQLite contains a high-quality pseudo-random number generator (PRNG) used to +** select random [ROWID | ROWIDs] when inserting new records into a table that +** already uses the largest possible [ROWID]. The PRNG is also used for +** the build-in random() and randomblob() SQL functions. This interface allows +** applications to access the same PRNG for other purposes. +** +** ^A call to this routine stores N bytes of randomness into buffer P. +** +** ^The first time this routine is invoked (either internally or by +** the application) the PRNG is seeded using randomness obtained +** from the xRandomness method of the default [sqlite3_vfs] object. +** ^On all subsequent invocations, the pseudo-randomness is generated +** internally and without recourse to the [sqlite3_vfs] xRandomness +** method. +*/ +SQLITE_API void sqlite3_randomness(int N, void *P); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks +** +** ^This routine registers a authorizer callback with a particular +** [database connection], supplied in the first argument. +** ^The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. ^The authorizer callback should +** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. ^If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then the [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. ^When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer will fail with an error message explaining that +** access is denied. +** +** ^The first parameter to the authorizer callback is a copy of the third +** parameter to the sqlite3_set_authorizer() interface. ^The second parameter +** to the callback is an integer [SQLITE_COPY | action code] that specifies +** the particular action to be authorized. ^The third through sixth parameters +** to the callback are zero-terminated strings that contain additional +** details about the action to be authorized. +** +** ^If the action code is [SQLITE_READ] +** and the callback returns [SQLITE_IGNORE] then the +** [prepared statement] statement is constructed to substitute +** a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] +** return can be used to deny an untrusted user access to individual +** columns of a table. +** ^If the action code is [SQLITE_DELETE] and the callback returns +** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the +** [truncate optimization] is disabled and all rows are deleted individually. +** +** An authorizer is used when [sqlite3_prepare | preparing] +** SQL statements from an untrusted source, to ensure that the SQL statements +** do not try to access data they are not allowed to see, or that they do not +** try to execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being [sqlite3_prepare | prepared] that +** disallows everything except [SELECT] statements. +** +** Applications that need to process SQL from untrusted sources +** might also consider lowering resource limits using [sqlite3_limit()] +** and limiting database size using the [max_page_count] [PRAGMA] +** in addition to using an authorizer. +** +** ^(Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call.)^ ^Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. +** +** The authorizer callback must not do anything that will modify +** the database connection that invoked the authorizer callback. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** statement might be re-prepared during [sqlite3_step()] due to a +** schema change. Hence, the application should ensure that the +** correct authorizer callback remains in place during the [sqlite3_step()]. +** +** ^Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. Authorization is not +** performed during statement evaluation in [sqlite3_step()], unless +** as stated in the previous paragraph, sqlite3_step() invokes +** sqlite3_prepare_v2() to reprepare a statement after a schema change. +*/ +SQLITE_API int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorize certain SQL statement actions. The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. +** +** These action code values signify what kind of operation is to be +** authorized. The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. ^(The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* Operation NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* NULL Function Name */ +#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** ^The callback function registered by sqlite3_trace() is invoked at +** various times when an SQL statement is being run by [sqlite3_step()]. +** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the +** SQL statement text as the statement first begins executing. +** ^(Additional sqlite3_trace() callbacks might occur +** as each triggered subprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger.)^ +** +** ^The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. ^The profile callback contains +** the original statement text and an estimate of wall-clock time +** of how long that statement took to run. ^The profile callback +** time is in units of nanoseconds, however the current implementation +** is only capable of millisecond resolution so the six least significant +** digits in the time are meaningless. Future versions of SQLite +** might provide greater resolution on the profiler callback. The +** sqlite3_profile() function is considered experimental and is +** subject to change in future versions of SQLite. +*/ +SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks +** +** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback +** function X to be invoked periodically during long running calls to +** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for +** database connection D. An example use for this +** interface is to keep a GUI updated during a large query. +** +** ^The parameter P is passed through as the only parameter to the +** callback function X. ^The parameter N is the number of +** [virtual machine instructions] that are evaluated between successive +** invocations of the callback X. +** +** ^Only a single progress handler may be defined at one time per +** [database connection]; setting a new progress handler cancels the +** old one. ^Setting parameter X to NULL disables the progress handler. +** ^The progress handler is also disabled by setting N to a value less +** than 1. +** +** ^If the progress callback returns non-zero, the operation is +** interrupted. This feature can be used to implement a +** "Cancel" button on a GUI progress dialog box. +** +** The progress handler callback must not do anything that will modify +** the database connection that invoked the progress handler. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +*/ +SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection +** +** ^These routines open an SQLite database file whose name is given by the +** filename argument. ^The filename argument is interpreted as UTF-8 for +** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte +** order for sqlite3_open16(). ^(A [database connection] handle is usually +** returned in *ppDb, even if an error occurs. The only exception is that +** if SQLite is unable to allocate memory to hold the [sqlite3] object, +** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] +** object.)^ ^(If the database is opened (and/or created) successfully, then +** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error following a failure of any +** of the sqlite3_open() routines. +** +** ^The default encoding for the database will be UTF-8 if +** sqlite3_open() or sqlite3_open_v2() is called and +** UTF-16 in the native byte order if sqlite3_open16() is used. +** +** Whether or not an error occurs when it is opened, resources +** associated with the [database connection] handle should be released by +** passing it to [sqlite3_close()] when it is no longer required. +** +** The sqlite3_open_v2() interface works like sqlite3_open() +** except that it accepts two additional parameters for additional control +** over the new database connection. ^(The flags parameter to +** sqlite3_open_v2() can take one of +** the following three values, optionally combined with the +** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], +** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^ +** +**
+** ^(
[SQLITE_OPEN_READONLY]
+**
The database is opened in read-only mode. If the database does not +** already exist, an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE]
+**
The database is opened for reading and writing if possible, or reading +** only if the file is write protected by the operating system. In either +** case the database must already exist, otherwise an error is returned.
)^ +** +** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
+**
The database is opened for reading and writing, and is created if +** it does not already exist. This is the behavior that is always used for +** sqlite3_open() and sqlite3_open16().
)^ +**
+** +** If the 3rd parameter to sqlite3_open_v2() is not one of the +** combinations shown above or one of the combinations shown above combined +** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], +** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags, +** then the behavior is undefined. +** +** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection +** opens in the multi-thread [threading mode] as long as the single-thread +** mode has not been set at compile-time or start-time. ^If the +** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens +** in the serialized [threading mode] unless single-thread was +** previously selected at compile-time or start-time. +** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be +** eligible to use [shared cache mode], regardless of whether or not shared +** cache is enabled using [sqlite3_enable_shared_cache()]. ^The +** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not +** participate in [shared cache mode] even if it is enabled. +** +** ^If the filename is ":memory:", then a private, temporary in-memory database +** is created for the connection. ^This in-memory database will vanish when +** the database connection is closed. Future versions of SQLite might +** make use of additional special filenames that begin with the ":" character. +** It is recommended that when a database filename actually does begin with +** a ":" character you should prefix the filename with a pathname such as +** "./" to avoid ambiguity. +** +** ^If the filename is an empty string, then a private, temporary +** on-disk database will be created. ^This private database will be +** automatically deleted as soon as the database connection is closed. +** +** ^The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system interface that +** the new database connection should use. ^If the fourth parameter is +** a NULL pointer then the default [sqlite3_vfs] object is used. +** +** Note to Windows users: The encoding used for the filename argument +** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** sqlite3_open() or sqlite3_open_v2(). +*/ +SQLITE_API int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +SQLITE_API int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages +** +** ^The sqlite3_errcode() interface returns the numeric [result code] or +** [extended result code] for the most recent failed sqlite3_* API call +** associated with a [database connection]. If a prior API call failed +** but the most recent API call succeeded, the return value from +** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() +** interface is the same except that it always returns the +** [extended result code] even when extended result codes are +** disabled. +** +** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF-8 or UTF-16 respectively. +** ^(Memory to hold the error message string is managed internally. +** The application does not need to worry about freeing the result. +** However, the error string might be overwritten or deallocated by +** subsequent calls to other SQLite interface functions.)^ +** +** When the serialized [threading mode] is in use, it might be the +** case that a second error occurs on a separate thread in between +** the time of the first error and the call to these interfaces. +** When that happens, the second error will be reported since these +** interfaces always report the most recent result. To avoid +** this, each thread can obtain exclusive use of the [database connection] D +** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning +** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after +** all calls to the interfaces listed here are completed. +** +** If an interface fails with SQLITE_MISUSE, that means the interface +** was invoked incorrectly by the application. In that case, the +** error code and message may or may not be set. +*/ +SQLITE_API int sqlite3_errcode(sqlite3 *db); +SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); +SQLITE_API const char *sqlite3_errmsg(sqlite3*); +SQLITE_API const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object +** KEYWORDS: {prepared statement} {prepared statements} +** +** An instance of this object represents a single SQL statement. +** This object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
    +**
  1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
  2. Bind values to [host parameters] using the sqlite3_bind_*() +** interfaces. +**
  3. Run the SQL by calling [sqlite3_step()] one or more times. +**
  4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
  5. Destroy the object using [sqlite3_finalize()]. +**
+** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Run-time Limits +** +** ^(This interface allows the size of various constructs to be limited +** on a connection by connection basis. The first parameter is the +** [database connection] whose limit is to be set or queried. The +** second parameter is one of the [limit categories] that define a +** class of constructs to be size limited. The third parameter is the +** new limit for that construct.)^ +** +** ^If the new limit is a negative number, the limit is unchanged. +** ^(For each limit category SQLITE_LIMIT_NAME there is a +** [limits | hard upper bound] +** set at compile-time by a C preprocessor macro called +** [limits | SQLITE_MAX_NAME]. +** (The "_LIMIT_" in the name is changed to "_MAX_".))^ +** ^Attempts to increase a limit above its hard upper bound are +** silently truncated to the hard upper bound. +** +** ^Regardless of whether or not the limit was changed, the +** [sqlite3_limit()] interface returns the prior value of the limit. +** ^Hence, to find the current value of a limit without changing it, +** simply invoke this interface with the third parameter set to -1. +** +** Run-time limits are intended for use in applications that manage +** both their own internal database and also databases that are controlled +** by untrusted external sources. An example application might be a +** web browser that has its own databases for storing history and +** separate databases controlled by JavaScript applications downloaded +** off the Internet. The internal databases can be given the +** large, default limits. Databases managed by external sources can +** be given much smaller limits designed to prevent a denial of service +** attack. Developers might also want to use the [sqlite3_set_authorizer()] +** interface to further control untrusted SQL. The size of the database +** created by an untrusted script can be contained using the +** [max_page_count] [PRAGMA]. +** +** New run-time limit categories may be added in future releases. +*/ +SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); + +/* +** CAPI3REF: Run-Time Limit Categories +** KEYWORDS: {limit category} {*limit categories} +** +** These constants define various performance limits +** that can be lowered at run-time using [sqlite3_limit()]. +** The synopsis of the meanings of the various limits is shown below. +** Additional information is available at [limits | Limits in SQLite]. +** +**
+** ^(
SQLITE_LIMIT_LENGTH
+**
The maximum size of any string or BLOB or table row, in bytes.
)^ +** +** ^(
SQLITE_LIMIT_SQL_LENGTH
+**
The maximum length of an SQL statement, in bytes.
)^ +** +** ^(
SQLITE_LIMIT_COLUMN
+**
The maximum number of columns in a table definition or in the +** result set of a [SELECT] or the maximum number of columns in an index +** or in an ORDER BY or GROUP BY clause.
)^ +** +** ^(
SQLITE_LIMIT_EXPR_DEPTH
+**
The maximum depth of the parse tree on any expression.
)^ +** +** ^(
SQLITE_LIMIT_COMPOUND_SELECT
+**
The maximum number of terms in a compound SELECT statement.
)^ +** +** ^(
SQLITE_LIMIT_VDBE_OP
+**
The maximum number of instructions in a virtual machine program +** used to implement an SQL statement. This limit is not currently +** enforced, though that might be added in some future release of +** SQLite.
)^ +** +** ^(
SQLITE_LIMIT_FUNCTION_ARG
+**
The maximum number of arguments on a function.
)^ +** +** ^(
SQLITE_LIMIT_ATTACHED
+**
The maximum number of [ATTACH | attached databases].)^
+** +** ^(
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
+**
The maximum length of the pattern argument to the [LIKE] or +** [GLOB] operators.
)^ +** +** ^(
SQLITE_LIMIT_VARIABLE_NUMBER
+**
The maximum index number of any [parameter] in an SQL statement.)^ +** +** ^(
SQLITE_LIMIT_TRIGGER_DEPTH
+**
The maximum depth of recursion for triggers.
)^ +**
+*/ +#define SQLITE_LIMIT_LENGTH 0 +#define SQLITE_LIMIT_SQL_LENGTH 1 +#define SQLITE_LIMIT_COLUMN 2 +#define SQLITE_LIMIT_EXPR_DEPTH 3 +#define SQLITE_LIMIT_COMPOUND_SELECT 4 +#define SQLITE_LIMIT_VDBE_OP 5 +#define SQLITE_LIMIT_FUNCTION_ARG 6 +#define SQLITE_LIMIT_ATTACHED 7 +#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 +#define SQLITE_LIMIT_VARIABLE_NUMBER 9 +#define SQLITE_LIMIT_TRIGGER_DEPTH 10 + +/* +** CAPI3REF: Compiling An SQL Statement +** KEYWORDS: {SQL statement compiler} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** The first argument, "db", is a [database connection] obtained from a +** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or +** [sqlite3_open16()]. The database connection must not have been closed. +** +** The second argument, "zSql", is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. +** +** ^If the nByte argument is less than zero, then zSql is read up to the +** first zero terminator. ^If nByte is non-negative, then it is the maximum +** number of bytes read from zSql. ^When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** the nByte-th byte, whichever comes first. If the caller knows +** that the supplied string is nul-terminated, then there is a small +** performance advantage to be gained by passing an nByte parameter that +** is equal to the number of bytes in the input string including +** the nul-terminator bytes. +** +** ^If pzTail is not NULL then *pzTail is made to point to the first byte +** past the end of the first SQL statement in zSql. These routines only +** compile the first statement in zSql, so *pzTail is left pointing to +** what remains uncompiled. +** +** ^*ppStmt is left pointing to a compiled [prepared statement] that can be +** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set +** to NULL. ^If the input text contains no SQL (if the input is an empty +** string or a comment) then *ppStmt is set to NULL. +** The calling procedure is responsible for deleting the compiled +** SQL statement using [sqlite3_finalize()] after it has finished with it. +** ppStmt may not be NULL. +** +** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; +** otherwise an [error code] is returned. +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** ^In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. This causes the [sqlite3_step()] interface to +** behave differently in three ways: +** +**
    +**
  1. +** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. +**
  2. +** +**
  3. +** ^When an error occurs, [sqlite3_step()] will return one of the detailed +** [error codes] or [extended error codes]. ^The legacy behavior was that +** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code +** and the application would have to make a second call to [sqlite3_reset()] +** in order to find the underlying cause of the problem. With the "v2" prepare +** interfaces, the underlying reason for the error is returned immediately. +**
  4. +** +**
  5. +** ^If the specific value bound to [parameter | host parameter] in the +** WHERE clause might influence the choice of query plan for a statement, +** then the statement will be automatically recompiled, as if there had been +** a schema change, on the first [sqlite3_step()] call following any change +** to the [sqlite3_bind_text | bindings] of that [parameter]. +** ^The specific value of WHERE-clause [parameter] might influence the +** choice of query plan if the parameter is the left-hand side of a [LIKE] +** or [GLOB] operator or if the parameter is compared to an indexed column +** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled. +** the +**
  6. +**
+*/ +SQLITE_API int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +SQLITE_API int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPI3REF: Retrieving Statement SQL +** +** ^This interface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement] if that statement was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +*/ +SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Determine If An SQL Statement Writes The Database +** +** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if +** and only if the [prepared statement] X makes no direct changes to +** the content of the database file. +** +** Note that [application-defined SQL functions] or +** [virtual tables] might change the database indirectly as a side effect. +** ^(For example, if an application defines a function "eval()" that +** calls [sqlite3_exec()], then the following SQL statement would +** change the database file through side-effects: +** +**
+**    SELECT eval('DELETE FROM t1') FROM t2;
+** 
+** +** But because the [SELECT] statement does not change the database file +** directly, sqlite3_stmt_readonly() would still return true.)^ +** +** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], +** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, +** since the statements themselves do not actually modify the database but +** rather they control the timing of when other statements modify the +** database. ^The [ATTACH] and [DETACH] statements also cause +** sqlite3_stmt_readonly() to return true since, while those statements +** change the configuration of a database connection, they do not make +** changes to the content of the database files on disk. +*/ +SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object +** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** +** SQLite uses the sqlite3_value object to represent all values +** that can be stored in a database table. SQLite uses dynamic typing +** for the values it stores. ^Values stored in sqlite3_value objects +** can be integers, floating point values, strings, BLOBs, or NULL. +** +** An sqlite3_value object may be either "protected" or "unprotected". +** Some interfaces require a protected sqlite3_value. Other interfaces +** will accept either a protected or an unprotected sqlite3_value. +** Every interface that accepts sqlite3_value arguments specifies +** whether or not it requires a protected sqlite3_value. +** +** The terms "protected" and "unprotected" refer to whether or not +** a mutex is held. A internal mutex is held for a protected +** sqlite3_value object but no mutex is held for an unprotected +** sqlite3_value object. If SQLite is compiled to be single-threaded +** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) +** or if SQLite is run in one of reduced mutex modes +** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] +** then there is no distinction between protected and unprotected +** sqlite3_value objects and they can be used interchangeably. However, +** for maximum code portability it is recommended that applications +** still make the distinction between protected and unprotected +** sqlite3_value objects even when not strictly required. +** +** ^The sqlite3_value objects that are passed as parameters into the +** implementation of [application-defined SQL functions] are protected. +** ^The sqlite3_value object returned by +** [sqlite3_column_value()] is unprotected. +** Unprotected sqlite3_value objects may only be used with +** [sqlite3_result_value()] and [sqlite3_bind_value()]. +** The [sqlite3_value_blob | sqlite3_value_type()] family of +** interfaces require protected sqlite3_value objects. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. ^A pointer to an sqlite3_context object +** is always first parameter to [application-defined SQL functions]. +** The application-defined SQL function implementation will pass this +** pointer through into calls to [sqlite3_result_int | sqlite3_result()], +** [sqlite3_aggregate_context()], [sqlite3_user_data()], +** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], +** and/or [sqlite3_set_auxdata()]. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements +** KEYWORDS: {host parameter} {host parameters} {host parameter name} +** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** +** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, +** literals may be replaced by a [parameter] that matches one of following +** templates: +** +**
    +**
  • ? +**
  • ?NNN +**
  • :VVV +**
  • @VVV +**
  • $VVV +**
+** +** In the templates above, NNN represents an integer literal, +** and VVV represents an alphanumeric identifier.)^ ^The values of these +** parameters (also called "host parameter names" or "SQL parameters") +** can be set using the sqlite3_bind_*() routines defined here. +** +** ^The first argument to the sqlite3_bind_*() routines is always +** a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. +** +** ^The second argument is the index of the SQL parameter to be set. +** ^The leftmost SQL parameter has an index of 1. ^When the same named +** SQL parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** ^The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_index()] API if desired. ^The index +** for "?NNN" parameters is the value of NNN. +** ^The NNN value must be between 1 and the [sqlite3_limit()] +** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** +** ^The third argument is the value to bind to the parameter. +** +** ^(In those routines that have a fourth argument, its value is the +** number of bytes in the parameter. To be clear: the value is the +** number of bytes in the value, not the number of characters.)^ +** ^If the fourth parameter is negative, the length of the string is +** the number of bytes up to the first zero terminator. +** +** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** string after SQLite has finished with it. ^The destructor is called +** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), +** sqlite3_bind_text(), or sqlite3_bind_text16() fails. +** ^If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite assumes that the +** information is in static, unmanaged space and does not need to be freed. +** ^If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeroes. ^A zeroblob uses a fixed amount of memory +** (just an integer to hold its size) while it is being processed. +** Zeroblobs are intended to serve as placeholders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | incremental BLOB I/O] routines. +** ^A negative value for the zeroblob results in a zero-length BLOB. +** +** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer +** for the [prepared statement] or with a prepared statement for which +** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() +** routine is passed a [prepared statement] that has been finalized, the +** result is undefined and probably harmful. +** +** ^Bindings are not cleared by the [sqlite3_reset()] routine. +** ^Unbound parameters are interpreted as NULL. +** +** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an +** [error code] if anything goes wrong. +** ^[SQLITE_RANGE] is returned if the parameter +** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. +** +** See also: [sqlite3_bind_parameter_count()], +** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); +SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); +SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); +SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of SQL Parameters +** +** ^This routine can be used to find the number of [SQL parameters] +** in a [prepared statement]. SQL parameters are tokens of the +** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as +** placeholders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** ^(This routine actually returns the index of the largest (rightmost) +** parameter. For all forms except ?NNN, this will correspond to the +** number of unique parameters. If parameters of the ?NNN form are used, +** there may be gaps in the list.)^ +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_name()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter +** +** ^The sqlite3_bind_parameter_name(P,N) interface returns +** the name of the N-th [SQL parameter] in the [prepared statement] P. +** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" +** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" +** respectively. +** In other words, the initial ":" or "$" or "@" or "?" +** is included as part of the name.)^ +** ^Parameters of the form "?" without a following integer have no name +** and are referred to as "nameless" or "anonymous parameters". +** +** ^The first host parameter has an index of 1, not 0. +** +** ^If the value N is out of range or if the N-th parameter is +** nameless, then NULL is returned. ^The returned string is +** always in UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name +** +** ^Return the index of an SQL parameter given its name. ^The +** index value returned is suitable for use as the second +** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero +** is returned if no matching parameter is found. ^The parameter +** name must be given in UTF-8 even if the original statement +** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. +** +** See also: [sqlite3_bind_blob|sqlite3_bind()], +** [sqlite3_bind_parameter_count()], and +** [sqlite3_bind_parameter_index()]. +*/ +SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement +** +** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset +** the [sqlite3_bind_blob | bindings] on a [prepared statement]. +** ^Use this routine to reset all host parameters to NULL. +*/ +SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set +** +** ^Return the number of columns in the result set returned by the +** [prepared statement]. ^This routine returns 0 if pStmt is an SQL +** statement that does not return data (for example an [UPDATE]). +** +** See also: [sqlite3_data_count()] +*/ +SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set +** +** ^These routines return the name assigned to a particular column +** in the result set of a [SELECT] statement. ^The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF-8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF-16 string. ^The first parameter is the [prepared statement] +** that implements the [SELECT] statement. ^The second parameter is the +** column number. ^The leftmost column is number 0. +** +** ^The returned string pointer is valid until either the [prepared statement] +** is destroyed by [sqlite3_finalize()] or until the next call to +** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** +** ^If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +** +** ^The name of a result column is the value of the "AS" clause for +** that column, if there is an AS clause. If there is no AS clause +** then the name of the column is unspecified and may change from +** one release of SQLite to the next. +*/ +SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); +SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result +** +** ^These routines provide a means to determine the database, table, and +** table column that is the origin of a particular result column in +** [SELECT] statement. +** ^The name of the database or table or column can be returned as +** either a UTF-8 or UTF-16 string. ^The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. +** ^The returned string is valid until the [prepared statement] is destroyed +** using [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** ^The names returned are the original un-aliased names of the +** database, table, and column. +** +** ^The first argument to these interfaces is a [prepared statement]. +** ^These functions return information about the Nth result column returned by +** the statement, where N is the second function argument. +** ^The left-most column is column 0 for these routines. +** +** ^If the Nth column returned by the statement is an expression or +** subquery and is not a column value, then all of these functions return +** NULL. ^These routine might also return NULL if a memory allocation error +** occurs. ^Otherwise, they return the name of the attached database, table, +** or column that query result column was extracted from. +** +** ^As with all other SQLite APIs, those whose names end with "16" return +** UTF-16 encoded strings and the other functions return UTF-8. +** +** ^These APIs are only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. +** +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +** +** If two or more threads call one or more +** [sqlite3_column_database_name | column metadata interfaces] +** for the same [prepared statement] and result column +** at the same time then the results are undefined. +*/ +SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result +** +** ^(The first parameter is a [prepared statement]. +** If this statement is a [SELECT] statement and the Nth column of the +** returned result set of that [SELECT] is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned.)^ ^If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** ^The returned string is always UTF-8 encoded. +** +** ^(For example, given the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** and the following statement to be compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** this routine would return the string "VARIANT" for the second result +** column (i==1), and a NULL pointer for the first result column (i==0).)^ +** +** ^SQLite uses dynamic run-time typing. ^So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. ^Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement +** +** After a [prepared statement] has been prepared using either +** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function +** must be called one or more times to evaluate the statement. +** +** The details of the behavior of the sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** ^In the legacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** ^With the "v2" interface, any of the other [result codes] or +** [extended result codes] might be returned as well. +** +** ^[SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. ^If the statement is a [COMMIT] +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a [COMMIT] and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** ^[SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] +** is returned each time a new row of data is ready for processing by the +** caller. The values may be accessed using the [column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** ^[SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** ^With the legacy interface, a more specific error code (for example, +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [prepared statement]. ^In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** For all versions of SQLite up to and including 3.6.23.1, a call to +** [sqlite3_reset()] was required after sqlite3_step() returned anything +** other than [SQLITE_ROW] before any subsequent invocation of +** sqlite3_step(). Failure to reset the prepared statement using +** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from +** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began +** calling [sqlite3_reset()] automatically in this circumstance rather +** than returning [SQLITE_MISUSE]. This is not considered a compatibility +** break because any application that ever receives an SQLITE_MISUSE error +** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option +** can be used to restore the legacy behavior. +** +** Goofy Interface Alert: In the legacy interface, the sqlite3_step() +** API always returns a generic error code, [SQLITE_ERROR], following any +** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call +** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the +** specific [error codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, +** then the more specific [error codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +SQLITE_API int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set +** +** ^The sqlite3_data_count(P) interface returns the number of columns in the +** current row of the result set of [prepared statement] P. +** ^If prepared statement P does not have results ready to return +** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of +** interfaces) then sqlite3_data_count(P) returns 0. +** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. +** +** See also: [sqlite3_column_count()] +*/ +SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes +** KEYWORDS: SQLITE_TEXT +** +** ^(Every value in SQLite has one of five fundamental datatypes: +** +**
    +**
  • 64-bit signed integer +**
  • 64-bit IEEE floating point number +**
  • string +**
  • BLOB +**
  • NULL +**
)^ +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Result Values From A Query +** KEYWORDS: {column access functions} +** +** These routines form the "result set" interface. +** +** ^These routines return information about a single column of the current +** result row of a query. ^In every case the first argument is a pointer +** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] +** that was returned from [sqlite3_prepare_v2()] or one of its variants) +** and the second argument is the index of the column for which information +** should be returned. ^The leftmost column of the result set has the index 0. +** ^The number of columns in the result can be determined using +** [sqlite3_column_count()]. +** +** If the SQL statement does not currently point to a valid row, or if the +** column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** ^The sqlite3_column_type() routine returns the +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. ^The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes() returns zero. +** +** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() +** routine returns the number of bytes in that BLOB or string. +** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts +** the string to UTF-16 and then returns the number of bytes. +** ^If the result is a numeric value then sqlite3_column_bytes16() uses +** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns +** the number of bytes in that string. +** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. +** +** ^The values returned by [sqlite3_column_bytes()] and +** [sqlite3_column_bytes16()] do not include the zero terminators at the end +** of the string. ^For clarity: the values returned by +** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of +** bytes in the string, not the number of characters. +** +** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even empty strings, are always zero terminated. ^The return +** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. +** +** ^The object returned by [sqlite3_column_value()] is an +** [unprotected sqlite3_value] object. An unprotected sqlite3_value object +** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. +** If the [unprotected sqlite3_value] object returned by +** [sqlite3_column_value()] is used in any other way, including calls +** to routines like [sqlite3_value_int()], [sqlite3_value_text()], +** or [sqlite3_value_bytes()], then the behavior is undefined. +** +** These routines attempt to convert the value where appropriate. ^For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to perform the +** conversion automatically. ^(The following table details the conversions +** that are applied: +** +**
+** +**
Internal
Type
Requested
Type
Conversion +** +**
NULL INTEGER Result is 0 +**
NULL FLOAT Result is 0.0 +**
NULL TEXT Result is NULL pointer +**
NULL BLOB Result is NULL pointer +**
INTEGER FLOAT Convert from integer to float +**
INTEGER TEXT ASCII rendering of the integer +**
INTEGER BLOB Same as INTEGER->TEXT +**
FLOAT INTEGER Convert from float to integer +**
FLOAT TEXT ASCII rendering of the float +**
FLOAT BLOB Same as FLOAT->TEXT +**
TEXT INTEGER Use atoi() +**
TEXT FLOAT Use atof() +**
TEXT BLOB No change +**
BLOB INTEGER Convert to TEXT then use atoi() +**
BLOB FLOAT Convert to TEXT then use atof() +**
BLOB TEXT Add a zero terminator if needed +**
+**
)^ +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** own equivalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
    +**
  • The initial content is a BLOB and sqlite3_column_text() or +** sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.
  • +**
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.
  • +**
  • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.
  • +**
+** +** ^Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer references will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometimes they +** are not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
    +**
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • +**
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • +**
+** +** In other words, you should call sqlite3_column_text(), +** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result +** into the desired format, then invoke sqlite3_column_bytes() or +** sqlite3_column_bytes16() to find the size of the result. Do not mix calls +** to sqlite3_column_text() or sqlite3_column_blob() with calls to +** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() +** with calls to sqlite3_column_bytes(). +** +** ^The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. ^The memory space used to hold strings +** and BLOBs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** ^(If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM].)^ +*/ +SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); +SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object +** +** ^The sqlite3_finalize() function is called to delete a [prepared statement]. +** ^If the most recent evaluation of the statement encountered no errors or +** or if the statement is never been evaluated, then sqlite3_finalize() returns +** SQLITE_OK. ^If the most recent evaluation of statement S failed, then +** sqlite3_finalize(S) returns the appropriate [error code] or +** [extended error code]. +** +** ^The sqlite3_finalize(S) routine can be called at any point during +** the life cycle of [prepared statement] S: +** before statement S is ever evaluated, after +** one or more calls to [sqlite3_reset()], or after any call +** to [sqlite3_step()] regardless of whether or not the statement has +** completed execution. +** +** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. +** +** The application must finalize every [prepared statement] in order to avoid +** resource leaks. It is a grievous error for the application to try to use +** a prepared statement after it has been finalized. Any use of a prepared +** statement after it has been finalized can result in undefined and +** undesirable behavior such as segfaults and heap corruption. +*/ +SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object +** +** The sqlite3_reset() function is called to reset a [prepared statement] +** object back to its initial state, ready to be re-executed. +** ^Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +** +** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S +** back to the beginning of its program. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], +** or if [sqlite3_step(S)] has never before been called on S, +** then [sqlite3_reset(S)] returns [SQLITE_OK]. +** +** ^If the most recent call to [sqlite3_step(S)] for the +** [prepared statement] S indicated an error, then +** [sqlite3_reset(S)] returns an appropriate [error code]. +** +** ^The [sqlite3_reset(S)] interface does not change the values +** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. +*/ +SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions +** KEYWORDS: {function creation routines} +** KEYWORDS: {application-defined SQL function} +** KEYWORDS: {application-defined SQL functions} +** +** ^These functions (collectively known as "function creation routines") +** are used to add SQL functions or aggregates or to redefine the behavior +** of existing SQL functions or aggregates. The only differences between +** these routines are the text encoding expected for +** the the second parameter (the name of the function being created) +** and the presence or absence of a destructor callback for +** the application data pointer. +** +** ^The first parameter is the [database connection] to which the SQL +** function is to be added. ^If an application uses more than one database +** connection then application-defined SQL functions must be added +** to each database connection separately. +** +** ^The second parameter is the name of the SQL function to be created or +** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 +** representation, exclusive of the zero-terminator. ^Note that the name +** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. +** ^Any attempt to create a function with a longer name +** will result in [SQLITE_MISUSE] being returned. +** +** ^The third parameter (nArg) +** is the number of arguments that the SQL function or +** aggregate takes. ^If this parameter is -1, then the SQL function or +** aggregate may take any number of arguments between 0 and the limit +** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third +** parameter is less than -1 or greater than 127 then the behavior is +** undefined. +** +** ^The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Every SQL function implementation must be able to work +** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. ^An application may +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** ^When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what text +** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** +** ^(The fifth parameter is an arbitrary pointer. The implementation of the +** function can gain access to this pointer using [sqlite3_user_data()].)^ +** +** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL function or +** aggregate. ^A scalar SQL function requires an implementation of the xFunc +** callback only; NULL pointers must be passed as the xStep and xFinal +** parameters. ^An aggregate SQL function requires an implementation of xStep +** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing +** SQL function or aggregate, pass NULL poiners for all three function +** callbacks. +** +** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, +** then it is destructor for the application data pointer. +** The destructor is invoked when the function is deleted, either by being +** overloaded or when the database connection closes.)^ +** ^The destructor is also invoked if the call to +** sqlite3_create_function_v2() fails. +** ^When the destructor callback of the tenth parameter is invoked, it +** is passed a single argument which is a copy of the application data +** pointer which was the fifth parameter to sqlite3_create_function_v2(). +** +** ^It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing preferred text encodings. ^SQLite will use +** the implementation that most closely matches the way in which the +** SQL function is used. ^A function implementation with a non-negative +** nArg parameter is a better match than a function implementation with +** a negative nArg. ^A function where the preferred text encoding +** matches the database encoding is a better +** match than a function where the encoding is different. +** ^A function where the encoding difference is between UTF16le and UTF16be +** is a closer match than a function where the encoding difference is +** between UTF8 and UTF16. +** +** ^Built-in functions may be overloaded by new application-defined functions. +** +** ^An application-defined function is permitted to call other +** SQLite interfaces. However, such calls must not +** close the database connection nor finalize or reset the prepared +** statement in which the function is running. +*/ +SQLITE_API int sqlite3_create_function( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function16( + sqlite3 *db, + const void *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +SQLITE_API int sqlite3_create_function_v2( + sqlite3 *db, + const char *zFunctionName, + int nArg, + int eTextRep, + void *pApp, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*), + void(*xDestroy)(void*) +); + +/* +** CAPI3REF: Text Encodings +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Deprecated Functions +** DEPRECATED +** +** These functions are [deprecated]. In order to maintain +** backwards compatibility with older code, these functions continue +** to be supported. However, new applications should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you what they do. +*/ +#ifndef SQLITE_OMIT_DEPRECATED +SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); +SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); +SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); +#endif + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 3rd parameter to these callbacks is an array of pointers to +** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work only with [protected sqlite3_value] objects. +** Any attempt to use these routines on an [unprotected sqlite3_value] +** object results in undefined behavior. +** +** ^These routines work just like the corresponding [column access functions] +** except that these routines take a single [protected sqlite3_value] object +** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. +** +** ^The sqlite3_value_text16() interface extracts a UTF-16 string +** in the native byte-order of the host machine. ^The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF-16 strings as big-endian and little-endian respectively. +** +** ^(The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words, if the value is a string that looks like a number) +** then the conversion is performed. Otherwise no conversion occurs. +** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ +** +** Please pay particular attention to the fact that the pointer returned +** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the [sqlite3_value*] parameters. +*/ +SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes(sqlite3_value*); +SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); +SQLITE_API double sqlite3_value_double(sqlite3_value*); +SQLITE_API int sqlite3_value_int(sqlite3_value*); +SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); +SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); +SQLITE_API int sqlite3_value_type(sqlite3_value*); +SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context +** +** Implementations of aggregate SQL functions use this +** routine to allocate memory for storing their state. +** +** ^The first time the sqlite3_aggregate_context(C,N) routine is called +** for a particular aggregate function, SQLite +** allocates N of memory, zeroes out that memory, and returns a pointer +** to the new memory. ^On second and subsequent calls to +** sqlite3_aggregate_context() for the same aggregate function instance, +** the same buffer is returned. Sqlite3_aggregate_context() is normally +** called once for each invocation of the xStep callback and then one +** last time when the xFinal callback is invoked. ^(When no rows match +** an aggregate query, the xStep() callback of the aggregate function +** implementation is never called and xFinal() is called exactly once. +** In those cases, sqlite3_aggregate_context() might be called for the +** first time from within xFinal().)^ +** +** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is +** less than or equal to zero or if a memory allocate error occurs. +** +** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is +** determined by the N parameter on first successful call. Changing the +** value of N in subsequent call to sqlite3_aggregate_context() within +** the same aggregate function instance will not resize the memory +** allocation.)^ +** +** ^SQLite automatically frees the memory allocated by +** sqlite3_aggregate_context() when the aggregate query concludes. +** +** The first parameter must be a copy of the +** [sqlite3_context | SQL function context] that is the first parameter +** to the xStep or xFinal callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions +** +** ^The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +** +** This routine must be called from the same thread in which +** the application-defined function is running. +*/ +SQLITE_API void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Database Connection For Functions +** +** ^The sqlite3_context_db_handle() interface returns a copy of +** the pointer to the [database connection] (the 1st parameter) +** of the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. +*/ +SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data +** +** The following two functions may be used by scalar SQL functions to +** associate metadata with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated metadata may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** metadata associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. ^If no metadata has been ever +** been set for the Nth argument of the function, or if the corresponding +** function parameter has changed since the meta-data was set, +** then sqlite3_get_auxdata() returns a NULL pointer. +** +** ^The sqlite3_set_auxdata() interface saves the metadata +** pointed to by its 3rd parameter as the metadata for the N-th +** argument of the application-defined function. Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** ^If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the metadata when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. +** +** SQLite is free to call the destructor and drop metadata on any +** parameter of any function at any time. ^The only guarantee is that +** the destructor will be called before the metadata is dropped. +** +** ^(In practice, metadata is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and [parameters].)^ +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior +** +** These are special values for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. ^If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. ^The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the [parameter binding] family of +** functions used to bind values to host parameters in prepared statements. +** Refer to the [SQL parameter] documentation for additional information. +** +** ^The sqlite3_result_blob() interface sets the result from +** an application-defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** +** ^The sqlite3_result_zeroblob() interfaces set the result of +** the application-defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** ^The sqlite3_result_double() interface sets the result from +** an application-defined function to be a floating point value specified +** by its 2nd argument. +** +** ^The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** ^SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. ^SQLite interprets the error +** message string from sqlite3_result_error() as UTF-8. ^SQLite +** interprets the string from sqlite3_result_error16() as UTF-16 in native +** byte order. ^If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** ^If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** ^The sqlite3_result_error() and sqlite3_result_error16() +** routines make a private copy of the error message text before +** they return. Hence, the calling function can deallocate or +** modify the text after they return without harm. +** ^The sqlite3_result_error_code() function changes the error code +** returned by SQLite as a result of an error in a function. ^By default, +** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() +** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. +** +** ^The sqlite3_result_toobig() interface causes SQLite to throw an error +** indicating that a string or BLOB is too long to represent. +** +** ^The sqlite3_result_nomem() interface causes SQLite to throw an error +** indicating that a memory allocation failed. +** +** ^The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** ^The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** ^The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** ^The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** ^SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** ^If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or BLOB result when it has +** finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces or to +** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite +** assumes that the text or BLOB result is in constant space and does not +** copy the content of the parameter nor call a destructor on the content +** when it has finished using that result. +** ^If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** ^The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the +** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that the [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** ^A [protected sqlite3_value] object may always be used where an +** [unprotected sqlite3_value] object is required, so either +** kind of [sqlite3_value] object can be used with this interface. +** +** If these routines are called from within the different thread +** than the one containing the application-defined function that received +** the [sqlite3_context] pointer, the results are undefined. +*/ +SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_double(sqlite3_context*, double); +SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); +SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); +SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); +SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); +SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int(sqlite3_context*, int); +SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +SQLITE_API void sqlite3_result_null(sqlite3_context*); +SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences +** +** ^These functions add, remove, or modify a [collation] associated +** with the [database connection] specified as the first argument. +** +** ^The name of the collation is a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string in native byte order for sqlite3_create_collation16(). +** ^Collation names that compare equal according to [sqlite3_strnicmp()] are +** considered to be the same name. +** +** ^(The third argument (eTextRep) must be one of the constants: +**
    +**
  • [SQLITE_UTF8], +**
  • [SQLITE_UTF16LE], +**
  • [SQLITE_UTF16BE], +**
  • [SQLITE_UTF16], or +**
  • [SQLITE_UTF16_ALIGNED]. +**
)^ +** ^The eTextRep argument determines the encoding of strings passed +** to the collating function callback, xCallback. +** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep +** force strings to be UTF16 with native byte order. +** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin +** on an even byte address. +** +** ^The fourth argument, pArg, is a application data pointer that is passed +** through as the first argument to the collating function callback. +** +** ^The fifth argument, xCallback, is a pointer to the collating function. +** ^Multiple collating functions can be registered using the same name but +** with different eTextRep parameters and SQLite will use whichever +** function requires the least amount of data transformation. +** ^If the xCallback argument is NULL then the collating function is +** deleted. ^When all collating functions having the same name are deleted, +** that collation is no longer usable. +** +** ^The collating function callback is invoked with a copy of the pArg +** application data pointer and with two strings in the encoding specified +** by the eTextRep argument. The collating function must return an +** integer that is negative, zero, or positive +** if the first string is less than, equal to, or greater than the second, +** respectively. A collating function must alway return the same answer +** given the same inputs. If two or more collating functions are registered +** to the same collation name (using different eTextRep values) then all +** must give an equivalent answer when invoked with equivalent strings. +** The collating function must obey the following properties for all +** strings A, B, and C: +** +**
    +**
  1. If A==B then B==A. +**
  2. If A==B and B==C then A==C. +**
  3. If A<B THEN B>A. +**
  4. If A<B and B<C then A<C. +**
+** +** If a collating function fails any of the above constraints and that +** collating function is registered and used, then the behavior of SQLite +** is undefined. +** +** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** with the addition that the xDestroy callback is invoked on pArg when +** the collating function is deleted. +** ^Collating functions are deleted when they are overridden by later +** calls to the collation creation functions or when the +** [database connection] is closed using [sqlite3_close()]. +** +** ^The xDestroy callback is not called if the +** sqlite3_create_collation_v2() function fails. Applications that invoke +** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should +** check the return code and dispose of the application data pointer +** themselves rather than expecting SQLite to deal with it for them. +** This is different from every other SQLite interface. The inconsistency +** is unfortunate but cannot be changed without breaking backwards +** compatibility. +** +** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. +*/ +SQLITE_API int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); +SQLITE_API int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +SQLITE_API int sqlite3_create_collation16( + sqlite3*, + const void *zName, + int eTextRep, + void *pArg, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks +** +** ^To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** [database connection] to be invoked whenever an undefined collation +** sequence is required. +** +** ^If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, +** the names are passed as UTF-16 in machine native byte order. +** ^A call to either function replaces the existing collation-needed callback. +** +** ^(When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). The second argument is the database +** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE], indicating the most desirable form of the collation +** sequence function required. The fourth parameter is the name of the +** required collation sequence.)^ +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +SQLITE_API int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +SQLITE_API int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +#ifdef SQLITE_HAS_CODEC +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +SQLITE_API int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** Specify the activation key for a SEE database. Unless +** activated, none of the SEE routines will work. +*/ +SQLITE_API void sqlite3_activate_see( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +#ifdef SQLITE_ENABLE_CEROD +/* +** Specify the activation key for a CEROD database. Unless +** activated, none of the CEROD routines will work. +*/ +SQLITE_API void sqlite3_activate_cerod( + const char *zPassPhrase /* Activation phrase */ +); +#endif + +/* +** CAPI3REF: Suspend Execution For A Short Time +** +** The sqlite3_sleep() function causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** ^SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. If the xSleep() method +** of the default VFS is not implemented correctly, or not implemented at +** all, then the behavior of sqlite3_sleep() may deviate from the description +** in the previous paragraphs. +*/ +SQLITE_API int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files +** +** ^(If this global variable is made to point to a string which is +** the name of a folder (a.k.a. directory), then all temporary files +** created by SQLite when using a built-in [sqlite3_vfs | VFS] +** will be placed in that directory.)^ ^If this variable +** is a NULL pointer, then SQLite performs a search for an appropriate +** temporary file directory. +** +** It is not safe to read or modify this variable in more than one +** thread at a time. It is not safe to read or modify this variable +** if a [database connection] is being used at the same time in a separate +** thread. +** It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been called and that this variable remain unchanged +** thereafter. +** +** ^The [temp_store_directory pragma] may modify this variable and cause +** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, +** the [temp_store_directory pragma] always assumes that any string +** that this variable points to is held in memory obtained from +** [sqlite3_malloc] and the pragma may attempt to free that memory +** using [sqlite3_free]. +** Hence, if this variable is modified directly, either it should be +** made NULL or made to point to memory obtained from [sqlite3_malloc] +** or else the use of the [temp_store_directory pragma] should be avoided. +*/ +SQLITE_API char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test For Auto-Commit Mode +** KEYWORDS: {autocommit mode} +** +** ^The sqlite3_get_autocommit() interface returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. ^Autocommit mode is on by default. +** ^Autocommit mode is disabled by a [BEGIN] statement. +** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** +** If certain kinds of errors occur on a statement within a multi-statement +** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. The only way to +** find out whether SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. +*/ +SQLITE_API int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement +** +** ^The sqlite3_db_handle interface returns the [database connection] handle +** to which a [prepared statement] belongs. ^The [database connection] +** returned by sqlite3_db_handle is the same [database connection] +** that was the first argument +** to the [sqlite3_prepare_v2()] call (or its variants) that was used to +** create the statement in the first place. +*/ +SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + +/* +** CAPI3REF: Find the next prepared statement +** +** ^This interface returns a pointer to the next [prepared statement] after +** pStmt associated with the [database connection] pDb. ^If pStmt is NULL +** then this interface returns a pointer to the first prepared statement +** associated with the database connection pDb. ^If no prepared statement +** satisfies the conditions of this routine, it returns NULL. +** +** The [database connection] pointer D in a call to +** [sqlite3_next_stmt(D,S)] must refer to an open database +** connection and in particular must not be a NULL pointer. +*/ +SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks +** +** ^The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is [COMMIT | committed]. +** ^Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** ^The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. +** ^Any callback set by a previous call to sqlite3_rollback_hook() +** for the same database connection is overridden. +** ^The pArg argument is passed through to the callback. +** ^If the callback on a commit hook function returns non-zero, +** then the commit is converted into a rollback. +** +** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions +** return the P argument from the previous call of the same function +** on the same [database connection] D, or NULL for +** the first call for each function on D. +** +** The callback implementation must not do anything that will modify +** the database connection that invoked the callback. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the commit +** or rollback hook in the first place. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^Registering a NULL function disables the callback. +** +** ^When the commit hook callback routine returns zero, the [COMMIT] +** operation is allowed to continue normally. ^If the commit hook +** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. +** ^The rollback hook is invoked on a rollback that results from a commit +** hook returning non-zero, just as it would be with any other rollback. +** +** ^For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** ^The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** +** See also the [sqlite3_update_hook()] interface. +*/ +SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks +** +** ^The sqlite3_update_hook() interface registers a callback function +** with the [database connection] identified by the first argument +** to be invoked whenever a row is updated, inserted or deleted. +** ^Any callback set by a previous call to this function +** for the same database connection is overridden. +** +** ^The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** ^The first argument to the callback is a copy of the third argument +** to sqlite3_update_hook(). +** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], +** or [SQLITE_UPDATE], depending on the operation that caused the callback +** to be invoked. +** ^The third and fourth arguments to the callback contain pointers to the +** database and table name containing the affected row. +** ^The final callback parameter is the [rowid] of the row. +** ^In the case of an update, this is the [rowid] after the update takes place. +** +** ^(The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence).)^ +** +** ^In the current implementation, the update hook +** is not invoked when duplication rows are deleted because of an +** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook +** invoked when rows are deleted using the [truncate optimization]. +** The exceptions defined in this paragraph might change in a future +** release of SQLite. +** +** The update hook implementation must not do anything that will modify +** the database connection that invoked the update hook. Any actions +** to modify the database connection must be deferred until after the +** completion of the [sqlite3_step()] call that triggered the update hook. +** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their +** database connections for the meaning of "modify" in this paragraph. +** +** ^The sqlite3_update_hook(D,C,P) function +** returns the P argument from the previous call +** on the same [database connection] D, or NULL for +** the first call on D. +** +** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] +** interfaces. +*/ +SQLITE_API void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache +** KEYWORDS: {shared cache} +** +** ^(This routine enables or disables the sharing of the database cache +** and schema data structures between [database connection | connections] +** to the same database. Sharing is enabled if the argument is true +** and disabled if the argument is false.)^ +** +** ^Cache sharing is enabled and disabled for an entire process. +** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, +** sharing was enabled or disabled for each thread separately. +** +** ^(The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** Existing database connections continue use the sharing mode +** that was in effect at the time they were opened.)^ +** +** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled +** successfully. An [error code] is returned otherwise.)^ +** +** ^Shared cache is disabled by default. But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +** +** See Also: [SQLite Shared-Cache Mode] +*/ +SQLITE_API int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory +** +** ^The sqlite3_release_memory() interface attempts to free N bytes +** of heap memory by deallocating non-essential memory allocations +** held by the database library. Memory used to cache database +** pages to improve performance is an example of non-essential memory. +** ^sqlite3_release_memory() returns the number of bytes actually freed, +** which might be more or less than the amount requested. +** ^The sqlite3_release_memory() routine is a no-op returning zero +** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +*/ +SQLITE_API int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size +** +** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the +** soft limit on the amount of heap memory that may be allocated by SQLite. +** ^SQLite strives to keep heap memory utilization below the soft heap +** limit by reducing the number of pages held in the page cache +** as heap memory usages approaches the limit. +** ^The soft heap limit is "soft" because even though SQLite strives to stay +** below the limit, it will exceed the limit rather than generate +** an [SQLITE_NOMEM] error. In other words, the soft heap limit +** is advisory only. +** +** ^The return value from sqlite3_soft_heap_limit64() is the size of +** the soft heap limit prior to the call. ^If the argument N is negative +** then no change is made to the soft heap limit. Hence, the current +** size of the soft heap limit can be determined by invoking +** sqlite3_soft_heap_limit64() with a negative argument. +** +** ^If the argument N is zero then the soft heap limit is disabled. +** +** ^(The soft heap limit is not enforced in the current implementation +** if one or more of following conditions are true: +** +**
    +**
  • The soft heap limit is set to zero. +**
  • Memory accounting is disabled using a combination of the +** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and +** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. +**
  • An alternative page cache implementation is specifed using +** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...). +**
  • The page cache allocates from its own memory pool supplied +** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than +** from the heap. +**
)^ +** +** Beginning with SQLite version 3.7.3, the soft heap limit is enforced +** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] +** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], +** the soft heap limit is enforced on every memory allocation. Without +** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced +** when memory is allocated by the page cache. Testing suggests that because +** the page cache is the predominate memory user in SQLite, most +** applications will achieve adequate soft heap limit enforcement without +** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. +** +** The circumstances under which SQLite will enforce the soft heap limit may +** changes in future releases of SQLite. +*/ +SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); + +/* +** CAPI3REF: Deprecated Soft Heap Limit Interface +** DEPRECATED +** +** This is a deprecated version of the [sqlite3_soft_heap_limit64()] +** interface. This routine is provided for historical compatibility +** only. All new applications should use the +** [sqlite3_soft_heap_limit64()] interface rather than this one. +*/ +SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); + + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table +** +** ^This routine returns metadata about a specific column of a specific +** database table accessible using the [database connection] handle +** passed as the first function argument. +** +** ^The column is identified by the second, third and fourth parameters to +** this function. ^The second parameter is either the name of the database +** (i.e. "main", "temp", or an attached database) containing the specified +** table or NULL. ^If it is NULL, then all attached databases are searched +** for the table using the same algorithm used by the database engine to +** resolve unqualified table references. +** +** ^The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** ^Metadata is returned by writing to the memory locations passed as the 5th +** and subsequent parameters to this function. ^Any of these arguments may be +** NULL, in which case the corresponding element of metadata is omitted. +** +** ^(
+** +**
Parameter Output
Type
Description +** +**
5th const char* Data type +**
6th const char* Name of default collation sequence +**
7th int True if column has a NOT NULL constraint +**
8th int True if column is part of the PRIMARY KEY +**
9th int True if column is [AUTOINCREMENT] +**
+**
)^ +** +** ^The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any SQLite API function. +** +** ^If the specified table is actually a view, an [error code] is returned. +** +** ^If the specified column is "rowid", "oid" or "_rowid_" and an +** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. ^(If there is no +** explicitly declared [INTEGER PRIMARY KEY] column, then the output +** parameters are set as follows: +** +**
+**     data type: "INTEGER"
+**     collation sequence: "BINARY"
+**     not null: 0
+**     primary key: 1
+**     auto increment: 0
+** 
)^ +** +** ^(This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an [error code] is returned and an error message left +** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ +** +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +*/ +SQLITE_API int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension +** +** ^This interface loads an SQLite extension library from the named file. +** +** ^The sqlite3_load_extension() interface attempts to load an +** SQLite extension library contained in the file zFile. +** +** ^The entry point is zProc. +** ^zProc may be 0, in which case the name of the entry point +** defaults to "sqlite3_extension_init". +** ^The sqlite3_load_extension() interface returns +** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** ^If an error occurs and pzErrMsg is not 0, then the +** [sqlite3_load_extension()] interface shall attempt to +** fill *pzErrMsg with error message text stored in memory +** obtained from [sqlite3_malloc()]. The calling function +** should free this memory by calling [sqlite3_free()]. +** +** ^Extension loading must be enabled using +** [sqlite3_enable_load_extension()] prior to calling this API, +** otherwise an error will be returned. +** +** See also the [load_extension() SQL function]. +*/ +SQLITE_API int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading +** +** ^So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following API +** is provided to turn the [sqlite3_load_extension()] mechanism on and off. +** +** ^Extension loading is off by default. See ticket #1863. +** ^Call the sqlite3_enable_load_extension() routine with onoff==1 +** to turn extension loading on and call it with onoff==0 to turn +** it back off again. +*/ +SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Automatically Load Statically Linked Extensions +** +** ^This interface causes the xEntryPoint() function to be invoked for +** each new [database connection] that is created. The idea here is that +** xEntryPoint() is the entry point for a statically linked SQLite extension +** that is to be automatically loaded into all new database connections. +** +** ^(Even though the function prototype shows that xEntryPoint() takes +** no arguments and returns void, SQLite invokes xEntryPoint() with three +** arguments and expects and integer result as if the signature of the +** entry point where as follows: +** +**
+**    int xEntryPoint(
+**      sqlite3 *db,
+**      const char **pzErrMsg,
+**      const struct sqlite3_api_routines *pThunk
+**    );
+** 
)^ +** +** If the xEntryPoint routine encounters an error, it should make *pzErrMsg +** point to an appropriate error message (obtained from [sqlite3_mprintf()]) +** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg +** is NULL before calling the xEntryPoint(). ^SQLite will invoke +** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any +** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], +** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. +** +** ^Calling sqlite3_auto_extension(X) with an entry point X that is already +** on the list of automatic extensions is a harmless no-op. ^No entry point +** will be called more than once for each database connection that is opened. +** +** See also: [sqlite3_reset_auto_extension()]. +*/ +SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); + +/* +** CAPI3REF: Reset Automatic Extension Loading +** +** ^This interface disables all automatic extensions previously +** registered using [sqlite3_auto_extension()]. +*/ +SQLITE_API void sqlite3_reset_auto_extension(void); + +/* +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** CAPI3REF: Virtual Table Object +** KEYWORDS: sqlite3_module {virtual table module} +** +** This structure, sometimes called a a "virtual table module", +** defines the implementation of a [virtual tables]. +** This structure consists mostly of methods for the module. +** +** ^A virtual table module is created by filling in a persistent +** instance of this structure and passing a pointer to that instance +** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. +** ^The registration remains valid until it is replaced by a different +** module or until the [database connection] closes. The content +** of this structure must not change while it is registered with +** any database connection. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** CAPI3REF: Virtual Table Indexing Information +** KEYWORDS: sqlite3_index_info +** +** The sqlite3_index_info structure and its substructures is used as part +** of the [virtual table] interface to +** pass information into and receive the reply from the [xBestIndex] +** method of a [virtual table module]. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** ^(The aConstraint[] array records WHERE clause constraints of the form: +** +**
column OP expr
+** +** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is +** stored in aConstraint[].op using one of the +** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ +** ^(The index of the column is stored in +** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot.)^ +** +** ^The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** ^The aConstraint[] array only reports WHERE clause terms that are +** relevant to the particular virtual table being queried. +** +** ^Information about the ORDER BY clause is stored in aOrderBy[]. +** ^Each term of aOrderBy records a column of the ORDER BY clause. +** +** The [xBestIndex] method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. ^If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite.)^ +** +** ^The idxNum and idxPtr values are recorded and passed into the +** [xFilter] method. +** ^[sqlite3_free()] is used to free idxPtr if and only if +** needToFreeIdxPtr is true. +** +** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** ^The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; + +/* +** CAPI3REF: Virtual Table Constraint Operator Codes +** +** These macros defined the allowed values for the +** [sqlite3_index_info].aConstraint[].op field. Each value represents +** an operator that is part of a constraint term in the wHERE clause of +** a query that uses a [virtual table]. +*/ +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** CAPI3REF: Register A Virtual Table Implementation +** +** ^These routines are used to register a new [virtual table module] name. +** ^Module names must be registered before +** creating a new [virtual table] using the module and before using a +** preexisting [virtual table] for the module. +** +** ^The module name is registered on the [database connection] specified +** by the first parameter. ^The name of the module is given by the +** second parameter. ^The third parameter is a pointer to +** the implementation of the [virtual table module]. ^The fourth +** parameter is an arbitrary client data pointer that is passed through +** into the [xCreate] and [xConnect] methods of the virtual table module +** when a new virtual table is be being created or reinitialized. +** +** ^The sqlite3_create_module_v2() interface has a fifth parameter which +** is a pointer to a destructor for the pClientData. ^SQLite will +** invoke the destructor function (if it is not NULL) when SQLite +** no longer needs the pClientData pointer. ^The destructor will also +** be invoked if the call to sqlite3_create_module_v2() fails. +** ^The sqlite3_create_module() +** interface is equivalent to sqlite3_create_module_v2() with a NULL +** destructor. +*/ +SQLITE_API int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData /* Client data for xCreate/xConnect */ +); +SQLITE_API int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *p, /* Methods for the module */ + void *pClientData, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** CAPI3REF: Virtual Table Instance Object +** KEYWORDS: sqlite3_vtab +** +** Every [virtual table module] implementation uses a subclass +** of this object to describe a particular instance +** of the [virtual table]. Each subclass will +** be tailored to the specific needs of the module implementation. +** The purpose of this superclass is to define certain fields that are +** common to all module implementations. +** +** ^Virtual tables methods can set an error message by assigning a +** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should +** take care that any prior string is freed by a call to [sqlite3_free()] +** prior to assigning a new string to zErrMsg. ^After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* NO LONGER USED */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Virtual Table Cursor Object +** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} +** +** Every [virtual table module] implementation uses a subclass of the +** following structure to describe cursors that point into the +** [virtual table] and are used +** to loop through the virtual table. Cursors are created using the +** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed +** by the [sqlite3_module.xClose | xClose] method. Cursors are used +** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods +** of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** CAPI3REF: Declare The Schema Of A Virtual Table +** +** ^The [xCreate] and [xConnect] methods of a +** [virtual table module] call this interface +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); + +/* +** CAPI3REF: Overload A Function For A Virtual Table +** +** ^(Virtual tables can provide alternative implementations of functions +** using the [xFindFunction] method of the [virtual table module]. +** But global versions of those functions +** must exist in order to be overloaded.)^ +** +** ^(This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created.)^ ^The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a placeholder function that can be overloaded +** by a [virtual table]. +*/ +SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB +** KEYWORDS: {BLOB handle} {BLOB handles} +** +** An instance of this object represents an open BLOB on which +** [sqlite3_blob_open | incremental BLOB I/O] can be performed. +** ^Objects of this type are created by [sqlite3_blob_open()] +** and destroyed by [sqlite3_blob_close()]. +** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the BLOB. +** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O +** +** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located +** in row iRow, column zColumn, table zTable in database zDb; +** in other words, the same BLOB that would be selected by: +** +**
+**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
+** 
)^ +** +** ^If the flags parameter is non-zero, then the BLOB is opened for read +** and write access. ^If it is zero, the BLOB is opened for read access. +** ^It is not possible to open a column that is part of an index or primary +** key for writing. ^If [foreign key constraints] are enabled, it is +** not possible to open a column that is part of a [child key] for writing. +** +** ^Note that the database name is not the filename that contains +** the database but rather the symbolic name of the database that +** appears after the AS keyword when the database is connected using [ATTACH]. +** ^For the main database file, the database name is "main". +** ^For TEMP tables, the database name is "temp". +** +** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written +** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set +** to be a null pointer.)^ +** ^This function sets the [database connection] error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related +** functions. ^Note that the *ppBlob variable is always initialized in a +** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob +** regardless of the success or failure of this routine. +** +** ^(If the row that a BLOB handle points to is modified by an +** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects +** then the BLOB handle is marked as "expired". +** This is true if any column of the row is changed, even a column +** other than the one the BLOB handle is open on.)^ +** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for +** a expired BLOB handle fail with an return code of [SQLITE_ABORT]. +** ^(Changes written into a BLOB prior to the BLOB expiring are not +** rolled back by the expiration of the BLOB. Such changes will eventually +** commit if the transaction continues to completion.)^ +** +** ^Use the [sqlite3_blob_bytes()] interface to determine the size of +** the opened blob. ^The size of a blob may not be changed by this +** interface. Use the [UPDATE] SQL command to change the size of a +** blob. +** +** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces +** and the built-in [zeroblob] SQL function can be used, if desired, +** to create an empty, zero-filled blob in which to read or write using +** this interface. +** +** To avoid a resource leak, every open [BLOB handle] should eventually +** be released by a call to [sqlite3_blob_close()]. +*/ +SQLITE_API int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Move a BLOB Handle to a New Row +** +** ^This function is used to move an existing blob handle so that it points +** to a different row of the same database table. ^The new row is identified +** by the rowid value passed as the second argument. Only the row can be +** changed. ^The database, table and column on which the blob handle is open +** remain the same. Moving an existing blob handle to a new row can be +** faster than closing the existing handle and opening a new one. +** +** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - +** it must exist and there must be either a blob or text value stored in +** the nominated column.)^ ^If the new row is not present in the table, or if +** it does not contain a blob or text value, or if another error occurs, an +** SQLite error code is returned and the blob handle is considered aborted. +** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or +** [sqlite3_blob_reopen()] on an aborted blob handle immediately return +** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle +** always returns zero. +** +** ^This function sets the database handle error code and message. +*/ +SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); + +/* +** CAPI3REF: Close A BLOB Handle +** +** ^Closes an open [BLOB handle]. +** +** ^Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in [autocommit mode]. +** ^If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. +** +** ^(Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. Any errors that occur during +** closing are reported as a non-zero return value.)^ +** +** ^(The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed.)^ +** +** ^Calling this routine with a null pointer (such as would be returned +** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. +*/ +SQLITE_API int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB +** +** ^Returns the size in bytes of the BLOB accessible via the +** successfully opened [BLOB handle] in its only argument. ^The +** incremental blob I/O routines can only read or overwriting existing +** blob content; they cannot change the size of a blob. +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +*/ +SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally +** +** ^(This function is used to read data from an open [BLOB handle] into a +** caller-supplied buffer. N bytes of data are copied into buffer Z +** from the open BLOB, starting at offset iOffset.)^ +** +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is +** less than zero, [SQLITE_ERROR] is returned and no data is read. +** ^The size of the blob (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to read from an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. +** +** ^(On success, sqlite3_blob_read() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_write()]. +*/ +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally +** +** ^This function is used to write data into an open [BLOB handle] from a +** caller-supplied buffer. ^N bytes of data are copied from the buffer Z +** into the open BLOB, starting at offset iOffset. +** +** ^If the [BLOB handle] passed as the first argument was not opened for +** writing (the flags parameter to [sqlite3_blob_open()] was zero), +** this function returns [SQLITE_READONLY]. +** +** ^This function may only modify the contents of the BLOB; it is +** not possible to increase the size of a BLOB using this API. +** ^If offset iOffset is less than N bytes from the end of the BLOB, +** [SQLITE_ERROR] is returned and no data is written. ^If N is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** The size of the BLOB (and hence the maximum value of N+iOffset) +** can be determined using the [sqlite3_blob_bytes()] interface. +** +** ^An attempt to write to an expired [BLOB handle] fails with an +** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred +** before the [BLOB handle] expired are not rolled back by the +** expiration of the handle, though of course those changes might +** have been overwritten by the statement that expired the BLOB handle +** or by other independent statements. +** +** ^(On success, sqlite3_blob_write() returns SQLITE_OK. +** Otherwise, an [error code] or an [extended error code] is returned.)^ +** +** This routine only works on a [BLOB handle] which has been created +** by a prior successful call to [sqlite3_blob_open()] and which has not +** been closed by [sqlite3_blob_close()]. Passing any other pointer in +** to this routine results in undefined and probably undesirable behavior. +** +** See also: [sqlite3_blob_read()]. +*/ +SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most SQLite builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. +** ^Names are case sensitive. +** ^Names are zero-terminated UTF-8 strings. +** ^If there is no match, a NULL pointer is returned. +** ^If zVfsName is NULL then the default VFS is returned. +** +** ^New VFSes are registered with sqlite3_vfs_register(). +** ^Each new VFS becomes the default VFS if the makeDflt flag is set. +** ^The same VFS can be registered multiple times without injury. +** ^To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. If two different VFSes with the +** same name are registered, the behavior is undefined. If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. +** ^(If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary.)^ +*/ +SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. ^(The following +** implementations are available in the SQLite core: +** +**
    +**
  • SQLITE_MUTEX_OS2 +**
  • SQLITE_MUTEX_PTHREAD +**
  • SQLITE_MUTEX_W32 +**
  • SQLITE_MUTEX_NOOP +**
)^ +** +** ^The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. ^The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on OS/2, Unix, and Windows. +** +** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. In this case the +** application must supply a custom mutex implementation using the +** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function +** before calling sqlite3_initialize() or any other public sqlite3_ +** function that calls sqlite3_initialize().)^ +** +** ^The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. ^If it returns NULL +** that means that a mutex could not be allocated. ^SQLite +** will unwind its stack and return an error. ^(The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
    +**
  • SQLITE_MUTEX_FAST +**
  • SQLITE_MUTEX_RECURSIVE +**
  • SQLITE_MUTEX_STATIC_MASTER +**
  • SQLITE_MUTEX_STATIC_MEM +**
  • SQLITE_MUTEX_STATIC_MEM2 +**
  • SQLITE_MUTEX_STATIC_PRNG +**
  • SQLITE_MUTEX_STATIC_LRU +**
  • SQLITE_MUTEX_STATIC_LRU2 +**
)^ +** +** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) +** cause sqlite3_mutex_alloc() to create +** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. ^SQLite will only request a recursive mutex in +** cases where it really needs one. ^If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other +** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return +** a pointer to a static preexisting mutex. ^Six static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. ^But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. +** +** ^The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. ^SQLite is careful to deallocate every +** dynamic mutex that it allocates. The dynamic mutexes must not be in +** use when they are deallocated. Attempting to deallocate a static +** mutex results in undefined behavior. ^SQLite never deallocates +** a static mutex. +** +** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. ^If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] +** upon successful entry. ^(Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter.)^ ^(If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** SQLite will never exhibit +** such behavior in its own use of mutexes.)^ +** +** ^(Some systems (for example, Windows 95) do not support the operation +** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() +** will always return SQLITE_BUSY. The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ +** +** ^The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. ^(The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. SQLite will +** never do either.)^ +** +** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or +** sqlite3_mutex_leave() is a NULL pointer, then all three routines +** behave as no-ops. +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); +SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); +SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Methods Object +** +** An instance of this structure defines the low-level routines +** used to allocate and use mutexes. +** +** Usually, the default mutex implementations provided by SQLite are +** sufficient, however the user has the option of substituting a custom +** implementation for specialized deployments or systems for which SQLite +** does not provide a suitable implementation. In this case, the user +** creates and populates an instance of this structure to pass +** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. +** Additionally, an instance of this structure can be used as an +** output variable when querying the system for the current mutex +** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. +** +** ^The xMutexInit method defined by this structure is invoked as +** part of system initialization by the sqlite3_initialize() function. +** ^The xMutexInit routine is called by SQLite exactly once for each +** effective call to [sqlite3_initialize()]. +** +** ^The xMutexEnd method defined by this structure is invoked as +** part of system shutdown by the sqlite3_shutdown() function. The +** implementation of this method is expected to release all outstanding +** resources obtained by the mutex methods implementation, especially +** those obtained by the xMutexInit method. ^The xMutexEnd() +** interface is invoked exactly once for each call to [sqlite3_shutdown()]. +** +** ^(The remaining seven methods defined by this structure (xMutexAlloc, +** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and +** xMutexNotheld) implement the following interfaces (respectively): +** +**
    +**
  • [sqlite3_mutex_alloc()]
  • +**
  • [sqlite3_mutex_free()]
  • +**
  • [sqlite3_mutex_enter()]
  • +**
  • [sqlite3_mutex_try()]
  • +**
  • [sqlite3_mutex_leave()]
  • +**
  • [sqlite3_mutex_held()]
  • +**
  • [sqlite3_mutex_notheld()]
  • +**
)^ +** +** The only difference is that the public sqlite3_XXX functions enumerated +** above silently ignore any invocations that pass a NULL pointer instead +** of a valid mutex handle. The implementations of the methods defined +** by this structure are not required to handle this case, the results +** of passing a NULL pointer instead of a valid mutex handle are undefined +** (i.e. it is acceptable to provide an implementation that segfaults if +** it is passed a NULL pointer). +** +** The xMutexInit() method must be threadsafe. ^It must be harmless to +** invoke xMutexInit() multiple times within the same process and without +** intervening calls to xMutexEnd(). Second and subsequent calls to +** xMutexInit() must be no-ops. +** +** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] +** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory +** allocation for a static mutex. ^However xMutexAlloc() may use SQLite +** memory allocation for a fast or recursive mutex. +** +** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is +** called, but only if the prior call to xMutexInit returned SQLITE_OK. +** If xMutexInit fails in any way, it is expected to clean up after itself +** prior to returning. +*/ +typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; +struct sqlite3_mutex_methods { + int (*xMutexInit)(void); + int (*xMutexEnd)(void); + sqlite3_mutex *(*xMutexAlloc)(int); + void (*xMutexFree)(sqlite3_mutex *); + void (*xMutexEnter)(sqlite3_mutex *); + int (*xMutexTry)(sqlite3_mutex *); + void (*xMutexLeave)(sqlite3_mutex *); + int (*xMutexHeld)(sqlite3_mutex *); + int (*xMutexNotheld)(sqlite3_mutex *); +}; + +/* +** CAPI3REF: Mutex Verification Routines +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. ^The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. ^The SQLite core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. ^External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** ^These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. +** +** ^The implementation is not required to provided versions of these +** routines that actually work. If the implementation does not provide working +** versions of these routines, it should at least provide stubs that always +** return true so that one does not get spurious assertion failures. +** +** ^If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. ^The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +#ifndef NDEBUG +SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); +SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); +#endif + +/* +** CAPI3REF: Mutex Types +** +** The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. +** +** The set of static mutexes may change from one SQLite release to the +** next. Applications that override the built-in mutex logic must be +** prepared to accommodate additional static mutexes. +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ +#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ +#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ + +/* +** CAPI3REF: Retrieve the mutex for a database connection +** +** ^This interface returns a pointer the [sqlite3_mutex] object that +** serializes access to the [database connection] given in the argument +** when the [threading mode] is Serialized. +** ^If the [threading mode] is Single-thread or Multi-thread then this +** routine returns a NULL pointer. +*/ +SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); + +/* +** CAPI3REF: Low-Level Control Of Database Files +** +** ^The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. ^The +** name of the database is "main" for the main database or "temp" for the +** TEMP database, or the name that appears after the AS keyword for +** databases that are added using the [ATTACH] SQL command. +** ^A NULL pointer can be used in place of "main" to refer to the +** main database file. +** ^The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. ^The return value of the xFileControl +** method becomes the return value of this routine. +** +** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes +** a pointer to the underlying [sqlite3_file] object to be written into +** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER +** case is a short-circuit path which does not actually invoke the +** underlying sqlite3_io_methods.xFileControl method. +** +** ^If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. ^This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. The underlying xFileControl method might +** also return SQLITE_ERROR. There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** CAPI3REF: Testing Interface +** +** ^The sqlite3_test_control() interface is used to read out internal +** state of SQLite and to inject faults into SQLite for testing +** purposes. ^The first parameter is an operation code that determines +** the number, meaning, and operation of all subsequent parameters. +** +** This interface is not for use by applications. It exists solely +** for verifying the correct operation of the SQLite library. Depending +** on how the SQLite library is compiled, this interface might not exist. +** +** The details of the operation codes, their meanings, the parameters +** they take, and what they do are all subject to change without notice. +** Unlike most of the SQLite API, this function is not guaranteed to +** operate consistently from one release to the next. +*/ +SQLITE_API int sqlite3_test_control(int op, ...); + +/* +** CAPI3REF: Testing Interface Operation Codes +** +** These constants are the valid operation code parameters used +** as the first argument to [sqlite3_test_control()]. +** +** These parameters and their meanings are subject to change +** without notice. These values are for testing purposes only. +** Applications should not use any of these parameters or the +** [sqlite3_test_control()] interface. +*/ +#define SQLITE_TESTCTRL_FIRST 5 +#define SQLITE_TESTCTRL_PRNG_SAVE 5 +#define SQLITE_TESTCTRL_PRNG_RESTORE 6 +#define SQLITE_TESTCTRL_PRNG_RESET 7 +#define SQLITE_TESTCTRL_BITVEC_TEST 8 +#define SQLITE_TESTCTRL_FAULT_INSTALL 9 +#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 +#define SQLITE_TESTCTRL_PENDING_BYTE 11 +#define SQLITE_TESTCTRL_ASSERT 12 +#define SQLITE_TESTCTRL_ALWAYS 13 +#define SQLITE_TESTCTRL_RESERVE 14 +#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 +#define SQLITE_TESTCTRL_ISKEYWORD 16 +#define SQLITE_TESTCTRL_PGHDRSZ 17 +#define SQLITE_TESTCTRL_SCRATCHMALLOC 18 +#define SQLITE_TESTCTRL_LAST 18 + +/* +** CAPI3REF: SQLite Runtime Status +** +** ^This interface is used to retrieve runtime status information +** about the performance of SQLite, and optionally to reset various +** highwater marks. ^The first argument is an integer code for +** the specific parameter to measure. ^(Recognized integer codes +** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^ +** ^The current value of the parameter is returned into *pCurrent. +** ^The highest recorded value is returned in *pHighwater. ^If the +** resetFlag is true, then the highest record value is reset after +** *pHighwater is written. ^(Some parameters do not record the highest +** value. For those parameters +** nothing is written into *pHighwater and the resetFlag is ignored.)^ +** ^(Other parameters record only the highwater mark and not the current +** value. For these latter parameters nothing is written into *pCurrent.)^ +** +** ^The sqlite3_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** This routine is threadsafe but is not atomic. This routine can be +** called while other threads are running the same or different SQLite +** interfaces. However the values returned in *pCurrent and +** *pHighwater reflect the status of SQLite at different points in time +** and it is possible that another thread might change the parameter +** in between the times when *pCurrent and *pHighwater are written. +** +** See also: [sqlite3_db_status()] +*/ +SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); + + +/* +** CAPI3REF: Status Parameters +** +** These integer constants designate various run-time status parameters +** that can be returned by [sqlite3_status()]. +** +**
+** ^(
SQLITE_STATUS_MEMORY_USED
+**
This parameter is the current amount of memory checked out +** using [sqlite3_malloc()], either directly or indirectly. The +** figure includes calls made to [sqlite3_malloc()] by the application +** and internal memory usage by the SQLite library. Scratch memory +** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache +** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in +** this parameter. The amount returned is the sum of the allocation +** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ +** +** ^(
SQLITE_STATUS_MALLOC_SIZE
+**
This parameter records the largest memory allocation request +** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their +** internal equivalents). Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** ^(
SQLITE_STATUS_MALLOC_COUNT
+**
This parameter records the number of separate memory allocations +** currently checked out.
)^ +** +** ^(
SQLITE_STATUS_PAGECACHE_USED
+**
This parameter returns the number of pages used out of the +** [pagecache memory allocator] that was configured using +** [SQLITE_CONFIG_PAGECACHE]. The +** value returned is in pages, not in bytes.
)^ +** +** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
+**
This parameter returns the number of bytes of page cache +** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] +** buffer and where forced to overflow to [sqlite3_malloc()]. The +** returned value includes allocations that overflowed because they +** where too large (they were larger than the "sz" parameter to +** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because +** no space was left in the page cache.
)^ +** +** ^(
SQLITE_STATUS_PAGECACHE_SIZE
+**
This parameter records the largest memory allocation request +** handed to [pagecache memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** ^(
SQLITE_STATUS_SCRATCH_USED
+**
This parameter returns the number of allocations used out of the +** [scratch memory allocator] configured using +** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not +** in bytes. Since a single thread may only have one scratch allocation +** outstanding at time, this parameter also reports the number of threads +** using scratch memory at the same time.
)^ +** +** ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
+**
This parameter returns the number of bytes of scratch memory +** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] +** buffer and where forced to overflow to [sqlite3_malloc()]. The values +** returned include overflows because the requested allocation was too +** larger (that is, because the requested allocation was larger than the +** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer +** slots were available. +**
)^ +** +** ^(
SQLITE_STATUS_SCRATCH_SIZE
+**
This parameter records the largest memory allocation request +** handed to [scratch memory allocator]. Only the value returned in the +** *pHighwater parameter to [sqlite3_status()] is of interest. +** The value written into the *pCurrent parameter is undefined.
)^ +** +** ^(
SQLITE_STATUS_PARSER_STACK
+**
This parameter records the deepest parser stack. It is only +** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ +**
+** +** New status parameters may be added from time to time. +*/ +#define SQLITE_STATUS_MEMORY_USED 0 +#define SQLITE_STATUS_PAGECACHE_USED 1 +#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 +#define SQLITE_STATUS_SCRATCH_USED 3 +#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 +#define SQLITE_STATUS_MALLOC_SIZE 5 +#define SQLITE_STATUS_PARSER_STACK 6 +#define SQLITE_STATUS_PAGECACHE_SIZE 7 +#define SQLITE_STATUS_SCRATCH_SIZE 8 +#define SQLITE_STATUS_MALLOC_COUNT 9 + +/* +** CAPI3REF: Database Connection Status +** +** ^This interface is used to retrieve runtime status information +** about a single [database connection]. ^The first argument is the +** database connection object to be interrogated. ^The second argument +** is an integer constant, taken from the set of +** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that +** determines the parameter to interrogate. The set of +** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely +** to grow in future releases of SQLite. +** +** ^The current value of the requested parameter is written into *pCur +** and the highest instantaneous value is written into *pHiwtr. ^If +** the resetFlg is true, then the highest instantaneous value is +** reset back down to the current value. +** +** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a +** non-zero [error code] on failure. +** +** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. +*/ +SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); + +/* +** CAPI3REF: Status Parameters for database connections +** +** These constants are the available integer "verbs" that can be passed as +** the second argument to the [sqlite3_db_status()] interface. +** +** New verbs may be added in future releases of SQLite. Existing verbs +** might be discontinued. Applications should check the return code from +** [sqlite3_db_status()] to make sure that the call worked. +** The [sqlite3_db_status()] interface will return a non-zero error code +** if a discontinued or unsupported verb is invoked. +** +**
+** ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
+**
This parameter returns the number of lookaside memory slots currently +** checked out.
)^ +** +** ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
+**
This parameter returns the number malloc attempts that were +** satisfied using lookaside memory. Only the high-water value is meaningful; +** the current value is always zero. +** checked out.
)^ +** +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to the amount of +** memory requested being larger than the lookaside slot size. +** Only the high-water value is meaningful; +** the current value is always zero. +** checked out.
)^ +** +** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
+**
This parameter returns the number malloc attempts that might have +** been satisfied using lookaside memory but failed due to all lookaside +** memory already being in use. +** Only the high-water value is meaningful; +** the current value is always zero. +** checked out.
)^ +** +** ^(
SQLITE_DBSTATUS_CACHE_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used by all pager caches associated with the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** +** ^(
SQLITE_DBSTATUS_SCHEMA_USED
+**
This parameter returns the approximate number of of bytes of heap +** memory used to store the schema for all databases associated +** with the connection - main, temp, and any [ATTACH]-ed databases.)^ +** ^The full amount of memory used by the schemas is reported, even if the +** schema memory is shared with other database connections due to +** [shared cache mode] being enabled. +** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** +** ^(
SQLITE_DBSTATUS_STMT_USED
+**
This parameter returns the approximate number of of bytes of heap +** and lookaside memory used by all prepared statements associated with +** the database connection.)^ +** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. +**
+**
+*/ +#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 +#define SQLITE_DBSTATUS_CACHE_USED 1 +#define SQLITE_DBSTATUS_SCHEMA_USED 2 +#define SQLITE_DBSTATUS_STMT_USED 3 +#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 +#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 +#define SQLITE_DBSTATUS_MAX 6 /* Largest defined DBSTATUS */ + + +/* +** CAPI3REF: Prepared Statement Status +** +** ^(Each prepared statement maintains various +** [SQLITE_STMTSTATUS_SORT | counters] that measure the number +** of times it has performed specific operations.)^ These counters can +** be used to monitor the performance characteristics of the prepared +** statements. For example, if the number of table steps greatly exceeds +** the number of table searches or result rows, that would tend to indicate +** that the prepared statement is using a full table scan rather than +** an index. +** +** ^(This interface is used to retrieve and reset counter values from +** a [prepared statement]. The first argument is the prepared statement +** object to be interrogated. The second argument +** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter] +** to be interrogated.)^ +** ^The current value of the requested counter is returned. +** ^If the resetFlg is true, then the counter is reset to zero after this +** interface call returns. +** +** See also: [sqlite3_status()] and [sqlite3_db_status()]. +*/ +SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); + +/* +** CAPI3REF: Status Parameters for prepared statements +** +** These preprocessor macros define integer codes that name counter +** values associated with the [sqlite3_stmt_status()] interface. +** The meanings of the various counters are as follows: +** +**
+**
SQLITE_STMTSTATUS_FULLSCAN_STEP
+**
^This is the number of times that SQLite has stepped forward in +** a table as part of a full table scan. Large numbers for this counter +** may indicate opportunities for performance improvement through +** careful use of indices.
+** +**
SQLITE_STMTSTATUS_SORT
+**
^This is the number of sort operations that have occurred. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance through careful use of indices.
+** +**
SQLITE_STMTSTATUS_AUTOINDEX
+**
^This is the number of rows inserted into transient indices that +** were created automatically in order to help joins run faster. +** A non-zero value in this counter may indicate an opportunity to +** improvement performance by adding permanent indices that do not +** need to be reinitialized each time the statement is run.
+** +**
+*/ +#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 +#define SQLITE_STMTSTATUS_SORT 2 +#define SQLITE_STMTSTATUS_AUTOINDEX 3 + +/* +** CAPI3REF: Custom Page Cache Object +** +** The sqlite3_pcache type is opaque. It is implemented by +** the pluggable module. The SQLite core has no knowledge of +** its size or internal structure and never deals with the +** sqlite3_pcache object except by holding and passing pointers +** to the object. +** +** See [sqlite3_pcache_methods] for additional information. +*/ +typedef struct sqlite3_pcache sqlite3_pcache; + +/* +** CAPI3REF: Application Defined Page Cache. +** KEYWORDS: {page cache} +** +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can +** register an alternative page cache implementation by passing in an +** instance of the sqlite3_pcache_methods structure.)^ +** In many applications, most of the heap memory allocated by +** SQLite is used for the page cache. +** By implementing a +** custom page cache using this API, an application can better control +** the amount of memory consumed by SQLite, the way in which +** that memory is allocated and released, and the policies used to +** determine exactly which parts of a database file are cached and for +** how long. +** +** The alternative page cache mechanism is an +** extreme measure that is only needed by the most demanding applications. +** The built-in page cache is recommended for most uses. +** +** ^(The contents of the sqlite3_pcache_methods structure are copied to an +** internal buffer by SQLite within the call to [sqlite3_config]. Hence +** the application may discard the parameter after the call to +** [sqlite3_config()] returns.)^ +** +** ^(The xInit() method is called once for each effective +** call to [sqlite3_initialize()])^ +** (usually only once during the lifetime of the process). ^(The xInit() +** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^ +** The intent of the xInit() method is to set up global data structures +** required by the custom page cache implementation. +** ^(If the xInit() method is NULL, then the +** built-in default page cache is used instead of the application defined +** page cache.)^ +** +** ^The xShutdown() method is called by [sqlite3_shutdown()]. +** It can be used to clean up +** any outstanding resources before process shutdown, if required. +** ^The xShutdown() method may be NULL. +** +** ^SQLite automatically serializes calls to the xInit method, +** so the xInit method need not be threadsafe. ^The +** xShutdown method is only called from [sqlite3_shutdown()] so it does +** not need to be threadsafe either. All other methods must be threadsafe +** in multithreaded applications. +** +** ^SQLite will never invoke xInit() more than once without an intervening +** call to xShutdown(). +** +** ^SQLite invokes the xCreate() method to construct a new cache instance. +** SQLite will typically create one cache instance for each open database file, +** though this is not guaranteed. ^The +** first parameter, szPage, is the size in bytes of the pages that must +** be allocated by the cache. ^szPage will not be a power of two. ^szPage +** will the page size of the database file that is to be cached plus an +** increment (here called "R") of less than 250. SQLite will use the +** extra R bytes on each page to store metadata about the underlying +** database page on disk. The value of R depends +** on the SQLite version, the target platform, and how SQLite was compiled. +** ^(R is constant for a particular build of SQLite. Except, there are two +** distinct values of R when SQLite is compiled with the proprietary +** ZIPVFS extension.)^ ^The second argument to +** xCreate(), bPurgeable, is true if the cache being created will +** be used to cache database pages of a file stored on disk, or +** false if it is used for an in-memory database. The cache implementation +** does not have to do anything special based with the value of bPurgeable; +** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will +** never invoke xUnpin() except to deliberately delete a page. +** ^In other words, calls to xUnpin() on a cache with bPurgeable set to +** false will always have the "discard" flag set to true. +** ^Hence, a cache created with bPurgeable false will +** never contain any unpinned pages. +** +** ^(The xCachesize() method may be called at any time by SQLite to set the +** suggested maximum cache-size (number of pages stored by) the cache +** instance passed as the first argument. This is the value configured using +** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable +** parameter, the implementation is not required to do anything with this +** value; it is advisory only. +** +** The xPagecount() method must return the number of pages currently +** stored in the cache, both pinned and unpinned. +** +** The xFetch() method locates a page in the cache and returns a pointer to +** the page, or a NULL pointer. +** A "page", in this context, means a buffer of szPage bytes aligned at an +** 8-byte boundary. The page to be fetched is determined by the key. ^The +** mimimum key value is 1. After it has been retrieved using xFetch, the page +** is considered to be "pinned". +** +** If the requested page is already in the page cache, then the page cache +** implementation must return a pointer to the page buffer with its content +** intact. If the requested page is not already in the cache, then the +** cache implementation should use the value of the createFlag +** parameter to help it determined what action to take: +** +** +**
createFlag Behaviour when page is not already in cache +**
0 Do not allocate a new page. Return NULL. +**
1 Allocate a new page if it easy and convenient to do so. +** Otherwise return NULL. +**
2 Make every effort to allocate a new page. Only return +** NULL if allocating a new page is effectively impossible. +**
+** +** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite +** will only use a createFlag of 2 after a prior call with a createFlag of 1 +** failed.)^ In between the to xFetch() calls, SQLite may +** attempt to unpin one or more cache pages by spilling the content of +** pinned pages to disk and synching the operating system disk cache. +** +** ^xUnpin() is called by SQLite with a pointer to a currently pinned page +** as its second argument. If the third parameter, discard, is non-zero, +** then the page must be evicted from the cache. +** ^If the discard parameter is +** zero, then the page may be discarded or retained at the discretion of +** page cache implementation. ^The page cache implementation +** may choose to evict unpinned pages at any time. +** +** The cache must not perform any reference counting. A single +** call to xUnpin() unpins the page regardless of the number of prior calls +** to xFetch(). +** +** The xRekey() method is used to change the key value associated with the +** page passed as the second argument. If the cache +** previously contains an entry associated with newKey, it must be +** discarded. ^Any prior cache entry associated with newKey is guaranteed not +** to be pinned. +** +** When SQLite calls the xTruncate() method, the cache must discard all +** existing cache entries with page numbers (keys) greater than or equal +** to the value of the iLimit parameter passed to xTruncate(). If any +** of these pages are pinned, they are implicitly unpinned, meaning that +** they can be safely discarded. +** +** ^The xDestroy() method is used to delete a cache allocated by xCreate(). +** All resources associated with the specified cache should be freed. ^After +** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] +** handle invalid, and will not use it with any other sqlite3_pcache_methods +** functions. +*/ +typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; +struct sqlite3_pcache_methods { + void *pArg; + int (*xInit)(void*); + void (*xShutdown)(void*); + sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); + void (*xCachesize)(sqlite3_pcache*, int nCachesize); + int (*xPagecount)(sqlite3_pcache*); + void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); + void (*xUnpin)(sqlite3_pcache*, void*, int discard); + void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); + void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); + void (*xDestroy)(sqlite3_pcache*); +}; + +/* +** CAPI3REF: Online Backup Object +** +** The sqlite3_backup object records state information about an ongoing +** online backup operation. ^The sqlite3_backup object is created by +** a call to [sqlite3_backup_init()] and is destroyed by a call to +** [sqlite3_backup_finish()]. +** +** See Also: [Using the SQLite Online Backup API] +*/ +typedef struct sqlite3_backup sqlite3_backup; + +/* +** CAPI3REF: Online Backup API. +** +** The backup API copies the content of one database into another. +** It is useful either for creating backups of databases or +** for copying in-memory databases to or from persistent files. +** +** See Also: [Using the SQLite Online Backup API] +** +** ^SQLite holds a write transaction open on the destination database file +** for the duration of the backup operation. +** ^The source database is read-locked only while it is being read; +** it is not locked continuously for the entire backup operation. +** ^Thus, the backup may be performed on a live source database without +** preventing other database connections from +** reading or writing to the source database while the backup is underway. +** +** ^(To perform a backup operation: +**
    +**
  1. sqlite3_backup_init() is called once to initialize the +** backup, +**
  2. sqlite3_backup_step() is called one or more times to transfer +** the data between the two databases, and finally +**
  3. sqlite3_backup_finish() is called to release all resources +** associated with the backup operation. +**
)^ +** There should be exactly one call to sqlite3_backup_finish() for each +** successful call to sqlite3_backup_init(). +** +** sqlite3_backup_init() +** +** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the +** [database connection] associated with the destination database +** and the database name, respectively. +** ^The database name is "main" for the main database, "temp" for the +** temporary database, or the name specified after the AS keyword in +** an [ATTACH] statement for an attached database. +** ^The S and M arguments passed to +** sqlite3_backup_init(D,N,S,M) identify the [database connection] +** and database name of the source database, respectively. +** ^The source and destination [database connections] (parameters S and D) +** must be different or else sqlite3_backup_init(D,N,S,M) will fail with +** an error. +** +** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is +** returned and an error code and error message are stored in the +** destination [database connection] D. +** ^The error code and message for the failed call to sqlite3_backup_init() +** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or +** [sqlite3_errmsg16()] functions. +** ^A successful call to sqlite3_backup_init() returns a pointer to an +** [sqlite3_backup] object. +** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and +** sqlite3_backup_finish() functions to perform the specified backup +** operation. +** +** sqlite3_backup_step() +** +** ^Function sqlite3_backup_step(B,N) will copy up to N pages between +** the source and destination databases specified by [sqlite3_backup] object B. +** ^If N is negative, all remaining source pages are copied. +** ^If sqlite3_backup_step(B,N) successfully copies N pages and there +** are still more pages to be copied, then the function returns [SQLITE_OK]. +** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages +** from source to destination, then it returns [SQLITE_DONE]. +** ^If an error occurs while running sqlite3_backup_step(B,N), +** then an [error code] is returned. ^As well as [SQLITE_OK] and +** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], +** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. +** +** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if +**
    +**
  1. the destination database was opened read-only, or +**
  2. the destination database is using write-ahead-log journaling +** and the destination and source page sizes differ, or +**
  3. the destination database is an in-memory database and the +** destination and source page sizes differ. +**
)^ +** +** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then +** the [sqlite3_busy_handler | busy-handler function] +** is invoked (if one is specified). ^If the +** busy-handler returns non-zero before the lock is available, then +** [SQLITE_BUSY] is returned to the caller. ^In this case the call to +** sqlite3_backup_step() can be retried later. ^If the source +** [database connection] +** is being used to write to the source database when sqlite3_backup_step() +** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this +** case the call to sqlite3_backup_step() can be retried later on. ^(If +** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or +** [SQLITE_READONLY] is returned, then +** there is no point in retrying the call to sqlite3_backup_step(). These +** errors are considered fatal.)^ The application must accept +** that the backup operation has failed and pass the backup operation handle +** to the sqlite3_backup_finish() to release associated resources. +** +** ^The first call to sqlite3_backup_step() obtains an exclusive lock +** on the destination file. ^The exclusive lock is not released until either +** sqlite3_backup_finish() is called or the backup operation is complete +** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to +** sqlite3_backup_step() obtains a [shared lock] on the source database that +** lasts for the duration of the sqlite3_backup_step() call. +** ^Because the source database is not locked between calls to +** sqlite3_backup_step(), the source database may be modified mid-way +** through the backup process. ^If the source database is modified by an +** external process or via a database connection other than the one being +** used by the backup operation, then the backup will be automatically +** restarted by the next call to sqlite3_backup_step(). ^If the source +** database is modified by the using the same database connection as is used +** by the backup operation, then the backup database is automatically +** updated at the same time. +** +** sqlite3_backup_finish() +** +** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the +** application wishes to abandon the backup operation, the application +** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). +** ^The sqlite3_backup_finish() interfaces releases all +** resources associated with the [sqlite3_backup] object. +** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any +** active write-transaction on the destination database is rolled back. +** The [sqlite3_backup] object is invalid +** and may not be used following a call to sqlite3_backup_finish(). +** +** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no +** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() completed. +** ^If an out-of-memory condition or IO error occurred during any prior +** sqlite3_backup_step() call on the same [sqlite3_backup] object, then +** sqlite3_backup_finish() returns the corresponding [error code]. +** +** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() +** is not a permanent error and does not affect the return value of +** sqlite3_backup_finish(). +** +** sqlite3_backup_remaining(), sqlite3_backup_pagecount() +** +** ^Each call to sqlite3_backup_step() sets two values inside +** the [sqlite3_backup] object: the number of pages still to be backed +** up and the total number of pages in the source database file. +** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces +** retrieve these two values, respectively. +** +** ^The values returned by these functions are only updated by +** sqlite3_backup_step(). ^If the source database is modified during a backup +** operation, then the values are not updated to account for any extra +** pages that need to be updated or the size of the source database file +** changing. +** +** Concurrent Usage of Database Handles +** +** ^The source [database connection] may be used by the application for other +** purposes while a backup operation is underway or being initialized. +** ^If SQLite is compiled and configured to support threadsafe database +** connections, then the source database connection may be used concurrently +** from within other threads. +** +** However, the application must guarantee that the destination +** [database connection] is not passed to any other API (by any thread) after +** sqlite3_backup_init() is called and before the corresponding call to +** sqlite3_backup_finish(). SQLite does not currently check to see +** if the application incorrectly accesses the destination [database connection] +** and so no error code is reported, but the operations may malfunction +** nevertheless. Use of the destination database connection while a +** backup is in progress might also also cause a mutex deadlock. +** +** If running in [shared cache mode], the application must +** guarantee that the shared cache used by the destination database +** is not accessed while the backup is running. In practice this means +** that the application must guarantee that the disk file being +** backed up to is not accessed by any connection within the process, +** not just the specific connection that was passed to sqlite3_backup_init(). +** +** The [sqlite3_backup] object itself is partially threadsafe. Multiple +** threads may safely make multiple concurrent calls to sqlite3_backup_step(). +** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() +** APIs are not strictly speaking threadsafe. If they are invoked at the +** same time as another thread is invoking sqlite3_backup_step() it is +** possible that they return invalid values. +*/ +SQLITE_API sqlite3_backup *sqlite3_backup_init( + sqlite3 *pDest, /* Destination database handle */ + const char *zDestName, /* Destination database name */ + sqlite3 *pSource, /* Source database handle */ + const char *zSourceName /* Source database name */ +); +SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); +SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); +SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); + +/* +** CAPI3REF: Unlock Notification +** +** ^When running in shared-cache mode, a database operation may fail with +** an [SQLITE_LOCKED] error if the required locks on the shared-cache or +** individual tables within the shared-cache cannot be obtained. See +** [SQLite Shared-Cache Mode] for a description of shared-cache locking. +** ^This API may be used to register a callback that SQLite will invoke +** when the connection currently holding the required lock relinquishes it. +** ^This API is only available if the library was compiled with the +** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. +** +** See Also: [Using the SQLite Unlock Notification Feature]. +** +** ^Shared-cache locks are released when a database connection concludes +** its current transaction, either by committing it or rolling it back. +** +** ^When a connection (known as the blocked connection) fails to obtain a +** shared-cache lock and SQLITE_LOCKED is returned to the caller, the +** identity of the database connection (the blocking connection) that +** has locked the required resource is stored internally. ^After an +** application receives an SQLITE_LOCKED error, it may call the +** sqlite3_unlock_notify() method with the blocked connection handle as +** the first argument to register for a callback that will be invoked +** when the blocking connections current transaction is concluded. ^The +** callback is invoked from within the [sqlite3_step] or [sqlite3_close] +** call that concludes the blocking connections transaction. +** +** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, +** there is a chance that the blocking connection will have already +** concluded its transaction by the time sqlite3_unlock_notify() is invoked. +** If this happens, then the specified callback is invoked immediately, +** from within the call to sqlite3_unlock_notify().)^ +** +** ^If the blocked connection is attempting to obtain a write-lock on a +** shared-cache table, and more than one other connection currently holds +** a read-lock on the same table, then SQLite arbitrarily selects one of +** the other connections to use as the blocking connection. +** +** ^(There may be at most one unlock-notify callback registered by a +** blocked connection. If sqlite3_unlock_notify() is called when the +** blocked connection already has a registered unlock-notify callback, +** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is +** called with a NULL pointer as its second argument, then any existing +** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback may also be canceled by closing the blocked +** connection using [sqlite3_close()]. +** +** The unlock-notify callback is not reentrant. If an application invokes +** any sqlite3_xxx API functions from within an unlock-notify callback, a +** crash or deadlock may be the result. +** +** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always +** returns SQLITE_OK. +** +** Callback Invocation Details +** +** When an unlock-notify callback is registered, the application provides a +** single void* pointer that is passed to the callback when it is invoked. +** However, the signature of the callback function allows SQLite to pass +** it an array of void* context pointers. The first argument passed to +** an unlock-notify callback is a pointer to an array of void* pointers, +** and the second is the number of entries in the array. +** +** When a blocking connections transaction is concluded, there may be +** more than one blocked connection that has registered for an unlock-notify +** callback. ^If two or more such blocked connections have specified the +** same callback function, then instead of invoking the callback function +** multiple times, it is invoked once with the set of void* context pointers +** specified by the blocked connections bundled together into an array. +** This gives the application an opportunity to prioritize any actions +** related to the set of unblocked database connections. +** +** Deadlock Detection +** +** Assuming that after registering for an unlock-notify callback a +** database waits for the callback to be issued before taking any further +** action (a reasonable assumption), then using this API may cause the +** application to deadlock. For example, if connection X is waiting for +** connection Y's transaction to be concluded, and similarly connection +** Y is waiting on connection X's transaction, then neither connection +** will proceed and the system may remain deadlocked indefinitely. +** +** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock +** detection. ^If a given call to sqlite3_unlock_notify() would put the +** system in a deadlocked state, then SQLITE_LOCKED is returned and no +** unlock-notify callback is registered. The system is said to be in +** a deadlocked state if connection A has registered for an unlock-notify +** callback on the conclusion of connection B's transaction, and connection +** B has itself registered for an unlock-notify callback when connection +** A's transaction is concluded. ^Indirect deadlock is also detected, so +** the system is also considered to be deadlocked if connection B has +** registered for an unlock-notify callback on the conclusion of connection +** C's transaction, where connection C is waiting on connection A. ^Any +** number of levels of indirection are allowed. +** +** The "DROP TABLE" Exception +** +** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost +** always appropriate to call sqlite3_unlock_notify(). There is however, +** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, +** SQLite checks if there are any currently executing SELECT statements +** that belong to the same connection. If there are, SQLITE_LOCKED is +** returned. In this case there is no "blocking connection", so invoking +** sqlite3_unlock_notify() results in the unlock-notify callback being +** invoked immediately. If the application then re-attempts the "DROP TABLE" +** or "DROP INDEX" query, an infinite loop might be the result. +** +** One way around this problem is to check the extended error code returned +** by an sqlite3_step() call. ^(If there is a blocking connection, then the +** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in +** the special "DROP TABLE/INDEX" case, the extended error code is just +** SQLITE_LOCKED.)^ +*/ +SQLITE_API int sqlite3_unlock_notify( + sqlite3 *pBlocked, /* Waiting connection */ + void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ + void *pNotifyArg /* Argument to pass to xNotify */ +); + + +/* +** CAPI3REF: String Comparison +** +** ^The [sqlite3_strnicmp()] API allows applications and extensions to +** compare the contents of two buffers containing UTF-8 strings in a +** case-independent fashion, using the same definition of case independence +** that SQLite uses internally when comparing identifiers. +*/ +SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); + +/* +** CAPI3REF: Error Logging Interface +** +** ^The [sqlite3_log()] interface writes a message into the error log +** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. +** ^If logging is enabled, the zFormat string and subsequent arguments are +** used with [sqlite3_snprintf()] to generate the final output string. +** +** The sqlite3_log() interface is intended for use by extensions such as +** virtual tables, collating functions, and SQL functions. While there is +** nothing to prevent an application from calling sqlite3_log(), doing so +** is considered bad form. +** +** The zFormat string must not be NULL. +** +** To avoid deadlocks and other threading problems, the sqlite3_log() routine +** will not use dynamically allocated memory. The log message is stored in +** a fixed-length buffer on the stack. If the log message is longer than +** a few hundred characters, it will be truncated to the length of the +** buffer. +*/ +SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); + +/* +** CAPI3REF: Write-Ahead Log Commit Hook +** +** ^The [sqlite3_wal_hook()] function is used to register a callback that +** will be invoked each time a database connection commits data to a +** [write-ahead log] (i.e. whenever a transaction is committed in +** [journal_mode | journal_mode=WAL mode]). +** +** ^The callback is invoked by SQLite after the commit has taken place and +** the associated write-lock on the database released, so the implementation +** may read, write or [checkpoint] the database as required. +** +** ^The first parameter passed to the callback function when it is invoked +** is a copy of the third parameter passed to sqlite3_wal_hook() when +** registering the callback. ^The second is a copy of the database handle. +** ^The third parameter is the name of the database that was written to - +** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter +** is the number of pages currently in the write-ahead log file, +** including those that were just committed. +** +** The callback function should normally return [SQLITE_OK]. ^If an error +** code is returned, that error will propagate back up through the +** SQLite code base to cause the statement that provoked the callback +** to report an error, though the commit will have still occurred. If the +** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value +** that does not correspond to any valid SQLite error code, the results +** are undefined. +** +** A single database handle may have at most a single write-ahead log callback +** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any +** previously registered write-ahead log callback. ^Note that the +** [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will +** those overwrite any prior [sqlite3_wal_hook()] settings. +*/ +SQLITE_API void *sqlite3_wal_hook( + sqlite3*, + int(*)(void *,sqlite3*,const char*,int), + void* +); + +/* +** CAPI3REF: Configure an auto-checkpoint +** +** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around +** [sqlite3_wal_hook()] that causes any database on [database connection] D +** to automatically [checkpoint] +** after committing a transaction if there are N or +** more frames in the [write-ahead log] file. ^Passing zero or +** a negative value as the nFrame parameter disables automatic +** checkpoints entirely. +** +** ^The callback registered by this function replaces any existing callback +** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback +** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism +** configured by this function. +** +** ^The [wal_autocheckpoint pragma] can be used to invoke this interface +** from SQL. +** +** ^Every new [database connection] defaults to having the auto-checkpoint +** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] +** pages. The use of this interface +** is only necessary if the default setting is found to be suboptimal +** for a particular application. +*/ +SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); + +/* +** CAPI3REF: Checkpoint a database +** +** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X +** on [database connection] D to be [checkpointed]. ^If X is NULL or an +** empty string, then a checkpoint is run on all databases of +** connection D. ^If the database connection D is not in +** [WAL | write-ahead log mode] then this interface is a harmless no-op. +** +** ^The [wal_checkpoint pragma] can be used to invoke this interface +** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] can be used to cause this interface to be +** run whenever the WAL reaches a certain size threshold. +*/ +SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/* +** 2010 August 30 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +*/ + +#ifndef _SQLITE3RTREE_H_ +#define _SQLITE3RTREE_H_ + + +#if 0 +extern "C" { +#endif + +typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; + +/* +** Register a geometry callback named zGeom that can be used as part of an +** R-Tree geometry query as follows: +** +** SELECT ... FROM WHERE MATCH $zGeom(... params ...) +*/ +SQLITE_API int sqlite3_rtree_geometry_callback( + sqlite3 *db, + const char *zGeom, + int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes), + void *pContext +); + + +/* +** A pointer to a structure of the following type is passed as the first +** argument to callbacks registered using rtree_geometry_callback(). +*/ +struct sqlite3_rtree_geometry { + void *pContext; /* Copy of pContext passed to s_r_g_c() */ + int nParam; /* Size of array aParam[] */ + double *aParam; /* Parameters passed to SQL geom function */ + void *pUser; /* Callback implementation user data */ + void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ +}; + + +#if 0 +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE3RTREE_H_ */ + + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include hash.h in the middle of sqliteInt.h ******************/ +/************** Begin file hash.h ********************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implemenation +** used in SQLite. +*/ +#ifndef _SQLITE_HASH_H_ +#define _SQLITE_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct Hash Hash; +typedef struct HashElem HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, some of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +** +** All elements of the hash table are on a single doubly-linked list. +** Hash.first points to the head of this list. +** +** There are Hash.htsize buckets. Each bucket points to a spot in +** the global doubly-linked list. The contents of the bucket are the +** element pointed to plus the next _ht.count-1 elements in the list. +** +** Hash.htsize and Hash.ht may be zero. In that case lookup is done +** by a linear search of the global list. For small tables, the +** Hash.ht table is never allocated because if there are few elements +** in the table, it is faster to do a linear search than to manage +** the hash table. +*/ +struct Hash { + unsigned int htsize; /* Number of buckets in the hash table */ + unsigned int count; /* Number of entries in this table */ + HashElem *first; /* The first element of the array */ + struct _ht { /* the hash table */ + int count; /* Number of entries with this hash */ + HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct HashElem { + HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + const char *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +SQLITE_PRIVATE void sqlite3HashInit(Hash*); +SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); +SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); +SQLITE_PRIVATE void sqlite3HashClear(Hash*); + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** Hash h; +** HashElem *p; +** ... +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ +** SomeStructure *pData = sqliteHashData(p); +** // do something with pData +** } +*/ +#define sqliteHashFirst(H) ((H)->first) +#define sqliteHashNext(E) ((E)->next) +#define sqliteHashData(E) ((E)->data) +/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ +/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ + +/* +** Number of entries in a hash table +*/ +/* #define sqliteHashCount(H) ((H)->count) // NOT USED */ + +#endif /* _SQLITE_HASH_H_ */ + +/************** End of hash.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include parse.h in the middle of sqliteInt.h *****************/ +/************** Begin file parse.h *******************************************/ +#define TK_SEMI 1 +#define TK_EXPLAIN 2 +#define TK_QUERY 3 +#define TK_PLAN 4 +#define TK_BEGIN 5 +#define TK_TRANSACTION 6 +#define TK_DEFERRED 7 +#define TK_IMMEDIATE 8 +#define TK_EXCLUSIVE 9 +#define TK_COMMIT 10 +#define TK_END 11 +#define TK_ROLLBACK 12 +#define TK_SAVEPOINT 13 +#define TK_RELEASE 14 +#define TK_TO 15 +#define TK_TABLE 16 +#define TK_CREATE 17 +#define TK_IF 18 +#define TK_NOT 19 +#define TK_EXISTS 20 +#define TK_TEMP 21 +#define TK_LP 22 +#define TK_RP 23 +#define TK_AS 24 +#define TK_COMMA 25 +#define TK_ID 26 +#define TK_INDEXED 27 +#define TK_ABORT 28 +#define TK_ACTION 29 +#define TK_AFTER 30 +#define TK_ANALYZE 31 +#define TK_ASC 32 +#define TK_ATTACH 33 +#define TK_BEFORE 34 +#define TK_BY 35 +#define TK_CASCADE 36 +#define TK_CAST 37 +#define TK_COLUMNKW 38 +#define TK_CONFLICT 39 +#define TK_DATABASE 40 +#define TK_DESC 41 +#define TK_DETACH 42 +#define TK_EACH 43 +#define TK_FAIL 44 +#define TK_FOR 45 +#define TK_IGNORE 46 +#define TK_INITIALLY 47 +#define TK_INSTEAD 48 +#define TK_LIKE_KW 49 +#define TK_MATCH 50 +#define TK_NO 51 +#define TK_KEY 52 +#define TK_OF 53 +#define TK_OFFSET 54 +#define TK_PRAGMA 55 +#define TK_RAISE 56 +#define TK_REPLACE 57 +#define TK_RESTRICT 58 +#define TK_ROW 59 +#define TK_TRIGGER 60 +#define TK_VACUUM 61 +#define TK_VIEW 62 +#define TK_VIRTUAL 63 +#define TK_REINDEX 64 +#define TK_RENAME 65 +#define TK_CTIME_KW 66 +#define TK_ANY 67 +#define TK_OR 68 +#define TK_AND 69 +#define TK_IS 70 +#define TK_BETWEEN 71 +#define TK_IN 72 +#define TK_ISNULL 73 +#define TK_NOTNULL 74 +#define TK_NE 75 +#define TK_EQ 76 +#define TK_GT 77 +#define TK_LE 78 +#define TK_LT 79 +#define TK_GE 80 +#define TK_ESCAPE 81 +#define TK_BITAND 82 +#define TK_BITOR 83 +#define TK_LSHIFT 84 +#define TK_RSHIFT 85 +#define TK_PLUS 86 +#define TK_MINUS 87 +#define TK_STAR 88 +#define TK_SLASH 89 +#define TK_REM 90 +#define TK_CONCAT 91 +#define TK_COLLATE 92 +#define TK_BITNOT 93 +#define TK_STRING 94 +#define TK_JOIN_KW 95 +#define TK_CONSTRAINT 96 +#define TK_DEFAULT 97 +#define TK_NULL 98 +#define TK_PRIMARY 99 +#define TK_UNIQUE 100 +#define TK_CHECK 101 +#define TK_REFERENCES 102 +#define TK_AUTOINCR 103 +#define TK_ON 104 +#define TK_INSERT 105 +#define TK_DELETE 106 +#define TK_UPDATE 107 +#define TK_SET 108 +#define TK_DEFERRABLE 109 +#define TK_FOREIGN 110 +#define TK_DROP 111 +#define TK_UNION 112 +#define TK_ALL 113 +#define TK_EXCEPT 114 +#define TK_INTERSECT 115 +#define TK_SELECT 116 +#define TK_DISTINCT 117 +#define TK_DOT 118 +#define TK_FROM 119 +#define TK_JOIN 120 +#define TK_USING 121 +#define TK_ORDER 122 +#define TK_GROUP 123 +#define TK_HAVING 124 +#define TK_LIMIT 125 +#define TK_WHERE 126 +#define TK_INTO 127 +#define TK_VALUES 128 +#define TK_INTEGER 129 +#define TK_FLOAT 130 +#define TK_BLOB 131 +#define TK_REGISTER 132 +#define TK_VARIABLE 133 +#define TK_CASE 134 +#define TK_WHEN 135 +#define TK_THEN 136 +#define TK_ELSE 137 +#define TK_INDEX 138 +#define TK_ALTER 139 +#define TK_ADD 140 +#define TK_TO_TEXT 141 +#define TK_TO_BLOB 142 +#define TK_TO_NUMERIC 143 +#define TK_TO_INT 144 +#define TK_TO_REAL 145 +#define TK_ISNOT 146 +#define TK_END_OF_FILE 147 +#define TK_ILLEGAL 148 +#define TK_SPACE 149 +#define TK_UNCLOSED_STRING 150 +#define TK_FUNCTION 151 +#define TK_COLUMN 152 +#define TK_AGG_FUNCTION 153 +#define TK_AGG_COLUMN 154 +#define TK_CONST_FUNC 155 +#define TK_UMINUS 156 +#define TK_UPLUS 157 + +/************** End of parse.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +#include +#include +#include +#include +#include + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite_int64 +# define float sqlite_int64 +# define LONGDOUBLE_TYPE sqlite_int64 +# ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) +# endif +# define SQLITE_OMIT_DATETIME_FUNCS 1 +# define SQLITE_OMIT_TRACE 1 +# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT +# undef SQLITE_HAVE_ISNAN +#endif +#ifndef SQLITE_BIG_DBL +# define SQLITE_BIG_DBL (1e99) +#endif + +/* +** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 +** afterward. Having this macro allows us to cause the C compiler +** to omit code used by TEMP tables without messy #ifndef statements. +*/ +#ifdef SQLITE_OMIT_TEMPDB +#define OMIT_TEMPDB 1 +#else +#define OMIT_TEMPDB 0 +#endif + +/* +** The "file format" number is an integer that is incremented whenever +** the VDBE-level file format changes. The following macros define the +** the default file format for new databases and the maximum file format +** that the library can read. +*/ +#define SQLITE_MAX_FILE_FORMAT 4 +#ifndef SQLITE_DEFAULT_FILE_FORMAT +# define SQLITE_DEFAULT_FILE_FORMAT 1 +#endif + +/* +** Determine whether triggers are recursive by default. This can be +** changed at run-time using a pragma. +*/ +#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS +# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 +#endif + +/* +** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** on the command-line +*/ +#ifndef SQLITE_TEMP_STORE +# define SQLITE_TEMP_STORE 1 +#endif + +/* +** GCC does not define the offsetof() macro so we'll have to do it +** ourselves. +*/ +#ifndef offsetof +#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +#endif + +/* +** Check to see if this machine uses EBCDIC. (Yes, believe it or +** not, there are still machines out there that use EBCDIC.) +*/ +#if 'A' == '\301' +# define SQLITE_EBCDIC 1 +#else +# define SQLITE_ASCII 1 +#endif + +/* +** Integers of known sizes. These typedefs might change for architectures +** where the sizes very. Preprocessor macros are available so that the +** types can be conveniently redefined at compile-type. Like this: +** +** cc '-DUINTPTR_TYPE=long long int' ... +*/ +#ifndef UINT32_TYPE +# ifdef HAVE_UINT32_T +# define UINT32_TYPE uint32_t +# else +# define UINT32_TYPE unsigned int +# endif +#endif +#ifndef UINT16_TYPE +# ifdef HAVE_UINT16_T +# define UINT16_TYPE uint16_t +# else +# define UINT16_TYPE unsigned short int +# endif +#endif +#ifndef INT16_TYPE +# ifdef HAVE_INT16_T +# define INT16_TYPE int16_t +# else +# define INT16_TYPE short int +# endif +#endif +#ifndef UINT8_TYPE +# ifdef HAVE_UINT8_T +# define UINT8_TYPE uint8_t +# else +# define UINT8_TYPE unsigned char +# endif +#endif +#ifndef INT8_TYPE +# ifdef HAVE_INT8_T +# define INT8_TYPE int8_t +# else +# define INT8_TYPE signed char +# endif +#endif +#ifndef LONGDOUBLE_TYPE +# define LONGDOUBLE_TYPE long double +#endif +typedef sqlite_int64 i64; /* 8-byte signed integer */ +typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ +typedef INT16_TYPE i16; /* 2-byte signed integer */ +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ +typedef INT8_TYPE i8; /* 1-byte signed integer */ + +/* +** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value +** that can be stored in a u32 without loss of data. The value +** is 0x00000000ffffffff. But because of quirks of some compilers, we +** have to specify the value in the less intuitive manner shown: +*/ +#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) + +/* +** Macros to determine whether the machine is big or little endian, +** evaluated at runtime. +*/ +#ifdef SQLITE_AMALGAMATION +SQLITE_PRIVATE const int sqlite3one = 1; +#else +SQLITE_PRIVATE const int sqlite3one; +#endif +#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ + || defined(__x86_64) || defined(__x86_64__) +# define SQLITE_BIGENDIAN 0 +# define SQLITE_LITTLEENDIAN 1 +# define SQLITE_UTF16NATIVE SQLITE_UTF16LE +#else +# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) +# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) +# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) +#endif + +/* +** Constants for the largest and smallest possible 64-bit signed integers. +** These macros are designed to work correctly on both 32-bit and 64-bit +** compilers. +*/ +#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) +#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) + +/* +** Round up a number to the next larger multiple of 8. This is used +** to force 8-byte alignment on 64-bit architectures. +*/ +#define ROUND8(x) (((x)+7)&~7) + +/* +** Round down to the nearest multiple of 8 +*/ +#define ROUNDDOWN8(x) ((x)&~7) + +/* +** Assert that the pointer X is aligned to an 8-byte boundary. This +** macro is used only within assert() to verify that the code gets +** all alignment restrictions correct. +** +** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the +** underlying malloc() implemention might return us 4-byte aligned +** pointers. In that case, only verify 4-byte alignment. +*/ +#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) +#else +# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) +#endif + + +/* +** An instance of the following structure is used to store the busy-handler +** callback for a given sqlite handle. +** +** The sqlite.busyHandler member of the sqlite struct contains the busy +** callback for the database handle. Each pager opened via the sqlite +** handle is passed a pointer to sqlite.busyHandler. The busy-handler +** callback is currently invoked only from within pager.c. +*/ +typedef struct BusyHandler BusyHandler; +struct BusyHandler { + int (*xFunc)(void *,int); /* The busy callback */ + void *pArg; /* First arg to busy callback */ + int nBusy; /* Incremented with each busy call */ +}; + +/* +** Name of the master database table. The master database table +** is a special table that holds the names and attributes of all +** user tables and indices. +*/ +#define MASTER_NAME "sqlite_master" +#define TEMP_MASTER_NAME "sqlite_temp_master" + +/* +** The root-page of the master database table. +*/ +#define MASTER_ROOT 1 + +/* +** The name of the schema table. +*/ +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + +/* +** A convenience macro that returns the number of elements in +** an array. +*/ +#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) + +/* +** The following value as a destructor means to use sqlite3DbFree(). +** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT. +*/ +#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree) + +/* +** When SQLITE_OMIT_WSD is defined, it means that the target platform does +** not support Writable Static Data (WSD) such as global and static variables. +** All variables must either be on the stack or dynamically allocated from +** the heap. When WSD is unsupported, the variable declarations scattered +** throughout the SQLite code must become constants instead. The SQLITE_WSD +** macro is used for this purpose. And instead of referencing the variable +** directly, we use its constant as a key to lookup the run-time allocated +** buffer that holds real variable. The constant is also the initializer +** for the run-time allocated buffer. +** +** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL +** macros become no-ops and have zero performance impact. +*/ +#ifdef SQLITE_OMIT_WSD + #define SQLITE_WSD const + #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) + #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) +SQLITE_API int sqlite3_wsd_init(int N, int J); +SQLITE_API void *sqlite3_wsd_find(void *K, int L); +#else + #define SQLITE_WSD + #define GLOBAL(t,v) v + #define sqlite3GlobalConfig sqlite3Config +#endif + +/* +** The following macros are used to suppress compiler warnings and to +** make it clear to human readers when a function parameter is deliberately +** left unused within the body of a function. This usually happens when +** a function is called via a function pointer. For example the +** implementation of an SQL aggregate step callback may not use the +** parameter indicating the number of arguments passed to the aggregate, +** if it knows that this is enforced elsewhere. +** +** When a function parameter is not used at all within the body of a function, +** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. +** However, these macros may also be used to suppress warnings related to +** parameters that may or may not be used depending on compilation options. +** For example those parameters only used in assert() statements. In these +** cases the parameters are named as per the usual conventions. +*/ +#define UNUSED_PARAMETER(x) (void)(x) +#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) + +/* +** Forward references to structures +*/ +typedef struct AggInfo AggInfo; +typedef struct AuthContext AuthContext; +typedef struct AutoincInfo AutoincInfo; +typedef struct Bitvec Bitvec; +typedef struct CollSeq CollSeq; +typedef struct Column Column; +typedef struct Db Db; +typedef struct Schema Schema; +typedef struct Expr Expr; +typedef struct ExprList ExprList; +typedef struct ExprSpan ExprSpan; +typedef struct FKey FKey; +typedef struct FuncDestructor FuncDestructor; +typedef struct FuncDef FuncDef; +typedef struct FuncDefHash FuncDefHash; +typedef struct IdList IdList; +typedef struct Index Index; +typedef struct IndexSample IndexSample; +typedef struct KeyClass KeyClass; +typedef struct KeyInfo KeyInfo; +typedef struct Lookaside Lookaside; +typedef struct LookasideSlot LookasideSlot; +typedef struct Module Module; +typedef struct NameContext NameContext; +typedef struct Parse Parse; +typedef struct RowSet RowSet; +typedef struct Savepoint Savepoint; +typedef struct Select Select; +typedef struct SrcList SrcList; +typedef struct StrAccum StrAccum; +typedef struct Table Table; +typedef struct TableLock TableLock; +typedef struct Token Token; +typedef struct Trigger Trigger; +typedef struct TriggerPrg TriggerPrg; +typedef struct TriggerStep TriggerStep; +typedef struct UnpackedRecord UnpackedRecord; +typedef struct VTable VTable; +typedef struct Walker Walker; +typedef struct WherePlan WherePlan; +typedef struct WhereInfo WhereInfo; +typedef struct WhereLevel WhereLevel; + +/* +** Defer sourcing vdbe.h and btree.h until after the "u8" and +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque +** pointer types (i.e. FuncDef) defined above. +*/ +/************** Include btree.h in the middle of sqliteInt.h *****************/ +/************** Begin file btree.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite B-Tree file +** subsystem. See comments in the source code for a detailed description +** of what each interface routine does. +*/ +#ifndef _BTREE_H_ +#define _BTREE_H_ + +/* TODO: This definition is just included so other modules compile. It +** needs to be revisited. +*/ +#define SQLITE_N_BTREE_META 10 + +/* +** If defined as non-zero, auto-vacuum is enabled by default. Otherwise +** it must be turned on for each database using "PRAGMA auto_vacuum = 1". +*/ +#ifndef SQLITE_DEFAULT_AUTOVACUUM + #define SQLITE_DEFAULT_AUTOVACUUM 0 +#endif + +#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ +#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ +#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ + +/* +** Forward declarations of structure +*/ +typedef struct Btree Btree; +typedef struct BtCursor BtCursor; +typedef struct BtShared BtShared; +typedef struct BtreeMutexArray BtreeMutexArray; + +/* +** This structure records all of the Btrees that need to hold +** a mutex before we enter sqlite3VdbeExec(). The Btrees are +** are placed in aBtree[] in order of aBtree[]->pBt. That way, +** we can always lock and unlock them all quickly. +*/ +struct BtreeMutexArray { + int nMutex; + Btree *aBtree[SQLITE_MAX_ATTACHED+1]; +}; + + +SQLITE_PRIVATE int sqlite3BtreeOpen( + const char *zFilename, /* Name of database file to open */ + sqlite3 *db, /* Associated database connection */ + Btree **ppBtree, /* Return open Btree* here */ + int flags, /* Flags */ + int vfsFlags /* Flags passed through to VFS open */ +); + +/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the +** following values. +** +** NOTE: These values must match the corresponding PAGER_ values in +** pager.h. +*/ +#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ +#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */ +#define BTREE_MEMORY 4 /* This is an in-memory DB */ +#define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */ +#define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */ + +SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int); +SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); +SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); +SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); +SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); +SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); +SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); +SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); +SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*); +SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); +SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*); +SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); +SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); +SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); +SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); +SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); +SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); +SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); +SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); + +SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); +SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); + +SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); + +/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR +** of the flags shown below. +** +** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. +** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data +** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With +** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored +** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL +** indices.) +*/ +#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ +#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ + +SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); +SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); +SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); + +SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); +SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); + +/* +** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta +** should be one of the following values. The integer values are assigned +** to constants so that the offset of the corresponding field in an +** SQLite database header may be found using the following formula: +** +** offset = 36 + (idx * 4) +** +** For example, the free-page-count field is located at byte offset 36 of +** the database file header. The incr-vacuum-flag field is located at +** byte offset 64 (== 36+4*7). +*/ +#define BTREE_FREE_PAGE_COUNT 0 +#define BTREE_SCHEMA_VERSION 1 +#define BTREE_FILE_FORMAT 2 +#define BTREE_DEFAULT_CACHE_SIZE 3 +#define BTREE_LARGEST_ROOT_PAGE 4 +#define BTREE_TEXT_ENCODING 5 +#define BTREE_USER_VERSION 6 +#define BTREE_INCR_VACUUM 7 + +SQLITE_PRIVATE int sqlite3BtreeCursor( + Btree*, /* BTree containing table to open */ + int iTable, /* Index of root page */ + int wrFlag, /* 1 for writing. 0 for read-only */ + struct KeyInfo*, /* First argument to compare function */ + BtCursor *pCursor /* Space to write cursor structure */ +); +SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); +SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); + +SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( + BtCursor*, + UnpackedRecord *pUnKey, + i64 intKey, + int bias, + int *pRes +); +SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); +SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, + const void *pData, int nData, + int nZero, int bias, int seekResult); +SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); +SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); +SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); +SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); +SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); +SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); + +SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); +SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); + +SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); +SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); +SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); + +SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); + +#ifndef NDEBUG +SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); +#endif + +#ifndef SQLITE_OMIT_BTREECOUNT +SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); +SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); +#endif + +#ifndef SQLITE_OMIT_WAL +SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*); +#endif + +/* +** If we are not using shared cache, then there is no need to +** use mutexes to access the BtShared structures. So make the +** Enter and Leave procedures no-ops. +*/ +#ifndef SQLITE_OMIT_SHARED_CACHE +SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); +#else +# define sqlite3BtreeEnter(X) +# define sqlite3BtreeEnterAll(X) +#endif + +#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE +SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); +SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); +SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); +SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*); +SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*); +SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); +#ifndef NDEBUG + /* These routines are used inside assert() statements only. */ +SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); +SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); +#endif +#else + +# define sqlite3BtreeLeave(X) +# define sqlite3BtreeEnterCursor(X) +# define sqlite3BtreeLeaveCursor(X) +# define sqlite3BtreeLeaveAll(X) +# define sqlite3BtreeMutexArrayEnter(X) +# define sqlite3BtreeMutexArrayLeave(X) +# define sqlite3BtreeMutexArrayInsert(X,Y) + +# define sqlite3BtreeHoldsMutex(X) 1 +# define sqlite3BtreeHoldsAllMutexes(X) 1 +#endif + + +#endif /* _BTREE_H_ */ + +/************** End of btree.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include vdbe.h in the middle of sqliteInt.h ******************/ +/************** Begin file vdbe.h ********************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** Header file for the Virtual DataBase Engine (VDBE) +** +** This header defines the interface to the virtual database engine +** or VDBE. The VDBE implements an abstract machine that runs a +** simple program to access and modify the underlying database. +*/ +#ifndef _SQLITE_VDBE_H_ +#define _SQLITE_VDBE_H_ + +/* +** A single VDBE is an opaque structure named "Vdbe". Only routines +** in the source file sqliteVdbe.c are allowed to see the insides +** of this structure. +*/ +typedef struct Vdbe Vdbe; + +/* +** The names of the following types declared in vdbeInt.h are required +** for the VdbeOp definition. +*/ +typedef struct VdbeFunc VdbeFunc; +typedef struct Mem Mem; +typedef struct SubProgram SubProgram; + +/* +** A single instruction of the virtual machine has an opcode +** and as many as three operands. The instruction is recorded +** as an instance of the following structure: +*/ +struct VdbeOp { + u8 opcode; /* What operation to perform */ + signed char p4type; /* One of the P4_xxx constants for p4 */ + u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */ + u8 p5; /* Fifth parameter is an unsigned character */ + int p1; /* First operand */ + int p2; /* Second parameter (often the jump destination) */ + int p3; /* The third parameter */ + union { /* fourth parameter */ + int i; /* Integer value if p4type==P4_INT32 */ + void *p; /* Generic pointer */ + char *z; /* Pointer to data for string (char array) types */ + i64 *pI64; /* Used when p4type is P4_INT64 */ + double *pReal; /* Used when p4type is P4_REAL */ + FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ + VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ + CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ + Mem *pMem; /* Used when p4type is P4_MEM */ + VTable *pVtab; /* Used when p4type is P4_VTAB */ + KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ + int *ai; /* Used when p4type is P4_INTARRAY */ + SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ + } p4; +#ifdef SQLITE_DEBUG + char *zComment; /* Comment to improve readability */ +#endif +#ifdef VDBE_PROFILE + int cnt; /* Number of times this instruction was executed */ + u64 cycles; /* Total time spent executing this instruction */ +#endif +}; +typedef struct VdbeOp VdbeOp; + + +/* +** A sub-routine used to implement a trigger program. +*/ +struct SubProgram { + VdbeOp *aOp; /* Array of opcodes for sub-program */ + int nOp; /* Elements in aOp[] */ + int nMem; /* Number of memory cells required */ + int nCsr; /* Number of cursors required */ + void *token; /* id that may be used to recursive triggers */ + SubProgram *pNext; /* Next sub-program already visited */ +}; + +/* +** A smaller version of VdbeOp used for the VdbeAddOpList() function because +** it takes up less space. +*/ +struct VdbeOpList { + u8 opcode; /* What operation to perform */ + signed char p1; /* First operand */ + signed char p2; /* Second parameter (often the jump destination) */ + signed char p3; /* Third parameter */ +}; +typedef struct VdbeOpList VdbeOpList; + +/* +** Allowed values of VdbeOp.p4type +*/ +#define P4_NOTUSED 0 /* The P4 parameter is not used */ +#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ +#define P4_STATIC (-2) /* Pointer to a static string */ +#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ +#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ +#define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */ +#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ +#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */ +#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ +#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ +#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ +#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ +#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ +#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ + +/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure +** is made. That copy is freed when the Vdbe is finalized. But if the +** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still +** gets freed when the Vdbe is finalized so it still should be obtained +** from a single sqliteMalloc(). But no copy is made and the calling +** function should *not* try to free the KeyInfo. +*/ +#define P4_KEYINFO_HANDOFF (-16) +#define P4_KEYINFO_STATIC (-17) + +/* +** The Vdbe.aColName array contains 5n Mem structures, where n is the +** number of columns of data returned by the statement. +*/ +#define COLNAME_NAME 0 +#define COLNAME_DECLTYPE 1 +#define COLNAME_DATABASE 2 +#define COLNAME_TABLE 3 +#define COLNAME_COLUMN 4 +#ifdef SQLITE_ENABLE_COLUMN_METADATA +# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ +#else +# ifdef SQLITE_OMIT_DECLTYPE +# define COLNAME_N 1 /* Store only the name */ +# else +# define COLNAME_N 2 /* Store the name and decltype */ +# endif +#endif + +/* +** The following macro converts a relative address in the p2 field +** of a VdbeOp structure into a negative number so that +** sqlite3VdbeAddOpList() knows that the address is relative. Calling +** the macro again restores the address. +*/ +#define ADDR(X) (-1-(X)) + +/* +** The makefile scans the vdbe.c source file and creates the "opcodes.h" +** header file that defines a number for each opcode used by the VDBE. +*/ +/************** Include opcodes.h in the middle of vdbe.h ********************/ +/************** Begin file opcodes.h *****************************************/ +/* Automatically generated. Do not edit */ +/* See the mkopcodeh.awk script for details */ +#define OP_Goto 1 +#define OP_Gosub 2 +#define OP_Return 3 +#define OP_Yield 4 +#define OP_HaltIfNull 5 +#define OP_Halt 6 +#define OP_Integer 7 +#define OP_Int64 8 +#define OP_Real 130 /* same as TK_FLOAT */ +#define OP_String8 94 /* same as TK_STRING */ +#define OP_String 9 +#define OP_Null 10 +#define OP_Blob 11 +#define OP_Variable 12 +#define OP_Move 13 +#define OP_Copy 14 +#define OP_SCopy 15 +#define OP_ResultRow 16 +#define OP_Concat 91 /* same as TK_CONCAT */ +#define OP_Add 86 /* same as TK_PLUS */ +#define OP_Subtract 87 /* same as TK_MINUS */ +#define OP_Multiply 88 /* same as TK_STAR */ +#define OP_Divide 89 /* same as TK_SLASH */ +#define OP_Remainder 90 /* same as TK_REM */ +#define OP_CollSeq 17 +#define OP_Function 18 +#define OP_BitAnd 82 /* same as TK_BITAND */ +#define OP_BitOr 83 /* same as TK_BITOR */ +#define OP_ShiftLeft 84 /* same as TK_LSHIFT */ +#define OP_ShiftRight 85 /* same as TK_RSHIFT */ +#define OP_AddImm 20 +#define OP_MustBeInt 21 +#define OP_RealAffinity 22 +#define OP_ToText 141 /* same as TK_TO_TEXT */ +#define OP_ToBlob 142 /* same as TK_TO_BLOB */ +#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ +#define OP_ToInt 144 /* same as TK_TO_INT */ +#define OP_ToReal 145 /* same as TK_TO_REAL */ +#define OP_Eq 76 /* same as TK_EQ */ +#define OP_Ne 75 /* same as TK_NE */ +#define OP_Lt 79 /* same as TK_LT */ +#define OP_Le 78 /* same as TK_LE */ +#define OP_Gt 77 /* same as TK_GT */ +#define OP_Ge 80 /* same as TK_GE */ +#define OP_Permutation 23 +#define OP_Compare 24 +#define OP_Jump 25 +#define OP_And 69 /* same as TK_AND */ +#define OP_Or 68 /* same as TK_OR */ +#define OP_Not 19 /* same as TK_NOT */ +#define OP_BitNot 93 /* same as TK_BITNOT */ +#define OP_If 26 +#define OP_IfNot 27 +#define OP_IsNull 73 /* same as TK_ISNULL */ +#define OP_NotNull 74 /* same as TK_NOTNULL */ +#define OP_Column 28 +#define OP_Affinity 29 +#define OP_MakeRecord 30 +#define OP_Count 31 +#define OP_Savepoint 32 +#define OP_AutoCommit 33 +#define OP_Transaction 34 +#define OP_ReadCookie 35 +#define OP_SetCookie 36 +#define OP_VerifyCookie 37 +#define OP_OpenRead 38 +#define OP_OpenWrite 39 +#define OP_OpenAutoindex 40 +#define OP_OpenEphemeral 41 +#define OP_OpenPseudo 42 +#define OP_Close 43 +#define OP_SeekLt 44 +#define OP_SeekLe 45 +#define OP_SeekGe 46 +#define OP_SeekGt 47 +#define OP_Seek 48 +#define OP_NotFound 49 +#define OP_Found 50 +#define OP_IsUnique 51 +#define OP_NotExists 52 +#define OP_Sequence 53 +#define OP_NewRowid 54 +#define OP_Insert 55 +#define OP_InsertInt 56 +#define OP_Delete 57 +#define OP_ResetCount 58 +#define OP_RowKey 59 +#define OP_RowData 60 +#define OP_Rowid 61 +#define OP_NullRow 62 +#define OP_Last 63 +#define OP_Sort 64 +#define OP_Rewind 65 +#define OP_Prev 66 +#define OP_Next 67 +#define OP_IdxInsert 70 +#define OP_IdxDelete 71 +#define OP_IdxRowid 72 +#define OP_IdxLT 81 +#define OP_IdxGE 92 +#define OP_Destroy 95 +#define OP_Clear 96 +#define OP_CreateIndex 97 +#define OP_CreateTable 98 +#define OP_ParseSchema 99 +#define OP_LoadAnalysis 100 +#define OP_DropTable 101 +#define OP_DropIndex 102 +#define OP_DropTrigger 103 +#define OP_IntegrityCk 104 +#define OP_RowSetAdd 105 +#define OP_RowSetRead 106 +#define OP_RowSetTest 107 +#define OP_Program 108 +#define OP_Param 109 +#define OP_FkCounter 110 +#define OP_FkIfZero 111 +#define OP_MemMax 112 +#define OP_IfPos 113 +#define OP_IfNeg 114 +#define OP_IfZero 115 +#define OP_AggStep 116 +#define OP_AggFinal 117 +#define OP_Checkpoint 118 +#define OP_JournalMode 119 +#define OP_Vacuum 120 +#define OP_IncrVacuum 121 +#define OP_Expire 122 +#define OP_TableLock 123 +#define OP_VBegin 124 +#define OP_VCreate 125 +#define OP_VDestroy 126 +#define OP_VOpen 127 +#define OP_VFilter 128 +#define OP_VColumn 129 +#define OP_VNext 131 +#define OP_VRename 132 +#define OP_VUpdate 133 +#define OP_Pagecount 134 +#define OP_MaxPgcnt 135 +#define OP_Trace 136 +#define OP_Noop 137 +#define OP_Explain 138 + +/* The following opcode values are never used */ +#define OP_NotUsed_139 139 +#define OP_NotUsed_140 140 + + +/* Properties such as "out2" or "jump" that are specified in +** comments following the "case" for each opcode in the vdbe.c +** are encoded into bitvectors as follows: +*/ +#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ +#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ +#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ +#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ +#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ +#define OPFLG_OUT2 0x0020 /* out2: P2 is an output */ +#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */ +#define OPFLG_INITIALIZER {\ +/* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\ +/* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\ +/* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\ +/* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\ +/* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\ +/* 40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\ +/* 48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\ +/* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\ +/* 64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\ +/* 72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ +/* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\ +/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\ +/* 96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\ +/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\ +/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\ +/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\ +/* 144 */ 0x04, 0x04,} + +/************** End of opcodes.h *********************************************/ +/************** Continuing where we left off in vdbe.h ***********************/ + +/* +** Prototypes for the VDBE interface. See comments on the implementation +** for a description of what each of these routines does. +*/ +SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); +SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); +SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); +SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); +SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); +SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); +#endif +SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); +SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); +SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); +SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); +SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); +SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); +SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); +SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8); +SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); +#ifndef SQLITE_OMIT_TRACE +SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); +#endif + +SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int); +SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*); +SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); + +#ifndef SQLITE_OMIT_TRIGGER +SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); +#endif + + +#ifndef NDEBUG +SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); +# define VdbeComment(X) sqlite3VdbeComment X +SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); +# define VdbeNoopComment(X) sqlite3VdbeNoopComment X +#else +# define VdbeComment(X) +# define VdbeNoopComment(X) +#endif + +#endif + +/************** End of vdbe.h ************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pager.h in the middle of sqliteInt.h *****************/ +/************** Begin file pager.h *******************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. The page cache subsystem reads and writes a file a page +** at a time and provides a journal for rollback. +*/ + +#ifndef _PAGER_H_ +#define _PAGER_H_ + +/* +** Default maximum size for persistent journal files. A negative +** value means no limit. This value may be overridden using the +** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". +*/ +#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT + #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 +#endif + +/* +** The type used to represent a page number. The first page in a file +** is called page 1. 0 is used to represent "not a page". +*/ +typedef u32 Pgno; + +/* +** Each open file is managed by a separate instance of the "Pager" structure. +*/ +typedef struct Pager Pager; + +/* +** Handle type for pages. +*/ +typedef struct PgHdr DbPage; + +/* +** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is +** reserved for working around a windows/posix incompatibility). It is +** used in the journal to signify that the remainder of the journal file +** is devoted to storing a master journal name - there are no more pages to +** roll back. See comments for function writeMasterJournal() in pager.c +** for details. +*/ +#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) + +/* +** Allowed values for the flags parameter to sqlite3PagerOpen(). +** +** NOTE: These values must match the corresponding BTREE_ values in btree.h. +*/ +#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ +#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */ +#define PAGER_MEMORY 0x0004 /* In-memory database */ + +/* +** Valid values for the second argument to sqlite3PagerLockingMode(). +*/ +#define PAGER_LOCKINGMODE_QUERY -1 +#define PAGER_LOCKINGMODE_NORMAL 0 +#define PAGER_LOCKINGMODE_EXCLUSIVE 1 + +/* +** Numeric constants that encode the journalmode. +*/ +#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ +#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ +#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ +#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ +#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ +#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ +#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ + +/* +** The remainder of this file contains the declarations of the functions +** that make up the Pager sub-system API. See source code comments for +** a detailed description of each routine. +*/ + +/* Open and close a Pager connection. */ +SQLITE_PRIVATE int sqlite3PagerOpen( + sqlite3_vfs*, + Pager **ppPager, + const char*, + int, + int, + int, + void(*)(DbPage*) +); +SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); + +/* Functions used to configure a Pager object. */ +SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); +SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); +SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); +SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int); +SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); +SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); +SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); +SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); +SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); + +/* Functions used to obtain and release page references. */ +SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); +#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) +SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); +SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); +SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); + +/* Operations on page references. */ +SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); +SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); +SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); +SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); +SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); +SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); + +/* Functions used to manage pager transactions and savepoints. */ +SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); +SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); +SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); +SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); +SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); +SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); +SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); +SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); + +SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); +SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); +SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); + +/* Functions used to query pager state and configuration. */ +SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); +SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); +SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*); +SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*); +SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); +SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); +SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); +SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); + +/* Functions used to truncate the database file. */ +SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); + +#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) +SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); +#endif + +/* Functions to support testing and debugging. */ +#if !defined(NDEBUG) || defined(SQLITE_TEST) +SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); +SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); +#endif +#ifdef SQLITE_TEST +SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); +SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); + void disable_simulated_io_errors(void); + void enable_simulated_io_errors(void); +#else +# define disable_simulated_io_errors() +# define enable_simulated_io_errors() +#endif + +#endif /* _PAGER_H_ */ + +/************** End of pager.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include pcache.h in the middle of sqliteInt.h ****************/ +/************** Begin file pcache.h ******************************************/ +/* +** 2008 August 05 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the sqlite page cache +** subsystem. +*/ + +#ifndef _PCACHE_H_ + +typedef struct PgHdr PgHdr; +typedef struct PCache PCache; + +/* +** Every page in the cache is controlled by an instance of the following +** structure. +*/ +struct PgHdr { + void *pData; /* Content of this page */ + void *pExtra; /* Extra content */ + PgHdr *pDirty; /* Transient list of dirty pages */ + Pgno pgno; /* Page number for this page */ + Pager *pPager; /* The pager this page is part of */ +#ifdef SQLITE_CHECK_PAGES + u32 pageHash; /* Hash of page content */ +#endif + u16 flags; /* PGHDR flags defined below */ + + /********************************************************************** + ** Elements above are public. All that follows is private to pcache.c + ** and should not be accessed by other modules. + */ + i16 nRef; /* Number of users of this page */ + PCache *pCache; /* Cache that owns this page */ + + PgHdr *pDirtyNext; /* Next element in list of dirty pages */ + PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ +}; + +/* Bit values for PgHdr.flags */ +#define PGHDR_DIRTY 0x002 /* Page has changed */ +#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before + ** writing this page to the database */ +#define PGHDR_NEED_READ 0x008 /* Content is unread */ +#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ +#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ + +/* Initialize and shutdown the page cache subsystem */ +SQLITE_PRIVATE int sqlite3PcacheInitialize(void); +SQLITE_PRIVATE void sqlite3PcacheShutdown(void); + +/* Page cache buffer management: +** These routines implement SQLITE_CONFIG_PAGECACHE. +*/ +SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); + +/* Create a new pager cache. +** Under memory stress, invoke xStress to try to make pages clean. +** Only clean and unpinned pages can be reclaimed. +*/ +SQLITE_PRIVATE void sqlite3PcacheOpen( + int szPage, /* Size of every page */ + int szExtra, /* Extra space associated with each page */ + int bPurgeable, /* True if pages are on backing store */ + int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ + void *pStress, /* Argument to xStress */ + PCache *pToInit /* Preallocated space for the PCache */ +); + +/* Modify the page-size after the cache has been created. */ +SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int); + +/* Return the size in bytes of a PCache object. Used to preallocate +** storage space. +*/ +SQLITE_PRIVATE int sqlite3PcacheSize(void); + +/* One release per successful fetch. Page is pinned until released. +** Reference counted. +*/ +SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); +SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); + +SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ +SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ +SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ +SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ + +/* Change a page number. Used by incr-vacuum. */ +SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); + +/* Remove all pages with pgno>x. Reset the cache if x==0 */ +SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); + +/* Get a list of all dirty pages in the cache, sorted by page number */ +SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); + +/* Reset and close the cache object */ +SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); + +/* Clear flags from pages of the page cache */ +SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); + +/* Discard the contents of the cache */ +SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); + +/* Return the total number of outstanding page references */ +SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); + +/* Increment the reference count of an existing page */ +SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); + +SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); + +/* Return the total number of pages stored in the cache */ +SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); + +#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) +/* Iterate through all dirty pages currently stored in the cache. This +** interface is only available if SQLITE_CHECK_PAGES is defined when the +** library is built. +*/ +SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); +#endif + +/* Set and get the suggested cache-size for the specified pager-cache. +** +** If no global maximum is configured, then the system attempts to limit +** the total number of pages cached by purgeable pager-caches to the sum +** of the suggested cache-sizes. +*/ +SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); +#ifdef SQLITE_TEST +SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); +#endif + +#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT +/* Try to return memory used by the pcache module to the main memory heap */ +SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); +#endif + +#ifdef SQLITE_TEST +SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); +#endif + +SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); + +#endif /* _PCACHE_H_ */ + +/************** End of pcache.h **********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + +/************** Include os.h in the middle of sqliteInt.h ********************/ +/************** Begin file os.h **********************************************/ +/* +** 2001 September 16 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file (together with is companion C source-code file +** "os.c") attempt to abstract the underlying operating system so that +** the SQLite library will work on both POSIX and windows systems. +** +** This header file is #include-ed by sqliteInt.h and thus ends up +** being included by every source file. +*/ +#ifndef _SQLITE_OS_H_ +#define _SQLITE_OS_H_ + +/* +** Figure out if we are dealing with Unix, Windows, or some other +** operating system. After the following block of preprocess macros, +** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER +** will defined to either 1 or 0. One of the four will be 1. The other +** three will be 0. +*/ +#if defined(SQLITE_OS_OTHER) +# if SQLITE_OS_OTHER==1 +# undef SQLITE_OS_UNIX +# define SQLITE_OS_UNIX 0 +# undef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# undef SQLITE_OS_OS2 +# define SQLITE_OS_OS2 0 +# else +# undef SQLITE_OS_OTHER +# endif +#endif +#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) +# define SQLITE_OS_OTHER 0 +# ifndef SQLITE_OS_WIN +# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) +# define SQLITE_OS_WIN 1 +# define SQLITE_OS_UNIX 0 +# define SQLITE_OS_OS2 0 +# elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__) +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 0 +# define SQLITE_OS_OS2 1 +# else +# define SQLITE_OS_WIN 0 +# define SQLITE_OS_UNIX 1 +# define SQLITE_OS_OS2 0 +# endif +# else +# define SQLITE_OS_UNIX 0 +# define SQLITE_OS_OS2 0 +# endif +#else +# ifndef SQLITE_OS_WIN +# define SQLITE_OS_WIN 0 +# endif +#endif + +/* +** Determine if we are dealing with WindowsCE - which has a much +** reduced API. +*/ +#if defined(_WIN32_WCE) +# define SQLITE_OS_WINCE 1 +#else +# define SQLITE_OS_WINCE 0 +#endif + + +/* +** Define the maximum size of a temporary filename +*/ +#if SQLITE_OS_WIN +# include +# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50) +#elif SQLITE_OS_OS2 +# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY) +# include /* has to be included before os2.h for linking to work */ +# endif +# define INCL_DOSDATETIME +# define INCL_DOSFILEMGR +# define INCL_DOSERRORS +# define INCL_DOSMISC +# define INCL_DOSPROCESS +# define INCL_DOSMODULEMGR +# define INCL_DOSSEMAPHORES +# include +# include +# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP) +#else +# define SQLITE_TEMPNAME_SIZE 200 +#endif + +/* If the SET_FULLSYNC macro is not defined above, then make it +** a no-op +*/ +#ifndef SET_FULLSYNC +# define SET_FULLSYNC(x,y) +#endif + +/* +** The default size of a disk sector +*/ +#ifndef SQLITE_DEFAULT_SECTOR_SIZE +# define SQLITE_DEFAULT_SECTOR_SIZE 512 +#endif + +/* +** Temporary files are named starting with this prefix followed by 16 random +** alphanumeric characters, and no file extension. They are stored in the +** OS's standard temporary file directory, and are deleted prior to exit. +** If sqlite is being embedded in another program, you may wish to change the +** prefix to reflect your program's name, so that if your program exits +** prematurely, old temporary files can be easily identified. This can be done +** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. +** +** 2006-10-31: The default prefix used to be "sqlite_". But then +** Mcafee started using SQLite in their anti-virus product and it +** started putting files with the "sqlite" name in the c:/temp folder. +** This annoyed many windows users. Those users would then do a +** Google search for "sqlite", find the telephone numbers of the +** developers and call to wake them up at night and complain. +** For this reason, the default name prefix is changed to be "sqlite" +** spelled backwards. So the temp files are still identified, but +** anybody smart enough to figure out the code is also likely smart +** enough to know that calling the developer will not help get rid +** of the file. +*/ +#ifndef SQLITE_TEMP_FILE_PREFIX +# define SQLITE_TEMP_FILE_PREFIX "etilqs_" +#endif + +/* +** The following values may be passed as the second argument to +** sqlite3OsLock(). The various locks exhibit the following semantics: +** +** SHARED: Any number of processes may hold a SHARED lock simultaneously. +** RESERVED: A single process may hold a RESERVED lock on a file at +** any time. Other processes may hold and obtain new SHARED locks. +** PENDING: A single process may hold a PENDING lock on a file at +** any one time. Existing SHARED locks may persist, but no new +** SHARED locks may be obtained by other processes. +** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. +** +** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a +** process that requests an EXCLUSIVE lock may actually obtain a PENDING +** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to +** sqlite3OsLock(). +*/ +#define NO_LOCK 0 +#define SHARED_LOCK 1 +#define RESERVED_LOCK 2 +#define PENDING_LOCK 3 +#define EXCLUSIVE_LOCK 4 + +/* +** File Locking Notes: (Mostly about windows but also some info for Unix) +** +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because +** those functions are not available. So we use only LockFile() and +** UnlockFile(). +** +** LockFile() prevents not just writing but also reading by other processes. +** A SHARED_LOCK is obtained by locking a single randomly-chosen +** byte out of a specific range of bytes. The lock byte is obtained at +** random so two separate readers can probably access the file at the +** same time, unless they are unlucky and choose the same lock byte. +** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. +** There can only be one writer. A RESERVED_LOCK is obtained by locking +** a single byte of the file that is designated as the reserved lock byte. +** A PENDING_LOCK is obtained by locking a designated byte different from +** the RESERVED_LOCK byte. +** +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, +** which means we can use reader/writer locks. When reader/writer locks +** are used, the lock is placed on the same range of bytes that is used +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme +** will support two or more Win95 readers or two or more WinNT readers. +** But a single Win95 reader will lock out all WinNT readers and a single +** WinNT reader will lock out all other Win95 readers. +** +** The following #defines specify the range of bytes used for locking. +** SHARED_SIZE is the number of bytes available in the pool from which +** a random byte is selected for a shared lock. The pool of bytes for +** shared locks begins at SHARED_FIRST. +** +** The same locking strategy and +** byte ranges are used for Unix. This leaves open the possiblity of having +** clients on win95, winNT, and unix all talking to the same shared file +** and all locking correctly. To do so would require that samba (or whatever +** tool is being used for file sharing) implements locks correctly between +** windows and unix. I'm guessing that isn't likely to happen, but by +** using the same locking range we are at least open to the possibility. +** +** Locking in windows is manditory. For this reason, we cannot store +** actual data in the bytes used for locking. The pager never allocates +** the pages involved in locking therefore. SHARED_SIZE is selected so +** that all locks will fit on a single page even at the minimum page size. +** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE +** is set high so that we don't have to allocate an unused page except +** for very large databases. But one should test the page skipping logic +** by setting PENDING_BYTE low and running the entire regression suite. +** +** Changing the value of PENDING_BYTE results in a subtly incompatible +** file format. Depending on how it is changed, you might not notice +** the incompatibility right away, even running a full regression test. +** The default location of PENDING_BYTE is the first byte past the +** 1GB boundary. +** +*/ +#ifdef SQLITE_OMIT_WSD +# define PENDING_BYTE (0x40000000) +#else +# define PENDING_BYTE sqlite3PendingByte +#endif +#define RESERVED_BYTE (PENDING_BYTE+1) +#define SHARED_FIRST (PENDING_BYTE+2) +#define SHARED_SIZE 510 + +/* +** Wrapper around OS specific sqlite3_os_init() function. +*/ +SQLITE_PRIVATE int sqlite3OsInit(void); + +/* +** Functions for accessing sqlite3_file methods +*/ +SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*); +SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); +SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); +SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); +SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); +#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); +SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); +SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); +SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); + +/* +** Functions for accessing sqlite3_vfs methods +*/ +SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); +SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); +SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); +SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); +#ifndef SQLITE_OMIT_LOAD_EXTENSION +SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); +SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); +SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ +SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); +SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); +SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); + +/* +** Convenience functions for opening and closing files using +** sqlite3_malloc() to obtain space for the file-handle structure. +*/ +SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); +SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); + +#endif /* _SQLITE_OS_H_ */ + +/************** End of os.h **************************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ +/************** Include mutex.h in the middle of sqliteInt.h *****************/ +/************** Begin file mutex.h *******************************************/ +/* +** 2007 August 28 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the common header for all mutex implementations. +** The sqliteInt.h header #includes this file so that it is available +** to all source files. We break it out in an effort to keep the code +** better organized. +** +** NOTE: source files should *not* #include this header file directly. +** Source files should #include the sqliteInt.h file and let that file +** include this one indirectly. +*/ + + +/* +** Figure out what version of the code to use. The choices are +** +** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The +** mutexes implemention cannot be overridden +** at start-time. +** +** SQLITE_MUTEX_NOOP For single-threaded applications. No +** mutual exclusion is provided. But this +** implementation can be overridden at +** start-time. +** +** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. +** +** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. +** +** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2. +*/ +#if !SQLITE_THREADSAFE +# define SQLITE_MUTEX_OMIT +#endif +#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) +# if SQLITE_OS_UNIX +# define SQLITE_MUTEX_PTHREADS +# elif SQLITE_OS_WIN +# define SQLITE_MUTEX_W32 +# elif SQLITE_OS_OS2 +# define SQLITE_MUTEX_OS2 +# else +# define SQLITE_MUTEX_NOOP +# endif +#endif + +#ifdef SQLITE_MUTEX_OMIT +/* +** If this is a no-op implementation, implement everything as macros. +*/ +#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) +#define sqlite3_mutex_free(X) +#define sqlite3_mutex_enter(X) +#define sqlite3_mutex_try(X) SQLITE_OK +#define sqlite3_mutex_leave(X) +#define sqlite3_mutex_held(X) ((void)(X),1) +#define sqlite3_mutex_notheld(X) ((void)(X),1) +#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) +#define sqlite3MutexInit() SQLITE_OK +#define sqlite3MutexEnd() +#endif /* defined(SQLITE_MUTEX_OMIT) */ + +/************** End of mutex.h ***********************************************/ +/************** Continuing where we left off in sqliteInt.h ******************/ + + +/* +** Each database file to be accessed by the system is an instance +** of the following structure. There are normally two of these structures +** in the sqlite.aDb[] array. aDb[0] is the main database file and +** aDb[1] is the database file used to hold temporary tables. Additional +** databases may be attached. +*/ +struct Db { + char *zName; /* Name of this database */ + Btree *pBt; /* The B*Tree structure for this database file */ + u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ + u8 safety_level; /* How aggressive at syncing data to disk */ + Schema *pSchema; /* Pointer to database schema (possibly shared) */ +}; + +/* +** An instance of the following structure stores a database schema. +*/ +struct Schema { + int schema_cookie; /* Database schema version number for this file */ + Hash tblHash; /* All tables indexed by name */ + Hash idxHash; /* All (named) indices indexed by name */ + Hash trigHash; /* All triggers indexed by name */ + Hash fkeyHash; /* All foreign keys by referenced table name */ + Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ + u8 file_format; /* Schema format version for this file */ + u8 enc; /* Text encoding used by this database */ + u16 flags; /* Flags associated with this schema */ + int cache_size; /* Number of pages to use in the cache */ +}; + +/* +** These macros can be used to test, set, or clear bits in the +** Db.pSchema->flags field. +*/ +#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) +#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) +#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) + +/* +** Allowed values for the DB.pSchema->flags field. +** +** The DB_SchemaLoaded flag is set after the database schema has been +** read into internal hash tables. +** +** DB_UnresetViews means that one or more views have column names that +** have been filled out. If the schema changes, these column names might +** changes and so the view will need to be reset. +*/ +#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ +#define DB_UnresetViews 0x0002 /* Some views have defined column names */ +#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ + +/* +** The number of different kinds of things that can be limited +** using the sqlite3_limit() interface. +*/ +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) + +/* +** Lookaside malloc is a set of fixed-size buffers that can be used +** to satisfy small transient memory allocation requests for objects +** associated with a particular database connection. The use of +** lookaside malloc provides a significant performance enhancement +** (approx 10%) by avoiding numerous malloc/free requests while parsing +** SQL statements. +** +** The Lookaside structure holds configuration information about the +** lookaside malloc subsystem. Each available memory allocation in +** the lookaside subsystem is stored on a linked list of LookasideSlot +** objects. +** +** Lookaside allocations are only allowed for objects that are associated +** with a particular database connection. Hence, schema information cannot +** be stored in lookaside because in shared cache mode the schema information +** is shared by multiple database connections. Therefore, while parsing +** schema information, the Lookaside.bEnabled flag is cleared so that +** lookaside allocations are not used to construct the schema objects. +*/ +struct Lookaside { + u16 sz; /* Size of each buffer in bytes */ + u8 bEnabled; /* False to disable new lookaside allocations */ + u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ + int nOut; /* Number of buffers currently checked out */ + int mxOut; /* Highwater mark for nOut */ + int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ + LookasideSlot *pFree; /* List of available buffers */ + void *pStart; /* First byte of available memory space */ + void *pEnd; /* First byte past end of available space */ +}; +struct LookasideSlot { + LookasideSlot *pNext; /* Next buffer in the list of free buffers */ +}; + +/* +** A hash table for function definitions. +** +** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. +** Collisions are on the FuncDef.pHash chain. +*/ +struct FuncDefHash { + FuncDef *a[23]; /* Hash table for functions */ +}; + +/* +** Each database connection is an instance of the following structure. +** +** The sqlite.lastRowid records the last insert rowid generated by an +** insert statement. Inserts on views do not affect its value. Each +** trigger has its own context, so that lastRowid can be updated inside +** triggers as usual. The previous value will be restored once the trigger +** exits. Upon entering a before or instead of trigger, lastRowid is no +** longer (since after version 2.8.12) reset to -1. +** +** The sqlite.nChange does not count changes within triggers and keeps no +** context. It is reset at start of sqlite3_exec. +** The sqlite.lsChange represents the number of changes made by the last +** insert, update, or delete statement. It remains constant throughout the +** length of a statement and is then updated by OP_SetCounts. It keeps a +** context stack just like lastRowid so that the count of changes +** within a trigger is not seen outside the trigger. Changes to views do not +** affect the value of lsChange. +** The sqlite.csChange keeps track of the number of current changes (since +** the last statement) and is used to update sqlite_lsChange. +** +** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16 +** store the most recent error code and, if applicable, string. The +** internal function sqlite3Error() is used to set these variables +** consistently. +*/ +struct sqlite3 { + sqlite3_vfs *pVfs; /* OS Interface */ + int nDb; /* Number of backends currently in use */ + Db *aDb; /* All backends */ + int flags; /* Miscellaneous flags. See below */ + int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ + int errCode; /* Most recent error code (SQLITE_*) */ + int errMask; /* & result codes with this before returning */ + u8 autoCommit; /* The auto-commit flag. */ + u8 temp_store; /* 1: file 2: memory 0: default */ + u8 mallocFailed; /* True if we have seen a malloc failure */ + u8 dfltLockMode; /* Default locking-mode for attached dbs */ + signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ + u8 suppressErr; /* Do not issue error messages if true */ + int nextPagesize; /* Pagesize after VACUUM if >0 */ + int nTable; /* Number of tables in the database */ + CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ + i64 lastRowid; /* ROWID of most recent insert (see above) */ + u32 magic; /* Magic number for detect library misuse */ + int nChange; /* Value returned by sqlite3_changes() */ + int nTotalChange; /* Value returned by sqlite3_total_changes() */ + sqlite3_mutex *mutex; /* Connection mutex */ + int aLimit[SQLITE_N_LIMIT]; /* Limits */ + struct sqlite3InitInfo { /* Information used during initialization */ + int iDb; /* When back is being initialized */ + int newTnum; /* Rootpage of table being initialized */ + u8 busy; /* TRUE if currently initializing */ + u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ + } init; + int nExtension; /* Number of loaded extensions */ + void **aExtension; /* Array of shared library handles */ + struct Vdbe *pVdbe; /* List of active virtual machines */ + int activeVdbeCnt; /* Number of VDBEs currently executing */ + int writeVdbeCnt; /* Number of active VDBEs that are writing */ + int vdbeExecCnt; /* Number of nested calls to VdbeExec() */ + void (*xTrace)(void*,const char*); /* Trace function */ + void *pTraceArg; /* Argument to the trace function */ + void (*xProfile)(void*,const char*,u64); /* Profiling function */ + void *pProfileArg; /* Argument to profile function */ + void *pCommitArg; /* Argument to xCommitCallback() */ + int (*xCommitCallback)(void*); /* Invoked at every commit. */ + void *pRollbackArg; /* Argument to xRollbackCallback() */ + void (*xRollbackCallback)(void*); /* Invoked at every commit. */ + void *pUpdateArg; + void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); +#ifndef SQLITE_OMIT_WAL + int (*xWalCallback)(void *, sqlite3 *, const char *, int); + void *pWalArg; +#endif + void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); + void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); + void *pCollNeededArg; + sqlite3_value *pErr; /* Most recent error message */ + char *zErrMsg; /* Most recent error message (UTF-8 encoded) */ + char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */ + union { + volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ + double notUsed1; /* Spacer */ + } u1; + Lookaside lookaside; /* Lookaside malloc configuration */ +#ifndef SQLITE_OMIT_AUTHORIZATION + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); + /* Access authorization function */ + void *pAuthArg; /* 1st argument to the access auth function */ +#endif +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK + int (*xProgress)(void *); /* The progress callback */ + void *pProgressArg; /* Argument to the progress callback */ + int nProgressOps; /* Number of opcodes for progress callback */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + Hash aModule; /* populated by sqlite3_create_module() */ + Table *pVTab; /* vtab with active Connect/Create method */ + VTable **aVTrans; /* Virtual tables with open transactions */ + int nVTrans; /* Allocated size of aVTrans */ + VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ +#endif + FuncDefHash aFunc; /* Hash table of connection functions */ + Hash aCollSeq; /* All collating sequences */ + BusyHandler busyHandler; /* Busy callback */ + int busyTimeout; /* Busy handler timeout, in msec */ + Db aDbStatic[2]; /* Static space for the 2 default backends */ + Savepoint *pSavepoint; /* List of active savepoints */ + int nSavepoint; /* Number of non-transaction savepoints */ + int nStatement; /* Number of nested statement-transactions */ + u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ + i64 nDeferredCons; /* Net deferred constraints this transaction. */ + int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ + +#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY + /* The following variables are all protected by the STATIC_MASTER + ** mutex, not by sqlite3.mutex. They are used by code in notify.c. + ** + ** When X.pUnlockConnection==Y, that means that X is waiting for Y to + ** unlock so that it can proceed. + ** + ** When X.pBlockingConnection==Y, that means that something that X tried + ** tried to do recently failed with an SQLITE_LOCKED error due to locks + ** held by Y. + */ + sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ + sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ + void *pUnlockArg; /* Argument to xUnlockNotify */ + void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ + sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ +#endif +}; + +/* +** A macro to discover the encoding of a database. +*/ +#define ENC(db) ((db)->aDb[0].pSchema->enc) + +/* +** Possible values for the sqlite3.flags. +*/ +#define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */ +#define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */ +#define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */ +#define SQLITE_ShortColNames 0x00000800 /* Show short columns names */ +#define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */ + /* DELETE, or UPDATE and return */ + /* the count using a callback. */ +#define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */ + /* result set is empty */ +#define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */ +#define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */ +#define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */ +#define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when + ** accessing read-only databases */ +#define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */ +#define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */ +#define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */ +#define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */ +#define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */ +#define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */ +#define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */ +#define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */ +#define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */ +#define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */ +#define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */ +#define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */ + +/* +** Bits of the sqlite3.flags field that are used by the +** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface. +** These must be the low-order bits of the flags field. +*/ +#define SQLITE_QueryFlattener 0x01 /* Disable query flattening */ +#define SQLITE_ColumnCache 0x02 /* Disable the column cache */ +#define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */ +#define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */ +#define SQLITE_IndexCover 0x10 /* Disable index covering table */ +#define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */ +#define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */ +#define SQLITE_OptMask 0xff /* Mask of all disablable opts */ + +/* +** Possible values for the sqlite.magic field. +** The numbers are obtained at random and have no special meaning, other +** than being distinct from one another. +*/ +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ +#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ + +/* +** Each SQL function is defined by an instance of the following +** structure. A pointer to this structure is stored in the sqlite.aFunc +** hash table. When multiple functions have the same name, the hash table +** points to a linked list of these structures. +*/ +struct FuncDef { + i16 nArg; /* Number of arguments. -1 means unlimited */ + u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ + u8 flags; /* Some combination of SQLITE_FUNC_* */ + void *pUserData; /* User data parameter */ + FuncDef *pNext; /* Next function with same name */ + void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ + void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ + void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ + char *zName; /* SQL name of the function. */ + FuncDef *pHash; /* Next with a different name but the same hash */ + FuncDestructor *pDestructor; /* Reference counted destructor function */ +}; + +/* +** This structure encapsulates a user-function destructor callback (as +** configured using create_function_v2()) and a reference counter. When +** create_function_v2() is called to create a function with a destructor, +** a single object of this type is allocated. FuncDestructor.nRef is set to +** the number of FuncDef objects created (either 1 or 3, depending on whether +** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor +** member of each of the new FuncDef objects is set to point to the allocated +** FuncDestructor. +** +** Thereafter, when one of the FuncDef objects is deleted, the reference +** count on this object is decremented. When it reaches 0, the destructor +** is invoked and the FuncDestructor structure freed. +*/ +struct FuncDestructor { + int nRef; + void (*xDestroy)(void *); + void *pUserData; +}; + +/* +** Possible values for FuncDef.flags +*/ +#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ +#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ +#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ +#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ +#define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */ +#define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */ +#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */ + +/* +** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are +** used to create the initializers for the FuncDef structures. +** +** FUNCTION(zName, nArg, iArg, bNC, xFunc) +** Used to create a scalar function definition of a function zName +** implemented by C function xFunc that accepts nArg arguments. The +** value passed as iArg is cast to a (void*) and made available +** as the user-data (sqlite3_user_data()) for the function. If +** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. +** +** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) +** Used to create an aggregate function definition implemented by +** the C functions xStep and xFinal. The first four parameters +** are interpreted in the same way as the first 4 parameters to +** FUNCTION(). +** +** LIKEFUNC(zName, nArg, pArg, flags) +** Used to create a scalar function definition of a function zName +** that accepts nArg arguments and is implemented by a call to C +** function likeFunc. Argument pArg is cast to a (void *) and made +** available as the function user-data (sqlite3_user_data()). The +** FuncDef.flags variable is set to the value passed as the flags +** parameter. +*/ +#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} +#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ + {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ + pArg, 0, xFunc, 0, 0, #zName, 0, 0} +#define LIKEFUNC(zName, nArg, arg, flags) \ + {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0} +#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ + {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ + SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0} + +/* +** All current savepoints are stored in a linked list starting at +** sqlite3.pSavepoint. The first element in the list is the most recently +** opened savepoint. Savepoints are added to the list by the vdbe +** OP_Savepoint instruction. +*/ +struct Savepoint { + char *zName; /* Savepoint name (nul-terminated) */ + i64 nDeferredCons; /* Number of deferred fk violations */ + Savepoint *pNext; /* Parent savepoint (if any) */ +}; + +/* +** The following are used as the second parameter to sqlite3Savepoint(), +** and as the P1 argument to the OP_Savepoint instruction. +*/ +#define SAVEPOINT_BEGIN 0 +#define SAVEPOINT_RELEASE 1 +#define SAVEPOINT_ROLLBACK 2 + + +/* +** Each SQLite module (virtual table definition) is defined by an +** instance of the following structure, stored in the sqlite3.aModule +** hash table. +*/ +struct Module { + const sqlite3_module *pModule; /* Callback pointers */ + const char *zName; /* Name passed to create_module() */ + void *pAux; /* pAux passed to create_module() */ + void (*xDestroy)(void *); /* Module destructor function */ +}; + +/* +** information about each column of an SQL table is held in an instance +** of this structure. +*/ +struct Column { + char *zName; /* Name of this column */ + Expr *pDflt; /* Default value of this column */ + char *zDflt; /* Original text of the default value */ + char *zType; /* Data type for this column */ + char *zColl; /* Collating sequence. If NULL, use the default */ + u8 notNull; /* True if there is a NOT NULL constraint */ + u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */ + char affinity; /* One of the SQLITE_AFF_... values */ +#ifndef SQLITE_OMIT_VIRTUALTABLE + u8 isHidden; /* True if this column is 'hidden' */ +#endif +}; + +/* +** A "Collating Sequence" is defined by an instance of the following +** structure. Conceptually, a collating sequence consists of a name and +** a comparison routine that defines the order of that sequence. +** +** There may two separate implementations of the collation function, one +** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that +** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine +** native byte order. When a collation sequence is invoked, SQLite selects +** the version that will require the least expensive encoding +** translations, if any. +** +** The CollSeq.pUser member variable is an extra parameter that passed in +** as the first argument to the UTF-8 comparison function, xCmp. +** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function, +** xCmp16. +** +** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the +** collating sequence is undefined. Indices built on an undefined +** collating sequence may not be read or written. +*/ +struct CollSeq { + char *zName; /* Name of the collating sequence, UTF-8 encoded */ + u8 enc; /* Text encoding handled by xCmp() */ + u8 type; /* One of the SQLITE_COLL_... values below */ + void *pUser; /* First argument to xCmp() */ + int (*xCmp)(void*,int, const void*, int, const void*); + void (*xDel)(void*); /* Destructor for pUser */ +}; + +/* +** Allowed values of CollSeq.type: +*/ +#define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */ +#define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */ +#define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */ +#define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */ + +/* +** A sort order can be either ASC or DESC. +*/ +#define SQLITE_SO_ASC 0 /* Sort in ascending order */ +#define SQLITE_SO_DESC 1 /* Sort in ascending order */ + +/* +** Column affinity types. +** +** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and +** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve +** the speed a little by numbering the values consecutively. +** +** But rather than start with 0 or 1, we begin with 'a'. That way, +** when multiple affinity types are concatenated into a string and +** used as the P4 operand, they will be more readable. +** +** Note also that the numeric types are grouped together so that testing +** for a numeric type is a single comparison. +*/ +#define SQLITE_AFF_TEXT 'a' +#define SQLITE_AFF_NONE 'b' +#define SQLITE_AFF_NUMERIC 'c' +#define SQLITE_AFF_INTEGER 'd' +#define SQLITE_AFF_REAL 'e' + +#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) + +/* +** The SQLITE_AFF_MASK values masks off the significant bits of an +** affinity value. +*/ +#define SQLITE_AFF_MASK 0x67 + +/* +** Additional bit values that can be ORed with an affinity without +** changing the affinity. +*/ +#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ +#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ +#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ + +/* +** An object of this type is created for each virtual table present in +** the database schema. +** +** If the database schema is shared, then there is one instance of this +** structure for each database connection (sqlite3*) that uses the shared +** schema. This is because each database connection requires its own unique +** instance of the sqlite3_vtab* handle used to access the virtual table +** implementation. sqlite3_vtab* handles can not be shared between +** database connections, even when the rest of the in-memory database +** schema is shared, as the implementation often stores the database +** connection handle passed to it via the xConnect() or xCreate() method +** during initialization internally. This database connection handle may +** then used by the virtual table implementation to access real tables +** within the database. So that they appear as part of the callers +** transaction, these accesses need to be made via the same database +** connection as that used to execute SQL operations on the virtual table. +** +** All VTable objects that correspond to a single table in a shared +** database schema are initially stored in a linked-list pointed to by +** the Table.pVTable member variable of the corresponding Table object. +** When an sqlite3_prepare() operation is required to access the virtual +** table, it searches the list for the VTable that corresponds to the +** database connection doing the preparing so as to use the correct +** sqlite3_vtab* handle in the compiled query. +** +** When an in-memory Table object is deleted (for example when the +** schema is being reloaded for some reason), the VTable objects are not +** deleted and the sqlite3_vtab* handles are not xDisconnect()ed +** immediately. Instead, they are moved from the Table.pVTable list to +** another linked list headed by the sqlite3.pDisconnect member of the +** corresponding sqlite3 structure. They are then deleted/xDisconnected +** next time a statement is prepared using said sqlite3*. This is done +** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. +** Refer to comments above function sqlite3VtabUnlockList() for an +** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect +** list without holding the corresponding sqlite3.mutex mutex. +** +** The memory for objects of this type is always allocated by +** sqlite3DbMalloc(), using the connection handle stored in VTable.db as +** the first argument. +*/ +struct VTable { + sqlite3 *db; /* Database connection associated with this table */ + Module *pMod; /* Pointer to module implementation */ + sqlite3_vtab *pVtab; /* Pointer to vtab instance */ + int nRef; /* Number of pointers to this structure */ + VTable *pNext; /* Next in linked list (see above) */ +}; + +/* +** Each SQL table is represented in memory by an instance of the +** following structure. +** +** Table.zName is the name of the table. The case of the original +** CREATE TABLE statement is stored, but case is not significant for +** comparisons. +** +** Table.nCol is the number of columns in this table. Table.aCol is a +** pointer to an array of Column structures, one for each column. +** +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of +** the column that is that key. Otherwise Table.iPKey is negative. Note +** that the datatype of the PRIMARY KEY must be INTEGER for this field to +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid +** is generated for each row of the table. TF_HasPrimaryKey is set if +** the table has any PRIMARY KEY, INTEGER or otherwise. +** +** Table.tnum is the page number for the root BTree page of the table in the +** database file. If Table.iDb is the index of the database table backend +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that +** holds temporary tables and indices. If TF_Ephemeral is set +** then the table is stored in a file that is automatically deleted +** when the VDBE cursor to the table is closed. In this case Table.tnum +** refers VDBE cursor number that holds the table open, not to the root +** page number. Transient tables are used to hold the results of a +** sub-query that appears instead of a real table name in the FROM clause +** of a SELECT statement. +*/ +struct Table { + char *zName; /* Name of the table or view */ + int iPKey; /* If not negative, use aCol[iPKey] as the primary key */ + int nCol; /* Number of columns in this table */ + Column *aCol; /* Information about each column */ + Index *pIndex; /* List of SQL indexes on this table. */ + int tnum; /* Root BTree node for this table (see note above) */ + unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ + Select *pSelect; /* NULL for tables. Points to definition if a view. */ + u16 nRef; /* Number of pointers to this Table */ + u8 tabFlags; /* Mask of TF_* values */ + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ + FKey *pFKey; /* Linked list of all foreign keys in this table */ + char *zColAff; /* String defining the affinity of each column */ +#ifndef SQLITE_OMIT_CHECK + Expr *pCheck; /* The AND of all CHECK constraints */ +#endif +#ifndef SQLITE_OMIT_ALTERTABLE + int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ +#endif +#ifndef SQLITE_OMIT_VIRTUALTABLE + VTable *pVTable; /* List of VTable objects. */ + int nModuleArg; /* Number of arguments to the module */ + char **azModuleArg; /* Text of all module args. [0] is module name */ +#endif + Trigger *pTrigger; /* List of triggers stored in pSchema */ + Schema *pSchema; /* Schema that contains this table */ + Table *pNextZombie; /* Next on the Parse.pZombieTab list */ +}; + +/* +** Allowed values for Tabe.tabFlags. +*/ +#define TF_Readonly 0x01 /* Read-only system table */ +#define TF_Ephemeral 0x02 /* An ephemeral table */ +#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ +#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ +#define TF_Virtual 0x10 /* Is a virtual table */ +#define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */ + + + +/* +** Test to see whether or not a table is a virtual table. This is +** done as a macro so that it will be optimized out when virtual +** table support is omitted from the build. +*/ +#ifndef SQLITE_OMIT_VIRTUALTABLE +# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) +# define IsHiddenColumn(X) ((X)->isHidden) +#else +# define IsVirtual(X) 0 +# define IsHiddenColumn(X) 0 +#endif + +/* +** Each foreign key constraint is an instance of the following structure. +** +** A foreign key is associated with two tables. The "from" table is +** the table that contains the REFERENCES clause that creates the foreign +** key. The "to" table is the table that is named in the REFERENCES clause. +** Consider this example: +** +** CREATE TABLE ex1( +** a INTEGER PRIMARY KEY, +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) +** ); +** +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". +** +** Each REFERENCES clause generates an instance of the following structure +** which is attached to the from-table. The to-table need not exist when +** the from-table is created. The existence of the to-table is not checked. +*/ +struct FKey { + Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ + FKey *pNextFrom; /* Next foreign key in pFrom */ + char *zTo; /* Name of table that the key points to (aka: Parent) */ + FKey *pNextTo; /* Next foreign key on table named zTo */ + FKey *pPrevTo; /* Previous foreign key on table named zTo */ + int nCol; /* Number of columns in this key */ + /* EV: R-30323-21917 */ + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ + u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ + Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ + int iFrom; /* Index of column in pFrom */ + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ + } aCol[1]; /* One entry for each of nCol column s */ +}; + +/* +** SQLite supports many different ways to resolve a constraint +** error. ROLLBACK processing means that a constraint violation +** causes the operation in process to fail and for the current transaction +** to be rolled back. ABORT processing means the operation in process +** fails and any prior changes from that one operation are backed out, +** but the transaction is not rolled back. FAIL processing means that +** the operation in progress stops and returns an error code. But prior +** changes due to the same operation are not backed out and no rollback +** occurs. IGNORE means that the particular row that caused the constraint +** error is not inserted or updated. Processing continues and no error +** is returned. REPLACE means that preexisting database rows that caused +** a UNIQUE constraint violation are removed so that the new insert or +** update can proceed. Processing continues and no error is reported. +** +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the +** referenced table row is propagated into the row that holds the +** foreign key. +** +** The following symbolic values are used to record which type +** of action to take. +*/ +#define OE_None 0 /* There is no constraint to check */ +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ +#define OE_Abort 2 /* Back out changes but do no rollback transaction */ +#define OE_Fail 3 /* Stop the operation but leave all prior changes */ +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ + +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ +#define OE_SetNull 7 /* Set the foreign key value to NULL */ +#define OE_SetDflt 8 /* Set the foreign key value to its default */ +#define OE_Cascade 9 /* Cascade the changes */ + +#define OE_Default 99 /* Do whatever the default action is */ + + +/* +** An instance of the following structure is passed as the first +** argument to sqlite3VdbeKeyCompare and is used to control the +** comparison of the two index keys. +*/ +struct KeyInfo { + sqlite3 *db; /* The database connection */ + u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ + u16 nField; /* Number of entries in aColl[] */ + u8 *aSortOrder; /* Sort order for each column. May be NULL */ + CollSeq *aColl[1]; /* Collating sequence for each term of the key */ +}; + +/* +** An instance of the following structure holds information about a +** single index record that has already been parsed out into individual +** values. +** +** A record is an object that contains one or more fields of data. +** Records are used to store the content of a table row and to store +** the key of an index. A blob encoding of a record is created by +** the OP_MakeRecord opcode of the VDBE and is disassembled by the +** OP_Column opcode. +** +** This structure holds a record that has already been disassembled +** into its constituent fields. +*/ +struct UnpackedRecord { + KeyInfo *pKeyInfo; /* Collation and sort-order information */ + u16 nField; /* Number of entries in apMem[] */ + u16 flags; /* Boolean settings. UNPACKED_... below */ + i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ + Mem *aMem; /* Values */ +}; + +/* +** Allowed values of UnpackedRecord.flags +*/ +#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */ +#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */ +#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */ +#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */ +#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */ +#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */ + +/* +** Each SQL index is represented in memory by an +** instance of the following structure. +** +** The columns of the table that are to be indexed are described +** by the aiColumn[] field of this structure. For example, suppose +** we have the following table and index: +** +** CREATE TABLE Ex1(c1 int, c2 int, c3 text); +** CREATE INDEX Ex2 ON Ex1(c3,c1); +** +** In the Table structure describing Ex1, nCol==3 because there are +** three columns in the table. In the Index structure describing +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. +** The second column to be indexed (c1) has an index of 0 in +** Ex1.aCol[], hence Ex2.aiColumn[1]==0. +** +** The Index.onError field determines whether or not the indexed columns +** must be unique and what to do if they are not. When Index.onError=OE_None, +** it means this is not a unique index. Otherwise it is a unique index +** and the value of Index.onError indicate the which conflict resolution +** algorithm to employ whenever an attempt is made to insert a non-unique +** element. +*/ +struct Index { + char *zName; /* Name of this index */ + int nColumn; /* Number of columns in the table used by this index */ + int *aiColumn; /* Which columns are used by this index. 1st is 0 */ + unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */ + Table *pTable; /* The SQL table being indexed */ + int tnum; /* Page containing root of this index in database file */ + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ + u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */ + char *zColAff; /* String defining the affinity of each column */ + Index *pNext; /* The next index associated with the same table */ + Schema *pSchema; /* Schema containing this index */ + u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */ + char **azColl; /* Array of collation sequence names for index */ + IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */ +}; + +/* +** Each sample stored in the sqlite_stat2 table is represented in memory +** using a structure of this type. +*/ +struct IndexSample { + union { + char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */ + double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */ + } u; + u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ + u8 nByte; /* Size in byte of text or blob. */ +}; + +/* +** Each token coming out of the lexer is an instance of +** this structure. Tokens are also used as part of an expression. +** +** Note if Token.z==0 then Token.dyn and Token.n are undefined and +** may contain random values. Do not make any assumptions about Token.dyn +** and Token.n when Token.z==0. +*/ +struct Token { + const char *z; /* Text of the token. Not NULL-terminated! */ + unsigned int n; /* Number of characters in this token */ +}; + +/* +** An instance of this structure contains information needed to generate +** code for a SELECT that contains aggregate functions. +** +** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a +** pointer to this structure. The Expr.iColumn field is the index in +** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate +** code for that node. +** +** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the +** original Select structure that describes the SELECT statement. These +** fields do not need to be freed when deallocating the AggInfo structure. +*/ +struct AggInfo { + u8 directMode; /* Direct rendering mode means take data directly + ** from source tables rather than from accumulators */ + u8 useSortingIdx; /* In direct mode, reference the sorting index rather + ** than the source table */ + int sortingIdx; /* Cursor number of the sorting index */ + ExprList *pGroupBy; /* The group by clause */ + int nSortingColumn; /* Number of columns in the sorting index */ + struct AggInfo_col { /* For each column used in source tables */ + Table *pTab; /* Source table */ + int iTable; /* Cursor number of the source table */ + int iColumn; /* Column number within the source table */ + int iSorterColumn; /* Column number in the sorting index */ + int iMem; /* Memory location that acts as accumulator */ + Expr *pExpr; /* The original expression */ + } *aCol; + int nColumn; /* Number of used entries in aCol[] */ + int nColumnAlloc; /* Number of slots allocated for aCol[] */ + int nAccumulator; /* Number of columns that show through to the output. + ** Additional columns are used only as parameters to + ** aggregate functions */ + struct AggInfo_func { /* For each aggregate function */ + Expr *pExpr; /* Expression encoding the function */ + FuncDef *pFunc; /* The aggregate function implementation */ + int iMem; /* Memory location that acts as accumulator */ + int iDistinct; /* Ephemeral table used to enforce DISTINCT */ + } *aFunc; + int nFunc; /* Number of entries in aFunc[] */ + int nFuncAlloc; /* Number of slots allocated for aFunc[] */ +}; + +/* +** The datatype ynVar is a signed integer, either 16-bit or 32-bit. +** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater +** than 32767 we have to make it 32-bit. 16-bit is preferred because +** it uses less memory in the Expr object, which is a big memory user +** in systems with lots of prepared statements. And few applications +** need more than about 10 or 20 variables. But some extreme users want +** to have prepared statements with over 32767 variables, and for them +** the option is available (at compile-time). +*/ +#if SQLITE_MAX_VARIABLE_NUMBER<=32767 +typedef i16 ynVar; +#else +typedef int ynVar; +#endif + +/* +** Each node of an expression in the parse tree is an instance +** of this structure. +** +** Expr.op is the opcode. The integer parser token codes are reused +** as opcodes here. For example, the parser defines TK_GE to be an integer +** code representing the ">=" operator. This same integer code is reused +** to represent the greater-than-or-equal-to operator in the expression +** tree. +** +** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, +** or TK_STRING), then Expr.token contains the text of the SQL literal. If +** the expression is a variable (TK_VARIABLE), then Expr.token contains the +** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), +** then Expr.token contains the name of the function. +** +** Expr.pRight and Expr.pLeft are the left and right subexpressions of a +** binary operator. Either or both may be NULL. +** +** Expr.x.pList is a list of arguments if the expression is an SQL function, +** a CASE expression or an IN expression of the form " IN (, ...)". +** Expr.x.pSelect is used if the expression is a sub-select or an expression of +** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the +** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is +** valid. +** +** An expression of the form ID or ID.ID refers to a column in a table. +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is +** the integer cursor number of a VDBE cursor pointing to that table and +** Expr.iColumn is the column number for the specific column. If the +** expression is used as a result in an aggregate SELECT, then the +** value is also stored in the Expr.iAgg column in the aggregate so that +** it can be accessed after all aggregates are computed. +** +** If the expression is an unbound variable marker (a question mark +** character '?' in the original SQL) then the Expr.iTable holds the index +** number for that variable. +** +** If the expression is a subquery then Expr.iColumn holds an integer +** register number containing the result of the subquery. If the +** subquery gives a constant result, then iTable is -1. If the subquery +** gives a different answer at different times during statement processing +** then iTable is the address of a subroutine that computes the subquery. +** +** If the Expr is of type OP_Column, and the table it is selecting from +** is a disk table or the "old.*" pseudo-table, then pTab points to the +** corresponding table definition. +** +** ALLOCATION NOTES: +** +** Expr objects can use a lot of memory space in database schema. To +** help reduce memory requirements, sometimes an Expr object will be +** truncated. And to reduce the number of memory allocations, sometimes +** two or more Expr objects will be stored in a single memory allocation, +** together with Expr.zToken strings. +** +** If the EP_Reduced and EP_TokenOnly flags are set when +** an Expr object is truncated. When EP_Reduced is set, then all +** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees +** are contained within the same memory allocation. Note, however, that +** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately +** allocated, regardless of whether or not EP_Reduced is set. +*/ +struct Expr { + u8 op; /* Operation performed by this node */ + char affinity; /* The affinity of the column or 0 if not a column */ + u16 flags; /* Various flags. EP_* See below */ + union { + char *zToken; /* Token value. Zero terminated and dequoted */ + int iValue; /* Integer value if EP_IntValue */ + } u; + + /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no + ** space is allocated for the fields below this point. An attempt to + ** access them will result in a segfault or malfunction. + *********************************************************************/ + + Expr *pLeft; /* Left subnode */ + Expr *pRight; /* Right subnode */ + union { + ExprList *pList; /* Function arguments or in " IN ( IN (